1use std::fmt::Write as _;
4
5use ruprizzle_core::ir::{
6 EnumDef, Field, FieldKind, IndexDef, Model, RelationKind, ResolvedRelation, ScalarType, Schema,
7 UniqueDef,
8};
9
10use crate::common::{
11 base_column_type, create_table_body, default_sql, fk_constraint_sql, render_index_targets,
12 rust_type_for,
13};
14use crate::{Capabilities, DbDialect, DialectError, JsonSupport, RustType, Stmt};
15
16#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
18pub struct PostgresDialect;
19
20impl DbDialect for PostgresDialect {
21 fn name(&self) -> &'static str {
22 "postgres"
23 }
24
25 fn quote_ident(&self, s: &str) -> String {
26 format!("\"{}\"", s.replace('"', "\"\""))
27 }
28
29 fn placeholder(&self, index: usize) -> String {
30 format!("${}", index + 1)
31 }
32
33 fn column_type(&self, f: &Field) -> Result<String, DialectError> {
34 base_column_type("postgres", f, |f| pg_kind_type(&f.kind))
35 }
36
37 fn rust_type(&self, f: &Field) -> RustType {
38 rust_type_for(f)
39 }
40
41 fn create_table(&self, schema: &Schema, m: &Model) -> Vec<Stmt> {
42 match create_table_body(self, schema, m) {
43 Ok(stmt) => vec![stmt],
44 Err(e) => vec![Stmt::new(format!("-- error: {e}"))],
45 }
46 }
47
48 fn drop_table(&self, table: &str) -> Vec<Stmt> {
49 vec![Stmt::new(format!("DROP TABLE IF EXISTS {};", self.quote_ident(table))).destructive()]
50 }
51
52 fn add_column(&self, _schema: &Schema, m: &Model, f: &Field) -> Vec<Stmt> {
53 let col = self.column_type(f);
54 let mut out = Vec::new();
55
56 if let Ok(sql_type) = col {
57 let mut parts = vec![self.quote_ident(&f.column), sql_type];
58
59 if f.optional {
60 parts.push("NULL".to_owned());
61 } else {
62 parts.push("NOT NULL".to_owned());
63 }
64
65 let default = default_sql(self, f);
66 if !default.is_empty() {
67 parts.push(format!("DEFAULT {default}"));
68 }
69
70 out.push(Stmt::new(format!(
71 "ALTER TABLE {} ADD COLUMN {};",
72 self.quote_ident(&m.table),
73 parts.join(" ")
74 )));
75 } else {
76 out.push(Stmt::new(format!(
77 "-- error adding column: {}",
78 col.unwrap_err()
79 )));
80 }
81
82 out
86 }
87
88 fn drop_column(&self, table: &str, col: &str) -> Vec<Stmt> {
89 vec![Stmt::new(format!(
90 "ALTER TABLE {} DROP COLUMN {};",
91 self.quote_ident(table),
92 self.quote_ident(col)
93 ))]
94 }
95
96 fn alter_column(&self, _schema: &Schema, m: &Model, from: &Field, to: &Field) -> Vec<Stmt> {
97 let table = self.quote_ident(&m.table);
98 let col = self.quote_ident(&from.column);
99 let mut stmts = Vec::new();
100
101 if from.column != to.column {
102 stmts.push(Stmt::new(format!(
103 "ALTER TABLE {table} RENAME COLUMN {col} TO {};",
104 self.quote_ident(&to.column)
105 )));
106 }
107
108 let to_col = self.quote_ident(&to.column);
109
110 if from.kind != to.kind {
111 match self.column_type(to) {
112 Ok(sql_type) => stmts.push(Stmt::new(format!(
113 "ALTER TABLE {table} ALTER COLUMN {to_col} TYPE {sql_type} USING {to_col}::{sql_type};"
114 ))),
115 Err(e) => stmts.push(Stmt::new(format!("-- error: {e}"))),
116 }
117 }
118
119 let old_default = default_sql(self, from);
120 let new_default = default_sql(self, to);
121 if old_default != new_default {
122 if new_default.is_empty() {
123 stmts.push(Stmt::new(format!(
124 "ALTER TABLE {table} ALTER COLUMN {to_col} DROP DEFAULT;"
125 )));
126 } else {
127 stmts.push(Stmt::new(format!(
128 "ALTER TABLE {table} ALTER COLUMN {to_col} SET DEFAULT {new_default};"
129 )));
130 }
131 }
132
133 if from.optional != to.optional {
134 if to.optional {
135 stmts.push(Stmt::new(format!(
136 "ALTER TABLE {table} ALTER COLUMN {to_col} DROP NOT NULL;"
137 )));
138 } else {
139 stmts.push(Stmt::new(format!(
140 "ALTER TABLE {table} ALTER COLUMN {to_col} SET NOT NULL;"
141 )));
142 }
143 }
144
145 stmts
146 }
147
148 fn create_index(&self, m: &Model, ix: &IndexDef) -> Vec<Stmt> {
149 let cols = render_index_targets(self, m, &ix.targets);
150 let using = match ix.index_type {
151 Some(ruprizzle_core::ir::IndexType::Gist) => " USING GIST",
152 Some(ruprizzle_core::ir::IndexType::Gin) => " USING GIN",
153 Some(ruprizzle_core::ir::IndexType::Hash) => " USING HASH",
154 Some(ruprizzle_core::ir::IndexType::SpGist) => " USING SPGIST",
155 Some(ruprizzle_core::ir::IndexType::Brin) => " USING BRIN",
156 _ => "",
157 };
158 let mut sql = format!(
159 "CREATE INDEX {} ON {}{using} ({})",
160 self.quote_ident(&ix.db_name),
161 self.quote_ident(&m.table),
162 cols
163 );
164 if let Some(ref w) = ix.where_clause {
165 let _ = write!(sql, " WHERE {w}");
166 }
167 sql.push(';');
168 vec![Stmt::new(sql)]
169 }
170
171 fn drop_index(&self, _table: &str, name: &str) -> Vec<Stmt> {
172 vec![Stmt::new(format!(
173 "DROP INDEX IF EXISTS {};",
174 self.quote_ident(name)
175 ))]
176 }
177
178 fn add_unique(&self, m: &Model, uq: &UniqueDef) -> Vec<Stmt> {
179 let table = self.quote_ident(&m.table);
180 let name = self.quote_ident(&uq.db_name);
181 let cols = render_index_targets(self, m, &uq.targets);
182 vec![Stmt::new(format!(
183 "ALTER TABLE {table} ADD CONSTRAINT {name} UNIQUE ({cols});"
184 ))]
185 }
186
187 fn drop_unique(&self, table: &str, name: &str) -> Vec<Stmt> {
188 vec![Stmt::new(format!(
189 "ALTER TABLE {} DROP CONSTRAINT {};",
190 self.quote_ident(table),
191 self.quote_ident(name)
192 ))]
193 }
194
195 fn add_foreign_key(&self, m: &Model, r: &ResolvedRelation) -> Vec<Stmt> {
196 if r.kind == RelationKind::ManyToMany {
197 return Vec::new();
198 }
199 let table = self.quote_ident(&m.table);
200 let constraint = fk_constraint_sql(self, r);
201 vec![Stmt::new(format!("ALTER TABLE {table} ADD {constraint};"))]
202 }
203
204 fn drop_foreign_key(&self, m: &Model, r: &ResolvedRelation) -> Vec<Stmt> {
205 if r.kind == RelationKind::ManyToMany {
206 return Vec::new();
207 }
208 let table = self.quote_ident(&m.table);
209 let name = self.quote_ident(&r.constraint_name);
210 vec![Stmt::new(format!(
211 "ALTER TABLE {table} DROP CONSTRAINT {name};"
212 ))]
213 }
214
215 fn create_enum(&self, e: &EnumDef) -> Vec<Stmt> {
216 let name = self.quote_ident(&e.db_name);
217 let variants = e
218 .variants
219 .values()
220 .map(|v| format!("'{}'", v.db_name.replace('\'', "''")))
221 .collect::<Vec<_>>()
222 .join(", ");
223 vec![Stmt::new(format!("CREATE TYPE {name} AS ENUM ({variants});")).non_transactional()]
224 }
225
226 fn alter_enum_add_variant(&self, e: &EnumDef, v: &str) -> Vec<Stmt> {
227 let name = self.quote_ident(&e.db_name);
228 let escaped = v.replace('\'', "''");
229 vec![Stmt::new(format!("ALTER TYPE {name} ADD VALUE '{escaped}';")).non_transactional()]
230 }
231
232 fn returning_supported(&self) -> bool {
233 true
234 }
235
236 fn upsert_clause(&self, conflict: &[String], update: &[String]) -> String {
237 if update.is_empty() {
238 format!("ON CONFLICT ({}) DO NOTHING", conflict.join(", "))
239 } else {
240 let quoted_update = update
241 .iter()
242 .map(|c| format!("{} = EXCLUDED.{}", self.quote_ident(c), self.quote_ident(c)))
243 .collect::<Vec<_>>()
244 .join(", ");
245 format!(
246 "ON CONFLICT ({}) DO UPDATE SET {}",
247 conflict.join(", "),
248 quoted_update
249 )
250 }
251 }
252
253 fn limit_offset(&self, limit: Option<u64>, offset: Option<u64>) -> String {
254 let mut parts = Vec::new();
255 if let Some(l) = limit {
256 parts.push(format!("LIMIT {l}"));
257 }
258 if let Some(o) = offset {
259 parts.push(format!("OFFSET {o}"));
260 }
261 parts.join(" ")
262 }
263
264 fn cast_expr(&self, expr: &str, ty: ScalarType) -> String {
265 format!("{}::{}", expr, pg_type_name(ty))
266 }
267
268 fn capabilities(&self) -> Capabilities {
269 Capabilities {
270 native_enums: true,
271 native_uuid: true,
272 alter_column_type: true,
273 drop_column: true,
274 add_fk_after_create: true,
275 returning: true,
276 partial_indexes: true,
277 deferrable_fks: true,
278 json_type: JsonSupport::Native,
279 max_query_params: 65_535,
280 postgis: true,
281 window_functions: true,
282 }
283 }
284}
285
286fn pg_type_name(ty: ScalarType) -> &'static str {
287 match ty {
288 ScalarType::String => "TEXT",
289 ScalarType::Int => "INTEGER",
290 ScalarType::BigInt => "BIGINT",
291 ScalarType::Float => "DOUBLE PRECISION",
292 ScalarType::Decimal => "NUMERIC",
293 ScalarType::Boolean => "BOOLEAN",
294 ScalarType::DateTime => "TIMESTAMPTZ",
295 ScalarType::Date => "DATE",
296 ScalarType::Time => "TIME",
297 ScalarType::Uuid => "UUID",
298 ScalarType::Json => "JSONB",
299 ScalarType::Bytes => "BYTEA",
300 ScalarType::Point => "GEOMETRY(Point, 4326)",
301 ScalarType::Polygon => "GEOMETRY(Polygon, 4326)",
302 ScalarType::MultiPolygon => "GEOMETRY(MultiPolygon, 4326)",
303 ScalarType::LineString => "GEOMETRY(LineString, 4326)",
304 }
305}
306
307fn pg_kind_type(kind: &FieldKind) -> String {
308 match kind {
309 FieldKind::Scalar(ScalarType::String) | FieldKind::Relation(_) => "TEXT".to_owned(),
310 FieldKind::Scalar(st) => pg_type_name(*st).to_owned(),
311 FieldKind::Enum(name) => name.as_str().to_owned(),
312 FieldKind::List(inner) => format!("{}[]", pg_kind_type(inner)),
313 }
314}