|
3 | 3 | [](LICENSE) |
4 | 4 | [](https://www.npmjs.org/package/coa-mysql) |
5 | 5 | [](http://npm-stat.com/charts.html?package=coa-mysql) |
6 | | -[](https://github.com/coajs/coa-mysql/pulls) |
| 6 | +[](https://github.com/coajs/coa-mysql/pulls) |
| 7 | + |
| 8 | +COA核心MySQL数据库组件,包含基本数据模型、缓存数据模型、分布式ID等 |
| 9 | + |
| 10 | +## 特点 |
| 11 | + |
| 12 | +- **功能齐全** 基础数据连接基于[mysql](https://github.com/mysqljs/mysql),SQL查询基于[knex](https://github.com/knex/knex)库,注重性能,功能齐全包含原生库所有使用方式 |
| 13 | +- **简单轻量** 不超过1000行代码,不依赖于其他第三方库 |
| 14 | +- **快捷方便** 基本数据模型自带CRUD操作,无需额外代码 |
| 15 | +- **自动缓存** 缓存数据模型能自动处理数据缓存、数据淘汰逻辑,缓存基于[coa-redis](https://github.com/coajs/coa-redis) |
| 16 | +- **TypeScript** 全部使用TypeScript书写,类型约束、IDE友好 |
| 17 | + |
| 18 | +## 组件 |
| 19 | + |
| 20 | +- 基本数据模型 `MysqlCache` 自动实现基本的CRUD等操作 |
| 21 | +- 缓存数据模型 `MysqlNative` 在基本数据模型上自动处理数据缓存机制 |
| 22 | +- 分布式ID `MysqlUuid` 超轻量的分布式UUID |
| 23 | + |
| 24 | +## 快速开始 |
| 25 | + |
| 26 | +### 安装 |
| 27 | + |
| 28 | +```shell |
| 29 | +yarn add coa-mysql |
| 30 | +``` |
| 31 | + |
| 32 | +### 实例配置 |
| 33 | + |
| 34 | +```typescript |
| 35 | +import { MysqlBin } from '..' |
| 36 | + |
| 37 | +// MySQL配置 |
| 38 | +const mysqlConfig = { |
| 39 | + host: '127.0.0.1', |
| 40 | + port: 3306, |
| 41 | + user: 'root', |
| 42 | + password: 'root', |
| 43 | + charset: 'utf8mb4', |
| 44 | + trace: true, |
| 45 | + debug: false, |
| 46 | + databases: { |
| 47 | + main: { database: 'test', ms: 7 * 24 * 3600 * 1000 }, |
| 48 | + other: { database: 'other', ms: 7 * 24 * 3600 * 1000 } |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +// 初始化Mysql基本连接,后续所有模型均依赖此实例 |
| 53 | +const mysqlBin = new MysqlBin(mysqlConfig) |
| 54 | +``` |
| 55 | + |
| 56 | +### 基本SQL查询 |
| 57 | + |
| 58 | +现在用户表`user`,表结构如下 |
| 59 | + |
| 60 | +```shell |
| 61 | +CREATE TABLE `user` ( |
| 62 | + `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增长主键', |
| 63 | + `userId` varchar(32) NOT NULL DEFAULT '' COMMENT '用户ID', |
| 64 | + `name` varchar(64) NOT NULL DEFAULT '' COMMENT '姓名', |
| 65 | + `mobile` varchar(16) NOT NULL DEFAULT '' COMMENT '手机号', |
| 66 | + `avatar` varchar(256) NOT NULL DEFAULT '' COMMENT '头像', |
| 67 | + `gender` int(11) NOT NULL DEFAULT '0' COMMENT '性别,1男 2女', |
| 68 | + `language` varchar(16) NOT NULL DEFAULT '' COMMENT '语言', |
| 69 | + `status` int(1) NOT NULL DEFAULT '1' COMMENT '状态,1正常 2隐藏', |
| 70 | + `created` bigint(20) NOT NULL DEFAULT '0' COMMENT '创建时间', |
| 71 | + `updated` bigint(20) NOT NULL DEFAULT '0' COMMENT '更新时间', |
| 72 | + PRIMARY KEY (`id`) USING BTREE, |
| 73 | + UNIQUE KEY `user_userid_unique` (`userId`) USING BTREE |
| 74 | +) COMMENT='用户表'; |
| 75 | +``` |
| 76 | + |
| 77 | +对用户表进行SQL操作 |
| 78 | + |
| 79 | +```typescript |
| 80 | +// 插入数据 https://knexjs.org/#Builder-insert |
| 81 | +mysqlBin.io.table('user').insert({ userId: 'user-a', name: 'A', mobile: '15010001001', gender: 1, language: 'zh-CN', status: 1 }) |
| 82 | + |
| 83 | +// 查询全部数据,详见 https://knexjs.org/#Builder-select |
| 84 | +mysqlBin.io.table('user').select() |
| 85 | +mysqlBin.io.select('*').from('user') |
| 86 | + |
| 87 | +// 带条件查询,详见 https://knexjs.org/#Builder-where |
| 88 | +mysqlBin.io.table('user').where('status', '=', 1) |
| 89 | + |
| 90 | +// 修改数据,详见 http://knexjs.org/#Builder-update |
| 91 | +mysqlBin.io.table('user').update({ name: 'AA', gender: 2 }).where({ userId: 'user-a' }) |
| 92 | + |
| 93 | +// 删除数据,详见 http://knexjs.org/#Builder-del%20/%20delete |
| 94 | +mysqlBin.io.table('user').delete().where({ userId: 'user-a' }) |
| 95 | +``` |
| 96 | + |
| 97 | +其中`io`是一个`Knex`对象,可以支持 [Knex.js](http://knexjs.org/#Builder) 的**全部**用法 |
| 98 | + |
| 99 | +### 基本数据模型 |
| 100 | + |
| 101 | +在实际项目工程中,为了保证查询的高效、严谨,我们并不会直接操作SQL语句。基本的数据模块可以帮助我们实现CURD操作。 通过如下方式定义一个基本数据模型`User` |
| 102 | + |
| 103 | +```typescript |
| 104 | +import { MysqlBin, MysqlNative } from 'coa-mysql' |
| 105 | + |
| 106 | +// 定义User默认结构 |
| 107 | +const userScheme = { |
| 108 | + userId: '' as string, |
| 109 | + name: '' as string, |
| 110 | + mobile: '' as string, |
| 111 | + avatar: '' as string, |
| 112 | + gender: 1 as number, |
| 113 | + language: '' as string, |
| 114 | + status: 1 as number, |
| 115 | + created: 0 as number, |
| 116 | + updated: 0 as number, |
| 117 | +} |
| 118 | +// 定义User类型(通过默认结构自动生成) |
| 119 | +type UserScheme = typeof userScheme |
| 120 | + |
| 121 | +// 通过基类初始化 |
| 122 | +const User = new class extends MysqlNative<UserScheme> { |
| 123 | + constructor () { |
| 124 | + super({ |
| 125 | + name: 'User', // 表名,默认会转化为下划线(snackCase)形式,如 User->user UserPhoto->user_photo |
| 126 | + title: '用户表', // 表的备注名称 |
| 127 | + scheme: userScheme, // 表的默认结构 |
| 128 | + pick: ['userId', 'name'] // 查询列表时显示的字段信息 |
| 129 | + }, mysqlBin) // 绑定配置实例bin |
| 130 | + } |
| 131 | + |
| 132 | + // 自定义方法 |
| 133 | + async customMethod () { |
| 134 | + // 做一些事情 |
| 135 | + } |
| 136 | +} |
| 137 | +``` |
| 138 | + |
| 139 | +一般一个数据表对应一个模型,定义模型后,我们直接操作模型就可以对表进行操作 |
| 140 | + |
| 141 | +```typescript |
| 142 | +// 插入 |
| 143 | +await User.insert({ name: '王小明', gender: 1 }) // 返回 'id001',即该条数据的 userId = 'id001' |
| 144 | + |
| 145 | +// 批量插入 |
| 146 | +await User.mInsert([{ name: '王小明', gender: 1 }, { name: '宋小华', gender: 1 }]) // 返回 ['id002','id003'] |
| 147 | + |
| 148 | +// 通过ID更新 |
| 149 | +await User.updateById('id002', { name: '李四' }) // 返回 1 |
| 150 | + |
| 151 | +// 通过ID批量更新 |
| 152 | +await User.updateByIds(['id002', 'id003'], { status: 2 }) // 返回 2 |
| 153 | + |
| 154 | +// 通过ID更新或插入(如果id存在就更新,如果不存在就插入) |
| 155 | +await User.upsertById('id002', { name: '王小明', gender: 1 }) // 返回 1 ,更新了一条 userId = 'id02' 的数据 |
| 156 | +await User.upsertById('id004', { name: '李四', gender: 1 }) // 返回 0 ,插入一条新数据,数据的 userId = 'id04' |
| 157 | + |
| 158 | +// 通过ID删除多个 |
| 159 | +await User.deleteByIds(['id003', 'id004']) // 返回 2 |
| 160 | + |
| 161 | +// 通过ID查询一个,第二个参数设置返回结果所包含的数据 |
| 162 | +await User.getById('id001', ['name']) // 数据为{userId:'id001',name:'王小明',gender:1,status:1,...} 实际返回 {userId:'id001',name:'王小明'} |
| 163 | + |
| 164 | +// 通过ID获取多个 |
| 165 | +await User.mGetByIds(['id001', 'id002'], ['name']) //返回 {id001:{userId:'id001',name:'王小明'},id002:{userId:'id002',name:'李四'}} |
| 166 | + |
| 167 | +// 截断表 |
| 168 | +await User.truncate() // 无返回值,不报错即成功截断整个表 |
| 169 | + |
| 170 | +// 自定义方法 |
| 171 | +await User.customMethod() // 执行自定义方法 |
| 172 | +``` |
| 173 | + |
| 174 | +实际项目中,我们可能需要定义多个模型,每个模型上都有一些公共方法。这时,我们可以抽象一个基类模型,其他模型继承这个基类模型 |
| 175 | + |
| 176 | +```typescript |
| 177 | +import { CoaMysql } from 'coa-mysql' |
| 178 | + |
| 179 | +// 通过mysqlBin定义一个模型的基类,各个模型都可以使用这个基类 |
| 180 | +export class MysqlNativeModel<T> extends MysqlNative<T> { |
| 181 | + |
| 182 | + constructor (option: CoaMysql.ModelOption<T>) { |
| 183 | + // 将实例配置bin绑定 |
| 184 | + super(option, mysqlBin) |
| 185 | + } |
| 186 | + |
| 187 | + // 也可以定义一些通用方法 |
| 188 | + commonMethod () { |
| 189 | + // do something |
| 190 | + } |
| 191 | +} |
| 192 | + |
| 193 | +// 通过基类模型定义用户模型 |
| 194 | +const User = new class extends MysqlNativeModel<UserScheme> { |
| 195 | + constructor () { |
| 196 | + super({ name: 'User', title: '用户表', scheme: userScheme, pick: ['userId', 'name'] }) |
| 197 | + } |
| 198 | + |
| 199 | + // 自定义方法 |
| 200 | + async customMethodForUser () { |
| 201 | + // 做一些事情 |
| 202 | + } |
| 203 | +} |
| 204 | + |
| 205 | +// 通过基类模型定义管理员模型 |
| 206 | +const Manager = new class extends MysqlNativeModel<UserScheme> { |
| 207 | + constructor () { |
| 208 | + super({ name: 'Manager', title: '管理员表', scheme: userScheme, pick: ['userId', 'name'] }) |
| 209 | + } |
| 210 | +} |
| 211 | + |
| 212 | +// 用户模型和管理员模型均可以调用公共方法 |
| 213 | +await User.commonMethod() |
| 214 | +await Manager.commonMethod() |
| 215 | + |
| 216 | +// 仅仅用户模型可以调用自定义方法 |
| 217 | +await User.customMethodForUser() |
| 218 | +``` |
| 219 | + |
| 220 | +### 缓存数据模型 |
| 221 | + |
| 222 | +缓存数据模型基于 [coa-redis](https://www.npmjs.com/package/coa-redis) 实现快速高效的数据缓存,并**统一对缓存进行管理、维护缓存的生命周期、保证缓存与MySQL数据的一致性** |
| 223 | + |
| 224 | +使用之前需安装 `coa-redis` ,使用方法可查看 [这里](https://github.com/coajs/coa-redis) |
| 225 | + |
| 226 | +缓存数据模型的使用方法和基本数据模型完全相同,仅需要将 `MysqlNative` 替换为 `MysqlCache` |
| 227 | + |
| 228 | +```typescript |
| 229 | +import { CoaMysql, MysqlCache } from 'coa-mysql' |
| 230 | +import { RedisBin, RedisCache } from 'coa-redis' |
| 231 | + |
| 232 | +// 定义一个redis实例,详细用法详见 https://github.com/coajs/coa-redis |
| 233 | +const redisCache = new RedisCache(new RedisBin({ host: '127.0.0.1' })) |
| 234 | + |
| 235 | +// 定义一个缓存数据模型的基类 |
| 236 | +export class MysqlCacheModel<T> extends MysqlCache<T> { |
| 237 | + constructor (option: CoaMysql.ModelOption<T>) { |
| 238 | + // 将配置实例 和 redisCache实例 都绑定到这个基类上 |
| 239 | + super(option, mysqlBin, redisCache) |
| 240 | + } |
| 241 | +} |
| 242 | + |
| 243 | +// 通过缓存基类模型定义缓存用户模型 |
| 244 | +const UserCached = new class extends MysqlCacheModel<UserScheme> { |
| 245 | + constructor () { |
| 246 | + super({ name: 'User', title: '用户表', scheme: userScheme, pick: ['userId', 'name'] }) |
| 247 | + } |
| 248 | +} |
| 249 | + |
| 250 | +// 查询数据 |
| 251 | +await User.getById('id001') // 首次查询会先读取数据库 |
| 252 | +await User.getById('id001') // 第二次调用会直接从缓存中读取数据 |
| 253 | + |
| 254 | +// 增删改操作和基本数据模型一直 |
| 255 | +await User.insert({ name: '王小明', gender: 1 }) // 返回 'id001' |
| 256 | +await User.updateById('id001', { name: '李四' }) // 返回 1 |
| 257 | +``` |
| 258 | +缓存模型会自动维护和管理缓存,如果缓存已经存在,接下来又调用update更新了数据,再次查询数据时自动从数据库中取出最新的数据。 实现原理可点击 这里(todo) 了解更多 |
0 commit comments