标签: rust-diesel

无法推断出"U"的类型

我正在使用Rust和Diesel:

fn create_asset_from_object(assets: &HashMap<String, Assets_Json>) {
    let connection: PgConnection  = establish_connection();
    println!("==========================================================");
    insert_Asset(&connection, &assets);
}

pub fn insert_Asset(conn: &PgConnection, assests: &HashMap<String, Assets_Json>){
    use self::schema::assets;

    for (currency, assetInfo) in assests {

        let new_asset = self::models::NewAssets {
            asset_name: &currency,
            aclass:  &assetInfo.aclass,
            altname: &assetInfo.altname,
            decimals:  assetInfo.decimals,
            display_decimals: assetInfo.display_decimals,
        };

       //let result = diesel::insert(&new_asset).into(assets::table).get_result(conn).expect("Error saving new post");
       println!("result, {:#?}", diesel::insert(&new_asset).into(assets::table).get_result(conn).expect("Error saving new post"));

    }
}
Run Code Online (Sandbox Code Playgroud)

编译错误:

error[E0282]: type annotations needed
   --> src/persistence_service.rs:107:81
    |
107 |        println!("result, {:#?}", diesel::insert(&new_asset).into(assets::table).get_result(conn).expect("Error saving new post"));
    |                                                                                 ^^^^^^^^^^ cannot …
Run Code Online (Sandbox Code Playgroud)

rust rust-diesel

2
推荐指数
1
解决办法
4447
查看次数

为什么 rustc 没有将 libmariadb 包含到发布二进制文件中?

我认为 rust 编译器使用静态绑定并在编译时包含所有依赖库(因此可执行文件大小)。

但是,当我尝试在 docker 暂存映像中使用已编译的二进制文件与 actix、mysql 客户端和启用 mysql 功能的柴油机时,会弹出此错误:

error while loading shared libraries: libmariadb.so.3: cannot open shared object file: No such file or director
Run Code Online (Sandbox Code Playgroud)

我的码头档案:

FROM rust:1.43 as builder
WORKDIR /var/app

RUN apt-get update && apt-get install -y libclang-dev clang libmariadb-dev-compat libmariadb-dev

COPY Cargo.toml Cargo.lock diesel.toml ./
COPY src src

RUN cargo install diesel_cli --no-default-features --features mysql
RUN cp /usr/local/cargo/bin/diesel diesel
RUN cargo build --release

FROM ubuntu
USER 1000
WORKDIR /var/app

COPY --from=builder --chown=1000:1000 /var/app/target/release/sniper_api app
COPY --from=builder …
Run Code Online (Sandbox Code Playgroud)

mysql rust rust-diesel

2
推荐指数
1
解决办法
159
查看次数

Diesel“get_results”给出了特征限制错误

我正在尝试使用 Diesel 制作 Actix API,并且在制作第一个端点 (/books/create) 时,我在尝试将插入的值返回到我的代码中时遇到问题。

这是我的插入内容:

use diesel::prelude::*;
use crate::models::Book;
use crate::schema::books;
use crate::db;


pub fn create_book(book: &Book) -> Book {
    
    let mut connection: SqliteConnection = db::establish_connection();
    let result: QueryResult<Book> = diesel::insert_into(books::table)
        .values([book])
        .get_result::<Book>(&mut connection);
        
    
    result.unwrap()
}
Run Code Online (Sandbox Code Playgroud)

这是错误,我将其包装在 Pastebin 中,因为它对于 Stackoverflow 来说太长: https: //pastebin.com/Evq6tUYq

我想知道这是否可能是架构或模型的问题,但据我所知,它们似乎没问题并且没有不匹配的值:

use diesel::prelude::*;
use serde::{Serialize, Deserialize};    
use crate::schema::books;

#[derive(Queryable, Serialize, Deserialize, Insertable)]
#[diesel(table_name = books)]
pub struct Book {
    pub id: i32,
    pub title: String,
    pub author: String,
    pub creation_date: Option<String>,
    pub publishing_house: Option<String>, …
Run Code Online (Sandbox Code Playgroud)

rust rust-diesel

2
推荐指数
1
解决办法
1272
查看次数

将Diesel连接注入Iron中间件

在编写测试时,我希望能够在请求中注入连接,以便我可以将整个测试用例包装在事务中(即使测试用例中有多个请求).

我尝试使用BeforeMiddleware我可以在我的测试用例中链接的插入连接,如下所示:

pub type DatabaseConnection = PooledConnection<ConnectionManager<PgConnection>>;

pub struct DatabaseOverride {
    conn: DatabaseConnection,
}

impl BeforeMiddleware for DatabaseOverride {
    fn before(&self, req: &mut Request) -> IronResult<()> {
        req.extensions_mut().entry::<DatabaseOverride>().or_insert(self.conn);
        Ok(())
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我在尝试执行此操作时遇到编译错误:

error: the trait bound `std::rc::Rc<diesel::pg::connection::raw::RawConnection>: std::marker::Sync` is not satisfied [E0277]
impl BeforeMiddleware for DatabaseOverride {
     ^~~~~~~~~~~~~~~~
help: run `rustc --explain E0277` to see a detailed explanation
note: `std::rc::Rc<diesel::pg::connection::raw::RawConnection>` cannot be shared between threads safely
note: required because it appears within the type `diesel::pg::PgConnection`
note: required because …
Run Code Online (Sandbox Code Playgroud)

iron rust rust-diesel

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

如何通过抽象将使用 Diesel 的多个功能合二为一?

我有以下两个功能:

pub fn get_most_recent_eth_entry(conn: &SqliteConnection) -> Result<i32, Error> {
    let res = types::ethereum::table
        .order(types::ethereum::time.desc())
        .limit(1)
        .load::<types::ETHRecord>(&*conn);
    match res {
        Ok(x) => {
            if x.len() > 0 {
                Ok(x.get(0).unwrap().time)
            } else {
                Ok(0)
            }
        }
        Err(err) => Err(format_err!("Error here! {:?}", err)),
    }
}

pub fn get_most_recent_btc_entry(conn: &SqliteConnection) -> Result<i32, Error> {
    let res = types::bitcoin::table
        .order(types::bitcoin::time.desc())
        .limit(1)
        .load::<types::BTCRecord>(&*conn);
    match res {
        Ok(x) => {
            if x.len() > 0 {
                Ok(x.get(0).unwrap().time)
            } else {
                Ok(0)
            }
        }
        Err(err) => Err(format_err!("Error here! {:?}", …
Run Code Online (Sandbox Code Playgroud)

generics types traits rust rust-diesel

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

在请求保护中访问 Rocket 0.4 数据库连接池

我正在使用 Rocket 创建一个带有身份验证的 web 应用程序。为此,我创建了一个User实现FromRequest. 它采用授权标头,其中包含一个 JSON Web 令牌。我反序列化此令牌以获取有效负载,然后从数据库中查询用户。这意味着FromRequest实现需要一个diesel::PgConnection. 在 Rocket 0.3 中,这意味着调用PgConnection::establish,但在 Rocket 0.4 中,我们可以访问连接池。通常我会按如下方式访问这个连接池:

fn get_data(conn: db::MyDatabasePool) -> MyModel {
    MyModel::get(&conn)
}
Run Code Online (Sandbox Code Playgroud)

但是,在 impl 块中,FromRequest我不能只将conn参数添加到函数的参数列表中from_request。如何在请求保护之外访问我的连接池?

rust rust-diesel rust-rocket

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

如何在生产中使用 Rocket 运行 Diesel 迁移?

我需要在生产环境中为基于 Rocket 的应用程序运行 Diesel 数据库迁移。通常有几种方法可以为数据库执行迁移:

  1. 在应用程序启动时。
  2. 与应用程序启动分开。

我更喜欢使用--migrate应用程序二进制文件的标志调用的第二个选项,但由于目标应用程序相当简单,第一种方法就可以了。

Diesel 问题跟踪器中有一个关于在生产中运行迁移的线程,并提供有关如何执行此操作的建议:

  1. 添加diesel_migrations到您的依赖项
  2. 包括extern crate diesel_migrations在你的箱子,并确保与装饰它#[macro_use]
  3. 在代码的开头,添加 embed_migrations!()
  4. 要运行迁移,请使用 embedded_migrations::run(&db_conn)

main.rs我做了:

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_migrations;

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

#[database("my_db_name")]
pub struct DbConn(diesel::PgConnection);

fn main() {
    // Update database
    embed_migrations!();
    embedded_migrations::run(&DbConn);
    // Launch the app
    ...
}
Run Code Online (Sandbox Code Playgroud)

这导致错误:

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_migrations;

#[macro_use]
extern …
Run Code Online (Sandbox Code Playgroud)

database database-migration rust rust-diesel rust-rocket

1
推荐指数
2
解决办法
1394
查看次数

铁锈柴油方法“过滤器”存在模式表,但其特征边界不满足?

这是我的工作环境:

  • rustc-1.57.0
  • 货物 - 1.57.0
  • diesel - 1.4.8 具有 mysql 功能

这是项目的结构:

- src
   - lib.rs 
   + quant 
      - mod.rs
      + common
         - mod.rs
         + persistence
            - mod.rs
            - database.rs
            - model.rs
            - schema.rs
Cargo.toml
diesel.toml
Run Code Online (Sandbox Code Playgroud)

这是lib.rs

#[macro_use]  
extern crate diesel;

pub mod quant;
Run Code Online (Sandbox Code Playgroud)

这是model.rs

use diesel::Queryable;

#[derive(Queryable)]
pub struct NetWorthModel {
    pub fund_code: String,
    pub date: String,
    pub create_time: i64,
    pub update_time: i64,
    pub payload: String,
}
Run Code Online (Sandbox Code Playgroud)

这是schema.rs

use diesel::table;

table! {
    tb_net_worth(fund_code) …
Run Code Online (Sandbox Code Playgroud)

mysql orm rust rust-diesel

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

Rust Diesel 在多种条件下左连接

我很难从 Diesel 的文档中确定如何使用 Diesel 表达此查询(不使用raw_sql):

SELECT *
FROM budgets AS b 
LEFT JOIN user_budgets AS ub
ON (ub.budget_id = {budget_id} 
    AND ub.user_id = {user_id})
WHERE b.id = {budget_id}
LIMIT 1;
Run Code Online (Sandbox Code Playgroud)

{budget_id}并且{user_id}是可变的。这是我尝试过的:

let budget = budgets
    .select(budget_fields::all_columns)
    .left_join(user_budgets.on(user_budget_fields::budget_id.eq(budget_id)))
    .left_join(user_budget_fields::user_id.eq(user_id))
    .filter(budget_fields::id.eq(budget_id))
    .first::<Budget>(db_connection)?;
Run Code Online (Sandbox Code Playgroud)

但我收到此错误:

error[E0277]: the trait bound `budgets::table: JoinTo<diesel::expression::operators::Eq<user_budgets::columns::user_id, diesel::expression::bound::Bound<diesel::sql_types::Uuid, uuid::Uuid>>>` is not satisfied
  --> src/utils/db/budget.rs:46:10
   |
46 |         .left_join(user_budget_fields::user_id.eq(user_id))
   |          ^^^^^^^^^ the trait `JoinTo<diesel::expression::operators::Eq<user_budgets::columns::user_id, diesel::expression::bound::Bound<diesel::sql_types::Uuid, uuid::Uuid>>>` is not implemented for `budgets::table`
   |
   = help: the following …
Run Code Online (Sandbox Code Playgroud)

rust rust-diesel

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

错误:无法为 `syn` 选择版本

error: failed to select a version for `syn`. \
    ... required by package `serde_derive v1.0.125`\
    ... which satisfies dependency `serde_derive = "=1.0.125"` of package `serde v1.0.125`    
    ... which satisfies dependency `serde = "^1.0.125"` of package `mongodb v2.1.0`\
    ... which satisfies dependency `mongodb = "^2.1"` of package `wagmeet v0.1.0 
 \(/mnt/e/College/Eighth Semester/Crypto_Capable/wagmeet_app)`\
versions that meet the requirements `^1.0.60` are: 1.0.86, 1.0.85, 1.0.84, 1.0.83, 1.0.82, 1.0.81, 1.0.80, 1.0.79, 1.0.78, 1.0.77, 1.0.76, 1.0.75, 1.0.74, 1.0.73, 1.0.72, 1.0.71, 1.0.70, 1.0.69, 1.0.68, 1.0.67, 1.0.66, 1.0.65, 1.0.64, …
Run Code Online (Sandbox Code Playgroud)

rust rust-cargo rust-diesel rust-tokio nearprotocol

0
推荐指数
1
解决办法
4156
查看次数

使用 u128 的包装类型扩展 Diesel 时出错

我在尝试创建 Diesel 默认情况下未实现的自定义类型时遇到了以下代码的U128困难u128。我的目标是将原u128语作为文本格式或数字(最好是数字)存储在 Postgresql 数据库中。

use std::io::Write;
use diesel::{AsExpression, deserialize, FromSqlRow, serialize};
use diesel::deserialize::{FromSql};
use diesel::pg::{Pg};
use diesel::serialize::{IsNull, Output, ToSql};
use diesel::sql_types::{Text};

#[derive(AsExpression, FromSqlRow, Debug, Clone, Copy)]
#[diesel(sql_type = Text)]
pub struct U128(pub u128);

impl ToSql<Text, Pg> for U128 {
    fn to_sql<'b>(&self, out: &mut Output<'b, '_, Pg>) -> serialize::Result {
        write!(out, "{}", self.0.to_string())?;
        Ok(IsNull::No)
    }
}

impl FromSql<Text, Pg> for U128 {
    fn from_sql(bytes: Option<&[u8]>) -> deserialize::Result<Self> {
        let s = String::from_utf8_lossy(bytes.as_bytes());
        Ok(U128(s.parse()?))
    } …
Run Code Online (Sandbox Code Playgroud)

postgresql rust rust-diesel

0
推荐指数
1
解决办法
68
查看次数

Traitdiesel::Expression 未针对 NaiveDate 实现,但适用于 NaiveDateTime

我正在尝试用作chrono::NaiveDate数据库模型字段。这是模型:

\n
use chrono::{NaiveDate, NaiveDateTime};\nuse diesel::{Insertable, Queryable};\nuse serde::{Deserialize, Serialize};\n\nuse crate::schema::users;\n\n#[derive(Debug, Serialize, Deserialize, Associations, Identifiable, Queryable)]\n#[table_name = "users"]\npub struct User {\n    pub id: uuid::Uuid,\n    pub password_hash: String,\n    pub is_active: bool,\n\n    pub is_premium: bool,\n    pub premium_expiration: Option<NaiveDate>,\n\n    pub email: String,\n    pub first_name: String,\n    pub last_name: String,\n    pub date_of_birth: NaiveDate,\n    pub currency: String,\n\n    pub modified_timestamp: NaiveDateTime,\n    pub created_timestamp: NaiveDateTime,\n}\n\n#[derive(Debug, Insertable)]\n#[table_name = "users"]\npub struct NewUser<'a> {\n    pub id: uuid::Uuid,\n    pub password_hash: &'a str,\n    pub is_active: bool,\n\n    pub is_premium: bool,\n    pub premium_expiration: Option<NaiveDate>,\n\n …
Run Code Online (Sandbox Code Playgroud)

rust rust-cargo rust-chrono rust-diesel

-1
推荐指数
1
解决办法
2668
查看次数