### Serve Toasty Guide Locally Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/README.md Starts a local development server for the Toasty guide, opening it in a browser. The server automatically rebuilds the guide on file changes, facilitating rapid iteration. ```sh mdbook serve docs/guide --open ``` -------------------------------- ### Build Toasty Guide Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/README.md Performs a one-shot build of the Toasty user guide, outputting HTML to the 'docs/guide/book/' directory. This command is used in the CI process. ```sh mdbook build docs/guide ``` -------------------------------- ### Full Query Expansion Example Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/design/query-macro.md Presents a comprehensive example of a complex `query!` macro input and its full expansion into a chain of query builder methods. ```rust // Input: query!(User { todos } FILTER .name == "Carl" ORDER BY .created_at DESC LIMIT 10) // Expands to: User::filter(User::fields().name().eq("Carl")) .include(User::fields().todos()) .order_by(User::fields().created_at().desc()) .limit(10) ``` -------------------------------- ### Install mdBook and linkcheck2 Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/README.md Installs the necessary tools for building and checking the Toasty user guide locally. Ensure the mdBook version matches the one pinned in the CI workflow. ```sh cargo install mdbook@0.5.2 mdbook-linkcheck2 ``` -------------------------------- ### Example Docs Commit Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/COMMITS.md Use the 'docs' type for documentation-only changes. This example shows linking a documentation file. ```text docs: link COMMITS.md from CONTRIBUTING ``` -------------------------------- ### Connect to PostgreSQL Database Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/postgresql.md Connect to a PostgreSQL database using a connection URL. This example shows basic connection setup with models. ```rust let db = toasty::Db::builder() .models(toasty::models!(crate::*)) .connect("postgresql://user:pass@localhost:5432/mydb") .await?; ``` -------------------------------- ### Connect to Database with Models Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/getting-started.md Example of building a database connection handle and registering models from the current crate. ```rust let mut db = toasty::Db::builder() .models(toasty::models!(crate::*)) .connect("sqlite::memory:") .await?; ``` -------------------------------- ### Connection URL Examples Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/database-setup.md Provides examples of connection URLs for various database backends, including in-memory SQLite, file-based SQLite, PostgreSQL, MySQL, and DynamoDB. Ensure the corresponding feature flag is enabled in `Cargo.toml`. ```rust // In-memory SQLite .connect("sqlite::memory:") ``` ```rust // SQLite file .connect("sqlite:./path/to/db.sqlite") ``` ```rust // PostgreSQL .connect("postgresql://user:pass@localhost:5432/mydb") ``` ```rust // MySQL .connect("mysql://user:pass@localhost:3306/mydb") ``` ```rust // DynamoDB (uses AWS config from environment) .connect("dynamodb://us-east-1") ``` -------------------------------- ### Example Output Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/getting-started.md Expected output after running the Rust project, showing the created and fetched user details. ```text Created: "Alice" Found: "alice@example.com" ``` -------------------------------- ### Example User and Todo Models Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/design/static-assertions-create-macro.md These are example Rust structs representing User and Todo models, used to demonstrate the problem of missing required fields in the `create!` macro. ```rust #[derive(Model)] struct User { #[key] #[auto] id: Id, name: String, #[has_many] todos: Deferred>, } #[derive(Model)] struct Todo { #[key] #[auto] id: Id, #[index] user_id: Id, #[belongs_to(key = user_id, references = id)] user: Deferred, title: String, } ``` -------------------------------- ### Path Structure Example Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/architecture/path-system.md Illustrates the basic structure of a Path, including its root and projection. ```rust Path { root: PathRoot::Model(user_model_id), projection: [2], // third field on User } ``` -------------------------------- ### Test Toasty Guide Code Samples Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/README.md Compiles and tests all runnable code samples within the Toasty guide using rustdoc. This ensures that the examples are correct and the Toasty crate is properly integrated. ```sh cargo test -p tests --doc ``` -------------------------------- ### Source Expansion Example Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/design/query-macro.md Shows how the `query!(User)` macro input expands to the `User::all()` method call in the underlying query builder API. ```rust // Input: query!(User) // Expands to: User::all() ``` -------------------------------- ### Start and Commit a Transaction Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/transactions.md Begins a transaction, performs create operations, and then commits the changes. ```rust use toasty::{Model, Executor}; #[derive(Debug, toasty::Model)] struct User { #[key] #[auto] id: u64, name: String, } async fn __example(mut db: toasty::Db) -> toasty::Result<()> { let mut tx = db.transaction().await?; toasty::create!(User { name: "Alice" }).exec(&mut tx).await?; toasty::create!(User { name: "Bob" }).exec(&mut tx).await?; tx.commit().await?; Ok(()) } ``` -------------------------------- ### Example Feat Commit Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/COMMITS.md Use the 'feat' type for new features. This example shows a feature that simplifies a Match expression in the engine. ```text feat(engine): simplify uniform-arms Match into a projection When every arm of a Match produces the same shape, projection can be pushed through the Match and the arms folded together. This enables the planner to emit a single SQL expression for enum-over-primitive comparisons instead of a CASE. ``` -------------------------------- ### Generated SQL Example (SQLite) Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/schema-management.md An example of database-specific SQL DDL generated by Toasty for SQLite. It includes table creation and index definition, with breakpoint comments for statement splitting. ```sql CREATE TABLE "users" ( "id" TEXT NOT NULL, "name" TEXT NOT NULL, "email" TEXT NOT NULL, PRIMARY KEY ("id") ); -- #[toasty::breakpoint] CREATE UNIQUE INDEX "index_users_by_email" ON "users" ("email"); ``` -------------------------------- ### Quick Schema Setup with `push_schema` Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/schema-management.md Use `db.push_schema()` to create all tables and indexes based on registered models. This is suitable for prototyping and tests as it pushes the full schema on each run. ```rust let mut db = toasty::Db::builder() .models(toasty::models!(crate::*)) .connect("sqlite::memory:") .await?; db.push_schema().await?; ``` -------------------------------- ### Generated CreateMeta Example Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/design/static-assertions-create-macro.md An example of a `CreateMeta` constant generated by the `#[derive(Model)]` macro, showing how `required` is determined based on the `Field::NULLABLE` trait. ```rust // generated by #[derive(Model)] const CREATE_META: CreateMeta = CreateMeta { fields: &[ CreateField { name: "name", required: !::NULLABLE }, CreateField { name: "bio", required: ! as Field>::NULLABLE }, ], model_name: "User", }; ``` -------------------------------- ### SQL for Custom Column Name Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/field-options.md Example SQL `CREATE TABLE` statement showing the custom column name `display_name`. ```sql CREATE TABLE users ( id INTEGER PRIMARY KEY AUTOINCREMENT, display_name TEXT NOT NULL ); ``` -------------------------------- ### String Prefix Matching with starts_with Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/filtering-with-expressions.md Tests if a string field starts with a given prefix. This is case-sensitive and works across all supported databases. ```rust # use toasty::Model; # #[derive(Debug, toasty::Model)] # struct User { # #[key] # #[auto] # id: u64, # name: String, # } # async fn __example(mut db: toasty::Db) -> toasty::Result<()> { // Find users whose name starts with "Al" let users = User::filter(User::fields().name().starts_with("Al")) .exec(&mut db) .await?; # Ok(()) # } ``` -------------------------------- ### SQL to Toasty Program Compilation Example Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/architecture/query-engine.md Illustrates how a SQL query involving nested selects is compiled into a sequence of executable actions and variables within the Toasty engine. ```sql SELECT users.id, users.name, ( SELECT todos.id, todos.title FROM todos WHERE todos.user_id = users.id ) FROM users WHERE ... ``` ```text $0 = ExecSQL("SELECT * FROM users WHERE ...") $1 = ExecSQL("SELECT * FROM todos WHERE user_id IN ...") $2 = NestedMerge($0, $1, by: user_id) return $2 ``` -------------------------------- ### Runtime Panic Example Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/design/static-assertions-create-macro.md This code snippet demonstrates a scenario that compiles successfully but will panic at runtime because a required field (`name`) is missing from the `User` creation. ```rust // Missing `name` — no compile error let user = toasty::create!(User { }).exec(&mut db).await?; ``` -------------------------------- ### Illustrating the N+1 Problem Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/preloading-associations.md This example demonstrates how accessing a relation on each record in a list without preloading leads to multiple database queries. The `.await` calls clearly indicate where queries are executed. ```rust # // 1 query: load all users # let users = User::all().exec(&mut db).await?; # # for user in &users { # // N queries: one per user to load their posts # let posts = user.posts().exec(&mut db).await?; # println!("{}: {} posts", user.name, posts.len()); # } ``` -------------------------------- ### Configure transaction with lock-acquisition mode Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/transactions.md Demonstrates setting the lock-acquisition mode to Immediate using `transaction_builder()`. This mode acquires the write lock at the start of the transaction. ```rust use toasty_core::driver::operation::TransactionMode; let mut tx = db.transaction_builder() .mode(TransactionMode::Immediate) .begin() .await?; ``` -------------------------------- ### Simple Query Lowering Example Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/architecture/query-engine.md Compares a simple SELECT query before and after the lowering phase. Before lowering, it's a model-level statement; after lowering, it expands to select specific table columns. ```sql -- Before lowering (toasty_core::stmt::Statement) SELECT MODEL FROM User WHERE id = ? ``` ```sql -- After lowering SELECT id, first_and_last_name, email FROM users WHERE id = ? ``` -------------------------------- ### Get Top N Records Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/sorting-limits-and-pagination.md Retrieve the top N records based on a specific sorting order. This example gets the top 7 items sorted by 'order' in descending sequence. ```rust # use toasty::Model; # #[derive(Debug, toasty::Model)] # struct Item { # #[key] # #[auto] # id: u64, # #[index] # order: i64, # } # async fn __example(mut db: toasty::Db) -> toasty::Result<()> { // Top 7 items by order (highest first) let items = Item::all() .order_by(Item::fields().order().desc()) .limit(7) .exec(&mut db) .await?; # Ok(()) # } ``` -------------------------------- ### Create CLI Binary for Migrations Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/schema-management.md Set up a CLI binary in `src/bin/cli.rs` using `toasty-cli` to handle argument parsing and migration subcommands. This requires loading configuration and connecting to the database. ```rust use toasty_cli::{Config, ToastyCli}; #[tokio::main] async fn main() -> anyhow::Result<()> { let config = Config::load()?; let db = toasty::Db::builder() .models(toasty::models!(crate::*)) .connect("sqlite:./my_app.db") .await?; let cli = ToastyCli::with_config(db, config); cli.parse_and_run().await?; Ok(()) } ``` -------------------------------- ### Create New Project and Navigate Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/getting-started.md Initial commands to create a new Rust project using Cargo and navigate into the project directory. ```bash cargo new my-app cd my-app ``` -------------------------------- ### Example Fix Commit Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/COMMITS.md Use the 'fix' type for bug fixes. This example addresses an issue with quoting reserved identifiers in SQLite. ```text fix(sqlite): quote reserved identifiers in column definitions ``` -------------------------------- ### Configure Connection Pool Settings Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/database-setup.md This example demonstrates how to configure advanced connection pool settings such as maximum pool size, wait timeout, and creation timeout. These settings allow fine-tuning of database connection management. ```rust use std::time::Duration; let mut db = toasty::Db::builder() .models(toasty::models!(crate::*)) .max_pool_size(32) .pool_wait_timeout(Some(Duration::from_secs(5))) .pool_create_timeout(Some(Duration::from_secs(10))) .connect("postgresql://user:pass@localhost/mydb") .await?; ``` -------------------------------- ### Build Database with Direct Driver Instance Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/database-setup.md This snippet shows how to construct a database driver directly and pass it to `Db::builder().build()` for more granular control over driver configuration, instead of using `connect()`. ```rust let driver = toasty_driver_sqlite::Sqlite::in_memory(); let mut db = toasty::Db::builder() .models(toasty::models!(User)) .build(driver) .await?; ``` -------------------------------- ### Raw Document Path Expression Example Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/design/document-fields.md An example of a raw document path expression used as an escape hatch for queries that typed accessors cannot express. This is considered out of scope for the current version. ```Rust path_match("$.a[*] ? (@.b > 1)") ``` -------------------------------- ### Eager Relation Field Example Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/preloading-associations.md This example shows an eager relation field (`posts: Vec`) which is loaded by every query returning the `User` model. Accessing this relation is synchronous and does not involve a database query. ```rust # #[derive(Debug, toasty::Model)] # struct User { # #[key] # #[auto] # id: u64, # # #[has_many] # posts: Vec, # } # #[derive(Debug, toasty::Model)] # struct Post { # #[key] # #[auto] # id: u64, # #[index] # user_id: u64, # #[belongs_to(key = user_id, references = id)] # user: toasty::Deferred, # title: String, # } # async fn __example(mut db: toasty::Db) -> toasty::Result<()> { # let user_id = 1; let user = User::filter_by_id(user_id).get(&mut db).await?; // Already loaded — no .include() and no .get() wrapper. let post_count = user.posts.len(); # Ok(()) # } ``` -------------------------------- ### Run the Project Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/getting-started.md Command to compile and run the Rust project after setting up dependencies and code. ```bash cargo run ``` -------------------------------- ### Create User With Profile (Required HasOne) Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/has-one.md Shows how to create a User record when the HasOne relationship is required (`Deferred`), necessitating the provision of child data during parent creation. Asserts the created profile's content. ```rust use toasty::Model; #[derive(Debug, toasty::Model)] struct User { #[key] #[auto] id: u64, #[has_one] profile: toasty::Deferred, } #[derive(Debug, toasty::Model)] struct Profile { #[key] #[auto] id: u64, #[unique] user_id: Option, #[belongs_to(key = user_id, references = id)] user: toasty::Deferred>, bio: String, } async fn __example(mut db: toasty::Db) -> toasty::Result<()> { // Must provide a profile when creating the user let user = toasty::create!(User { profile: { bio: "Hello" }, }) .exec(&mut db) .await?; let profile = user.profile().exec(&mut db).await?; assert_eq!(profile.bio, "Hello"); Ok(()) } ``` -------------------------------- ### Connect to File-Backed Turso Database Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/turso.md Connect to a file-backed Turso database using a 'turso:' URL. Relative paths are resolved against the current working directory. ```rust let db = toasty::Db::builder() .models(toasty::models!(crate::*)) .connect("turso:./app.db") .await?; ``` -------------------------------- ### Building Projections with the path! Macro Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/architecture/path-system.md Shows how to construct a projection using the path! macro with a dot-separated index list. ```rust let p: Path = path![.0 .1]; // two-step projection ``` -------------------------------- ### Generated Create Macro Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/creating-records.md Example of the `toasty::create!(User { ... })` macro, which is generated and expands to builder calls. ```rust toasty::create!(User { ... }) ``` -------------------------------- ### Get Associated Model Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/has-one.md Loads and returns the associated model for a has-one relationship. Requires a mutable database connection. ```Rust .get(&mut db) ``` -------------------------------- ### Source with Include Expansion Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/design/query-macro.md Illustrates the expansion of `query!(User { todos })` to `User::all().include(User::fields().todos())`, demonstrating eager loading expansion. ```rust // Input: query!(User { todos }) // Expands to: User::all().include(User::fields().todos()) ``` -------------------------------- ### Example of Instance Update and Query-Based Delete Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/design/field-version.md Demonstrates creating a document, updating it, and then attempting to delete a stale version. Query-based updates and deletes do not check the caller's prior view of the row. ```rust async fn __example(mut db: toasty::Db) -> toasty::Result<()> { let mut doc = toasty::create!(Document { content: "hello" }) .exec(&mut db) .await?; let stale = Document::filter_by_id(doc.id).get(&mut db).await?; doc.update().content("moved on").exec(&mut db).await?; let result = stale.delete().exec(&mut db).await; assert!(result.is_err()); Ok(()) } ``` -------------------------------- ### Limit Query Results Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/sorting-limits-and-pagination.md Restrict the maximum number of records returned by a query. This example limits the results to at most 5 items. ```rust # use toasty::Model; # #[derive(Debug, toasty::Model)] # struct Item { # #[key] # #[auto] # id: u64, # #[index] # order: i64, # } # async fn __example(mut db: toasty::Db) -> toasty::Result<()> { // At most 5 items let items = Item::all().limit(5).exec(&mut db).await?; # Ok(()) # } ``` -------------------------------- ### Basic User Query with Macro Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/design/query-macro.md Demonstrates the basic usage of the `query!` macro to filter users by name. This is the macro-based equivalent of a more verbose method-chaining approach. ```rust let users = query!(User FILTER .name == "Carl").exec(&mut db).await?; ``` ```rust let users = User::filter(User::fields().name().eq("Carl")).exec(&mut db).await?; ``` -------------------------------- ### Query with Association Lowering Example Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/architecture/query-engine.md Illustrates a query with an association (including 'todos') before and after lowering. After lowering, the association is expanded into a subquery. ```sql -- Before lowering (toasty_core::stmt::Statement) SELECT MODEL FROM User WHERE id = ? INCLUDE todos ``` ```sql -- After lowering SELECT id, first_and_last_name, email, ( SELECT id, title, user_id FROM todos WHERE todos.user_id = users.id ) FROM users WHERE id = ? ``` -------------------------------- ### Nested Resource Creation Macro vs. Builder Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/creating-records.md Shows how to create nested resources, like todos for a user, using both macro and builder syntax. ```rust toasty::create!(in user.todos() { title: "Buy milk" }) ``` ```rust user.todos().create().title("Buy milk") ``` -------------------------------- ### Filtering by Nested Field Equality Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/design/document-fields.md Example of filtering a User collection based on the equality of a nested field within the preferences embed. ```rust User::all().filter( User::FIELDS.preferences().theme().eq("dark") ); ``` -------------------------------- ### Build Db with Direct Turso Driver Instance Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/turso.md Construct the Turso driver directly to configure Turso-specific options before passing it to Db::builder().build(). ```rust let driver = toasty_driver_turso::Turso::in_memory().concurrent_writes(); let db = toasty::Db::builder() .models(toasty::models!(crate::*)) .build(driver) .await?; ``` -------------------------------- ### Case-insensitive ASCII LIKE filter Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/sqlite.md Use the `.like()` method for case-insensitive ASCII matching. This example filters users by email address. ```rust let users = User::filter(User::fields().email().like("%@example.com")) .exec(&mut db) .await?; ``` -------------------------------- ### Fetch Record by Single-Field Key Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/keys-and-auto-generation.md After defining a key, Toasty generates a `get_by_key` method. This example shows fetching a `User` by its `id`. ```rust use toasty::Model; #[derive(Debug, toasty::Model)] struct User { #[key] #[auto] id: u64, name: String, } async fn __example(mut db: toasty::Db) -> toasty::Result<()> { let user = User::get_by_id(&mut db, &1).await?; Ok(()) } ``` -------------------------------- ### Configure Migration Settings in `Toasty.toml` Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/schema-management.md Define migration behavior by configuring the `[migration]` section in `Toasty.toml`. Options include the path for migration files, naming style, checksum usage, and statement splitting. ```toml [migration] path = "toasty" prefix_style = "Sequential" checksums = false statement_breakpoints = true ``` -------------------------------- ### Batch Creation Macro vs. Builder (Tuple) Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/creating-records.md Demonstrates the conversion from a macro for creating multiple, different types of records to the `toasty::batch` function returning a tuple. ```rust toasty::create!((User { ... }, Post { ... })) ``` ```rust toasty::batch((User::create()..., Post::create()...)) → tuple ``` -------------------------------- ### Generated User Create Builder Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/creating-records.md Example of the `User::create()` method generated by `#[derive(Model)]`, which returns a builder for setting fields. ```rust User::create() ``` -------------------------------- ### Connect with Connection URL Options Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/postgresql.md Connect to a PostgreSQL database using a URL with query parameters to configure SSL mode and application name. ```rust .connect("postgresql://app:secret@db.internal/store\ ?sslmode=verify-full&application_name=store-api") ``` -------------------------------- ### Operator Sugar Lowering Example Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/design/update-macro.md Shows how compound-assignment operator sugar will be lowered to a specific statement variant once the necessary engine components are implemented. ```rust field: stmt::increment(val) ``` -------------------------------- ### Get All Records Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/querying-records.md Returns a query builder for all records of a given model. This query must be executed using a terminal method like .exec(). ```rust # use toasty::Model; # #[derive(Debug, toasty::Model)] # struct User { # #[key] # #[auto] # id: u64, # name: String, # #[unique] # email: String, # } # async fn __example(mut db: toasty::Db) -> toasty::Result<()> { let users = User::all().exec(&mut db).await?; for user in &users { println!("{}: {}", user.id, user.name); } # Ok(()) # } ``` -------------------------------- ### Using #[default] and #[update] in Practice Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/field-options.md Illustrates the behavior of a 'status' field with #[default] and #[update] attributes during create and update operations. ```rust # use toasty::Model; # #[derive(Debug, toasty::Model)] # struct Post { # #[key] # #[auto] # id: u64, # title: String, # #[default("draft".to_string())] # #[update("edited".to_string())] # status: String, # } # async fn __example(mut db: toasty::Db) -> toasty::Result<()> let mut post = toasty::create!(Post { title: "Hello" }) .exec(&mut db) .await?; assert_eq!(post.status, "draft"); post.update().title("Updated").exec(&mut db).await?; assert_eq!(post.status, "edited"); # Ok(()) # } ``` -------------------------------- ### Build and Test Commands Source: https://github.com/tokio-rs/toasty/blob/main/AGENTS.md Standard Cargo commands for building the project and running tests. Use these for general development and verification. ```bash # Build everything cargo build # Run all tests (SQLite only, no external services needed) cargo test ``` -------------------------------- ### Filter map entries by keys Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/design/document-fields.md Filter map entries where at least one key satisfies a given condition, such as starting with a specific prefix. ```rust User::all().filter( User::FIELDS.metadata().keys().any(|k| k.starts_with("internal_")) ); ``` -------------------------------- ### Start Pagination After a Specific Value Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/sorting-limits-and-pagination.md Demonstrates how to begin pagination from a point after a specific value in the sort field using the `.after()` method. This is useful for resuming pagination or fetching records that meet a certain threshold. ```rust // Start after order=90 (descending), so the first item will be order=89 let page: Page<_> = Item::all() .order_by(Item::fields().order().desc()) .paginate(10) .after(90) .exec(&mut db) .await?; ``` -------------------------------- ### Configure transaction with isolation level and read-only Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/transactions.md Shows how to use `transaction_builder()` to set the isolation level to Serializable and mark the transaction as read-only before starting it. ```rust use toasty::IsolationLevel; let mut tx = db.transaction_builder() .isolation(IsolationLevel::Serializable) .read_only(true) .begin() .await?; ``` -------------------------------- ### Binding Typed Null Values Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/raw-sql.md Use `.bind_typed(value, db_type)` when the type is ambiguous, such as `NULL` or an empty list. This example binds a `NULL` timestamp. ```rust use toasty::schema::db; toasty::sql::statement("UPDATE users SET archived_at = ?1 WHERE id = ?2") .bind_typed(toasty::stmt::Value::Null, db::Type::Timestamp(6)) .bind(1_i64) .exec(&mut db) .await?; ``` -------------------------------- ### Connect to an In-Memory SQLite Database Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/database-setup.md This snippet shows the basic process of building and connecting to a database. It registers `User` and `Post` models and connects to an in-memory SQLite database. ```rust let mut db = toasty::Db::builder() .models(toasty::models!(User, Post)) .connect("sqlite::memory:") .await?; ``` -------------------------------- ### Missing Required Field Error Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/design/static-assertions-create-macro.md Example of a compile-time error message when a required top-level field is missing in a `create!` macro invocation for the `User` model. ```rust error[E0080]: evaluation panicked: missing required field `name` in create! for `User` --> src/main.rs:10:5 | 10 | toasty::create!(User { }) | ^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `_CREATE` failed inside this call ``` -------------------------------- ### Configure Experimental Encryption Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/turso.md Demonstrates how to configure at-rest encryption for the database using a specified cipher and a hex-encoded key. This requires constructing an EncryptionOpts struct. ```rust use toasty_driver_turso::{EncryptionOpts, Turso}; let driver = Turso::file("encrypted.db") .experimental_encryption(EncryptionOpts { cipher: "aes256gcm".into(), hexkey: "<64-hex-character-key>".into(), }); ``` -------------------------------- ### Self-Referential Model Example Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/design/static-assertions-create-macro.md Shows a self-referential model `Person` with a `children` field. The `CREATE_META` for `Person` only references its own fields, preventing const cycles during validation. ```rust #[derive(Model)] struct Person { #[key] #[auto] id: Id, name: String, #[has_many] children: Deferred>, } ``` -------------------------------- ### Filter Expansion Example Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/design/query-macro.md Demonstrates how a macro filter like `query!(User FILTER .name == "Carl" AND .age > 18)` expands into chained method calls on the query builder API. ```rust // Input: query!(User FILTER .name == "Carl" AND .age > 18) // Expands to: User::filter( User::fields().name().eq("Carl") .and(User::fields().age().gt(18)) ) ``` -------------------------------- ### Including Multiple Deferred Fields Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/deferred-fields.md Multiple `.include()` calls on the same query coalesce. This example shows including body, summary, and a related author field. ```rust let doc = Document::filter_by_id(id) .include(Document::fields().body()) .include(Document::fields().summary()) .include(Document::fields().author()) // relation .get(&mut db) .await?; ``` -------------------------------- ### Create Parent and Child Separately Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/has-one.md Demonstrates creating a parent record first, then creating and associating a child record using the `create!` macro with a nested block. ```rust # use toasty::Model; # #[derive(Debug, toasty::Model)] # struct User { # #[key] # #[auto] # id: u64, # name: String, # #[has_one] # profile: toasty::Deferred>, # } # #[derive(Debug, toasty::Model)] # struct Profile { # #[key] # #[auto] # id: u64, # #[unique] # user_id: Option, # #[belongs_to(key = user_id, references = id)] # user: toasty::Deferred>, # bio: String, # } # async fn __example(mut db: toasty::Db) -> toasty::Result<()> let user = toasty::create!(User { name: "Alice" }).exec(&mut db).await?; let profile = toasty::create!(in user.profile() { bio: "A person" }) .exec(&mut db) .await?; assert_eq!(profile.user_id, Some(user.id)); # Ok(()) # } ``` -------------------------------- ### ValidateCreate Impl for Fields Struct Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/design/static-assertions-create-macro.md Example of a `ValidateCreate` implementation for a generated fields struct (e.g., `TodoFieldsList`), which references the target model's `CREATE_META`. ```rust // On the fields struct for Todo (generated by derive) impl<__Origin> ValidateCreate for TodoFieldsList<__Origin> { const CREATE_META: &'static CreateMeta = &Todo::CREATE_META; } ``` -------------------------------- ### User Creation Macro vs. Builder Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/creating-records.md Illustrates the direct translation from the `toasty::create!` macro for a User model to its builder equivalent. ```rust toasty::create!(User { name: "Alice" }) ``` ```rust User::create().name("Alice") ``` -------------------------------- ### Batch Creation Macro vs. Builder (Vec) Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/creating-records.md Shows the conversion from a macro for creating multiple users to the `toasty::batch` function returning a Vec. ```rust toasty::create!(User::[{ ... }, { ... }]) ``` ```rust toasty::batch([User::create()...]) → Vec ``` -------------------------------- ### Filter by Variant-Specific Field Source: https://github.com/tokio-rs/toasty/blob/main/docs/dev/design/enums-and-embedded-structs.md Use `.matches()` to apply filters to fields specific to a particular enum variant. This example filters for humans named 'Alice'. ```rust // Variant-specific: humans named "Alice" Character::all().filter( Character::FIELDS.creature().matches( Creature::VARIANTS.human().name().eq("Alice") ) ); ``` -------------------------------- ### Connect to File-Backed SQLite Database Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/sqlite.md Connect to a file-backed SQLite database by providing a file path in the connection URL. ```rust let db = toasty::Db::builder() .models(toasty::models!(crate::*)) .connect("sqlite:./app.db") .await?; ``` -------------------------------- ### Filter and Sort Items Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/sorting-limits-and-pagination.md Combine filtering and sorting to retrieve specific records in a desired order. This example fetches 'books' sorted by their order in descending sequence. ```rust # use toasty::Model; # #[derive(Debug, toasty::Model)] # struct Item { # #[key] # #[auto] # id: u64, # #[index] # order: i64, # category: String, # } # async fn __example(mut db: toasty::Db) -> toasty::Result<()> { let items = Item::filter(Item::fields().category().eq("books")) .order_by(Item::fields().order().desc()) .exec(&mut db) .await?; # Ok(()) # } ``` -------------------------------- ### Navigate Between Pages Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/sorting-limits-and-pagination.md Shows how to fetch the next and previous pages of results using the `.next()` and `.prev()` methods on a `Page` object. These methods return `Option`, indicating if more pages exist. ```rust let first_page: Page<_> = Item::all() .order_by(Item::fields().order().asc()) .paginate(10) .exec(&mut db) .await?; // Move to the next page if let Some(second_page) = first_page.next(&mut db).await? { println!("page 2 has {} items", second_page.len()); // Go back if let Some(back) = second_page.prev(&mut db).await? { println!("back to page 1: {} items", back.len()); } } ``` -------------------------------- ### Update Expression for Timestamp Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/field-options.md Use `#[update(expr)]` to automatically set a field on create and update. This example uses `jiff::Timestamp::now()` to set `updated_at`. ```rust use toasty::Model; #[derive(Debug, toasty::Model)] struct Post { #[key] #[auto] id: u64, title: String, #[update(jiff::Timestamp::now())] updated_at: jiff::Timestamp, } ``` -------------------------------- ### Create User Model with Macro Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/defining-models.md Use the `toasty::create!` macro for struct-literal syntax to define and initialize a new User model. ```rust # use toasty::Model; # #[derive(Debug, toasty::Model)] # struct User { # #[key] # #[auto] # id: u64, # name: String, # email: String, # } # async fn __example(mut db: toasty::Db) -> toasty::Result<() P> { let user = toasty::create!(User { name: "Alice", email: "alice@example.com", }) .exec(&mut db) .await?; # Ok(()) # } ``` -------------------------------- ### DynamoDB Query: is_superset with concrete Vec Source: https://github.com/tokio-rs/toasty/blob/main/docs/guide/src/dynamodb.md Example of using the `is_superset` predicate with a concrete `Vec` for DynamoDB queries. This translates to a `contains()` clause for each element in the vector. ```rust let admins = User::filter(User::fields().roles().is_superset(vec!["admin", "owner"])) .all(&mut db) .await?; ```