我有一个 Postgres 表,其中包含三个字段
id,即 a bigserial、metaajsonb字段和 uuidUUID字段。
pub struct MetaLogs {
pub id:i64,
pub uuid: <what type should I give here >
pub meta: < What type should I give here >
}
Run Code Online (Sandbox Code Playgroud)
我正在使用sqlxORM 进行Rust. 虽然我明白我必须添加
features = [ "runtime-tokio", "macros" ,"postgres","json","uuid"]
Run Code Online (Sandbox Code Playgroud)
我不知道之后如何继续
我在测试中使用了一些https://github.com/launchbadge/sqlx query!宏,并且我需要能够运行cargo sqlx prepare它们,以便我的 IDE 可以扩展宏并提供类型信息(自动完成等)。
但如果我只是运行cargo sqlx prepare,所有后面的代码#[cfg(test)]都会被忽略。
我如何告诉 Cargo/sqlx 也分析我的测试?
我正在使用 Rust 从零到产品,但我有点脱离了脚本。我正在努力在本地对整个设置进行 docker 化,包括数据库。在ENTRYPOINT容器上调用一个启动脚本,该脚本尝试调用sqlx migrate run,导致错误./scripts/init_db.sh: line 10: sqlx: command not found。
我想我已经解决了这个问题,因为我使用的bullseye-slim是运行时,所以它不会为最终映像保留已安装的 Rust 包,这有助于缩短构建时间和映像大小。
有没有一种方法可以在不安装 Rust、Cargo 等的情况下运行 sqlx 迁移?或者有更好的方法来完成这个任务吗?我想避免只是重新安装bullseye-slim映像中的所有内容并丢失一些 docker 优化。
# Dockerfile
# .... chef segment omitted
FROM chef as builder
COPY --from=planner /app/recipe.json recipe.json
# Build our project dependencies, not our application!
RUN cargo chef cook --release --recipe-path recipe.json
# Up to this point, if our dependency tree stays the same,
# all layers should be …Run Code Online (Sandbox Code Playgroud) 我有一个查询将用户的数据插入数据库。它工作正常,但该users表在 上有一个唯一索引username,因此当尝试创建用户名已存在的行时,它会抛出错误:
pub async fn create(user: UserRequest, pool: &PgPool) -> anyhow::Result<User> {
let new_user = sqlx::query_as!(
User,
r#"
INSERT INTO users (first_name, username)
VALUES ($1, $2)
RETURNING id, first_name, username
"#,
&user.first_name,
&user.username,
)
.fetch_one(&pool.clone())
.await?;
Ok(User {
id: new_user.id,
first_name: new_user.first_name,
username: new_user.username,
})
}
Run Code Online (Sandbox Code Playgroud)
&user是一个函数参数,定义为:
pub struct UserRequest {
pub first_name: String,
pub username: String,
}
Run Code Online (Sandbox Code Playgroud)
使用此函数的端点用于match检查它是否是Ok(user)或其他任何内容,并返回其响应:
pub async fn create_user(
user: web::Json<UserRequest>,
pool: Data<PgPool>,
) -> impl Responder …Run Code Online (Sandbox Code Playgroud) 我想将数据polars从mysql数据库读入数据帧。我在用sqlx。
sqlx生成结构向量,例如:Vec<Country>如下:
来自sqlx 文档:
// no traits are needed
struct Country { country: String, count: i64 }
let countries = sqlx::query_as!(Country,
"
SELECT country, COUNT(*) as count
FROM users
GROUP BY country
WHERE organization = ?
",
organization
)
.fetch_all(&pool) // -> Vec<Country>
.await?;
// countries[0].country
// countries[0].count
Run Code Online (Sandbox Code Playgroud)
我如何使用它Vec<Country>来生成极坐标数据框
来自polars 文档:
use polars_core::prelude::*;
let s0 = Series::new("a", &[1i64, 2, 3]);
let s1 = Series::new("b", …Run Code Online (Sandbox Code Playgroud) 我有两种 Rust 方法,根据两个不同的参数从同一个 SQLite 表中使用 sqlx 选择数据。
由于错误,我无法让两者都工作expected `i64`, found enum `std::option::Option` 。
代码
// src/main.rs
use tokio;
use anyhow::Result;
use sqlx::sqlite::SqlitePool;
// The model `StorageName` that I'm retrieving is something like
pub struct StorageName {
pub _id: i64,
pub name: String,
pub url: String,
}
// This compiles only if `_id` is `Option<i64>`
async fn queryByName(pool: &SqlitePool, name: String) -> Result<Vec<StorageName>> {
let results = sqlx::query_as!(
StorageName,
"SELECT * FROM names
WHERE name = ?;",
name,
)
.fetch_all(pool) …Run Code Online (Sandbox Code Playgroud) 我有一个关于将数据结构插入数据库的问题,但我似乎找不到任何相关文档。
我有一个数据结构
#[derive(FromRow, Getters, Default, Serialize, Deserialize, Debug)]
#[serde(crate = "rocket::serde")]
#[getset(get = "pub")]
pub struct RefreshKeys {
id: i64,
customer_id: i64,
key: String,
enabled: bool,
}
Run Code Online (Sandbox Code Playgroud)
我想将其插入到具有相同字段的数据库中,称为refresh_keys.
rocket_db_pools::sqlx::query_as::<_, RefreshKeys>(
"INSERT INTO refresh_keys (id, customer_id, key, enabled)
VALUES (?1, ?2, ?3, ?4)"
)
.fetch_one(&mut *db)
.await?
Run Code Online (Sandbox Code Playgroud)
遗憾的是,这似乎不起作用,我收到以下错误:
SqliteError { code: 1299, message: "NOT NULL constraint failed: refresh_keys.customer_id" }
Run Code Online (Sandbox Code Playgroud)
我已经尝试了几个小时来查找相关文档,但我什么也没找到。
提前致谢!
我正在开发一个用 Rust 编写的 REST API,使用 actix-web、SQLx 和 PostgreSQL 进行存储。假设这是我的模式(表示为 Rust 结构):
struct User {
pub id: Uuid,
pub email: String
// And so on...
}
struct Customer {
pub id: Uuid,
pub user_id: Uuid,
pub name: String,
// And so on...
}
Run Code Online (Sandbox Code Playgroud)
我当前的目标是实现一个端点,该端点返回所有用户及其嵌套的客户。即像这样:
// GET /users
// Response from endpoint
[{
"id": "uuid-1",
"email": "test@test.com",
"customers": [{
"id": "uuid-customer-1",
"name": "Customer 1"
}, {
"id": "uuid-customer-2",
"name": "Customer 2"
}]
}]
Run Code Online (Sandbox Code Playgroud)
上面的有效负载可以使用以下结构来表示:
#[derive(Serialize)]
struct CustomerData {
pub id: Uuid,
pub …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用actix-web和sqlx设置一个 Web 应用程序,我可以在其中进行具有自己的 Web 服务器和数据库事务的测试。我尝试设置我的服务器创建,以便它接受数据库(Postgres)池或使用Executor特征的事务。虽然我在编译应用程序代码和测试时遇到了一些问题:
// main.rs
use std::net::TcpListener;
use actix_web::dev::Server;
use actix_web::{web, App, HttpServer, Responder};
use sqlx::PgPool;
async fn create_pool() -> PgPool {
PgPool::connect("postgres://postgres:postgres@localhost:5432/postgres")
.await
.expect("Failed to create pool")
}
async fn index() -> impl Responder {
"Hello World!"
}
pub fn create_server<'a, E: 'static>(
listener: TcpListener,
pool: E,
) -> Result<Server, std::io::Error>
where
E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy,
{
let server = HttpServer::new(move || App::new().data(pool).route("/", web::get().to(index)))
.listen(listener)?
.run();
Ok(server)
} …Run Code Online (Sandbox Code Playgroud) 一个 Rust 新手,尝试通过结合来编写一个 Web 服务
https://github.com/seanmonstar/warp/blob/master/examples/todos.rs和https://github.com/launchbadge/sqlx/blob/master/examples/postgres/todos/src/main.rs
以下代码处于运行状态。我的问题是,我是否需要为每个处理程序克隆 dbpool?Rust 中的惯用方式是什么(我来自 Java/Kotlin->Go 背景,FWIW)
#![deny(warnings)]
use sqlx::postgres::{PgPoolOptions};
use std::env;
use warp::Filter;
#[tokio::main]
async fn main() -> Result<(), sqlx::Error> {
let pool = PgPoolOptions::new()
.max_connections(5)
.connect("postgres://:@localhost/todo_db").await?;
if env::var_os("RUST_LOG").is_none() {
env::set_var("RUST_LOG", "todos=info");
}
pretty_env_logger::init();
let api = filters::todos(pool);
let routes = api.with(warp::log("todos"));
// Start up the server...
warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
Ok(())
}
mod filters {
use sqlx::{Pool, Postgres};
use super::handlers;
use super::models::{ListOptions, Todo};
use warp::Filter;
pub fn todos(
db: Pool<Postgres>,
) …Run Code Online (Sandbox Code Playgroud) 我将从这个示例开始学习如何将 Axum 与 SQLx 结合使用。基本示例有效,但我在尝试继续前进时遇到问题。我正在使用一个简单的数据库表,如下所示:
todo | description
--------+--------------
todo_1 | doing todo 1
todo_2 | doing todo 2
todo_3 | doing todo 3
Run Code Online (Sandbox Code Playgroud)
我试图简单地返回“SELECT * FROM todos”,但出现错误。我认为我返回的类型是Result错误的,但我不知道下一步该怎么做。全文main.rs如下所示。
//! Example of application using <https://github.com/launchbadge/sqlx>
//!
//! Run with
//!
//! ```not_rust
//! cd examples && cargo run -p example-sqlx-postgres
//! ```
//!
//! Test with curl:
//!
//! ```not_rust
//! curl 127.0.0.1:3000
//! curl -X POST 127.0.0.1:3000
//! ```
use axum::{
async_trait,
extract::{Extension, FromRequest, …Run Code Online (Sandbox Code Playgroud) rust ×11
rust-sqlx ×11
actix-web ×2
sql ×2
dataframe ×1
docker ×1
lifetime ×1
postgresql ×1
rust-axum ×1
rust-cargo ×1
rust-polars ×1
rust-rocket ×1
rust-warp ×1
sqlite ×1
types ×1