1e41f4b71Sopenharmony_ci# Cross-Device Sync of RDB Stores 2e41f4b71Sopenharmony_ci 3e41f4b71Sopenharmony_ci 4e41f4b71Sopenharmony_ci## When to Use 5e41f4b71Sopenharmony_ci 6e41f4b71Sopenharmony_ciYou can sync the application data in a local RDB store on a device to other devices that form a Super Device. 7e41f4b71Sopenharmony_ci 8e41f4b71Sopenharmony_ci 9e41f4b71Sopenharmony_ci## Basic Concepts 10e41f4b71Sopenharmony_ci 11e41f4b71Sopenharmony_ciOpenHamony supports sync of the relational data of an application across multiple devices. 12e41f4b71Sopenharmony_ci 13e41f4b71Sopenharmony_ci- If a table created for an application in the database is set as a distributed table, when data is queried from the RDB store of a remote device, the distributed table name of the remote device can be obtained based on the local table name. 14e41f4b71Sopenharmony_ci 15e41f4b71Sopenharmony_ci- Data can be synced between devices in either of the following ways: <br>- Pushing data from a local device to a remote device. <br>- Pulling data from a remote device to a local device. 16e41f4b71Sopenharmony_ci 17e41f4b71Sopenharmony_ci 18e41f4b71Sopenharmony_ci## Working Principles 19e41f4b71Sopenharmony_ci 20e41f4b71Sopenharmony_ciAfter completing device discovery and authentication, the underlying communication component notifies the application that the device goes online. The **DatamgrService** then establishes an encrypted transmission channel to synchronize data between the two devices. 21e41f4b71Sopenharmony_ci 22e41f4b71Sopenharmony_ci 23e41f4b71Sopenharmony_ci### Cross-Device Data Sync Mechanism 24e41f4b71Sopenharmony_ci 25e41f4b71Sopenharmony_ci 26e41f4b71Sopenharmony_ci 27e41f4b71Sopenharmony_ciAfter writing data to an RDB store, the service sends a sync request to the **DatamgrService**. 28e41f4b71Sopenharmony_ci 29e41f4b71Sopenharmony_ciThe **DatamgrService** reads the data to be synced from the application sandbox and sends the data to the **DatamgrService** of the target device based on the **deviceId** of the peer device. Then, the **DatamgrService** writes the data to the RDB of the same application. 30e41f4b71Sopenharmony_ci 31e41f4b71Sopenharmony_ci 32e41f4b71Sopenharmony_ci### Data Change Notification Mechanism 33e41f4b71Sopenharmony_ci 34e41f4b71Sopenharmony_ciWhen data is added, deleted, or modified, a notification is sent to the subscriber. The notifications can be classified into the following types: 35e41f4b71Sopenharmony_ci 36e41f4b71Sopenharmony_ci- Local data change notification: subscription of the application data changes on the local device. When the data in the local KV store is added, deleted, or modified in the database, a notification is received. 37e41f4b71Sopenharmony_ci 38e41f4b71Sopenharmony_ci- Distributed data change notification: subscription of the application data changes of other devices in the network. When the data in the local RDB store changes after being synced with data from another device in the same network, a notification is received. 39e41f4b71Sopenharmony_ci 40e41f4b71Sopenharmony_ci 41e41f4b71Sopenharmony_ci## Constraints 42e41f4b71Sopenharmony_ci 43e41f4b71Sopenharmony_ci- A maximum of 16 RDB stores can be opened simultaneously for an application. 44e41f4b71Sopenharmony_ci 45e41f4b71Sopenharmony_ci- Each RDB store supports a maximum of eight callbacks for subscription of data change notifications. 46e41f4b71Sopenharmony_ci 47e41f4b71Sopenharmony_ci 48e41f4b71Sopenharmony_ci## Available APIs 49e41f4b71Sopenharmony_ci 50e41f4b71Sopenharmony_ciMost of the APIs for cross-device data sync of RDB stores are executed asynchronously, using a callback or promise to return the result. The following table uses the callback-based APIs as an example. For more information about the APIs, see [RDB Store](../reference/apis-arkdata/js-apis-data-relationalStore.md). 51e41f4b71Sopenharmony_ci 52e41f4b71Sopenharmony_ci| API| Description| 53e41f4b71Sopenharmony_ci| -------- | -------- | 54e41f4b71Sopenharmony_ci| setDistributedTables(tables: Array<string>, callback: AsyncCallback<void>): void | Sets the distributed tables to be synced.| 55e41f4b71Sopenharmony_ci| sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback<Array<[string, number]>>): void | Synchronizes data across devices.| 56e41f4b71Sopenharmony_ci| on(event: 'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void | Subscribes to changes in the distributed data.| 57e41f4b71Sopenharmony_ci| off(event:'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void | Unsubscribe from changes in the distributed data.| 58e41f4b71Sopenharmony_ci| obtainDistributedTableName(device: string, table: string, callback: AsyncCallback<string>): void; | Obtains the table name on the specified device based on the local table name.| 59e41f4b71Sopenharmony_ci| remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string> , callback: AsyncCallback<ResultSet>): void | Queries data from the RDB store of a remote device based on specified conditions.| 60e41f4b71Sopenharmony_ci 61e41f4b71Sopenharmony_ci 62e41f4b71Sopenharmony_ci## How to Develop 63e41f4b71Sopenharmony_ci 64e41f4b71Sopenharmony_ci> **NOTE** 65e41f4b71Sopenharmony_ci> 66e41f4b71Sopenharmony_ci> The security level of the destination device (to which data is synced) cannot be higher than that of the source device. For details, see [Access Control Mechanism in Cross-Device Sync](access-control-by-device-and-data-level.md#access-control-mechanism-in-cross-device-sync). 67e41f4b71Sopenharmony_ci 68e41f4b71Sopenharmony_ci1. Import the module. 69e41f4b71Sopenharmony_ci 70e41f4b71Sopenharmony_ci ```ts 71e41f4b71Sopenharmony_ci import { relationalStore } from '@kit.ArkData'; 72e41f4b71Sopenharmony_ci ``` 73e41f4b71Sopenharmony_ci 74e41f4b71Sopenharmony_ci2. Request permissions. 75e41f4b71Sopenharmony_ci 76e41f4b71Sopenharmony_ci 1. Declare the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions](../security/AccessToken/declare-permissions.md). 77e41f4b71Sopenharmony_ci 2. Display a dialog box to ask for user authorization when the application is started for the first time. For details, see [Requesting User Authorization](../security/AccessToken/request-user-authorization.md). 78e41f4b71Sopenharmony_ci 79e41f4b71Sopenharmony_ci3. Create an RDB store and set a table for distributed sync. 80e41f4b71Sopenharmony_ci 81e41f4b71Sopenharmony_ci ```ts 82e41f4b71Sopenharmony_ci import { UIAbility } from '@kit.AbilityKit'; 83e41f4b71Sopenharmony_ci import { BusinessError } from '@kit.BasicServicesKit'; 84e41f4b71Sopenharmony_ci import { window } from '@kit.ArkUI'; 85e41f4b71Sopenharmony_ci 86e41f4b71Sopenharmony_ci class EntryAbility extends UIAbility { 87e41f4b71Sopenharmony_ci onWindowStageCreate(windowStage: window.WindowStage) { 88e41f4b71Sopenharmony_ci const STORE_CONFIG: relationalStore.StoreConfig = { 89e41f4b71Sopenharmony_ci name: "RdbTest.db", 90e41f4b71Sopenharmony_ci securityLevel: relationalStore.SecurityLevel.S3 91e41f4b71Sopenharmony_ci }; 92e41f4b71Sopenharmony_ci 93e41f4b71Sopenharmony_ci relationalStore.getRdbStore(this.context, STORE_CONFIG, (err: BusinessError, store: relationalStore.RdbStore) => { 94e41f4b71Sopenharmony_ci store.executeSql('CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)', (err) => { 95e41f4b71Sopenharmony_ci // Set the table for distributed sync. 96e41f4b71Sopenharmony_ci store.setDistributedTables(['EMPLOYEE']); 97e41f4b71Sopenharmony_ci // Perform related operations. 98e41f4b71Sopenharmony_ci }) 99e41f4b71Sopenharmony_ci }) 100e41f4b71Sopenharmony_ci } 101e41f4b71Sopenharmony_ci } 102e41f4b71Sopenharmony_ci ``` 103e41f4b71Sopenharmony_ci 104e41f4b71Sopenharmony_ci4. Synchronize data across devices. After **sync()** is called to trigger a sync, data is synced from the local device to all other devices on the network. 105e41f4b71Sopenharmony_ci 106e41f4b71Sopenharmony_ci ```ts 107e41f4b71Sopenharmony_ci // Construct the predicate object for synchronizing the distributed table. 108e41f4b71Sopenharmony_ci let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); 109e41f4b71Sopenharmony_ci // Call sync() to synchronize data. 110e41f4b71Sopenharmony_ci if(store != undefined) 111e41f4b71Sopenharmony_ci { 112e41f4b71Sopenharmony_ci (store as relationalStore.RdbStore).sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates, (err, result) => { 113e41f4b71Sopenharmony_ci // Check whether data sync is successful. 114e41f4b71Sopenharmony_ci if (err) { 115e41f4b71Sopenharmony_ci console.error(`Failed to sync data. Code:${err.code},message:${err.message}`); 116e41f4b71Sopenharmony_ci return; 117e41f4b71Sopenharmony_ci } 118e41f4b71Sopenharmony_ci console.info('Succeeded in syncing data.'); 119e41f4b71Sopenharmony_ci for (let i = 0; i < result.length; i++) { 120e41f4b71Sopenharmony_ci console.info(`device:${result[i][0]},status:${result[i][1]}`); 121e41f4b71Sopenharmony_ci } 122e41f4b71Sopenharmony_ci }) 123e41f4b71Sopenharmony_ci } 124e41f4b71Sopenharmony_ci ``` 125e41f4b71Sopenharmony_ci 126e41f4b71Sopenharmony_ci5. Subscribe to changes in the distributed data. The data sync triggers the **observer** callback registered in **on()**. The input parameter of the callback is the ID of the device whose data changes. 127e41f4b71Sopenharmony_ci 128e41f4b71Sopenharmony_ci ```ts 129e41f4b71Sopenharmony_ci let devices: string | undefined = undefined; 130e41f4b71Sopenharmony_ci try { 131e41f4b71Sopenharmony_ci // Register an observer to listen for the changes of the distributed data. 132e41f4b71Sopenharmony_ci // When data in the RDB store changes, the registered callback will be invoked to return the data changes. 133e41f4b71Sopenharmony_ci if(store != undefined) { 134e41f4b71Sopenharmony_ci (store as relationalStore.RdbStore).on('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (storeObserver)=>{ 135e41f4b71Sopenharmony_ci if(devices != undefined){ 136e41f4b71Sopenharmony_ci for (let i = 0; i < devices.length; i++) { 137e41f4b71Sopenharmony_ci console.info(`The data of device:${devices[i]} has been changed.`); 138e41f4b71Sopenharmony_ci } 139e41f4b71Sopenharmony_ci } 140e41f4b71Sopenharmony_ci }); 141e41f4b71Sopenharmony_ci } 142e41f4b71Sopenharmony_ci } catch (err) { 143e41f4b71Sopenharmony_ci console.error('Failed to register observer. Code:${err.code},message:${err.message}'); 144e41f4b71Sopenharmony_ci } 145e41f4b71Sopenharmony_ci // You can unsubscribe from the data changes if required. 146e41f4b71Sopenharmony_ci try { 147e41f4b71Sopenharmony_ci if(store != undefined) { 148e41f4b71Sopenharmony_ci (store as relationalStore.RdbStore).off('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (storeObserver)=>{ 149e41f4b71Sopenharmony_ci }); 150e41f4b71Sopenharmony_ci } 151e41f4b71Sopenharmony_ci } catch (err) { 152e41f4b71Sopenharmony_ci console.error('Failed to register observer. Code:${err.code},message:${err.message}'); 153e41f4b71Sopenharmony_ci } 154e41f4b71Sopenharmony_ci ``` 155e41f4b71Sopenharmony_ci 156e41f4b71Sopenharmony_ci6. Query data across devices. If data sync is not complete or triggered, an application can call **remoteQuery()** to query data from a remote device. 157e41f4b71Sopenharmony_ci 158e41f4b71Sopenharmony_ci > **NOTE** 159e41f4b71Sopenharmony_ci > 160e41f4b71Sopenharmony_ci > The value of **deviceIds** can be obtained by using [deviceManager.getAvailableDeviceListSync](../reference/apis-distributedservice-kit/js-apis-distributedDeviceManager.md#getavailabledevicelistsync) method. 161e41f4b71Sopenharmony_ci 162e41f4b71Sopenharmony_ci 163e41f4b71Sopenharmony_ci ```ts 164e41f4b71Sopenharmony_ci // Obtain device IDs. 165e41f4b71Sopenharmony_ci import { distributedDeviceManager } from '@kit.DistributedServiceKit'; 166e41f4b71Sopenharmony_ci import { BusinessError } from '@kit.BasicServicesKit'; 167e41f4b71Sopenharmony_ci 168e41f4b71Sopenharmony_ci let dmInstance: distributedDeviceManager.DeviceManager; 169e41f4b71Sopenharmony_ci let deviceId: string | undefined = undefined ; 170e41f4b71Sopenharmony_ci 171e41f4b71Sopenharmony_ci try { 172e41f4b71Sopenharmony_ci dmInstance = distributedDeviceManager.createDeviceManager("com.example.appdatamgrverify"); 173e41f4b71Sopenharmony_ci let devices = dmInstance.getAvailableDeviceListSync(); 174e41f4b71Sopenharmony_ci 175e41f4b71Sopenharmony_ci deviceId = devices[0].networkId; 176e41f4b71Sopenharmony_ci 177e41f4b71Sopenharmony_ci // Construct a predicate object for querying the distributed table. 178e41f4b71Sopenharmony_ci let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); 179e41f4b71Sopenharmony_ci // Query data from the specified remote device and return the query result. 180e41f4b71Sopenharmony_ci if(store != undefined && deviceId != undefined) { 181e41f4b71Sopenharmony_ci (store as relationalStore.RdbStore).remoteQuery(deviceId, 'EMPLOYEE', predicates, ['ID', 'NAME', 'AGE', 'SALARY', 'CODES'], 182e41f4b71Sopenharmony_ci (err: BusinessError, resultSet: relationalStore.ResultSet) => { 183e41f4b71Sopenharmony_ci if (err) { 184e41f4b71Sopenharmony_ci console.error(`Failed to remoteQuery data. Code:${err.code},message:${err.message}`); 185e41f4b71Sopenharmony_ci return; 186e41f4b71Sopenharmony_ci } 187e41f4b71Sopenharmony_ci console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); 188e41f4b71Sopenharmony_ci } 189e41f4b71Sopenharmony_ci ) 190e41f4b71Sopenharmony_ci } 191e41f4b71Sopenharmony_ci } catch (err) { 192e41f4b71Sopenharmony_ci let code = (err as BusinessError).code; 193e41f4b71Sopenharmony_ci let message = (err as BusinessError).message; 194e41f4b71Sopenharmony_ci console.error("createDeviceManager errCode:" + code + ",errMessage:" + message); 195e41f4b71Sopenharmony_ci } 196e41f4b71Sopenharmony_ci ``` 197