Skip to content

迁移指南

从 @dpapejs/emysql 迁移到 @aicblock/emysql

1. 库名变更

首先,您需要将项目中的依赖从 @dpapejs/emysql 更改为 @aicblock/emysql

sh
# 使用 npm
npm uninstall @dpapejs/emysql
npm install @aicblock/emysql@latest -S

# 使用 yarn
yarn remove @dpapejs/emysql
yarn add @aicblock/emysql@latest -S

然后,更新所有导入语句:

diff
- import emysql from '@dpapejs/emysql'
+ import emysql from '@aicblock/emysql'

从 V1.2.x 迁移到 V1.3.x

1. table.create 方法的重大变化

在 V1.3.x 版本中,table.create 方法的参数类型发生了重大变化。现在它不再直接接受表配置对象,而是接受 DefineTableResultDefineTableResult[] 类型的参数。

旧版本 (V1.2.x) 用法:

ts
// 直接传递表配置对象
mysql.table
  .create([
    {
      tableName: 't_user',
      columns: [
        {
          name: 'id',
          primaryKey: true,
          autoIncrement: true,
          dataType: 'INT',
          comments: '主键'
        },
        // 其他字段...
      ]
    }
  ])

新版本 (V1.3.x) 用法:

ts
import emysql, { DefineTable } from '@aicblock/emysql'

// 1. 首先使用 DefineTable 函数定义表结构
const userTable = DefineTable({
  tableName: 't_user',
  columns: [
    {
      name: 'id',
      primaryKey: true,
      autoIncrement: true,
      dataType: 'INT',
      comments: '主键'
    },
    // 其他字段...
  ]
})

// 2. 然后将 DefineTable 返回的结果传递给 table.create
mysql.table
  .create([userTable])

2. DefineTable 函数的使用

DefineTable 函数是 V1.3.x 版本中新增的,用于定义表结构并生成创建表的 SQL 语句。它接受与旧版本 table.create 相同的表配置对象,并返回一个包含表名、创建 SQL 和字段列表的对象。

使用示例:

ts
import emysql, { DefineTable } from '@aicblock/emysql'

// 定义单个表
const userTable = DefineTable({
  tableName: 't_user',
  columns: [
    {
      name: 'id',
      primaryKey: true,
      autoIncrement: true,
      dataType: 'INT',
      comments: '主键'
    },
    {
      name: 'username',
      dataType: 'VARCHAR',
      length: 255,
      notNull: true,
      unique: true,
      comments: '用户名'
    },
    // 更多字段...
  ],
  engine: 'InnoDB',
  charset: 'utf8mb4',
  collate: 'utf8mb4_0900_bin'
})

// 定义多个表
const orderTable = DefineTable({
  tableName: 't_order',
  columns: [
    {
      name: 'id',
      primaryKey: true,
      autoIncrement: true,
      dataType: 'INT',
      comments: '主键'
    },
    {
      name: 'user_id',
      dataType: 'INT',
      notNull: true,
      comments: '用户ID'
    },
    // 更多字段...
  ]
})

// 创建表
mysql.table.create([userTable, orderTable])
  .then(() => {
    console.log('表创建成功')
  })
  .catch((error) => {
    console.error('表创建失败:', error)
  })

3. 其他注意事项

  • 除了 table.create 方法外,其他方法的使用方式保持不变
  • 类型定义也进行了相应的更新,确保与新的 API 兼容
  • 建议您在迁移过程中仔细检查代码,确保所有 table.create 调用都已更新为新的用法

总结

迁移到 V1.3.x 版本主要涉及两个方面:

  1. 将依赖从 @dpapejs/emysql 更改为 @aicblock/emysql
  2. 更新 table.create 方法的使用方式,使用 DefineTable 函数先定义表结构

这些变化提高了代码的类型安全性和可维护性,同时保持了与旧版本的向后兼容性(除了 table.create 方法)。