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