exports.up = async function(knex) { await knex.schema.createTable('relations_types', (table) => { table.text('type') .primary(); // symmetric relations have no direction, e.g. wet and dry variants of each other, stored with the lowest scene ID as the source table.boolean('symmetric') .notNullable() .defaultTo(false); }); await knex('relations_types').insert([ { type: 'rerelease' }, { type: 'remaster' }, { type: 'compilation' }, { type: 'bts' }, // behind the scenes { type: 'variant', symmetric: true }, ]); await knex.schema.createTable('scenes_relations', (table) => { table.increments('id'); // the derivation or compilation table.integer('source_scene_id') .notNullable() .references('id') .inTable('releases') .onDelete('cascade'); // the original or compilation part table.integer('target_scene_id') .notNullable() .references('id') .inTable('releases') .onDelete('cascade'); table.text('type') .notNullable() .references('type') .inTable('relations_types') .onUpdate('cascade'); table.integer('created_by') .references('id') .inTable('users') .onDelete('set null'); table.datetime('created_at') .notNullable() .defaultTo(knex.fn.now()); table.unique(['source_scene_id', 'target_scene_id', 'type']); table.index('target_scene_id'); // the unique index only covers lookups from the source side }); await knex.raw(` ALTER TABLE scenes_relations ADD CONSTRAINT scenes_relations_not_self CHECK (source_scene_id <> target_scene_id) `); // other scenes changed by a revision, e.g. the related scene when a relation is added or removed, so it shows in their history too await knex.schema.alterTable('scenes_revisions', (table) => { table.specificType('affected_scene_ids', 'integer[]') .notNullable() .defaultTo('{}'); table.index('affected_scene_ids', null, 'gin'); }); }; exports.down = async function(knex) { await knex.schema.alterTable('scenes_revisions', (table) => { table.dropColumn('affected_scene_ids'); }); await knex.schema.dropTable('scenes_relations'); await knex.schema.dropTable('relations_types'); };