1# Persisting RDB Store Data 2 3 4## When to Use 5 6A relational database (RDB) store is used to store data in complex relational models, such as the student information including names, student IDs, and scores of each subject, or employee information including names, employee IDs, and positions, based on SQLite. The data is more complex than key-value (KV) pairs due to strict mappings. You can use **RelationalStore** to implement persistence of this type of data. 7 8Querying data from a large amount of data may take time or even cause application suspension. In this case, you can perform batch operations. For details, see [Batch Database Operations](../arkts-utils/batch-database-operations-guide.md). Moreover, observe the following: 9- The number of data records to be queried at a time should not exceed 5000. 10- Use [TaskPool](../reference/apis-arkts/js-apis-taskpool.md) if there is a large amount of data needs to be queried. 11- Keep concatenated SQL statements as concise as possible. 12- Query data in batches. 13 14## Basic Concepts 15 16- **Predicates**: a representation of the property or feature of a data entity, or the relationship between data entities. It is used to define operation conditions. 17 18- **ResultSet**: a set of query results, which allows access to the required data in flexible modes. 19 20 21## Working Principles 22 23**RelationalStore** provides APIs for applications to perform data operations. With SQLite as the underlying persistent storage engine, **RelationalStore** provides SQLite database features, including transactions, indexes, views, triggers, foreign keys, parameterized queries, prepared SQL statements, and more. 24 25**Figure 1** Working mechanism 26 27 28 29 30## Constraints 31 32- The default logging mode is Write Ahead Log (WAL), and the default flushing mode is **FULL** mode. 33 34- The RDB store supports a maximum of four read connections and one write connection. A thread performs the read operation when acquiring a read connection. When there is no read connection available but the write connection is idle, the write connection can be used to perform the read operation. 35 36- To ensure data accuracy, only one write operation is allowed at a time. 37 38- Once an application is uninstalled, related database files and temporary files on the device are automatically deleted. 39 40- ArkTS supports the following basic data types: number, string, binary data, and boolean. 41 42- The maximum size of a data record is 2 MB. If a data record exceeds 2 MB, it can be inserted successfully but cannot be read. 43 44## Available APIs 45 46The following table lists the APIs used for RDB data persistence. Most of the APIs 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). 47 48| API| Description| 49| -------- | -------- | 50| getRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback<RdbStore>): void | Obtains an **RdbStore** instance to implement RDB store operations. You can set **RdbStore** parameters based on actual requirements and use **RdbStore** APIs to perform data operations.| 51| executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void | Executes an SQL statement that contains specified arguments but returns no value.| 52| insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void | Inserts a row of data into a table.| 53| update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void | Updates data in the RDB store based on the specified **predicates** instance.| 54| delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void | Deletes data from the RDB store based on the specified **predicates** instance.| 55| query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void | Queries data in the RDB store based on specified conditions.| 56| deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void>): void | Deletes an RDB store.| 57 58 59## How to Develop 60Unless otherwise specified, the sample code without "stage model" or "FA model" applies to both models. 61 62If error code 14800011 is reported, the RDB store is corrupted and needs to be rebuilt. For details, see [Rebuilding an RDB Store](data-backup-and-restore.md#rebuilding-an-rdb-store). 63 641. Obtain an **RdbStore** instance, which includes operations of creating an RDB store and tables, and upgrading or downgrading the RDB store. <br>Example: 65 66 Stage model: 67 68 ```ts 69 import { relationalStore} from '@kit.ArkData'; // Import the relationalStore module. 70 import { UIAbility } from '@kit.AbilityKit'; 71 import { BusinessError } from '@kit.BasicServicesKit'; 72 import { window } from '@kit.ArkUI'; 73 74 // In this example, Ability is used to obtain an RdbStore instance. You can use other implementations as required. 75 class EntryAbility extends UIAbility { 76 onWindowStageCreate(windowStage: window.WindowStage) { 77 const STORE_CONFIG :relationalStore.StoreConfig= { 78 name: 'RdbTest.db', // Database file name. 79 securityLevel: relationalStore.SecurityLevel.S3, // Database security level. 80 encrypt: false, // Whether to encrypt the database. This parameter is optional. By default, the database is not encrypted. 81 customDir: 'customDir/subCustomDir' // (Optional) Customized database path. The database is created in the context.databaseDir + '/rdb/' + customDir directory, where context.databaseDir indicates the application sandbox path, '/rdb/' indicates a relational database, and customDir indicates the customized path. If this parameter is not specified, an RdbStore instance is created in the sandbox directory of the application. 82 isReadOnly: false // (Optional) Specify whether the RDB store is opened in read-only mode. The default value is false, which means the RDB store is readable and writable. If this parameter is true, data can only be read from the RDB store. If write operation is performed, error code 801 is returned. 83 }; 84 85 // Check the RDB store version. If the version is incorrect, upgrade or downgrade the RDB store. 86 // For example, the RDB store version is 3 and the table structure is EMPLOYEE (NAME, AGE, SALARY, CODES, IDENTITY). 87 const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB, IDENTITY UNLIMITED INT)'; // SQL statement used to create a table. In the statement, the IDENTITY type bigint should be UNLIMITED INT. 88 89 relationalStore.getRdbStore(this.context, STORE_CONFIG, (err, store) => { 90 if (err) { 91 console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`); 92 return; 93 } 94 console.info('Succeeded in getting RdbStore.'); 95 96 // When the RDB store is created, the default version is 0. 97 if (store.version === 0) { 98 store.executeSql(SQL_CREATE_TABLE); // Create a data table. 99 // Set the RDB store version, which must be an integer greater than 0. 100 store.version = 3; 101 } 102 103 // If the RDB store version is not 0 and does not match the current version, upgrade or downgrade the RDB store. 104 // For example, upgrade the RDB store from version 1 to version 2. 105 if (store.version === 1) { 106 // Upgrade the RDB store from version 1 to version 2, and change the table structure from EMPLOYEE (NAME, SALARY, CODES, ADDRESS) to EMPLOYEE (NAME, AGE, SALARY, CODES, ADDRESS). 107 (store as relationalStore.RdbStore).executeSql('ALTER TABLE EMPLOYEE ADD COLUMN AGE INTEGER'); 108 store.version = 2; 109 } 110 111 // For example, upgrade the RDB store from version 2 to version 3. 112 if (store.version === 2) { 113 // Upgrade the RDB store from version 2 to version 3, and change the table structure from EMPLOYEE (NAME, AGE, SALARY, CODES, ADDRESS) to EMPLOYEE (NAME, AGE, SALARY, CODES). 114 (store as relationalStore.RdbStore).executeSql('ALTER TABLE EMPLOYEE DROP COLUMN ADDRESS TEXT'); 115 store.version = 3; 116 } 117 }); 118 119 // Before performing data operations on the database, obtain an RdbStore instance. 120 } 121 } 122 ``` 123 124 FA model: 125 126 ```ts 127 import { relationalStore} from '@kit.ArkData'; // Import the relationalStore module. 128 import { featureAbility } from '@kit.AbilityKit'; 129 import { BusinessError } from '@kit.BasicServicesKit'; 130 131 let context = featureAbility.getContext(); 132 133 const STORE_CONFIG :relationalStore.StoreConfig = { 134 name: 'RdbTest.db', // Database file name. 135 securityLevel: relationalStore.SecurityLevel.S3 // Database security level. 136 }; 137 138 // For example, the RDB store version is 3 and the table structure is EMPLOYEE (NAME, AGE, SALARY, CODES, IDENTITY). 139 const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB, IDENTITY UNLIMITED INT)'; // SQL statement used to create a table. In the statement, the IDENTITY type bigint should be UNLIMITED INT. 140 141 relationalStore.getRdbStore(context, STORE_CONFIG, (err, store) => { 142 if (err) { 143 console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`); 144 return; 145 } 146 console.info('Succeeded in getting RdbStore.'); 147 148 // When the RDB store is created, the default version is 0. 149 if (store.version === 0) { 150 store.executeSql(SQL_CREATE_TABLE); // Create a data table. 151 // Set the RDB store version, which must be an integer greater than 0. 152 store.version = 3; 153 } 154 155 // If the RDB store version is not 0 and does not match the current version, upgrade or downgrade the RDB store. 156 // For example, upgrade the RDB store from version 1 to version 2. 157 if (store.version === 1) { 158 // Upgrade the RDB store from version 1 to version 2, and change the table structure from EMPLOYEE (NAME, SALARY, CODES, ADDRESS) to EMPLOYEE (NAME, AGE, SALARY, CODES, ADDRESS). 159 store.executeSql('ALTER TABLE EMPLOYEE ADD COLUMN AGE INTEGER'); 160 store.version = 2; 161 } 162 163 // For example, upgrade the RDB store from version 2 to version 3. 164 if (store.version === 2) { 165 // Upgrade the RDB store from version 2 to version 3, and change the table structure from EMPLOYEE (NAME, AGE, SALARY, CODES, ADDRESS) to EMPLOYEE (NAME, AGE, SALARY, CODES). 166 store.executeSql('ALTER TABLE EMPLOYEE DROP COLUMN ADDRESS TEXT'); 167 store.version = 3; 168 } 169 }); 170 171 // Before performing data operations on the database, obtain an RdbStore instance. 172 ``` 173 174 > **NOTE** 175 > 176 > - The RDB store created by an application varies with the context. Multiple RDB stores are created for the same database name with different application contexts. For example, each UIAbility has its own context. 177 > 178 > - When an application calls **getRdbStore()** to obtain an RDB store instance for the first time, the corresponding database file is generated in the application sandbox. When the RDB store is used, temporary files ended with **-wal** and **-shm** may be generated in the same directory as the database file. If you want to move the database files to other places, you must also move these temporary files. After the application is uninstalled, the database files and temporary files generated on the device are also removed. 179 > 180 > - For details about the error codes, see [Universal Error Codes](../reference/errorcode-universal.md) and [RDB Store Error Codes](../reference/apis-arkdata/errorcode-data-rdb.md). 181 1822. Use **insert()** to insert data to the RDB store. <br>Example: 183 184 ```ts 185 let store: relationalStore.RdbStore | undefined = undefined; 186 187 let value1 = 'Lisa'; 188 let value2 = 18; 189 let value3 = 100.5; 190 let value4 = new Uint8Array([1, 2, 3, 4, 5]); 191 let value5 = BigInt('15822401018187971961171'); 192 // You can use either of the following: 193 const valueBucket1: relationalStore.ValuesBucket = { 194 'NAME': value1, 195 'AGE': value2, 196 'SALARY': value3, 197 'CODES': value4, 198 'IDENTITY': value5, 199 }; 200 const valueBucket2: relationalStore.ValuesBucket = { 201 NAME: value1, 202 AGE: value2, 203 SALARY: value3, 204 CODES: value4, 205 IDENTITY: value5, 206 }; 207 const valueBucket3: relationalStore.ValuesBucket = { 208 "NAME": value1, 209 "AGE": value2, 210 "SALARY": value3, 211 "CODES": value4, 212 "IDENTITY": value5, 213 }; 214 215 if (store !== undefined) { 216 (store as relationalStore.RdbStore).insert('EMPLOYEE', valueBucket1, (err: BusinessError, rowId: number) => { 217 if (err) { 218 console.error(`Failed to insert data. Code:${err.code}, message:${err.message}`); 219 return; 220 } 221 console.info(`Succeeded in inserting data. rowId:${rowId}`); 222 }) 223 } 224 ``` 225 226 > **NOTE** 227 > 228 > **RelationalStore** does not provide explicit flush operations for data persistence. The **insert()** method stores data persistently. 229 2303. Modify or delete data based on the specified **Predicates** instance. 231 232 Use **update()** to modify data and **delete()** to delete data. <br>Example: 233 234 ```ts 235 let value6 = 'Rose'; 236 let value7 = 22; 237 let value8 = 200.5; 238 let value9 = new Uint8Array([1, 2, 3, 4, 5]); 239 let value10 = BigInt('15822401018187971967863'); 240 // You can use either of the following: 241 const valueBucket4: relationalStore.ValuesBucket = { 242 'NAME': value6, 243 'AGE': value7, 244 'SALARY': value8, 245 'CODES': value9, 246 'IDENTITY': value10, 247 }; 248 const valueBucket5: relationalStore.ValuesBucket = { 249 NAME: value6, 250 AGE: value7, 251 SALARY: value8, 252 CODES: value9, 253 IDENTITY: value10, 254 }; 255 const valueBucket6: relationalStore.ValuesBucket = { 256 "NAME": value6, 257 "AGE": value7, 258 "SALARY": value8, 259 "CODES": value9, 260 "IDENTITY": value10, 261 }; 262 263 // Modify data. 264 let predicates1 = new relationalStore.RdbPredicates('EMPLOYEE'); // Create predicates for the table named EMPLOYEE. 265 predicates1.equalTo('NAME', 'Lisa'); // Modify the data of Lisa in the EMPLOYEE table to the specified data. 266 if (store !== undefined) { 267 (store as relationalStore.RdbStore).update(valueBucket4, predicates1, (err: BusinessError, rows: number) => { 268 if (err) { 269 console.error(`Failed to update data. Code:${err.code}, message:${err.message}`); 270 return; 271 } 272 console.info(`Succeeded in updating data. row count: ${rows}`); 273 }) 274 } 275 276 // Delete data. 277 predicates1 = new relationalStore.RdbPredicates('EMPLOYEE'); 278 predicates1.equalTo('NAME', 'Lisa'); 279 if (store !== undefined) { 280 (store as relationalStore.RdbStore).delete(predicates1, (err: BusinessError, rows: number) => { 281 if (err) { 282 console.error(`Failed to delete data. Code:${err.code}, message:${err.message}`); 283 return; 284 } 285 console.info(`Delete rows: ${rows}`); 286 }) 287 } 288 ``` 289 2904. Query data based on the conditions specified by **Predicates**. 291 292 Use **query()** to query data. The data obtained is returned in a **ResultSet** object. <br>Example: 293 294 ```ts 295 let predicates2 = new relationalStore.RdbPredicates('EMPLOYEE'); 296 predicates2.equalTo('NAME', 'Rose'); 297 if (store !== undefined) { 298 (store as relationalStore.RdbStore).query(predicates2, ['ID', 'NAME', 'AGE', 'SALARY', 'IDENTITY'], (err: BusinessError, resultSet) => { 299 if (err) { 300 console.error(`Failed to query data. Code:${err.code}, message:${err.message}`); 301 return; 302 } 303 console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); 304 // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0. 305 while (resultSet.goToNextRow()) { 306 const id = resultSet.getLong(resultSet.getColumnIndex('ID')); 307 const name = resultSet.getString(resultSet.getColumnIndex('NAME')); 308 const age = resultSet.getLong(resultSet.getColumnIndex('AGE')); 309 const salary = resultSet.getDouble(resultSet.getColumnIndex('SALARY')); 310 const identity = resultSet.getValue(resultSet.getColumnIndex('IDENTITY')); 311 console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}, identity=${identity}`); 312 } 313 // Release the data set memory. 314 resultSet.close(); 315 }) 316 } 317 ``` 318 319 > **NOTE** 320 > 321 > Use **close()** to close the **ResultSet** that is no longer used in a timely manner so that the memory allocated can be released. 322 3235. Back up the database in the same directory. 324 325 Two backup modes are available: manual backup and automatic backup (available only for system applications). For details, see [Backing Up an RDB Store](data-backup-and-restore.md#backing-up-an-rdb store). 326 327 Example: Perform manual backup of an RDB store. 328 329 ```ts 330 if (store !== undefined) { 331 // Backup.db indicates the name of the database backup file. By default, it is in the same directory as the RdbStore file. You can also specify the directory, which is in the customDir + backup.db format. 332 (store as relationalStore.RdbStore).backup("Backup.db", (err: BusinessError) => { 333 if (err) { 334 console.error(`Failed to backup RdbStore. Code:${err.code}, message:${err.message}`); 335 return; 336 } 337 console.info(`Succeeded in backing up RdbStore.`); 338 }) 339 } 340 ``` 341 3426. Restore data from the database backup. 343 344 You can restore an RDB store from the manual backup data or automatic backup data (available only for system applications). For details, see [Restoring RDB Store Data](data-backup-and-restore.md#restoring-rdb-store-data). 345 346 Example: Call [restore](../reference/apis-arkdata/js-apis-data-relationalStore.md#restore) to restore an RDB store from the data that is manually backed up. 347 348 ```ts 349 if (store !== undefined) { 350 (store as relationalStore.RdbStore).restore("Backup.db", (err: BusinessError) => { 351 if (err) { 352 console.error(`Failed to restore RdbStore. Code:${err.code}, message:${err.message}`); 353 return; 354 } 355 console.info(`Succeeded in restoring RdbStore.`); 356 }) 357 } 358 ``` 359 3607. Delete the RDB store. 361 362 Use **deleteRdbStore()** to delete the RDB store and related database files. <br>Example: 363 364 Stage model: 365 366 ```ts 367 relationalStore.deleteRdbStore(this.context, 'RdbTest.db', (err: BusinessError) => { 368 if (err) { 369 console.error(`Failed to delete RdbStore. Code:${err.code}, message:${err.message}`); 370 return; 371 } 372 console.info('Succeeded in deleting RdbStore.'); 373 }); 374 ``` 375 376 FA model: 377 378 ```ts 379 relationalStore.deleteRdbStore(context, 'RdbTest.db', (err: BusinessError) => { 380 if (err) { 381 console.error(`Failed to delete RdbStore. Code:${err.code}, message:${err.message}`); 382 return; 383 } 384 console.info('Succeeded in deleting RdbStore.'); 385 }); 386 ```