Database synchronization

When starting a new project you won't have a database structure and using Sequelize you won't need to. Just specify your model structures and let the library do the rest. Currently supported is the creation and deletion of tables:

  1. // Create the tables:
  2. Project.sync()
  3. Task.sync()
  4. // Force the creation!
  5. Project.sync({force: true}) // this will drop the table first and re-create it afterwards
  6. // drop the tables:
  7. Project.drop()
  8. Task.drop()
  9. // event handling:
  10. Project.[sync|drop]().then(() => {
  11. // ok ... everything is nice!
  12. }).catch(error => {
  13. // oooh, did you enter wrong database credentials?
  14. })

Because synchronizing and dropping all of your tables might be a lot of lines to write, you can also let Sequelize do the work for you:

  1. // Sync all models that aren't already in the database
  2. sequelize.sync()
  3. // Force sync all models
  4. sequelize.sync({force: true})
  5. // Drop all tables
  6. sequelize.drop()
  7. // emit handling:
  8. sequelize.[sync|drop]().then(() => {
  9. // woot woot
  10. }).catch(error => {
  11. // whooops
  12. })

Because .sync({ force: true }) is destructive operation, you can use match option as an additional safety check.match option tells sequelize to match a regex against the database name before syncing - a safety check for caseswhere force: true is used in tests but not live code.

  1. // This will run .sync() only if database name ends with '_test'
  2. sequelize.sync({ force: true, match: /_test$/ });