use std::future::Future;
use sqlx::FromRow;
use sqlx::postgres::PgRow;
use sqlx::Row;
use crate::exec;
use crate::query::{Conflict, ConflictAction, ConflictTarget, Insert, InsertMany, Select, Update};
use crate::sql::Sql;
use crate::validate::ValidationErrors;
use crate::{Column, Error, Executor, Expr, Order, Result, Value};
pub trait Hooks {
fn before_insert(&self) -> Result<()> {
Ok(())
}
fn after_insert(&self) -> Result<()> {
Ok(())
}
fn before_save(&self) -> Result<()> {
Ok(())
}
fn after_save(&self) -> Result<()> {
Ok(())
}
fn before_delete(&self) -> Result<()> {
Ok(())
}
fn after_delete(&self) -> Result<()> {
Ok(())
}
}
pub trait Model:
for<'r> FromRow<'r, PgRow> + Hooks + Send + Sync + Unpin + Sized + 'static
{
const TABLE: &'static str;
const PRIMARY_KEY: &'static str;
const COLUMNS: &'static [&'static str];
const GENERATED: &'static [&'static str] = &[];
const CREATED_AT_COLUMN: Option<&'static str> = None;
const UPDATED_AT_COLUMN: Option<&'static str> = None;
const DELETED_AT_COLUMN: Option<&'static str> = None;
const TENANT_COLUMN: Option<&'static str> = None;
const VERSION_COLUMN: Option<&'static str> = None;
fn primary_key(&self) -> Value;
fn values(&self) -> Vec<(&'static str, Value)>;
fn validate(&self) -> std::result::Result<(), ValidationErrors> {
Ok(())
}
fn default_scope() -> Option<Expr<Self>> {
None
}
fn value_of(&self, column: &str) -> Option<Value> {
self.values()
.into_iter()
.find(|(c, _)| *c == column)
.map(|(_, v)| v)
}
fn query() -> Select<Self> {
Select::new()
}
fn filter(expr: Expr<Self>) -> Select<Self> {
Select::new().filter(expr)
}
fn order_by(order: impl Into<Order<Self>>) -> Select<Self> {
Select::new().order_by(order)
}
fn create() -> Insert<Self> {
Insert::new()
}
fn insert_many(records: &[Self]) -> InsertMany<'_, Self> {
InsertMany::new(records)
}
fn update_all() -> Update<Self> {
Update::new()
}
fn primary_key_column() -> Column<Self> {
Column::new(Self::PRIMARY_KEY)
}
fn find<'e, E>(
executor: E,
id: impl Into<Value>,
) -> impl Future<Output = Result<Option<Self>>> + Send
where
E: Executor<'e>,
{
let select = Self::filter(Self::primary_key_column().eq(id));
async move { select.first(executor).await }
}
fn find_or_fail<'e, E>(
executor: E,
id: impl Into<Value>,
) -> impl Future<Output = Result<Self>> + Send
where
E: Executor<'e>,
{
let id = id.into();
let key = id.to_string();
let select = Self::filter(Self::primary_key_column().eq(id));
async move {
select
.first(executor)
.await?
.ok_or_else(|| Error::not_found::<Self>(Some(key)))
}
}
fn find_many<'e, E, V>(
executor: E,
ids: impl IntoIterator<Item = V>,
) -> impl Future<Output = Result<Vec<Self>>> + Send
where
E: Executor<'e>,
V: Into<Value>,
{
let select = Self::filter(Self::primary_key_column().is_in(ids));
async move { select.all(executor).await }
}
fn all<'e, E>(executor: E) -> impl Future<Output = Result<Vec<Self>>> + Send
where
E: Executor<'e>,
{
Self::query().all(executor)
}
fn count<'e, E>(executor: E) -> impl Future<Output = Result<i64>> + Send
where
E: Executor<'e>,
{
Self::query().count(executor)
}
fn reload<'e, E>(&self, executor: E) -> impl Future<Output = Result<Self>> + Send
where
E: Executor<'e>,
{
let key = self.primary_key();
let missing = key.to_string();
let select = Self::filter(Self::primary_key_column().eq(key))
.with_trashed()
.unscoped();
async move {
select
.first(executor)
.await?
.ok_or_else(|| Error::not_found::<Self>(Some(missing)))
}
}
fn track(self) -> crate::Tracked<Self> {
crate::Tracked::new(self)
}
fn install_change_notifications(db: &crate::Db) -> impl Future<Output = Result<()>> + Send {
let sql = crate::notify::install_sql::<Self>();
async move {
db.execute(&sql?).await?;
Ok(())
}
}
fn uninstall_change_notifications(db: &crate::Db) -> impl Future<Output = Result<()>> + Send {
let sql = crate::notify::uninstall_sql::<Self>();
async move {
db.execute(&sql).await?;
Ok(())
}
}
fn changes(
db: &crate::Db,
) -> impl Future<Output = Result<crate::notify::ChangeStream<Self>>> + Send {
async move {
let listener = db.listen(&[&crate::notify::channel::<Self>()]).await?;
Ok(crate::notify::ChangeStream::new(listener))
}
}
fn is_trashed(&self) -> bool {
Self::DELETED_AT_COLUMN
.and_then(|c| self.value_of(c))
.is_some_and(|v| !v.is_null())
}
fn insert<'e, E>(&self, executor: E) -> impl Future<Output = Result<Self>> + Send
where
E: Executor<'e>,
{
async move {
pre_insert(self)?;
let sql = insert_sql::<Self>(std::slice::from_ref(self), false, None);
let row = exec::fetch_optional::<Self, _>(executor, &sql?, &[Self::TABLE], false)
.await?
.ok_or_else(|| Error::not_found::<Self>(None))?;
row.after_insert()?;
Ok(row)
}
}
fn insert_all<'e, E>(
executor: E,
records: &[Self],
) -> impl Future<Output = Result<Vec<Self>>> + Send
where
E: Executor<'e>,
{
Self::insert_many(records).exec(executor)
}
fn copy_in<'a>(
target: impl Into<crate::copy::CopyTarget<'a>>,
records: &[Self],
) -> impl Future<Output = Result<u64>> + Send {
let target = target.into();
async move { crate::copy::copy_in(target, records).await }
}
fn upsert<'e, E>(&self, executor: E) -> impl Future<Output = Result<Self>> + Send
where
E: Executor<'e>,
{
let conflict = Conflict {
target: ConflictTarget::Columns(vec![Self::PRIMARY_KEY]),
action: ConflictAction::UpdateAll,
};
async move {
pre_insert(self)?;
let sql = insert_sql::<Self>(std::slice::from_ref(self), true, Some(&conflict));
let row = exec::fetch_optional::<Self, _>(executor, &sql?, &[Self::TABLE], false)
.await?
.ok_or_else(|| Error::not_found::<Self>(None))?;
row.after_insert()?;
Ok(row)
}
}
fn upsert_on<'e, E>(
&self,
executor: E,
columns: impl IntoIterator<Item = Column<Self>>,
) -> impl Future<Output = Result<Self>> + Send
where
E: Executor<'e>,
{
let conflict = Conflict {
target: ConflictTarget::Columns(columns.into_iter().map(|c| c.name()).collect()),
action: ConflictAction::UpdateAll,
};
async move {
pre_insert(self)?;
let sql = insert_sql::<Self>(std::slice::from_ref(self), false, Some(&conflict));
let row = exec::fetch_optional::<Self, _>(executor, &sql?, &[Self::TABLE], false)
.await?
.ok_or_else(|| Error::not_found::<Self>(None))?;
row.after_insert()?;
Ok(row)
}
}
fn save<'e, E>(&self, executor: E) -> impl Future<Output = Result<Self>> + Send
where
E: Executor<'e>,
{
self.save_only(executor, None)
}
fn save_only<'e, E>(
&self,
executor: E,
columns: Option<Vec<Column<Self>>>,
) -> impl Future<Output = Result<Self>> + Send
where
E: Executor<'e>,
{
let only: Option<Vec<&'static str>> = columns.map(|c| c.iter().map(|c| c.name()).collect());
let pre = self
.validate()
.map_err(Error::Validation)
.and_then(|()| self.before_save());
let pk = self.primary_key();
let key = pk.to_string();
let managed = |c: &str| {
c == Self::PRIMARY_KEY
|| is_timestamp::<Self>(c)
|| Self::VERSION_COLUMN == Some(c)
|| Self::TENANT_COLUMN == Some(c)
};
let sets: Vec<_> = writable::<Self>(self.values())
.filter(|(c, _)| !managed(c))
.filter(|(c, _)| only.as_ref().is_none_or(|only| only.contains(c)))
.collect();
let mut update = Self::update_all()
.with_trashed()
.unscoped()
.filter(Self::primary_key_column().eq(pk.clone()));
let version = Self::VERSION_COLUMN.and_then(|c| self.value_of(c).map(|v| (c, v)));
if let Some((column, current)) = version.clone() {
update = update.filter(Column::new(column).eq(current));
}
for (column, value) in sets {
update = update.set(Column::new(column), value);
}
let changes = update.has_sets()
|| Self::UPDATED_AT_COLUMN.is_some()
|| Self::VERSION_COLUMN.is_some();
async move {
pre?;
let row = if !changes {
update
.into_select()
.first(executor)
.await?
.ok_or_else(|| Error::not_found::<Self>(Some(key)))?
} else if version.is_some() {
let mut sql = Sql::new();
update.write_into(&mut sql);
let exists = Self::filter(Self::primary_key_column().eq(pk.clone()))
.with_trashed()
.unscoped();
checked_write::<Self, _>(executor, sql, pk, exists).await?
} else {
update
.returning_one(executor)
.await?
.ok_or_else(|| Error::not_found::<Self>(Some(key)))?
};
row.after_save()?;
Ok(row)
}
}
fn delete<'e, E>(&self, executor: E) -> impl Future<Output = Result<()>> + Send
where
E: Executor<'e>,
{
self.delete_by_key(executor, false)
}
fn force_delete<'e, E>(&self, executor: E) -> impl Future<Output = Result<()>> + Send
where
E: Executor<'e>,
{
self.delete_by_key(executor, true)
}
#[doc(hidden)]
fn delete_by_key<'e, E>(
&self,
executor: E,
force: bool,
) -> impl Future<Output = Result<()>> + Send
where
E: Executor<'e>,
{
let pre = self.before_delete();
let pk = self.primary_key();
let key = pk.to_string();
let soft = Self::DELETED_AT_COLUMN.filter(|_| !force);
let version = Self::VERSION_COLUMN.and_then(|c| self.value_of(c).map(|v| (c, v)));
let mut select = Self::filter(Self::primary_key_column().eq(pk.clone())).unscoped();
if force {
select = select.with_trashed();
}
let exists = select.clone();
if let Some((column, current)) = version.clone() {
select = select.filter(Column::new(column).eq(current));
}
async move {
pre?;
let mut sql = Sql::new();
match soft {
Some(deleted_at) => select
.update()
.set_raw(Column::new(deleted_at), "now()", [] as [Value; 0])
.write_into(&mut sql),
None => {
let delete = if force {
select.force_delete_sql()
} else {
select.delete_sql()
};
sql = delete;
}
}
if version.is_some() {
checked_write::<Self, _>(executor, sql, pk, exists).await?;
} else if exec::execute(executor, &sql, &[Self::TABLE]).await? == 0 {
return Err(Error::not_found::<Self>(Some(key)));
}
self.after_delete()
}
}
fn restore<'e, E>(&self, executor: E) -> impl Future<Output = Result<Self>> + Send
where
E: Executor<'e>,
{
let pk = self.primary_key();
let key = pk.to_string();
let update = Self::DELETED_AT_COLUMN.map(|deleted_at| {
Self::filter(Self::primary_key_column().eq(pk))
.only_trashed()
.unscoped()
.update()
.set_raw(Column::new(deleted_at), "NULL", [] as [Value; 0])
});
async move {
let Some(update) = update else {
return Err(Error::InvalidQuery(format!(
"`{}` has no soft-delete column",
Self::TABLE
)));
};
update
.returning_one(executor)
.await?
.ok_or_else(|| Error::not_found::<Self>(Some(key)))
}
}
}
async fn checked_write<'e, M: Model, E: Executor<'e>>(
executor: E,
write: Sql,
pk: Value,
exists: Select<M>,
) -> Result<M> {
let key = pk.to_string();
let mut sql = Sql::new();
sql.push(r#"WITH "__rok_w" AS ("#);
sql.append(write);
sql.push(r#" RETURNING TRUE AS "__rok_present", "#);
push_columns::<M>(&mut sql);
sql.push(") SELECT EXISTS(");
exists.write_exists_body(&mut sql);
sql.push(r#") AS "__rok_exists", "w".* FROM (SELECT 1) AS "__rok_d" LEFT JOIN "__rok_w" AS "w" ON TRUE"#);
let rows = exec::fetch_rows(executor, &sql, &[M::TABLE], false).await?;
let row = rows
.first()
.ok_or_else(|| Error::not_found::<M>(Some(key.clone())))?;
if row.try_get::<Option<bool>, _>("__rok_present")?.is_some() {
Ok(M::from_row(row)?)
} else if row.try_get::<bool, _>("__rok_exists")? {
Err(Error::Conflict {
table: M::TABLE,
key,
})
} else {
Err(Error::not_found::<M>(Some(key)))
}
}
pub(crate) fn pre_insert<M: Model>(record: &M) -> Result<()> {
record.validate().map_err(Error::Validation)?;
record.before_insert()
}
fn writable<M: Model>(
values: Vec<(&'static str, Value)>,
) -> impl Iterator<Item = (&'static str, Value)> {
values
.into_iter()
.filter(|(c, _)| !M::GENERATED.contains(c))
}
fn is_timestamp<M: Model>(column: &str) -> bool {
M::CREATED_AT_COLUMN == Some(column) || M::UPDATED_AT_COLUMN == Some(column)
}
pub(crate) fn insert_sql<M: Model>(
records: &[M],
include_pk: bool,
conflict: Option<&Conflict>,
) -> Result<Sql> {
let include = |c: &str| !M::GENERATED.contains(&c) || (include_pk && c == M::PRIMARY_KEY);
let columns: Vec<&'static str> = M::COLUMNS.iter().copied().filter(|c| include(c)).collect();
let mut sql = Sql::new();
sql.push("INSERT INTO ").push_ident(M::TABLE);
if columns.is_empty() {
sql.push(" DEFAULT VALUES");
} else {
sql.push(" (")
.push_list(&columns, ", ", |sql, c| {
sql.push_ident(c);
})
.push(") VALUES ");
let tenant = M::TENANT_COLUMN.zip(crate::tenant::current());
sql.push_list(records, ", ", |sql, record| {
let values = record.values().into_iter().filter(|(c, _)| include(c));
sql.push("(")
.push_list(values, ", ", |sql, (c, v)| {
if is_timestamp::<M>(c) {
sql.push("now()");
} else if let Some((_, current)) = tenant.as_ref().filter(|(t, _)| *t == c) {
sql.bind(current.clone());
} else {
sql.bind(v);
}
})
.push(")");
});
}
if let Some(conflict) = conflict {
conflict.write::<M>(&mut sql, &columns)?;
}
push_returning::<M>(&mut sql);
Ok(sql)
}
pub(crate) fn tenant_override<M: Model>(column: &str) -> Option<Value> {
M::TENANT_COLUMN
.filter(|c| *c == column)
.and_then(|_| crate::tenant::current())
}
pub(crate) fn push_columns<M: Model>(sql: &mut Sql) {
sql.push_list(M::COLUMNS, ", ", |sql, c| {
sql.push_ident(c);
});
}
pub(crate) fn push_returning<M: Model>(sql: &mut Sql) {
sql.push(" RETURNING ");
push_columns::<M>(sql);
}
#[doc(hidden)]
pub fn __insert_sql<M: Model>(records: &[M], upsert: bool) -> Sql {
let conflict = upsert.then(|| Conflict {
target: ConflictTarget::Columns(vec![M::PRIMARY_KEY]),
action: ConflictAction::UpdateAll,
});
insert_sql(records, upsert, conflict.as_ref()).expect("valid insert")
}