use std::any::{Any, TypeId};
use std::borrow::Cow;
use std::fmt;
use navree_kernel::BoxFuture;
use serde::{Serialize, Serializer};
use crate::error::Result;
use crate::exec::Target;
use crate::model::{Model, PrimaryKey};
use crate::record::Record;
use crate::value::{Field, Value};
trait ErasedRecord: Send + Sync + 'static {
fn as_any(&self) -> &dyn Any;
fn as_any_mut(&mut self) -> &mut dyn Any;
fn into_any(self: Box<Self>) -> Box<dyn Any>;
fn clone_box(&self) -> Box<dyn ErasedRecord>;
fn to_json(&self) -> std::result::Result<serde_json::Value, serde_json::Error>;
fn model_type(&self) -> TypeId;
fn model_name(&self) -> &'static str;
fn morph_name(&self) -> Cow<'static, str>;
fn key_value(&self) -> Value;
fn key_text(&self) -> String;
fn column(&self, column: &str) -> Result<Option<Value>>;
fn push_on<'a, 'b>(&'a mut self, target: &'a Target<'b>) -> BoxFuture<'a, Result<bool>>;
fn touch_on<'a, 'b>(&'a mut self, target: &'a Target<'b>) -> BoxFuture<'a, Result<bool>>;
}
impl<M: Model> ErasedRecord for Record<M> {
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn into_any(self: Box<Self>) -> Box<dyn Any> {
self
}
fn clone_box(&self) -> Box<dyn ErasedRecord> {
Box::new(self.clone())
}
fn to_json(&self) -> std::result::Result<serde_json::Value, serde_json::Error> {
serde_json::to_value(self)
}
fn model_type(&self) -> TypeId {
TypeId::of::<M>()
}
fn model_name(&self) -> &'static str {
M::meta().name()
}
fn morph_name(&self) -> Cow<'static, str> {
M::morph_name()
}
fn key_value(&self) -> Value {
self.key().to_value()
}
fn key_text(&self) -> String {
self.key().to_key_string()
}
fn column(&self, column: &str) -> Result<Option<Value>> {
self.model.value(column)
}
fn push_on<'a, 'b>(&'a mut self, target: &'a Target<'b>) -> BoxFuture<'a, Result<bool>> {
crate::relations::lazy::push_record(self, target)
}
fn touch_on<'a, 'b>(&'a mut self, target: &'a Target<'b>) -> BoxFuture<'a, Result<bool>> {
Box::pin(async move {
if crate::relations::touch::is_ignoring_touch_of::<M>() {
return Ok(false);
}
crate::persist::touch(target, self, None).await
})
}
}
pub struct AnyRecord {
inner: Box<dyn ErasedRecord>,
}
impl AnyRecord {
pub fn new<M: Model>(record: Record<M>) -> Self {
AnyRecord {
inner: Box::new(record),
}
}
pub fn is<M: Model>(&self) -> bool {
self.inner.model_type() == TypeId::of::<M>()
}
pub fn downcast_ref<M: Model>(&self) -> Option<&Record<M>> {
self.inner.as_any().downcast_ref::<Record<M>>()
}
pub fn downcast_mut<M: Model>(&mut self) -> Option<&mut Record<M>> {
self.inner.as_any_mut().downcast_mut::<Record<M>>()
}
pub fn downcast<M: Model>(self) -> std::result::Result<Record<M>, AnyRecord> {
if !self.is::<M>() {
return Err(self);
}
match self.inner.into_any().downcast::<Record<M>>() {
Ok(record) => Ok(*record),
Err(_) => unreachable!("the model type was checked"),
}
}
pub fn model_name(&self) -> &'static str {
self.inner.model_name()
}
pub fn morph_name(&self) -> Cow<'static, str> {
self.inner.morph_name()
}
pub fn key(&self) -> Value {
self.inner.key_value()
}
pub fn key_string(&self) -> String {
self.inner.key_text()
}
pub fn value(&self, column: &str) -> Result<Option<Value>> {
self.inner.column(column)
}
pub(crate) fn push_on<'a, 'b>(
&'a mut self,
target: &'a Target<'b>,
) -> BoxFuture<'a, Result<bool>> {
self.inner.push_on(target)
}
pub(crate) fn touch_on<'a, 'b>(
&'a mut self,
target: &'a Target<'b>,
) -> BoxFuture<'a, Result<bool>> {
self.inner.touch_on(target)
}
}
impl<M: Model> From<Record<M>> for AnyRecord {
fn from(record: Record<M>) -> Self {
AnyRecord::new(record)
}
}
impl Clone for AnyRecord {
fn clone(&self) -> Self {
AnyRecord {
inner: self.inner.clone_box(),
}
}
}
impl fmt::Debug for AnyRecord {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AnyRecord")
.field("model", &self.model_name())
.field("key", &self.key_string())
.finish_non_exhaustive()
}
}
impl Serialize for AnyRecord {
fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
self.inner
.to_json()
.map_err(serde::ser::Error::custom)?
.serialize(serializer)
}
}
#[macro_export]
macro_rules! morph_types {
(
$(#[$meta:meta])*
$vis:vis enum $name:ident {
$($variant:ident($model:ty)),+ $(,)?
}
) => {
$(#[$meta])*
#[derive(Clone)]
$vis enum $name {
$(
#[doc = concat!("A `", stringify!($model), "`.")]
$variant($crate::Record<$model>),
)+
}
impl $name {
$vis fn register() {
$($crate::relations::MorphMap::register::<$model>();)+
}
$vis fn into_any(self) -> $crate::relations::AnyRecord {
match self {
$($name::$variant(record) => $crate::relations::AnyRecord::new(record),)+
}
}
}
impl ::core::convert::TryFrom<$crate::relations::AnyRecord> for $name {
type Error = $crate::relations::AnyRecord;
fn try_from(
record: $crate::relations::AnyRecord,
) -> ::core::result::Result<Self, $crate::relations::AnyRecord> {
$(
let record = match record.downcast::<$model>() {
::core::result::Result::Ok(record) => {
return ::core::result::Result::Ok($name::$variant(record));
}
::core::result::Result::Err(record) => record,
};
)+
::core::result::Result::Err(record)
}
}
impl $crate::__private::serde::Serialize for $name {
fn serialize<S: $crate::__private::serde::Serializer>(
&self,
serializer: S,
) -> ::core::result::Result<S::Ok, S::Error> {
match self {
$($name::$variant(record) => {
$crate::__private::serde::Serialize::serialize(record, serializer)
})+
}
}
}
};
}