Skip to main content

drizzle_types/postgres/ddl/
schema.rs

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