'use strict'; const helpers = require('../app/migration_helpers'); exports.up = function(knex, Promise) { const dbType = helpers.getDbType(knex); // Defer has the promise resulting from creating the initial tables let defer = knex.schema.createTableIfNotExists('users', (table) => { table.comment('User authentication table'); table.increments() .unsigned(); table.string('user'); table.binary('password_hash'); table.timestamp('created_at') .defaultTo(knex.fn.now()); table.timestamp('updated_at') .defaultTo(knex.fn.now()); }).then(() => { return knex.schema.createTableIfNotExists('posts', (table) => { table.comment('Blog post table'); table.increments() .unsigned(); table.integer('created_by') .unsigned() .references('users.id'); table.string('uri') .index() .comment('The uri segment of the blog post'); table.string('title') .comment('The title of the blog post'); table.text('content') .comment('The content of the blog post'); table.timestamp('created_at') .defaultTo(knex.fn.now()); table.timestamp('updated_at') .defaultTo(knex.fn.now()); }); }); if ('pg' === dbType) { // Create the function to update return knex.schema.raw(helpers.pgTimestampUpdateFunction()) // Create the tables .then(() => defer) // Add trigger for tables .then(() => knex.schema.raw(helpers.pgCreateTimestampUpdateTrigger('users'))) .then(() => knex.schema.raw(helpers.pgCreateTimestampUpdateTrigger('posts'))); } else if ('sqlite3' === dbType) { return defer.then(() => knex.schema.raw(helpers.sqlite3CreateTimestampUpdateTrigger('users'))) .then(() => knex.schema.raw(helpers.sqlite3CreateTimestampUpdateTrigger('posts'))); } else { return defer; } }; exports.down = function(knex, Promise) { const dbType = helpers.getDbType(knex); let defer = knex.schema.dropTableIfExists('posts') .then(() => knex.schema.dropTableIfExists('users')); if ('pg' === dbType) { return knex.schema.raw(helpers.pgDeleteTimestampUpdateTrigger('users')) .then(() => knex.schema.raw(helpers.pgDeleteTimestampUpdateTrigger('posts'))) .then(() => defer); } else if ('sqlite3' === dbType) { return knex.schema.raw(helpers.sqlite3DeleteTimestampUpdateTrigger('users')) .then(() => knex.schema.raw(helpers.sqlite3DeleteTimestampUpdateTrigger('posts'))) .then(() => defer); } else { return defer; } };