Skip to content

Commit 907b617

Browse files
committed
Finished blobs
1 parent 78218fa commit 907b617

52 files changed

Lines changed: 3621 additions & 63 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎plans/document-blobs.md‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Document Blobs (v11.2)
2+
3+
Binary payloads attached to documents, in a **sidecar table**, **loaded on demand**, **metadata inline**.
4+
5+
## Status
6+
7+
**SHIPPED + tested on the relational family** (committed: `1c35907 Converter fixes`, `fb6f5b9 Blob sidecar`;
8+
backup/temporal/sweep in working tree):
9+
10+
- **Object model** — `DocumentBlob` (self-loading `LoadAsync`/`GetBytesAsync`), `DocumentBlobCollection`
11+
(`LoadAllAsync`, fluent `Add(bytes,…)`), two metadata-only converters. `Bytes` throws until loaded.
12+
- **Mapping** — `MapBlob`/`MapBlobCollection` (+ AOT accessor overloads); `BlobOptions` (Key/ComputeHash/MaxSize).
13+
- **Provider contract** — `MaxBlobSize` (0 = unsupported) + SQL builders on `IDatabaseProvider`; DDL for
14+
SQLite, PostgreSQL, SQL Server, MySQL, Oracle, DuckDB (MariaDB/CockroachDB inherit).
15+
- **Store** — `IBlobDocumentStore` (`BatchLoadBlobs` + `GetBlob`), `DocumentStore.Blob.cs`: prepare/hash/
16+
size-guard, sidecar write + prune, cascade, self-loading via `AttachBlobLoaders` + shared `Materialize<T>`
17+
seam routed through `DocumentQuery.Deserialize` and the non-tx read paths.
18+
- **Init** — blob DDL in both init paths; blob-mapped types off the `IsBatchFastEligible` fast path.
19+
- **Backup** — `BackupExportOptions.IncludeBlobs` (default true); payloads base64 inline per document
20+
(`RawBlob` on `RawDocument`/`RawBulkRow`, `blobs[]` in the record DTO), restored into the sidecar in the
21+
chunk transaction. Export buffers a blob-mapped table's doc rows (payloads read one at a time) to avoid a
22+
nested reader on shared-connection providers.
23+
- **Temporal** — blobs not versioned; `RestampBlobsFromCurrent` keeps live blobs on `Restore` so metadata
24+
never describes a superseded payload.
25+
- **Maintenance** — `IDocumentMaintenance.SweepOrphanedBlobs<T>()` (default-impl returns 0).
26+
- **AOT** — `Generated` fixture carries `DocumentBlob` + `DocumentBlobCollection`; compiling proves the
27+
converter branch beats the non-`List<T>` collection guard (depends on the shipped generator fix).
28+
- **Docs** — `blobs.mdx` + sidebar, release note, `SKILL.md`, `readme.md`, `limitations.mdx` fix. Site builds.
29+
30+
Tests: 20 blob tests + Generated AOT; full suite green (last confirmed 4551/0, re-run in progress).
31+
32+
**Known limitation:** a document materialized inside an explicit transaction stamps a loader that reads via
33+
the parent store (committed state) — self-loading an uncommitted blob mid-transaction won't see it.
34+
35+
## Outstanding — the 8 non-relational providers
36+
37+
Each is a standalone `*DocumentStore` with a standalone options class (they mirror, not inherit), so each
38+
needs: `MapBlob`/`MapBlobCollection` mirrored onto its options + `blobMappings`/`ResolveBlobMappings`; a
39+
`{collection}_blobs` sidecar; strip-to-sidecar on write + write-sidecar; self-loading stamp at its
40+
materialization; cascade delete; **blobs-first write ordering** (crash → orphan bytes, never dangling
41+
metadata); `SweepOrphanedBlobs`. Providers: Mongo, Cosmos, LiteDB, IndexedDB, Redis, Firestore, Azure Table,
42+
DynamoDB — RavenDB via **native attachments**. 7 of 8 need Testcontainers. These are 8 separate substantial
43+
implementations, not a shared change. A reusable core helper (`BlobSupport.PrepareBlobs(mappings, max, doc)`)
44+
would cut the per-provider cost.
45+
46+
## Design decisions (locked)
47+
48+
Reads-only store API (mutations via the document); byte[] only; cascade delete; backup includes by default;
49+
temporal not versioned; Hash opt-in; single-blob Key defaults to property name, collection items carry keys.

‎readme.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ A lightweight, multi-provider document store for .NET that turns relational data
5656
- **Per-query change monitoring** — call `.NotifyOnChange()` on any query to receive only the changes whose document matches the query's `Where` predicates: `await foreach (var c in store.Query<Order>().Where(o => o.Status == "Pending").NotifyOnChange(ct)) { ... }`. Property-level / removal / clear events that don't carry the document body are passed through so the consumer can re-check membership.
5757
- **Global query filters** — `options.AddQueryFilter<User>(u => !u.IsDeleted)` registers a predicate that's automatically AND-applied to every query of `User` — including `Query<T>()`, single-doc paths (`Get`/`Update`/`Remove`/`SetProperty`/`RemoveProperty`/`Clear`), bulk operations (`ExecuteUpdate`/`ExecuteDelete`), and per-query change monitoring. Named filters can be disabled individually via `query.IgnoreQueryFilters("name")`; all filters can be disabled with `query.IgnoreQueryFilters()`. Use for soft-delete, row-level security, or "active only" scopes. Insert is intentionally unfiltered (matches Entity Framework Core).
5858
- **Temporal history (system-time versioning)** — `options.MapTemporal<Order>(o => { o.Retention = TimeSpan.FromDays(90); o.MaxVersions = 50; o.CaptureActor = () => userId; })` opts a type into append-only versioning. **Scope-aware actor:** `o.ResolveActor = sp => sp.GetService<ICurrentUser>()?.Id` captures "who" from the write's request-scoped DI (per unit of work), taking precedence over `CaptureActor`. Every Insert/Update/Upsert/Remove/SetProperty/RemoveProperty/BatchInsert (including inside a session) records a snapshot to a per-type history sidecar. Read it back with `History<T>(id)`, `AsOf<T>(id, when)`, `Restore<T>(id, version)`, `GetDiffBetween<T>(id, from, to)`, plus fleet-wide `AsOfAll<T>(when)`, `ChangesByActor<T>(actor)`, and `ChangesBetween<T>(from, to)`. Opt-in per type (non-temporal types pay nothing); supported on **every** provider — all relational (SQLite, SQLCipher, PostgreSQL, SQL Server, MySQL, Oracle, DuckDB) and the document stores (LiteDB, MongoDB, CosmosDB, IndexedDB). The history methods live on the `ITemporalDocumentStore` capability interface (not `IDocumentStore`) — resolve or cast to it. Retention pruned on every write.
59+
- **Blobs (binary payloads in a sidecar)** — attach binary data (PDFs, images, signatures) to a document without bloating it. Map a `DocumentBlob` (single) or `DocumentBlobCollection` (many) with `MapBlob<T>` / `MapBlobCollection<T>`, and the bytes go to a `{table}_blobs` sidecar table while only the metadata (length, content type, file name) rides along in the document JSON — so ordinary queries never drag the payload along, and you can `Where`/`OrderBy` on that metadata like any other property (`Where(x => x.Pdf.Length > 1_000_000)`). Payloads self-load: `await doc.Pdf.LoadAsync()` for one blob, `await doc.Attachments.LoadAllAsync()` for a whole collection in one round trip (or `store.BatchLoadBlobs(page)` across a page, `store.GetBlob<T>(id, key)` with no document in hand); `Bytes` throws until loaded, so there's no hidden I/O behind a property getter. Writes go through the document (assign the member and save — no `SetBlob`), so the inline metadata can never disagree with the stored bytes; deleting a document cascades to its blob rows. Opt-in SHA-256 hashing and a per-mapping size ceiling; `store.MaxBlobSize` reports the provider limit. Use it instead of a raw `byte[]` property (which is base64'd into the document body and read on every query). **Relational providers only** (SQLite, PostgreSQL/CockroachDB, SQL Server, MySQL/MariaDB, Oracle, DuckDB); NoSQL providers report `MaxBlobSize == 0` and throw.
5960
- **Native change feeds (`IChangeFeedDocumentStore`)** — observe changes from *any* writer (other processes/connections), not just this instance: `await using var sub = await store.SubscribeChanges<User>(async (change, ct) => { ... });`. Backed by each database's own mechanism — **PostgreSQL** `LISTEN`/`NOTIFY` (row-level triggers, true push), **SQL Server** Change Tracking with optional `SqlDependency` query-notification wake-ups (configurable via `SqlServerChangeFeedOptions`), and **CosmosDB** Change Feed. Provisioning (triggers / enabling change tracking) is automatic and idempotent. Dispose the returned handle to stop. (SQLite, LiteDB, IndexedDB, MySQL and Oracle have no proper external-change mechanism and throw `NotSupportedException`.)
6061
- **Concurrent operations on server SQL** — a single `DocumentStore` instance backed by PostgreSQL, MySQL, SQL Server, or Oracle opens a fresh connection per operation and lets the ADO.NET driver pool multiplex callers. No per-store semaphore. SQLite and DuckDB (embedded engines that lock the whole DB on writes) keep the long-lived shared connection + serialization model. Providers opt in to shared mode via `IDatabaseProvider.RequiresSingleConnection`. Table init is exactly-once per table across concurrent first-touch callers (`ConcurrentDictionary<string, Lazy<Task>>`).
6162
- **Unit of work (`IDocumentSession`)** — the document store is a connection: open a short-lived session and group writes into one transaction: `await using var session = store.OpenSession(); session.Add(a).Update(b).Remove<C>(id); await session.SaveChanges();` with automatic commit/rollback. Contiguous same-type runs of inserts, upserts, updates, and removes are each coalesced into the matching batch method. Inject `IDocumentSession` (scoped) in ASP.NET via `AddScopedDocumentSession()`, or open one from the singleton `IDocumentSessionFactory` (MAUI/desktop/background — mirrors EF's `IDbContextFactory`). For finer control the session exposes an explicit transaction — `await using var tx = await session.BeginTransaction();` — for locking reads (`session.Get(id, LockMode.Update)`) and grouping `ExecuteUpdate`/`ExecuteDelete`; `SaveChanges` joins it. Pass an `IsolationLevel` (`BeginTransaction(IsolationLevel.Snapshot)`) for a **consistent-read session**. (Replaces the removed `CreateUnitOfWork()`/`UnitOfWork`.)

‎skills/shiny-documentdb/SKILL.md‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,14 @@ triggers:
4343
- MapComputedProperty
4444
- derived property
4545
- generated column
46+
- blob
47+
- DocumentBlob
48+
- DocumentBlobCollection
49+
- MapBlob
50+
- MapBlobCollection
51+
- attachment
52+
- binary payload
53+
- IBlobDocumentStore
4654
- DocumentContext
4755
- DocumentSet
4856
- Document attribute
@@ -1574,6 +1582,67 @@ var texas = GeoDataSets.Cities.Where(c => c.RegionCode == "TX");
15741582

15751583
Region boundaries are intentionally low-resolution (coarse containment, not cartography). The embedded city lists are regenerated from US Census / Statistics Canada by the dev-only `tools/Shiny.DocumentDb.Geo.DataSeeder` (not part of CI).
15761584

1585+
## Blobs (MapBlob / MapBlobCollection)
1586+
1587+
Binary payloads (PDF, image, signature) attached to a document. The bytes go to a `{table}_blobs` **sidecar table**, not the document JSON; only metadata (length, content type, file name) rides along in the body. **Use `DocumentBlob` instead of a raw `byte[]` property** — a `byte[]` is base64'd into the document body and materialized on every read.
1588+
1589+
**Supported on every server-side provider** — relational (SQLite, PostgreSQL/CockroachDB, SQL Server, MySQL/MariaDB, Oracle, DuckDB) and document/NoSQL (LiteDB, MongoDB/Amazon DocumentDB, Redis, Azure Table, DynamoDB, Cosmos, Firestore, RavenDB-native-attachments). **Only IndexedDB (Blazor WASM) is unsupported** — it reports `store.MaxBlobSize == 0` and **throws `NotSupportedException`**. Per-provider caps vary (Azure Table 64KB, DynamoDB 390KB, Cosmos 1.4MB, Firestore/LiteDB 1-16MB, relational/Redis/Raven ≥512MB) — check `store.MaxBlobSize`.
1590+
1591+
```csharp
1592+
public class Invoice
1593+
{
1594+
public string Id { get; set; } = "";
1595+
public DocumentBlob? Pdf { get; set; } // single
1596+
public DocumentBlobCollection Attachments { get; set; } = new(); // many — NOT List<DocumentBlob>
1597+
}
1598+
1599+
services.AddDocumentStore(opts =>
1600+
{
1601+
opts.DatabaseProvider = new SqliteDatabaseProvider("Data Source=app.db");
1602+
opts.MapBlob<Invoice>(i => i.Pdf);
1603+
opts.MapBlobCollection<Invoice>(i => i.Attachments);
1604+
// options: o => { o.Key = "sig"; o.ComputeHash = true; o.MaxSize = 256*1024; } (ComputeHash OFF by default)
1605+
});
1606+
```
1607+
1608+
**Write** — assign the member and save the document; there is NO `SetBlob`. Metadata can never disagree with the bytes because every mutation goes through the document.
1609+
1610+
```csharp
1611+
inv.Pdf = DocumentBlob.FromBytes(pdfBytes, "application/pdf", "acme.pdf");
1612+
inv.Attachments.Add(scanBytes, "image/png"); // collection.Add(bytes,…) assigns the key up front
1613+
await store.Insert(inv);
1614+
inv.Pdf = null; await store.Upsert(inv); // null drops the row; RemoveAt prunes a collection item
1615+
```
1616+
1617+
**Read** — metadata is populated, bytes are NOT. `Bytes` throws until loaded.
1618+
1619+
```csharp
1620+
var inv = await store.Get<Invoice>(id);
1621+
inv.Pdf!.Length; // from the body — free
1622+
inv.Pdf.IsLoaded; // false
1623+
inv.Pdf.Bytes; // throws until loaded
1624+
1625+
// metadata is queryable (json_extract), payload never touched:
1626+
store.Query<Invoice>().Where(x => x.Pdf!.Length > 1_000_000);
1627+
// x.Pdf.Bytes in a query throws at translation time
1628+
```
1629+
1630+
**Load on demand** — blobs self-load (the store stamped a loader during hydration):
1631+
1632+
```csharp
1633+
await inv.Pdf!.LoadAsync(); // one blob
1634+
var raw = await inv.Pdf.GetBytesAsync(); // load + read
1635+
await inv.Attachments[0].LoadAsync(); // one item of a collection
1636+
await inv.Attachments.LoadAllAsync(); // whole collection, ONE round trip
1637+
1638+
// page of results — avoid N+1 with the store batch load:
1639+
await ((IBlobDocumentStore)store).BatchLoadBlobs(page);
1640+
// no document in hand (download endpoint):
1641+
var bytes = await ((IBlobDocumentStore)store).GetBlob<Invoice>(id, "Pdf");
1642+
```
1643+
1644+
Deleting a document cascades to its blob rows. `store.MaxBlobSize` (bytes) reports the provider ceiling; `0` = unsupported. Backup includes payloads by default (`ExportAsync(stream, new BackupExportOptions { IncludeBlobs = false })` to skip). Blobs are **not** temporally versioned — `Restore` keeps current blobs. `IDocumentMaintenance.SweepOrphanedBlobs<T>()` reclaims rows whose document is gone.
1645+
15771646
## Temporal History (System-Time Versioning)
15781647

15791648
Opt-in append-only versioning per type. Enable with `MapTemporal<T>` on the options; every `Insert`/`Update`/`Upsert`/`Remove`/`SetProperty`/`RemoveProperty`/`BatchInsert` (including writes inside a `UnitOfWork`) records a versioned snapshot to a per-type history sidecar. Only mapped types incur the extra write.

0 commit comments

Comments
 (0)