database library
The query builder, ORM, schema builder, migrations and seeding.
A subset of package:daravel/daravel.dart for files that need only this
area, or whose own names collide with the full barrel (JwtException,
UniqueRule, ModelNotFoundException, CorsMiddleware, ...).
Classes
- AggregateClause
-
Aggregate request (
count,sum...). - BasicWhere
-
BelongsTo<
R extends Model> -
belongsTo: the parent carriesforeignKey= relatedownerKey. -
BelongsToMany<
R extends Model> -
belongsToManythrough a pivot table. - BetweenWhere
- Blueprint
-
Collects column, index and foreign key definitions for
Schema.createand the change commands forSchema.table. - BoolCast
- Cast
-
Attribute casting (Laravel
$casts). get converts a raw database value into the Dart value exposed by the model; set converts a Dart value into what is stored. - ColumnDefinition
- A column being defined (or changed) inside a Blueprint.
- ColumnInfo
-
Column metadata returned by
Schema.getColumns. - ColumnWhere
- Compilation
- Accumulates bindings while compiling and emits dialect placeholders.
- CompiledQuery
- SQL text plus its ordered bindings, ready for a driver.
- ConnectionConfig
-
A single named connection (
config/database.phpparity). - Cursor
-
Opaque cursor for CursorPaginator, encoded like Laravel's
Cursor: URL-safe unpadded base64 of the PHP JSON of the boundary row's ordered column values plus_pointsToNextItems, so cursors are interchangeable with a Laravel app over the same table. -
CursorPaginator<
T> -
cursorPaginate()result (keyset pagination). -
CustomCast<
T> - DatabaseConfig
- Database configuration section.
- DatabaseDriver
- A connection to a database server or file.
- DatabaseManager
- DateCast
- DatePartWhere
-
whereDate/Month/Day/Year/Time. - DateTimeCast
- DateTimeFormatCast
-
Cast.dateTimeFormat: a DateTime attribute that
Model.toJsonwrites with a PHPdate()format. - DoubleCast
-
EnumCast<
E extends Enum> - ExistsWhere
- Faker
-
Minimal, dependency-free fake data generator for seeders and factories.
Deterministic when constructed with a
seed(Faker(seed: 42)). - ForeignIdDefinition
-
A
foreignId()column that can beconstrained(). - ForeignKeyDefinition
- A foreign key constraint.
-
HasMany<
R extends Model> -
hasMany: related rows carryforeignKey= parentlocalKey. -
HasManyThrough<
R extends Model> -
hasManyThrough: parent → through (firstKey= parentlocalKey) → related (secondKey= throughsecondLocalKey). -
HasOne<
R extends Model> -
hasOne: like HasMany but a single row. -
HasOneThrough<
R extends Model> -
hasOneThrough: like HasManyThrough but a single model (or null). - HavingClause
-
HAVINGentry. - IndexDefinition
- A table-level index.
- IntCast
- InWhere
- JoinBuilder
-
Fluent
ONbuilder for closure joins. - JoinClause
- A join clause.
- JoinCondition
-
One
ONcondition of a join. - JsonCast
- JsonWhere
-
whereJsonContains/whereJsonLength(dialect specific). - KeyGenerator
- Generates client-side keys.
-
LengthAwarePaginator<
T> -
paginate()result. Serializes exactly like Laravel'sLengthAwarePaginator(key order,linkswithpage, URL window). - ListeningQueryExecutor
- Wraps an executor to report every query to listeners. Only used while listeners are registered, so queries cost nothing extra otherwise.
- Migration
-
A schema migration. name must be unique and stable (it is recorded in
the
migrationstable, Laravel-compatible:id,migration,batch). - MigrationStatus
-
Status row reported by
migrate:status. - Migrator
-
Runs migrations in batches (
migrate,migrate:rollback,migrate:status,migrate:reset). - Model
-
Base for Hybrid Active Record models (ADR-006): an attribute bag with
typed accessors written by the developer (or
dartisan make:model), dirty tracking, casts, timestamps, soft deletes, relations and events. -
ModelCollection<
T extends Model> -
A list of models with Laravel
Collectionconveniences. -
ModelDefinition<
T extends Model> - Static metadata of a model (ADR-006). Declared once per model class with an explicit type (so mutually referencing models do not create an inference cycle):
-
ModelFactory<
T extends Model> -
Model factory (named
ModelFactorybecauseModelFactoryis the container binding typedef; BLUEPRINT_V2 §7.5.6). -
ModelObserver<
T extends Model> -
Observes a model's lifecycle. Return
falsefrom a*inghook to cancel the operation (creating,updating,saving,deleting,restoring). -
ModelQuery<
T extends Model> -
Model-aware query (Laravel's Eloquent
Builder): wraps a QueryBuilder and hydrates models, applies global scopes and soft deletes, eager loads relations and offerswhereHas/withCount. - ModelRegistry
-
The application's models (
bootstrap/models.dart, registered withApplicationBuilder.withModels): the explicit list thatmodel:show,mcp:serveand generators read instead of discovering classes. -
MorphedByMany<
R extends Model> -
morphedByMany: the inverse of MorphToMany (the posts of a tag). The pivot's{morphName}_typeis the related model's morph class. -
MorphMany<
R extends Model> -
morphMany: related rows carry{morphName}_type= the parent's morph class (Relation.morphClassOf) and{morphName}_id= the parent's localKey, so posts and videos can share onecommentstable. -
MorphOne<
R extends Model> -
morphOne: like MorphMany but a single row. - MorphTo
-
morphTo: the inverse of MorphOne / MorphMany. Each row names its owner's type in morphType and key in foreignKey, so rows of one table may point at different models (a comment on a post or a video). -
MorphToMany<
R extends Model> -
morphToMany: a polymorphic many-to-many through a pivot table holding{morphName}_type,{morphName}_idand relatedPivotKey (taggables: the tags of posts and of videos). pivotTable defaults to{morphName}s; pass it when the plural is irregular. - MySqlQueryGrammar
-
MySQL/MariaDB grammar: backtick quoting,
?placeholders, no RETURNING. - MySqlSchemaGrammar
- MySQL/MariaDB DDL grammar.
- NestedWhere
- NotifyingDriver
-
A driver that delivers notifications between connections to the same
database (PostgreSQL's
LISTEN/NOTIFY), so other processes and machines can be woken instead of polling. - NullWhere
- OrderClause
-
ORDER BYentry. - Pagination
-
Resolves pagination input from the current request, like Laravel's
PaginationState(page from the query string, path from$request->url()). Outside a request it falls back to page 1 and/. - PostgresDriver
-
PostgreSQL driver backed by
package:postgres(pure Dart, pooled). - PostgresQueryGrammar
-
PostgreSQL grammar:
$nplaceholders,RETURNING,ON CONFLICT. - PostgresSchemaGrammar
- PostgreSQL DDL grammar.
- QueryAst
-
Dialect-neutral description of a query, compiled by a
QueryGrammar. - QueryBuilder
- Fluent SQL builder (BLUEPRINT_V2 §7.5.3). Mutable like Laravel's; use clone to branch. Compiles through the grammar of the connection it runs on, so the same builder works on SQLite, PostgreSQL and MySQL.
- QueryErrors
-
A driver that recognises a unique index or primary key refusing a row
among its errors (Laravel's
isUniqueConstraintError), so it surfaces as UniqueConstraintViolationException. - QueryExceptionExecutor
-
Wraps an executor so a failing query throws QueryException, or
UniqueConstraintViolationException when errors recognises one, as
Laravel's
runQueryCallbackdoes. - QueryExecuted
-
A query that ran (Laravel's
QueryExecuted), passed toDatabaseManager.listen/DB.listenlisteners: SQL with its bindings, duration and connection. For debugging, slow-query logging, N+1 detection and inspection tools. - QueryExecutor
-
Executes parameterized SQL. Bindings use
?placeholders in Tier 0; the dialect-aware grammar (ADR-005) takes over placeholder emission in S5. - QueryGrammar
- Compiles a QueryAst into SQL for one dialect (ADR-005). Placeholders are emitted while compiling, never rewritten textually afterwards.
- RawExpression
- Raw SQL fragment with its own bindings; inserted verbatim by grammars.
- RawWhere
-
Relation<
R extends Model> - Base relation (BLUEPRINT_V2 §7.5.4). Related definitions are resolved lazily through a thunk so two models may reference each other.
- RetryableErrors
-
A driver that recognises its own transient errors (deadlocks, lock
timeouts), so
DB.transaction(attempts: n)retries them. - SchemaBuilder
-
Executes schema operations against a QueryExecutor (
Schema::create,Schema::table,Schema::dropIfExists,Schema::hasTable...). - SchemaGrammar
- Compiles blueprints into DDL for one dialect.
- Seeder
-
Populates the database (
db:seed). Seeders run inside the application's command scope, so facades (DB, models, factories) are available. - SeederRegistry
-
Seeders registered with
ApplicationBuilder.withSeeders. The first entry is the root seeder run by a baredb:seed(Laravel'sDatabaseSeeder). -
SimplePaginator<
T> -
simplePaginate()result: no total, only next/previous. - SqlBindings
-
Expands raw SQL bindings into a dialect's placeholders without touching
string literals, comments,
::castsor PostgreSQL JSON operators (ADR-005). - SqliteDriver
-
SQLite driver backed by
package:sqlite3(synchronous FFI). - SqliteQueryGrammar
-
SQLite grammar:
?placeholders,INSERT OR IGNORE,ON CONFLICT. - SqliteSchemaGrammar
- SQLite DDL grammar.
- SqliteTableRebuilder
-
Rebuilds a SQLite table to apply changes
ALTER TABLEcannot express (the documented 12-step procedure, as Laravel/Doctrine do): create a temp table with the new definition, copy rows, drop the old table, rename, recreate indexes. Works inside the migration transaction because the old table is dropped only after the rebuilt table has taken its name. - SqliteVersion
-
Parsed
sqlite_version(). - StringCast
- SubSelect
-
A subquery in the select list:
(SELECT ...) AS alias, orEXISTS(SELECT ...) AS aliaswhen exists. Compiled in the same pass as the outer query, so dialects with numbered placeholders stay in order. - UnionClause
-
UNIONentry. - WhereClause
- Where clauses (sealed so grammars can be exhaustive).
Enums
- ColumnType
- Column types supported by the schema builder.
- JoinType
- Join types.
- KeyType
- Primary key strategies.
- LockMode
- Row-lock modes.
- ModelEvent
- Lifecycle events a model fires (Laravel parity).
- PostgresSslMode
-
SSL modes exposed without leaking the
postgrespackage type. - SqlDialect
- SQL dialects known to the framework.
Functions
-
castName(
Cast cast) → String -
The cast's name in Laravel's vocabulary (
integer,datetime, ...). -
describeModel(
ModelDefinition< Model> definition) → Map<String, Object?> -
definitionas JSON-friendly data, in the spirit ofartisan model:show --json(database columns are added by the caller that can query them). -
describeRelation(
Relation< Model> relation) → Map<String, Object?> - One relation: its name, type, related model and keys.
-
formatDate(
DateTime value) → String -
yyyy-MM-dd. -
formatDateTime(
DateTime value) → String -
yyyy-MM-dd HH:mm:ssin UTC (Laravel's default date format). -
formatPhpDate(
DateTime value, String format) → String -
Formats
value, converted to UTC, with a PHPdate()format:Y-m-d H:i:s,D, d M Y,c,U, ... Every PHP token is supported,\escapes the next character and any other character is copied. Zone tokens (e,T,O,P,p,Z,I) describe UTC. -
modelClassName(
ModelDefinition< Model> definition) → String -
The Dart class name of the models
definitioncreates. -
parseDateTime(
Object? raw) → DateTime? -
Parses ISO-8601,
yyyy-MM-dd HH:mm:ssand epoch values as UTC. -
phpJsonEncode(
Object? value) → String -
PHP
json_encode()with default flags: like jsonEncode, but/is escaped as\/and non-ASCII characters as\uXXXX(UTF-16 units). -
rfc3986Query(
Map< String, String> parameters) → String -
PHP
http_build_query(..., PHP_QUERY_RFC3986)for flat parameters (LaravelArr::query):rawurlencodekeys and values joined by&. -
urlWindow(
int current, int last, [int onEachSide = 3]) → List< int?> -
Laravel's
UrlWindow: all pages when there are fewer thanonEachSide * 2 + 8, otherwise the first/last two pages and a slider aroundcurrent.nullstands for a...separator.
Typedefs
-
AccessorFn<
T extends Model> = Object? Function(T model) -
Computed attribute:
accessors: {'full_name': (u) => '${u.first} ${u.last}'}. - DatabaseDriverFactory = DatabaseDriver Function(String name, ConnectionConfig connection)
- Manages named connections, Zone-aware transactions with savepoints and raw SQL binding expansion (BLUEPRINT_V2 §5.6, ADR-005).
-
FactoryDefinition
= Map<
String, Object?> Function(Faker faker) -
Produces default attributes for a model (
definition()in Laravel). -
FactoryState
= Map<
String, Object?> Function(Faker faker) -
A state transformation (
state()): receives the faker, returns overrides. -
GlobalScopeFn<
T extends Model> = void Function(ModelQuery< T> query) -
Global scope applied to every query unless
withoutGlobalScopes(). -
Models<
T extends Model> = ModelCollection< T> - Convenience alias used by generated code.
-
MorphConstraint
= void Function(ModelQuery<
Model> query, ModelDefinition<Model> type) -
Constraint for
whereHasMorph, called once per targettype. -
MutatorFn<
T extends Model> = Object? Function(T model, Object? value) -
Attribute mutator:
mutators: {'email': (u, v) => '$v'.toLowerCase()}. - Raw = RawExpression
- Raw helper re-exported for relation subqueries.
-
RelationConstraint
= void Function(ModelQuery<
Model> query) -
Constraint applied to a relation query (
with({'posts': (q) => ...})). -
RelationFactory
= Relation<
Model> Function() - Lazily builds a relation (lazy so definitions may reference each other).
-
ScopeFn<
T extends Model> = void Function(ModelQuery< T> query, List<Object?> args) -
Local scope:
scopes: {'published': (q, args) => q.where('published', true)}.
Exceptions / Errors
- DaravelQueryException
- Base for query-layer exceptions.
- MassAssignmentException
- Thrown when mass assigning a guarded attribute while Model.preventSilentlyDiscardingAttributes is enabled.
- ModelNotFoundException
-
Thrown by
findOrFail()and friends. - MultipleRecordsFoundException
-
Thrown by
sole()when more than one row matches. - QueryException
-
A query the database refused (Laravel's
QueryException): the driver's error (previous) with the connection and the SQL. - RecordNotFound
- Base for "not found" model errors (kept separate from HTTP so it can be mapped by the exception handler).
- RecordNotFoundException
-
Thrown by
firstOrFail()/sole(). - UniqueConstraintViolationException
-
A row a unique index or primary key refused (Laravel's
UniqueConstraintViolationException): two requests registering the same email at once, say. As in Laravel it is a server error unless caught;createOrFirstandfirstOrCreatecatch it for you.