Expand description
QueryBuilder + a process-wide connection pool over sqlx (SQLite or
MySQL, chosen at runtime by DATABASE_URL - see pool::Backend), plus
a minimal migration runner. #[derive(Model)] (in larust-macros)
generates the CRUD methods that use these.
Re-exports§
pub use sqlx;
Structs§
- AnyRepository
- Stateless marker type
#[derive(Model)]implementslarust_repository::Repository<T>for - seelarust-macros’model.rsfor the actual generatedimpl Repository<T> for AnyRepository<T>body, which just forwards to the already-generatedT::find/create/update/deletestatic methods andQueryBuilder<T>. - Connection
Config - One named connection block - Laravel’s
config/database.php'mysql' => [...], narrowed to the settings this framework actually needs (nounix_socket/prefix/strict/engine- nothing here consumes them today; add them if a real caller ever needs to). - Database
Connections - Every named connection block plus which one is active - Laravel’s
config/database.phpin full:'default' => env('DB_CONNECTION', 'sqlite')and'connections' => [...]. - Factory
Builder - Accumulates
.state(...)overrides before.make()/.create()actually builds a value - Laravel’s own factory builder, minus the PHP-side magic (no$this->state(fn (array $attributes) => [...])merge-by-array-key; a state here is a plainFnOnce-shaped closure over the whole typed value, applied via Rust’s own struct-update syntax:|p| NewPost { title: "x".into(), ..p }). - Query
Builder - Laravel-shaped query builder (
Post::query().where_eq(...).latest(...)) oversqlx. Column names passed in (Post::TITLE) are&'static strconstants generated by#[derive(Model)], never user input, so they’re interpolated directly into the SQL string; bound values always go through placeholders - never string-formatted into the query.
Enums§
- Backend
- Which real database engine
DATABASE_URLselected - set once, insideconnect, by reading the URL’s own scheme (sqlite://vsmysql://).larust-ormdeliberately doesn’t asksqlxthis (sqlx::any::AnyKindis#[deprecated = "not used or returned by any API"]in 0.8) - it already knows the answer the moment it parses the URL to connect, so it just remembers it. - Bind
Value - A dynamically-typed bind value -
where_eqaccepts any of these viaInto<BindValue>so the builder can accumulate heterogeneous conditions (where_eq(Post::TITLE, "x").where_eq(Post::ID, 1)) in oneVecbefore binding them to the query at execution time. - Driver
- Which wire protocol a named connection speaks - distinct from
crate::Backendon purpose:Backendis “whatsqlx::Anyis actually talking to,” resolved from a URL scheme onceconnect()runs, and every exhaustivematchon it across this codebase assumes the connection is reachable throughAnyPool.Driver::Sqlsrvnames a connection SQL Server can never reach that way at all (nosqlxdriver exists for it) - collapsing the two enums would forceBackendto grow a variant nothing durable can do anything with. - Op
WHERE column <op> ?- richer comparisons thanwhere_eq’s plain equality (Laravel’s 3-argument->where($col, '>', $val)).- Order
.order_by(column, Order::Desc)- Laravel’s->orderBy($col, 'desc').
Traits§
- Factory
- Implemented by hand for each model that needs factory-built test/seed
data.
Self::Model::New(the model’s own generatedNew{Model}type) is whatdefinitionbuilds and what.state(...)transforms. - Model
- Implemented automatically by
#[derive(Model)]. - Soft
Deletes - Implemented automatically, only for a
#[derive(Model)]struct marked#[soft_deletes]- gateswith_trashed/only_trashed(below) at compile time, so calling either on a model that never opted in is a compile error (no such method exists onQueryBuilder<NotSoftDeleted>), not a silent no-op or a runtime error.
Functions§
- backend
- This app’s database backend - see
Backend. Checks the task-local override first (set only insidewith_pool_override, alongsidePOOL_OVERRIDE), then falls back to the process-wide [BACKEND] - the identical two-steppoolitself already uses forPOOL/POOL_OVERRIDE, kept consistent for the same reason: code that branches onbackend()to decide which dialect of SQL to emit must agree with whichever poolpool()actually resolves to in the same task, not whatever backend happened to connect first in the process. Panics if neither is set, matchinglarust_core::config()’s own “real caller-contract violation” reasoning (nothing beforeconnect()/with_pool_overridecould plausibly need to know the backend either). - connect
- Connects to the database and stores the pool process-wide (same
OnceLockpattern aslarust-http’s route-name registry). Call once at startup, after config/.envhas been loaded. - ensure_
backend - Sets [
BACKEND] fromdatabase_url’s scheme, without touching the process-wide [POOL] - unlikeconnect, safe to call more than once per process (every call after the first is a harmless no-op, the same.ok()-swallowed idempotencyconnectitself already givesBACKEND). Forlarust_testing::test_transaction’s ownconnect_isolated, which deliberately builds its own dedicated pool outside the process-wide singleton (see that function’s own doc comment for why) but still needsbackend()to resolve correctly for whatever it runs - every framework crate’s own bootstrap SQL branches on it. - migrate
- Runs every
.sqlfile inmigrations_dirthat hasn’t already been applied, in filename order (hence the numeric prefixxr make:migrationgenerates), tracking progress in a bookkeeping_migrationstable - the same shape as Laravel’s ownmigrationstable. - migrate_
fresh - Drops every table in the connected database (including
_migrationsitself) and reapplies every migration inmigrations_dirfrom scratch - Laravel’smigrate:fresh. Forward-only, likerun: there is nodown()/rollback anywhere in this codebase, so a Laravel-stylemigrate:refresh(rollback + reapply) has nothing to build on;freshneeds no rollback and is what this framework can actually offer. - normalize_
sqlite_ url - Rewrites a
sqlite:URL sosqlx::any::AnyConnectOptions::from_str’s strict RFC 3986 parsing (via theurlcrate) resolves it the same way the old, lenient, SQLite-specificSqliteConnectOptions::from_strthis crate used before adding MySQL support always did - seeconnect’s own doc comment for the full explanation of why this is needed at all (in short: a Windows absolute path’sC:drive letter, sitting right aftersqlite://, gets misread as ahost:port-shaped URL authority component otherwise). - placeholder
- One placeholder for
backendat 1-based positionnin left-to-right order across a statement -"?"for SQLite/MySQL,"$n"for Postgres (confirmed by readingsqlx-core’s own doc comment:sqlx::Anydoes not rewrite placeholders between dialects, so every framework crate with a fixed, statically-known placeholder count in a hand-written SQL string uses this instead of a bare"?"literal -larust-cache,larust-queue,larust-sanctum,larust-permissions,larust-notifications,larust-http::session, and this crate’s ownmigrate.rsall do.QueryBuilder’s own placeholder rendering (query_builder.rs) has a genuinely dynamic count instead - a running counter threaded through its own condition renderer - and doesn’t use this helper, but follows the identical?/$nsplit. - pool
- Returns the pool every
#[derive(Model)]method andQueryBuildercall resolves its connection through - this single resolution point (not a parameter threaded through every generated method) is what makeswith_pool_overridebelow work at all. Checks the task-local override first (set only insidelarust_testing::test_transaction), then falls back to the process-wide pool. Errors (rather than panics) if neither is set - a misconfigured startup order is a real possibility (e.g. a route handler running beforemainfinishes wiring up the database), not a truly unreachable state. - table_
names - Every real table in the connected database, alphabetical - the one
portable piece of schema introspection this crate needs (
sqlx::Anyhas no catalog API of its own; seelarust-db’s ownsql::introspectmodule for the fuller browse/edit-oriented introspection built on top of this same query). SQLite’s internalsqlite_%tables are excluded; MySQL/Postgres’sinformation_schema.tablesquery is already scoped to just the connected database/schema, so nothing internal leaks through. - with_
pool_ override - Runs
futwithpool(andbackend, its ownbackendoverride - always scoped together, never independently, sopoolandbackendcan never disagree about which databasefutis actually talking to) resolved by everypool()/backend()call made from within it - and from anything it directly.awaits, since atokio::task_local!is visible throughout one task’s execution. A futurefuthands off totokio::spawnas a separate detached task would not see this override (spawned tasks don’t inherit their parent’s task-locals) - confirmed nothing inlarust-orm‘s orlarust-macros’ generated code does that (grepfortokio::spawn/join_allin both turns up nothing), so this is safe for every existing#[derive(Model)]/QueryBuildercall path today.