简体   繁体   中英

Common practice for database schema load on Bookshelf.js/Knex.js

Both ActiveRecord (from Rails) and Sequelize (another node.js ORM) provide a way to initialize a database, creating the table structures from the model definitions. Rails does that through the rails db:schema:load command, while Sequelize has the sync() method that does the same. By using that, we don't need to run the entire migration stack of the application to start a fresh database, neither save SQL dumps on the project repository.

Coming from this background, I was expecting Bookshelf.js or Knex.js to have some kind of similar functionality, but I couldn't find it on the documentation of both projects.

I decided then to take a look at the source code of the Ghost blogging engine , which uses Bookshelf, and I found out that they treat the database initialization inside their own codebase:

I'd like to avoid having to write my own code to treat things like this specially because other options like Sequelize offer this out of the box.

Is there any common practice, plugin or library recommended for database schema loading on Bookshelf?

I think you were on the right track and maybe just missed the docs.

http://knexjs.org/#Migrations

For loading a schema, you can run the migration stack if the migrations are written to be idempotent.

Another option is to use the database's export and import features. For example: https://www.postgresql.org/docs/9.1/static/app-pgdump.html

Rails achieves its migrations by having two rake tasks db:schema:dump and db:schema:load. Dump will dump your db schema to a local schema.rb file in a custom ruby format. db:schema:load loads that file.

So you could achieve something similar using pg_dump and pg_restore and an npm package script. Just make the script use node's exec method to call pg_dump and dump to the same file every time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM