ormed library

Ormed - A strongly-typed ORM for Dart.

Ormed provides a complete Object-Relational Mapping solution for Dart applications, inspired by Eloquent, GORM, SQLAlchemy, and ActiveRecord. It combines compile-time code generation with runtime flexibility to deliver type-safe database operations.

Quick Start

  1. Annotate your model class:
import 'package:ormed/ormed.dart';

part 'user.orm.dart';

@OrmModel(table: 'users')
class User extends Model<User> {
  const User({required this.id, required this.email, this.name});

  @OrmField(isPrimaryKey: true, autoIncrement: true)
  final int id;

  final String email;
  final String? name;
}
  1. Run the code generator:
dart run build_runner build
  1. Use the generated code:
import 'package:ormed/ormed.dart';
import 'orm_registry.g.dart'; // Generated by Ormed.

final registry = buildOrmRegistry();
final dataSource = DataSource(
  DataSourceOptions(
    driver: myDriver,
    registry: registry,
  ),
);
await dataSource.init();

// Query with fluent API
final users = await dataSource.query<$User>()
    .whereEquals('active', true)
    .orderBy('createdAt', descending: true)
    .limit(10)
    .get();

// Repository operations
final repo = dataSource.repo<$User>();
final user = await repo.find(1);
if (user != null) {
  user.name = 'John';
  await repo.update(user);
}

Core Components

Annotations

  • OrmModel - Marks a class as a database table/entity
  • OrmField - Customizes column mapping (primary key, codec, default values)
  • OrmRelation - Defines relationships (hasOne, hasMany, belongsTo, belongsToMany)

Query Builder

The Query class provides a fluent, type-safe API for building database queries:

final results = await dataSource.query<$User>()
    .select(['id', 'email', 'name'])
    .whereEquals('active', true)
    .whereIn('role', ['admin', 'moderator'])
    .orderBy('createdAt', descending: true)
    .limit(20)
    .offset(40)
    .with_(['posts', 'profile'])  // Eager load relations
    .get();

Repository Pattern

Repositories provide CRUD operations with flexible input handling:

final repo = dataSource.repo<$User>();

// Create
final user = await repo.insert($User(email: 'new@example.com', active: true));

// Read
final found = await repo.find(1);
final all = await repo.all();

// Update - accepts tracked models, DTOs, or maps
user.name = 'Updated';
await repo.update(user);
await repo.update(UserUpdateDto(name: 'New Name'), where: {'id': 1});
await repo.update(dto, where: (Query<$User> q) => q.whereEquals('email', 'test@example.com'));

// Delete - accepts various input types including Query callbacks
await repo.delete(user);
await repo.delete((Query<$User> q) => q.whereEquals('role', 'guest'));
await repo.deleteByIds([1, 2, 3]);

DataSource

DataSource is the primary entry point for database operations:

final dataSource = DataSource(
  DataSourceOptions(
    driver: myDriver,
    registry: buildOrmRegistry(),
  ),
);
await dataSource.init();

// Query API
final users = await dataSource.query<$User>().get();

// Repository API
final userRepo = dataSource.repo<$User>();

// Raw table access (ad-hoc queries)
final rows = await dataSource.table('audit_logs')
    .whereEquals('action', 'login')
    .get();

Value Codecs

ValueCodec enables custom type serialization between Dart and database:

class UuidCodec extends ValueCodec<UuidValue> {
  const UuidCodec();

  @override
  UuidValue? decode(Object? value) =>
      value == null ? null : UuidValue.fromString(value as String);

  @override
  Object? encode(UuidValue? value) => value?.uuid;
}

// Use in model
@OrmField(codec: UuidCodec)
final UuidValue id;

Relations

Define and load relationships between models:

@OrmModel(table: 'posts')
class Post extends Model<Post> {
  @OrmRelation.belongsTo(target: User, foreignKey: 'author_id')
  User? author;

  @OrmRelation.hasMany(target: Comment)
  List<Comment>? comments;
}

// Eager loading
final posts = await dataSource.query<$Post>()
    .with_(['author', 'comments'])
    .get();

// Lazy loading
await post.load(['author']);

Soft Deletes

Enable soft delete functionality using the SoftDeletes marker mixin:

@OrmModel(table: 'posts')
class Post extends Model<Post> with SoftDeletes {
  final int? id;
  final String title;
  const Post({this.id, required this.title});
}

The code generator detects this mixin and:

  • Adds a virtual deletedAt field if not explicitly defined
  • Applies soft-delete implementation to the generated tracked class
  • Enables soft-delete query scopes automatically
// Soft delete (sets deleted_at timestamp)
await repo.delete(post);

// Query including soft-deleted records
final allIncludingDeleted = await dataSource.query<$Post>().withTrashed().get();

// Restore a soft-deleted record
await repo.restore(post);

For timezone-aware soft deletes (UTC storage), use SoftDeletesTZ instead.

Timestamps

Enable automatic timestamp management using the Timestamps marker mixin:

@OrmModel(table: 'posts')
class Post extends Model<Post> with Timestamps {
  final int? id;
  final String title;
  const Post({this.id, required this.title});
}

The code generator detects this mixin and:

  • Adds virtual createdAt and updatedAt fields if not explicitly defined
  • Automatically sets timestamps on insert/update operations

For timezone-aware timestamps (UTC storage), use TimestampsTZ instead.

Driver Support

Ormed works with any database through driver adapters:

  • ormed_sqlite - SQLite support (in-memory and file-based)
  • ormed_postgres - PostgreSQL support (planned)
  • ormed_mysql - MySQL support (planned)

Migrations

Schema migrations with a fluent builder API:

class CreateUsersTable extends Migration {
  @override
  Future<void> up(MigrationBuilder builder) async {
    await builder.create('users', (table) {
      table.increments('id').primary();
      table.string('email').unique();
      table.string('name').nullable();
      table.boolean('active').defaultValue(true);
      table.timestamps();
    });
  }

  @override
  Future<void> down(MigrationBuilder builder) async {
    await builder.drop('users');
  }
}

Testing

Built-in testing utilities:

// In-memory database for tests
final testDb = await TestDatabaseManager.create();

// Use OrmedTest mixin for common test patterns
class MyTest with OrmedTest { ... }

Key Classes

Additional Resources

  • See the repository examples for complete working code
  • Check individual class documentation for detailed API reference

Classes

$OrmMigrationRecord
Generated tracked model class for OrmMigrationRecord.
AdHocColumn
Column definition for ad-hoc queries.
AdHocModelDefinition
A model definition for ad-hoc queries without a concrete model class.
AdHocRow
Map-backed row returned for ad-hoc table queries.
AggregateExpression
Aggregate expression descriptor.
AppliedMigrationRecord
Snapshot of a migration persisted inside the ledger table.
AttributeCastContext
Context passed to AttributeCastHandler implementations.
AttributeCastHandler
Handles custom attribute cast logic by key.
AttributeInspector
Mirrors Laravel-style attribute guards, hidden lists, and casts.
BitwisePredicate
BoolCodec
Codec that normalizes boolean-like values.
CacheEvent
Events emitted during query caching lifecycle.
CacheFlushEvent
Emitted when cache is flushed.
CacheForgetEvent
Emitted when a cache entry is manually removed.
CacheHitEvent
Emitted when a query result is retrieved from cache.
CacheMissEvent
Emitted when a query result is not in cache.
CacheStats
Statistics about cache state.
CacheStoreEvent
Emitted when a query result is stored in cache.
CacheVacuumEvent
Emitted when cache is vacuumed (expired entries removed).
Carbon
CarbonCodec
Codec for Carbon/CarbonInterface fields.
CarbonComponents
Immutable snapshot returned by Carbon.toArray()/toObject().
CarbonConfig
Configuration for Carbon date/time functionality in Ormed.
CarbonDateFormat
CarbonDateFormat formats dates in a locale-sensitive manner.
CarbonDateTimeView
Bridges a CarbonInterface to the standard DateTime API surface so the instance can be passed wherever a DateTime is expected.
CarbonFactory
Builds Carbon instances with pre-configured locale, timezone, settings, and per-instance toString format (mirrors PHP's Carbon\Factory).
CarbonImmutable
Immutable Carbon implementation.
CarbonInterface
Contract shared by Carbon and CarbonImmutable.
CarbonInterval
Span that can express both calendar months and exact microseconds.
CarbonLastErrors
Captures the results of the most recent parsing or creation attempt.
CarbonLocaleData
CarbonPeriod
Iterable range produced by Carbon's range* helpers.
CarbonSettings
Global knobs that shape how Carbon performs calendar math.
CarbonTestSubclass
Internal helper used by tests to verify subclass behavior.
CarbonTranslator
Registry for language overrides inspired by PHP's Translator class.
ClosurePlanCompiler
ColumnBuilder
ColumnCommand
Snapshot of a column mutation.
ColumnDefault
Representation of a default value. Literal values and SQL expressions are both supported.
ColumnDefinition
Declarative column metadata captured by the DSL.
ColumnDriverOverride
Driver-specific column hints that override the default definition.
ColumnRename
Records the original and new names for a column rename.
ColumnType
Declarative column type metadata.
ConnectionClosed
Fired when a connection is closed.
ConnectionConfig
Immutable metadata describing how an ORM connection should be identified.
ConnectionDefinition
ConnectionEstablished
Fired when a new database connection is established.
ConnectionEvent
Base class for all connection-scoped events.
ConnectionFactory
Factory that dispatches to registered connectors based on driver type.
ConnectionFailed
Fired when connection fails.
ConnectionHandle<TClient>
Handle returned by connectors. Wraps a client and exposes a close callback.
ConnectionManager
ConnectionMetadata
Metadata describing a materialized connection handle.
ConnectionResolver
Describes a runtime context capable of executing ORM queries.
ConnectionStarted
Fired when connecting to a database starts.
Connector<TClient>
Connector implementations build concrete connections for a driver.
CursorPageResult<T extends OrmEntity>
Cursor-based pagination payload.
CustomGroupByExpression
Custom GROUP BY expression compiled by a driver extension.
CustomOrderExpression
Custom ORDER BY expression compiled by a driver extension.
CustomPredicate
Custom predicate compiled by a driver extension.
CustomSelectExpression
Custom select expression compiled by a driver extension.
DatabaseConfig
High-level database configuration that may include read replicas.
DatabaseEndpoint
Endpoint configuration describing a single concrete connection target.
DatabaseSeeder
Base class for database seeders that work with OrmConnection
DataSource
A unified entry point for ORM operations that manages connections, model registration, and provides ergonomic access to queries and repositories.
DataSourceOptions
Configuration options for initializing a DataSource.
DateCodec
Codec for date-only values.
DatePredicateCompilation
Result of compiling a DateWhereClause into SQL + bindings.
DatePredicateInput
DateTimeCodec
Codec for DateTime fields that handles Carbon type conversion. This ensures that Carbon values stored during operations like soft delete can be properly decoded back to DateTime.
DateWhereClause
DecimalCodec
Codec for Decimal values.
DefaultFieldGeneratorProvider
Default generator that returns simple primitives for common scalar fields.
DistinctOnClause
DocumentStatementPayload
Generic command/payload used by document drivers.
DoubleCodec
Codec that normalizes floating-point values.
DriverAdapter
Handles the lifecycle of connections and query execution for a specific backend.
DriverAdapterRegistry
Registry of DriverAdapter factories keyed by driver type.
DriverConfig
DriverExtension
Bundle of driver extension handlers.
DriverExtensionContext
Context passed to driver extension handlers during compilation.
DriverExtensionFragment
Result of compiling a custom clause into SQL and bindings.
DriverExtensionHandler
Handler for a driver extension clause.
DriverExtensionHost
Implemented by drivers that can register custom query clause extensions.
DriverExtensionRegistry
Registry of driver extension handlers by clause kind.
DriverMetadata
Capabilities advertised by a driver.
DriverModel
Marker annotation used to flag the driver that should handle this model.
DriverRegistry
Registry of driver callbacks keyed by normalized driver type.
DriverTypeMapper
Abstract base class for driver-specific type mappings
DropTableOptions
DtoInsertInput<T extends OrmEntity>
Insert input wrapper for insert DTOs.
DtoUpdateInput<T extends OrmEntity>
Update input wrapper for update DTOs.
Event
Base class for all events in the system.
EventBus
A type-safe event bus implementing the publish/subscribe pattern.
ExecutingStatement
FallbackPlanCompiler
FieldAttributeMetadata
Per-field metadata overrides for attribute behavior.
FieldDefinition
Metadata for a single model field/column.
FieldDriverOverride
Driver-specific metadata for a field definition.
FieldPredicate
Predicate that targets a specific column.
FilterClause
Filter clause applied to a single column.
ForeignKeyBuilder
ForeignKeyCommand
Snapshot of a foreign key mutation.
ForeignKeyDefinition
Declarative foreign key metadata.
ForeignKeyEntry
FullTextWhere
GeneratorProvider
Provides backend-aware fallbacks when no bespoke generator is supplied.
GroupLimit
HasFactory
Marker annotation that enables factory support for a model.
IdentityCodec<TDart>
No-op codec used for primitives.
IndexCommand
Snapshot of an index mutation.
IndexDefinition
Declarative index metadata.
IndexHint
InsertDto<T extends OrmEntity>
Represents insertable data for an ORM entity.
InsertInput<T extends OrmEntity>
Union type representing valid inputs for repository insert operations.
IntCodec
Codec that normalizes integer-like values.
JoinBuilder
Fluent builder for constructing complex JOIN conditions.
JoinCondition
Predicate fragment within a JOIN clause.
JoinDefinition
Representation of a JOIN clause applied during query compilation.
JoinTarget
Target table or subquery for a JOIN clause.
JsonArrayCodec
Codec for JSON array encoding/decoding List fields. Encodes to JSON string for storage, decodes from JSON string to List.
JsonAttributeUpdate
Represents a queued JSON attribute operation.
JsonCodec
Codec for JSON encoding/decoding Map<String, Object?> fields. Encodes to JSON string for storage, decodes from JSON string to Map.
JsonPathReference
JsonPredicateCompilation
Result of compiling a JsonWhereClause into SQL + bindings.
JsonSelector
Normalized reference to a JSON selector (column + path).
JsonUpdateClause
JsonUpdateCompilation
Result of compiling a JSON update into SQL + bindings.
JsonUpdateDefinition
Defines a JSON update operation.
JsonUpdateSupport<T extends OrmEntity>
JsonValueCodec
Codec for JSON values of any type (object, array, string, number, bool).
JsonWhereClause
LockClauses
LongRunningQueryEvent
MapInsertInput<T extends OrmEntity>
Insert input wrapper for raw maps.
MappedAdHocQuery<R extends OrmEntity>
A query that maps its results to a different type.
MapUpdateInput<T extends OrmEntity>
Update input wrapper for raw maps.
Migration
Base contract migrations extend.
MigrationAction
Describes a single migration action that occurred.
MigrationBatchCompletedEvent
Event emitted when a migration batch completes.
MigrationBatchStartedEvent
Event emitted when a migration batch starts.
MigrationCompletedEvent
Event emitted when a single migration completes.
MigrationDescriptor
Snapshot of a compiled migration ready to be logged inside the ledger.
MigrationEntry
Ties a MigrationId to a Migration instance.
MigrationEvent
Base class for migration events.
MigrationFailedEvent
Event emitted when a migration fails.
MigrationId
Value object representing a migration identifier derived from its file name.
MigrationLedger
Storage abstraction for recording applied migrations.
MigrationReport
High-level summary returned after applying or rolling back migrations.
MigrationRunner
MigrationSection
MigrationSqlExporter
Exports SQL text files derived from schema plan previews.
MigrationStartedEvent
Event emitted when a single migration starts.
MigrationStatus
Status information for a migration when listing history.
Model<TModel extends Model<TModel>>
Base class for Ormed models.
ModelAttributesMetadata
Annotation-driven metadata for attribute behavior.
ModelCodec<TModel>
Base contract for generated model codecs.
ModelColumnSnapshot
Snapshot of a single column derived from a model field.
ModelCompanion<T extends Model<T>>
Generic base class for model companion objects that provide static helpers.
ModelCreatedEvent
Event emitted after a model is created in the database.
ModelCreatingEvent
Event emitted before a model is created in the database.
ModelDefinition<TModel extends OrmEntity>
Runtime description of a generated ORM model.
ModelDeletedEvent
Event emitted after a model is deleted from the database.
ModelDeletingEvent
Event emitted before a model is deleted from the database.
ModelEvent
Base class for model lifecycle events.
ModelFactoryBuilder<TModel extends OrmEntity>
Builder used by generated factory helpers.
ModelFactoryConnection<T extends OrmEntity>
Helper that binds a generated model definition to a QueryContext.
ModelFactoryDefinition<TModel extends OrmEntity>
Base class for defining external factory behavior.
ModelFactoryGenerationContext<TModel extends OrmEntity>
Context passed to generators while building factory output.
ModelFactoryRegistry
Internal registry that associates models with their generated definitions.
ModelForceDeletedEvent
Event emitted when a model is permanently deleted (force delete).
ModelGraphSnapshot
Captures the tables derived from the current ModelDefinition registry.
ModelInsertInput<T extends OrmEntity>
Insert input wrapper for model instances.
ModelRegistry
Registry that stores ModelDefinition objects by model type and name.
ModelReplicatingEvent
Event emitted when a model is being replicated.
ModelRestoredEvent
Event emitted after a model is restored from soft delete.
ModelRestoringEvent
Event emitted before a model is restored from soft delete.
ModelRetrievedEvent
Event emitted when a model is retrieved from the database.
ModelSavedEvent
Event emitted after a model is saved (create or update).
ModelSavingEvent
Event emitted before a model is saved (create or update).
ModelTableSnapshot
Snapshot of a single model's table shape.
ModelTrashedEvent
Event emitted when a soft-deleted model is trashed.
ModelUpdatedEvent
Event emitted after a model is updated in the database.
ModelUpdateInput<T extends OrmEntity>
Update input wrapper for model instances.
ModelUpdatingEvent
Event emitted before a model is updated in the database.
ModelWithTracked<T>
Interface for user-defined models that have a corresponding tracked model.
MutationEvent
Event payload emitted for every mutation execution.
MutationPlan
Description of a write operation to execute against a driver.
MutationResult
Result information produced by MutationPlan execution.
MutationRow
NormalizedPreview
Normalized preview data shared across drivers.
OnCreated
Convenience annotation for model created events.
OnCreating
Convenience annotation for model creating events.
OnDeleted
Convenience annotation for model deleted events.
OnDeleting
Convenience annotation for model deleting events.
OnEvent
Annotation to mark a method as an event handler.
OnForceDeleted
Convenience annotation for model force-deleted events.
OnReplicating
Convenience annotation for model replicating events.
OnRestored
Convenience annotation for model restored events.
OnRestoring
Convenience annotation for model restoring events.
OnRetrieved
Convenience annotation for model retrieved events.
OnSaved
Convenience annotation for model saved events.
OnSaving
Convenience annotation for model saving events.
OnTrashed
Convenience annotation for model trashed events.
OnUpdated
Convenience annotation for model updated events.
OnUpdating
Convenience annotation for model updating events.
OrderClause
Ordering rule applied to a column.
OrmAccessor
Marks an instance getter or method as an attribute accessor.
OrmConfig
Global configuration for the ORM.
OrmConnection
Represents a fully materialized ORM connection that exposes helpers, metadata, and instrumentation hooks.
OrmConnectionFactory
Registers named ORM connections and returns disposable handles.
OrmConnectionHandle
Lightweight handle returned when registering a named OrmConnection.
OrmDriverFieldOverride
Describes driver-specific overrides for a model field.
OrmedTestConfig
Global test counter for unique IDs Configuration object returned by setUpOrmed. Pass this to ormedGroup to ensure the correct manager is used.
OrmEntity
Marker interface for ORM-managed entities and generated tracked models.
OrmEvent
Marks a model method as a handler for a specific event type.
OrmField
Additional metadata for a model field/column.
OrmMigrationRecord
Internal model used to track applied migrations in the database.
OrmMigrationRecordInsertDto
Insert DTO for OrmMigrationRecord.
OrmMigrationRecordModelFactory
OrmMigrationRecordPartial
Partial projection for OrmMigrationRecord.
OrmMigrationRecords
OrmMigrationRecordUpdateDto
Update DTO for OrmMigrationRecord.
OrmModel
Marks a Dart class as an Ormed model.
OrmMutator
Marks an instance setter or method as an attribute mutator.
OrmProjectConfig
OrmRelation
Relationship descriptor applied to fields referencing other models.
OrmScope
Marks a static model method as a query scope.
OrmSoftDelete
Marks a field as the soft-delete column for a model.
PageResult<T extends OrmEntity>
Rich pagination payload returned by Query.paginate.
PartialEntity<T extends OrmEntity>
Partial projection of an ORM entity where all fields are nullable.
PlanCompiler
Translates ORM plans into statement previews for a backend.
PredicateBuilder<T extends OrmEntity>
Lightweight builder used for nested predicate callbacks.
PredicateField<T extends OrmEntity, TValue>
Typed field helper for predicate callbacks.
PredicateGroup
A group of predicates joined by logicalOperator.
ProjectionOrderEntry
Query<T extends OrmEntity>
Fluent builder for filtering, ordering, paginating, and eager-loading models of type T.
QueryBuilderHook
Extension points that allow adapters to customize query building and schema handling for ORM models.
QueryCache
Portable query result cache with TTL support and event emission.
QueryCompilation
Result of compiling a QueryPlan into SQL + bindings.
QueryContext
The central hub for interacting with the ORM.
QueryEvent
Event payload emitted for every query execution.
QueryExecuted
Fired after every query executes.
QueryExecutor
Executes QueryPlan objects against a concrete backend.
QueryGrammar
Base grammar capable of compiling QueryPlan objects into SQL strings.
QueryLogEntry
Structured representation of a logged query or mutation.
QueryPlan
Immutable description of a query that QueryExecutor implementations consume.
QueryPredicate
Base type for predicate nodes.
QueryRow<T extends OrmEntity>
Holds the model, its raw row, and any eager-loaded relations.
QueryRowIdentifier
Describes the expression a driver uses to uniquely identify rows for query-driven updates when no primary key is available.
QueryUnion
QueryWarning
Warning payload emitted when the query layer detects a risky condition.
RawGroupByExpression
Raw GROUP BY expression.
RawOrderExpression
Raw ORDER BY expression.
RawPredicate
Raw SQL predicate fragment with optional bindings.
RawSelectExpression
Raw select expression.
RelationAggregate
RelationDefinition
Metadata for a relationship between two models.
RelationHook
Optional hook drivers can use to customize how eager-loaded relations materialize after the base query fetches rows.
RelationJoin
Captures a join edge between the base table and a related segment the query references. Grammars can reuse this graph across aggregates, ordering, and eager loading helpers.
RelationJoinEdge
RelationJoinRequest
RelationLoad
Declaration describing an eager-loaded relation request.
RelationLoader
Hydrates eager-loaded relations after the base query executes.
RelationOrder
RelationPath
RelationPredicate
RelationResolver
Utility class for resolving and building relation metadata.
RelationSegment
RenameTableOptions
Repository<T extends OrmEntity>
A repository for a model of type T.
RepositoryBase<T extends OrmEntity>
Base class for repositories.
RepositoryHook
Extension point for replacing the default repository implementation.
ResolvedField
SchemaBuilder
Fluent builder that collects schema commands for a migration direction.
SchemaColumn
Metadata describing a table column.
SchemaDialect
Dialects convert individual schema mutations into executable SQL.
SchemaDiff
Aggregated diff output describing a migration plan.
SchemaDiffEntry
One human-readable entry produced by the schema differ.
SchemaDiffer
Computes a diff between the desired schema plan and the current snapshot.
SchemaDriver
Contract implemented by database drivers that can execute schema plans and introspect live database metadata.
SchemaForeignKey
Metadata describing a foreign key constraint.
SchemaIndex
Metadata describing an index.
SchemaInspector
High-level helper that mirrors Laravel's schema inspector.
SchemaMutation
A mutation emitted by the schema builder.
SchemaMutationHook
Allows drivers to intercept schema mutations produced by the Blueprint DSL.
SchemaNamespace
Additional metadata about namespaces/schemas available on a connection.
SchemaPlan
Immutable collection of schema mutations.
SchemaPlanCompiler
Translates SchemaPlan objects into SQL statements using a dialect.
SchemaPreview
Preview of the SQL statements a schema plan would execute. A preview of SQL statements that would be executed for a schema plan.
SchemaSnapshot
Captures a read-only snapshot of schema metadata for offline inspection.
SchemaState
Abstraction for drivers that can dump/load the schema via native tooling.
SchemaStatement
Represents a single schema statement and optional structured payload.
SchemaStateProvider
Optional interface drivers can implement to expose schema dump helpers.
SchemaTable
Metadata describing a database table (excluding views).
SchemaTableIdentifier
Identifier that pairs a schema with a table name for comparisons.
SchemaView
Metadata describing a database view.
ScopeRegistry
A registry for query scopes and macros.
Seeder
Base class for database seeders
SeederAction
Result of a single seeder execution.
SeederCompletedEvent
Event emitted when a single seeder completes.
SeederEvent
Base class for seeder events.
SeederFailedEvent
Event emitted when a seeder fails.
SeederRegistration
Seeder registration for managing multiple seeders.
SeederRegistry
Registry and runner for database seeders
SeederRunner
Runs seeders and emits lifecycle events.
SeederStartedEvent
Event emitted when a single seeder starts.
SeedingCompletedEvent
Event emitted when seeding completes.
SeedingReport
Summary of a seeding run.
SeedingStartedEvent
Event emitted when seeding starts.
SeedSection
SimplePageResult<T extends OrmEntity>
Lightweight pagination payload that skips total counting.
SnapshotSchemaDriver
Lightweight driver backed entirely by a SchemaSnapshot.
SqlFileMigration
A Migration implementation backed by SQL files (up.sql and down.sql).
SqliteFullTextOptions
Options for SQLite full text search indexes.
SqliteSpatialIndexOptions
Options controlling SQLite spatial indexes.
SqlMigrationLedger
Generic SQL ledger that persists migrations inside a driver-managed table.
SqlStatementPayload
SQL statement emitted by relational drivers.
StatementPayload
Statement payloads produced by drivers (SQL text or backend-specific command).
StatementPreview
Preview of a statement produced by a plan compiler.
StringCodec
Codec that normalizes string values.
StructuredQueryLogger
Serializes query + mutation events into structured log entries.
SubqueryPredicate
Subquery predicate for WHERE IN, WHERE EXISTS, etc.
TableBlueprint
Mutable blueprint that records the operations to perform against a table.
TableQueryDefinition<T extends OrmEntity>
A wrapper definition that uses an underlying registered model definition but returns Map<String, Object?> for table() queries.
TestDatabaseManager
Manages the lifecycle and isolation of test databases.
TestSchemaManager
Manages test schema setup with migrations and seeding support
TimestampCodec
Codec for Unix timestamps (seconds since epoch).
TouchesList
Immutable list wrapper for touched relations that also supports call syntax.
TransactionBeginning
Fired when a transaction begins.
TransactionCommitted
Fired after a transaction commits successfully.
TransactionCommitting
Fired when a transaction is about to commit.
TransactionRolledBack
Fired after a transaction rolls back.
TypeMapperRegistry
Registry for driver type mappers
TypeMapping
Represents a mapping between Dart and SQL types with codec support
UpdateDto<T extends OrmEntity>
Represents updatable data for an ORM entity.
UpdateInput<T extends OrmEntity>
Union type representing valid inputs for repository update operations.
UpdatePayload
ValueCodec<TDart>
Converts between backend driver payloads and Dart values.
ValueCodecRegistry
Registry that resolves codecs per field/type, with driver-specific overlays.
ValueEncrypter
Encrypts and decrypts string payloads for encrypted casts.

Enums

AggregateFunction
Supported aggregate functions.
CarbonUnit
Units accepted by helper methods such as add/sub.
CastOperation
ColumnCommandKind
Low-level column command kinds surfaced through TableBlueprint.
ColumnMutation
Describes whether a column command adds or alters a column.
ColumnTypeName
Logical column type names recognized by the DSL.
ConnectionRole
Indicates which connection role should be established.
DatabaseIsolationStrategy
Defines strategies for database isolation in tests.
DateComponent
DriverCapability
DriverExtensionKind
Clause kinds that can be extended by drivers.
ExecutingStatementType
FilterOperator
Supported comparison operators for filters.
ForeignKeyCommandKind
Foreign-key command kinds supported by the fluent DSL.
FullTextMode
IndexCommandKind
Index command kinds supported by the fluent DSL.
IndexHintType
IndexType
Logical index types that influence naming and SQL generation.
JoinType
Supported JOIN clause types applied by the grammar.
JsonPredicateType
MigrationDirection
Directions supported by a migration lifecycle.
MigrationFormat
Default authoring format used by CLI migration generation.
MigrationOperation
Supported operations tracked inside a MigrationAction.
MorphKeyType
Morph key variants supported by helper methods like TableBlueprint.morphs.
MutationOperation
Supported mutation types.
PredicateLogicalOperator
Logical operator used for predicate grouping.
PredicateOperator
Comparison operators for complex predicates.
ProjectionKind
QueryCacheInvalidationPolicy
Policies for invalidating cached query results after mutations.
ReferenceAction
Reference actions that control cascading behavior for foreign keys.
RelationAggregateType
RelationKind
Supported relationship kinds mirrored after Eloquent/GORM semantics.
SchemaDiffAction
Describes the action a diff entry represents.
SchemaDiffSeverity
Severity used when presenting schema change diagnostics.
SchemaMutationOperation
High-level operations supported by the schema planner.
SubqueryType
Types of subquery predicates.
TableAliasStrategy
Strategies for auto-generating table aliases in ad-hoc queries.
TableOperationKind
Determines whether a blueprint is creating a new table or mutating an existing one.
TransactionOutcome
TransactionScope

Mixins

CancellableEvent
Mixin for events that can be cancelled.
ModelAttributes
Attribute storage and change tracking for a model instance.
ModelConnection
Provides access to the connection context that hydrated a model instance.
ModelFactoryCapable
Marker mixin that enables the generated factory helpers.
ModelRelations
Provides runtime relation caching and lazy loading support for model instances.
RepositoryDeleteMixin<T extends OrmEntity>
Mixin that provides delete operations for repositories.
RepositoryHelpersMixin<T extends OrmEntity>
Mixin that provides internal helper methods for repository operations.
RepositoryInputHandlerMixin<T extends OrmEntity>
Mixin that provides input handling utilities for repositories.
RepositoryInsertMixin<T extends OrmEntity>
Mixin that provides insert operations for repositories.
RepositoryPreviewMixin<T extends OrmEntity>
Mixin that provides preview methods for repository operations.
RepositoryReadMixin<T extends OrmEntity>
Read-side helpers for repositories, delegating to the query builder.
RepositoryUpdateMixin<T extends OrmEntity>
Mixin that provides update operations for repositories.
RepositoryUpsertMixin<T extends OrmEntity>
Mixin that provides upsert operations for repositories.
ResultEvent<T>
Mixin for events that carry a result/response.
SoftDeletes
Marker mixin for soft-delete functionality.
SoftDeletesImpl
Implementation mixin for soft-delete functionality.
SoftDeletesTZ
Marker mixin for timezone-aware soft-delete functionality.
SoftDeletesTZImpl
Implementation mixin for timezone-aware soft-delete functionality.
Timestamps
Marker mixin for timestamp functionality (non-timezone aware).
TimestampsImpl
Implementation mixin for timestamp functionality (non-timezone aware).
TimestampsTZ
Marker mixin for timezone-aware timestamp functionality.
TimestampsTZImpl
Implementation mixin for timezone-aware timestamp functionality.

Extensions

AggregateExtension on Query<T>
Extension providing aggregate functions for query results.
BatchOperationsExtension on Query<T>
Extension providing batch operation methods for efficient bulk queries.
CarbonAliasShims on CarbonInterface
Adds the PHP-style alias methods (addDay, subMonth, etc.) to any CarbonInterface. Each alias simply forwards to the canonical method so mixin users get the familiar Carbon API surface.
CarbonDateTimeInterop on CarbonInterface
Convenience extension to create DateTime views from any Carbon instance.
ConnectionRoleX on ConnectionRole
CrudExtension on Query<T>
DataSourceManagerExtension on ConnectionManager
Extension to add data source registration to ConnectionManager.
DataSourceSeeding on DataSource
Extension on DataSource for convenient seeding
DistinctExtension on Query<T>
Extension providing DISTINCT clause methods for query results.
GroupingExtension on Query<T>
Extension providing GROUP BY and HAVING clause methods for query results.
IndexExtension on Query<T>
Extension providing index hint methods for query optimization.
JoinExtension on Query<T>
JsonExtension on Query<T>
LockExtension on Query<T>
Extension providing row locking methods for transaction safety.
MapQueryExtensions on Query<AdHocRow>
ModelAttributeExtensions on Model<T>
Extensions on Model that provide convenient access to attribute and relation tracking features.
ModelAttributeMapExtensions on Map<String, Object?>
Extensions for applying model attribute metadata to a raw map.
ModelRegistryX on ModelRegistry
ModelScopeExtensions on Type
ModelSoftDeleteExtensions on Model<T>
Extensions for soft delete functionality on models.
ModelTimestampExtensions on Model<T>
Extensions for timestamp functionality on models.
OrderExtension on Query<T>
Extension providing ordering methods for query results.
OrmMigrationRecordOrmDefinition on OrmMigrationRecord
OrmMigrationRecordOrmExtension on OrmMigrationRecord
PaginateExtension on Query<T>
Extension providing pagination and limit/offset methods for query results.
QueryCachingExtension on Query<T>
Extension providing query result caching (Laravel-style remember).
RawQueryExtension on Query<T>
Extension providing additional raw SQL query helpers for advanced use cases.
RelationExtension on Query<T>
Extension providing relation eager loading and aggregate methods.
SchemaDriverTestExtensions on SchemaDriver
Extension to add test schema management to SchemaDriver
ScopeExtension on Query<T>
SelectExtension on Query<T>
Extension providing SELECT clause and projection methods for query results.
SoftDeleteExtension on Query<T>
Extension providing soft delete functionality for models.
StreamingExtension on Query<T>
SubqueryExtension on Query<T>
Extension providing subquery support for query builder.
UnionExtension on Query<T>
Extension providing UNION operations and insert-from-select functionality.
UtilityExtension on Query<T>
Extension providing utility methods for query inspection and validation.
WhereExtension on Query<T>

Constants

hasFactory → const HasFactory
Convenience constant for @HasFactory().

Properties

allLocales Map<String, CarbonLocaleData>
final
currentTestDataSource DataSource?
Get the current test data source (valid inside ormedGroup/ormedTest)
no setter
testDatabaseManager TestDatabaseManager?
Get current test database manager
no setter

Functions

connectionNameForConfig(Directory root, OrmProjectConfig config) String
Returns the canonical ConnectionManager name for the active config.
expandEnv(Object? value, Map<String, String> environment) Object?
Recursively expand ${VAR} or ${VAR:-default} placeholders inside a YAML structure using environment. Strings without placeholders are returned unchanged.
fallbackPlanCompiler() PlanCompiler
findOrmConfigFile([Directory? startDirectory]) File?
Finds the ormed.yaml file by searching from startDirectory up to the filesystem root.
hasJsonSelector(String expression) bool
Whether expression contains a JSON selector operator.
jsonPathSegments(String normalizedPath) List<String>
Splits a normalized JSON path (starting with $) into its individual segments.
loadOrmConfig([Directory? startDirectory]) OrmProjectConfig
Loads OrmProjectConfig by finding ormed.yaml in the current directory or any parent directory.
loadOrmProjectConfig(File file) OrmProjectConfig
Loads OrmProjectConfig from file.
normalizeJsonPath(String rawPath) String
Normalizes a user-supplied JSON path expression into a canonical representation starting with $.
ormedGroup(String description, void body(DataSource dataSource), {OrmedTestConfig? config, DataSource? dataSource, List<Migration>? migrations, DatabaseRefreshStrategy? refreshStrategy, String? testOn, Timeout? timeout, dynamic skip, dynamic tags, Map<String, dynamic>? onPlatform, int? retry}) → void
Runs a test group with database isolation.
ormedTest(String description, FutureOr<void> body(DataSource dataSource), {String? testOn, Timeout? timeout, dynamic skip, dynamic tags, Map<String, dynamic>? onPlatform, int? retry}) → void
Runs a test with database isolation.
parseJsonSelectorExpression(String expression) JsonSelector?
Attempts to parse expression into a JsonSelector. Returns null when no JSON operator is present.
previewTestSeed(List<DatabaseSeeder Function(OrmConnection)> seeders, DataSource dataSource) Future<List<QueryLogEntry>>
Preview seeder queries without executing them
registerConnectionsFromConfig({required Directory root, required OrmProjectConfig config, ConnectionManager? manager, ModelRegistry? registry, String? targetConnection}) Future<OrmConnectionHandle>
Registers every entry from config with ConnectionManager.defaultManager.
registerOrmMigrationRecordEventHandlers(EventBus bus) → void
runSeederRegistry(OrmConnection connection, List<SeederRegistration> seeders, {List<String>? names, bool pretend = false, void log(String message)?}) Future<void>
Run registered seeders on a connection
seedTestData(List<DatabaseSeeder Function(OrmConnection)> seeders, DataSource dataSource) Future<void>
Seed data in the current test environment
setUpOrmed({required DataSource dataSource, Future<void> runMigrations(DataSource)?, List<Migration>? migrations, List<MigrationDescriptor>? migrationDescriptors, List<DatabaseSeeder Function(OrmConnection)>? seeders, DatabaseIsolationStrategy strategy = DatabaseIsolationStrategy.migrateWithTransactions, bool parallel = false, DriverAdapter adapterFactory(String testDbName)?, bool migrateBaseDatabase = true}) OrmedTestConfig
Configures Ormed for testing.
testMigrationStatus(DataSource dataSource) Future<List<MigrationStatus>>
Get migration status in the test environment

Typedefs

AttributeAccessor = Object? Function(OrmEntity model, Object? value)
Reads a model attribute value using a custom accessor.
AttributeMutator = Object? Function(OrmEntity model, Object? value)
Transforms a model attribute value using a custom mutator.
CarbonMacro = dynamic Function(dynamic target, List positionalArguments, Map<Symbol, dynamic> namedArguments)
Function signature used by Carbon.registerMacro.
ChunkCallback<T extends OrmEntity> = FutureOr<bool> Function(List<QueryRow<T>> chunk)
A callback that receives a chunk of QueryRows.
ConnectionReleaseHook = FutureOr<void> Function(OrmConnection connection)
ConnectionResolverFactory = ConnectionResolver Function(String connectionName)
Function that resolves a ConnectionResolver for a given connection name.
ConnectorBuilder = Connector Function()
DatabaseRefreshStrategy = DatabaseIsolationStrategy
Re-export DatabaseIsolationStrategy as DatabaseRefreshStrategy for backwards compatibility
DriverAdapterFactory = DriverAdapter Function(DriverConfig config)
Signature for a factory that creates a DriverAdapter from a DriverConfig.
DriverExtensionCompiler = DriverExtensionFragment Function(DriverExtensionContext context, Object? payload)
Function signature used to compile a custom clause.
DriverRegistration = FutureOr<OrmConnectionHandle> Function({required String connectionName, required ConnectionDefinition definition, required ConnectionManager manager, required ModelRegistry registry, required Directory root})
Signature used by drivers to register an OrmConnection for a tenant.
EventListener<T extends Event> = void Function(T event)
Callback type for event listeners.
ExecutingStatementCallback = void Function(ExecutingStatement statement)
FieldValueGenerator<TModel extends OrmEntity> = Object? Function(FieldDefinition field, ModelFactoryGenerationContext<TModel> context)
Signature used to generate a field value for a factory.
GlobalScopeCallback<T extends OrmEntity> = Query<T> Function(Query<T> query)
A callback for a global scope.
JoinConstraintBuilder = void Function(JoinBuilder join)
JsonUpdateBuilder<T extends OrmEntity> = List<JsonUpdateDefinition> Function(T model)
LocalScopeCallback<T extends OrmEntity> = Query<T> Function(Query<T> query, List<Object?> args)
A callback for a local scope.
LongRunningQueryCallback = void Function(LongRunningQueryEvent event)
MigrationPlanResolver = Future<SchemaPlan> Function(MigrationDescriptor descriptor, MigrationDirection direction)
Coordinates applying and rolling back migrations using a SchemaDriver and ledger store.
MutationHook = void Function(MutationPlan plan)
OrmConnectionBuilder = OrmConnection Function(ConnectionConfig config)
PredicateCallback<T extends OrmEntity> = void Function(PredicateBuilder<T> builder)
A callback that receives a PredicateBuilder.
QueryHook = void Function(QueryPlan plan)
QueryLogHook = void Function(QueryLogEntry entry)
QueryMacroCallback = Query<OrmEntity> Function(Query<OrmEntity> query, List<Object?> args)
A callback for a query macro.
RelationCallback = void Function(PredicateBuilder builder)
A callback that receives a PredicateBuilder for a relation.
RowCallback<T extends OrmEntity> = FutureOr<bool> Function(QueryRow<T> row)
A callback that receives a single QueryRow.
SequenceGenerator = Map<String, Object?> Function(int index)
Signature for sequence generators.
StateTransformer<TModel extends OrmEntity> = Map<String, Object?> Function(Map<String, Object?> attributes)
Model factories for generating test data and seed records.
TransactionHook = FutureOr<void> Function()
TransactionOutcomeHook = FutureOr<void> Function(TransactionOutcome outcome, TransactionScope scope)
UntrackedModelEncoder = Map<String, Object?> Function(Object model, ValueCodecRegistry registry)
Encodes a user-defined (untracked) model instance to a column/value map.
UntypedLocalScope = Query<OrmEntity> Function(Query<OrmEntity> query, List<Object?> args)
An untyped local scope.
UntypedScope = Query<OrmEntity> Function(Query<OrmEntity> query)
An untyped global scope.

Exceptions / Errors

CarbonBadComparisonUnitException
CarbonBadFluentConstructorException
CarbonBadFluentSetterException
CarbonBadMethodCallException
Mirrors PHP's BadMethodCallException interface.
CarbonEndLessPeriodException
CarbonImmutableException
CarbonInvalidArgumentException
Mirrors PHP's InvalidArgumentException interface.
CarbonInvalidCastException
CarbonInvalidDateException
Thrown when a helper receives an out-of-range date component.
CarbonInvalidFormatException
CarbonInvalidIntervalException
CarbonInvalidPeriodDateException
CarbonInvalidPeriodParameterException
CarbonInvalidTimeZoneException
CarbonInvalidTypeException
CarbonMessageException
Base class for Carbon exceptions that carry a human-readable message.
CarbonNotACarbonClassException
CarbonNotAPeriodException
CarbonNotLocaleAwareException
CarbonOutOfRangeException
CarbonParseErrorException
CarbonRuntimeException
Mirrors PHP's RuntimeException interface.
CarbonUnitException
Base class for all unit-related exceptions.
CarbonUnitNotConfiguredException
CarbonUnknownGetterException
CarbonUnknownMethodException
CarbonUnknownSetterException
CarbonUnknownUnitException
CarbonUnreachableException
CarbonUnsupportedUnitException
CodecNotFound
Thrown when a requested codec type is missing from the registry.
DriverException
Driver-specific exception with structured context for CLI/runtime output.
DriverExtensionConflictError
Thrown when a driver extension key is registered twice for the same kind.
LazyLoadingViolationException
Exception thrown when attempting to lazy load a relation while lazy loading is globally prevented.
MassAssignmentException
MissingDriverExtensionError
Thrown when a driver extension handler is missing during compilation.
ModelNotFoundException
Thrown when a query expected at least one row but none were returned.
ModelNotRegistered
Thrown when a model definition hasn't been registered in a registry.
ModelNotRegisteredByName
Thrown when a model is requested by name but not found in the registry.
ModelNotRegisteredByTableName
Thrown when a model is requested by table name but not found in the registry.
MultipleRecordsFoundException
Thrown when a query expected only one row but multiple were returned.
OrmException
Base exception type for Ormed runtime errors that should be user-facing.