rust-query 0.9.0

A query builder using rust concepts.
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
#![allow(private_bounds, private_interfaces)]
#![doc = include_str!("../README.md")]
#![cfg_attr(not(docsrs), cfg(feature = "base0"))]
#![cfg_attr(docsrs, feature(doc_cfg))]

extern crate self as rust_query;

#[macro_use]
extern crate static_assertions;

#[cfg(doc)]
#[doc = include_str!("_guide.md")]
pub mod _guide {}
// mod ast;
mod async_db;
mod db;
mod error;
mod joinable;
mod lazy;
mod lower;
mod migrate;
mod mutable;
#[cfg(feature = "mutants")]
mod mutants;
mod pool;
mod query;
mod rows;
mod schema;
mod select;
mod transaction;
mod value;
mod writable;

use private::Reader;
use schema::from_macro::TypBuilder;
use std::ops::Deref;

pub use async_db::DatabaseAsync;
pub use db::TableRow;
pub use error::Conflict;
pub use lazy::Lazy;
pub use mutable::Mutable;
pub use select::{IntoSelect, Select};
pub use transaction::{Database, Transaction, TransactionWeak};
pub use value::aggregate::aggregate;
pub use value::from_expr::FromExpr;
pub use value::{Expr, into_expr::IntoExpr, optional::optional};

/// Derive [derive@Select] to create a new `*Select` struct.
///
/// This `*Select` struct will implement the [IntoSelect] trait and can be used
/// with [args::Query::into_iter], [Transaction::query_one] etc.
///
/// Usage can also be nested.
///
/// ```
/// #[rust_query::migration::schema(Schema)]
/// pub mod vN {
///     pub struct Thing {
///         pub details: rust_query::TableRow<Details>,
///         pub beta: f64,
///         pub seconds: i64,
///     }
///     pub struct Details {
///         pub name: String,
///     }
/// }
/// use v0::*;
/// use rust_query::{Table, Select, Transaction};
///
/// #[derive(Select)]
/// struct MyData {
///     seconds: i64,
///     is_it_real: bool,
///     name: String,
///     other: OtherData
/// }
///
/// #[derive(Select)]
/// struct OtherData {
///     alpha: f64,
///     beta: f64,
/// }
///
/// fn do_query(db: &Transaction<Schema>) -> Vec<MyData> {
///     db.query(|rows| {
///         let thing = rows.join(Thing);
///
///         rows.into_vec(MyDataSelect {
///             seconds: &thing.seconds,
///             is_it_real: thing.seconds.lt(100),
///             name: &thing.details.name,
///             other: OtherDataSelect {
///                 alpha: thing.beta.add(2.0),
///                 beta: &thing.beta,
///             },
///         })
///     })
/// }
/// # fn main() {}
/// ```
pub use rust_query_macros::Select;

/// Use in combination with `#[rust_query(From = Thing)]` to specify which tables
/// this struct should implement [trait@FromExpr] for.
///
/// The implementation of [trait@FromExpr] will initialize every field from the column with
/// the corresponding name. It is also possible to change the type of each field
/// as long as the new field type implements [trait@FromExpr].
///
/// ```
/// # use rust_query::migration::schema;
/// # use rust_query::{TableRow, FromExpr};
/// #[schema(Example)]
/// pub mod vN {
///     pub struct User {
///         pub name: String,
///         pub score: i64,
///         pub best_game: Option<rust_query::TableRow<Game>>,
///     }
///     pub struct Game;
/// }
///
/// #[derive(FromExpr)]
/// #[rust_query(From = v0::User)]
/// struct MyUserFields {
///     name: String,
///     best_game: Option<TableRow<v0::Game>>,
/// }
/// # fn main() {}
/// ```
pub use rust_query_macros::FromExpr;

use crate::error::FromConflict;

/// Types that are used as closure arguments.
///
/// You generally don't need to import these types.
pub mod args {
    pub use crate::query::{OrderBy, Query};
    pub use crate::rows::Rows;
    pub use crate::value::aggregate::Aggregate;
    pub use crate::value::optional::Optional;
}

/// Types to declare schemas and migrations.
///
/// A good starting point is too look at [crate::migration::schema].
pub mod migration {
    pub use crate::migrate::{
        Migrator,
        config::{Config, ForeignKeys, Synchronous},
        migration::{Migrated, TransactionMigrate},
    };
    #[cfg(feature = "dev")]
    pub use crate::schema::dev::hash_schema;

    /// Use this macro to define your schema.
    ///
    /// The macro must be applied to a module named `vN`. This is because the module
    /// is a template that can be used to generate multiple modules called `v0`, `v1` etc.
    /// Only one module, named `v0`, is generated by default.
    ///
    /// ```
    /// #[rust_query::migration::schema(SchemaName)]
    /// pub mod vN {
    ///     pub struct TableName {
    ///         pub column_name: i64,
    ///     }
    /// }
    /// use v0::TableName; // the actual module name is `v0`
    /// # fn main() {}
    /// ```
    ///
    /// Note that the schema module, table structs and column fields all must be `pub`.
    /// The `id` column field is currently reserved for internal use and can not be used.
    ///
    /// Supported data types are:
    /// - `i64` (sqlite `integer`)
    /// - `f64` (sqlite `real`)
    /// - `String` (sqlite `text`)
    /// - `Vec<u8>` (sqlite `blob`)
    /// - `bool` (sqlite `integer` with `CHECK "col" IN (0, 1)`)
    /// - Any table in the same schema (sqlite `integer` with foreign key constraint)
    /// - `Option<T>` where `T` is not an `Option` (sqlite nullable)
    ///
    /// ## Unique constraints
    ///
    /// To define a unique constraint on a column, you need to add an attribute to the table or field.
    ///
    /// For example:
    /// ```
    /// #[rust_query::migration::schema(SchemaName)]
    /// pub mod vN {
    ///     #[unique(username, movie)] // <-- here
    ///     pub struct Rating {
    ///         pub movie: String,
    ///         pub username: String,
    ///         #[unique] // <-- or here
    ///         pub uuid: String,
    ///     }
    /// }
    /// ```
    /// This will create a single schema version with a single table called `rating` and three columns.
    /// The table will also have two unique contraints (one on the `uuid` column and one on the combination of `username` and `movie`).
    /// Note that optional types are not allowed in unique constraints.
    ///
    /// ## Indexes
    /// Indexes are very similar to unique constraints, but they don't require the columns to be unique.
    /// These are useful to prevent sqlite from having to scan a whole table.
    /// To incentivise creating indices you also get some extra sugar to use the index!
    ///
    /// ```
    /// #[rust_query::migration::schema(SchemaName)]
    /// pub mod vN {
    ///     pub struct Topic {
    ///         #[unique]
    ///         pub title: String,
    ///         #[index]
    ///         pub category: String,
    ///     }
    /// }
    /// fn test(txn: &rust_query::Transaction<v0::SchemaName>) {
    ///     let _ = txn.lazy_iter(v0::Topic.category("sports"));
    ///     let _ = txn.lazy(v0::Topic.title("star wars"));
    /// }
    /// ```
    ///
    /// The `TableName.column_name(value)` syntax is only allowed if `TableName` has an index or
    /// unique constraint that starts with `column_name`.
    ///
    /// Adding and removing indexes and changing the order of columns in indexes and unique constraints
    /// is considered backwards compatible and thus does not require a new schema version.
    ///
    /// # Multiple schema versions
    ///
    /// At some point you might want to change something substantial in your schema.
    /// It would be really sad if you had to throw away all the old data in your database.
    /// That is why [rust_query] allows us to define multiple schema versions and how to transition between them.
    ///
    /// ## Adding tables
    /// One of the simplest things to do is adding a new table.
    ///
    /// ```
    /// #[rust_query::migration::schema(SchemaName)]
    /// #[version(0..=1)]
    /// pub mod vN {
    ///     pub struct User {
    ///         #[unique]
    ///         pub username: String,
    ///     }
    ///     #[version(1..)] // <-- note that `Game`` has a version range
    ///     pub struct Game {
    ///         #[unique]
    ///         pub name: String,
    ///         pub size: i64,
    ///     }
    /// }
    ///
    /// // These are just examples of tables you can use
    /// use v0::SchemaName as _;
    /// use v1::SchemaName as _;
    /// use v0::User as _;
    /// use v1::User as _;
    /// // `v0::Game` does not exist
    /// use v1::Game as _;
    /// # fn main() {}
    ///
    /// fn migrate() -> rust_query::Database<v1::SchemaName> {
    ///     rust_query::Database::migrator(rust_query::migration::Config::open("test.db"))
    ///         .expect("database version is before supported versions")
    ///         .migrate(|_txn| v0::migrate::SchemaName {})
    ///         .finish()
    ///         .expect("database version is after supported versions")
    /// }
    /// ```
    /// The migration itself is not very interesting because new tables are automatically created
    /// without any data. To have some initial data, take a look at the `#[from]` attribute down below or use
    /// [crate::migration::Migrator::fixup].
    ///
    /// ## Changing columns
    /// Changing columns is very similar to adding and removing structs.
    /// ```
    /// use rust_query::migration::{schema, Config};
    /// use rust_query::{Database, Lazy};
    /// #[schema(Schema)]
    /// #[version(0..=1)]
    /// pub mod vN {
    ///     pub struct User {
    ///         #[unique]
    ///         pub username: String,
    ///         #[version(1..)] // <-- here
    ///         pub score: i64,
    ///     }
    /// }
    /// pub fn migrate() -> Database<v1::Schema> {
    ///     Database::migrator(Config::open_in_memory()) // we use an in memory database for this test
    ///         .expect("database version is before supported versions")
    ///         .migrate(|txn| v0::migrate::Schema {
    ///             // In this case it is required to provide a value for each row that already exists.
    ///             // This is done with the `v0::migrate::User` struct:
    ///             user: txn.migrate_ok(|old: Lazy<v0::User>| v0::migrate::User {
    ///                 score: old.username.len() as i64 // use the username length as the new score
    ///             }),
    ///         })
    ///         .finish()
    ///         .expect("database version is after supported versions")
    /// }
    /// # fn main() {}
    /// ```
    ///
    /// ## `#[from(TableName)]` Attribute
    /// You can use this attribute when renaming or splitting a table.
    /// This will make it clear that data in the table should have the
    /// same row ids as the `from` table.
    ///
    /// For example:
    ///
    /// ```
    /// # use rust_query::migration::{schema, Config};
    /// # use rust_query::{Database, Lazy};
    /// # fn main() {}
    /// #[schema(Schema)]
    /// #[version(0..=1)]
    /// pub mod vN {
    ///     #[version(..1)]
    ///     pub struct User {
    ///         pub name: String,
    ///     }
    ///     #[version(1..)]
    ///     #[from(User)]
    ///     pub struct Author {
    ///         pub name: String,
    ///     }
    ///     pub struct Book {
    ///         pub author: rust_query::TableRow<Author>,
    ///     }
    /// }
    /// pub fn migrate() -> Database<v1::Schema> {
    ///     Database::migrator(Config::open_in_memory()) // we use an in memory database for this test
    ///         .expect("database version is before supported versions")
    ///         .migrate(|txn| v0::migrate::Schema {
    ///             author: txn.migrate_ok(|old: Lazy<v0::User>| v0::migrate::Author {
    ///                 name: old.name.clone(),
    ///             }),
    ///         })
    ///         .finish()
    ///         .expect("database version is after supported versions")
    /// }
    /// ```
    /// In this example the `Book` table exists in both `v0` and `v1`,
    /// however `User` only exists in `v0` and `Author` only exist in `v1`.
    /// Note that the `pub author: Author` field only specifies the latest version
    /// of the table, it will use the `#[from]` attribute to find previous versions.
    ///
    /// ## `#[no_reference]` Attribute
    /// You can put this attribute on your table definitions and it will make it impossible
    /// to have foreign key references to such table.
    /// This makes it possible to use `TransactionWeak::delete_ok`.
    pub use rust_query_macros::schema;
}

/// These items are only exposed for use by the proc macros.
/// Direct use is unsupported.
#[doc(hidden)]
pub mod private {

    pub use crate::joinable::{IntoJoinable, Joinable};
    pub use crate::migrate::{
        Schema, SchemaMigration, TableTypBuilder,
        migration::{Migration, SchemaBuilder},
    };
    pub use crate::query::get_plan;
    pub use crate::schema::from_macro::{SchemaType, TypBuilder};
    pub use crate::schema::tokenizer::{Token, get_token};
    pub use crate::value::{DbTyp, adhoc_expr, new_column, unique_from_joinable};
    pub use crate::writable::Reader;

    // pub trait Apply {
    //     type Out<T: MigrateTyp>;
    // }

    // pub struct AsNormal;
    // impl Apply for AsNormal {
    //     type Out<T: MigrateTyp> = T;
    // }

    // struct AsExpr<'x, S>(PhantomData<(&'x (), S)>);
    // impl<'x, S> Apply for AsExpr<'x, S> {
    //     type Out<T: MigrateTyp> = crate::Expr<'x, S, T::ExprTyp>;
    // }

    // struct AsLazy<'x>(PhantomData<&'x ()>);
    // impl<'x> Apply for AsLazy<'x> {
    //     type Out<T: MigrateTyp> = T::Lazy<'x>;
    // }

    pub mod doctest_aggregate {
        #[crate::migration::schema(M)]
        pub mod vN {
            pub struct Val {
                pub x: i64,
            }
        }
        pub use crate::aggregate;
        pub use v0::*;

        #[cfg_attr(test, mutants::skip)]
        pub fn get_txn(f: impl Send + FnOnce(&'static mut crate::Transaction<M>)) {
            crate::Database::new(rust_query::migration::Config::open_in_memory())
                .transaction_mut_ok(f)
        }
    }

    pub mod doctest {
        use crate::{Database, Transaction, migrate::config::Config, migration};

        #[migration::schema(Empty)]
        pub mod vN {
            pub struct User {
                #[unique]
                pub name: String,
            }
        }
        pub use v0::*;

        #[cfg_attr(test, mutants::skip)]
        pub fn get_txn(f: impl Send + FnOnce(&'static mut Transaction<Empty>)) {
            let db = Database::new(Config::open_in_memory());
            db.transaction_mut_ok(|txn| {
                txn.insert(User {
                    name: "Alice".to_owned(),
                })
                .unwrap();
                f(txn)
            })
        }
    }
}

/// This trait is implemented for all table types as generated by the [crate::migration::schema] macro.
///
/// **You can not implement this trait yourself!**
pub trait Table: Sized + 'static {
    #[doc(hidden)]
    type Ext2<'t>;

    #[doc(hidden)]
    fn covariant_ext<'x, 't>(val: &'x Self::Ext2<'static>) -> &'x Self::Ext2<'t>;

    #[doc(hidden)]
    fn build_ext2<'t>(val: &Expr<'t, Self::Schema, TableRow<Self>>) -> Self::Ext2<'t>;

    /// The schema that this table is a part of.
    type Schema;

    #[doc(hidden)]
    /// The table that this table can be migrated from.
    type MigrateFrom: Table;

    /// The type of conflict that can result from inserting a row in this table.
    /// This is the same type that is used for row updates too.
    type Conflict: FromConflict;
    /// The type of error when a delete fails due to a foreign key constraint.
    type Referer;

    #[doc(hidden)]
    type Mutable: Deref;
    #[doc(hidden)]
    type Lazy<'t>;

    #[doc(hidden)]
    fn read(&self, f: &mut Reader);

    #[doc(hidden)]
    type Select;

    #[doc(hidden)]
    fn into_select(
        val: Expr<'_, Self::Schema, TableRow<Self>>,
    ) -> Select<'_, Self::Schema, Self::Select>;

    #[doc(hidden)]
    fn select_mutable(select: Self::Select) -> Self::Mutable;

    #[doc(hidden)]
    fn select_lazy<'t>(select: Self::Select) -> Self::Lazy<'t>;

    #[doc(hidden)]
    fn mutable_as_unique(val: &mut Self::Mutable) -> &mut <Self::Mutable as Deref>::Target;

    #[doc(hidden)]
    fn mutable_into_insert(val: Self::Mutable) -> Self
    where
        Self: Sized;

    #[doc(hidden)]
    fn get_referer_unchecked() -> Self::Referer;

    #[doc(hidden)]
    fn typs(f: &mut TypBuilder<Self::Schema>);

    #[doc(hidden)]
    const SPAN: (usize, usize);

    #[doc(hidden)]
    const ID: &'static str;
    #[doc(hidden)]
    const NAME: &'static str;
}

trait CustomJoin: Table {
    fn name(&self) -> lower::JoinableTable;
    fn main_column(&self) -> &'static str;
}

#[test]
#[cfg(feature = "jiff-02")]
fn compile_tests() {
    let t = trybuild::TestCases::new();
    t.compile_fail("tests/compile/*.rs");
}