数据库

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

CI Test Coverage Audit

安装

npm i @sumor/database --save

先决条件

Node.JS 版本

要求 Node.JS 版本为 18.x 或以上

需要 Node.JS ES 模块

由于此软件包是用 ES 模块编写的, 请在您的 package.json 文件中更改以下代码:

{
  "type": "module"
}

用法

通用用法

import database from '@sumor/database'

const config = {
  host: 'localhost',
  user: 'root',
  password: '密码',
  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('测试用户')

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

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

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

// 计算记录数量
const count = await db.count('Car', {
  brand: '宝马'
})
// count = 2

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

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

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

// 删除记录
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: '宝马'
  },
  {
    term: 'X5',
    termRange: ['model'],
    top: 10,
    skip: 0
  }
)

实体定义选项

索引

您可以在实体定义中添加索引数组以在表上创建索引,默认情况下会在id字段上创建索引。

连接

您可以在实体定义中添加连接对象以在表上创建连接。 例如下面的示例,将在 Car 实体中创建 userId 字段。

import database from '@sumor/database'

const config = {
  host: 'localhost',
  user: 'root',
  password: '密码',
  database: '数据库',
  port: 3306
}

await database.install(config, {
  entity: {
    Car: {
      property: {
        brand: {
          type: 'string',
          length: 100
        },
        model: {
          type: 'string',
          length: 100
        }
      },
      index: ['userId'],
      join: {
        user: 'User'
      }
    }
  },
  view: {}
})