Skip to main content

drizzle_core/traits/
mod.rs

1//! Core traits for SQL generation.
2
3use crate::TableRef;
4use crate::prelude::*;
5use core::any::Any;
6
7#[macro_use]
8mod tuple;
9
10mod column;
11mod constraint;
12mod foreign_key;
13mod index;
14mod param;
15mod policy;
16mod primary_key;
17mod table;
18mod to_sql;
19mod type_set;
20mod view;
21
22pub use column::*;
23pub use constraint::*;
24pub use foreign_key::*;
25pub use index::*;
26pub use param::*;
27pub use policy::*;
28pub use primary_key::*;
29pub use table::*;
30pub use to_sql::*;
31pub use type_set::*;
32pub use view::*;
33
34/// Trait for schema elements (tables, columns, etc.).
35///
36/// The `'a` lifetime ties any borrowed parameter values to generated SQL.
37#[diagnostic::on_unimplemented(
38    message = "`{Self}` is not a SQL schema element",
39    label = "this type was not derived with a drizzle schema macro"
40)]
41pub trait SQLSchema<'a, T, V: SQLParam + 'a>: ToSQL<'a, V> {
42    const NAME: &'static str;
43    const TYPE: T;
44    /// Static SQL string for schema creation (e.g., CREATE TABLE ...).
45    const SQL: &'static str;
46}
47
48impl<'a, S, T, V> SQLSchema<'a, T, V> for &S
49where
50    S: SQLSchema<'a, T, V>,
51    V: SQLParam + 'a,
52{
53    const NAME: &'static str = <S as SQLSchema<'a, T, V>>::NAME;
54    const TYPE: T = <S as SQLSchema<'a, T, V>>::TYPE;
55    const SQL: &'static str = <S as SQLSchema<'a, T, V>>::SQL;
56}
57
58/// Maps a schema item type to its table contribution.
59///
60/// - Table items map to `Cons<Table, Nil>`
61/// - Non-table items (indexes/views/enums) map to `Nil`
62#[diagnostic::on_unimplemented(
63    message = "`{Self}` is not a recognized schema item",
64    label = "schema items must be tables, views, indexes, or enums derived with drizzle macros"
65)]
66pub trait SchemaItemTables {
67    type Tables: TypeSet;
68    /// For table items, a reference to the const `TableRef` metadata.
69    /// Non-table items (views, indexes, enums) use the default `None`.
70    const TABLE_REF_CONST: Option<&'static TableRef> = None;
71}
72
73/// Marker trait for schema types (used for type-level discrimination).
74#[diagnostic::on_unimplemented(
75    message = "`{Self}` is not a SQL schema type marker",
76    label = "expected a dialect marker like SQLiteSchemaType or PostgresSchemaType"
77)]
78pub trait SQLSchemaType: core::fmt::Debug + Any + Send + Sync {}
79
80/// Trait for schema implementations that can generate CREATE statements.
81pub trait SQLSchemaImpl: Any + Send + Sync {
82    fn table_refs(&self) -> &'static [&'static TableRef];
83    /// Generate CREATE statements for every table in this schema.
84    ///
85    /// # Errors
86    ///
87    /// Returns an error if SQL generation for any table fails.
88    fn create_statements(&self) -> crate::error::Result<impl Iterator<Item = String>>;
89}