use std::future::Future;
use crate::context::Params;
use crate::db::{Changeset, Expr, Order, Preload, Query, Record, Row, Save, ToValue, Value};
use crate::error::Result;
pub trait Callbacks: Send {
fn validate_record(&self, errors: &mut crate::db::Errors) {
let _ = errors;
}
fn before_validation(&mut self) -> impl Future<Output = Result<()>> + Send {
async { Ok(()) }
}
fn before_save(&mut self) -> impl Future<Output = Result<()>> + Send {
async { Ok(()) }
}
fn before_create(&mut self) -> impl Future<Output = Result<()>> + Send {
async { Ok(()) }
}
fn before_update(&mut self) -> impl Future<Output = Result<()>> + Send {
async { Ok(()) }
}
fn after_create(&mut self) -> impl Future<Output = Result<()>> + Send {
async { Ok(()) }
}
fn after_update(&mut self) -> impl Future<Output = Result<()>> + Send {
async { Ok(()) }
}
fn after_save(&mut self) -> impl Future<Output = Result<()>> + Send {
async { Ok(()) }
}
fn before_destroy(&mut self) -> impl Future<Output = Result<()>> + Send {
async { Ok(()) }
}
fn after_destroy(&mut self) -> impl Future<Output = Result<()>> + Send {
async { Ok(()) }
}
}
pub trait Model: Callbacks + Sized + Send + Sync + 'static {
const TABLE: &'static str;
const COLUMNS: &'static [&'static str];
const PRIMARY_KEY: &'static str = "id";
const DATABASE: Option<&'static str> = None;
const CREATED_AT: Option<&'static str> = None;
const UPDATED_AT: Option<&'static str> = None;
type Columns;
fn columns() -> Self::Columns;
fn from_row(row: &Row) -> Result<Self>;
fn values(&self) -> Vec<(&'static str, Value)>;
fn attribute_values(&self) -> Vec<(&'static str, Value)> {
Vec::new()
}
fn id_value(&self) -> Value;
fn validate(changeset: Changeset<Self>) -> Changeset<Self> {
changeset
}
fn from_params(params: &Params) -> Changeset<Self> {
let _ = params;
Changeset::new()
}
fn params_schema() -> serde_json::Value {
serde_json::json!({"type": "object"})
}
fn path(&self) -> String {
let id = self.id_value().to_text();
format!(
"{}/{}",
Self::collection_path(),
crate::router::encode_segment(&id)
)
}
fn collection_path() -> String {
format!("/{}", Self::TABLE)
}
fn all() -> Query<Self> {
Query::new()
}
fn default_scope(query: Query<Self>) -> Query<Self> {
query
}
fn unscoped() -> Query<Self> {
Query::unscoped()
}
fn filter(condition: impl FnOnce(&Self::Columns) -> Expr) -> Query<Self> {
Query::new().filter(condition)
}
fn order(order: impl FnOnce(&Self::Columns) -> Order) -> Query<Self> {
Query::new().order(order)
}
fn preload<P: Into<Preload<Self>>>(
association: impl FnOnce(&Self::Columns) -> P,
) -> Query<Self> {
Query::new().preload(association)
}
fn find(id: impl ToValue) -> impl Future<Output = Result<Self>> + Send {
let query = by_id::<Self>(id.to_value());
async move { query.one().await }
}
fn find_by(
condition: impl FnOnce(&Self::Columns) -> Expr,
) -> impl Future<Output = Result<Option<Self>>> + Send {
let query = Self::filter(condition);
async move { query.first().await }
}
fn find_or_initialize_by(
condition: impl FnOnce(&Self::Columns) -> Expr,
init: impl FnOnce(&mut Self) + Send,
) -> impl Future<Output = Result<Self>> + Send
where
Self: Default,
{
let query = Self::filter(condition);
async move {
Ok(match query.first().await? {
Some(found) => found,
None => Self::default().tap(init),
})
}
}
fn find_or_create_by(
condition: impl FnOnce(&Self::Columns) -> Expr,
init: impl FnOnce(&mut Self) + Send,
) -> impl Future<Output = Result<Self>> + Send
where
Self: Default + Clone,
{
let query = Self::filter(condition);
async move {
if let Some(found) = query.first().await? {
return Ok(found);
}
let mut record = Self::default().tap(init);
record.save().await?;
Ok(record)
}
}
fn first() -> impl Future<Output = Result<Option<Self>>> + Send {
Query::<Self>::new().first()
}
fn last() -> impl Future<Output = Result<Option<Self>>> + Send {
Query::<Self>::new().last()
}
fn take(n: u64) -> impl Future<Output = Result<Vec<Self>>> + Send {
Query::<Self>::new()
.order(|_| Order::by(Self::PRIMARY_KEY, false))
.take(n)
}
fn count() -> impl Future<Output = Result<i64>> + Send {
Query::<Self>::new().count()
}
fn join<C: Model>(
association: impl FnOnce(&Self::Columns) -> crate::db::Association<Self, C>,
condition: impl FnOnce(&C::Columns) -> Expr,
) -> Query<Self> {
Query::new().join(association, condition)
}
fn joins<C: Model>(
association: impl FnOnce(&Self::Columns) -> crate::db::Association<Self, C>,
) -> Query<Self> {
Query::new().joins(association)
}
fn group<K: crate::db::FromColumn>(
column: impl FnOnce(&Self::Columns) -> crate::db::Col<Self, K>,
) -> crate::db::Grouped<Self, K> {
Query::new().group(column)
}
fn sum<T: crate::db::Summable>(
column: impl FnOnce(&Self::Columns) -> crate::db::Col<Self, T>,
) -> impl Future<Output = Result<T::Sum>> + Send {
Query::<Self>::new().sum(column)
}
fn average<T: crate::db::Summable>(
column: impl FnOnce(&Self::Columns) -> crate::db::Col<Self, T>,
) -> impl Future<Output = Result<Option<f64>>> + Send {
Query::<Self>::new().average(column)
}
fn minimum<T: crate::db::Aggregable>(
column: impl FnOnce(&Self::Columns) -> crate::db::Col<Self, T>,
) -> impl Future<Output = Result<Option<T::Value>>> + Send {
Query::<Self>::new().minimum(column)
}
fn maximum<T: crate::db::Aggregable>(
column: impl FnOnce(&Self::Columns) -> crate::db::Col<Self, T>,
) -> impl Future<Output = Result<Option<T::Value>>> + Send {
Query::<Self>::new().maximum(column)
}
fn create(
changes: impl Into<Changeset<Self>>,
) -> impl Future<Output = Result<Save<Self>>> + Send {
let changeset = changes.into();
async move { changeset.insert().await }
}
fn changeset() -> Changeset<Self> {
Changeset::new()
}
fn change(self) -> Changeset<Self> {
Changeset::for_record(self)
}
fn update_changeset(
self,
changes: impl Into<Changeset<Self>>,
) -> impl Future<Output = Result<Save<Self>>> + Send {
let changeset = changes.into().attach(self);
async move { changeset.update().await }
}
fn destroy(mut self) -> impl Future<Output = Result<()>> + Send {
async move {
self.before_destroy().await?;
self.destroy_dependents().await?;
by_id::<Self>(self.id_value()).delete_all().await?;
self.touch_parents().await?;
self.after_destroy().await
}
}
#[doc(hidden)]
fn touch_parents(&self) -> impl Future<Output = Result<()>> + Send {
async { Ok(()) }
}
#[doc(hidden)]
fn destroy_dependents(&self) -> impl Future<Output = Result<()>> + Send {
async { Ok(()) }
}
fn delete(self) -> impl Future<Output = Result<()>> + Send {
let query = by_id::<Self>(self.id_value());
async move {
query.delete_all().await?;
Ok(())
}
}
fn record(&self) -> Option<&Record> {
None
}
fn record_mut(&mut self) -> Option<&mut Record> {
None
}
fn new() -> Self
where
Self: Default,
{
Self::default()
}
fn tap(mut self, change: impl FnOnce(&mut Self)) -> Self {
change(&mut self);
self
}
fn build(params: impl Into<Params>) -> Self
where
Self: Default,
{
let mut record = Self::default();
record.assign(¶ms.into());
record
}
fn assign(&mut self, params: &Params) {
let _ = params;
}
fn is_new(&self) -> bool {
match self.record() {
Some(state) => !state.is_persisted(),
None => matches!(self.id_value(), Value::Null | Value::Int(0)),
}
}
fn is_persisted(&self) -> bool {
!self.is_new()
}
fn changes(&self) -> Vec<(&'static str, Value)> {
crate::db::record::changes(self)
}
fn is_changed(&self) -> bool {
!self.changes().is_empty()
}
fn changed(&self, column: &str) -> bool {
self.changes().iter().any(|(c, _)| *c == column)
}
fn was(&self, column: &str) -> Option<Value> {
self.record()?.original(column).cloned()
}
fn save(&mut self) -> impl Future<Output = Result<bool>> + Send
where
Self: Clone,
{
crate::db::record::save(self)
}
fn update(&mut self, params: impl Into<Params>) -> impl Future<Output = Result<bool>> + Send
where
Self: Clone,
{
let params = params.into();
self.assign(¶ms);
async move {
if !Self::HAS_NESTED {
return crate::db::record::save(self).await;
}
let saved = crate::db::savepoint_in(Self::DATABASE, async {
if !crate::db::record::save(&mut *self).await? || !self.save_nested(¶ms).await?
{
return Err(crate::db::assoc::nested_invalid());
}
Ok(())
})
.await;
match saved {
Ok(()) => Ok(true),
Err(err) if crate::db::assoc::is_nested_invalid(&err) => Ok(false),
Err(err) => Err(err),
}
}
}
#[doc(hidden)]
const HAS_NESTED: bool = false;
#[doc(hidden)]
fn save_nested<'a>(
&'a mut self,
params: &'a Params,
) -> std::pin::Pin<Box<dyn Future<Output = Result<bool>> + Send + 'a>> {
let _ = params;
Box::pin(async { Ok(true) })
}
fn update_with(
&mut self,
change: impl FnOnce(&mut Self),
) -> impl Future<Output = Result<bool>> + Send
where
Self: Clone,
{
change(self);
crate::db::record::save(self)
}
fn reload(&mut self) -> impl Future<Output = Result<()>> + Send {
let query = by_id::<Self>(self.id_value());
async move {
*self = query.one().await?;
Ok(())
}
}
fn errors(&self) -> &[(&'static str, String)] {
self.record().map_or(&[], Record::errors)
}
fn errors_on(&self, column: &str) -> Vec<&str> {
self.errors()
.iter()
.filter(|(c, _)| *c == column)
.map(|(_, m)| m.as_str())
.collect()
}
fn errors_json(&self) -> serde_json::Value {
crate::db::record::errors_json(self.errors())
}
fn messages(&self) -> Vec<String> {
self.errors()
.iter()
.map(|(c, m)| format!("{} {m}", c.replace('_', " ")))
.collect()
}
fn full_messages(&self) -> Vec<String> {
self.errors()
.iter()
.map(|(c, m)| format!("{} {m}", crate::db::humanize(c)))
.collect()
}
fn text(&self, column: &str) -> String {
if let Some(raw) = self.record().and_then(|r| r.raw(column)) {
return raw.to_owned();
}
self.values()
.into_iter()
.chain(self.attribute_values())
.find(|(c, _)| *c == column)
.map(|(_, v)| v.to_text())
.unwrap_or_default()
}
}
fn by_id<M: Model>(id: Value) -> Query<M> {
Query::new().filter(|_| Expr::Compare {
column: M::PRIMARY_KEY,
op: "=",
value: id,
})
}