PhilWaldmann / openrecord

Make ORMs great again!
https://openrecord.js.org
MIT License
486 stars 38 forks source link

migration example or test? #75

Closed bitinn closed 6 years ago

bitinn commented 6 years ago

Actual question: when does a migration run exactly?

say I have this file:

const openrecord = require('openrecord/store/sqlite3');

const db = new openrecord({
  type: 'sqlite3',
  file: './database/test.sqlite',
  migrations: [
    require('./migrations/migration20181002.js')
  ]
});

db.ready(async () => {
  // todo
})

where test.sqlite is created already but as an empty database.

Basically, I am using migration feature as a database setup tool, is it supported?

bitinn commented 6 years ago

PS: I can run raw sql with https://github.com/mapbox/node-sqlite3 and it indeed creates the right tables, but I would like to use openrecord's model as it's less prone to sql mistakes.

PhilWaldmann commented 6 years ago

Hi,

migrations will run before the db.ready(callback) callback will be called. So on every start openrecord will check if what migrations are new and executes them. After executing the migrations, it will load your schema and populate your models with attributes. Then the ready callback will be called.

bitinn commented 6 years ago

@PhilWaldmann thx for the quick reply!

But I am facing a problem where migration isn't ran, my migration file is something like this:

module.export = function migration20181002 () {
  this.createTable('shots', function () {
    this.string('hash', { unique: true });
    this.string('text');
    this.string('text_romanized');
    this.integer('user_id');
    this.datetime('created');
    this.datetime('updated');
    this.integer('up_votes');
    this.integer('down_votes');
  });
  // and more
}

I also know db.ready is called on my script exit, so by all means migration should have been ran, but it isn't (since the sqlite file remain empty, it's unclear to me how openrecord remembers that a migration has been ran before)

======

To verify sqlite does work, I have this snippet, where I can verify empty table are created properly. I am https://github.com/sqlitebrowser/sqlitebrowser to view the result.

const sqlite3 = require('sqlite3');

const db = new sqlite3.Database('./database/test.sqlite');

db.serialize(function () {
  db.run("CREATE TABLE lorem (info TEXT)");
});
bitinn commented 6 years ago

spend much time testing and realize it should be module.exports instead of module.export.