-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathinsert_and_select.rs
76 lines (67 loc) · 2.06 KB
/
insert_and_select.rs
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
use rust_query::{
migration::{schema, Config},
LocalClient, Table, TransactionMut,
};
// Start by defining your schema.
#[schema]
enum MySchema {
User {
name: String,
},
Image {
description: String,
uploaded_by: User,
},
}
// Bring the latest schema version into scope.
use v0::*;
// Use your schema to initalize a database.
fn main() {
// Get a LocalClient to prove that we have our own thread.
// This is necessary to keep transactions separated.
let mut client = LocalClient::try_new().unwrap();
let database = client
.migrator(Config::open_in_memory())
.expect("database version is before supported versions")
// migrations go here
.finish()
.expect("database version is after supported versions");
let mut txn = client.transaction_mut(&database);
do_stuff_with_database(&mut txn);
// After we are done we commit the changes!
txn.commit();
}
// Use the database to insert and query.
fn do_stuff_with_database(db: &mut TransactionMut<MySchema>) {
// Lets make a new user 'mike',
let mike = User { name: "mike" };
let mike_id = db.insert(mike);
// and also insert a dog picture for 'mike'.
let dog_picture = Image {
description: "dog",
uploaded_by: mike_id,
};
let _picture_id = db.insert(dog_picture);
// Now we want to get all pictures for 'mike'.
let mike_pictures = db.query(|rows| {
// Initially there is one empty row.
// Lets join the pictures table.
let picture = Image::join(rows);
// Now lets filter for pictures from mike,
rows.filter(picture.uploaded_by().eq(mike_id));
// and finally turn the rows into a vec.
rows.into_vec(picture.description())
});
println!("{mike_pictures:?}"); // This should print `["dog"]`.
}
#[test]
fn run() {
main();
}
#[test]
#[cfg(feature = "dev")]
fn schema_hash() {
use expect_test::expect;
use rust_query::migration::hash_schema;
expect!["e6dbf93daba3ccfa"].assert_eq(&hash_schema::<v0::MySchema>());
}