Skip to main content

qcraft_sqlite/
lib.rs

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