Skip to main content

utopia_query/schema/
postgresql.rs

1//! [`PostgreSql`]: the PostgreSQL schema.
2
3use super::column::{self, Column};
4use super::enums::{ColumnType, IndexType, ParameterDirection, TriggerEvent, TriggerTiming};
5use super::feature;
6use super::index::IndexOptions;
7use super::table::{self, ForeignKey, Table};
8use super::{Schema, base, names};
9use crate::builder::{AnyBuilder, Executor, Statement};
10use crate::error::{Error, Result};
11
12/// The PostgreSQL schema: double-quote quoting, identity columns, `SERIAL`
13/// types, `CHECK`-emulated enums, standalone index statements, PL/pgSQL
14/// procedures and triggers, types, sequences, extensions and collations.
15///
16/// ```
17/// use utopia_query::schema::{PostgreSql, Schema};
18///
19/// let mut table = PostgreSql::new().table("users");
20/// table.add_column("bio", utopia_query::schema::ColumnType::Text, None).nullable();
21/// table.drop_column("legacy");
22/// table.index(["email"])?;
23/// assert_eq!(
24///     table.alter()?.query,
25///     "ALTER TABLE \"users\" ADD COLUMN \"bio\" TEXT NULL, DROP COLUMN \"legacy\"; \
26///      CREATE INDEX \"idx_email\" ON \"users\" (\"email\")"
27/// );
28/// # Ok::<(), utopia_query::Error>(())
29/// ```
30///
31/// ```php
32/// use Utopia\Query\Schema\ColumnType;
33/// use Utopia\Query\Schema\PostgreSQL;
34///
35/// $table = (new PostgreSQL())->table('users');
36/// $table->addColumn('bio', ColumnType::Text)->nullable();
37/// $table->dropColumn('legacy');
38/// $table->index(['email']);
39/// echo $table->alter()->query, "\n";
40/// ```
41///
42/// PHP: `Utopia\Query\Schema\PostgreSQL`.
43#[derive(Clone, Default)]
44pub struct PostgreSql {
45    executor: Option<Executor>,
46}
47
48impl std::fmt::Debug for PostgreSql {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        f.debug_struct("PostgreSql").field("executor", &self.executor.is_some()).finish()
51    }
52}
53
54/// Refuses bodies containing the `$$` that would end the dollar-quoted block.
55fn dollar_quoted(body: &str) -> Result<()> {
56    if body.contains("$$") {
57        return Err(Error::Validation(
58            "Procedure/trigger body must not contain the dollar-quote terminator \"$$\"".into(),
59        ));
60    }
61    Ok(())
62}
63
64/// Refuses expressions over 1024 bytes or containing `;`, `--` or `/*`.
65fn safe_expression(expression: &str, label: &str) -> Result<()> {
66    if expression.len() > 1024 {
67        return Err(Error::Validation(format!("{label} exceeds 1024 character limit")));
68    }
69    if expression.contains(';') || expression.contains("--") || expression.contains("/*") {
70        return Err(Error::Validation(format!("Invalid {label}: {expression}")));
71    }
72    Ok(())
73}
74
75impl PostgreSql {
76    /// A PostgreSQL schema without an executor.
77    ///
78    /// PHP: `new PostgreSQL()`.
79    pub fn new() -> Self {
80        PostgreSql::default()
81    }
82
83    /// `CREATE EXTENSION IF NOT EXISTS name`.
84    ///
85    /// PHP: `createExtension()`.
86    pub fn create_extension(&self, name: &str) -> Result<Statement> {
87        base::plain(self, format!("CREATE EXTENSION IF NOT EXISTS {}", self.quote(name)?))
88    }
89
90    /// `DROP EXTENSION IF EXISTS name`.
91    ///
92    /// PHP: `dropExtension()`.
93    pub fn drop_extension(&self, name: &str) -> Result<Statement> {
94        base::plain(self, format!("DROP EXTENSION IF EXISTS {}", self.quote(name)?))
95    }
96
97    /// `CREATE COLLATION IF NOT EXISTS name (key = 'value', ..., deterministic = ...)`;
98    /// option keys are identifiers (PHP's default for `deterministic` is `true`).
99    ///
100    /// PHP: `createCollation()`.
101    pub fn create_collation(&self, name: &str, options: &[(&str, &str)], deterministic: bool) -> Result<Statement> {
102        let mut parts = Vec::with_capacity(options.len() + 1);
103        for (key, value) in options {
104            if !names::is_identifier(key) {
105                return Err(Error::Validation(format!("Invalid collation option key: {key}")));
106            }
107            parts.push(format!("{key} = {}", self.literal().quote(value)?));
108        }
109        parts.push(format!("deterministic = {deterministic}"));
110        base::plain(self, format!("CREATE COLLATION IF NOT EXISTS {} ({})", self.quote(name)?, parts.join(", ")))
111    }
112
113    /// `ALTER TABLE table ALTER COLUMN column TYPE type [USING expr]`: the
114    /// type is a type declaration, the cast expression has no `;`, `--` or
115    /// `/*` (PHP's default for `using` is empty).
116    ///
117    /// PHP: `alterColumnType()`.
118    pub fn alter_column_type(&self, table: &str, column: &str, kind: &str, using: &str) -> Result<Statement> {
119        if !names::is_type_declaration(kind) {
120            return Err(Error::Validation(format!("Invalid column type: {kind}")));
121        }
122        if !using.is_empty() {
123            safe_expression(using, "USING expression")?;
124        }
125        let mut sql =
126            format!("ALTER TABLE {} ALTER COLUMN {} TYPE {kind}", self.quote(table)?, self.quote_literal(column)?);
127        if !using.is_empty() {
128            sql.push_str(" USING ");
129            sql.push_str(using);
130        }
131        base::plain(self, sql)
132    }
133
134    /// `ALTER TABLE table ALTER COLUMN column DROP NOT NULL` / `SET NOT NULL`.
135    ///
136    /// PHP: `alterColumnNullable()`.
137    pub fn alter_column_nullable(&self, table: &str, column: &str, nullable: bool) -> Result<Statement> {
138        base::plain(
139            self,
140            format!(
141                "ALTER TABLE {} ALTER COLUMN {}{}",
142                self.quote(table)?,
143                self.quote_literal(column)?,
144                if nullable { " DROP NOT NULL" } else { " SET NOT NULL" }
145            ),
146        )
147    }
148
149    /// `DROP INDEX CONCURRENTLY name`.
150    ///
151    /// PHP: `dropIndexConcurrently()`.
152    pub fn drop_index_concurrently(&self, name: &str) -> Result<Statement> {
153        base::plain(self, format!("DROP INDEX CONCURRENTLY {}", self.quote(name)?))
154    }
155}
156
157impl Schema for PostgreSql {
158    fn executor(&self) -> Option<&Executor> {
159        self.executor.as_ref()
160    }
161
162    fn set_executor(&mut self, executor: Executor) -> &mut Self {
163        self.executor = Some(executor);
164        self
165    }
166
167    fn literal(&self) -> crate::StringLiteral {
168        crate::StringLiteral::Extended
169    }
170
171    fn quote(&self, identifier: &str) -> Result<String> {
172        crate::quote(identifier, '"')
173    }
174
175    fn quote_literal(&self, identifier: &str) -> Result<String> {
176        crate::quote_literal(identifier, '"')
177    }
178
179    fn compile_column_type(&self, column: &Column<Self>) -> Result<String> {
180        let c = &column.def;
181        if let Some(user_type) = &c.user_type {
182            return self.quote(user_type);
183        }
184        let geometry = |kind: &str| match c.srid {
185            Some(srid) => format!("GEOMETRY({kind}, {srid})"),
186            None => format!("GEOMETRY({kind})"),
187        };
188        let precision = c.precision.filter(|p| *p != 0);
189        Ok(match c.kind {
190            ColumnType::String | ColumnType::Varchar | ColumnType::Relationship => {
191                format!("VARCHAR({})", c.length.unwrap_or(255))
192            }
193            ColumnType::Text | ColumnType::MediumText | ColumnType::LongText => "TEXT".into(),
194            ColumnType::TinyInteger | ColumnType::SmallInteger => "SMALLINT".into(),
195            ColumnType::Integer => "INTEGER".into(),
196            ColumnType::BigInteger | ColumnType::Id => "BIGINT".into(),
197            ColumnType::Float | ColumnType::Double => "DOUBLE PRECISION".into(),
198            ColumnType::Decimal => format!("DECIMAL({}, {})", c.precision.unwrap_or(10), c.scale.unwrap_or(0)),
199            ColumnType::Boolean => "BOOLEAN".into(),
200            ColumnType::Datetime => match precision {
201                Some(p) => format!("TIMESTAMP({p})"),
202                None => "TIMESTAMP".into(),
203            },
204            ColumnType::Timestamp => match precision {
205                Some(p) => format!("TIMESTAMP({p}) WITHOUT TIME ZONE"),
206                None => "TIMESTAMP WITHOUT TIME ZONE".into(),
207            },
208            ColumnType::Json | ColumnType::Object => "JSONB".into(),
209            ColumnType::Binary => "BYTEA".into(),
210            ColumnType::Enum => "TEXT".into(),
211            ColumnType::Point => geometry("POINT"),
212            ColumnType::Linestring => geometry("LINESTRING"),
213            ColumnType::Polygon => geometry("POLYGON"),
214            ColumnType::Uuid => "UUID".into(),
215            ColumnType::Uuid7 => "VARCHAR(36)".into(),
216            ColumnType::Vector => format!("VECTOR({})", c.dimensions.unwrap_or(0)),
217            ColumnType::Serial => "SERIAL".into(),
218            ColumnType::BigSerial => "BIGSERIAL".into(),
219            ColumnType::SmallSerial => "SMALLSERIAL".into(),
220            ColumnType::Array | ColumnType::Tuple => {
221                return Err(Error::Unsupported("Array/Tuple column types are not supported in PostgreSQL.".into()));
222            }
223        })
224    }
225
226    fn compile_auto_increment(&self) -> &'static str {
227        "GENERATED BY DEFAULT AS IDENTITY"
228    }
229
230    fn quote_collation(&self, collation: &str) -> Result<String> {
231        self.quote(collation)
232    }
233
234    fn compile_unsigned(&self) -> &'static str {
235        ""
236    }
237
238    /// Identity instead of `AUTO_INCREMENT` (none for `SERIAL` types), enums
239    /// as a `CHECK (... IN (...))`, no inline comment.
240    fn compile_column_definition(&self, column: &Column<Self>) -> Result<String> {
241        let c = &column.def;
242        let mut out = base::column_start(self, column)?;
243        if let Some(collation) = &c.collation {
244            base::add(&mut out, &["COLLATE ", &self.quote_collation(collation)?]);
245        }
246        let generated = c.generated_expression.is_some();
247        let serial = matches!(c.kind, ColumnType::Serial | ColumnType::BigSerial | ColumnType::SmallSerial);
248        if generated {
249            base::add(&mut out, &[&self.compile_generated_clause(column)]);
250        } else if c.auto_increment && !serial {
251            base::add(&mut out, &[self.compile_auto_increment()]);
252        }
253        base::add(&mut out, &[if c.nullable { "NULL" } else { "NOT NULL" }]);
254        if !generated {
255            base::add_default(self, &mut out, column)?;
256            if c.kind == ColumnType::Enum && !c.enum_values.is_empty() {
257                let values = c.enum_values.iter().map(|v| self.literal().quote(v)).collect::<Result<Vec<_>>>()?;
258                base::add(&mut out, &["CHECK (", &self.quote_literal(&c.name)?, " IN (", &values.join(", "), "))"]);
259            }
260        }
261        if let Some(check) = &c.check {
262            base::add(&mut out, &["CHECK (", check, ")"]);
263        }
264        Ok(out)
265    }
266
267    /// Always `STORED`: PostgreSQL has no virtual generated columns.
268    fn compile_generated_clause(&self, column: &Column<Self>) -> String {
269        format!("GENERATED ALWAYS AS ({}) STORED", column.def.generated_expression.as_deref().unwrap_or_default())
270    }
271
272    fn compile_create_suffix(&self, table: &Table<Self>) -> String {
273        feature::Partitioning::compile_create_partitioning(self, table)
274    }
275
276    /// Column changes in one `ALTER TABLE`, indexes as separate `CREATE` /
277    /// `DROP INDEX` statements, joined by `; `.
278    fn compile_alter(&self, table: &Table<Self>) -> Result<Statement> {
279        let t = table.definition();
280        let mut alterations = Vec::new();
281        for column in &t.columns {
282            if column.def.modify {
283                alterations.push(format!(
284                    "ALTER COLUMN {} TYPE {}",
285                    self.quote_literal(&column.def.name)?,
286                    self.compile_column_type(column)?
287                ));
288            } else {
289                alterations.push(format!("ADD COLUMN {}", self.compile_column_definition(column)?));
290            }
291        }
292        for rename in &t.rename_columns {
293            alterations.push(format!(
294                "RENAME COLUMN {} TO {}",
295                self.quote_literal(&rename.from)?,
296                self.quote_literal(&rename.to)?
297            ));
298        }
299        for column in &t.drop_columns {
300            alterations.push(format!("DROP COLUMN {}", self.quote_literal(column)?));
301        }
302        for key in &t.foreign_keys {
303            alterations.push(format!("ADD {}", base::foreign_key_clause(self, key)?));
304        }
305        for name in &t.drop_foreign_keys {
306            alterations.push(format!("DROP CONSTRAINT {}", self.quote(name)?));
307        }
308        let mut statements = Vec::new();
309        if !alterations.is_empty() {
310            statements.push(format!("ALTER TABLE {} {}", self.quote(&t.name)?, alterations.join(", ")));
311        }
312        for index in &t.indexes {
313            let keyword = if index.kind == IndexType::Unique { "CREATE UNIQUE INDEX" } else { "CREATE INDEX" };
314            let mut sql = format!("{keyword} {} ON {}", self.quote(&index.name)?, self.quote(&t.name)?);
315            if !index.method.is_empty() {
316                sql.push_str(" USING ");
317                sql.push_str(&index.method.to_ascii_uppercase());
318            }
319            sql.push_str(&format!(" ({})", self.compile_index_columns(index)?));
320            statements.push(sql);
321        }
322        for name in &t.drop_indexes {
323            statements.push(format!("DROP INDEX {}", self.quote(name)?));
324        }
325        base::plain(self, statements.join("; "))
326    }
327
328    fn compile_rename(&self, from: &str, to: &str) -> Result<Statement> {
329        base::plain(self, format!("ALTER TABLE {} RENAME TO {}", self.quote(from)?, self.quote(to)?))
330    }
331
332    /// `CREATE [UNIQUE] INDEX [CONCURRENTLY] name ON table [USING method] (...)`.
333    fn create_index(&self, table: &str, name: &str, columns: &[&str], options: &IndexOptions) -> Result<Statement> {
334        if !options.method.is_empty() && !names::is_word(&options.method) {
335            return Err(Error::Validation(format!("Invalid index method: {}", options.method)));
336        }
337        if !options.operator_class.is_empty() && !names::is_dotted_word(&options.operator_class) {
338            return Err(Error::Validation(format!("Invalid operator class: {}", options.operator_class)));
339        }
340        let mut sql = String::from(if options.unique { "CREATE UNIQUE INDEX" } else { "CREATE INDEX" });
341        if options.concurrently {
342            sql.push_str(" CONCURRENTLY");
343        }
344        sql.push_str(&format!(" {} ON {}", self.quote(name)?, self.quote(table)?));
345        if !options.method.is_empty() {
346            sql.push_str(" USING ");
347            sql.push_str(&options.method.to_ascii_uppercase());
348        }
349        let index = options.index(name, columns)?;
350        sql.push_str(&format!(" ({})", self.compile_index_columns(&index)?));
351        base::plain(self, sql)
352    }
353
354    fn drop_index(&self, _table: &str, name: &str) -> Result<Statement> {
355        base::plain(self, format!("DROP INDEX {}", self.quote(name)?))
356    }
357}
358
359impl column::AutoIncrement for PostgreSql {}
360impl column::Collation for PostgreSql {}
361impl column::Dimensions for PostgreSql {}
362impl column::Generated for PostgreSql {}
363impl column::Srid for PostgreSql {}
364impl column::Unique for PostgreSql {}
365impl table::Serial for PostgreSql {}
366impl table::Checks for PostgreSql {}
367impl table::ColumnAlterations for PostgreSql {}
368impl table::CompositePrimary for PostgreSql {}
369impl table::InlineForeignKey for PostgreSql {}
370impl table::ForeignKeys for PostgreSql {}
371impl table::FulltextSpatialIndex for PostgreSql {}
372impl table::StandardPartitioning for PostgreSql {}
373
374impl feature::ForeignKeys for PostgreSql {
375    fn add_foreign_key(&self, table: &str, name: &str, key: &ForeignKey) -> Result<Statement> {
376        base::add_foreign_key(self, table, name, key)
377    }
378
379    fn drop_foreign_key(&self, table: &str, name: &str) -> Result<Statement> {
380        base::plain(self, format!("ALTER TABLE {} DROP CONSTRAINT {}", self.quote(table)?, self.quote(name)?))
381    }
382}
383
384impl feature::Procedures for PostgreSql {
385    /// A PL/pgSQL function returning `VOID`; the body must not contain `$$`.
386    fn create_procedure(
387        &self,
388        name: &str,
389        params: &[(ParameterDirection, &str, &str)],
390        body: &str,
391    ) -> Result<Statement> {
392        dollar_quoted(body)?;
393        let params = base::procedure_params(self, params)?;
394        base::plain(
395            self,
396            format!(
397                "CREATE FUNCTION {}({}) RETURNS VOID LANGUAGE plpgsql AS $$ BEGIN {body} END; $$",
398                self.quote(name)?,
399                params.join(", ")
400            ),
401        )
402    }
403
404    fn drop_procedure(&self, name: &str) -> Result<Statement> {
405        base::plain(self, format!("DROP FUNCTION {}()", self.quote(name)?))
406    }
407}
408
409impl feature::Triggers for PostgreSql {
410    /// A trigger function `<name>_func` and the trigger executing it; the
411    /// body must not contain `$$`.
412    fn create_trigger(
413        &self,
414        name: &str,
415        table: &str,
416        timing: TriggerTiming,
417        event: TriggerEvent,
418        body: &str,
419    ) -> Result<Statement> {
420        dollar_quoted(body)?;
421        let function = self.quote(&format!("{name}_func"))?;
422        base::plain(
423            self,
424            format!(
425                "CREATE FUNCTION {function}() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN {body} RETURN NEW; END; $$; \
426                 CREATE TRIGGER {} {} {} ON {} FOR EACH ROW EXECUTE FUNCTION {function}()",
427                self.quote(name)?,
428                timing.as_str(),
429                event.as_str(),
430                self.quote(table)?
431            ),
432        )
433    }
434
435    /// Drops the trigger and its function; the table is required.
436    fn drop_trigger(&self, name: &str, table: Option<&str>) -> Result<Statement> {
437        let Some(table) = table else {
438            return Err(Error::Validation("PostgreSQL dropTrigger() requires the table name.".into()));
439        };
440        base::plain(
441            self,
442            format!(
443                "DROP TRIGGER {} ON {}; DROP FUNCTION {}()",
444                self.quote(name)?,
445                self.quote(table)?,
446                self.quote(&format!("{name}_func"))?
447            ),
448        )
449    }
450}
451
452impl feature::Types for PostgreSql {
453    fn create_type(&self, name: &str, values: &[&str]) -> Result<Statement> {
454        let values = values.iter().map(|v| self.literal().quote(v)).collect::<Result<Vec<_>>>()?;
455        base::plain(self, format!("CREATE TYPE {} AS ENUM ({})", self.quote(name)?, values.join(", ")))
456    }
457
458    fn drop_type(&self, name: &str) -> Result<Statement> {
459        base::plain(self, format!("DROP TYPE {}", self.quote(name)?))
460    }
461}
462
463impl feature::Sequences for PostgreSql {
464    fn create_sequence(&self, name: &str, start: i64, increment_by: i64) -> Result<Statement> {
465        base::plain(self, format!("CREATE SEQUENCE {} START {start} INCREMENT BY {increment_by}", self.quote(name)?))
466    }
467
468    fn drop_sequence(&self, name: &str) -> Result<Statement> {
469        base::plain(self, format!("DROP SEQUENCE {}", self.quote(name)?))
470    }
471
472    fn next_val(&self, name: &str) -> Result<Statement> {
473        base::plain(self, format!("SELECT nextval({})", self.literal().quote(name)?))
474    }
475}
476
477impl feature::TableComments for PostgreSql {
478    fn comment_on_table(&self, table: &str, comment: &str) -> Result<Statement> {
479        base::plain(self, format!("COMMENT ON TABLE {} IS {}", self.quote(table)?, self.literal().quote(comment)?))
480    }
481}
482
483impl feature::ColumnComments for PostgreSql {
484    fn comment_on_column(&self, table: &str, column: &str, comment: &str) -> Result<Statement> {
485        base::plain(
486            self,
487            format!(
488                "COMMENT ON COLUMN {}.{} IS {}",
489                self.quote(table)?,
490                self.quote_literal(column)?,
491                self.literal().quote(comment)?
492            ),
493        )
494    }
495}
496
497impl feature::CreatePartition for PostgreSql {
498    /// `CREATE TABLE name PARTITION OF parent FOR VALUES expression`; the
499    /// expression has no `;`, `--` or `/*`.
500    fn create_partition(&self, parent: &str, name: &str, expression: &str) -> Result<Statement> {
501        safe_expression(expression, "partition expression")?;
502        base::plain(
503            self,
504            format!("CREATE TABLE {} PARTITION OF {} FOR VALUES {expression}", self.quote(name)?, self.quote(parent)?),
505        )
506    }
507}
508
509impl feature::DropPartition for PostgreSql {
510    fn drop_partition(&self, _table: &str, name: &str) -> Result<Statement> {
511        base::plain(self, format!("DROP TABLE {}", self.quote(name)?))
512    }
513}
514
515impl feature::Views for PostgreSql {
516    fn create_view(&self, name: &str, query: &mut dyn AnyBuilder) -> Result<Statement> {
517        base::create_view(self, "CREATE VIEW", name, query)
518    }
519
520    fn drop_view(&self, name: &str) -> Result<Statement> {
521        base::plain(self, format!("DROP VIEW {}", self.quote(name)?))
522    }
523}
524
525impl feature::ReplaceView for PostgreSql {
526    fn create_or_replace_view(&self, name: &str, query: &mut dyn AnyBuilder) -> Result<Statement> {
527        base::create_view(self, "CREATE OR REPLACE VIEW", name, query)
528    }
529}
530
531impl feature::Databases for PostgreSql {
532    /// `CREATE SCHEMA name`: PostgreSQL namespaces with schemas.
533    fn create_database(&self, name: &str) -> Result<Statement> {
534        base::plain(self, format!("CREATE SCHEMA {}", self.quote(name)?))
535    }
536
537    fn drop_database(&self, name: &str) -> Result<Statement> {
538        base::plain(self, format!("DROP SCHEMA IF EXISTS {} CASCADE", self.quote(name)?))
539    }
540}
541
542impl feature::RenameIndex for PostgreSql {
543    fn rename_index(&self, _table: &str, from: &str, to: &str) -> Result<Statement> {
544        base::plain(self, format!("ALTER INDEX {} RENAME TO {}", self.quote(from)?, self.quote(to)?))
545    }
546}
547
548impl feature::AnalyzeTable for PostgreSql {
549    fn analyze_table(&self, table: &str) -> Result<Statement> {
550        base::plain(self, format!("ANALYZE {}", self.quote(table)?))
551    }
552}
553
554impl feature::Partitioning for PostgreSql {
555    /// `PARTITION BY kind(expression)`, without a partition count.
556    fn compile_create_partitioning(&self, table: &Table<Self>) -> String {
557        base::partitioning(table, false)
558    }
559}