1pub mod assoc;
24mod cast;
25mod changeset;
26mod decimal;
27mod loaded;
28pub mod migration;
29mod multi;
30mod query;
31pub mod query_cache;
32pub(crate) mod record;
33mod sql;
34mod value;
35
36#[cfg(not(any(feature = "postgres", feature = "sqlite")))]
37compile_error!("glacier needs at least one database feature: `postgres` or `sqlite`");
38
39use std::future::Future;
40use std::sync::Arc;
41use std::sync::atomic::{AtomicBool, Ordering};
42use tracing::Instrument;
43use tracing::field::Empty;
44
45use sqlx::{AssertSqlSafe, Row as _};
46use tokio::sync::Mutex;
47
48pub use assoc::{Association, BelongsTo, ForeignKey, HasMany, HasOne, Nested, ParentKey, Preload};
49pub use cast::Cast;
50pub(crate) use changeset::humanize;
51pub use changeset::{Changeset, Numericality, Save};
52pub use decimal::Decimal;
53pub use loaded::{LoadedRecords, Records};
54pub use multi::{Done, Failure, Multi, MultiError};
55pub use query::{Aggregable, Assign, Batches, Col, Expr, Grouped, Order, Query, Summable};
56pub use record::{Errors, IntoField, Record, accepted, field, normalized, normalized_option};
57pub use sql::{Dialect, Sql, quote_ident};
58pub use uuid::Uuid;
60pub use value::{Date, FromColumn, JsonValue, NaiveTimestamp, Timestamp, ToValue, Value};
61pub use value::{StoreSource, StoreTarget, store_get, store_set};
62
63use crate::config::Config;
64use crate::error::{Error, Result};
65
66const PING_AFTER_IDLE: std::time::Duration = std::time::Duration::from_secs(30);
69
70#[derive(Clone)]
73pub struct Repo {
74 pool: Pool,
75 replica: Option<Arc<Repo>>,
76 name: Arc<str>,
78}
79
80#[derive(Clone)]
81enum Pool {
82 #[cfg(feature = "postgres")]
83 Postgres(sqlx::PgPool),
84 #[cfg(feature = "sqlite")]
85 Sqlite(sqlx::SqlitePool),
86}
87
88impl Repo {
89 pub async fn connect(url: &str) -> Result<Self> {
93 Self::connect_with(url, None).await
94 }
95
96 pub async fn from_config(config: &Config) -> Result<Self> {
100 let url: String = config.get("database.url")?;
101 let pool_size: Option<u32> = config.get_opt("database.pool_size")?;
102 let repo = Self::connect_with(&url, pool_size).await?;
103 match config.get_opt::<String>("database.replica_url")? {
104 Some(replica_url) => {
105 let pool_size: Option<u32> = config.get_opt("database.replica_pool_size")?;
106 Ok(repo.with_replica(Self::connect_with(&replica_url, pool_size).await?))
107 }
108 None => Ok(repo),
109 }
110 }
111
112 pub async fn from_config_named(config: &Config, name: &str) -> Result<Self> {
116 let key = |setting: &str| format!("databases.{name}.{setting}");
117 let url: String = config.get(&key("url"))?;
118 let pool_size: Option<u32> = config.get_opt(&key("pool_size"))?;
119 let repo = Self::connect_with(&url, pool_size).await?;
120 match config.get_opt::<String>(&key("replica_url"))? {
121 Some(replica_url) => {
122 let pool_size: Option<u32> = config.get_opt(&key("replica_pool_size"))?;
123 Ok(repo.with_replica(Self::connect_with(&replica_url, pool_size).await?))
124 }
125 None => Ok(repo),
126 }
127 }
128
129 pub fn with_replica(mut self, replica: Repo) -> Self {
134 assert_eq!(
135 self.dialect(),
136 replica.dialect(),
137 "a replica is the same kind of database as its primary"
138 );
139 self.replica = Some(Arc::new(Repo {
140 pool: replica.pool,
141 name: replica.name,
142 replica: None,
143 }));
144 self
145 }
146
147 pub fn name(&self) -> &str {
150 &self.name
151 }
152
153 pub fn has_replica(&self) -> bool {
155 self.replica.is_some()
156 }
157
158 async fn connect_with(url: &str, pool_size: Option<u32>) -> Result<Self> {
159 let pool = if url.starts_with("postgres://") || url.starts_with("postgresql://") {
160 Self::postgres(url, pool_size).await?
161 } else if url.starts_with("sqlite:") {
162 Self::sqlite(url, pool_size).await?
163 } else {
164 return Err(Error::internal(format!(
165 "unsupported database URL `{url}`; expected postgres:// or sqlite:"
166 )));
167 };
168 Ok(Self {
169 pool,
170 replica: None,
171 name: without_credentials(url).into(),
172 })
173 }
174
175 #[cfg(feature = "postgres")]
176 async fn postgres(url: &str, pool_size: Option<u32>) -> Result<Pool> {
177 use std::str::FromStr;
178
179 let mut options = sqlx::postgres::PgConnectOptions::from_str(url)?;
180 if !has_user(url)
183 && std::env::var_os("PGUSER").is_none()
184 && let Some(user) = std::env::var("USER").ok().filter(|u| !u.is_empty())
185 {
186 options = options.username(&user);
187 }
188 let pool = sqlx::postgres::PgPoolOptions::new()
189 .max_connections(pool_size.unwrap_or(10))
190 .test_before_acquire(false)
196 .before_acquire(|conn, meta| {
197 Box::pin(async move {
198 if meta.idle_for >= PING_AFTER_IDLE {
199 sqlx::Connection::ping(conn).await?;
200 }
201 Ok(true)
202 })
203 })
204 .connect_with(options)
205 .await?;
206 Ok(Pool::Postgres(pool))
207 }
208
209 #[cfg(not(feature = "postgres"))]
210 async fn postgres(_url: &str, _pool_size: Option<u32>) -> Result<Pool> {
211 Err(Error::internal(
212 "Postgres support needs glacier's `postgres` feature",
213 ))
214 }
215
216 #[cfg(feature = "sqlite")]
217 async fn sqlite(url: &str, pool_size: Option<u32>) -> Result<Pool> {
218 use std::path::Path;
219 use std::str::FromStr;
220
221 use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
222
223 let memory = url.contains(":memory:") || url.contains("mode=memory");
224 if !memory {
225 let path = url
226 .trim_start_matches("sqlite://")
227 .trim_start_matches("sqlite:");
228 let path = path.split('?').next().unwrap_or(path);
229 if let Some(dir) = Path::new(path)
230 .parent()
231 .filter(|d| !d.as_os_str().is_empty())
232 {
233 std::fs::create_dir_all(dir)?;
234 }
235 }
236 let options = SqliteConnectOptions::from_str(url)?
237 .create_if_missing(true)
238 .foreign_keys(true);
239 let pool = if memory {
240 SqlitePoolOptions::new()
243 .max_connections(1)
244 .min_connections(1)
245 .idle_timeout(None)
246 .max_lifetime(None)
247 } else {
248 SqlitePoolOptions::new().max_connections(pool_size.unwrap_or(5))
249 };
250 Ok(Pool::Sqlite(pool.connect_with(options).await?))
251 }
252
253 #[cfg(not(feature = "sqlite"))]
254 async fn sqlite(_url: &str, _pool_size: Option<u32>) -> Result<Pool> {
255 Err(Error::internal(
256 "SQLite support needs glacier's `sqlite` feature",
257 ))
258 }
259
260 #[cfg(feature = "postgres")]
267 pub fn postgres_pool(&self) -> Option<&sqlx::PgPool> {
268 match &self.pool {
269 Pool::Postgres(pool) => Some(pool),
270 #[allow(unreachable_patterns)]
271 _ => None,
272 }
273 }
274
275 #[cfg(feature = "sqlite")]
278 pub fn sqlite_pool(&self) -> Option<&sqlx::SqlitePool> {
279 match &self.pool {
280 Pool::Sqlite(pool) => Some(pool),
281 #[allow(unreachable_patterns)]
282 _ => None,
283 }
284 }
285
286 pub async fn close(&self) {
289 match &self.pool {
290 #[cfg(feature = "postgres")]
291 Pool::Postgres(pool) => pool.close().await,
292 #[cfg(feature = "sqlite")]
293 Pool::Sqlite(pool) => pool.close().await,
294 }
295 if let Some(replica) = &self.replica {
296 Box::pin(replica.close()).await;
297 }
298 }
299
300 pub fn dialect(&self) -> Dialect {
301 match self.pool {
302 #[cfg(feature = "postgres")]
303 Pool::Postgres(_) => Dialect::Postgres,
304 #[cfg(feature = "sqlite")]
305 Pool::Sqlite(_) => Dialect::Sqlite,
306 }
307 }
308
309 pub async fn begin(&self) -> Result<Transaction> {
312 let inner = match &self.pool {
313 #[cfg(feature = "postgres")]
314 Pool::Postgres(pool) => TxInner::Postgres(pool.begin().await?),
315 #[cfg(feature = "sqlite")]
316 Pool::Sqlite(pool) => TxInner::Sqlite(pool.begin().await?),
317 };
318 Ok(Transaction {
319 inner: Arc::new(Mutex::new(Some(inner))),
320 dialect: self.dialect(),
321 name: self.name.clone(),
322 })
323 }
324}
325
326#[derive(Clone)]
329pub struct Transaction {
330 inner: Arc<Mutex<Option<TxInner>>>,
331 dialect: Dialect,
332 name: Arc<str>,
334}
335
336enum TxInner {
337 #[cfg(feature = "postgres")]
338 Postgres(sqlx::Transaction<'static, sqlx::Postgres>),
339 #[cfg(feature = "sqlite")]
340 Sqlite(sqlx::Transaction<'static, sqlx::Sqlite>),
341}
342
343impl Transaction {
344 pub async fn commit(&self) -> Result<()> {
345 query_cache::clear();
346 match self.inner.lock().await.take() {
347 #[cfg(feature = "postgres")]
348 Some(TxInner::Postgres(tx)) => tx.commit().await?,
349 #[cfg(feature = "sqlite")]
350 Some(TxInner::Sqlite(tx)) => tx.commit().await?,
351 None => return Err(Error::internal("transaction already finished")),
352 }
353 Ok(())
354 }
355
356 pub async fn rollback(&self) -> Result<()> {
357 query_cache::clear();
359 match self.inner.lock().await.take() {
360 #[cfg(feature = "postgres")]
361 Some(TxInner::Postgres(tx)) => tx.rollback().await?,
362 #[cfg(feature = "sqlite")]
363 Some(TxInner::Sqlite(tx)) => tx.rollback().await?,
364 None => {}
365 }
366 Ok(())
367 }
368}
369
370#[derive(Clone)]
373pub struct Connection(Conn, Arc<Role>);
374
375struct Role {
377 replica: AtomicBool,
379 wrote: Arc<AtomicBool>,
382}
383
384impl Role {
385 fn new(replica: bool) -> Arc<Self> {
386 Arc::new(Self {
387 replica: AtomicBool::new(replica),
388 wrote: Arc::new(AtomicBool::new(false)),
389 })
390 }
391}
392
393#[derive(Clone)]
394enum Conn {
395 Repo(Repo),
396 Tx(Transaction),
397 Held(Held),
401}
402
403#[derive(Clone)]
404struct Held {
405 repo: Repo,
406 slot: Arc<Mutex<Option<HeldConn>>>,
407}
408
409enum HeldConn {
410 #[cfg(feature = "postgres")]
411 Postgres(sqlx::pool::PoolConnection<sqlx::Postgres>),
412 #[cfg(feature = "sqlite")]
413 Sqlite(sqlx::pool::PoolConnection<sqlx::Sqlite>),
414}
415
416impl Held {
417 fn new(repo: &Repo) -> Self {
418 Self {
419 repo: repo.clone(),
420 slot: Arc::new(Mutex::new(None)),
421 }
422 }
423
424 async fn acquire(&self) -> std::result::Result<HeldConn, sqlx::Error> {
425 Ok(match &self.repo.pool {
426 #[cfg(feature = "postgres")]
427 Pool::Postgres(pool) => HeldConn::Postgres(pool.acquire().await?),
428 #[cfg(feature = "sqlite")]
429 Pool::Sqlite(pool) => HeldConn::Sqlite(pool.acquire().await?),
430 })
431 }
432
433 async fn begin(&self) -> Result<Transaction> {
437 let held = self.slot.lock().await.take();
438 let inner = match held {
439 #[cfg(feature = "postgres")]
440 Some(HeldConn::Postgres(conn)) => {
441 TxInner::Postgres(sqlx::Transaction::begin(conn, None).await?)
442 }
443 #[cfg(feature = "sqlite")]
444 Some(HeldConn::Sqlite(conn)) => {
445 TxInner::Sqlite(sqlx::Transaction::begin(conn, None).await?)
446 }
447 None => return self.repo.begin().await,
448 };
449 Ok(Transaction {
450 inner: Arc::new(Mutex::new(Some(inner))),
451 dialect: self.repo.dialect(),
452 name: self.repo.name.clone(),
453 })
454 }
455}
456
457impl From<&Repo> for Connection {
458 fn from(repo: &Repo) -> Self {
459 Connection(Conn::Repo(repo.clone()), Role::new(false))
460 }
461}
462
463impl From<&Transaction> for Connection {
464 fn from(tx: &Transaction) -> Self {
465 Connection(Conn::Tx(tx.clone()), Role::new(false))
466 }
467}
468
469tokio::task_local! {
470 static CURRENT: Connection;
471 static NAMED: Arc<Vec<(String, Connection)>>;
473}
474
475pub fn current_in(database: Option<&str>) -> Result<Connection> {
478 let Some(name) = database else {
479 return current();
480 };
481 NAMED
482 .try_with(|named| {
483 named
484 .iter()
485 .find(|(n, _)| n == name)
486 .map(|(_, conn)| conn.clone())
487 })
488 .ok()
489 .flatten()
490 .ok_or_else(|| {
491 Error::internal(format!(
492 "no `{name}` database here: register it with \
493 App::named_database(\"{name}\", repo), or wrap the code in \
494 glacier::db::with_named(\"{name}\", &repo, ..)"
495 ))
496 })
497}
498
499pub(crate) fn has_named(name: &str) -> bool {
501 NAMED
502 .try_with(|named| named.iter().any(|(n, _)| n == name))
503 .unwrap_or(false)
504}
505
506pub(crate) async fn scope_named<F: Future>(
509 connections: Vec<(String, Connection)>,
510 fut: F,
511) -> F::Output {
512 if connections.is_empty() {
513 return fut.await;
514 }
515 let mut named = NAMED.try_with(|n| (**n).clone()).unwrap_or_default();
516 for (name, conn) in connections {
517 named.retain(|(n, _)| *n != name);
518 named.push((name, conn));
519 }
520 NAMED.scope(Arc::new(named), fut).await
521}
522
523pub async fn with_named<F: Future>(name: &str, repo: &Repo, fut: F) -> F::Output {
526 scope_named(vec![(name.to_owned(), Connection::from(repo))], fut).await
527}
528
529pub async fn sandbox_named<F: Future>(name: &str, repo: &Repo, fut: F) -> Result<F::Output> {
532 let tx = repo.begin().await?;
533 let output = scope_named(vec![(name.to_owned(), Connection::from(&tx))], fut).await;
534 tx.rollback().await?;
535 Ok(output)
536}
537
538pub fn current() -> Result<Connection> {
540 CURRENT.try_with(Connection::clone).map_err(|_| {
541 Error::internal(
542 "no database connection here: register one with App::database(repo), \
543 wrap the code in glacier::db::with(&repo, ..), or call .on(&repo)",
544 )
545 })
546}
547
548pub(crate) fn scope<F: Future>(conn: Connection, fut: F) -> impl Future<Output = F::Output> {
549 CURRENT.scope(conn, fut)
550}
551
552pub fn active() -> bool {
554 CURRENT.try_with(|_| ()).is_ok()
555}
556
557pub async fn with<F: Future>(repo: &Repo, fut: F) -> F::Output {
560 CURRENT.scope(Connection::from(repo), fut).await
561}
562
563pub async fn reading<F: Future>(fut: F) -> F::Output {
569 in_role(true, fut).await
570}
571
572pub async fn writing<F: Future>(fut: F) -> F::Output {
576 in_role(false, fut).await
577}
578
579async fn in_role<F: Future>(replica: bool, fut: F) -> F::Output {
580 let with_role = |conn: &Connection| {
581 let role = Arc::new(Role {
582 replica: AtomicBool::new(replica),
583 wrote: conn.1.wrote.clone(),
584 });
585 Connection(conn.0.clone(), role)
586 };
587 let named: Vec<(String, Connection)> = NAMED
588 .try_with(|named| {
589 named
590 .iter()
591 .map(|(name, conn)| (name.clone(), with_role(conn)))
592 .collect()
593 })
594 .unwrap_or_default();
595 let fut = scope_named(named, fut);
596 match current() {
597 Ok(conn) => CURRENT.scope(with_role(&conn), fut).await,
598 Err(_) => fut.await,
599 }
600}
601
602pub(crate) const REPLICA_DELAY_SECONDS: i64 = 2;
605
606pub(crate) const LAST_WRITE_COOKIE: &str = "_glacier_last_write";
608
609pub(crate) fn request_connection(repo: &Repo, replica: bool) -> Connection {
611 Connection(
612 Conn::Held(Held::new(repo)),
613 Role::new(replica && repo.has_replica()),
614 )
615}
616
617pub async fn transaction<T, F>(fut: F) -> Result<T>
633where
634 F: Future<Output = Result<T>>,
635{
636 transaction_in(None, fut).await
637}
638
639pub async fn transaction_in<T, F>(database: Option<&str>, fut: F) -> Result<T>
642where
643 F: Future<Output = Result<T>>,
644{
645 let conn = current_in(database)?;
646 let tx = match &conn.0 {
647 Conn::Tx(_) => return fut.await,
648 Conn::Repo(repo) => repo.begin().await?,
649 Conn::Held(held) => held.begin().await?,
650 };
651 let inside = Connection(Conn::Tx(tx.clone()), conn.1.clone());
652 let result = match database {
653 None => CURRENT.scope(inside, fut).await,
654 Some(name) => scope_named(vec![(name.to_owned(), inside)], fut).await,
655 };
656 match result {
657 Ok(value) => {
658 tx.commit().await?;
659 Ok(value)
660 }
661 Err(err) => {
662 tx.rollback().await?;
663 Err(err)
664 }
665 }
666}
667
668pub async fn savepoint<T, F>(fut: F) -> Result<T>
672where
673 F: Future<Output = Result<T>>,
674{
675 savepoint_in(None, fut).await
676}
677
678pub async fn savepoint_in<T, F>(database: Option<&str>, fut: F) -> Result<T>
680where
681 F: Future<Output = Result<T>>,
682{
683 static SAVEPOINTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
684 let conn = current_in(database)?;
685 if !conn.in_transaction() {
686 return transaction_in(database, fut).await;
687 }
688 let name = format!(
689 "glacier_nested_{}",
690 SAVEPOINTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
691 );
692 conn.execute(Sql::new().push(&format!("SAVEPOINT {name}")))
693 .await?;
694 let result = fut.await;
695 let finish = if result.is_ok() {
696 format!("RELEASE SAVEPOINT {name}")
697 } else {
698 format!("ROLLBACK TO SAVEPOINT {name}")
699 };
700 conn.execute(Sql::new().push(&finish)).await?;
701 result
702}
703
704pub async fn sandbox<F: Future>(repo: &Repo, fut: F) -> Result<F::Output> {
708 let tx = repo.begin().await?;
709 let output = CURRENT.scope(Connection::from(&tx), fut).await;
710 tx.rollback().await?;
711 Ok(output)
712}
713
714pub struct Row(RowInner);
716
717enum RowInner {
718 #[cfg(feature = "postgres")]
719 Postgres(sqlx::postgres::PgRow),
720 #[cfg(feature = "sqlite")]
721 Sqlite(sqlx::sqlite::SqliteRow),
722}
723
724macro_rules! column_json {
727 ($row:expr, $i:expr) => {{
728 use sqlx::ValueRef as _;
729 let row = $row;
730 match row.try_get_raw($i) {
731 Ok(raw) if raw.is_null() => serde_json::Value::Null,
732 _ => {
733 if let Ok(v) = row.try_get::<i64, _>($i) {
736 v.into()
737 } else if let Ok(v) = row.try_get::<i32, _>($i) {
738 v.into()
739 } else if let Ok(v) = row.try_get::<i16, _>($i) {
740 v.into()
741 } else if let Ok(v) = row.try_get::<bool, _>($i) {
742 serde_json::Value::Bool(v)
743 } else if let Ok(v) = row.try_get::<f64, _>($i) {
744 v.into()
745 } else if let Ok(v) = row.try_get::<String, _>($i) {
748 v.into()
749 } else if let Ok(v) = row.try_get::<Decimal, _>($i) {
750 serde_json::Value::String(v.to_string())
751 } else if let Ok(v) = row.try_get::<chrono::DateTime<chrono::Utc>, _>($i) {
752 v.to_rfc3339().into()
753 } else if let Ok(v) = row.try_get::<chrono::NaiveDateTime, _>($i) {
754 v.to_string().into()
755 } else if let Ok(v) = row.try_get::<chrono::NaiveDate, _>($i) {
756 v.to_string().into()
757 } else if let Ok(v) = row.try_get::<sqlx::types::Json<serde_json::Value>, _>($i) {
758 v.0
759 } else if let Ok(v) = row.try_get::<uuid::Uuid, _>($i) {
760 v.to_string().into()
761 } else {
762 serde_json::Value::String("<unreadable>".into())
763 }
764 }
765 }
766 }};
767}
768
769impl Row {
770 pub fn to_json(&self) -> serde_json::Value {
773 use sqlx::Column as _;
774 let mut object = serde_json::Map::new();
775 match &self.0 {
776 #[cfg(feature = "postgres")]
777 RowInner::Postgres(row) => {
778 for (i, column) in row.columns().iter().enumerate() {
779 object.insert(column.name().to_owned(), column_json!(row, i));
780 }
781 }
782 #[cfg(feature = "sqlite")]
783 RowInner::Sqlite(row) => {
784 for (i, column) in row.columns().iter().enumerate() {
785 object.insert(column.name().to_owned(), column_json!(row, i));
786 }
787 }
788 }
789 serde_json::Value::Object(object)
790 }
791
792 pub fn get<T: FromColumn>(&self, column: &str) -> Result<T> {
793 let result = match &self.0 {
794 #[cfg(feature = "postgres")]
795 RowInner::Postgres(row) => row.try_get(column),
796 #[cfg(feature = "sqlite")]
797 RowInner::Sqlite(row) => row.try_get(column),
798 };
799 result.map_err(|e| Error::internal(format!("reading column `{column}`: {e}")))
800 }
801
802 pub fn first<T: FromColumn>(&self) -> Result<T> {
804 let result = match &self.0 {
805 #[cfg(feature = "postgres")]
806 RowInner::Postgres(row) => row.try_get(0usize),
807 #[cfg(feature = "sqlite")]
808 RowInner::Sqlite(row) => row.try_get(0usize),
809 };
810 result.map_err(|e| Error::internal(format!("reading the first column: {e}")))
811 }
812}
813
814macro_rules! bind_all {
815 ($query:expr, $values:expr, $list:ident) => {{
816 let mut query = $query;
817 for value in $values {
818 query = match value {
819 Value::Null => unreachable!("NULL is rendered inline"),
820 Value::List(items) => bind_list!($list, query, items),
821 Value::Bool(v) => query.bind(v),
822 Value::Int(v) => query.bind(v),
823 Value::Float(v) => query.bind(v),
824 Value::Text(v) => query.bind(v),
825 Value::Bytes(v) => query.bind(v),
826 Value::Json(v) => query.bind(sqlx::types::Json(v)),
827 Value::Decimal(v) => query.bind(v),
828 Value::Uuid(v) => query.bind(v),
829 Value::Timestamp(v) => bind_timestamp!($list, query, v),
830 Value::Date(v) => query.bind(v),
831 };
832 }
833 query
834 }};
835}
836
837macro_rules! bind_timestamp {
841 (postgres, $query:expr, $value:expr) => {
842 $query.bind($value)
843 };
844 (sqlite, $query:expr, $value:expr) => {
845 $query.bind(sqlite_timestamp(&$value))
846 };
847}
848
849pub(crate) fn sqlite_timestamp(at: &Timestamp) -> String {
851 at.format("%Y-%m-%d %H:%M:%S%.6f").to_string()
852}
853
854macro_rules! bind_list {
857 (postgres, $query:expr, $items:expr) => {{
858 let items: Vec<Value> = $items;
859 match items.first() {
860 Some(Value::Int(_)) => $query.bind(
861 items
862 .into_iter()
863 .filter_map(|v| if let Value::Int(n) = v { Some(n) } else { None })
864 .collect::<Vec<i64>>(),
865 ),
866 Some(Value::Uuid(_)) => $query.bind(
867 items
868 .into_iter()
869 .filter_map(|v| {
870 if let Value::Uuid(u) = v {
871 Some(u)
872 } else {
873 None
874 }
875 })
876 .collect::<Vec<uuid::Uuid>>(),
877 ),
878 _ => $query.bind(
879 items
880 .into_iter()
881 .map(|v| v.to_text())
882 .collect::<Vec<String>>(),
883 ),
884 }
885 }};
886 (sqlite, $query:expr, $items:expr) => {{
887 let _ = $items;
888 unreachable!("SQLite lists are rendered as separate values")
889 }};
890}
891
892macro_rules! run {
894 ($conn:expr, $sql:expr, |$query:ident, $executor:ident| $body:expr) => {{
895 let conn: &Connection = $conn;
896 let (text, values) = $sql;
897 match &conn.0 {
898 Conn::Repo(repo) => match &repo.pool {
899 #[cfg(feature = "postgres")]
900 Pool::Postgres(pool) => {
901 let $query = bind_all!(
902 sqlx::query::<sqlx::Postgres>(AssertSqlSafe(text)),
903 values,
904 postgres
905 );
906 let $executor = pool;
907 $body
908 }
909 #[cfg(feature = "sqlite")]
910 Pool::Sqlite(pool) => {
911 let $query = bind_all!(
912 sqlx::query::<sqlx::Sqlite>(AssertSqlSafe(text)),
913 values,
914 sqlite
915 );
916 let $executor = pool;
917 $body
918 }
919 },
920 Conn::Tx(tx) => {
921 let mut guard = tx.inner.lock().await;
922 match guard.as_mut() {
923 #[cfg(feature = "postgres")]
924 Some(TxInner::Postgres(tx)) => {
925 let $query = bind_all!(
926 sqlx::query::<sqlx::Postgres>(AssertSqlSafe(text)),
927 values,
928 postgres
929 );
930 let $executor = &mut **tx;
931 $body
932 }
933 #[cfg(feature = "sqlite")]
934 Some(TxInner::Sqlite(tx)) => {
935 let $query = bind_all!(
936 sqlx::query::<sqlx::Sqlite>(AssertSqlSafe(text)),
937 values,
938 sqlite
939 );
940 let $executor = &mut **tx;
941 $body
942 }
943 None => Err(sqlx::Error::Protocol("transaction already finished".into())),
944 }
945 }
946 Conn::Held(held) => {
947 let mut guard = held.slot.lock().await;
948 let ready = match guard.as_ref() {
949 Some(_) => Ok(()),
950 None => held.acquire().await.map(|conn| {
951 *guard = Some(conn);
952 }),
953 };
954 match (ready, guard.as_mut()) {
955 (Err(err), _) => Err(err),
956 #[cfg(feature = "postgres")]
957 (Ok(()), Some(HeldConn::Postgres(conn))) => {
958 let $query = bind_all!(
959 sqlx::query::<sqlx::Postgres>(AssertSqlSafe(text)),
960 values,
961 postgres
962 );
963 let $executor = &mut **conn;
964 $body
965 }
966 #[cfg(feature = "sqlite")]
967 (Ok(()), Some(HeldConn::Sqlite(conn))) => {
968 let $query = bind_all!(
969 sqlx::query::<sqlx::Sqlite>(AssertSqlSafe(text)),
970 values,
971 sqlite
972 );
973 let $executor = &mut **conn;
974 $body
975 }
976 (Ok(()), None) => unreachable!("just acquired"),
977 }
978 }
979 }
980 }};
981}
982
983impl Connection {
984 pub fn dialect(&self) -> Dialect {
985 match &self.0 {
986 Conn::Repo(repo) => repo.dialect(),
987 Conn::Held(held) => held.repo.dialect(),
988 Conn::Tx(tx) => tx.dialect,
989 }
990 }
991
992 pub(crate) fn in_transaction(&self) -> bool {
993 matches!(self.0, Conn::Tx(_))
994 }
995
996 pub(crate) fn wrote(&self) -> bool {
999 self.1.wrote.load(Ordering::Relaxed)
1000 }
1001
1002 fn replica(&self) -> Option<Connection> {
1004 match &self.0 {
1005 Conn::Repo(repo) | Conn::Held(Held { repo, .. })
1006 if self.1.replica.load(Ordering::Relaxed) =>
1007 {
1008 let replica = repo.replica.as_deref()?.clone();
1009 Some(Connection(Conn::Repo(replica), self.1.clone()))
1010 }
1011 _ => None,
1012 }
1013 }
1014
1015 fn wrote_now(&self) {
1018 self.1.replica.store(false, Ordering::Relaxed);
1019 self.1.wrote.store(true, Ordering::Relaxed);
1020 query_cache::clear();
1021 }
1022
1023 fn database_name(&self) -> &str {
1025 match &self.0 {
1026 Conn::Repo(repo) | Conn::Held(Held { repo, .. }) => &repo.name,
1027 Conn::Tx(tx) => &tx.name,
1028 }
1029 }
1030
1031 pub(crate) async fn read_all(
1035 &self,
1036 sql: &Sql,
1037 ) -> std::result::Result<query_cache::Rows, sqlx::Error> {
1038 let rendered = sql.render(self.dialect());
1039 let key = (query_cache::active() && is_cacheable(&rendered.0))
1040 .then(|| format!("{}\0{}\0{:?}", self.database_name(), rendered.0, rendered.1));
1041 if let Some(rows) = key.as_deref().and_then(query_cache::get) {
1042 tracing::debug!(target: "glacier", "CACHE {}", rendered.0);
1043 return Ok(rows);
1044 }
1045 let rows: query_cache::Rows = match self.replica() {
1046 Some(replica) => replica.run_all(rendered).await?,
1047 None => {
1048 if !is_select(&rendered.0) {
1049 self.wrote_now();
1050 }
1051 self.run_all(rendered).await?
1052 }
1053 }
1054 .into();
1055 if let Some(key) = key {
1056 query_cache::put(key, rows.clone());
1057 }
1058 Ok(rows)
1059 }
1060
1061 pub(crate) async fn fetch_all(&self, sql: &Sql) -> std::result::Result<Vec<Row>, sqlx::Error> {
1064 let rendered = sql.render(self.dialect());
1065 if !is_select(&rendered.0) {
1066 self.wrote_now();
1067 }
1068 self.run_all(rendered).await
1069 }
1070
1071 async fn run_all(
1072 &self,
1073 (text, values): (String, Vec<Value>),
1074 ) -> std::result::Result<Vec<Row>, sqlx::Error> {
1075 let retry = matches!(self.0, Conn::Repo(_) | Conn::Held(_)) && is_select(&text);
1080 let again = retry.then(|| (text.clone(), values.clone()));
1081 let rows = self.run_once((text, values)).await;
1082 match (rows, again) {
1083 (Err(err), Some(again)) if is_lost_connection(&err) => {
1084 tracing::warn!(target: "glacier", "database connection lost ({err}); retrying the query");
1085 if let Conn::Held(held) = &self.0 {
1086 held.slot.lock().await.take();
1088 }
1089 self.run_once(again).await
1090 }
1091 (rows, _) => rows,
1092 }
1093 }
1094
1095 async fn run_once(
1096 &self,
1097 (text, values): (String, Vec<Value>),
1098 ) -> std::result::Result<Vec<Row>, sqlx::Error> {
1099 let span = query_span(self.dialect(), &text);
1100 let rows: std::result::Result<Vec<Row>, sqlx::Error> =
1101 run!(self, (text, values), |query, executor| {
1102 query
1103 .fetch_all(executor)
1104 .instrument(span.clone())
1105 .await
1106 .map(|rows| rows.into_iter().map(Row::from).collect())
1107 });
1108 finish_query(&span, rows.as_ref().map(Vec::len));
1109 rows
1110 }
1111
1112 pub(crate) async fn execute(&self, sql: &Sql) -> std::result::Result<u64, sqlx::Error> {
1113 self.wrote_now();
1114 let (text, values) = sql.render(self.dialect());
1115 let span = query_span(self.dialect(), &text);
1116 let done: std::result::Result<u64, sqlx::Error> =
1117 run!(self, (text, values), |query, executor| {
1118 query
1119 .execute(executor)
1120 .instrument(span.clone())
1121 .await
1122 .map(|done| done.rows_affected())
1123 });
1124 finish_query(&span, done.as_ref().map(|n| *n as usize));
1125 done
1126 }
1127}
1128
1129fn is_lost_connection(err: &sqlx::Error) -> bool {
1132 match err {
1133 sqlx::Error::Io(_) => true,
1134 sqlx::Error::Database(db) => db
1137 .code()
1138 .is_some_and(|code| code.starts_with("08") || code.starts_with("57P0")),
1139 _ => false,
1140 }
1141}
1142
1143fn is_cacheable(text: &str) -> bool {
1147 let lower = text.to_ascii_lowercase();
1148 is_select(text)
1149 && !lower.contains(" for update")
1150 && !lower.contains(" for share")
1151 && !lower.contains(" for no key update")
1152 && !lower.contains(" for key share")
1153}
1154
1155fn is_select(text: &str) -> bool {
1156 let start = text.trim_start();
1157 let word = start.split_whitespace().next().unwrap_or_default();
1158 word.eq_ignore_ascii_case("select")
1159 || (word.eq_ignore_ascii_case("with")
1160 && !["insert", "update", "delete"]
1161 .iter()
1162 .any(|w| start.to_ascii_lowercase().contains(w)))
1163}
1164
1165fn query_span(dialect: Dialect, text: &str) -> tracing::Span {
1169 record_query(text);
1170 let operation = text
1171 .split_whitespace()
1172 .next()
1173 .unwrap_or_default()
1174 .to_ascii_uppercase();
1175 tracing::info_span!(
1176 target: "glacier",
1177 "glacier.db.query",
1178 otel.name = %operation,
1179 otel.kind = "client",
1180 otel.status_code = Empty,
1181 db.system.name = match dialect {
1182 Dialect::Postgres => "postgresql",
1183 Dialect::Sqlite => "sqlite",
1184 },
1185 db.operation.name = %operation,
1186 db.query.text = %text,
1187 db.response.returned_rows = Empty,
1188 error.message = Empty,
1189 )
1190}
1191
1192fn finish_query(span: &tracing::Span, rows: std::result::Result<usize, &sqlx::Error>) {
1193 match rows {
1194 Ok(rows) => {
1195 span.record(
1196 "db.response.returned_rows",
1197 i64::try_from(rows).unwrap_or(i64::MAX),
1198 );
1199 }
1200 Err(err) => {
1201 span.record("otel.status_code", "ERROR");
1202 span.record("error.message", tracing::field::display(err));
1203 }
1204 }
1205}
1206
1207tokio::task_local! {
1208 static QUERY_LOG: Arc<std::sync::Mutex<Vec<String>>>;
1210}
1211
1212fn record_query(text: &str) {
1213 let _ = QUERY_LOG.try_with(|log| {
1214 log.lock()
1215 .unwrap_or_else(|e| e.into_inner())
1216 .push(text.to_owned());
1217 });
1218}
1219
1220pub(crate) async fn logging_queries<F: Future>(fut: F) -> (F::Output, Vec<String>) {
1223 let log = Arc::new(std::sync::Mutex::new(Vec::new()));
1224 let output = QUERY_LOG.scope(log.clone(), fut).await;
1225 let queries = std::mem::take(&mut *log.lock().unwrap_or_else(|e| e.into_inner()));
1226 (output, queries)
1227}
1228
1229tokio::task_local! {
1230 static DEVELOPMENT: ();
1232}
1233
1234pub(crate) async fn development_checks<F: Future>(fut: F) -> F::Output {
1236 DEVELOPMENT.scope((), fut).await
1237}
1238
1239pub(crate) async fn warn_unindexed(conn: &Connection, table: &'static str, column: &'static str) {
1243 static CHECKED: std::sync::Mutex<Vec<(&'static str, &'static str)>> =
1244 std::sync::Mutex::new(Vec::new());
1245 if DEVELOPMENT.try_with(|()| ()).is_err() {
1246 return;
1247 }
1248 {
1249 let mut checked = CHECKED.lock().unwrap_or_else(|e| e.into_inner());
1250 if checked.contains(&(table, column)) {
1251 return;
1252 }
1253 checked.push((table, column));
1254 }
1255 let mut sql = Sql::new();
1256 match conn.dialect() {
1257 Dialect::Sqlite => {
1258 sql.push("SELECT 1 AS found FROM pragma_index_list(")
1259 .push_value(Value::Text(table.to_owned()))
1260 .push(") l JOIN pragma_index_info(l.name) i WHERE i.seqno = 0 AND i.name = ")
1261 .push_value(Value::Text(column.to_owned()));
1262 }
1263 Dialect::Postgres => {
1264 sql.push(
1265 "SELECT 1 AS found FROM pg_index x JOIN pg_class t ON t.oid = x.indrelid \
1266 JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = x.indkey[0] \
1267 WHERE t.relnamespace = current_schema()::regnamespace AND t.relname = ",
1268 )
1269 .push_value(Value::Text(table.to_owned()))
1270 .push(" AND a.attname = ")
1271 .push_value(Value::Text(column.to_owned()));
1272 }
1273 }
1274 if let Ok(rows) = conn.fetch_all(&sql).await
1275 && rows.is_empty()
1276 {
1277 tracing::warn!(
1278 target: "glacier",
1279 "cursor pagination on `{table}` orders by `{column}`, which no index starts \
1280 with, so every page reads the whole table; add one in a migration: \
1281 add_index :{table}, [:{column}, :id]"
1282 );
1283 }
1284}
1285
1286pub(crate) const REPEATED_QUERY_THRESHOLD: usize = 3;
1289
1290pub(crate) fn repeated_selects(queries: &[String], at_least: usize) -> Vec<(String, usize)> {
1293 let mut counts: Vec<(String, usize)> = Vec::new();
1294 for query in queries.iter().filter(|q| is_select(q)) {
1295 match counts.iter_mut().find(|(q, _)| q == query) {
1296 Some((_, n)) => *n += 1,
1297 None => counts.push((query.clone(), 1)),
1298 }
1299 }
1300 counts.retain(|(_, n)| *n >= at_least);
1301 counts
1302}
1303
1304#[cfg(feature = "postgres")]
1305impl From<sqlx::postgres::PgRow> for Row {
1306 fn from(row: sqlx::postgres::PgRow) -> Self {
1307 Row(RowInner::Postgres(row))
1308 }
1309}
1310
1311#[cfg(feature = "sqlite")]
1312impl From<sqlx::sqlite::SqliteRow> for Row {
1313 fn from(row: sqlx::sqlite::SqliteRow) -> Self {
1314 Row(RowInner::Sqlite(row))
1315 }
1316}
1317
1318pub fn sql(text: &str) -> RawQuery {
1331 RawQuery {
1332 text: text.to_owned(),
1333 values: Vec::new(),
1334 conn: None,
1335 }
1336}
1337
1338pub struct RawQuery {
1339 text: String,
1340 values: Vec<Value>,
1341 conn: Option<Connection>,
1342}
1343
1344impl RawQuery {
1345 pub fn bind(mut self, value: impl ToValue) -> Self {
1346 self.values.push(value.to_value());
1347 self
1348 }
1349
1350 pub fn on(mut self, conn: impl Into<Connection>) -> Self {
1351 self.conn = Some(conn.into());
1352 self
1353 }
1354
1355 fn statement(&self) -> Result<(Connection, Sql)> {
1356 let conn = match &self.conn {
1357 Some(conn) => conn.clone(),
1358 None => current()?,
1359 };
1360 Ok((conn, Sql::raw(&self.text, self.values.clone())))
1361 }
1362
1363 pub async fn fetch_all(self) -> Result<Vec<Row>> {
1364 let (conn, sql) = self.statement()?;
1365 Ok(conn.fetch_all(&sql).await?)
1366 }
1367
1368 pub async fn values<T: FromColumn>(self) -> Result<Vec<T>> {
1371 self.fetch_all().await?.iter().map(Row::first).collect()
1372 }
1373
1374 pub async fn value<T: FromColumn>(self) -> Result<Option<T>> {
1377 self.fetch_all().await?.first().map(Row::first).transpose()
1378 }
1379
1380 pub async fn execute(self) -> Result<u64> {
1382 let (conn, sql) = self.statement()?;
1383 Ok(conn.execute(&sql).await?)
1384 }
1385}
1386
1387#[cfg_attr(not(feature = "postgres"), allow(dead_code))]
1389fn has_user(url: &str) -> bool {
1390 let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
1391 let authority = rest.split(['/', '?']).next().unwrap_or(rest);
1392 authority.contains('@')
1393}
1394
1395#[cfg(test)]
1396mod url_tests {
1397 #[test]
1398 fn finds_users_in_urls() {
1399 assert!(super::has_user("postgres://me@localhost/db"));
1400 assert!(super::has_user(
1401 "postgres://me:secret@localhost:5432/db?sslmode=disable"
1402 ));
1403 assert!(!super::has_user("postgres://localhost/db"));
1404 assert!(!super::has_user("postgres://localhost/db?options=a@b"));
1405 }
1406}
1407
1408fn without_credentials(url: &str) -> String {
1411 match (url.split_once("://"), url.rfind('@')) {
1412 (Some((scheme, _)), Some(at)) => format!("{scheme}://{}", &url[at + 1..]),
1413 _ => url.to_owned(),
1414 }
1415}
1416
1417#[cfg(test)]
1418mod name_tests {
1419 #[test]
1420 fn hides_credentials() {
1421 assert_eq!(
1422 super::without_credentials("postgres://me:secret@db.internal:5432/shop"),
1423 "postgres://db.internal:5432/shop"
1424 );
1425 assert_eq!(
1426 super::without_credentials("sqlite://db/development.sqlite3"),
1427 "sqlite://db/development.sqlite3"
1428 );
1429 }
1430}