pub mod assoc;
mod cast;
mod changeset;
mod decimal;
pub mod migration;
mod multi;
mod query;
pub mod query_cache;
pub(crate) mod record;
mod sql;
mod value;
#[cfg(not(any(feature = "postgres", feature = "sqlite")))]
compile_error!("glacier needs at least one database feature: `postgres` or `sqlite`");
use std::future::Future;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use tracing::Instrument;
use tracing::field::Empty;
use sqlx::{AssertSqlSafe, Row as _};
use tokio::sync::Mutex;
pub use assoc::{Association, BelongsTo, HasMany, Nested, Preload};
pub use cast::Cast;
pub(crate) use changeset::humanize;
pub use changeset::{Changeset, Numericality, Save};
pub use decimal::Decimal;
pub use multi::{Done, Failure, Multi, MultiError};
pub use query::{Aggregable, Assign, Batches, Col, Expr, Grouped, Order, Query, Summable};
pub use record::{Errors, IntoField, Record, field};
pub use sql::{Dialect, Sql, quote_ident};
pub use uuid::Uuid;
pub use value::{Date, FromColumn, JsonValue, NaiveTimestamp, Timestamp, ToValue, Value};
pub use value::{StoreSource, StoreTarget, store_get, store_set};
use crate::config::Config;
use crate::error::{Error, Result};
const PING_AFTER_IDLE: std::time::Duration = std::time::Duration::from_secs(30);
#[derive(Clone)]
pub struct Repo {
pool: Pool,
replica: Option<Arc<Repo>>,
name: Arc<str>,
}
#[derive(Clone)]
enum Pool {
#[cfg(feature = "postgres")]
Postgres(sqlx::PgPool),
#[cfg(feature = "sqlite")]
Sqlite(sqlx::SqlitePool),
}
impl Repo {
pub async fn connect(url: &str) -> Result<Self> {
Self::connect_with(url, None).await
}
pub async fn from_config(config: &Config) -> Result<Self> {
let url: String = config.get("database.url")?;
let pool_size: Option<u32> = config.get_opt("database.pool_size")?;
let repo = Self::connect_with(&url, pool_size).await?;
match config.get_opt::<String>("database.replica_url")? {
Some(replica_url) => {
let pool_size: Option<u32> = config.get_opt("database.replica_pool_size")?;
Ok(repo.with_replica(Self::connect_with(&replica_url, pool_size).await?))
}
None => Ok(repo),
}
}
pub async fn from_config_named(config: &Config, name: &str) -> Result<Self> {
let key = |setting: &str| format!("databases.{name}.{setting}");
let url: String = config.get(&key("url"))?;
let pool_size: Option<u32> = config.get_opt(&key("pool_size"))?;
let repo = Self::connect_with(&url, pool_size).await?;
match config.get_opt::<String>(&key("replica_url"))? {
Some(replica_url) => {
let pool_size: Option<u32> = config.get_opt(&key("replica_pool_size"))?;
Ok(repo.with_replica(Self::connect_with(&replica_url, pool_size).await?))
}
None => Ok(repo),
}
}
pub fn with_replica(mut self, replica: Repo) -> Self {
assert_eq!(
self.dialect(),
replica.dialect(),
"a replica is the same kind of database as its primary"
);
self.replica = Some(Arc::new(Repo {
pool: replica.pool,
name: replica.name,
replica: None,
}));
self
}
pub fn name(&self) -> &str {
&self.name
}
pub fn has_replica(&self) -> bool {
self.replica.is_some()
}
async fn connect_with(url: &str, pool_size: Option<u32>) -> Result<Self> {
let pool = if url.starts_with("postgres://") || url.starts_with("postgresql://") {
Self::postgres(url, pool_size).await?
} else if url.starts_with("sqlite:") {
Self::sqlite(url, pool_size).await?
} else {
return Err(Error::internal(format!(
"unsupported database URL `{url}`; expected postgres:// or sqlite:"
)));
};
Ok(Self {
pool,
replica: None,
name: without_credentials(url).into(),
})
}
#[cfg(feature = "postgres")]
async fn postgres(url: &str, pool_size: Option<u32>) -> Result<Pool> {
use std::str::FromStr;
let mut options = sqlx::postgres::PgConnectOptions::from_str(url)?;
if !has_user(url)
&& std::env::var_os("PGUSER").is_none()
&& let Some(user) = std::env::var("USER").ok().filter(|u| !u.is_empty())
{
options = options.username(&user);
}
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(pool_size.unwrap_or(10))
.test_before_acquire(false)
.before_acquire(|conn, meta| {
Box::pin(async move {
if meta.idle_for >= PING_AFTER_IDLE {
sqlx::Connection::ping(conn).await?;
}
Ok(true)
})
})
.connect_with(options)
.await?;
Ok(Pool::Postgres(pool))
}
#[cfg(not(feature = "postgres"))]
async fn postgres(_url: &str, _pool_size: Option<u32>) -> Result<Pool> {
Err(Error::internal(
"Postgres support needs glacier's `postgres` feature",
))
}
#[cfg(feature = "sqlite")]
async fn sqlite(url: &str, pool_size: Option<u32>) -> Result<Pool> {
use std::path::Path;
use std::str::FromStr;
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
let memory = url.contains(":memory:") || url.contains("mode=memory");
if !memory {
let path = url
.trim_start_matches("sqlite://")
.trim_start_matches("sqlite:");
let path = path.split('?').next().unwrap_or(path);
if let Some(dir) = Path::new(path)
.parent()
.filter(|d| !d.as_os_str().is_empty())
{
std::fs::create_dir_all(dir)?;
}
}
let options = SqliteConnectOptions::from_str(url)?
.create_if_missing(true)
.foreign_keys(true);
let pool = if memory {
SqlitePoolOptions::new()
.max_connections(1)
.min_connections(1)
.idle_timeout(None)
.max_lifetime(None)
} else {
SqlitePoolOptions::new().max_connections(pool_size.unwrap_or(5))
};
Ok(Pool::Sqlite(pool.connect_with(options).await?))
}
#[cfg(not(feature = "sqlite"))]
async fn sqlite(_url: &str, _pool_size: Option<u32>) -> Result<Pool> {
Err(Error::internal(
"SQLite support needs glacier's `sqlite` feature",
))
}
#[cfg(feature = "postgres")]
pub fn postgres_pool(&self) -> Option<&sqlx::PgPool> {
match &self.pool {
Pool::Postgres(pool) => Some(pool),
#[allow(unreachable_patterns)]
_ => None,
}
}
#[cfg(feature = "sqlite")]
pub fn sqlite_pool(&self) -> Option<&sqlx::SqlitePool> {
match &self.pool {
Pool::Sqlite(pool) => Some(pool),
#[allow(unreachable_patterns)]
_ => None,
}
}
pub async fn close(&self) {
match &self.pool {
#[cfg(feature = "postgres")]
Pool::Postgres(pool) => pool.close().await,
#[cfg(feature = "sqlite")]
Pool::Sqlite(pool) => pool.close().await,
}
if let Some(replica) = &self.replica {
Box::pin(replica.close()).await;
}
}
pub fn dialect(&self) -> Dialect {
match self.pool {
#[cfg(feature = "postgres")]
Pool::Postgres(_) => Dialect::Postgres,
#[cfg(feature = "sqlite")]
Pool::Sqlite(_) => Dialect::Sqlite,
}
}
pub async fn begin(&self) -> Result<Transaction> {
let inner = match &self.pool {
#[cfg(feature = "postgres")]
Pool::Postgres(pool) => TxInner::Postgres(pool.begin().await?),
#[cfg(feature = "sqlite")]
Pool::Sqlite(pool) => TxInner::Sqlite(pool.begin().await?),
};
Ok(Transaction {
inner: Arc::new(Mutex::new(Some(inner))),
dialect: self.dialect(),
name: self.name.clone(),
})
}
}
#[derive(Clone)]
pub struct Transaction {
inner: Arc<Mutex<Option<TxInner>>>,
dialect: Dialect,
name: Arc<str>,
}
enum TxInner {
#[cfg(feature = "postgres")]
Postgres(sqlx::Transaction<'static, sqlx::Postgres>),
#[cfg(feature = "sqlite")]
Sqlite(sqlx::Transaction<'static, sqlx::Sqlite>),
}
impl Transaction {
pub async fn commit(&self) -> Result<()> {
query_cache::clear();
match self.inner.lock().await.take() {
#[cfg(feature = "postgres")]
Some(TxInner::Postgres(tx)) => tx.commit().await?,
#[cfg(feature = "sqlite")]
Some(TxInner::Sqlite(tx)) => tx.commit().await?,
None => return Err(Error::internal("transaction already finished")),
}
Ok(())
}
pub async fn rollback(&self) -> Result<()> {
query_cache::clear();
match self.inner.lock().await.take() {
#[cfg(feature = "postgres")]
Some(TxInner::Postgres(tx)) => tx.rollback().await?,
#[cfg(feature = "sqlite")]
Some(TxInner::Sqlite(tx)) => tx.rollback().await?,
None => {}
}
Ok(())
}
}
#[derive(Clone)]
pub struct Connection(Conn, Arc<Role>);
struct Role {
replica: AtomicBool,
wrote: Arc<AtomicBool>,
}
impl Role {
fn new(replica: bool) -> Arc<Self> {
Arc::new(Self {
replica: AtomicBool::new(replica),
wrote: Arc::new(AtomicBool::new(false)),
})
}
}
#[derive(Clone)]
enum Conn {
Repo(Repo),
Tx(Transaction),
Held(Held),
}
#[derive(Clone)]
struct Held {
repo: Repo,
slot: Arc<Mutex<Option<HeldConn>>>,
}
enum HeldConn {
#[cfg(feature = "postgres")]
Postgres(sqlx::pool::PoolConnection<sqlx::Postgres>),
#[cfg(feature = "sqlite")]
Sqlite(sqlx::pool::PoolConnection<sqlx::Sqlite>),
}
impl Held {
fn new(repo: &Repo) -> Self {
Self {
repo: repo.clone(),
slot: Arc::new(Mutex::new(None)),
}
}
async fn acquire(&self) -> std::result::Result<HeldConn, sqlx::Error> {
Ok(match &self.repo.pool {
#[cfg(feature = "postgres")]
Pool::Postgres(pool) => HeldConn::Postgres(pool.acquire().await?),
#[cfg(feature = "sqlite")]
Pool::Sqlite(pool) => HeldConn::Sqlite(pool.acquire().await?),
})
}
async fn begin(&self) -> Result<Transaction> {
let held = self.slot.lock().await.take();
let inner = match held {
#[cfg(feature = "postgres")]
Some(HeldConn::Postgres(conn)) => {
TxInner::Postgres(sqlx::Transaction::begin(conn, None).await?)
}
#[cfg(feature = "sqlite")]
Some(HeldConn::Sqlite(conn)) => {
TxInner::Sqlite(sqlx::Transaction::begin(conn, None).await?)
}
None => return self.repo.begin().await,
};
Ok(Transaction {
inner: Arc::new(Mutex::new(Some(inner))),
dialect: self.repo.dialect(),
name: self.repo.name.clone(),
})
}
}
impl From<&Repo> for Connection {
fn from(repo: &Repo) -> Self {
Connection(Conn::Repo(repo.clone()), Role::new(false))
}
}
impl From<&Transaction> for Connection {
fn from(tx: &Transaction) -> Self {
Connection(Conn::Tx(tx.clone()), Role::new(false))
}
}
tokio::task_local! {
static CURRENT: Connection;
static NAMED: Arc<Vec<(String, Connection)>>;
}
pub fn current_in(database: Option<&str>) -> Result<Connection> {
let Some(name) = database else {
return current();
};
NAMED
.try_with(|named| {
named
.iter()
.find(|(n, _)| n == name)
.map(|(_, conn)| conn.clone())
})
.ok()
.flatten()
.ok_or_else(|| {
Error::internal(format!(
"no `{name}` database here: register it with \
App::named_database(\"{name}\", repo), or wrap the code in \
glacier::db::with_named(\"{name}\", &repo, ..)"
))
})
}
pub(crate) fn has_named(name: &str) -> bool {
NAMED
.try_with(|named| named.iter().any(|(n, _)| n == name))
.unwrap_or(false)
}
pub(crate) async fn scope_named<F: Future>(
connections: Vec<(String, Connection)>,
fut: F,
) -> F::Output {
if connections.is_empty() {
return fut.await;
}
let mut named = NAMED.try_with(|n| (**n).clone()).unwrap_or_default();
for (name, conn) in connections {
named.retain(|(n, _)| *n != name);
named.push((name, conn));
}
NAMED.scope(Arc::new(named), fut).await
}
pub async fn with_named<F: Future>(name: &str, repo: &Repo, fut: F) -> F::Output {
scope_named(vec![(name.to_owned(), Connection::from(repo))], fut).await
}
pub async fn sandbox_named<F: Future>(name: &str, repo: &Repo, fut: F) -> Result<F::Output> {
let tx = repo.begin().await?;
let output = scope_named(vec![(name.to_owned(), Connection::from(&tx))], fut).await;
tx.rollback().await?;
Ok(output)
}
pub fn current() -> Result<Connection> {
CURRENT.try_with(Connection::clone).map_err(|_| {
Error::internal(
"no database connection here: register one with App::database(repo), \
wrap the code in glacier::db::with(&repo, ..), or call .on(&repo)",
)
})
}
pub(crate) fn scope<F: Future>(conn: Connection, fut: F) -> impl Future<Output = F::Output> {
CURRENT.scope(conn, fut)
}
pub fn active() -> bool {
CURRENT.try_with(|_| ()).is_ok()
}
pub async fn with<F: Future>(repo: &Repo, fut: F) -> F::Output {
CURRENT.scope(Connection::from(repo), fut).await
}
pub async fn reading<F: Future>(fut: F) -> F::Output {
in_role(true, fut).await
}
pub async fn writing<F: Future>(fut: F) -> F::Output {
in_role(false, fut).await
}
async fn in_role<F: Future>(replica: bool, fut: F) -> F::Output {
let with_role = |conn: &Connection| {
let role = Arc::new(Role {
replica: AtomicBool::new(replica),
wrote: conn.1.wrote.clone(),
});
Connection(conn.0.clone(), role)
};
let named: Vec<(String, Connection)> = NAMED
.try_with(|named| {
named
.iter()
.map(|(name, conn)| (name.clone(), with_role(conn)))
.collect()
})
.unwrap_or_default();
let fut = scope_named(named, fut);
match current() {
Ok(conn) => CURRENT.scope(with_role(&conn), fut).await,
Err(_) => fut.await,
}
}
pub(crate) const REPLICA_DELAY_SECONDS: i64 = 2;
pub(crate) const LAST_WRITE_COOKIE: &str = "_glacier_last_write";
pub(crate) fn request_connection(repo: &Repo, replica: bool) -> Connection {
Connection(
Conn::Held(Held::new(repo)),
Role::new(replica && repo.has_replica()),
)
}
pub async fn transaction<T, F>(fut: F) -> Result<T>
where
F: Future<Output = Result<T>>,
{
transaction_in(None, fut).await
}
pub async fn transaction_in<T, F>(database: Option<&str>, fut: F) -> Result<T>
where
F: Future<Output = Result<T>>,
{
let conn = current_in(database)?;
let tx = match &conn.0 {
Conn::Tx(_) => return fut.await,
Conn::Repo(repo) => repo.begin().await?,
Conn::Held(held) => held.begin().await?,
};
let inside = Connection(Conn::Tx(tx.clone()), conn.1.clone());
let result = match database {
None => CURRENT.scope(inside, fut).await,
Some(name) => scope_named(vec![(name.to_owned(), inside)], fut).await,
};
match result {
Ok(value) => {
tx.commit().await?;
Ok(value)
}
Err(err) => {
tx.rollback().await?;
Err(err)
}
}
}
pub async fn savepoint<T, F>(fut: F) -> Result<T>
where
F: Future<Output = Result<T>>,
{
savepoint_in(None, fut).await
}
pub async fn savepoint_in<T, F>(database: Option<&str>, fut: F) -> Result<T>
where
F: Future<Output = Result<T>>,
{
static SAVEPOINTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let conn = current_in(database)?;
if !conn.in_transaction() {
return transaction_in(database, fut).await;
}
let name = format!(
"glacier_nested_{}",
SAVEPOINTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
);
conn.execute(Sql::new().push(&format!("SAVEPOINT {name}")))
.await?;
let result = fut.await;
let finish = if result.is_ok() {
format!("RELEASE SAVEPOINT {name}")
} else {
format!("ROLLBACK TO SAVEPOINT {name}")
};
conn.execute(Sql::new().push(&finish)).await?;
result
}
pub async fn sandbox<F: Future>(repo: &Repo, fut: F) -> Result<F::Output> {
let tx = repo.begin().await?;
let output = CURRENT.scope(Connection::from(&tx), fut).await;
tx.rollback().await?;
Ok(output)
}
pub struct Row(RowInner);
enum RowInner {
#[cfg(feature = "postgres")]
Postgres(sqlx::postgres::PgRow),
#[cfg(feature = "sqlite")]
Sqlite(sqlx::sqlite::SqliteRow),
}
macro_rules! column_json {
($row:expr, $i:expr) => {{
use sqlx::ValueRef as _;
let row = $row;
match row.try_get_raw($i) {
Ok(raw) if raw.is_null() => serde_json::Value::Null,
_ => {
if let Ok(v) = row.try_get::<i64, _>($i) {
v.into()
} else if let Ok(v) = row.try_get::<i32, _>($i) {
v.into()
} else if let Ok(v) = row.try_get::<i16, _>($i) {
v.into()
} else if let Ok(v) = row.try_get::<bool, _>($i) {
serde_json::Value::Bool(v)
} else if let Ok(v) = row.try_get::<f64, _>($i) {
v.into()
} else if let Ok(v) = row.try_get::<String, _>($i) {
v.into()
} else if let Ok(v) = row.try_get::<Decimal, _>($i) {
serde_json::Value::String(v.to_string())
} else if let Ok(v) = row.try_get::<chrono::DateTime<chrono::Utc>, _>($i) {
v.to_rfc3339().into()
} else if let Ok(v) = row.try_get::<chrono::NaiveDateTime, _>($i) {
v.to_string().into()
} else if let Ok(v) = row.try_get::<chrono::NaiveDate, _>($i) {
v.to_string().into()
} else if let Ok(v) = row.try_get::<sqlx::types::Json<serde_json::Value>, _>($i) {
v.0
} else if let Ok(v) = row.try_get::<uuid::Uuid, _>($i) {
v.to_string().into()
} else {
serde_json::Value::String("<unreadable>".into())
}
}
}
}};
}
impl Row {
pub fn to_json(&self) -> serde_json::Value {
use sqlx::Column as _;
let mut object = serde_json::Map::new();
match &self.0 {
#[cfg(feature = "postgres")]
RowInner::Postgres(row) => {
for (i, column) in row.columns().iter().enumerate() {
object.insert(column.name().to_owned(), column_json!(row, i));
}
}
#[cfg(feature = "sqlite")]
RowInner::Sqlite(row) => {
for (i, column) in row.columns().iter().enumerate() {
object.insert(column.name().to_owned(), column_json!(row, i));
}
}
}
serde_json::Value::Object(object)
}
pub fn get<T: FromColumn>(&self, column: &str) -> Result<T> {
let result = match &self.0 {
#[cfg(feature = "postgres")]
RowInner::Postgres(row) => row.try_get(column),
#[cfg(feature = "sqlite")]
RowInner::Sqlite(row) => row.try_get(column),
};
result.map_err(|e| Error::internal(format!("reading column `{column}`: {e}")))
}
}
macro_rules! bind_all {
($query:expr, $values:expr, $list:ident) => {{
let mut query = $query;
for value in $values {
query = match value {
Value::Null => unreachable!("NULL is rendered inline"),
Value::List(items) => bind_list!($list, query, items),
Value::Bool(v) => query.bind(v),
Value::Int(v) => query.bind(v),
Value::Float(v) => query.bind(v),
Value::Text(v) => query.bind(v),
Value::Bytes(v) => query.bind(v),
Value::Json(v) => query.bind(sqlx::types::Json(v)),
Value::Decimal(v) => query.bind(v),
Value::Uuid(v) => query.bind(v),
Value::Timestamp(v) => bind_timestamp!($list, query, v),
Value::Date(v) => query.bind(v),
};
}
query
}};
}
macro_rules! bind_timestamp {
(postgres, $query:expr, $value:expr) => {
$query.bind($value)
};
(sqlite, $query:expr, $value:expr) => {
$query.bind(sqlite_timestamp(&$value))
};
}
pub(crate) fn sqlite_timestamp(at: &Timestamp) -> String {
at.format("%Y-%m-%d %H:%M:%S%.6f").to_string()
}
macro_rules! bind_list {
(postgres, $query:expr, $items:expr) => {{
let items: Vec<Value> = $items;
match items.first() {
Some(Value::Int(_)) => $query.bind(
items
.into_iter()
.filter_map(|v| if let Value::Int(n) = v { Some(n) } else { None })
.collect::<Vec<i64>>(),
),
Some(Value::Uuid(_)) => $query.bind(
items
.into_iter()
.filter_map(|v| {
if let Value::Uuid(u) = v {
Some(u)
} else {
None
}
})
.collect::<Vec<uuid::Uuid>>(),
),
_ => $query.bind(
items
.into_iter()
.map(|v| v.to_text())
.collect::<Vec<String>>(),
),
}
}};
(sqlite, $query:expr, $items:expr) => {{
let _ = $items;
unreachable!("SQLite lists are rendered as separate values")
}};
}
macro_rules! run {
($conn:expr, $sql:expr, |$query:ident, $executor:ident| $body:expr) => {{
let conn: &Connection = $conn;
let (text, values) = $sql;
match &conn.0 {
Conn::Repo(repo) => match &repo.pool {
#[cfg(feature = "postgres")]
Pool::Postgres(pool) => {
let $query = bind_all!(
sqlx::query::<sqlx::Postgres>(AssertSqlSafe(text)),
values,
postgres
);
let $executor = pool;
$body
}
#[cfg(feature = "sqlite")]
Pool::Sqlite(pool) => {
let $query = bind_all!(
sqlx::query::<sqlx::Sqlite>(AssertSqlSafe(text)),
values,
sqlite
);
let $executor = pool;
$body
}
},
Conn::Tx(tx) => {
let mut guard = tx.inner.lock().await;
match guard.as_mut() {
#[cfg(feature = "postgres")]
Some(TxInner::Postgres(tx)) => {
let $query = bind_all!(
sqlx::query::<sqlx::Postgres>(AssertSqlSafe(text)),
values,
postgres
);
let $executor = &mut **tx;
$body
}
#[cfg(feature = "sqlite")]
Some(TxInner::Sqlite(tx)) => {
let $query = bind_all!(
sqlx::query::<sqlx::Sqlite>(AssertSqlSafe(text)),
values,
sqlite
);
let $executor = &mut **tx;
$body
}
None => Err(sqlx::Error::Protocol("transaction already finished".into())),
}
}
Conn::Held(held) => {
let mut guard = held.slot.lock().await;
let ready = match guard.as_ref() {
Some(_) => Ok(()),
None => held.acquire().await.map(|conn| {
*guard = Some(conn);
}),
};
match (ready, guard.as_mut()) {
(Err(err), _) => Err(err),
#[cfg(feature = "postgres")]
(Ok(()), Some(HeldConn::Postgres(conn))) => {
let $query = bind_all!(
sqlx::query::<sqlx::Postgres>(AssertSqlSafe(text)),
values,
postgres
);
let $executor = &mut **conn;
$body
}
#[cfg(feature = "sqlite")]
(Ok(()), Some(HeldConn::Sqlite(conn))) => {
let $query = bind_all!(
sqlx::query::<sqlx::Sqlite>(AssertSqlSafe(text)),
values,
sqlite
);
let $executor = &mut **conn;
$body
}
(Ok(()), None) => unreachable!("just acquired"),
}
}
}
}};
}
impl Connection {
pub fn dialect(&self) -> Dialect {
match &self.0 {
Conn::Repo(repo) => repo.dialect(),
Conn::Held(held) => held.repo.dialect(),
Conn::Tx(tx) => tx.dialect,
}
}
pub(crate) fn in_transaction(&self) -> bool {
matches!(self.0, Conn::Tx(_))
}
pub(crate) fn wrote(&self) -> bool {
self.1.wrote.load(Ordering::Relaxed)
}
fn replica(&self) -> Option<Connection> {
match &self.0 {
Conn::Repo(repo) | Conn::Held(Held { repo, .. })
if self.1.replica.load(Ordering::Relaxed) =>
{
let replica = repo.replica.as_deref()?.clone();
Some(Connection(Conn::Repo(replica), self.1.clone()))
}
_ => None,
}
}
fn wrote_now(&self) {
self.1.replica.store(false, Ordering::Relaxed);
self.1.wrote.store(true, Ordering::Relaxed);
query_cache::clear();
}
fn database_name(&self) -> &str {
match &self.0 {
Conn::Repo(repo) | Conn::Held(Held { repo, .. }) => &repo.name,
Conn::Tx(tx) => &tx.name,
}
}
pub(crate) async fn read_all(
&self,
sql: &Sql,
) -> std::result::Result<query_cache::Rows, sqlx::Error> {
let rendered = sql.render(self.dialect());
let key = (query_cache::active() && is_cacheable(&rendered.0))
.then(|| format!("{}\0{}\0{:?}", self.database_name(), rendered.0, rendered.1));
if let Some(rows) = key.as_deref().and_then(query_cache::get) {
tracing::debug!(target: "glacier", "CACHE {}", rendered.0);
return Ok(rows);
}
let rows: query_cache::Rows = match self.replica() {
Some(replica) => replica.run_all(rendered).await?,
None => {
if !is_select(&rendered.0) {
self.wrote_now();
}
self.run_all(rendered).await?
}
}
.into();
if let Some(key) = key {
query_cache::put(key, rows.clone());
}
Ok(rows)
}
pub(crate) async fn fetch_all(&self, sql: &Sql) -> std::result::Result<Vec<Row>, sqlx::Error> {
let rendered = sql.render(self.dialect());
if !is_select(&rendered.0) {
self.wrote_now();
}
self.run_all(rendered).await
}
async fn run_all(
&self,
(text, values): (String, Vec<Value>),
) -> std::result::Result<Vec<Row>, sqlx::Error> {
let retry = matches!(self.0, Conn::Repo(_) | Conn::Held(_)) && is_select(&text);
let again = retry.then(|| (text.clone(), values.clone()));
let rows = self.run_once((text, values)).await;
match (rows, again) {
(Err(err), Some(again)) if is_lost_connection(&err) => {
tracing::warn!(target: "glacier", "database connection lost ({err}); retrying the query");
if let Conn::Held(held) = &self.0 {
held.slot.lock().await.take();
}
self.run_once(again).await
}
(rows, _) => rows,
}
}
async fn run_once(
&self,
(text, values): (String, Vec<Value>),
) -> std::result::Result<Vec<Row>, sqlx::Error> {
let span = query_span(self.dialect(), &text);
let rows: std::result::Result<Vec<Row>, sqlx::Error> =
run!(self, (text, values), |query, executor| {
query
.fetch_all(executor)
.instrument(span.clone())
.await
.map(|rows| rows.into_iter().map(Row::from).collect())
});
finish_query(&span, rows.as_ref().map(Vec::len));
rows
}
pub(crate) async fn execute(&self, sql: &Sql) -> std::result::Result<u64, sqlx::Error> {
self.wrote_now();
let (text, values) = sql.render(self.dialect());
let span = query_span(self.dialect(), &text);
let done: std::result::Result<u64, sqlx::Error> =
run!(self, (text, values), |query, executor| {
query
.execute(executor)
.instrument(span.clone())
.await
.map(|done| done.rows_affected())
});
finish_query(&span, done.as_ref().map(|n| *n as usize));
done
}
}
fn is_lost_connection(err: &sqlx::Error) -> bool {
match err {
sqlx::Error::Io(_) => true,
sqlx::Error::Database(db) => db
.code()
.is_some_and(|code| code.starts_with("08") || code.starts_with("57P0")),
_ => false,
}
}
fn is_cacheable(text: &str) -> bool {
let lower = text.to_ascii_lowercase();
is_select(text)
&& !lower.contains(" for update")
&& !lower.contains(" for share")
&& !lower.contains(" for no key update")
&& !lower.contains(" for key share")
}
fn is_select(text: &str) -> bool {
let start = text.trim_start();
let word = start.split_whitespace().next().unwrap_or_default();
word.eq_ignore_ascii_case("select")
|| (word.eq_ignore_ascii_case("with")
&& !["insert", "update", "delete"]
.iter()
.any(|w| start.to_ascii_lowercase().contains(w)))
}
fn query_span(dialect: Dialect, text: &str) -> tracing::Span {
record_query(text);
let operation = text
.split_whitespace()
.next()
.unwrap_or_default()
.to_ascii_uppercase();
tracing::info_span!(
target: "glacier",
"glacier.db.query",
otel.name = %operation,
otel.kind = "client",
otel.status_code = Empty,
db.system.name = match dialect {
Dialect::Postgres => "postgresql",
Dialect::Sqlite => "sqlite",
},
db.operation.name = %operation,
db.query.text = %text,
db.response.returned_rows = Empty,
error.message = Empty,
)
}
fn finish_query(span: &tracing::Span, rows: std::result::Result<usize, &sqlx::Error>) {
match rows {
Ok(rows) => {
span.record(
"db.response.returned_rows",
i64::try_from(rows).unwrap_or(i64::MAX),
);
}
Err(err) => {
span.record("otel.status_code", "ERROR");
span.record("error.message", tracing::field::display(err));
}
}
}
tokio::task_local! {
static QUERY_LOG: Arc<std::sync::Mutex<Vec<String>>>;
}
fn record_query(text: &str) {
let _ = QUERY_LOG.try_with(|log| {
log.lock()
.unwrap_or_else(|e| e.into_inner())
.push(text.to_owned());
});
}
pub(crate) async fn logging_queries<F: Future>(fut: F) -> (F::Output, Vec<String>) {
let log = Arc::new(std::sync::Mutex::new(Vec::new()));
let output = QUERY_LOG.scope(log.clone(), fut).await;
let queries = std::mem::take(&mut *log.lock().unwrap_or_else(|e| e.into_inner()));
(output, queries)
}
tokio::task_local! {
static DEVELOPMENT: ();
}
pub(crate) async fn development_checks<F: Future>(fut: F) -> F::Output {
DEVELOPMENT.scope((), fut).await
}
pub(crate) async fn warn_unindexed(conn: &Connection, table: &'static str, column: &'static str) {
static CHECKED: std::sync::Mutex<Vec<(&'static str, &'static str)>> =
std::sync::Mutex::new(Vec::new());
if DEVELOPMENT.try_with(|()| ()).is_err() {
return;
}
{
let mut checked = CHECKED.lock().unwrap_or_else(|e| e.into_inner());
if checked.contains(&(table, column)) {
return;
}
checked.push((table, column));
}
let mut sql = Sql::new();
match conn.dialect() {
Dialect::Sqlite => {
sql.push("SELECT 1 AS found FROM pragma_index_list(")
.push_value(Value::Text(table.to_owned()))
.push(") l JOIN pragma_index_info(l.name) i WHERE i.seqno = 0 AND i.name = ")
.push_value(Value::Text(column.to_owned()));
}
Dialect::Postgres => {
sql.push(
"SELECT 1 AS found FROM pg_index x JOIN pg_class t ON t.oid = x.indrelid \
JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = x.indkey[0] \
WHERE t.relnamespace = current_schema()::regnamespace AND t.relname = ",
)
.push_value(Value::Text(table.to_owned()))
.push(" AND a.attname = ")
.push_value(Value::Text(column.to_owned()));
}
}
if let Ok(rows) = conn.fetch_all(&sql).await
&& rows.is_empty()
{
tracing::warn!(
target: "glacier",
"cursor pagination on `{table}` orders by `{column}`, which no index starts \
with, so every page reads the whole table; add one in a migration: \
s.add_index(\"{table}\", &[\"{column}\", \"id\"])"
);
}
}
pub(crate) const REPEATED_QUERY_THRESHOLD: usize = 3;
pub(crate) fn repeated_selects(queries: &[String], at_least: usize) -> Vec<(String, usize)> {
let mut counts: Vec<(String, usize)> = Vec::new();
for query in queries.iter().filter(|q| is_select(q)) {
match counts.iter_mut().find(|(q, _)| q == query) {
Some((_, n)) => *n += 1,
None => counts.push((query.clone(), 1)),
}
}
counts.retain(|(_, n)| *n >= at_least);
counts
}
#[cfg(feature = "postgres")]
impl From<sqlx::postgres::PgRow> for Row {
fn from(row: sqlx::postgres::PgRow) -> Self {
Row(RowInner::Postgres(row))
}
}
#[cfg(feature = "sqlite")]
impl From<sqlx::sqlite::SqliteRow> for Row {
fn from(row: sqlx::sqlite::SqliteRow) -> Self {
Row(RowInner::Sqlite(row))
}
}
pub fn sql(text: &str) -> RawQuery {
RawQuery {
text: text.to_owned(),
values: Vec::new(),
conn: None,
}
}
pub struct RawQuery {
text: String,
values: Vec<Value>,
conn: Option<Connection>,
}
impl RawQuery {
pub fn bind(mut self, value: impl ToValue) -> Self {
self.values.push(value.to_value());
self
}
pub fn on(mut self, conn: impl Into<Connection>) -> Self {
self.conn = Some(conn.into());
self
}
fn statement(&self) -> Result<(Connection, Sql)> {
let conn = match &self.conn {
Some(conn) => conn.clone(),
None => current()?,
};
Ok((conn, Sql::raw(&self.text, self.values.clone())))
}
pub async fn fetch_all(self) -> Result<Vec<Row>> {
let (conn, sql) = self.statement()?;
Ok(conn.fetch_all(&sql).await?)
}
pub async fn execute(self) -> Result<u64> {
let (conn, sql) = self.statement()?;
Ok(conn.execute(&sql).await?)
}
}
#[cfg_attr(not(feature = "postgres"), allow(dead_code))]
fn has_user(url: &str) -> bool {
let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
let authority = rest.split(['/', '?']).next().unwrap_or(rest);
authority.contains('@')
}
#[cfg(test)]
mod url_tests {
#[test]
fn finds_users_in_urls() {
assert!(super::has_user("postgres://me@localhost/db"));
assert!(super::has_user(
"postgres://me:secret@localhost:5432/db?sslmode=disable"
));
assert!(!super::has_user("postgres://localhost/db"));
assert!(!super::has_user("postgres://localhost/db?options=a@b"));
}
}
fn without_credentials(url: &str) -> String {
match (url.split_once("://"), url.rfind('@')) {
(Some((scheme, _)), Some(at)) => format!("{scheme}://{}", &url[at + 1..]),
_ => url.to_owned(),
}
}
#[cfg(test)]
mod name_tests {
#[test]
fn hides_credentials() {
assert_eq!(
super::without_credentials("postgres://me:secret@db.internal:5432/shop"),
"postgres://db.internal:5432/shop"
);
assert_eq!(
super::without_credentials("sqlite://db/development.sqlite3"),
"sqlite://db/development.sqlite3"
);
}
}