1use qcraft_core::ast::common::{FieldRef, NullsOrder, OrderByDef, OrderDir, SchemaRef};
2use qcraft_core::ast::conditions::{CompareOp, ConditionNode, Conditions, Connector};
3use qcraft_core::ast::ddl::{
4 ColumnDef, ConstraintDef, DeferrableConstraint, FieldType, IdentityColumn, IndexColumnDef,
5 IndexDef, IndexExpr, LikeTableDef, MatchType, OnCommitAction, PartitionByDef,
6 PartitionStrategy, ReferentialAction, SchemaDef, SchemaMutationStmt,
7};
8use qcraft_core::ast::dml::{
9 ConflictAction, ConflictTarget, DeleteStmt, InsertSource, InsertStmt, MutationStmt,
10 OnConflictDef, OverridingKind, UpdateStmt,
11};
12use qcraft_core::ast::expr::{
13 AggregationDef, BinaryOp, CaseDef, Expr, UnaryOp, WindowDef, WindowFrameBound, WindowFrameDef,
14 WindowFrameType,
15};
16use qcraft_core::ast::query::{
17 CteDef, CteMaterialized, DistinctDef, FromItem, GroupByItem, JoinCondition, JoinDef, JoinType,
18 LimitDef, LimitKind, LockStrength, QueryStmt, SampleMethod, SelectColumn, SelectLockDef,
19 SetOpDef, SetOperationType, TableSource, WindowNameDef,
20};
21use qcraft_core::ast::tcl::{
22 BeginStmt, CommitStmt, IsolationLevel, LockMode, LockTableStmt, RollbackStmt,
23 SetTransactionStmt, TransactionMode, TransactionScope, TransactionStmt,
24};
25use qcraft_core::ast::value::Value;
26use qcraft_core::error::{RenderError, RenderResult};
27use qcraft_core::render::ctx::{ParamStyle, RenderCtx};
28use qcraft_core::render::escape_like_value;
29use qcraft_core::render::renderer::Renderer;
30
31fn render_like_pattern(op: &CompareOp, right: &Expr, ctx: &mut RenderCtx) -> RenderResult<()> {
32 let raw = match right {
33 Expr::Value(Value::Str(s)) => s.as_str(),
34 _ => {
35 return Err(RenderError::unsupported(
36 "CompareOp",
37 "Contains/StartsWith/EndsWith require a string value on the right side",
38 ));
39 }
40 };
41 let escaped = escape_like_value(raw);
42 let pattern = match op {
43 CompareOp::Contains | CompareOp::IContains => format!("%{escaped}%"),
44 CompareOp::StartsWith | CompareOp::IStartsWith => format!("{escaped}%"),
45 CompareOp::EndsWith | CompareOp::IEndsWith => format!("%{escaped}"),
46 _ => unreachable!(),
47 };
48 if ctx.parameterize() {
49 ctx.param(Value::Str(pattern));
50 } else {
51 ctx.string_literal(&pattern);
52 }
53 Ok(())
54}
55
56struct PgCreateTableOpts<'a> {
57 tablespace: Option<&'a str>,
58 partition_by: Option<&'a PartitionByDef>,
59 inherits: Option<&'a [SchemaRef]>,
60 using_method: Option<&'a str>,
61 with_options: Option<&'a [(String, String)]>,
62 on_commit: Option<&'a OnCommitAction>,
63}
64
65pub struct PostgresRenderer {
66 param_style: ParamStyle,
67}
68
69impl PostgresRenderer {
70 pub fn new() -> Self {
71 Self {
72 param_style: ParamStyle::Dollar,
73 }
74 }
75
76 pub fn with_param_style(mut self, style: ParamStyle) -> Self {
78 self.param_style = style;
79 self
80 }
81
82 pub fn render_schema_stmt(
84 &self,
85 stmt: &SchemaMutationStmt,
86 ) -> RenderResult<(String, Vec<Value>)> {
87 let mut ctx = RenderCtx::new(self.param_style);
88 self.render_schema_mutation(stmt, &mut ctx)?;
89 Ok(ctx.finish())
90 }
91
92 pub fn render_transaction_stmt(
94 &self,
95 stmt: &TransactionStmt,
96 ) -> RenderResult<(String, Vec<Value>)> {
97 let mut ctx = RenderCtx::new(self.param_style);
98 self.render_transaction(stmt, &mut ctx)?;
99 Ok(ctx.finish())
100 }
101
102 pub fn render_mutation_stmt(&self, stmt: &MutationStmt) -> RenderResult<(String, Vec<Value>)> {
104 let mut ctx = RenderCtx::new(self.param_style).with_parameterize(true);
105 self.render_mutation(stmt, &mut ctx)?;
106 Ok(ctx.finish())
107 }
108
109 pub fn render_query_stmt(&self, stmt: &QueryStmt) -> RenderResult<(String, Vec<Value>)> {
111 let mut ctx = RenderCtx::new(self.param_style).with_parameterize(true);
112 self.render_query(stmt, &mut ctx)?;
113 Ok(ctx.finish())
114 }
115}
116
117impl Default for PostgresRenderer {
118 fn default() -> Self {
119 Self::new()
120 }
121}
122
123impl Renderer for PostgresRenderer {
128 fn render_schema_mutation(
131 &self,
132 stmt: &SchemaMutationStmt,
133 ctx: &mut RenderCtx,
134 ) -> RenderResult<()> {
135 match stmt {
136 SchemaMutationStmt::CreateTable {
137 schema,
138 if_not_exists,
139 temporary,
140 unlogged,
141 tablespace,
142 partition_by,
143 inherits,
144 using_method,
145 with_options,
146 on_commit,
147 table_options: _, without_rowid: _, strict: _, } => self.pg_create_table(
151 schema,
152 *if_not_exists,
153 *temporary,
154 *unlogged,
155 &PgCreateTableOpts {
156 tablespace: tablespace.as_deref(),
157 partition_by: partition_by.as_ref(),
158 inherits: inherits.as_deref(),
159 using_method: using_method.as_deref(),
160 with_options: with_options.as_deref(),
161 on_commit: on_commit.as_ref(),
162 },
163 ctx,
164 ),
165
166 SchemaMutationStmt::DropTable {
167 schema_ref,
168 if_exists,
169 cascade,
170 } => {
171 ctx.keyword("DROP TABLE");
172 if *if_exists {
173 ctx.keyword("IF EXISTS");
174 }
175 self.pg_schema_ref(schema_ref, ctx);
176 if *cascade {
177 ctx.keyword("CASCADE");
178 }
179 Ok(())
180 }
181
182 SchemaMutationStmt::RenameTable {
183 schema_ref,
184 new_name,
185 } => {
186 ctx.keyword("ALTER TABLE");
187 self.pg_schema_ref(schema_ref, ctx);
188 ctx.keyword("RENAME TO").ident(new_name);
189 Ok(())
190 }
191
192 SchemaMutationStmt::TruncateTable {
193 schema_ref,
194 restart_identity,
195 cascade,
196 } => {
197 ctx.keyword("TRUNCATE TABLE");
198 self.pg_schema_ref(schema_ref, ctx);
199 if *restart_identity {
200 ctx.keyword("RESTART IDENTITY");
201 }
202 if *cascade {
203 ctx.keyword("CASCADE");
204 }
205 Ok(())
206 }
207
208 SchemaMutationStmt::AddColumn {
209 schema_ref,
210 column,
211 if_not_exists,
212 position: _, } => {
214 ctx.keyword("ALTER TABLE");
215 self.pg_schema_ref(schema_ref, ctx);
216 ctx.keyword("ADD COLUMN");
217 if *if_not_exists {
218 ctx.keyword("IF NOT EXISTS");
219 }
220 self.render_column_def(column, ctx)
221 }
222
223 SchemaMutationStmt::DropColumn {
224 schema_ref,
225 name,
226 if_exists,
227 cascade,
228 } => {
229 ctx.keyword("ALTER TABLE");
230 self.pg_schema_ref(schema_ref, ctx);
231 ctx.keyword("DROP COLUMN");
232 if *if_exists {
233 ctx.keyword("IF EXISTS");
234 }
235 ctx.ident(name);
236 if *cascade {
237 ctx.keyword("CASCADE");
238 }
239 Ok(())
240 }
241
242 SchemaMutationStmt::RenameColumn {
243 schema_ref,
244 old_name,
245 new_name,
246 } => {
247 ctx.keyword("ALTER TABLE");
248 self.pg_schema_ref(schema_ref, ctx);
249 ctx.keyword("RENAME COLUMN")
250 .ident(old_name)
251 .keyword("TO")
252 .ident(new_name);
253 Ok(())
254 }
255
256 SchemaMutationStmt::AlterColumnType {
257 schema_ref,
258 column_name,
259 new_type,
260 using_expr,
261 } => {
262 ctx.keyword("ALTER TABLE");
263 self.pg_schema_ref(schema_ref, ctx);
264 ctx.keyword("ALTER COLUMN")
265 .ident(column_name)
266 .keyword("SET DATA TYPE");
267 self.render_column_type(new_type, ctx)?;
268 if let Some(expr) = using_expr {
269 ctx.keyword("USING");
270 self.render_expr(expr, ctx)?;
271 }
272 Ok(())
273 }
274
275 SchemaMutationStmt::AlterColumnDefault {
276 schema_ref,
277 column_name,
278 default,
279 } => {
280 ctx.keyword("ALTER TABLE");
281 self.pg_schema_ref(schema_ref, ctx);
282 ctx.keyword("ALTER COLUMN").ident(column_name);
283 match default {
284 Some(expr) => {
285 ctx.keyword("SET DEFAULT");
286 self.render_expr(expr, ctx)?;
287 }
288 None => {
289 ctx.keyword("DROP DEFAULT");
290 }
291 }
292 Ok(())
293 }
294
295 SchemaMutationStmt::AlterColumnNullability {
296 schema_ref,
297 column_name,
298 not_null,
299 } => {
300 ctx.keyword("ALTER TABLE");
301 self.pg_schema_ref(schema_ref, ctx);
302 ctx.keyword("ALTER COLUMN").ident(column_name);
303 if *not_null {
304 ctx.keyword("SET NOT NULL");
305 } else {
306 ctx.keyword("DROP NOT NULL");
307 }
308 Ok(())
309 }
310
311 SchemaMutationStmt::AddConstraint {
312 schema_ref,
313 constraint,
314 not_valid,
315 } => {
316 ctx.keyword("ALTER TABLE");
317 self.pg_schema_ref(schema_ref, ctx);
318 ctx.keyword("ADD");
319 self.render_constraint(constraint, ctx)?;
320 if *not_valid {
321 ctx.keyword("NOT VALID");
322 }
323 Ok(())
324 }
325
326 SchemaMutationStmt::DropConstraint {
327 schema_ref,
328 constraint_name,
329 if_exists,
330 cascade,
331 } => {
332 ctx.keyword("ALTER TABLE");
333 self.pg_schema_ref(schema_ref, ctx);
334 ctx.keyword("DROP CONSTRAINT");
335 if *if_exists {
336 ctx.keyword("IF EXISTS");
337 }
338 ctx.ident(constraint_name);
339 if *cascade {
340 ctx.keyword("CASCADE");
341 }
342 Ok(())
343 }
344
345 SchemaMutationStmt::RenameConstraint {
346 schema_ref,
347 old_name,
348 new_name,
349 } => {
350 ctx.keyword("ALTER TABLE");
351 self.pg_schema_ref(schema_ref, ctx);
352 ctx.keyword("RENAME CONSTRAINT")
353 .ident(old_name)
354 .keyword("TO")
355 .ident(new_name);
356 Ok(())
357 }
358
359 SchemaMutationStmt::ValidateConstraint {
360 schema_ref,
361 constraint_name,
362 } => {
363 ctx.keyword("ALTER TABLE");
364 self.pg_schema_ref(schema_ref, ctx);
365 ctx.keyword("VALIDATE CONSTRAINT").ident(constraint_name);
366 Ok(())
367 }
368
369 SchemaMutationStmt::CreateIndex {
370 schema_ref,
371 index,
372 if_not_exists,
373 concurrently,
374 } => self.pg_create_index(schema_ref, index, *if_not_exists, *concurrently, ctx),
375
376 SchemaMutationStmt::DropIndex {
377 schema_ref: _,
378 index_name,
379 if_exists,
380 concurrently,
381 cascade,
382 } => {
383 ctx.keyword("DROP INDEX");
384 if *concurrently {
385 ctx.keyword("CONCURRENTLY");
386 }
387 if *if_exists {
388 ctx.keyword("IF EXISTS");
389 }
390 ctx.ident(index_name);
391 if *cascade {
392 ctx.keyword("CASCADE");
393 }
394 Ok(())
395 }
396
397 SchemaMutationStmt::CreateExtension {
398 name,
399 if_not_exists,
400 schema,
401 version,
402 cascade,
403 } => {
404 ctx.keyword("CREATE EXTENSION");
405 if *if_not_exists {
406 ctx.keyword("IF NOT EXISTS");
407 }
408 ctx.ident(name);
409 if let Some(s) = schema {
410 ctx.keyword("SCHEMA").ident(s);
411 }
412 if let Some(v) = version {
413 ctx.keyword("VERSION").string_literal(v);
414 }
415 if *cascade {
416 ctx.keyword("CASCADE");
417 }
418 Ok(())
419 }
420
421 SchemaMutationStmt::DropExtension {
422 name,
423 if_exists,
424 cascade,
425 } => {
426 ctx.keyword("DROP EXTENSION");
427 if *if_exists {
428 ctx.keyword("IF EXISTS");
429 }
430 ctx.ident(name);
431 if *cascade {
432 ctx.keyword("CASCADE");
433 }
434 Ok(())
435 }
436
437 SchemaMutationStmt::Custom(_) => Err(RenderError::unsupported(
438 "CustomSchemaMutation",
439 "custom DDL must be handled by a wrapping renderer",
440 )),
441 }
442 }
443
444 fn render_column_def(&self, col: &ColumnDef, ctx: &mut RenderCtx) -> RenderResult<()> {
445 ctx.ident(&col.name);
446 self.render_column_type(&col.field_type, ctx)?;
447
448 if let Some(storage) = &col.storage {
449 ctx.keyword("STORAGE").keyword(storage);
450 }
451
452 if let Some(compression) = &col.compression {
453 ctx.keyword("COMPRESSION").keyword(compression);
454 }
455
456 if let Some(collation) = &col.collation {
457 ctx.keyword("COLLATE").ident(collation);
458 }
459
460 if col.not_null {
461 ctx.keyword("NOT NULL");
462 }
463
464 if let Some(default) = &col.default {
465 ctx.keyword("DEFAULT");
466 self.render_expr(default, ctx)?;
467 }
468
469 if let Some(identity) = &col.identity {
470 self.pg_identity(identity, ctx);
471 }
472
473 if let Some(generated) = &col.generated {
474 ctx.keyword("GENERATED ALWAYS AS").space().paren_open();
475 self.render_expr(&generated.expr, ctx)?;
476 ctx.paren_close().keyword("STORED");
477 }
478
479 Ok(())
480 }
481
482 fn render_column_type(&self, ty: &FieldType, ctx: &mut RenderCtx) -> RenderResult<()> {
483 match ty {
484 FieldType::Scalar(name) => {
485 ctx.keyword(name);
486 }
487 FieldType::Parameterized { name, params } => {
488 ctx.keyword(name).write("(");
489 for (i, p) in params.iter().enumerate() {
490 if i > 0 {
491 ctx.comma();
492 }
493 ctx.write(p);
494 }
495 ctx.paren_close();
496 }
497 FieldType::Array(inner) => {
498 self.render_column_type(inner, ctx)?;
499 ctx.write("[]");
500 }
501 FieldType::Vector(dim) => {
502 ctx.keyword("VECTOR")
503 .write("(")
504 .write(&dim.to_string())
505 .paren_close();
506 }
507 FieldType::Custom(_) => {
508 return Err(RenderError::unsupported(
509 "CustomFieldType",
510 "custom field type must be handled by a wrapping renderer",
511 ));
512 }
513 }
514 Ok(())
515 }
516
517 fn render_constraint(&self, c: &ConstraintDef, ctx: &mut RenderCtx) -> RenderResult<()> {
518 match c {
519 ConstraintDef::PrimaryKey {
520 name,
521 columns,
522 include,
523 autoincrement: _, } => {
525 if let Some(n) = name {
526 ctx.keyword("CONSTRAINT").ident(n);
527 }
528 ctx.keyword("PRIMARY KEY").paren_open();
529 self.pg_comma_idents(columns, ctx);
530 ctx.paren_close();
531 if let Some(inc) = include {
532 ctx.keyword("INCLUDE").paren_open();
533 self.pg_comma_idents(inc, ctx);
534 ctx.paren_close();
535 }
536 }
537
538 ConstraintDef::ForeignKey {
539 name,
540 columns,
541 ref_table,
542 ref_columns,
543 on_delete,
544 on_update,
545 deferrable,
546 match_type,
547 } => {
548 if let Some(n) = name {
549 ctx.keyword("CONSTRAINT").ident(n);
550 }
551 ctx.keyword("FOREIGN KEY").paren_open();
552 self.pg_comma_idents(columns, ctx);
553 ctx.paren_close().keyword("REFERENCES");
554 self.pg_schema_ref(ref_table, ctx);
555 ctx.paren_open();
556 self.pg_comma_idents(ref_columns, ctx);
557 ctx.paren_close();
558 if let Some(mt) = match_type {
559 ctx.keyword(match mt {
560 MatchType::Full => "MATCH FULL",
561 MatchType::Partial => "MATCH PARTIAL",
562 MatchType::Simple => "MATCH SIMPLE",
563 });
564 }
565 if let Some(action) = on_delete {
566 ctx.keyword("ON DELETE");
567 self.pg_referential_action(action, ctx);
568 }
569 if let Some(action) = on_update {
570 ctx.keyword("ON UPDATE");
571 self.pg_referential_action(action, ctx);
572 }
573 if let Some(def) = deferrable {
574 self.pg_deferrable(def, ctx);
575 }
576 }
577
578 ConstraintDef::Unique {
579 name,
580 columns,
581 include,
582 nulls_distinct,
583 condition: _, } => {
585 if let Some(n) = name {
586 ctx.keyword("CONSTRAINT").ident(n);
587 }
588 ctx.keyword("UNIQUE");
589 if let Some(false) = nulls_distinct {
590 ctx.keyword("NULLS NOT DISTINCT");
591 }
592 ctx.paren_open();
593 self.pg_comma_idents(columns, ctx);
594 ctx.paren_close();
595 if let Some(inc) = include {
596 ctx.keyword("INCLUDE").paren_open();
597 self.pg_comma_idents(inc, ctx);
598 ctx.paren_close();
599 }
600 }
601
602 ConstraintDef::Check {
603 name,
604 condition,
605 no_inherit,
606 enforced: _, } => {
608 if let Some(n) = name {
609 ctx.keyword("CONSTRAINT").ident(n);
610 }
611 ctx.keyword("CHECK").paren_open();
612 self.render_condition(condition, ctx)?;
613 ctx.paren_close();
614 if *no_inherit {
615 ctx.keyword("NO INHERIT");
616 }
617 }
618
619 ConstraintDef::Exclusion {
620 name,
621 elements,
622 index_method,
623 condition,
624 } => {
625 if let Some(n) = name {
626 ctx.keyword("CONSTRAINT").ident(n);
627 }
628 ctx.keyword("EXCLUDE USING")
629 .keyword(index_method)
630 .paren_open();
631 for (i, elem) in elements.iter().enumerate() {
632 if i > 0 {
633 ctx.comma();
634 }
635 ctx.ident(&elem.column)
636 .keyword("WITH")
637 .keyword(&elem.operator);
638 }
639 ctx.paren_close();
640 if let Some(cond) = condition {
641 ctx.keyword("WHERE").paren_open();
642 self.render_condition(cond, ctx)?;
643 ctx.paren_close();
644 }
645 }
646
647 ConstraintDef::Custom(_) => {
648 return Err(RenderError::unsupported(
649 "CustomConstraint",
650 "custom constraint must be handled by a wrapping renderer",
651 ));
652 }
653 }
654 Ok(())
655 }
656
657 fn render_index_def(&self, idx: &IndexDef, ctx: &mut RenderCtx) -> RenderResult<()> {
658 ctx.ident(&idx.name);
661 if let Some(index_type) = &idx.index_type {
662 ctx.keyword("USING").keyword(index_type);
663 }
664 ctx.paren_open();
665 self.pg_index_columns(&idx.columns, ctx)?;
666 ctx.paren_close();
667 Ok(())
668 }
669
670 fn render_expr(&self, expr: &Expr, ctx: &mut RenderCtx) -> RenderResult<()> {
673 match expr {
674 Expr::Value(val) => self.pg_value(val, ctx),
675
676 Expr::Field(field_ref) => {
677 self.pg_field_ref(field_ref, ctx);
678 Ok(())
679 }
680
681 Expr::Binary { left, op, right } => {
682 self.render_expr(left, ctx)?;
683 let mod_op = if self.param_style == ParamStyle::Percent {
686 "%%"
687 } else {
688 "%"
689 };
690 ctx.keyword(match op {
691 BinaryOp::Add => "+",
692 BinaryOp::Sub => "-",
693 BinaryOp::Mul => "*",
694 BinaryOp::Div => "/",
695 BinaryOp::Mod => mod_op,
696 BinaryOp::BitwiseAnd => "&",
697 BinaryOp::BitwiseOr => "|",
698 BinaryOp::ShiftLeft => "<<",
699 BinaryOp::ShiftRight => ">>",
700 BinaryOp::Concat => "||",
701 });
702 self.render_expr(right, ctx)
703 }
704
705 Expr::Unary { op, expr: inner } => {
706 match op {
707 UnaryOp::Neg => ctx.write("-"),
708 UnaryOp::Not => ctx.keyword("NOT"),
709 UnaryOp::BitwiseNot => ctx.write("~"),
710 };
711 self.render_expr(inner, ctx)
712 }
713
714 Expr::Func { name, args } => {
715 ctx.keyword(name).write("(");
716 for (i, arg) in args.iter().enumerate() {
717 if i > 0 {
718 ctx.comma();
719 }
720 self.render_expr(arg, ctx)?;
721 }
722 ctx.paren_close();
723 Ok(())
724 }
725
726 Expr::Aggregate(agg) => self.render_aggregate(agg, ctx),
727
728 Expr::Cast {
729 expr: inner,
730 to_type,
731 } => {
732 self.render_expr(inner, ctx)?;
733 ctx.operator("::");
734 ctx.write(to_type);
735 Ok(())
736 }
737
738 Expr::Case(case) => self.render_case(case, ctx),
739
740 Expr::Window(win) => self.render_window(win, ctx),
741
742 Expr::Exists(query) => {
743 ctx.keyword("EXISTS").paren_open();
744 self.render_query(query, ctx)?;
745 ctx.paren_close();
746 Ok(())
747 }
748
749 Expr::SubQuery(query) => {
750 ctx.paren_open();
751 self.render_query(query, ctx)?;
752 ctx.paren_close();
753 Ok(())
754 }
755
756 Expr::ArraySubQuery(query) => {
757 ctx.keyword("ARRAY").paren_open();
758 self.render_query(query, ctx)?;
759 ctx.paren_close();
760 Ok(())
761 }
762
763 Expr::Raw { sql, params } => {
764 ctx.keyword(sql);
765 let _ = params;
767 Ok(())
768 }
769
770 Expr::Custom(_) => Err(RenderError::unsupported(
771 "CustomExpr",
772 "custom expression must be handled by a wrapping renderer",
773 )),
774 }
775 }
776
777 fn render_aggregate(&self, agg: &AggregationDef, ctx: &mut RenderCtx) -> RenderResult<()> {
778 ctx.keyword(&agg.name).write("(");
779 if agg.distinct {
780 ctx.keyword("DISTINCT");
781 }
782 if let Some(expr) = &agg.expression {
783 self.render_expr(expr, ctx)?;
784 } else {
785 ctx.write("*");
786 }
787 if let Some(args) = &agg.args {
788 for arg in args {
789 ctx.comma();
790 self.render_expr(arg, ctx)?;
791 }
792 }
793 if let Some(order_by) = &agg.order_by {
794 ctx.keyword("ORDER BY");
795 self.pg_order_by_list(order_by, ctx)?;
796 }
797 ctx.paren_close();
798 if let Some(filter) = &agg.filter {
799 ctx.keyword("FILTER").paren_open().keyword("WHERE");
800 self.render_condition(filter, ctx)?;
801 ctx.paren_close();
802 }
803 Ok(())
804 }
805
806 fn render_window(&self, win: &WindowDef, ctx: &mut RenderCtx) -> RenderResult<()> {
807 self.render_expr(&win.expression, ctx)?;
808 ctx.keyword("OVER").paren_open();
809 if let Some(partition_by) = &win.partition_by {
810 ctx.keyword("PARTITION BY");
811 for (i, expr) in partition_by.iter().enumerate() {
812 if i > 0 {
813 ctx.comma();
814 }
815 self.render_expr(expr, ctx)?;
816 }
817 }
818 if let Some(order_by) = &win.order_by {
819 ctx.keyword("ORDER BY");
820 self.pg_order_by_list(order_by, ctx)?;
821 }
822 if let Some(frame) = &win.frame {
823 self.pg_window_frame(frame, ctx);
824 }
825 ctx.paren_close();
826 Ok(())
827 }
828
829 fn render_case(&self, case: &CaseDef, ctx: &mut RenderCtx) -> RenderResult<()> {
830 ctx.keyword("CASE");
831 for clause in &case.cases {
832 ctx.keyword("WHEN");
833 self.render_condition(&clause.condition, ctx)?;
834 ctx.keyword("THEN");
835 self.render_expr(&clause.result, ctx)?;
836 }
837 if let Some(default) = &case.default {
838 ctx.keyword("ELSE");
839 self.render_expr(default, ctx)?;
840 }
841 ctx.keyword("END");
842 Ok(())
843 }
844
845 fn render_condition(&self, cond: &Conditions, ctx: &mut RenderCtx) -> RenderResult<()> {
848 if cond.negated {
849 ctx.keyword("NOT").paren_open();
850 }
851 let connector = match cond.connector {
852 Connector::And => " AND ",
853 Connector::Or => " OR ",
854 };
855 for (i, child) in cond.children.iter().enumerate() {
856 if i > 0 {
857 ctx.write(connector);
858 }
859 match child {
860 ConditionNode::Comparison(comp) => {
861 if comp.negate {
862 ctx.keyword("NOT").paren_open();
863 }
864 self.render_compare_op(&comp.op, &comp.left, &comp.right, ctx)?;
865 if comp.negate {
866 ctx.paren_close();
867 }
868 }
869 ConditionNode::Group(group) => {
870 ctx.paren_open();
871 self.render_condition(group, ctx)?;
872 ctx.paren_close();
873 }
874 ConditionNode::Exists(query) => {
875 ctx.keyword("EXISTS").paren_open();
876 self.render_query(query, ctx)?;
877 ctx.paren_close();
878 }
879 ConditionNode::Custom(_) => {
880 return Err(RenderError::unsupported(
881 "CustomCondition",
882 "custom condition must be handled by a wrapping renderer",
883 ));
884 }
885 }
886 }
887 if cond.negated {
888 ctx.paren_close();
889 }
890 Ok(())
891 }
892
893 fn render_compare_op(
894 &self,
895 op: &CompareOp,
896 left: &Expr,
897 right: &Expr,
898 ctx: &mut RenderCtx,
899 ) -> RenderResult<()> {
900 self.render_expr(left, ctx)?;
901 match op {
902 CompareOp::Eq => ctx.write(" = "),
903 CompareOp::Neq => ctx.write(" <> "),
904 CompareOp::Gt => ctx.write(" > "),
905 CompareOp::Gte => ctx.write(" >= "),
906 CompareOp::Lt => ctx.write(" < "),
907 CompareOp::Lte => ctx.write(" <= "),
908 CompareOp::Like => ctx.keyword("LIKE"),
909 CompareOp::ILike => ctx.keyword("ILIKE"),
910 CompareOp::Contains | CompareOp::StartsWith | CompareOp::EndsWith => {
911 ctx.keyword("LIKE");
912 render_like_pattern(op, right, ctx)?;
913 return Ok(());
914 }
915 CompareOp::IContains | CompareOp::IStartsWith | CompareOp::IEndsWith => {
916 ctx.keyword("ILIKE");
917 render_like_pattern(op, right, ctx)?;
918 return Ok(());
919 }
920 CompareOp::In => ctx.keyword("IN"),
921 CompareOp::Between => {
922 ctx.keyword("BETWEEN");
923 self.render_expr(right, ctx)?;
924 return Ok(());
925 }
926 CompareOp::IsNull => {
927 ctx.keyword("IS NULL");
928 return Ok(());
929 }
930 CompareOp::Similar => ctx.keyword("SIMILAR TO"),
931 CompareOp::Regex => ctx.write(" ~ "),
932 CompareOp::IRegex => ctx.write(" ~* "),
933 CompareOp::JsonbContains => ctx.write(" @> "),
934 CompareOp::JsonbContainedBy => ctx.write(" <@ "),
935 CompareOp::JsonbHasKey => ctx.write(" ? "),
936 CompareOp::JsonbHasAnyKey => ctx.write(" ?| "),
937 CompareOp::JsonbHasAllKeys => ctx.write(" ?& "),
938 CompareOp::FtsMatch => ctx.write(" @@ "),
939 CompareOp::TrigramSimilar => {
940 if self.param_style == ParamStyle::Percent {
941 ctx.write(" %% ")
942 } else {
943 ctx.write(" % ")
944 }
945 }
946 CompareOp::TrigramWordSimilar => {
947 if self.param_style == ParamStyle::Percent {
948 ctx.write(" <%% ")
949 } else {
950 ctx.write(" <% ")
951 }
952 }
953 CompareOp::TrigramStrictWordSimilar => {
954 if self.param_style == ParamStyle::Percent {
955 ctx.write(" <<%% ")
956 } else {
957 ctx.write(" <<% ")
958 }
959 }
960 CompareOp::RangeContains => ctx.write(" @> "),
961 CompareOp::RangeContainedBy => ctx.write(" <@ "),
962 CompareOp::RangeOverlap => ctx.write(" && "),
963 CompareOp::Custom(_) => {
964 return Err(RenderError::unsupported(
965 "CustomCompareOp",
966 "custom compare op must be handled by a wrapping renderer",
967 ));
968 }
969 };
970 self.render_expr(right, ctx)
971 }
972
973 fn render_query(&self, stmt: &QueryStmt, ctx: &mut RenderCtx) -> RenderResult<()> {
976 if let Some(ctes) = &stmt.ctes {
978 self.render_ctes(ctes, ctx)?;
979 }
980
981 ctx.keyword("SELECT");
983
984 if let Some(distinct) = &stmt.distinct {
986 match distinct {
987 DistinctDef::Distinct => {
988 ctx.keyword("DISTINCT");
989 }
990 DistinctDef::DistinctOn(exprs) => {
991 ctx.keyword("DISTINCT ON").paren_open();
992 for (i, expr) in exprs.iter().enumerate() {
993 if i > 0 {
994 ctx.comma();
995 }
996 self.render_expr(expr, ctx)?;
997 }
998 ctx.paren_close();
999 }
1000 }
1001 }
1002
1003 self.render_select_columns(&stmt.columns, ctx)?;
1005
1006 if let Some(from) = &stmt.from {
1008 ctx.keyword("FROM");
1009 for (i, item) in from.iter().enumerate() {
1010 if i > 0 {
1011 ctx.comma();
1012 }
1013 self.pg_render_from_item(item, ctx)?;
1014 }
1015 }
1016
1017 if let Some(joins) = &stmt.joins {
1019 self.render_joins(joins, ctx)?;
1020 }
1021
1022 if let Some(cond) = &stmt.where_clause {
1024 self.render_where(cond, ctx)?;
1025 }
1026
1027 if let Some(group_by) = &stmt.group_by {
1029 self.pg_render_group_by(group_by, ctx)?;
1030 }
1031
1032 if let Some(having) = &stmt.having {
1034 ctx.keyword("HAVING");
1035 self.render_condition(having, ctx)?;
1036 }
1037
1038 if let Some(windows) = &stmt.window {
1040 self.pg_render_window_clause(windows, ctx)?;
1041 }
1042
1043 if let Some(order_by) = &stmt.order_by {
1045 self.render_order_by(order_by, ctx)?;
1046 }
1047
1048 if let Some(limit) = &stmt.limit {
1050 self.render_limit(limit, ctx)?;
1051 }
1052
1053 if let Some(locks) = &stmt.lock {
1055 for lock in locks {
1056 self.render_lock(lock, ctx)?;
1057 }
1058 }
1059
1060 Ok(())
1061 }
1062
1063 fn render_select_columns(
1064 &self,
1065 cols: &[SelectColumn],
1066 ctx: &mut RenderCtx,
1067 ) -> RenderResult<()> {
1068 for (i, col) in cols.iter().enumerate() {
1069 if i > 0 {
1070 ctx.comma();
1071 }
1072 match col {
1073 SelectColumn::Star(None) => {
1074 ctx.keyword("*");
1075 }
1076 SelectColumn::Star(Some(table)) => {
1077 ctx.ident(table).operator(".").keyword("*");
1078 }
1079 SelectColumn::Expr { expr, alias } => {
1080 self.render_expr(expr, ctx)?;
1081 if let Some(a) = alias {
1082 ctx.keyword("AS").ident(a);
1083 }
1084 }
1085 SelectColumn::Field { field, alias } => {
1086 self.pg_field_ref(field, ctx);
1087 if let Some(a) = alias {
1088 ctx.keyword("AS").ident(a);
1089 }
1090 }
1091 }
1092 }
1093 Ok(())
1094 }
1095 fn render_from(&self, source: &TableSource, ctx: &mut RenderCtx) -> RenderResult<()> {
1096 match source {
1097 TableSource::Table(schema_ref) => {
1098 self.pg_schema_ref(schema_ref, ctx);
1099 if let Some(alias) = &schema_ref.alias {
1100 ctx.keyword("AS").ident(alias);
1101 }
1102 }
1103 TableSource::SubQuery(sq) => {
1104 ctx.paren_open();
1105 self.render_query(&sq.query, ctx)?;
1106 ctx.paren_close().keyword("AS").ident(&sq.alias);
1107 }
1108 TableSource::SetOp(set_op) => {
1109 ctx.paren_open();
1110 self.pg_render_set_op(set_op, ctx)?;
1111 ctx.paren_close();
1112 }
1113 TableSource::Lateral(inner) => {
1114 ctx.keyword("LATERAL");
1115 self.render_from(&inner.source, ctx)?;
1116 }
1117 TableSource::Function { name, args, alias } => {
1118 ctx.keyword(name).write("(");
1119 for (i, arg) in args.iter().enumerate() {
1120 if i > 0 {
1121 ctx.comma();
1122 }
1123 self.render_expr(arg, ctx)?;
1124 }
1125 ctx.paren_close();
1126 if let Some(a) = alias {
1127 ctx.keyword("AS").ident(a);
1128 }
1129 }
1130 TableSource::Values {
1131 rows,
1132 alias,
1133 column_aliases,
1134 } => {
1135 ctx.paren_open().keyword("VALUES");
1136 for (i, row) in rows.iter().enumerate() {
1137 if i > 0 {
1138 ctx.comma();
1139 }
1140 ctx.paren_open();
1141 for (j, val) in row.iter().enumerate() {
1142 if j > 0 {
1143 ctx.comma();
1144 }
1145 self.render_expr(val, ctx)?;
1146 }
1147 ctx.paren_close();
1148 }
1149 ctx.paren_close().keyword("AS").ident(alias);
1150 if let Some(cols) = column_aliases {
1151 ctx.paren_open();
1152 for (i, c) in cols.iter().enumerate() {
1153 if i > 0 {
1154 ctx.comma();
1155 }
1156 ctx.ident(c);
1157 }
1158 ctx.paren_close();
1159 }
1160 }
1161 TableSource::Custom(_) => {
1162 return Err(RenderError::unsupported(
1163 "CustomTableSource",
1164 "custom table source must be handled by a wrapping renderer",
1165 ));
1166 }
1167 }
1168 Ok(())
1169 }
1170 fn render_joins(&self, joins: &[JoinDef], ctx: &mut RenderCtx) -> RenderResult<()> {
1171 for join in joins {
1172 if join.natural {
1173 ctx.keyword("NATURAL");
1174 }
1175 ctx.keyword(match join.join_type {
1176 JoinType::Inner => "INNER JOIN",
1177 JoinType::Left => "LEFT JOIN",
1178 JoinType::Right => "RIGHT JOIN",
1179 JoinType::Full => "FULL JOIN",
1180 JoinType::Cross => "CROSS JOIN",
1181 JoinType::CrossApply => "CROSS JOIN LATERAL",
1182 JoinType::OuterApply => "LEFT JOIN LATERAL",
1183 });
1184 self.pg_render_from_item(&join.source, ctx)?;
1185 if let Some(condition) = &join.condition {
1186 match condition {
1187 JoinCondition::On(cond) => {
1188 ctx.keyword("ON");
1189 self.render_condition(cond, ctx)?;
1190 }
1191 JoinCondition::Using(cols) => {
1192 ctx.keyword("USING").paren_open();
1193 self.pg_comma_idents(cols, ctx);
1194 ctx.paren_close();
1195 }
1196 }
1197 }
1198 if matches!(join.join_type, JoinType::OuterApply) && join.condition.is_none() {
1200 ctx.keyword("ON TRUE");
1201 }
1202 }
1203 Ok(())
1204 }
1205 fn render_where(&self, cond: &Conditions, ctx: &mut RenderCtx) -> RenderResult<()> {
1206 ctx.keyword("WHERE");
1207 self.render_condition(cond, ctx)
1208 }
1209 fn render_order_by(&self, order: &[OrderByDef], ctx: &mut RenderCtx) -> RenderResult<()> {
1210 ctx.keyword("ORDER BY");
1211 self.pg_order_by_list(order, ctx)
1212 }
1213 fn render_limit(&self, limit: &LimitDef, ctx: &mut RenderCtx) -> RenderResult<()> {
1214 match &limit.kind {
1215 LimitKind::Limit(n) => {
1216 ctx.keyword("LIMIT").space().write(&n.to_string());
1217 }
1218 LimitKind::FetchFirst {
1219 count,
1220 with_ties,
1221 percent,
1222 } => {
1223 if let Some(offset) = limit.offset {
1224 ctx.keyword("OFFSET")
1225 .space()
1226 .write(&offset.to_string())
1227 .keyword("ROWS");
1228 }
1229 ctx.keyword("FETCH FIRST");
1230 if *percent {
1231 ctx.space().write(&count.to_string()).keyword("PERCENT");
1232 } else {
1233 ctx.space().write(&count.to_string());
1234 }
1235 if *with_ties {
1236 ctx.keyword("ROWS WITH TIES");
1237 } else {
1238 ctx.keyword("ROWS ONLY");
1239 }
1240 return Ok(());
1241 }
1242 LimitKind::Top { count, .. } => {
1243 ctx.keyword("LIMIT").space().write(&count.to_string());
1245 }
1246 }
1247 if let Some(offset) = limit.offset {
1248 ctx.keyword("OFFSET").space().write(&offset.to_string());
1249 }
1250 Ok(())
1251 }
1252 fn render_ctes(&self, ctes: &[CteDef], ctx: &mut RenderCtx) -> RenderResult<()> {
1253 let any_recursive = ctes.iter().any(|c| c.recursive);
1255 ctx.keyword("WITH");
1256 if any_recursive {
1257 ctx.keyword("RECURSIVE");
1258 }
1259 for (i, cte) in ctes.iter().enumerate() {
1260 if i > 0 {
1261 ctx.comma();
1262 }
1263 ctx.ident(&cte.name);
1264 if let Some(col_names) = &cte.column_names {
1265 ctx.paren_open();
1266 self.pg_comma_idents(col_names, ctx);
1267 ctx.paren_close();
1268 }
1269 ctx.keyword("AS");
1270 if let Some(mat) = &cte.materialized {
1271 match mat {
1272 CteMaterialized::Materialized => {
1273 ctx.keyword("MATERIALIZED");
1274 }
1275 CteMaterialized::NotMaterialized => {
1276 ctx.keyword("NOT MATERIALIZED");
1277 }
1278 }
1279 }
1280 ctx.paren_open();
1281 self.render_query(&cte.query, ctx)?;
1282 ctx.paren_close();
1283 }
1284 Ok(())
1285 }
1286 fn render_lock(&self, lock: &SelectLockDef, ctx: &mut RenderCtx) -> RenderResult<()> {
1287 ctx.keyword("FOR");
1288 ctx.keyword(match lock.strength {
1289 LockStrength::Update => "UPDATE",
1290 LockStrength::NoKeyUpdate => "NO KEY UPDATE",
1291 LockStrength::Share => "SHARE",
1292 LockStrength::KeyShare => "KEY SHARE",
1293 });
1294 if let Some(of) = &lock.of {
1295 ctx.keyword("OF");
1296 for (i, table) in of.iter().enumerate() {
1297 if i > 0 {
1298 ctx.comma();
1299 }
1300 self.pg_schema_ref(table, ctx);
1301 }
1302 }
1303 if lock.nowait {
1304 ctx.keyword("NOWAIT");
1305 }
1306 if lock.skip_locked {
1307 ctx.keyword("SKIP LOCKED");
1308 }
1309 Ok(())
1310 }
1311
1312 fn render_mutation(&self, stmt: &MutationStmt, ctx: &mut RenderCtx) -> RenderResult<()> {
1315 match stmt {
1316 MutationStmt::Insert(s) => self.render_insert(s, ctx),
1317 MutationStmt::Update(s) => self.render_update(s, ctx),
1318 MutationStmt::Delete(s) => self.render_delete(s, ctx),
1319 MutationStmt::Custom(_) => Err(RenderError::unsupported(
1320 "CustomMutation",
1321 "custom DML must be handled by a wrapping renderer",
1322 )),
1323 }
1324 }
1325
1326 fn render_insert(&self, stmt: &InsertStmt, ctx: &mut RenderCtx) -> RenderResult<()> {
1327 if let Some(ctes) = &stmt.ctes {
1329 self.pg_render_ctes(ctes, ctx)?;
1330 }
1331
1332 ctx.keyword("INSERT INTO");
1333 self.pg_schema_ref(&stmt.table, ctx);
1334
1335 if let Some(cols) = &stmt.columns {
1337 ctx.paren_open();
1338 self.pg_comma_idents(cols, ctx);
1339 ctx.paren_close();
1340 }
1341
1342 if let Some(overriding) = &stmt.overriding {
1344 ctx.keyword(match overriding {
1345 OverridingKind::System => "OVERRIDING SYSTEM VALUE",
1346 OverridingKind::User => "OVERRIDING USER VALUE",
1347 });
1348 }
1349
1350 match &stmt.source {
1352 InsertSource::Values(rows) => {
1353 ctx.keyword("VALUES");
1354 for (i, row) in rows.iter().enumerate() {
1355 if i > 0 {
1356 ctx.comma();
1357 }
1358 ctx.paren_open();
1359 for (j, expr) in row.iter().enumerate() {
1360 if j > 0 {
1361 ctx.comma();
1362 }
1363 self.render_expr(expr, ctx)?;
1364 }
1365 ctx.paren_close();
1366 }
1367 }
1368 InsertSource::Select(query) => {
1369 self.render_query(query, ctx)?;
1370 }
1371 InsertSource::DefaultValues => {
1372 ctx.keyword("DEFAULT VALUES");
1373 }
1374 }
1375
1376 if let Some(conflicts) = &stmt.on_conflict {
1378 for oc in conflicts {
1379 self.render_on_conflict(oc, ctx)?;
1380 }
1381 }
1382
1383 if let Some(returning) = &stmt.returning {
1385 self.render_returning(returning, ctx)?;
1386 }
1387
1388 Ok(())
1389 }
1390
1391 fn render_update(&self, stmt: &UpdateStmt, ctx: &mut RenderCtx) -> RenderResult<()> {
1392 if let Some(ctes) = &stmt.ctes {
1394 self.pg_render_ctes(ctes, ctx)?;
1395 }
1396
1397 ctx.keyword("UPDATE");
1398
1399 if stmt.only {
1401 ctx.keyword("ONLY");
1402 }
1403
1404 self.pg_schema_ref(&stmt.table, ctx);
1405
1406 if let Some(alias) = &stmt.table.alias {
1408 ctx.keyword("AS").ident(alias);
1409 }
1410
1411 ctx.keyword("SET");
1413 for (i, (col, expr)) in stmt.assignments.iter().enumerate() {
1414 if i > 0 {
1415 ctx.comma();
1416 }
1417 ctx.ident(col).write(" = ");
1418 self.render_expr(expr, ctx)?;
1419 }
1420
1421 if let Some(from) = &stmt.from {
1423 ctx.keyword("FROM");
1424 for (i, source) in from.iter().enumerate() {
1425 if i > 0 {
1426 ctx.comma();
1427 }
1428 self.render_from(source, ctx)?;
1429 }
1430 }
1431
1432 if let Some(cond) = &stmt.where_clause {
1434 ctx.keyword("WHERE");
1435 self.render_condition(cond, ctx)?;
1436 }
1437
1438 if let Some(returning) = &stmt.returning {
1440 self.render_returning(returning, ctx)?;
1441 }
1442
1443 Ok(())
1444 }
1445
1446 fn render_delete(&self, stmt: &DeleteStmt, ctx: &mut RenderCtx) -> RenderResult<()> {
1447 if let Some(ctes) = &stmt.ctes {
1449 self.pg_render_ctes(ctes, ctx)?;
1450 }
1451
1452 ctx.keyword("DELETE FROM");
1453
1454 if stmt.only {
1456 ctx.keyword("ONLY");
1457 }
1458
1459 self.pg_schema_ref(&stmt.table, ctx);
1460
1461 if let Some(alias) = &stmt.table.alias {
1463 ctx.keyword("AS").ident(alias);
1464 }
1465
1466 if let Some(using) = &stmt.using {
1468 ctx.keyword("USING");
1469 for (i, source) in using.iter().enumerate() {
1470 if i > 0 {
1471 ctx.comma();
1472 }
1473 self.render_from(source, ctx)?;
1474 }
1475 }
1476
1477 if let Some(cond) = &stmt.where_clause {
1479 ctx.keyword("WHERE");
1480 self.render_condition(cond, ctx)?;
1481 }
1482
1483 if let Some(returning) = &stmt.returning {
1485 self.render_returning(returning, ctx)?;
1486 }
1487
1488 Ok(())
1489 }
1490
1491 fn render_on_conflict(&self, oc: &OnConflictDef, ctx: &mut RenderCtx) -> RenderResult<()> {
1492 ctx.keyword("ON CONFLICT");
1493
1494 if let Some(target) = &oc.target {
1496 match target {
1497 ConflictTarget::Columns {
1498 columns,
1499 where_clause,
1500 } => {
1501 ctx.paren_open();
1502 self.pg_comma_idents(columns, ctx);
1503 ctx.paren_close();
1504 if let Some(cond) = where_clause {
1505 ctx.keyword("WHERE");
1506 self.render_condition(cond, ctx)?;
1507 }
1508 }
1509 ConflictTarget::Constraint(name) => {
1510 ctx.keyword("ON CONSTRAINT").ident(name);
1511 }
1512 }
1513 }
1514
1515 match &oc.action {
1517 ConflictAction::DoNothing => {
1518 ctx.keyword("DO NOTHING");
1519 }
1520 ConflictAction::DoUpdate {
1521 assignments,
1522 where_clause,
1523 } => {
1524 ctx.keyword("DO UPDATE SET");
1525 for (i, (col, expr)) in assignments.iter().enumerate() {
1526 if i > 0 {
1527 ctx.comma();
1528 }
1529 ctx.ident(col).write(" = ");
1530 self.render_expr(expr, ctx)?;
1531 }
1532 if let Some(cond) = where_clause {
1533 ctx.keyword("WHERE");
1534 self.render_condition(cond, ctx)?;
1535 }
1536 }
1537 }
1538
1539 Ok(())
1540 }
1541
1542 fn render_returning(&self, cols: &[SelectColumn], ctx: &mut RenderCtx) -> RenderResult<()> {
1543 ctx.keyword("RETURNING");
1544 for (i, col) in cols.iter().enumerate() {
1545 if i > 0 {
1546 ctx.comma();
1547 }
1548 match col {
1549 SelectColumn::Star(None) => {
1550 ctx.keyword("*");
1551 }
1552 SelectColumn::Star(Some(table)) => {
1553 ctx.ident(table).operator(".").keyword("*");
1554 }
1555 SelectColumn::Expr { expr, alias } => {
1556 self.render_expr(expr, ctx)?;
1557 if let Some(a) = alias {
1558 ctx.keyword("AS").ident(a);
1559 }
1560 }
1561 SelectColumn::Field { field, alias } => {
1562 self.pg_field_ref(field, ctx);
1563 if let Some(a) = alias {
1564 ctx.keyword("AS").ident(a);
1565 }
1566 }
1567 }
1568 }
1569 Ok(())
1570 }
1571
1572 fn render_transaction(&self, stmt: &TransactionStmt, ctx: &mut RenderCtx) -> RenderResult<()> {
1575 match stmt {
1576 TransactionStmt::Begin(s) => self.pg_begin(s, ctx),
1577 TransactionStmt::Commit(s) => self.pg_commit(s, ctx),
1578 TransactionStmt::Rollback(s) => self.pg_rollback(s, ctx),
1579 TransactionStmt::Savepoint(s) => {
1580 ctx.keyword("SAVEPOINT").ident(&s.name);
1581 Ok(())
1582 }
1583 TransactionStmt::ReleaseSavepoint(s) => {
1584 ctx.keyword("RELEASE").keyword("SAVEPOINT").ident(&s.name);
1585 Ok(())
1586 }
1587 TransactionStmt::SetTransaction(s) => self.pg_set_transaction(s, ctx),
1588 TransactionStmt::LockTable(s) => self.pg_lock_table(s, ctx),
1589 TransactionStmt::PrepareTransaction(s) => {
1590 ctx.keyword("PREPARE")
1591 .keyword("TRANSACTION")
1592 .string_literal(&s.transaction_id);
1593 Ok(())
1594 }
1595 TransactionStmt::CommitPrepared(s) => {
1596 ctx.keyword("COMMIT")
1597 .keyword("PREPARED")
1598 .string_literal(&s.transaction_id);
1599 Ok(())
1600 }
1601 TransactionStmt::RollbackPrepared(s) => {
1602 ctx.keyword("ROLLBACK")
1603 .keyword("PREPARED")
1604 .string_literal(&s.transaction_id);
1605 Ok(())
1606 }
1607 TransactionStmt::Custom(_) => Err(RenderError::unsupported(
1608 "Custom TCL",
1609 "not supported by PostgresRenderer",
1610 )),
1611 }
1612 }
1613}
1614
1615impl PostgresRenderer {
1620 fn pg_begin(&self, stmt: &BeginStmt, ctx: &mut RenderCtx) -> RenderResult<()> {
1623 ctx.keyword("BEGIN");
1624 if let Some(modes) = &stmt.modes {
1625 self.pg_transaction_modes(modes, ctx);
1626 }
1627 Ok(())
1628 }
1629
1630 fn pg_commit(&self, stmt: &CommitStmt, ctx: &mut RenderCtx) -> RenderResult<()> {
1631 ctx.keyword("COMMIT");
1632 if stmt.and_chain {
1633 ctx.keyword("AND").keyword("CHAIN");
1634 }
1635 Ok(())
1636 }
1637
1638 fn pg_rollback(&self, stmt: &RollbackStmt, ctx: &mut RenderCtx) -> RenderResult<()> {
1639 ctx.keyword("ROLLBACK");
1640 if let Some(sp) = &stmt.to_savepoint {
1641 ctx.keyword("TO").keyword("SAVEPOINT").ident(sp);
1642 }
1643 if stmt.and_chain {
1644 ctx.keyword("AND").keyword("CHAIN");
1645 }
1646 Ok(())
1647 }
1648
1649 fn pg_set_transaction(
1650 &self,
1651 stmt: &SetTransactionStmt,
1652 ctx: &mut RenderCtx,
1653 ) -> RenderResult<()> {
1654 ctx.keyword("SET");
1655 match &stmt.scope {
1656 Some(TransactionScope::Session) => {
1657 ctx.keyword("SESSION")
1658 .keyword("CHARACTERISTICS")
1659 .keyword("AS")
1660 .keyword("TRANSACTION");
1661 }
1662 _ => {
1663 ctx.keyword("TRANSACTION");
1664 }
1665 }
1666 if let Some(snap_id) = &stmt.snapshot_id {
1667 ctx.keyword("SNAPSHOT").string_literal(snap_id);
1668 } else {
1669 self.pg_transaction_modes(&stmt.modes, ctx);
1670 }
1671 Ok(())
1672 }
1673
1674 fn pg_transaction_modes(&self, modes: &[TransactionMode], ctx: &mut RenderCtx) {
1675 for (i, mode) in modes.iter().enumerate() {
1676 if i > 0 {
1677 ctx.comma();
1678 }
1679 match mode {
1680 TransactionMode::IsolationLevel(lvl) => {
1681 ctx.keyword("ISOLATION").keyword("LEVEL");
1682 ctx.keyword(match lvl {
1683 IsolationLevel::ReadUncommitted => "READ UNCOMMITTED",
1684 IsolationLevel::ReadCommitted => "READ COMMITTED",
1685 IsolationLevel::RepeatableRead => "REPEATABLE READ",
1686 IsolationLevel::Serializable => "SERIALIZABLE",
1687 IsolationLevel::Snapshot => "SERIALIZABLE", });
1689 }
1690 TransactionMode::ReadOnly => {
1691 ctx.keyword("READ ONLY");
1692 }
1693 TransactionMode::ReadWrite => {
1694 ctx.keyword("READ WRITE");
1695 }
1696 TransactionMode::Deferrable => {
1697 ctx.keyword("DEFERRABLE");
1698 }
1699 TransactionMode::NotDeferrable => {
1700 ctx.keyword("NOT DEFERRABLE");
1701 }
1702 TransactionMode::WithConsistentSnapshot => {} }
1704 }
1705 }
1706
1707 fn pg_lock_table(&self, stmt: &LockTableStmt, ctx: &mut RenderCtx) -> RenderResult<()> {
1708 ctx.keyword("LOCK").keyword("TABLE");
1709 for (i, def) in stmt.tables.iter().enumerate() {
1710 if i > 0 {
1711 ctx.comma();
1712 }
1713 if def.only {
1714 ctx.keyword("ONLY");
1715 }
1716 if let Some(schema) = &def.schema {
1717 ctx.ident(schema).operator(".");
1718 }
1719 ctx.ident(&def.table);
1720 }
1721 if let Some(first) = stmt.tables.first() {
1723 ctx.keyword("IN");
1724 ctx.keyword(match first.mode {
1725 LockMode::AccessShare => "ACCESS SHARE",
1726 LockMode::RowShare => "ROW SHARE",
1727 LockMode::RowExclusive => "ROW EXCLUSIVE",
1728 LockMode::ShareUpdateExclusive => "SHARE UPDATE EXCLUSIVE",
1729 LockMode::Share => "SHARE",
1730 LockMode::ShareRowExclusive => "SHARE ROW EXCLUSIVE",
1731 LockMode::Exclusive => "EXCLUSIVE",
1732 LockMode::AccessExclusive => "ACCESS EXCLUSIVE",
1733 _ => "ACCESS EXCLUSIVE", });
1735 ctx.keyword("MODE");
1736 }
1737 if stmt.nowait {
1738 ctx.keyword("NOWAIT");
1739 }
1740 Ok(())
1741 }
1742
1743 fn pg_schema_ref(&self, schema_ref: &qcraft_core::ast::common::SchemaRef, ctx: &mut RenderCtx) {
1746 if let Some(ns) = &schema_ref.namespace {
1747 ctx.ident(ns).operator(".");
1748 }
1749 ctx.ident(&schema_ref.name);
1750 }
1751
1752 fn pg_field_ref(&self, field_ref: &FieldRef, ctx: &mut RenderCtx) {
1753 ctx.ident(&field_ref.table_name)
1754 .operator(".")
1755 .ident(&field_ref.field.name);
1756 }
1757
1758 fn pg_comma_idents(&self, names: &[String], ctx: &mut RenderCtx) {
1759 for (i, name) in names.iter().enumerate() {
1760 if i > 0 {
1761 ctx.comma();
1762 }
1763 ctx.ident(name);
1764 }
1765 }
1766
1767 fn pg_value(&self, val: &Value, ctx: &mut RenderCtx) -> RenderResult<()> {
1768 if matches!(val, Value::Null) {
1770 ctx.keyword("NULL");
1771 return Ok(());
1772 }
1773
1774 if ctx.parameterize() {
1778 ctx.param(val.clone());
1779 return Ok(());
1780 }
1781
1782 self.pg_value_literal(val, ctx)
1784 }
1785
1786 fn pg_value_literal(&self, val: &Value, ctx: &mut RenderCtx) -> RenderResult<()> {
1787 match val {
1788 Value::Null => {
1789 ctx.keyword("NULL");
1790 }
1791 Value::Bool(b) => {
1792 ctx.keyword(if *b { "TRUE" } else { "FALSE" });
1793 }
1794 Value::Int(n) => {
1795 ctx.keyword(&n.to_string());
1796 }
1797 Value::Float(f) => {
1798 ctx.keyword(&f.to_string());
1799 }
1800 Value::Str(s) => {
1801 ctx.string_literal(s);
1802 }
1803 Value::Bytes(b) => {
1804 ctx.write("'\\x");
1805 for byte in b {
1806 ctx.write(&format!("{byte:02x}"));
1807 }
1808 ctx.write("'");
1809 }
1810 Value::Date(s) | Value::DateTime(s) | Value::Time(s) => {
1811 ctx.string_literal(s);
1812 }
1813 Value::Decimal(s) => {
1814 ctx.keyword(s);
1815 }
1816 Value::Uuid(s) => {
1817 ctx.string_literal(s);
1818 }
1819 Value::Json(s) => {
1820 ctx.string_literal(s);
1821 ctx.write("::json");
1822 }
1823 Value::Jsonb(s) => {
1824 ctx.string_literal(s);
1825 ctx.write("::jsonb");
1826 }
1827 Value::IpNetwork(s) => {
1828 ctx.string_literal(s);
1829 ctx.write("::inet");
1830 }
1831 Value::Array(items) => {
1832 ctx.keyword("ARRAY").write("[");
1833 for (i, item) in items.iter().enumerate() {
1834 if i > 0 {
1835 ctx.comma();
1836 }
1837 self.pg_value_literal(item, ctx)?;
1838 }
1839 ctx.write("]");
1840 }
1841 Value::Vector(values) => {
1842 let parts: Vec<String> = values.iter().map(|v| v.to_string()).collect();
1843 let literal = format!("[{}]", parts.join(","));
1844 ctx.string_literal(&literal);
1845 ctx.write("::vector");
1846 }
1847 Value::TimeDelta {
1848 years,
1849 months,
1850 days,
1851 seconds,
1852 microseconds,
1853 } => {
1854 ctx.keyword("INTERVAL");
1855 let mut parts = Vec::new();
1856 if *years != 0 {
1857 parts.push(format!("{years} years"));
1858 }
1859 if *months != 0 {
1860 parts.push(format!("{months} months"));
1861 }
1862 if *days != 0 {
1863 parts.push(format!("{days} days"));
1864 }
1865 if *seconds != 0 {
1866 parts.push(format!("{seconds} seconds"));
1867 }
1868 if *microseconds != 0 {
1869 parts.push(format!("{microseconds} microseconds"));
1870 }
1871 if parts.is_empty() {
1872 parts.push("0 seconds".into());
1873 }
1874 ctx.string_literal(&parts.join(" "));
1875 }
1876 }
1877 Ok(())
1878 }
1879
1880 fn pg_referential_action(&self, action: &ReferentialAction, ctx: &mut RenderCtx) {
1881 match action {
1882 ReferentialAction::NoAction => {
1883 ctx.keyword("NO ACTION");
1884 }
1885 ReferentialAction::Restrict => {
1886 ctx.keyword("RESTRICT");
1887 }
1888 ReferentialAction::Cascade => {
1889 ctx.keyword("CASCADE");
1890 }
1891 ReferentialAction::SetNull(cols) => {
1892 ctx.keyword("SET NULL");
1893 if let Some(cols) = cols {
1894 ctx.paren_open();
1895 self.pg_comma_idents(cols, ctx);
1896 ctx.paren_close();
1897 }
1898 }
1899 ReferentialAction::SetDefault(cols) => {
1900 ctx.keyword("SET DEFAULT");
1901 if let Some(cols) = cols {
1902 ctx.paren_open();
1903 self.pg_comma_idents(cols, ctx);
1904 ctx.paren_close();
1905 }
1906 }
1907 }
1908 }
1909
1910 fn pg_deferrable(&self, def: &DeferrableConstraint, ctx: &mut RenderCtx) {
1911 if def.deferrable {
1912 ctx.keyword("DEFERRABLE");
1913 } else {
1914 ctx.keyword("NOT DEFERRABLE");
1915 }
1916 if def.initially_deferred {
1917 ctx.keyword("INITIALLY DEFERRED");
1918 } else {
1919 ctx.keyword("INITIALLY IMMEDIATE");
1920 }
1921 }
1922
1923 fn pg_identity(&self, identity: &IdentityColumn, ctx: &mut RenderCtx) {
1924 if identity.always {
1925 ctx.keyword("GENERATED ALWAYS AS IDENTITY");
1926 } else {
1927 ctx.keyword("GENERATED BY DEFAULT AS IDENTITY");
1928 }
1929 let has_options = identity.start.is_some()
1930 || identity.increment.is_some()
1931 || identity.min_value.is_some()
1932 || identity.max_value.is_some()
1933 || identity.cycle
1934 || identity.cache.is_some();
1935 if has_options {
1936 ctx.paren_open();
1937 if let Some(start) = identity.start {
1938 ctx.keyword("START WITH").keyword(&start.to_string());
1939 }
1940 if let Some(inc) = identity.increment {
1941 ctx.keyword("INCREMENT BY").keyword(&inc.to_string());
1942 }
1943 if let Some(min) = identity.min_value {
1944 ctx.keyword("MINVALUE").keyword(&min.to_string());
1945 }
1946 if let Some(max) = identity.max_value {
1947 ctx.keyword("MAXVALUE").keyword(&max.to_string());
1948 }
1949 if identity.cycle {
1950 ctx.keyword("CYCLE");
1951 }
1952 if let Some(cache) = identity.cache {
1953 ctx.keyword("CACHE").write(&cache.to_string());
1954 }
1955 ctx.paren_close();
1956 }
1957 }
1958
1959 fn pg_render_ctes(&self, ctes: &[CteDef], ctx: &mut RenderCtx) -> RenderResult<()> {
1960 self.render_ctes(ctes, ctx)
1962 }
1963
1964 fn pg_render_from_item(&self, item: &FromItem, ctx: &mut RenderCtx) -> RenderResult<()> {
1965 if item.only {
1966 ctx.keyword("ONLY");
1967 }
1968 self.render_from(&item.source, ctx)?;
1969 if let Some(sample) = &item.sample {
1970 ctx.keyword("TABLESAMPLE");
1971 ctx.keyword(match sample.method {
1972 SampleMethod::Bernoulli => "BERNOULLI",
1973 SampleMethod::System => "SYSTEM",
1974 SampleMethod::Block => "SYSTEM", });
1976 ctx.paren_open()
1977 .write(&sample.percentage.to_string())
1978 .paren_close();
1979 if let Some(seed) = sample.seed {
1980 ctx.keyword("REPEATABLE")
1981 .paren_open()
1982 .write(&seed.to_string())
1983 .paren_close();
1984 }
1985 }
1986 Ok(())
1987 }
1988
1989 fn pg_render_group_by(&self, items: &[GroupByItem], ctx: &mut RenderCtx) -> RenderResult<()> {
1990 ctx.keyword("GROUP BY");
1991 for (i, item) in items.iter().enumerate() {
1992 if i > 0 {
1993 ctx.comma();
1994 }
1995 match item {
1996 GroupByItem::Expr(expr) => {
1997 self.render_expr(expr, ctx)?;
1998 }
1999 GroupByItem::Rollup(exprs) => {
2000 ctx.keyword("ROLLUP").paren_open();
2001 for (j, expr) in exprs.iter().enumerate() {
2002 if j > 0 {
2003 ctx.comma();
2004 }
2005 self.render_expr(expr, ctx)?;
2006 }
2007 ctx.paren_close();
2008 }
2009 GroupByItem::Cube(exprs) => {
2010 ctx.keyword("CUBE").paren_open();
2011 for (j, expr) in exprs.iter().enumerate() {
2012 if j > 0 {
2013 ctx.comma();
2014 }
2015 self.render_expr(expr, ctx)?;
2016 }
2017 ctx.paren_close();
2018 }
2019 GroupByItem::GroupingSets(sets) => {
2020 ctx.keyword("GROUPING SETS").paren_open();
2021 for (j, set) in sets.iter().enumerate() {
2022 if j > 0 {
2023 ctx.comma();
2024 }
2025 ctx.paren_open();
2026 for (k, expr) in set.iter().enumerate() {
2027 if k > 0 {
2028 ctx.comma();
2029 }
2030 self.render_expr(expr, ctx)?;
2031 }
2032 ctx.paren_close();
2033 }
2034 ctx.paren_close();
2035 }
2036 }
2037 }
2038 Ok(())
2039 }
2040
2041 fn pg_render_window_clause(
2042 &self,
2043 windows: &[WindowNameDef],
2044 ctx: &mut RenderCtx,
2045 ) -> RenderResult<()> {
2046 ctx.keyword("WINDOW");
2047 for (i, win) in windows.iter().enumerate() {
2048 if i > 0 {
2049 ctx.comma();
2050 }
2051 ctx.ident(&win.name).keyword("AS").paren_open();
2052 if let Some(base) = &win.base_window {
2053 ctx.ident(base);
2054 }
2055 if let Some(partition_by) = &win.partition_by {
2056 ctx.keyword("PARTITION BY");
2057 for (j, expr) in partition_by.iter().enumerate() {
2058 if j > 0 {
2059 ctx.comma();
2060 }
2061 self.render_expr(expr, ctx)?;
2062 }
2063 }
2064 if let Some(order_by) = &win.order_by {
2065 ctx.keyword("ORDER BY");
2066 self.pg_order_by_list(order_by, ctx)?;
2067 }
2068 if let Some(frame) = &win.frame {
2069 self.pg_window_frame(frame, ctx);
2070 }
2071 ctx.paren_close();
2072 }
2073 Ok(())
2074 }
2075
2076 fn pg_render_set_op(&self, set_op: &SetOpDef, ctx: &mut RenderCtx) -> RenderResult<()> {
2077 self.render_query(&set_op.left, ctx)?;
2078 ctx.keyword(match set_op.operation {
2079 SetOperationType::Union => "UNION",
2080 SetOperationType::UnionAll => "UNION ALL",
2081 SetOperationType::Intersect => "INTERSECT",
2082 SetOperationType::IntersectAll => "INTERSECT ALL",
2083 SetOperationType::Except => "EXCEPT",
2084 SetOperationType::ExceptAll => "EXCEPT ALL",
2085 });
2086 self.render_query(&set_op.right, ctx)
2087 }
2088
2089 fn pg_create_table(
2090 &self,
2091 schema: &SchemaDef,
2092 if_not_exists: bool,
2093 temporary: bool,
2094 unlogged: bool,
2095 opts: &PgCreateTableOpts<'_>,
2096 ctx: &mut RenderCtx,
2097 ) -> RenderResult<()> {
2098 let PgCreateTableOpts {
2099 tablespace,
2100 partition_by,
2101 inherits,
2102 using_method,
2103 with_options,
2104 on_commit,
2105 } = opts;
2106 ctx.keyword("CREATE");
2107 if temporary {
2108 ctx.keyword("TEMPORARY");
2109 }
2110 if unlogged {
2111 ctx.keyword("UNLOGGED");
2112 }
2113 ctx.keyword("TABLE");
2114 if if_not_exists {
2115 ctx.keyword("IF NOT EXISTS");
2116 }
2117 if let Some(ns) = &schema.namespace {
2118 ctx.ident(ns).operator(".");
2119 }
2120 ctx.ident(&schema.name);
2121
2122 ctx.paren_open();
2124 let mut first = true;
2125 for col in &schema.columns {
2126 if !first {
2127 ctx.comma();
2128 }
2129 first = false;
2130 self.render_column_def(col, ctx)?;
2131 }
2132 if let Some(like_tables) = &schema.like_tables {
2133 for like in like_tables {
2134 if !first {
2135 ctx.comma();
2136 }
2137 first = false;
2138 self.pg_like_table(like, ctx);
2139 }
2140 }
2141 if let Some(constraints) = &schema.constraints {
2142 for constraint in constraints {
2143 if !first {
2144 ctx.comma();
2145 }
2146 first = false;
2147 self.render_constraint(constraint, ctx)?;
2148 }
2149 }
2150 ctx.paren_close();
2151
2152 if let Some(parents) = inherits {
2154 ctx.keyword("INHERITS").paren_open();
2155 for (i, parent) in parents.iter().enumerate() {
2156 if i > 0 {
2157 ctx.comma();
2158 }
2159 self.pg_schema_ref(parent, ctx);
2160 }
2161 ctx.paren_close();
2162 }
2163
2164 if let Some(part) = partition_by {
2166 ctx.keyword("PARTITION BY");
2167 ctx.keyword(match part.strategy {
2168 PartitionStrategy::Range => "RANGE",
2169 PartitionStrategy::List => "LIST",
2170 PartitionStrategy::Hash => "HASH",
2171 });
2172 ctx.paren_open();
2173 for (i, col) in part.columns.iter().enumerate() {
2174 if i > 0 {
2175 ctx.comma();
2176 }
2177 match &col.expr {
2178 IndexExpr::Column(name) => {
2179 ctx.ident(name);
2180 }
2181 IndexExpr::Expression(expr) => {
2182 ctx.paren_open();
2183 self.render_expr(expr, ctx)?;
2184 ctx.paren_close();
2185 }
2186 }
2187 if let Some(collation) = &col.collation {
2188 ctx.keyword("COLLATE").ident(collation);
2189 }
2190 if let Some(opclass) = &col.opclass {
2191 ctx.keyword(opclass);
2192 }
2193 }
2194 ctx.paren_close();
2195 }
2196
2197 if let Some(method) = using_method {
2199 ctx.keyword("USING").keyword(method);
2200 }
2201
2202 if let Some(opts) = with_options {
2204 ctx.keyword("WITH").paren_open();
2205 for (i, (key, value)) in opts.iter().enumerate() {
2206 if i > 0 {
2207 ctx.comma();
2208 }
2209 ctx.write(key).write(" = ").write(value);
2210 }
2211 ctx.paren_close();
2212 }
2213
2214 if let Some(action) = on_commit {
2216 ctx.keyword("ON COMMIT");
2217 ctx.keyword(match action {
2218 OnCommitAction::PreserveRows => "PRESERVE ROWS",
2219 OnCommitAction::DeleteRows => "DELETE ROWS",
2220 OnCommitAction::Drop => "DROP",
2221 });
2222 }
2223
2224 if let Some(ts) = tablespace {
2226 ctx.keyword("TABLESPACE").ident(ts);
2227 }
2228
2229 Ok(())
2230 }
2231
2232 fn pg_like_table(&self, like: &LikeTableDef, ctx: &mut RenderCtx) {
2233 ctx.keyword("LIKE");
2234 self.pg_schema_ref(&like.source_table, ctx);
2235 for opt in &like.options {
2236 if opt.include {
2237 ctx.keyword("INCLUDING");
2238 } else {
2239 ctx.keyword("EXCLUDING");
2240 }
2241 ctx.keyword(match opt.kind {
2242 qcraft_core::ast::ddl::LikeOptionKind::Comments => "COMMENTS",
2243 qcraft_core::ast::ddl::LikeOptionKind::Compression => "COMPRESSION",
2244 qcraft_core::ast::ddl::LikeOptionKind::Constraints => "CONSTRAINTS",
2245 qcraft_core::ast::ddl::LikeOptionKind::Defaults => "DEFAULTS",
2246 qcraft_core::ast::ddl::LikeOptionKind::Generated => "GENERATED",
2247 qcraft_core::ast::ddl::LikeOptionKind::Identity => "IDENTITY",
2248 qcraft_core::ast::ddl::LikeOptionKind::Indexes => "INDEXES",
2249 qcraft_core::ast::ddl::LikeOptionKind::Statistics => "STATISTICS",
2250 qcraft_core::ast::ddl::LikeOptionKind::Storage => "STORAGE",
2251 qcraft_core::ast::ddl::LikeOptionKind::All => "ALL",
2252 });
2253 }
2254 }
2255
2256 fn pg_create_index(
2257 &self,
2258 schema_ref: &qcraft_core::ast::common::SchemaRef,
2259 index: &IndexDef,
2260 if_not_exists: bool,
2261 concurrently: bool,
2262 ctx: &mut RenderCtx,
2263 ) -> RenderResult<()> {
2264 ctx.keyword("CREATE");
2265 if index.unique {
2266 ctx.keyword("UNIQUE");
2267 }
2268 ctx.keyword("INDEX");
2269 if concurrently {
2270 ctx.keyword("CONCURRENTLY");
2271 }
2272 if if_not_exists {
2273 ctx.keyword("IF NOT EXISTS");
2274 }
2275 ctx.ident(&index.name).keyword("ON");
2276 self.pg_schema_ref(schema_ref, ctx);
2277
2278 if let Some(index_type) = &index.index_type {
2279 ctx.keyword("USING").keyword(index_type);
2280 }
2281
2282 ctx.paren_open();
2283 self.pg_index_columns(&index.columns, ctx)?;
2284 ctx.paren_close();
2285
2286 if let Some(include) = &index.include {
2287 ctx.keyword("INCLUDE").paren_open();
2288 self.pg_comma_idents(include, ctx);
2289 ctx.paren_close();
2290 }
2291
2292 if let Some(nd) = index.nulls_distinct {
2293 if !nd {
2294 ctx.keyword("NULLS NOT DISTINCT");
2295 }
2296 }
2297
2298 if let Some(params) = &index.parameters {
2299 ctx.keyword("WITH").paren_open();
2300 for (i, (key, value)) in params.iter().enumerate() {
2301 if i > 0 {
2302 ctx.comma();
2303 }
2304 ctx.write(key).write(" = ").write(value);
2305 }
2306 ctx.paren_close();
2307 }
2308
2309 if let Some(ts) = &index.tablespace {
2310 ctx.keyword("TABLESPACE").ident(ts);
2311 }
2312
2313 if let Some(condition) = &index.condition {
2314 ctx.keyword("WHERE");
2315 self.render_condition(condition, ctx)?;
2316 }
2317
2318 Ok(())
2319 }
2320
2321 fn pg_index_columns(
2322 &self,
2323 columns: &[IndexColumnDef],
2324 ctx: &mut RenderCtx,
2325 ) -> RenderResult<()> {
2326 for (i, col) in columns.iter().enumerate() {
2327 if i > 0 {
2328 ctx.comma();
2329 }
2330 match &col.expr {
2331 IndexExpr::Column(name) => {
2332 ctx.ident(name);
2333 }
2334 IndexExpr::Expression(expr) => {
2335 ctx.paren_open();
2336 self.render_expr(expr, ctx)?;
2337 ctx.paren_close();
2338 }
2339 }
2340 if let Some(collation) = &col.collation {
2341 ctx.keyword("COLLATE").ident(collation);
2342 }
2343 if let Some(opclass) = &col.opclass {
2344 ctx.keyword(opclass);
2345 }
2346 if let Some(dir) = col.direction {
2347 ctx.keyword(match dir {
2348 OrderDir::Asc => "ASC",
2349 OrderDir::Desc => "DESC",
2350 });
2351 }
2352 if let Some(nulls) = col.nulls {
2353 ctx.keyword(match nulls {
2354 NullsOrder::First => "NULLS FIRST",
2355 NullsOrder::Last => "NULLS LAST",
2356 });
2357 }
2358 }
2359 Ok(())
2360 }
2361
2362 fn pg_order_by_list(&self, order_by: &[OrderByDef], ctx: &mut RenderCtx) -> RenderResult<()> {
2363 for (i, ob) in order_by.iter().enumerate() {
2364 if i > 0 {
2365 ctx.comma();
2366 }
2367 self.render_expr(&ob.expr, ctx)?;
2368 ctx.keyword(match ob.direction {
2369 OrderDir::Asc => "ASC",
2370 OrderDir::Desc => "DESC",
2371 });
2372 if let Some(nulls) = &ob.nulls {
2373 ctx.keyword(match nulls {
2374 NullsOrder::First => "NULLS FIRST",
2375 NullsOrder::Last => "NULLS LAST",
2376 });
2377 }
2378 }
2379 Ok(())
2380 }
2381
2382 fn pg_window_frame(&self, frame: &WindowFrameDef, ctx: &mut RenderCtx) {
2383 ctx.keyword(match frame.frame_type {
2384 WindowFrameType::Rows => "ROWS",
2385 WindowFrameType::Range => "RANGE",
2386 WindowFrameType::Groups => "GROUPS",
2387 });
2388 if let Some(end) = &frame.end {
2389 ctx.keyword("BETWEEN");
2390 self.pg_frame_bound(&frame.start, ctx);
2391 ctx.keyword("AND");
2392 self.pg_frame_bound(end, ctx);
2393 } else {
2394 self.pg_frame_bound(&frame.start, ctx);
2395 }
2396 }
2397
2398 fn pg_frame_bound(&self, bound: &WindowFrameBound, ctx: &mut RenderCtx) {
2399 match bound {
2400 WindowFrameBound::CurrentRow => {
2401 ctx.keyword("CURRENT ROW");
2402 }
2403 WindowFrameBound::Preceding(None) => {
2404 ctx.keyword("UNBOUNDED PRECEDING");
2405 }
2406 WindowFrameBound::Preceding(Some(n)) => {
2407 ctx.keyword(&n.to_string()).keyword("PRECEDING");
2408 }
2409 WindowFrameBound::Following(None) => {
2410 ctx.keyword("UNBOUNDED FOLLOWING");
2411 }
2412 WindowFrameBound::Following(Some(n)) => {
2413 ctx.keyword(&n.to_string()).keyword("FOLLOWING");
2414 }
2415 }
2416 }
2417}