データベース

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: '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が既に存在する場合はレコードを挿入しません

// レコードを変更
await db.modify('Car', ['brand'], {
  brand: 'BMW',
  model: 'X5C'
})
// brandが既に存在する場合はレコードの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
  }
)

エンティティ定義オプション

インデックス

エンティティ定義にインデックス配列を追加して、テーブルにインデックスを作成できます。デフォルトではidフィールドにインデックスが作成されます。

結合

エンティティ定義に結合オブジェクトを追加して、テーブルに結合を作成できます。
以下の例のように、CarエンティティにuserIdフィールドを作成します。

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
        }
      },
      index: ['userId'],
      join: {
        user: 'User'
      }
    }
  },
  view: {}
})