接口.jianghuKnex

12003

jianghuKnex 是一个基于 knex 的数据库查询和操作库,提供了简洁易用的 API,支持常规的 CRUD 操作、数据历史记录、事务处理和复杂连表查询。以下是 jianghuKnex 的常用操作:

  • 查询:selectfirstcount
  • 新增:jhInsert
  • 更新:jhUpdate
  • 删除:jhDelete
  • 内连接:innerJoin
  • 左连接:leftJoin
  • 右连接:rightJoin
  • 分页: offset&limit
  • 事务处理: transaction
  • ...更多操作 参考knex文档

jianghuKnex启用

/config/config.local.js or /config/config.prod.js中配置knex信息,
框架会自动将knexjianghuKnex挂载到 this.app上。

  1. {
  2. knex: {
  3. client: {
  4. dialect: 'mysql',
  5. connection: {
  6. host: '127.0.0.1',
  7. port: 3306,
  8. user: 'root',
  9. password: '123456',
  10. database: 'test01'
  11. },
  12. pool: { min: 0, max: 10 },
  13. acquireConnectionTimeout: 30000
  14. },
  15. app: true
  16. }
  17. }

jianghuKnex使用

jianghuKnex 在原有 knex 的基础上进行了扩展,提供了一些额外的功能。以下是一些常用操作及示例代码

查询

  • select:查询返回列表
    1. const list = await this.app.jianghuKnex("student").where({ gender: 'male' }).select();
    2. this.app.logger.info('jianghuKnexExample.js select()', '=====>',`result length: ${list.length}`);
  • first:查询返回第一个结果
    1. const student = await this.app.jianghuKnex("student").where({ studentId: 'S10001' }).first();
    2. this.app.logger.info('jianghuKnexExample.js first()', '=====>', { studentId: student?.studentId, name: student?.name });
  • count:查询数量
    1. const countResult = await this.app.jianghuKnex("student").where({}).count('* as count').first();
    2. this.app.logger.info('jianghuKnexExample.js count()', '=====>', countResult);

新增

  • jhInsert:新增数据。
    1. const student = { studentId: 'T00001', name: '测试001' };
    2. await this.app.jianghuKnex("student", this.ctx).jhInsert(student);
    3. this.app.logger.info('jianghuKnexExample.js jhInsert()', '=====>', student);

更新

  • jhUpdate:更新现有数据
    1. const student = { studentId: 'T00001', name: '测试同学001' };
    2. await this.app.jianghuKnex("student", this.ctx)
    3. .where({ studentId: student.studentId })
    4. .jhUpdate({ name: student.name });
    5. this.app.logger.info('jianghuKnexExample.js jhUpdate()', '=====>', student);

删除

  • jhDelete:删除数据
    1. const student = { studentId: 'T00001' };
    2. await this.app.jianghuKnex("student", this.ctx)
    3. .where({ studentId: student.studentId })
    4. .jhDelete({ name: student.name });
    5. this.app.logger.info('jianghuKnexExample.js jhDelete()', '=====>', student);

连表查询

  • innerJoin: 内连接
  • leftJoin: 左连接
  • rightJoin: 右连接
    1. const classId = '2021-01级-01班';
    2. const list = await this.app.jianghuKnex("class", this.ctx)
    3. .leftJoin('student', 'class.classId', 'student.classId')
    4. .whereRaw('class.classId = ?', [classId])
    5. .select();
    6. this.app.logger.info('jianghuKnexExample.js leftJoin()', '=====>', `result length: ${list.length}`);

分页查询

  • offset: 第几页
  • limit: 每页多少条数据
    1. const pageSize = 5;
    2. const pageNumber = 1;
    3. const list = await this.app.jianghuKnex("student")
    4. .offset((pageNumber - 1) * pageSize)
    5. .limit(pageSize)
    6. .select();
    7. this.app.logger.info('jianghuKnexExample.js offset()', '=====>',`result length: ${list.length}`);

数据历史

jianghuKnex('student', this.ctx), 在传入 this.ctx 后,jianghuKnex 会自动记录本次操作记录 同时 也会记录数据历史

  • 操作记录
    • 当前表.operationByUserId:操作者的 userId。
    • 当前表.operationByUser:操作者的用户名。
    • 当前表.operationAt:操作发生的时间。
  • 数据历史: _record_history里记录了数据历史, 可以通过使用 jianghu-init tool --type=record-history-page 工具,您可以生成查看 数据历史页面,以便查看历史变动。

事务

jianghuKnex 支持事务处理,以确保数据操作的一致性和完整性。事务可以确保一组操作要么全部成功执行,要么全部失败回滚。要使用事务,您可以使用框架提供的 transaction 方法。

  1. const student = { studentId: 'T00002', name: '测试002' };
  2. const classObj = { classId: '2021-07级-01班', className: '七年级一班' };
  3. await this.app.jianghuKnex.transaction(async trx => {
  4. // 删除
  5. await trx('student', this.ctx).jhDelete(student);
  6. await trx('class', this.ctx).jhDelete(classObj);
  7. // 新增
  8. await trx('student', this.ctx).jhInsert(student);
  9. await trx('class', this.ctx).jhInsert(classObj);
  10. });
  11. this.app.logger.info('jianghuKnexExample.js transaction()', '=====>', classObj);

测试表

  1. CREATE TABLE `class` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT,
  3. `classId` varchar(255) DEFAULT NULL COMMENT '班级ID',
  4. `className` varchar(255) DEFAULT NULL COMMENT '学生状态',
  5. `remarks` mediumtext COMMENT '备注',
  6. `operation` varchar(255) DEFAULT 'insert' COMMENT '操作; insert, update, jhInsert, jhUpdate, jhDelete jhRestore',
  7. `operationByUserId` varchar(255) DEFAULT NULL COMMENT '操作者userId',
  8. `operationByUser` varchar(255) DEFAULT NULL COMMENT '操作者用户名',
  9. `operationAt` varchar(255) DEFAULT NULL COMMENT '操作时间; E.g: 2021-05-28T10:24:54+08:00 ',
  10. PRIMARY KEY (`id`) USING BTREE
  11. ) ENGINE=InnoDB AUTO_INCREMENT=175 DEFAULT CHARSET=utf8mb4;
  12. CREATE TABLE `student` (
  13. `id` int(11) NOT NULL AUTO_INCREMENT,
  14. `studentId` varchar(255) DEFAULT NULL COMMENT '学生ID',
  15. `name` varchar(255) DEFAULT NULL COMMENT '学生名字',
  16. `gender` varchar(255) DEFAULT NULL COMMENT '性别',
  17. `dateOfBirth` varchar(255) DEFAULT NULL COMMENT '出生日期',
  18. `classId` varchar(255) DEFAULT NULL COMMENT '班级ID',
  19. `level` varchar(255) DEFAULT NULL COMMENT '年级',
  20. `bodyHeight` varchar(255) DEFAULT NULL COMMENT '身高',
  21. `studentStatus` varchar(255) DEFAULT NULL COMMENT '学生状态',
  22. `remarks` mediumtext COMMENT '备注',
  23. `operation` varchar(255) DEFAULT 'insert' COMMENT '操作; insert, update, jhInsert, jhUpdate, jhDelete jhRestore',
  24. `operationByUserId` varchar(255) DEFAULT NULL COMMENT '操作者userId',
  25. `operationByUser` varchar(255) DEFAULT NULL COMMENT '操作者用户名',
  26. `operationAt` varchar(255) DEFAULT NULL COMMENT '操作时间; E.g: 2021-05-28T10:24:54+08:00 ',
  27. PRIMARY KEY (`id`) USING BTREE,
  28. KEY `studentId` (`studentId`) USING BTREE
  29. ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;

数据隔离

多应用共用一个数据库时,每个应用之间数据隔离,更新参考多应用-jhId

  • enable: 是否开启
  • jhId: 数据隔离的标记
  • careTableViewList: 采用数据隔离的表
    1. jianghuConfig:{
    2. jhIdConfig: {
    3. enable: false,
    4. jhId: 'project01',
    5. careTableViewList: [ 'class', 'student' ],
    6. },
    7. }