我需要在生产环境中为基于 Rocket 的应用程序运行 Diesel 数据库迁移。通常有几种方法可以为数据库执行迁移:
- 在应用程序启动时。
- 与应用程序启动分开。
我更喜欢使用--migrate
应用程序二进制标志调用的第二个选项,但由于目标应用程序相当简单,第一种方法就可以了。
Diesel 问题跟踪器中有一个关于在生产中运行迁移的线程,并建议如何执行此操作:
- 添加
diesel_migrations
到您的依赖项- 在你的板条箱中加入一个
extern crate diesel_migrations
,并确保用它来装饰它#[macro_use]
- 在代码的开头,添加
embed_migrations!()
- 要运行迁移,请使用
embedded_migrations::run(&db_conn)
在main.rs
我做了:
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_migrations;
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate rocket_contrib;
#[database("my_db_name")]
pub struct DbConn(diesel::PgConnection);
fn main() {
// Update database
embed_migrations!();
embedded_migrations::run(&DbConn);
// Launch the app
...
}
这会导致错误:
error[E0277]: the trait bound `fn(diesel::r2d2::PooledConnection<<diesel::PgConnection as rocket_contrib::databases::Poolable>::Manager>) -> DbConn {DbConn}: diesel::Connection` is not satisfied
--> src/main.rs:30:30
|
29 | embed_migrations!();
| --------------------
| |
| required by this bound in `main::embedded_migrations::run`
30 | embedded_migrations::run(&DbConn);
| ^^^^^^^ the trait `diesel::Connection` is not implemented for `fn(diesel::r2d2::PooledConnection<<diesel::PgConnection as rocket_contrib::databases::Poolable>::Manager>) -> DbConn {DbConn}`
|
= note: required because of the requirements on the impl of `diesel_migrations::MigrationConnection` for `fn(diesel::r2d2::PooledConnection<<diesel::PgConnection as rocket_contrib::databases::Poolable>::Manager>) -> DbConn {DbConn}`
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
如何解决?