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