1#[cfg(any(feature = "postgres", test))]
10use std::borrow::Cow;
11use std::fmt;
12use std::sync::Arc;
13
14use cookie::Key;
15
16use sqlx::sqlite::{Sqlite, SqliteArguments, SqlitePool, SqliteRow};
17use sqlx::{AssertSqlSafe, Column, Row as _};
18
19use super::value::DbValue;
20use super::{DbError, ToDbValue};
21
22#[cfg(feature = "postgres")]
23use sqlx::postgres::{PgArguments, PgPool, PgRow, Postgres};
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum Dialect {
28 Sqlite,
30 Postgres,
32}
33
34impl fmt::Display for Dialect {
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 f.write_str(match self {
37 Dialect::Sqlite => "sqlite",
38 Dialect::Postgres => "postgres",
39 })
40 }
41}
42
43#[derive(Clone)]
49pub struct Db {
50 pool: Pool,
51 schema: SchemaEpoch,
52 key: Option<Arc<Key>>,
54 custom_fields: crate::custom_fields::Cache,
56}
57
58#[derive(Clone, Default)]
68pub(crate) struct SchemaEpoch(std::sync::Arc<std::sync::Mutex<Option<std::time::Instant>>>);
69
70impl SchemaEpoch {
71 pub(crate) fn changed(&self) {
72 *self.0.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::time::Instant::now());
73 }
74
75 pub(crate) fn is_stale(&self, age: std::time::Duration) -> bool {
77 self.0
78 .lock()
79 .unwrap_or_else(|e| e.into_inner())
80 .is_some_and(|at| age >= at.elapsed())
81 }
82}
83
84#[derive(Clone)]
85enum Pool {
86 Sqlite(SqlitePool),
87 #[cfg(feature = "postgres")]
88 Postgres(PgPool),
89}
90
91impl fmt::Debug for Db {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 f.debug_struct("Db")
94 .field("dialect", &self.dialect())
95 .finish_non_exhaustive()
96 }
97}
98
99impl From<SqlitePool> for Db {
100 fn from(pool: SqlitePool) -> Self {
101 Self::with_epoch(Pool::Sqlite(pool), SchemaEpoch::default())
102 }
103}
104
105#[cfg(feature = "postgres")]
106impl From<PgPool> for Db {
107 fn from(pool: PgPool) -> Self {
108 Self::with_epoch(Pool::Postgres(pool), SchemaEpoch::default())
109 }
110}
111
112impl Db {
113 fn with_epoch(pool: Pool, schema: SchemaEpoch) -> Self {
114 Self {
115 pool,
116 schema,
117 key: None,
118 custom_fields: Default::default(),
119 }
120 }
121
122 pub(crate) fn with_key(mut self, key: Key) -> Self {
125 self.key = Some(Arc::new(key));
126 self
127 }
128
129 pub(crate) fn from_sqlite(pool: SqlitePool, schema: SchemaEpoch) -> Self {
130 Self::with_epoch(Pool::Sqlite(pool), schema)
131 }
132
133 #[cfg(feature = "postgres")]
134 pub(crate) fn from_postgres(pool: PgPool, schema: SchemaEpoch) -> Self {
135 Self::with_epoch(Pool::Postgres(pool), schema)
136 }
137
138 pub(crate) fn seal_key(&self) -> Option<&Key> {
140 self.key.as_deref()
141 }
142
143 pub(crate) fn custom_fields_cache(&self) -> &crate::custom_fields::Cache {
144 &self.custom_fields
145 }
146
147 pub(crate) fn schema_changed(&self) {
150 self.schema.changed();
151 }
152
153 pub fn dialect(&self) -> Dialect {
155 match self.pool {
156 Pool::Sqlite(_) => Dialect::Sqlite,
157 #[cfg(feature = "postgres")]
158 Pool::Postgres(_) => Dialect::Postgres,
159 }
160 }
161
162 pub fn sqlite(&self) -> Option<&SqlitePool> {
164 match &self.pool {
165 Pool::Sqlite(pool) => Some(pool),
166 #[cfg(feature = "postgres")]
167 Pool::Postgres(_) => None,
168 }
169 }
170
171 #[cfg(feature = "postgres")]
173 pub fn postgres(&self) -> Option<&PgPool> {
174 match &self.pool {
175 Pool::Postgres(pool) => Some(pool),
176 Pool::Sqlite(_) => None,
177 }
178 }
179
180 pub async fn begin(&self) -> Result<Transaction, DbError> {
183 let inner = match &self.pool {
184 Pool::Sqlite(pool) => TxInner::Sqlite(pool.begin().await?),
185 #[cfg(feature = "postgres")]
186 Pool::Postgres(pool) => TxInner::Postgres(pool.begin().await?),
187 };
188 Ok(Transaction {
189 inner,
190 key: self.key.clone(),
191 savepoints: 0,
192 })
193 }
194
195 pub async fn transaction<T, F>(&self, work: F) -> crate::Result<T>
217 where
218 F: for<'t> FnMut(
219 &'t mut Transaction,
220 ) -> futures_util::future::BoxFuture<'t, crate::Result<T>>,
221 {
222 self.transaction_retrying(1, work).await
223 }
224
225 pub async fn transaction_retrying<T, F>(&self, attempts: u32, mut work: F) -> crate::Result<T>
230 where
231 F: for<'t> FnMut(
232 &'t mut Transaction,
233 ) -> futures_util::future::BoxFuture<'t, crate::Result<T>>,
234 {
235 let attempts = attempts.max(1);
236 let mut attempt = 1;
237 loop {
238 let outcome = async {
239 let mut tx = self.begin().await?;
240 let value = work(&mut tx).await?;
241 tx.commit().await?;
242 Ok::<T, crate::Error>(value)
243 }
244 .await;
245 match outcome {
246 Err(err) if attempt < attempts && err.is_retryable() => {
247 let pause = std::time::Duration::from_millis(20 * u64::from(attempt));
248 tokio::time::sleep(pause).await;
249 attempt += 1;
250 }
251 other => return other,
252 }
253 }
254 }
255
256 pub fn retrying<'a, T, F, Fut>(
296 &'a self,
297 attempts: u32,
298 mut work: F,
299 ) -> impl Future<Output = crate::Result<T>> + Send + 'a
300 where
301 T: Send + 'a,
302 F: FnMut() -> Fut + Send + 'a,
303 Fut: Future<Output = crate::Result<T>> + Send + 'a,
304 {
305 let attempts = attempts.max(1);
306 async move {
307 let mut attempt = 1;
308 loop {
309 match work().await {
310 Err(err) if attempt < attempts && err.is_retryable() => {
311 let pause = std::time::Duration::from_millis(20 * u64::from(attempt));
312 tokio::time::sleep(pause).await;
313 attempt += 1;
314 }
315 other => return other,
316 }
317 }
318 }
319 }
320
321 pub async fn begin_immediate(&self) -> Result<Transaction, DbError> {
325 let inner = match &self.pool {
326 Pool::Sqlite(pool) => TxInner::Sqlite(pool.begin_with("BEGIN IMMEDIATE").await?),
327 #[cfg(feature = "postgres")]
328 Pool::Postgres(pool) => TxInner::Postgres(pool.begin().await?),
329 };
330 Ok(Transaction {
331 inner,
332 key: self.key.clone(),
333 savepoints: 0,
334 })
335 }
336
337 pub async fn close(&self) {
339 match &self.pool {
340 Pool::Sqlite(pool) => pool.close().await,
341 #[cfg(feature = "postgres")]
342 Pool::Postgres(pool) => pool.close().await,
343 }
344 }
345}
346
347pub struct Transaction {
349 inner: TxInner,
350 key: Option<Arc<Key>>,
351 savepoints: u32,
353}
354
355enum TxInner {
356 Sqlite(sqlx::Transaction<'static, Sqlite>),
357 #[cfg(feature = "postgres")]
358 Postgres(sqlx::Transaction<'static, Postgres>),
359}
360
361impl Transaction {
362 pub fn dialect(&self) -> Dialect {
364 match self.inner {
365 TxInner::Sqlite(_) => Dialect::Sqlite,
366 #[cfg(feature = "postgres")]
367 TxInner::Postgres(_) => Dialect::Postgres,
368 }
369 }
370
371 pub async fn commit(self) -> Result<(), DbError> {
373 match self.inner {
374 TxInner::Sqlite(tx) => Ok(tx.commit().await?),
375 #[cfg(feature = "postgres")]
376 TxInner::Postgres(tx) => Ok(tx.commit().await?),
377 }
378 }
379
380 pub async fn rollback(self) -> Result<(), DbError> {
382 match self.inner {
383 TxInner::Sqlite(tx) => Ok(tx.rollback().await?),
384 #[cfg(feature = "postgres")]
385 TxInner::Postgres(tx) => Ok(tx.rollback().await?),
386 }
387 }
388
389 pub async fn savepoint<T, F>(&mut self, work: F) -> crate::Result<T>
421 where
422 F: for<'t> FnOnce(
423 &'t mut Transaction,
424 ) -> futures_util::future::BoxFuture<'t, crate::Result<T>>,
425 {
426 let name = format!("renox_savepoint_{}", self.savepoints + 1);
427 sql(format!("SAVEPOINT {name}")).execute(&mut *self).await?;
428 self.savepoints += 1;
429 let outcome = work(self).await;
430 self.savepoints -= 1;
431 match outcome {
432 Ok(value) => {
433 sql(format!("RELEASE SAVEPOINT {name}"))
434 .execute(&mut *self)
435 .await?;
436 Ok(value)
437 }
438 Err(err) => {
439 sql(format!("ROLLBACK TO SAVEPOINT {name}"))
440 .execute(&mut *self)
441 .await?;
442 sql(format!("RELEASE SAVEPOINT {name}"))
443 .execute(&mut *self)
444 .await?;
445 Err(err)
446 }
447 }
448 }
449}
450
451impl fmt::Debug for Transaction {
452 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
453 f.debug_struct("Transaction")
454 .field("dialect", &self.dialect())
455 .finish_non_exhaustive()
456 }
457}
458
459pub trait Executor<'c>: Send + executor::Sealed {
492 fn into_conn(self) -> Conn<'c>;
494}
495
496mod executor {
497 pub trait Sealed {}
498 impl Sealed for &super::Db {}
499 impl Sealed for &mut super::Transaction {}
500 impl Sealed for &mut crate::import::ImportTx<'_> {}
501 impl Sealed for super::Conn<'_> {}
502}
503
504pub enum Conn<'c> {
508 #[doc(hidden)]
510 Pool(&'c Db),
511 #[doc(hidden)]
513 Tx(&'c mut Transaction),
514}
515
516impl<'c> Executor<'c> for &'c Db {
517 fn into_conn(self) -> Conn<'c> {
518 Conn::Pool(self)
519 }
520}
521
522impl<'c> Executor<'c> for &'c mut Transaction {
523 fn into_conn(self) -> Conn<'c> {
524 Conn::Tx(self)
525 }
526}
527
528impl<'c> Executor<'c> for Conn<'c> {
529 fn into_conn(self) -> Conn<'c> {
530 self
531 }
532}
533
534impl Conn<'_> {
535 fn key(&self) -> Option<Arc<Key>> {
537 match self {
538 Conn::Pool(db) => db.key.clone(),
539 Conn::Tx(tx) => tx.key.clone(),
540 }
541 }
542
543 pub fn reborrow(&mut self) -> Conn<'_> {
546 match self {
547 Conn::Pool(db) => Conn::Pool(db),
548 Conn::Tx(tx) => Conn::Tx(tx),
549 }
550 }
551
552 pub fn dialect(&self) -> Dialect {
554 match self {
555 Conn::Pool(db) => db.dialect(),
556 Conn::Tx(tx) => tx.dialect(),
557 }
558 }
559}
560
561macro_rules! dispatch {
564 ($conn:expr, |$build:ident, $exec:ident| $body:expr) => {
565 match $conn {
566 Conn::Pool(db) => match &db.pool {
567 Pool::Sqlite(pool) => {
568 #[allow(unused_variables)]
569 let $build = sqlite_query;
570 let $exec = pool;
571 ($body).map_err(DbError::from)
572 }
573 #[cfg(feature = "postgres")]
574 Pool::Postgres(pool) => {
575 #[allow(unused_variables)]
576 let $build = postgres_query;
577 let $exec = pool;
578 ($body).map_err(DbError::from)
579 }
580 },
581 Conn::Tx(tx) => match &mut tx.inner {
582 TxInner::Sqlite(tx) => {
583 #[allow(unused_variables)]
584 let $build = sqlite_query;
585 let $exec = &mut **tx;
586 ($body).map_err(DbError::from)
587 }
588 #[cfg(feature = "postgres")]
589 TxInner::Postgres(tx) => {
590 #[allow(unused_variables)]
591 let $build = postgres_query;
592 let $exec = &mut **tx;
593 ($body).map_err(DbError::from)
594 }
595 },
596 }
597 };
598}
599
600fn seal(key: Option<&Key>, args: Vec<DbValue>) -> Result<Vec<DbValue>, DbError> {
602 args.into_iter()
603 .map(|value| match value {
604 DbValue::Encrypted(plain) => match key {
605 Some(key) => Ok(DbValue::Text(super::encrypted::seal(key, &plain.0))),
606 None => Err(DbError::from(sqlx::Error::Encode(
607 "an Encrypted value needs the app's Db (it has the APP_KEY); \
608 this Db was made outside App"
609 .into(),
610 ))),
611 },
612 other => Ok(other),
613 })
614 .collect()
615}
616
617fn sqlite_query(
618 sql: String,
619 args: Vec<DbValue>,
620) -> sqlx::query::Query<'static, Sqlite, SqliteArguments> {
621 args.into_iter().fold(
622 sqlx::query(AssertSqlSafe(sql)),
623 |query, value| match value.for_sqlite() {
624 DbValue::Integer(v) => query.bind(v),
625 DbValue::Real(v) => query.bind(v),
626 DbValue::Text(v) => query.bind(v),
627 DbValue::Blob(v) => query.bind(v),
628 _ => query.bind(None::<i64>),
629 },
630 )
631}
632
633#[cfg(feature = "postgres")]
634fn postgres_query(
635 sql: String,
636 args: Vec<DbValue>,
637) -> sqlx::query::Query<'static, Postgres, PgArguments> {
638 let sql = numbered_placeholders(&sql).into_owned();
639 args.into_iter().fold(
640 sqlx::query(AssertSqlSafe(sql)),
641 |query, value| match value {
642 DbValue::Null => query.bind(UntypedNull),
643 DbValue::Integer(v) => query.bind(v),
644 DbValue::Real(v) => query.bind(v),
645 DbValue::Text(v) => query.bind(v),
646 DbValue::Blob(v) => query.bind(v),
647 DbValue::Bool(v) => query.bind(v),
648 DbValue::DateTime(v) => query.bind(v),
649 DbValue::NaiveDateTime(v) => query.bind(v),
650 DbValue::Date(v) => query.bind(v),
651 DbValue::Time(v) => query.bind(v),
652 DbValue::Json(v) => query.bind(sqlx::types::Json(v)),
653 #[cfg(feature = "uuid")]
654 DbValue::Uuid(v) => query.bind(v),
655 DbValue::Encrypted(_) => query.bind(UntypedNull),
657 },
658 )
659}
660
661#[cfg(feature = "postgres")]
664struct UntypedNull;
665
666#[cfg(feature = "postgres")]
667impl sqlx::Type<Postgres> for UntypedNull {
668 fn type_info() -> sqlx::postgres::PgTypeInfo {
669 sqlx::postgres::PgTypeInfo::with_oid(sqlx::postgres::types::Oid(0))
671 }
672}
673
674#[cfg(feature = "postgres")]
675impl sqlx::Encode<'_, Postgres> for UntypedNull {
676 fn encode_by_ref(
677 &self,
678 _buf: &mut sqlx::postgres::PgArgumentBuffer,
679 ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
680 Ok(sqlx::encode::IsNull::Yes)
681 }
682}
683
684#[cfg(any(feature = "postgres", test))]
688pub(crate) fn numbered_placeholders(sql: &str) -> Cow<'_, str> {
689 if !sql.contains('?') {
690 return Cow::Borrowed(sql);
691 }
692 let bytes = sql.as_bytes();
694 let ident = |b: u8| b.is_ascii_alphanumeric() || b == b'_' || b == b'$';
695 let mut out = String::with_capacity(sql.len() + 8);
696 let mut n = 0;
697 let mut copied = 0; let mut i = 0;
699 while i < bytes.len() {
700 let at = i;
701 let end = match bytes[i] {
702 quote @ (b'\'' | b'"') => {
703 let escapes = quote == b'\''
705 && i > 0
706 && matches!(bytes[i - 1], b'E' | b'e')
707 && (i < 2 || !ident(bytes[i - 2]));
708 let mut j = i + 1;
709 while j < bytes.len() && bytes[j] != quote {
712 j += if escapes && bytes[j] == b'\\' { 2 } else { 1 };
713 }
714 j + 1
715 }
716 b'-' if bytes.get(i + 1) == Some(&b'-') => {
717 sql[i..].find('\n').map_or(bytes.len(), |nl| i + nl + 1)
718 }
719 b'/' if bytes.get(i + 1) == Some(&b'*') => sql[i + 2..]
720 .find("*/")
721 .map_or(bytes.len(), |e| i + 2 + e + 2),
722 b'$' if i == 0 || !ident(bytes[i - 1]) => {
723 let tag_len = bytes[i + 1..]
727 .iter()
728 .take_while(|b| b.is_ascii_alphanumeric() || **b == b'_')
729 .count();
730 let starts_with_digit = bytes.get(i + 1).is_some_and(u8::is_ascii_digit);
731 if !starts_with_digit && bytes.get(i + 1 + tag_len) == Some(&b'$') {
732 let tag = &sql[i..i + tag_len + 2];
733 sql[i + tag.len()..]
734 .find(tag)
735 .map_or(bytes.len(), |e| i + tag.len() + e + tag.len())
736 } else {
737 i + 1
738 }
739 }
740 b'?' => {
741 n += 1;
742 out.push_str(&sql[copied..i]);
743 out.push_str(&format!("${n}"));
744 copied = i + 1;
745 i + 1
746 }
747 _ => i + 1,
748 };
749 i = end.min(bytes.len()).max(at + 1);
750 }
751 out.push_str(&sql[copied..]);
752 Cow::Owned(out)
753}
754
755pub fn sql(sql: impl Into<String>) -> Sql {
770 Sql {
771 sql: sql.into(),
772 args: Vec::new(),
773 }
774}
775
776#[derive(Debug, Clone)]
778#[must_use = "a statement does nothing until it is run"]
779pub struct Sql {
780 sql: String,
781 args: Vec<DbValue>,
782}
783
784impl Sql {
785 pub fn bind(mut self, value: impl ToDbValue) -> Self {
787 self.args.push(value.to_db_value());
788 self
789 }
790
791 pub fn bind_all(mut self, values: impl IntoIterator<Item = DbValue>) -> Self {
793 self.args.extend(values);
794 self
795 }
796
797 pub async fn fetch_all<'c>(self, db: impl Executor<'c>) -> Result<Vec<Row>, DbError> {
799 let Self { sql, args } = self;
800 super::query_log::record(&sql);
801 let conn = db.into_conn();
802 let key = conn.key();
803 let args = seal(key.as_deref(), args)?;
804 let rows: Vec<Row> = dispatch!(conn, |build, exec| build(sql, args)
805 .fetch_all(exec)
806 .await
807 .map(|rows| rows.into_iter().map(Row::from).collect()))?;
808 Ok(rows
809 .into_iter()
810 .map(|row| row.with_key(key.clone()))
811 .collect())
812 }
813
814 pub async fn fetch_optional<'c>(self, db: impl Executor<'c>) -> Result<Option<Row>, DbError> {
816 let Self { sql, args } = self;
817 super::query_log::record(&sql);
818 let conn = db.into_conn();
819 let key = conn.key();
820 let args = seal(key.as_deref(), args)?;
821 let row: Option<Row> = dispatch!(conn, |build, exec| build(sql, args)
822 .fetch_optional(exec)
823 .await
824 .map(|row| row.map(Row::from)))?;
825 Ok(row.map(|row| row.with_key(key)))
826 }
827
828 pub async fn fetch_one<'c>(self, db: impl Executor<'c>) -> Result<Row, DbError> {
830 self.fetch_optional(db)
831 .await?
832 .ok_or_else(|| DbError::from(sqlx::Error::RowNotFound))
833 }
834
835 pub async fn execute<'c>(self, db: impl Executor<'c>) -> Result<u64, DbError> {
837 let Self { sql, args } = self;
838 super::query_log::record(&sql);
839 let conn = db.into_conn();
840 let args = seal(conn.key().as_deref(), args)?;
841 dispatch!(conn, |build, exec| build(sql, args)
842 .execute(exec)
843 .await
844 .map(|done| done.rows_affected()))
845 }
846
847 pub async fn fetch_as<'c, T: super::FromRow>(
850 self,
851 db: impl Executor<'c>,
852 ) -> Result<Vec<T>, DbError> {
853 self.fetch_all(db).await?.iter().map(T::from_row).collect()
854 }
855
856 pub async fn fetch_optional_as<'c, T: super::FromRow>(
858 self,
859 db: impl Executor<'c>,
860 ) -> Result<Option<T>, DbError> {
861 self.fetch_optional(db)
862 .await?
863 .as_ref()
864 .map(T::from_row)
865 .transpose()
866 }
867
868 pub async fn fetch_one_as<'c, T: super::FromRow>(
870 self,
871 db: impl Executor<'c>,
872 ) -> Result<T, DbError> {
873 T::from_row(&self.fetch_one(db).await?)
874 }
875
876 pub async fn scalar<'c, T: FromDb>(self, db: impl Executor<'c>) -> Result<T, DbError> {
878 self.fetch_one(db).await?.try_get(0)
879 }
880
881 pub async fn scalar_optional<'c, T: FromDb>(
883 self,
884 db: impl Executor<'c>,
885 ) -> Result<Option<T>, DbError> {
886 self.fetch_optional(db)
887 .await?
888 .map(|row| row.try_get(0))
889 .transpose()
890 }
891
892 pub async fn scalars<'c, T: FromDb>(self, db: impl Executor<'c>) -> Result<Vec<T>, DbError> {
894 self.fetch_all(db)
895 .await?
896 .iter()
897 .map(|row| row.try_get(0))
898 .collect()
899 }
900}
901
902pub(crate) async fn script<'c>(db: impl Executor<'c>, sql: &str) -> Result<u64, DbError> {
905 let sql = sql.to_owned();
906 dispatch!(db.into_conn(), |build, exec| sqlx::raw_sql(AssertSqlSafe(
907 sql
908 ))
909 .execute(exec)
910 .await
911 .map(|done| done.rows_affected()))
912}
913
914pub struct Row(pub(crate) RowInner, Option<Arc<Key>>);
916
917pub(crate) enum RowInner {
918 Sqlite(SqliteRow),
919 #[cfg(feature = "postgres")]
920 Postgres(PgRow),
921}
922
923impl From<SqliteRow> for Row {
924 fn from(row: SqliteRow) -> Self {
925 Self(RowInner::Sqlite(row), None)
926 }
927}
928
929#[cfg(feature = "postgres")]
930impl From<PgRow> for Row {
931 fn from(row: PgRow) -> Self {
932 Self(RowInner::Postgres(row), None)
933 }
934}
935
936impl Row {
937 fn with_key(mut self, key: Option<Arc<Key>>) -> Self {
938 self.1 = key;
939 self
940 }
941
942 pub fn try_get<T: FromDb>(&self, index: impl RowIndex) -> Result<T, DbError> {
944 super::encrypted::reading(self.1.as_ref(), || match &self.0 {
945 RowInner::Sqlite(row) => Ok(row.try_get(index)?),
946 #[cfg(feature = "postgres")]
947 RowInner::Postgres(row) => Ok(row.try_get(index)?),
948 })
949 }
950
951 pub(crate) fn json(&self, column: &str) -> serde_json::Value {
954 use serde_json::Value;
955 if let Ok(v) = self.try_get::<Option<i64>>(column) {
956 return v.map_or(Value::Null, Value::from);
957 }
958 if let Ok(v) = self.try_get::<Option<i32>>(column) {
959 return v.map_or(Value::Null, Value::from);
960 }
961 if let Ok(v) = self.try_get::<Option<i16>>(column) {
963 return v.map_or(Value::Null, Value::from);
964 }
965 if let Ok(v) = self.try_get::<Option<f64>>(column) {
966 return v.map_or(Value::Null, Value::from);
967 }
968 if let Ok(v) = self.try_get::<Option<f32>>(column) {
969 return v.map_or(Value::Null, |n| Value::from(f64::from(n)));
970 }
971 if let Ok(v) = self.try_get::<Option<bool>>(column) {
972 return v.map_or(Value::Null, Value::from);
973 }
974 if let Ok(v) = self.try_get::<Option<chrono::DateTime<chrono::Utc>>>(column) {
975 return v.map_or(Value::Null, |d| Value::from(d.to_rfc3339()));
976 }
977 if let Ok(v) = self.try_get::<Option<chrono::NaiveDateTime>>(column) {
978 return v.map_or(Value::Null, |d| {
979 Value::from(d.format("%Y-%m-%dT%H:%M:%S").to_string())
980 });
981 }
982 if let Ok(v) = self.try_get::<Option<chrono::NaiveDate>>(column) {
983 return v.map_or(Value::Null, |d| Value::from(d.to_string()));
984 }
985 if let Ok(v) = self.try_get::<Option<String>>(column) {
986 return v.map_or(Value::Null, Value::from);
987 }
988 if let Ok(v) = self.try_get::<Option<chrono::NaiveTime>>(column) {
991 return v.map_or(Value::Null, |t| Value::from(t.to_string()));
992 }
993 if let Ok(v) = self.try_get::<Option<serde_json::Value>>(column) {
994 return v.unwrap_or(Value::Null);
995 }
996 Value::Null
997 }
998
999 pub fn columns(&self) -> Vec<&str> {
1001 match &self.0 {
1002 RowInner::Sqlite(row) => row.columns().iter().map(Column::name).collect(),
1003 #[cfg(feature = "postgres")]
1004 RowInner::Postgres(row) => row.columns().iter().map(Column::name).collect(),
1005 }
1006 }
1007
1008 pub fn sqlite(&self) -> Option<&SqliteRow> {
1010 match &self.0 {
1011 RowInner::Sqlite(row) => Some(row),
1012 #[cfg(feature = "postgres")]
1013 RowInner::Postgres(_) => None,
1014 }
1015 }
1016
1017 #[cfg(feature = "postgres")]
1019 pub fn postgres(&self) -> Option<&PgRow> {
1020 match &self.0 {
1021 RowInner::Postgres(row) => Some(row),
1022 RowInner::Sqlite(_) => None,
1023 }
1024 }
1025}
1026
1027impl fmt::Debug for Row {
1028 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1029 f.debug_struct("Row")
1030 .field("columns", &self.columns())
1031 .finish_non_exhaustive()
1032 }
1033}
1034
1035pub trait FromDb: for<'r> sqlx::Decode<'r, Sqlite> + sqlx::Type<Sqlite> + bounds::Postgres {}
1043
1044impl<T> FromDb for T where
1045 T: for<'r> sqlx::Decode<'r, Sqlite> + sqlx::Type<Sqlite> + bounds::Postgres
1046{
1047}
1048
1049pub trait RowIndex: sqlx::ColumnIndex<SqliteRow> + bounds::PostgresIndex {}
1051
1052impl<T> RowIndex for T where T: sqlx::ColumnIndex<SqliteRow> + bounds::PostgresIndex {}
1053
1054#[doc(hidden)]
1056pub mod bounds {
1057 #[cfg(feature = "postgres")]
1058 mod on {
1059 use sqlx::postgres::PgRow;
1060
1061 pub trait Postgres:
1062 for<'r> sqlx::Decode<'r, sqlx::Postgres> + sqlx::Type<sqlx::Postgres>
1063 {
1064 }
1065 impl<T> Postgres for T where T: for<'r> sqlx::Decode<'r, sqlx::Postgres> + sqlx::Type<sqlx::Postgres>
1066 {}
1067
1068 pub trait PostgresIndex: sqlx::ColumnIndex<PgRow> {}
1069 impl<T: sqlx::ColumnIndex<PgRow>> PostgresIndex for T {}
1070 }
1071
1072 #[cfg(not(feature = "postgres"))]
1073 mod on {
1074 pub trait Postgres {}
1075 impl<T: ?Sized> Postgres for T {}
1076
1077 pub trait PostgresIndex {}
1078 impl<T: ?Sized> PostgresIndex for T {}
1079 }
1080
1081 pub use on::{Postgres, PostgresIndex};
1082}
1083
1084#[cfg(test)]
1085mod tests {
1086 use super::{numbered_placeholders, seal};
1087 use crate::db::DbValue;
1088
1089 #[test]
1090 fn numbers_placeholders_outside_quotes_and_comments() {
1091 assert_eq!(
1092 numbered_placeholders("SELECT * FROM t WHERE a = ? AND b IN (?, ?)"),
1093 "SELECT * FROM t WHERE a = $1 AND b IN ($2, $3)"
1094 );
1095 assert_eq!(
1096 numbered_placeholders("SELECT '?', \"a?\" -- why?\nFROM t /* ? */ WHERE x = ?"),
1097 "SELECT '?', \"a?\" -- why?\nFROM t /* ? */ WHERE x = $1"
1098 );
1099 assert_eq!(
1100 numbered_placeholders("SELECT 'it''s ?' WHERE y = ?"),
1101 "SELECT 'it''s ?' WHERE y = $1"
1102 );
1103 assert_eq!(numbered_placeholders("SELECT 1"), "SELECT 1");
1104 }
1105
1106 #[test]
1108 fn skips_dollar_quoted_and_escaped_strings() {
1109 assert_eq!(
1110 numbered_placeholders("SELECT $$why?$$, $fn$ a ? b $fn$ WHERE x = ?"),
1111 "SELECT $$why?$$, $fn$ a ? b $fn$ WHERE x = $1"
1112 );
1113 assert_eq!(
1114 numbered_placeholders(r"SELECT E'it\'s ?', e'\\' WHERE y = ? AND z = ?"),
1115 r"SELECT E'it\'s ?', e'\\' WHERE y = $1 AND z = $2"
1116 );
1117 assert_eq!(
1119 numbered_placeholders(r"SELECT '\', a$b$ FROM t WHERE c = ?"),
1120 r"SELECT '\', a$b$ FROM t WHERE c = $1"
1121 );
1122 assert_eq!(
1123 numbered_placeholders("SELECT 'é?' WHERE ü = ?"),
1124 "SELECT 'é?' WHERE ü = $1"
1125 );
1126 }
1127
1128 #[test]
1131 fn placeholders_after_unfinished_quotes_stay() {
1132 assert_eq!(numbered_placeholders("SELECT 'open ?"), "SELECT 'open ?");
1133 assert_eq!(numbered_placeholders("SELECT 1 -- ?"), "SELECT 1 -- ?");
1134 assert_eq!(numbered_placeholders("SELECT 1 /* ?"), "SELECT 1 /* ?");
1135 assert_eq!(numbered_placeholders("SELECT $tag$ ?"), "SELECT $tag$ ?");
1136 assert_eq!(numbered_placeholders("SELECT ? || $"), "SELECT $1 || $");
1137 assert!(numbered_placeholders("SELECT $1, ?").ends_with(", $1"));
1139 assert_eq!(numbered_placeholders("?"), "$1");
1140 }
1141
1142 #[tokio::test]
1145 async fn retrying_follows_the_error_kind() {
1146 use std::sync::Arc;
1147 use std::sync::atomic::{AtomicU32, Ordering};
1148
1149 use crate::db::DbError;
1150 use crate::db::error::fake;
1151
1152 fn busy() -> crate::Error {
1153 crate::Error::from(DbError::from(fake::coded(Some("5"))))
1154 }
1155 let db = super::super::connect(&crate::Config::default())
1156 .await
1157 .unwrap();
1158
1159 let tries = Arc::new(AtomicU32::new(0));
1160 let counter = tries.clone();
1161 let value = db
1162 .retrying(3, move || {
1163 let counter = counter.clone();
1164 async move {
1165 match counter.fetch_add(1, Ordering::SeqCst) {
1166 0 | 1 => Err(busy()),
1167 _ => Ok("done"),
1168 }
1169 }
1170 })
1171 .await
1172 .unwrap();
1173 assert_eq!((value, tries.load(Ordering::SeqCst)), ("done", 3));
1174
1175 let tries = Arc::new(AtomicU32::new(0));
1176 let counter = tries.clone();
1177 let err = db
1178 .retrying(2, move || {
1179 counter.fetch_add(1, Ordering::SeqCst);
1180 async { Err::<(), _>(busy()) }
1181 })
1182 .await
1183 .unwrap_err();
1184 assert!(err.is_retryable());
1185 assert_eq!(
1186 tries.load(Ordering::SeqCst),
1187 2,
1188 "gives up at the last attempt"
1189 );
1190
1191 let tries = Arc::new(AtomicU32::new(0));
1192 let counter = tries.clone();
1193 let err = db
1194 .retrying(5, move || {
1195 counter.fetch_add(1, Ordering::SeqCst);
1196 async { Err::<(), _>(crate::Error::NotFound) }
1197 })
1198 .await
1199 .unwrap_err();
1200 assert!(matches!(err, crate::Error::NotFound));
1201 assert_eq!(tries.load(Ordering::SeqCst), 1, "not retried");
1202
1203 let tries = Arc::new(AtomicU32::new(0));
1204 let counter = tries.clone();
1205 let value = db
1206 .transaction_retrying(3, move |tx| {
1207 let first = counter.fetch_add(1, Ordering::SeqCst) == 0;
1208 Box::pin(async move {
1209 let one: i64 = super::sql("SELECT CAST(1 AS BIGINT)").scalar(tx).await?;
1210 if first { Err(busy()) } else { Ok(one) }
1211 })
1212 })
1213 .await
1214 .unwrap();
1215 assert_eq!((value, tries.load(Ordering::SeqCst)), (1, 2));
1216 }
1217
1218 #[test]
1220 fn sealing_needs_the_apps_key() {
1221 let err = seal(
1222 None,
1223 vec![DbValue::Encrypted(super::super::encrypted::Unsealed(
1224 "x".into(),
1225 ))],
1226 )
1227 .unwrap_err();
1228 assert!(
1229 err.to_string()
1230 .contains("an Encrypted value needs the app's Db"),
1231 "{err}"
1232 );
1233 assert!(matches!(
1235 seal(None, vec![DbValue::Integer(1)]).unwrap()[..],
1236 [DbValue::Integer(1)]
1237 ));
1238 }
1239}