数据库

一个 Sumor Cloud 工具。
更多文档
一个用于 MySQL 等数据库的数据库连接器,基于实体。

CI
Test
Coverage
Audit

安装

npm i @sumor/database --save

先决条件

Node.JS 版本

要求 Node.JS 版本 16.x 或以上

需要 Node.JS 的 ES 模块

由于该软件包使用 ES 模块编写,请在您的 package.json 文件中做如下更改:

{
  "type": "module"
}

使用方法

通用用法

import database from '@sumor/database'

const config = {
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'database',
  port: 3306
}

await database.install(config, {
  entity: {
    Car: {
      property: {
        brand: {
          type: 'string',
          length: 100
        },
        model: {
          type: 'string',
          length: 100
        }
      }
    }
  },
  view: {}
})

// 获取带连接池的客户端
const client = await database.client(config)

// 获取连接
const db = await client.connect()

// 设置操作用户
db.setUser('tester')

// 创建记录
const car1Id = await db.insert('Car', {
  brand: 'BMW',
  model: 'X5'
})
const car2Id = await db.insert('Car', {
  brand: 'BMW',
  model: 'X6'
})

// 读取记录
const car = await db.single('Car', { id: carId })
// car = {id: car1Id, brand: 'BMW', model: 'X5'}

// 查询记录
const cars = await db.query('Car', {
  brand: 'BMW'
})
// cars = [{id: car1Id, brand: 'BMW', model: 'X5'}, {id: car2Id, brand: 'BMW', model: 'X6'}]

// 统计记录数
const count = await db.count('Car', {
  brand: 'BMW'
})
// count = 2

// 更新记录
await db.update(
  'Car',
  { id: car1Id },
  {
    brand: 'BMW',
    model: 'X5M'
  }
)

// 确认记录
await db.ensure('Car', ['brand'], {
  brand: 'BMW',
  model: 'X5C'
})
// 如果'BMW'的品牌已经存在,则不会插入记录

// 修改记录
await db.modify('Car', ['brand'], {
  brand: 'BMW',
  model: 'X5C'
})
// 如果'BMW'的品牌已经存在,则会更新记录的型号

// 删除记录
await db.delete('Car', { id: car1Id })

// 提交更改
await db.commit()

// 回滚
await db.rollback()

// 关闭连接
await db.release()

// 当服务器应关闭时销毁客户端
await client.destroy()

查询选项

// 带选项查询记录
const cars = await db.select(
  'Car',
  {
    brand: 'BMW'
  },
  {
    term: 'X5',
    termRange: ['model'],
    top: 10,
    skip: 0
  }
)