You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Diesel与SQLite构建Rust数据库应用时遭遇未声明crate/模块错误

解决Diesel+SQLite构建时的未声明模块错误

看起来你遇到的问题主要是两个点:模块作用域未正确声明和Diesel的表名推导和你的实际表名不匹配,下面一步步来解决:

步骤1:在主文件中声明schema模块

你的main.rs里只导入了models模块,但Diesel生成的schema.rs也是一个独立的模块,必须在main.rs里声明它,否则models里无法访问到schema的内容。修改后的main.rs如下:

mod models;
mod schema; // 新增这一行,让Rust识别schema模块

fn main() {
    println!("Hello, world!");
}

步骤2:修正models.rs中的表名映射和schema导入

你之前尝试添加use schema::*但没成功,大概率是因为第一步没做。现在加上正确的导入,同时给每个结构体添加#[table_name]属性——因为Identifiable trait默认会把驼峰结构体名转成蛇形复数(比如Category → categorys),但你的数据库表都是单数命名(category、correspondent等),所以必须手动指定表名:

修改后的models.rs:

// Generated by diesel_ext
#![allow(unused)]
#![allow(clippy::all)]
use chrono::NaiveDate;
use diesel::Queryable;
use diesel::Identifiable;
use diesel::sql_types::Binary;
use crate::schema::*; // 正确导入schema模块

#[derive(Queryable, Debug, Identifiable)]
#[table_name = "category"] // 指定对应的数据表名
pub struct Category {
    pub id: i32,
    pub name: String,
    pub color: Option<i32>,
}

#[derive(Queryable, Debug, Identifiable)]
#[table_name = "correspondent"]
pub struct Correspondent {
    pub id: i32,
    pub name: String,
}

#[derive(Queryable, Debug, Identifiable)]
#[table_name = "doctype"]
pub struct Doctype {
    pub id: i32,
    pub name: String,
    pub correspondent_name: Option<String>,
    pub support_extra_date_number: Option<bool>,
    pub icon: Option<Binary>,
}

#[derive(Queryable, Debug, Identifiable)]
#[primary_key(number, date_of_document, doc_type_id)]
#[table_name = "document"] // 同样指定对应表名
pub struct Document {
    pub number: i32,
    pub date_of_document: NaiveDate,
    pub doc_type_id: i32,
    pub extra_number: Option<String>,
    pub extra_date: Option<NaiveDate>,
    pub correspondent_id: i32,
    pub content: String,
    pub notes: Option<String>,
    pub category_id: Option<i32>,
    pub document_file_name: Option<String>,
    pub document_file_size: Option<i32>,
    pub document_file: Option<Binary>,
}

为什么这样能解决问题?

  1. 模块作用域问题:Rust默认不会自动识别src下的所有文件作为模块,必须在主文件(main.rs)中用mod xxx;声明,这样其他模块才能通过crate::xxx或者use xxx::*访问到对应的内容。
  2. 表名映射问题:Diesel的Identifiable trait是用来标记结构体对应数据库中的有主键的表,它默认的表名推导规则是把结构体的驼峰名转为蛇形复数,但你的表都是单数命名,所以必须手动指定#[table_name]来匹配实际的表名,这样Diesel就能找到schema中对应的表模块了。

现在重新运行cargo build,应该就能解决那些未声明模块的错误了。

内容的提问来源于stack exchange,提问作者user12510970

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 11:24:19