pgx_sql_entity_graph/schema/
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`#[pg_schema]` related entities for Rust to SQL translation
12
13> Like all of the [`sql_entity_graph`][crate::pgx_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::pgx_sql::PgxSql;
18use crate::to_sql::ToSql;
19use crate::{SqlGraphEntity, SqlGraphIdentifier};
20
21/// The output of a [`Schema`](crate::schema::Schema) from `quote::ToTokens::to_tokens`.
22#[derive(Debug, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
23pub struct SchemaEntity {
24    pub module_path: &'static str,
25    pub name: &'static str,
26    pub file: &'static str,
27    pub line: u32,
28}
29
30impl From<SchemaEntity> for SqlGraphEntity {
31    fn from(val: SchemaEntity) -> Self {
32        SqlGraphEntity::Schema(val)
33    }
34}
35
36impl SqlGraphIdentifier for SchemaEntity {
37    fn dot_identifier(&self) -> String {
38        format!("schema {}", self.module_path)
39    }
40    fn rust_identifier(&self) -> String {
41        self.module_path.to_string()
42    }
43
44    fn file(&self) -> Option<&'static str> {
45        Some(self.file)
46    }
47
48    fn line(&self) -> Option<u32> {
49        Some(self.line)
50    }
51}
52
53impl ToSql for SchemaEntity {
54    fn to_sql(&self, _context: &PgxSql) -> eyre::Result<String> {
55        let sql = format!(
56            "\n\
57                -- {file}:{line}\n\
58                CREATE SCHEMA IF NOT EXISTS {name}; /* {module_path} */\
59            ",
60            name = self.name,
61            file = self.file,
62            line = self.line,
63            module_path = self.module_path,
64        );
65        Ok(sql)
66    }
67}