0

I am trying to create a basic crud app with actix and diesel but there is a problem with diesel. This is the folder structure of project:

|─ migrations 
|─ src 
| ├─ users
| ├─mod.rs
| ├─models.rs
|─ main.rs
|─ schema.rs

where schema.rs is created and managed by diesel by running migration commands.

These are the files with their contents:

mod.rs

pub mod models;
pub mod routes;

pub use models::*;*
pub use routes::;

models.rs

use diesel::{Insertable, Queryable};
use crate::schema::users;

#[derive(Queryable)]
pub struct User {
    pub id: i64,
    pub email: String,
    pub password_hash: String,
    pub confirmed: bool,
}

#[derive(Insertable)]
#[table_name = "users"]
pub struct NewUser {
    pub email: String,
    pub password_hash: String,
    pub confirmed: bool,
}

main.rs

#![allow(unused)]

#[macro_use]
extern crate diesel;

mod users;
mod schema;

use diesel::pg::PgConnection;
use diesel::prelude::*;
use diesel::query_dsl::methods::FindDsl;
use dotenv::dotenv;
use std::env;

pub fn establish_connection() -> PgConnection {
    dotenv().ok();

    let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    PgConnection::establish(&database_url).expect(&format!("Error connecting to {}", database_url))
}

fn main() -> std::io::Result<()> {
    let connection = establish_connection();
    use schema::users::dsl as users_dsl;

    let results = users_dsl::users.filter(users_dsl::confirmed.eq_all(true)).limit(5).load::<users::models::User>(&connection).expect("Error loading users")  ;

    for _user in results {
        println!("user id {} with mail {}", _user.id, _user.email)
    }

    Ok(())
}

and schema.rs :

table! {
    users (id) {
        id -> Int8,
        email -> Varchar,
        password_hash -> Varchar,
        confirmed -> Bool,
    }
}

The problem is when I try to import schema from crate root into user/models.rs rustc says "unresolved import crate::schema could not find schema in the crate root" but rust-analyzer suggests what is present in that module (for example dsl, table and its columns).

So what's the problem?

1 Answers1

-1

Just found that I have to import schema module in a file called lib.rs (create it if it's not present):

src/lib.rs

pub mod schema;

#[macro_use]
extern crate diesel;

so it will be accessible with

use crate::schema::*;

Note that macro_use is needed inside lib.rs to be able to use table! macro in schema.rs without getting any errors.