Skip to content

Commit 58bc554

Browse files
committed
Add SyncConnectionWrapper type around diesel::Connection
1 parent 8fa0ee1 commit 58bc554

File tree

10 files changed

+402
-3
lines changed

10 files changed

+402
-3
lines changed

Cargo.toml

+3
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ diesel_migrations = "2.1.0"
3838
default = []
3939
mysql = ["diesel/mysql_backend", "mysql_async", "mysql_common", "futures-channel", "tokio"]
4040
postgres = ["diesel/postgres_backend", "tokio-postgres", "tokio", "tokio/rt"]
41+
sqlite = ["diesel/sqlite", "sync-connection-wrapper"]
42+
sync-connection-wrapper = ["tokio/rt"]
4143
async-connection-wrapper = ["tokio/net"]
4244
r2d2 = ["diesel/r2d2"]
4345

@@ -57,6 +59,7 @@ members = [
5759
".",
5860
"examples/postgres/pooled-with-rustls",
5961
"examples/postgres/run-pending-migrations-with-rustls",
62+
"examples/sync-wrapper",
6063
]
6164

6265
[patch.crates-io]

examples/sync-wrapper/Cargo.toml

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
[package]
2+
name = "sync-wrapper"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7+
8+
[dependencies]
9+
diesel = { version = "2.1.0", default-features = false }
10+
diesel-async = { version = "0.4.0", path = "../../", features = ["sync-connection-wrapper", "async-connection-wrapper"] }
11+
diesel_migrations = "2.1.0"
12+
futures-util = "0.3.21"
13+
tokio = { version = "1.2.0", default-features = false, features = ["macros", "rt-multi-thread"] }
14+
15+
[features]
16+
default = ["sqlite"]
17+
sqlite = ["diesel-async/sqlite"]

examples/sync-wrapper/diesel.toml

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# For documentation on how to configure this file,
2+
# see https://diesel.rs/guides/configuring-diesel-cli
3+
4+
[print_schema]
5+
file = "src/schema.rs"
6+
custom_type_derives = ["diesel::query_builder::QueryId"]
7+
8+
[migrations_directory]
9+
dir = "migrations"

examples/sync-wrapper/migrations/.keep

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
DROP TABLE IF EXISTS users;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);
2+
3+
INSERT INTO users(id, name) VALUES(123, 'hello world');

examples/sync-wrapper/src/main.rs

+88
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
use diesel::prelude::*;
2+
use diesel::sqlite::{Sqlite, SqliteConnection};
3+
use diesel_async::async_connection_wrapper::AsyncConnectionWrapper;
4+
use diesel_async::sync_connection_wrapper::SyncConnectionWrapper;
5+
use diesel_async::{AsyncConnection, RunQueryDsl, SimpleAsyncConnection};
6+
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
7+
8+
// ordinary diesel model setup
9+
10+
table! {
11+
users {
12+
id -> Integer,
13+
name -> Text,
14+
}
15+
}
16+
17+
#[derive(Debug, Queryable, Selectable)]
18+
#[diesel(table_name = users)]
19+
struct User {
20+
id: i32,
21+
name: String,
22+
}
23+
24+
const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
25+
26+
type InnerConnection = SqliteConnection;
27+
28+
type InnerDB = Sqlite;
29+
30+
async fn establish(db_url: &str) -> ConnectionResult<SyncConnectionWrapper<InnerConnection>> {
31+
SyncConnectionWrapper::<SqliteConnection>::establish(db_url).await
32+
}
33+
34+
async fn run_migrations<A>(async_connection: A) -> Result<(), Box<dyn std::error::Error>>
35+
where
36+
A: AsyncConnection<Backend = InnerDB> + 'static,
37+
{
38+
let mut async_wrapper: AsyncConnectionWrapper<A> =
39+
AsyncConnectionWrapper::from(async_connection);
40+
41+
tokio::task::spawn_blocking(move || {
42+
async_wrapper.run_pending_migrations(MIGRATIONS).unwrap();
43+
})
44+
.await
45+
.map_err(|e| Box::new(e) as Box<dyn std::error::Error>)
46+
}
47+
48+
#[tokio::main]
49+
async fn main() -> Result<(), Box<dyn std::error::Error>> {
50+
let db_url = std::env::var("DATABASE_URL").expect("Env var `DATABASE_URL` not set");
51+
52+
// create an async connection for the migrations
53+
let sync_wrapper: SyncConnectionWrapper<InnerConnection> = establish(&db_url).await?;
54+
run_migrations(sync_wrapper).await?;
55+
56+
let mut sync_wrapper: SyncConnectionWrapper<InnerConnection> = establish(&db_url).await?;
57+
58+
sync_wrapper.batch_execute("DELETE FROM users").await?;
59+
60+
sync_wrapper
61+
.batch_execute("INSERT INTO users(id, name) VALUES (3, 'toto')")
62+
.await?;
63+
64+
let data: Vec<User> = users::table
65+
.select(User::as_select())
66+
.load(&mut sync_wrapper)
67+
.await?;
68+
println!("{data:?}");
69+
70+
diesel::delete(users::table)
71+
.execute(&mut sync_wrapper)
72+
.await?;
73+
74+
diesel::insert_into(users::table)
75+
.values((users::id.eq(1), users::name.eq("iLuke")))
76+
.execute(&mut sync_wrapper)
77+
.await?;
78+
79+
let data: Vec<User> = users::table
80+
.filter(users::id.gt(0))
81+
.or_filter(users::name.like("%Luke"))
82+
.select(User::as_select())
83+
.load(&mut sync_wrapper)
84+
.await?;
85+
println!("{data:?}");
86+
87+
Ok(())
88+
}

src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,8 @@ pub mod pg;
9393
pub mod pooled_connection;
9494
mod run_query_dsl;
9595
mod stmt_cache;
96+
#[cfg(feature = "sync-connection-wrapper")]
97+
pub mod sync_connection_wrapper;
9698
mod transaction_manager;
9799

98100
#[cfg(feature = "mysql")]

0 commit comments

Comments
 (0)