Skip to main content

Crate larust_orm

Crate larust_orm 

Source
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)] implements larust_repository::Repository<T> for - see larust-macros’ model.rs for the actual generated impl Repository<T> for AnyRepository<T> body, which just forwards to the already-generated T::find/create/update/ delete static methods and QueryBuilder<T>.
ConnectionConfig
One named connection block - Laravel’s config/database.php 'mysql' => [...], narrowed to the settings this framework actually needs (no unix_socket/prefix/strict/engine - nothing here consumes them today; add them if a real caller ever needs to).
DatabaseConnections
Every named connection block plus which one is active - Laravel’s config/database.php in full: 'default' => env('DB_CONNECTION', 'sqlite') and 'connections' => [...].
FactoryBuilder
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 plain FnOnce-shaped closure over the whole typed value, applied via Rust’s own struct-update syntax: |p| NewPost { title: "x".into(), ..p }).
QueryBuilder
Laravel-shaped query builder (Post::query().where_eq(...).latest(...)) over sqlx. Column names passed in (Post::TITLE) are &'static str constants 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_URL selected - set once, inside connect, by reading the URL’s own scheme (sqlite:// vs mysql://). larust-orm deliberately doesn’t ask sqlx this (sqlx::any::AnyKind is #[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.
BindValue
A dynamically-typed bind value - where_eq accepts any of these via Into<BindValue> so the builder can accumulate heterogeneous conditions (where_eq(Post::TITLE, "x").where_eq(Post::ID, 1)) in one Vec before binding them to the query at execution time.
Driver
Which wire protocol a named connection speaks - distinct from crate::Backend on purpose: Backend is “what sqlx::Any is actually talking to,” resolved from a URL scheme once connect() runs, and every exhaustive match on it across this codebase assumes the connection is reachable through AnyPool. Driver::Sqlsrv names a connection SQL Server can never reach that way at all (no sqlx driver exists for it) - collapsing the two enums would force Backend to grow a variant nothing durable can do anything with.
Op
WHERE column <op> ? - richer comparisons than where_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 generated New{Model} type) is what definition builds and what .state(...) transforms.
Model
Implemented automatically by #[derive(Model)].
SoftDeletes
Implemented automatically, only for a #[derive(Model)] struct marked #[soft_deletes] - gates with_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 on QueryBuilder<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 inside with_pool_override, alongside POOL_OVERRIDE), then falls back to the process-wide [BACKEND] - the identical two-step pool itself already uses for POOL/ POOL_OVERRIDE, kept consistent for the same reason: code that branches on backend() to decide which dialect of SQL to emit must agree with whichever pool pool() actually resolves to in the same task, not whatever backend happened to connect first in the process. Panics if neither is set, matching larust_core::config()’s own “real caller-contract violation” reasoning (nothing before connect()/ with_pool_override could plausibly need to know the backend either).
connect
Connects to the database and stores the pool process-wide (same OnceLock pattern as larust-http’s route-name registry). Call once at startup, after config/.env has been loaded.
ensure_backend
Sets [BACKEND] from database_url’s scheme, without touching the process-wide [POOL] - unlike connect, safe to call more than once per process (every call after the first is a harmless no-op, the same .ok()-swallowed idempotency connect itself already gives BACKEND). For larust_testing::test_transaction’s own connect_isolated, which deliberately builds its own dedicated pool outside the process-wide singleton (see that function’s own doc comment for why) but still needs backend() to resolve correctly for whatever it runs - every framework crate’s own bootstrap SQL branches on it.
migrate
Runs every .sql file in migrations_dir that hasn’t already been applied, in filename order (hence the numeric prefix xr make:migration generates), tracking progress in a bookkeeping _migrations table - the same shape as Laravel’s own migrations table.
migrate_fresh
Drops every table in the connected database (including _migrations itself) and reapplies every migration in migrations_dir from scratch - Laravel’s migrate:fresh. Forward-only, like run: there is no down()/rollback anywhere in this codebase, so a Laravel-style migrate:refresh (rollback + reapply) has nothing to build on; fresh needs no rollback and is what this framework can actually offer.
normalize_sqlite_url
Rewrites a sqlite: URL so sqlx::any::AnyConnectOptions::from_str’s strict RFC 3986 parsing (via the url crate) resolves it the same way the old, lenient, SQLite-specific SqliteConnectOptions::from_str this crate used before adding MySQL support always did - see connect’s own doc comment for the full explanation of why this is needed at all (in short: a Windows absolute path’s C: drive letter, sitting right after sqlite://, gets misread as a host:port-shaped URL authority component otherwise).
placeholder
One placeholder for backend at 1-based position n in left-to-right order across a statement - "?" for SQLite/MySQL, "$n" for Postgres (confirmed by reading sqlx-core’s own doc comment: sqlx::Any does 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 own migrate.rs all 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 ?/$n split.
pool
Returns the pool every #[derive(Model)] method and QueryBuilder call resolves its connection through - this single resolution point (not a parameter threaded through every generated method) is what makes with_pool_override below work at all. Checks the task-local override first (set only inside larust_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 before main finishes 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::Any has no catalog API of its own; see larust-db’s own sql::introspect module for the fuller browse/edit-oriented introspection built on top of this same query). SQLite’s internal sqlite_% tables are excluded; MySQL/Postgres’s information_schema.tables query is already scoped to just the connected database/schema, so nothing internal leaks through.
with_pool_override
Runs fut with pool (and backend, its own backend override - always scoped together, never independently, so pool and backend can never disagree about which database fut is actually talking to) resolved by every pool()/backend() call made from within it - and from anything it directly .awaits, since a tokio::task_local! is visible throughout one task’s execution. A future fut hands off to tokio::spawn as a separate detached task would not see this override (spawned tasks don’t inherit their parent’s task-locals) - confirmed nothing in larust-orm‘s or larust-macros’ generated code does that (grep for tokio::spawn/ join_all in both turns up nothing), so this is safe for every existing #[derive(Model)]/QueryBuilder call path today.