简体   繁体   English

Bookshelf.js / Knex.js上数据库架构加载的常见做法

[英]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. ActiveRecord(来自Rails)和Sequelize(另一个node.js ORM)都提供了一种初始化数据库的方法,从模型定义创建表结构。 Rails does that through the rails db:schema:load command, while Sequelize has the sync() method that does the same. Rails通过rails db:schema:load命令执行此操作,而Sequelize使用sync()方法执行相同操作。 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. 通过使用它,我们不需要运行应用程序的整个迁移堆栈来启动新数据库,也不需要在项目存储库中保存SQL转储。

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. 从这个背景来看,我期待Bookshelf.js或Knex.js具有某种类似的功能,但我无法在两个项目的文档中找到它。

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: 然后我决定看一下使用Bookshelf的Ghost博客引擎的源代码,我发现他们在自己的代码库中处理数据库初始化:

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. 我想避免编写自己的代码来处理这样的事情,因为Sequelize等其他选项提供了开箱即用的功能。

Is there any common practice, plugin or library recommended for database schema loading on Bookshelf? 是否有任何常见的做法,插件或库建议在Bookshelf上加载数据库模式?

I think you were on the right track and maybe just missed the docs. 我认为你走在正确的轨道上,也许只是错过了文档。

http://knexjs.org/#Migrations 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 例如: 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. Rails通过两个rake任务db:schema:dump和db:schema:load来实现迁移。 Dump will dump your db schema to a local schema.rb file in a custom ruby format. 转储将以自定义ruby格式将数据库模式转储到本地schema.rb文件。 db:schema:load loads that file. db:schema:加载加载该文件。

So you could achieve something similar using pg_dump and pg_restore and an npm package script. 所以你可以使用pg_dump和pg_restore以及一个npm包脚本来实现类似的功能。 Just make the script use node's exec method to call pg_dump and dump to the same file every time. 只需让脚本使用node的exec方法调用pg_dump并每次都转储到同一个文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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