'use strict'; module.exports = { async up(queryInterface, Sequelize) { await queryInterface.createTable('course_instructors', { id: { type: Sequelize.BIGINT, primaryKey: true, autoIncrement: true }, course_id: { type: Sequelize.BIGINT, allowNull: false, references: { model: 'courses', key: 'course_id' }, onDelete: 'CASCADE' }, user_id: { type: Sequelize.BIGINT, allowNull: true, references: { model: 'users', key: 'user_id' }, onDelete: 'CASCADE' }, order_index: { type: Sequelize.BIGINT, allowNull: false, defaultValue: 0 }, display_name: { type: Sequelize.STRING(255), allowNull: false, defaultValue: '' }, created_by: { type: Sequelize.BIGINT, allowNull: true }, created_at: { type: Sequelize.DATE, allowNull: false, defaultValue: Sequelize.NOW }, updated_at: { type: Sequelize.DATE, allowNull: false, defaultValue: Sequelize.NOW }, }); await queryInterface.addConstraint('course_instructors', { fields: ['course_id', 'user_id'], type: 'unique', name: 'course_instructors_course_id_user_id_key', }); await queryInterface.addIndex('course_instructors', ['course_id'], { name: 'idx_course_instructors_course' }); // Partial unique index — same columns as the constraint above, scoped to // non-null user_id. Raw SQL since queryInterface addIndex's `where` // support is unreliable for IS NOT NULL across dialects. await queryInterface.sequelize.query(` CREATE UNIQUE INDEX idx_course_instructors_user ON course_instructors (course_id, user_id) WHERE user_id IS NOT NULL; `); }, async down(queryInterface) { await queryInterface.dropTable('course_instructors'); }, };