Skip to main content

renox_core/db/
schema.rs

1//! A runtime description of a model's columns: the kind of each field's Rust
2//! type, which `db:check` compares with the real table.
3
4use chrono::{NaiveDate, NaiveDateTime, NaiveTime, TimeZone};
5
6use super::{Encrypted, Json, Ulid};
7
8/// The kind of value a model field stores, as far as the database cares.
9///
10/// `Unknown` is a field type Renox has no [`ColumnType`] for (a custom type);
11/// checks skip it.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum ColumnKind {
15    /// 64-bit integer (`i64`, `u32`).
16    BigInt,
17    /// 32-bit integer (`i32`, `u16`).
18    Int,
19    /// 16-bit integer or smaller (`i8`, `i16`, `u8`).
20    SmallInt,
21    /// `f64`.
22    Double,
23    /// `f32`.
24    Real,
25    /// Text (`String`, `Ulid`, `Encrypted<T>`, enums).
26    Text,
27    /// Bytes (`Vec<u8>`).
28    Blob,
29    /// `bool`.
30    Bool,
31    /// `chrono::DateTime<Tz>`.
32    DateTime,
33    /// `chrono::NaiveDateTime`.
34    NaiveDateTime,
35    /// `chrono::NaiveDate`.
36    Date,
37    /// `chrono::NaiveTime`.
38    Time,
39    /// `serde_json::Value` and `Json<T>`.
40    Json,
41    /// `uuid::Uuid`.
42    Uuid,
43    /// A type Renox doesn't know.
44    Unknown,
45}
46
47impl ColumnKind {
48    /// A lowercase name for messages.
49    pub fn as_str(&self) -> &'static str {
50        match self {
51            Self::BigInt => "bigint",
52            Self::Int => "int",
53            Self::SmallInt => "smallint",
54            Self::Double => "double",
55            Self::Real => "real",
56            Self::Text => "text",
57            Self::Blob => "blob",
58            Self::Bool => "bool",
59            Self::DateTime => "datetime",
60            Self::NaiveDateTime => "naive datetime",
61            Self::Date => "date",
62            Self::Time => "time",
63            Self::Json => "json",
64            Self::Uuid => "uuid",
65            Self::Unknown => "unknown",
66        }
67    }
68}
69
70/// A Rust type that can be a model field, and the kind of column it fills.
71/// Implemented for every type with a `ToDbValue` impl, plus `Option<T>`,
72/// `Json<T>`, `Encrypted<T>` and `Ulid`.
73pub trait ColumnType {
74    /// The kind of column this type is stored in.
75    const KIND: ColumnKind;
76}
77
78macro_rules! kinds {
79    ($($kind:ident => $($t:ty),*;)*) => {$($(
80        impl ColumnType for $t {
81            const KIND: ColumnKind = ColumnKind::$kind;
82        }
83    )*)*};
84}
85
86kinds! {
87    BigInt => i64, u32;
88    Int => i32, u16;
89    SmallInt => i8, i16, u8;
90    Double => f64;
91    Real => f32;
92    Text => String, Ulid;
93    Blob => Vec<u8>;
94    Bool => bool;
95    NaiveDateTime => NaiveDateTime;
96    Date => NaiveDate;
97    Time => NaiveTime;
98    Json => serde_json::Value;
99}
100
101#[cfg(feature = "uuid")]
102impl ColumnType for uuid::Uuid {
103    const KIND: ColumnKind = ColumnKind::Uuid;
104}
105
106impl<Tz: TimeZone> ColumnType for chrono::DateTime<Tz> {
107    const KIND: ColumnKind = ColumnKind::DateTime;
108}
109
110/// A `Quantity` is one `BIGINT` column; the scale is in the Rust type only.
111impl<const S: u32> ColumnType for crate::quantity::Quantity<S> {
112    const KIND: ColumnKind = ColumnKind::BigInt;
113}
114
115impl<T: ColumnType> ColumnType for Option<T> {
116    const KIND: ColumnKind = T::KIND;
117}
118
119impl<T> ColumnType for Json<T> {
120    const KIND: ColumnKind = ColumnKind::Json;
121}
122
123impl<T> ColumnType for Encrypted<T> {
124    const KIND: ColumnKind = ColumnKind::Text;
125}
126
127/// One column of a model, as the derive describes it.
128#[derive(Debug, Clone)]
129#[non_exhaustive]
130pub struct ModelColumn {
131    /// The column's name.
132    pub name: &'static str,
133    /// The field's Rust type, as written.
134    pub rust_type: &'static str,
135    /// What kind of column the type fills.
136    pub kind: ColumnKind,
137    /// Whether the field is an `Option`.
138    pub nullable: bool,
139    /// The SQL default from `#[model(default = "…")]`, if any.
140    pub default: Option<&'static str>,
141    /// The table from `#[model(references = "…")]`, if any.
142    pub references: Option<&'static str>,
143}
144
145impl ModelColumn {
146    /// Describes one column.
147    pub const fn new(
148        name: &'static str,
149        rust_type: &'static str,
150        kind: ColumnKind,
151        nullable: bool,
152    ) -> Self {
153        Self {
154            name,
155            rust_type,
156            kind,
157            nullable,
158            default: None,
159            references: None,
160        }
161    }
162
163    /// Sets the column's SQL default (`#[model(default = "0")]`).
164    pub const fn default_sql(mut self, sql: &'static str) -> Self {
165        self.default = Some(sql);
166        self
167    }
168
169    /// Sets the table the column points at (`#[model(references = "users")]`).
170    pub const fn references(mut self, table: &'static str) -> Self {
171        self.references = Some(table);
172        self
173    }
174}
175
176/// An index a model declares with `#[model(index(a, b))]` or
177/// `#[model(unique(a))]`.
178#[derive(Debug, Clone)]
179#[non_exhaustive]
180pub struct ModelIndex {
181    /// The indexed columns, in order.
182    pub columns: &'static [&'static str],
183    /// Whether the index is unique.
184    pub unique: bool,
185}
186
187impl ModelIndex {
188    /// Describes one index.
189    pub const fn new(columns: &'static [&'static str], unique: bool) -> Self {
190        Self { columns, unique }
191    }
192}
193
194#[doc(hidden)]
195pub struct ColumnProbe<T>(std::marker::PhantomData<fn() -> T>);
196impl<T> ColumnProbe<T> {
197    pub const fn new() -> Self {
198        Self(std::marker::PhantomData)
199    }
200}
201impl<T> Default for ColumnProbe<T> {
202    fn default() -> Self {
203        Self::new()
204    }
205}
206#[doc(hidden)]
207pub trait KnownColumn {
208    fn kind(&self) -> ColumnKind;
209}
210impl<T: ColumnType> KnownColumn for ColumnProbe<T> {
211    fn kind(&self) -> ColumnKind {
212        T::KIND
213    }
214}
215#[doc(hidden)]
216pub trait UnknownColumn {
217    fn kind(&self) -> ColumnKind;
218}
219impl<T> UnknownColumn for &ColumnProbe<T> {
220    fn kind(&self) -> ColumnKind {
221        ColumnKind::Unknown
222    }
223}
224
225/// A model registered with `App::model`, for `db:check`.
226#[derive(Clone)]
227#[allow(dead_code)] // read by the schema comparison (370.4)
228pub(crate) struct ModelInfo {
229    pub(crate) type_id: std::any::TypeId,
230    pub(crate) name: &'static str,
231    pub(crate) table: &'static str,
232    pub(crate) columns: fn() -> Vec<ModelColumn>,
233    pub(crate) indexes: fn() -> Vec<super::ModelIndex>,
234}
235
236/// Describes `M` for the registry.
237pub(crate) fn model_info<M: super::Model>() -> ModelInfo {
238    ModelInfo {
239        type_id: std::any::TypeId::of::<M>(),
240        name: std::any::type_name::<M>(),
241        table: M::TABLE,
242        columns: M::column_info,
243        indexes: M::indexes,
244    }
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250
251    struct Custom;
252
253    #[test]
254    fn kinds_of_known_types() {
255        assert_eq!(<i64 as ColumnType>::KIND, ColumnKind::BigInt);
256        assert_eq!(<Option<String> as ColumnType>::KIND, ColumnKind::Text);
257        assert_eq!(<Json<Vec<i64>> as ColumnType>::KIND, ColumnKind::Json);
258        assert_eq!(ColumnKind::BigInt.as_str(), "bigint");
259    }
260
261    #[test]
262    #[allow(clippy::needless_borrow)]
263    fn probe_tells_known_from_unknown() {
264        #[allow(unused_imports)]
265        use super::{KnownColumn as _, UnknownColumn as _};
266        assert_eq!((&ColumnProbe::<i64>::new()).kind(), ColumnKind::BigInt);
267        assert_eq!((&ColumnProbe::<Custom>::new()).kind(), ColumnKind::Unknown);
268        assert_eq!(
269            (&ColumnProbe::<Option<Custom>>::new()).kind(),
270            ColumnKind::Unknown
271        );
272    }
273}