Skip to content

Instantly share code, notes, and snippets.

@andrewmunro
Created July 17, 2017 11:30
Show Gist options
  • Star 34 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save andrewmunro/030f0bf62453239c495b0347c8cd1247 to your computer and use it in GitHub Desktop.
Save andrewmunro/030f0bf62453239c495b0347c8cd1247 to your computer and use it in GitHub Desktop.
Sequelize cli with ES6
{
"presets": ["es2015"],
"plugins": [
"add-module-exports"
],
}
const path = require('path');
module.exports = {
'config': path.resolve('migrations/config/babelHook.js'),
'migrations-path': path.resolve('migrations'),
'seeders-path': path.resolve('migrations/seeders'),
'models-path': path.resolve('migrations/models')
};
// migrations/config/babelHook.js
require('babel-core/register');
module.exports = require('./config');
// migrations/config/config.js
import config from 'my/app/config';
const env = process.env.NODE_ENV || 'development';
export default {
[env]: {
url: config.mysql.migrate,
dialect: 'mysql',
migrationStorageTableName: 'SequelizeMeta'
}
};

npm run sequelize db:migrate:all

// migrations/models/model.js
import sequelize from 'sequelize';
const model = sequelize.define('foo', {
createdAt: {
type: this.sequelize.DATE,
allowNull: false,
},
updatedAt: {
type: this.sequelize.DATE,
allowNull: true,
},
});
export default model;
{
"name": "seqelize-with-es6",
"description": "Example of sequelize cli running with es6 models",
"version": "0.0.1",
"main": "index.js",
"contributors": [],
"scripts": {
"sequelize": "sequelize $*"
},
"dependencies": {
"sequelize": "^3.30.4"
},
"devDependencies": {
"babel-core": "^6.24.0",
"babel-plugin-add-module-exports": "^0.2.1",
"babel-preset-es2015": "^6.24.0",
"sequelize-cli": "^2.7.0"
}
}
@andadevs
Copy link

andadevs commented Feb 21, 2018

Hi Andrew,
Thanks for your good approach adding those files. I have been following your steps, but in the config.js in the line
import config from 'my/app/config';
i don not know what should i import here. Can you share it with me please, i´ll appreciate your time. Thank you.

@eze-nonso
Copy link

eze-nonso commented Feb 25, 2018

@clenondavis The import is likely a small raw config.json that means little.
You can as well, and preferably personally, define everything in the config.js.

BTW it works like magic and I can't yet understand how it works, this is the first real method that lets me do migrations in ES6, great job!

@kaiomagalhaes
Copy link

Thanks for it!

@macdougall
Copy link

macdougall commented May 23, 2018

can't seem to get the dialect to work, I'm getting this:

RROR: Dialect undefined does not support db:create / db:drop commands

Note: the "undefined".

My config.js for the babelHook.js looks like:

// migrations/config/config.js
import config from '../../config/config.json';
const env = process.env.NODE_ENV || 'development';

export default {
  [env]: {
    dialect: config[env]['dialect'],
    username: config[env]['username'],
    password: config[env]['password'],
    host: config[env]['host'],
    migrationStorageTableName: 'SequelizeMeta'
  }
};

Running it, such as...

$ npm run sequelize db:drop

> @2.10.0 sequelize /Users/gary/Development/digsup/DigsUp
> sequelize $* "db:drop"


Sequelize CLI [Node: 9.8.0, CLI: 4.0.0, ORM: 4.37.8]

Loaded configuration file "migrations/config/babelHook.js".

ERROR: Dialect undefined does not support db:create / db:drop commands

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @2.10.0 sequelize: `sequelize $* "db:drop"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @2.10.0 sequelize script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/gary/.npm/_logs/2018-05-23T21_38_39_285Z-debug.log

Any help appreciated.

@macdougall
Copy link

Resolved. The issue was actually that I needed to pass the environment variable through to babel.
I used cross-env, so this solved it by adding it to my package.json.

"sequelize": "cross-env NODE_ENV=local sequelize $*",

@jayceekay
Copy link

jayceekay commented Sep 19, 2018

this doesn't actually work for me with import and export statements. i'm trying the following:

  • running ./node_modules/.bin/sequelize via ./node_modules/.bin/babel-node
  • requiring babel-core/register in my sequelize config.js
  • using cross-env (didn't help)

relevant npm run commands:

    "sequelize": "NODE_ENV=development ./node_modules/.bin/babel-node ./node_modules/.bin/sequelize --config config/sequelize-cli.js",
    "db:migrate": "npm run sequelize db:migrate",
    "db:seed": "npm run sequelize db:seed:all",

my sequelize config:

require('babel-core/register');

const path = require('path');
const conf = require(path.resolve('.', 'config'));

const env = conf.get('NODE_ENV');

console.log(`env=${env}, db config=`);
console.log(conf.get('db'));

module.exports = { [env]: conf.get('db') };

the tests:

$ NODE_ENV=test ./node_modules/.bin/babel-node  ./node_modules/.bin/sequelize --config config/sequelize-cli.js db:seed:all

Sequelize CLI [Node: 8.11.1, CLI: 4.0.0, ORM: 4.38.0]

env=test, db config=
{ dialect: 'postgres',
  database: 'appraise',
  port: 5432,
  migrationStorageTableName: 'SequelizeMeta',
  operatorsAliases: false,
  define: { underscored: true },
  logging: true,
  pool: { max: 5, min: 0, acquire: 30000, idle: 10000 },
  query: { pool: true, debug: true },
  debug: true,
  host: 'localhost' }
Loaded configuration file "config/sequelize-cli.js".
Using environment "test".
Executing (default): SELECT 1+1 AS result
== 20180910163130-demo-user: migrating =======

ERROR: Unexpected token export

$ NODE_ENV=test ./node_modules/.bin/babel-node  ./node_modules/.bin/sequelize --config config/sequelize-cli.js db:migrate

Sequelize CLI [Node: 8.11.1, CLI: 4.0.0, ORM: 4.38.0]

env=test, db config=
{ dialect: 'postgres',
  database: 'appraise',
  port: 5432,
  migrationStorageTableName: 'SequelizeMeta',
  operatorsAliases: false,
  define: { underscored: true },
  logging: true,
  pool: { max: 5, min: 0, acquire: 30000, idle: 10000 },
  query: { pool: true, debug: true },
  debug: true,
  host: 'localhost' }
Loaded configuration file "config/sequelize-cli.js".
Using environment "test".
Executing (default): SELECT 1+1 AS result
Executing (default): SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type LIKE '%TABLE' AND table_name != 'spatial_ref_sys';
Executing (default): SELECT pk.constraint_type as "Constraint", c.column_name as "Field", c.column_default as "Default", c.is_nullable as "Null", (CASE WHEN c.udt_name = 'hstore' THEN c.udt_name ELSE c.data_type END) || (CASE WHEN c.character_maximum_length IS NOT NULL THEN '(' || c.character_maximum_length || ')' ELSE '' END) as "Type", (SELECT array_agg(e.enumlabel) FROM pg_catalog.pg_type t JOIN pg_catalog.pg_enum e ON t.oid=e.enumtypid WHERE t.typname=c.udt_name) AS "special" FROM information_schema.columns c LEFT JOIN (SELECT tc.table_schema, tc.table_name, cu.column_name, tc.constraint_type FROM information_schema.TABLE_CONSTRAINTS tc JOIN information_schema.KEY_COLUMN_USAGE  cu ON tc.table_schema=cu.table_schema and tc.table_name=cu.table_name and tc.constraint_name=cu.constraint_name and tc.constraint_type='PRIMARY KEY') pk ON pk.table_schema=c.table_schema AND pk.table_name=c.table_name AND pk.column_name=c.column_name WHERE c.table_name = 'SequelizeMeta' AND c.table_schema = 'public'
File: .DS_Store does not match pattern: /\.js$/
Executing (default): CREATE TABLE IF NOT EXISTS "SequelizeMeta" ("name" VARCHAR(255) NOT NULL UNIQUE , PRIMARY KEY ("name"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'SequelizeMeta' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): SELECT "name" FROM "SequelizeMeta" AS "SequelizeMeta" ORDER BY "SequelizeMeta"."name" ASC;
No migrations were executed, database schema was already up to date.

$ NODE_ENV=test   ./node_modules/.bin/sequelize --config config/sequelize-cli.js db:migrate

Sequelize CLI [Node: 8.11.1, CLI: 4.0.0, ORM: 4.38.0]

env=test, db config=
{ dialect: 'postgres',
  database: 'appraise',
  port: 5432,
  migrationStorageTableName: 'SequelizeMeta',
  operatorsAliases: false,
  define: { underscored: true },
  logging: true,
  pool: { max: 5, min: 0, acquire: 30000, idle: 10000 },
  query: { pool: true, debug: true },
  debug: true,
  host: 'localhost' }
Loaded configuration file "config/sequelize-cli.js".
Using environment "test".
Executing (default): SELECT 1+1 AS result
Executing (default): SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type LIKE '%TABLE' AND table_name != 'spatial_ref_sys';
Executing (default): SELECT pk.constraint_type as "Constraint", c.column_name as "Field", c.column_default as "Default", c.is_nullable as "Null", (CASE WHEN c.udt_name = 'hstore' THEN c.udt_name ELSE c.data_type END) || (CASE WHEN c.character_maximum_length IS NOT NULL THEN '(' || c.character_maximum_length || ')' ELSE '' END) as "Type", (SELECT array_agg(e.enumlabel) FROM pg_catalog.pg_type t JOIN pg_catalog.pg_enum e ON t.oid=e.enumtypid WHERE t.typname=c.udt_name) AS "special" FROM information_schema.columns c LEFT JOIN (SELECT tc.table_schema, tc.table_name, cu.column_name, tc.constraint_type FROM information_schema.TABLE_CONSTRAINTS tc JOIN information_schema.KEY_COLUMN_USAGE  cu ON tc.table_schema=cu.table_schema and tc.table_name=cu.table_name and tc.constraint_name=cu.constraint_name and tc.constraint_type='PRIMARY KEY') pk ON pk.table_schema=c.table_schema AND pk.table_name=c.table_name AND pk.column_name=c.column_name WHERE c.table_name = 'SequelizeMeta' AND c.table_schema = 'public'
File: .DS_Store does not match pattern: /\.js$/
Executing (default): CREATE TABLE IF NOT EXISTS "SequelizeMeta" ("name" VARCHAR(255) NOT NULL UNIQUE , PRIMARY KEY ("name"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'SequelizeMeta' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): SELECT "name" FROM "SequelizeMeta" AS "SequelizeMeta" ORDER BY "SequelizeMeta"."name" ASC;
No migrations were executed, database schema was already up to date.


$ NODE_ENV=test   ./node_modules/.bin/sequelize --config config/sequelize-cli.js db:seed:all

Sequelize CLI [Node: 8.11.1, CLI: 4.0.0, ORM: 4.38.0]

env=test, db config=
{ dialect: 'postgres',
  database: 'appraise',
  port: 5432,
  migrationStorageTableName: 'SequelizeMeta',
  operatorsAliases: false,
  define: { underscored: true },
  logging: true,
  pool: { max: 5, min: 0, acquire: 30000, idle: 10000 },
  query: { pool: true, debug: true },
  debug: true,
  host: 'localhost' }
Loaded configuration file "config/sequelize-cli.js".
Using environment "test".
Executing (default): SELECT 1+1 AS result
== 20180910163130-demo-user: migrating =======

ERROR: Unexpected token export

once the first import or export statements gets processed they all fail with something like the above.

@tolulope-od
Copy link

Experiencing the same issue after requiring @babe/core in my package.json

Here's the error output:

Loaded configuration file "server/config/babelHook.js".
Using environment "development".
sequelize deprecated String based operators are now deprecated. Please use Symbol based operators for better security, read more at http://docs.sequelizejs.com/manual/tutorial/querying.html#operators node_modules/sequelize/lib/sequelize.js:242:13
== 20190218092918-create-menu: migrating =======

ERROR: Unexpected token export

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! indulgent-treats@1.0.0 sequelize: `sequelize $* "db:migrate"`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the indulgent-treats@1.0.0 sequelize script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/techcellent/.npm/_logs/2019-02-18T13_50_12_190Z-debug.log

and here's my package.json file:

"name": ".....",
  "version": "1.0.0",
  "description": "....",
  "main": "index.js",
  "sequelize": {
    "require": [
      "@babel/register"
    ]
  },
  "scripts": {
    "start": "nodemon --exec babel-node index.js",
    "test": "cross-env NODE_ENV=test nyc --reporter=lcov --reporter=text-lcov ./node_modules/.bin/mocha --exit --timeout 10000 --reporter spec --compilers js:@babel/register ./test/*.js",
    "coveralls": "nyc npm test && nyc report --reporter=text-lcov | coveralls",
    "sequelize": "sequelize $*"
  },
.......

@cjancsar
Copy link

cjancsar commented Sep 5, 2019

No example of a migration

@lucas-jones
Copy link

Needs Typescript definitions

@YavorK
Copy link

YavorK commented Dec 18, 2019

EcmaScript in migrations worked for me only with this file (and installing the packages in it)
https://gist.github.com/YavorK/816041feed5113986cfeb8fc304eb5df

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment