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参数 */} +