1# Sharing Data Using DataShareExtensionAbility 2 3 4## When to Use 5 6If complex services are involved in cross-application data access, you can use **DataShareExtensionAbility** to start the application of the data provider to implement data access. 7 8You need to implement flexible service logics via callbacks of the service provider. 9 10 11## Working Principles 12 13There are two roles in **DataShare**: 14 15- Data provider: implements operations, such as adding, deleting, modifying, and querying data, and opening a file, using [DataShareExtensionAbility](../reference/apis-arkdata/js-apis-application-dataShareExtensionAbility-sys.md). 16 17- Data consumer: accesses the data provided by the provider using [createDataShareHelper()](../reference/apis-arkdata/js-apis-data-dataShare-sys.md#datasharecreatedatasharehelper). 18 19**Figure 1** Data sharing mechanism 20 21 22- The **DataShareExtensionAbility** module, as the data provider, implements services related to data sharing between applications. 23 24- The **DataShareHelper** module, as the data consumer, provides APIs for accessing data, including adding, deleting, modifying, and querying data. 25 26- The data consumer communicates with the data provider via inter-process communication (IPC). The data provider can be implemented through a database or other data storage. 27 28- The **ResultSet** module is implemented through shared memory. Shared memory stores the result sets, and interfaces are provided to traverse result sets. 29 30 31## How to Develop 32 33 34### Data Provider Application Development (for System Applications Only) 35 36The [DataShareExtensionAbility](../reference/apis-arkdata/js-apis-application-dataShareExtensionAbility-sys.md) provides the following APIs. You can override these APIs as required. 37 38- **onCreate**: called by the server to initialize service logic when the DataShare client connects to the DataShareExtensionAbility server. 39- **insert**: called to insert data upon the request of the client. Data insertion must be implemented in this callback on the server. 40- **update**: called to update data upon the request of the client. Data update must be implemented in this callback on the server. 41- **batchUpdate**: called to update batch data upon the request of the client. Batch data update must be implemented in this callback on the server. 42- **delete**: called to delete data upon the request of the client. Data deletion must be implemented in this callback on the server. 43- **query**: called to query data upon the request of the client. Data query must be implemented in this callback on the server. 44- **batchInsert**: called to batch insert data upon the request of the client. Batch data insertion must be implemented in this callback on the server. 45- **normalizeUri**: converts the URI provided by the client to the URI used by the server. 46- **denormalizeUri**: converts the URI used by the server to the initial URI passed by the client. 47 48Before implementing a **DataShare** service, you need to create a **DataShareExtensionAbility** object in the DevEco Studio project as follows: 49 501. In the **ets** directory of the **Module** project, right-click and choose **New > Directory** to create a directory named **DataShareExtAbility**. 51 522. Right-click the **DataShareAbility** directory, and choose **New > ArkTS File** to create a file named **DataShareExtAbility.ets**. 53 543. In the **DataShareExtAbility.ets** file, import the **DataShareExtensionAbility** module. You can override the service implementation as required. For example, if the data provider provides only the insert, delete, and query services, you can override only these APIs and import the dependency modules. If permission verification is required, override the callbacks using [getCallingPid](../reference/apis-ipc-kit/js-apis-rpc.md#getcallingpid), [getCallingUid](../reference/apis-ipc-kit/js-apis-rpc.md#getcallinguid), and [getCallingTokenId](../reference/apis-ipc-kit/js-apis-rpc.md#getcallingtokenid8) provided by the IPC module to obtain the data consumer information for permission verification. 55 56 ```ts 57 import { DataShareExtensionAbility, dataShare, dataSharePredicates, relationalStore, DataShareResultSet } from '@kit.ArkData'; 58 import { Want } from '@kit.AbilityKit'; 59 import { BusinessError } from '@kit.BasicServicesKit' 60 ``` 61 624. Implement the data provider services. For example, implement data storage of the data provider by creating and using a database, reading and writing files, or accessing the network. 63 64 ```ts 65 const DB_NAME = 'DB00.db'; 66 const TBL_NAME = 'TBL00'; 67 const DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " 68 + TBL_NAME 69 + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)'; 70 71 let rdbStore: relationalStore.RdbStore; 72 let result: string; 73 74 export default class DataShareExtAbility extends DataShareExtensionAbility { 75 // Override onCreate(). 76 onCreate(want: Want, callback: Function) { 77 result = this.context.cacheDir + '/datashare.txt'; 78 // Create an RDB store. 79 relationalStore.getRdbStore(this.context, { 80 name: DB_NAME, 81 securityLevel: relationalStore.SecurityLevel.S3 82 }, (err:BusinessError, data:relationalStore.RdbStore) => { 83 rdbStore = data; 84 rdbStore.executeSql(DDL_TBL_CREATE, [], (err) => { 85 console.info(`DataShareExtAbility onCreate, executeSql done err:${err}`); 86 }); 87 if (callback) { 88 callback(); 89 } 90 }); 91 } 92 93 // Override query(). 94 query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: Function) { 95 if (predicates === null || predicates === undefined) { 96 console.info('invalid predicates'); 97 } 98 try { 99 rdbStore.query(TBL_NAME, predicates, columns, (err:BusinessError, resultSet:relationalStore.ResultSet) => { 100 if (resultSet !== undefined) { 101 console.info(`resultSet.rowCount:${resultSet.rowCount}`); 102 } 103 if (callback !== undefined) { 104 callback(err, resultSet); 105 } 106 }); 107 } catch (err) { 108 let code = (err as BusinessError).code; 109 let message = (err as BusinessError).message 110 console.error(`Failed to query. Code:${code},message:${message}`); 111 } 112 } 113 // Override the batchUpdate API. 114 batchUpdate(operations:Record<string, Array<dataShare.UpdateOperation>>, callback:Function) { 115 let recordOps : Record<string, Array<dataShare.UpdateOperation>> = operations; 116 let results : Record<string, Array<number>> = {}; 117 let a = Object.entries(recordOps); 118 for (let i = 0; i < a.length; i++) { 119 let key = a[i][0]; 120 let values = a[i][1]; 121 let result : number[] = []; 122 for (const value of values) { 123 rdbStore.update(TBL_NAME, value.values, value.predicates).then(async (rows) => { 124 console.info('Update row count is ' + rows); 125 result.push(rows); 126 }).catch((err:BusinessError) => { 127 console.info('Update failed, err is ' + JSON.stringify(err)); 128 result.push(-1) 129 }) 130 } 131 results[key] = result; 132 } 133 callback(null, results); 134 } 135 // Override other APIs as required. 136 }; 137 ``` 138 1395. Define **DataShareExtensionAbility** in **module.json5**. 140 141 **Table 1** Fields in module.json5 142 143 | Field| Description| Mandatory| 144 | -------- | -------- | -------- | 145 | name | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**.| Yes| 146 | type | Ability type. The value **dataShare** indicates that the development is based on the **datashare** template.| Yes| 147 | uri | Unique identifier for the data consumer to access the data provider.| Yes| 148 | exported | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**.| Yes| 149 | readPermission | Permission required for accessing data. If this parameter is not set, read permission verification is not performed by default.| No| 150 | writePermission | Permission required for modifying data. If this parameter is not set, write permission verification is not performed by default.| No| 151 | metadata | Silent access configuration, which includes the following:<br>- **name**: identifies the configuration, which has a fixed value of **ohos.extension.dataShare**.<br>- **resource**: has a fixed value of **$profile:data_share_config**, which indicates that the profile name is **data_share_config.json**.| **metadata** is mandatory when the ability launch type is **singleton**. For details about the ability launch type, see **launchType** in the [Internal Structure of the abilities Attribute](../quick-start/module-structure.md#internal-structure-of-the-abilities-attribute).| 152 153 **module.json5 example** 154 155 ```json 156 "extensionAbilities": [ 157 { 158 "srcEntry": "./ets/DataShareExtAbility/DataShareExtAbility.ets", 159 "name": "DataShareExtAbility", 160 "icon": "$media:icon", 161 "description": "$string:description_datashareextability", 162 "type": "dataShare", 163 "uri": "datashare://com.samples.datasharetest.DataShare", 164 "exported": true, 165 "metadata": [{"name": "ohos.extension.dataShare", "resource": "$profile:data_share_config"}] 166 } 167 ] 168 ``` 169 170 **Table 2** Fields in the data_share_config.json file 171 172 | Field | Description | Mandatory| 173 | ------------------- | ------------------------------------------------------------ | ---- | 174 | tableConfig | Configuration label, which includes **uri** and **crossUserMode**.<br>- **uri**: specifies the range for which the configuration takes effect. The URI supports the following formats in descending order by priority:<br> 1. *****: indicates all databases and tables.<br> 2. **datashare:///{*bundleName*}/{*moduleName*}/{*storeName*}**: specifies a database.<br> 3. **datashare:///{*bundleName*}/{*moduleName*}/{*storeName*}/{*tableName*}**: specifies a table.<br>If URIs of different formats are configured, only the URI with the higher priority takes effect.<br>- **crossUserMode**: Whether to share data between multiple users.<br>The value **1** means to share data between multiple users, and the value **2** means the opposite.| Yes | 175 | isSilentProxyEnable | Whether to enable silent access for this ExtensionAbility.<br>The value **true** means to enable silent access, and the value **false** means the opposite.<br>The default value is **true**.<br>If an application has multiple ExtensionAbilities and this field is set to **false** for one of them, silent access is disabled for the application.<br>If the data provider has called **enableSilentProxy** or **disableSilentProxy**, silent access is enabled or disabled based on the API settings. Otherwise, the setting here takes effect.| No | 176 | launchInfos | Launch information, which includes **storeId** and **tableNames**.<br>If the data in a table involved in the configuration changes, an extensionAbility will be started based on the URI in **extensionAbilities**. You need to set this parameter only when the service needs to start an extensionAbility to process data that is not actively changed by the service.<br>- **storeId**: database name, excluding the file name extension. For example, if the database name is **test.db**, set this parameter to **test**.<br>- **tableNames**: names of the database tables. Any change in a table will start an an extensionAbility. | No | 177 178 **data_share_config.json Example** 179 180 ```json 181 { 182 "tableConfig":[ 183 { 184 "uri":"*", 185 "crossUserMode":1 186 }, 187 { 188 "uri":"datashare:///com.acts.datasharetest/entry/DB00", 189 "crossUserMode":1 190 }, 191 { 192 "uri":"datashare:///com.acts.datasharetest/entry/DB00/TBL00", 193 "crossUserMode":2 194 } 195 ], 196 "isSilentProxyEnable":true, 197 "launchInfos":[ 198 { 199 "storeId": "test", 200 "tableNames":["test1", "test2"] 201 } 202 ] 203 } 204 ``` 205 206 207### Data Consumer Application Development 208 2091. Import the dependencies. 210 211 ```ts 212 import { UIAbility } from '@kit.AbilityKit'; 213 import { dataShare, dataSharePredicates, DataShareResultSet, ValuesBucket } from '@kit.ArkData'; 214 import { window } from '@kit.ArkUI'; 215 import { BusinessError } from '@kit.BasicServicesKit'; 216 ``` 217 2182. Define the URI string for communicating with the data provider. 219 220 ```ts 221 // Different from the URI defined in the module.json5 file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/). 222 let dseUri = ('datashare:///com.samples.datasharetest.DataShare'); 223 ``` 224 2253. Create a **DataShareHelper** instance. 226 227 ```ts 228 let dsHelper: dataShare.DataShareHelper | undefined = undefined; 229 let abilityContext: Context; 230 231 export default class EntryAbility extends UIAbility { 232 onWindowStageCreate(windowStage: window.WindowStage) { 233 abilityContext = this.context; 234 dataShare.createDataShareHelper(abilityContext, dseUri, (err, data) => { 235 dsHelper = data; 236 }); 237 } 238 } 239 ``` 240 2414. Use the APIs provided by **DataShareHelper** to access the services provided by the provider, for example, adding, deleting, modifying, and querying data. 242 243 ```ts 244 // Construct a piece of data. 245 let key1 = 'name'; 246 let key2 = 'age'; 247 let key3 = 'isStudent'; 248 let key4 = 'Binary'; 249 let valueName1 = 'ZhangSan'; 250 let valueName2 = 'LiSi'; 251 let valueAge1 = 21; 252 let valueAge2 = 18; 253 let valueIsStudent1 = false; 254 let valueIsStudent2 = true; 255 let valueBinary = new Uint8Array([1, 2, 3]); 256 let valuesBucket: ValuesBucket = { key1: valueName1, key2: valueAge1, key3: valueIsStudent1, key4: valueBinary }; 257 let updateBucket: ValuesBucket = { key1: valueName2, key2: valueAge2, key3: valueIsStudent2, key4: valueBinary }; 258 let predicates = new dataSharePredicates.DataSharePredicates(); 259 let valArray = ['*']; 260 261 let record: Record<string, Array<dataShare.UpdateOperation>> = {}; 262 let operations1: Array<dataShare.UpdateOperation> = []; 263 let operations2: Array<dataShare.UpdateOperation> = []; 264 let operation1: dataShare.UpdateOperation = { 265 values: valuesBucket, 266 predicates: predicates 267 } 268 operations1.push(operation1); 269 let operation2: dataShare.UpdateOperation = { 270 values: updateBucket, 271 predicates: predicates 272 } 273 operations2.push(operation2); 274 record["uri1"] = operations1; 275 record["uri2"] = operations2; 276 277 if (dsHelper != undefined) { 278 // Insert a piece of data. 279 (dsHelper as dataShare.DataShareHelper).insert(dseUri, valuesBucket, (err:BusinessError, data:number) => { 280 console.info(`dsHelper insert result:${data}`); 281 }); 282 // Update data. 283 (dsHelper as dataShare.DataShareHelper).update(dseUri, predicates, updateBucket, (err:BusinessError, data:number) => { 284 console.info(`dsHelper update result:${data}`); 285 }); 286 // Query data. 287 (dsHelper as dataShare.DataShareHelper).query(dseUri, predicates, valArray, (err:BusinessError, data:DataShareResultSet) => { 288 console.info(`dsHelper query result:${data}`); 289 }); 290 // Delete data. 291 (dsHelper as dataShare.DataShareHelper).delete(dseUri, predicates, (err:BusinessError, data:number) => { 292 console.info(`dsHelper delete result:${data}`); 293 }); 294 // Update data in batches. 295 (dsHelper as dataShare.DataShareHelper).batchUpdate(record).then((data: Record<string, Array<number>>) => { 296 // Traverse data to obtain the update result of each data record. value indicates the number of data records that are successfully updated. If value is less than 0, the update fails. 297 let a = Object.entries(data); 298 for (let i = 0; i < a.length; i++) { 299 let key = a[i][0]; 300 let values = a[i][1] 301 console.info(`Update uri:${key}`); 302 for (const value of values) { 303 console.info(`Update result:${value}`); 304 } 305 } 306 }); 307 // Close the DataShareHelper instance. 308 (dsHelper as dataShare.DataShareHelper).close(); 309 } 310 ```