1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
//! `QuerySetTx` — a QuerySet bound to an open transaction.
//!
//! Construction happens in [`super::QuerySet::on_tx`] /
//! [`super::Manager::on_tx`] using struct-literal syntax against the
//! `pub(super)` fields. All terminals here mirror their plain-QuerySet
//! siblings but route their SQL through the borrowed
//! [`crate::db::Transaction`] so the operations commit or roll back
//! as a unit with every other operation in the same
//! `umbral::db::transaction(...)` closure.
//!
//! The struct borrows `&mut Transaction` so the borrow checker
//! enforces that only one `QuerySetTx` uses the transaction at a
//! time, and that the transaction stays alive for the duration of
//! each terminal call.
use sea_query::{Expr, Func, PostgresQueryBuilder, SqliteQueryBuilder};
use sea_query_binder::SqlxBinder;
use crate::orm::{HydrateRelated, Model};
use super::QuerySet;
use super::errors::GetError;
use super::write_helpers::{build_insert_one_for, pk_field, serialize_to_map};
/// A `QuerySet` bound to an open transaction. See module docs for
/// the construction sites and the borrow-checker contract.
pub struct QuerySetTx<'tx, T> {
pub(super) qs: QuerySet<T>,
pub(super) tx: &'tx mut crate::db::Transaction,
}
impl<'tx, T: Model> QuerySetTx<'tx, T> {
// -----------------------------------------------------------------------
// Read terminals
// -----------------------------------------------------------------------
/// SELECT all matching rows inside the transaction.
pub async fn fetch(self) -> Result<Vec<T>, sqlx::Error>
where
T: for<'r> sqlx::FromRow<'r, sqlx::sqlite::SqliteRow>
+ for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow>
+ HydrateRelated,
{
let q = self.qs.build_query_for(self.tx.backend_name());
let mut rows = match self.tx.backend_name() {
"sqlite" => {
let tx = self.tx.as_sqlite_mut().unwrap();
let (sql, values) = q.build_sqlx(SqliteQueryBuilder);
sqlx::query_as_with::<sqlx::Sqlite, T, _>(&sql, values)
.fetch_all(&mut **tx)
.await?
}
_ => {
let tx = self.tx.as_pg_mut().unwrap();
let (sql, values) = q.build_sqlx(PostgresQueryBuilder);
sqlx::query_as_with::<sqlx::Postgres, T, _>(&sql, values)
.fetch_all(&mut **tx)
.await?
}
};
// BUG-16 step 2: wire each row's PK into its M2M slots so
// junction-table accessors used inside the transaction see
// the right parent.
for r in &mut rows {
r.set_m2m_parent_ids();
}
Ok(rows)
}
/// SELECT LIMIT 1 and return the first row, if any.
pub async fn first(mut self) -> Result<Option<T>, sqlx::Error>
where
T: for<'r> sqlx::FromRow<'r, sqlx::sqlite::SqliteRow>
+ for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow>
+ HydrateRelated,
{
self.qs.query.limit(1);
let q = self.qs.build_query_for(self.tx.backend_name());
let mut row = match self.tx.backend_name() {
"sqlite" => {
let tx = self.tx.as_sqlite_mut().unwrap();
let (sql, values) = q.build_sqlx(SqliteQueryBuilder);
sqlx::query_as_with::<sqlx::Sqlite, T, _>(&sql, values)
.fetch_optional(&mut **tx)
.await?
}
_ => {
let tx = self.tx.as_pg_mut().unwrap();
let (sql, values) = q.build_sqlx(PostgresQueryBuilder);
sqlx::query_as_with::<sqlx::Postgres, T, _>(&sql, values)
.fetch_optional(&mut **tx)
.await?
}
};
if let Some(r) = row.as_mut() {
r.set_m2m_parent_ids();
}
Ok(row)
}
/// SELECT COUNT(*) inside the transaction.
pub async fn count(self) -> Result<i64, sqlx::Error> {
let backend = self.tx.backend_name();
let mut rebuilt = self.qs.build_query_for(backend);
rebuilt.clear_selects();
// `sea_query::Asterisk` renders the bare SQL `*` token; `Alias::new("*")`
// would render `COUNT("*")` — a quoted identifier Postgres reads as a
// column named `*`. Matches the non-transactional count path.
rebuilt.expr(Func::count(Expr::col(sea_query::Asterisk)));
rebuilt.reset_limit();
rebuilt.reset_offset();
match backend {
"sqlite" => {
let tx = self.tx.as_sqlite_mut().unwrap();
let (sql, values) = rebuilt.build_sqlx(SqliteQueryBuilder);
let (n,): (i64,) = sqlx::query_as_with::<sqlx::Sqlite, (i64,), _>(&sql, values)
.fetch_one(&mut **tx)
.await?;
Ok(n)
}
_ => {
let tx = self.tx.as_pg_mut().unwrap();
let (sql, values) = rebuilt.build_sqlx(PostgresQueryBuilder);
let (n,): (i64,) = sqlx::query_as_with::<sqlx::Postgres, (i64,), _>(&sql, values)
.fetch_one(&mut **tx)
.await?;
Ok(n)
}
}
}
/// Return whether any row matches, inside the transaction.
pub async fn exists(mut self) -> Result<bool, sqlx::Error>
where
T: for<'r> sqlx::FromRow<'r, sqlx::sqlite::SqliteRow>
+ for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow>,
{
self.qs.query.limit(1);
let backend = self.tx.backend_name();
let q = self.qs.build_query_for(backend);
let row_opt: Option<T> = match backend {
"sqlite" => {
let tx = self.tx.as_sqlite_mut().unwrap();
let (sql, values) = q.build_sqlx(SqliteQueryBuilder);
sqlx::query_as_with::<sqlx::Sqlite, T, _>(&sql, values)
.fetch_optional(&mut **tx)
.await?
}
_ => {
let tx = self.tx.as_pg_mut().unwrap();
let (sql, values) = q.build_sqlx(PostgresQueryBuilder);
sqlx::query_as_with::<sqlx::Postgres, T, _>(&sql, values)
.fetch_optional(&mut **tx)
.await?
}
};
Ok(row_opt.is_some())
}
/// Exactly-one terminal inside the transaction. See [`super::QuerySet::get`].
pub async fn get(mut self) -> Result<T, GetError>
where
T: for<'r> sqlx::FromRow<'r, sqlx::sqlite::SqliteRow>
+ for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow>,
{
self.qs.query.limit(2);
let q = self.qs.build_query_for(self.tx.backend_name());
let mut rows: Vec<T> = match self.tx.backend_name() {
"sqlite" => {
let tx = self.tx.as_sqlite_mut().unwrap();
let (sql, values) = q.build_sqlx(SqliteQueryBuilder);
sqlx::query_as_with::<sqlx::Sqlite, T, _>(&sql, values)
.fetch_all(&mut **tx)
.await
.map_err(GetError::Sqlx)?
}
_ => {
let tx = self.tx.as_pg_mut().unwrap();
let (sql, values) = q.build_sqlx(PostgresQueryBuilder);
sqlx::query_as_with::<sqlx::Postgres, T, _>(&sql, values)
.fetch_all(&mut **tx)
.await
.map_err(GetError::Sqlx)?
}
};
match rows.len() {
0 => Err(GetError::NotFound),
1 => Ok(rows.pop().unwrap()),
_ => Err(GetError::MultipleObjectsReturned),
}
}
// -----------------------------------------------------------------------
// Write terminals
// -----------------------------------------------------------------------
/// DELETE inside the transaction. Returns the number of rows deleted.
///
/// On a `#[umbral(soft_delete)]` model this rewrites to
/// `UPDATE ... SET deleted_at = NOW()` (plus the on_delete=cascade
/// soft-cascade), exactly like the non-transactional `QuerySet::delete`
/// — otherwise a `.delete()` that happened to run inside `on_tx()` would
/// permanently destroy rows the caller expected to be recoverable.
/// `.hard_delete()` opts back into a real DELETE.
pub async fn delete(self) -> Result<u64, sqlx::Error> {
if self.qs.soft_delete_active && !self.qs.hard_delete {
return self.soft_delete_in_tx().await;
}
let stmt = self.qs.build_delete_for(self.tx.backend_name());
match self.tx.backend_name() {
"sqlite" => {
let tx = self.tx.as_sqlite_mut().unwrap();
let (sql, values) = stmt.build_sqlx(SqliteQueryBuilder);
let result = sqlx::query_with::<sqlx::Sqlite, _>(&sql, values)
.execute(&mut **tx)
.await?;
Ok(result.rows_affected())
}
_ => {
let tx = self.tx.as_pg_mut().unwrap();
let (sql, values) = stmt.build_sqlx(PostgresQueryBuilder);
let result = sqlx::query_with::<sqlx::Postgres, _>(&sql, values)
.execute(&mut **tx)
.await?;
Ok(result.rows_affected())
}
}
}
/// The soft-delete rewrite of [`Self::delete`], run inside the caller's
/// transaction: cascade to any `on_delete = "cascade"` children, then
/// stamp `deleted_at = NOW()` on the matched live rows (idempotent —
/// never re-stamps an already soft-deleted row). Mirrors
/// `QuerySet::soft_delete_update`, minus the private tx it opens.
async fn soft_delete_in_tx(self) -> Result<u64, sqlx::Error> {
use sea_query::{Alias, Query, Value};
let backend = self.tx.backend_name();
let now = chrono::Utc::now();
let table = crate::db::router::schema_qualified_table(T::TABLE);
// Cascade first — locate children through the parent's still-live
// predicate before the parent is stamped, so no orphaned live child
// is left behind.
if let Some(pkf) = pk_field::<T>() {
let mut sel = Query::select();
sel.column(Alias::new(pkf.name)).from(table.clone());
for p in &self.qs.predicates {
sel.and_where(p.cond_for(backend));
}
sel.and_where(Expr::col(Alias::new("deleted_at")).is_null());
let meta = crate::migrate::ModelMeta::for_::<T>();
let mut conn = crate::orm::soft_delete_cascade::CascadeConn::from_tx(self.tx);
crate::orm::soft_delete_cascade::cascade_soft_delete(&mut conn, &meta, sel, now)
.await?;
}
let mut stmt = Query::update();
stmt.table(table);
stmt.value(
Alias::new("deleted_at"),
Value::ChronoDateTimeUtc(Some(Box::new(now))),
);
for p in &self.qs.predicates {
stmt.and_where(p.cond_for(backend));
}
stmt.and_where(Expr::col(Alias::new("deleted_at")).is_null());
match backend {
"sqlite" => {
let tx = self.tx.as_sqlite_mut().unwrap();
let (sql, values) = stmt.build_sqlx(SqliteQueryBuilder);
let result = sqlx::query_with::<sqlx::Sqlite, _>(&sql, values)
.execute(&mut **tx)
.await?;
Ok(result.rows_affected())
}
_ => {
let tx = self.tx.as_pg_mut().unwrap();
let (sql, values) = stmt.build_sqlx(PostgresQueryBuilder);
let result = sqlx::query_with::<sqlx::Postgres, _>(&sql, values)
.execute(&mut **tx)
.await?;
Ok(result.rows_affected())
}
}
}
/// UPDATE inside the transaction. Takes the same `column → JSON value`
/// map as [`super::QuerySet::update_values`].
pub async fn update_values(
self,
values: serde_json::Map<String, serde_json::Value>,
) -> Result<u64, crate::orm::write::WriteError> {
let stmt = self.qs.build_update_for(self.tx.backend_name(), &values)?;
match self.tx.backend_name() {
"sqlite" => {
let tx = self.tx.as_sqlite_mut().unwrap();
let (sql, values) = stmt.build_sqlx(SqliteQueryBuilder);
let result = sqlx::query_with::<sqlx::Sqlite, _>(&sql, values)
.execute(&mut **tx)
.await?;
Ok(result.rows_affected())
}
_ => {
let tx = self.tx.as_pg_mut().unwrap();
let (sql, values) = stmt.build_sqlx(PostgresQueryBuilder);
let result = sqlx::query_with::<sqlx::Postgres, _>(&sql, values)
.execute(&mut **tx)
.await?;
Ok(result.rows_affected())
}
}
}
/// INSERT one row and return the populated row, inside the transaction.
///
/// This is the `Manager::create_in_tx` equivalent called through the
/// QuerySet API: `Post::objects().on_tx(tx).create(instance).await?`.
pub async fn create(self, instance: T) -> Result<T, crate::orm::write::WriteError>
where
T: serde::Serialize
+ for<'r> sqlx::FromRow<'r, sqlx::sqlite::SqliteRow>
+ for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow>
+ HydrateRelated,
{
let map = serialize_to_map(&instance)?;
let stmt = build_insert_one_for::<T>(self.tx.backend_name(), &map)?;
match self.tx.backend_name() {
"sqlite" => {
let tx = self.tx.as_sqlite_mut().unwrap();
let (sql, values) = stmt.build_sqlx(SqliteQueryBuilder);
// Classify UNIQUE / FK / NOT NULL / CHECK violations into the
// structured `WriteError` variants, symmetric with the non-tx
// `QuerySet::create`. Without this a constraint violation inside
// a transaction surfaces as an opaque `Sqlx(_)`, so callers that
// branch on `WriteError::UniqueViolation` (e.g. the OAuth
// username-retry loop) can't tell a collision from a real error.
let mut row = sqlx::query_as_with::<sqlx::Sqlite, T, _>(&sql, values)
.fetch_one(&mut **tx)
.await
.map_err(|e| {
crate::orm::validation::classify_sql_error(&e, &map)
.unwrap_or(crate::orm::write::WriteError::Sqlx(e))
})?;
row.set_m2m_parent_ids();
Ok(row)
}
_ => {
let tx = self.tx.as_pg_mut().unwrap();
let (sql, values) = stmt.build_sqlx(PostgresQueryBuilder);
let mut row = sqlx::query_as_with::<sqlx::Postgres, T, _>(&sql, values)
.fetch_one(&mut **tx)
.await
.map_err(|e| {
crate::orm::validation::classify_sql_error(&e, &map)
.unwrap_or(crate::orm::write::WriteError::Sqlx(e))
})?;
row.set_m2m_parent_ids();
Ok(row)
}
}
}
}