コンテンツにスキップ
Sutando
Esc
↑↓移動↵開く⌘Jプレビュー

Sutando でデータベースマイグレーション:完全ガイド

データベーススキーマの管理は、アプリケーション開発において重要な要素です。Sutando のスキーマビルダーとマイグレーション機能を使って、バージョン管理可能なスキーマ管理を実現しましょう。

データベーススキーマの管理は、アプリケーション開発において重要な要素です。Sutando のスキーマビルダーとマイグレーション機能を使って、バージョン管理可能なスキーマ管理を実現しましょう。

スキーマビルダーの基本

Sutando のスキーマビルダーは、Knex.js の上に構築されており、データベースに依存しないスキーマ操作を提供します。

テーブルの作成

import { sutando } from 'sutando';

await sutando.schema().createTable('users', table => {
  table.increments('id').primary();
  table.string('name').notNullable();
  table.string('email').notNullable().unique();
  table.string('password');
  table.boolean('is_admin').defaultTo(false);
  table.timestamps();
});

カラムタイプ

await sutando.schema().createTable('posts', table => {
  table.increments('id').primary();
  table.string('title', 200).notNullable();
  table.text('content');
  table.integer('user_id').unsigned().references('id').inTable('users');
  table.boolean('published').defaultTo(false);
  table.json('metadata');
  table.timestamp('published_at').nullable();
  table.timestamps();
});

テーブルの変更

await sutando.schema().alterTable('users', table => {
  table.string('avatar').nullable();
  table.dropColumn('password');
  table.renameColumn('name', 'display_name');
});

テーブルの削除

await sutando.schema().dropTableIfExists('old_table');

マイグレーションファイル

Sutando では、マイグレーションをファイルとして管理できます:

// migrations/001_create_users_table.js
const { Migration } = require('sutando');

module.exports = class extends Migration {
  async up(schema) {
    await schema.createTable('users', table => {
      table.increments('id').primary();
      table.string('name').notNullable();
      table.string('email').notNullable().unique();
      table.timestamps();
    });
  }

  async down(schema) {
    await schema.dropTableIfExists('users');
  }
};
// migrations/002_create_posts_table.js
const { Migration } = require('sutando');

module.exports = class extends Migration {
  async up(schema) {
    await schema.createTable('posts', table => {
      table.increments('id').primary();
      table.string('title').notNullable();
      table.text('content');
      table.integer('user_id').unsigned().references('id').inTable('users');
      table.boolean('published').defaultTo(false);
      table.timestamps();
    });
  }

  async down(schema) {
    await schema.dropTableIfExists('posts');
  }
};

インデックス

await sutando.schema().alterTable('posts', table => {
  table.index(['user_id', 'published'], 'posts_user_published_index');
});

外部キー

await sutando.schema().createTable('comments', table => {
  table.increments('id').primary();
  table.text('content').notNullable();
  table.integer('post_id').unsigned()
    .references('id').inTable('posts')
    .onDelete('CASCADE');
  table.integer('user_id').unsigned()
    .references('id').inTable('users');
  table.timestamps();
});

まとめ

Sutando のスキーマビルダーを使えば、データベースに依存しないマイグレーションを簡単に作成できます。バージョン管理とロールバック機能で、チーム開発でも安全にスキーマを管理できます。

ドキュメント でさらに詳しく。

このページは役に立ちましたか?