d_rocket_engine_web library

🚀 d_rocket_engine_web — web engine for d_rocket 2.0.

The runtime that powers the WebDb / DbContext / DbSet / LINQ Queryable / versioned-migrations stack of d_rocket, for the browser — backed by IndexedDB (the browser's native database).

What this package is

d_rocket is engine-agnostic. Each database backend (SQLite, Postgres, IndexedDB, ...) ships as its own d_rocket_engine_* package. This package is the web (browser) implementation. Unlike the SQLite / Postgres engines (which use FFI to a native binding), this engine uses IndexedDB — the database the browser already provides.

Why IndexedDB and not SQLite-in-WASM

Other web engines in the d_rocket ecosystem could ship SQLite compiled to WASM, but that approach:

  • Requires a Rust toolchain (1.94+) to compile the binding at dart pub get time.
  • Adds 10-20 MB to the page bundle.
  • Adds a 1-2 s cold-start (WASM compilation).
  • Provides no offline-first benefit over what IndexedDB already gives us.

IndexedDB is built into every modern browser, indexed, transactional, persistent across sessions, and quota-aware. We use package:idb_shim — the canonical pure-Dart wrapper.

Usage

# pubspec.yaml
dependencies:
  d_rocket: ^2.0.0
  d_rocket_engine_web: ^2.0.0
import 'package:d_rocket_engine_web/d_rocket_engine_web.dart';

void main() async {
  // Required: register the web engine once
  // at app startup.
  dRocketWeb(
    config: WebEngineConfig(
      databaseName: 'my_app',
      version: 1,
    ),
  );
  initializeD();
  final db = await WebDb.open();
}

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).
DeferredWebQueryProvider
A test-only WebQueryProvider that defers writes during an open transaction and applies them on commit. See file-level docs.
DiagnosticEvent
Immutable, serializable record of one runtime diagnostic event.
DiagnosticHttpClient
HTTP wrapper that publishes one structured event per request.
DiagnosticSseConnection
SSE connection decorator that publishes DevTools events.
DiagnosticWebSocketConnection
WebSocket connection decorator that publishes DevTools events.
DRest
Singleton accesible como dRest.client, dRest.config, etc.
DrocketDevToolsBridge
Registers the VM Service endpoints consumed by a DevTools extension.
DrocketDiagnostics
Development diagnostics hub shared by all d_rocket layers.
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.
EtagCacheHttpClient
Caches successful GET responses per URL and revalidates stale entries with If-None-Match when the server provides an ETag.
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.
GzipHttpClient
Compresses request bodies with gzip before forwarding them to inner.
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.
HmacSignedHttpClient
Adds an HMAC signature and timestamp header to every outgoing request.
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.
MigrationTracker
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.
OrderByClause
Parameter
Anotaciones a nivel de parámetro. Determinan de dónde sale el valor.
ParamExpr
ParsedQuery
A parsed SQL fragment. Handles the subset d_rocket's LINQ emits.
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.
Projection
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.
RestClientConfig
Optional per-instance configuration for a generated @RestClient.
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.
SseReconnector
Auto-reconnecting SSE stream with Last-Event-ID resume support.
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.
WebDb
(Web-First): the user-facing database facade. Extends DbContext and wires a WebQueryProvider (IndexedDB) as the underlying storage.
WebDialect
A tiny parser for the web dialect.
WebDialectStatement
A parsed WebDialect statement.
WebEngine
The web engine. Owns the IndexedDB database handle and produces AsyncQueryProviders.
WebEngineConfig
The configuration for the web engine.
WebIndexSchema
A description of a single index on an object store. Equivalent to CREATE INDEX in SQL.
WebMigration
A migration step. Subclass and override version (the target version this migration migrates TO) and up (the migration logic).
WebMigrationExecutor
The operations available inside WebMigration.up. Wraps the raw idb.Database and idb.Transaction handles that IndexedDB exposes during onupgradeneeded.
WebObjectStoreSchema
A description of a single IndexedDB object store. Equivalent to a "CREATE TABLE" in SQL.
WebQueryPlan
A heuristic query plan. If non-null, the adapter will push down parts of the query to IndexedDB indexes.
WebQueryPlanner
WebQueryProvider
The IndexedDB-backed AsyncQueryProvider implementation.
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.
WebSqlAdapter
WebSqlPredicate
WebSqlWhere
A simple WHERE clause parser. Handles:

Enums

ChangeEventType
The kind of a ChangeEvent.
DiagnosticCategory
Runtime areas that can publish d_rocket diagnostic events.
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.
WebDialectKind
The kind of statement in a WebDialectStatement. IndexedDB's API surface is small — the dialect covers it.
WebSocketMessageType
The type of a WebSocketMessage frame.
WebSqlOp

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>
MigrationExecutorExtensions on MigrationExecutor
Convenience SQL operations for hand-written migrations.
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.
dRocketWeb({WebEngineConfig? config}) → void
Top-level registration helper. Call once at app startup before any WebDb.open call. Idempotent — calling it twice replaces the previously registered engine with a fresh WebEngine (the EngineRegistry only holds one slot).
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, {HttpClient? client}) → Future<T>
Helper que se llama desde el código generado para invocar el cliente con la respuesta adecuada.
quoteIdentifier(String value) → String
Quotes a SQLite identifier and rejects embedded quote characters.
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.
HttpClientWrapper = HttpClient Function(HttpClient inner)
Builds the HTTP client used by one generated REST client.
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
WebDatabaseException
A database exception. Wraps any error raised by the IndexedDB binding (or the dialect parser).