MeWrite Docs

SequelizeDatabaseError: relation does not exist

Sequelizeでマイグレーションやテーブル関連のエラーが発生した場合の対処法

概要

Sequelizeでテーブルが存在しない、またはマイグレーションに問題がある場合に発生するエラーです。

エラーメッセージ

SequelizeDatabaseError: relation "users" does not exist
SequelizeDatabaseError: column "email" of relation "users" does not exist
ERROR: Migrations are pending. Run `sequelize db:migrate`

解決策

1. マイグレーションを実行

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# マイグレーションを実行
npx sequelize-cli db:migrate

# 状態を確認
npx sequelize-cli db:migrate:status

# ロールバック
npx sequelize-cli db:migrate:undo

# 全てロールバック
npx sequelize-cli db:migrate:undo:all

2. マイグレーションファイルの作成

1
2
# マイグレーションを生成
npx sequelize-cli migration:generate --name create-users
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// migrations/20250122000000-create-users.js
'use strict'

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('users', {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      email: {
        type: Sequelize.STRING,
        allowNull: false,
        unique: true,
      },
      name: {
        type: Sequelize.STRING,
      },
      createdAt: {
        type: Sequelize.DATE,
        allowNull: false,
      },
      updatedAt: {
        type: Sequelize.DATE,
        allowNull: false,
      },
    })
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.dropTable('users')
  },
}

3. モデルとマイグレーションの同期

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// モデル定義
// models/user.js
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
    },
    name: DataTypes.STRING,
  }, {
    tableName: 'users',  // テーブル名を明示
  })

  return User
}

4. 開発環境での自動同期

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// 開発時のみ使用(本番では非推奨)
const sequelize = new Sequelize(/* config */)

// テーブルを作成(存在しない場合)
await sequelize.sync()

// テーブルを再作成(データ削除)
await sequelize.sync({ force: true })

// 差分を適用
await sequelize.sync({ alter: true })

5. カラムの追加/変更

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// migrations/20250122000001-add-role-to-users.js
module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.addColumn('users', 'role', {
      type: Sequelize.ENUM('admin', 'user'),
      defaultValue: 'user',
    })
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.removeColumn('users', 'role')
    // ENUMを削除する場合
    await queryInterface.sequelize.query('DROP TYPE IF EXISTS "enum_users_role";')
  },
}

6. 設定ファイルの確認

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// config/config.js
module.exports = {
  development: {
    username: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    host: process.env.DB_HOST,
    dialect: 'postgres',
  },
  production: {
    use_env_variable: 'DATABASE_URL',
    dialect: 'postgres',
    dialectOptions: {
      ssl: {
        require: true,
        rejectUnauthorized: false,
      },
    },
  },
}

7. シーダーの実行

1
2
3
4
5
# シーダーを実行
npx sequelize-cli db:seed:all

# シーダーを元に戻す
npx sequelize-cli db:seed:undo:all

8. トランザクションを使用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
module.exports = {
  async up(queryInterface, Sequelize) {
    const transaction = await queryInterface.sequelize.transaction()

    try {
      await queryInterface.createTable('posts', { /* ... */ }, { transaction })
      await queryInterface.addIndex('posts', ['userId'], { transaction })
      await transaction.commit()
    } catch (error) {
      await transaction.rollback()
      throw error
    }
  },
}

デバッグ

1
2
3
4
5
6
7
8
// SQLログを有効化
const sequelize = new Sequelize({
  // ...
  logging: console.log,  // または logging: (sql) => logger.debug(sql)
})

// マイグレーションテーブルを確認
// SELECT * FROM "SequelizeMeta";

関連エラー

関連エラー

最終更新: 2025-12-22