pgx_utils/sql_entity_graph/postgres_enum/
entity.rs

1/*
2Portions Copyright 2019-2021 ZomboDB, LLC.
3Portions Copyright 2021-2022 Technology Concepts & Design, Inc. <support@tcdi.com>
4
5All rights reserved.
6
7Use of this source code is governed by the MIT license that can be found in the LICENSE file.
8*/
9/*!
10
11`#[derive(PostgresEnum)]` related entities for Rust to SQL translation
12
13> Like all of the [`sql_entity_graph`][crate::sql_entity_graph] APIs, this is considered **internal**
14to the `pgx` framework and very subject to change between versions. While you may use this, please do it with caution.
15
16*/
17use crate::sql_entity_graph::mapping::RustSqlMapping;
18use crate::sql_entity_graph::pgx_sql::PgxSql;
19use crate::sql_entity_graph::to_sql::entity::ToSqlConfigEntity;
20use crate::sql_entity_graph::to_sql::ToSql;
21use crate::sql_entity_graph::{SqlGraphEntity, SqlGraphIdentifier};
22
23use std::cmp::Ordering;
24use std::hash::{Hash, Hasher};
25
26/// The output of a [`PostgresEnum`](crate::sql_entity_graph::postgres_enum::PostgresEnum) from `quote::ToTokens::to_tokens`.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct PostgresEnumEntity {
29    pub name: &'static str,
30    pub file: &'static str,
31    pub line: u32,
32    pub full_path: &'static str,
33    pub module_path: &'static str,
34    pub mappings: std::collections::HashSet<RustSqlMapping>,
35    pub variants: Vec<&'static str>,
36    pub to_sql_config: ToSqlConfigEntity,
37}
38
39impl Hash for PostgresEnumEntity {
40    fn hash<H: Hasher>(&self, state: &mut H) {
41        self.full_path.hash(state);
42    }
43}
44
45impl Ord for PostgresEnumEntity {
46    fn cmp(&self, other: &Self) -> Ordering {
47        self.file.cmp(other.file).then_with(|| self.file.cmp(other.file))
48    }
49}
50
51impl PartialOrd for PostgresEnumEntity {
52    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
53        Some(self.cmp(other))
54    }
55}
56
57impl PostgresEnumEntity {
58    pub fn id_matches(&self, candidate: &core::any::TypeId) -> bool {
59        self.mappings.iter().any(|tester| *candidate == tester.id)
60    }
61}
62
63impl From<PostgresEnumEntity> for SqlGraphEntity {
64    fn from(val: PostgresEnumEntity) -> Self {
65        SqlGraphEntity::Enum(val)
66    }
67}
68
69impl SqlGraphIdentifier for PostgresEnumEntity {
70    fn dot_identifier(&self) -> String {
71        format!("enum {}", self.full_path)
72    }
73    fn rust_identifier(&self) -> String {
74        self.full_path.to_string()
75    }
76
77    fn file(&self) -> Option<&'static str> {
78        Some(self.file)
79    }
80
81    fn line(&self) -> Option<u32> {
82        Some(self.line)
83    }
84}
85
86impl ToSql for PostgresEnumEntity {
87    #[tracing::instrument(level = "debug", err, skip(self, context), fields(identifier = %self.rust_identifier()))]
88    fn to_sql(&self, context: &PgxSql) -> eyre::Result<String> {
89        let self_index = context.enums[self];
90        let sql = format!(
91            "\n\
92                    -- {file}:{line}\n\
93                    -- {full_path}\n\
94                    CREATE TYPE {schema}{name} AS ENUM (\n\
95                        {variants}\
96                    );\
97                ",
98            schema = context.schema_prefix_for(&self_index),
99            full_path = self.full_path,
100            file = self.file,
101            line = self.line,
102            name = self.name,
103            variants = self
104                .variants
105                .iter()
106                .map(|variant| format!("\t'{}'", variant))
107                .collect::<Vec<_>>()
108                .join(",\n")
109                + "\n",
110        );
111        tracing::trace!(%sql);
112        Ok(sql)
113    }
114}