Skip to content

Commit 0db4bde

Browse files
Randolf J.claude
andauthored
feat: support PoolConnection via AsExecutor trait (#4)
## Summary - Replaces the `for<'c> &'c mut E: sqlx::Executor<'c, Database = Postgres>` bound on `Queries<E>` with a generated `AsExecutor` trait. - `AsExecutor` has impls for `PgPool`, `&PgPool`, `PgConnection`, `Transaction<'_, Postgres>`, `PoolConnection<Postgres>`, and `&mut T` — covering all eight call shapes (owned + `&mut`). - Fixes a latent bug: the README previously claimed `Queries::new(&pool)` and `Queries::new(&mut tx)` worked, but neither actually type-checked against the old bound. Only `Queries::new(conn)` with owned `PgConnection` did. - Also fixes broken `enums` and `batch` example mains that didn't match the current codegen (struct params / stream returns). ## Why the previous bound failed sqlx has a commented-out `impl Executor for &mut PoolConnection<DB>` in `sqlx-core/src/pool/executor.rs` citing trait-resolver overflow in the generic blanket form. `AsExecutor` sidesteps that by providing concrete per-type impls that yield `&mut PgConnection` directly. ## Test plan - [x] `cargo fmt --all --check` - [x] `cargo clippy --workspace --all-targets -- -D warnings` - [x] `cargo test --workspace` (snapshots; integration tests require DATABASE_URL) - [x] `cargo build --target wasm32-wasip1` - [x] e2e test (testcontainers Postgres) — compiles and runs generated code for all annotation types 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 88ce606 commit 0db4bde

33 files changed

Lines changed: 1248 additions & 205 deletions

‎Cargo.lock‎

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎README.md‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,18 @@ For each SQL query annotated with a sqlc command, the plugin emits:
1111
- An optional params struct (`QueryNameParams`) when a query has 2+ parameters.
1212
- A `&mut self` method on `pub struct Queries<E>` that executes the query.
1313

14-
`Queries<E>` wraps an executor once at construction. Pass `&pool` for pool usage or `&mut tx` for transactions:
14+
`Queries<E>` wraps anything implementing the generated `AsExecutor` trait. `AsExecutor` is implemented for `PgPool`, `&PgPool`, `PgConnection`, `Transaction<'_, Postgres>`, `PoolConnection<Postgres>`, and `&mut T` of each:
1515

1616
```rust
17+
// From a pool:
1718
let mut q = Queries::new(&pool);
1819
let author = q.get_author(1).await?;
1920

21+
// Borrowed or owned pool connection:
22+
let mut conn = pool.acquire().await?;
23+
let mut q = Queries::new(&mut conn);
24+
// ...or Queries::new(conn) to take ownership.
25+
2026
// Transactions:
2127
let mut tx = pool.begin().await?;
2228
let mut q = Queries::new(&mut tx);
@@ -126,7 +132,7 @@ Array types (`type[]`) become `Vec<T>`. Nullable columns become `Option<T>`.
126132
| `:batchmany` | `impl Stream<Item = Result<Vec<QueryRow>, sqlx::Error>>` | Lazily fetch all rows per item |
127133
| `:copyfrom` | `Result<u64, sqlx::Error>` | Chunked bulk insert from any `IntoIterator` |
128134

129-
All functions are `&mut self` methods on `Queries<E>`. The bound `for<'c> &'c mut E: sqlx::Executor<'c, Database = sqlx::Postgres>` is satisfied by `&PgPool`, `&mut PgConnection`, and `&mut Transaction<'_, Postgres>`.
135+
All functions are `&mut self` methods on `Queries<E>`. The bound is `E: AsExecutor`, where `AsExecutor` is the trait emitted in each generated file. Impls cover `PgPool`, `&PgPool`, `PgConnection`, `Transaction<'_, Postgres>`, `PoolConnection<Postgres>`, and `&mut T` of each.
130136

131137
Batch methods generate `Stream`-returning APIs and reference `futures_core` and `futures_util` directly. Consumer crates should include those dependencies alongside `sqlx`.
132138

Lines changed: 65 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,105 @@
1-
// Code generated by sqlc-gen-sqlx. DO NOT EDIT.
1+
// Code generated by sqlc-gen-sqlx v0.1.0. DO NOT EDIT.
2+
// sqlc version: v1.30.0
23

34
#![allow(
45
dead_code,
56
reason = "generated queries may expose items a caller does not use"
67
)]
78

89
const GET_EVENT: &str = "SELECT id, name, flags, event_window FROM events WHERE id = $1";
9-
1010
#[derive(Debug, Clone, sqlx::FromRow)]
1111
pub struct GetEventRow {
1212
pub id: i64,
1313
pub name: String,
1414
pub flags: bit_vec::BitVec,
1515
pub event_window: sqlx::postgres::types::PgRange<chrono::DateTime<chrono::Utc>>,
1616
}
17-
1817
const LIST_EVENTS: &str = "SELECT id, name, flags, event_window FROM events";
19-
2018
#[derive(Debug, Clone, sqlx::FromRow)]
2119
pub struct ListEventsRow {
2220
pub id: i64,
2321
pub name: String,
2422
pub flags: bit_vec::BitVec,
2523
pub event_window: sqlx::postgres::types::PgRange<chrono::DateTime<chrono::Utc>>,
2624
}
27-
25+
pub trait AsExecutor {
26+
type Exec<'c>: sqlx::Executor<'c, Database = sqlx::Postgres>
27+
where
28+
Self: 'c;
29+
fn as_executor(&mut self) -> Self::Exec<'_>;
30+
}
31+
impl AsExecutor for sqlx::PgPool {
32+
type Exec<'c>
33+
= &'c sqlx::PgPool
34+
where
35+
Self: 'c;
36+
fn as_executor(&mut self) -> Self::Exec<'_> {
37+
&*self
38+
}
39+
}
40+
impl AsExecutor for &sqlx::PgPool {
41+
type Exec<'c>
42+
= &'c sqlx::PgPool
43+
where
44+
Self: 'c;
45+
fn as_executor(&mut self) -> Self::Exec<'_> {
46+
*self
47+
}
48+
}
49+
impl AsExecutor for sqlx::PgConnection {
50+
type Exec<'c>
51+
= &'c mut sqlx::PgConnection
52+
where
53+
Self: 'c;
54+
fn as_executor(&mut self) -> Self::Exec<'_> {
55+
self
56+
}
57+
}
58+
impl AsExecutor for sqlx::Transaction<'_, sqlx::Postgres> {
59+
type Exec<'c>
60+
= &'c mut sqlx::PgConnection
61+
where
62+
Self: 'c;
63+
fn as_executor(&mut self) -> Self::Exec<'_> {
64+
&mut **self
65+
}
66+
}
67+
impl AsExecutor for sqlx::pool::PoolConnection<sqlx::Postgres> {
68+
type Exec<'c>
69+
= &'c mut sqlx::PgConnection
70+
where
71+
Self: 'c;
72+
fn as_executor(&mut self) -> Self::Exec<'_> {
73+
&mut **self
74+
}
75+
}
76+
impl<T: AsExecutor + ?Sized> AsExecutor for &mut T {
77+
type Exec<'c>
78+
= T::Exec<'c>
79+
where
80+
Self: 'c;
81+
fn as_executor(&mut self) -> Self::Exec<'_> {
82+
(**self).as_executor()
83+
}
84+
}
2885
pub struct Queries<E> {
2986
db: E,
3087
}
31-
3288
impl<E> Queries<E> {
3389
pub fn new(db: E) -> Self {
3490
Self { db }
3591
}
3692
}
37-
38-
impl<E> Queries<E>
39-
where
40-
for<'c> &'c mut E: sqlx::Executor<'c, Database = sqlx::Postgres>,
41-
{
93+
impl<E: AsExecutor> Queries<E> {
4294
pub async fn get_event(&mut self, id: i64) -> Result<GetEventRow, sqlx::Error> {
4395
sqlx::query_as::<_, GetEventRow>(GET_EVENT)
4496
.bind(id)
45-
.fetch_one(&mut self.db)
97+
.fetch_one(self.db.as_executor())
4698
.await
4799
}
48-
49100
pub async fn list_events(&mut self) -> Result<Vec<ListEventsRow>, sqlx::Error> {
50101
sqlx::query_as::<_, ListEventsRow>(LIST_EVENTS)
51-
.fetch_all(&mut self.db)
102+
.fetch_all(self.db.as_executor())
52103
.await
53104
}
54105
}

‎examples/basic/src/queries.rs‎

Lines changed: 66 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,66 @@ pub struct CreateAuthorRow {
3535
}
3636
const DELETE_AUTHOR: &str = "DELETE FROM authors WHERE id = $1";
3737
const DELETE_AUTHOR_ROWS: &str = "DELETE FROM authors WHERE id = $1";
38+
pub trait AsExecutor {
39+
type Exec<'c>: sqlx::Executor<'c, Database = sqlx::Postgres>
40+
where
41+
Self: 'c;
42+
fn as_executor(&mut self) -> Self::Exec<'_>;
43+
}
44+
impl AsExecutor for sqlx::PgPool {
45+
type Exec<'c>
46+
= &'c sqlx::PgPool
47+
where
48+
Self: 'c;
49+
fn as_executor(&mut self) -> Self::Exec<'_> {
50+
&*self
51+
}
52+
}
53+
impl AsExecutor for &sqlx::PgPool {
54+
type Exec<'c>
55+
= &'c sqlx::PgPool
56+
where
57+
Self: 'c;
58+
fn as_executor(&mut self) -> Self::Exec<'_> {
59+
*self
60+
}
61+
}
62+
impl AsExecutor for sqlx::PgConnection {
63+
type Exec<'c>
64+
= &'c mut sqlx::PgConnection
65+
where
66+
Self: 'c;
67+
fn as_executor(&mut self) -> Self::Exec<'_> {
68+
self
69+
}
70+
}
71+
impl AsExecutor for sqlx::Transaction<'_, sqlx::Postgres> {
72+
type Exec<'c>
73+
= &'c mut sqlx::PgConnection
74+
where
75+
Self: 'c;
76+
fn as_executor(&mut self) -> Self::Exec<'_> {
77+
&mut **self
78+
}
79+
}
80+
impl AsExecutor for sqlx::pool::PoolConnection<sqlx::Postgres> {
81+
type Exec<'c>
82+
= &'c mut sqlx::PgConnection
83+
where
84+
Self: 'c;
85+
fn as_executor(&mut self) -> Self::Exec<'_> {
86+
&mut **self
87+
}
88+
}
89+
impl<T: AsExecutor + ?Sized> AsExecutor for &mut T {
90+
type Exec<'c>
91+
= T::Exec<'c>
92+
where
93+
Self: 'c;
94+
fn as_executor(&mut self) -> Self::Exec<'_> {
95+
(**self).as_executor()
96+
}
97+
}
3898
pub struct Queries<E> {
3999
db: E,
40100
}
@@ -43,19 +103,16 @@ impl<E> Queries<E> {
43103
Self { db }
44104
}
45105
}
46-
impl<E> Queries<E>
47-
where
48-
for<'c> &'c mut E: sqlx::Executor<'c, Database = sqlx::Postgres>,
49-
{
106+
impl<E: AsExecutor> Queries<E> {
50107
pub async fn get_author(&mut self, id: i64) -> Result<GetAuthorRow, sqlx::Error> {
51108
sqlx::query_as::<_, GetAuthorRow>(GET_AUTHOR)
52109
.bind(id)
53-
.fetch_one(&mut self.db)
110+
.fetch_one(self.db.as_executor())
54111
.await
55112
}
56113
pub async fn list_authors(&mut self) -> Result<Vec<ListAuthorsRow>, sqlx::Error> {
57114
sqlx::query_as::<_, ListAuthorsRow>(LIST_AUTHORS)
58-
.fetch_all(&mut self.db)
115+
.fetch_all(self.db.as_executor())
59116
.await
60117
}
61118
pub async fn create_author(
@@ -65,20 +122,20 @@ where
65122
sqlx::query_as::<_, CreateAuthorRow>(CREATE_AUTHOR)
66123
.bind(arg.name)
67124
.bind(arg.bio)
68-
.fetch_one(&mut self.db)
125+
.fetch_one(self.db.as_executor())
69126
.await
70127
}
71128
pub async fn delete_author(&mut self, id: i64) -> Result<(), sqlx::Error> {
72129
sqlx::query(DELETE_AUTHOR)
73130
.bind(id)
74-
.execute(&mut self.db)
131+
.execute(self.db.as_executor())
75132
.await?;
76133
Ok(())
77134
}
78135
pub async fn delete_author_rows(&mut self, id: i64) -> Result<u64, sqlx::Error> {
79136
let result = sqlx::query(DELETE_AUTHOR_ROWS)
80137
.bind(id)
81-
.execute(&mut self.db)
138+
.execute(self.db.as_executor())
82139
.await?;
83140
Ok(result.rows_affected())
84141
}

‎examples/batch/Cargo.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,5 @@ edition = "2024"
66
[dependencies]
77
sqlx = { workspace = true }
88
tokio = { workspace = true }
9+
futures-core = "0.3"
10+
futures-util = "0.3"

‎examples/batch/src/main.rs‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
#[path = "queries.rs"]
33
mod queries;
44
#[cfg(test)]
5+
use futures_util::TryStreamExt;
6+
#[cfg(test)]
57
use queries::Queries;
68
#[cfg(test)]
79
use sqlx::{Connection as _, PgConnection};
@@ -34,12 +36,18 @@ async fn test_batch_roundtrip() {
3436

3537
let mut q = Queries::new(conn);
3638

37-
let authors = q.batch_get_author(vec![1, 2]).await.expect("batch get");
39+
let authors: Vec<_> = q
40+
.batch_get_author(vec![1, 2])
41+
.try_collect()
42+
.await
43+
.expect("batch get");
3844
assert_eq!(authors.len(), 2);
3945
assert_eq!(authors[0].name, "Alice");
4046
assert_eq!(authors[1].name, "Bob");
4147

42-
q.batch_delete_author(vec![1, 2])
48+
let _: Vec<()> = q
49+
.batch_delete_author(vec![1, 2])
50+
.try_collect()
4351
.await
4452
.expect("batch delete");
4553

0 commit comments

Comments
 (0)