未验证 提交 c5aafca0 编写于 作者: O openharmony_ci 提交者: Gitee

!4146 #I56HWH完成,请审批

Merge pull request !4146 from Annie_wang/PR3715
......@@ -6,9 +6,9 @@
- Relational Database
- [RDB Overview](database-relational-overview.md)
- [RDB Development](database-relational-guidelines.md)
- Lightweight Data Store
- [Lightweight Data Store Overview](database-preference-overview.md)
- [Lightweight Data Store Development](database-preference-guidelines.md)
- Preferences
- [Preferences Overview](database-preference-overview.md)
- [Preferences Development](database-preference-guidelines.md)
- Distributed Data Object
- [Distributed Data Object Overview](database-distributedobject-overview.md)
- [Distributed Data Object Development](database-distributedobject-guidelines.md)
# Lightweight Data Store Development
# Preferences Development
## When to Use
The lightweight data store is ideal for storing lightweight and frequently used data, but not for storing a large amount of data or data with frequent changes. The application data is persistently stored on a device in the form of files. Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can perform data operations using the **Storage** APIs.
Preferences are ideal for storing data frequently used by applications, but not for storing a large amount of data or data with frequent changes. The application data is persistently stored on a device in the form of files. Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can perform data operations using the **Preferences** APIs.
## Available APIs
The lightweight data store provides applications with data processing capability and allows applications to perform lightweight data storage and query. Data is stored in key-value (KV) pairs. Keys are of the string type, and values can be of the number, string, or Boolean type.
Preferences provide capabilities for processing data in the form of key-value (KV) pairs and support data persistence, modification, and query. In KV pairs, keys are of the string type, and values can be of the number, string, or Boolean type.
**Creating a Storage Instance**
### Creating a Preferences Instance
Create a **Storage** instance for data operations. A **Storage** instance is created after data is read from a specified file and loaded to the instance.
Create a **Preferences** instance for data operations. A **Preferences** instance is created after data is read from a specified file and loaded to the instance.
**Table 1** API for creating a **Storage** instance
**Table 1** API for creating a **Preferences** instance
| Package | API | Description |
| ----------------- | ------------------------------------------- | ------------------------------------------- |
| ohos.data.storage | getStorage(path: string): Promise\<Storage> | Obtains the **Storage** singleton corresponding to a file for data operations.|
| ohos.data.preferences | getPreferences(context: Context, name: string): Promise\<Preferences> | Obtains a **Preferences** instance for data operations.|
**Writing Data**
### Writing Data
Call the **put()** method to add or modify data in a **Storage** instance.
Call the **put()** method to add or modify data in a **Preferences** instance.
**Table 2** API for writing data
| Class | API | Description |
| ------- | -------------------------------------------------- | ----------------------------------------------- |
| Storage | put(key: string, value: ValueType): Promise\<void> | Writes data of the number, string, and Boolean types.|
| Preferences | put(key: string, value: ValueType): Promise\<void> | Writes data of the number, string, and Boolean types.|
**Reading Data**
### Reading Data
Call the **get()** method to read data from a **Storage** instance.
Call the **get()** method to read data from a **Preferences** instance.
**Table 3** API for reading data
| Class | API | Description |
| ------- | ---------------------------------------------------------- | ----------------------------------------------- |
| Storage | get(key: string, defValue: ValueType): Promise\<ValueType> | Reads data of the number, string, and Boolean types.|
| Preferences | get(key: string, defValue: ValueType): Promise\<ValueType> | Reads data of the number, string, and Boolean types.|
**Storing Data Persistently**
### Storing Data Persistently
Call the **flush()** method to write the cached data back to its text file for persistent storage.
......@@ -46,119 +46,120 @@ Call the **flush()** method to write the cached data back to its text file for p
| Class | API | Description |
| ------- | ----------------------- | --------------------------------------- |
| Storage | flush(): Promise\<void> | Writes data in the **Storage** instance back to its file through an asynchronous thread.|
| Preferences | flush(): Promise\<void> | Writes data from the **Preferences** instance back to its file through an asynchronous thread.|
**Observing Data Changes**
### Observing Data Changes
Specify **StorageObserver** as the callback to subscribe to data changes. When the value of the subscribed key is changed and the **flush()** method is executed, **StorageObserver** will be invoked.
You can subscribe to data changes. When the value of the subscribed key is changed by **flush()**, a callback will be invoked to return the new data.
**Table 5** APIs for observing data changes
**Table 5** APIs for observing **Preferences** changes
| Class | API | Description |
| ------- | ------------------------------------------------------------ | -------------- |
| Storage | on(type: 'change', callback: Callback\<StorageObserver>): void | Subscribe to data changes.|
| Storage | off(type: 'change', callback: Callback\<StorageObserver>): void | Unsubscribes from data changes. |
| Preferences | on(type: 'change', callback: Callback<{ key : string }>): void | Subscribes to data changes.|
| Preferences | off(type: 'change', callback: Callback<{ key : string }>): void | Unsubscribes from data changes. |
**Deleting Data**
### Deleting Data
Use the following APIs to delete a **Storage** instance or data file.
Use the following APIs to delete a **Preferences** instance or data file.
**Table 6** APIs for deleting data
**Table 6** APIs for deleting **Preferences**
| Package | API | Description |
| ----------------- | ---------------------------------------------------- | ------------------------------------------------------------ |
| ohos.data.storage | deleteStorage(path: string): Promise\<void> | Deletes a **Storage** instance from the cache and deletes its file from the device.|
| ohos.data.storage | removeStorageFromCache(path: string): Promise\<void> | Deletes a **Storage** instance from the cache to release memory. |
| ohos.data.preferences | deletePreferences(context: Context, name: string): Promise<void>; | Deletes a **Preferences** instance from the cache and deletes its file from the device.|
| ohos.data.preferences | removePreferencesFromCache(context: Context, name: string): Promise\<void>; | Removes a **Preferences** instance from the memory to release memory.
## How to Develop
1. Import @ohos.data.storage and related modules to the development environment.
1. Import @ohos.data.preferences and related modules to the development environment.
```js
import dataStorage from '@ohos.data.storage'
import featureAbility from '@ohos.ability.featureAbility' // Used to obtain the file storage path.
import data_preferences from '@ohos.data.preferences'
```
2. Create a **Storage** instance.
2. Create a **Preferences** instance.
Read the specified file and load its data to the **Storage** instance for data operations.
Read the specified file and load its data to the **Preferences** instance for data operations.
```js
var context = featureAbility.getContext()
context.getFilesDir().then(() => {
console.info("======================>getFilesDirPromsie====================>");
});
let promise = dataStorage.getStorage(path + '/mystore')
let promise = data_preferences.getPreferences(this.context, 'mystore')
```
3. Write data.
Use the **put()** method of the **Storage** class to write data to the cached **Storage** instance.
Use the **put()** method of the **Preferences** class to write data to the cached **Preferences** instance.
```js
promise.then((storage) => {
let getPromise = storage.put('startup', 'auto') // Save data to the Storage instance.
promise.then((preferences) => {
let getPromise = preferences.put('startup', 'auto')
getPromise.then(() => {
console.info("Put the value of startup successfully.")
}).catch((err) => {
console.info("Put the value of startup failed with err: " + err)
console.info("Failed to put the value of startup with err: " + err)
})
}).catch((err) => {
console.info("Get the storage failed")
console.info("Failed to get the preferences")
})
```
4. Read data.
Use the **get()** method of the **Storage** class to read data.
Use the **get()** method of the **Preferences** class to read data.
```js
promise.then((storage) => {
let getPromise = storage.get('startup', 'default')
promise.then((preferences) => {
let getPromise = preferences.get('startup', 'default')
getPromise.then((value) => {
console.info("The value of startup is " + value)
}).catch((err) => {
console.info("Get the value of startup failed with err: " + err)
console.info("Failed to get the value of startup with err: " + err)
})
}).catch((err) => {
console.info("Get the storage failed")})
console.info("Failed to get the preferences")})
```
5. Store data persistently.
Use the **flush()** or **flushSync()** method to flush data in the **Storage** instance to its file.
Use the **flush()** method to flush data from the **Preferences** instance to its file.
```js
storage.flush();
preferences.flush();
```
6. Observe data changes.
6. Observe data changes.
Specify **StorageObserver** as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and the **flush()** method is executed, **StorageObserver** will be invoked. Unregister the **StorageObserver** when it is no longer required.
Specify an observer as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and the **flush()** method is executed, the observe callback will be invoked to return the change.
```js
promise.then((storage) => {
var observer = function (key) {
console.info("The key of " + key + " changed.")
}
storage.on('change', observer)
storage.putSync('startup', 'auto') // Modify data in the Storage instance.
storage.flushSync() // Trigger the StorageObserver callback.
storage.off(...change..., observer) // Unsubscribe from the data changes.
}).catch((err) => {
console.info("Get the storage failed")
})
var observer = function (key) {
console.info("The key of " + key + " changed.")
}
preferences.on('change', observer)
preferences.put('startup', 'auto', function (err) {
if (err) {
console.info("Failed to put the value of startup with err: " + err)
return
}
console.info("Put the value of startup successfully.")
preferences.flush(function (err) {
if (err) {
console.info("Failed to flush data to file with err: " + err)
return
}
console.info("Flushed to file successfully.") // Observer will be called.
})
})
```
7. Delete the specified file.
Use the **deleteStorage** method to delete the **Storage** singleton of the specified file from the memory, and delete the specified file, its backup file, and damaged files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will occur. The deleted data and files cannot be restored.
Use the **deletePreferences** method to delete the **Preferences** singleton of the specified file from the memory, and delete the specified file, its backup file, and corrupted files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will occur. The deleted data and files cannot be restored.
```js
let promise = dataStorage.deleteStorage(path + '/mystore')
promise.then(() => {
console.info("Deleted successfully.")
}).catch((err) => {
console.info("Deleted failed with err: " + err)})
let proDelete = data_preferences.deletePreferences(context, 'mystore')
proDelete.then(() => {
console.info("Data deleted successfully.")
}).catch((err) => {
console.info("Failed to delete data with err: " + err)
})
```
# Lightweight Data Store Overview<a name="EN-US_TOPIC_0000001230752103"></a>
# Preferences Overview
Lightweight data store is applicable to access and persistence operations on the data in key-value pairs. When an application accesses a lightweight **Storage** instance, data in the **Storage** instance will be cached in the memory for faster access. The cached data can also be written back to the text file for persistent storage. Since file read and write consume system resources, you are advised to minimize the frequency of reading and writing persistent files.
Preferences are used for access and persistence operations on the data in the key-value structure. When an application accesses a **Preferences** instance, the data in the instance will be cached in the memory for faster access. The cached data can also be written back to the text file for persistent storage. Since file read and write consume system resources, you are advised to minimize the frequency of reading and writing persistent files.
## Basic Concepts<a name="section1055404171115"></a>
## Basic Concepts
- **Key-Value data structure**
- **Key-value data structure**
A type of data structure. The key is the unique identifier for a piece of data, and the value is the specific data being identified.
A type of data structure. The key is the unique identifier for a piece of data, and the value is the specific data being identified.
- **Non-relational database**
- **Non-relational database**
A database not in compliance with the atomicity, consistency, isolation, and durability \(ACID\) database management properties of relational data transactions. The data in a non-relational database is independent.
A database not in compliance with the atomicity, consistency, isolation, and durability (ACID) database management properties of relational data transactions. The data in a non-relational database is independent.
## Working Principles
## Working Principles<a name="section682631371115"></a>
When an application loads data from a **Preferences** file to a **Preferences** instance, the system stores the instance in the memory through a static container. Each file of an application or process has only one **Preferences** instance in the memory, till the application removes the instance from the memory or deletes the **Preferences** file.
1. When an application loads data from a specified **Storage** file to a **Storage** instance, the system stores the instance in the memory through a static container. Each file of an application or process has only one **Storage** instance in the memory, till the application removes the instance from the memory or deletes the **Storage** file.
2. When obtaining a **Storage** instance, the application can read data from or write data to the instance. The data in the **Storage** instance can be flushed to its **Storage** file by calling the **flush** or **flushSync** method.
When obtaining a **Preferences** instance, the application can read data from or write data to the instance. The data in the instance can be flushed to its **Preferences** file by calling the **flush()** method.
**Figure 1** How lightweight data store works<a name="fig1657785713509"></a>
**Figure 1** How **Preferences** work
![](figures/preferences.png)
![](figures/en-us_image_0000001199139454.png)
## Constraints<a name="section17243172883219"></a>
- **Storage** instances are loaded to the memory. To minimize non-memory overhead, the number of data records stored in a **Storage** instance cannot exceed 10,000. Delete the instances that are no longer used in a timely manner.
- The key in the key-value pairs is of the string type. It cannot be empty or exceed 80 characters.
- If the value in the key-value pairs is of the string type, it can be empty or contain a maximum of 8192 characters.
## Constraints
- **Preferences** instances are loaded to the memory. To minimize non-memory overhead, the number of data records stored in a **Preferences** instance cannot exceed 10,000. Delete the instances that are no longer used in a timely manner.
- The key in key-value pairs is of the string type. It cannot be empty or exceed 80 bytes.
- The value of the string type in key-value pairs can be empty, but cannot exceed 8192 bytes if not empty.
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册