drizzle_core/
schema.rs

1use crate::prelude::*;
2use crate::{ToSQL, sql::SQL, traits::SQLParam};
3use core::any::Any;
4
5/// Trait for database enum types that can be part of a schema
6pub trait SQLEnumInfo: Any + Send + Sync {
7    /// The name of this enum type
8    fn name(&self) -> &'static str;
9
10    /// The SQL CREATE TYPE statement for this enum
11    fn create_type_sql(&self) -> String;
12
13    /// All possible values of this enum
14    fn variants(&self) -> &'static [&'static str];
15}
16
17/// Helper trait for converting enum info objects to trait objects
18pub trait AsEnumInfo: SQLEnumInfo {
19    fn as_enum(&self) -> &dyn SQLEnumInfo;
20}
21
22impl<T: SQLEnumInfo> AsEnumInfo for T {
23    fn as_enum(&self) -> &dyn SQLEnumInfo {
24        self
25    }
26}
27
28impl core::fmt::Debug for dyn SQLEnumInfo {
29    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
30        f.debug_struct("SQLEnumInfo")
31            .field("name", &self.name())
32            .field("variants", &self.variants())
33            .finish()
34    }
35}
36
37/// Sort direction for ORDER BY clauses
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub enum OrderBy {
40    Asc,
41    Desc,
42}
43
44impl OrderBy {
45    /// Creates an ascending ORDER BY clause: "column ASC"
46    pub fn asc<'a, V, T>(column: T) -> SQL<'a, V>
47    where
48        V: SQLParam + 'a,
49        T: ToSQL<'a, V>,
50    {
51        column.to_sql().append(&Self::Asc)
52    }
53
54    /// Creates a descending ORDER BY clause: "column DESC"
55    pub fn desc<'a, V, T>(column: T) -> SQL<'a, V>
56    where
57        V: SQLParam + 'a,
58        T: ToSQL<'a, V>,
59    {
60        column.to_sql().append(&Self::Desc)
61    }
62}
63
64impl<'a, V: SQLParam + 'a> ToSQL<'a, V> for OrderBy {
65    fn to_sql(&self) -> SQL<'a, V> {
66        let sql_str = match self {
67            OrderBy::Asc => "ASC",
68            OrderBy::Desc => "DESC",
69        };
70        SQL::raw(sql_str)
71    }
72}