db.mdc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. ---
  2. description: 数据库(db)
  3. globs:
  4. ---
  5. # 数据库(db)
  6. 数据库使用的是`typeorm`库
  7. 中文文档:](httpsom)
  8. 官方文档:[https://typeorm.io](mdc:https:/据库文档:[https:/www.midwayjs.org/docs/extensions/orm](https:/www.midwayjs.org/docs/extensions/orm)
  9. ## 数据库配置
  10. 支持`Mysql`、`PostgreSQL`、`Sqlite`三种数据库
  11. #### Mysql
  12. `src/config/config.local.ts`
  13. ```ts
  14. import { CoolConfig } from "@cool-midway/core";
  15. import { MidwayConfig } from "@midwayjs/core";
  16. export default {
  17. typeorm: {
  18. dataSource: {
  19. default: {
  20. type: "mysql",
  21. host: "127.0.0.1",
  22. port: 3306,
  23. username: "root",
  24. password: "123456",
  25. database: "cool",
  26. // 自动建表 注意:线上部署的时候不要使用,有可能导致数据丢失
  27. synchronize: true,
  28. // 打印日志
  29. logging: false,
  30. // 字符集
  31. charset: "utf8mb4",
  32. // 是否开启缓存
  33. cache: true,
  34. // 实体路径
  35. entities: ["**/modules/*/entity"],
  36. },
  37. },
  38. },
  39. } as MidwayConfig;
  40. ```
  41. #### PostgreSQL
  42. 需要先安装驱动
  43. ```shell
  44. npm install pg --save
  45. ```
  46. `src/config/config.local.ts`
  47. ```ts
  48. import { CoolConfig } from "@cool-midway/core";
  49. import { MidwayConfig } from "@midwayjs/core";
  50. export default {
  51. typeorm: {
  52. dataSource: {
  53. default: {
  54. type: "postgres",
  55. host: "127.0.0.1",
  56. port: 5432,
  57. username: "postgres",
  58. password: "123456",
  59. database: "cool",
  60. // 自动建表 注意:线上部署的时候不要使用,有可能导致数据丢失
  61. synchronize: true,
  62. // 打印日志
  63. logging: false,
  64. // 字符集
  65. charset: "utf8mb4",
  66. // 是否开启缓存
  67. cache: true,
  68. // 实体路径
  69. entities: ["**/modules/*/entity"],
  70. },
  71. },
  72. },
  73. } as MidwayConfig;
  74. ```
  75. #### Sqlite
  76. 需要先安装驱动
  77. ```shell
  78. npm install sqlite3 --save
  79. ```
  80. `src/config/config.local.ts`
  81. ```ts
  82. import { CoolConfig } from "@cool-midway/core";
  83. import { MidwayConfig } from "@midwayjs/core";
  84. import * as path from "path";
  85. export default {
  86. typeorm: {
  87. dataSource: {
  88. default: {
  89. type: "sqlite",
  90. // 数据库文件地址
  91. database: path.join(__dirname, "../../cool.sqlite"),
  92. // 自动建表 注意:线上部署的时候不要使用,有可能导致数据丢失
  93. synchronize: true,
  94. // 打印日志
  95. logging: false,
  96. // 实体路径
  97. entities: ["**/modules/*/entity"],
  98. },
  99. },
  100. },
  101. } as MidwayConfig;
  102. ```
  103. ## 事务示例
  104. `cool-admin`封装了自己事务,让代码更简洁
  105. #### 示例
  106. ```ts
  107. import { Inject, Provide } from "@midwayjs/core";
  108. import { BaseService, CoolTransaction } from "@cool-midway/core";
  109. import { InjectEntityModel } from "@midwayjs/orm";
  110. import { Repository, QueryRunner } from "typeorm";
  111. import { DemoAppGoodsEntity } from "../entity/goods";
  112. /**
  113. * 商品
  114. */
  115. @Provide()
  116. export class DemoGoodsService extends BaseService {
  117. @InjectEntityModel(DemoAppGoodsEntity)
  118. demoAppGoodsEntity: Repository<DemoAppGoodsEntity>;
  119. /**
  120. * 事务
  121. * @param params
  122. * @param queryRunner 无需调用者传参, 自动注入,最后一个参数
  123. */
  124. @CoolTransaction({ isolation: "SERIALIZABLE" })
  125. async testTransaction(params: any, queryRunner?: QueryRunner) {
  126. await queryRunner.manager.insert<DemoAppGoodsEntity>(DemoAppGoodsEntity, {
  127. title: "这是个商品",
  128. pic: "商品图",
  129. price: 99.0,
  130. type: 1,
  131. });
  132. }
  133. }
  134. ```
  135. ::: tip
  136. `CoolTransaction`中已经做了异常捕获,所以方法内部无需捕获异常,必须使用`queryRunner`做数据库操作,
  137. 而且不能是异步的,否则事务无效,
  138. `queryRunner`会注入到被注解的方法最后一个参数中, 无需调用者传参
  139. :::
  140. ## 字段
  141. BaseEntity 是实体基类,所有实体类都需要继承它。
  142. - v8.x 之前位于`@cool-midway/core`包中
  143. - v8.x 之后位于`src/modules/base/entity/base.ts`
  144. ```typescript
  145. import { Index, PrimaryGeneratedColumn, Column } from "typeorm";
  146. import * as moment from "moment";
  147. import { CoolBaseEntity } from "@cool-midway/core";
  148. const transformer = {
  149. to(value) {
  150. return value
  151. ? moment(value).format("YYYY-MM-DD HH:mm:ss")
  152. : moment().format("YYYY-MM-DD HH:mm:ss");
  153. },
  154. from(value) {
  155. return value;
  156. },
  157. };
  158. /**
  159. * 实体基类
  160. */
  161. export abstract class BaseEntity extends CoolBaseEntity {
  162. // 默认自增
  163. @PrimaryGeneratedColumn("increment", {
  164. comment: "ID",
  165. })
  166. id: number;
  167. @Index()
  168. @Column({
  169. comment: "创建时间",
  170. type: "varchar",
  171. transformer,
  172. })
  173. createTime: Date;
  174. @Index()
  175. @Column({
  176. comment: "更新时间",
  177. type: "varchar",
  178. transformer,
  179. })
  180. updateTime: Date;
  181. @Index()
  182. @Column({ comment: "租户ID", nullable: true })
  183. tenantId: number;
  184. }
  185. ```
  186. ```typescript
  187. // v8.x 之前
  188. import { BaseEntity } from "@cool-midway/core";
  189. // v8.x 之后
  190. import { BaseEntity } from "../../base/entity/base";
  191. import { Column, Entity, Index } from "typeorm";
  192. /**
  193. * demo模块-用户信息
  194. */
  195. // 表名必须包含模块固定格式:模块_,
  196. @Entity("demo_user_info")
  197. // DemoUserInfoEntity是模块+表名+Entity
  198. export class DemoUserInfoEntity extends BaseEntity {
  199. @Index()
  200. @Column({ comment: "手机号", length: 11 })
  201. phone: string;
  202. @Index({ unique: true })
  203. @Column({ comment: "身份证", length: 50 })
  204. idCard: string;
  205. // 生日只需要精确到哪一天,所以type:'date',如果需要精确到时分秒,应为'datetime'
  206. @Column({ comment: "生日", type: "date" })
  207. birthday: Date;
  208. @Column({ comment: "状态 0-禁用 1-启用", default: 1 })
  209. status: number;
  210. @Column({
  211. comment: "分类 0-普通 1-会员 2-超级会员",
  212. default: 0,
  213. type: "tinyint",
  214. })
  215. type: number;
  216. // 由于labels的类型是一个数组,所以Column中的type类型必须得是'json'
  217. @Column({ comment: "标签", nullable: true, type: "json" })
  218. labels: string[];
  219. @Column({
  220. comment: "余额",
  221. type: "decimal",
  222. precision: 5,
  223. scale: 2,
  224. })
  225. balance: number;
  226. @Column({ comment: "备注", nullable: true })
  227. remark: string;
  228. @Column({ comment: "简介", type: "text", nullable: true })
  229. summary: string;
  230. }
  231. ```
  232. ## 虚拟字段
  233. 虚拟字段是指数据库中没有实际存储的字段,而是通过其他字段计算得到的字段,这种字段在查询时可以直接使用,但是不能进行更新操作
  234. ```ts
  235. import { BaseEntity } from "@cool-midway/core";
  236. import { Column, Entity, Index } from "typeorm";
  237. /**
  238. * 数据实体
  239. */
  240. @Entity("xxx_xxx")
  241. export class XxxEntity extends BaseEntity {
  242. @Index()
  243. @Column({
  244. type: "varchar",
  245. length: 7,
  246. asExpression: "DATE_FORMAT(createTime, '%Y-%m')",
  247. generatedType: "VIRTUAL",
  248. comment: "月份",
  249. })
  250. month: string;
  251. @Index()
  252. @Column({
  253. type: "varchar",
  254. length: 4,
  255. asExpression: "DATE_FORMAT(createTime, '%Y')",
  256. generatedType: "VIRTUAL",
  257. comment: "年份",
  258. })
  259. year: string;
  260. @Index()
  261. @Column({
  262. type: "varchar",
  263. length: 10,
  264. asExpression: "DATE_FORMAT(createTime, '%Y-%m-%d')",
  265. generatedType: "VIRTUAL",
  266. comment: "日期",
  267. })
  268. date: string;
  269. @Column({ comment: "退款", type: "json", nullable: true })
  270. refund: {
  271. // 退款单号
  272. orderNum: string;
  273. // 金额
  274. amount: number;
  275. // 实际退款金额
  276. realAmount: number;
  277. // 状态 0-申请中 1-已退款 2-拒绝
  278. status: number;
  279. // 申请时间
  280. applyTime: Date;
  281. // 退款时间
  282. time: Date;
  283. // 退款原因
  284. reason: string;
  285. // 拒绝原因
  286. refuseReason: string;
  287. };
  288. // 将退款状态提取出来,方便查询
  289. @Index()
  290. @Column({
  291. asExpression: "JSON_EXTRACT(refund, '$.status')",
  292. generatedType: "VIRTUAL",
  293. comment: "退款状态",
  294. nullable: true,
  295. })
  296. refundStatus: number;
  297. }
  298. ```
  299. ## 不使用外键
  300. typeorm 有很多 OneToMany, ManyToOne, ManyToMany 等关联关系,这种都会生成外键,但是在实际生产开发中,不推荐使用外键:
  301. - 性能影响:外键会在插入、更新或删除操作时增加额外的开销。数据库需要检查外键约束是否满足,这可能会降低数据库的性能,特别是在大规模数据操作时更为明显。
  302. - 复杂性增加:随着系统的发展,数据库结构可能会变得越来越复杂。外键约束增加了数据库结构的复杂性,使得数据库的维护和理解变得更加困难。
  303. - 可扩展性问题:在分布式数据库系统中,数据可能分布在不同的服务器上。外键约束会影响数据的分片和分布,限制了数据库的可扩展性。
  304. - 迁移和备份困难:带有外键约束的数据库迁移或备份可能会变得更加复杂。迁移时需要保证数据的完整性和约束的一致性,这可能会增加迁移的难度和时间。
  305. - 业务逻辑耦合:过多依赖数据库的外键约束可能会导致业务逻辑过度耦合于数据库层。这可能会限制应用程序的灵活性和后期的业务逻辑调整。
  306. - 并发操作问题:在高并发的场景下,外键约束可能会导致锁的竞争,增加死锁的风险,影响系统的稳定性和响应速度。
  307. 尽管外键提供了数据完整性保障,但在某些场景下,特别是在高性能和高可扩展性要求的系统中,可能会选择在应用层实现相应的完整性检查和约束逻辑,以避免上述问题。这需要在设计系统时根据实际需求和环境来权衡利弊,做出合适的决策。
  308. ## 多表关联查询
  309. cool-admin 有三种方式的联表查询:
  310. 1、controller 上配置
  311. 特别注意要配置 select, 不然会报重复字段错误
  312. ```ts
  313. @CoolController({
  314. // 添加通用CRUD接口
  315. api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  316. // 设置表实体
  317. entity: DemoAppGoodsEntity,
  318. // 分页查询配置
  319. pageQueryOp: {
  320. // 指定返回字段,注意多表查询这个是必要的,否则会出现重复字段的问题
  321. select: ['a.*', 'b.name', 'a.name AS userName'],
  322. // 联表查询
  323. join: [
  324. {
  325. entity: BaseSysUserEntity,
  326. alias: 'b',
  327. condition: 'a.userId = b.id'
  328. },
  329. ]
  330. })
  331. ```
  332. 2、service 中
  333. 通过`this.nativeQuery`或者`this.sqlRenderPage`两种方法执行自定义 sql
  334. - nativeQuery:执行原生 sql,返回数组
  335. - sqlRenderPage:执行原生 sql,返回分页对象
  336. 模板 sql 示例,方便动态传入参数,千万不要直接拼接 sql,有 sql 注入风险,以下方法 cool-admin 内部已经做了防注入处理
  337. - setSql:第一个参数是条件,第二个参数是 sql,第三个参数是参数数组
  338. ```ts
  339. this.nativeQuery(
  340. `SELECT
  341. a.*,
  342. b.nickName
  343. FROM
  344. demo_goods a
  345. LEFT JOIN user_info b ON a.userId = b.id
  346. ${this.setSql(true, 'and b.userId = ?', [userId])}`
  347. ```
  348. 3、通过 typeorm 原生的写法
  349. 示例
  350. ```ts
  351. const find = this.demoGoodsEntity
  352. .createQueryBuilder("a")
  353. .select(["a.*", "b.nickName as userName"])
  354. .leftJoin(UserInfoEntity, "b", "a.id = b.id")
  355. .getRawMany();
  356. ```
  357. ## 配置字典和可选项(8.x 新增)
  358. 为了让前端可能自动识别某个字段的可选项或者属于哪个字典,我们可以在@Column 注解上配置`options`和`dict`属性,
  359. 旧的写法
  360. ```ts
  361. // 无法指定字典
  362. // 可选项只能按照一定规则编写,否则前端无法识别
  363. @Column({ comment: '状态 0-禁用 1-启用', default: 1 })
  364. status: number;
  365. ```
  366. 新的写法
  367. ```ts
  368. // 指定字典为goodsType,这样前端生成的时候就会默认指定这个字典
  369. @Column({ comment: '分类', dict: 'goodsType' })
  370. type: number;
  371. // 状态的可选项有禁用和启用,默认是启用,值是数组的下标,0-禁用,1-启用
  372. @Column({ comment: '状态', dict: ['禁用', '启用'], default: 1 })
  373. status: number;
  374. ```