use std::any::type_name;
use rainier_orm::Entity;
use rainier_support::str::class_basename;
pub trait Model: Entity + Clone + Send + Sync + 'static {
fn model_name() -> &'static str {
class_basename(type_name::<Self>())
}
fn route_key_name() -> &'static str {
Self::primary_key()
}
}
#[derive(Debug, Clone)]
pub struct Creating<M> {
pub model: M,
}
#[derive(Debug, Clone)]
pub struct Created<M> {
pub model: M,
pub id: i64,
}
#[derive(Debug, Clone)]
pub struct Updating<M> {
pub model: M,
}
#[derive(Debug, Clone)]
pub struct Updated<M> {
pub model: M,
pub rows_affected: u64,
}
#[derive(Debug, Clone)]
pub struct Deleting<M> {
pub key: String,
pub model: std::marker::PhantomData<M>,
}
#[derive(Debug, Clone)]
pub struct Deleted<M> {
pub key: String,
pub rows_affected: u64,
pub model: std::marker::PhantomData<M>,
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(rainier_orm::Entity, Clone, Debug)]
#[orm(table = "posts")]
struct Post {
#[orm(pk, auto_increment)]
id: u64,
#[orm(unique)]
slug: String,
title: String,
}
impl Model for Post {}
#[derive(rainier_orm::Entity, Clone, Debug)]
#[orm(table = "pages")]
struct Page {
#[orm(pk, auto_increment)]
id: u64,
#[orm(unique)]
slug: String,
}
impl Model for Page {
fn route_key_name() -> &'static str {
"slug"
}
}
#[test]
fn the_model_name_is_the_type_name_without_its_module_path() {
assert_eq!(Post::model_name(), "Post");
}
#[test]
fn the_route_key_defaults_to_the_primary_key() {
assert_eq!(Post::route_key_name(), "id");
assert_eq!(Post::route_key_name(), Post::primary_key());
}
#[test]
fn the_route_key_can_be_overridden() {
assert_eq!(Page::route_key_name(), "slug");
assert_eq!(Page::primary_key(), "id", "the primary key is unchanged");
}
#[test]
fn the_entity_metadata_still_comes_from_the_derive() {
assert_eq!(Post::table(), "posts");
assert_eq!(Post::columns().len(), 3);
}
#[test]
fn hook_events_carry_the_model() {
let post = Post { id: 1, slug: "hi".into(), title: "Hi".into() };
let creating = Creating { model: post.clone() };
assert_eq!(creating.model.title, "Hi");
let created = Created { model: post, id: 7 };
assert_eq!(created.id, 7);
}
}