navree-orm 1.2.2

Navree ORM: active-record models, a typed query builder, dirty tracking and pagination on PostgreSQL/TimescaleDB, MySQL and SQLite.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
//! The ORM's IR ([`crate::ir`]) as [syntax trees](super::ast), with the
//! dialect rules of each database (date parts, LIKE variants, JSON paths
//! and containment, full text, upserts, group limits, time buckets, vector
//! distances, the MySQL timeout hint). The `render_*` functions lower and
//! render in one step; they write every statement the ORM runs.
//!
//! [`Where::Raw`](crate::ir::Where::Raw) (portable SQL with `?`
//! placeholders, such as a navree-db `Statement::portable` fragment) is
//! embedded as a parenthesized fragment;
//! [`Where::Tree`](crate::ir::Where::Tree) is a render-tree condition,
//! embedded as it is.
//!
//! ```
//! use navree_orm::Dialect;
//! use navree_orm::ir::QueryIr;
//! use navree_orm::render::render_select;
//!
//! let mut query = QueryIr::new("deals");
//! query.limit = Some(10);
//! query.offset = Some(20);
//! assert_eq!(
//!     render_select(&query, Dialect::Sqlite).unwrap().sql,
//!     r#"SELECT * FROM "deals" LIMIT ? OFFSET ?"#
//! );
//! ```

use std::borrow::Cow;

use super::ast;
use super::grammar::{is_identifier, json_path_text};
use crate::error::{OrmError, Result};
use crate::ir::{
    AggregateFunction, ArithmeticOp, ColumnRef, Direction, Expr, JsonSegment, Nulls, Order,
    VectorMetric,
};
use crate::sql::{Dialect, Statement, Syntax};
use crate::value::Value;

mod filter;
mod select;
mod text;
mod timescale;
mod write;

pub(crate) use select::timeout_millis;
pub use select::{aggregate, exists, select};
pub use write::{delete, insert, truncate, update, update_from};

/// The SQL of a read query.
pub fn render_select(query: &crate::ir::QueryIr, syntax: impl Into<Syntax>) -> Result<Statement> {
    let syntax = syntax.into();
    super::render_query(&select(query, syntax)?, syntax)
}

/// The SQL of an aggregate over a query's rows, in a column named
/// `aggregate`. Queries with groups, `HAVING`, `DISTINCT`, unions, a limit
/// or an offset are aggregated as a subquery, so the result counts what the
/// query returns; others replace the select list (and drop the order).
pub fn render_aggregate(
    query: &crate::ir::QueryIr,
    aggregate: &crate::ir::Aggregate,
    syntax: impl Into<Syntax>,
) -> Result<Statement> {
    let syntax = syntax.into();
    super::render_query(&select::aggregate(query, aggregate, syntax)?, syntax)
}

/// `SELECT EXISTS(query) AS "exists"`.
pub fn render_exists(query: &crate::ir::QueryIr, syntax: impl Into<Syntax>) -> Result<Statement> {
    let syntax = syntax.into();
    super::render_query(&select::exists(query, syntax)?, syntax)
}

/// The SQL of an insert (`RETURNING` on PostgreSQL and SQLite only; MySQL reads
/// `last_insert_id`).
///
/// ```
/// use navree_orm::Value;
/// use navree_orm::ir::{Expr, InsertIr, OnConflict};
/// use navree_orm::render::render_insert;
/// use navree_orm::sql::Dialect;
///
/// let insert = InsertIr::new("deals", vec!["title".into()], vec![vec![Expr::Value(Value::from("Renewal"))]])
///     .returning(vec!["id".into()]);
/// let sql = render_insert(&insert, Dialect::Postgres).unwrap();
/// assert_eq!(sql.sql, r#"INSERT INTO "deals" ("title") VALUES ($1) RETURNING "id""#);
///
/// let ignore = insert.on_conflict(OnConflict::Ignore { target: vec![] });
/// assert_eq!(
///     render_insert(&ignore, Dialect::MySql).unwrap().sql,
///     "INSERT IGNORE INTO `deals` (`title`) VALUES (?)"
/// );
/// ```
pub fn render_insert(insert: &crate::ir::InsertIr, syntax: impl Into<Syntax>) -> Result<Statement> {
    let syntax = syntax.into();
    super::render(
        &ast::Statement::from(write::insert(insert, syntax)?),
        syntax,
    )
}

/// The SQL of an update (JSON path assignments folded per column).
pub fn render_update(update: &crate::ir::UpdateIr, syntax: impl Into<Syntax>) -> Result<Statement> {
    let syntax = syntax.into();
    super::render(
        &ast::Statement::from(write::update(update, syntax)?),
        syntax,
    )
}

/// `UPDATE table SET .. FROM joined .. WHERE ..` (MySQL: `UPDATE table,
/// joined SET ..`, for one joined table).
pub fn render_update_from(
    table: &crate::ir::TableRef,
    sets: &[(Cow<'static, str>, Expr)],
    joins: &[crate::ir::Join],
    wheres: &[crate::ir::WhereClause],
    syntax: impl Into<Syntax>,
) -> Result<Statement> {
    let syntax = syntax.into();
    let update = write::update_from(table, sets, joins, wheres, syntax)?;
    super::render(&ast::Statement::from(update), syntax)
}

/// The SQL of a delete.
pub fn render_delete(delete: &crate::ir::DeleteIr, syntax: impl Into<Syntax>) -> Result<Statement> {
    let syntax = syntax.into();
    super::render(
        &ast::Statement::from(write::delete(delete, syntax)?),
        syntax,
    )
}

/// The statements that empty `table` and reset its identity: `TRUNCATE ..
/// RESTART IDENTITY` on PostgreSQL (`CASCADE` also empties the tables whose
/// foreign keys point at it), `TRUNCATE` on MySQL, and on SQLite a delete
/// of its rows after resetting its `sqlite_sequence` entry.
pub fn render_truncate(table: &str, cascade: bool, syntax: impl Into<Syntax>) -> Vec<Statement> {
    super::grammar::for_dialect(syntax.into().dialect()).truncate(&write::truncate(table, cascade))
}

/// An index from the end of a JSON array, refused on MariaDB: 10.6 has
/// no `[last]`, and 10.9 to 11.4 answer it from the first row's array for
/// every row.
pub(crate) const FROM_THE_END: &str = "an index from the end of a JSON array";

/// Whether `path` counts an index from the end of an array.
pub(crate) fn from_the_end(path: &[JsonSegment]) -> bool {
    path.iter()
        .any(|segment| matches!(segment, JsonSegment::Index(index) if *index < 0))
}

/// Lowers IR nodes for one dialect.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Lowerer {
    pub(crate) dialect: Dialect,
    /// MariaDB's syntax, or the dialect's.
    pub(crate) syntax: Syntax,
}

impl Lowerer {
    pub(crate) fn new(syntax: impl Into<Syntax>) -> Self {
        let syntax = syntax.into();
        Lowerer {
            dialect: syntax.dialect(),
            syntax,
        }
    }

    pub(crate) fn unsupported(&self, feature: impl Into<Cow<'static, str>>) -> OrmError {
        if self.syntax.is_mariadb() {
            super::unsupported_on_mariadb(feature)
        } else {
            super::unsupported(self.dialect, feature)
        }
    }

    /// A column, with its JSON path read as text.
    pub(crate) fn column(&self, column: &ColumnRef) -> ast::Expr {
        let base = self.plain_column(column);
        if column.path.is_empty() {
            base
        } else {
            base.json_text(column.path.clone())
        }
    }

    /// A column without its JSON path.
    pub(crate) fn plain_column(&self, column: &ColumnRef) -> ast::Expr {
        ast::Expr::Column(ast::ColumnName {
            table: column.table.clone().map(ast::ObjectName::parse),
            name: ast::Ident(column.name.clone()),
        })
    }

    /// The JSON at the column's path, kept as JSON (PostgreSQL's `->`).
    pub(crate) fn json_value(&self, column: &ColumnRef) -> ast::Expr {
        let base = self.plain_column(column);
        if column.path.is_empty() {
            base
        } else {
            base.json(column.path.clone())
        }
    }

    /// A JSON path as the string literal MySQL and SQLite take:
    /// `'$."a"[0]'`.
    pub(crate) fn json_path(&self, path: &[JsonSegment]) -> Result<ast::Expr> {
        if self.syntax.is_mariadb() && from_the_end(path) {
            return Err(self.unsupported(FROM_THE_END));
        }
        Ok(ast::Expr::string(json_path_text(path, self.dialect)))
    }

    /// An expression.
    pub(crate) fn expr(&self, expr: &Expr) -> Result<ast::Expr> {
        Ok(match expr {
            Expr::Column(column) => self.column(column),
            Expr::Value(value) => ast::Expr::Value(value.clone()),
            Expr::Raw { sql, values } => self.raw(sql.clone(), values)?,
            Expr::Function { name, args } => {
                if !is_identifier(name) {
                    return Err(OrmError::invalid(format!(
                        "`{name}` is not a valid SQL function name"
                    )));
                }
                let args = args
                    .iter()
                    .map(|arg| self.expr(arg))
                    .collect::<Result<Vec<_>>>()?;
                ast::Expr::func(name.clone(), args)
            }
            Expr::Aggregate {
                function,
                arg,
                distinct,
            } => {
                let arg = match arg {
                    Some(arg) => self.expr(arg)?,
                    None => ast::Expr::Wildcard(None),
                };
                aggregate_call(*function, arg, *distinct)
            }
            Expr::Arithmetic { left, op, right } => {
                let left = self.expr(left)?;
                let right = self.expr(right)?;
                left.binary(
                    match op {
                        ArithmeticOp::Add => ast::BinaryOp::Add,
                        ArithmeticOp::Sub => ast::BinaryOp::Sub,
                        ArithmeticOp::Mul => ast::BinaryOp::Mul,
                        ArithmeticOp::Div => ast::BinaryOp::Div,
                    },
                    right,
                )
            }
            Expr::Subquery(query) => ast::Expr::Subquery(Box::new(self.select(query)?)),
            Expr::TimeBucket {
                width,
                expr,
                origin,
            } => {
                let expr = self.expr(expr)?;
                let origin = origin
                    .as_deref()
                    .map(|origin| self.expr(origin))
                    .transpose()?;
                self.time_bucket(width, expr, origin)?
            }
            Expr::First { value, time } => self.first_last("first", value, time)?,
            Expr::Last { value, time } => self.first_last("last", value, time)?,
            Expr::All { table } => ast::Expr::Wildcard(table.clone().map(ast::ObjectName::parse)),
            Expr::Exists(query) => {
                let mut query = (**query).clone();
                query.orders.clear();
                filter::exists_select_list(&mut query);
                ast::Expr::Exists {
                    query: Box::new(self.select(&query)?),
                    negated: false,
                }
            }
            Expr::RowNumber { partition, order } => {
                let partition = partition
                    .iter()
                    .map(|expr| self.expr(expr))
                    .collect::<Result<Vec<_>>>()?;
                ast::Expr::row_number().over(partition, self.orders(order, false)?)
            }
            Expr::VectorDistance {
                expr,
                vector,
                metric,
            } => self.vector_distance(expr, vector, *metric)?,
            Expr::Binary { left, op, right } => {
                let allowed = value_operators(self.dialect);
                let normalized = normalize_operator(op);
                let Some(known) = allowed.iter().find(|known| **known == normalized) else {
                    return Err(OrmError::invalid(format!(
                        "`{op}` is not an operator {} expressions take (they take: {})",
                        self.dialect.name(),
                        allowed.join(", ")
                    )));
                };
                let (left, right) = (self.expr(left)?, self.expr(right)?);
                left.binary(ast::BinaryOp::Custom(Cow::Borrowed(known)), right)
            }
            Expr::Excluded { column } => ast::Expr::Excluded(ast::Ident(column.clone())),
        })
    }

    /// A raw fragment, its placeholders checked against its values now
    /// (so a mismatch fails while lowering, before any SQL is written).
    pub(crate) fn raw(&self, sql: Cow<'static, str>, values: &[Value]) -> Result<ast::Expr> {
        super::writer::check_raw(&sql, values.len(), self.dialect)?;
        Ok(ast::Expr::Raw {
            sql,
            values: values.to_vec(),
        })
    }

    /// `ORDER BY` items. With `unqualified`, plain columns lose their
    /// table: the orders of a union name its result columns.
    pub(crate) fn orders(&self, orders: &[Order], unqualified: bool) -> Result<Vec<ast::OrderBy>> {
        let mut items = Vec::with_capacity(orders.len());
        for order in orders {
            items.push(match order {
                Order::By {
                    expr,
                    direction,
                    nulls,
                } => ast::OrderBy {
                    expr: if unqualified {
                        self.expr(&unqualify(expr))?
                    } else {
                        self.expr(expr)?
                    },
                    descending: *direction == Direction::Desc,
                    nulls: nulls.map(|nulls| match nulls {
                        Nulls::First => ast::NullsOrder::First,
                        Nulls::Last => ast::NullsOrder::Last,
                    }),
                },
                Order::Random => ast::OrderBy {
                    expr: ast::Expr::Random,
                    descending: false,
                    nulls: None,
                },
                Order::Raw { sql, values } => {
                    let (body, descending, nulls) = split_direction(sql);
                    ast::OrderBy {
                        expr: self.raw(Cow::Owned(body.to_owned()), values)?,
                        descending,
                        nulls,
                    }
                }
            });
        }
        Ok(items)
    }

    /// The distance between the vector `expr` and `vector`: pgvector's
    /// operators on PostgreSQL, MariaDB's `VEC_DISTANCE_*` on MySQL.
    fn vector_distance(
        &self,
        expr: &Expr,
        vector: &[f32],
        metric: VectorMetric,
    ) -> Result<ast::Expr> {
        if vector.is_empty() || vector.iter().any(|x| !x.is_finite()) {
            return Err(OrmError::invalid(
                "a vector to compare with must hold at least one number, and only finite ones",
            ));
        }
        let text = format!(
            "[{}]",
            vector
                .iter()
                .map(f32::to_string)
                .collect::<Vec<_>>()
                .join(",")
        );
        let column = self.expr(expr)?;
        let literal = ast::Expr::Value(Value::from(text));
        Ok(match (self.dialect, metric) {
            (Dialect::Postgres, metric) => {
                let op = match metric {
                    VectorMetric::Euclidean => "<->",
                    VectorMetric::InnerProduct => "<#>",
                    _ => "<=>",
                };
                column.binary(
                    ast::BinaryOp::Custom(Cow::Borrowed(op)),
                    literal.cast(ast::SqlType::Custom(Cow::Borrowed("vector"))),
                )
            }
            (Dialect::MySql, _) if self.syntax.mariadb_before(11, 7) => {
                return Err(self.unsupported("a vector distance before MariaDB 11.7"));
            }
            (Dialect::MySql, VectorMetric::Cosine | VectorMetric::Euclidean) => {
                let function = if metric == VectorMetric::Euclidean {
                    "VEC_DISTANCE_EUCLIDEAN"
                } else {
                    "VEC_DISTANCE_COSINE"
                };
                ast::Expr::func(
                    function,
                    vec![column, ast::Expr::func("VEC_FromText", vec![literal])],
                )
            }
            (Dialect::MySql, _) => {
                return Err(self.unsupported("the inner-product vector distance"));
            }
            (Dialect::Sqlite, _) => return Err(self.unsupported("a vector distance")),
        })
    }
}

/// `FUNCTION([DISTINCT] arg)` of an aggregate.
pub(crate) fn aggregate_call(
    function: AggregateFunction,
    arg: ast::Expr,
    distinct: bool,
) -> ast::Expr {
    ast::Expr::Function(ast::Function {
        name: Cow::Borrowed(function.sql_name()),
        args: vec![arg],
        distinct,
    })
}

/// A column reference without its table (outside a subquery, the columns
/// of a derived table are unqualified).
pub(crate) fn unqualify(expr: &Expr) -> Expr {
    match expr {
        Expr::Column(column) => Expr::Column(ColumnRef {
            table: None,
            ..column.clone()
        }),
        other => other.clone(),
    }
}

/// Splits the trailing direction (and NULLs placement) off a raw order:
/// `"field(stage, ?) DESC NULLS LAST"` is `field(stage, ?)`, descending,
/// NULLs last. Without a direction the order is ascending, as in SQL.
pub(crate) fn split_direction(sql: &str) -> (&str, bool, Option<ast::NullsOrder>) {
    let mut body = sql.trim_end();
    let mut nulls = None;
    for (suffix, placement) in [
        (" nulls first", ast::NullsOrder::First),
        (" nulls last", ast::NullsOrder::Last),
    ] {
        if ends_with_ignore_case(body, suffix) {
            body = body[..body.len() - suffix.len()].trim_end();
            nulls = Some(placement);
            break;
        }
    }
    let mut descending = false;
    for (suffix, desc) in [(" desc", true), (" asc", false)] {
        if ends_with_ignore_case(body, suffix) {
            body = body[..body.len() - suffix.len()].trim_end();
            descending = desc;
            break;
        }
    }
    (body, descending, nulls)
}

fn ends_with_ignore_case(text: &str, suffix: &str) -> bool {
    text.len() >= suffix.len()
        && text.is_char_boundary(text.len() - suffix.len())
        && text[text.len() - suffix.len()..].eq_ignore_ascii_case(suffix)
}

/// The operators a hand-written expression ([`Expr::Binary`]) may use on
/// each database: arithmetic, bit operations, concatenation, and the JSON,
/// array and vector operators that compute values.
fn value_operators(dialect: Dialect) -> &'static [&'static str] {
    match dialect {
        Dialect::Postgres => &[
            "+", "-", "*", "/", "%", "^", "||", "#-", "->", "->>", "#>", "#>>", "<->", "<=>",
            "<#>", "<+>", "&", "|", "#", "<<", ">>",
        ],
        Dialect::MySql => &[
            "+", "-", "*", "/", "%", "DIV", "MOD", "&", "|", "^", "<<", ">>", "->", "->>",
        ],
        Dialect::Sqlite => &[
            "+", "-", "*", "/", "%", "||", "&", "|", "<<", ">>", "->", "->>",
        ],
    }
}

/// An operator as the allow-lists spell it: upper case, single spaces.
pub(crate) fn normalize_operator(op: &str) -> String {
    op.split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
        .to_ascii_uppercase()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn raw_orders_split_their_direction() {
        assert_eq!(
            split_direction("field(stage, ?) DESC NULLS LAST"),
            ("field(stage, ?)", true, Some(ast::NullsOrder::Last))
        );
        assert_eq!(split_direction("a asc"), ("a", false, None));
        assert_eq!(split_direction("score"), ("score", false, None));
    }
}