• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/**
2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import relationalStore from '@ohos.data.relationalStore';
17import { BusinessError } from '@ohos.base';
18import deviceInfo from '@ohos.deviceInfo';
19import hiSysEvent from '@ohos.hiSysEvent';
20import { Log } from '../utils/Log';
21import { CheckEmptyUtils } from '../utils/CheckEmptyUtils';
22import { CommonConstants } from '../constants/CommonConstants';
23import RdbStoreConfig from '../configs/RdbStoreConfig';
24import BadgeItemInfo from '../bean/BadgeItemInfo';
25import { AppItemInfo } from '../bean/AppItemInfo';
26import { DockItemInfo } from '../bean/DockItemInfo';
27import { CardItemInfo } from '../bean/CardItemInfo';
28import GridLayoutItemInfo from '../bean/GridLayoutItemInfo';
29import GridLayoutItemBuilder from '../bean/GridLayoutItemBuilder';
30import GridLayoutInfoColumns from '../bean/GridLayoutInfoColumns';
31import DesktopApplicationColumns from '../bean/DesktopApplicationColumns';
32import { GridLayoutInfo } from '../interface';
33import { LauncherDragItemInfo } from '../bean';
34
35const TAG = 'RdbStoreManager';
36
37/**
38 * Wrapper class for rdb interfaces.
39 */
40export class RdbStoreManager {
41  private mRdbStore: relationalStore.RdbStore;
42
43  private constructor() {
44  }
45  /**
46   * db manager instance
47   *
48   * @return rdbStoreManager instance
49   */
50  static getInstance(): RdbStoreManager {
51    if (globalThis.RdbStoreManagerInstance == null) {
52      globalThis.RdbStoreManagerInstance = new RdbStoreManager();
53    }
54    return globalThis.RdbStoreManagerInstance;
55  }
56
57  async initRdbConfig(): Promise<void> {
58    Log.showInfo(TAG, 'initRdbConfig start');
59    try {
60      const STORE_CONFIG: relationalStore.StoreConfig = {
61        name: RdbStoreConfig.DB_NAME,
62        securityLevel: relationalStore.SecurityLevel.S3
63      };
64
65      this.mRdbStore = await relationalStore.getRdbStore(globalThis.desktopContext, STORE_CONFIG);
66    } catch (error) {
67      let err = error as BusinessError;
68      Log.showError(TAG, `initRdbConfig Failed. code: ${err.code}, message: ${err.message}`);
69    }
70  }
71
72  async createTable(): Promise<void> {
73    Log.showDebug(TAG, 'create table start');
74    try {
75      await this.mRdbStore.executeSql(RdbStoreConfig.Settings.CREATE_TABLE);
76      await this.mRdbStore.executeSql(RdbStoreConfig.Badge.CREATE_TABLE);
77      await this.mRdbStore.executeSql(RdbStoreConfig.Form.CREATE_TABLE);
78      await this.mRdbStore.executeSql(RdbStoreConfig.SmartDock.CREATE_TABLE);
79      await this.mRdbStore.executeSql(RdbStoreConfig.DesktopApplicationInfo.CREATE_TABLE);
80      await this.mRdbStore.executeSql(RdbStoreConfig.GridLayoutInfo.CREATE_TABLE);
81
82      // set default settings data
83      await this.updateSettings();
84    } catch (error) {
85      Log.showError(TAG, `createTable error: ${JSON.stringify(error)}`);
86    }
87    Log.showDebug(TAG, 'create table end');
88  }
89
90  async getAllBadge(): Promise<BadgeItemInfo[]> {
91    Log.showDebug(TAG, 'getAllBadge start');
92    const predicates = new relationalStore.RdbPredicates(RdbStoreConfig.Badge.TABLE_NAME);
93    const resultList: BadgeItemInfo[] = [];
94    try {
95      let resultSet = await this.mRdbStore.query(predicates);
96      let isLast = resultSet.goToFirstRow();
97      while (isLast) {
98        const itemInfo: BadgeItemInfo = new BadgeItemInfo();
99        itemInfo.id = resultSet.getString(resultSet.getColumnIndex('id'));
100        itemInfo.bundleName = resultSet.getString(resultSet.getColumnIndex('bundle_name'));
101        itemInfo.badgeNumber = resultSet.getLong(resultSet.getColumnIndex('badge_number'));
102        itemInfo.display = this.numberToBoolean(resultSet.getLong(resultSet.getColumnIndex('display')));
103        itemInfo.userId = resultSet.getLong(resultSet.getColumnIndex('user_id'));
104        resultList.push(itemInfo);
105        isLast = resultSet.goToNextRow();
106      }
107      resultSet.close()
108      resultSet = null;
109    } catch (e) {
110      Log.showError(TAG, 'getAllBadge error:' + JSON.stringify(e));
111    }
112    return resultList;
113  }
114
115  async getBadgeByBundle(bundleName: string): Promise<BadgeItemInfo[]> {
116    Log.showDebug(TAG, 'getBadgeByBundle start');
117    const resultList: BadgeItemInfo[] = [];
118    if (this.ifStringIsNull(bundleName)) {
119      return resultList;
120    }
121    try {
122      const predicates = new relationalStore.RdbPredicates(RdbStoreConfig.Badge.TABLE_NAME);
123      predicates.equalTo('bundle_name', bundleName);
124      let resultSet = await this.mRdbStore.query(predicates);
125      let isLast = resultSet.goToFirstRow();
126      while (isLast) {
127        const itemInfo: BadgeItemInfo = new BadgeItemInfo();
128        itemInfo.id = resultSet.getString(resultSet.getColumnIndex('id'));
129        itemInfo.bundleName = resultSet.getString(resultSet.getColumnIndex('bundle_name'));
130        itemInfo.badgeNumber = resultSet.getLong(resultSet.getColumnIndex('badge_number'));
131        itemInfo.display = this.numberToBoolean(resultSet.getLong(resultSet.getColumnIndex('display')));
132        itemInfo.userId = resultSet.getLong(resultSet.getColumnIndex('user_id'));
133        resultList.push(itemInfo);
134        isLast = resultSet.goToNextRow();
135      }
136      resultSet.close()
137      resultSet = null;
138    } catch (e) {
139      Log.showError(TAG, 'getBadgeByBundle error:' + JSON.stringify(e));
140    }
141    return resultList;
142  }
143
144  async updateBadgeByBundle(bundleName: string, badgeNum: number): Promise<boolean> {
145    Log.showDebug(TAG, 'updateBadgeByBundle start');
146    let result = false;
147    if (badgeNum < 0 || this.ifStringIsNull(bundleName)) {
148      return result;
149    }
150    try {
151      const predicates = new relationalStore.RdbPredicates(RdbStoreConfig.Badge.TABLE_NAME);
152      predicates.equalTo('bundle_name', bundleName);
153      const updateBucket = {
154        'badge_number': badgeNum
155      };
156      let changeRows = await this.mRdbStore.update(updateBucket, predicates);
157      if (changeRows == 1) {
158        result = true;
159      } else {
160        const insertBucket = {
161          'bundle_name': bundleName,
162          'badge_number': badgeNum,
163          'display': CommonConstants.BADGE_DISPLAY_SHOW,
164          'user_id': CommonConstants.DEFAULT_USER_ID
165        };
166        changeRows = await this.mRdbStore.insert(RdbStoreConfig.Badge.TABLE_NAME, insertBucket);
167        result = (changeRows != CommonConstants.INVALID_VALUE);
168      }
169    } catch (e) {
170      Log.showError(TAG, 'updateBadgeByBundle error:' + JSON.stringify(e));
171    }
172    return result;
173  }
174
175  async deleteBadgeByBundle(bundleName: string): Promise<boolean> {
176    Log.showDebug(TAG, 'deleteBadgeByBundle start');
177    let result = false;
178    if (this.ifStringIsNull(bundleName)) {
179      return result;
180    }
181    try {
182      const predicates = new relationalStore.RdbPredicates(RdbStoreConfig.Badge.TABLE_NAME);
183      predicates.equalTo('bundle_name', bundleName);
184      const changeRows = await this.mRdbStore.delete(predicates);
185      if (changeRows == 1) {
186        result = true;
187      }
188    } catch (e) {
189      Log.showError(TAG, 'deleteBadgeByBundle error:' + JSON.stringify(e));
190    }
191    return result;
192  }
193
194  /**
195   * get all forms info form rdb
196   *
197   * @param cardId = CommonConstants.INVALID_VALUE
198   * @return Array<CardItemInfo> resultList
199   */
200  async getAllFormInfos(cardId = CommonConstants.INVALID_VALUE): Promise<CardItemInfo[]> {
201    Log.showDebug(TAG, 'getAllFormInfos start');
202    const predicates = new relationalStore.RdbPredicates(RdbStoreConfig.Form.TABLE_NAME);
203    if (cardId != CommonConstants.INVALID_VALUE) {
204      predicates.equalTo('card_id', cardId);
205    }
206    const resultList: CardItemInfo[] = [];
207    try {
208      let resultSet = await this.mRdbStore.query(predicates);
209      let isLast = resultSet.goToFirstRow();
210      while (isLast) {
211        const itemInfo: CardItemInfo = new CardItemInfo();
212        itemInfo.cardId = resultSet.getLong(resultSet.getColumnIndex('card_id'));
213        itemInfo.cardName = resultSet.getString(resultSet.getColumnIndex('card_name'));
214        itemInfo.bundleName = resultSet.getString(resultSet.getColumnIndex('bundle_name'));
215        itemInfo.abilityName = resultSet.getString(resultSet.getColumnIndex('ability_name'));
216        itemInfo.moduleName = resultSet.getString(resultSet.getColumnIndex('module_name'));
217        itemInfo.formConfigAbility = resultSet.getString(resultSet.getColumnIndex('config_ability'));
218        itemInfo.appLabelId = resultSet.getLong(resultSet.getColumnIndex('app_label_id'));
219        itemInfo.cardDimension = resultSet.getLong(resultSet.getColumnIndex('dimension'));
220        resultList.push(itemInfo);
221        isLast = resultSet.goToNextRow();
222      }
223      resultSet.close()
224      resultSet = null;
225    } catch (e) {
226      Log.showError(TAG, 'getAllFormInfos error:' + JSON.stringify(e));
227    }
228    return resultList;
229  }
230
231  /**
232   * get forms info form rdb by cardId
233   *
234   * @param cardId = CommonConstants.INVALID_VALUE
235   * @return Array<CardItemInfo> resultList
236   */
237  async getFormInfoById(cardId: number): Promise<CardItemInfo[]> {
238    Log.showDebug(TAG, 'getFormInfoById start');
239    const resultList: CardItemInfo[] = await this.getAllFormInfos(cardId);
240    return resultList;
241  }
242
243  async updateFormInfoById(cardItemInfo: CardItemInfo): Promise<boolean> {
244    Log.showDebug(TAG, 'updateFormInfoById start');
245    let result = false;
246    try {
247      const predicates = new relationalStore.RdbPredicates(RdbStoreConfig.Form.TABLE_NAME);
248      predicates.equalTo('card_id', cardItemInfo.cardId);
249      const updateBucket = {
250        'card_name': cardItemInfo.cardName,
251        'bundle_name': cardItemInfo.bundleName,
252        'ability_name': cardItemInfo.abilityName,
253        'module_name': cardItemInfo.moduleName,
254        'config_ability': cardItemInfo.formConfigAbility,
255        'app_label_id': cardItemInfo.appLabelId,
256        'dimension': cardItemInfo.cardDimension,
257      };
258      let changeRows = await this.mRdbStore.update(updateBucket, predicates);
259      if (changeRows == 1) {
260        result = true;
261      } else {
262        const insertBucket = {
263          'card_id': cardItemInfo.cardId,
264          'card_name': cardItemInfo.cardName,
265          'bundle_name': cardItemInfo.bundleName,
266          'ability_name': cardItemInfo.abilityName,
267          'module_name': cardItemInfo.moduleName,
268          'config_ability': cardItemInfo.formConfigAbility,
269          'app_label_id': cardItemInfo.appLabelId,
270          'dimension': cardItemInfo.cardDimension,
271        };
272        changeRows = await this.mRdbStore.insert(RdbStoreConfig.Form.TABLE_NAME, insertBucket);
273        result = (changeRows != CommonConstants.INVALID_VALUE);
274      }
275    } catch (e) {
276      Log.showError(TAG, 'updateFormInfoById error:' + JSON.stringify(e));
277    }
278    return result;
279  }
280
281  async deleteFormInfoById(cardId: number): Promise<boolean> {
282    Log.showDebug(TAG, 'deleteFormInfoById start');
283    let result = false;
284    try {
285      const predicates = new relationalStore.RdbPredicates(RdbStoreConfig.Form.TABLE_NAME);
286      predicates.equalTo('card_id', cardId);
287      const changeRows = await this.mRdbStore.delete(predicates);
288      if (changeRows == 1) {
289        result = true;
290      }
291    } catch (e) {
292      Log.showError(TAG, 'deleteFormInfoById error:' + JSON.stringify(e));
293    }
294    return result;
295  }
296
297  async deleteFormInfoByBundle(bundleName: string): Promise<boolean> {
298    Log.showDebug(TAG, 'deleteFormInfoByBundle start');
299    let result = false;
300    try {
301      const predicates = new relationalStore.RdbPredicates(RdbStoreConfig.Form.TABLE_NAME);
302      predicates.equalTo('bundle_name', bundleName);
303      const changeRows = await this.mRdbStore.delete(predicates);
304      if (changeRows == 1) {
305        result = true;
306      }
307    } catch (e) {
308      Log.showError(TAG, 'deleteFormInfoByBundle error:' + JSON.stringify(e));
309    }
310    return result;
311  }
312
313  private ifStringIsNull(str: string | null | undefined): boolean {
314    if (str == undefined || str == '' || str == null) {
315      return true;
316    }
317    return false;
318  }
319
320  async updateSettings(key?: string, value?: any): Promise<boolean> {
321    Log.showDebug(TAG, 'updateSettings start');
322    let result = false;
323    try {
324      // get deviceType
325      let deviceType = deviceInfo.deviceType;
326
327      // init default settings config
328      if (CheckEmptyUtils.isEmpty(key) || CheckEmptyUtils.isEmpty(value)) {
329        const firstDbData = {
330          'app_start_page_type': 'Grid',
331          'grid_config': 0,
332          'device_type': deviceType,
333          'page_count': 1,
334          'row': 5,
335          'column': 11
336        };
337        // insert sql
338        let ret = await this.mRdbStore.insert(RdbStoreConfig.Settings.TABLE_NAME, firstDbData);
339        Log.showDebug(TAG, `updateSettings insert successful. ${ret}`);
340      } else {
341        // update settings by key and value
342        let sql = `UPDATE ${RdbStoreConfig.Settings.TABLE_NAME} SET ${key} = '${value}' WHERE id = 1`;
343        await this.mRdbStore.executeSql(sql);
344        Log.showDebug(TAG, 'updateSettings update successful.');
345      }
346    } catch (e) {
347      Log.showError(TAG, 'updateSettings error:' + JSON.stringify(e));
348    }
349    return result;
350  }
351
352  async insertIntoSmartdock(dockInfoList: DockItemInfo[]): Promise<boolean> {
353    Log.showDebug(TAG, 'insertIntoSmartdock start');
354    let result = false;
355    try {
356      // delete smartdock table
357      await this.deleteTable(RdbStoreConfig.SmartDock.TABLE_NAME);
358
359      // insert into smartdock
360      for (const element of dockInfoList) {
361        let smartDockDbItem = {
362          'item_type': element.itemType,
363          'editable': this.booleanToNumber(element.editable),
364          'bundle_name': element.bundleName,
365          'ability_name': element.abilityName,
366          'module_name': element.moduleName,
367          'app_icon_id': element.appIconId,
368          'app_label_id': element.appLabelId,
369          'app_name': element.appName,
370          'is_system_app': this.booleanToNumber(element.isSystemApp),
371          'is_uninstallAble': this.booleanToNumber(element.isUninstallAble),
372          'key_name': element.keyName,
373          'install_time': element.installTime
374        }
375        let ret = await this.mRdbStore.insert(RdbStoreConfig.SmartDock.TABLE_NAME, smartDockDbItem);
376        Log.showDebug(TAG, `insertIntoSmartdock insert successful. ${ret}-${element.keyName}`);
377      }
378    } catch (e) {
379      Log.showError(TAG, 'insertIntoSmartdock error:' + JSON.stringify(e));
380      this.sendFaultEvent();
381    }
382    return result;
383  }
384
385  /**
386   * 1.clear table content
387   * 2.updata table
388   *
389   * @param tableName
390   */
391  async deleteTable(tableName: string): Promise<void> {
392    Log.showDebug(TAG, 'deleteTable start');
393    try {
394      let detelSql = `DELETE FROM ${tableName};`;
395      let detelSequenceSql = `UPDATE sqlite_sequence SET seq=0 WHERE name = '${tableName}';`;
396      await this.mRdbStore.executeSql(detelSql);
397      await this.mRdbStore.executeSql(detelSequenceSql);
398      Log.showDebug(TAG, 'deleteTable successful.');
399    } catch (e) {
400      Log.showError(TAG, `deleteTable err: ${JSON.stringify(e)}`);
401    }
402  }
403
404  /**
405   * 1.deleta table
406   * 2.create table
407   *
408   * @param tableName
409   */
410  async dropTable(tableName: string): Promise<void> {
411    Log.showDebug(TAG, 'dropTable start');
412    try {
413      let dropSql = `DROP TABLE IF EXISTS ${tableName}`;
414      await this.mRdbStore.executeSql(dropSql);
415      await this.mRdbStore.executeSql(RdbStoreConfig.GridLayoutInfo.CREATE_TABLE);
416      Log.showDebug(TAG, 'dropTable successful.');
417    } catch (e) {
418      Log.showError(TAG, `dropTable err: ${JSON.stringify(e)}`);
419    }
420  }
421
422  async querySmartDock(): Promise<DockItemInfo[]> {
423    const resultList: DockItemInfo[] = [];
424    try {
425      const predicates = new relationalStore.RdbPredicates(RdbStoreConfig.SmartDock.TABLE_NAME);
426      let resultSet = await this.mRdbStore.query(predicates);
427      let isLast = resultSet.goToFirstRow();
428      while (isLast) {
429        const itemInfo: DockItemInfo = new DockItemInfo();
430        itemInfo.itemType = resultSet.getLong(resultSet.getColumnIndex('item_type'));
431        itemInfo.editable = this.numberToBoolean(resultSet.getLong(resultSet.getColumnIndex('editable')));
432        itemInfo.bundleName = resultSet.getString(resultSet.getColumnIndex('bundle_name'));
433        itemInfo.abilityName = resultSet.getString(resultSet.getColumnIndex('ability_name'));
434        itemInfo.moduleName = resultSet.getString(resultSet.getColumnIndex('module_name'));
435        itemInfo.appIconId = resultSet.getLong(resultSet.getColumnIndex('app_icon_id'));
436        itemInfo.appLabelId = resultSet.getLong(resultSet.getColumnIndex('app_label_id'));
437        itemInfo.appName = resultSet.getString(resultSet.getColumnIndex('app_name'));
438        itemInfo.installTime = resultSet.getString(resultSet.getColumnIndex('install_time'));
439        itemInfo.isSystemApp = this.numberToBoolean(resultSet.getLong(resultSet.getColumnIndex('is_system_app')));
440        itemInfo.isUninstallAble = this.numberToBoolean(resultSet.getLong(resultSet.getColumnIndex('is_uninstallAble')));
441        itemInfo.keyName = resultSet.getString(resultSet.getColumnIndex('key_name'));
442        resultList.push(itemInfo);
443        isLast = resultSet.goToNextRow();
444      }
445      resultSet.close();
446      resultSet = null;
447    } catch (e) {
448      Log.showError(TAG, 'querySmartDock error:' + JSON.stringify(e));
449    }
450    return resultList;
451  }
452
453  async insertDesktopApplication(desktopApplicationInfo: any): Promise<boolean> {
454    Log.showDebug(TAG, 'insertDesktopApplication start');
455    let result: boolean = true;
456    if (CheckEmptyUtils.isEmptyArr(desktopApplicationInfo)) {
457      Log.showError(TAG, 'insertDesktopApplication desktopApplicationInfo is empty');
458      result = false;
459      return result;
460    }
461    try {
462      this.mRdbStore.beginTransaction();
463      // delete desktopApplicationInfo table
464      await this.deleteTable(RdbStoreConfig.DesktopApplicationInfo.TABLE_NAME);
465      // insert into desktopApplicationInfo
466      for (let i in desktopApplicationInfo) {
467        let element = desktopApplicationInfo[i];
468        let item = {
469          'app_name': element.appName,
470          'is_system_app': element.isSystemApp ? 1 : 0,
471          'is_uninstallAble': element.isUninstallAble ? 1 : 0,
472          'badge_number':element.badgeNumber,
473          'appIcon_id': element.appIconId,
474          'appLabel_id': element.appLabelId,
475          'bundle_name': element.bundleName,
476          'module_name': element.moduleName,
477          'ability_name': element.abilityName,
478          'key_name': element.bundleName + element.abilityName + element.moduleName,
479          'install_time': element.installTime
480        }
481        this.mRdbStore.insert(RdbStoreConfig.DesktopApplicationInfo.TABLE_NAME, item)
482          .then((ret) => {
483            if (ret === -1) {
484              result = false;
485            }
486          });
487      }
488      this.mRdbStore.commit();
489    } catch (e) {
490      Log.showError(TAG, 'insertDesktopApplication error:' + JSON.stringify(e));
491      this.mRdbStore.rollBack();
492      this.sendFaultEvent();
493    }
494    return result;
495  }
496
497  sendFaultEvent(){
498    const sysEventInfo = {
499      domain: 'LAUNCHER_APP',
500      name: 'LAUNCHER_FAULT',
501      eventType: hiSysEvent.EventType.FAULT,
502      params: {
503        'FAULT_ID': 'ICON_LOST',
504        'MSG': 'read or write rdb fault',
505      }
506    };
507    hiSysEvent.write(sysEventInfo,
508      (err, value) => {
509        if (err) {
510          Log.showError(TAG, `launcher fault hiSysEvent write error: ${err.code}`);
511        }
512      })
513  }
514
515  async queryDesktopApplication(): Promise<AppItemInfo[]> {
516    const resultList: AppItemInfo[] = [];
517    try {
518      const predicates = new relationalStore.RdbPredicates(RdbStoreConfig.DesktopApplicationInfo.TABLE_NAME);
519      let resultSet = await this.mRdbStore.query(predicates);
520      let isLast = resultSet.goToFirstRow();
521      while (isLast) {
522        let appItemInfo: AppItemInfo = new AppItemInfo();
523        appItemInfo.appName = resultSet.getString(resultSet.getColumnIndex(DesktopApplicationColumns.APP_NAME));
524        appItemInfo.isSystemApp = resultSet.getLong(resultSet.getColumnIndex(DesktopApplicationColumns.IS_SYSTEM_APP)) > 0 ? true : false;
525        appItemInfo.isUninstallAble = resultSet.getLong(resultSet.getColumnIndex(DesktopApplicationColumns.IS_UNINSTALLABLE)) > 0 ? true : false;
526        appItemInfo.appIconId = resultSet.getLong(resultSet.getColumnIndex(DesktopApplicationColumns.APPICON_ID));
527        appItemInfo.appLabelId = resultSet.getLong(resultSet.getColumnIndex(DesktopApplicationColumns.APPLABEL_ID));
528        appItemInfo.badgeNumber = resultSet.getLong(resultSet.getColumnIndex(DesktopApplicationColumns.BADGE_NUMBER));
529        appItemInfo.bundleName = resultSet.getString(resultSet.getColumnIndex(DesktopApplicationColumns.BUNDLE_NAME));
530        appItemInfo.abilityName = resultSet.getString(resultSet.getColumnIndex(DesktopApplicationColumns.ABILITY_NAME));
531        appItemInfo.moduleName = resultSet.getString(resultSet.getColumnIndex(DesktopApplicationColumns.MODULE_NAME));
532        appItemInfo.keyName = resultSet.getString(resultSet.getColumnIndex(DesktopApplicationColumns.KEY_NAME));
533        appItemInfo.installTime = resultSet.getString(resultSet.getColumnIndex(DesktopApplicationColumns.INSTALL_TIME));
534        resultList.push(appItemInfo);
535        isLast = resultSet.goToNextRow();
536      }
537      resultSet.close()
538      resultSet = null;
539    } catch (e) {
540      Log.showError(TAG, 'queryDesktopApplication error:' + JSON.stringify(e));
541    }
542    return resultList;
543  }
544
545  async insertGridLayoutInfo(gridLayoutInfo: GridLayoutInfo): Promise<void> {
546    Log.showDebug(TAG, 'insertGridLayoutInfo start');
547    if (CheckEmptyUtils.isEmpty(gridLayoutInfo) || CheckEmptyUtils.isEmptyArr(gridLayoutInfo.layoutInfo)) {
548      Log.showError(TAG, 'insertGridLayoutInfo gridlayoutinfo is empty');
549      return;
550    }
551
552    try {
553      // delete gridlayoutinfo table
554      await this.dropTable(RdbStoreConfig.GridLayoutInfo.TABLE_NAME);
555      // insert into gridlayoutinfo
556      let layoutInfo: Array<LauncherDragItemInfo> = gridLayoutInfo.layoutInfo;
557      for (const element of layoutInfo) {
558        let item = {};
559        if (element.typeId === CommonConstants.TYPE_APP) {
560          item = {
561            'bundle_name': element.bundleName,
562            'ability_name': element.abilityName,
563            'module_name': element.moduleName,
564            'key_name': element.bundleName + element.abilityName + element.moduleName,
565            'type_id': element.typeId,
566            'area': element.area[0] + ',' + element.area[1],
567            'page': element.page,
568            'column': element.column,
569            'row': element.row,
570            'container': -100,
571            'badge_number': element.badgeNumber
572          };
573          await this.mRdbStore.insert(RdbStoreConfig.GridLayoutInfo.TABLE_NAME, item);
574        } else if (element.typeId === CommonConstants.TYPE_CARD) {
575          item = {
576            'bundle_name':element.bundleName,
577            'ability_name': element.abilityName,
578            'module_name': element.moduleName,
579            'key_name': "" + element.cardId,
580            'card_id': element.cardId,
581            'type_id': element.typeId,
582            'area': element.area[0] + ',' + element.area[1],
583            'page': element.page,
584            'column': element.column,
585            'row': element.row,
586            'container': -100,
587            'badge_number': element.badgeNumber
588          };
589          await this.mRdbStore.insert(RdbStoreConfig.GridLayoutInfo.TABLE_NAME, item);
590        } else if (element.typeId === CommonConstants.TYPE_FOLDER) {
591          item = {
592            'bundle_name':element.bundleName,
593            'ability_name': element.abilityName,
594            'module_name': element.moduleName,
595            'folder_id': element.folderId,
596            'folder_name': element.folderName,
597            'type_id': element.typeId,
598            'area': element.area[0] + ',' + element.area[1],
599            'page': element.page,
600            'column': element.column,
601            'row': element.row,
602            'container': -100,
603            'badge_number': element.badgeNumber
604          };
605          Log.showDebug(TAG, `element prev: ${JSON.stringify(element)}`);
606          let ret: number = await this.mRdbStore.insert(RdbStoreConfig.GridLayoutInfo.TABLE_NAME, item);
607          Log.showDebug(TAG, `element ret: ${JSON.stringify(ret)}`);
608          if (ret !== -1) {
609            await this.insertLayoutInfo(element.layoutInfo, ret);
610          }
611        } else {
612          continue;
613        }
614      }
615    } catch (e) {
616      Log.showError(TAG, 'insertGridLayoutInfo error:' + JSON.stringify(e));
617      this.sendFaultEvent();
618    }
619  }
620
621  private async insertLayoutInfo(layoutInfo: AppItemInfo[][], container: number): Promise<boolean> {
622    Log.showDebug(TAG, 'insertLayoutInfo start');
623    let result: boolean = true;
624    if (CheckEmptyUtils.isEmptyArr(layoutInfo)) {
625      Log.showError(TAG, 'insertLayoutInfo layoutInfo is empty');
626      result = false;
627      return result;
628    }
629    for (const curItem of layoutInfo) {
630      for (const bigFolderApp of curItem) {
631        if (bigFolderApp.typeId !== CommonConstants.TYPE_APP) {
632          continue;
633        }
634        let item = {
635          'container': container,
636          'app_name': bigFolderApp.appName,
637          'is_system_app': bigFolderApp.isSystemApp ? 1 : 0,
638          'is_uninstallAble': bigFolderApp.isUninstallAble ? 1 : 0,
639          'appIcon_id': bigFolderApp.appIconId,
640          'appLabel_id': bigFolderApp.appLabelId,
641          'bundle_name': bigFolderApp.bundleName,
642          'module_name': bigFolderApp.moduleName,
643          'ability_name': bigFolderApp.abilityName,
644          'key_name': bigFolderApp.bundleName + bigFolderApp.abilityName + bigFolderApp.moduleName,
645          'install_time': bigFolderApp.installTime,
646          'type_id': bigFolderApp.typeId,
647          'area': bigFolderApp.area[0] + ',' + bigFolderApp.area[1],
648          'page': bigFolderApp.page,
649          'column': bigFolderApp.column,
650          'row': bigFolderApp.row,
651          'badge_number': bigFolderApp.badgeNumber
652        };
653        let ret: number = await this.mRdbStore.insert(RdbStoreConfig.GridLayoutInfo.TABLE_NAME, item);
654        Log.showDebug(TAG, `insertLayoutInfo ret ${container}-${ret}`);
655        if (ret === -1) {
656          result = false;
657        }
658      }
659    }
660    return result;
661  }
662
663  async queryGridLayoutInfo(): Promise<GridLayoutItemInfo[]> {
664    const resultList: GridLayoutItemInfo[] = [];
665    try {
666      const predicates = new relationalStore.RdbPredicates(RdbStoreConfig.GridLayoutInfo.TABLE_NAME);
667      predicates.equalTo(GridLayoutInfoColumns.CONTAINER, -100);
668      let resultSet = await this.mRdbStore.query(predicates);
669      let isLast = resultSet.goToFirstRow();
670      while (isLast) {
671        let typeId: number = resultSet.getLong(resultSet.getColumnIndex(GridLayoutInfoColumns.TYPE_ID));
672        const builder: GridLayoutItemBuilder = GridLayoutItemBuilder.fromResultSet(resultSet);
673        if (typeId === CommonConstants.TYPE_FOLDER) {
674          let id = resultSet.getLong(resultSet.getColumnIndex(GridLayoutInfoColumns.ID));
675          let layoutInfo:AppItemInfo[] = await this.queryLayoutInfo(id);
676          builder.setLayoutInfo(layoutInfo);
677        }
678        resultList.push(builder.buildGridLayoutItem());
679        isLast = resultSet.goToNextRow();
680      }
681      resultSet.close();
682      resultSet = null;
683    } catch (e) {
684      Log.showError(TAG, 'queryGridLayoutInfo error:' + JSON.stringify(e));
685    }
686    return resultList;
687  }
688
689  private async queryLayoutInfo(container: number): Promise<AppItemInfo[]> {
690    const resultList: AppItemInfo[] = [];
691    try {
692      let layoutPredicates = new relationalStore.RdbPredicates(RdbStoreConfig.GridLayoutInfo.TABLE_NAME);
693      layoutPredicates.equalTo('container', container);
694      let columns = [GridLayoutInfoColumns.APP_NAME,
695        GridLayoutInfoColumns.IS_SYSTEM_APP,
696        GridLayoutInfoColumns.IS_UNINSTALLABLE,
697        GridLayoutInfoColumns.APPICON_ID,
698        GridLayoutInfoColumns.APPLABEL_ID,
699        GridLayoutInfoColumns.BUNDLE_NAME,
700        GridLayoutInfoColumns.ABILITY_NAME,
701        GridLayoutInfoColumns.MODULE_NAME,
702        GridLayoutInfoColumns.KEY_NAME,
703        GridLayoutInfoColumns.CONTAINER,
704        GridLayoutInfoColumns.INSTALL_TIME,
705        GridLayoutInfoColumns.TYPE_ID,
706        GridLayoutInfoColumns.AREA,
707        GridLayoutInfoColumns.PAGE,
708        GridLayoutInfoColumns.COLUMN,
709        GridLayoutInfoColumns.ROW];
710
711      // columns - The columns to query. If the value is null, the query applies to all columns.
712      let resultSet = await this.mRdbStore.query(layoutPredicates, columns);
713      let isLast = resultSet.goToFirstRow();
714      while (isLast) {
715        const itemInfo: AppItemInfo = GridLayoutItemBuilder.buildLayout(resultSet);
716        resultList.push(itemInfo);
717        isLast = resultSet.goToNextRow();
718      }
719      resultSet.close();
720      resultSet = null;
721    } catch (e) {
722      Log.showError(TAG, 'queryLayoutInfo error:' + JSON.stringify(e));
723    }
724    return resultList;
725  }
726
727  booleanToNumber(data: boolean): number {
728    return data ? 1 : 0;
729  }
730
731  numberToBoolean(data: number): boolean {
732    return data === 1;
733  }
734
735}