Skip to main content

sql_builder/backend/sqlite/
query.rs

1use super::*;
2
3impl QueryBuilder for SqliteQueryBuilder {
4    fn lexer_dialect(&self) -> crate::lexer::Dialect {
5        crate::lexer::Dialect::Sqlite
6    }
7
8    fn prepare_expr(
9        &self,
10        simple_expr: &Expr,
11        sql: &mut impl SqlWriter,
12    ) -> Result<(), RenderError> {
13        if matches!(simple_expr, Expr::Keyword(Keyword::Default)) {
14            return Err(RenderError::Unsupported(
15                "SQLite has no DEFAULT value; leave the column out of the INSERT".into(),
16            ));
17        }
18        expressions::prepare_expr_common(self, simple_expr, sql)
19    }
20
21    fn prepare_function_name(
22        &self,
23        function: &Func,
24        sql: &mut impl SqlWriter,
25    ) -> Result<(), RenderError> {
26        if matches!(function, Func::BitAnd | Func::BitOr | Func::Md5) {
27            return Err(RenderError::Unsupported(
28                "SQLite has no BIT_AND, BIT_OR or MD5; call an extension's through Func::cust"
29                    .into(),
30            ));
31        }
32        functions::prepare_function_name_common(self, function, sql)
33    }
34
35    fn prepare_select_lock(
36        &self,
37        _select_lock: &LockClause,
38        _sql: &mut impl SqlWriter,
39    ) -> Result<(), RenderError> {
40        // SQLite doesn't supports row locking
41        Ok(())
42    }
43
44    fn prepare_select_into(
45        &self,
46        _: &SelectInto,
47        _: &mut impl SqlWriter,
48    ) -> Result<(), RenderError> {
49        Err(RenderError::Unsupported(
50            "SQLite has no SELECT INTO a table".into(),
51        ))
52    }
53
54    // Only a SQLite compiled with SQLITE_ENABLE_UPDATE_DELETE_LIMIT parses
55    // them, and the bundled one is not.
56    fn prepare_mutation_order_limit(
57        &self,
58        orders: &[OrderExpr],
59        limit: &Option<Value>,
60        _: &mut impl SqlWriter,
61    ) -> Result<(), RenderError> {
62        if orders.is_empty() && limit.is_none() {
63            return Ok(());
64        }
65        Err(RenderError::Unsupported(
66            "SQLite has no ORDER BY or LIMIT in UPDATE or DELETE; scope it with a key subquery"
67                .into(),
68        ))
69    }
70
71    fn prepare_on_conflict_target(
72        &self,
73        targets: &OnConflictTarget,
74        sql: &mut impl SqlWriter,
75    ) -> Result<(), RenderError> {
76        if let OnConflictTarget::Constraint(_) = targets {
77            return Err(RenderError::Unsupported(
78                "SQLite has no ON CONFLICT ON CONSTRAINT; name the columns".into(),
79            ));
80        }
81        conflict::prepare_on_conflict_target(self, targets, sql)
82    }
83
84    fn prepare_sub_query_oper(
85        &self,
86        oper: &SubQueryOper,
87        sql: &mut impl SqlWriter,
88    ) -> Result<(), RenderError> {
89        sql.write_str(match oper {
90            SubQueryOper::Exists => "EXISTS",
91            SubQueryOper::Any => {
92                return Err(RenderError::Unsupported(
93                    "SQLite has no ANY subquery operator".into(),
94                ));
95            }
96            SubQueryOper::Some => {
97                return Err(RenderError::Unsupported(
98                    "SQLite has no SOME subquery operator".into(),
99                ));
100            }
101            SubQueryOper::All => {
102                return Err(RenderError::Unsupported(
103                    "SQLite has no ALL subquery operator".into(),
104                ));
105            }
106        })
107        .unwrap();
108        Ok(())
109    }
110
111    fn prepare_bin_oper(
112        &self,
113        bin_oper: &BinOper,
114        sql: &mut impl SqlWriter,
115    ) -> Result<(), RenderError> {
116        match bin_oper {
117            BinOper::SqliteOperator(oper) => sql.write_str(oper.sql()).unwrap(),
118            _ => expressions::prepare_bin_oper_common(self, bin_oper, sql)?,
119        }
120        Ok(())
121    }
122
123    fn prepare_union_statement(
124        &self,
125        union_type: UnionType,
126        select_statement: &SelectStatement,
127        sql: &mut impl SqlWriter,
128    ) -> Result<(), RenderError> {
129        match union_type {
130            UnionType::Intersect => sql.write_str(" INTERSECT ").unwrap(),
131            UnionType::Distinct => sql.write_str(" UNION ").unwrap(),
132            UnionType::Except => sql.write_str(" EXCEPT ").unwrap(),
133            UnionType::All => sql.write_str(" UNION ALL ").unwrap(),
134        }
135        // An operand is a bare select core here, so one with an ordering,
136        // paging, operands or CTEs of its own is read through a derived table.
137        if select_statement.orders.is_empty()
138            && select_statement.limit.is_none()
139            && select_statement.offset.is_none()
140            && select_statement.unions.is_empty()
141            && select_statement.with.is_none()
142        {
143            return statements::prepare_select_statement(self, select_statement, sql);
144        }
145        let mut derived = SelectStatement::new();
146        derived
147            .column(Asterisk)
148            .from_subquery(select_statement.clone(), "tideorm_union_operand");
149        statements::prepare_select_statement(self, &derived, sql)
150    }
151
152    fn prepare_select_limit_offset(
153        &self,
154        select: &SelectStatement,
155        sql: &mut impl SqlWriter,
156    ) -> Result<(), RenderError> {
157        prepare_limit_offset(self, select, SqlDialect::open_limit(self), sql)
158    }
159
160    fn greatest_function(&self) -> &str {
161        "MAX"
162    }
163
164    fn least_function(&self) -> &str {
165        "MIN"
166    }
167
168    fn char_length_function(&self) -> &str {
169        "LENGTH"
170    }
171
172    fn insert_default_values(
173        &self,
174        num_rows: usize,
175        sql: &mut impl SqlWriter,
176    ) -> Result<(), RenderError> {
177        // `DEFAULT VALUES` inserts one row. More name the rowid, which SQLite
178        // numbers when it is NULL, so every declared column takes its default;
179        // a `WITHOUT ROWID` table has no rowid to name.
180        if num_rows <= 1 {
181            sql.write_str("DEFAULT VALUES").unwrap();
182            return Ok(());
183        }
184        sql.write_str("(rowid) VALUES (NULL)").unwrap();
185        for _ in 1..num_rows {
186            sql.write_str(", (NULL)").unwrap();
187        }
188        Ok(())
189    }
190}