データベース

Sumor Cloud ツール。
さらなるドキュメント MySQL などのデータベース コネクタ。Entity ベース。

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'
})
// brand が 'BMW' で既に存在する場合は、レコードを挿入しません

// レコードを修正
await db.modify('Car', ['brand'], {
  brand: 'BMW',
  model: 'X5C'
})
// brand が 'BMW' で既に存在する場合は、レコードの model を更新します

// レコードを削除
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
  }
)