chenritian 1 сар өмнө
parent
commit
b596d59e83

+ 1 - 0
commons/basic/Index.ets

@@ -3,6 +3,7 @@ export { Test } from './src/main/ets/rdb/tables/Test'
 
 
 
+
 export { registerFontUtil } from './src/main/ets/utils/RegisterFontUtil'
 export { RouterPage } from './src/main/ets/ts'
 export { YTToast } from './src/main/ets/utils/YTToast'

+ 1 - 1
commons/basic/src/main/ets/rdb/sqls/RDBSql.ts

@@ -1,3 +1,3 @@
 export const rDbSql = {
-  CREATE_TEST_TABLE: 'CREATE TABLE IF NOT EXISTS Test (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER NOT NULL)'
+  CREATE_TEST_TABLE: 'CREATE TABLE IF NOT EXISTS Test (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)'
 }

+ 4 - 4
commons/basic/src/main/ets/rdb/tables/Test.ets

@@ -1,6 +1,6 @@
 //名称就是表名
-export interface Test {
-  id: number;
-  name: string;
-  age: number;
+export class Test {
+  id?: number;
+  name?: string;
+  age?: number;
 }

+ 97 - 14
commons/basic/src/main/ets/rdb/utils/RelationalStoreUtis.ets → commons/basic/src/main/ets/rdb/utils/RelationalStoreUtis.ts

@@ -44,9 +44,9 @@ export class RelationalStoreUtils {
         }
         // 设置数据库的版本,入参为大于0的整数
         store.version = 3;
+        RelationalStoreUtils.cloudLoadStore = store;
       }
       success?.()
-      RelationalStoreUtils.cloudLoadStore = store;
     })
   }
 
@@ -57,45 +57,80 @@ export class RelationalStoreUtils {
 
 
   /**
-   * 插入数据
-   * @param tableName
+   * 插入数据 --id不用传,数据库自增
+   * @param table 对呀的哪张表
    * @param param
    * @param success
    */
-  static insert(tableName: string, param: ESObject, success?: () => void) {
+  static insert<T>(table: new () => T, param: ESObject, success?: (id: number) => void) {
+    // 添加参数校验
+    if (!table || !table.name) {
+      console.error('Invalid table constructor provided');
+      return;
+    }
+
     const insertParam: relationalStore.ValuesBucket = {};
     if (param) {
       Object.keys(param).forEach((key) => {
         insertParam[key] = param[key];
       })
     }
+
     if (RelationalStoreUtils.cloudLoadStore !== undefined) {
-      (RelationalStoreUtils.cloudLoadStore as relationalStore.RdbStore).insert(tableName, insertParam,
+      (RelationalStoreUtils.cloudLoadStore as relationalStore.RdbStore).insert(table.name, insertParam,
         (err: BusinessError, rowId: number) => {
           if (err) {
             console.error(`Failed to insert data. Code:${err.code}, message:${err.message}`);
             return;
           }
-          success?.();
+          success?.(rowId);
           console.info(`Succeeded in inserting data. rowId:${rowId}`);
         })
     }
   }
 
 
+  /**
+   * 插入数据 --id不用传,数据库自增
+   * @param table 对呀的哪张表
+   * @param param
+   * @param success  返回插入后的id
+   */
+  static insertSync<T>(table: new () => T, param: ESObject) {
+    let id = -1
+    // 添加参数校验
+    if (!table || !table.name) {
+      console.error('Invalid table constructor provided');
+      return;
+    }
+
+    const insertParam: relationalStore.ValuesBucket = {};
+    if (param) {
+      Object.keys(param).forEach((key) => {
+        insertParam[key] = param[key];
+      })
+    }
+
+    if (RelationalStoreUtils.cloudLoadStore !== undefined) {
+    id =   (RelationalStoreUtils.cloudLoadStore as relationalStore.RdbStore).insertSync(table.name, insertParam)
+    }
+    return id
+  }
+
+
   /**
    * 根据id更新数据
    * @param tableName
    * @param param
    * @param success
    */
-  static updateItemById(tableName: string, param: ESObject, success?: () => void) {
+  static updateItemById<T>(table: new () => T, param: ESObject, success?: () => void) {
     const updateParam: relationalStore.ValuesBucket = {};
     Object.keys(param).forEach((key) => {
       updateParam[key] = param[key];
     })
 
-    let predicates = new relationalStore.RdbPredicates(tableName);
+    let predicates = new relationalStore.RdbPredicates(table.name);
     predicates = predicates.equalTo("id", updateParam.id)
 
     if (RelationalStoreUtils.cloudLoadStore !== undefined) {
@@ -111,15 +146,37 @@ export class RelationalStoreUtils {
     }
   }
 
+
+  /**
+   * 根据id更新数据
+   * @param tableName
+   * @param param
+   * @param success
+   */
+  static updateItemByIdSync<T>(table: new () => T, param: ESObject) {
+    const updateParam: relationalStore.ValuesBucket = {};
+    Object.keys(param).forEach((key) => {
+      updateParam[key] = param[key];
+    })
+
+    let predicates = new relationalStore.RdbPredicates(table.name);
+    predicates = predicates.equalTo("id", updateParam.id)
+
+    if (RelationalStoreUtils.cloudLoadStore !== undefined) {
+      (RelationalStoreUtils.cloudLoadStore as relationalStore.RdbStore).updateSync(updateParam, predicates)
+    }
+  }
+
+
   /**
    * 查询列表
    * @param tableName
    * @param queryParam
    * @returns
    */
-  static getList<T = ESObject>(tableName: string, queryParam?: ESObject): T[] {
+  static getListSync<T = ESObject>(table: new () => T, queryParam?: ESObject): T[] {
     const list: T[] = []
-    let predicates = new relationalStore.RdbPredicates(tableName);
+    let predicates = new relationalStore.RdbPredicates(table.name);
     let keys: string[] = []
     if (queryParam) {
       keys = Object.keys(queryParam);
@@ -167,10 +224,10 @@ export class RelationalStoreUtils {
    * @param queryParam
    * @returns
    */
-  static getItemById<T = ESObject>(tableName: string, queryParam: ESObject) {
+  static getItemByIdSync<T = ESObject>(table: new () => T, queryParam: ESObject) {
     const keys = Object.keys(queryParam);
     const item: ESObject = {}
-    let predicates = new relationalStore.RdbPredicates(tableName);
+    let predicates = new relationalStore.RdbPredicates(table.name);
 
     if (RelationalStoreUtils.cloudLoadStore != undefined) {
       //高级写法
@@ -199,15 +256,41 @@ export class RelationalStoreUtils {
     return item as T;
   }
 
+
+  /**
+   * 根据id删除数据
+   * @param tableName
+   * @param queryParam
+   * @param success
+   */
+  static deleteItemById<T>(table: new () => T, id: number, success?: () => void) {
+
+    let predicates = new relationalStore.RdbPredicates(table.name);
+    predicates = predicates.equalTo("id", id)
+
+    if (RelationalStoreUtils.cloudLoadStore !== undefined) {
+      (RelationalStoreUtils.cloudLoadStore as relationalStore.RdbStore).delete(predicates,
+        (err: BusinessError, flag: number) => {
+          if (err) {
+            console.error(`Updated failed, code is ${err.code},message is ${err.message}`);
+            return;
+          }
+          if (flag != 0) {
+            success?.()
+          }
+        })
+    }
+  }
+
   /**
    * 根据id删除数据
    * @param tableName
    * @param queryParam
    * @param success
    */
-  static deleteItemById(tableName: string, id: number, success?: () => void) {
+  static deleteItemByIdSync<T>(table: new () => T, id: number) {
 
-    let predicates = new relationalStore.RdbPredicates(tableName);
+    let predicates = new relationalStore.RdbPredicates(table.name);
     predicates = predicates.equalTo("id", id)
 
     if (RelationalStoreUtils.cloudLoadStore !== undefined) {

+ 6 - 6
features/feature/src/main/ets/view/ThirdView.ets

@@ -8,9 +8,9 @@ export struct ThirdView {
       Row() {
         Button('测试新增')
           .onClick(() => {
-            RelationalStoreUtils.insert('Test', { name: 'test1', age: 18 }, () => {
+            RelationalStoreUtils.insert(Test, { name: 'test1', age: 18 }, () => {
               console.log('insert success');
-              let list = RelationalStoreUtils.getList<Test>('Test')
+              let list = RelationalStoreUtils.getListSync(Test)
               this.list = list
               console.log('list:', JSON.stringify(list))
             })
@@ -18,18 +18,18 @@ export struct ThirdView {
 
         Button('测试修改')
           .onClick(() => {
-            RelationalStoreUtils.updateItemById('Test', { id: 1, name: '测试1修改', age: 20 }, () => {
+            RelationalStoreUtils.updateItemById(Test, { id: 1, name: '测试1修改', age: 20 }, () => {
               console.log('insert success');
-              let list = RelationalStoreUtils.getList<Test>('Test')
+              let list = RelationalStoreUtils.getListSync(Test)
               this.list = list
               console.log('list:', JSON.stringify(list))
             })
           })
         Button('测试删除')
           .onClick(() => {
-            RelationalStoreUtils.deleteItemById('Test', 1)
+            RelationalStoreUtils.deleteItemById(Test, 1)
             console.log('insert success');
-            let list = RelationalStoreUtils.getList<Test>('Test')
+            let list = RelationalStoreUtils.getListSync(Test)
             this.list = list
             console.log('list:', JSON.stringify(list))
           })

+ 79 - 29
hvigorfile.ts

@@ -273,22 +273,23 @@ function rDBPlugin(): HvigorPlugin {
                             const content = fs.readFileSync(fullPath, 'utf8');
 
                             // 使用正则表达式匹配interface名称
-                            const interfaceRegex = /export\s+interface\s+(\w+)/g;
+                            const typeRegex = /export\s+(interface|class)\s+(\w+)/g;
                             let match;
 
-                            while ((match = interfaceRegex.exec(content)) !== null) {
-                                const interfaceName = match[1];
-                                tableNames.push(interfaceName);
+                            while ((match = typeRegex.exec(content)) !== null) {
+                                const typeKind = match[1]; // 'interface' 或 'class'
+                                const typeName = match[2]; // 类型名称
+                                tableNames.push(typeName);
 
-                                // 解析接口属性并生成字段
-                                const fieldDefinitions = parseInterfaceFields(content, interfaceName);
+                                // 解析字段定义
+                                const fieldDefinitions = parseTypeFields(content, typeName);
 
-                                // 生成CREATE TABLE SQL语句(包含字段)
+                                // 生成CREATE TABLE SQL语句
                                 const sqlStatement =
-                                    `static readonly CREATE_${interfaceName.toUpperCase()}_TABLE = 'CREATE TABLE IF NOT EXISTS ${interfaceName} (${fieldDefinitions})';`;
+                                    `static readonly CREATE_${typeName.toUpperCase()}_TABLE = 'CREATE TABLE IF NOT EXISTS ${typeName} (${fieldDefinitions})';`;
                                 sqlStatements.push(sqlStatement);
 
-                                console.log(`Found interface: ${interfaceName}`);
+                                console.log(`Found ${typeKind}: ${typeName}`);
                             }
                         } catch (readError) {
                             console.error(`Error reading file ${file}:`, readError);
@@ -297,54 +298,84 @@ function rDBPlugin(): HvigorPlugin {
                 });
 
                 // 添加解析接口字段的辅助函数
-                function parseInterfaceFields(content: string, interfaceName: string): string {
-                    // 查找接口定义区域
-                    const interfaceStart = content.indexOf(`export interface ${interfaceName}`);
-                    if (interfaceStart === -1) {
+                function parseTypeFields(content: string, typeName: string): string {
+                    // 使用正则表达式查找 interface 或 class 定义,允许中间有多个空格
+                    const classRegex = new RegExp(`export\\s+class\\s+${typeName}`, 'g');
+                    const interfaceRegex = new RegExp(`export\\s+interface\\s+${typeName}`, 'g');
+
+                    const classMatch = classRegex.exec(content);
+                    const interfaceMatch = interfaceRegex.exec(content);
+
+                    let typeStart = -1;
+                    if (classMatch) {
+                        typeStart = classMatch.index;
+                    } else if (interfaceMatch) {
+                        typeStart = interfaceMatch.index;
+                    }
+
+                    console.log('开始解析类型体内容:');
+                    console.log('typeStart内容:', typeStart);
+
+                    if (typeStart === -1) {
                         return 'ID INTEGER PRIMARY KEY AUTOINCREMENT';
                     }
 
-                    const openBrace = content.indexOf('{', interfaceStart);
+                    // 后续逻辑保持不变...
+                    const openBrace = content.indexOf('{', typeStart);
                     const closeBrace = content.indexOf('}', openBrace);
 
                     if (openBrace === -1 || closeBrace === -1) {
+                        console.log('openBrace和closeBrace内容:', openBrace,closeBrace);
                         return 'ID INTEGER PRIMARY KEY AUTOINCREMENT';
                     }
 
-                    const interfaceBody = content.substring(openBrace + 1, closeBrace);
-                    const lines = interfaceBody.split('\n');
+                    const typeBody = content.substring(openBrace + 1, closeBrace);
+                    const lines = typeBody.split('\n');
 
                     const fields: string[] = [];
                     let hasPrimaryKey = false;
 
+                    // 改进字段解析逻辑
                     lines.forEach(line => {
-                        const fieldMatch = line.trim().match(/^(\w+)\??\s*:\s*(.+?);?$/);
+                        const trimmedLine = line.trim();
+
+                        // 使用更宽松的正则表达式,支持多种格式
+                        // 匹配格式: fieldName?: type; 或 fieldName: type; (允许前后空格)
+                        const fieldMatch = trimmedLine.match(/^(\w+)(\??)\s*:\s*([^;]+?)\s*(?:;|$)/);
+
                         if (fieldMatch) {
                             const fieldName = fieldMatch[1];
-                            const fieldType = fieldMatch[2].trim();
+                            const isOptional = fieldMatch[2] === '?';
+                            const fieldType = fieldMatch[3].trim();
+
+                            console.log(`解析字段: ${fieldName}, 可选: ${isOptional}, 类型: ${fieldType}`); // 调试信息
 
                             // 根据TypeScript类型映射到SQLite类型
                             let sqliteType = 'TEXT';
-                            if (fieldType.includes('number') || fieldType.includes('Number')) {
+                            const normalizedFieldType = fieldType.toLowerCase();
+
+                            if (normalizedFieldType.includes('number') || normalizedFieldType.includes('int') || normalizedFieldType.includes('float')) {
                                 sqliteType = 'INTEGER';
-                            } else if (fieldType.includes('boolean') || fieldType.includes('Boolean')) {
+                            } else if (normalizedFieldType.includes('boolean')) {
                                 sqliteType = 'INTEGER';
-                            } else if (fieldType.includes('Date')) {
+                            } else if (normalizedFieldType.includes('date')) {
                                 sqliteType = 'TEXT';
                             }
 
-                            // 检查是否为主键字段(约定以id命名的字段作为主键)
+                            // 检查是否为主键字段
                             if (fieldName.toLowerCase() === 'id') {
                                 fields.push(`${fieldName} INTEGER PRIMARY KEY AUTOINCREMENT`);
                                 hasPrimaryKey = true;
                             } else {
                                 // 处理可选字段
-                                const nullable = line.trim().includes('?') ? '' : ' NOT NULL';
+                                const nullable = isOptional ? '' : ' NOT NULL';
                                 fields.push(`${fieldName} ${sqliteType}${nullable}`);
                             }
                         }
                     });
 
+
+
                     // 如果没有定义主键,则添加默认主键
                     if (!hasPrimaryKey) {
                         fields.unshift('ID INTEGER PRIMARY KEY AUTOINCREMENT');
@@ -354,6 +385,8 @@ function rDBPlugin(): HvigorPlugin {
                 }
 
 
+
+
                 // 更新RelationalStoreUtils.ets文件中的tables数组
                 const relationalStorePath =
                     path.join(currentDir, 'src', 'main', 'ets', 'rdb', 'utils', 'RelationalStoreUtis.ets');
@@ -373,29 +406,45 @@ function rDBPlugin(): HvigorPlugin {
                 // 替换原有的更新RDBSql.ets文件的代码块
 
                 // 更新RDBSql.ts文件
+                // 更新RDBSql.ts文件的改进逻辑
                 const rdbSqlPath = path.join(currentDir, 'src', 'main', 'ets', 'rdb', 'sqls', 'RDBSql.ts');
                 if (fs.existsSync(rdbSqlPath)) {
                     let content = fs.readFileSync(rdbSqlPath, 'utf8');
 
+                    // 解析现有rDbSql对象中的属性
+                    const existingProperties: Map<string, string> = new Map();
+                    const propertyRegex = /(\w+):\s*'([^']+)'/g;
+                    let match;
+                    while ((match = propertyRegex.exec(content)) !== null) {
+                        existingProperties.set(match[1], match[2]);
+                    }
+
                     // 构建SQL语句对象属性
                     if (sqlStatements.length > 0) {
-                        // 提取属性名和值
                         const sqlProperties: string[] = [];
+
+                        // 首先保留现有的属性(用于手动添加的SQL)
+                        existingProperties.forEach((value, key) => {
+                            // 检查是否是自动生成的CREATE_*_TABLE属性
+                            if (!key.startsWith('CREATE_') || !key.endsWith('_TABLE')) {
+                                sqlProperties.push(`  ${key}: '${value}'`);
+                            }
+                        });
+
+                        // 添加或更新基于类定义生成的SQL属性
                         sqlStatements.forEach(statement => {
-                            // 从 static readonly CREATE_USER_TABLE = 'CREATE TABLE...' 提取属性
                             const propertyName = statement.split('=')[0].trim().replace('static readonly ', '');
-                            const propertyValue = statement.split('=')[1].trim().slice(1, -2); // 去掉引号和分号
+                            const propertyValue = statement.split('=')[1].trim().slice(1, -2);
                             sqlProperties.push(`  ${propertyName}: '${propertyValue}'`);
                         });
 
                         // 构建新的对象内容
                         const newContent = `export const rDbSql = {\n${sqlProperties.join(',\n')}\n}`;
-
                         fs.writeFileSync(rdbSqlPath, newContent, 'utf8');
-                        console.log('RDBSql.ts文件已更新为对象形式');
+                        console.log('RDBSql.ts文件已更新,保留了手动添加的SQL语句');
                     }
                 } else {
-                    // 如果文件不存在,创建新文件
+                    // 如果文件不存在,创建新文件(原有逻辑保持不变)
                     if (sqlStatements.length > 0) {
                         const sqlProperties: string[] = [];
                         sqlStatements.forEach(statement => {
@@ -418,6 +467,7 @@ function rDBPlugin(): HvigorPlugin {
                 }
 
 
+
                 console.log('----------------------------------------');
             } else {
                 console.log('Tables directory not found');