Type safe SQLite using the Rust type system
The goal of this library is to allow using relational databases (only SQLite right now) using familiar Rust syntax. The library should guarantee that queries and migrations can not fail when they compile. While rust-query goes quite far to achieve this, there are still some exceptions that can cause queries to fail, such as integer overflow.
Writing queries using this library involves:
- Interact with row/column references as Rust values.
- Lifetimes to check the scopes of row/column references.
- Procedural mutation of row sets with methods like
filter
andjoin
. - "Combinators" like
optional
andaggregate
.
Notably writing queries itself does not involve any new syntax or macro, while still being completely type safe. (There are macros to define the schema and to simplify defining composite types to retrieve from queries)
What it looks like
Define a schema using the syntax of a module with structs:
#
use schema;
Get proof that we are running on a unique thread:
# use LocalClient;
let mut client = try_new.unwrap;
Initialize a database:
let database = client
.migrator
.expect
// migrations go here
.finish
.expect;
Perform a transaction!
let mut txn = client.transaction_mut;
do_stuff_with_database;
// After we are done we commit the changes!
txn.commit;
Insert in the database:
// Lets make a new user 'mike',
let mike = User ;
let mike_id = txn.insert_ok;
// and also insert a dog picture for 'mike'.
let dog_picture = Image ;
let _picture_id = txn.insert_ok;
Query from the database:
// Now we want to get all pictures for 'mike'.
let mike_pictures = txn.query;
println!; // This should print `["dog"]`.
The full example code can be found in insert_and_select.rs
Examples
For more examples you can look at the examples directory.
Roadmap
This project is under development and there are some things missing. Below is a checklist of planned features and implemented features. (Implemented features have a checkmark, planned features do not).
Schema:
- Basic types (integer, real, text, blob, null)
- Basic foreign keys
- (Multi column) unique constraints
- Check constraints
- Overlapping foreign keys
Statements:
- Multi row query + single row query (and optional query)
- Single row insert, update and delete
Expressions:
- Some basic math, boolean and string operations
- Aggregate combinator
- Optional combinator
- Everything else
Advanced operations:
- Window
- Limit
Despite these limitations, I am dogfooding this query builder and using it in my own project: advent-of-wasm.