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