Rust `unresolved import` when trying to import an external crate into a module not in the root directory

1.1k Views Asked by At

I'm very new to Rust, so maybe this is an obvious question, but I couldn't find anything that answered it. I can't seem to import the external crate diesel_derive_enum in my module sub-module database/models.rs. It works perfectly if I simply move the models.rs file to the src/ directory. I'm guessing I'm missing something where I need to tell it to look up to the root level for the external crate?

I have a project that's structured like:

src
├── database
│   ├── models.rs
│   ├── mod.rs
│   └── schema.rs
└── main.rs

Models.rs

use diesel::pg::PgConnection;
use diesel::prelude::*;
use diesel_derive_enum;
use uuid::Uuid;

use super::schema::market_trade_goods;

#[derive(Debug, PartialEq, Clone, diesel_derive_enum::DbEnum)] // <- error is here
#[ExistingTypePath = "crate::schema::sql_types::SupplyType"]
pub enum SupplyType {
    Scarce,
    Limited,
    Moderate,
    Abundant,
}
// ...then more

database/mod.rs

pub mod models;
pub mod schema;

main.rs

mod database;

use diesel::pg::PgConnection;
use diesel::prelude::*;
use dotenvy::dotenv;
use std::env;
use uuid::Uuid;

use crate::database::models::{SupplyType, TradeGood};
// ...then some more functions and whatnot

I've tried a bunch of different ways of importing things like crate::diesel_derive_enum or extern crate diesel_derive_enum (in models.rs and main.rs). Nothing seems to make a difference, but I'm sure I'm just missing something obvious.

Edit: Full error message is:

error[E0433]: failed to resolve: unresolved import
 --> src/database/models.rs:8:35
  |
8 | #[derive(Debug, PartialEq, Clone, diesel_derive_enum::DbEnum)]
  |                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^
  |                                   |
  |                                   unresolved import
  |                                   help: a similar path exists: `crate::database::schema`
  |
  = note: this error originates in the derive macro `diesel_derive_enum::DbEnum` (in Nightly builds, run with -Z macro-backtrace for more info)
1

There are 1 best solutions below

2
Chayim Friedman On BEST ANSWER

The derive macro itself is resolved correctly, but its expansion includes crate::schema::sql_types::SupplyType. The problem is, schema is not directly under the crate root - it is under database. So change it to:

#[derive(Debug, PartialEq, Clone, diesel_derive_enum::DbEnum)] // <- error is here
#[ExistingTypePath = "crate::database::schema::sql_types::SupplyType"]
pub enum SupplyType {
    Scarce,
    Limited,
    Moderate,
    Abundant,
}