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