标签: rust-diesel

如何使用 Diesel 将 i64 与 Insertable 结合使用

我如何使用i64/u64与柴油一起使用?

我真的需要实施 diesel::Expression为原始类型trait 吗?

这是我的代码。

Cargo.toml

[dependencies]
...
diesel = { version = "1.4.5", features = ["sqlite", "numeric"] }
Run Code Online (Sandbox Code Playgroud)

migration/up.sql

[dependencies]
...
diesel = { version = "1.4.5", features = ["sqlite", "numeric"] }
Run Code Online (Sandbox Code Playgroud)

schema.rs

CREATE TABLE books (
  id INTEGER NOT NULL PRIMARY KEY,
  size INTEGER NOT NULL
);
Run Code Online (Sandbox Code Playgroud)

来源:

table! {
    books (id) {
        id -> Integer,
        size -> Integer,
    }
}
Run Code Online (Sandbox Code Playgroud)

这给出了以下错误:

use crate::schema::books;

#[derive(Insertable, Queryable)]
#[table_name="books"]
pub struct BookRecord …
Run Code Online (Sandbox Code Playgroud)

sqlite rust rust-diesel

5
推荐指数
1
解决办法
426
查看次数

如何使用 Diesel 生成和解析原始 SQL 查询?

我正在使用 Rocket 框架测试 Rust。对于数据库,我使用 Diesel 与 MySQL 数据库交互。

通过几个例子,幕后发生了很多事情。我有一个 MySQL 数据库正在运行,其中有一个填充表,我想对其进行原始查询。

下面的代码有效:

use diesel::{prelude::*};

mod schema {
    table! {
        organization {
            id -> Nullable<Integer>,
            name -> Text,
            country -> Text,
        }
    }
}

use self::schema::organization;
use self::schema::organization::dsl::{organization as all_orgs};

#[table_name="organization"]
#[derive(Serialize, Deserialize, Queryable, Insertable, Debug, Clone)]
pub struct Organization {
    pub id: Option<i32>,
    pub name: String,
    pub country: String
}

impl Organization {
    pub fn all(conn: &MysqlConnection) -> Vec<Organization> {
        all_orgs.order(organization).load::<Organization>(conn).unwrap()
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我不需要按任何顺序订购。事实上,我只想进行一个原始查询,SELECT id, name, country FROM organization …

mysql rust rust-diesel

5
推荐指数
1
解决办法
5844
查看次数

Rust Diesel:特性绑定`NaiveDateTime: Deserialize&lt;'_&gt;` 不满足

我是铁锈和柴油的新手。并尝试使用火箭框架创建一个小型演示 api。
得到错误:不满足特征界限NaiveDateTime: Deserialize<'_>

我用谷歌搜索并找到了一些有用的链接,比如这里:https : //github.com/serde-rs/serde/issues/759
看起来版本有问题。

这是我的文件:
schema.rs

table! {
    department (dept_id) {
        dept_id -> Int4,
        dept_name -> Nullable<Text>,
        created_on -> Nullable<Timestamp>,
        created_by -> Nullable<Text>,
        modified_on -> Nullable<Timestamp>,
        modified_by -> Nullable<Text>,
        is_active -> Nullable<Bool>,
    }
}
Run Code Online (Sandbox Code Playgroud)

货物.toml

[dependencies]
diesel = { version = "1.4.5", features = ["postgres","chrono","numeric"] }
dotenv = "0.15.0"
chrono = { version = "0.4.19" }
bigdecimal = { version = "0.1.0" }
rocket = "0.4.6"
rocket_codegen = "0.4.6"
r2d2-diesel = "1.0.0" …
Run Code Online (Sandbox Code Playgroud)

rust rust-chrono rust-diesel serde rust-rocket

5
推荐指数
1
解决办法
674
查看次数

Diesel 中多个外键引用同一个表

我正在尝试创建一个引用同一个表两次的结构。这样做的目的是创建一种类别层次结构。这是我正在尝试对下表执行的操作:

create table product_category_rollup(
    id serial primary key,
    upper_category_id integer not null,
    lower_category_id integer not null,
    foreign key (upper_category_id) references product_category(id),
    foreign key (lower_category_id) references product_category(id)
);

create table product_category(
    id serial primary key,
    name varchar unique not null
);

Run Code Online (Sandbox Code Playgroud)

我正在尝试创建匹配的结构,如下所示:

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

#[derive(Queryable, Identifiable, Associations)]
#[belongs_to(ProductCategory, foreign_key="upper_category_id")]
#[belongs_to(ProductCategory, foreign_key="lower_category_id")]
#[table_name = "product_category_rollup"]
pub struct ProductCategoryRollup {
    id: i32,
    upper_category_id: i32,
    lower_category_id: i32,
}

Run Code Online (Sandbox Code Playgroud)

我收到一条错误消息:

error[E0119]: conflicting implementations …
Run Code Online (Sandbox Code Playgroud)

rust rust-diesel

5
推荐指数
1
解决办法
1971
查看次数

没有为“DbConnection”实现特征“diesel::Connection”

我正在尝试使用柴油将 postgres 数据库添加到火箭应用程序。我的main.rs文件看起来像这样,但给出了错误“该特征diesel::Connection未实现DbConnection.get_result(connection)

#[macro_use] extern crate diesel;
extern crate dotenv;
#[macro_use] extern crate rocket;
#[macro_use] extern crate rocket_contrib;

use diesel::prelude::*;
use rocket_contrib::database;
use rocket_contrib::json::JsonValue;

mod models;
mod schema;

use self::models::*;
use self::schema::*;

#[database("my_db")]
struct DbConnection(diesel::PgConnection);

#[get("/")]
fn index(connection: DbConnection) -> JsonValue {
    json!(all_bicycles(&connection))
}

fn create_bicycle<'a>(connection: &DbConnection, make: &'a str, model: &'a str, rider_type: &'a str, size: &'a str) -> Bicycle {
    let new_bicycle = NewBicycle {
        make,
        model,
        rider_type,
        size
    };

    diesel::insert_into(bicycles::table) …
Run Code Online (Sandbox Code Playgroud)

postgresql rust rust-diesel rust-rocket

5
推荐指数
1
解决办法
2992
查看次数

Rust Diesel 未构建错误使用未声明的板条箱或模块

我正在尝试使用数据库支持创建我的第一个 Rust 应用程序,我使用 Diesel 和 SQLite,每当我构建我的应用程序时,我都会收到以下错误消息:

failed to resolve: use of undeclared crate or module `categorys`
  --> src/models.rs:14:12
   |
14 | pub struct Category {
   |            ^^^^^^^^ use of undeclared crate or module `categorys`

error[E0433]: failed to resolve: use of undeclared crate or module `correspondents`
  --> src/models.rs:21:12
   |
21 | pub struct Correspondent {
   |            ^^^^^^^^^^^^^ use of undeclared crate or module `correspondents`

error[E0433]: failed to resolve: use of undeclared crate or module `doctypes`
  --> src/models.rs:27:12
   |
27 | pub …
Run Code Online (Sandbox Code Playgroud)

sqlite orm struct rust rust-diesel

5
推荐指数
1
解决办法
1034
查看次数

如何使用diesel进行IN查询?

我想使用 PostgreSQL 13IN柴油进行查询,以从某些 id 集合中的歌曲表中选择歌曲集合。数据库执行的SQL可能如下所示:

select * from songs where id in(1,2,3)
Run Code Online (Sandbox Code Playgroud)

我尝试使用像这样的铁锈柴油方式做的事情:

pub fn songs(ids: Vec<i64>){
    use schema::songs::dsl::*;
    let connection = config::establish_connection();
    let results = songs.filter(id.contains(ids))
        .load::<QuerySongs>(&connection)
        .expect("Error loading posts");
}
Run Code Online (Sandbox Code Playgroud)

似乎不起作用,当我使用cargo build显示错误编译项目代码时,如下所示:

pub fn songs(ids: Vec<i64>){
    use schema::songs::dsl::*;
    let connection = config::establish_connection();
    let results = songs.filter(id.contains(ids))
        .load::<QuerySongs>(&connection)
        .expect("Error loading posts");
}
Run Code Online (Sandbox Code Playgroud)

我阅读了文档源代码演示,但它太短了,没有提到如何通过集合中的 id 执行查询。我应该怎么做才能在 rustdiesel( diesel = { version = "1.4.4", features = ["postgres"] }) 中进行 IN …

postgresql rust rust-diesel

5
推荐指数
1
解决办法
2827
查看次数

柴油和生锈特性的问题和困惑

我正在尝试将 Diesel crate (版本 2.0.2;rustc 1.63.0)用于应用程序,并有一些如下所示的代码:

src/models.rs

use uuid::Uuid;
use diesel::prelude::*;

use crate::schema::entities::dsl::entities;

type DB = diesel::pg::Pg;

#[derive(Queryable, PartialEq, Debug)]
#[diesel(table_name = entities)]
pub struct Entity {
    pub id: u16,
    pub uuid: Uuid,
    pub username: Option<String>
}

impl Entity {
    pub fn get_all(connection: &mut PgConnection) -> QueryResult<Vec<Entity>> {
        entities.load::<Entity>(connection)
    }
}
Run Code Online (Sandbox Code Playgroud)

src/schema.rs

// @generated automatically by Diesel CLI.

diesel::table! {
    entities (id) {
        id -> Int4,
        uuid -> Uuid,
        username -> Nullable<Text>,
    }
}

diesel::allow_tables_to_appear_in_same_query!(
    entities,
);
Run Code Online (Sandbox Code Playgroud)

但是,这不会编译。当我尝试时会抛出以下错误:

error[E0277]: the …
Run Code Online (Sandbox Code Playgroud)

traits rust rust-diesel

5
推荐指数
1
解决办法
1058
查看次数

锈柴油的交易

我正在学习 Rust 和 Rocket 框架,并尝试使用 Diesel 构建一个具有数据库连接的应用程序。我已经能够成功连接到 SqLite 数据库并执行一些基本的 CRUD 操作。现在我希望能够确保事务原子性。例如,我有一个用户模型,其中包含用户表和角色表,这两个表处于多对多关系,并通过名为 user_role 的联结表连接。因此,要插入新用户,我会执行以下操作:

    let new_user = CreateUser{id: Option::from(new_id), username, email, password_hash: password };
    diesel::insert_into(user::table)
        .values(&new_user)
        .execute(connection)
        .expect("Error saving the user");

    let user_role = CreateUserRole{user_id: new_user.id, role_id: existing_role.id};
    diesel::insert_into(user_role::table)
        .values(&user_role)
        .execute(connection)
        .expect("Could not add role to user");
Run Code Online (Sandbox Code Playgroud)

现在的问题是,如果角色分配出现问题,则会创建用户,但不会分配角色,这是我不希望发生的情况。有没有办法确保原子性,以便要么执行两个操作,要么都不执行任何操作。我在有关事务管理器的文档中看到了此页面:https ://docs.diesel.rs/master/diesel/connection/trait.TransactionManager.html ,但我真的不明白如何使用它,而且我还没有找到任何例子。

rust rust-diesel

5
推荐指数
1
解决办法
2360
查看次数

Diesel 的查找或过滤器执行删除操作的一般用法

我正在尝试使用通用 Diesel 函数来缩小重复性任务,例如根据主键删除一行。

我得到了相对较快的行的通用插入,但删除查询似乎非常困难。我尝试通过使用find()和 来解决它filter()。我也咨询过类似的话题12,但没有成功。

使用 find

use diesel::prelude::*;
use diesel::query_dsl::methods::FindDsl;
use std::error::Error;

pub struct DB {
    conn: SqliteConnection,
}

impl DB {
    pub fn remove_row<'a, T>(&self, table: T, pk: &'a str) -> Result<(), Box<Error>>
    where
        T: FindDsl<&'a str>,
        <T as FindDsl<&'a str>>::Output: diesel::Identifiable,
        <T as FindDsl<&'a str>>::Output: diesel::associations::HasTable,
    {
        diesel::delete(table.find(pk)).execute(&self.conn)?;
        Ok(())
    }
}
Run Code Online (Sandbox Code Playgroud)

这导致以下错误,我根本无法解释:

error[E0275]: overflow evaluating the requirement `_: std::marker::Sized`
   --> src/db/mod.rs:103:3
    |
103 |         diesel::delete (table.find (pk)) .execute (&self.conn) …
Run Code Online (Sandbox Code Playgroud)

generics generic-programming rust rust-diesel

4
推荐指数
1
解决办法
2173
查看次数