• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Database Backup and Restoration
2
3
4## When to Use
5
6You may need to restore a database in any of the following cases:
7
8An important operation being performed by an application is interrupted.
9
10The database is unavailable due to data loss or corruption, or dirty data.
11
12
13Both KV stores and RDB stores support database backup and restoration. In addition, KV stores allow you to delete database backups to release local storage space.
14
15
16## Backing Up, Restoring, and Deleting a KV Store
17
18You can use **backup()** to back up a KV store, use **restore()** to restore a KV store, and use **deletebackup()** to delete a KV store backup file. For details about the APIs, see [Distributed KV Store](../reference/apis/js-apis-distributedKVStore.md).
19
201. Create a KV store.
21
22   (1) Create a **kvManager** instance.
23
24   (2) Set database parameters.
25
26   (3) Create a **kvStore** instance.
27
28
29   ```js
30   import distributedKVStore from '@ohos.data.distributedKVStore';
31
32   let kvManager;
33   let context = getContext(this);
34   const kvManagerConfig = {
35     context: context,
36     bundleName: 'com.example.datamanagertest'
37   }
38   try {
39     kvManager = distributedKVStore.createKVManager(kvManagerConfig);
40     console.info('Succeeded in creating KVManager.');
41   } catch (e) {
42     console.error(`Failed to create KVManager. Code:${e.code},message:${e.message}`);
43   }
44   let kvStore;
45   try {
46     const options = {
47       createIfMissing: true,
48       encrypt: false,
49       backup: false,
50       autoSync: true,
51       kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
52       securityLevel: distributedKVStore.SecurityLevel.S2
53     };
54     kvManager.getKVStore('storeId', options, (err, store) => {
55       if (err) {
56         console.error(`Fail to get KVStore. Code:${err.code},message:${err.message}`);
57         return;
58       }
59       console.info('Succeeded in getting KVStore.');
60       kvStore = store;
61     });
62   } catch (e) {
63     console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`);
64   }
65   ```
66
672. Use **put()** to insert data to the KV store.
68
69   ```js
70   const KEY_TEST_STRING_ELEMENT = 'key_test_string';
71   const VALUE_TEST_STRING_ELEMENT = 'value_test_string';
72   try {
73     kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
74       if (err !== undefined) {
75         console.error(`Fail to put data. Code:${err.code},message:${err.message}`);
76         return;
77       }
78       console.info('Succeeded in putting data.');
79     });
80   } catch (e) {
81     console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`);
82   }
83   ```
84
853. Use **backup()** to back up the KV store.
86
87   ```js
88   let file = 'BK001';
89   try {
90     kvStore.backup(file, (err) => {
91       if (err) {
92         console.error(`Fail to backup data.code:${err.code},message:${err.message}`);
93       } else {
94         console.info('Succeeded in backupping data.');
95       }
96     });
97   } catch (e) {
98     console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`);
99   }
100   ```
101
1024. Use **delete()** to delete data to simulate unexpected deletion or data tampering.
103
104   ```js
105   try {
106     kvStore.delete(KEY_TEST_STRING_ELEMENT, (err) => {
107       if (err !== undefined) {
108         console.error(`Fail to delete data. Code:${err.code},message:${err.message}`);
109         return;
110       }
111       console.info('Succeeded in deleting data.');
112     });
113   } catch (e) {
114     console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`);
115   }
116   ```
117
1185. Use **restore()** to restore the KV store.
119
120   ```js
121   let file = 'BK001';
122   try {
123     kvStore.restore(file, (err) => {
124       if (err) {
125         console.error(`Fail to restore data. Code:${err.code},message:${err.message}`);
126       } else {
127         console.info('Succeeded in restoring data.');
128       }
129     });
130   } catch (e) {
131     console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`);
132   }
133   ```
134
1356. Use **deleteBackup()** to delete the backup file to release storage space.
136
137   ```js
138   let kvStore;
139   let files = ['BK001'];
140   try {
141     kvStore.deleteBackup(files).then((data) => {
142       console.info(`Succeed in deleting Backup. Data:filename is ${data[0]},result is ${data[1]}.`);
143     }).catch((err) => {
144       console.error(`Fail to delete Backup. Code:${err.code},message:${err.message}`);
145     })
146   } catch (e) {
147     console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`);
148   }
149   ```
150
151
152## Backing Up and Restoring an RDB Store
153
154You can use **backup()** to back up an RDB store, and use **restore()** to restore an RDB store. For details about the APIs, see [RDB Store](../reference/apis/js-apis-data-relationalStore.md).
155
1561. Use **getRdbStore()** to create an RDB store.
157
158   ```js
159   import relationalStore from '@ohos.data.relationalStore';
160
161   let store;
162   let context = getContext(this);
163   const STORE_CONFIG = {
164     name: 'RdbTest.db',
165     securityLevel: relationalStore.SecurityLevel.S1
166   };
167   relationalStore.getRdbStore(context, STORE_CONFIG, (err, rdbStore) => {
168     store = rdbStore;
169     if (err) {
170       console.error(`Failed to get RdbStore. Code:${err.code},message:${err.message}`);
171       return;
172     }
173     store.executeSql("CREATE TABLE IF NOT EXISTS EMPLOYEE (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER, salary INTEGER, codes Uint8Array);", null);
174     console.info('Succeeded in getting RdbStore.');
175   })
176   ```
177
1782. Use **insert()** to insert data to the RDB store.
179
180   ```js
181   const valueBucket = {
182     'NAME': 'Lisa',
183     'AGE': 18,
184     'SALARY': 100.5,
185     'CODES': new Uint8Array([1, 2, 3, 4, 5])
186   };
187   store.insert('EMPLOYEE', valueBucket, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, (err, rowId) => {
188     if (err) {
189       console.error(`Failed to insert data. Code:${err.code},message:${err.message}`);
190       return;
191     }
192     console.info(`Succeeded in inserting data. rowId:${rowId}`);
193   })
194   ```
195
1963. Use **backup()** to back up the RDB store.
197
198   ```js
199   store.backup('dbBackup.db', (err) => {
200     if (err) {
201       console.error(`Failed to backup data. Code:${err.code},message:${err.message}`);
202       return;
203     }
204     console.info(`Succeeded in backuping data.`);
205   })
206   ```
207
2084. Use **delete()** to delete data to simulate unexpected deletion or data tampering.
209
210   ```js
211   let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
212   predicates.equalTo('NAME', 'Lisa');
213   let promise = store.delete(predicates);
214   promise.then((rows) => {
215     console.info(`Delete rows: ${rows}`);
216   }).catch((err) => {
217     console.error(`Failed to delete data. Code:${err.code},message:${err.message}`);
218   })
219   ```
220
2215. Use **restore()** to restore the RDB store.
222
223   ```js
224   store.restore('dbBackup.db', (err) => {
225     if (err) {
226       console.error(`Failed to restore data. Code:${err.code},message:${err.message}`);
227       return;
228     }
229     console.info(`Succeeded in restoring data.`);
230   })
231   ```
232