datum library

Classes

AdapterPair
AdapterPairImpl<T extends DatumEntityInterface>
AddColumn
See ColumnOperation.add.
AutoMigrationExecutor<T extends DatumEntityInterface>
Introspects, diffs, and applies the reconciliation for one entity store.
BelongsTo<T extends DatumEntityInterface>
CancellationToken
Cancellation token for cascade operations.
CascadeAnalytics
Analytics data collected during cascade delete operations.
CascadeAnalyticsBuilder
Builder for collecting cascade analytics during operations.
CascadeDeleteBuilder<T extends DatumEntityInterface>
Fluent API builder for cascade delete operations.
CascadeDeletePreview
Represents a preview of the cascade delete operation.
CascadeDeleteResult<T extends DatumEntityInterface>
Result of a cascade delete operation.
CascadeDeleteStepPreview
Represents a single step in the cascade delete preview.
CascadeError
Detailed error information for cascade operations.
CascadeFailure<T extends DatumEntityInterface>
Failed cascade delete result.
CascadeOptions
Configuration for cascade delete operations.
CascadeProgress
Progress information for cascade delete operations.
CascadeResult<T extends DatumEntityInterface>
Enhanced result types for cascade operations.
CascadeSuccess<T extends DatumEntityInterface>
Successful cascade delete result.
ColdStartConfig
Configuration for cold start synchronization behavior.
ColdStartMetrics
Metrics collected during cold start sync operations
CollectingLogSink
A DatumLogSink that collects entries in memory. Useful for tests.
ColumnOperation
A single declarative transformation applied to one raw entity map during a schema migration.
CompositeFilter
Represents a composite filter with AND/OR logic.
ConflictDetectedEvent<T extends DatumEntityInterface>
Event emitted when the engine detects a conflict between local and remote data.
ConflictResolvedEvent<T extends DatumEntityInterface>
Event emitted after a conflict has been successfully resolved.
ConsoleLogSink
The default DatumLogSink, printing to stdout via print.
CountBasedSampler
Count-based sampler that logs every Nth occurrence.
CRDT<T>
Base interface for Conflict-free Replicated Data Types (CRDTs).
CRDTResolver<T extends DatumEntityInterface>
A resolver that use the entity's built-in merge logic.
CustomBackoff
Implements a custom backoff strategy defined by a function. Useful for testing or complex retry logic.
CustomManagerConfig<T extends DatumEntityInterface>
A testing-only config to smuggle a mock manager into the creation process.
DataChangeEvent<T extends DatumEntityInterface>
Event emitted whenever local or remote data changes.
Datum
DatumBackoffStrategy
Abstract base class for retry backoff strategies.
DatumChangeDetail<T extends DatumEntityInterface>
Represents a change that occurred in a data source. This is used by adapters to notify the engine about external changes.
DatumConfig<T extends DatumEntityInterface>
Configuration for the Datum engine and its managers.
DatumConfigPresets
Configuration presets for common use cases.
DatumConflictContext
Context information describing a synchronization conflict.
DatumConflictDetector<T extends DatumEntityInterface>
Detects conflicts between local and remote versions of an entity.
DatumConflictResolution<T extends DatumEntityInterface>
Result of a conflict resolution attempt.
DatumConflictResolver<T extends DatumEntityInterface>
Base interface for components that resolve synchronization conflicts.
DatumConnectivityChecker
An abstract interface for checking network connectivity.
DatumCoreFields<E extends DatumEntityInterface>
The six standard sync fields every DatumEntityInterface carries, as individually-typed specs plus an all list to spread into a schema:
DatumCustomFieldQuery<T>
Helper class for building complex queries with custom field definitions.
DatumEither<L, R>
A sealed class representing a value that can be one of two types.
DatumEntity
The base abstract class for all entities managed by Datum without built-in relationship handling.
DatumEntityBase
The base sealed class for all entities managed by the Datum framework.
DatumEntityInterface
Interface for all Datum entities, allowing both inheritance and mixin approaches.
DatumEntitySyncDetails
Describes the synchronization state for a single entity type.
DatumErrorRecoveryStrategy
Defines a strategy for how the sync engine should behave on errors.
DatumFieldCodec<V>
Converts between a Dart value of type V and its persisted form.
DatumFieldSpec<E, V>
A full runtime descriptor for one serialized field of entity E with Dart value type V.
DatumHashGenerator
Utility for generating consistent hashes for data integrity checks.
DatumHealth
Represents the operational health of a sync manager.
DatumIndexConfig<T extends DatumEntityInterface>
Configuration for database indexes on syncable entities.
DatumLogger
Enhanced logger for the Datum package with structured logging and performance optimizations.
DatumLogSink
A pluggable destination for formatted log output.
DatumManager<T extends DatumEntityInterface>
DatumMetrics
An immutable snapshot of key synchronization statistics.
DatumMiddleware<T extends DatumEntityInterface>
Middleware for intercepting and transforming data during CRUD operations.
DatumObserver<T extends DatumEntityInterface>
An observer class to monitor operations within DatumManager.
DatumPersistence
Abstract interface for persistent storage of Datum sync metadata and configuration.
DatumQuery
Defines a query for filtering and sorting items from a data source.
DatumQueryBuilder<T>
A fluent builder for creating DatumQuery objects with type-safe field access.
DatumQueryField<E, V>
A type-safe field descriptor for an entity of type E whose value type is V.
DatumQueryMatcher
In-memory evaluation of a DatumQuery against entities and raw maps.
DatumRawQuery
An adapter-aware raw query for projections, aggregations, and joins that bypass full entity hydration (#11).
DatumRegistration<T extends DatumEntityInterface>
A helper class to encapsulate the registration details for a single entity type.
DatumRelationSchema
A global registry mapping an entity Type to its relation schema.
DatumRelationSpec<E extends RelationalDatumEntity, R extends DatumEntityInterface>
A typed, declare-once relation between entities E and R.
DatumRollingHash
An incrementally maintainable set hash for change/drift detection.
DatumSchema<E extends DatumEntityInterface>
A declarative, runtime description of entity E's serialized shape.
DatumSchemaReader<E extends DatumEntityInterface>
Reads field values out of one raw map with precise, field-named errors — the as-cast-free way to implement fromMap:
DatumSyncBatchOperation<T extends DatumEntityInterface>
Represents a batch of pending operations to be synchronized together.
DatumSyncCompletedEvent<T extends DatumEntityInterface>
Event fired when a synchronization cycle completes.
DatumSyncConflictSummary<T extends DatumEntityInterface>
Description of a conflict encountered during a sync.
DatumSyncEngine<T extends DatumEntityInterface>
The core engine that orchestrates the synchronization process.
DatumSyncErrorEvent<T extends DatumEntityInterface>
Event fired when an error occurs during synchronization.
DatumSyncEvent<T extends DatumEntityInterface>
Base class for all synchronization-related events.
DatumSyncExecutionStrategy
Defines the execution strategy for processing the sync queue.
DatumSyncMetadata
Metadata describing the synchronization state for a specific user.
DatumSyncOperation<T extends DatumEntityInterface>
Represents a single pending operation to be synchronized.
DatumSyncOptions<T extends DatumEntityInterface>
Configuration passed when triggering a manual synchronization via Datum.sync().
DatumSyncProgressEvent<T extends DatumEntityInterface>
Event fired to report synchronization progress.
DatumSyncRequestStrategy
Defines the strategy for handling concurrent calls to the synchronize method.
DatumSyncResult<T extends DatumEntityInterface>
Represents the outcome of a synchronization cycle.
DatumSyncScope
Defines a scope for a synchronization operation, allowing for partial syncs.
DatumSyncStartedEvent<T extends DatumEntityInterface>
Event fired when a synchronization cycle starts.
DatumSyncStatistics
Aggregated statistics about multiple sync cycles.
DatumSyncStatusSnapshot
An immutable snapshot describing the current sync state for a user.
DatumUserSwitchResult
Result of a user switching operation.
ExcludableEntity
An example entity with fields that can be excluded from local/remote storage.
ExponentialBackoff
Implements an exponential backoff retry strategy.
Failure<L, R>
Represents the failure case of an Either.
Filter
Represents a single filter condition in a DatumQuery.
FilterCondition
Represents a filter condition (can be simple or composite).
FixedBackoff
Implements a fixed backoff retry strategy where the delay is always the same.
GlobalDatumObserver
A specialized observer that can handle any entity type. This is used for global observers registered on the main Datum instance.
HasMany<T extends DatumEntityInterface>
HasOne<T extends DatumEntityInterface>
InitialSyncEvent<T extends DatumEntityInterface>
Event emitted when event listeners are attached for a user and the full dataset snapshot needs to be delivered.
InMemoryDatumPersistence
In-memory implementation of DatumPersistence for testing and development.
InMemoryLocalAdapter<T extends DatumEntityInterface>
A complete, dependency-free in-memory LocalAdapter implementation.
IsolateHelper
IsolateStrategy
A strategy that runs the sync process in a background isolate.
LastWriteWinsResolver<T extends DatumEntityInterface>
A simple conflict resolver that chooses the entity with the later modifiedAt timestamp.
LinearBackoff
Implements a linear backoff retry strategy where the delay increases by a fixed amount.
LocalAdapter<T extends DatumEntityInterface>
Local storage adapter abstraction that provides access to offline data.
LocalPriorityResolver<T extends DatumEntityInterface>
Resolves conflicts by always preferring the local version of the entity. If the local version does not exist, it will use the remote version.
LogEntry
Structured log entry with metadata for better debugging and monitoring.
LogSampler
Sampling strategy for high-frequency log operations.
ManyToMany<T extends DatumEntityInterface>
MergeResolver<T extends DatumEntityInterface>
A resolver that uses a provided function to merge conflicting entities.
Migration
Represents a single migration step from one schema version to another.
MigrationExecutor<T extends DatumEntityInterface>
Orchestrates the execution of schema migrations.
MigrationPlan
Resolves and validates the chain of Migrations needed to move a store from one schema version to another, before any data is touched.
ORSet<T>
An Observed-Remove Set CRDT.
PaginatedResult<T extends DatumEntityInterface>
Result of a paginated query.
PaginationConfig
Configuration for paginated queries.
ParallelStrategy
Processes pending operations in parallel batches.
PNCounter
A Positive-Negative Counter CRDT.
QueueManager<T extends DatumEntityInterface>
Manages the queue of pending synchronization operations for a specific entity type T.
RateLimitingSampler
Time-based sampler that limits logs to a maximum rate.
RawDataSchemaIntrospector<T extends DatumEntityInterface>
Introspects a schemaless store (Hive, in-memory, …) from its raw rows — one getAllRawData() pass computing the key union, intersection, and row count.
Relation<T extends DatumEntityInterface>
RelationalDatumEntity
An extension of DatumEntity that includes support for defining relationships.
RelationDescriptor
A type-level, instance-free description of a single relationship.
RelationSchemaProvider
Contract for objects that can describe their relation schema without needing their relation values to be loaded. Implemented by RelationalDatumEntity.
RemoteAdapter<T extends DatumEntityInterface>
Remote storage adapter abstraction for cloud data sources.
RemotePriorityResolver<T extends DatumEntityInterface>
Resolves conflicts by always preferring the remote version of the entity. If the remote version does not exist, it will use the local version.
RemoveColumn
See ColumnOperation.remove.
RenameColumn
See ColumnOperation.rename.
RgaList<T>
A Replicated Growable Array (RGA) — a convergent ordered-sequence CRDT.
RgaNode<T>
A single element of an RgaList, identified by its (replicaId, counter) pair and anchored after its origin element.
RgaText
A convergent collaborative text CRDT for editors, built on RgaList.
RowTransform
See ColumnOperation.row.
SchemaChange
One reconciliation step the differ decided on.
SchemaColumnAdded
A declared field is missing from the store and will be added (backfilled with its default / null).
SchemaColumnRemoved
A stored column not present in the declaration will be dropped (only when autoMigrateDropColumns is on).
SchemaColumnRenamed
A stored column will be renamed to a declared field (via renamedFrom:).
SchemaIntrospector
Produces a SchemaShape for one entity store.
SchemaMigration
A Migration described as a list of ColumnOperations instead of hand-written map surgery.
SchemaRenameOperation
A rename that never clobbers: on the map path the value moves only when the target key is absent (a partially-migrated row keeps its newer value); on the SQL path it emits ALTER TABLE … RENAME COLUMN through the SqlConvertibleOperation hook.
SequentialRequestStrategy
A strategy that queues new sync requests if one is already in progress.
SequentialStrategy
Processes pending operations one by one. This is safer and less resource-intensive.
SkipConcurrentStrategy
A strategy that skips new sync requests if one is already in progress. This prevents re-entrant sync calls.
SortDescriptor
Defines sorting for a field in a DatumQuery.
SqlConvertibleOperation
Implemented by custom ColumnOperations that know their own SQL form.
SqlMigrationExecutor<T extends DatumEntityInterface>
Runs SchemaMigrations natively on a SQL store through the adapter's RawQueryCapable.rawQuery — the SQL twin of the map-based MigrationExecutor.
SqlMigrationGenerator
Translates a SchemaMigration into SQL statements for a given dialect.
SqlSchemaIntrospector
Introspects a SQL table's real columns through the adapter's own RawQueryCapable.rawQueryPRAGMA table_info on SQLite, information_schema.columns on PostgreSQL. No adapter API changes needed.
Success<L, R>
Represents the success case of an Either.
TransformColumn
See ColumnOperation.transform.
TypeAdaptedConflictResolver<E extends DatumEntityInterface, S extends DatumEntityInterface>
Adapts a conflict resolver declared for a broader entity type S so it can be used where a resolver for a more specific type E is required (E must be a subtype of S).
TypeSafeManagerRegistry
A type-safe registry for storing and retrieving managers.
UserPromptResolver<T extends DatumEntityInterface>
A resolver that delegates the conflict decision to the user via a prompt.
UserSwitchedEvent<T extends DatumEntityInterface>
Event emitted when the active user is changed in the manager.
VectorClock
Represents a Vector Clock for tracking causality in a distributed system.

Enums

AdapterHealthStatus
Describes the health of an individual adapter.
CascadeDeleteBehavior
Defines the cascading behavior for delete operations on relationships.
ChangeType
Type of data change.
ColdStartStrategy
Strategy for handling synchronization when the app is fully closed and reopened.
DataFetchStrategy
Strategy for choosing between the local and remote data sources when fetching data via DatumManager.fetch / DatumManager.fetchById.
DataSource
Source of data change.
DatumConflictType
Types of conflicts detected between local and remote representations.
DatumCoreRole
Which of the six standard sync fields a spec represents, when built by datumCoreFieldSpecs. Payload fields have no role.
DatumExceptionCode
DatumOperationType
Defines the type of a synchronization or data manipulation operation.
DatumRelationKind
The shape of a typed relation.
DatumResolutionStrategy
Strategies used when resolving conflicts.
DatumSyncHealth
Describes the overall health of a synchronization process.
DatumSyncStatus
High-level states for the synchronization process.
DatumSyncTrigger
Defines the scope of a synchronization operation triggered after a local change.
DeleteBehavior
Defines how delete operations are handled by the DatumManager.
FilterOperator
Defines the available comparison operators for filters.
LogicalOperator
Defines logical operators for combining filters.
LogLevel
Log levels for structured logging with performance awareness.
MapTarget
The target for serialization, allowing different fields to be included or excluded based on whether the data is going to a local or remote data source.
NullSortOrder
Defines how null values are sorted.
RelationKind
The kind of a relationship, independent of any entity instance.
SqlDialect
Defines the SQL dialect to be used for generating queries.
SyncDirection
Defines the direction of a synchronization operation. Defines the order of operations during a synchronization cycle.
SyncStatus
Sync status enumeration.
UserSwitchStrategy
Defines the strategy to use when switching between users.

Mixins

CursorSyncCapable<T extends DatumEntityInterface>
The remote adapter serves incremental pulls from an opaque change cursor — the natural fit for changes-feed backends (Firestore snapshot tokens, DynamoDB streams, CouchDB since sequences, or a plain monotonically increasing change counter).
DatumEntityMixin
A mixin that provides the base functionality for Datum entities.
DeltaSyncCapable<T extends DatumEntityInterface>
The remote adapter can serve incremental pulls: instead of returning the full dataset every cycle, it returns only entities modified at or after a watermark (typically WHERE modified_at >= ? on the backend).
Disposable
A mixin to provide disposable behavior to a class.
MemoizedRelations
Memoizes an entity's relations so eager loading (withRelated) works reliably for hand-written entities.
PaginatedAdapter
The adapter natively supports pagination (readAllPaginated / watchAllPaginated) rather than throwing or loading everything.
RawQueryCapable
The adapter supports raw queries for projections/aggregations without full entity hydration (#11).
RelationalAdapter
The adapter can resolve relationships at the storage layer (fetchRelated / watchRelated).
RelationalDatumEntityMixin
A mixin that provides relational functionality for Datum entities.
SchemaFingerprintCapable
The local adapter persists an opaque schema fingerprint — the auto-migration fast path.
SqlSchemaCapable
A SQL-backed local adapter that exposes its table and dialect, letting the engine run schema DDL against it (the auto-migration SQL path) without knowing adapter internals. Pair with RawQueryCapable.
TransactionalAdapter
The adapter implements real ACID-style transaction semantics (atomic commit/rollback), not just a pass-through.
WatchableAdapter
The adapter supports reactive queries (watchAll/watchById/watchQuery return live, non-null streams).

Extensions

DatumManagerAutoSyncInfo on DatumManager<T>
DatumQuerySqlConverter on DatumQuery
An extension on DatumQuery to provide SQL conversion capabilities.
DatumRelationSpecNames on Iterable<DatumRelationSpec<RelationalDatumEntity, DatumEntityInterface>>
withRelated: from typed specs: withRelated: [Project.ticketsRel].names.

Constants

kReservedColumnNames → const Set<String>
Column names auto-migration never adds, renames, or drops: the sync core fields plus anything __-prefixed (engine-internal, e.g. __typename).

Functions

datumCoreFieldSpecs<E extends DatumEntityInterface>({String id = 'id', String userId = 'userId', String modifiedAt = 'modifiedAt', String createdAt = 'createdAt', String version = 'version', String isDeleted = 'isDeleted', DatumFieldCodec<DateTime> dateCodec = DatumFieldCodec.dateTimeIso}) DatumCoreFields<E>
Builds the six standard sync-field specs with camelCase keys by default (matching SqliteLocalAdapter's core columns). Every key is overridable for snake_case stores, and dateCodec controls how the two timestamps are persisted (ISO-8601 by default, with lenient decode that also accepts epoch milliseconds).
datumEntityDigest(Map<String, dynamic> map) Uint8List
Computes the canonical 32-byte SHA-256 digest of a single serialized entity map. Map keys are sorted recursively so the digest is independent of key insertion order (local vs remote serialization).
datumRelationsFor<E extends RelationalDatumEntity>(E entity, List<DatumRelationSpec<E, DatumEntityInterface>> specs) Map<String, Relation<DatumEntityInterface>>
Builds an entity's relations map from typed specs:
diffSchema<E extends DatumEntityInterface>({required DatumSchema<E> schema, required SchemaShape actual, required bool dropRemovedColumns, required bool sqlPath, SqlDialect dialect = SqlDialect.sqlite}) SchemaDiffResult
Diffs schema against the observed actual shape.
formatDuration(Duration d) String
Formats a Duration into a more human-readable string.
isSubtype<S, T>() bool
The central engine for the Datum framework, managing data synchronization, entity registration, and communication between local and remote sources.
sameTypes<S, V>() bool

Typedefs

AutoMigrationOutcome = ({List<SchemaChange> applied, Object? error, StackTrace? stackTrace, bool success, List<String> warnings})
What one auto-migration pass did (or failed to do).
CursorPage<T> = ({List<T> items, String nextCursor})
The result of one CursorSyncCapable.readChanges page: the changed entities plus the opaque cursor to pass on the next call.
DatumCustomSqlBuilder = String? Function(Filter filter, String getPlaceholder(), List<Object?> params)
A builder function for custom SQL operator logic.
DatumEntityType = DatumEntityInterface
Marker used by the schema registry; kept here to avoid import cycles.
DatumFieldGetter<E, V> = V Function(E entity)
Reads the value of this field from an entity (for DatumSchema.toMap).
DatumMergeFunction<T extends DatumEntityInterface> = FutureOr<T?> Function(T local, T remote, DatumConflictContext context)
A function that defines how to merge a local and remote entity.
DatumPlaceholderBuilder = String Function(int index)
A builder function for custom SQL placeholder logic.
DatumRawRow = Map<String, dynamic>
A single raw result row.
DatumSqlQueryResult = ({List<Object?> params, String sql})
A record holding the generated SQL string and its corresponding parameters.
MigrationErrorHandler = Future<void> Function(Object error, StackTrace stackTrace)
A handler for migration errors.
MigrationResult = ({Object? migrationError, StackTrace? migrationStack, bool success})
A record representing the outcome of a migration execution.
SchemaDiffResult = ({List<SchemaChange> changes, List<ColumnOperation> operations, List<String> warnings})
The differ's output: the decided changes, the operations that execute them (fed into the existing map / SQL migration machinery), and human-readable warnings for everything noticed but deliberately not touched.
SchemaShape = ({Set<String> allKeys, int rowCount, Set<String> universalKeys})
The observed shape of a store.
SchemaViolation = ({String field, String message})
One problem found by DatumSchema.validate for a raw map.
SyncDirectionResolver = SyncDirection? Function(int pendingCount, SyncDirection defaultDirection)
A callback that allows customizing the sync direction based on pending operations.

Exceptions / Errors

AdapterException
Exception thrown when an error occurs within an adapter implementation.
AuthenticationException
Exception thrown when authentication fails.
AuthorizationException
Exception thrown when authorization fails.
BadRequestException
Exception thrown when the client makes a bad request.
CancellationException
Exception thrown when an operation is cancelled.
ConflictError
A synchronization conflict could not be resolved automatically.
ConflictException
Exception thrown when a conflict is detected during synchronization.
DatumError
A sealed, pattern-matchable error type for Datum's result-returning (tryX) API surface.
DatumException
Base exception class for all errors originating from the Datum library.
EntityNotFoundException
Exception thrown when an entity with the specified ID is not found.
MigrationException
NetworkError
A network/transport failure (no connection, timeout, server error).
NetworkException
Exception thrown when a network-related error occurs.
NotFoundError
The requested entity does not exist locally or remotely.
PreconditionFailedException
Exception thrown when a precondition for an operation is not met.
SchemaReadException
SerializationException
Exception thrown when an error occurs during data serialization or deserialization.
ServerException
Exception thrown when the server responds with an error.
StorageError
A local/remote storage, serialization, schema, or migration failure.
SyncExceptionWithEvents<T extends DatumEntityInterface>
A special exception to carry events back up the call stack on failure.
TimeoutException
Exception thrown when an operation times out.
UnavailableException
Exception thrown when the requested resource is unavailable.
UnknownError
An error that does not map to a more specific case.
UnknownException
Exception thrown when original exception unknown
UserSwitchException
ValidationError
Input or precondition validation failed (bad request, invalid data).
ValidationException
Exception thrown when a validation error occurs.