我正在使用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: ¤cy,
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 编译器使用静态绑定并在编译时包含所有依赖库(因此可执行文件大小)。
但是,当我尝试在 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) 我正在尝试使用 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) 在编写测试时,我希望能够在请求中注入连接,以便我可以将整个测试用例包装在事务中(即使测试用例中有多个请求).
我尝试使用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) 我有以下两个功能:
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) 我正在使用 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。如何在请求保护之外访问我的连接池?
我需要在生产环境中为基于 Rocket 的应用程序运行 Diesel 数据库迁移。通常有几种方法可以为数据库执行迁移:
我更喜欢使用--migrate应用程序二进制文件的标志调用的第二个选项,但由于目标应用程序相当简单,第一种方法就可以了。
Diesel 问题跟踪器中有一个关于在生产中运行迁移的线程,并提供有关如何执行此操作的建议:
- 添加
diesel_migrations到您的依赖项- 包括
extern crate diesel_migrations在你的箱子,并确保与装饰它#[macro_use]- 在代码的开头,添加
embed_migrations!()- 要运行迁移,请使用
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) 这是我的工作环境:
这是项目的结构:
- 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) 我很难从 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) 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) 我在尝试创建 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) 我正在尝试用作chrono::NaiveDate数据库模型字段。这是模型:
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 ×12
rust-diesel ×12
mysql ×2
rust-cargo ×2
rust-rocket ×2
database ×1
generics ×1
iron ×1
nearprotocol ×1
orm ×1
postgresql ×1
rust-chrono ×1
rust-tokio ×1
traits ×1
types ×1