看了 Rust 的基础视频,然后又跟着码 web 相关的视频学习;
学习的视频链接,https://www.bilibili.com/video/BV1RP4y1G7KF
其中,第 16 节课的时候,感觉是按着教学码出来的,但是一直 cargo check 报错,也不知道怎么改了。
报错的提示:
error[E0308]: mismatched types
--> webservice/src/bin/../dbaccess/course.rs:7:30
|
7 | let rows: Vec<Course> = sqlx::query_as!(Course,
| ______________________________^
8 | | r#"select * from course where teacher_id = $1"#,
9 | | teacher_id
10 | | )
| |_____^ expected enum `std::option::Option`, found struct `std::string::String`
|
= note: expected enum `std::option::Option<std::string::String>`
found struct `std::string::String`
= note: this error originates in the macro `$crate::sqlx_macros::expand_query` (in Nightly builds, run with -Z macro-backtrace for more info)
help: try wrapping the expression in `errors::_::_serde::__private::Some`
|
554| errors::_::_serde::__private::Some($crate::sqlx_macros::expand_query!(record = $out_struct, source = $query, args = [$($args)*]))
| +++++++++++++++++++++++++++++++++++ +
其中代码部分是:
dbaccess/course.rs
pub async fn get_courses_for_teacher_db(pool: &PgPool, teacher_id: i32,) -> Result<Vec<Course>, MyError> {
let rows: Vec<Course> = sqlx::query_as!(Course,
r#"select * from course where teacher_id = $1"#,
teacher_id
)
.fetch_all(pool)
.await?;
Ok(rows)
}
models/course.rs 中 Course 的类
#[derive(Serialize, Debug, Clone, sqlx::FromRow)]
pub struct Course {
pub teacher_id: i32,
pub id: i32,
pub name: String,
pub time: Option<NaiveDateTime>,
pub description: Option<String>,
pub format: Option<String>,
pub structure: Option<String>,
pub duration: Option<String>,
pub price: Option<i32>,
pub language: Option<String>,
pub level: Option<String>
}
不知道,是否有同学看过这个视频,跟着码过代码部分?
1
Kilerd 2022-04-14 17:02:09 +08:00
检查你的 name 在数据库类型,数据库里面没有加 not null 的约束,sqlx 解析到的类型是 Option<String> 而不是 String
|
2
louzhumuyou OP @Kilerd 数据库这么创建的
``` CREATE TABLE course ( id serial PRIMARY KEY, teacher_id INT NOT NULL, name varchar(140) NOT NULL, time timestamp DEFAULT now(), description varchar(2000) not null, format varchar(30) not null, structure varchar(200) not null, duration varchar(30) not null, price Int not null, language varchar(30) not null, level varchar(30) not null ); ``` |
3
louzhumuyou OP @Kilerd 感谢。创建数据库的应该是这样就对了。
CREATE TABLE course ( id serial PRIMARY KEY, teacher_id INT not null, name varchar(140) not null, time timestamp DEFAULT now(), description varchar(2000), format varchar(30), structure varchar(200), duration varchar(30), price Int, language varchar(30) , level varchar(30) ); |