database-mdds-guidelines.md 10.4 KB
Newer Older
A
Annie_wang 已提交
1 2 3 4 5 6 7 8
# Distributed Data Service Development

## When to Use

The Distributed Data Service (DDS) implements synchronization of application data across user devices. When data is added, deleted, or modified for an application on a device, the same application on another device can obtain the updated data. The DDS applies to the distributed gallery, messages, contacts, and file manager.


## Available APIs
A
Annie_wang 已提交
9

10
For details about the APIs, see [Distributed KV Store](../reference/apis/js-apis-distributedKVStore.md).
A
Annie_wang 已提交
11 12 13

**Table 1** APIs provided by the DDS

14 15 16 17 18 19 20 21 22
| API                                                    | Description                                                        |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| createKVManager(config: KVManagerConfig, callback: AsyncCallback&lt;KVManager&gt;): void<br>createKVManager(config: KVManagerConfig): Promise&lt;KVManager> | Creates a **KvManager** object for database management.           |
| getKVStore&lt;TextendsKVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;TextendsKVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Creates and obtains a KV store.|
| put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback&lt;void&gt;): void<br>put(key: string, value: Uint8Array\|string\|number\|boolean): Promise&lt;void> | Inserts and updates data.                                            |
| delete(key: string, callback: AsyncCallback&lt;void&gt;): void<br>delete(key: string): Promise&lt;void> | Deletes data.                                                  |
| get(key: string, callback: AsyncCallback&lt;Uint8Array\|string\|boolean\|number&gt;): void<br>get(key: string): Promise&lt;Uint8Array\|string\|boolean\|number> | Queries data.                                                  |
| on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;ChangeNotification&gt;): void<br>on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string,number]&gt;&gt;): void | Subscribes to data changes in the KV store.                                    |
| sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode.                              |
A
Annie_wang 已提交
23 24

## How to Develop
Z
zengyawen 已提交
25 26 27

The following uses a single KV store as an example to describe the development procedure.

A
Annie_wang 已提交
28
1. Import the distributed data module.
A
Annie_wang 已提交
29

A
Annie_wang 已提交
30
   ```js
31
   import distributedKVStore from '@ohos.data.distributedKVStore';
A
Annie_wang 已提交
32
   ```
33

A
Annie_wang 已提交
34
2. Apply for the required permission if data synchronization is required.
A
Annie_wang 已提交
35

A
Annie_wang 已提交
36 37 38
   Add the permission required (FA model) in the **config.json** file. The sample code is as follows:

    ```json
39 40 41 42 43 44 45 46 47
    {
      "module": {
          "reqPermissions": [
              {
                 "name": "ohos.permission.DISTRIBUTED_DATASYNC"
              }
          ]
      }
    }
A
Annie_wang 已提交
48
    ```
49

A
Annie_wang 已提交
50 51 52 53 54
   For the apps based on the stage model, see [Declaring Permissions](../security/accesstoken-guidelines.md#stage-model).

   This permission must also be granted by the user when the application is started for the first time. The sample code is as follows:

    ```js
A
Annie_wang 已提交
55
    // FA model
A
Annie_wang 已提交
56
    import featureAbility from '@ohos.ability.featureAbility';
57
   
A
Annie_wang 已提交
58
    function grantPermission() {
A
Annie_wang 已提交
59 60 61 62 63 64 65
    console.info('grantPermission');
    let context = featureAbility.getContext();
    context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666).then((data) => {
        console.info('success: ${data}');
    }).catch((error) => {
        console.info('failed: ${error}');
    })
A
Annie_wang 已提交
66
    }
67
   
A
Annie_wang 已提交
68
    grantPermission();
69
   
A
Annie_wang 已提交
70 71
    // Stage model
    import Ability from '@ohos.application.Ability';
72
   
A
Annie_wang 已提交
73
    let context = null;
74
   
A
Annie_wang 已提交
75 76 77 78 79 80
    function grantPermission() {
    class MainAbility extends Ability {
        onWindowStageCreate(windowStage) {
        let context = this.context;
        }
    }
81
   
A
Annie_wang 已提交
82 83 84 85 86 87 88
    let permissions = ['ohos.permission.DISTRIBUTED_DATASYNC'];
    context.requestPermissionsFromUser(permissions).then((data) => {
        console.log('success: ${data}');
    }).catch((error) => {
        console.log('failed: ${error}');
    });
    }
89
   
A
Annie_wang 已提交
90 91 92
    grantPermission();
    ```

93
3. Create a **KvManager** instance based on the specified **KvManagerConfig** object.
A
Annie_wang 已提交
94 95

   1. Create a **kvManagerConfig** object based on the application context.
96
   2. Create a **KvManager** instance.
A
Annie_wang 已提交
97 98

   The sample code is as follows:
A
Annie_wang 已提交
99 100

   ```js
A
Annie_wang 已提交
101 102 103
   // Obtain the context of the FA model.
   import featureAbility from '@ohos.ability.featureAbility';
   let context = featureAbility.getContext();
104
   
A
Annie_wang 已提交
105 106 107 108 109 110 111 112
   // Obtain the context of the stage model.
   import AbilityStage from '@ohos.application.Ability';
   let context = null;
   class MainAbility extends AbilityStage{
      onWindowStageCreate(windowStage){
        context = this.context;
      }
   }
113
   
A
Annie_wang 已提交
114 115
   let kvManager;
   try {
A
Annie_wang 已提交
116 117
     const kvManagerConfig = {
       bundleName: 'com.example.datamanagertest',
118
       context:context,
A
Annie_wang 已提交
119
     }
120
     distributedKVStore.createKVManager(kvManagerConfig, function (err, manager) {
A
Annie_wang 已提交
121
       if (err) {
122
         console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
123 124
         return;
       }
A
Annie_wang 已提交
125
       console.log('Created KVManager successfully');
A
Annie_wang 已提交
126 127
       kvManager = manager;
     });
A
Annie_wang 已提交
128
   } catch (e) {
129
     console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
130 131
   }
   ```
A
Annie_wang 已提交
132

A
Annie_wang 已提交
133
4. Create and obtain a single KV store.
A
Annie_wang 已提交
134

A
Annie_wang 已提交
135 136
   1. Declare the ID of the single KV store to create.
   2. Create a single KV store. You are advised to disable automatic synchronization (`autoSync:false`) and call `sync` when a synchronization is required.
A
Annie_wang 已提交
137 138

   The sample code is as follows:
A
Annie_wang 已提交
139

A
Annie_wang 已提交
140 141 142
   ```js
   let kvStore;
   try {
A
Annie_wang 已提交
143 144 145 146 147
     const options = {
       createIfMissing: true,
       encrypt: false,
       backup: false,
       autoSync: false,
148 149
       kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
       securityLevel: distributedKVStore.SecurityLevel.S1
A
Annie_wang 已提交
150 151 152
     };
     kvManager.getKVStore('storeId', options, function (err, store) {
       if (err) {
153
         console.error(`Failed to get KVStore: code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
154 155
         return;
       }
156
       console.log('Obtained KVStore successfully');
A
Annie_wang 已提交
157 158
       kvStore = store;
     });
A
Annie_wang 已提交
159
   } catch (e) {
160
     console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
161 162 163
   }
   ```

A
Annie_wang 已提交
164
   > **NOTE**<br>
A
Annie_wang 已提交
165 166
   >
   > For data synchronization between networked devices, you are advised to open the distributed KV store during application startup to obtain the database handle. With this database handle (`kvStore` in this example), you can perform operations, such as inserting data into the KV store, without creating the KV store repeatedly during the lifecycle of the handle.
167

A
Annie_wang 已提交
168
5. Subscribe to changes in the distributed data.
A
Annie_wang 已提交
169 170

   The following is the sample code for subscribing to the data changes of a single KV store:
A
Annie_wang 已提交
171

A
Annie_wang 已提交
172
   ```js
173 174 175 176 177 178 179
   try{
       kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) {
           console.log(`dataChange callback call data: ${data}`);
       });
   }catch(e){
       console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`);
   }
A
Annie_wang 已提交
180 181
   ```

A
Annie_wang 已提交
182
6. Write data to the single KV store.
A
Annie_wang 已提交
183

A
Annie_wang 已提交
184 185
   1. Construct the `Key` and `Value` to be written into the single KV store.
   2. Write key-value pairs into the single KV store.
A
Annie_wang 已提交
186 187 188 189 190 191 192

   The following is the sample code for writing key-value pairs of the string type into the single KV store:

   ```js
   const KEY_TEST_STRING_ELEMENT = 'key_test_string';
   const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
   try {
193
       kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) {
A
Annie_wang 已提交
194
           if (err != undefined) {
195
               console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
196 197
               return;
           }
A
Annie_wang 已提交
198
           console.log('Put data successfully');
A
Annie_wang 已提交
199
       });
200 201
   }catch (e) {
       console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
202 203 204
   }
   ```

A
Annie_wang 已提交
205
7. Query data in the single KV store.
A
Annie_wang 已提交
206

A
Annie_wang 已提交
207 208
   1. Construct the `Key` to be queried from the single KV store.
   2. Query data from the single KV store.
A
Annie_wang 已提交
209 210

   The following is the sample code for querying data of the string type from the single KV store:
A
Annie_wang 已提交
211

A
Annie_wang 已提交
212 213 214 215
   ```js
   const KEY_TEST_STRING_ELEMENT = 'key_test_string';
   const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
   try {
216
       kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) {
A
Annie_wang 已提交
217
           if (err != undefined) {
218
               console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
219 220
               return;
           }
A
Annie_wang 已提交
221
           console.log('Put data successfully');
222 223 224 225 226 227
           kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) {
           if (err != undefined) {
               console.error(`Failed to get data.code is ${err.code},message is ${err.message}`);
               return;
           }
               console.log(`Obtained data successfully:${data}`);
A
Annie_wang 已提交
228 229
           });
       });
230 231
   }catch (e) {
       console.error(`Failed to get.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
232 233 234
   }
   ```

A
Annie_wang 已提交
235 236
8. Synchronize data to other devices.

A
Annie_wang 已提交
237 238
   Select the devices in the same network and the synchronization mode to synchronize data.

A
Annie_wang 已提交
239
   > **NOTE**<br>
A
Annie_wang 已提交
240 241
   >
   > The APIs of the `deviceManager` module are system interfaces.
242

A
Annie_wang 已提交
243
   The following is the example code for synchronizing data in a single KV store:
A
Annie_wang 已提交
244

A
Annie_wang 已提交
245 246 247 248 249
   ```js
   import deviceManager from '@ohos.distributedHardware.deviceManager';
   
   let devManager;
   // Create deviceManager.
A
Annie_wang 已提交
250
   deviceManager.createDeviceManager('bundleName', (err, value) => {
A
Annie_wang 已提交
251 252
       if (!err) {
           devManager = value;
A
Annie_wang 已提交
253
           // deviceIds is obtained by deviceManager by calling getTrustedDeviceListSync().
A
Annie_wang 已提交
254 255 256 257 258 259 260 261
           let deviceIds = [];
           if (devManager != null) {
               var devices = devManager.getTrustedDeviceListSync();
               for (var i = 0; i < devices.length; i++) {
                   deviceIds[i] = devices[i].deviceId;
               }
           }
           try{
A
Annie_wang 已提交
262
               // 1000 indicates that the maximum delay is 1000 ms.
263
               kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_ONLY, 1000);
A
Annie_wang 已提交
264
           } catch (e) {
265
                console.error(`An unexpected error occurred. code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
266 267 268 269
           }
       }
   });
   ```