diff --git a/en/watermelondb.md b/en/watermelondb.md
new file mode 100644
index 0000000000000000000000000000000000000000..d250216ea3a97a02b303298b27be7e1941bc5916
--- /dev/null
+++ b/en/watermelondb.md
@@ -0,0 +1,948 @@
+> Template version:v0.3.0
+
+
+
watermelondb
+
+
+This project is developed based on [watermelondb@[v0.28.1-0](https://github.com/Nozbe/WatermelonDB)].
+
+Please go to the Releases page of the third-party library to check the matching version information: ([@react-native-ohos/watermelondb Releases](https://gitcode.com/OpenHarmony-RN/rntpc_watermelondb)). For older versions that have not been released to npm, please refer to the Installation [Install Guide](/zh-cn/tgz-usage.md)。
+
+ information:
+| Third-party library version | Release information | Supported RN version |
+| ---------- | -------------------------------------------------------------------------------------------------------------------------- | ------------ |
+| v0.28.1-0 | [@react-native-ohos/watermelondb Releases](https://github.com/) | 0.72/0.77 |
+
+## 1. Installation and Usage
+
+Go to the project directory and execute the following instruction:
+
+#### npm
+
+```bash
+npm install @react-native-ohos/watermelondb
+```
+
+#### yarn
+
+```bash
+yarn add @react-native-ohos/watermelondb
+```
+
+The following code demonstrates the basic usage scenarios of this library:
+
+> [!WARNING] The library name imported remains unchanged during usage.
+### watermelondb example
+```js
+// jsi: false
+import React, { useState } from 'react';
+import { View, Text, Button, StyleSheet, ScrollView } from 'react-native';
+import {
+ appSchema,
+ tableSchema,
+ tableName,
+ columnName,
+ validateColumnSchema,
+} from '@nozbe/watermelondb/Schema';
+import { Database } from '@nozbe/watermelondb';
+import SQLiteAdapter from '@nozbe/watermelondb/adapters/sqlite';
+import { schemaMigrations } from '@nozbe/watermelondb/Schema/migrations';
+
+const userTable = tableName('users');
+
+const userColumns = {
+ name: columnName('name'),
+ email: columnName('email'),
+ age: columnName('age'),
+};
+
+const userTableSchema = tableSchema({
+ name: userTable,
+ columns: [
+ { name: userColumns.name, type: 'string' },
+ { name: userColumns.email, type: 'string', isIndexed: true },
+ { name: userColumns.age, type: 'number', isOptional: true },
+ ],
+});
+
+const userInfoTable = tableName('user_info');
+const userInfoColumns = {
+ userId: columnName('user_id'),
+ address: columnName('address'),
+ phone: columnName('phone'),
+};
+const userInfoTableSchema = tableSchema({
+ name: userInfoTable,
+ columns: [
+ { name: userInfoColumns.userId, type: 'string', isIndexed: true },
+ { name: userInfoColumns.address, type: 'string' },
+ { name: userInfoColumns.phone, type: 'string', isOptional: true },
+ ],
+});
+
+const orderTable = tableName('order');
+const orderTableSchema = tableSchema({
+ name: orderTable,
+ columns: [
+ { name: columnName('order_no'), type: 'string', isIndexed: true },
+ { name: columnName('user_id'), type: 'string', isIndexed: true },
+ { name: columnName('amount'), type: 'number' },
+ { name: columnName('status'), type: 'string', defaultValue: 'pending' },
+ ],
+});
+
+const productTable = tableName('product');
+const productTableSchema = tableSchema({
+ name: productTable,
+ columns: [
+ { name: columnName('product_name'), type: 'string' },
+ { name: columnName('price'), type: 'number' },
+ { name: columnName('stock'), type: 'number', defaultValue: 0 },
+ ],
+});
+
+const tableSchemaMap = {
+ tableName: userTableSchema,
+ columnName: userInfoTableSchema,
+ tableSchema: orderTableSchema,
+ appSchema: productTableSchema,
+};
+
+
+const getAppDatabaseSchema = (tableSchema) => {
+ return appSchema({
+ version: 1,
+ tables: [tableSchema],
+ });
+};
+
+const validateUserColumns = () => {
+ const results = [];
+ userTableSchema.columnArray.forEach(column => {
+ try {
+ validateColumnSchema(column);
+ results.push({ column: column.name, valid: true });
+ } catch (error) {
+ results.push({ column: column.name, valid: false, error: error.message });
+ }
+ });
+ console.log(results);
+ return results;
+};
+
+// ===================== 初始化数据库改为接收表类型参数(核心修改)=====================
+// 初始化数据库(新增tableType参数)
+const initializeDatabase = async (tableType) => {
+ // 根据表类型获取对应表结构
+ const targetTableSchema = tableSchemaMap[tableType] || userTableSchema;
+ const adapter = new SQLiteAdapter({
+ dbName: `watermelon_${tableType}_db`, // 不同表使用不同数据库名
+ schema: getAppDatabaseSchema(targetTableSchema),
+ jsi: false,
+ migrations: schemaMigrations({ migrations: [] }),
+ });
+
+ await adapter.initializingPromise; // 等待适配器初始化
+ return new Database({ adapter, modelClasses: [] });
+};
+
+const SchemaExample = () => {
+ const [validationResult, setValidationResult] = useState(null);
+ const [createResult, setCreateResult] = useState(null);
+ const [database, setDatabase] = useState({}); // 修改为对象存储不同表的数据库实例
+
+ // 验证字段结构(保留原有)
+ const handleValidateSchema = () => {
+ const results = validateUserColumns();
+ setValidationResult(results);
+ setCreateResult(null);
+ };
+
+ // ===================== 修改创建方法为接收表类型参数(核心修改)=====================
+ // 创建数据库表(新增tableType参数)
+ const handleCreateTables = async (tableType) => {
+ try {
+ // 检查该表是否已创建
+ if (database[tableType]) {
+ const tableName = tableSchemaMap[tableType]?.name || userTable;
+ setCreateResult({
+ success: true,
+ message: `数据库(${tableType})已存在`,
+ tables: [tableName],
+ });
+ return;
+ }
+
+ const db = await initializeDatabase(tableType);
+ // 存储对应表类型的数据库实例
+ setDatabase({ ...database, [tableType]: db });
+ const tableName = tableSchemaMap[tableType]?.name || userTable;
+ setCreateResult({
+ success: true,
+ message: `数据库表(${tableType})创建成功`,
+ tables: [tableName],
+ });
+ } catch (error) {
+ setCreateResult({
+ success: false,
+ message: `数据库表(${tableType})创建失败`,
+ error: error.message,
+ });
+ }
+ };
+
+ // 清空页面状态(保留原有)
+ const handleClear = () => {
+ setValidationResult(null);
+ setCreateResult(null);
+ setDatabase({}); // 重置为空对象
+ };
+
+ return (
+
+ WatermelonDB 表创建示例
+
+
+ {/* 为每个按钮绑定不同的tableType参数 */}
+
+
+ {/* 字段验证结果展示(完全保留原有) */}
+ {validationResult && (
+
+ 字段验证结果
+ {validationResult.every(r => r.valid) ? (
+ 所有字段定义均有效
+ ) : (
+
+ 发现无效字段定义
+
+ {' '}
+ WatermelonDB 版本过旧,该版本未导出 validateColumnSchema
+ 函数(该函数是较新版本才对外暴露的
+
+
+ )}
+ {validationResult.map((item, i) => (
+
+
+ 字段 {item.column}:{' '}
+ {item.valid ? '有效' : `无效 (${item.error})`}
+
+
+ ))}
+
+ )}
+
+ {/* 创建结果展示(完全保留原有) */}
+ {createResult && (
+
+
+ {createResult.success ? '操作成功' : '操作失败'}
+
+ {createResult.message}
+ {createResult.error && (
+ {createResult.error}
+ )}
+ {createResult.tables && (
+
+ 已创建表:
+ {createResult.tables.map((table, i) => (
+ - {table}
+ ))}
+
+ )}
+
+ )}
+
+ );
+};
+
+// ===================== 样式完全保留原有 =====================
+const styles = StyleSheet.create({
+ container: {
+ flex: 1,
+ padding: 20,
+ backgroundColor: '#f5f5f5',
+ },
+ title: {
+ fontSize: 18,
+ fontWeight: 'bold',
+ marginBottom: 20,
+ textAlign: 'center',
+ },
+ buttons: {
+ flexDirection: 'row',
+ gap: 10,
+ marginBottom: 20,
+ flexWrap: 'wrap',
+ },
+ result: {
+ padding: 15,
+ backgroundColor: 'white',
+ borderRadius: 8,
+ elevation: 2,
+ marginBottom: 20,
+ },
+ resultTitle: {
+ fontSize: 16,
+ fontWeight: 'bold',
+ marginBottom: 10,
+ },
+ validationItem: {
+ marginVertical: 4,
+ padding: 4,
+ borderBottomWidth: 1,
+ borderBottomColor: '#eee',
+ },
+ success: {
+ color: 'green',
+ marginBottom: 10,
+ },
+ error: {
+ color: 'red',
+ },
+});
+
+export default SchemaExample;
+```
+```js
+// jsi: ture
+import React, { useState } from 'react';
+import { View, Text, Button, StyleSheet, ScrollView } from 'react-native';
+import {
+ appSchema,
+ tableSchema,
+ tableName,
+ columnName,
+ validateColumnSchema,
+} from '@nozbe/watermelondb/Schema';
+import { Database } from '@nozbe/watermelondb';
+import SQLiteAdapter from '@nozbe/watermelondb/adapters/sqlite';
+import { schemaMigrations } from '@nozbe/watermelondb/Schema/migrations';
+
+// ===================== 原有表定义(保留)=====================
+// 使用 tableName 定义表名(带类型)
+const userTable = tableName('users');
+
+// 使用 columnName 定义字段名
+const userColumns = {
+ name: columnName('name'),
+ email: columnName('email'),
+ age: columnName('age'),
+};
+
+// 定义用户表结构(使用 tableSchema)
+const userTableSchema = tableSchema({
+ name: userTable,
+ columns: [
+ { name: userColumns.name, type: 'string' },
+ { name: userColumns.email, type: 'string', isIndexed: true },
+ { name: userColumns.age, type: 'number', isOptional: true },
+ ],
+});
+
+// ===================== 新增4个不同表的定义(核心新增)=====================
+// 1. 用户信息表(user_info)- 对应columnName按钮
+const userInfoTable = tableName('user_info');
+const userInfoColumns = {
+ userId: columnName('user_id'),
+ address: columnName('address'),
+ phone: columnName('phone'),
+};
+const userInfoTableSchema = tableSchema({
+ name: userInfoTable,
+ columns: [
+ { name: userInfoColumns.userId, type: 'string', isIndexed: true },
+ { name: userInfoColumns.address, type: 'string' },
+ { name: userInfoColumns.phone, type: 'string', isOptional: true },
+ ],
+});
+
+// 2. 订单表(order)- 对应tableSchema按钮
+const orderTable = tableName('order');
+const orderTableSchema = tableSchema({
+ name: orderTable,
+ columns: [
+ { name: columnName('order_no'), type: 'string', isIndexed: true },
+ { name: columnName('user_id'), type: 'string', isIndexed: true },
+ { name: columnName('amount'), type: 'number' },
+ { name: columnName('status'), type: 'string', defaultValue: 'pending' },
+ ],
+});
+
+// 3. 商品表(product)- 对应appSchema按钮
+const productTable = tableName('product');
+const productTableSchema = tableSchema({
+ name: productTable,
+ columns: [
+ { name: columnName('product_name'), type: 'string' },
+ { name: columnName('price'), type: 'number' },
+ { name: columnName('stock'), type: 'number', defaultValue: 0 },
+ ],
+});
+
+// 表结构映射 - 用于根据类型获取对应表
+const tableSchemaMap = {
+ tableName: userTableSchema,
+ columnName: userInfoTableSchema,
+ tableSchema: orderTableSchema,
+ appSchema: productTableSchema,
+};
+
+// ===================== 原有应用schema改为动态生成(仅修改此处)=====================
+// 动态生成appSchema(根据传入的表结构)
+const getAppDatabaseSchema = tableSchema => {
+ return appSchema({
+ version: 1,
+ tables: [tableSchema],
+ });
+};
+
+// 验证字段定义(使用 validateColumnSchema)
+const validateUserColumns = () => {
+ const results = [];
+ // 修复原有错误:columnArray → columns
+ userTableSchema.columnArray.forEach(column => {
+ try {
+ validateColumnSchema(column);
+ results.push({ column: column.name, valid: true });
+ } catch (error) {
+ results.push({ column: column.name, valid: false, error: error.message });
+ }
+ });
+ console.log(results);
+ return results;
+};
+
+// ===================== 初始化数据库改为接收表类型参数(核心修改)=====================
+// 初始化数据库(新增tableType参数)
+const initializeDatabase = tableType => {
+ // 根据表类型获取对应表结构
+ const targetTableSchema = tableSchemaMap[tableType] || userTableSchema;
+ const adapter = new SQLiteAdapter({
+ dbName: `watermelonT_${tableType}_db`, // 不同表使用不同数据库名
+ schema: getAppDatabaseSchema(targetTableSchema),
+ jsi: true,
+ migrations: schemaMigrations({ migrations: [] }),
+ });
+
+ adapter.initializingPromise; // 等待适配器初始化
+ return new Database({ adapter, modelClasses: [] });
+};
+
+const SchemaExampleT = () => {
+ const [validationResult, setValidationResult] = useState(null);
+ const [createResult, setCreateResult] = useState(null);
+ const [database, setDatabase] = useState({}); // 修改为对象存储不同表的数据库实例
+
+ // 验证字段结构(保留原有)
+ const handleValidateSchema = () => {
+ const results = validateUserColumns();
+ setValidationResult(results);
+ setCreateResult(null);
+ };
+
+ // ===================== 修改创建方法为接收表类型参数(核心修改)=====================
+ // 创建数据库表(新增tableType参数)
+ const handleCreateTables = tableType => {
+ try {
+ // 检查该表是否已创建
+ if (database[tableType]) {
+ const tableName = tableSchemaMap[tableType]?.name || userTable;
+ setCreateResult({
+ success: true,
+ message: `数据库(${tableType})已存在`,
+ tables: [tableName],
+ });
+ return;
+ }
+
+ const db = initializeDatabase(tableType);
+ // 存储对应表类型的数据库实例
+ setDatabase({ ...database, [tableType]: db });
+ const tableName = tableSchemaMap[tableType]?.name || userTable;
+ setCreateResult({
+ success: true,
+ message: `数据库表(${tableType})创建成功`,
+ tables: [tableName],
+ });
+ } catch (error) {
+ setCreateResult({
+ success: false,
+ message: `数据库表(${tableType})创建失败`,
+ error: error.message,
+ });
+ }
+ };
+
+ // 清空页面状态(保留原有)
+ const handleClear = () => {
+ setValidationResult(null);
+ setCreateResult(null);
+ setDatabase({}); // 重置为空对象
+ };
+
+ return (
+
+ WatermelonDB 表创建示例
+
+
+ {/* 为每个按钮绑定不同的tableType参数 */}
+ handleCreateTables('tableName')} // 新增参数
+ color="#4CAF50"
+ />
+ handleCreateTables('columnName')} // 新增参数
+ color="#4CAF50"
+ />
+ handleCreateTables('tableSchema')} // 新增参数
+ color="#4CAF50"
+ />
+ handleCreateTables('appSchema')} // 新增参数
+ color="#4CAF50"
+ />
+
+
+
+
+ {/* 字段验证结果展示(完全保留原有) */}
+ {validationResult && (
+
+ 字段验证结果
+ {validationResult.every(r => r.valid) ? (
+ 所有字段定义均有效
+ ) : (
+
+ 发现无效字段定义
+
+ {' '}
+ WatermelonDB 版本过旧,该版本未导出 validateColumnSchema
+ 函数(该函数是较新版本才对外暴露的
+
+
+ )}
+ {validationResult.map((item, i) => (
+
+
+ 字段 {item.column}:{' '}
+ {item.valid ? '有效' : `无效 (${item.error})`}
+
+
+ ))}
+
+ )}
+
+ {/* 创建结果展示(完全保留原有) */}
+ {createResult && (
+
+
+ {createResult.success ? '操作成功' : '操作失败'}
+
+ {createResult.message}
+ {createResult.error && (
+ {createResult.error}
+ )}
+ {createResult.tables && (
+
+ 已创建表:
+ {createResult.tables.map((table, i) => (
+ - {table}
+ ))}
+
+ )}
+
+ )}
+
+ );
+};
+
+// ===================== 样式完全保留原有 =====================
+const styles = StyleSheet.create({
+ container: {
+ flex: 1,
+ padding: 20,
+ backgroundColor: '#f5f5f5',
+ },
+ title: {
+ fontSize: 18,
+ fontWeight: 'bold',
+ marginBottom: 20,
+ textAlign: 'center',
+ },
+ buttons: {
+ flexDirection: 'row',
+ gap: 10,
+ marginBottom: 20,
+ flexWrap: 'wrap',
+ },
+ result: {
+ padding: 15,
+ backgroundColor: 'white',
+ borderRadius: 8,
+ elevation: 2,
+ marginBottom: 20,
+ },
+ resultTitle: {
+ fontSize: 16,
+ fontWeight: 'bold',
+ marginBottom: 10,
+ },
+ validationItem: {
+ marginVertical: 4,
+ padding: 4,
+ borderBottomWidth: 1,
+ borderBottomColor: '#eee',
+ },
+ success: {
+ color: 'green',
+ marginBottom: 10,
+ },
+ error: {
+ color: 'red',
+ },
+});
+
+export default SchemaExampleT;
+```
+
+## Manual Link
+
+This step is a guide for manually configuring native dependencies.
+First, you need to open the HarmonyOS project harmony in the project using DevEco Studio.
+
+### 1.Add overrides field to oh-package.json in the project root directory
+
+```json
+{
+ "overrides": {
+ "@rnoh/react-native-openharmony" : "./react_native_openharmony"
+ }
+}
+```
+
+### 2. There are currently two methods:
+
+Import via har package (this method will be deprecated after the IDE improves related functions, and it is the preferred method currently);
+Link source code directly.
+
+Method 1: Import via har package (recommended)
+
+> [!TIP] The HAR package can be found in the harmony subfolder of the third-party library's installation directory.
+
+Open the entry/oh-package.json5 file and append the following dependencies:
+
+```json
+"dependencies": {
+ "@rnoh/react-native-openharmony": "0.72.32",
+ "@react-native-ohos/watermelondb": "file:../../node_modules/@react-native-ohos/watermelondb/harmony/watermelondb.har"
+ }
+```
+
+Click the sync button at the top right corner.
+
+Or run this command in the terminal:
+
+```bash
+cd entry
+ohpm install
+```
+
+Method 2: Link the source code directly
+
+> [!TIP] For direct source code linking, refer to [Direct Source Code Linking Instructions](/zh-cn/link-source-code.md)
+
+### 3.Configure CMakeLists and import WatermelonDBPackage
+
+open `entry/src/main/cpp/CMakeLists.txt`,add:
+
+```diff
+project(rnapp)
+cmake_minimum_required(VERSION 3.4.1)
+set(CMAKE_SKIP_BUILD_RPATH TRUE)
+set(RNOH_APP_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
+set(NODE_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../node_modules")
+set(OH_MODULE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
+set(RNOH_CPP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules/@rnoh/react-native-openharmony/src/main/cpp")
+set(RNOH_GENERATED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/generated")
+set(LOG_VERBOSITY_LEVEL 1)
+set(CMAKE_ASM_FLAGS "-Wno-error=unused-command-line-argument -Qunused-arguments")
+set(CMAKE_CXX_FLAGS "-fstack-protector-strong -Wl,-z,relro,-z,now,-z,noexecstack -s -fPIE -pie")
+set(OH_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
+
+set(WITH_HITRACE_SYSTRACE 1) # for other CMakeLists.txt files to use
+add_compile_definitions(WITH_HITRACE_SYSTRACE)
+
+add_subdirectory("${RNOH_CPP_DIR}" ./rn)
+
+# RNOH_BEGIN: manual_package_linking_1
+# RNOH_END: manual_package_linking_1
+
+file(GLOB GENERATED_CPP_FILES "${CMAKE_CURRENT_SOURCE_DIR}/generated/*.cpp") # this line is needed by codegen v1
+
++ add_subdirectory("${OH_MODULES}/@react-native-ohos/watermelondb/src/main/cpp" ./watermelondb)
+
+
+
+add_library(rnoh_app SHARED
+ ${GENERATED_CPP_FILES}
+ "./PackageProvider.cpp"
+ "${RNOH_CPP_DIR}/RNOHAppNapiBridge.cpp"
+)
+target_link_libraries(rnoh_app PUBLIC rnoh)
+
+# RNOH_BEGIN: manual_package_linking_2
++ target_link_libraries(rnoh_app PUBLIC watermelondb)
+
+
+# RNOH_END: manual_package_linking_2
+```
+
+open `entry/src/main/cpp/PackageProvider.cpp`,add:
+
+```diff
+#include "RNOH/PackageProvider.h"
+#include "generated/RNOHGeneratedPackage.h"
++ #include "WatermelondbPackage.h"
+
+using namespace rnoh;
+
+std::vector> PackageProvider::getPackages(
+ Package::Context ctx) {
+ return {
+ std::make_shared(ctx), // generated by codegen v1
++ std::make_shared(ctx)
+ };
+}
+```
+
+### 4. Import the watermelondb module on the ArkTS side
+
+open `entry/src/main/ets/RNPackagesFactory.ts`,add:
+
+```diff
+...
+import type {RNPackageContext, RNPackage} from '@rnoh/react-native-openharmony/ts';
++ import { WatermelonDBPackage } from '@react-native-ohos/watermelondb';
+
+export function createRNPackages(ctx: RNPackageContext): RNPackage[] {
+ return [
++ new WatermelonDBPackage(ctx)
+ ];
+ }
+...
+...
+```
+
+### 5.Run
+
+Click the sync button in the upper right corner.
+
+Alternatively, execute the following command in the terminal:
+
+```bash
+cd entry
+ohpm install
+```
+
+Then compile and run the project.
+
+## Constraints and Limitations
+
+### Compatibility Support
+
+The content of this document has been verified based on the following versions:
+1. RNOH:0.72.90; SDK:HarmonyOS NEXT Developer DB3; IDE: DevEco Studio: 5.0.5.220; ROM:NEXT.0.0.105;
+2. RNOH:0.77.18; SDK:HarmonyOS 6.0.0 Release; IDE: DevEco Studio 6.0.0.858; ROM:6.0.0.112;
+
+#### Add the reason for applying for the above permissions in the entry directory
+
+Open `entry/src/main/resources/base/element/string.json`,add:
+
+```diff
+...
+{
+ "string": [
++ {
++ "name": "module_desc",
++ "value": "moudle description"
++ },
++ {
++ "name": "EntryAbility_desc",
++ "value": "description"
++ },
++ {
++ "name": "EntryAbility_label",
++ "value": "WatermelonDB"
++ },
+ ]
+}
+```
+
+## Properties
+
+> [!TIP] "Platform"This column shows which platforms the property supports in the original third-party library。
+
+> [!TIP] "HarmonyOS Support"A value of "yes" in this column means the HarmonyOS platform supports the property; "no" means it does not; "partially" means partial support. The usage method is consistent across platforms, and the effect is comparable to that on iOS or Android。
+
+**Collection class**
+| Name | Description | Type | Required | Platform | HarmonyOS Support |
+| --------------------------------------------- | --------------------------------------------- | -------- | -------- | ----------- | ----------------- |
+| db | Get the reference to the database instance that this collection belongs to | function | no | iOS/Android | yes |
+| find | Query for matching records in the collection based on specified conditions | function | yes | iOS/Android | yes |
+| findAndObserve | Query records and establish responsive observation to monitor data changes | function | yes | iOS/Android | yes |
+| create | Create and save new records in the collection | function | yes | iOS/Android | yes |
+| prepareCreate | Pre - create a record object without immediately persisting it to the database | function | yes | iOS/Android | yes |
+| prepareCreateFromDirtyRaw | Pre - create a record object from raw unvalidated data | function | yes | iOS/Android | yes |
+| disposableFromDirtyRaw | Create a one - time temporary record based on raw dirty data | function | yes | iOS/Android | yes |
+| table | Get the name of the database table corresponding to this collection | function | no | iOS/Android | yes |
+| schema | Get the data table structure definition corresponding to this collection | function | no | iOS/Android | yes |
+| experimentalSubscribe | Subscribe to collection - level data change notifications | function | yes | iOS/Android | yes |
+
+**Database class**
+| Name | Description | Type | Required | Platform | HarmonyOS Support |
+| --------------------------------------------- | --------------------------------------------- | -------- | -------- | ----------- | ----------------- |
+| get<T extends Model> | Retrieve a specific record from the database according to the model class and ID | function | yes | iOS/Android | yes |
+| localStorage | Get the local storage adapter of the database for key - value pair data | function | yes | iOS/Android | yes |
+| batch | Create batch operations to efficiently perform multiple database writes | function | yes | iOS/Android | yes |
+| write<T> | Perform database modification operations in a write transaction | function | yes | iOS/Android | yes |
+| read<T> | Perform database query operations in a read - only transaction | function | yes | iOS/Android | yes |
+| action<T> | Perform database actions that require read and write permissions | function | yes | iOS/Android | yes |
+| withChangesForTables | Create an observer that monitors data changes in specified tables | function | yes | iOS/Android | yes |
+| experimentalSubscribe | Subscribe to database - level change notifications | function | yes | iOS/Android | yes |
+| unsafeResetDatabase | Completely reset the database and clear all data | function | no | iOS/Android | yes |
+| \_ensurelnWtiter | Ensure that the current operation is executed in the write thread | function | yes | iOS/Android | yes |
+| \_fataError | Handle database fatal errors and terminate the connection | function | yes | iOS/Android | yes |
+
+**Relation class**
+| Name | Description | Type | Required | Platform | HarmonyOS Support |
+| --------------------------------------------- | --------------------------------------------- | -------- | -------- | ----------- | ----------------- |
+| get id | Get the unique identifier of the associated target model | function | no | iOS/Android | yes |
+| set id | Set the identifier value of the associated target model | function | no | iOS/Android | yes |
+| fetch | Asynchronously obtain the promise of complete data of the associated record | function | no | iOS/Android | yes |
+| then<U> | Support Promise chain calls to process asynchronously obtained associated data | function | no | iOS/Android | yes |
+| set | Establish an association relationship with another model instance | function | no | iOS/Android | yes |
+| observe | Monitor real - time changes in associated model data | function | no | iOS/Android | yes |
+
+**Model class**
+| Name | Description | Type | Required | Platform | HarmonyOS Support |
+| --------------------------------------------- | --------------------------------------------- | -------- | -------- | ----------- | ----------------- |
+| associations | Define the association relationship mapping between the model and other data tables | function | no | iOS/Android | yes |
+| prepareMarkAsDeleted | Mark as deleted status | function | no | iOS/Android | no |
+| \_getChanges | Get the model change observation object | function | no | iOS/Android | yes |
+| get id | Get the unique identifier of the instance | function | no | iOS/Android | yes |
+| get syncStatus | Get the data synchronization status | function | no | iOS/Android | yes |
+| update | Update the model and submit immediately | function | no | iOS/Android | yes |
+| prepareUpdate | Prepare for update | function | no | iOS/Android | yes |
+| prepareDestroyPermanently | Prepare for permanent destruction without execution | function | no | iOS/Android | yes |
+| markAsDeleted | Delete the model and submit | function | no | iOS/Android | yes |
+| destroyPermanently | Permanently delete model records | function | no | iOS/Android | yes |
+| experimentalMarkAsDeleted | Soft delete function | function | no | iOS/Android | yes |
+| experimentalDestroyPermanently | Permanent delete function | function | no | iOS/Android | yes |
+| observe | Monitor model data changes | function | no | iOS/Android | yes |
+| collection | Get the associated data set | function | no | iOS/Android | yes |
+| get collections | Get all collection mappings | function | no | iOS/Android | yes |
+| get database | Get the database instance | function | no | iOS/Android | yes |
+| get db | Get the database instance | function | no | iOS/Android | yes |
+| get asModel | Return its own instance | function | no | iOS/Android | yes |
+| callWriter<T> | Perform operations in the write thread | function | yes | iOS/Android | yes |
+| callReader<T> | Perform queries in the read thread | function | yes | iOS/Android | yes |
+| subAction<T> | Perform sub - operations in a transaction | function | yes | iOS/Android | yes |
+| get table | Get the corresponding data table name | function | no | iOS/Android | yes |
+| prepareCreate | Prepare to create a model | function | yes | iOS/Android | yes |
+| \_prepareCreateFromDirtyRaw | Create a model from dirty data | function | yes | iOS/Android | yes |
+| \_disposableFromDirtyRaw | Create a one - time model | function | yes | iOS/Android | yes |
+| experimentalSubscribe | Experimental subscription to model changes | function | yes | iOS/Android | yes |
+| \_notifyChanged | Internally notify model changes | function | no | iOS/Android | yes |
+| \_notifyDestroyed | Internally notify model destruction | function | no | iOS/Android | yes |
+| \_getRaw | Internally get the original field value | function | yes | iOS/Android | yes |
+| \_setRaw | Internally set field values and mark changes | function | yes | iOS/Android | yes |
+| \_dangerouslySetRawWithoutMarkingColumnChange | Internally unsafely set field values | function | yes | iOS/Android | yes |
+| \_ensureCanSetRaw | Internally ensure that raw values can be set | function | no | iOS/Android | yes |
+| \_ensureNotDisposable | Internally ensure non - disposable instances | function | yes | iOS/Android | yes |
+
+**Query class**
+| Name | Description | Type | Required | Platform | HarmonyOS Support |
+| --------------------------------------------- | --------------------------------------------- | -------- | -------- | ----------- | ----------------- |
+| pipe<T> | Perform chain conversion operations on query results | function | no | iOS/Android | yes |
+| fetch | Execute the query immediately to get results | function | no | iOS/Android | yes |
+| then<U> | Support Promise chain calls for query results | function | no | iOS/Android | yes |
+| observe | Monitor real - time changes in query results | function | no | iOS/Android | yes |
+| observeWithColumns | Monitor query results of specific field changes | function | yes | iOS/Android | yes |
+| fetchCount | Get the quantity statistics of query results | function | yes | iOS/Android | yes |
+| get count | Get the total number of query results | function | no | iOS/Android | yes |
+| observeCount | Monitor changes in the number of query results | function | no | iOS/Android | yes |
+| fetchIds | Get the ID list of query results | function | no | iOS/Android | yes |
+| unsafeFetchRaw | Unsafely get raw query data | function | no | iOS/Android | yes |
+| experimentalSubscribe | Experimental query subscription function | function | yes | iOS/Android | yes |
+| experimentalSubscribeWithColumns | Experimental field change subscription | function | yes | iOS/Android | yes |
+| experimentalSubscribeToCount | Experimental quantity change subscription | function | yes | iOS/Android | yes |
+| markAllAsDeleted | Mark all query results as soft deleted | function | no | iOS/Android | yes |
+| destroyAllPermanently | Permanently delete all query results | function | no | iOS/Android | yes |
+| get modelClass | Get the model class corresponding to the query | function | no | iOS/Android | yes |
+| get table | Get the main table name of the query | function |no | iOS/Android | yes |
+| get secondaryTables | Get the associated tables involved in the query | function | no | iOS/Android | yes |
+| get allTables | Get all tables related to the query | function | no | iOS/Android | yes |
+| get associations | Get the association relationships of the query | function | no | iOS/Android | yes |
+| serialize | Serialize the query into a transferable format | function | no | iOS/Android | yes |
+
+**Schema class**
+| Name | Description | Type | Required | Platform | HarmonyOS Support |
+| --------------------------------------------- | --------------------------------------------- | -------- | -------- | ----------- | ----------------- |
+| tableName<T extends Model> | Define the name of the database table | function | yes | iOS/Android | yes |
+| columnName | Define the name of the database field | function | yes | iOS/Android | yes |
+| appSchema | Define the structural schema of the entire application database | function | yes | iOS/Android | yes |
+| validateColumnsSchema | Verify the validity of the field schema definition | function | yes | iOS/Android | yes |
+| tableSchema | Define the structure and field configuration of a single data table | function | yes | iOS/Android | yes |
+
+## Pending Issues
+
+## Others
+
+## Open Source License
+
+This project is based on [The MIT License (MIT)](https://github.com/Nozbe/WatermelonDB/blob/master/LICENSE) ,Feel free to enjoy and contribute to the open source project。
diff --git a/zh-cn/watermelondb.md b/zh-cn/watermelondb.md
new file mode 100644
index 0000000000000000000000000000000000000000..bf52c7ec33ff3bb5849f511ab8e9b389123db95b
--- /dev/null
+++ b/zh-cn/watermelondb.md
@@ -0,0 +1,958 @@
+> 模板版本:v0.3.0
+
+
+
watermelondb
+
+
+本项目基于 [watermelondb@[v0.28.1-0](https://github.com/Nozbe/WatermelonDB)]开发。
+
+请到三方库的 Releases 发布地址查看配套的版本信息:([@react-native-ohos/watermelondb Releases](https://gitcode.com/OpenHarmony-RN/rntpc_watermelondb))。对于未发布到 npm 的旧版本,请参考[安装指南](/zh-cn/tgz-usage.md)安装 tgz 包。
+
+| 三方库版本 | 发布信息 | 支持 RN 版本 |
+| ---------- | -------------------------------------------------------------------------------------------------------------------------- | ------------ |
+| v0.28.1-0 | [@react-native-ohos/watermelondb Releases](https://github.com/) | 0.72/0.77 |
+
+## 1. 安装与使用
+
+进入到工程目录并输入以下命令:
+
+#### npm
+
+```bash
+npm install @react-native-ohos/watermelondb
+```
+
+#### yarn
+
+```bash
+yarn add @react-native-ohos/watermelondb
+```
+
+下面的代码展示了这个库的基本使用场景:
+
+> [!WARNING] 使用时 import 的库名不变。
+
+```js
+// jsi: false
+import React, { useState } from 'react';
+import { View, Text, Button, StyleSheet, ScrollView } from 'react-native';
+import {
+ appSchema,
+ tableSchema,
+ tableName,
+ columnName,
+ validateColumnSchema,
+} from '@nozbe/watermelondb/Schema';
+import { Database } from '@nozbe/watermelondb';
+import SQLiteAdapter from '@nozbe/watermelondb/adapters/sqlite';
+import { schemaMigrations } from '@nozbe/watermelondb/Schema/migrations';
+
+const userTable = tableName('users');
+
+const userColumns = {
+ name: columnName('name'),
+ email: columnName('email'),
+ age: columnName('age'),
+};
+
+const userTableSchema = tableSchema({
+ name: userTable,
+ columns: [
+ { name: userColumns.name, type: 'string' },
+ { name: userColumns.email, type: 'string', isIndexed: true },
+ { name: userColumns.age, type: 'number', isOptional: true },
+ ],
+});
+
+const userInfoTable = tableName('user_info');
+const userInfoColumns = {
+ userId: columnName('user_id'),
+ address: columnName('address'),
+ phone: columnName('phone'),
+};
+const userInfoTableSchema = tableSchema({
+ name: userInfoTable,
+ columns: [
+ { name: userInfoColumns.userId, type: 'string', isIndexed: true },
+ { name: userInfoColumns.address, type: 'string' },
+ { name: userInfoColumns.phone, type: 'string', isOptional: true },
+ ],
+});
+
+const orderTable = tableName('order');
+const orderTableSchema = tableSchema({
+ name: orderTable,
+ columns: [
+ { name: columnName('order_no'), type: 'string', isIndexed: true },
+ { name: columnName('user_id'), type: 'string', isIndexed: true },
+ { name: columnName('amount'), type: 'number' },
+ { name: columnName('status'), type: 'string', defaultValue: 'pending' },
+ ],
+});
+
+const productTable = tableName('product');
+const productTableSchema = tableSchema({
+ name: productTable,
+ columns: [
+ { name: columnName('product_name'), type: 'string' },
+ { name: columnName('price'), type: 'number' },
+ { name: columnName('stock'), type: 'number', defaultValue: 0 },
+ ],
+});
+
+const tableSchemaMap = {
+ tableName: userTableSchema,
+ columnName: userInfoTableSchema,
+ tableSchema: orderTableSchema,
+ appSchema: productTableSchema,
+};
+
+
+const getAppDatabaseSchema = (tableSchema) => {
+ return appSchema({
+ version: 1,
+ tables: [tableSchema],
+ });
+};
+
+const validateUserColumns = () => {
+ const results = [];
+ userTableSchema.columnArray.forEach(column => {
+ try {
+ validateColumnSchema(column);
+ results.push({ column: column.name, valid: true });
+ } catch (error) {
+ results.push({ column: column.name, valid: false, error: error.message });
+ }
+ });
+ console.log(results);
+ return results;
+};
+
+// ===================== 初始化数据库改为接收表类型参数(核心修改)=====================
+// 初始化数据库(新增tableType参数)
+const initializeDatabase = async (tableType) => {
+ // 根据表类型获取对应表结构
+ const targetTableSchema = tableSchemaMap[tableType] || userTableSchema;
+ const adapter = new SQLiteAdapter({
+ dbName: `watermelon_${tableType}_db`, // 不同表使用不同数据库名
+ schema: getAppDatabaseSchema(targetTableSchema),
+ jsi: false,
+ migrations: schemaMigrations({ migrations: [] }),
+ });
+
+ await adapter.initializingPromise; // 等待适配器初始化
+ return new Database({ adapter, modelClasses: [] });
+};
+
+const SchemaExample = () => {
+ const [validationResult, setValidationResult] = useState(null);
+ const [createResult, setCreateResult] = useState(null);
+ const [database, setDatabase] = useState({}); // 修改为对象存储不同表的数据库实例
+
+ // 验证字段结构(保留原有)
+ const handleValidateSchema = () => {
+ const results = validateUserColumns();
+ setValidationResult(results);
+ setCreateResult(null);
+ };
+
+ // ===================== 修改创建方法为接收表类型参数(核心修改)=====================
+ // 创建数据库表(新增tableType参数)
+ const handleCreateTables = async (tableType) => {
+ try {
+ // 检查该表是否已创建
+ if (database[tableType]) {
+ const tableName = tableSchemaMap[tableType]?.name || userTable;
+ setCreateResult({
+ success: true,
+ message: `数据库(${tableType})已存在`,
+ tables: [tableName],
+ });
+ return;
+ }
+
+ const db = await initializeDatabase(tableType);
+ // 存储对应表类型的数据库实例
+ setDatabase({ ...database, [tableType]: db });
+ const tableName = tableSchemaMap[tableType]?.name || userTable;
+ setCreateResult({
+ success: true,
+ message: `数据库表(${tableType})创建成功`,
+ tables: [tableName],
+ });
+ } catch (error) {
+ setCreateResult({
+ success: false,
+ message: `数据库表(${tableType})创建失败`,
+ error: error.message,
+ });
+ }
+ };
+
+ // 清空页面状态(保留原有)
+ const handleClear = () => {
+ setValidationResult(null);
+ setCreateResult(null);
+ setDatabase({}); // 重置为空对象
+ };
+
+ return (
+
+ WatermelonDB 表创建示例
+
+
+ {/* 为每个按钮绑定不同的tableType参数 */}
+ handleCreateTables('tableName')} // 新增参数
+ color="#4CAF50"
+ />
+ handleCreateTables('columnName')} // 新增参数
+ color="#4CAF50"
+ />
+ handleCreateTables('tableSchema')} // 新增参数
+ color="#4CAF50"
+ />
+ handleCreateTables('appSchema')} // 新增参数
+ color="#4CAF50"
+ />
+
+
+
+
+ {/* 字段验证结果展示(完全保留原有) */}
+ {validationResult && (
+
+ 字段验证结果
+ {validationResult.every(r => r.valid) ? (
+ 所有字段定义均有效
+ ) : (
+
+ 发现无效字段定义
+
+ {' '}
+ WatermelonDB 版本过旧,该版本未导出 validateColumnSchema
+ 函数(该函数是较新版本才对外暴露的
+
+
+ )}
+ {validationResult.map((item, i) => (
+
+
+ 字段 {item.column}:{' '}
+ {item.valid ? '有效' : `无效 (${item.error})`}
+
+
+ ))}
+
+ )}
+
+ {/* 创建结果展示(完全保留原有) */}
+ {createResult && (
+
+
+ {createResult.success ? '操作成功' : '操作失败'}
+
+ {createResult.message}
+ {createResult.error && (
+ {createResult.error}
+ )}
+ {createResult.tables && (
+
+ 已创建表:
+ {createResult.tables.map((table, i) => (
+ - {table}
+ ))}
+
+ )}
+
+ )}
+
+ );
+};
+
+// ===================== 样式完全保留原有 =====================
+const styles = StyleSheet.create({
+ container: {
+ flex: 1,
+ padding: 20,
+ backgroundColor: '#f5f5f5',
+ },
+ title: {
+ fontSize: 18,
+ fontWeight: 'bold',
+ marginBottom: 20,
+ textAlign: 'center',
+ },
+ buttons: {
+ flexDirection: 'row',
+ gap: 10,
+ marginBottom: 20,
+ flexWrap: 'wrap',
+ },
+ result: {
+ padding: 15,
+ backgroundColor: 'white',
+ borderRadius: 8,
+ elevation: 2,
+ marginBottom: 20,
+ },
+ resultTitle: {
+ fontSize: 16,
+ fontWeight: 'bold',
+ marginBottom: 10,
+ },
+ validationItem: {
+ marginVertical: 4,
+ padding: 4,
+ borderBottomWidth: 1,
+ borderBottomColor: '#eee',
+ },
+ success: {
+ color: 'green',
+ marginBottom: 10,
+ },
+ error: {
+ color: 'red',
+ },
+});
+
+export default SchemaExample;
+```
+
+```js
+// jsi: ture
+import React, { useState } from 'react';
+import { View, Text, Button, StyleSheet, ScrollView } from 'react-native';
+import {
+ appSchema,
+ tableSchema,
+ tableName,
+ columnName,
+ validateColumnSchema,
+} from '@nozbe/watermelondb/Schema';
+import { Database } from '@nozbe/watermelondb';
+import SQLiteAdapter from '@nozbe/watermelondb/adapters/sqlite';
+import { schemaMigrations } from '@nozbe/watermelondb/Schema/migrations';
+
+// ===================== 原有表定义(保留)=====================
+// 使用 tableName 定义表名(带类型)
+const userTable = tableName('users');
+
+// 使用 columnName 定义字段名
+const userColumns = {
+ name: columnName('name'),
+ email: columnName('email'),
+ age: columnName('age'),
+};
+
+// 定义用户表结构(使用 tableSchema)
+const userTableSchema = tableSchema({
+ name: userTable,
+ columns: [
+ { name: userColumns.name, type: 'string' },
+ { name: userColumns.email, type: 'string', isIndexed: true },
+ { name: userColumns.age, type: 'number', isOptional: true },
+ ],
+});
+
+// ===================== 新增4个不同表的定义(核心新增)=====================
+// 1. 用户信息表(user_info)- 对应columnName按钮
+const userInfoTable = tableName('user_info');
+const userInfoColumns = {
+ userId: columnName('user_id'),
+ address: columnName('address'),
+ phone: columnName('phone'),
+};
+const userInfoTableSchema = tableSchema({
+ name: userInfoTable,
+ columns: [
+ { name: userInfoColumns.userId, type: 'string', isIndexed: true },
+ { name: userInfoColumns.address, type: 'string' },
+ { name: userInfoColumns.phone, type: 'string', isOptional: true },
+ ],
+});
+
+// 2. 订单表(order)- 对应tableSchema按钮
+const orderTable = tableName('order');
+const orderTableSchema = tableSchema({
+ name: orderTable,
+ columns: [
+ { name: columnName('order_no'), type: 'string', isIndexed: true },
+ { name: columnName('user_id'), type: 'string', isIndexed: true },
+ { name: columnName('amount'), type: 'number' },
+ { name: columnName('status'), type: 'string', defaultValue: 'pending' },
+ ],
+});
+
+// 3. 商品表(product)- 对应appSchema按钮
+const productTable = tableName('product');
+const productTableSchema = tableSchema({
+ name: productTable,
+ columns: [
+ { name: columnName('product_name'), type: 'string' },
+ { name: columnName('price'), type: 'number' },
+ { name: columnName('stock'), type: 'number', defaultValue: 0 },
+ ],
+});
+
+// 表结构映射 - 用于根据类型获取对应表
+const tableSchemaMap = {
+ tableName: userTableSchema,
+ columnName: userInfoTableSchema,
+ tableSchema: orderTableSchema,
+ appSchema: productTableSchema,
+};
+
+// ===================== 原有应用schema改为动态生成(仅修改此处)=====================
+// 动态生成appSchema(根据传入的表结构)
+const getAppDatabaseSchema = tableSchema => {
+ return appSchema({
+ version: 1,
+ tables: [tableSchema],
+ });
+};
+
+// 验证字段定义(使用 validateColumnSchema)
+const validateUserColumns = () => {
+ const results = [];
+ // 修复原有错误:columnArray → columns
+ userTableSchema.columnArray.forEach(column => {
+ try {
+ validateColumnSchema(column);
+ results.push({ column: column.name, valid: true });
+ } catch (error) {
+ results.push({ column: column.name, valid: false, error: error.message });
+ }
+ });
+ console.log(results);
+ return results;
+};
+
+// ===================== 初始化数据库改为接收表类型参数(核心修改)=====================
+// 初始化数据库(新增tableType参数)
+const initializeDatabase = tableType => {
+ // 根据表类型获取对应表结构
+ const targetTableSchema = tableSchemaMap[tableType] || userTableSchema;
+ const adapter = new SQLiteAdapter({
+ dbName: `watermelonT_${tableType}_db`, // 不同表使用不同数据库名
+ schema: getAppDatabaseSchema(targetTableSchema),
+ jsi: true,
+ migrations: schemaMigrations({ migrations: [] }),
+ });
+
+ adapter.initializingPromise; // 等待适配器初始化
+ return new Database({ adapter, modelClasses: [] });
+};
+
+const SchemaExampleT = () => {
+ const [validationResult, setValidationResult] = useState(null);
+ const [createResult, setCreateResult] = useState(null);
+ const [database, setDatabase] = useState({}); // 修改为对象存储不同表的数据库实例
+
+ // 验证字段结构(保留原有)
+ const handleValidateSchema = () => {
+ const results = validateUserColumns();
+ setValidationResult(results);
+ setCreateResult(null);
+ };
+
+ // ===================== 修改创建方法为接收表类型参数(核心修改)=====================
+ // 创建数据库表(新增tableType参数)
+ const handleCreateTables = tableType => {
+ try {
+ // 检查该表是否已创建
+ if (database[tableType]) {
+ const tableName = tableSchemaMap[tableType]?.name || userTable;
+ setCreateResult({
+ success: true,
+ message: `数据库(${tableType})已存在`,
+ tables: [tableName],
+ });
+ return;
+ }
+
+ const db = initializeDatabase(tableType);
+ // 存储对应表类型的数据库实例
+ setDatabase({ ...database, [tableType]: db });
+ const tableName = tableSchemaMap[tableType]?.name || userTable;
+ setCreateResult({
+ success: true,
+ message: `数据库表(${tableType})创建成功`,
+ tables: [tableName],
+ });
+ } catch (error) {
+ setCreateResult({
+ success: false,
+ message: `数据库表(${tableType})创建失败`,
+ error: error.message,
+ });
+ }
+ };
+
+ // 清空页面状态(保留原有)
+ const handleClear = () => {
+ setValidationResult(null);
+ setCreateResult(null);
+ setDatabase({}); // 重置为空对象
+ };
+
+ return (
+
+ WatermelonDB 表创建示例
+
+
+ {/* 为每个按钮绑定不同的tableType参数 */}
+ handleCreateTables('tableName')} // 新增参数
+ color="#4CAF50"
+ />
+ handleCreateTables('columnName')} // 新增参数
+ color="#4CAF50"
+ />
+ handleCreateTables('tableSchema')} // 新增参数
+ color="#4CAF50"
+ />
+ handleCreateTables('appSchema')} // 新增参数
+ color="#4CAF50"
+ />
+
+
+
+
+ {/* 字段验证结果展示(完全保留原有) */}
+ {validationResult && (
+
+ 字段验证结果
+ {validationResult.every(r => r.valid) ? (
+ 所有字段定义均有效
+ ) : (
+
+ 发现无效字段定义
+
+ {' '}
+ WatermelonDB 版本过旧,该版本未导出 validateColumnSchema
+ 函数(该函数是较新版本才对外暴露的
+
+
+ )}
+ {validationResult.map((item, i) => (
+
+
+ 字段 {item.column}:{' '}
+ {item.valid ? '有效' : `无效 (${item.error})`}
+
+
+ ))}
+
+ )}
+
+ {/* 创建结果展示(完全保留原有) */}
+ {createResult && (
+
+
+ {createResult.success ? '操作成功' : '操作失败'}
+
+ {createResult.message}
+ {createResult.error && (
+ {createResult.error}
+ )}
+ {createResult.tables && (
+
+ 已创建表:
+ {createResult.tables.map((table, i) => (
+ - {table}
+ ))}
+
+ )}
+
+ )}
+
+ );
+};
+
+// ===================== 样式完全保留原有 =====================
+const styles = StyleSheet.create({
+ container: {
+ flex: 1,
+ padding: 20,
+ backgroundColor: '#f5f5f5',
+ },
+ title: {
+ fontSize: 18,
+ fontWeight: 'bold',
+ marginBottom: 20,
+ textAlign: 'center',
+ },
+ buttons: {
+ flexDirection: 'row',
+ gap: 10,
+ marginBottom: 20,
+ flexWrap: 'wrap',
+ },
+ result: {
+ padding: 15,
+ backgroundColor: 'white',
+ borderRadius: 8,
+ elevation: 2,
+ marginBottom: 20,
+ },
+ resultTitle: {
+ fontSize: 16,
+ fontWeight: 'bold',
+ marginBottom: 10,
+ },
+ validationItem: {
+ marginVertical: 4,
+ padding: 4,
+ borderBottomWidth: 1,
+ borderBottomColor: '#eee',
+ },
+ success: {
+ color: 'green',
+ marginBottom: 10,
+ },
+ error: {
+ color: 'red',
+ },
+});
+
+export default SchemaExampleT;
+```
+
+## Manual Link
+
+此步骤为手动配置原生依赖项的指导。
+
+首先需要使用 DevEco Studio 打开项目里的 HarmonyOS 工程 `harmony`。
+
+### 1.在工程根目录的 `oh-package.json` 添加 overrides字段
+
+为了让工程依赖同一个版本的 RN SDK,需要在工程根目录的 `oh-package.json5` 添加 overrides 字段,指向工程需要使用的 RN SDK 版本。替换的版本既可以是一个具体的版本号,也可以是一个模糊版本,还可以是本地存在的 HAR 包或源码目录。
+
+关于该字段的作用请阅读[官方说明](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/ide-oh-package-json5-V5#zh-cn_topic_0000001792256137_overrides):
+
+```json
+{
+ "overrides": {
+ "@rnoh/react-native-openharmony" : "./react_native_openharmony"
+ }
+}
+```
+
+### 2. 引入原生端代码
+
+目前有两种方法:
+
+1. 通过 har 包引入(在 IDE 完善相关功能后该方法会被遗弃,目前首选此方法);
+2. 直接链接源码。
+
+方法一:通过 har 包引入(推荐)
+
+> [!TIP] har 包位于三方库安装路径的 `harmony` 文件夹下。
+
+打开 `entry/oh-package.json5`,添加以下依赖
+
+```json
+"dependencies": {
+ "@rnoh/react-native-openharmony": "0.72.32",
+ "@react-native-ohos/watermelondb": "file:../../node_modules/@react-native-ohos/watermelondb/harmony/watermelondb.har"
+ }
+```
+
+点击右上角的 `sync` 按钮
+
+或者在终端执行:
+
+```bash
+cd entry
+ohpm install
+```
+
+方法二:直接链接源码
+
+> [!TIP] 如需使用直接链接源码,请参考[直接链接源码说明](/zh-cn/link-source-code.md)
+
+### 3. 配置 CMakeLists 和引入 WatermelonDBPackage
+
+打开 `entry/src/main/cpp/CMakeLists.txt`,添加:
+
+```diff
+project(rnapp)
+cmake_minimum_required(VERSION 3.4.1)
+set(CMAKE_SKIP_BUILD_RPATH TRUE)
+set(RNOH_APP_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
+set(NODE_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../node_modules")
+set(OH_MODULE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
+set(RNOH_CPP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules/@rnoh/react-native-openharmony/src/main/cpp")
+set(RNOH_GENERATED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/generated")
+set(LOG_VERBOSITY_LEVEL 1)
+set(CMAKE_ASM_FLAGS "-Wno-error=unused-command-line-argument -Qunused-arguments")
+set(CMAKE_CXX_FLAGS "-fstack-protector-strong -Wl,-z,relro,-z,now,-z,noexecstack -s -fPIE -pie")
+set(OH_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
+
+set(WITH_HITRACE_SYSTRACE 1) # for other CMakeLists.txt files to use
+add_compile_definitions(WITH_HITRACE_SYSTRACE)
+
+add_subdirectory("${RNOH_CPP_DIR}" ./rn)
+
+# RNOH_BEGIN: manual_package_linking_1
+# RNOH_END: manual_package_linking_1
+
+file(GLOB GENERATED_CPP_FILES "${CMAKE_CURRENT_SOURCE_DIR}/generated/*.cpp") # this line is needed by codegen v1
+
++ add_subdirectory("${OH_MODULES}/@react-native-ohos/watermelondb/src/main/cpp" ./watermelondb)
+
+
+
+add_library(rnoh_app SHARED
+ ${GENERATED_CPP_FILES}
+ "./PackageProvider.cpp"
+ "${RNOH_CPP_DIR}/RNOHAppNapiBridge.cpp"
+)
+target_link_libraries(rnoh_app PUBLIC rnoh)
+
+# RNOH_BEGIN: manual_package_linking_2
++ target_link_libraries(rnoh_app PUBLIC watermelondb)
+
+
+# RNOH_END: manual_package_linking_2
+```
+
+打开 `entry/src/main/cpp/PackageProvider.cpp`,添加:
+
+```diff
+#include "RNOH/PackageProvider.h"
+#include "generated/RNOHGeneratedPackage.h"
++ #include "WatermelondbPackage.h"
+
+using namespace rnoh;
+
+std::vector> PackageProvider::getPackages(
+ Package::Context ctx) {
+ return {
+ std::make_shared(ctx), // generated by codegen v1
++ std::make_shared(ctx)
+ };
+}
+```
+
+### 4. 在 ArkTs 侧引入 watermelondb 组件
+
+找到 `entry/src/main/ets/RNPackagesFactory.ts`,添加:
+
+```diff
+...
+import type {RNPackageContext, RNPackage} from '@rnoh/react-native-openharmony/ts';
++ import { WatermelonDBPackage } from '@react-native-ohos/watermelondb';
+
+export function createRNPackages(ctx: RNPackageContext): RNPackage[] {
+return [
++ new WatermelonDBPackage(ctx)
+ ];
+ }
+...
+...
+```
+
+### 5.运行
+
+点击右上角的 `sync` 按钮
+
+或者在终端执行:
+
+```bash
+cd entry
+ohpm install
+```
+
+然后编译、运行即可。
+
+## 约束与限制
+
+### 兼容性
+
+本文档内容基于以下版本验证通过:
+1. RNOH:0.72.90; SDK:HarmonyOS NEXT Developer DB3; IDE: DevEco Studio: 5.0.5.220; ROM:NEXT.0.0.105;
+2. RNOH:0.77.18; SDK:HarmonyOS 6.0.0 Release; IDE: DevEco Studio 6.0.0.858; ROM:6.0.0.112;
+
+### 权限要求
+
+#### 在 entry 目录下添加申请以上权限的原因
+
+打开 `entry/src/main/resources/base/element/string.json`,添加:
+
+```diff
+...
+{
+ "string": [
++ {
++ "name": "module_desc",
++ "value": "moudle description"
++ },
++ {
++ "name": "EntryAbility_desc",
++ "value": "description"
++ },
++ {
++ "name": "EntryAbility_label",
++ "value": "WatermelonDB"
++ },
+ ]
+}
+```
+
+## 属性
+
+> [!TIP] "Platform"列表示该属性在原三方库上支持的平台。
+
+> [!TIP] "HarmonyOS Support"列为 yes 表示 HarmonyOS 平台支持该属性;no 则表示不支持;partially 表示部分支持。使用方法跨平台一致,效果对标 iOS 或 Android 的效果。
+
+**Collection 类**
+| Name | Description | Type | Required | Platform | HarmonyOS Support |
+| --------------------------------------------- | --------------------------------------------- | -------- | -------- | ----------- | ----------------- |
+| db | 获取该集合所属的数据库实例引用 | function | no | iOS/Android | yes |
+| find | 根据指定条件查询集合中匹配的记录 | function | yes | iOS/Android | yes |
+| findAndObserve | 查询记录并建立响应式观察以监听数据变更 | function | yes | iOS/Android | yes |
+| create | 在集合中创建并保存新纪录 | function | yes | iOS/Android | yes |
+| prepareCreate | 预创建记录对象但不立即持久化到数据库 | function | yes | iOS/Android | yes |
+| prepareCreateFromDirtyRaw | 从原始未经验证的数据预创建记录对象 | function | yes | iOS/Android | yes |
+| disposableFromDirtyRaw | 基于原始脏数据创建一次性使用的临时记录 | function | yes | iOS/Android | yes |
+| table | 获取该集合对应的数据库表名称 | function | no | iOS/Android | yes |
+| schema | 获取该集合对应的数据表结构定义 | function | no | iOS/Android | yes |
+| experimentalSubscribe | 订阅集合级别的数据变更通知 | function | yes | iOS/Android | yes |
+
+**Database 类**
+| Name | Description | Type | Required | Platform | HarmonyOS Support |
+| --------------------------------------------- | --------------------------------------------- | -------- | -------- | ----------- | ----------------- |
+| get<T extends Model> | 根据模型类型和 ID 从数据库获取特定记录 | function | yes | iOS/Android | yes |
+| localStorage | 获取数据库的本地存储适配器用于键值对数据 | function | yes | iOS/Android | yes |
+| batch | 创建批量操作以高效执行多个数据库写入 | function | yes | iOS/Android | yes |
+| write<T> | 在写入事务中执行数据库修改操作 | function | yes | iOS/Android | yes |
+| read<T> | 在只读事务中执行数据库查询操作 | function | yes | iOS/Android | yes |
+| action<T> | 执行需要读写权限的数据库动作 | function | yes | iOS/Android | yes |
+| withChangesForTables | 创建监听指定表数据变更的观察者 | function | yes | iOS/Android | yes |
+| experimentalSubscribe | 订阅数据库级别的变更通知 | function | yes | iOS/Android | yes |
+| unsafeResetDatabase | 完全重置数据库并清除所有数据 | function | no | iOS/Android | yes |
+| \_ensurelnWtiter | 确保当前在写入线程中执行操作 | function | yes | iOS/Android | yes |
+| \_fataError | 处理数据库致命错误并终止连接 | function | yes | iOS/Android | yes |
+
+**Relation 类**
+| Name | Description | Type | Required | Platform | HarmonyOS Support |
+| --------------------------------------------- | --------------------------------------------- | -------- | -------- | ----------- | ----------------- |
+| get id | 获取关联目标模型的唯一标识符 | function | no | iOS/Android | yes |
+| set id | 设置关联目标模型的标识符值 | function | yes | iOS/Android | yes |
+| fetch | 异步获取关联记录的完整数据承诺 | function | no | iOS/Android | yes |
+| then<U> | 支持 Promise 链式调用,处理异步获取的关联数据 | function | yes | iOS/Android | yes |
+| set | 建立与另一个模型实例的关联关系 | function | yes | iOS/Android | yes |
+| observe | 监听关联模型数据的实时变化 | function | no | iOS/Android | yes |
+
+**Model 类**
+| Name | Description | Type | Required | Platform | HarmonyOS Support |
+| --------------------------------------------- | --------------------------------------------- | -------- | -------- | ----------- | ----------------- |
+| associations | 定义模型与其他数据表之间的关联关系映射 | function | no | iOS/Android | yes |
+| prepareMarkAsDeleted | 标记为删除状态 | function | no | iOS/Android | yes |
+| \_getChanges | 获取模型变更观察对象 | function | no | iOS/Android | yes |
+| get id | 获取实例的唯一标识符 | function | no | iOS/Android | yes |
+| get syncStatus | 获取数据同步状态 | function | no | iOS/Android | yes |
+| update | 更新模型并立即提交 | function | no | iOS/Android | yes |
+| prepareUpdate | 准备更新 | function | no | iOS/Android | yes |
+| prepareDestroyPermanently | 准备永久销毁但不执行 | function | no | iOS/Android | yes |
+| markAsDeleted | 删除模型并提交 | function | no | iOS/Android | yes |
+| destroyPermanently | 永久删除模型记录 | function | no | iOS/Android | yes |
+| experimentalMarkAsDeleted | 软删除功能 | function | no | iOS/Android | yes |
+| experimentalDestroyPermanently | 永久删除功能 | function | no | iOS/Android | yes |
+| observe | 监听模型数据变化 | function | no | iOS/Android | yes |
+| collection | 获取所属数据集合 | function | no | iOS/Android | yes |
+| get collections | 获取所有集合映射 | function | no | iOS/Android | yes |
+| get database | 获取数据库实例 | function | no | iOS/Android | yes |
+| get db | 获取数据库实例 | function | no | iOS/Android | yes |
+| get asModel | 返回自身实例 | function | no | iOS/Android | yes |
+| callWriter<T> | 在写入线程执行操作 | function | yes | iOS/Android | yes |
+| callReader<T> | 在读取线程执行查询 | function | yes | iOS/Android | yes |
+| subAction<T> | 在事务中执行子操作 | function | yes | iOS/Android | yes |
+| get table | 获取对应数据表名 | function | no | iOS/Android | yes |
+| prepareCreate | 准备创建模型 | function | yes | iOS/Android | yes |
+| \_prepareCreateFromDirtyRaw | 从脏数据创建模型 | function | yes | iOS/Android | yes |
+| \_disposableFromDirtyRaw | 创建一次性模型 | function | yes | iOS/Android | yes |
+| experimentalSubscribe | 实验性订阅模型变更 | function | yes | iOS/Android | yes |
+| \_notifyChanged | 内部通知模型变更 | function | no | iOS/Android | yes |
+| \_notifyDestroyed | 内部通知模型销毁 | function | no | iOS/Android | yes |
+| \_getRaw | 内部获取原始字段值 | function | yes | iOS/Android | yes |
+| \_setRaw | 内部设置字段值并标记变更 | function | yes | iOS/Android | yes |
+| \_dangerouslySetRawWithoutMarkingColumnChange | 内部不安全设置字段值 | function | yes | iOS/Android | yes |
+| \_ensureCanSetRaw | 内部确保可设置原始值 | function | no | iOS/Android | yes |
+| \_ensureNotDisposable | 内部确保非一次性实例 | function | yes | iOS/Android | yes |
+
+**Query 类**
+| Name | Description | Type | Required | Platform | HarmonyOS Support |
+| --------------------------------------------- | --------------------------------------------- | -------- | -------- | ----------- | ----------------- |
+| pipe<T> | 对查询结果进行链式转换操作 | function | no | iOS/Android | yes |
+| fetch | 立即执行查询获取结果 | function | no | iOS/Android | yes |
+| then<U> | 支持 Promise 链式调用查询结果 | function | no | iOS/Android | yes |
+| observe | 监听查询结果的实时变化 | function | no | iOS/Android | yes |
+| observeWithColumns | 监听特定字段变化的查询结果 | function | yes | iOS/Android | yes |
+| fetchCount | 获取查询结果的数量统计 | function | yes | iOS/Android | yes |
+| get count | 获取查询结果总数 | function | no | iOS/Android | yes |
+| observeCount | 监听查询结果数量的变化 | function | no | iOS/Android | yes |
+| fetchIds | 获取查询结果的 ID 列表 | function | no | iOS/Android | yes |
+| unsafeFetchRaw | 不安全地获取原始查询数据 | function | no | iOS/Android | yes |
+| experimentalSubscribe | 实验性查询订阅功能 | function | yes | iOS/Android | yes |
+| experimentalSubscribeWithColumns | 实验性字段变化订阅 | function | yes | iOS/Android | yes |
+| experimentalSubscribeToCount | 实验性数量变化订阅 | function | yes | iOS/Android | yes |
+| markAllAsDeleted | 标记所有查询结果为软删除 | function | no | iOS/Android | yes |
+| destroyAllPermanently | 永久删除所有查询结果 | function | no | iOS/Android | yes |
+| get modelClass | 获取查询对应的模型类 | function | no | iOS/Android | yes |
+| get table | 获取查询的主表名称 | function | no | iOS/Android | yes |
+| get secondaryTables | 获取查询涉及的关联表 | function | no | iOS/Android | yes |
+| get allTables | 获取查询所有相关表 | function | no | iOS/Android | yes |
+| get associations | 获取查询的关联关系 | function | no | iOS/Android | yes |
+| serialize | 序列化查询为可传输格式 | function | no | iOS/Android | yes |
+
+**Schema 类**
+| Name | Description | Type | Required | Platform | HarmonyOS Support |
+| --------------------------------------------- | --------------------------------------------- | -------- | -------- | ----------- | ----------------- |
+| tableName<T extends Model> | 定义数据库表的名称 | function | yes | iOS/Android | yes |
+| columnName | 定义数据库字段的名称 | function | yes | iOS/Android | yes |
+| appSchema | 定义整个应用数据库的结构模式 | function | yes | iOS/Android | yes |
+| validateColumnsSchema | 验证字段模式定义的合法性 | function | yes | iOS/Android | yes |
+| tableSchema | 定义单个数据表的结构和字段配置 | function | yes | iOS/Android | yes |
+
+## 5.遗留问题
+
+## 6.其他
+
+## 7.开源协议
+
+本项目基于 [MIT License (MIT)](https://github.com/Nozbe/WatermelonDB/blob/master/LICENSE) ,请自由地享受和参与开源。
+