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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
use super::Query;
use crate::backend::{Backend, DieselReserveSpecialization};
use crate::query_builder::{AstPass, QueryFragment, QueryId};
use crate::query_dsl::RunQueryDslSupport;
use crate::result::QueryResult;
use crate::serialize::ToSql;
use crate::sql_types::{HasSqlType, Untyped};
use alloc::boxed::Box;
use alloc::string::String;
use alloc::string::ToString;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::marker::PhantomData;
#[derive(Debug, Clone)]
#[must_use = "Queries are only executed when calling `load`, `get_result` or similar."]
/// The return value of `sql_query`.
///
/// Unlike most queries in Diesel, `SqlQuery` loads its data by column name,
/// rather than by index. This means that you cannot deserialize this query into
/// a tuple, and any structs used must implement `QueryableByName`.
///
/// See [`sql_query`](crate::sql_query()) for examples.
pub struct SqlQuery<Inner = self::private::Empty> {
inner: Inner,
query: String,
}
impl<Inner> SqlQuery<Inner> {
pub(crate) fn new(inner: Inner, query: String) -> Self {
SqlQuery { inner, query }
}
/// Bind a value for use with this SQL query. The given query should have
/// placeholders that vary based on the database type,
/// like [SQLite Parameter](https://sqlite.org/lang_expr.html#varparam) syntax,
/// [PostgreSQL PREPARE syntax](https://www.postgresql.org/docs/current/sql-prepare.html),
/// or [MySQL bind syntax](https://dev.mysql.com/doc/refman/8.0/en/mysql-stmt-bind-param.html).
///
/// For binding a variable number of values in a loop, use `into_boxed` first.
///
/// # Safety
///
/// This function should be used with care, as Diesel cannot validate that
/// the value is of the right type nor can it validate that you have passed
/// the correct number of parameters.
///
/// # Example
///
/// ```
/// # include!("../doctest_setup.rs");
/// #
/// # use schema::users;
/// #
/// # #[derive(QueryableByName, Debug, PartialEq)]
/// # struct User {
/// # id: i32,
/// # name: String,
/// # }
/// #
/// # // Reading the query result requires reading memory allocated by the
/// # // native sqlite library, which miri cannot track provenance for.
/// # #[cfg(miri)]
/// # fn main() {}
/// # #[cfg(not(miri))]
/// # fn main() {
/// # use diesel::sql_query;
/// # use diesel::sql_types::{Integer, Text};
/// #
/// # let connection = &mut establish_connection();
/// # diesel::insert_into(users::table)
/// # .values(users::name.eq("Jim"))
/// # .execute(connection).unwrap();
/// # #[cfg(feature = "postgres")]
/// # let users = sql_query("SELECT * FROM users WHERE id > $1 AND name != $2");
/// # #[cfg(not(feature = "postgres"))]
/// // sqlite/mysql bind syntax
/// let users = sql_query("SELECT * FROM users WHERE id > ? AND name <> ?")
/// # ;
/// # let users = users
/// .bind::<Integer, _>(1)
/// .bind::<Text, _>("Tess")
/// .get_results(connection);
/// let expected_users = vec![User {
/// id: 3,
/// name: "Jim".into(),
/// }];
/// assert_eq!(Ok(expected_users), users);
/// # }
/// ```
pub fn bind<ST, Value>(self, value: Value) -> UncheckedBind<Self, Value, ST> {
UncheckedBind::new(self, value)
}
/// Internally boxes the query, which allows to calls `bind` and `sql` so that they don't
/// change the type nor the instance. This allows to call `bind` or `sql`
/// in a loop, e.g.:
///
/// ```
/// # include!("../doctest_setup.rs");
/// #
/// # use schema::users;
/// #
/// # #[derive(QueryableByName, Debug, PartialEq)]
/// # struct User {
/// # id: i32,
/// # name: String,
/// # }
/// #
/// # // Reading the query result requires reading memory allocated by the
/// # // native sqlite library, which miri cannot track provenance for.
/// # #[cfg(miri)]
/// # fn main() {}
/// # #[cfg(not(miri))]
/// # fn main() {
/// # use diesel::sql_query;
/// # use diesel::sql_types::{Integer};
/// #
/// # let connection = &mut establish_connection();
/// # diesel::insert_into(users::table)
/// # .values(users::name.eq("Jim"))
/// # .execute(connection).unwrap();
/// let mut q = diesel::sql_query("SELECT * FROM users WHERE id IN(").into_boxed();
/// for (idx, user_id) in [3, 4, 5].into_iter().enumerate() {
/// if idx != 0 {
/// q = q.sql(", ");
/// }
/// # #[cfg(feature = "postgres")]
/// # {
/// q = q
/// // postgresql bind syntax
/// .sql(format!("${}", idx + 1))
/// .bind::<Integer, _>(user_id);
/// # }
/// # #[cfg(not(feature = "postgres"))]
/// # {
/// # q = q
/// # .sql(format!("?"))
/// # .bind::<Integer, _>(user_id);
/// # }
/// }
/// let users = q.sql(");").get_results(connection);
/// let expected_users = vec![User {
/// id: 3,
/// name: "Jim".into(),
/// }];
/// assert_eq!(Ok(expected_users), users);
/// # }
/// ```
///
/// This allows doing things you otherwise couldn't do, e.g. `bind`ing in a
/// loop.
///
/// Boxed queries are not cloneable.
/// If you need cloning, use [`into_boxed_clone`] to create a [`BoxedCloneSqlQuery`].
///
/// [`into_boxed_clone`]: SqlQuery::into_boxed_clone()
pub fn into_boxed<'f, DB: Backend>(self) -> BoxedSqlQuery<'f, DB, Self> {
BoxedSqlQuery::new(self)
}
/// Internally wraps the query in an [`Arc`], which allows to calls `bind` and `sql` so that
/// they don't change the type nor the instance. This allows to clone the query and call
/// `bind` or `sql` in a loop, e.g.:
///
/// ```
/// # include!("../doctest_setup.rs");
/// #
/// # use schema::users;
/// #
/// # #[derive(QueryableByName, Debug, PartialEq)]
/// # struct User {
/// # id: i32,
/// # name: String,
/// # }
/// #
/// # // Reading the query result requires reading memory allocated by the
/// # // native sqlite library, which miri cannot track provenance for.
/// # #[cfg(miri)]
/// # fn main() {}
/// # #[cfg(not(miri))]
/// # fn main() {
/// # use diesel::sql_query;
/// # use diesel::sql_types::{Integer};
/// #
/// # let connection = &mut establish_connection();
/// # diesel::insert_into(users::table)
/// # .values(users::name.eq("Jim"))
/// # .execute(connection).unwrap();
/// let q = diesel::sql_query("SELECT * FROM users WHERE id IN(").into_boxed_clone();
/// let mut q = q.clone();
/// for (idx, user_id) in [3, 4, 5].into_iter().enumerate() {
/// if idx != 0 {
/// q = q.sql(", ");
/// }
/// # #[cfg(feature = "postgres")]
/// # {
/// q = q
/// // postgresql bind syntax
/// .sql(format!("${}", idx + 1))
/// .bind::<Integer, _>(user_id);
/// # }
/// # #[cfg(not(feature = "postgres"))]
/// # {
/// # q = q
/// # .sql(format!("?"))
/// # .bind::<Integer, _>(user_id);
/// # }
/// }
/// let users = q.sql(");").get_results(connection);
/// let expected_users = vec![User {
/// id: 3,
/// name: "Jim".into(),
/// }];
/// assert_eq!(Ok(expected_users), users);
/// # }
/// ```
///
/// This allows doing things you otherwise couldn't do, e.g. `bind`ing in a
/// loop.
///
/// In cases where the query does not need to be cloned, [`BoxedSqlQuery`] (created with
/// [`into_boxed`]) provides better performance.
///
/// [`into_boxed`]: SqlQuery::into_boxed()
pub fn into_boxed_clone<'f, DB: Backend>(self) -> BoxedCloneSqlQuery<'f, DB, Self> {
BoxedCloneSqlQuery::new(self)
}
/// Appends a piece of SQL code at the end.
///
/// # Safety
///
/// Diesel passes the given string to the database as written. It must
/// therefore never contain values that come from outside your own code,
/// because anything interpolated into the SQL text can carry an SQL
/// injection. Pass such values with [`bind`] instead.
///
/// [`bind`]: SqlQuery::bind()
pub fn sql<T: AsRef<str>>(mut self, sql: T) -> Self {
self.query += sql.as_ref();
self
}
}
impl SqlQuery {
pub(crate) fn from_sql(query: String) -> SqlQuery {
Self {
inner: self::private::Empty,
query,
}
}
}
impl<DB, Inner> QueryFragment<DB> for SqlQuery<Inner>
where
DB: Backend + DieselReserveSpecialization,
Inner: QueryFragment<DB>,
{
fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
out.unsafe_to_cache_prepared();
self.inner.walk_ast(out.reborrow())?;
out.push_sql(&self.query);
Ok(())
}
}
impl<Inner> QueryId for SqlQuery<Inner> {
type QueryId = ();
const HAS_STATIC_QUERY_ID: bool = false;
}
impl<Inner> Query for SqlQuery<Inner> {
type SqlType = Untyped;
}
impl<Inner> RunQueryDslSupport for SqlQuery<Inner> {}
#[derive(Debug, Clone, Copy)]
#[must_use = "Queries are only executed when calling `load`, `get_result` or similar."]
/// Returned by the [`SqlQuery::bind()`] method when binding a value to a fragment of SQL.
pub struct UncheckedBind<Query, Value, ST> {
query: Query,
value: Value,
_marker: PhantomData<ST>,
}
impl<Query, Value, ST> UncheckedBind<Query, Value, ST> {
pub fn new(query: Query, value: Value) -> Self {
UncheckedBind {
query,
value,
_marker: PhantomData,
}
}
pub fn bind<ST2, Value2>(self, value: Value2) -> UncheckedBind<Self, Value2, ST2> {
UncheckedBind::new(self, value)
}
pub fn into_boxed<'f, DB: Backend>(self) -> BoxedSqlQuery<'f, DB, Self> {
BoxedSqlQuery::new(self)
}
pub fn into_boxed_clone<'f, DB: Backend>(self) -> BoxedCloneSqlQuery<'f, DB, Self> {
BoxedCloneSqlQuery::new(self)
}
/// Append raw SQL after this query and the values bound to it.
///
/// The wrapped query renders first, then the given SQL text. This allows
/// interleaving raw SQL fragments with [`bind`] calls when the query
/// builder cannot express the statement as a whole.
///
/// # Safety
///
/// Diesel passes the given string to the database as written. It must
/// therefore never contain values that come from outside your own code,
/// because anything interpolated into the SQL text can carry an SQL
/// injection. Pass such values with [`bind`] instead.
///
/// # Examples
///
/// ```rust
/// # include!("../doctest_setup.rs");
/// #
/// # use schema::users;
/// #
/// # #[derive(QueryableByName, Debug, PartialEq)]
/// # struct User {
/// # id: i32,
/// # name: String,
/// # }
/// #
/// # // Reading the query result requires reading memory allocated by the
/// # // native sqlite library, which miri cannot track provenance for.
/// # #[cfg(miri)]
/// # fn main() {}
/// # #[cfg(not(miri))]
/// # fn main() {
/// # use diesel::sql_query;
/// # use diesel::sql_types::Integer;
/// #
/// # let connection = &mut establish_connection();
/// # #[cfg(feature = "postgres")]
/// # let base = sql_query("SELECT id, name FROM users WHERE id >= $1");
/// # #[cfg(not(feature = "postgres"))]
/// // Checkout the documentation of your database for the correct
/// // bind placeholder
/// let base = sql_query("SELECT id, name FROM users WHERE id >= ?");
/// // The appended fragment decides the order of the returned rows.
/// let users = base
/// .bind::<Integer, _>(1)
/// .sql(" ORDER BY id DESC")
/// .load::<User>(connection);
/// assert_eq!(
/// Ok(vec![
/// User {
/// id: 2,
/// name: "Tess".into()
/// },
/// User {
/// id: 1,
/// name: "Sean".into()
/// }
/// ]),
/// users
/// );
/// # }
/// ```
///
/// [`bind`]: Self::bind()
pub fn sql<T: Into<String>>(self, sql: T) -> SqlQuery<Self> {
SqlQuery::new(self, sql.into())
}
}
impl<Query, Value, ST> QueryId for UncheckedBind<Query, Value, ST>
where
Query: QueryId,
ST: QueryId,
{
type QueryId = UncheckedBind<Query::QueryId, (), ST::QueryId>;
const HAS_STATIC_QUERY_ID: bool = Query::HAS_STATIC_QUERY_ID && ST::HAS_STATIC_QUERY_ID;
}
impl<Query, Value, ST, DB> QueryFragment<DB> for UncheckedBind<Query, Value, ST>
where
DB: Backend + HasSqlType<ST> + DieselReserveSpecialization,
Query: QueryFragment<DB>,
Value: ToSql<ST, DB>,
{
fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
self.query.walk_ast(out.reborrow())?;
out.push_bind_param_value_only(&self.value)?;
Ok(())
}
}
impl<Q, Value, ST> Query for UncheckedBind<Q, Value, ST> {
type SqlType = Untyped;
}
impl<Query, Value, ST> RunQueryDslSupport for UncheckedBind<Query, Value, ST> {}
#[must_use = "Queries are only executed when calling `load`, `get_result`, or similar."]
/// See [`SqlQuery::into_boxed`].
///
/// [`SqlQuery::into_boxed`]: SqlQuery::into_boxed()
#[allow(missing_debug_implementations)]
pub struct BoxedSqlQuery<'f, DB: Backend, Query> {
query: Query,
sql: String,
binds: Vec<Box<dyn QueryFragment<DB> + Send + 'f>>,
}
#[derive(Clone)]
#[must_use = "Queries are only executed when calling `load`, `get_result`, or similar."]
/// See [`SqlQuery::into_boxed_clone`].
///
/// [`SqlQuery::into_boxed_clone`]: SqlQuery::into_boxed_clone()
#[allow(missing_debug_implementations)]
pub struct BoxedCloneSqlQuery<'f, DB: Backend, Query> {
query: Query,
sql: String,
binds: Vec<Arc<dyn QueryFragment<DB> + Send + Sync + 'f>>,
}
struct RawBind<ST, U> {
value: U,
p: PhantomData<ST>,
}
impl<ST, U, DB> QueryFragment<DB> for RawBind<ST, U>
where
DB: Backend + HasSqlType<ST>,
U: ToSql<ST, DB>,
{
fn walk_ast<'b>(&'b self, mut pass: AstPass<'_, 'b, DB>) -> QueryResult<()> {
pass.push_bind_param_value_only(&self.value)
}
}
impl<'f, DB: Backend, Query> BoxedSqlQuery<'f, DB, Query> {
pub(crate) fn new(query: Query) -> Self {
BoxedSqlQuery {
query,
sql: "".to_string(),
binds: alloc::vec![],
}
}
/// See [`SqlQuery::bind`].
///
/// [`SqlQuery::bind`]: SqlQuery::bind()
pub fn bind<BindSt, Value>(mut self, b: Value) -> Self
where
DB: HasSqlType<BindSt>,
Value: ToSql<BindSt, DB> + Send + 'f,
BindSt: Send + 'f,
{
self.binds.push(Box::new(RawBind {
value: b,
p: PhantomData,
}) as Box<_>);
self
}
/// See [`SqlQuery::sql`].
///
/// [`SqlQuery::sql`]: SqlQuery::sql()
pub fn sql<T: AsRef<str>>(mut self, sql: T) -> Self {
self.sql += sql.as_ref();
self
}
}
/// Walk a boxed SQL query, whichever pointer holds its binds.
fn walk_boxed_sql_query<'b, DB, Query, P>(
query: &'b Query,
sql: &'b str,
binds: &'b [P],
mut out: AstPass<'_, 'b, DB>,
) -> QueryResult<()>
where
DB: Backend,
Query: QueryFragment<DB>,
P: QueryFragment<DB>,
{
out.unsafe_to_cache_prepared();
query.walk_ast(out.reborrow())?;
out.push_sql(sql);
for b in binds {
b.walk_ast(out.reborrow())?;
}
Ok(())
}
impl<DB, Query> QueryFragment<DB> for BoxedSqlQuery<'_, DB, Query>
where
DB: Backend + DieselReserveSpecialization,
Query: QueryFragment<DB>,
{
fn walk_ast<'b>(&'b self, out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
walk_boxed_sql_query(&self.query, &self.sql, &self.binds, out)
}
}
impl<DB: Backend, Query> QueryId for BoxedSqlQuery<'_, DB, Query> {
type QueryId = ();
const HAS_STATIC_QUERY_ID: bool = false;
}
impl<DB, Q> Query for BoxedSqlQuery<'_, DB, Q>
where
DB: Backend,
{
type SqlType = Untyped;
}
impl<DB: Backend, Query> RunQueryDslSupport for BoxedSqlQuery<'_, DB, Query> {}
impl<'f, DB: Backend, Query> BoxedCloneSqlQuery<'f, DB, Query> {
pub(crate) fn new(query: Query) -> Self {
BoxedCloneSqlQuery {
query,
sql: "".to_string(),
binds: alloc::vec![],
}
}
/// See [`SqlQuery::bind`].
///
/// [`SqlQuery::bind`]: SqlQuery::bind()
pub fn bind<BindSt, Value>(mut self, b: Value) -> Self
where
DB: HasSqlType<BindSt>,
Value: ToSql<BindSt, DB> + Send + Sync + 'f,
BindSt: Send + Sync + 'f,
{
self.binds.push(Arc::new(RawBind {
value: b,
p: PhantomData,
}) as Arc<_>);
self
}
/// See [`SqlQuery::sql`].
///
/// [`SqlQuery::sql`]: SqlQuery::sql()
pub fn sql<T: AsRef<str>>(mut self, sql: T) -> Self {
self.sql += sql.as_ref();
self
}
}
impl<DB, Query> QueryFragment<DB> for BoxedCloneSqlQuery<'_, DB, Query>
where
DB: Backend + DieselReserveSpecialization,
Query: QueryFragment<DB>,
{
fn walk_ast<'b>(&'b self, out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
walk_boxed_sql_query(&self.query, &self.sql, &self.binds, out)
}
}
impl<DB: Backend, Query> QueryId for BoxedCloneSqlQuery<'_, DB, Query> {
type QueryId = ();
const HAS_STATIC_QUERY_ID: bool = false;
}
impl<DB, Q> Query for BoxedCloneSqlQuery<'_, DB, Q>
where
DB: Backend,
{
type SqlType = Untyped;
}
impl<DB: Backend, Query> RunQueryDslSupport for BoxedCloneSqlQuery<'_, DB, Query> {}
mod private {
use crate::backend::{Backend, DieselReserveSpecialization};
use crate::query_builder::{QueryFragment, QueryId};
#[derive(Debug, Clone, Copy, QueryId)]
pub struct Empty;
impl<DB> QueryFragment<DB> for Empty
where
DB: Backend + DieselReserveSpecialization,
{
fn walk_ast<'b>(
&'b self,
_pass: crate::query_builder::AstPass<'_, 'b, DB>,
) -> crate::QueryResult<()> {
Ok(())
}
}
}
#[cfg(test)]
mod tests {
fn assert_send<S: Send>(_: S) {}
#[diesel_test_helper::test]
fn check_boxed_sql_query_is_send() {
let query = crate::sql_query("SELECT 1")
.into_boxed::<<crate::test_helpers::TestConnection as crate::Connection>::Backend>(
);
assert_send(query);
}
}