我一包含文件,Diesel 和 Rocket 的导入就会中断

Diesel and Rocket imports break as soon as I include a file

我有文件“user.rs”,它具有 postgres 数据库的结构 table。每当我尝试将它包含在我的 main.rs 文件(一个 Rocket 网络项目)中时,所有 Diesel“东西”都无法解析。这是我的 user.js 文件:

use super::schema::users;

pub mod handler;
pub mod repository;
pub mod router;

#[derive(Queryable, AsChangeset, Serialize, Deserialize)]
#[table_name = "users"]
pub struct User {
    pub id: String,
    pub username: String,
    pub password: String,
}

#[derive(Insertable)]
#[table_name = "users"]
pub struct InsertableUser {
    username: String,
    password: String,
}

pub impl InsertableUser {
    pub fn from_user(user: User) -> InsertableUser {
        InsertableUser {
            username: user.username,
            password: user.password,
        }
    }
}

pub fn all(connection: &PgConnection) -> QueryResult<Vec<User>> {
    users::table.load::<User>(&*connection)
}

pub fn get(id: i32, connection: &PgConnection) -> QueryResult<User> {
    users::table.find(id).get_result::<User>(connection)
}

pub fn insert(user: User, connection: &PgConnection) -> QueryResult<User> {
    diesel::insert_into(users::table)
        .values(&InsertableUser::from_user(user))
        .get_result(connection)
}

pub fn update(id: i32, user: User, connection: &PgConnection) -> QueryResult<User> {
    diesel::update(users::table.find(id))
        .set(&user)
        .get_result(connection)
}

pub fn delete(id: i32, connection: &PgConnection) -> QueryResult<usize> {
    diesel::delete(users::table.find(id)).execute(connection)
}

这是我的 main.rs:

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate rocket;

#[macro_use]
extern crate rocket_contrib;

use rocket_contrib::databases::diesel;

#[database("camera-server-db")]
struct CameraServerDbConn(diesel::PgConnection);

mod user;

#[get("/")]
fn index() -> &'static str {
    "Hello World!"
}

fn main() {
    rocket::ignite()
        .attach(CameraServerDbConn::fairing())
        .mount("/", routes![index])
        .launch();
}

如果我从 main.rs 中删除 mod user;,则不会出现错误。当我 运行 cargo check 时,我得到很多“在此范围内找不到 x”。这是一个例子:

error: cannot find derive macro `AsChangeset` in this scope
 --> src/user.rs:7:21
  |
7 | #[derive(Queryable, AsChangeset, Serialize, Deserialize)]
  |                     ^^^^^^^^^^^

我正在尝试遵循 this guide(诚然这已经过时了,但它是我能找到的仅有的实际指南之一)。

如“最后一步”部分的链接指南中所述,您需要正确导入柴油,否则编译器无法解析这些 traits/derives/functions。这意味着您需要按如下方式更改 main.rs 文件:

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate rocket;

#[macro_use]
extern crate rocket_contrib;

#[macro_use]
extern crate diesel;

use rocket_contrib::databases::diesel;

#[database("camera-server-db")]
struct CameraServerDbConn(diesel::PgConnection);

mod user;

#[get("/")]
fn index() -> &'static str {
    "Hello World!"
}

fn main() {
    rocket::ignite()
        .attach(CameraServerDbConn::fairing())
        .mount("/", routes![index])
        .launch();
}

(请注意您的 extern crate 部分中的附加 #[macro_use] extern crate diesel;。)