Skip to main content

drizzle_types/postgres/ddl/
schema.rs

1//! `PostgreSQL` Schema DDL types
2//!
3//! This module provides two complementary types:
4//! - [`SchemaDef`] - A const-friendly definition type for compile-time schema definitions
5//! - [`Schema`] - A runtime type for serde serialization/deserialization
6
7use crate::alloc_prelude::*;
8
9#[cfg(feature = "serde")]
10use crate::serde_helpers::cow_from_string;
11
12// =============================================================================
13// Const-friendly Definition Type
14// =============================================================================
15
16/// Const-friendly schema definition for compile-time schema definitions.
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18pub struct SchemaDef {
19    /// Schema name
20    pub name: &'static str,
21}
22
23impl SchemaDef {
24    /// Create a new schema definition
25    #[must_use]
26    pub const fn new(name: &'static str) -> Self {
27        Self { name }
28    }
29
30    /// Convert to runtime [`Schema`] type
31    #[must_use]
32    pub const fn into_schema(self) -> Schema {
33        Schema {
34            name: Cow::Borrowed(self.name),
35        }
36    }
37}
38
39impl Default for SchemaDef {
40    fn default() -> Self {
41        Self::new("public")
42    }
43}
44
45// =============================================================================
46// Runtime Type for Serde
47// =============================================================================
48
49/// Runtime schema entity for serde serialization.
50#[derive(Clone, Debug, PartialEq, Eq)]
51#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
52#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
53pub struct Schema {
54    /// Schema name
55    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_from_string"))]
56    pub name: Cow<'static, str>,
57}
58
59impl Schema {
60    /// Create a new schema (runtime)
61    #[must_use]
62    pub fn new(name: impl Into<Cow<'static, str>>) -> Self {
63        Self { name: name.into() }
64    }
65
66    /// Get the schema name
67    #[inline]
68    #[must_use]
69    pub fn name(&self) -> &str {
70        &self.name
71    }
72}
73
74impl Default for Schema {
75    fn default() -> Self {
76        Self::new("public")
77    }
78}
79
80impl From<SchemaDef> for Schema {
81    fn from(def: SchemaDef) -> Self {
82        def.into_schema()
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89
90    #[test]
91    fn test_const_schema_def() {
92        const SCHEMA: SchemaDef = SchemaDef::new("custom_schema");
93
94        assert_eq!(SCHEMA.name, "custom_schema");
95    }
96
97    #[test]
98    fn test_schema_def_to_schema() {
99        const DEF: SchemaDef = SchemaDef::new("public");
100        let schema = DEF.into_schema();
101        assert_eq!(schema.name(), "public");
102    }
103}