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
//! Building [`Expr`]essions: columns, values, raw SQL, functions,
//! aggregates, arithmetic, subqueries and TimescaleDB's `time_bucket`,
//! `first` and `last`.
//!
//! ```
//! use navree_orm::{Dialect, Expr, TableBuilder, table};
//!
//! // Hourly temperature readings: bucket, first and last value per bucket.
//! let query = table("readings")
//! .select_expr(Expr::time_bucket("1 hour", Expr::col("taken_at")), "bucket")
//! .select_expr(Expr::first(Expr::col("celsius"), Expr::col("taken_at")), "opening")
//! .select_expr(Expr::last(Expr::col("celsius"), Expr::col("taken_at")), "closing")
//! .group_by(["bucket"])
//! .order_by("bucket");
//! let sql = query.to_sql(Dialect::Postgres).unwrap();
//! assert_eq!(
//! sql.sql,
//! r#"SELECT time_bucket(CAST($1 AS INTERVAL), "taken_at") AS "bucket", first("celsius", "taken_at") AS "opening", last("celsius", "taken_at") AS "closing" FROM "readings" GROUP BY "bucket" ORDER BY "bucket" ASC"#
//! );
//! # let _: TableBuilder = query;
//! ```
use std::borrow::Cow;
use crate::column::{Filter, IntoQuery};
use crate::ir::{
AggregateFunction, ArithmeticOp, ColumnRef, Expr, InValues, Operator, Order, Where,
};
use crate::value::Value;
impl<V: Into<Value>> From<V> for Expr {
/// A value is a bound parameter.
fn from(value: V) -> Self {
Expr::Value(value.into())
}
}
impl Expr {
/// The column `name`: `"title"`, `"deals.title"`, or a JSON path
/// `"meta->status"`.
pub fn col(name: impl Into<Cow<'static, str>>) -> Expr {
Expr::Column(ColumnRef::parse(name))
}
/// A bound value.
pub fn val(value: impl Into<Value>) -> Expr {
Expr::Value(value.into())
}
/// Raw SQL with `?` placeholders for `values` (`??` for a literal
/// `?`). SQL databases only.
pub fn raw(
sql: impl Into<Cow<'static, str>>,
values: impl IntoIterator<Item = impl Into<Value>>,
) -> Expr {
Expr::Raw {
sql: sql.into(),
values: values.into_iter().map(Into::into).collect(),
}
}
/// A call of the SQL function `name`.
pub fn func(
name: impl Into<Cow<'static, str>>,
args: impl IntoIterator<Item = impl Into<Expr>>,
) -> Expr {
Expr::Function {
name: name.into(),
args: args.into_iter().map(Into::into).collect(),
}
}
/// `lower(expr)`.
pub fn lower(expr: impl Into<Expr>) -> Expr {
Expr::func("lower", [expr.into()])
}
/// `upper(expr)`.
pub fn upper(expr: impl Into<Expr>) -> Expr {
Expr::func("upper", [expr.into()])
}
/// `coalesce(a, b, ...)`: the first non-NULL argument.
pub fn coalesce(args: impl IntoIterator<Item = impl Into<Expr>>) -> Expr {
Expr::func("coalesce", args)
}
fn aggregate(function: AggregateFunction, arg: Option<Expr>, distinct: bool) -> Expr {
Expr::Aggregate {
function,
arg: arg.map(Box::new),
distinct,
}
}
/// `count(*)`.
pub fn count_all() -> Expr {
Expr::aggregate(AggregateFunction::Count, None, false)
}
/// `count(expr)`: the rows where `expr` is not NULL.
pub fn count(expr: impl Into<Expr>) -> Expr {
Expr::aggregate(AggregateFunction::Count, Some(expr.into()), false)
}
/// `count(DISTINCT expr)`.
pub fn count_distinct(expr: impl Into<Expr>) -> Expr {
Expr::aggregate(AggregateFunction::Count, Some(expr.into()), true)
}
/// `sum(expr)`.
pub fn sum(expr: impl Into<Expr>) -> Expr {
Expr::aggregate(AggregateFunction::Sum, Some(expr.into()), false)
}
/// `avg(expr)`.
pub fn avg(expr: impl Into<Expr>) -> Expr {
Expr::aggregate(AggregateFunction::Avg, Some(expr.into()), false)
}
/// `min(expr)`.
pub fn min(expr: impl Into<Expr>) -> Expr {
Expr::aggregate(AggregateFunction::Min, Some(expr.into()), false)
}
/// `max(expr)`.
pub fn max(expr: impl Into<Expr>) -> Expr {
Expr::aggregate(AggregateFunction::Max, Some(expr.into()), false)
}
/// A subquery returning one value.
pub fn subquery(query: impl IntoQuery) -> Expr {
Expr::Subquery(Box::new(query.into_query()))
}
/// In an upsert's update: the value `column` would have been inserted
/// with, e.g. to add to a counter instead of replacing it.
///
/// ```
/// use navree_orm::ir::{InsertIr, OnConflict};
/// use navree_orm::sql::{Dialect, render_insert};
/// use navree_orm::{Expr, Value};
///
/// let insert = InsertIr::new(
/// "page_views",
/// vec!["path".into(), "views".into()],
/// vec![vec![Expr::val("/pricing"), Expr::val(1)]],
/// )
/// .on_conflict(OnConflict::Update {
/// target: vec!["path".into()],
/// sets: vec![("views".into(), Expr::col("page_views.views").add(Expr::excluded("views")))],
/// });
/// assert_eq!(
/// render_insert(&insert, Dialect::Postgres).unwrap().sql,
/// r#"INSERT INTO "page_views" ("path", "views") VALUES ($1, $2) ON CONFLICT ("path") DO UPDATE SET "views" = "page_views"."views" + "excluded"."views""#
/// );
/// assert_eq!(
/// render_insert(&insert, Dialect::MySql).unwrap().sql,
/// "INSERT INTO `page_views` (`path`, `views`) VALUES (?, ?) ON DUPLICATE KEY UPDATE `views` = `page_views`.`views` + VALUES(`views`)"
/// );
/// # let _ = Value::from(1);
/// ```
pub fn excluded(column: impl Into<Cow<'static, str>>) -> Expr {
Expr::Excluded {
column: column.into(),
}
}
/// TimescaleDB's `time_bucket(width, expr)`: the start of the bucket of
/// width `width` (`"5 minutes"`, `"1 hour"`, `"1 day"`, `"1 week"`,
/// `"1 month"`) that `expr` falls in.
///
/// On SQLite and MySQL, fixed widths (microseconds to weeks) are
/// computed with the same alignment as TimescaleDB (buckets start at
/// 2000-01-03, a Monday, plus whole widths); month and year buckets
/// need TimescaleDB.
pub fn time_bucket(width: impl Into<String>, expr: impl Into<Expr>) -> Expr {
Expr::TimeBucket {
width: width.into(),
expr: Box::new(expr.into()),
origin: None,
}
}
/// `time_bucket(width, expr, origin)`: buckets aligned to `origin`.
pub fn time_bucket_from(
width: impl Into<String>,
expr: impl Into<Expr>,
origin: impl Into<Expr>,
) -> Expr {
Expr::TimeBucket {
width: width.into(),
expr: Box::new(expr.into()),
origin: Some(Box::new(origin.into())),
}
}
/// TimescaleDB's `first(value, time)`: in each group, `value` at the
/// earliest `time`.
pub fn first(value: impl Into<Expr>, time: impl Into<Expr>) -> Expr {
Expr::First {
value: Box::new(value.into()),
time: Box::new(time.into()),
}
}
/// TimescaleDB's `last(value, time)`: in each group, `value` at the
/// latest `time`.
pub fn last(value: impl Into<Expr>, time: impl Into<Expr>) -> Expr {
Expr::Last {
value: Box::new(value.into()),
time: Box::new(time.into()),
}
}
fn arithmetic(self, op: ArithmeticOp, other: impl Into<Expr>) -> Expr {
Expr::Arithmetic {
left: Box::new(self),
op,
right: Box::new(other.into()),
}
}
/// `self + other`.
#[allow(clippy::should_implement_trait)]
pub fn add(self, other: impl Into<Expr>) -> Expr {
self.arithmetic(ArithmeticOp::Add, other)
}
/// `self - other`.
#[allow(clippy::should_implement_trait)]
pub fn sub(self, other: impl Into<Expr>) -> Expr {
self.arithmetic(ArithmeticOp::Sub, other)
}
/// `self * other`.
#[allow(clippy::should_implement_trait)]
pub fn mul(self, other: impl Into<Expr>) -> Expr {
self.arithmetic(ArithmeticOp::Mul, other)
}
/// `self / other`.
#[allow(clippy::should_implement_trait)]
pub fn div(self, other: impl Into<Expr>) -> Expr {
self.arithmetic(ArithmeticOp::Div, other)
}
/// `self = other` (`IS NULL` for a NULL value).
pub fn eq(self, other: impl Into<Expr>) -> Filter {
Filter::compare(self, Operator::Eq, other.into())
}
/// `self <> other` (`IS NOT NULL` for a NULL value).
pub fn ne(self, other: impl Into<Expr>) -> Filter {
Filter::compare(self, Operator::Ne, other.into())
}
/// `self > other`.
pub fn gt(self, other: impl Into<Expr>) -> Filter {
Filter::compare(self, Operator::Gt, other.into())
}
/// `self >= other`.
pub fn gte(self, other: impl Into<Expr>) -> Filter {
Filter::compare(self, Operator::Gte, other.into())
}
/// `self < other`.
pub fn lt(self, other: impl Into<Expr>) -> Filter {
Filter::compare(self, Operator::Lt, other.into())
}
/// `self <= other`.
pub fn lte(self, other: impl Into<Expr>) -> Filter {
Filter::compare(self, Operator::Lte, other.into())
}
/// `self <op> other`.
pub fn op(self, op: impl Into<Operator>, other: impl Into<Expr>) -> Filter {
Filter::compare(self, op.into(), other.into())
}
/// `self IN (values)`.
pub fn is_in(self, values: impl IntoIterator<Item = impl Into<Expr>>) -> Filter {
Filter(Where::In {
expr: self,
values: InValues::List(values.into_iter().map(Into::into).collect()),
not: false,
})
}
/// `self NOT IN (values)`.
pub fn not_in(self, values: impl IntoIterator<Item = impl Into<Expr>>) -> Filter {
Filter(Where::In {
expr: self,
values: InValues::List(values.into_iter().map(Into::into).collect()),
not: true,
})
}
/// `self IS NULL`.
pub fn is_null(self) -> Filter {
Filter(Where::Null {
expr: self,
not: false,
})
}
/// `self IS NOT NULL`.
pub fn is_not_null(self) -> Filter {
Filter(Where::Null {
expr: self,
not: true,
})
}
/// `self BETWEEN low AND high`.
pub fn between(self, low: impl Into<Expr>, high: impl Into<Expr>) -> Filter {
Filter(Where::Between {
expr: self,
low: low.into(),
high: high.into(),
not: false,
})
}
/// `self NOT BETWEEN low AND high`.
pub fn not_between(self, low: impl Into<Expr>, high: impl Into<Expr>) -> Filter {
Filter(Where::Between {
expr: self,
low: low.into(),
high: high.into(),
not: true,
})
}
/// `self LIKE pattern`, ignoring case on every database.
pub fn like(self, pattern: impl Into<String>) -> Filter {
Filter::like(self, pattern.into(), false, false)
}
/// `self NOT LIKE pattern`, ignoring case on every database.
pub fn not_like(self, pattern: impl Into<String>) -> Filter {
Filter::like(self, pattern.into(), false, true)
}
/// The expression in ascending order.
pub fn asc(self) -> Order {
Order::asc(self)
}
/// The expression in descending order.
pub fn desc(self) -> Order {
Order::desc(self)
}
}