• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 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 dataAbility from '@ohos.data.dataAbility'
17import featureAbility from '@ohos.ability.featureAbility'
18import rdb from '@ohos.data.rdb'
19import Logger from '../MainAbility/util/Logger'
20import { TABLE_NAME, STORE_CONFIG, SQL_CREATE_TABLE } from '../MainAbility/model/DaHelperConst'
21
22const TAG: string = 'data'
23let rdbStore: rdb.RdbStore = undefined
24// 对应stage模型中DataShareExtensionAbility.ts
25export default {
26
27  // 对应stage模型中的onCreate
28  onInitialized(abilityInfo) {
29    Logger.info(TAG, 'DataAbility onInitialized start')
30
31    // 初始化RDB数据库
32    rdb.getRdbStore(featureAbility.getContext(), STORE_CONFIG, 1, (err, data) => { // 1代表需要升级或降级的数据库版本号
33      if (err) {
34        Logger.info(TAG, `getRdbStore create table err = ${JSON.stringify(err)}`)
35      }
36      Logger.info(TAG, `getRdbStore create table done`)
37      data.executeSql(SQL_CREATE_TABLE)
38      rdbStore = data
39      Logger.info(TAG, `create table end, rdbStore = ${rdbStore}`)
40    })
41    Logger.info(TAG, 'DataAbility onInitialized end')
42  },
43
44  // 添加单条数据,对应stage模型中的insert
45  insert(uri, valueBucket, callback) {
46    Logger.info(TAG, `insert start`)
47    if (rdbStore) {
48      rdbStore.insert(TABLE_NAME, valueBucket, callback)
49    }
50  },
51
52  // 查询数据,对应stage模型中的query
53  query(uri, columns, predicates, callback) {
54    Logger.info(TAG, `query start`)
55    if (rdbStore) {
56      let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates)
57      rdbStore.query(rdbPredicates, columns, callback)
58    }
59  },
60
61  update(uri, valueBucket, predicates, callback) {
62    Logger.info(TAG, 'update start')
63    if (rdbStore) {
64      let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates)
65      rdbStore.update(valueBucket, rdbPredicates, callback)
66    }
67  },
68
69  // 删除数据,对应stage模型中的delete
70  delete(uri, predicates, callback) {
71    Logger.info(TAG, `delete start`)
72    if (rdbStore) {
73      let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates)
74      rdbStore.delete(rdbPredicates, callback)
75    }
76  }
77}