use std::fmt;
use std::marker::PhantomData;
use std::sync::Arc;
use id_effect::{Effect, HList, Selector, fail, need, succeed};
use sea_query::{Condition, Expr, ExprTrait, IntoCondition, Order, Query, SelectStatement, Value};
use crate::client::{SqlClient, SqlClientService};
use crate::error::SqlError;
use crate::from_row::{FromRow, from_rows};
use crate::query_builder::{BuildSql, Dialect};
use crate::row::SqlRow;
use crate::transaction::{SqlTransaction, SqlTransactionService};
use crate::value::{SqlValue, ToSqlValue};
pub mod hooks;
#[cfg(feature = "outbox")]
pub mod outbox;
pub mod page;
pub mod relations;
pub use hooks::{BoundHookedRepository, EntityHooks, HookContext, HookedRepository};
pub use page::{Keyset, PageCursor, PageCursorError, PageLimits, Paged, SortOrder};
pub use relations::{
BoundEagerRepository, EagerRepository, FieldMeta, Loaded, MAX_EAGER_DEPTH, Relation,
RelationKind, RelationMeta,
};
pub trait Entity: FromRow + Send + 'static {
type Id: ToSqlValue + fmt::Debug + Send + 'static;
const NAME: &'static str;
const TABLE: &'static str;
const COLUMNS: &'static [&'static str];
const ID: &'static str;
const ID_GENERATED: bool = false;
const VERSION: Option<&'static str> = None;
const SOFT_DELETE: Option<&'static str> = None;
const TENANT: Option<&'static str> = None;
const LABEL: &'static str = Self::NAME;
const FIELDS: &'static [FieldMeta] = &[];
const RELATIONS: &'static [RelationMeta] = &[];
fn id(&self) -> Self::Id;
fn values(&self) -> Vec<(&'static str, SqlValue)>;
fn bump_version(&mut self) {}
fn scope() -> Condition {
Condition::all()
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct CurrentTenant(pub SqlValue);
impl CurrentTenant {
#[inline]
pub fn new(value: impl ToSqlValue) -> Self {
Self(value.to_sql_value())
}
}
pub trait SqlExecutor: Send + Sync + 'static {
fn query(&self, sql: &str, params: &[SqlValue]) -> Effect<Vec<SqlRow>, SqlError>;
fn execute(&self, sql: &str, params: &[SqlValue]) -> Effect<u64, SqlError>;
}
macro_rules! executor {
($ty:ty) => {
impl SqlExecutor for $ty {
fn query(&self, sql: &str, params: &[SqlValue]) -> Effect<Vec<SqlRow>, SqlError> {
(**self).query(sql, params)
}
fn execute(&self, sql: &str, params: &[SqlValue]) -> Effect<u64, SqlError> {
(**self).execute(sql, params)
}
}
};
}
executor!(SqlClientService);
executor!(SqlTransactionService);
executor!(Arc<dyn SqlClient>);
executor!(Arc<dyn SqlTransaction>);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Page {
pub limit: u64,
pub offset: u64,
}
impl Page {
#[inline]
pub fn new(limit: u64, offset: u64) -> Self {
Self { limit, offset }
}
#[inline]
pub fn number(number: u64, size: u64) -> Self {
Self::new(size, number.saturating_mul(size))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Filters {
All,
WithDeleted,
None,
}
type Stmt = (String, Vec<SqlValue>);
type Run<A> = Box<dyn FnOnce(Arc<dyn SqlExecutor>) -> Effect<A, SqlError> + Send>;
fn ready<A: Send + 'static>(r: Result<A, SqlError>) -> Effect<A, SqlError> {
match r {
Ok(a) => succeed(a),
Err(e) => fail(e),
}
}
fn rows<A: Send + 'static>(
(sql, params): Stmt,
f: impl FnOnce(Vec<SqlRow>) -> Result<A, SqlError> + Send + 'static,
) -> Run<A> {
Box::new(move |ex| ex.query(&sql, ¶ms).flat_map(|rows| ready(f(rows))))
}
fn affected_any((sql, params): Stmt) -> Run<bool> {
Box::new(move |ex| ex.execute(&sql, ¶ms).map(|n| n > 0))
}
fn first<T: FromRow>(rows: Vec<SqlRow>) -> Result<Option<T>, SqlError> {
rows.first().map(T::from_row).transpose()
}
fn the_row<T: FromRow>(rows: Vec<SqlRow>) -> Result<T, SqlError> {
first(rows)?.ok_or(SqlError::RowNotFound)
}
fn and(base: Condition, cond: Condition) -> Condition {
if cond.is_empty() {
base
} else {
base.add(cond)
}
}
pub struct Repository<T> {
dialect: Dialect,
tenant: Option<SqlValue>,
filters: Filters,
entity: PhantomData<fn() -> T>,
}
impl<T> Clone for Repository<T> {
fn clone(&self) -> Self {
Self {
dialect: self.dialect,
tenant: self.tenant.clone(),
filters: self.filters,
entity: PhantomData,
}
}
}
impl<T> fmt::Debug for Repository<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Repository")
.field("entity", &std::any::type_name::<T>())
.field("dialect", &self.dialect)
.field("tenant", &self.tenant)
.field("filters", &self.filters)
.finish()
}
}
pub struct BoundRepository<T> {
repo: Repository<T>,
ex: Arc<dyn SqlExecutor>,
}
impl<T> Clone for BoundRepository<T> {
fn clone(&self) -> Self {
Self {
repo: self.repo.clone(),
ex: Arc::clone(&self.ex),
}
}
}
impl<T> fmt::Debug for BoundRepository<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("BoundRepository").field(&self.repo).finish()
}
}
impl<T: Entity> Repository<T> {
pub fn new(dialect: Dialect) -> Self {
Self {
dialect,
tenant: None,
filters: Filters::All,
entity: PhantomData,
}
}
pub fn for_current_tenant<R, J>(dialect: Dialect) -> Effect<Self, SqlError, R>
where
R: Selector<CurrentTenant, J> + HList,
{
need::<CurrentTenant>().flat_map(move |t| succeed(Self::new(dialect).with_tenant(t.0.clone())))
}
#[must_use]
pub fn with_tenant(&self, tenant: impl ToSqlValue) -> Self {
Self {
tenant: Some(tenant.to_sql_value()),
..self.clone()
}
}
#[must_use]
pub fn with_deleted(&self) -> Self {
Self {
filters: Filters::WithDeleted,
..self.clone()
}
}
#[must_use]
pub fn unscoped(&self) -> Self {
Self {
filters: Filters::None,
..self.clone()
}
}
#[inline]
pub fn dialect(&self) -> Dialect {
self.dialect
}
#[inline]
pub fn tenant(&self) -> Option<&SqlValue> {
self.tenant.as_ref()
}
pub fn on(&self, executor: impl SqlExecutor) -> BoundRepository<T> {
BoundRepository {
repo: self.clone(),
ex: Arc::new(executor),
}
}
fn tenant_value(&self) -> Result<Option<SqlValue>, SqlError> {
match (T::TENANT, &self.tenant) {
(None, _) => Ok(None),
(Some(_), Some(v)) => Ok(Some(v.clone())),
(Some(_), None) if self.filters == Filters::None => Ok(None),
(Some(col), None) => Err(SqlError::Unsupported(format!(
"entity `{}` is scoped by tenant column `{col}` but the repository has no tenant \
(Repository::with_tenant / for_current_tenant, or unscoped())",
T::NAME
))),
}
}
fn scope(&self, soft_delete: bool) -> Result<Condition, SqlError> {
self.scope_in(None, soft_delete)
}
fn scope_in(
&self,
table: Option<&'static str>,
soft_delete: bool,
) -> Result<Condition, SqlError> {
let tenant = self.tenant_value()?;
let mut cond = Condition::all();
if self.filters == Filters::None {
return Ok(cond);
}
let column = |col: &'static str| match table {
Some(table) => Expr::col((table, col)),
None => Expr::col(col),
};
if let (Some(col), Some(v)) = (T::TENANT, tenant) {
cond = cond.add(column(col).eq(Value::from(v)));
}
if let (Some(col), true, Filters::All) = (T::SOFT_DELETE, soft_delete, self.filters) {
cond = cond.add(column(col).is_null());
}
Ok(and(cond, T::scope()))
}
fn cast<C: Entity>(&self) -> Repository<C> {
Repository {
dialect: self.dialect,
tenant: self.tenant.clone(),
filters: self.filters,
entity: PhantomData,
}
}
fn id_is(id: &T::Id) -> Condition {
Condition::all().add(Expr::col(T::ID).eq(Value::from(id.to_sql_value())))
}
fn render(&self, stmt: &impl BuildSql) -> Result<Stmt, SqlError> {
stmt.build_sql(self.dialect)
}
fn select(&self, cond: Condition) -> Result<SelectStatement, SqlError> {
let mut stmt = Query::select();
stmt.columns(T::COLUMNS.iter().copied()).from(T::TABLE);
self.filter(&mut stmt, cond)?;
Ok(stmt)
}
fn filter(&self, stmt: &mut SelectStatement, cond: Condition) -> Result<(), SqlError> {
let cond = and(self.scope(true)?, cond);
if !cond.is_empty() {
stmt.cond_where(cond);
}
Ok(())
}
fn find_op(&self, id: &T::Id) -> Result<Run<Option<T>>, SqlError> {
let stmt = self.select(Self::id_is(id))?.limit(1).to_owned();
Ok(rows(self.render(&stmt)?, first))
}
fn find_by_op(&self, cond: Condition, page: Option<Page>) -> Result<Run<Vec<T>>, SqlError> {
let mut stmt = self.select(cond)?;
stmt.order_by(T::ID, Order::Asc);
if let Some(page) = page {
stmt.limit(page.limit).offset(page.offset);
}
Ok(rows(self.render(&stmt)?, |rows| from_rows(&rows)))
}
fn count_op(&self, cond: Condition) -> Result<Run<u64>, SqlError> {
let mut stmt = Query::select();
stmt.expr(Expr::cust("COUNT(*)")).from(T::TABLE);
self.filter(&mut stmt, cond)?;
Ok(rows(self.render(&stmt)?, |rows| {
let n = rows
.first()
.ok_or(SqlError::RowNotFound)?
.get::<i64>(0usize)?;
Ok(u64::try_from(n).unwrap_or_default())
}))
}
fn exists_stmt(&self, id: &T::Id) -> Result<Stmt, SqlError> {
let stmt = Query::select()
.column(T::ID)
.from(T::TABLE)
.cond_where(and(self.scope(true)?, Self::id_is(id)))
.limit(1)
.to_owned();
self.render(&stmt)
}
fn exists_op(&self, id: &T::Id) -> Result<Run<bool>, SqlError> {
Ok(rows(self.exists_stmt(id)?, |rows| Ok(!rows.is_empty())))
}
fn insert_op(&self, entity: T) -> Result<Run<T>, SqlError> {
let tenant = self.tenant_value()?;
let (mut columns, mut values) = (Vec::new(), Vec::new());
for (col, v) in entity.values() {
let generated = col == T::ID && T::ID_GENERATED;
if generated || (tenant.is_some() && Some(col) == T::TENANT) {
continue;
}
columns.push(col);
values.push(Expr::val(Value::from(v)));
}
if let (Some(col), Some(v)) = (T::TENANT, tenant) {
columns.push(col);
values.push(Expr::val(Value::from(v)));
}
let mut stmt = Query::insert();
stmt
.into_table(T::TABLE)
.columns(columns)
.values_panic(values);
if self.dialect != Dialect::MySql {
stmt.returning(Query::returning().columns(T::COLUMNS.iter().copied()));
return Ok(rows(self.render(&stmt)?, the_row));
}
if T::ID_GENERATED {
return Err(SqlError::Unsupported(format!(
"entity `{}`: MySQL has no RETURNING, so a generated id cannot be read back on insert",
T::NAME
)));
}
let (sql, params) = self.render(&stmt)?;
let read_back = Query::select()
.columns(T::COLUMNS.iter().copied())
.from(T::TABLE)
.cond_where(Self::id_is(&entity.id()))
.to_owned();
let read_back = rows(self.render(&read_back)?, the_row);
Ok(Box::new(move |ex| {
let again = Arc::clone(&ex);
ex.execute(&sql, ¶ms)
.flat_map(move |_| read_back(again))
}))
}
fn update_op(&self, mut entity: T) -> Result<Run<T>, SqlError> {
let id = entity.id();
let mut cond = and(self.scope(true)?, Self::id_is(&id));
let mut stmt = Query::update();
stmt.table(T::TABLE);
for (col, v) in entity.values() {
if Some(col) == T::VERSION {
cond = cond.add(Expr::col(col).eq(Value::from(v)));
stmt.value(col, Expr::col(col).add(1));
} else if col != T::ID && Some(col) != T::TENANT && Some(col) != T::SOFT_DELETE {
stmt.value(col, Value::from(v));
}
}
stmt.cond_where(cond);
let (sql, params) = self.render(&stmt)?;
let stale = match T::VERSION {
Some(_) => Some(self.exists_stmt(&id)?),
None => None,
};
let id = format!("{id:?}");
Ok(Box::new(move |ex| {
ex.execute(&sql, ¶ms).flat_map(move |n| {
if n > 0 {
entity.bump_version();
return succeed(entity);
}
let Some((sql, params)) = stale else {
return fail(SqlError::RowNotFound);
};
ex.query(&sql, ¶ms).flat_map(move |rows| {
fail(if rows.is_empty() {
SqlError::RowNotFound
} else {
SqlError::StaleVersion {
entity: T::NAME.to_owned(),
id,
}
})
})
})
}))
}
fn delete_op(&self, id: &T::Id) -> Result<Run<bool>, SqlError> {
let Some(col) = T::SOFT_DELETE else {
return self.hard_delete_op(id);
};
let mut stmt = Query::update();
stmt.table(T::TABLE).value(
col,
Value::from(SqlValue::Timestamp(jiff::Timestamp::now())),
);
if let Some(version) = T::VERSION {
stmt.value(version, Expr::col(version).add(1));
}
stmt.cond_where(and(self.scope(true)?, Self::id_is(id)));
Ok(affected_any(self.render(&stmt)?))
}
fn hard_delete_op(&self, id: &T::Id) -> Result<Run<bool>, SqlError> {
let stmt = Query::delete()
.from_table(T::TABLE)
.cond_where(and(self.scope(false)?, Self::id_is(id)))
.to_owned();
Ok(affected_any(self.render(&stmt)?))
}
fn in_env<A, R, I>(op: Result<Run<A>, SqlError>) -> Effect<A, SqlError, R>
where
A: Send + 'static,
R: Selector<SqlClientService, I> + HList,
{
match op {
Ok(run) => need::<SqlClientService>().flat_map(move |svc| run(svc).narrow()),
Err(e) => fail(e),
}
}
}
impl<T: Entity> BoundRepository<T> {
#[inline]
pub fn repository(&self) -> &Repository<T> {
&self.repo
}
fn run<A: Send + 'static>(&self, op: Result<Run<A>, SqlError>) -> Effect<A, SqlError> {
match op {
Ok(run) => run(Arc::clone(&self.ex)),
Err(e) => fail(e),
}
}
}
macro_rules! operations {
($(
$(#[$doc:meta])*
fn $name:ident($($arg:ident: $ty:ty),*) -> $ret:ty = $op:ident($($call:expr),*);
)*) => {
impl<T: Entity> Repository<T> {
$(
$(#[$doc])*
pub fn $name<R, I>(&self, $($arg: $ty),*) -> Effect<$ret, SqlError, R>
where
R: Selector<SqlClientService, I> + HList,
{
Self::in_env(self.$op($($call),*))
}
)*
}
impl<T: Entity> BoundRepository<T> {
$(
$(#[$doc])*
pub fn $name(&self, $($arg: $ty),*) -> Effect<$ret, SqlError> {
self.run(self.repo.$op($($call),*))
}
)*
}
};
}
operations! {
fn find(id: T::Id) -> Option<T> = find_op(&id);
fn find_all() -> Vec<T> = find_by_op(Condition::all(), None);
fn find_by(cond: impl IntoCondition) -> Vec<T> = find_by_op(cond.into_condition(), None);
fn find_page(cond: impl IntoCondition, page: Page) -> Vec<T> =
find_by_op(cond.into_condition(), Some(page));
fn count() -> u64 = count_op(Condition::all());
fn count_by(cond: impl IntoCondition) -> u64 = count_op(cond.into_condition());
fn exists(id: T::Id) -> bool = exists_op(&id);
fn insert(entity: T) -> T = insert_op(entity);
fn update(entity: T) -> T = update_op(entity);
fn delete(id: T::Id) -> bool = delete_op(&id);
fn hard_delete(id: T::Id) -> bool = hard_delete_op(&id);
}