use std::borrow::Cow;
use std::fmt;
use std::future::Future;
use std::sync::Arc;
use chrono::{DateTime, FixedOffset, NaiveDateTime, Utc};
use navree_kernel::BoxFuture;
use serde::Serialize;
use uuid::Uuid;
use crate::attributes::{Accessor, CastContext};
use crate::collection::Collection;
use crate::column::{Assignment, Filter};
use crate::error::Result;
use crate::exec::Executor;
use crate::factory::RelationshipInfo;
use crate::hooks::ModelHook;
use crate::query::Builder;
use crate::record::Record;
use crate::relations::{DynRelation, RelationMeta};
use crate::row::Row;
use crate::scope::GlobalScope;
use crate::ulid::Ulid;
use crate::value::{Field, FieldKind, Value};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum KeyKind {
Increments,
UuidV7,
UuidV4,
Ulid,
ObjectId,
Manual,
}
#[diagnostic::on_unimplemented(
message = "`{Self}` cannot be a model key",
note = "use an integer, `Uuid`, `Ulid` or `String` field as the primary key"
)]
pub trait PrimaryKey: Field + Clone + PartialEq + fmt::Debug {
fn is_empty(&self) -> bool;
fn generate(kind: KeyKind) -> Option<Self>;
fn empty() -> Self;
fn to_key_string(&self) -> String;
}
macro_rules! integer_key {
($($ty:ty),*) => {$(
impl PrimaryKey for $ty {
fn is_empty(&self) -> bool {
*self == 0
}
fn generate(_kind: KeyKind) -> Option<Self> {
None
}
fn empty() -> Self {
0
}
fn to_key_string(&self) -> String {
self.to_string()
}
}
)*};
}
integer_key!(i16, i32, i64, u32, u64);
impl PrimaryKey for Uuid {
fn is_empty(&self) -> bool {
self.is_nil()
}
fn generate(kind: KeyKind) -> Option<Self> {
match kind {
KeyKind::UuidV7 => Some(Uuid::now_v7()),
KeyKind::UuidV4 => Some(Uuid::new_v4()),
KeyKind::Ulid => Some(Ulid::new().to_uuid()),
KeyKind::Increments | KeyKind::ObjectId | KeyKind::Manual => None,
}
}
fn empty() -> Self {
Uuid::nil()
}
fn to_key_string(&self) -> String {
self.to_string()
}
}
impl PrimaryKey for Ulid {
fn is_empty(&self) -> bool {
self.is_nil()
}
fn generate(kind: KeyKind) -> Option<Self> {
match kind {
KeyKind::Ulid | KeyKind::UuidV7 | KeyKind::UuidV4 => Some(Ulid::new()),
KeyKind::Increments | KeyKind::ObjectId | KeyKind::Manual => None,
}
}
fn empty() -> Self {
Ulid::nil()
}
fn to_key_string(&self) -> String {
self.to_string()
}
}
impl PrimaryKey for String {
fn is_empty(&self) -> bool {
str::is_empty(self)
}
fn generate(kind: KeyKind) -> Option<Self> {
match kind {
KeyKind::UuidV7 => Some(Uuid::now_v7().to_string()),
KeyKind::UuidV4 => Some(Uuid::new_v4().to_string()),
KeyKind::Ulid => Some(Ulid::new().to_string()),
KeyKind::Increments | KeyKind::ObjectId | KeyKind::Manual => None,
}
}
fn empty() -> Self {
String::new()
}
fn to_key_string(&self) -> String {
self.clone()
}
}
#[diagnostic::on_unimplemented(
message = "`{Self}` cannot be a timestamp column",
note = "use `DateTime<Utc>`, `DateTime<FixedOffset>`, `NaiveDateTime`, `i64` or an `Option` of one"
)]
pub trait Timestamp: Field {
fn from_now(now: DateTime<Utc>) -> Self;
fn is_empty(&self) -> bool;
fn empty() -> Self;
}
impl Timestamp for DateTime<Utc> {
fn from_now(now: DateTime<Utc>) -> Self {
now
}
fn is_empty(&self) -> bool {
*self == DateTime::<Utc>::UNIX_EPOCH
}
fn empty() -> Self {
DateTime::<Utc>::UNIX_EPOCH
}
}
impl Timestamp for DateTime<FixedOffset> {
fn from_now(now: DateTime<Utc>) -> Self {
now.fixed_offset()
}
fn is_empty(&self) -> bool {
*self == DateTime::<Utc>::UNIX_EPOCH
}
fn empty() -> Self {
DateTime::<Utc>::UNIX_EPOCH.fixed_offset()
}
}
impl Timestamp for NaiveDateTime {
fn from_now(now: DateTime<Utc>) -> Self {
now.naive_utc()
}
fn is_empty(&self) -> bool {
*self == DateTime::<Utc>::UNIX_EPOCH.naive_utc()
}
fn empty() -> Self {
DateTime::<Utc>::UNIX_EPOCH.naive_utc()
}
}
impl Timestamp for i64 {
fn from_now(now: DateTime<Utc>) -> Self {
now.timestamp()
}
fn is_empty(&self) -> bool {
*self == 0
}
fn empty() -> Self {
0
}
}
impl<T: Timestamp> Timestamp for Option<T> {
fn from_now(now: DateTime<Utc>) -> Self {
Some(T::from_now(now))
}
fn is_empty(&self) -> bool {
self.as_ref().is_none_or(T::is_empty)
}
fn empty() -> Self {
None
}
}
pub type PartialSchemaFn = fn() -> navree_openapi::Schema;
#[derive(Clone, Copy, Debug)]
pub struct ColumnMeta {
name: &'static str,
field: &'static str,
rust_type: &'static str,
nullable: bool,
cast: Option<&'static str>,
serialized: Option<&'static str>,
kind: FieldKind,
serde_custom: bool,
serde_optional: bool,
mutator: bool,
schema: Option<PartialSchemaFn>,
}
impl ColumnMeta {
pub const fn new(name: &'static str, field: &'static str, rust_type: &'static str) -> Self {
ColumnMeta {
name,
field,
rust_type,
nullable: false,
cast: None,
serialized: Some(field),
kind: FieldKind::Any,
serde_custom: false,
serde_optional: false,
mutator: false,
schema: None,
}
}
pub const fn nullable(self) -> Self {
ColumnMeta {
nullable: true,
..self
}
}
pub const fn cast(self, cast: &'static str) -> Self {
ColumnMeta {
cast: Some(cast),
..self
}
}
pub const fn serialized_as(self, key: Option<&'static str>) -> Self {
ColumnMeta {
serialized: key,
..self
}
}
pub const fn kind(self, kind: FieldKind) -> Self {
ColumnMeta { kind, ..self }
}
pub const fn serde_custom(self) -> Self {
ColumnMeta {
serde_custom: true,
..self
}
}
pub const fn serde_optional(self) -> Self {
ColumnMeta {
serde_optional: true,
..self
}
}
pub const fn mutator(self) -> Self {
ColumnMeta {
mutator: true,
..self
}
}
pub const fn schema(self, schema: PartialSchemaFn) -> Self {
ColumnMeta {
schema: Some(schema),
..self
}
}
pub const fn name(&self) -> &'static str {
self.name
}
pub const fn field(&self) -> &'static str {
self.field
}
pub const fn rust_type(&self) -> &'static str {
self.rust_type
}
pub const fn is_nullable(&self) -> bool {
self.nullable
}
pub const fn cast_name(&self) -> Option<&'static str> {
self.cast
}
pub const fn serialized_name(&self) -> Option<&'static str> {
self.serialized
}
pub const fn field_kind(&self) -> FieldKind {
self.kind
}
pub const fn is_date_time(&self) -> bool {
matches!(self.kind, FieldKind::DateTime) && !self.serde_custom
}
pub const fn is_json(&self) -> bool {
matches!(self.kind, FieldKind::Json)
}
pub const fn has_custom_serde(&self) -> bool {
self.serde_custom
}
pub const fn is_serde_optional(&self) -> bool {
self.serde_optional
}
pub const fn has_mutator(&self) -> bool {
self.mutator
}
pub const fn schema_override(&self) -> Option<PartialSchemaFn> {
self.schema
}
}
impl PartialEq for ColumnMeta {
fn eq(&self, other: &Self) -> bool {
let same_schema = match (self.schema, other.schema) {
(Some(a), Some(b)) => std::ptr::fn_addr_eq(a, b),
(None, None) => true,
_ => false,
};
self.name == other.name
&& self.field == other.field
&& self.rust_type == other.rust_type
&& self.nullable == other.nullable
&& self.cast == other.cast
&& self.serialized == other.serialized
&& self.kind == other.kind
&& self.serde_custom == other.serde_custom
&& self.serde_optional == other.serde_optional
&& self.mutator == other.mutator
&& same_schema
}
}
impl Eq for ColumnMeta {}
#[derive(Debug)]
pub struct ModelMeta {
name: &'static str,
table: &'static str,
key: &'static str,
key_kind: KeyKind,
columns: &'static [ColumnMeta],
created_at: Option<&'static str>,
updated_at: Option<&'static str>,
deleted_at: Option<&'static str>,
connection: Option<&'static str>,
driver: Option<&'static str>,
per_page: u64,
pruning: Option<crate::prune::Pruning>,
morph_name: Option<&'static str>,
foreign_key: Option<&'static str>,
touches: &'static [&'static str],
with: &'static [&'static str],
with_count: &'static [&'static str],
pivot_keys: Option<(&'static str, &'static str)>,
fillable: &'static [&'static str],
guarded: Option<&'static [&'static str]>,
unguarded: bool,
hidden: &'static [&'static str],
visible: &'static [&'static str],
appends: &'static [&'static str],
encrypter: Option<&'static str>,
cast_context: bool,
date_serializer: Option<DateSerializer>,
route_key: Option<&'static str>,
workspace: Option<&'static str>,
factory: Option<&'static str>,
relationships: Option<fn() -> Vec<RelationshipInfo>>,
subject: Option<&'static str>,
policy: Option<&'static str>,
}
pub type DateSerializer = fn(&DateTime<FixedOffset>) -> serde_json::Value;
impl ModelMeta {
pub const fn new(name: &'static str, table: &'static str) -> Self {
ModelMeta {
name,
table,
key: "id",
key_kind: KeyKind::Increments,
columns: &[],
created_at: None,
updated_at: None,
deleted_at: None,
connection: None,
driver: None,
per_page: 15,
pruning: None,
morph_name: None,
foreign_key: None,
touches: &[],
with: &[],
with_count: &[],
pivot_keys: None,
fillable: &[],
guarded: None,
unguarded: false,
hidden: &[],
visible: &[],
appends: &[],
encrypter: None,
cast_context: false,
date_serializer: None,
route_key: None,
workspace: None,
factory: None,
relationships: None,
subject: None,
policy: None,
}
}
pub const fn fillable(self, columns: &'static [&'static str]) -> Self {
ModelMeta {
fillable: columns,
..self
}
}
pub const fn guarded(self, columns: &'static [&'static str]) -> Self {
ModelMeta {
guarded: Some(columns),
..self
}
}
pub const fn unguarded(self) -> Self {
ModelMeta {
unguarded: true,
..self
}
}
pub const fn hidden(self, names: &'static [&'static str]) -> Self {
ModelMeta {
hidden: names,
..self
}
}
pub const fn visible(self, names: &'static [&'static str]) -> Self {
ModelMeta {
visible: names,
..self
}
}
pub const fn appends(self, names: &'static [&'static str]) -> Self {
ModelMeta {
appends: names,
..self
}
}
pub const fn encrypter(self, name: &'static str) -> Self {
ModelMeta {
encrypter: Some(name),
..self
}
}
pub const fn factory(
self,
name: &'static str,
relationships: fn() -> Vec<RelationshipInfo>,
) -> Self {
ModelMeta {
factory: Some(name),
relationships: Some(relationships),
..self
}
}
pub const fn subject(self, subject: &'static str) -> Self {
ModelMeta {
subject: Some(subject),
..self
}
}
pub const fn policy(self, policy: &'static str) -> Self {
ModelMeta {
policy: Some(policy),
..self
}
}
pub const fn factory_name(&self) -> Option<&'static str> {
self.factory
}
pub fn factory_relationships(&self) -> Vec<RelationshipInfo> {
self.relationships.map(|f| f()).unwrap_or_default()
}
pub const fn subject_name(&self) -> Option<&'static str> {
self.subject
}
pub const fn policy_name(&self) -> Option<&'static str> {
self.policy
}
pub const fn route_key(self, column: &'static str) -> Self {
ModelMeta {
route_key: Some(column),
..self
}
}
pub const fn workspace(self, column: &'static str) -> Self {
ModelMeta {
workspace: Some(column),
..self
}
}
pub const fn cast_context(self, needed: bool) -> Self {
ModelMeta {
cast_context: needed,
..self
}
}
pub const fn serialize_dates_with(self, serializer: DateSerializer) -> Self {
ModelMeta {
date_serializer: Some(serializer),
..self
}
}
pub const fn morph_name(self, name: &'static str) -> Self {
ModelMeta {
morph_name: Some(name),
..self
}
}
pub const fn foreign_key(self, column: &'static str) -> Self {
ModelMeta {
foreign_key: Some(column),
..self
}
}
pub const fn touches(self, relations: &'static [&'static str]) -> Self {
ModelMeta {
touches: relations,
..self
}
}
pub const fn with(self, relations: &'static [&'static str]) -> Self {
ModelMeta {
with: relations,
..self
}
}
pub const fn with_count(self, relations: &'static [&'static str]) -> Self {
ModelMeta {
with_count: relations,
..self
}
}
pub const fn pivot_keys(self, foreign_key: &'static str, related_key: &'static str) -> Self {
ModelMeta {
pivot_keys: Some((foreign_key, related_key)),
..self
}
}
pub const fn pruned(self, pruning: crate::prune::Pruning) -> Self {
ModelMeta {
pruning: Some(pruning),
..self
}
}
pub const fn pruning(&self) -> Option<&crate::prune::Pruning> {
self.pruning.as_ref()
}
pub const fn primary_key(self, column: &'static str, kind: KeyKind) -> Self {
ModelMeta {
key: column,
key_kind: kind,
..self
}
}
pub const fn columns(self, columns: &'static [ColumnMeta]) -> Self {
ModelMeta { columns, ..self }
}
pub const fn timestamps(
self,
created_at: Option<&'static str>,
updated_at: Option<&'static str>,
) -> Self {
ModelMeta {
created_at,
updated_at,
..self
}
}
pub const fn soft_deletes(self, column: &'static str) -> Self {
ModelMeta {
deleted_at: Some(column),
..self
}
}
pub const fn connection(self, name: &'static str) -> Self {
ModelMeta {
connection: Some(name),
..self
}
}
pub const fn driver(self, name: &'static str) -> Self {
ModelMeta {
driver: Some(name),
..self
}
}
pub const fn per_page(self, per_page: u64) -> Self {
ModelMeta { per_page, ..self }
}
pub const fn name(&self) -> &'static str {
self.name
}
pub const fn table(&self) -> &'static str {
self.table
}
pub const fn key_column(&self) -> &'static str {
self.key
}
pub const fn key_kind(&self) -> KeyKind {
self.key_kind
}
pub const fn all_columns(&self) -> &'static [ColumnMeta] {
self.columns
}
pub fn column(&self, name: &str) -> Option<&'static ColumnMeta> {
self.columns.iter().find(|column| column.name == name)
}
pub fn has_column(&self, name: &str) -> bool {
self.column(name).is_some()
}
pub const fn created_at(&self) -> Option<&'static str> {
self.created_at
}
pub const fn updated_at(&self) -> Option<&'static str> {
self.updated_at
}
pub const fn uses_timestamps(&self) -> bool {
self.created_at.is_some() || self.updated_at.is_some()
}
pub const fn deleted_at(&self) -> Option<&'static str> {
self.deleted_at
}
pub const fn soft_deletes_enabled(&self) -> bool {
self.deleted_at.is_some()
}
pub const fn connection_name(&self) -> Option<&'static str> {
self.connection
}
pub const fn driver_name(&self) -> Option<&'static str> {
self.driver
}
pub const fn default_per_page(&self) -> u64 {
self.per_page
}
pub fn morph_type(&self) -> Cow<'static, str> {
match self.morph_name {
Some(name) => Cow::Borrowed(name),
None => Cow::Owned(snake_case(self.name)),
}
}
pub fn foreign_key_name(&self) -> Cow<'static, str> {
match self.foreign_key {
Some(column) => Cow::Borrowed(column),
None => Cow::Owned(format!("{}_{}", snake_case(self.name), self.key)),
}
}
pub const fn touched_relations(&self) -> &'static [&'static str] {
self.touches
}
pub const fn default_with(&self) -> &'static [&'static str] {
self.with
}
pub const fn default_with_count(&self) -> &'static [&'static str] {
self.with_count
}
pub const fn pivot_key_columns(&self) -> Option<(&'static str, &'static str)> {
self.pivot_keys
}
pub const fn fillable_columns(&self) -> &'static [&'static str] {
self.fillable
}
pub const fn guarded_columns(&self) -> Option<&'static [&'static str]> {
self.guarded
}
pub const fn is_unguarded(&self) -> bool {
self.unguarded
}
pub const fn hidden_names(&self) -> &'static [&'static str] {
self.hidden
}
pub const fn visible_names(&self) -> &'static [&'static str] {
self.visible
}
pub const fn appended_names(&self) -> &'static [&'static str] {
self.appends
}
pub const fn encrypter_name(&self) -> Option<&'static str> {
self.encrypter
}
pub const fn uses_cast_context(&self) -> bool {
self.cast_context
}
pub const fn date_serializer(&self) -> Option<DateSerializer> {
self.date_serializer
}
pub fn column_of_field(&self, field: &str) -> Option<&'static ColumnMeta> {
self.columns.iter().find(|column| column.field == field)
}
pub fn column_named(&self, name: &str) -> Option<&'static ColumnMeta> {
self.column(name).or_else(|| self.column_of_field(name))
}
pub const fn route_key_column(&self) -> &'static str {
match self.route_key {
Some(column) => column,
None => self.key,
}
}
pub const fn workspace_column(&self) -> Option<&'static str> {
self.workspace
}
pub const fn is_workspace_scoped(&self) -> bool {
self.workspace.is_some()
}
}
pub(crate) fn snake_case(name: &str) -> String {
let chars: Vec<char> = name.chars().collect();
let mut out = String::with_capacity(name.len() + 4);
for (i, &c) in chars.iter().enumerate() {
if c.is_uppercase() {
let previous = i.checked_sub(1).map(|j| chars[j]);
let next = chars.get(i + 1).copied();
let boundary = match previous {
Some(p) if p.is_lowercase() || p.is_ascii_digit() => true,
Some(p) if p.is_uppercase() => next.is_some_and(char::is_lowercase),
_ => false,
};
if boundary && !out.ends_with('_') {
out.push('_');
}
out.extend(c.to_lowercase());
} else {
out.push(c);
}
}
out
}
pub trait Model: Clone + Send + Sync + Serialize + 'static {
type Key: PrimaryKey;
fn meta() -> &'static ModelMeta;
fn key(&self) -> Self::Key;
fn set_key(&mut self, key: Self::Key);
fn from_row(row: &Row) -> Result<Self>;
fn values(&self) -> Result<Vec<(&'static str, Value)>>;
fn value(&self, column: &str) -> Result<Option<Value>>;
fn set_value(&mut self, column: &str, value: Value) -> Result<()>;
fn touch_timestamp(&mut self, column: &str, now: DateTime<Utc>) -> Result<()>;
fn timestamp_is_empty(&self, column: &str) -> bool;
fn clear_timestamp(&mut self, column: &str);
fn timestamp_value(column: &str, now: DateTime<Utc>) -> Option<Value>;
fn global_scopes() -> Vec<Arc<dyn GlobalScope<Self>>> {
Vec::new()
}
fn hooks() -> Vec<Arc<dyn ModelHook<Self>>> {
Vec::new()
}
fn set_attribute(&mut self, column: &str, input: serde_json::Value) -> Result<()> {
self.set_value(column, crate::value::json_to_value(input))
}
#[doc(hidden)]
fn set_attribute_parts(
&mut self,
field: &str,
inputs: Vec<(String, serde_json::Value)>,
) -> Result<()> {
let _ = field;
for (column, input) in inputs {
self.set_attribute(&column, input)?;
}
Ok(())
}
fn changed_columns(&self, original: &Self) -> Result<Vec<&'static str>> {
let now = self.values()?;
let then = original.values()?;
Ok(now
.into_iter()
.zip(then)
.filter(|((_, a), (_, b))| !crate::value::same_value(a, b))
.map(|((column, _), _)| column)
.collect())
}
fn json_attribute(&self, column: &str) -> Result<Option<serde_json::Value>> {
let _ = column;
Ok(None)
}
fn accessors() -> &'static [Accessor<Self>] {
&[]
}
fn fillable() -> &'static [&'static str] {
Self::meta().fillable_columns()
}
fn guarded() -> Option<&'static [&'static str]> {
Self::meta().guarded_columns()
}
fn is_fillable(column: &str) -> bool {
crate::attributes::fill::is_fillable(Self::meta(), column, false)
}
fn is_guarded(column: &str) -> bool {
crate::attributes::fill::is_guarded(Self::meta(), column, false)
}
fn totally_guarded() -> bool {
crate::attributes::fill::totally_guarded(Self::meta(), false)
}
#[doc(hidden)]
fn prepare_for_write<'a>(&'a mut self, context: &'a CastContext) -> BoxFuture<'a, Result<()>> {
let _ = context;
Box::pin(std::future::ready(Ok(())))
}
#[doc(hidden)]
fn serialized_overrides(&self) -> Result<Vec<(&'static str, serde_json::Value)>> {
Ok(Vec::new())
}
#[doc(hidden)]
fn stale_columns(row: &Row) -> Vec<&'static str> {
let _ = row;
Vec::new()
}
#[doc(hidden)]
fn increment_cast(&mut self, column: &str, amount: Value, decrement: bool) -> Result<()> {
let _ = (amount, decrement);
Err(derive_support::not_a_cast_column::<Self>(column))
}
fn relation(name: &str) -> Option<DynRelation<Self>> {
crate::relations::registry::defined::<Self>(name)
}
fn relation_names() -> Vec<Cow<'static, str>> {
crate::relations::registry::defined_names::<Self>()
}
fn relation_meta(name: &str) -> Option<RelationMeta> {
Self::relation(name).map(|relation| relation.meta())
}
fn morph_name() -> Cow<'static, str> {
Self::meta().morph_type()
}
fn foreign_key_name() -> Cow<'static, str> {
Self::meta().foreign_key_name()
}
fn touched_relations() -> &'static [&'static str] {
Self::meta().touched_relations()
}
fn table_name() -> &'static str {
Self::meta().table()
}
fn route_key_name() -> &'static str {
Self::meta().route_key_column()
}
fn query() -> Builder<Self> {
Builder::new().with_model_defaults()
}
fn where_(filter: impl Into<Filter>) -> Builder<Self> {
Self::query().where_(filter)
}
fn connection_name() -> Option<&'static str> {
Self::meta().connection_name()
}
fn on_connection(name: impl Into<std::borrow::Cow<'static, str>>) -> Builder<Self> {
Builder::new().on_connection(name)
}
fn on_write_connection() -> Builder<Self> {
Builder::new().use_write()
}
fn all<E: Executor + ?Sized>(
exec: &E,
) -> impl Future<Output = Result<Collection<Self>>> + Send {
Self::query().get(exec)
}
fn find<E: Executor + ?Sized>(
exec: &E,
key: impl Into<Self::Key>,
) -> impl Future<Output = Result<Option<Record<Self>>>> + Send {
let key: Self::Key = key.into();
Self::query().find(exec, key)
}
fn find_or_fail<E: Executor + ?Sized>(
exec: &E,
key: impl Into<Self::Key>,
) -> impl Future<Output = Result<Record<Self>>> + Send {
let key: Self::Key = key.into();
Self::query().find_or_fail(exec, key)
}
fn find_many<E: Executor + ?Sized>(
exec: &E,
keys: impl IntoIterator<Item = impl Into<Self::Key>>,
) -> impl Future<Output = Result<Collection<Self>>> + Send {
let keys: Vec<Self::Key> = keys.into_iter().map(Into::into).collect();
Self::query().find_many(exec, keys)
}
fn create<E: Executor + ?Sized>(
exec: &E,
model: Self,
) -> impl Future<Output = Result<Record<Self>>> + Send {
async move {
let mut record = Record::new(model);
record.save(exec).await?;
Ok(record)
}
}
fn create_from<E: Executor + ?Sized>(
exec: &E,
attributes: impl Into<crate::attributes::Attributes>,
) -> impl Future<Output = Result<Record<Self>>> + Send
where
Self: Default,
{
let attributes = attributes.into();
Self::query().create_from(exec, attributes)
}
fn force_create<E: Executor + ?Sized>(
exec: &E,
attributes: impl Into<crate::attributes::Attributes>,
) -> impl Future<Output = Result<Record<Self>>> + Send
where
Self: Default,
{
let attributes = attributes.into();
Self::query().force_create(exec, attributes)
}
fn insert<E: Executor + ?Sized>(
exec: &E,
models: impl IntoIterator<Item = Self>,
) -> impl Future<Output = Result<u64>> + Send {
let models: Vec<Self> = models.into_iter().collect();
Self::query().insert(exec, models)
}
fn insert_or_ignore<E: Executor + ?Sized>(
exec: &E,
models: impl IntoIterator<Item = Self>,
) -> impl Future<Output = Result<u64>> + Send {
let models: Vec<Self> = models.into_iter().collect();
Self::query().insert_or_ignore(exec, models)
}
fn fill_and_insert<E: Executor + ?Sized>(
exec: &E,
models: impl IntoIterator<Item = Self>,
) -> impl Future<Output = Result<u64>> + Send {
let models: Vec<Self> = models.into_iter().collect();
Self::query().fill_and_insert(exec, models)
}
fn upsert<E, U>(
exec: &E,
models: impl IntoIterator<Item = Self>,
unique_by: impl IntoIterator<Item = impl crate::column::ColumnName>,
update: impl IntoIterator<Item = U>,
) -> impl Future<Output = Result<u64>> + Send
where
E: Executor + ?Sized,
U: Into<crate::query::ConflictUpdate>,
{
let models: Vec<Self> = models.into_iter().collect();
let unique_by: Vec<String> = unique_by
.into_iter()
.map(|column| column.column_name().into_owned())
.collect();
let update: Vec<crate::query::ConflictUpdate> =
update.into_iter().map(Into::into).collect();
Self::query().upsert(exec, models, unique_by, update)
}
fn destroy<E: Executor + ?Sized>(
exec: &E,
keys: impl IntoIterator<Item = impl Into<Self::Key>>,
) -> impl Future<Output = Result<u64>> + Send {
let keys: Vec<Self::Key> = keys.into_iter().map(Into::into).collect();
async move {
if keys.is_empty() {
return Ok(0);
}
let records = Self::query().where_key_in(keys).get(exec).await?;
let mut deleted = 0;
for mut record in records {
if record.delete(exec).await? {
deleted += 1;
}
}
Ok(deleted)
}
}
fn first_or_create<E: Executor + ?Sized>(
exec: &E,
attributes: impl IntoIterator<Item = Assignment>,
fill: impl FnOnce(&mut Self) + Send,
) -> impl Future<Output = Result<Record<Self>>> + Send
where
Self: Default,
{
let attributes: Vec<Assignment> = attributes.into_iter().collect();
Self::query().first_or_create(exec, attributes, fill)
}
fn first_or_new<E: Executor + ?Sized>(
exec: &E,
attributes: impl IntoIterator<Item = Assignment>,
fill: impl FnOnce(&mut Self) + Send,
) -> impl Future<Output = Result<Record<Self>>> + Send
where
Self: Default,
{
let attributes: Vec<Assignment> = attributes.into_iter().collect();
Self::query().first_or_new(exec, attributes, fill)
}
fn create_or_first<E: Executor + ?Sized>(
exec: &E,
attributes: impl IntoIterator<Item = Assignment>,
fill: impl FnOnce(&mut Self) + Send,
) -> impl Future<Output = Result<Record<Self>>> + Send
where
Self: Default,
{
let attributes: Vec<Assignment> = attributes.into_iter().collect();
Self::query().create_or_first(exec, attributes, fill)
}
fn update_or_create<E: Executor + ?Sized>(
exec: &E,
attributes: impl IntoIterator<Item = Assignment>,
fill: impl Fn(&mut Self) + Send + Sync,
) -> impl Future<Output = Result<Record<Self>>> + Send
where
Self: Default,
{
let attributes: Vec<Assignment> = attributes.into_iter().collect();
Self::query().update_or_create(exec, attributes, fill)
}
}
#[doc(hidden)]
pub mod derive_support {
use std::borrow::Cow;
use serde::Serialize;
use crate::attributes::CastContext;
use crate::cast::{Cast, CastError, MultiColumnCast, StoredColumns};
use crate::error::OrmError;
use crate::model::Model;
use crate::row::{Row, decode_error};
use crate::value::{Field, FieldError, Value, same_value};
fn cast_error<M: Model>(column: &str, message: impl Into<String>) -> OrmError {
OrmError::Cast {
model: Cow::Borrowed(M::meta().name()),
column: column.to_owned(),
message: message.into(),
}
}
pub fn read<M: Model, T: Field>(
row: &Row,
column: &str,
default: Option<fn() -> T>,
) -> Result<T, OrmError> {
match row.field::<T>(column) {
Ok(value) => Ok(value),
Err(FieldError::Missing) => missing::<M, T>(row, column, T::type_name(), default),
Err(error) => Err(decode_error(
M::meta().name(),
column,
T::type_name(),
&error,
)),
}
}
fn missing<M: Model, T>(
row: &Row,
column: &str,
expected: Cow<'static, str>,
default: Option<fn() -> T>,
) -> Result<T, OrmError> {
let error = |expected| OrmError::MissingAttribute {
model: Cow::Borrowed(M::meta().name()),
column: column.to_owned(),
expected,
selected: row.columns(),
};
let Some(default) = default else {
return Err(error(expected));
};
crate::strict::current().check_with(
crate::strict::Violation::MissingAttribute {
model: M::meta().name(),
column: column.to_owned(),
},
|_| error(expected),
)?;
Ok(default())
}
pub struct DefaultOf<T>(std::marker::PhantomData<fn() -> T>);
impl<T> DefaultOf<T> {
pub const fn new() -> Self {
DefaultOf(std::marker::PhantomData)
}
}
impl<T> Default for DefaultOf<T> {
fn default() -> Self {
DefaultOf::new()
}
}
pub trait ViaDefault {
type Field;
fn default_fn(&self) -> Option<fn() -> Self::Field>;
}
impl<T: Default> ViaDefault for DefaultOf<T> {
type Field = T;
fn default_fn(&self) -> Option<fn() -> T> {
Some(T::default)
}
}
pub trait WithoutDefault {
type Field;
fn default_fn(&self) -> Option<fn() -> Self::Field>;
}
impl<T> WithoutDefault for &DefaultOf<T> {
type Field = T;
fn default_fn(&self) -> Option<fn() -> T> {
None
}
}
pub fn read_or_default<M: Model, T: Field + Default>(
row: &Row,
column: &str,
) -> Result<T, OrmError> {
match row.field::<T>(column) {
Ok(value) => Ok(value),
Err(FieldError::Missing) => Ok(T::default()),
Err(error) => Err(decode_error(
M::meta().name(),
column,
T::type_name(),
&error,
)),
}
}
pub fn read_cast<M: Model, C: Cast<T>, T>(
row: &Row,
column: &str,
default: Option<fn() -> T>,
) -> Result<T, OrmError> {
match row.field::<C::Stored>(column) {
Ok(stored) => get::<M, C, T>(column, stored),
Err(FieldError::Missing) => {
missing::<M, T>(row, column, C::Stored::type_name(), default)
}
Err(error) => Err(decode_error(
M::meta().name(),
column,
C::Stored::type_name(),
&error,
)),
}
}
fn get<M: Model, C: Cast<T>, T>(column: &str, stored: C::Stored) -> Result<T, OrmError> {
CastContext::with_current(|context| C::get_with(stored, context))
.map_err(|error| cast_error::<M>(column, error.to_string()))
}
fn set<M: Model, C: Cast<T>, T>(column: &str, value: &T) -> Result<C::Stored, OrmError> {
CastContext::with_current(|context| C::set_with(value, context))
.map_err(|error| cast_error::<M>(column, error.to_string()))
}
pub fn read_cast_option<M: Model, C: Cast<T>, T>(
row: &Row,
column: &str,
default: Option<fn() -> Option<T>>,
) -> Result<Option<T>, OrmError> {
match row.field::<Option<C::Stored>>(column) {
Ok(Some(stored)) => get::<M, C, T>(column, stored).map(Some),
Ok(None) => Ok(None),
Err(FieldError::Missing) => {
missing::<M, Option<T>>(row, column, <Option<C::Stored>>::type_name(), default)
}
Err(error) => Err(decode_error(
M::meta().name(),
column,
<Option<C::Stored>>::type_name(),
&error,
)),
}
}
pub fn read_cast_or_default<M: Model, C: Cast<T>, T: Default>(
row: &Row,
column: &str,
) -> Result<T, OrmError> {
if row.has_column(column) {
read_cast::<M, C, T>(row, column, Some(T::default))
} else {
Ok(T::default())
}
}
pub fn read_cast_option_or_default<M: Model, C: Cast<T>, T>(
row: &Row,
column: &str,
) -> Result<Option<T>, OrmError> {
if row.has_column(column) {
read_cast_option::<M, C, T>(row, column, Some(|| None))
} else {
Ok(None)
}
}
pub fn write_cast<M: Model, C: Cast<T>, T>(column: &str, value: &T) -> Result<Value, OrmError> {
set::<M, C, T>(column, value).map(|stored| stored.to_value())
}
pub fn write_cast_option<M: Model, C: Cast<T>, T>(
column: &str,
value: &Option<T>,
) -> Result<Value, OrmError> {
match value {
Some(value) => write_cast::<M, C, T>(column, value),
None => Ok(CastContext::with_current(C::null_with)),
}
}
pub fn convert<M: Model, T: Field>(column: &str, value: Value) -> Result<T, OrmError> {
T::from_value(value)
.map_err(|error| decode_error(M::meta().name(), column, T::type_name(), &error))
}
pub fn convert_cast<M: Model, C: Cast<T>, T>(
column: &str,
value: Value,
) -> Result<T, OrmError> {
let stored = convert::<M, C::Stored>(column, value)?;
get::<M, C, T>(column, stored)
}
pub fn convert_cast_option<M: Model, C: Cast<T>, T>(
column: &str,
value: Value,
) -> Result<Option<T>, OrmError> {
match convert::<M, Option<C::Stored>>(column, value)? {
Some(stored) => get::<M, C, T>(column, stored).map(Some),
None => Ok(None),
}
}
fn input_error<M: Model>(
column: &str,
expected: Cow<'static, str>,
message: String,
) -> OrmError {
OrmError::Decode {
model: Cow::Borrowed(M::meta().name()),
column: column.to_owned(),
expected,
message,
}
}
pub fn input<M: Model, T: Field>(
column: &str,
input: serde_json::Value,
) -> Result<T, OrmError> {
T::from_json(input).map_err(|error| {
input_error::<M>(
column,
T::type_name(),
match error {
FieldError::Null => "the input is null (make the field an Option)".to_owned(),
other => other.to_string(),
},
)
})
}
pub fn input_cast<M: Model, C: Cast<T>, T>(
column: &str,
input: serde_json::Value,
) -> Result<T, OrmError> {
if input.is_null() {
return Err(input_error::<M>(
column,
Cow::Borrowed(short_type_name::<T>()),
"the input is null (make the field an Option)".to_owned(),
));
}
CastContext::with_current(|context| C::from_json(input, context))
.map_err(|error| cast_error::<M>(column, error.to_string()))
}
pub fn input_cast_option<M: Model, C: Cast<T>, T>(
column: &str,
input: serde_json::Value,
) -> Result<Option<T>, OrmError> {
if input.is_null() {
return Ok(None);
}
input_cast::<M, C, T>(column, input).map(Some)
}
fn short_type_name<T>() -> &'static str {
let full = std::any::type_name::<T>();
let base = full.split('<').next().unwrap_or(full);
base.rsplit("::").next().unwrap_or(base)
}
pub fn same_field<T: Field>(a: &T, b: &T) -> bool {
same_value(&a.to_value(), &b.to_value())
}
pub fn same_cast<C: Cast<T>, T>(a: &T, b: &T) -> bool {
CastContext::with_current(|context| C::same(a, b, context))
}
pub fn same_cast_option<C: Cast<T>, T>(a: &Option<T>, b: &Option<T>) -> bool {
match (a, b) {
(Some(a), Some(b)) => same_cast::<C, T>(a, b),
(None, None) => true,
_ => false,
}
}
pub fn stale_cast<C: Cast<T>, T>(row: &Row, column: &str) -> bool {
CastContext::with_current(|context| C::is_stale(row, column, context))
}
pub async fn prepare_cast<M: Model, C: Cast<T>, T>(
column: &str,
value: &mut T,
context: &CastContext,
) -> Result<(), OrmError> {
C::prepare(value, context)
.await
.map_err(|error| cast_error::<M>(column, error.to_string()))
}
pub async fn prepare_cast_option<M: Model, C: Cast<T>, T>(
column: &str,
value: &mut Option<T>,
context: &CastContext,
) -> Result<(), OrmError> {
match value {
Some(value) => prepare_cast::<M, C, T>(column, value, context).await,
None => Ok(()),
}
}
pub fn serialize_cast<M: Model, C: Cast<T>, T>(
column: &str,
value: &T,
) -> Result<Option<serde_json::Value>, OrmError> {
C::serialize(value)
.transpose()
.map_err(|error| serialize_error::<M>(column, error.to_string()))
}
pub fn serialize_cast_option<M: Model, C: Cast<T>, T>(
column: &str,
value: &Option<T>,
) -> Result<Option<serde_json::Value>, OrmError> {
match value {
Some(value) => serialize_cast::<M, C, T>(column, value),
None => Ok(None),
}
}
fn serialize_error<M: Model>(column: &str, message: String) -> OrmError {
OrmError::Serialize {
model: Cow::Borrowed(M::meta().name()),
column: Some(column.to_owned()),
message,
}
}
pub fn json_of<M: Model, T: Serialize>(
column: &str,
value: &T,
) -> Result<serde_json::Value, OrmError> {
serde_json::to_value(value).map_err(|error| serialize_error::<M>(column, error.to_string()))
}
pub fn increment_cast<M: Model, C: Cast<T>, T>(
column: &str,
value: &mut T,
amount: Value,
decrement: bool,
) -> Result<(), OrmError> {
let amount = convert_cast::<M, C, T>(column, amount)?;
let next = if decrement {
C::decrement(value, &amount)
} else {
C::increment(value, &amount)
};
*value = next.map_err(|error| cast_error::<M>(column, error.to_string()))?;
Ok(())
}
pub fn increment_cast_option<M: Model, C: Cast<T>, T>(
column: &str,
value: &mut Option<T>,
amount: Value,
decrement: bool,
) -> Result<(), OrmError> {
match value {
Some(value) => increment_cast::<M, C, T>(column, value, amount, decrement),
None => Ok(()),
}
}
pub fn not_a_cast_column<M: Model>(column: &str) -> OrmError {
OrmError::InvalidQuery(format!(
"`{column}` of {} is not a cast column: increment it with Record::increment",
M::meta().name()
))
}
pub fn read_multi<M: Model, C: MultiColumnCast<T>, T>(
field: &str,
stored: C::Stored,
) -> Result<T, OrmError> {
CastContext::with_current(|context| C::get_with(stored, context))
.map_err(|error| cast_error::<M>(field, error.to_string()))
}
pub fn write_multi<M: Model, C: MultiColumnCast<T>, T>(
field: &str,
value: &T,
) -> Result<C::Stored, OrmError> {
CastContext::with_current(|context| C::set_with(value, context))
.map_err(|error| cast_error::<M>(field, error.to_string()))
}
pub fn write_multi_option<M: Model, C: MultiColumnCast<T>, T>(
field: &str,
value: &Option<T>,
) -> Result<Vec<Value>, OrmError> {
match value {
Some(value) => write_multi::<M, C, T>(field, value).map(|stored| stored.to_values()),
None => Ok(C::Stored::nulls()),
}
}
pub fn multi_values<M: Model, C: MultiColumnCast<T>, T>(
field: &str,
value: &T,
) -> Result<Vec<Value>, OrmError> {
write_multi::<M, C, T>(field, value).map(|stored| stored.to_values())
}
fn multi_error<M: Model, C: MultiColumnCast<T>, T>(
row: &Row,
columns: &[&str],
(index, error): (usize, FieldError),
) -> OrmError {
let column = columns.get(index).copied().unwrap_or("?");
let expected = C::Stored::type_name(index);
match error {
FieldError::Missing => OrmError::MissingAttribute {
model: Cow::Borrowed(M::meta().name()),
column: column.to_owned(),
expected,
selected: row.columns(),
},
other => decode_error(M::meta().name(), column, expected, &other),
}
}
pub fn read_multi_row<M: Model, C: MultiColumnCast<T>, T>(
row: &Row,
field: &str,
columns: &[&str],
) -> Result<T, OrmError> {
let stored = C::Stored::from_row(row, columns)
.map_err(|error| multi_error::<M, C, T>(row, columns, error))?;
read_multi::<M, C, T>(field, stored)
}
pub fn read_multi_row_option<M: Model, C: MultiColumnCast<T>, T>(
row: &Row,
field: &str,
columns: &[&str],
) -> Result<Option<T>, OrmError> {
match C::Stored::from_row_option(row, columns)
.map_err(|error| multi_error::<M, C, T>(row, columns, error))?
{
Some(stored) => read_multi::<M, C, T>(field, stored).map(Some),
None => Ok(None),
}
}
pub fn replace_multi<M: Model, C: MultiColumnCast<T>, T>(
field: &str,
current: &T,
column: &str,
index: usize,
value: Value,
) -> Result<T, OrmError> {
let mut values = write_multi::<M, C, T>(field, current)?.to_values();
values[index] = value;
let stored = C::Stored::from_values(values).map_err(|(index, error)| {
decode_error(
M::meta().name(),
column,
C::Stored::type_name(index),
&error,
)
})?;
read_multi::<M, C, T>(field, stored)
}
pub fn replace_multi_option<M: Model, C: MultiColumnCast<T>, T>(
field: &str,
current: &Option<T>,
column: &str,
index: usize,
value: Value,
) -> Result<Option<T>, OrmError> {
let mut values = write_multi_option::<M, C, T>(field, current)?;
values[index] = value;
if values.iter().all(crate::value::is_null) {
return Ok(None);
}
let stored = C::Stored::from_values(values).map_err(|(index, error)| {
decode_error(
M::meta().name(),
column,
C::Stored::type_name(index),
&error,
)
})?;
read_multi::<M, C, T>(field, stored).map(Some)
}
pub fn multi_from_values<M: Model, C: MultiColumnCast<T>, T>(
field: &str,
columns: &[&str],
values: Vec<Value>,
) -> Result<T, OrmError> {
let stored = C::Stored::from_values(values).map_err(|(index, error)| {
let column = columns.get(index).copied().unwrap_or(field);
decode_error(
M::meta().name(),
column,
C::Stored::type_name(index),
&error,
)
})?;
read_multi::<M, C, T>(field, stored)
}
pub fn multi_from_values_option<M: Model, C: MultiColumnCast<T>, T>(
field: &str,
columns: &[&str],
values: Vec<Value>,
) -> Result<Option<T>, OrmError> {
if values.iter().all(crate::value::is_null) {
return Ok(None);
}
multi_from_values::<M, C, T>(field, columns, values).map(Some)
}
pub fn changed_multi<M: Model, C: MultiColumnCast<T>, T>(
field: &str,
a: &T,
b: &T,
) -> Vec<usize> {
match (
multi_values::<M, C, T>(field, a),
multi_values::<M, C, T>(field, b),
) {
(Ok(a), Ok(b)) => (0..a.len())
.filter(|&i| !same_value(&a[i], &b[i]))
.collect(),
_ => (0..C::Stored::COUNT).collect(),
}
}
pub fn changed_multi_option<M: Model, C: MultiColumnCast<T>, T>(
field: &str,
a: &Option<T>,
b: &Option<T>,
) -> Vec<usize> {
match (
write_multi_option::<M, C, T>(field, a),
write_multi_option::<M, C, T>(field, b),
) {
(Ok(a), Ok(b)) => (0..a.len())
.filter(|&i| !same_value(&a[i], &b[i]))
.collect(),
_ => (0..C::Stored::COUNT).collect(),
}
}
pub fn factory_relationships<F: crate::factory::ModelFactory>()
-> Vec<crate::factory::RelationshipInfo> {
crate::factory::Relationships::<F::Model>::of::<F>().infos()
}
pub fn unknown_column<M: Model>(column: &str) -> OrmError {
OrmError::InvalidQuery(format!("{} has no column `{column}`", M::meta().name()))
}
pub fn not_a_timestamp<M: Model>(column: &str) -> OrmError {
OrmError::InvalidQuery(format!(
"`{column}` is not a timestamp column of {}",
M::meta().name()
))
}
pub fn accessor_json<T: Serialize>(value: &T) -> Result<serde_json::Value, CastError> {
serde_json::to_value(value).map_err(|error| CastError::new(error.to_string()))
}
pub fn stored_json(value: Value) -> Option<serde_json::Value> {
match value {
Value::Json(json) => Some(json),
_ => None,
}
}
pub struct JsonProbe<'a, T>(pub &'a T);
pub trait JsonProbeJson {
fn json_attribute(&self) -> Result<Option<serde_json::Value>, OrmError>;
}
impl JsonProbeJson for JsonProbe<'_, serde_json::Value> {
fn json_attribute(&self) -> Result<Option<serde_json::Value>, OrmError> {
Ok(Some(self.0.clone()))
}
}
impl JsonProbeJson for JsonProbe<'_, Option<serde_json::Value>> {
fn json_attribute(&self) -> Result<Option<serde_json::Value>, OrmError> {
Ok(Some(self.0.clone().unwrap_or(serde_json::Value::Null)))
}
}
pub trait JsonProbeAny {
fn json_attribute(&self) -> Result<Option<serde_json::Value>, OrmError>;
}
impl<T> JsonProbeAny for &JsonProbe<'_, T> {
fn json_attribute(&self) -> Result<Option<serde_json::Value>, OrmError> {
Ok(None)
}
}
}