pub mod assoc;
mod cast;
mod changeset;
mod decimal;
pub mod migration;
mod query;
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 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 use changeset::{Changeset, Numericality, Save};
pub use decimal::Decimal;
pub use query::{Aggregable, Assign, 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};
#[derive(Clone)]
pub struct Repo {
pool: Pool,
}
#[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")?;
Self::connect_with(&url, pool_size).await
}
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 })
}
#[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))
.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,
}
}
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(),
})
}
}
#[derive(Clone)]
pub struct Transaction {
inner: Arc<Mutex<Option<TxInner>>>,
dialect: Dialect,
}
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<()> {
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<()> {
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);
#[derive(Clone)]
enum Conn {
Repo(Repo),
Tx(Transaction),
}
impl From<&Repo> for Connection {
fn from(repo: &Repo) -> Self {
Connection(Conn::Repo(repo.clone()))
}
}
impl From<&Transaction> for Connection {
fn from(tx: &Transaction) -> Self {
Connection(Conn::Tx(tx.clone()))
}
}
tokio::task_local! {
static CURRENT: Connection;
}
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 transaction<T, F>(fut: F) -> Result<T>
where
F: Future<Output = Result<T>>,
{
let repo = match current()?.0 {
Conn::Tx(_) => return fut.await,
Conn::Repo(repo) => repo,
};
let tx = repo.begin().await?;
let result = CURRENT.scope(Connection::from(&tx), 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>>,
{
static SAVEPOINTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let conn = current()?;
if !conn.in_transaction() {
return transaction(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),
}
impl Row {
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) => {{
let mut query = $query;
for value in $values {
query = match value {
Value::Null => unreachable!("NULL is rendered inline"),
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) => query.bind(v),
Value::Date(v) => query.bind(v),
};
}
query
}};
}
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);
let $executor = pool;
$body
}
#[cfg(feature = "sqlite")]
Pool::Sqlite(pool) => {
let $query =
bind_all!(sqlx::query::<sqlx::Sqlite>(AssertSqlSafe(text)), values);
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);
let $executor = &mut **tx;
$body
}
#[cfg(feature = "sqlite")]
Some(TxInner::Sqlite(tx)) => {
let $query =
bind_all!(sqlx::query::<sqlx::Sqlite>(AssertSqlSafe(text)), values);
let $executor = &mut **tx;
$body
}
None => Err(sqlx::Error::Protocol("transaction already finished".into())),
}
}
}
}};
}
impl Connection {
pub fn dialect(&self) -> Dialect {
match &self.0 {
Conn::Repo(repo) => repo.dialect(),
Conn::Tx(tx) => tx.dialect,
}
}
pub(crate) fn in_transaction(&self) -> bool {
matches!(self.0, Conn::Tx(_))
}
pub(crate) async fn fetch_all(&self, sql: &Sql) -> std::result::Result<Vec<Row>, sqlx::Error> {
let (text, values) = sql.render(self.dialect());
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> {
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 query_span(dialect: Dialect, text: &str) -> tracing::Span {
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));
}
}
}
impl Connection {}
#[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"));
}
}