Getting Started

SoloDB stores your C# and F# objects in a SQLite database inside your application.

Installation

Create a console app and add SoloDB:

dotnet new console -n HelloSoloDB
cd HelloSoloDB
dotnet add package SoloDB

For an existing project, run dotnet add package SoloDB in its directory.

Requirements

SoloDB runs on Windows, Linux and macOS, on .NET 6 and later, .NET Framework 4.6.1 and later, other .NET Standard 2.0 and 2.1 runtimes, and NativeAOT. The package includes .NET 6, .NET Standard 2.0 and .NET Standard 2.1 libraries; NuGet selects the appropriate one automatically.

Your first database

Paste this into Program.cs and run it:

using System;
using System.Linq;
using SoloDatabase;

using var db = new SoloDB("myapp.db");
var users = db.GetCollection<User>();

// Insert an object. SoloDB fills its Id.
var alice = new User { Name = "Alice", Email = "alice@example.com" };
users.Insert(alice);

// Query with LINQ.
var found = users.Single(user => user.Id == alice.Id);
Console.WriteLine(found.Name); // Alice

// Update and delete.
found.Email = "alice@new.example";
users.Update(found);
users.Delete(found.Id);

public class User
{
    public long Id { get; set; }
    public string Name { get; set; } = "";
    public string Email { get; set; } = "";
    public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
}

Reuse the database while your application runs. The using statement closes it when you finish.

Working with Collections

Collections are containers for your documents, similar to tables in SQL databases.

Getting a Collection

// Typed collection - name derived from type (recommended)
var users = db.GetCollection<User>();  // Collection name: "User"

// Custom name - useful for multiple collections of same type
var activeUsers = db.GetCollection<User>("ActiveUsers");
var archivedUsers = db.GetCollection<User>("ArchivedUsers");

// Untyped collection for dynamic scenarios
var untypedCollection = db.GetUntypedCollection("MyData");

An untyped collection reads and writes the stored JSON as it is. Decimal and BigInteger fields of typed documents appear there as encoded text; keep that form when you write them for later typed access.

Collection Lifecycle

  • Collections are created automatically when first accessed
  • The underlying SQLite table is created with the proper schema
  • Indexes defined via attributes are created on first access

Reserved names: Collection names starting with SoloDB are reserved for internal use and will throw an ArgumentException. For example, "SoloDBUsers" is not allowed, but "MyUsers" or "UsersSoloDB" are fine.

// Check if a collection exists
bool exists = db.CollectionExists<User>();
bool existsByName = db.CollectionExists("User");

// Drop a collection (deletes all data!)
db.DropCollection<User>();
db.DropCollection("ArchivedUsers");

CRUD Operations

Insert

var users = db.GetCollection<User>();

// Single insert - returns the generated ID
var user = new User { Name = "Alice", Email = "alice@example.com" };
long id = users.Insert(user);
// user.Id is also set to the same value

// Batch insert - much faster for multiple items
var newUsers = new List<User>
{
    new User { Name = "Bob", Email = "bob@example.com" },
    new User { Name = "Charlie", Email = "charlie@example.com" }
};
IList<long> ids = users.InsertBatch(newUsers);

Insert or Replace (Upsert)

When you have unique indexes, you can upsert based on those constraints:

// If a user with this email exists (assuming unique index), replace it
var user = new User { Name = "Alice Updated", Email = "alice@example.com" };
users.InsertOrReplace(user);

// Batch version
users.InsertOrReplaceBatch(manyUsers);

Read

// By ID (throws KeyNotFoundException if not found)
User user = users.GetById(id);

// All documents as a list
var allUsers = users.ToList();

TryGetById returns an F# option in C#. Import Microsoft.FSharp.Core and use its static accessor with the option argument. Here id is the key to look up:

using Microsoft.FSharp.Core;

// TryGetById returns FSharpOption<User> in C#
var userOption = users.TryGetById(id);
if (FSharpOption<User>.get_IsSome(userOption))
{
    User existingUser = userOption.Value;
    Console.WriteLine(existingUser.Name);
}
else
{
    Console.WriteLine("No matching user");
}
// By custom ID type (using the Document model and generator from ID Generation)
var documents = db.GetCollection<Document>();
Document doc = documents.GetById<string>("doc-abc-123");

Update

// Full document update
var user = users.GetById(1);
user.Name = "New Name";
user.Email = "new@email.com";
users.Update(user);  // Replaces entire document

// Replace matching documents
users.ReplaceOne(u => u.Email == "old@example.com", newUserData);
users.ReplaceMany(u => u.Status == "pending", templateUser);

Methods ending in One (like ReplaceOne, DeleteOne) affect only one document. If multiple documents match the filter, which one is affected is determined by SQLite's internal ordering and may appear random. Use these methods only when you expect exactly one match, or when you don't care which matching document is affected.

Partial Updates with UpdateMany

For efficient partial updates without loading the full document. This is significantly faster than loading documents with GetById, modifying them, and calling Update, because it executes a single SQL statement instead of multiple round-trips.

The update expressions use .Set(...) and .Append(...) — these are SoloDB helpers that translate to SQL, not regular methods on your properties.

// Set a single field
int count = users.UpdateMany(
    u => u.Id <= 10,           // Filter
    u => u.IsActive.Set(true)   // Update action
);

// Set multiple fields at once
users.UpdateMany(
    u => u.Status == "pending",
    u => u.Status.Set("approved"),
    u => u.ApprovedAt.Set(DateTime.UtcNow),
    u => u.ApprovedBy.Set("admin")
);

// Append to a collection property
users.UpdateMany(
    u => u.Id == userId,
    u => u.Tags.Append("verified")
);

Delete

// By ID - returns count of deleted (0 or 1)
int deleted = users.Delete(1);

// By custom ID
documents.Delete<string>("doc-abc-123");

// By predicate
users.DeleteOne(u => u.Email == "old@example.com");   // First match only
users.DeleteMany(u => u.IsActive == false);           // All matches

Querying with LINQ

SoloDB collections implement IQueryable<T>. Queries are translated to SQL and executed on SQLite. Some LINQ methods, including Aggregate, Zip, Reverse, Prepend and SequenceEqual, are not translated. Use AsEnumerable() explicitly before operations you want to run on the client. Root-query Append is supported; this does not add Append to DBRefMany relation queries.

Filtering

// Where clause
var activeUsers = users.Where(u => u.IsActive).ToList();

// Multiple conditions
var thirtyDaysAgo = DateTime.UtcNow.AddDays(-30);
var results = users.Where(u =>
    u.IsActive &&
    u.CreatedAt > thirtyDaysAgo &&
    u.Email.Contains("@company.com")
).ToList();

Single Item Queries

// First match (throws if none)
var first = users.First(u => u.Email == "admin@example.com");

// First or default (returns null if none)
var admin = users.FirstOrDefault(u => u.Role == "Admin");

// Single (throws if not exactly one)
var unique = users.Single(u => u.Username == "johndoe");

// Check existence
bool hasAdmins = users.Any(u => u.Role == "Admin");
bool allActive = users.All(u => u.IsActive);

Ordering and Pagination

// Order by
var sorted = users
    .OrderBy(u => u.Name)
    .ThenByDescending(u => u.CreatedAt)
    .ToList();

// Pagination
int page = 2;
int pageSize = 20;
var pageResults = users
    .OrderBy(u => u.Id)
    .Skip((page - 1) * pageSize)
    .Take(pageSize)
    .ToList();

Projections

// Select specific properties
var emails = users.Select(u => u.Email).ToList();

// Project to anonymous type
var summaries = users.Select(u => new
{
    u.Name,
    u.Email,
    DaysSinceCreated = (DateTime.UtcNow - u.CreatedAt).Days
}).ToList();

// Project to DTO
var dtos = users.Select(u => new UserDto
{
    FullName = u.Name,
    ContactEmail = u.Email
}).ToList();

Aggregates

int totalUsers = users.Count();
int activeCount = users.Count(u => u.IsActive);
long total = users.LongCount();

// Note: Min, Max, Sum, Average are supported on numeric projections
var maxId = users.Max(u => u.Id);
var avgPrice = products.Average(p => p.Price);

v1.4 Decimal aggregates keep Decimal precision; integer and floating-point aggregates keep their native behavior. See Decimal and BigInteger.

String Operations

// Contains, StartsWith, EndsWith
var results = users.Where(u =>
    u.Name.Contains("john") ||
    u.Email.StartsWith("admin") ||
    u.Email.EndsWith("@company.com")
).ToList();

// SQL LIKE pattern (extension method — import SoloDatabase namespace)
var pattern = users.Where(u => u.Name.Like("J%n")).ToList();

StartsWith can use an index because SoloDB translates it to a range predicate that SQLite can search efficiently. EndsWith and Contains still require a scan. Like(...) is available after using SoloDatabase;.

Array/Collection Queries

// Query nested arrays
var tagged = users.Where(u => u.Tags.Contains("premium")).ToList();

// Check if any element matches
var oneWeekAgo = DateTime.UtcNow.AddDays(-7);
var withRecentOrders = users.Where(u =>
    u.Orders.Any(o => o.Date > oneWeekAgo)
).ToList();

Indexing

Indexes dramatically improve query performance for filtered and sorted operations. Without an index, SoloDB must scan every document.

Attribute-Based Indexes

The easiest way - add [Indexed] to properties you frequently query:

using SoloDatabase.Attributes;

public class Product
{
    public long Id { get; set; }  // Always indexed (primary key)

    [Indexed(unique: true)]       // Unique index - no duplicates allowed
    public string SKU { get; set; }

    [Indexed]                     // Non-unique index
    public string Category { get; set; }

    [Indexed]
    public decimal Price { get; set; }

    public string Description { get; set; }  // Not indexed
}

Indexes are automatically created when the collection is first accessed.

When to Index

  • DO index: Properties used in Where clauses, OrderBy, and unique constraints
  • DON'T index: Properties rarely queried, or only used in Select projections
  • Consider trade-offs: Indexes speed up reads but slow down writes slightly, and increase the database file size on disk/memory

Programmatic Indexes

var products = db.GetCollection<Product>();

// Add an index on a property not covered by attributes
products.EnsureIndex(p => p.Description);

// Remove an index
products.DropIndexIfExists(p => p.Description);

// Ensure all attribute-defined indexes exist
products.EnsureAddedAttributeIndexes();

If you add new [Indexed] attributes to your model classes after the database already exists, the indexes won't be created automatically until you call EnsureAddedAttributeIndexes(). Indexes are only auto-created on first collection access. If you remove an [Indexed] attribute later, SoloDB does not drop the old index automatically; remove it explicitly with DropIndexIfExists(...) if you no longer want it.

Supported Index Expressions

EnsureIndex and EnsureUniqueAndIndex accept expressions that reference entity properties directly:

// Direct property
products.EnsureIndex(p => p.Category);

// Composite index (C# expression trees require the ValueTuple constructor form)
products.EnsureIndex(p => new ValueTuple<string, decimal>(p.Category, p.Price));

// DBRef.Id navigation (indexes the foreign key)
orders.EnsureIndex(o => o.Author.Id);

In C#, composite index expressions must use the ValueTuple constructor form because expression trees do not accept tuple literal syntax.

Unsupported Index Expressions

The following expressions are rejected at call time with a descriptive error message:

x => x.IdEntity Id is always indexed automatically
x => x.Items.CountRelation expressions that resolve through link tables cannot be indexed
x => x.Tag.Value.NameDBRef.Value navigation requires a JOIN and cannot be indexed
x => x.Name + "suffix"Binary expressions are not accepted as index terms
x => 42Constant expressions must reference the entity parameter

Unique Constraint Violations

v1.4 The native engine exposes structured SQLite error codes. Handle a unique-constraint failure without parsing its message:

try
{
    products.Insert(new Product { SKU = "EXISTING-SKU" });
}
catch (SoloDatabase.NativeSqliteException ex)
    when (ex.SqliteExtendedErrorCode == 2067) // SQLITE_CONSTRAINT_UNIQUE
{
    Console.WriteLine("SKU already exists!");
}

Serialization Rules

Understanding what gets serialized is crucial for designing your data models correctly.

Classes: Only Public Properties

For classes, SoloDB serializes public instance properties with getters. Fields are ignored.

public class Example
{
    // SERIALIZED - public property with getter
    public string Name { get; set; }

    // SERIALIZED - public property (setter used for mutable models)
    public int Age { get; set; }

    // NOT SERIALIZED - field (even if public)
    public string PublicField;

    // NOT SERIALIZED - private property
    private string Secret { get; set; }

    // NOT SERIALIZED - internal property
    internal string Internal { get; set; }
}

Reading models: Mutable models use the available setters of their public properties, including nonpublic and init setters. Constructor-bound models use a supported matching public constructor instead. A read-only property can be reconstructed through that constructor; a getter alone does not guarantee a read path. See typed reader behavior.

Structs: Fields and Properties

Structs behave differently - both public fields AND public properties are serialized:

public struct Point
{
    public int X;  // SERIALIZED - public field on struct
    public int Y;  // SERIALIZED - public field on struct

    public double Distance { get; set; }  // SERIALIZED - public property
}

Supported Types

SoloDB's built-in serializer handles these types natively:

Primitivesint, long, float, double, decimal, bool, char, byte, etc.
Arbitrary integersSystem.Numerics.BigInteger in SoloDB 1.4; see numerical storage
EnumsStored as their underlying integer value, not as strings
Stringsstring (null-safe)
Date/TimeDateTime, DateTimeOffset, TimeSpan
GUIDsGuid
CollectionsArrays, List<T>, Dictionary<K,V>, HashSet<T>, Queue<T>, Stack<T>
NullableNullable<T> (e.g., int?, DateTime?)
TuplesValueTuple, Tuple
F# TypesF# records (see F# records), discriminated unions, F# lists
Binarybyte[] (stored as Base64)
Nested ObjectsAny class/struct following these rules

Nested Objects

Objects can contain nested objects and lists. They are stored inside the same document. To link separate documents instead, use relations:

public class Order
{
    public long Id { get; set; }
    public Customer Customer { get; set; }        // Nested object
    public List<OrderItem> Items { get; set; }   // List of objects
    public Address ShippingAddress { get; set; }  // Another nested object
}

public class OrderItem
{
    public string ProductName { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }
}

C# Language Features

  • init-only setters (C# 9+) — supported. Properties round-trip correctly.
  • required modifier (C# 11+) — supported as the normal compiler feature. SoloDB does not add runtime enforcement beyond what C# provides.
  • Enums — stored as their underlying integer value, not as strings.

F# records

F# records work as SoloDB models without [<CLIMutable>]. Mark only these fields mutable:

  • Id: Insert writes the generated key into it, and Update uses it to find the stored record.
  • Reference fields: DBRef, DBRefMany, FileRef, FileRefMany, DirectoryRef and DirectoryRefMany must be writable.

All other fields can stay immutable. NativeAOT needs no extra attribute either; use the normal generated registration and CompileQuotation for queries.

open SoloDatabase

type Author = { mutable Id: int64; Name: string }
type Tag = { mutable Id: int64; Label: string }
type Book =
    { mutable Id: int64
      Title: string
      mutable Author: DBRef<Author>
      mutable Tags: DBRefMany<Tag> }

let run () =
    use db = new SoloDB("memory:library")
    let authors = db.GetCollection<Author>()
    let books = db.GetCollection<Book>()

    let author = { Id = 0L; Name = "Hedy Lamarr" }
    authors.Insert(author) |> ignore // writes the generated key into author.Id

    let book =
        { Id = 0L
          Title = "Frequency Hopping"
          Author = DBRef<Author>.To(author.Id)
          Tags = DBRefMany<Tag>() }
    book.Tags.Add({ Id = 0L; Label = "radio" }) // inserted together with the book
    books.Insert(book) |> ignore

    let loaded = books.GetById(book.Id)
    System.Console.WriteLine(loaded.Title + " by " + loaded.Author.Value.Name + ", " + loaded.Tags.Count.ToString() + " tag")
    // Frequency Hopping by Hedy Lamarr, 1 tag

run ()

What to Avoid

  • Circular object graphs - an object cannot contain itself; link documents with references instead
  • Very deep nesting - impacts performance and query complexity
  • Storing huge binary data - use the FileSystem API instead

Built-in JSON Serializer

SoloDB uses its own high-performance JSON serializer instead of Newtonsoft.Json or System.Text.Json. The serializer is designed specifically for document database use cases:

  • Generic type caching - Serializers are generated once per type and cached for subsequent use
  • Polymorphic support - Adds a $type discriminator when the collection type is abstract, an interface or marked [Polymorphic]; see polymorphic collections
  • F# native support - Records, discriminated unions, and F# lists are handled natively
  • No external dependencies - Self-contained implementation with no JSON library dependencies

Schema Evolution for Plain Document Fields

SoloDB does not need a migration step for every document-class edit, but not every change means the same thing when older rows are read back.

ChangeWhat happens
Add a propertyOlder documents keep constructor defaults for missing mutable properties; missing constructor arguments use their typed default.
Remove a propertyThe old JSON field is ignored; the remaining mapped fields still load normally.
Rename a propertyNo automatic remap happens. Old JSON stays under the old name until you migrate it.
Change a property typeOld values are not converted automatically. For example, changing int to string can require your own migration.

Old fields are not cleaned up automatically after a rename or removal. Decimal and BigInteger data written before SoloDB 1.4 has its own one-time conversion.

ID Generation

Every document needs a unique identifier. SoloDB provides flexible options for ID handling.

Default: Auto-Increment Long

Give the model a readable, writable long Id property. SoloDB writes the SQLite row ID back after insertion and uses it for later Update(item) calls:

using SoloDatabase;

using var db = new SoloDB("memory:products");
var products = db.GetCollection<Product>();
var product = new Product { Name = "Widget" };
products.Insert(product);
// product.Id now holds the inserted physical row ID.
product.Name = "Updated Widget";
products.Update(product);

public class Product
{
    public long Id { get; set; }
    public string Name { get; set; } = "";
}

Custom ID with [SoloId] Attribute

For other ID types or custom generation logic, use the [SoloId] attribute with a custom generator:

using SoloDatabase.Attributes;

// Define a custom ID generator that produces string IDs from GUIDs
public class StringGuidIdGenerator : IIdGenerator<Document>
{
    public object GenerateId(ISoloDBCollection<Document> collection, Document item)
    {
        return Guid.NewGuid().ToString("N");  // Returns string like "a1b2c3d4..."
    }

    public bool IsEmpty(object id)
    {
        return string.IsNullOrEmpty(id as string);
    }
}

// Use it in your model
public class Document
{
    [SoloId(typeof(StringGuidIdGenerator))]
    public string Id { get; set; }  // String ID, not Guid

    public string Title { get; set; }
    public string Content { get; set; }
}

Supported ID Types

longDefault, auto-incremented by SQLite
intApplication key with an explicit [SoloId] generator; not an auto-generated physical row ID
GuidRequires a generator (e.g., one that calls Guid.NewGuid())
stringMust be provided by your generator or set before insert

Physical and application identity: Only a writable long Id receives the physical auto-generated ID. An ordinary int Id is a document property. Use [SoloId] for an application key of another type; its generator decides when a supplied key is empty. The generated application key and the SQLite row ID are separate. A model without either supported identity can be inserted, but Update(item) cannot infer which stored row to replace.

Custom Guid ID Generator Example

Here's a simple generator for Guid IDs:

public class GuidIdGenerator : IIdGenerator<MyDocument>
{
    public object GenerateId(ISoloDBCollection<MyDocument> collection, MyDocument item)
    {
        return Guid.NewGuid();
    }

    public bool IsEmpty(object id) => id is Guid g && g == Guid.Empty;
}

Transactions

For operations that must succeed or fail together, use transactions. If any exception occurs, all changes are automatically rolled back.

Basic Transaction

db.WithTransaction(tx =>
{
    var accounts = tx.GetCollection<Account>();

    var from = accounts.GetById(fromAccountId);
    var to = accounts.GetById(toAccountId);

    if (from.Balance < amount)
        throw new InvalidOperationException("Insufficient funds");

    from.Balance -= amount;
    to.Balance += amount;

    accounts.Update(from);
    accounts.Update(to);
});
// If we get here, transaction committed successfully

Transaction with Return Value

var orderId = db.WithTransaction(tx =>
{
    var orders = tx.GetCollection<Order>();
    var inventory = tx.GetCollection<InventoryItem>();

    // Create order and update inventory atomically
    var order = new Order { CustomerId = customerId, Total = total };
    orders.Insert(order);

    foreach (var item in orderItems)
    {
        var inv = inventory.Single(i => i.ProductId == item.ProductId);
        inv.Quantity -= item.Quantity;
        inventory.Update(inv);
    }

    return order.Id;
});

Automatic Rollback

try
{
    db.WithTransaction(tx =>
    {
        var users = tx.GetCollection<User>();
        users.Insert(new User { Name = "Test" });

        // This exception causes automatic rollback
        throw new Exception("Something went wrong!");
    });
}
catch (Exception)
{
    // The user was NOT inserted - transaction rolled back
}

Async Transactions

var result = await db.WithTransactionAsync(async tx =>
{
    var users = tx.GetCollection<User>();
    users.Insert(new User { Name = "Alice" });
    return users.Count();
});

WAL Read Snapshots

In SQLite's WAL journal mode, readers on separate connections can continue during a write transaction. Each read transaction observes a consistent snapshot: it sees none of that writer's changes or all of them, never a half-applied commit.

A reader that is already inside its own read transaction keeps the snapshot it started with until that read transaction ends, so it will not observe the commit mid-flight. Reads issued after the commit — a new read transaction, or an ordinary autocommit read — see the committed state in full.

This is what makes it safe to rebuild a collection in the background while it is being read. Note that the guarantee applies to a single transaction: two separate statements outside a transaction are two separate points in time, so a reader can observe the state between them.

A multi-step read such as Download can use several read transactions unless you explicitly provide an enclosing transaction. It does not automatically retain one snapshot for the whole transfer. Same-connection event callbacks also run inside their writer's active statement and can observe its in-flight work.

// Readers see the old rows until this commits, then all the new rows at once.
db.WithTransaction(tx =>
{
    var products = tx.GetCollection<Product>();
    products.DeleteMany(x => true);
    products.InsertBatch(freshRows);
});

Nested Transactions Since v1.1

Calling WithTransaction inside an existing transaction creates a nested SQLite SAVEPOINT. If the inner operation fails, only the inner changes are rolled back - the outer transaction continues:

db.WithTransaction(tx =>
{
    var users = tx.GetCollection<User>();
    users.Insert(new User { Name = "Alice" });

    try
    {
        tx.WithTransaction(inner =>
        {
            var orders = inner.GetCollection<Order>();
            orders.Insert(new Order { Total = -1 });
            throw new Exception("Invalid order");
        });
    }
    catch (Exception)
    {
        // Only the order insert was rolled back
        // Alice's insert is still part of the outer transaction
    }

    users.Insert(new User { Name = "Bob" });
    // Both Alice and Bob are committed when the outer transaction completes
});

Transactions in Event Handlers

Event handlers execute during active SQL statements. Calling WithTransaction on the event context's ISoloDB throws NotSupportedException at runtime because SQLite cannot open savepoints while a statement is in progress. Use the event context directly instead:

var orders = db.GetCollection<Order>();

// This compiles but throws NotSupportedException at runtime:
orders.OnInserted(ctx =>
{
    ctx.WithTransaction(tx => { ... }); // Throws NotSupportedException
    return SoloDBEventsResult.EventHandled;
});

// Instead, use the event context directly:
orders.OnInserted(ctx =>
{
    var audit = ctx.GetCollection<AuditLog>();
    audit.Insert(new AuditLog { Action = "OrderCreated" });
    return SoloDBEventsResult.EventHandled;
});

FileSystem in Transactions

FileSystem behavior depends on which context you access it from:

  • db.FileSystem — single-statement operations (Delete, SetMetadata, DeleteMetadata, SetFileModificationDate, SetFileCreationDate) are atomic via SQLite autocommit.
  • db.FileSystem — multi-step structural operations (MoveFile, MoveReplaceFile, MoveDirectory, CopyFile, CopyDirectory, WriteAt, UploadBulk) wrap their own internal transaction and are fully atomic.
  • db.FileSystem — Upload and UploadAsync wrap their own internal transaction and are fully atomic, same as other multi-step operations above.
  • tx.FileSystem — all operations participate in the enclosing transaction. A rollback undoes uploaded chunks, metadata changes, and structural operations atomically.
// Transactional upload: full rollback on failure
db.WithTransaction(tx =>
{
    var users = tx.GetCollection<User>();
    users.Insert(new User { Name = "Alice" });

    tx.FileSystem.Upload("/avatars/alice.png", imageStream);

    // If anything throws here, both user insert and file upload roll back.
});

Transaction and callback lifetime v1.4

The outer transaction owns a dedicated connection, destroyed when its scope finishes. Do not retain the transaction handle or collections beyond the callback. Nested transaction calls use the existing savepoint behavior. Event-context database work joins the active transaction; explicit transaction calls on an event context are unsupported. An after-event is not a commit notification, and a caught database fault inside a handler can still prevent commit.

Events API Since v1.0.0

SoloDB provides an event system that lets you react to document changes. Register handlers to run custom logic before or after insert, update, and delete operations. Files and directories have their own events; see filesystem events.

Event Types

Six event types are available, split into "before" and "after" events:

Before EventsRun before the corresponding database mutation. Can cause rollback.
OnInsertingBefore a document is inserted
OnUpdatingBefore a document is updated
OnDeletingBefore a document is deleted
After EventsRun after the operation, but still in the same transaction.
OnInsertedAfter a document is inserted
OnUpdatedAfter a document is updated
OnDeletedAfter a document is deleted

Registering Handlers

Collections implement the events interface directly:

var users = db.GetCollection<User>();

// Before-insert handler
users.OnInserting(ctx =>
{
    Console.WriteLine($"Inserting user: {ctx.Item.Name}");
    return SoloDBEventsResult.EventHandled;
});

// After-insert handler
users.OnInserted(ctx =>
{
    Console.WriteLine($"Inserted user with ID: {ctx.Item.Id}");
    return SoloDBEventsResult.EventHandled;
});

// Update handler with access to old and new values
users.OnUpdating(ctx =>
{
    Console.WriteLine($"Updating from {ctx.OldItem.Name} to {ctx.Item.Name}");
    return SoloDBEventsResult.EventHandled;
});

Handler Return Values

Handlers must return a SoloDBEventsResult value:

EventHandledHandler completed successfully. Continue with operation.
RemoveHandlerHandler completed and should be unregistered (one-time handler).
// One-time handler that removes itself after first execution
users.OnInserting(ctx =>
{
    Console.WriteLine("This runs only once!");
    return SoloDBEventsResult.RemoveHandler;
});

Handler Context

The context object provides access to the item and a scoped database connection:

users.OnInserting(ctx =>
{
    // Access the item being inserted/updated/deleted
    var user = ctx.Item;

    // Access the collection name
    string collectionName = ctx.CollectionName;

    // The context itself implements ISoloDB - use it for related operations
    var logs = ctx.GetCollection<AuditLog>();
    logs.Insert(new AuditLog { Action = "UserCreated", UserId = user.Id });

    return SoloDBEventsResult.EventHandled;
});

For update events, the context provides both old and proposed new values:

users.OnUpdating(ctx =>
{
    var oldUser = ctx.OldItem;  // Value before update
    var newUser = ctx.Item;     // Value after update

    if (oldUser.Email != newUser.Email)
    {
        Console.WriteLine($"Email changed from {oldUser.Email} to {newUser.Email}");
    }

    return SoloDBEventsResult.EventHandled;
});

Use the ctx parameter for database operations inside handlers. Access through an external SoloDB instance is rejected.

Unregistering Handlers

To remove a handler, keep a reference and call Unregister:

// Keep a reference to the handler
InsertingHandler<User> myHandler = ctx =>
{
    Console.WriteLine("Handler running");
    return SoloDBEventsResult.EventHandled;
};

// Register it
users.OnInserting(myHandler);

// Later, unregister it
users.Unregister(myHandler);

To remove a handler from inside its callback, return SoloDBEventsResult.RemoveHandler. Call Unregister outside callbacks.

Exception Handling and Rollback

All event handlers run inside the same SQLite transaction as the operation. If any handler throws an exception, the entire operation rolls back:

users.OnInserting(ctx =>
{
    if (ctx.Item.Email == null)
        throw new InvalidOperationException("Email is required");

    return SoloDBEventsResult.EventHandled;
});

try
{
    users.Insert(new User { Name = "Test", Email = null });
}
catch (NativeSqliteException ex)
{
    // Insert was rolled back - user was NOT inserted
    Console.WriteLine(ex.Message);  // Contains "Email is required"
}

After-event handlers (OnInserted, OnUpdated, OnDeleted) run inside the transaction. If one throws, the operation rolls back.

Multiple Handlers

You can register multiple handlers for the same event. They execute in registration order. If one throws, subsequent handlers do not run:

users.OnInserting(ctx =>
{
    Console.WriteLine("First handler");
    return SoloDBEventsResult.EventHandled;
});

users.OnInserting(ctx =>
{
    Console.WriteLine("Second handler");
    throw new Exception("Oops!");  // Stops here, third won't run
});

users.OnInserting(ctx =>
{
    Console.WriteLine("Third handler");  // Never reached
    return SoloDBEventsResult.EventHandled;
});

Use Cases

  • Audit logging - Record who changed what and when
  • Validation - Enforce business rules before changes commit
  • Cascading updates - Update related documents automatically
  • Cache invalidation - Clear caches when data changes
  • Notifications - Trigger external notifications on changes

SoloDB 1.4 callback contexts and their database/collection/filesystem adapters are borrowed for one invocation. Copy needed values; do not retain them. Use context database access on the callback thread. After-events run inside the transaction and are not commit notifications.

Polymorphic Collections

Store different derived types in a single collection and query them by base type or filter by concrete type.

Abstract Base Class

public abstract class Figure
{
    public long Id { get; set; }
    public string Color { get; set; }
    public abstract double CalculateArea();
}

public class Circle : Figure
{
    public double Radius { get; set; }
    public override double CalculateArea() => Math.PI * Radius * Radius;
}

public class Rectangle : Figure
{
    public double Width { get; set; }
    public double Height { get; set; }
    public override double CalculateArea() => Width * Height;
}

Usage

var figures = db.GetCollection<Figure>();

// Insert different types
figures.Insert(new Circle { Color = "Red", Radius = 5.0 });
figures.Insert(new Rectangle { Color = "Blue", Width = 4.0, Height = 6.0 });

// Query all figures (returns properly typed objects)
var allFigures = figures.ToList();
// allFigures[0] is Circle, allFigures[1] is Rectangle

// Query by base class properties
var blueFigures = figures.Where(s => s.Color == "Blue").ToList();

// Filter by concrete type using OfType<T>()
var circles = figures.OfType<Circle>().ToList();
var largeCircles = figures.OfType<Circle>()
    .Where(c => c.Radius > 3.0)
    .ToList();

SoloDB translates OfType<T>() using the stored $type discriminator in JSONB. This is stricter than normal CLR assignability: it matches rows stored exactly as T, not "base type plus every derived type."

How It Works

SoloDB stores the concrete type in a $type field when the collection type is an abstract class, an interface or a class marked [Polymorphic]. Reads use it to create the original type, and OfType<T>() filters on it.

Relations Since v1.1

Link documents with DBRef<T> for one target and DBRefMany<T> for many. SoloDB keeps the links in link tables, so it can enforce delete policies and query through them.

Reading an owner loads its references by default, up to a bounded depth. Use Include and Exclude to choose which references load.

Link changes commit or roll back together with the document write that makes them, including inside nested transactions.

Relation queries are translated to SQLite SQL, including DBRefMany filters and aggregates, GroupJoin and nested relation queries (since 1.2.0).

Single Reference (DBRef) Since v1.1

Use DBRef<T> to reference one document from another. A single entity can have multiple DBRef properties pointing to the same target type:

public class Person
{
    public long Id { get; set; }
    public string Name { get; set; }
}

public class Loan
{
    public long Id { get; set; }
    public decimal Amount { get; set; }

    // Unlink only — deleting a loan does not delete the referenced persons
    [SoloRef(OnOwnerDelete = DeletePolicy.Unlink)]
    public DBRef<Person> Borrower { get; set; }

    [SoloRef(OnOwnerDelete = DeletePolicy.Unlink)]
    public DBRef<Person> Guarantor { get; set; }
}

var people = db.GetCollection<Person>();
var loans = db.GetCollection<Loan>();

var aliceId = people.Insert(new Person { Name = "Alice" });
var bobId = people.Insert(new Person { Name = "Bob" });

// Reference existing persons by Id
loans.Insert(new Loan
{
    Amount = 5000,
    Borrower = DBRef<Person>.To(aliceId),
    Guarantor = DBRef<Person>.To(bobId)
});

// Or cascade-insert a new person automatically
loans.Insert(new Loan
{
    Amount = 3000,
    Borrower = DBRef<Person>.To(aliceId),
    Guarantor = DBRef<Person>.From(new Person { Name = "Charlie" })
});

// Query loans by borrower — referenced entity is loaded automatically
var aliceLoans = loans.Where(l => l.Borrower.Id == aliceId).ToList();
Console.WriteLine(aliceLoans[0].Borrower.Value.Name); // "Alice"
Console.WriteLine(aliceLoans[0].Guarantor.Value.Name); // "Bob"

// Query through the referenced entity's properties
var charlieGuaranteed = loans.Where(l =>
    l.Guarantor.Value.Name == "Charlie"
).ToList();
Console.WriteLine(charlieGuaranteed[0].Amount); // 3000

HasValue vs IsLoaded

HasValue and IsLoaded are independent properties:

  • HasValue — true if a reference exists (Id != 0). This is about whether a target is referenced.
  • IsLoaded — true if the Value has been loaded by the query. This is about whether the target entity data is available in memory.
DBRef<T>.NoneHasValue = false, IsLoaded = false
DBRef<T>.To(id)HasValue = true, IsLoaded = false
After query loads entityHasValue = true, IsLoaded = true

State Transition Examples

Example 1: Before Loading the Target Entity
// DBRef.To(id) sets HasValue=true but IsLoaded=false
var borrowerId = people.Insert(new Person { Name = "Alice" });
var loan = new Loan { Amount = 1000, Borrower = DBRef<Person>.To(borrowerId) };
Console.WriteLine(loan.Borrower.HasValue);  // true — reference exists
Console.WriteLine(loan.Borrower.IsLoaded);  // false — entity not loaded yet
// loan.Borrower.Value would throw InvalidOperationException here
Example 2: After Query Load
var loaded = loans.First(l => l.Amount == 5000);
Console.WriteLine(loaded.Borrower.HasValue);   // true
Console.WriteLine(loaded.Borrower.IsLoaded);   // true
Console.WriteLine(loaded.Borrower.Value.Name); // "Alice" — safe to access

DBRef Properties

IdThe database Id of the referenced entity (0 if empty)
HasValuetrue if a reference exists (Id != 0)
IsLoadedtrue if the entity was loaded by the query
ValueThe loaded entity (throws InvalidOperationException if not loaded or empty)

Factory Methods

DBRef<T>.To(id)Reference an existing entity by its database Id
DBRef<T>.From(entity)Cascade-insert a new entity, then reference it
DBRef<T>.NoneEmpty reference (no target)

Collection Reference (DBRefMany) Since v1.1

Use DBRefMany<T> to reference multiple documents. It implements IList<T> with change tracking — SoloDB computes the diff automatically on Update:

Initialize DBRefMany<T> with = new DBRefMany<T>(). Insert tolerates null and creates no links, and loading from the database gives you an empty tracked collection. Update and Upsert reject null with an error.

public class Tag
{
    public long Id { get; set; }
    public string Label { get; set; }
}

public class Article
{
    public long Id { get; set; }
    public string Title { get; set; }
    public DBRefMany<Tag> Tags { get; set; } = new();
}

var tags = db.GetCollection<Tag>();
var articles = db.GetCollection<Article>();

var article = new Article { Title = "Breaking News" };
article.Tags.Add(new Tag { Label = "News" });  // Cascade-insert
articles.Insert(article);

// Load and modify
var loaded = articles.First(a => a.Title == "Breaking News");
loaded.Tags.Add(new Tag { Label = "Tech" });  // Add a new tag
loaded.Tags.Remove(loaded.Tags.First(t => t.Label == "News")); // Remove a tag
articles.Update(loaded);                       // Diff is computed automatically

Ordering: DBRefMany<T> does not define a stable order unless your query applies one explicitly. For deterministic results with boundary-sensitive operators such as First, Last, Take, or Skip, start with OrderBy or OrderByDescending.

Delete Policies Since v1.1

Control what happens when referenced documents are deleted using the [SoloRef] attribute:

public class Order
{
    public long Id { get; set; }

    // Block deletion of the referenced Customer if orders reference it
    [SoloRef(OnDelete = DeletePolicy.Restrict)]
    public DBRef<Customer> Customer { get; set; }

    // When this order is deleted, unlink items (items survive)
    [SoloRef(OnOwnerDelete = DeletePolicy.Unlink)]
    public DBRefMany<OrderItem> Items { get; set; } = new();
}

OnDelete (target entity is deleted)

Restrict (default)Block the delete if any references exist
CascadeAlso delete the entity holding this reference
UnlinkRemove the reference (set to None / remove link row)

OnOwnerDelete (owner entity is deleted)

Deletion (default)Unlink, then delete targets with zero remaining references
UnlinkRemove link rows only, targets always survive
RestrictBlock owner deletion if any links exist

The default behavior in plain English is: deleting a target is blocked while something still points to it, and deleting an owner removes its links and then deletes any targets left with zero references.

OnOwnerDelete = Cascade is not supported for DBRefMany and is rejected at schema build time.

Delete-Policy Combination Matrix

OnDelete \ OnOwnerDeleteDeletionUnlinkRestrict
RestrictBlock target deletes; owner delete unlinks and removes zero-reference targetsBlock target deletes; owner delete only unlinksBlock target deletes and block owner deletes while links exist
CascadeDeleting the target also deletes the owner; owner delete still unlinks and removes zero-reference targetsDeleting the target also deletes the owner; owner delete only unlinksDeleting the target also deletes the owner; owner delete is still blocked while links exist
UnlinkDeleting the target unlinks references; owner delete unlinks and removes zero-reference targetsPure unlink behavior in both directionsDeleting the target unlinks references; owner delete is blocked while links exist

Typed-ID References Since v1.1

If your target entity uses a custom ID type (via [SoloId]), use the two-parameter generic form DBRef<T, TId>. The [SoloId] attribute requires an IIdGenerator<T> implementation that generates unique identifiers:

// Example tags: United States -> UN, Germany -> GE, Japan -> JA
public static class CountryTag
{
    public static string Get(Country c) => c.Name.Substring(0, 2).ToUpperInvariant();
}

// User-defined generator implementing IIdGenerator<T>
public class CountryCodeGenerator : IIdGenerator<Country>
{
    public object GenerateId(ISoloDBCollection<Country> collection, Country document)
        => CountryTag.Get(document);  // Derive code from Name
    public bool IsEmpty(object id) => string.IsNullOrEmpty(id as string);
}

public class Country
{
    public long Id { get; set; }      // Physical row identity of this reference target
    [SoloId(typeof(CountryCodeGenerator))]
    public string Code { get; set; }  // Auto-generated from Name (e.g. "UN", "GE", "JA")
    public string Name { get; set; }
}

public class Office
{
    public long Id { get; set; }
    public string City { get; set; }
    public DBRef<Country, string> Country { get; set; }
}

This example derives a tag from the first two letters. Different names can collide; supply authoritative unique application codes in real data. The unique index rejects duplicate codes rather than inventing a replacement.

To() — Reference by Custom ID (Reuse)

.To(id) resolves to an existing record by its [SoloId] value. No new entity is created:

var countries = db.GetCollection<Country>();
var offices = db.GetCollection<Office>();

// Code auto-generated via CountryTag.Get
countries.Insert(new Country { Name = "United States" }); // Code → "UN"
countries.Insert(new Country { Name = "Germany" });        // Code → "GE"

// Reference existing country by generated code
offices.Insert(new Office
{
    City = "New York",
    Country = DBRef<Country, string>.To("UN")
});

// Same country, different office — no duplicate created
offices.Insert(new Office
{
    City = "San Francisco",
    Country = DBRef<Country, string>.To("UN")
});

From() — Cascade Insert (No Reuse)

.From(entity) always cascade-inserts a new entity. If the [SoloId] value already exists, the insert fails with a unique constraint violation:

// This cascade-inserts a new Country — works when "JA" doesn't exist yet
offices.Insert(new Office
{
    City = "Tokyo",
    Country = DBRef<Country, string>.From(new Country { Name = "Japan" }) // Code → "JA"
});

// This FAILS — "UN" already exists (United States), From() tries to insert a duplicate
// Throws InvalidOperationException (UNIQUE constraint failed)
offices.Insert(new Office
{
    City = "Chicago",
    Country = DBRef<Country, string>.From(new Country { Name = "United States" })
});

Use .To(id) to reference existing targets. Use .From(entity) only when creating new targets. Typed-ID resolution requires a unique index on the [SoloId] property (provided automatically by the attribute). The resolver matches exactly one target row — if no match is found, the operation is rejected.

Schema Evolution Since v1.1

SoloDB detects relation schema changes when you call GetCollection<T>() and applies safe transitions automatically. Unsupported transitions raise an error with a descriptive message and a fix instruction. All detection and migration runs at collection-open time, not at individual entity access.

Supported Transitions

TransitionOutcomeDetails
Add DBRef or DBRefMany propertyAllowedLink table auto-created via CREATE TABLE IF NOT EXISTS. Catalog row inserted.
Remove relation (no persisted links)AllowedCatalog row orphaned, link table empty or absent. No error.
Single → Many (widen)AllowedAtomic table-recreate within the current transaction. The link table is rebuilt with UNIQUE(SourceId, TargetId) replacing UNIQUE(SourceId). Row count is verified before and after.
Add typed-id (DBRef<T> → DBRef<T,TId>)AllowedNo link table change. Requires a unique index on the target's [SoloId] property — raises an error if missing.
Remove typed-id (DBRef<T,TId> → DBRef<T>)AllowedTyped-id resolution disabled. No link table change.
Change OnDelete policyAllowedCatalog metadata updated via upsert. No link table DDL change. New policy enforced at application layer on next deletion.
Change OnOwnerDelete policyAllowedSame catalog metadata update. Exception: DBRefMany with OnOwnerDelete = Cascade is rejected at build time.

Rejected Transitions

TransitionError
Remove relation (persisted links exist)"relation property was removed but persisted link data exists"
Many → Single (narrow)"relation kind narrowing not supported"
Change target type"relation target type changed"
Single → Many (duplicate source-target pairs)"forward migration failed ... duplicate (SourceId, TargetId) pairs"

Important Notes

  • Rename a relation property is equivalent to removing the old property and adding a new one. If the old property has persisted link data, the removal is rejected.
  • Policy changes update the catalog metadata only. They do not modify link table DDL. Policies are enforced at the application layer by the relation engine, not by SQLite constraints.

SoloRef.Unique changes are not applied retroactively. The unique constraint takes effect only when the link table is first created. If you need to add or remove relation uniqueness later, rebuild that relation table deliberately instead of expecting the old one to mutate in place.

// Adding a new relation property — link table created automatically
public class Order
{
    public long Id { get; set; }
    public DBRef<Customer> Customer { get; set; }
    public DBRef<Person> SalesRep { get; set; }  // New property — safe to add
}
var orders = db.GetCollection<Order>(); // Link table for SalesRep created here

// Changing a delete policy — takes effect immediately
public class Order
{
    public long Id { get; set; }

    [SoloRef(OnDelete = DeletePolicy.Cascade)]  // Changed from default Restrict
    public DBRef<Customer> Customer { get; set; }
}
var orders = db.GetCollection<Order>(); // Catalog updated, new policy active

Reference mutation and concurrency v1.4

New reference edges must leave affected persisted paths acyclic and at most ten hops long, including existing ancestors. A cycle or excess depth throws InvalidOperationException atomically. Existing deep or cyclic data stays readable; unchanged membership and removals allow repair. Default GetById and ordinary query loading retain their existing eleven-hop boundary, distinct from the ten-hop new-write and query-navigation limits.

Saves outside a transaction use last-writer-wins, without stale-write detection or merging. For a loaded DBRefMany, Update and ReplaceOne apply the additions and removals you made, and Clear replaces the whole set; ReplaceMany, upserts and file-reference replacements use the membership you submit. Reload after a failed save before retrying. Uniqueness and delete policies apply per property, so two properties may target the same type with different policies.

Relation Queries Expanded in v1.2.0

This section covers relation queries, including DBRefMany, GroupJoin, left joins, and relation-query indexing.

Querying Relations Since v1.1

By default, SoloDB loads referenced documents when it reads a query result. You can also filter and project through relations directly in LINQ:

// Filter by referenced entity's Id
var aliceLoans = loans.Where(l => l.Borrower.Id == aliceId).ToList();

// Filter by DBRefMany content
var taggedArticles = articles.Where(a =>
    a.Tags.Any(t => t.Label == "News")
).ToList();

Include and Exclude

Include and Exclude control which relations are loaded. They do not change which relation predicates SoloDB can translate.

  • Include limits loading to the selected relations.
  • Exclude leaves the relation id available but does not fill Value.
  • The same relation cannot appear in both Include and Exclude.

DBRefMany LINQ Since v1.2.0

DBRefMany queries listed below are translated to SQL. Unsupported queries stop immediately with an error instead of running part of the work in memory.

Example models used below

public class Container
{
    public long Id { get; set; }
    public string Label { get; set; }
    public DBRefMany<Item> Items { get; set; } = new();
}

public class Item
{
    public long Id { get; set; }
    public string Name { get; set; }
    public bool Active { get; set; }
    public int Score { get; set; }
}

DBRefMany operator reference

OperatorStatusNotes
WhereSupported
Any, AllSupportedWith or without predicate
Count, LongCountSupportedWith or without predicate
Sum, AverageSupportedSelector required
Min, MaxSupportedSelector required
OrderBy, OrderByDescendingSupported
ThenBy, ThenByDescendingSupported
Take, SkipRequires orderingAdd OrderBy before these
First, FirstOrDefaultRequires orderingAdd OrderBy for deterministic results
Last, LastOrDefaultRequires orderingAdd OrderBy for deterministic results
Single, SingleOrDefaultSupported
ElementAt, ElementAtOrDefaultRequires orderingAdd OrderBy before these
TakeWhile, SkipWhileRequires orderingAdd OrderBy before these
SelectSupportedInto scalars or anonymous types
SelectManySupportedInside Select projection; supports inner Where, Select, OfType
Distinct, DistinctBySupported
UnionBy, IntersectBy, ExceptBySupported
GroupBySupportedWith aggregate operators such as Count, Sum, Min, Max, and Average
CountBySupported
ContainsSupportedOn scalar projections
DefaultIfEmptySupported
OfTypeSupportedFor polymorphic targets; filters by the exact stored type
CastSupportedChanges the element type without filtering
AggregateRejectedCannot translate custom folds to SQL
Zip, ReverseRejectedNo SQL equivalent
Append, PrependRejectedNo SQL equivalent
SequenceEqualRejectedNo SQL equivalent

Nested relation queries

Supported nested relation queries are translated to a single SQLite statement with correlated subqueries.

// Three hops: Order -> OrderLine (DBRefMany) -> Product (DBRef) -> Tags (DBRefMany)
var flagged = orders
    .Where(o => o.Lines.Any(line =>
        line.Product.Value.Tags.Any(t => t.Label == "hazardous")))
    .ToList();

Nested relation queries can follow up to 10 relation hops; a deeper query is rejected before it runs. Saving new references has its own depth rule, described under reference mutation and concurrency.

Error: Relation chain is too deep or circular (depth > 10).
Reason: The query exceeds the supported relation traversal depth.
Fix: Reduce relation depth or split the query into multiple steps.

Filtered aggregate example

// Find containers where the average score of active items exceeds 20
var highScoring = containers
    .Where(c => c.Items.Where(i => i.Active).Average(i => i.Score) > 20)
    .ToList();

// Count and project in one pass
var summary = containers
    .Select(c => new { c.Label, Total = c.Items.Count(), ActiveCount = c.Items.Count(i => i.Active) })
    .ToList();

Ordering and boundary operators

DBRefMany<T> does not define a stable element order. Use explicit ordering for deterministic results with boundary-sensitive operators such as First, Last, Take, and Skip. TakeWhile and SkipWhile require explicit ordering.

// Wrap the nested projection so the ordered subset stays addressable in C#
var topThree = containers
    .Where(c => c.Label == "main")
    .Select(c => new
    {
        Names = c.Items.OrderByDescending(i => i.Score).Take(3).Select(i => i.Name)
    })
    .Single()
    .Names
    .ToArray();
// Ordered TakeWhile and SkipWhile are supported
var middleBand = containers
    .Select(c => new
    {
        Names = c.Items
            .OrderBy(i => i.Score)
            .SkipWhile(i => i.Score < 10)
            .TakeWhile(i => i.Score <= 50)
            .Select(i => i.Name)
    })
    .ToList();

Without an explicit order, TakeWhile and SkipWhile are rejected with InvalidOperationException.

SelectMany inside a projection

This SelectMany form is supported:

public class Portfolio
{
    public long Id { get; set; }
    public DBRefMany<Book> Books { get; set; } = new();
}

public class Book
{
    public long Id { get; set; }
    public DBRefMany<OptionLeg> Legs { get; set; } = new();
}

public abstract class OptionLeg
{
    public long Id { get; set; }
}

public sealed class ProjectionOptionLeg : OptionLeg
{
    public decimal Strike { get; set; }
}

var legCounts = portfolios
    .Select(p => new
    {
        p.Id,
        ProjectionLegCount = p.Books.SelectMany(b => b.Legs.OfType<ProjectionOptionLeg>()).Count()
    })
    .ToList();

This example is supported. Other projection-local SelectMany queries may not be. The OfType<ProjectionOptionLeg>() filter matches the exact stored type discriminator.

Compatibility notes

  • F# option<DBRef<_>> and option<DBRefMany<_>> are not supported and are rejected at schema build time.

GroupJoin and Left Joins Since v1.2.0

SoloDB 1.2.0 supports grouped GroupJoin queries and the usual GroupJoin + SelectMany + DefaultIfEmpty left-join pattern. Grouped aggregates such as Count, Sum, Min, Max, and Average are translated to SQL aggregate functions.

Grouped aggregate example

// For each event, count tickets and sum VIP revenue
var summary = events.AsQueryable()
    .GroupJoin(
        tickets.AsQueryable(),
        e => e.Id,
        t => t.EventId,
        (e, group) => new
        {
            e.Title,
            TicketCount = group.Count(),
            VipRevenue = group.Where(t => t.Tier == "vip").Sum(t => t.Price)
        })
    .OrderBy(x => x.Title)
    .ToList();

Events with no matching tickets produce TicketCount = 0 and VipRevenue = 0, not a missing row. The GroupJoin + SelectMany + DefaultIfEmpty left-join pattern also translates to SQL LEFT JOIN.

Indexing Relations Since v1.1

You can index DBRef.Id to speed up queries that filter by foreign key. This creates an index on the JSON-extracted reference Id stored in the owner document, which is separate from the link table's internal indexes.

Owner-Side Index (DBRef.Id)

When you write a LINQ query filtering on a DBRef Id, SoloDB translates it to a jsonb_extract filter on the owner table:

// LINQ query:
var aliceLoans = loans.Where(l => l.Borrower.Id == aliceId).ToList();

// Translates to SQL:
// SELECT ... FROM Loan WHERE jsonb_extract(Value, '$.Borrower') = @p0

// Without an index: SQLite scans every row, extracting the JSON field per row.
// With an index: SQLite uses the expression index for direct lookup.

// Create the index:
loans.EnsureIndex(l => l.Borrower.Id);

// Composite index - useful for filtering by reference + another field:
loans.EnsureIndex(l => new ValueTuple<long, decimal>(l.Borrower.Id, l.Amount));

C# expression trees do not support tuple literal syntax. Composite index expressions must use the ValueTuple constructor form as shown above. In F#, the equivalent tuple syntax (u.Field1, u.Field2) works directly.

To confirm that a query uses the index, inspect it with SoloDB.ExplainQueryPlan(query).

Target-Side Queries

Queries that navigate through DBRef.Value or filter DBRefMany content resolve through JOIN or EXISTS subqueries against the link and target tables. Index the target collection instead:

// This query JOINs through the link table to the Person table:
var aliceLoans = loans.Where(l => l.Borrower.Value.Name == "Alice").ToList();
// Index the TARGET: people.EnsureIndex(p => p.Name);

// DBRefMany queries use EXISTS subqueries:
var tagged = articles.Where(a => a.Tags.Any(t => t.Label == "News")).ToList();
// Index the TARGET: tags.EnsureIndex(t => t.Label);

What Cannot Be Indexed

SoloDB rejects index expressions that navigate through relations at build time:

EnsureIndex(l => l.Borrower.Value.Name)Rejected - navigates through DBRef.Value (resolves via JOIN)
EnsureIndex(a => a.Tags.Count)Rejected - DBRefMany properties resolve through link tables

Owner-side DBRef.Id indexes are not redundant with the link table's SourceId/TargetId indexes. They help different queries: the owner-side index speeds up filtering on the owner collection's JSON field, while link table indexes speed up JOIN traversals.

File Storage

SoloDB includes a hierarchical file system stored in the same database. Files are split into 16 KB chunks and compressed with Snappy. This gives you:

  • Partial reads - Read only what you need without loading the entire file
  • Sparse file support - Write at any offset; unwritten areas don't consume space
  • Automatic compression - Snappy compression reduces storage size
  • Transactional safety - File operations participate in database transactions
  • Metadata support - Attach key-value metadata to files and directories

To link a document to a file, store a FileRef in it. To keep another SoloDB database inside these files, see nested storage.

Accessing the FileSystem

var fs = db.FileSystem;

Upload and Download

SoloDB normalizes slash direction and adds the leading / if you omit it. Names are case-sensitive, and Unicode names are supported.

// Upload from a stream
using (var stream = File.OpenRead("report.pdf"))
{
    fs.Upload("/documents/reports/2024-q4.pdf", stream);
}

// Download to a stream
using (var output = File.Create("downloaded.pdf"))
{
    fs.Download("/documents/reports/2024-q4.pdf", output);
}

// Check existence and delete
bool exists = fs.Exists("/documents/reports/2024-q4.pdf");
fs.DeleteFileAt("/documents/reports/2024-q4.pdf");

SoloDB sets no limit of its own on file size or metadata; the SQLite database size and your available storage do.

Outside an explicit transaction, Download and DownloadAsync do not hold a writer lock or a snapshot for the whole transfer. If an upload commits during a download, different reads may observe different file versions. Coordinate the operations or use an explicit transaction when one consistent view is required.

Stream-Based Access (Like File.Open)

The OpenOrCreateAt method returns a standard Stream that works just like File.Open(). You can use it with any .NET stream API:

// Compare: System.IO file access
using (var fileStream = File.Open("local.txt", FileMode.OpenOrCreate))
{
    fileStream.Write(data, 0, data.Length);
    fileStream.Position = 0;
    fileStream.Read(buffer, 0, buffer.Length);
}

// SoloDB file access - same API!
using (var fileStream = fs.OpenOrCreateAt("/data/log.txt"))
{
    fileStream.Write(data, 0, data.Length);
    fileStream.Position = 0;
    fileStream.Read(buffer, 0, buffer.Length);
}

Works with StreamReader/StreamWriter too:

// Write text
using (var stream = fs.OpenOrCreateAt("/logs/app.log"))
using (var writer = new StreamWriter(stream))
{
    writer.WriteLine($"[{DateTime.UtcNow}] Application started");
    writer.WriteLine($"[{DateTime.UtcNow}] Processing...");
}

// Read text
using (var stream = fs.OpenOrCreateAt("/logs/app.log"))
using (var reader = new StreamReader(stream))
{
    string contents = reader.ReadToEnd();
}

Random Access (Partial Reads/Writes)

Unlike document storage, FileSystem supports efficient partial access:

// Write at specific offset (creates sparse file if needed)
byte[] data = GetSomeData();
fs.WriteAt("/data/sparse.bin", 1024 * 1024, data);  // Write at 1MB offset

// Read from specific offset - doesn't load entire file
byte[] chunk = fs.ReadAt("/data/sparse.bin", 1024 * 1024, data.Length);

// Sparse files: unwritten areas read as zeros, don't consume storage
fs.WriteAt("/sparse.dat", 10_000_000, new byte[] { 1, 2, 3 });  // 10MB offset
// File is NOT 10MB on disk - only the written chunks are stored

File and Directory Metadata

// Set file metadata (key-value pairs)
fs.SetMetadata("/documents/report.pdf", "Author", "Finance Team");
fs.SetMetadata("/documents/report.pdf", "Department", "Accounting");

// Read file info with metadata
var fileInfo = fs.GetAt("/documents/report.pdf");
Console.WriteLine($"Name: {fileInfo.Name}");
Console.WriteLine($"Size: {fileInfo.Length} bytes");
Console.WriteLine($"Created: {fileInfo.Created}");
Console.WriteLine($"Modified: {fileInfo.Modified}");
Console.WriteLine($"Author: {fileInfo.Metadata["Author"]}");

// Delete specific metadata
fs.DeleteMetadata(fileInfo, "Department");

// Directory metadata works the same way
var dir = fs.GetOrCreateDirAt("/documents/archive");
fs.SetDirectoryMetadata(dir, "RetentionPolicy", "7years");
fs.DeleteDirectoryMetadata(dir, "RetentionPolicy");

Directory Operations

// Create directory (creates parent directories automatically)
var dir = fs.GetOrCreateDirAt("/documents/archive/2024");

// Get directory info
var dirInfo = fs.GetDirAt("/documents/archive");

// List files in a directory
var files = fs.ListFilesAt("/documents/reports/");

// List subdirectories
var dirs = fs.ListDirectoriesAt("/documents/");

// Recursive listing (files and directories)
var allEntries = fs.RecursiveListEntriesAt("/documents/");

// Lazy recursive listing (memory efficient for large trees)
var lazyEntries = fs.RecursiveListEntriesAtLazy("/");

// Delete directory (must be empty)
fs.DeleteDirAt("/documents/old");

Move and Rename Files

// Move/rename a file (throws IOException if destination exists)
fs.MoveFile("/documents/draft.pdf", "/documents/final.pdf");

// Move to different directory
fs.MoveFile("/inbox/file.txt", "/archive/2024/file.txt");

// Move and replace if exists
fs.MoveReplaceFile("/temp/new.pdf", "/documents/report.pdf");

Bulk Upload

UploadBulk writes many files in one transaction. Here imageBytes stands for your own image content:

using System.Text;
using SoloDatabase.Types;

var files = new List<BulkFileData>
{
    new("/logs/app1.log", Encoding.UTF8.GetBytes("Log data 1"), null, null),
    new("/logs/app2.log", Encoding.UTF8.GetBytes("Log data 2"), null, null),
    new("/images/logo.png", imageBytes, DateTimeOffset.UtcNow, null)
};

fs.UploadBulk(files);  // Single transaction for all files

File Timestamps

Files and directories track Created and Modified timestamps. The Modified timestamp is automatically updated whenever you write to a file or upload new content:

// Modified is automatically updated on writes
fs.WriteAt("/data/file.bin", 0, data);  // Modified = now
fs.Upload("/data/file.bin", stream);     // Modified = now

// Manually set timestamps when needed
fs.SetFileCreationDate("/archive/old.txt", DateTimeOffset.UtcNow.AddYears(-1));
fs.SetFileModificationDate("/archive/old.txt", DateTimeOffset.UtcNow.AddDays(-30));

// Read timestamps from file info
var info = fs.GetAt("/archive/old.txt");
Console.WriteLine($"Created: {info.Created}");
Console.WriteLine($"Modified: {info.Modified}");

Filesystem events v1.4

db.FileSystem registers before/after file and directory creation, deletion and header updates, metadata changes and logical content changes. Registrations cover root, transaction and callback-context operations of the same database.

using SoloDatabase;

using var db = new SoloDB("memory:file-events");
FileContentChangedHandler written = context => {
    System.Console.WriteLine($"{context.Path}: {context.Kind}, {context.Length} bytes");
    return SoloDBEventsResult.EventHandled;
};
db.FileSystem.OnFileContentChanged(written);
using (var file = db.FileSystem.OpenOrCreateAt("/report")) {
    file.Write(new byte[] { 1, 2, 3 }, 0, 3);
}
db.FileSystem.Unregister(written);

OnFileCreated handlers run right after the file entry is created, before content is written and before the transaction commits. Content events report the changed range as Offset and Length, plus the old and new file length; empty writes raise none. The filesystem events guide lists every event.

Paths follow current identity; a stream FullPath retains its opening path after a move. Metadata null means absence, while an empty string is present. Use borrowed contexts only during the callback, on its thread; do not retain contexts or their adapters. After-events are not commit notifications. Throwing or a caught callback-side database fault can veto commit; external side effects cannot be rolled back. Return RemoveHandler to self-remove; do not call Unregister inside a handler.

File and directory references v1.4

FileRef, DirectoryRef and their Many forms reference existing headers in the same database. Targets and protecting ancestors cannot be deleted or replaced until references are removed. Document deletion/drop unlinks and preserves the files. Loaded Value is a header/metadata snapshot without file bytes or a live connection.

using SoloDatabase;

internal sealed class Report
{
    public long Id { get; set; }
    public FileRef MainFile { get; set; }
    public FileRefMany Attachments { get; set; } = new();
}

internal static class Program
{
    private static void Main()
    {
        using var db = new SoloDB("memory:reports");
        var file = FileRef.From(db.FileSystem.GetOrCreateAt("/main.txt"));
        var reports = db.GetCollection<Report>();
        var report = new Report { MainFile = file };
        report.Attachments.Add(file);
        long id = reports.Insert(report);
        reports.UpdateMany(r => r.Id == id, r => r.Attachments.Clear());
        reports.UpdateMany(r => r.Id == id, r => r.MainFile.Set(FileRef.None));
    }
}

FileRef.To(id) references a file by its header Id, FileRef.From(header) uses a header you already have, and FileRef.None is empty. Add, Remove and Clear take references, not paths; save the change with Update or UpdateMany. A Many reference is an unordered set, and two references are equal when they point to the same file or directory. A loaded reference holds a snapshot of the header, so query again after a move. See the filesystem references guide.

Compiled queries Since v1.3

Compile a frequently used query once, then call it with new values. SoloDB keeps the translation; every call reads current rows.

using System.Linq;
using SoloDatabase;

using var db = new SoloDB("memory:compiled-example");
var numbers = db.GetCollection<int>();
numbers.Insert(7);
var count = numbers.Compile((IQueryable<int> query, int minimum) => query.Count(value => value >= minimum));
System.Console.WriteLine(count(5));
  • Compile from a nontransactional collection and keep the returned function alive. Reuse the function, not its result rows.
  • Supply zero through three invocation arguments; Select can change the result type.
  • A sequence query returns a function whose results read current rows each time you enumerate them. A scalar query, or one ending in ToArray, runs when you call the function.
  • Recompile after model or index changes, or to use refreshed statistics; retained plans do not watch the schema.

F# NativeAOT uses the whole-query CompileQuotation workflow. To compile inside a transaction, see Compile within a transaction.

Compose more query expressions v1.4.2

Computed array/list indexes, dictionary keys, composite joins, local values and date/time expressions can run inside SQLite. Use the following setup for the C# fragments in this section:

using System;
using System.Collections.Generic;
using System.Linq;
using SoloDatabase;

using var db = new SoloDB("memory:query-examples");
var rows = db.GetCollection<QueryRow>("rows");
rows.Insert(new QueryRow {
    Group = 2, Title = "alpha", Amount = 7,
    Numbers = new[] { 10, 20 }, Position = 1,
    Labels = new Dictionary<string, string> { ["colour"] = "blue" }, Key = "colour",
    Clock = new DateTime(2026, 1, 2, 13, 30, 0, DateTimeKind.Unspecified),
    Offset = TimeSpan.FromHours(2)
});

public sealed class QueryRow
{
    public long Id { get; set; }
    public int Group { get; set; }
    public string Title { get; set; } = "";
    public int Amount { get; set; }
    public int[] Numbers { get; set; } = Array.Empty<int>();
    public int Position { get; set; }
    public Dictionary<string, string> Labels { get; set; } = new();
    public string Key { get; set; } = "";
    public DateTime Clock { get; set; }
    public TimeSpan Offset { get; set; }
}

Computed indexes and dictionary keys

var chosen = rows.Select(row => new {
    Number = row.Numbers[row.Position],
    Label = row.Labels[row.Key]
}).ToArray();

var at = rows.Compile<int, int>((source, index) =>
    source.Select(row => row.Numbers[index]));
var first = at(0).ToArray();
var second = at(1).ToArray();

Indexes and keys can come from the row, a captured value or a retained argument. Invalid consumed indexes and missing dictionary keys raise errors; they do not silently become defaults. An unconsumed conditional branch does not access its invalid index. Stored value representations remain intact, including byte sequences and supported numeric dictionary keys.

Composite joins and local values

var other = db.GetCollection<QueryRow>("other_rows");
other.Insert(new QueryRow { Group = 2, Title = "alpha", Amount = 13 });
var totals = rows.Join(other,
    left => new { left.Group, left.Title },
    right => new { right.Group, right.Title },
    (left, right) => left.Amount + right.Amount).ToArray();

var adjustments = new[] { new QueryRow { Group = 2, Amount = 100 } };
var adjusted = rows.Join(adjustments,
    row => row.Group, adjustment => adjustment.Group,
    (row, adjustment) => row.Amount + adjustment.Amount).ToArray();
var appended = rows.Select(row => row.Title)
    .Concat(new[] { "local-only", "local-only" }).ToArray();

Composite keys preserve component equality, precision and null behavior. Grouped left joins can retain both their group and outer values. Local sequences bind as rows, with Concat preserving duplicates; retained queries acquire fresh enumerable values on invocation. A query from another database cannot use the local side to bypass database ownership.

Nested DBRefMany Where, OrderBy, Take, Skip and supported SelectMany compositions retain their correlation and bounds. The existing relation depth and cycle rules remain. Unordered relations have no stable element order; add OrderBy before selecting a particular page.

Dates, durations, formatting and parsing

var dates = rows.Select(row => new {
    row.Clock.Ticks,
    row.Clock.Kind,
    Day = row.Clock.Date,
    Time = row.Clock.TimeOfDay,
    LocalText = new DateTimeOffset(row.Clock, row.Offset)
        .ToString("yyyy-MM-dd HH:mm:ss zzz")
}).ToArray();

var format = rows.Compile<string, string>((source, pattern) =>
    source.Select(row => row.Clock.ToString(pattern)));
var months = format("yyyy-MM").ToArray();

var parse = rows.Compile<string, DateTime>((source, text) =>
    source.Select(row => DateTime.Parse(text)));
var parsed = parse("2026-01-02").ToArray();

DateTime constructors accept literal, captured, row-derived and retained DateTimeKind arguments. String formats can be supplied at execution for DateTime, DateTimeOffset, DateOnly, TimeOnly and TimeSpan. Formatting uses the established invariant-culture policy; single-string Parse uses the corresponding .NET parser and execution-time culture, preserving its errors.

Persistence still stores DateTimeOffset as UTC milliseconds, discarding its original offset. Store an offset separately when it matters. TimeOnly and TimeSpan retain millisecond storage. A directly constructed offset value can use its available offset during the query. See the temporal query guide for representation and precision details.

Supported comparer overloads

var ordered = rows.OrderBy(row => row.Title, StringComparer.Ordinal)
    .Select(row => row.Title).ToArray();
var distinct = rows.Select(row => row.Title)
    .Distinct(EqualityComparer<string>.Default).ToArray();
var smallest = rows.Select(row => row.Title).Min(StringComparer.Ordinal);

Supported equality overloads accept default equality or null, with ordinal string equality also available. Explicit string ordering supports Comparer<string>.Default and StringComparer.Ordinal, including scalar Min/Max. Retained queries bind captured comparer choices on invocation. Arbitrary custom comparers and StringComparer.OrdinalIgnoreCase are unsupported inside SQLite. Normalize a supported key or deliberately use AsEnumerable() for CLR execution.

Compile within a transaction

db.WithTransaction(tx => {
    var transactional = tx.GetCollection<QueryRow>("rows");
    var count = transactional.Compile(source => source.LongCount());
    Console.WriteLine(count());
});

Compile and consume results while the transaction callback is alive. A retained query or lazy result does not extend a completed transaction. Captured expression bodies stay fixed at compilation while their scalar captures bind on invocation; arbitrary opaque CLR delegates are not silently executed as database predicates.

Generated operations and NativeAOT v1.4

To generate operations, build with .NET SDK 8 or later. The SoloDB 1.4 package includes its C# source generator, F# type provider and build integration. Keep package build assets enabled; no separate generator package or manual model rewrite is needed. Generated operations use your original types, including private models, without requiring partial model declarations.

C# registration

To use generated operations, call SoloDBAOT.Register() before using SoloDB. Here, GetCollection<Person>() identifies the model to generate:

using System;
using SoloDatabase;

internal sealed class Person
{
    public long Id { get; set; }
    public string Name { get; set; } = "";
}

internal static class Program
{
    private static void Main()
    {
#if !DEBUG
        SoloDBAOT.Register();
#endif
        using var db = new SoloDB("memory:people");
        var people = db.GetCollection<Person>();
        long id = people.Insert(new Person { Name = "Ada" });
        Console.WriteLine(people.GetById(id).Name);
    }
}

Activation and deployment

The #if !DEBUG guards in these examples keep generation out of Debug builds, so those builds pay no code-generation cost. SoloDB uses runtime discovery there. Release builds include generated operations for NativeAOT.

In F#, guard both the provider alias and its registration call. Remove the guards if you want generated operations in Debug too.

Publish a NativeAOT application

Keep registration enabled when publishing. Start with the C# example above or the F# example below.

Set the standard SDK property in your executable project file:

<PropertyGroup>
  <PublishAot Condition="'$(Configuration)' == 'Release'">true</PublishAot>
</PropertyGroup>

This enables NativeAOT for Release builds. Keep the setting in the executable project, even when your models live in a .NET Standard library. Then publish, for example on Linux x64:

dotnet publish -c Release -r linux-x64

Choose the runtime identifier for your target and install the SDK's NativeAOT platform prerequisites. The publish directory contains the application and its required native assets. For registration, supported types and application-specific requirements, see the full setup guide.

The package includes generated operations in normal build and publish output. When copying a managed build, keep its generated helper assembly beside the application.

Model closure and new query operations

F# query data and explicit model requests receive generated operations. Objects used only to build expressions or invoke callbacks do not become JSON models.

Search and supplied storage use the same registration. Recursive models work when their shape is finite, such as a node that contains another node of the same type. A shape that needs endlessly new types, such as Node<T> containing Node<List<T>>, reports diagnostic SOLO001. See the generated-metadata guide for details.

What the generated code looks like

For the Person model in the C# example above, a Release build writes the generated operations into app.SoloDB.Generated.dll, named after your assembly, beside the application. This is the core of its UTF-8 JSON writer for Person, decompiled with ILSpy from a SoloDB 1.4.2 build; // ... marks trimmed lines:

internal static void WriteMembersUtf80(ref global::Person P_0, ref Span<byte> P_1, ref SoloDatabase.JsonSerializator.JsonWriteState<byte> P_2)
{
    int minimum = checked(P_2.Written + 1);
    SoloDatabase.JsonSerializator.JsonWriterRegion.ReserveSpan<byte>(ref P_1, ref P_2, minimum);
    ref byte source = ref SoloDatabase.JsonSerializator.JsonWriterRegion.Start<byte>(ref P_1);
    int num = SoloDatabase.JsonSerializator.JsonWriterRegion.Position<byte>(ref P_2);
    Unsafe.Add(ref source, (uint)(num + 0)) = 123;
    SoloDatabase.JsonSerializator.JsonWriterRegion.Advance<byte>(ref P_2, 1);
    // ... reserve 5 bytes (or skip Id when the caller omits it)
    if (BitConverter.IsLittleEndian)
    {
        Unsafe.WriteUnaligned(ref Unsafe.Add(ref source2, (uint)(num2 + 0)), 576997666);
        Unsafe.Add(ref source2, (uint)(num2 + 4)) = 58;
    }
    // ... big-endian constants
    SoloDatabase.JsonSerializator.JsonWriterRegion.Advance<byte>(ref P_2, 5);
    WriteNumericUtf81(ref P_0.Id__BackingField, ref P_1, ref P_2);
    // ... reserve 8 bytes
    if (BitConverter.IsLittleEndian)
    {
        Unsafe.WriteUnaligned(ref Unsafe.Add(ref source3, (uint)(num3 + 0)), 1632510508);
        Unsafe.WriteUnaligned(ref Unsafe.Add(ref source3, (uint)(num3 + 4)), 975332717);
    }
    // ... big-endian constants
    SoloDatabase.JsonSerializator.JsonWriterRegion.Advance<byte>(ref P_2, 8);
    WriteStringUtf82(ref P_0.Name__BackingField, ref P_1, ref P_2);
    // ... optional ,"$type": for polymorphic writes, then "}" written like "{"
}

Property names are written as constant bytes instead of being formatted at run time: 123 is {, 576997666 is "Id" in little-endian byte order, 58 is :, and 1632510508 followed by 975332717 is ,"Name":. Big-endian machines get their own constants, and polymorphic writes add ,"$type":. WriteNumericUtf81 and WriteStringUtf82 are further generated helpers. Each model gets writers and readers like this for UTF-8 and UTF-16, so a NativeAOT build converts typed JSON without generating code at run time.

F# NativeAOT queries v1.4

Declare the provider alias, register, then pass an ordinary whole-query lambda to CompileQuotation:

namespace Example

open System
open System.Linq
open SoloDatabase

type Person() =
    member val Id = 0L with get, set
    member val Name = "" with get, set

#if !DEBUG
type AOTSupport = SoloDBAOT<0>
#endif

module Program =
    [<EntryPoint>]
    let main _ =
#if !DEBUG
        AOTSupport.register()
#endif
        use db = new SoloDB("memory:people")
        let people = db.GetCollection<Person>()
        people.Insert(Person(Name = "Ada")) |> ignore
        let count = people.CompileQuotation(fun query -> query.Count())
        let find = people.CompileQuotation(fun query (name: string) ->
            query.Where(fun person -> person.Name = name).ToArray())
        Console.WriteLine(count.Invoke())
        Console.WriteLine(find.Invoke("Ada").[0].Name)
        0

Use CompileQuotation for F# queries that will run under NativeAOT. Keep the whole query inside its lambda, including Where, OrderBy and Select. Ordinary F# lambda conversion is unsupported under NativeAOT; existing Compile calls continue to work in JIT applications. Then publish the application.

The package prepares unsigned F# union libraries for NativeAOT when needed. If the same preparation is required for a signed library, publishing stops with SOLO005. Other signed libraries remain supported. See the F# query guide for details.

Direct typed JSON v1.4

Use ParseInto and WriteJson to convert typed values directly to and from JSON text or bytes. They avoid building an intermediate JSON tree. Use Parse and Serialize when you want to inspect or edit a tree instead.

using System;
using SoloDatabase.JsonSerializator;

Span<byte> output = Span<byte>.Empty;
int[] source = { 1, 2, 3 };
int written = JsonValue.WriteJson(ref source, ref output);
ReadOnlySpan<byte> json = output.Slice(0, written);
int[] values = JsonValue.ParseInto<int[]>(json);
Console.WriteLine(values.Length);

This writes [1,2,3] as UTF-8 and prints 3. SoloDB grows the empty span with a managed array; use only the written prefix of the final span returned through ref output. Character spans use UTF-16, and list destinations append to their existing contents. Returned models own their data. Buffer growth, model construction and output copies can allocate.

Choosing an input and destination

Choose UTF-8 for byte-oriented interfaces and UTF-16 when you already have characters. To control allocation, supply a growth callback as shown in the buffer example and ownership reference. It explains capacity, matching release callbacks and which buffer you own after success or failure.

When reading an encoded Decimal or BigInteger string extracted from a document, select JsonReadOptions.StoredNumericStrings. Ordinary JSON numbers use the default reader. Follow the stored-number examples to choose the input's role.

Reading objects

Direct readers convert properties in input order. Every duplicate is converted, so an invalid earlier value still fails even if a later value would be valid. Constructors and setters can run before a later input error; their effects are not rolled back. See the duplicate-property example and reader rules for defaults, errors and runtime type selection.

JSON numbers

Typed integer and floating-point conversion avoids the Decimal-backed tree representation. Direct and tree output can therefore differ outside Decimal precision or range. Direct floating-point writers preserve negative zero as -0 and support the JSON5 literals NaN, Infinity and -Infinity. Read the number-format reference when those values matter to your application.

F# Option and Result v1.4

An option stores absence as JSON null and presence as the underlying value:

F# valueJSON
Nonenull
Some 77
Some "Ada""Ada"

This simple format cannot preserve every layer of presence. Both Some null and Some None write null, which reads back as None. Use an explicit model if your application must distinguish those states.

Result keeps its case and payload in an object. For example, Ok 7 uses Tag, IsOk, IsError, ResultValue and ErrorValue; Error null still retains the Error case. See the complete JSON examples.

Readers also accept the older HasValue/Value option wrapper, with distinct input precedence and presence rules. Option conversion does not enable option-wrapped relation properties: option<DBRef<_>> and option<DBRefMany<_>> remain unsupported. Use the reference types and their empty-reference states; see relation guidance.

Decimal and BigInteger storage v1.4

Declare decimal and System.Numerics.BigInteger properties as usual. SoloDB keeps their exact values, and typed queries compare, sort and calculate with them inside SQLite:

using System;
using System.Linq;
using System.Numerics;
using SoloDatabase;

using var db = new SoloDB("memory:ledger");
var entries = db.GetCollection<LedgerEntry>();
entries.Insert(new LedgerEntry { Amount = 12.5m, Units = BigInteger.Pow(10, 30) });
entries.Insert(new LedgerEntry { Amount = 0.1m, Units = 7 });

var large = entries.Where(e => e.Amount > 1m).OrderBy(e => e.Amount).ToList();
decimal total = entries.Sum(e => e.Amount);
Console.WriteLine($"{large.Count} entry above 1, total {total}"); // 1 entry above 1, total 12.6

public sealed class LedgerEntry
{
    public long Id { get; set; }
    public decimal Amount { get; set; }
    public BigInteger Units { get; set; }
}

Databases written by SoloDB 1.3 or earlier need a one-time conversion of these fields.

Inside the database the values are stored as encoded text that SQLite compares exactly. Storage keeps the number, not Decimal's trailing zeros, so 12.50m reads back as 12.5m. Typed collections convert in both directions, and WriteJson still writes ordinary JSON numbers. Raw SQL and untyped collections see the encoded text: write these fields through typed collections, and see reading stored numbers from raw SQL when you read them directly.

Format numerical query results

Parameterless ToString() on a Decimal or BigInteger runs inside the query and formats the exact value with the current culture, as .NET does. This continues the entries example above:

var labels = entries.Select(e => e.Amount.ToString()).ToList(); // "12.5", "0.1" with en-US

The culture is read when the query runs, so a compiled query uses the culture of each call. This applies to parameterless ToString(); overloads with a format or provider are not covered by it. String concatenation and JSON output keep invariant number text.

Convert numbers saved by SoloDB 1.3 or earlier

Databases created by SoloDB 1.4 or later need nothing here. If a collection has Decimal or BigInteger fields written by SoloDB 1.3 or earlier, convert them once before reading those fields. Opening the database upgrades its schema automatically, but it does not convert numerical values; after that first open, SoloDB 1.3 can no longer open the database, so stop applications that still use 1.3 first. This call converts the values:

using SoloDatabase;

using var db = new SoloDB("app.db");

// Converts the Decimal and BigInteger fields of the "Invoice" collection.
db.MigrateDecimal<Invoice>();

// An existing collection with its own name:
db.MigrateDecimal<Invoice>("ArchivedInvoices");

public sealed class Invoice
{
    public long Id { get; set; }
    public decimal Amount { get; set; }
}
  • One call converts both the Decimal and the BigInteger fields that the model declares.
  • Each call is atomic. If it fails, the original values stay unchanged. Inside WithTransaction it uses a savepoint of that transaction.
  • Calling it again on a converted collection leaves the converted fields as they are.
  • A missing collection raises KeyNotFoundException; migration does not create collections.
  • Text values count as already converted. If raw SQL or untyped code stored quoted numeric strings in these fields, convert them with SoloDB 1.3 typed reads and writes before the first open with 1.4; otherwise they can produce wrong values or conversion errors.
  • Run it before your event handlers use the collection. It cannot run inside a handler, where an active statement prevents its savepoint.

The call checks the first non-null value of each numerical field and converts the field when that value is still a JSON number. Numerical fields that only appear in later subtypes can need an explicit migration model; the numerical migration guide shows how.

Read stored numbers from raw SQL

Typed collection reads already return native decimal and BigInteger values. You need these APIs only when raw SQL, an untyped collection or extracted JSON gives you the stored text.

Read an extracted numerical value

Choose the API for the input you have:

Unquoted key, such as d-SStoredNumeric.DecodeDecimal or DecodeBigInteger
JSON String token, such as "d-S"JsonValue.ParseInto<T> or a tree's ToObject, with JsonReadOptions.StoredNumericStrings
SQL TEXT resultQuery<T>, QueryFirst<T> or QueryFirstOrDefault<T>, with NumericStringFormat.StoredKey after SQL
using System;
using System.Numerics;
using SoloDatabase;
using SoloDatabase.JsonSerializator;

decimal amount = StoredNumeric.DecodeDecimal("d-S"); // 12.5
BigInteger whole = StoredNumeric.DecodeBigInteger("d-S"); // 12
bool valid = StoredNumeric.TryDecodeDecimal("d-S".AsSpan(), out amount);

var options = JsonReadOptions.StoredNumericStrings;
decimal fromJson = JsonValue.ParseInto<decimal>("\"d-S\"", options); // 12.5
decimal fromTree = JsonValue.Parse("\"d-S\"").ToObject<decimal>(options); // 12.5

// Ordinary numerical text and stored keys overlap. Select the input format.
decimal ordinary = JsonValue.ParseInto<decimal>("\"11\""); // 11
decimal encoded = JsonValue.ParseInto<decimal>("\"11\"", options); // -84000000000000
string unchanged = JsonValue.ParseInto<string>("\"d-S\"", options); // d-S
decimal number = JsonValue.ParseInto<decimal>("12.5", options); // 12.5

Malformed keys raise FormatException and Decimal overflow raises OverflowException; the TryDecode methods return false instead. The JSON options only affect strings converted to Decimal or BigInteger, and SoloDB never guesses between a stored key and ordinary numeric text. The stored-number guide lists the rounding and range rules.

open SoloDatabase
open SoloDatabase.JsonSerializator

let options = JsonReadOptions.StoredNumericStrings
let amount = JsonValue.ParseInto<decimal>("\"d-S\"", options) // 12.5M
let decoded = StoredNumeric.DecodeDecimal("d-S") // 12.5M

Read encoded SQL TEXT

using System.Numerics;
using SoloDatabase;
using SoloDatabase.JsonSerializator;
using static SoloDatabase.NativeSQLiteTools.IDbConnectionExtensions;

using var connection = new NativeSqliteConnection("Data Source=:memory:");
connection.Open();
var keys = NumericStringFormat.StoredKey;
decimal amount = connection.QueryFirst<decimal>("SELECT 'd-S'", keys); // 12.5
BigInteger wide = connection.QueryFirst<BigInteger>("SELECT 'x!5!'", keys); // 10^40
decimal ordinary = connection.QueryFirst<decimal>("SELECT '11'"); // 11
decimal encoded = connection.QueryFirst<decimal>("SELECT '11'", keys); // -84000000000000
var values = connection.Query<decimal>("SELECT @value", keys,
    parameters: new { value = "d-S" }); // converts when enumerated

The same format applies to model members, tuples, nullable values and multi-map queries. For native rows use rows.Row.GetDecimal(ordinal, keys) or GetBigInteger(ordinal, keys); through a standard data reader, decode reader.GetString(ordinal) with StoredNumeric.

Extract a stored document leaf

This complete example stores a typed amount, extracts its encoded String, and reads the same SQL result directly as Decimal:

using SoloDatabase;
using SoloDatabase.JsonSerializator;
using static SoloDatabase.SQLiteTools.IDbConnectionExtensions;

using var db = new SoloDB("memory:invoices");
var invoices = db.GetCollection<Invoice>();
invoices.Insert(new Invoice { Amount = 12.5m });
using var connection = db.Connection.Borrow();
const string sql = "SELECT jsonb_extract(Value, '$.Amount') FROM Invoice";
string key = connection.QueryFirst<string>(sql); // d-S
decimal decoded = StoredNumeric.DecodeDecimal(key); // 12.5
decimal mapped = connection.QueryFirst<decimal>(sql, NumericStringFormat.StoredKey); // 12.5

public sealed class Invoice
{
    public long Id { get; set; }
    public decimal Amount { get; set; }
}

Direct SQL and ADO access v1.4

Use direct SQL alongside document collections through the same SoloDB package. To run SQL against your database, borrow one of its connections:

using SoloDatabase;
using static SoloDatabase.SQLiteTools.IDbConnectionExtensions;

using var db = new SoloDB("memory:notes");
db.GetCollection<Note>().Insert(new Note { Text = "hello" });

using (var connection = db.Connection.Borrow())
{
    long count = connection.QueryFirst<long>("SELECT COUNT(*) FROM Note");
    string text = connection.QueryFirst<string>(
        "SELECT jsonb_extract(Value, '$.Text') FROM Note WHERE Id = @id", new { id = 1L });
    System.Console.WriteLine($"{count}: {text}"); // 1: hello
}

public sealed class Note
{
    public long Id { get; set; }
    public string Text { get; set; } = "";
}

Native and ADO.NET connections share the configured SQLitePCL engine. Register generated operations for NativeAOT; the same SQL calls supply argument capture and typed row mapping.

SoloDB has two connection types because they serve different callers. db.Connection.Borrow() lends a connection of your open database as an ADO.NET SqliteConnection. It already has SoloDB's setup, so use it for raw SQL against your collections and with code written for ADO.NET. NativeSqliteConnection talks to SQLite directly, without the ADO.NET layer; use it for a separate SQLite database, as below. Each type has its own Execute and Query extension methods: import SoloDatabase.SQLiteTools.IDbConnectionExtensions for borrowed connections and SoloDatabase.NativeSQLiteTools.IDbConnectionExtensions for native ones.

using SoloDatabase;
using static SoloDatabase.NativeSQLiteTools.IDbConnectionExtensions;

using var connection = new NativeSqliteConnection("Data Source=:memory:");
connection.Open();
connection.Execute("CREATE TABLE Notes(Value TEXT UNIQUE)");
connection.Execute("INSERT INTO Notes VALUES(@value)", new { value = "hello" });
System.Console.WriteLine(connection.QueryFirst<string>("SELECT Value FROM Notes"));
try {
    connection.Execute("INSERT INTO Notes VALUES(@value)", new { value = "hello" });
} catch (NativeSqliteException error) when (error.SqliteExtendedErrorCode == 2067) { // SQLITE_CONSTRAINT_UNIQUE
    System.Console.WriteLine("Duplicate value");
}

The same SoloDB package includes a limited ADO.NET emulation in SoloDatabase.Data.Sqlite; no extra provider package or wrapper is required. Stored procedures and output parameters are unsupported. Async entry points perform synchronous SQLite work, and Cancel() does not interrupt execution.

Raw SQL uses SQLite's native storage classes and arithmetic. A document property is stored inside JSONB, rather than as a separate SQL column. Extracted Decimal and BigInteger fields in SoloDB 1.4 are encoded text: use the typed numerical operations described under explicit typed SQL TEXT conversion when working with those values.

SQL batches execute sequentially at SQLite parser boundaries, so earlier effects can remain if a later statement fails. Use an explicit transaction for atomic batches. Advance results explicitly or use Execute to observe later statement errors; early disposal attempts the unread tail and does not guarantee reporting its errors.

ADO.NET calls raise SoloDatabase.Data.Sqlite.SqliteException; native connections raise SoloDatabase.NativeSqliteException.

Query<T> is lazy, and a SqlRow is valid only until the reader moves on; copy the values you keep. Dispose readers and query results before returning a borrowed connection, then dispose the borrow. Do not Close and reopen a connection SoloDB owns: closing can end an in-memory database, and reopening skips SoloDB's setup. PRAGMAs and TEMP objects you create stay on the pooled connection, and TEMP names can hide tables of the main database.

Recompile applications and libraries built against SoloDB 1.3: the native and ADO.NET types changed their public signatures, even where your source code compiles unchanged.

SQLite provider compatibility

SoloDB preserves an application-selected SQLitePCL provider, including vendor engines with backported fixes. Document-store startup requires SQLite 3.47.0 or later for the JSONB and trigger RAISE() message expressions it uses; it does not reject engines based on vulnerability-version labels or replace the selected provider. The default native dependency supplies SQLite 3.53.3, including the WAL-reset fix. Check the loaded engine with SELECT sqlite_version(). Direct native and ADO connections operate independently of the document-store feature requirement.

Supply your own SQLite storage v1.4.2

Use SqliteStorage when you want to supply streams or positional byte files for a database. Collections, transactions, search and ADO access keep their usual APIs. For an ordinary SQLite file, keep using new SoloDB("app.db").

FactorySupplied bytesChoose it for
Simple(main, journal, coordination)Main database and rollback journalSQLite PERSIST mode; readers normally finish before a writer commits.
Wal(main, log, coordination)Main database and write-ahead logA reader retaining its snapshot while another connection commits.
ReadOnly(main)One complete, unchanging main imageImmutable reads after preparing the database writable.

These overloads take ISqliteStorageFile objects. Stream overloads also take leaveOpen before coordination. Writable factories require a nonnull ISqliteStorageCoordination. Keep the main image and its matching journal or log together across reopenings; an empty replacement log can discard recovery information.

Open and reopen streams

Streams must be readable and seekable, and writable for Simple or WAL. This complete example stores a note in memory and reopens the same bytes after the first storage has closed. Its contents disappear when the process ends.

using System;
using System.IO;
using SoloDatabase;

using var main = new MemoryStream();
using var journal = new MemoryStream();
using var storage = SqliteStorage.Simple(main, journal, leaveOpen: true,
    coordination: SqliteStorageCoordination.SingleProcessInMemory);
using (var db = new SoloDB(storage))
{
    db.GetCollection<StoredNote>().Insert(new StoredNote { Id = 1, Text = "alpha" });
}

if (!storage.IsClosed)
    throw new InvalidOperationException("Finish the remaining database users before reopening.");
if (storage.ClosingFailure is Exception closeError)
    throw new IOException("Closing the database failed.", closeError);

using var next = SqliteStorage.Simple(main, journal, leaveOpen: true,
    coordination: SqliteStorageCoordination.SingleProcessInMemory);
using var reopened = new SoloDB(next);
Console.WriteLine(reopened.GetCollection<StoredNote>().GetById(1L).Text);

public sealed class StoredNote
{
    public long Id { get; set; }
    public string Text { get; set; } = "";
}

Several live database roots can use one storage. Closing its last database retires that storage; create a new storage object for sequential reuse. With leaveOpen: true, you close the streams after all users finish. With false, SoloDB closes them after the final participating storage finishes. Positional file implementations remain yours to close.

F# uses the same factories and explicit coordination. Put disposal scopes inside a function; this fragment reuses the Article record, imports and Generated registration setup from the F# search example:

open System.IO

let openMemoryDatabase () =
#if !DEBUG
    Generated.register()
#endif
    use main = new MemoryStream()
    use log = new MemoryStream()
    use storage = SqliteStorage.Wal(
        main, log, true, SqliteStorageCoordination.SingleProcessInMemory)
    use db = new SoloDB(storage)
    db.GetCollection<Article>().Insert(
        { Id = 0L; Title = "alpha"; Body = "example"; Tenant = 3 }) |> ignore

Choose coordination for your byte views

SingleProcessInMemory shares private pager locks and WAL memory by the actual main Stream or positional-file object. Separate storage objects using that same object share its domain. Independently opened wrappers of one path do not join automatically. This choice supplies no multiprocess guarantee.

For independent views or processes on one host, SqliteStorageCoordination.File uses the active SQLite engine's native filesystem for coordination. Every participant must use the same separate coordination path and expose coherent main/log bytes. Each participant opens its own streams:

using System.IO;
using SoloDatabase;

using var main = new FileStream("articles.main", FileMode.OpenOrCreate,
    FileAccess.ReadWrite, FileShare.ReadWrite, bufferSize: 1);
using var log = new FileStream("articles.wal", FileMode.OpenOrCreate,
    FileAccess.ReadWrite, FileShare.ReadWrite, bufferSize: 1);
var coordination = SqliteStorageCoordination.File("articles.coordination");
using var storage = SqliteStorage.Wal(main, log, true, coordination);
using var db = new SoloDB(storage);

Do not delete, replace, or independently open and close the coordination file while it is in use. Coordination does not make independently buffered readers coherent or arbitrary remote storage safe to share. A specialist native filesystem can use File(filename, registeredVfs); keep that registration alive through physical closure.

You can implement ISqliteStorageCoordination yourself. Its Open(main, profile) returns a distinct ISqliteStorageCoordinationSession per physical main-file open. Each session owns its pager locks, WAL mappings and Close operation, reports a stable compatible DomainIdentity, and returns SQLite result codes. Closing one session must preserve another session's grants. Follow the complete coordination contract.

Implement positional byte files

This complete ISqliteStorageFile implementation shows each byte-file contract above its method. Ordinary file users can pass a FileStream directly; the interface is useful for another backend.

SoloDB serializes calls for each actual supplied object, but calls can change threads. Consume spans synchronously, never retain them, and do not reenter the database. Independent views must expose coherent bytes and lengths; coordination supplies locks, not coherence or durability.

using System;
using System.IO;
using SoloDatabase;

// SoloDB serializes calls on this object, but they may change threads. Never retain
// spans or reenter SoloDB. Independent views must expose coherent bytes and lengths.
// Return expected file failures with their original cause. Use Full/ReadOnly
// only when the backend knows that classification; exception text is not a code.
// SoloDB also supports thrown exceptions; unexpected failures propagate here.
public sealed class PositionalFile : ISqliteStorageFile, IDisposable
{
    private readonly FileStream file;
    private readonly byte[] zeros = new byte[8192];

    [System.Runtime.InteropServices.DllImport("libc", EntryPoint = "fsync", SetLastError = true)]
    private static extern int SyncFile(int descriptor);
    [System.Runtime.InteropServices.DllImport("libc", EntryPoint = "fcntl", SetLastError = true)]
    private static extern int SyncFull(int descriptor, int command);

    private static readonly bool MacOS = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(
        System.Runtime.InteropServices.OSPlatform.OSX);

    // On Linux and macOS, .NET 6-10 FileStream.Flush(true) can report success even
    // when fsync fails, because the runtime returns a comparison instead of the
    // native result (dotnet/runtime#135201, fixed in .NET 11). On those runtimes,
    // call the native barrier directly and check it; elsewhere use Flush(true).
    private static readonly bool CheckedUnixSync = Environment.Version.Major >= 6 &&
        Environment.Version.Major < 11 && (MacOS ||
        System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(
            System.Runtime.InteropServices.OSPlatform.Linux));

    private void FlushToDisk()
    {
        if (!CheckedUnixSync) { file.Flush(true); return; }
        file.Flush(false); // Drain managed bytes before the one checked native barrier.
        var handle = file.SafeFileHandle;
        bool held = false;
        try
        {
            handle.DangerousAddRef(ref held);
            int descriptor = handle.DangerousGetHandle().ToInt32();
            while ((MacOS ? SyncFull(descriptor, 51) : SyncFile(descriptor)) != 0)
            {
                int error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                if (error != 4) // EINTR; Darwin command 51 is F_FULLFSYNC.
                    throw new IOException("File synchronization failed.",
                        new System.ComponentModel.Win32Exception(error));
            }
        }
        finally { if (held) handle.DangerousRelease(); }
    }

    public PositionalFile(string path)
    {
        file = new FileStream(path, FileMode.OpenOrCreate,
            FileAccess.ReadWrite, FileShare.ReadWrite, bufferSize: 1);
    }

    private static void CheckRange(long position, int count)
    {
        if (position < 0 || position > long.MaxValue - count)
            throw new ArgumentOutOfRangeException(nameof(position));
    }

    private void ExtendWithZeros(long length)
    {
        file.Position = file.Length;
        while (file.Position < length)
        {
            int count = (int)Math.Min(zeros.Length, length - file.Position);
            file.Write(zeros, 0, count);
        }
    }

    // Report actual bytes read: short reads are valid and SoloDB retries them.
    // For a nonempty request, success with Count=0 means EOF, never an I/O error.
    // SoloDB supplies SQLite's EOF zero-fill; this method does not report padding as data.
    // Validate even empty ranges. A failed result is never a successful EOF.
    public StorageReadResult ReadAt(long position, Span<byte> destination)
    {
        CheckRange(position, destination.Length);
        if (destination.IsEmpty) return new StorageReadResult(0, null);
        try
        {
            file.Position = position;
            return new StorageReadResult(file.Read(destination), null);
        }
        catch (Exception cause) when (cause is IOException || cause is UnauthorizedAccessException)
        {
            return new StorageReadResult(0, new StorageFailure(StorageFailureKind.IoError, cause));
        }
    }

    // Success writes the entire span; empty writes must not extend the file.
    // New gaps read as zeros. Failure may change the requested range, but must
    // preserve existing bytes outside it, never shrink, and never grow beyond
    // max(previous length, requested end). Do not turn a partial write into success.
    public StorageFailure? WriteAt(long position, ReadOnlySpan<byte> source)
    {
        CheckRange(position, source.Length);
        if (source.IsEmpty) return null;
        try
        {
            if (position > file.Length) ExtendWithZeros(position);
            file.Position = position;
            file.Write(source);
            return null;
        }
        catch (Exception cause) when (cause is IOException || cause is UnauthorizedAccessException)
        {
            return new StorageFailure(StorageFailureKind.IoError, cause);
        }
    }

    // Return the current logical length, not capacity or a stale private value.
    // Length is meaningful only on success; report or throw a real query failure.
    public StorageLengthResult GetLength()
    {
        try { return new StorageLengthResult(file.Length, null); }
        catch (Exception cause) when (cause is IOException || cause is UnauthorizedAccessException)
        {
            return new StorageLengthResult(0, new StorageFailure(StorageFailureKind.IoError, cause));
        }
    }

    // Reject negative lengths. Preserve the retained prefix, discard a shortened
    // tail, and zero every extension so shrink/regrow cannot reveal old bytes.
    // On failure, preserve the prefix common to the old and requested lengths.
    public StorageFailure? SetLength(long length)
    {
        if (length < 0) throw new ArgumentOutOfRangeException(nameof(length));
        try
        {
            if (length > file.Length) ExtendWithZeros(length);
            else file.SetLength(length);
            return null;
        }
        catch (Exception cause) when (cause is IOException || cause is UnauthorizedAccessException)
        {
            return new StorageFailure(StorageFailureKind.IoError, cause);
        }
    }

    // A persistent backend's success is an fsync-like ordered barrier: finish all
    // earlier byte/length writes and their promised persistence before returning.
    // Merely queuing or draining a userspace buffer is insufficient. Surface a
    // failed barrier even if WriteAt succeeded.
    // Device and new-name/directory durability still belong to the backing system.
    // A volatile backend cannot promise this persistence.
    public StorageFailure? Flush()
    {
        try
        {
            FlushToDisk();
            return null;
        }
        catch (Exception cause) when (cause is IOException || cause is UnauthorizedAccessException)
        {
            return new StorageFailure(StorageFailureKind.IoError, cause);
        }
    }

    public void Dispose() => file.Dispose();
}

The example lets original file exceptions propagate as I/O failures. A backend with a known capacity or read-only failure can return StorageFailure with Full or ReadOnly and the original cause. Never report a failed read as EOF or a failed persistence barrier as success. A volatile memory backend can make Flush a no-op, but it must remain explicitly volatile; it cannot promise disk persistence.

Durable creation of a new file name and its parent directory is a separate backing-system obligation. Keep the files available until storage physically closes. Custom storage uses an internal 4096-byte sector unit, separate from the database page size. See the complete byte-file guide for usage and failure boundaries.

Keep a database inside another SoloDB filesystem

Open the parent's byte streams once and keep the child open across updates. This example reuses StoredNote from the stream example:

using var parent = new SoloDB("tenant.db");
using var main = parent.FileSystem.OpenOrCreateAt("/notes.main");
using var log = parent.FileSystem.OpenOrCreateAt("/notes.wal");
using var storage = SqliteStorage.Wal(main, log, true,
    SqliteStorageCoordination.SingleProcessInMemory);
using var child = new SoloDB(storage);
var notes = child.GetCollection<StoredNote>();
notes.Insert(new StoredNote { Text = "first" });
notes.Insert(new StoredNote { Text = "second" });

The parent's file streams write affected chunks through their ordinary transactions and callbacks. Keep the parent alive until child storage physically closes. This same-object choice needs no coordination file and supplies no multiprocess guarantee. Do not assume a transaction writing both databases commits atomically across them.

The same pattern composes through three nested levels: retain each level's streams and storage and close deepest children first. Reuse the same storage for another live root of that child. Opening the same child path again creates different stream objects, so in-memory coordination does not join those views automatically. Independent views require shared coordination and coherent bytes. Different child databases can reuse the provider without joining their private locks or WAL memory.

Use each child's transaction API. Wrapping normal child work in a parent write transaction can make its root-owned backing streams wait on that parent writer through another connection. A parent transaction does not combine all live nested databases into one atomic transaction.

Each nesting level stores the child database in compressed 16 KiB chunks of its parent's filesystem, so a child write also pays the parent's page, index and journal or WAL work. A partial write rewrites only the affected chunks. Tenants that share an ancestor also share its single SQLite writer.

On Linux x64 tmpfs with .NET 10.0.14 and SQLite 3.53.3, using WAL, synchronous=FULL, 4 KiB pages and 256 rows of 512 characters, the median time for one transaction updating 32 rows was:

RootFirst childSecond child
0.1143 ms0.4317 ms1.9257 ms

That is +277.8% for the first child and +1,585.2% for the second, relative to the root, which used unbuffered FileStreams. Each median covers three rotated samples of eight transactions after warmup, excluding setup, checkpoints and disposal. The figures describe this workload on memory-backed storage, not a fixed cost per level or disk durability.

When dirty, a database filesystem stream's Flush performs parent metadata maintenance; earlier byte writes already used parent transactions. Persistence depends on the complete backing/commit chain: a child's FULL synchronization cannot strengthen a parent configured for weaker persistence, and a memory-backed root remains volatile.

Test a coordination implementation

SqliteStorageDiagnostics.TestCoordination explicitly exercises pager locks and, for Wal, shared-memory mappings and slot conflicts. The following helper takes your provider and two positional views of the same isolated test backing. Pass the same object twice for SingleProcessInMemory:

static void CheckCoordination(ISqliteStorageCoordination provider,
    ISqliteStorageFile firstView, ISqliteStorageFile secondView)
{
    var result = SqliteStorageDiagnostics.TestCoordination(
        provider, firstView, secondView, SqliteStorageProfile.Wal);
    foreach (var failure in result.Failures)
        Console.Error.WriteLine(failure.Message);
    result.ThrowIfFailed();
}

Use resources with no active database users: the checks overwrite test mappings. The report contains Passed, immutable Failures, expected/actual codes and original errors; ThrowIfFailed raises AggregateException. Provider methods must return normally; the synchronous test cannot interrupt blocked caller code. A pass establishes the exercised same-process cases, not independent byte coherence, multiprocess exclusion, crash recovery or durability. Opening a database does not automatically run it.

Read-only images, backup and export

ReadOnly takes a complete image already migrated by the current SoloDB version. Prepare older images through a writable open first. Finish WAL checkpointing or export a complete image; leave its bytes unchanged while open:

using (var source = new SoloDB("articles.db"))
    source.VacuumTo("articles.snapshot.db"); // Choose a new destination.

using var image = File.OpenRead("articles.snapshot.db");
using var storage = SqliteStorage.ReadOnly(image, leaveOpen: true);
using var snapshot = new SoloDB(storage);
var rows = snapshot.GetCollection<Article>("articles").ToArray();

This fragment uses the C# Article model and imports from the search example, plus System.IO. ReadOnly retains query functions and metadata but does not migrate, create collections or record model descriptions. Write administration throws InvalidOperationException. An unchanged Ensure can succeed without writing, as can removing an already absent target. Raw write SQL keeps SQLite's READONLY error.

source.BackupTo(destination) also works with supplied storage. A fresh WAL destination must match the source page size; use a rollback-mode destination when they differ. New WAL storage uses the engine default page size, 4096 bytes in the bundled engine; existing images keep their page size. See the import and export options.

Physical closure, buffered flushing and errors

Dispose readers, streams, borrowed connections and transactions before disposing their database. Storage can remain physically open while they still need it. Check storage.IsClosed before reusing or closing supplied files; do not spin on the thread that owns the unfinished reader. Inspect storage.ClosingFailure after completion for a closing error.

If opening fails, the exception keeps SQLite's error code and the original cause; failures while cleaning up appear in storage.ClosingFailure. For database errors, inspect SqliteErrorCode, SqliteExtendedErrorCode and the inner exceptions. Let SQLite roll back or recover a failed write rather than retrying the byte write yourself.

Flushing an ordinary writable FileStream writes its buffer and then synchronizes the file to disk. On Linux and macOS with .NET 6 through 10, SoloDB checks the operating system's result directly (fsync, or F_FULLFSYNC on macOS), so a failed synchronization is reported instead of lost. MemoryStream stays volatile, and durable creation of new file names and directories remains your application's job. The storage guide covers BufferedStream and custom stream wrappers.

Generated and NativeAOT applications keep their normal registration. Borrow connections from the database you opened; its diagnostic connection string cannot recreate the supplied files. Read the complete storage guide for recovery, sharing and provider requirements.

Configuration

Database Location

// File-based (persistent)
using var db = new SoloDB("path/to/database.db");
using var db = new SoloDB("./relative/path.db");
using var db = new SoloDB(@"C:\absolute\path.db");

// In-memory (lost when disposed)
using var db = new SoloDB("memory:my-database");

// Shared in-memory (accessible by name within process)
using var db1 = new SoloDB("memory:shared");
using var db2 = new SoloDB("memory:shared");  // Same database

Long-Running Applications

// Singleton pattern for web apps / services
public static class Database
{
    public static SoloDB Instance { get; } = new SoloDB("app.db");
}

// Usage
var users = Database.Instance.GetCollection<User>();

Typically you create one SoloDB instance and reuse it for the lifetime of the application; it is thread-safe. When several processes will share a new database file, create the file once first, for example during installation or from one startup step. The first opening configures the journal and schema, and simultaneous creation by several instances is not guaranteed to succeed. After that, concurrent use of the file works normally.

Database Maintenance

// Ask SQLite to optimize query plans (PRAGMA optimize)
db.Optimize();

// Backup to another database
using var backup = new SoloDB("backup.db");
db.BackupTo(backup);

// Vacuum into new file (compacts and defragments)
db.VacuumTo("compacted.db");

BackupTo cannot cross the file-memory boundary. A file-based database can back up only to another file-based database, and an in-memory database can back up only to another in-memory database. VacuumTo writes a compacted copy to a file on disk.

Query Caching

SoloDB caches prepared SQL statements for performance. Manage prepared-statement caching through the public methods below:

// Disable prepared-statement caching without clearing retained entries
db.DisableCaching();

// Re-enable caching
db.EnableCaching();

// Clear the current cache (frees memory, keeps caching enabled)
db.ClearCache();

Caching is enabled by default. DisableCaching stops using and adding cache entries for later executions; it does not clear existing entries. ClearCache retires cached statements, while active executions retain their own leases until completion. These controls do not clear type metadata or rebuild compiled queries.

Reuse frequent queries

SoloDB translates each LINQ query to SQL when it runs. For a query you run often with different values, compile it once and call the returned function.

Performance Tips

The examples below use this model:

public class User
{
    public long Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public bool NeedsUpdate { get; set; }
    public DateTime LastSeen { get; set; }
    public string Status { get; set; }
}

1. Use Indexes on Queried Properties

// Without index: Full table scan
var user = users.FirstOrDefault(u => u.Email == "test@example.com");

// With index: Fast lookup
[Indexed]
public string Email { get; set; }

2. Use Batch Operations

// Slow: 1000 individual transactions
foreach (var item in items)
    collection.Insert(item);

// Fast: Single transaction
collection.InsertBatch(items);

3. Use Transactions for Multiple Operations

// Slow: Each update is a separate transaction
foreach (var user in usersToUpdate)
{
    user.LastSeen = DateTime.UtcNow;
    users.Update(user);
}

// Fast: Single transaction
db.WithTransaction(tx =>
{
    var col = tx.GetCollection<User>();
    foreach (var user in usersToUpdate)
    {
        user.LastSeen = DateTime.UtcNow;
        col.Update(user);
    }
});

4. Use Projections for Large Documents

// Slow: Loads entire documents
var names = users.ToList().Select(u => u.Name);

// Fast: Only fetches Name field
var names = users.Select(u => u.Name).ToList();

5. Use UpdateMany for Partial Updates

// Slow: Load, modify, save each document
foreach (var user in users.Where(u => u.NeedsUpdate))
{
    var u = users.GetById(user.Id);
    u.Status = "updated";
    users.Update(u);
}

// Fast: Single SQL UPDATE statement
users.UpdateMany(u => u.NeedsUpdate, u => u.Status.Set("updated"));

6. Keep Documents Small

Reading a whole document reads and converts its complete payload. Projections return only the selected fields, and indexed queries and counts need not load whole documents. Keep large binary content out of documents:

// Avoid: every full read of a report also loads its PDF bytes.
public class ReportWithEmbeddedPdf
{
    public long Id { get; set; }
    public string Title { get; set; }
    public byte[] PdfContent { get; set; }
}

Store the bytes in the FileSystem and keep a FileRef in the document:

public class Report
{
    public long Id { get; set; }
    public string Title { get; set; }
    public FileRef Pdf { get; set; }  // The bytes stay in the FileSystem
}

using (var pdfStream = File.OpenRead("report-123.pdf"))
    db.FileSystem.Upload("/reports/report-123.pdf", pdfStream);

var reports = db.GetCollection<Report>();
long id = reports.Insert(new Report
{
    Title = "Quarterly report",
    Pdf = FileRef.From(db.FileSystem.GetAt("/reports/report-123.pdf"))
});

// Read the path without loading the PDF, then read only its first kilobyte.
string path = reports.Where(r => r.Id == id).Select(r => r.Pdf.Value.FullPath).First();
byte[] firstKilobyte = db.FileSystem.ReadAt(path, 0, 1024);

While a document references the file, SoloDB refuses to delete or replace it. Deleting the report keeps the file; delete the file afterwards if nothing else needs it.

Benchmark: SoloDB, LiteDB and MongoDB

The SoloDB vs LiteDB vs MongoDB benchmark compared SoloDB 1.3.0, LiteDB 5.0.21 and MongoDB Community 8.3.11 (C# driver 3.11.2) on 200,000 documents with six common indexes. All three ran with the same transactional guarantees; MongoDB ran as a single-node replica set with snapshot reads and journaled majority writes. Every result was checked against an in-memory copy of the data. The machine was a Ryzen 9 5900HS with Linux and .NET 9, storing all data on tmpfs.

The table uses each database's fastest verified API, in milliseconds. Query and write figures combine six measured samples per variant after warm-up; index construction has two setup observations. Lower is better:

OperationSoloDBLiteDBMongoDB
Count all documents0.2069.4422.40
Count one prefix2.9718.055.32
Count two prefixes38.56310.6484.22
Count unindexed tag101.11312.5669.19
Four workers × 50 exact prefix counts142.551,194.75258.67
First page5.64129.431.72
Page at offset 5,00014.12134.1324.57
Ten sequential pages65.661,307.2931.38
Ten pseudorandom pages199.891,310.241,060.72
1,000 individual point lookups10.3027.4296.44
Group by username initial61.94979.0254.34
Insert 200,000 documents atomically2,269.751,597.621,629.71
Native complex-predicate update56.98122.53207.17
Build common indexes and prepare statistics722.799,016.43735.02

The article shows the code behind each figure and adds file, JSON and two-field-index comparisons. These timings describe that workload on memory-backed storage; measure your own workload before choosing.

How Data is Stored

This part of the documentation is for raw SQL, database viewers and other tools. SoloDB manages the layout described here, upgrades it automatically when it opens a writable database, and can change it between versions. Application code should use the collection APIs. The storage layout guide describes every managed table and column.

The Storage Model

Each collection is a SQLite table with three columns:

  • Id - INTEGER PRIMARY KEY (auto-incremented by default)
  • Value - JSONB containing your serialized object
  • Metadata - JSONB managed by SoloDB; leave it unchanged

When you insert this object:

var user = new User { Name = "Alice", Email = "alice@example.com" };
users.Insert(user);

SoloDB creates a row like this:

// Conceptually:
// Id: 1
// Value: {"Name":"Alice","Email":"alice@example.com","CreatedAt":"..."}

JSONB Format

SoloDB uses SQLite's native JSONB (binary JSON) format, which means:

  • Queries can use SQLite's JSON functions for efficient filtering
  • SQLite can use stored JSONB without reparsing JSON text; loading a .NET model still requires conversion
  • You can even query the data using raw SQL with JSON functions

Typed conversion

Typed conversion uses fixed operations for each type and encoding, shared by ordinary runtime preparation and build generation. Ordinary concrete models do not need an intermediate JsonValue tree; explicit tree APIs keep their own conversion behavior. Runtime codec configuration and replacement are not supported. See direct JSON for numeric, input-order and buffer contracts.

Schema version

SoloDB records its schema version in PRAGMA user_version. Opening a writable database applies any needed schema upgrade automatically; each upgrade step runs in a transaction. SoloDB 1.4.2 uses schema version 7, and older SoloDB versions refuse to open a database with a newer schema.

Return to SoloDB 1.4.1

Schema version 7 adds the full-text search catalog. If you never declared a search index and want to run SoloDB 1.4.1 again, you can remove the empty catalog at your own risk. Close every application using the database, then run this with any SQLite tool:

BEGIN EXCLUSIVE;
DROP TABLE IF EXISTS "SoloDB.SearchIndexes";
PRAGMA user_version = 6;
COMMIT;

This is not a supported downgrade API and does not apply to a database with search indexes. It reverses no numerical conversion. Opening the file with SoloDB 1.4.2 later upgrades it again.

Recorded collection models v1.4.2

On a writable database, GetCollection<T>() automatically records a description of the model type. You do not call anything. Viewers and migration tools can read these descriptions without loading your assemblies:

SELECT Name, json(TypeInformation) AS RecordedTypes
FROM SoloDBCollections;

Each collection keeps its ten most recent distinct model descriptions, oldest first, and acquiring an already recorded model writes nothing. The descriptions show which shapes your application has used, not what every stored row contains. The recorded-type format describes every field.

API Reference

Database, collection, relation, file and JSON APIs, grouped by function. Behavior notes and larger examples live in the dedicated sections above.

SoloDB

class SoloDB : ISoloDB, IDisposable — The root database handle. Create one per file, share it across threads.

new SoloDB(string source)Open or create a database. Use a file path for persistent, "memory:name" for in-memory
new SoloDB(SqliteStorage storage)Open supplied Stream or positional storage; see storage and coordination
ConnectionStringThe SQLite connection string; for supplied storage it is diagnostic and cannot recreate the supplied files
FileSystemAccess the built-in file storage API
GetCollection<T>()Get a typed collection (name derived from type)
GetCollection<T>(string name)Get a typed collection with an explicit name
GetUntypedCollection(string name)Get an untyped JsonValue collection for dynamic use
MigrateDecimal<T>()Atomically migrate declared Decimal and BigInteger fields in the existing default collection
MigrateDecimal<T>(string name)Migrate an existing named collection; see numerical migration. Not supported inside event handlers
CollectionExists(string name)Check if a named collection exists
CollectionExists<T>()Check if a typed collection exists
ListCollectionNames()List all collection names as string[]
DropCollection(string name)Delete a named collection (throws if missing)
DropCollection<T>()Delete a typed collection and all its data
DropCollectionIfExists(string name)Delete a named collection if it exists
DropCollectionIfExists<T>()Delete a typed collection if it exists
WithTransaction(Action<TransactionalSoloDB>)Execute inside a BEGIN IMMEDIATE transaction
WithTransaction<R>(Func<TransactionalSoloDB, R>)Execute in transaction with a return value
WithTransactionAsync(Func<TransactionalSoloDB, Task>)Execute an async transaction
WithTransactionAsync<R>(Func<TransactionalSoloDB, Task<R>>)Execute an async transaction with a return value
Optimize()Run SQLite PRAGMA optimize to improve query plans
BackupTo(SoloDB target)Backup to another database (cannot cross file/memory boundary)
Vacuum()Compact the current database file in place
VacuumTo(string location)Compact into a new file
EnableCaching()Turn prepared-statement caching on
DisableCaching()Turn prepared-statement caching off without clearing existing entries
ClearCache()Drop the current prepared-statement cache
static GetSQL<T>(IQueryable<T> query)Return the SQL generated for a LINQ query
static ExplainQueryPlan<T>(IQueryable<T> query)Return SQLite's EXPLAIN QUERY PLAN output for a LINQ query
Dispose()Close the database connection and release resources

ISoloDB

interface ISoloDB : IDisposable — Common database API shared by SoloDB and TransactionalSoloDB.

ConnectionStringThe SQLite connection string
FileSystemAccess the file storage API
GetCollection<T>()Get a typed collection
GetCollection<T>(string name)Get a typed collection with explicit name
GetUntypedCollection(string name)Get an untyped collection
MigrateDecimal<T>()Atomically migrate declared Decimal and BigInteger fields in the existing default collection
MigrateDecimal<T>(string name)Migrate an existing named collection; see numerical migration. Not supported inside event handlers
CollectionExists(string name)Check if a named collection exists
CollectionExists<T>()Check if a typed collection exists
ListCollectionNames()List all collection names
DropCollection(string name)Delete a named collection
DropCollection<T>()Delete a typed collection
DropCollectionIfExists(string name)Delete a named collection if it exists
DropCollectionIfExists<T>()Delete a typed collection if it exists
WithTransaction(Action<ISoloDB>)Execute inside a transaction
WithTransaction<R>(Func<ISoloDB, R>)Execute in transaction with return value
WithTransactionAsync(Func<ISoloDB, Task>)Async transaction
WithTransactionAsync<R>(Func<ISoloDB, Task<R>>)Async transaction with return value
Optimize()Run SQLite PRAGMA optimize

TransactionalSoloDB

class TransactionalSoloDB : ISoloDB — Transaction-scoped database handle. Received inside WithTransaction callbacks. Do not store or use outside the callback.

ConnectionStringThe SQLite connection string
FileSystemFile storage API (participates in the transaction)
GetCollection<T>()Get a typed collection within the transaction
GetCollection<T>(string name)Get a named typed collection within the transaction
GetUntypedCollection(string name)Get an untyped collection within the transaction
MigrateDecimal<T>()Atomically migrate declared Decimal and BigInteger fields in the existing default collection
MigrateDecimal<T>(string name)Migrate an existing named collection; see numerical migration. Not supported inside event handlers
CollectionExists(string name)Check if a named collection exists
CollectionExists<T>()Check if a typed collection exists
ListCollectionNames()List all collection names
DropCollection(string name)Delete a named collection
DropCollection<T>()Delete a typed collection
DropCollectionIfExists(string name)Delete a named collection if it exists
DropCollectionIfExists<T>()Delete a typed collection if it exists
WithTransaction(Action<ISoloDB>)Nested transaction (uses savepoints)
WithTransaction<R>(Func<ISoloDB, R>)Nested transaction with return value
WithTransactionAsync(Func<ISoloDB, Task>)Async nested transaction
WithTransactionAsync<R>(Func<ISoloDB, Task<R>>)Async nested transaction with return value
Optimize()Run SQLite PRAGMA optimize

ISoloDBCollection<T>

interface ISoloDBCollection<T> : ISoloDBCollectionEvents<T>, IOrderedQueryable<T> — Typed collection. Use as a LINQ query root and for CRUD operations.

Properties
NameCollection name
InTransactionWhether this collection is operating inside a transaction
IncludeTypeWhether type discriminator info is stored for this collection
Insert
Insert(T item)Insert a document, returns its long ID
InsertBatch(IEnumerable<T> items)Batch insert, returns all IDs
InsertOrReplace(T item)Upsert a single document based on unique index
InsertOrReplaceBatch(IEnumerable<T> items)Batch upsert based on unique indexes
Read
GetById(long id)Get by ID (throws if not found)
GetById<TId>(TId id)Get by custom ID type (throws if not found)
TryGetById(long id)Get by ID, returns FSharpOption<T>
TryGetById<TId>(TId id)Get by custom ID type, returns FSharpOption<T>
Update
Update(T item)Replace the entire document (matched by ID)
UpdateMany(filter, transforms)Partial update of matching documents using transform expressions
ReplaceOne(filter, item)Replace the first matching document
ReplaceMany(filter, item)Replace all matching documents
Delete
Delete(long id)Delete by ID
Delete<TId>(TId id)Delete by custom ID type
DeleteOne(filter)Delete the first match
DeleteMany(filter)Delete all matches
Indexing
EnsureIndex(expression)Create a non-unique index on a property
EnsureUniqueAndIndex(expression)Create a unique index on a property
DropIndexIfExists(expression)Remove an index
EnsureAddedAttributeIndexes()Create indexes declared via [Indexed] attributes
Full-text search — declaration and query examples
EnsureSearchIndex(configure)Declare or maintain the default version-1 search index
EnsureSearchIndex(name, configure) / EnsureSearchIndex(name, version, configure)Declare a named index, optionally with an explicit declaration version
Search(text) / Search(query)Query the default index as IQueryable<SearchHit<T>>
SearchIn(name, text) / SearchIn(name, query)Query a named index
ListSearchIndexes()Return immutable declaration snapshots
VerifySearchIndex(name)Inspect artifacts, rank, integrity, content and ownership under a writer transaction
RebuildSearchIndex(name)Repair selected owned structures, retaining declaration version and identity
OptimizeSearchIndex(name)Explicit native FTS maintenance
DropSearchIndexIfExists(name)Remove an owned index; false when absent
Retained queries
Compile(query)Retain translation and bind current invocation values (since 1.3)
CompileQuotation(query)SoloDB 1.4 whole-query F# quotation entry; see the generated-operations guide
Advanced
GetInternalConnection()Return a borrowed standard ADO connection; SoloDB 1.4 uses SoloDatabase.Data.Sqlite

TryGetById returns FSharpOption<T> in C#. Import Microsoft.FSharp.Core and call FSharpOption<T>.get_IsSome(option), then read option.Value on a hit. A miss returns None.

Search and supplied-storage types

SearchQueryImmutable query Kind/Text with AllWords, LiteralChunks, Phrase, Prefix, TypeAhead and Fts5Syntax factories
SearchHit<T>Original Item and Score; Text/Snippet belong inside query projections
SearchTextStorage.Shared / CopiedRead document text or maintain an additional FTS text copy
SqliteStorage.Simple / Wal / ReadOnlyFactories over streams or positional files; IsClosed and ClosingFailure describe physical completion
ISqliteStorageFileReadAt, WriteAt, Flush, GetLength and SetLength; see the byte-file contract
ISqliteStorageCoordinationOpen returns a distinct session owning that physical open's locks and mappings
SqliteStorageCoordination.SingleProcessInMemory / File(...)Actual-main-object private coordination or native same-host file coordination
SqliteStorageDiagnostics.TestCoordination(...)Explicit same-process checks on isolated test resources

DBRef<T>

struct DBRef<T> : IEquatable, IComparable — A single reference to another entity. Stored as a foreign key, loaded on query.

DBRef<T>.To(long id)Create a reference to an existing entity by ID
DBRef<T>.From(T entity)Create a reference for cascade-insert of a new entity
DBRef<T>.NoneEmpty reference (no target)
.IdDatabase ID of the referenced entity
.HasValuetrue if the reference points to a target
.ValueThe loaded entity (throws if not loaded)
.IsLoadedtrue if the entity was populated by a query

DBRef<TTarget, TId>

struct DBRef<TTarget, TId> : IEquatable, IComparable — Same as DBRef<T> but with a custom ID type.

DBRef<TTarget, TId>.To(TId id)Create a reference by typed ID
DBRef<TTarget, TId>.From(TTarget entity)Create a typed-ID reference for cascade insert
DBRef<TTarget, TId>.NoneEmpty typed-ID reference
.IdDatabase ID of the referenced entity (as long)
.HasValuetrue if the reference points to a target
.ValueThe loaded entity
.IsLoadedtrue if populated by a query

DBRefMany<T>

class DBRefMany<T> : IList<T>, IReadOnlyList<T> — A one-to-many or many-to-many relation collection. Tracks mutations for persist on update.

new DBRefMany<T>()Create an empty relation collection
.CountNumber of items currently in the collection
.IsLoadedtrue if populated from a query
.HasPendingMutationstrue if in-memory changes are waiting to be written
.WasClearedtrue if the collection was cleared since load
Add(T item)Add an item to the relation
Remove(T item)Remove an item from the relation
RemoveAt(int index)Remove the item at a given index
Insert(int index, T item)Insert an item at a given index
Clear()Remove all items from the relation
Contains(T item)Check if an item is in the collection
IndexOf(T item)Get the index of an item
CopyTo(T[] array, int arrayIndex)Copy to an array
this[int index]Get or set by index

DBRefMany<TTarget, TId>

class DBRefMany<TTarget, TId> : IList<TTarget>, IReadOnlyList<TTarget> — Same as DBRefMany<T> but for entities with a custom ID type.

new DBRefMany<TTarget, TId>()Create an empty typed-ID relation collection
Same members as DBRefMany<T> — Count, IsLoaded, HasPendingMutations, WasCleared, Add, Remove, Clear, indexer, etc.

DeletePolicy (enum)

Controls what happens to relations when entities are deleted. Used via [SoloRef] attribute.

RestrictBlock the operation if references exist (default for OnDelete)
CascadeCascade delete to referencing entities (OnDelete only)
UnlinkRemove references; entities survive
DeletionUnlink then delete zero-reference targets (default for OnOwnerDelete)

DBRefOrder (enum)

Controls load ordering for DBRefMany collections. Used via [SoloRef] attribute.

UndefinedLoad order is not guaranteed (default)
TargetIdOrder loaded items by target ID

DBRefMany<T> is relation-backed state, not a detached in-memory list. See the Relations and Relation Queries sections for full behavior.

Attributes

[Indexed]

class IndexedAttribute : Attribute — Mark a property for automatic index creation.

[Indexed]Create a non-unique index on the property
[Indexed(unique: true)]Create a unique index on the property
UniqueWhether this attribute creates a unique index

[SoloId]

class SoloId : IndexedAttribute — Mark a property as a custom ID with a custom generator. Inherits index creation from [Indexed].

[SoloId(typeof(MyGenerator))]Mark as ID with a custom generator type
IdGeneratorThe generator Type used for this ID

[SoloRef]

class SoloRefAttribute : Attribute — Configure relation behavior on DBRef and DBRefMany properties.

OnDeleteDelete policy when the referenced target is deleted (default: Restrict)
OnOwnerDeleteDelete policy when the owning document is deleted (default: Deletion)
UniqueEnforce a one-to-one relation constraint (for DBRef<T>)
OrderByLoad ordering for DBRefMany collections

[Polymorphic]

class PolymorphicAttribute : Attribute — Mark a class for polymorphic serialization. SoloDB stores a $type discriminator so derived types round-trip correctly.

[Polymorphic]Enable polymorphic serialization on a class

In polymorphic queries, OfType<T>() matches the exact stored $type discriminator. It does not automatically include derived rows unless they were stored with that exact discriminator.

Events

ISoloDBCollectionEvents<T>

interface ISoloDBCollectionEvents<T> — Event registration API, inherited by ISoloDBCollection<T>. Register handlers on collection instances.

OnInserting(InsertingHandler<T>)Register a before-insert handler
OnInserted(InsertedHandler<T>)Register an after-insert handler
OnUpdating(UpdatingHandler<T>)Register a before-update handler
OnUpdated(UpdatedHandler<T>)Register an after-update handler
OnDeleting(DeletingHandler<T>)Register a before-delete handler
OnDeleted(DeletedHandler<T>)Register an after-delete handler
Unregister(handler)Remove a previously registered handler (any type)

Handler Delegates

All event handlers return SoloDBEventsResult.

InsertingHandler<T>Before-insert: receives ISoloDBItemEventContext<T>
InsertedHandler<T>After-insert: receives ISoloDBItemEventContext<T>
UpdatingHandler<T>Before-update: receives ISoloDBUpdatingEventContext<T>
UpdatedHandler<T>After-update: receives ISoloDBUpdatingEventContext<T>
DeletingHandler<T>Before-delete: receives ISoloDBItemEventContext<T>
DeletedHandler<T>After-delete: receives ISoloDBItemEventContext<T>

Event Contexts

ISoloDBItemEventContext<T> : ISoloDB — Context for insert and delete events
.ItemThe item being inserted or deleted
.CollectionNameName of the collection that triggered the event
ISoloDBUpdatingEventContext<T> : ISoloDB — Context for update events
.ItemThe item state after the update
.OldItemThe item state before the update
.CollectionNameName of the collection that triggered the event

Both event contexts implement ISoloDB, giving you full database access inside handlers (including FileSystem and other collections).

SoloDBEventsResult

class SoloDBEventsResult — Return value from event handlers.

SoloDBEventsResult.EventHandledHandler completed; keep it registered for future events
SoloDBEventsResult.RemoveHandlerHandler completed; unregister it automatically
.IsEventHandledCheck if this is EventHandled
.IsRemoveHandlerCheck if this is RemoveHandler

Query and Relation Extensions

RelationQueryExt

Extension methods for loading and excluding relations in LINQ queries.

Include(selector)Load one relation path eagerly
ThenInclude(selector)Continue an include chain through a loaded relation
ThenExclude(selector)Exclude a child relation under an include chain
Exclude(selector)Leave one relation unloaded (keeps its ID)
Exclude()Load no relations unless explicitly included

Include/Exclude only change which relations are loaded. They do not affect which predicates SoloDB can translate. See Relation Queries for full behavior.

IIncludableQueryable<T, TProperty>

interface IIncludableQueryable<T, TProperty> : IQueryable<T> — Returned by Include and ThenInclude to enable chaining.

Extensions (static class)

General LINQ and update helper extension methods usable inside queries and UpdateMany transforms.

Query Helpers
Like(string pattern)Translate to SQLite LIKE in a LINQ predicate
Any(predicate)Translate a collection predicate to EXISTS subquery
Dyn<T>(string propertyName)Read a property dynamically inside a query
Dyn<T>(PropertyInfo property)Read a property dynamically from a PropertyInfo
Dyn(string propertyName)Read a property dynamically as object
CastTo<T>()Cast an object inside a query expression
Items()Materialize an IGrouping<TKey, T> into an array
Update Transform Helpers (for use inside UpdateMany)
Set(value)Replace a scalar, reference, or object member
Append(value)Append a value to an array or collection member
SetAt(int index, value)Replace one element inside an array-like member
RemoveAt(int index)Remove one element from an array-like member

File Storage

IFileSystem

interface IFileSystem — Full file-system API inside the database. Access via db.FileSystem.

Upload / Download
Upload(string path, Stream stream)Write a file from a stream
UploadAsync(string path, Stream stream)Async file upload
UploadBulk(IEnumerable<BulkFileData> files)Write many files in one call
Download(string path, Stream stream)Stream a stored file out
DownloadAsync(string path, Stream stream)Async file download
ReplaceAsyncWithinTransaction(string path, Stream stream)Replace file contents inside the current transaction
Random Access
ReadAt(string path, long offset, int len)Read a byte range without loading the whole file
WriteAt(string path, long offset, byte[] data, bool createIfInexistent)Write bytes at an offset
WriteAt(string path, long offset, Stream data, bool createIfInexistent)Write a stream at an offset
Open Streams
Open(SoloDBFileHeader file)Open a file header as a DbFileStream
OpenAt(string path)Open a file by path as a DbFileStream
TryOpenAt(string path)Open a file by path, returns FSharpOption<DbFileStream>
OpenOrCreateAt(string path)Open or create a file stream at a path
File Headers
GetAt(string path)Get a file header by path (throws if missing)
TryGetAt(string path)Get a file header by path as FSharpOption
GetOrCreateAt(string path)Get or create a file header
Exists(string path)Check whether a file or directory entry exists
Directory Headers
GetDirAt(string path)Get a directory header by path
TryGetDirAt(string path)Get a directory header as FSharpOption
GetOrCreateDirAt(string path)Get or create a directory header
Metadata
SetMetadata(SoloDBFileHeader file, string key, string value)Set metadata on a file by header
SetMetadata(string path, string key, string value)Set metadata on a file by path
DeleteMetadata(SoloDBFileHeader file, string key)Delete metadata from a file by header
DeleteMetadata(string path, string key)Delete metadata from a file by path
SetDirectoryMetadata(SoloDBDirectoryHeader dir, string key, string value)Set metadata on a directory by header
SetDirectoryMetadata(string path, string key, string value)Set metadata on a directory by path
DeleteDirectoryMetadata(SoloDBDirectoryHeader dir, string key)Delete metadata from a directory by header
DeleteDirectoryMetadata(string path, string key)Delete metadata from a directory by path
Timestamps
SetFileModificationDate(string path, DateTimeOffset date)Set a file's modification time
SetFileCreationDate(string path, DateTimeOffset date)Set a file's creation time
Delete
Delete(SoloDBFileHeader file)Delete a file by header
Delete(SoloDBDirectoryHeader dir)Delete a directory by header
DeleteFileAt(string path)Delete a file by path
DeleteDirAt(string path)Delete a directory by path
Listing
ListFilesAt(string path)List files under a directory
ListDirectoriesAt(string path)List directories under a directory
ListFilesAtPaginated(path, sortBy, sortDir, limit, offset)Paginated file listing with total count
ListDirectoriesAtPaginated(path, sortBy, sortDir, limit, offset)Paginated directory listing with total count
ListEntriesAtPaginated(path, sortBy, sortDir, limit, offset)Paginated mixed listing with file and directory totals
RecursiveListEntriesAt(string path)Eager recursive listing of all entries
RecursiveListEntriesAtLazy(string path)Lazy recursive listing (streamed)
Move
MoveFile(string from, string toPath)Move a file
MoveReplaceFile(string from, string toPath)Move a file, replacing the target if it exists
MoveDirectory(string from, string toPath)Move a directory
Copy
CopyFile(string fromPath, string toPath, bool copyMetadata = false)Copy a file
CopyFileAsync(string fromPath, string toPath, bool copyMetadata = false)Async file copy
CopyReplaceFile(string fromPath, string toPath, bool copyMetadata = false)Copy a file, replacing the target if it exists
CopyReplaceFileAsync(string fromPath, string toPath, bool copyMetadata = false)Async copy-replace for a file
CopyDirectory(string fromPath, string toPath, bool recursive = true, bool copyMetadata = false)Copy a directory
CopyDirectoryAsync(string fromPath, string toPath, bool recursive = true, bool copyMetadata = false)Async directory copy
CopyReplaceDirectory(string fromPath, string toPath, bool recursive = true, bool copyMetadata = false)Copy a directory, replacing the target
CopyReplaceDirectoryAsync(string fromPath, string toPath, bool recursive = true, bool copyMetadata = false)Async copy-replace for a directory
Events (see filesystem events)
OnFileCreating, OnFileCreated, OnFileDeleting, OnFileDeleted, OnFileUpdating, OnFileUpdatedRegister a handler for file header changes
OnDirectoryCreating, OnDirectoryCreated, OnDirectoryDeleting, OnDirectoryDeleted, OnDirectoryUpdating, OnDirectoryUpdatedRegister a handler for directory header changes
OnFileMetadataChanging, OnFileMetadataChanged, OnDirectoryMetadataChanging, OnDirectoryMetadataChangedRegister a handler for metadata changes
OnFileContentChanging, OnFileContentChangedRegister a handler for content writes, resizes and copies
Unregister(handler)Remove a registered filesystem handler; return RemoveHandler instead from inside a handler

SoloDB normalizes slash direction and adds a leading / if omitted. Names are case-sensitive. Unicode names are supported. File data is stored in 16KB chunks.

DbFileStream

class DbFileStream : Stream — A seekable, readable, writable stream backed by the database. Returned by Open/OpenAt/OpenOrCreateAt.

FullPathThe file path captured when this stream was opened; later moves or renames do not update it
CanReadtrue while not disposed; checks access to a borrowed context
CanSeektrue while not disposed; checks access to a borrowed context
CanWritetrue while not disposed; checks access to a borrowed context
LengthFile size in bytes
PositionCurrent stream position
Read(byte[], int, int)Read bytes into a buffer
Read(Span<byte>)Read bytes into a span
Write(byte[], int, int)Write bytes from a buffer
Write(ReadOnlySpan<byte>)Write bytes from a span
WriteAsync(byte[], int, int, CancellationToken)Async write
Seek(long offset, SeekOrigin origin)Seek to a position
SetLength(long value)Set the stream length (truncate or extend)
Flush()Flush pending writes

File Storage Data Types

SoloDBFileHeader

class SoloDBFileHeader — Metadata header for a stored file.

IdFile ID (long)
NameFile name
FullPathFull file path
DirectoryIdParent directory ID
LengthFile size in bytes
CreatedCreation time (DateTimeOffset)
ModifiedModification time (DateTimeOffset)
MetadataKey-value metadata dictionary (IReadOnlyDictionary<string, string>)

SoloDBDirectoryHeader

class SoloDBDirectoryHeader — Metadata header for a stored directory.

IdDirectory ID (long)
NameDirectory name
FullPathFull directory path
ParentIdParent directory ID or null for root
CreatedCreation time
ModifiedModification time
MetadataKey-value metadata dictionary

SoloDBEntryHeader

struct SoloDBEntryHeader — Discriminated union: either a file or a directory. Returned by recursive listing methods.

IsFiletrue if this entry is a file
IsDirectorytrue if this entry is a directory
fileThe SoloDBFileHeader (when IsFile)
directoryThe SoloDBDirectoryHeader (when IsDirectory)
NameEntry name
FullPathEntry full path
DirectoryIdParent directory ID
CreatedEntry creation time
ModifiedEntry modification time
MetadataEntry metadata dictionary
static NewFile(SoloDBFileHeader)Create a file entry
static NewDirectory(SoloDBDirectoryHeader)Create a directory entry

BulkFileData

class BulkFileData — Input record for UploadBulk.

FullPathDestination path for the file
DataFile content as byte[]
CreatedOptional creation timestamp
ModifiedOptional modification timestamp

SortField / SortDirection (enums)

Used by paginated listing methods.

SortField.NameSort by name
SortField.SizeSort by file size
SortField.CreatedSort by creation time
SortField.ModifiedSort by modification time
SortDirection.AscendingAscending order
SortDirection.DescendingDescending order

File and Directory References

struct FileRef and struct DirectoryRef — A document property referencing an existing file or directory header in the same database. See file and directory references.

FileRef.To(long id)Reference a file header by Id (not loaded)
FileRef.From(SoloDBFileHeader header)Reference an existing header (loaded)
FileRef.NoneEmpty reference
IdReferenced header Id (0 if empty)
HasValuetrue if a header is referenced
IsLoadedtrue if Value is available
ValueHeader snapshot; throws InvalidOperationException if empty or not loaded
DirectoryRef has the same members, with SoloDBDirectoryHeader.

class FileRefMany and class DirectoryRefMany — An unordered set of references, compared by header Id.

Add(item), Remove(item), Clear()Change membership; saved by Update or UpdateMany
Contains(item), Count, indexer, enumerationRead the current members
IsLoadedtrue if membership was loaded from the database

ID Generation

IIdGenerator

interface IIdGenerator — Untyped custom ID generator. Implement this and pass the type to [SoloId].

IsEmpty(object id)Return true if the ID value is empty (needs generation)
GenerateId(object collection, object item)Generate a new ID for the item

IIdGenerator<T>

interface IIdGenerator<T> — Typed custom ID generator. Provides type-safe access to the collection and item.

IsEmpty(object id)Return true if the ID value is empty
GenerateId(ISoloDBCollection<T> collection, T item)Generate a new ID with typed collection and item

Serialization

JsonValue

class JsonValue : IDynamicMetaObjectProvider, IComparable, IEquatable — SoloDB's internal JSON representation. Used by untyped collections and for manual serialization.

Creation
JsonValue.New()Create an empty JSON object
JsonValue.New(IEnumerable<KeyValuePair<string, object>>)Create a JSON object from key-value pairs
JsonValue.NullThe JSON null value
JsonValue.NewString(string)Create a JSON string
JsonValue.NewNumber(decimal)Create a JSON number
JsonValue.NewBoolean(bool)Create a JSON boolean
JsonValue.NewList(IList<JsonValue>)Create a JSON array
JsonValue.NewObject(IDictionary<string, JsonValue>)Create a JSON object from a dictionary
Serialization
JsonValue.Serialize<T>(T value)Serialize any object to JsonValue
JsonValue.SerializeWithType<T>(T value)Serialize with $type discriminator
JsonValue.Parse(string json)Parse a JSON string
JsonValue.Parse(ReadOnlySpan<char>)Parse from a char span
JsonValue.Parse(ReadOnlySpan<byte>)Parse from a UTF-8 byte span
JsonValue.ParseInto<T>(string json)Parse JSON directly into a typed object
JsonValue.ParseInto<T>(ReadOnlySpan<char>)Parse char span into a typed object
JsonValue.ParseInto<T>(ReadOnlySpan<byte>)Parse UTF-8 span into a typed object
Deserialization
ToObject<T>()Convert this JsonValue to a typed object
ToObject(Type targetType)Convert to a specified type
ParseInto<T>(input, JsonReadOptions options)String, char-span or UTF-8-span typed read; options select numerical String interpretation
ToObject<T>(options) / ToObject(Type, options)Apply the same policy to an existing tree; see reading stored numbers
ToJsonString()Render as a JSON string
Property Access
this[string name]Get or set a property by name
GetProperty(string name)Get a property value
SetProperty(string name, JsonValue value)Set a property value
TryGetProperty(string name, out JsonValue v)Try to get a property
Contains(string name)Check if a property exists
Type Checks
JsonTypeThe JsonValueType of this value
IsNulltrue if null
IsStringtrue if string
IsNumbertrue if number
IsBooleantrue if boolean
IsListtrue if array
IsObjecttrue if object

StoredNumeric and numerical read options

StoredNumeric is in SoloDatabase; NumericStringFormat and JsonReadOptions are in SoloDatabase.JsonSerializator. Decode an extracted, unquoted stored key; typed collection reads already do this.

StoredNumeric.DecodeDecimal(key) / DecodeBigInteger(key)String or character-span input; native Decimal rounding/range and BigInteger truncation
TryDecodeDecimal(key, out value) / TryDecodeBigInteger(key, out value)False with zero on malformed, null String or unrepresentable target
NumericStringFormat.NumberText / StoredKeyExplicit ordinary-text or encoded-key policy; no guessing
JsonReadOptions.Default / StoredNumericStringsShared immutable presets; get-only NumericStrings, default and format constructors

Complete numerical read examples cover raw keys, JSON String tokens, trees and typed SQL TEXT, including the ambiguous 11 case and default behavior.

JsonValueType (enum)

NullJSON null
StringJSON string
NumberJSON number
BooleanJSON boolean
ListJSON array
ObjectJSON object

JsonValue Subtypes

Typed subclasses of JsonValue for each JSON kind. You rarely construct these directly; use the NewXxx factory methods.

JsonValue.StringHolds a string Item
JsonValue.NumberHolds a decimal Item
JsonValue.BooleanHolds a bool Item
JsonValue.ListHolds an IList<JsonValue> Item
JsonValue.ObjectHolds an IDictionary<string, JsonValue> Item

Untyped Collection Extensions

UntypedCollectionExt

Extension methods for ISoloDBCollection<JsonValue> to insert CLR objects without a compile-time type.

InsertObj(object value)Serialize an object to JsonValue and insert it
InsertBatchObj(IEnumerable<object> values)Batch insert untyped objects

MongoDB Compatibility Layer

The SoloDatabase.MongoDB namespace offers local MongoDB-style clients, filter builders and collection extensions over SoloDB. Its client takes a directory path or a memory: source; MongoDB server connections are unsupported. Use the listed operations when adapting application code to SoloDB.

MongoClient

class MongoClient : IDisposable

new MongoClient(string directoryDatabaseSource)Create a local client from a directory path, such as "data", or a memory: source
GetDatabase(string name)Get a named database; a disk client rooted at "data" opens data/name.solodb. Omitted name uses Master

MongoDatabase

class MongoDatabase : IDisposable

GetCollection<T>(string name)Get a typed collection by name
CreateCollection(string name)Create an untyped collection
ListCollections()List collection names
Dispose()Close the database

CollectionExtensions

MongoDB-style extension methods on ISoloDBCollection<T>.

InsertOne(collection, document)Insert a single document, returns ID
InsertMany(collection, documents)Insert multiple documents, returns InsertManyResult
Find(collection, filter)Query with a filter expression, returns IQueryable<T>
CountDocuments(collection)Count all documents
CountDocuments(collection, filter)Count matching documents
DeleteOne(collection, filter)Delete the first match
DeleteMany(collection, filter)Delete all matches
ReplaceOne(collection, filter, document)Replace the first match
ReplaceMany(collection, filter, document)Replace all matches

BsonDocument

class BsonDocument : IDynamicMetaObjectProvider — MongoDB-compatible document wrapper around JsonValue.

new BsonDocument()Create an empty document
new BsonDocument(JsonValue json)Wrap an existing JsonValue
new BsonDocument(object obj)Serialize an object into a document
JsonThe underlying JsonValue
this[string key]Get or set a property as BsonDocument
Add(string key, object value)Add a property
Remove(string key)Remove a property
Contains(object item)Check if a value exists
GetValue(string key)Get a property as JsonValue
ToObject<T>()Deserialize to a typed object
ToJsonString()Render as JSON
static Deserialize(string json)Parse a JSON string into a BsonDocument
Type Conversions
AsString / IsStringString access and check
AsInt32 / IsInt32Int32 access and check
AsInt64 / IsInt64Int64 access and check
AsDouble / IsDoubleDouble access and check
AsDecimalDecimal access
AsBoolean / IsBooleanBoolean access and check
AsBsonDocument / IsBsonDocumentNested document access and check
AsBsonArray / IsBsonArrayArray access and check
ToInt32() / ToInt64() / ToDouble() / ToDecimal() / ToBoolean()Explicit type conversion methods

FilterDefinitionBuilder<T>

MongoDB-style filter builder. Chain calls then Build() to get a LINQ expression.

EmptyA filter that matches all documents
Eq(field, value)Equality filter (by expression or string)
Gt(field, value)Greater-than filter
Lt(field, value)Less-than filter
In(field, values)Membership filter
Build()Produce the final Expression<Func<T, bool>>

QueryDefinitionBuilder<T>

Same as FilterDefinitionBuilder<T> with uppercase method names (EQ, GT, LT, IN).

EmptyA query that matches all documents
EQ / GT / LT / INSame semantics as FilterDefinitionBuilder
Build()Produce the final Expression<Func<T, bool>>

Builders<T>

Entry point for MongoDB-style builders.

FilterGet a FilterDefinitionBuilder<T>
QueryGet a QueryDefinitionBuilder<T>

InsertManyResult

class InsertManyResult — Result of a batch insert via the MongoDB compatibility layer.

IdsList of inserted IDs
CountNumber of inserted documents

Choosing a public API

Use db.FileSystem for file operations, JsonValue for explicit JSON trees, and SoloDBAOT.Register() for generated operation registration. The examples in file storage, direct JSON and generated operations show their setup and results.