crudly 0.6.0

Derivable crud helpers for sqlx. Write your SELECT, INSERT, UPDATE and DELETE queries once and reuse them for all your entities.
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
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
use crate::HasColumns;
use crate::HasId;
use crate::IntoRow;
use crate::Schema;
use crate::sql::reusable_executor::ReusableExecutor;
use sqlx::AssertSqlSafe;
use sqlx::{
    Arguments, Database, Encode, Executor, FromRow, IntoArguments, Type, query, query_as,
    query_with,
};

/// There is a similar function here: [sqlx::Arguments::format_placeholder] but thats
/// only really usable via the [sqlx::QueryBuilder] which is highly
/// undocumented and does not seem to be of great use here.
pub trait FormatPlaceholder {
    /// # Arguments
    /// - `idx`: The index of the placeholder starting at 0
    fn format_placeholder(idx: usize) -> String;
}

pub trait RowsAffected {
    fn rows_affected(&self) -> u64;
}

pub trait LastInsertedRowId {
    fn last_insert_rowid(&self) -> i64;
}

/// # Returns
/// A string of `n` placeholders separated by commas.
pub(super) fn format_placeholders<DB: FormatPlaceholder>(n: usize) -> String {
    (0..n)
        .map(|idx| DB::format_placeholder(idx))
        .collect::<Vec<String>>()
        .join(",")
}

/// # Returns
/// A comma-delimited, double-quoted string of every column returned by [`Schema::columns`].
/// For types with an id field this includes the id column (it is listed first by the derive).
pub(super) fn comma_delimited_columns<S>() -> String
where
    S: Schema,
{
    <S as Schema>::columns()
        .into_iter()
        .map(|c| format!("\"{c}\""))
        .collect::<Vec<String>>()
        .join(",")
}

pub async fn generic_select_all<S, DB: Database>(
    executor: impl Executor<'_, Database = DB>,
) -> sqlx::Result<Vec<S>>
where
    S: Schema + HasId + for<'r> FromRow<'r, DB::Row> + Unpin,
    <DB as Database>::Arguments: IntoArguments<DB>,
{
    let columns = comma_delimited_columns::<S>();
    let table_name = S::table_name();
    let id_column = S::id_column();

    let sql = format!("SELECT {columns} FROM {table_name} ORDER BY {id_column} ASC;");
    query_as(AssertSqlSafe(sql)).fetch_all(executor).await
}

/// Like [`generic_select_all`] but for entities without an id column; selects all columns from
/// [`Schema::columns`] with no `ORDER BY`.
pub async fn generic_select_all_no_id<S, DB: Database>(
    executor: impl Executor<'_, Database = DB>,
) -> sqlx::Result<Vec<S>>
where
    S: Schema + for<'r> FromRow<'r, DB::Row> + Unpin,
    <DB as Database>::Arguments: IntoArguments<DB>,
{
    let columns = comma_delimited_columns::<S>();
    let table_name = S::table_name();
    let sql = format!("SELECT {columns} FROM {table_name};");
    query_as(AssertSqlSafe(sql)).fetch_all(executor).await
}

pub async fn generic_delete_all<S, DB: Database>(
    executor: impl Executor<'_, Database = DB>,
) -> sqlx::Result<()>
where
    S: Schema,
    <DB as Database>::Arguments: IntoArguments<DB>,
{
    let table_name = S::table_name();
    let sql = format!("DELETE FROM {table_name};");
    query(AssertSqlSafe(sql)).execute(executor).await?;
    Ok(())
}

pub async fn generic_select_by_id<S, DB>(
    executor: impl Executor<'_, Database = DB>,
    id: &S::Id,
) -> sqlx::Result<Option<S>>
where
    DB: Database + FormatPlaceholder,
    S::Id: for<'q> Encode<'q, DB> + Type<DB>,
    S: Schema + HasId + for<'r> FromRow<'r, DB::Row> + Unpin,
    <DB as Database>::Arguments: IntoArguments<DB>,
{
    let columns = comma_delimited_columns::<S>();
    let table_name = S::table_name();
    let id_column = S::id_column();

    let placeholder = DB::format_placeholder(0);

    let sql = format!("SELECT {columns} FROM {table_name} WHERE {id_column} = {placeholder};");
    query_as(AssertSqlSafe(sql))
        .bind(id)
        .fetch_optional(executor)
        .await
}

pub async fn generic_select_by_ids<S, DB>(
    executor: impl Executor<'_, Database = DB>,
    ids: Vec<S::Id>,
    batch_size: usize,
) -> sqlx::Result<Vec<S>>
where
    DB: Database + FormatPlaceholder,
    S::Id: for<'q> Encode<'q, DB> + Type<DB>,
    S: Schema + HasId + for<'r> FromRow<'r, DB::Row> + Unpin,
    <DB as Database>::Arguments: IntoArguments<DB>,
{
    if ids.is_empty() {
        return Ok(Vec::new());
    }

    let columns = comma_delimited_columns::<S>();
    let table_name = S::table_name();
    let id_column = S::id_column();
    let ids_len = ids.len();
    let in_group_size = if batch_size == 0 {
        ids_len
    } else {
        batch_size.min(ids_len)
    };

    let mut next_placeholder_idx = 0;
    let mut in_clauses = Vec::new();
    let mut remaining = ids_len;
    while remaining > 0 {
        let current_group = in_group_size.min(remaining);
        let placeholders = (0..current_group)
            .map(|_| {
                let placeholder = DB::format_placeholder(next_placeholder_idx);
                next_placeholder_idx += 1;
                placeholder
            })
            .collect::<Vec<String>>()
            .join(",");
        in_clauses.push(format!("{id_column} IN ({placeholders})"));
        remaining -= current_group;
    }

    let sql = format!(
        "SELECT {columns} FROM {table_name} WHERE {} ORDER BY {id_column} ASC;",
        in_clauses.join(" OR ")
    );

    let mut query = query_as(AssertSqlSafe(sql));
    for id in ids {
        query = query.bind(id);
    }

    query.fetch_all(executor).await
}

pub async fn generic_id_exists<S, DB>(
    executor: impl Executor<'_, Database = DB>,
    id: &S::Id,
) -> sqlx::Result<bool>
where
    DB: Database + FormatPlaceholder,
    S::Id: for<'q> Encode<'q, DB> + Type<DB>,
    S: Schema + HasId,
    <DB as Database>::Arguments: IntoArguments<DB>,
{
    let table_name = S::table_name();
    let id_column = S::id_column();

    let placeholder = DB::format_placeholder(0);

    let sql = format!("SELECT 1 FROM {table_name} WHERE \"{id_column}\" = {placeholder};");

    query(AssertSqlSafe(sql))
        .bind(id)
        .fetch_optional(executor)
        .await
        .map(|option| option.is_some())
}

pub async fn generic_insert_with_id<S, DB>(
    executor: impl Executor<'_, Database = DB>,
    entity: S,
) -> sqlx::Result<()>
where
    DB: Database + FormatPlaceholder,
    S::Id: for<'q> Encode<'q, DB> + Type<DB>,
    S: Schema + IntoRow<DB> + HasId,
    <DB as Database>::Arguments: IntoArguments<DB>,
{
    let table_name = S::table_name();
    let columns = comma_delimited_columns::<S>();
    let placeholders = format_placeholders::<DB>(<S as Schema>::columns().len());

    let sql = format!("INSERT INTO {table_name} ({columns}) VALUES ({placeholders})");

    let mut arguments = DB::Arguments::default();
    arguments.add(entity.id()).map_err(sqlx::Error::Encode)?;
    entity.bind_arguments(&mut arguments)?;

    query_with(AssertSqlSafe(sql), arguments)
        .execute(executor)
        .await?;
    Ok(())
}

pub async fn generic_insert_without_id<S, DB>(
    executor: impl Executor<'_, Database = DB>,
    entity: S,
) -> sqlx::Result<DB::QueryResult>
where
    DB: Database + FormatPlaceholder,
    S: Schema + IntoRow<DB>,
    <DB as Database>::Arguments: IntoArguments<DB>,
{
    let table_name = S::table_name();
    let non_id_columns = <S as HasColumns>::columns();
    let columns = non_id_columns
        .iter()
        .map(|c| format!("\"{c}\""))
        .collect::<Vec<String>>()
        .join(",");

    let placeholders = format_placeholders::<DB>(non_id_columns.len());

    let sql = format!("INSERT INTO {table_name} ({columns}) VALUES ({placeholders})");

    let mut arguments = DB::Arguments::default();
    entity.bind_arguments(&mut arguments)?;

    query_with(AssertSqlSafe(sql), arguments)
        .execute(executor)
        .await
}

pub async fn generic_insert_returning_id<S, DB>(
    executor: impl Executor<'_, Database = DB>,
    entity: S,
) -> sqlx::Result<i64>
where
    DB: Database + FormatPlaceholder,
    DB::QueryResult: LastInsertedRowId,
    S: Schema + IntoRow<DB>,
    <DB as Database>::Arguments: IntoArguments<DB>,
{
    let result = generic_insert_without_id::<S, DB>(executor, entity).await?;
    Ok(result.last_insert_rowid())
}

/// Inserts many rows, omitting the id column (same shape as [`generic_insert_returning_id`] per row).
///
/// When `batch_size` is `0`, runs a single `INSERT` for all rows. Otherwise splits into multiple
/// statements of at most `batch_size` rows each.
pub async fn generic_insert_many_without_id<S, DB, E>(
    mut executor: E,
    entities: Vec<S>,
    batch_size: usize,
) -> sqlx::Result<()>
where
    E: ReusableExecutor<DB>,
    DB: Database + FormatPlaceholder,
    S: Schema + IntoRow<DB>,
    <DB as Database>::Arguments: IntoArguments<DB>,
{
    if entities.is_empty() {
        return Ok(());
    }

    let table_name = S::table_name();
    let non_id_columns = <S as HasColumns>::columns();
    let columns = non_id_columns
        .iter()
        .map(|c| format!("\"{c}\""))
        .collect::<Vec<String>>()
        .join(",");

    let cols_per_row = non_id_columns.len();

    let mut rest = entities;

    while !rest.is_empty() {
        let chunk_len = if batch_size == 0 {
            rest.len()
        } else {
            batch_size.min(rest.len())
        };
        let chunk = rest.split_off(chunk_len);
        let chunk_entities = std::mem::replace(&mut rest, chunk);

        let mut placeholder_idx = 0;
        let mut value_tuples = Vec::with_capacity(chunk_len);
        for _ in 0..chunk_len {
            let placeholders = (0..cols_per_row)
                .map(|_| {
                    let p = DB::format_placeholder(placeholder_idx);
                    placeholder_idx += 1;
                    p
                })
                .collect::<Vec<String>>()
                .join(",");
            value_tuples.push(format!("({placeholders})"));
        }

        let sql = format!(
            "INSERT INTO {table_name} ({columns}) VALUES {}",
            value_tuples.join(",")
        );

        let mut arguments = DB::Arguments::default();
        for entity in chunk_entities {
            entity.bind_arguments(&mut arguments)?;
        }
        executor
            .execute_query_with(AssertSqlSafe(sql), arguments)
            .await?;
    }

    Ok(())
}

/// Inserts many rows, with the id column (same shape as [`generic_insert_with_id`] per row).
///
/// When `batch_size` is `0`, runs a single `INSERT` for all rows. Otherwise splits into multiple
/// statements of at most `batch_size` rows each.
pub async fn generic_insert_many_with_id<'c, S, DB, E>(
    mut executor: E,
    entities: Vec<S>,
    batch_size: usize,
) -> sqlx::Result<()>
where
    S::Id: for<'q> Encode<'q, DB> + Type<DB>,
    E: ReusableExecutor<DB> + Send,
    DB: Database + FormatPlaceholder,
    S: Schema + IntoRow<DB> + HasId,
    <DB as Database>::Arguments: IntoArguments<DB>,
{
    if entities.is_empty() {
        return Ok(());
    }

    let table_name = S::table_name();
    let columns = comma_delimited_columns::<S>();

    let cols_per_row = <S as Schema>::columns().len();

    let mut rest = entities;

    while !rest.is_empty() {
        let chunk_len = if batch_size == 0 {
            rest.len()
        } else {
            batch_size.min(rest.len())
        };
        let remainder = rest.split_off(chunk_len);

        let mut placeholder_idx = 0;
        let mut value_tuples = Vec::with_capacity(chunk_len);
        for _ in 0..chunk_len {
            let placeholders = (0..cols_per_row)
                .map(|_| {
                    let p = DB::format_placeholder(placeholder_idx);
                    placeholder_idx += 1;
                    p
                })
                .collect::<Vec<String>>()
                .join(",");
            value_tuples.push(format!("({placeholders})"));
        }

        let sql = format!(
            "INSERT INTO {table_name} ({columns}) VALUES {}",
            value_tuples.join(",")
        );

        let mut arguments = DB::Arguments::default();
        for entity in rest {
            arguments.add(entity.id()).map_err(sqlx::Error::Encode)?;
            entity.bind_arguments(&mut arguments)?;
        }
        executor
            .execute_query_with(AssertSqlSafe(sql), arguments)
            .await?;
        rest = remainder;
    }

    Ok(())
}

/// # Returns
/// - Ok(true) if the entity was updated
/// - Ok(false) if it didn't exist
/// - Err(e) on error
pub async fn generic_update_by_id<S, DB>(
    executor: impl Executor<'_, Database = DB>,
    entity: S,
) -> sqlx::Result<bool>
where
    DB: Database + FormatPlaceholder,
    DB::QueryResult: RowsAffected,
    S::Id: for<'q> Encode<'q, DB> + Type<DB>,
    S: Schema + IntoRow<DB> + HasId,
    <DB as Database>::Arguments: IntoArguments<DB>,
{
    let table_name = S::table_name();
    let id_column = S::id_column();

    let mut set_sql = String::new();

    // columns are expected not to be empty
    for (idx, column) in <S as HasColumns>::columns().iter().enumerate() {
        if idx > 0 {
            set_sql.push(',');
        }
        set_sql.push_str(&format!(
            "\"{column}\"={placeholder}",
            placeholder = DB::format_placeholder(idx)
        ));
    }

    let entity_id = entity.id();

    let id_placeholder = DB::format_placeholder(<S as HasColumns>::columns().len());
    let sql = format!("UPDATE {table_name} SET {set_sql} WHERE {id_column} = {id_placeholder}");

    let mut arguments = DB::Arguments::default();
    entity.bind_arguments(&mut arguments)?;
    arguments.add(entity_id).map_err(sqlx::Error::Encode)?;

    let result = query_with(AssertSqlSafe(sql), arguments)
        .execute(executor)
        .await?;
    Ok(result.rows_affected() > 0)
}

/// # Returns
/// - Ok(true) if the entity was deleted
/// - Ok(false) if it didn't exist
/// - Err(e) on error
pub async fn generic_delete_by_id<S, DB>(
    executor: impl Executor<'_, Database = DB>,
    id: &S::Id,
) -> sqlx::Result<bool>
where
    DB: Database + FormatPlaceholder,
    DB::QueryResult: RowsAffected,
    S::Id: for<'q> Encode<'q, DB> + Type<DB>,
    S: Schema + HasId,
    <DB as Database>::Arguments: IntoArguments<DB>,
{
    let table_name = S::table_name();
    let id_column = S::id_column();
    let id_placeholder = DB::format_placeholder(0);

    let sql = format!("DELETE FROM {table_name} WHERE {id_column} = {id_placeholder}");

    let result = query(AssertSqlSafe(sql)).bind(id).execute(executor).await?;

    Ok(result.rows_affected() > 0)
}

#[cfg(test)]
pub mod tests {
    use super::*;
    use crate::{HasColumns, HasId, IntoRow, Schema};
    use sqlx::{Sqlite, SqliteConnection, SqlitePool};

    pub struct Dummy;

    impl HasColumns for Dummy {
        fn columns() -> Vec<&'static str> {
            unimplemented!()
        }
    }

    impl IntoRow<Sqlite> for Dummy {
        fn bind_arguments(
            self,
            _arguments: &mut <Sqlite as Database>::Arguments,
        ) -> sqlx::Result<()> {
            unimplemented!()
        }
    }

    impl Schema for Dummy {
        fn table_name() -> &'static str {
            unimplemented!()
        }

        fn columns() -> Vec<&'static str> {
            unimplemented!()
        }
    }

    impl HasId for Dummy {
        type Id = i64;

        fn id(&self) -> Self::Id {
            unimplemented!()
        }

        fn id_column() -> &'static str {
            unimplemented!()
        }
    }

    #[allow(dead_code)]
    async fn test_exec_pool_owned(pool: SqlitePool) {
        generic_insert_many_without_id(&pool, vec![Dummy], 0)
            .await
            .unwrap();
    }

    #[allow(dead_code)]
    async fn test_exec_pool_borrowed(pool: &SqlitePool) {
        generic_insert_many_without_id(pool, vec![Dummy], 0)
            .await
            .unwrap();

        generic_insert_many_without_id(pool, vec![Dummy], 0)
            .await
            .unwrap();
    }

    #[allow(dead_code)]
    async fn test_exec_pool_exclusive(pool: &mut SqlitePool) {
        generic_insert_many_without_id(&mut *pool, vec![Dummy], 0)
            .await
            .unwrap();

        generic_insert_many_without_id(&mut *pool, vec![Dummy], 0)
            .await
            .unwrap();
    }

    #[allow(dead_code)]
    async fn test_exec_con(con: &mut SqliteConnection) {
        generic_insert_many_without_id(&mut *con, vec![Dummy], 100)
            .await
            .unwrap();

        generic_insert_many_without_id(&mut *con, vec![Dummy], 100)
            .await
            .unwrap();
    }
}