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