-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathinsert_and_select.rs
More file actions
70 lines (61 loc) · 1.78 KB
/
Copy pathinsert_and_select.rs
File metadata and controls
70 lines (61 loc) · 1.78 KB
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
use rust_query::{
Database, Transaction,
migration::{Config, schema},
};
// Start by defining your schema.
#[schema(MySchema)]
pub mod vN {
pub struct User {
pub name: String,
}
pub struct Image {
pub description: String,
pub uploaded_by: rust_query::TableRow<User>,
}
}
// Bring the latest schema version into scope.
use v0::*;
// Use your schema to initalize a database.
fn main() {
let database = Database::new(Config::open_in_memory());
database.transaction_mut_ok(|txn| {
do_stuff_with_database(txn);
// Changes are committed at the end of the closure!
});
}
// Use the database to insert and query.
fn do_stuff_with_database(txn: &mut Transaction<MySchema>) {
// Lets make a new user 'mike',
let mike = User {
name: "mike".to_owned(),
};
let mike_id = txn.insert_ok(mike);
// and also insert a dog picture for 'mike'.
let dog_picture = Image {
description: "dog".to_owned(),
uploaded_by: mike_id,
};
let _picture_id = txn.insert_ok(dog_picture);
// Now we want to get all pictures for 'mike'.
let mike_pictures = txn.query(|rows| {
// Initially there is one empty row.
// Lets join the pictures table.
let picture = rows.join(Image);
// 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>());
}