DEV Community

Cover image for HarmonyOS Development: Realizing Key-Value Database Storage
程序员一鸣
程序员一鸣

Posted on

HarmonyOS Development: Realizing Key-Value Database Storage

Foreword 

this article is based on Api12 

the persistent storage of data in Hongmeng provides us with a variety of implementations, such as user preferences, relational databases, key-value database mode, file storage mode, etc., for relatively small data volume, we can directly choose lightweight user preference mode, while for relatively large data volume, we can directly use the database, while for relatively large data, we can use key-value database mode, which is a data storage mode between user preference and relational database. 

The Key-Value database is very simple to use. From the literal meaning, it can be known that it stores and acquires data in the form of Key-Value pairs, which is similar to user preferences. However, the Key-Value database has its own restrictive factors. The first is that for each record, the length of Key ≤ 896 Byte, and the length of Value <4MB, for a single-version database, the length of each record is less than or equal to 1KB, and the length of Value is less than 4MB. Each application supports opening up to 16 Key-Value distributed databases at the same time. The last one is that blocking operations are not allowed in the Key-Value database event callback method, such as modifying UI components. 

Common objects in key-value databases are as follows:

 

KVManager: A distributed key value database management instance used to retrieve relevant information from the database.
KVStoreResultSet: Provides methods for obtaining database result sets, including querying and moving data read locations.
Query: Use predicates to represent database queries, providing methods for creating Query instances, querying data in the database, and adding predicates.
SingleKVStore: A single version distributed key value database that does not distinguish the devices to which the data belongs, providing methods for querying and synchronizing data.
DeviceKVStore: Device collaborative database, inherited from SingleKVStore, distinguishes data based on device dimensions, and provides methods for querying and synchronizing data.
Enter fullscreen mode Exit fullscreen mode

the specific data storage is not introduced here, you can directly view the official documents, here is to introduce the specific usage of the key-value database after encapsulation. 

Rapid dependence 

method 1: in the Terminal window, run the following command to install the third-party package. DevEco Studio automatically adds the third-party package dependency to the project oh-package.json5.

Suggestion: Execute the command under the module path used.


ohpm install @abner/datastore
Enter fullscreen mode Exit fullscreen mode

Method 2: Set the three-party package dependency in the project oh-package.json5. The configuration example is as follows:

 

"dependencies": { "@abner/datastore": "^1.0.3"}
Enter fullscreen mode Exit fullscreen mode

code call 

1. Initialization 

it is recommended to initialize in the AbilityStage. If you want to use multiple file instances for storage, you can pass the second parameter.

 

DataKvUtil.getInstance().init(this.context, "com.abner.tool")
Enter fullscreen mode Exit fullscreen mode

Related Property Introduction 

property type overview
context  Context  context 
bundleName  string  caller's package name 
option  distributedKVStore.Options  (Optional) Database configuration information 
option related parameters 
property type required description
createIfMissing  boolean  no  whether to create a database when the database file does not exist. The default value is true.
encrypt  boolean  no  set whether the database file is encrypted. Encapsulation defaults to true, that is, it is not encrypted. 
backup  boolean  no  set whether the database file is backed up. Encapsulation defaults to true, that is, backup. 
autoSync  boolean  no  sets whether the database files are automatically synchronized. Encapsulation defaults to true, that is, Manual synchronization. 
kvStoreType  KVStoreType  no  set the type of the database to be created. The default value is DEVICE_COLLABORATION, which is a multi-device collaboration database. 
securityLevel  SecurityLevel  yes  set the database security level. 
schema  Schema  no  sets the value of the definition stored in the database. The default value is undefined, that is, no Schema is used. 
KVStoreType
KVStoreType Distributed Key Value Database Type Enumeration.

DEVICE_COLLABORATION

Represents a multi device collaborative database.

Database features: Data is managed in the dimension of devices, without conflicts; Support querying data based on device dimensions.

SINGLE_VERSION

Represents a single version database.

Database characteristics: Data is not device specific, and modifying the same key between devices will overwrite it.
Enter fullscreen mode Exit fullscreen mode
SecurityLevel


 

Enumeration of database security levels.

S1

The security level of the database is low, and data leakage, tampering, destruction, and destruction may have limited adverse effects on individuals or organizations.

For example, gender, nationality, user application records, etc.

S2

The security level of the database is considered medium, and data leakage, tampering, destruction, and destruction may cause serious adverse effects on individuals or organizations.

For example, personal detailed mailing address, name nickname, etc.

S3

The security level of the database is high, and data leakage, tampering, destruction, and destruction may have serious adverse effects on individuals or organizations.

For example, personal real-time precise positioning information, motion trajectories, etc.

S4

The security level of the database is considered critical, which is a special type of data defined in industry laws and regulations. It involves information in the most private areas of individuals or data that may cause significant adverse effects to individuals or organizations if leaked, tampered with, destroyed, or destroyed.

For example, political views, religious and philosophical beliefs, union membership, genetic data, biological information, health and sexual status, sexual orientation, or device authentication, personal credit card and other financial information.
Enter fullscreen mode Exit fullscreen mode

2. Data storage


 

DataKvUtil.getInstance().put("key", "value")
Enter fullscreen mode Exit fullscreen mode

whether listening is successfully stored


DataKvUtil.getInstance().put("key", "value", (isSuccess:boolean) => {

})
Enter fullscreen mode Exit fullscreen mode

listens for storage success and failure


DataKvUtil.getInstance().put("key", "value", (isSuccess:boolean, err:BusinessError) => {
  //When isSuccess is false, err is the error message
})
Enter fullscreen mode Exit fullscreen mode

using Promise asynchronous callbacks


let pPromise = DataKvUtil.getInstance().putPromise("key", "value")
Enter fullscreen mode Exit fullscreen mode

3 Obtaining data


 

DataKvUtil.getInstance().get("key", (data) => {

})
Enter fullscreen mode Exit fullscreen mode

monitoring failed


DataKvUtil.getInstance().get("key", (data) => {

}, (err:BusinessError) => {

})
Enter fullscreen mode Exit fullscreen mode

using Promise asynchronous callbacks


let pPromise = DataKvUtil.getInstance().getPromise("key")
Enter fullscreen mode Exit fullscreen mode

4. Delete data


 

DataKvUtil.getInstance().delete("key")
Enter fullscreen mode Exit fullscreen mode

whether the listener is deleted successfully


DataKvUtil.getInstance().delete("key", (isSuccess: boolean) => {

})
Enter fullscreen mode Exit fullscreen mode

whether the monitor fails to be deleted


DataKvUtil.getInstance().delete("key", (isSuccess: boolean, err?: BusinessError) => {

})
Enter fullscreen mode Exit fullscreen mode

using Promise asynchronous callbacks


let pPromise = DataKvUtil.getInstance().deletePromise("key")
Enter fullscreen mode Exit fullscreen mode

5. Modify data 

the modification is consistent with the addition, and the data will overwrite the original key.


6. Get the default StoreId


 

DataKvUtil.getInstance().getStoreId()
Enter fullscreen mode Exit fullscreen mode

7. Delete the specified distributed key-value database


 

DataKvUtil.getInstance().deleteKVStore("storeId")
Enter fullscreen mode Exit fullscreen mode

whether the listener is deleted successfully


DataKvUtil.getInstance().deleteKVStore("storeId", (isSuccess: boolean) => {

})
Enter fullscreen mode Exit fullscreen mode

whether the monitor fails to be deleted


DataKvUtil.getInstance().deleteKVStore("storeId", (isSuccess: boolean, err?: BusinessError) => {

})
Enter fullscreen mode Exit fullscreen mode

8. Create a new and get the distributed key-value database. 

There will be one by default, if you plan to create a new one, you can call this method!

 

DataKvUtil.getInstance().createKVStore("storeId")
Enter fullscreen mode Exit fullscreen mode

9. The new database is added, deleted, changed and checked 

first set up your own database, that is, storeId in section 7.

DataKvUtil.getInstance().setKVStore("storeId") 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)