rust_query/transaction.rs
1use std::{
2 cell::RefCell, convert::Infallible, iter::zip, marker::PhantomData, sync::atomic::AtomicI64,
3};
4
5use rusqlite::ErrorCode;
6use sea_query::{
7 Alias, CommonTableExpression, DeleteStatement, Expr, ExprTrait, InsertStatement, IntoTableRef,
8 SelectStatement, SqliteQueryBuilder, UpdateStatement, WithClause,
9};
10use sea_query_rusqlite::RusqliteBinder;
11use self_cell::{MutBorrow, self_cell};
12
13use crate::{
14 IntoExpr, IntoSelect, Table, TableRow,
15 joinable::DynJoinable,
16 migrate::{Schema, check_schema, schema_version, user_version},
17 migration::Config,
18 mutable::Mutable,
19 pool::Pool,
20 private::{Joinable, Reader},
21 query::{OwnedRows, Query, track_stmt},
22 rows::Rows,
23 value::{DynTypedExpr, MyTyp, OptTable, SecretFromSql, ValueBuilder},
24 writable::TableInsert,
25};
26
27/// [Database] is a proof that the database has been configured.
28///
29/// Creating a [Database] requires going through the steps to migrate an existing database to
30/// the required schema, or creating a new database from scratch (See also [crate::migration::Config]).
31/// Please see [Database::migrator] to get started.
32///
33/// Having done the setup to create a compatible database is sadly not a guarantee that the
34/// database will stay compatible for the lifetime of the [Database] struct.
35/// That is why [Database] also stores the `schema_version`. This allows detecting non-malicious
36/// modifications to the schema and gives us the ability to panic when this is detected.
37/// Such non-malicious modification of the schema can happen for example if another [Database]
38/// instance is created with additional migrations (e.g. by another newer instance of your program).
39pub struct Database<S> {
40 pub(crate) manager: Pool,
41 pub(crate) schema_version: AtomicI64,
42 pub(crate) schema: PhantomData<S>,
43 pub(crate) mut_lock: parking_lot::FairMutex<()>,
44}
45
46impl<S: Schema> Database<S> {
47 /// This is a quick way to open a database if you don't care about migration.
48 ///
49 /// Note that this will panic if the schema version doesn't match or when the schema
50 /// itself doesn't match the expected schema.
51 pub fn new(config: Config) -> Self {
52 let Some(m) = Self::migrator(config) else {
53 panic!("schema version {}, but got an older version", S::VERSION)
54 };
55 let Some(m) = m.finish() else {
56 panic!("schema version {}, but got a new version", S::VERSION)
57 };
58 m
59 }
60}
61
62use rusqlite::Connection;
63type RTransaction<'x> = Option<rusqlite::Transaction<'x>>;
64
65self_cell!(
66 pub struct OwnedTransaction {
67 owner: MutBorrow<Connection>,
68
69 #[covariant]
70 dependent: RTransaction,
71 }
72);
73
74/// SAFETY:
75/// `RTransaction: !Send` because it borrows from `Connection` and `Connection: !Sync`.
76/// `OwnedTransaction` can be `Send` because we know that `dependent` is the only
77/// borrow of `owner` and `OwnedTransaction: !Sync` so `dependent` can not be borrowed
78/// from multiple threads.
79unsafe impl Send for OwnedTransaction {}
80assert_not_impl_any! {OwnedTransaction: Sync}
81
82thread_local! {
83 pub(crate) static TXN: RefCell<Option<TransactionWithRows>> = const { RefCell::new(None) };
84}
85
86impl OwnedTransaction {
87 pub(crate) fn get(&self) -> &rusqlite::Transaction<'_> {
88 self.borrow_dependent().as_ref().unwrap()
89 }
90
91 pub(crate) fn with(
92 mut self,
93 f: impl FnOnce(rusqlite::Transaction<'_>),
94 ) -> rusqlite::Connection {
95 self.with_dependent_mut(|_, b| f(b.take().unwrap()));
96 self.into_owner().into_inner()
97 }
98}
99
100type OwnedRowsVec<'x> = slab::Slab<OwnedRows<'x>>;
101self_cell!(
102 pub struct TransactionWithRows {
103 owner: OwnedTransaction,
104
105 #[not_covariant]
106 dependent: OwnedRowsVec,
107 }
108);
109
110impl TransactionWithRows {
111 pub(crate) fn new_empty(txn: OwnedTransaction) -> Self {
112 Self::new(txn, |_| slab::Slab::new())
113 }
114
115 pub(crate) fn get(&self) -> &rusqlite::Transaction<'_> {
116 self.borrow_owner().get()
117 }
118}
119
120impl<S: Send + Sync + Schema> Database<S> {
121 /// Create a [Transaction]. Creating the transaction will not block by default.
122 ///
123 /// This function will panic if the schema was modified compared to when the [Database] value
124 /// was created. This can happen for example by running another instance of your program with
125 /// additional migrations.
126 ///
127 /// Note that many systems have a limit on the number of file descriptors that can
128 /// exist in a single process. On my machine the soft limit is (1024) by default.
129 /// If this limit is reached, it may cause a panic in this method.
130 pub fn transaction<R: Send>(&self, f: impl Send + FnOnce(&'static Transaction<S>) -> R) -> R {
131 let res = std::thread::scope(|scope| scope.spawn(|| self.transaction_local(f)).join());
132 match res {
133 Ok(val) => val,
134 Err(payload) => std::panic::resume_unwind(payload),
135 }
136 }
137
138 /// Same as [Self::transaction], but can only be used on a new thread.
139 pub(crate) fn transaction_local<R>(&self, f: impl FnOnce(&'static Transaction<S>) -> R) -> R {
140 let conn = self.manager.pop();
141
142 let owned = OwnedTransaction::new(MutBorrow::new(conn), |conn| {
143 Some(conn.borrow_mut().transaction().unwrap())
144 });
145
146 let res = f(Transaction::new_checked(owned, &self.schema_version));
147
148 let owned = TXN.take().unwrap().into_owner();
149 self.manager.push(owned.into_owner().into_inner());
150
151 res
152 }
153
154 /// Create a mutable [Transaction].
155 /// This operation needs to wait for all other mutable [Transaction]s for this database to be finished.
156 /// There is currently no timeout on this operation, so it will wait indefinitly if required.
157 ///
158 /// Whether the transaction is commited depends on the result of the closure.
159 /// The transaction is only commited if the closure return [Ok]. In the case that it returns [Err]
160 /// or when the closure panics, a rollback is performed.
161 ///
162 /// This function will panic if the schema was modified compared to when the [Database] value
163 /// was created. This can happen for example by running another instance of your program with
164 /// additional migrations.
165 ///
166 /// Note that many systems have a limit on the number of file descriptors that can
167 /// exist in a single process. On my machine the soft limit is (1024) by default.
168 /// If this limit is reached, it may cause a panic in this method.
169 pub fn transaction_mut<O: Send, E: Send>(
170 &self,
171 f: impl Send + FnOnce(&'static mut Transaction<S>) -> Result<O, E>,
172 ) -> Result<O, E> {
173 let join_res =
174 std::thread::scope(|scope| scope.spawn(|| self.transaction_mut_local(f)).join());
175
176 match join_res {
177 Ok(val) => val,
178 Err(payload) => std::panic::resume_unwind(payload),
179 }
180 }
181
182 pub(crate) fn transaction_mut_local<O, E>(
183 &self,
184 f: impl FnOnce(&'static mut Transaction<S>) -> Result<O, E>,
185 ) -> Result<O, E> {
186 // Acquire the lock before creating the connection.
187 // Technically we can acquire the lock later, but we don't want to waste
188 // file descriptors on transactions that need to wait anyway.
189 let guard = self.mut_lock.lock();
190
191 let conn = self.manager.pop();
192
193 let owned = OwnedTransaction::new(MutBorrow::new(conn), |conn| {
194 let txn = conn
195 .borrow_mut()
196 .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
197 .unwrap();
198 Some(txn)
199 });
200 // if this panics then the transaction is rolled back and the guard is dropped.
201 let res = f(Transaction::new_checked(owned, &self.schema_version));
202
203 // Drop the guard before commiting to let sqlite go to the next transaction
204 // more quickly while guaranteeing that the database will unlock soon.
205 drop(guard);
206
207 let owned = TXN.take().unwrap().into_owner();
208
209 let conn = if res.is_ok() {
210 owned.with(|x| x.commit().unwrap())
211 } else {
212 owned.with(|x| x.rollback().unwrap())
213 };
214 self.manager.push(conn);
215
216 res
217 }
218
219 /// Same as [Self::transaction_mut], but always commits the transaction.
220 ///
221 /// The only exception is that if the closure panics, a rollback is performed.
222 pub fn transaction_mut_ok<R: Send>(
223 &self,
224 f: impl Send + FnOnce(&'static mut Transaction<S>) -> R,
225 ) -> R {
226 self.transaction_mut(|txn| Ok::<R, Infallible>(f(txn)))
227 .unwrap()
228 }
229
230 /// Create a new [rusqlite::Connection] to the database.
231 ///
232 /// You can do (almost) anything you want with this connection as it is almost completely isolated from all other
233 /// [rust_query] connections. The only thing you should not do here is changing the schema.
234 /// Schema changes are detected with the `schema_version` pragma and will result in a panic when creating a new
235 /// [rust_query] transaction.
236 ///
237 /// The `foreign_keys` pragma is always enabled here, even if [crate::migration::ForeignKeys::SQLite] is not used.
238 ///
239 /// Note that many systems have a limit on the number of file descriptors that can
240 /// exist in a single process. On my machine the soft limit is (1024) by default.
241 /// If this limit is reached, it may cause a panic in this method.
242 pub fn rusqlite_connection(&self) -> rusqlite::Connection {
243 let conn = self.manager.pop();
244 conn.pragma_update(None, "foreign_keys", "ON").unwrap();
245 conn
246 }
247}
248
249/// [Transaction] can be used to query and update the database.
250///
251/// From the perspective of a [Transaction] each other [Transaction] is fully applied or not at all.
252/// Futhermore, the effects of [Transaction]s have a global order.
253/// So if we have mutations `A` and then `B`, it is impossible for a [Transaction] to see the effect of `B` without seeing the effect of `A`.
254pub struct Transaction<S> {
255 pub(crate) _p2: PhantomData<S>,
256 pub(crate) _local: PhantomData<*const ()>,
257}
258
259impl<S> Transaction<S> {
260 pub(crate) fn new() -> Self {
261 Self {
262 _p2: PhantomData,
263 _local: PhantomData,
264 }
265 }
266
267 pub(crate) fn new_ref() -> &'static mut Self {
268 // no memory is leaked because Self is zero sized
269 Box::leak(Box::new(Self::new()))
270 }
271}
272
273impl<S: Schema> Transaction<S> {
274 /// This will check the schema version and panic if it is not as expected
275 pub(crate) fn new_checked(txn: OwnedTransaction, expected: &AtomicI64) -> &'static mut Self {
276 let schema_version = schema_version(txn.get());
277 // If the schema version is not the expected version then we
278 // check if the changes are acceptable.
279 if schema_version != expected.load(std::sync::atomic::Ordering::Relaxed) {
280 if user_version(txn.get()).unwrap() != S::VERSION {
281 panic!("The database user_version changed unexpectedly")
282 }
283
284 TXN.set(Some(TransactionWithRows::new_empty(txn)));
285 check_schema::<S>(Self::new_ref());
286 expected.store(schema_version, std::sync::atomic::Ordering::Relaxed);
287 } else {
288 TXN.set(Some(TransactionWithRows::new_empty(txn)));
289 }
290
291 const {
292 assert!(size_of::<Self>() == 0);
293 }
294 Self::new_ref()
295 }
296}
297
298impl<S> Transaction<S> {
299 /// Execute a query with multiple results.
300 ///
301 /// ```
302 /// # use rust_query::{private::doctest::*};
303 /// # get_txn(|txn| {
304 /// let user_names = txn.query(|rows| {
305 /// let user = rows.join(User);
306 /// rows.into_vec(&user.name)
307 /// });
308 /// assert_eq!(user_names, vec!["Alice".to_owned()]);
309 /// # });
310 /// ```
311 pub fn query<'t, F, R>(&'t self, f: F) -> R
312 where
313 F: for<'inner> FnOnce(&mut Query<'t, 'inner, S>) -> R,
314 {
315 // Execution already happens in a [Transaction].
316 // and thus any [TransactionMut] that it might be borrowed
317 // from is borrowed immutably, which means the rows can not change.
318
319 let q = Rows {
320 phantom: PhantomData,
321 ast: Default::default(),
322 _p: PhantomData,
323 };
324 f(&mut Query {
325 q,
326 phantom: PhantomData,
327 })
328 }
329
330 /// Retrieve a single result from the database.
331 ///
332 /// ```
333 /// # use rust_query::{private::doctest::*, IntoExpr};
334 /// # rust_query::private::doctest::get_txn(|txn| {
335 /// let res = txn.query_one("test".into_expr());
336 /// assert_eq!(res, "test");
337 /// # });
338 /// ```
339 ///
340 /// Instead of using [Self::query_one] in a loop, it is better to
341 /// call [Self::query] and return all results at once.
342 pub fn query_one<O: 'static>(&self, val: impl IntoSelect<'static, S, Out = O>) -> O {
343 self.query(|e| e.into_iter(val.into_select()).next().unwrap())
344 }
345
346 pub fn lazy<'t, T: OptTable>(&'t self, val: impl IntoExpr<'static, S, Typ = T>) -> T::Lazy<'t> {
347 T::out_to_lazy(self.query_one(val.into_expr()))
348 }
349
350 pub fn lazy_iter<'t, T: Table<Schema = S>>(
351 &'t self,
352 val: impl Joinable<'static, Typ = T>,
353 ) -> LazyIter<'t, T> {
354 let val = DynJoinable::new(val);
355 self.query(|rows| {
356 let table = rows.join(val);
357 LazyIter {
358 txn: self,
359 iter: rows.into_iter(table),
360 }
361 })
362 }
363
364 pub fn mutable<'t, T: OptTable<Schema = S>>(
365 &'t mut self,
366 val: impl IntoExpr<'static, S, Typ = T>,
367 ) -> T::Mutable<'t> {
368 let x = self.query_one(T::select_opt_mutable(val.into_expr()));
369 T::into_mutable(x)
370 }
371
372 pub fn mutable_vec<'t, T: Table<Schema = S>>(
373 &'t mut self,
374 val: impl Joinable<'static, Typ = T>,
375 ) -> Vec<Mutable<'t, T>>
376 where
377 S: 'static,
378 {
379 let val = DynJoinable::new(val);
380 self.query(|rows| {
381 let val = rows.join(val);
382 rows.into_vec(T::select_mutable(val))
383 .into_iter()
384 .map(T::into_mutable)
385 .collect()
386 })
387 }
388}
389
390pub struct LazyIter<'t, T: Table> {
391 txn: &'t Transaction<T::Schema>,
392 iter: crate::query::Iter<'t, TableRow<T>>,
393}
394
395impl<'t, T: Table> Iterator for LazyIter<'t, T> {
396 type Item = <T as MyTyp>::Lazy<'t>;
397
398 fn next(&mut self) -> Option<Self::Item> {
399 self.iter.next().map(|x| self.txn.lazy(x))
400 }
401}
402
403impl<S: 'static> Transaction<S> {
404 /// Try inserting a value into the database.
405 ///
406 /// Returns [Ok] with a reference to the new inserted value or an [Err] with conflict information.
407 /// The type of conflict information depends on the number of unique constraints on the table:
408 /// - 0 unique constraints => [Infallible]
409 /// - 1 unique constraint => [Expr] reference to the conflicting table row.
410 /// - 2+ unique constraints => `()` no further information is provided.
411 ///
412 /// ```
413 /// # use rust_query::{private::doctest::*, IntoExpr};
414 /// # rust_query::private::doctest::get_txn(|mut txn| {
415 /// let res = txn.insert(User {
416 /// name: "Bob",
417 /// });
418 /// assert!(res.is_ok());
419 /// let res = txn.insert(User {
420 /// name: "Bob",
421 /// });
422 /// assert!(res.is_err(), "there is a unique constraint on the name");
423 /// # });
424 /// ```
425 pub fn insert<T: Table<Schema = S>>(
426 &mut self,
427 val: impl TableInsert<T = T>,
428 ) -> Result<TableRow<T>, T::Conflict> {
429 try_insert_private(T::NAME.into_table_ref(), None, val.into_insert())
430 }
431
432 /// This is a convenience function to make using [Transaction::insert]
433 /// easier for tables without unique constraints.
434 ///
435 /// The new row is added to the table and the row reference is returned.
436 pub fn insert_ok<T: Table<Schema = S, Conflict = Infallible>>(
437 &mut self,
438 val: impl TableInsert<T = T>,
439 ) -> TableRow<T> {
440 let Ok(row) = self.insert(val);
441 row
442 }
443
444 /// This is a convenience function to make using [Transaction::insert]
445 /// easier for tables with exactly one unique constraints.
446 ///
447 /// The new row is inserted and the reference to the row is returned OR
448 /// an existing row is found which conflicts with the new row and a reference
449 /// to the conflicting row is returned.
450 ///
451 /// ```
452 /// # use rust_query::{private::doctest::*, IntoExpr};
453 /// # rust_query::private::doctest::get_txn(|mut txn| {
454 /// let bob = txn.insert(User {
455 /// name: "Bob",
456 /// }).unwrap();
457 /// let bob2 = txn.find_or_insert(User {
458 /// name: "Bob", // this will conflict with the existing row.
459 /// });
460 /// assert_eq!(bob, bob2);
461 /// # });
462 /// ```
463 pub fn find_or_insert<T: Table<Schema = S, Conflict = TableRow<T>>>(
464 &mut self,
465 val: impl TableInsert<T = T>,
466 ) -> TableRow<T> {
467 match self.insert(val) {
468 Ok(row) => row,
469 Err(row) => row,
470 }
471 }
472
473 /// Try updating a row in the database to have new column values.
474 ///
475 /// Updating can fail just like [Transaction::insert] because of unique constraint conflicts.
476 /// This happens when the new values are in conflict with an existing different row.
477 ///
478 /// When the update succeeds, this function returns [Ok], when it fails it returns [Err] with one of
479 /// three conflict types:
480 /// - 0 unique constraints => [Infallible]
481 /// - 1 unique constraint => [Expr] reference to the conflicting table row.
482 /// - 2+ unique constraints => `()` no further information is provided.
483 ///
484 /// ```
485 /// # use rust_query::{private::doctest::*, IntoExpr, Update};
486 /// # rust_query::private::doctest::get_txn(|mut txn| {
487 /// let bob = txn.insert(User {
488 /// name: "Bob",
489 /// }).unwrap();
490 /// txn.update(bob, User {
491 /// name: Update::set("New Bob"),
492 /// }).unwrap();
493 /// # });
494 /// ```
495 pub fn update<T: Table<Schema = S>>(
496 &mut self,
497 row: impl IntoExpr<'static, S, Typ = T>,
498 val: T::Update,
499 ) -> Result<(), T::Conflict> {
500 let mut id = ValueBuilder::default();
501 let row = row.into_expr();
502 let (id, _) = id.simple_one(DynTypedExpr::erase(&row));
503
504 let val = T::apply_try_update(val, row);
505 let mut reader = Reader::default();
506 T::read(&val, &mut reader);
507 let (col_names, col_exprs): (Vec<_>, Vec<_>) = reader.builder.into_iter().collect();
508
509 let (select, col_fields) = ValueBuilder::default().simple(col_exprs);
510 let cte = CommonTableExpression::new()
511 .query(select)
512 .columns(col_fields.clone())
513 .table_name(Alias::new("cte"))
514 .to_owned();
515 let with_clause = WithClause::new().cte(cte).to_owned();
516
517 let mut update = UpdateStatement::new()
518 .table(("main", T::NAME))
519 .cond_where(Expr::col(("main", T::NAME, T::ID)).in_subquery(id))
520 .to_owned();
521
522 for (name, field) in zip(col_names, col_fields) {
523 let select = SelectStatement::new()
524 .from(Alias::new("cte"))
525 .column(field)
526 .to_owned();
527 let value = sea_query::Expr::SubQuery(
528 None,
529 Box::new(sea_query::SubQueryStatement::SelectStatement(select)),
530 );
531 update.value(Alias::new(name), value);
532 }
533
534 let (query, args) = update.with(with_clause).build_rusqlite(SqliteQueryBuilder);
535
536 let res = TXN.with_borrow(|txn| {
537 let txn = txn.as_ref().unwrap().get();
538
539 let mut stmt = txn.prepare_cached(&query).unwrap();
540 stmt.execute(&*args.as_params())
541 });
542
543 match res {
544 Ok(1) => Ok(()),
545 Ok(n) => panic!("unexpected number of updates: {n}"),
546 Err(rusqlite::Error::SqliteFailure(kind, Some(_val)))
547 if kind.code == ErrorCode::ConstraintViolation =>
548 {
549 // val looks like "UNIQUE constraint failed: playlist_track.playlist, playlist_track.track"
550 Err(T::get_conflict_unchecked(self, &val))
551 }
552 Err(err) => panic!("{err:?}"),
553 }
554 }
555
556 /// This is a convenience function to use [Transaction::update] for updates
557 /// that can not cause unique constraint violations.
558 ///
559 /// This method can be used for all tables, it just does not allow modifying
560 /// columns that are part of unique constraints.
561 #[deprecated = "Use Transaction::mutable instead"]
562 pub fn update_ok<T: Table<Schema = S>>(
563 &mut self,
564 row: impl IntoExpr<'static, S, Typ = T>,
565 val: T::UpdateOk,
566 ) {
567 match self.update(row, T::update_into_try_update(val)) {
568 Ok(val) => val,
569 Err(_) => {
570 unreachable!("update can not fail")
571 }
572 }
573 }
574
575 /// Convert the [Transaction] into a [TransactionWeak] to allow deletions.
576 pub fn downgrade(&'static mut self) -> &'static mut TransactionWeak<S> {
577 // TODO: clean this up
578 Box::leak(Box::new(TransactionWeak { inner: PhantomData }))
579 }
580}
581
582/// This is the weak version of [Transaction].
583///
584/// The reason that it is called `weak` is because [TransactionWeak] can not guarantee
585/// that [TableRow]s prove the existence of their particular row.
586///
587/// [TransactionWeak] is useful because it allowes deleting rows.
588pub struct TransactionWeak<S> {
589 inner: PhantomData<Transaction<S>>,
590}
591
592impl<S: Schema> TransactionWeak<S> {
593 /// Try to delete a row from the database.
594 ///
595 /// This will return an [Err] if there is a row that references the row that is being deleted.
596 /// When this method returns [Ok] it will contain a [bool] that is either
597 /// - `true` if the row was just deleted.
598 /// - `false` if the row was deleted previously in this transaction.
599 pub fn delete<T: Table<Schema = S>>(&mut self, val: TableRow<T>) -> Result<bool, T::Referer> {
600 let schema = crate::schema::from_macro::Schema::new::<S>();
601
602 // This is a manual check that foreign key constraints are not violated.
603 // We do this manually because we don't want to enabled foreign key constraints for the whole
604 // transaction (and is not possible to enable for part of a transaction).
605 let mut checks = vec![];
606 for (table_name, table) in &schema.tables {
607 for col in table.columns.iter().filter_map(|(col_name, col)| {
608 let col = &col.def;
609 col.fk
610 .as_ref()
611 .is_some_and(|(t, c)| t == T::NAME && c == T::ID)
612 .then_some(col_name)
613 }) {
614 let stmt = SelectStatement::new()
615 .expr(
616 val.in_subquery(
617 SelectStatement::new()
618 .from(Alias::new(table_name))
619 .column(Alias::new(col))
620 .take(),
621 ),
622 )
623 .take();
624 checks.push(stmt.build_rusqlite(SqliteQueryBuilder));
625 }
626 }
627
628 let stmt = DeleteStatement::new()
629 .from_table(("main", T::NAME))
630 .cond_where(Expr::col(("main", T::NAME, T::ID)).eq(val.inner.idx))
631 .take();
632
633 let (query, args) = stmt.build_rusqlite(SqliteQueryBuilder);
634
635 TXN.with_borrow(|txn| {
636 let txn = txn.as_ref().unwrap().get();
637
638 for (query, args) in checks {
639 let mut stmt = txn.prepare_cached(&query).unwrap();
640 match stmt.query_one(&*args.as_params(), |r| r.get(0)) {
641 Ok(true) => return Err(T::get_referer_unchecked()),
642 Ok(false) => {}
643 Err(err) => panic!("{err:?}"),
644 }
645 }
646
647 let mut stmt = txn.prepare_cached(&query).unwrap();
648 match stmt.execute(&*args.as_params()) {
649 Ok(0) => Ok(false),
650 Ok(1) => Ok(true),
651 Ok(n) => {
652 panic!("unexpected number of deletes {n}")
653 }
654 Err(err) => panic!("{err:?}"),
655 }
656 })
657 }
658
659 /// Delete a row from the database.
660 ///
661 /// This is the infallible version of [TransactionWeak::delete].
662 ///
663 /// To be able to use this method you have to mark the table as `#[no_reference]` in the schema.
664 pub fn delete_ok<T: Table<Referer = Infallible, Schema = S>>(
665 &mut self,
666 val: TableRow<T>,
667 ) -> bool {
668 let Ok(res) = self.delete(val);
669 res
670 }
671
672 /// This allows you to do (almost) anything you want with the internal [rusqlite::Transaction].
673 ///
674 /// Note that there are some things that you should not do with the transaction, such as:
675 /// - Changes to the schema, these will result in a panic as described in [Database].
676 /// - Making changes that violate foreign-key constraints (see below).
677 ///
678 /// Sadly it is not possible to enable (or disable) the `foreign_keys` pragma during a transaction.
679 /// This means that whether this pragma is enabled depends on which [crate::migration::ForeignKeys]
680 /// option is used and can not be changed.
681 pub fn rusqlite_transaction<R>(&mut self, f: impl FnOnce(&rusqlite::Transaction) -> R) -> R {
682 TXN.with_borrow(|txn| f(txn.as_ref().unwrap().get()))
683 }
684}
685
686pub fn try_insert_private<T: Table>(
687 table: sea_query::TableRef,
688 idx: Option<i64>,
689 val: T::Insert,
690) -> Result<TableRow<T>, T::Conflict> {
691 let mut reader = Reader::default();
692 T::read(&val, &mut reader);
693 if let Some(idx) = idx {
694 reader.col(T::ID, idx);
695 }
696 let (col_names, col_exprs): (Vec<_>, Vec<_>) = reader.builder.into_iter().collect();
697 let is_empty = col_names.is_empty();
698
699 let (select, _) = ValueBuilder::default().simple(col_exprs);
700
701 let mut insert = InsertStatement::new();
702 insert.into_table(table);
703 insert.columns(col_names.into_iter().map(Alias::new));
704 if is_empty {
705 // select always has at least one column, so we leave it out when there are no columns
706 insert.or_default_values();
707 } else {
708 insert.select_from(select).unwrap();
709 }
710 insert.returning_col(T::ID);
711
712 let (sql, values) = insert.build_rusqlite(SqliteQueryBuilder);
713
714 let res = TXN.with_borrow(|txn| {
715 let txn = txn.as_ref().unwrap().get();
716 track_stmt(txn, &sql, &values);
717
718 let mut statement = txn.prepare_cached(&sql).unwrap();
719 let mut res = statement
720 .query_map(&*values.as_params(), |row| {
721 Ok(TableRow::<T>::from_sql(row.get_ref(T::ID)?)?)
722 })
723 .unwrap();
724
725 res.next().unwrap()
726 });
727
728 match res {
729 Ok(id) => Ok(id),
730 Err(rusqlite::Error::SqliteFailure(kind, Some(_val)))
731 if kind.code == ErrorCode::ConstraintViolation =>
732 {
733 // val looks like "UNIQUE constraint failed: playlist_track.playlist, playlist_track.track"
734 Err(T::get_conflict_unchecked(&Transaction::new(), &val))
735 }
736 Err(err) => panic!("{err:?}"),
737 }
738}