Skip to main content

pgrx_sql_entity_graph/postgres_enum/
entity.rs

1//LICENSE Portions Copyright 2019-2021 ZomboDB, LLC.
2//LICENSE
3//LICENSE Portions Copyright 2021-2023 Technology Concepts & Design, Inc.
4//LICENSE
5//LICENSE Portions Copyright 2023-2023 PgCentral Foundation, Inc. <contact@pgcentral.org>
6//LICENSE
7//LICENSE All rights reserved.
8//LICENSE
9//LICENSE Use of this source code is governed by the MIT license that can be found in the LICENSE file.
10/*!
11
12`#[derive(PostgresEnum)]` related entities for Rust to SQL translation
13
14> Like all of the [`sql_entity_graph`][crate] APIs, this is considered **internal**
15> to the `pgrx` framework and very subject to change between versions. While you may use this, please do it with caution.
16
17*/
18use crate::pgrx_sql::PgrxSql;
19use crate::to_sql::ToSql;
20use crate::to_sql::entity::ToSqlConfigEntity;
21use crate::{SqlGraphEntity, SqlGraphIdentifier, TypeMatch};
22
23/// The output of a [`PostgresEnum`](crate::postgres_enum::PostgresEnum) from `quote::ToTokens::to_tokens`.
24#[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
25pub struct PostgresEnumEntity<'a> {
26    pub name: &'a str,
27    pub file: &'a str,
28    pub line: u32,
29    pub full_path: &'a str,
30    pub module_path: &'a str,
31    pub type_ident: &'a str,
32    pub variants: Vec<&'a str>,
33    pub to_sql_config: ToSqlConfigEntity<'a>,
34}
35
36impl TypeMatch for PostgresEnumEntity<'_> {
37    fn type_ident(&self) -> &str {
38        self.type_ident
39    }
40}
41
42impl<'a> From<PostgresEnumEntity<'a>> for SqlGraphEntity<'a> {
43    fn from(val: PostgresEnumEntity<'a>) -> Self {
44        SqlGraphEntity::Enum(val)
45    }
46}
47
48impl SqlGraphIdentifier for PostgresEnumEntity<'_> {
49    fn dot_identifier(&self) -> String {
50        format!("enum {}", self.full_path)
51    }
52    fn rust_identifier(&self) -> String {
53        self.full_path.to_string()
54    }
55
56    fn file(&self) -> Option<&str> {
57        Some(self.file)
58    }
59
60    fn line(&self) -> Option<u32> {
61        Some(self.line)
62    }
63}
64
65impl ToSql for PostgresEnumEntity<'_> {
66    fn to_sql(&self, context: &PgrxSql) -> eyre::Result<String> {
67        let self_index = context.enums[self];
68        let sql = format!(
69            "\n\
70                -- {file}:{line}\n\
71                -- {full_path}\n\
72                CREATE TYPE {schema}{name} AS ENUM (\n\
73                    {variants}\
74                );\
75            ",
76            schema = context.schema_prefix_for(&self_index),
77            full_path = self.full_path,
78            file = self.file,
79            line = self.line,
80            name = self.name,
81            variants = self
82                .variants
83                .iter()
84                .map(|variant| format!("\t'{variant}'"))
85                .collect::<Vec<_>>()
86                .join(",\n")
87                + "\n",
88        );
89        Ok(sql)
90    }
91}