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
//! Conditions beyond comparisons: pattern operators (`ILIKE`, regular
//! expressions, `SIMILAR TO`), text matching that ignores case beyond
//! ASCII, JSON containment, overlap and key existence on typed columns,
//! null-safe inequality, hand-written operators checked per database, and
//! vector distances.
//!
//! | Method | PostgreSQL | MySQL | SQLite |
//! |---|---|---|---|
//! | [`Column::ilike`] | `ILIKE` | `LOWER(..) LIKE LOWER(..)` | `LIKE` (ASCII case) |
//! | [`Column::contains_ignore_case`] | `LOWER(..) LIKE '%text%'` | `INSTR` of lower-cased bytes | `GLOB` of case variants |
//! | [`Column::eq_ignore_case`] | `LOWER(..) = 'text'` | lower-cased bytes `=` | `GLOB` of case variants |
//! | [`Column::regex`] | `~` | `REGEXP_LIKE(.., 'c')` | `REGEXP` (a registered function) |
//! | [`Column::regex_case_insensitive`] | `~*` | `REGEXP_LIKE(.., 'i')` | `REGEXP` with `(?i)` |
//! | [`Column::similar_to`] | `SIMILAR TO` | unsupported | unsupported |
//! | [`Column::contains`] | `@>` | `json_contains` | `json_each` (scalars) |
//! | [`Column::contained_by`] | `<@` | `json_contains(value, column)` | unsupported |
//! | [`Column::overlaps`] | `@>` on each element | `json_overlaps` | `json_each` |
//! | [`Column::has_key`] | `?` | `json_contains_path` | `json_type(..) IS NOT NULL` |
//! | [`Column::is_distinct_from`] | `IS DISTINCT FROM` | `NOT (.. <=> ..)` | `IS NOT` |
//!
//! SQLite has no regular expressions of its own: `REGEXP` calls the
//! application's `regexp(pattern, text)` function (SQLx registers one with
//! `SqliteConnectOptions::with_regexp`); without it the statement fails.
use std::borrow::Cow;
use crate::column::{Column, Filter, IntoExpr};
use crate::ir::{ColumnRef, Expr, IgnoreCaseMode, JsonSegment, Operator, VectorMetric, Where};
use crate::value::Value;
/// A JSON value for a condition, or the reason it cannot be one.
fn json_value(
value: impl serde::Serialize,
column: &ColumnRef,
) -> Result<serde_json::Value, String> {
serde_json::to_value(value)
.map_err(|error| format!("the value for JSON column `{column}` cannot be encoded: {error}"))
}
impl<M, T> Column<M, T> {
fn pattern(&self, op: Operator, pattern: impl Into<String>) -> Filter {
Filter(Where::Compare {
left: self.expr(),
op,
right: Expr::Value(Value::from(pattern.into())),
})
}
/// `column ILIKE pattern`: a `LIKE` ignoring case on every database
/// (`%` and `_` are wildcards).
pub fn ilike(&self, pattern: impl Into<String>) -> Filter {
Filter::like(self.expr(), pattern.into(), false, false)
}
/// `column NOT ILIKE pattern`.
pub fn not_ilike(&self, pattern: impl Into<String>) -> Filter {
Filter::like(self.expr(), pattern.into(), false, true)
}
/// The column contains `text`, ignoring letter case on every database,
/// non-ASCII letters included (`équipe` finds `Équipe Lyon`), and
/// keeping accents (it does not find `Equipe`). `text` is literal: `%`,
/// `_`, `*`, `?` and `[` match themselves. A NULL never matches. Use it
/// for search boxes; like any "contains" search, it reads every row.
///
/// SQLite's own `LOWER`, `LIKE` and `NOCASE` fold ASCII letters only, so
/// there the condition is a `GLOB` listing each letter's case variants;
/// PostgreSQL's `LOWER` folds ASCII letters only in a database with the
/// `C` locale, so a text with other cased letters is a regular
/// expression of their case variants there; MySQL compares the
/// lower-cased column byte for byte, so it ignores case under every
/// collation and never ignores accents (the column must be `utf8mb4`,
/// the connection's character set). These are navree-db's
/// `contains_ignore_case` and `eq_ignore_case`.
///
/// ```
/// use navree_orm::{Dialect, Value, col};
///
/// let sql = col("name").contains_ignore_case("Équipe").to_sql(Dialect::Sqlite).unwrap();
/// assert_eq!(sql.sql, r#""name" GLOB ?"#);
/// assert_eq!(sql.values, [Value::from("*[Éé][qQ][uU][iI][pP][eE]*")]);
/// let sql = col("name").contains_ignore_case("Équipe").to_sql(Dialect::Postgres).unwrap();
/// assert_eq!(sql.sql, r#""name" ~ $1"#);
/// assert_eq!(sql.values, [Value::from("[Éé][qQ][uU][iI][pP][eE]")]);
/// let sql = col("name").contains_ignore_case("Agra").to_sql(Dialect::Postgres).unwrap();
/// assert_eq!(sql.sql, r#"LOWER("name") LIKE $1 ESCAPE E'\\'"#);
/// assert_eq!(sql.values, [Value::from("%agra%")]);
/// ```
pub fn contains_ignore_case(&self, text: impl Into<String>) -> Filter {
self.ignore_case(text, IgnoreCaseMode::Contains)
}
/// The column equals `text`, ignoring letter case on every database the
/// way [`contains_ignore_case`](Column::contains_ignore_case) does:
/// non-ASCII letters included, accents kept, `text` literal.
pub fn eq_ignore_case(&self, text: impl Into<String>) -> Filter {
self.ignore_case(text, IgnoreCaseMode::Equals)
}
fn ignore_case(&self, text: impl Into<String>, mode: IgnoreCaseMode) -> Filter {
Filter(Where::IgnoreCase {
expr: self.expr(),
text: text.into(),
mode,
})
}
/// The column matches regular expression `pattern`, matching case.
///
/// ```
/// use navree_orm::{Dialect, col};
///
/// let sql = col("sku").regex("^[A-Z]{3}-[0-9]+$").to_sql(Dialect::MySql).unwrap();
/// assert_eq!(sql.sql, "REGEXP_LIKE(`sku`, ?, 'c')");
/// ```
pub fn regex(&self, pattern: impl Into<String>) -> Filter {
self.pattern(Operator::Regexp, pattern)
}
/// The column does not match regular expression `pattern`.
pub fn not_regex(&self, pattern: impl Into<String>) -> Filter {
self.pattern(Operator::NotRegexp, pattern)
}
/// The column matches regular expression `pattern`, ignoring case.
pub fn regex_case_insensitive(&self, pattern: impl Into<String>) -> Filter {
self.pattern(Operator::RegexpIgnoreCase, pattern)
}
/// The column does not match regular expression `pattern`, ignoring
/// case.
pub fn not_regex_case_insensitive(&self, pattern: impl Into<String>) -> Filter {
self.pattern(Operator::NotRegexpIgnoreCase, pattern)
}
/// PostgreSQL's `column SIMILAR TO pattern` (SQL regular expressions:
/// `%`, `_`, `|`, `*`, `+`, groups).
pub fn similar_to(&self, pattern: impl Into<String>) -> Filter {
self.pattern(Operator::Postgres("similar to"), pattern)
}
/// PostgreSQL's `column NOT SIMILAR TO pattern`.
pub fn not_similar_to(&self, pattern: impl Into<String>) -> Filter {
self.pattern(Operator::Postgres("not similar to"), pattern)
}
/// The JSON column (or path) contains `value`: an element of an array,
/// or (PostgreSQL and MySQL) an object's keys and values. The same as
/// `where_json_contains`.
pub fn contains(&self, value: impl serde::Serialize) -> Filter {
let column = self.column_ref();
match json_value(value, &column) {
Ok(value) => Filter(Where::JsonContains {
column,
value,
not: false,
}),
Err(problem) => Filter(Where::Invalid(problem)),
}
}
/// The JSON column (or path) is contained in `value` (`<@`; PostgreSQL
/// and MySQL).
///
/// ```
/// use navree_orm::{Dialect, col};
///
/// let sql = col("roles").contained_by(["admin", "manager"]).to_sql(Dialect::Postgres).unwrap();
/// assert_eq!(sql.sql, r#"CAST("roles" AS JSONB) <@ $1"#);
/// ```
pub fn contained_by(&self, value: impl serde::Serialize) -> Filter {
let column = self.column_ref();
match json_value(value, &column) {
Ok(value) => Filter(Where::JsonContainedBy {
column,
value,
not: false,
}),
Err(problem) => Filter(Where::Invalid(problem)),
}
}
/// The JSON array column (or path) shares an element with `values` (an
/// array; a scalar stands for a one-element array).
pub fn overlaps(&self, values: impl serde::Serialize) -> Filter {
let column = self.column_ref();
match json_value(values, &column) {
Ok(value) => Filter(Where::JsonOverlaps {
column,
value,
not: false,
}),
Err(problem) => Filter(Where::Invalid(problem)),
}
}
/// The JSON object column (or path) has key `key`.
///
/// ```
/// use navree_orm::{Dialect, col};
///
/// let sql = col("meta->owner").has_key("email").to_sql(Dialect::Sqlite).unwrap();
/// assert_eq!(sql.sql, r#"json_type("meta", '$."owner"."email"') IS NOT NULL"#);
/// ```
pub fn has_key(&self, key: impl Into<String>) -> Filter {
let mut column = self.column_ref();
column.path.push(JsonSegment::Key(key.into()));
Filter(Where::JsonContainsKey { column, not: false })
}
/// Null-safe inequality: true when the values differ, also when
/// exactly one is NULL (`IS DISTINCT FROM`).
pub fn is_distinct_from(&self, value: impl crate::value::ValueFor<T>) -> Filter {
match self.encode(&value.into_value_for()) {
Ok(value) => Filter(Where::Compare {
left: self.expr(),
op: Operator::NullSafeNe,
right: Expr::Value(value),
}),
Err(error) => Filter(Where::Invalid(format!(
"cannot use a value for column `{}`: {error}",
self.name()
))),
}
}
/// The distance between this vector column and `vector` (cosine; see
/// [`Expr::vector_distance`]).
pub fn vector_distance(&self, vector: &[f32]) -> Expr {
Expr::vector_distance(self.expr(), vector)
}
}
impl Filter {
/// `left op right` with an operator written as text, checked against
/// the database's list of condition operators when the query compiles
/// (PostgreSQL's JSON, array, range and text search operators such as
/// `@>`, `?|`, `&&`, `@@`; MySQL's `SOUNDS LIKE`; SQLite's `GLOB` and
/// `MATCH`; and the comparisons). An operator the database does not
/// take is an [`OrmError::InvalidQuery`](crate::OrmError::InvalidQuery)
/// naming the ones it does.
///
/// ```
/// use navree_orm::{Dialect, Expr, Filter, col};
///
/// let any_tag = Filter::op_raw(col("tags"), "?|", Expr::raw("ARRAY[?, ?]", ["vip", "gold"]));
/// let sql = any_tag.to_sql(Dialect::Postgres).unwrap();
/// assert_eq!(sql.sql, r#""tags" ?| (ARRAY[$1, $2])"#);
/// assert!(any_tag.to_sql(Dialect::MySql).unwrap_err().to_string().contains("is not an operator MySQL conditions take"));
/// ```
pub fn op_raw(left: impl IntoExpr, op: impl Into<String>, right: impl Into<Expr>) -> Filter {
Filter(Where::Compare {
left: left.into_expr(),
op: Operator::Raw(op.into()),
right: right.into(),
})
}
}
impl Expr {
/// `self op other` with an operator written as text (`||`, `-`, `#-`,
/// `->`, ...), checked against the database's list of value operators
/// when the query compiles.
///
/// ```
/// use navree_orm::{Dialect, Expr, table};
///
/// // The meta object without its `secret` key.
/// let sql = table("deals")
/// .select_expr(Expr::col("meta").binary("-", Expr::val("secret")), "meta")
/// .to_sql(Dialect::Postgres)
/// .unwrap();
/// assert_eq!(sql.sql, r#"SELECT "meta" - $1 AS "meta" FROM "deals""#);
/// ```
pub fn binary(self, op: impl Into<Cow<'static, str>>, other: impl Into<Expr>) -> Expr {
Expr::Binary {
left: Box::new(self),
op: op.into(),
right: Box::new(other.into()),
}
}
/// The cosine distance between the vector `expr` (an embedding column)
/// and `vector`: 0 for the same direction, 1 for unrelated, 2 for
/// opposite. pgvector's `<=>` on PostgreSQL, MariaDB's
/// `VEC_DISTANCE_COSINE`.
///
/// ```
/// use navree_orm::{Dialect, Expr};
///
/// let distance = Expr::vector_distance(Expr::col("embedding"), &[0.5, 1.0]);
/// let sql = distance.lt(0.3).to_sql(Dialect::Postgres).unwrap();
/// assert_eq!(sql.sql, r#""embedding" <=> CAST($1 AS vector) < $2"#);
/// ```
pub fn vector_distance(expr: impl Into<Expr>, vector: &[f32]) -> Expr {
Expr::vector_distance_by(expr, vector, VectorMetric::Cosine)
}
/// The distance between the vector `expr` and `vector`, measured by
/// `metric`.
pub fn vector_distance_by(expr: impl Into<Expr>, vector: &[f32], metric: VectorMetric) -> Expr {
Expr::VectorDistance {
expr: Box::new(expr.into()),
vector: vector.to_vec(),
metric,
}
}
}