Advanced Tutorial: Creating a new database table
In this tutorial, we will go over how to create a new table in our database by creating a new migration. To illustrate this, we are creating a plugin that allows users to add their twitter usernames. The requirements will be stored in a newly created table
Twitters
in the DB. This table will be created by a migration using the umzug
library.We DO NOT recommend creating a new table in the DB. This can potentially have cause adverse side effects on your exchange.
'use strict';
const {
app,
loggerPlugin,
toolsLib
} = this.pluginLibraries;
const sequelize = require('sequelize');
const umzug = require('umzug');
const { body, validationResult } = require('express-validator');
const init = async () => {
const umzugInstance = new umzug({
storage: 'sequelize',
storageOptions: {
sequelize: toolsLib.database.getModel('sequelize'),
modelName: 'PluginMigrations',
tableName: 'PluginMigrations'
},
upName: 'up',
downName: 'down',
migrations: umzug.migrationsList(
[
{
name: 'twitter_plugin-create_twitter_table',
up: (queryInterface, Sequelize) => queryInterface.createTable(
'Twitters',
{
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
user_id: {
type: Sequelize.INTEGER,
onDelete: 'CASCADE',
allowNull: false,
references: {
model: 'Users',
key: 'id'
}
},
username: {
type: Sequelize.STRING,
allowNull: false,
unique: true
},
updated_at: {
allowNull: false,
type: Sequelize.DATE,
defaultValue: Sequelize.literal('NOW()')
},
created_at: {
allowNull: false,
type: Sequelize.DATE,
defaultValue: Sequelize.literal('NOW()')
}
},
{
timestamps: true,
underscored: true
}
),
down: (queryInterface, Sequelize) => queryInterface.dropTable('Twitters')
}
],
[toolsLib.database.getModel('sequelize').getQueryInterface(), sequelize]
)
});