d_rocket library

🚀 d_rocket — Dart's data rocket.

d_rocket is a unified package for the four pillars of data handling in Dart/Flutter applications:

  1. LINQ-style queries — IQueryable<T> with deferred execution.
  2. Serialization — annotation-driven toJson / fromJson.
  3. REST with steroids — typed HTTP client with interceptors, wrap-around clients (retry, rate limit, circuit breaker), and cancelable requests.
  4. ORM (engine-agnostic) — DbContext / DbSet<T> / @Table / change tracking / code-first migrations / auto-migrations. The actual database engine is a separate d_rocket_engine_* package. d_rocket ships the engine-agnostic core + the EngineRegistry slot. To use a real database, add d_rocket_engine_sqlite (or another engine) and call its register() once at app startup.
  5. Sync (offline-first) — SyncProvider interface, push/pull pipeline, identity persistence, conflict resolution, retry with exponential backoff, sync triggers.
  6. Realtime — WebSocket + SSE clients with codegen.

Status

d_rocket is at 2.0.0 (engine-agnostic, lockstep with the d_rocket_engine_* packages). All six data layers are complete: LINQ, Serializer, REST (with wrap-around resilience + cancelable requests), ORM (engine-agnostic, three engines in 2.0: SQLite, Postgres, libsql_wasm), Sync (offline-first with conflict resolution), Realtime (WebSocket + SSE with codegen).

See CHANGELOG.md for the full history.

Classes

AggregateExpr
An aggregate call: SUM(x), COUNT(x), AVG(x), MIN(x), MAX(x). The function is one of "SUM", "COUNT", "AVG", "MIN", "MAX". distinct emits DISTINCT (COUNT(DISTINCT x)).
AllowAllSyncFilter
A no-op filter that includes every change. The default for DbContext.syncAsync when no filters are passed.
AppliedMigration
: a row from the _d_rocket_migrations table. Materialized into a typed struct so the user doesn't have to parse Map<String, Object?> rows by hand.
AsyncMigrationTransaction
: a transactional execution context for the async path. Returned by an AsyncMigrationTransactionFactory when the user opts in to automatic transaction wrapping on MigrationRunner.runAsync / MigrationRunner.rollbackAsync.
AsyncQueryProvider
: the async-first query provider contract.
AuthRefreshHandler
A handler that refreshes the auth token when a sync round-trip fails with 401.
AutoMigrationResult
: the result of an auto-migration run. Bundles the safe diffs that were applied (for logging) and the unsafe diffs that were NOT applied (for the caller to surface).
AutoMigrator
: the auto-migrator.
BinaryExpr
Body
El argumento se serializa como cuerpo de la petición (JSON).
CacheEntry
A cache entry: body + ETag + last-fetched time.
CancelToken
A token that can be attached to a RestRequest to allow the caller to cancel an in-flight HTTP request.
ChangeEntry
A single entity in a ChangeSet — the interceptor's view of one row about to be INSERTed / UPDATEd / DELETEd.
ChangeEvent
A single change event emitted by ChangeTracker.
ChangeSet
A snapshot of all changes about to be saved (or just saved) by a single saveChanges() call. Interceptors receive this in onSaveChangesStart and onSaveChangesEnd.
ChangeTracker
CircuitBreakerHttpClient
ClientWinsConflictPolicy
Client-wins policy. The merged row takes every local value and falls back to the remote value for columns the local row does not have.
CoalesceExpr
.e: a null-coalesce a ?? b.
Column
Marks a field as a column of its @Table entity.
ColumnMeta
Metadata for a single column of a @Table entity. Emitted by the codegen as part of the EntityMeta literal; the runtime never constructs a ColumnMeta by itself.
CompositeInterceptor
Composes several interceptors in order.
CompressedBody
A marker for a request that's been compressed. The actual compression is applied by the wrapper client.
ConflictPolicy
ConflictPolicy is the preferred API over the bare ConflictResolver typedef (which is still supported for back-compat). The typed form documents the four common cases as named constants and provides a single point of extensibility for custom merge logic via ConflictPolicy.custom.
ConnectivityProvider
The interface for a connectivity provider.
ConnectivityState
A snapshot of the current connectivity state.
ConstExpr
CustomConflictPolicy
User-provided merge policy. Wraps a ConflictResolver callback so it can be passed to anything expecting a ConflictPolicy.
CustomConflictResolver
Wraps a user-provided ConflictResolver callback so it can be set on EntityMeta.conflictResolver.
DbContext
Abstract base class for every d_rocket ORM context.
DbEngine
DbInterceptor
The base class for ORM interceptors.
DbSet<T>
A typed, queryable collection of T entities backed by a single SQL table.
DbSetInclude
.e: a pending navigation include.
DecorrelatedJitterRetryPolicy
The DecorrelatedJitterRetryPolicy from the AWS architecture blog. The next delay is uniformly distributed between baseDelay and min(cap, prevDelay * 3).
DefaultDialect
The default dialect (SQLite-flavoured).
DRest
Singleton accesible como dRest.client, dRest.config, etc.
Embedded
: marks a field as an embedded value object (EF Core's OwnsOne / ComplexProperty pattern). The fields of the embedded type are flattened into the parent table — they don't get their own table and they don't carry an FK.
EmbeddedMeta
Metadata for a single @Embedded value object (EF Core's OwnsOne / ComplexProperty pattern). The fields of the embedded type are flattened into the parent table — they don't get their own table and they don't carry an FK.
EngineRegistry
EntityMeta
Metadata for a single @Table entity.
EntityRegistry
EnumerableQuery<T>
An IQueryable backed by an Iterable. Used as the root of every in-memory query, and also as the result of operators that produce a new queryable (e.g. where_).
EnumerableQueryProvider
The default in-memory provider. Singleton.
ExponentialBackoffRetryPolicy
Expr
ExprVisitor<R>
FibonacciBackoffRetryPolicy
Fibonacci-spaced delays: 1, 1, 2, 3, 5, 8, 13, ... * unitDelay.
Field
El argumento se envía como application/x-www-form-urlencoded.
FileSyncReference
A reference to a binary file/blob stored in cloud storage. The FileSyncProvider (not in 2.0.0 — stub) is responsible for the actual upload/download.
FileSyncStateStore
Dart VM / server file-backed SyncStateStore that persists the state to a JSON file. The file is created lazily on the first write.
ForeignKey
Marks a field as a foreign key referencing another @Table.
Format
Field-level formatter configuration.
GatedConnectivityProvider
A ConnectivityProvider that gates sync based on a predicate. Used to express rules like "sync only on wifi" or "sync on any network, but skip when in airplane mode".
GroupByExpr
A GROUP BY clause with optional post-aggregation filter (HAVING). In SQL this is SELECT key[, element] FROM source GROUP BY key [HAVING pred].
GzipCodec
A codec for gzip compression / decompression.
HavingExpr
A HAVING predicate (post-aggregation filter).
El argumento se envía como header HTTP (name o name: value).
HmacSha256Signer
An HMAC signer. Computes HMAC signatures over HTTP requests using a shared secret.
HttpCache
An in-memory ETag cache for HTTP responses. Thread-safe (uses a lock-free single-threaded model — Dart is single-threaded per isolate).
HttpClient
Interfaz abstracta que todo backend HTTP debe implementar.
HttpDelete
HttpGet
HttpHead
HttpOptions
HttpPackageClient
Implementación por defecto de HttpClient basada en package:http.
HttpPatch
HttpPost
HttpPut
HttpSseClient
An SSE client backed by package:http. The httpClient is DI-friendly (default is a fresh http.Client per instance). For tests, inject a MockClient or a real http.Client.
HttpVerb
Verbo HTTP. Cada subclase se mapea a un HttpMethod específico.
IGrouping<TKey, T>
A group of elements sharing a key.
ILookup<TKey, TElement>
: the public interface for a lookup. The toLookup_ operator returns a _Lookup (the concrete impl in lib/src/sqlite/queryable.dart).
IncludeMany<T, R>
IncludeOne<T, R>
IncludeRelation<T, R>
A relation to be eager-loaded by DbSet<T>.findById(id, joins: [...]).
Index
Marks a field (or set of fields, in a future) for indexing. The MVP does not emit the CREATE INDEX DDL; the annotation is metadata-only and surfaces in the ColumnMeta for downstream tooling.
InMemoryOAuth2TokenStore
A volatile in-memory token store. Good for tests and for short-lived CLI tools.
InMemorySyncProvider
In-memory SyncProvider that buffers changes between "clients". Useful for tests and local development without a network.
InMemorySyncStateStore
Test / dev in-memory SyncStateStore backed by a Map<String, Object?>. No I/O.
InterceptorRegistry
Holds the ordered list of DbInterceptors for a DbContext. Interceptors are invoked in insertion order.
IOWebSocketClient
WebSocket client backed by dart:io's built-in WebSocket. Works on the Dart VM (server-side + tests) and Flutter (iOS / Android / desktop).
IQueryable<T>
A queryable source of T with deferred execution.
IQueryProvider
A backend that can execute LINQ expressions.
JoinExpr
A JOIN clause. The joinType is "INNER", "LEFT", "RIGHT", or "FULL".
JsonKey
Field-level serialisation customisations.
LambdaExpr
LegacySyncQueryProvider
The legacy sync query provider contract.
LinearBackoffRetryPolicy
Fixed delay between attempts.
ListExpr
LoggingInterceptor
The default configuration is conservative (method, URL, status — no headers, no bodies) so it is safe to drop in production without exposing secrets. Headers and bodies are opt-in via the includeHeaders and includeBodies flags.
LwwConflictPolicy
Server-wins policy. The merged row takes every remote value and falls back to the local value for columns the remote did not include.
LwwConflictResolver
The default strategy — Last Write Wins. The remote row is applied verbatim (no merging).
ManualSyncTrigger
Manual trigger that exposes SignalSyncTrigger.fire so the user can integrate it with their own event sources (e.g. a custom network-reconnect listener, an app-lifecycle observer, etc.). Same as SignalSyncTrigger but documented as "manual" to make the intent clearer.
MapLiteralExpr
.e: a map literal {'a': 1, 'b': 2}. Stored as a flat list of MapEntry<Expr, Expr> for stable ordering and duplicate-key support in the parser.
MemberAccess
Dispatches a member access (obj.field) for the in-memory provider.
MemberAccessExpr
MergeStrategies
Pre-built merge strategies for common cases.
MethodCall
Dispatches a method call for the in-memory provider. Minimal coverage in; will be extended in .
MethodCallExpr
Migration
: marks a top-level function as a code-first migration. The codegen emits a MigrationBase subclass (see migration.dart) with the given id and name, and an up that runs entityMeta.createTableDdl for every @Table class in the same library.
MigrationBase
Abstract base for a code-first migration. The user-facing annotation @Migration (in rocket_migration.dart) generates a concrete subclass of this class.
MigrationRunner
Runs a list of MigrationBases in order against a provider-agnostic MigrationExecutor.
MigrationStrategy
: a version-tagged, callback-driven migration declaration. The version is the target schema version (not the number of migrations applied). On a fresh install the runner applies every migration whose version is <= this.version.
MigrationTransaction
A transactional execution context. Returned by a MigrationTransactionFactory when the user opts in to automatic transaction wrapping.
MultiTenantSyncStateStore<S>
A map of TenantId -> value. The MultiTenantSyncStateStore wraps a single-tenant SyncStateStore and dispatches by tenant.
MultiTransportSyncProvider
A SyncProvider that combines multiple transports.
MutationCommand
An INSERT / UPDATE / DELETE command about to be executed. Same pattern as QueryCommand: interceptors can transform SQL and binds.
MutationResult
The result of a mutation. Interceptors receive this in onMutationComplete.
.a: metadata for a single navigation property. Constructed by the codegen and read by the runtime; the runtime never constructs one itself.
.c: a static helper for populating a navigation property on a list of entities. Fetches the related entities in one batched query and writes them into the NavigationRegistry.
.b: a per-instance map for navigation properties on entities. Used by the codegen-emitted extension XxxNavigation on Xxx getters to read the populated values, and by the framework (via set) to populate them after a fetch or .include_.
.d: an Expr that represents a navigation property reference. The SQL translator sees a NavRef and:
NoopConnectivityProvider
The default ConnectivityProvider. Always returns ConnectivityState.wifi. Good for tests and desktop/server apps.
NoRetryPolicy
Retry policy that always gives up. Use this to opt out of the default exponential backoff (e.g. for tests, or for transient-error-free environments).
NullExpr
NullSafeAccessExpr
.e: a null-safe member access a?.b.
OAuth2HttpClient
The real OAuth2 HTTP wrapper.
OAuth2Token
An OAuth2 access token + refresh token + expiry.
OAuth2TokenStore
A persistent token store. The default (InMemoryOAuth2TokenStore) is volatile — the user can plug in a Keychain / shared_preferences / file-based store.
Parameter
Anotaciones a nivel de parámetro. Determinan de dónde sale el valor.
ParamExpr
Part
El argumento se envía como parte de multipart/form-data.
Path
El argumento reemplaza un {name} en la ruta del método.
PeriodicSyncTrigger
Periodic timer trigger. The user provides an interval and a jitter (default 10% of the interval). The trigger fires every interval + jitter (jitter avoids synchronised spikes when many devices wake up at the same time).
PrimaryKey
Marks a field as the primary key of its @Table.
PushedSyncChange
A server-pushed SyncChange received over the WebSocket. Includes the time it was received (for telemetry + clock-skew detection).
Query
El argumento se envía como ?{name}={value}. Si name es null se usa el nombre del parámetro en el código Dart.
Queryable<T>
A SQL-backed IQueryable over a single table.
QueryCommand
A SELECT command about to be executed.
QueryResult
The result of a SELECT. Interceptors receive this in onQueryComplete (with error: null) or with error: <some exception> (the query failed).
RateLimitedHttpClient
: an HttpClient that wraps an inner client and rate-limits the requests using a token bucket. If the bucket is empty, requests block until a token is available.
RawBody
Cuerpo crudo (String o List<int>). Se envía tal cual sin serializar como JSON.
Record
Base class for RecordLike types whose field accessors are registered at startup by codegen.
RecordLike
Implemented by user models to expose their fields to the expression-tree evaluator.
RecordSyncFilter
A filter that includes only changes whose row matches a predicate. The predicate is a (Map<String, Object?> row) -> bool — the row is the column-value map for the change.
RestClient
Marca una clase abstracta como cliente HTTP tipado generado por d_rocket_builder.
RestConfig
Configuración global del runtime d_rocket (capa 2 — REST with steroids). Suele haber una sola instancia por aplicación (dRest).
RestInterceptor
Refit/OkHttp-style interceptor. Lets you transform requests (e.g. add an Authorization header) and responses (e.g. refresh a token on 401).
RestRequest
RestResponse<T>
RestSyncProvider
+: an HTTP + JSON SyncProvider backed by the high-level HttpClient interface.
RetryDecision
The decision returned by a RetryPolicy.shouldRetry call.
RetryingHttpClient
: an HttpClient that wraps an inner client and retries failed requests using a RetryPolicy. On success the response is returned. On failure the policy is consulted: if it returns RetryDecision.retry, the request is re-sent after the given delay. If it returns RetryDecision.giveUp, the last error is re-thrown.
RetryPolicy
Pluggable retry policy. Implementations:
Route
Prefijo de ruta aplicado a nivel de clase (estilo [Route] de ASP.NET Core).
SchemaColumn
: a single column in the snapshot. Mirrors the relevant fields of ColumnMeta but in a JSON-friendly form.
SchemaDiff
: a single diff entry. The fields depend on type:
SchemaForeignKey
: foreign-key target (used inside SchemaColumn).
SchemaIndex
: a single index in the snapshot.
SchemaSnapshot
: a serializable snapshot of the database schema. Produced by computeSnapshot from a list of EntityMeta and consumed by the diff algorithm.
SchemaState
: thin wrapper around the d_rocket_schema_state table. The wrapper is created by AutoMigrator and is not exported from the package barrel — application code interacts with it indirectly via Db.pendingSchemaDiff() and the Db.open(autoMigrate: true) flag.
SchemaTable
: a single table in the snapshot, including its columns and indexes.
ScopedSyncFilter
A composite filter that ANDs or ORs the results of filters.
Serializable
Marks a class as serialisable by d_rocket_builder.
SerializableUnion
Marks a base type as a polymorphic union root.
Serializer
Static JSON serializer with type registration.
SerializerSnapshot
SignalSyncTrigger
One-shot trigger that fires the next time the user manually calls fire. Useful for pull-to-refresh: the UI calls fire and the sync runs.
SqlDialect
The SQL dialect contract that each d_rocket engine implements.
SqlFragment
A SQL fragment together with its bind parameters.
SqliteGroupedQueryable<TKey, T>
A grouped queryable, produced by groupBy_.
SqliteJoinedQueryable<R>
A joined queryable, produced by join_ or groupJoin_.
SqliteSelectManyQueryable<R>
: the iterable wrapper for selectMany_. Mirrors the SqliteJoinedQueryable pattern: outer is fetched via SQL, inner is fetched via SQL (or materialised in memory), and the cartesian product is emitted through the result selector. Composes with where_ / orderBy_ / take_ / skip_ applied to the outer side.
SqliteSetOpQueryable<T>
: the iterable wrapper for set operations. Loads both queryables, then computes the set op in Dart. Returns a Queryable<T> (preserves the LINQ chain contract — user can chain where_ / orderBy_ / toList_ / toListAsync_ on the result).
SqlTranslator
Walks an Expr tree and produces a SqlFragment.
SseClient
: marks an abstract class as an HttpSseClient (the user defines the URL + optionally lastEventId, the builder emits the connect + lastEventId logic).
SseConnection
Abstract contract for an SSE connection.
SseEvent
A single Server-Sent Event.
SyncChange
One row in a SyncEnvelope.
SyncEnvelope
A batch of SyncChanges.
SyncFilter
A filter that decides which SyncChanges are pushed and which remote changes are applied during a sync round-trip.
SyncMetrics
A simple sync metrics recorder.
SyncMetricsSnapshot
A snapshot of sync metrics at a point in time.
SyncPriority
A sync priority. Higher = fires first.
SyncProgress
A single value emitted by DbContext.syncAsync (or the trigger-driven version) during a sync round-trip.
SyncProgressEventBus
A per-context broadcast stream of SyncProgress events. Owned by DbContext (one instance per context). Subscribers always see the latest event first (replay-1), so a late UI can show "currently applying" the moment it starts listening.
SyncProvider
Contract for a sync backend.
SyncQueueStore
Backing store for the persistent sync queue.
SyncSchemaVersion
The current schema version. The caller tracks this (e.g. in a d_rocket_meta table).
SyncStateStore
The persistence contract for sync state (clientId + watermark).
SyncTrigger
Base interface for a sync trigger. The user composes one or more triggers and hands them to DbContext.startSyncTriggers.
Table
Marks a class as an entity managed by the d_rocket ORM.
TableNameSyncFilter
A filter that includes only changes for the given table(s). Use this to scope a round-trip to a single table or a set of tables.
TenantId
A tenant identifier.
TernaryExpr
.e: a ternary cond ? then: else.
TrackedEntry
A single entity tracked by the ChangeTracker.
UnaryExpr
VectorClock
A vector clock — a map of clientId -> monotonic counter.
WebSocketClient
: marks an abstract class as a IOWebSocketClient (the user defines the URL + optionally headers, the builder emits the connection + reconnect glue).
WebSocketConnection
Abstract contract for a WebSocket connection.
WebSocketMessage
One WebSocket frame: either a text string or a binary blob. Use WebSocketMessage.text and WebSocketMessage.binary to construct one.
WebSocketReconnector
Auto-reconnecting wrapper. Wraps any WebSocketConnection factory and retries connection with exponential backoff when the initial start fails.
WebSocketSyncProvider
A WebSocket-based SyncProvider that also receives server-pushed changes.

Enums

ChangeEventType
The kind of a ChangeEvent.
DiffSeverity
: severity classification for a SchemaDiff. safe operations are non-destructive and are auto-applied. unsafe operations are potentially destructive and are reported only.
EntityState
The state of a TrackedEntry in the change tracker.
HmacAlgorithm
The hash algorithm to use. The default is SHA-256 (recommended). SHA-1 is provided for compatibility with legacy systems.
InheritanceStrategy
The inheritance strategy used by a hierarchy of entities. Mirrors EF Core's InheritanceStrategy enum, which has the same three values (Tph, Tpt, Tpc). d_rocket supports all three.
JsonNaming
Naming policy applied to generated JSON keys.
NetworkType
The type of network currently available.
OnDeleteAction
ON DELETE policy for foreign-key columns. Maps directly to SQLite's ON DELETE CASCADE / SET NULL / RESTRICT / NO ACTION clauses (and to EF Core's OnDelete enum, for parity).
SchemaOperationType
: type of a SchemaDiff. Maps 1:1 to a SQL DDL operation (with two exceptions: modifyColumn has no direct SQL in SQLite, and renameColumn is a heuristic that suggests a possible rename).
SyncChangeType
The kind of change encoded in a SyncChange.
SyncPhase
The high-level phase of a sync round-trip.
SyncSchemaResult
The result of a schema check during sync.
SyncTransport
The kind of transport a SyncProvider uses.
UnknownKeyPolicy
Policy for handling unknown keys during deserialisation.
WebSocketMessageType
The type of a WebSocketMessage frame.

Extensions

AggregatesOp on IQueryable<T>
BulkOpsAsync on AsyncQueryProvider
(bulk update): extension on AsyncQueryProvider that runs a single UPDATE <table> SET col1 = ?, col2 = ? [WHERE ...] statement.
ConcatOp on IQueryable<T>
The concat_ LINQ operator.
ConversionMapOps on IQueryable<T>
ConversionsOp on IQueryable<T>
DistinctOp on IQueryable<T>
The distinct_ LINQ operator.
ElementOp on IQueryable<T>
ExprNavRefFactory on Expr
GroupByOp on IQueryable<T>
InMemoryLookupOp on Iterable<T>
(in-memory extension): builds a ILookup<TKey, T> from any IQueryable<T> (this is the in-memory counterpart of Queryable.toLookup_). Materialises the source in memory.
JoinOp on IQueryable<TOuter>
OfTypeOp on IQueryable<T>
The ofType_ LINQ operator.
OrderByOp on IQueryable<T>
The orderBy_ LINQ operator.
QuantifiersOp on IQueryable<T>
QueryableSelectManyOnQueryable on Queryable<T>
(SQL-backed CROSS JOIN): the C#-style from o in outer from i in inner select result(o, i). Composes with where_ / orderBy_ / take_ / skip_ applied to the outer side. The inner is materialised in memory (it's an IQueryable we iterate once).
QueryableSetOpsOnQueryable on Queryable<T>
(set operations): union/intersect/except. The result preserves the outer queryable's chain (so chained where_ / orderBy_ on the left work) and the right side is materialised eagerly.
SelectManyOp on IQueryable<T>
The selectMany_ LINQ operator.
SelectOp on IQueryable<T>
The select_ LINQ operator.
SetOps on IQueryable<T>
SkipOp on IQueryable<T>
The skip_ LINQ operator.
SkipWhileOp on IQueryable<T>
The skipWhile_ LINQ operator.
TakeOp on IQueryable<T>
The take_ LINQ operator.
TakeWhileOp on IQueryable<T>
The takeWhile_ LINQ operator.
ThenByOp on IQueryable<T>
The thenBy_ / thenByDescending_ operators, available only on queryables that have already been ordered.
ToQueryableExtension on Iterable<T>
Sugar: lift an Iterable to IQueryable.
WhereOp on IQueryable<T>
The where_ LINQ operator.

Constants

dRocketMigrationsTable → const String
Internal name of the table that tracks applied migrations.
isAvailable → const bool
true if gzip is available on this platform.
schemaStateTableDdl → const String
: schema for the schemaStateTableName table. A single row keyed by id = 1. The CHECK (id = 1) constraint guards against accidental multi-row inserts.
schemaStateTableName → const String
: name of the on-disk table that stores the last applied schema snapshot. A single row, keyed by id = 1.
serializable → const Serializable

Properties

dRest → DRest
Acceso de azúcar: dRest.client, dRest.config, etc.
final

Functions

buildLookup<T, TKey>(Iterable<T> source, LambdaExpr keySelector) → ILookup<TKey, T>
(in-memory helper): builds a ILookup from a source Iterable<T> and a key extractor. Reused by both the SQL-backed Queryable.toLookup_ and the in-memory IQueryable.toLookup_ extensions.
checkSchema({required SyncSchemaVersion local, required SyncSchemaVersion remote}) → SyncSchemaResult
Checks the local and remote schema versions and returns a SyncSchemaResult.
columnToSnapshot(ColumnMeta c, {String? nameOverride}) → SchemaColumn
: convert a ColumnMeta to a SchemaColumn. The conversion is deterministic (same input → same output).
computeSchemaDiff(SchemaSnapshot old, SchemaSnapshot newSnap) → List<SchemaDiff>
: compute the diff between two snapshots. Returns a deterministic list of SchemaDiffs. The caller decides what to do with unsafe entries (typically: log them, surface them via Db.pendingSchemaDiff(), and DO NOT apply them).
computeSnapshot(List<EntityMeta> metas) → SchemaSnapshot
: produce a SchemaSnapshot from a list of EntityMetas. The order of tables in the output is the order of the input. TPH subclass columns are flattened into the parent table (matching the on-disk shape).
defaultIsUnauthenticated(Object error) → bool
The default 401 detector: checks if the error is a RestHttpException with status 401, or any object that has a statusCode property equal to 401.
embedColumns(EmbeddedMeta em) → String
Emit the comma-separated flattened column list for an EmbeddedMeta's fields, e.g. 'street TEXT NOT NULL, city TEXT NOT NULL'.
fkClause(ColumnMeta c) → String
Emit the REFERENCES … [ON DELETE …] SQL fragment for a ColumnMeta that is a foreign key. Returns the empty string for non-FK columns.
generateUuidV4() → String
Generates a random UUID v4 string in the canonical 8-4-4-4-12 lowercase hex form (for example f47ac10b-58cc-4372-a567-0e02b2c3d479).
gzipDecode(List<int> data) → List<int>
Decompress data with gzip. Returns the original bytes. Equivalent to dart:io.gzip.decode(data).
gzipEncode(List<int> data) → List<int>
Compress data with gzip. Returns the gzipped bytes. Equivalent to dart:io.gzip.encode(data).
httpOAuth2RefreshFn({required String tokenEndpoint, required String clientId, required String clientSecret, HttpClient? client}) → OAuth2RefreshFn
A OAuth2RefreshFn that POSTs to an OAuth2 token endpoint. Uses the wrapped HttpClient to make the refresh call. The tokenEndpoint is the URL (e.g. https://auth.example.com/oauth2/token). The clientId and clientSecret are sent in the body (as application/x-www-form- urlencoded, the OAuth2 standard).
httpVerbToString(HttpVerb verb) → String
Atajo para serializar verbos en strings.
indexNameFor(SchemaTable table, ColumnMeta c) → String
: derive the index name for a ColumnMeta that has isIndexed: true. Same heuristic as EntityMeta.createIndexStatements.
invokeRequest<T>(RestRequest request, Decoder decoder) → Future<T>
Helper que se llama desde el código generado para invocar el cliente con la respuesta adecuada.
redactPragmaKey(String sql) → String
registerNavLookup(Object? f(Object, String)) → void
.d: register the navigation lookup function. Called by NavigationRegistry on first use.
sqliteTypeFor(Type t) → String
: convert the canonical SQLite type for a Dart Type. Same mapping as EntityMeta._sqliteType (private there, so duplicated here — they MUST stay in sync).
validateMapKeysImpl(Map map) → void
withAuthRefresh<T>({required Future<T> operation(), required AuthRefreshHandler handler, IsUnauthenticatedFn? isUnauthenticated}) → Future<T>
Wraps a Future so that a 401 error triggers an auth refresh and a retry.

Typedefs

AsyncMigrationExecutor = Future<void> Function(String sql, [List<Object?>? binds])
Callback signature for executing a single SQL statement asynchronously. Mirrors AsyncQueryProvider.executeAsync.
AsyncMigrationSelector = Future<List<Map<String, Object?>>> Function(String sql, [List<Object?>? binds])
Callback signature for a SELECT statement, asynchronously. Mirrors AsyncQueryProvider.selectAsync.
AsyncMigrationTransactionFactory = Future<AsyncMigrationTransaction> Function()
: factory that returns a fresh AsyncMigrationTransaction per upAsync / downAsync invocation. The user's implementation typically looks like:
CodecEncoder = Object? Function(Object? value)
Encoder side of a value codec. Recursive values are delegated back to the supplied encode function so collections can recurse without re-walking the codec table.
ConflictResolver = Map<String, Object?> Function(Map<String, Object?> localRow, Map<String, Object?> remotePayload)
The contract for a conflict resolution strategy. The framework calls this when applying a remote upsert to a row that already exists locally (concurrent edit).
Decoder<T> = T Function(dynamic data)
HmacSha256 = HmacSha256Signer
Backwards-compatible alias for the original 2.0.0 stub API. The new class is HmacSha256Signer; this typedef is here to keep the older import lines working.
IsUnauthenticatedFn = bool Function(Object error)
A typedef for a function that checks if an error is a 401 (Unauthorized) error.
JsonEncoder<T> = Map<String, dynamic> Function(T value)
Serialises an instance of T into a JSON map.
JsonFactory<T> = T Function(Map<String, dynamic> json)
Deserialises a map into an instance of T.
MigrationExecutor = void Function(String sql, [List<Object?>? binds])
Callback signature for executing a single SQL statement (optionally with positional binds).
MigrationSelector = List<Map<String, Object?>> Function(String sql, [List<Object?>? binds])
Callback signature for a SELECT statement. Returns a list of rows, where each row is a Map<String, Object?> keyed by the column names. Mirrors the DbSet.select contract.
MigrationTransactionFactory = MigrationTransaction Function()
Factory that returns a fresh MigrationTransaction per up / down invocation. The user's implementation typically looks like:
OAuth2InitialFn = Future<OAuth2Token> Function()
A function that fetches the initial token (called when no token is in the store).
OAuth2RefreshFn = Future<OAuth2Token> Function(OAuth2Token current)
A function that refreshes an OAuth2 token. The default implementation uses an HTTP-style POST to the token endpoint. The user can provide their own (e.g. to use a different HTTP client).
RequestCodec = Future<RestResponse> Function(RestRequest request, Decoder decoder)
ResultRowReader<T> = T Function(Map<String, Object?> row)
A function that maps a Row to a user value of type T.
ServerPushHandler = Future<void> Function(PushedSyncChange change)
A handler for server-pushed changes. Called once per change, on the main isolate.

Exceptions / Errors

DatabaseException
GzipUnavailableException
Thrown by GzipCodec.encode / decode when the platform has no gzip support and no polyfill is set.
NetworkException
The connection failed (no response from the server).
RequestCancelledException
Thrown from HttpClient.execute when the CancelToken the user attached to the RestRequest is cancelled before the response finishes streaming.
RestConfigException
Configuration error (missing annotation, empty baseUrl, etc.).
RestException
Exceptions raised by the d_rest runtime (now absorbed into d_rocket as part of the roadmap).
RestHttpException
The server responded with an error status code.
RestSyncException