ABOUT ME

-

Total
-
  • Rust: diesel db query 코드 정리
    컴퓨터/Rust 2021. 7. 18. 14:30
    728x90
    반응형

    SELECT * FROM table WHERE date = ? ORDER BY id

    #[derive(Queryable, AsChangeset, Serialize, Deserialize, Debug, Clone)]
    #[table_name = "table"]
    pub struct Data {
        pub id: i32,
        pub title: String,
        pub date: String,
        pub link: String,
        pub writer: String,
    }
    
    use crate::db::models::Model;
    
    use crate::db::schema::table;
    use crate::db::schema::table::dsl::*;
    
    // SELECT * FROM table WHERE date = ? ORDER BY id
    pub fn get_notices(conn: &MysqlConnection, _date: String) -> QueryResult<Vec<Model>> {
        table
            .filter(date.eq(_date))
            .order(table::id.desc()) // if ambiguous
            .load::<Model>(&*conn)
    }

     

    SELECT * FROM table limit 5

    #[derive(Queryable, AsChangeset, Serialize, Deserialize, Debug, Clone)]
    #[table_name = "table"]
    pub struct Data {
        pub id: i32,
        pub title: String,
        pub date: String,
        pub link: String,
        pub writer: String,
    }
    
    use crate::db::models::Model;
    
    use crate::db::schema::table;
    use crate::db::schema::table::dsl::*;
    
    // SELECT * FROM table LIMIT 5
    pub fn get_notices(conn: &MysqlConnection) -> QueryResult<Vec<Model>> {
        table
            .limit(5)
            .load::<Model>(&*conn)
    }
    728x90

    '컴퓨터 > Rust' 카테고리의 다른 글

    Rust: serde De/Serialize traits into JSON  (0) 2021.07.19
    Rust: HTML 파싱하기 (crawling)  (0) 2021.07.15
    Rust: Remove duplicate strs in String  (0) 2021.07.15

    댓글