pgx_utils/sql_entity_graph/postgres_enum/
entity.rs1use 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#[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}