Glesity.Wasm.Sqlite 0.4.2-alpha

This is a prerelease version of Glesity.Wasm.Sqlite.
dotnet add package Glesity.Wasm.Sqlite --version 0.4.2-alpha
                    
NuGet\Install-Package Glesity.Wasm.Sqlite -Version 0.4.2-alpha
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Glesity.Wasm.Sqlite" Version="0.4.2-alpha" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Glesity.Wasm.Sqlite" Version="0.4.2-alpha" />
                    
Directory.Packages.props
<PackageReference Include="Glesity.Wasm.Sqlite" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Glesity.Wasm.Sqlite --version 0.4.2-alpha
                    
#r "nuget: Glesity.Wasm.Sqlite, 0.4.2-alpha"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Glesity.Wasm.Sqlite@0.4.2-alpha
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Glesity.Wasm.Sqlite&version=0.4.2-alpha&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Glesity.Wasm.Sqlite&version=0.4.2-alpha&prerelease
                    
Install as a Cake Tool

Glesity.Wasm.Sqlite

NuGet License: MIT

Zero-reflection, NativeAOT-LLVM SQLite engine for .NET WebAssembly (wasi-wasm), built on top of Glesity.Wasm.Data.Abstractions.

Bundles a statically compiled SQLite (libsqlite3.a v3.54.1), MSBuild targets for automatic DirectPInvoke linking, and a Roslyn Source Generator that emits AOT-safe ISqlRepository<TEntity, TKey> implementations without runtime reflection.

Features

  • Zero Reflection & Full Trimming Safe: Built with [LibraryImport] and IIncrementalGenerator, compatible with <PublishTrimmed>true</PublishTrimmed> and <TrimMode>full</TrimMode>.
  • Self-Contained WASI Native Library: Ships runtimes/wasi-wasm/native/libsqlite3.a and MSBuild buildTransitive targets that automatically wire DirectPInvoke and NativeLibrary into ilc and wasm-ld.
  • Rich Source-Generated Repositories: Supports [DataEntity], [PrimaryKey], [Column], [Index], [OrderBy], [ValueConverter], [DefaultValueConverter], [Flatten], [JsonColumn], and [Ignore] to generate FindBy<Prop>, ListBy<Prop>, DeleteBy<Prop>, TopBy<Prop>(limit), and Migrate(...).
  • Automatic Default Type Converters: Automatically discovers [DefaultValueConverter] implementations across referenced assemblies and prioritizes overrides cleanly ([DefaultValueConverter] → [assembly: ValueConverter] → entity [ValueConverter] → property [ValueConverter]).
  • Idempotent Schema Migrations: Tracks per-table versions in _glesity_schema_migrations and safely adds missing columns and indexes via SqliteMigrationStep.
  • Unified Exception Hierarchy: Maps SQLite result codes to WasmDataConstraintException, WasmDataConnectionException, and SqliteException : WasmDataException.
  • WASI VFS & In-Memory Support: Works with both :memory: databases and persistent files inside WASI preopened directories (e.g., /data/app.db).

Installation

Add the NuGet package to your wasi-wasm project:

dotnet add package Glesity.Wasm.Sqlite --prerelease

Note: Prebuilt libsqlite3.a for wasi-wasm is bundled inside the package — consumers do not need to install Bytecode Alliance wasi-sdk manually. Your target project only needs .NET NativeAOT-LLVM (wasi-wasm) configured.

Your WASI project should target net11.0 with wasi-wasm and BytecodeAlliance.Componentize.DotNet.Wasm.SDK:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net11.0</TargetFramework>
    <RuntimeIdentifier>wasi-wasm</RuntimeIdentifier>

    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>

    <SelfContained>true</SelfContained>
    <UseAppHost>false</UseAppHost>

    <InvariantGlobalization>true</InvariantGlobalization>

    <PublishTrimmed>true</PublishTrimmed>
    <TrimMode>full</TrimMode>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Glesity.Wasm.Sqlite" Version="0.3.0-alpha" />

    <PackageReference
      Include="BytecodeAlliance.Componentize.DotNet.Wasm.SDK"
      Version="0.8.0-preview00011" />

    <PackageReference
      Condition="$([MSBuild]::IsOSPlatform('Linux'))"
      Include="runtime.linux-x64.Microsoft.DotNet.ILCompiler.LLVM"
      Version="10.0.0-rc.1.26306.1" />

    <PackageReference
      Condition="$([MSBuild]::IsOSPlatform('Windows'))"
      Include="runtime.win-x64.Microsoft.DotNet.ILCompiler.LLVM"
      Version="10.0.0-rc.1.26306.1" />

    <PackageReference
      Condition="$([MSBuild]::IsOSPlatform('OSX'))"
      Include="runtime.osx-x64.Microsoft.DotNet.ILCompiler.LLVM"
      Version="10.0.0-rc.1.26306.1" />
  </ItemGroup>

</Project>

Quick Start

1. Define Models, Value Converters & Flattened Structs

Annotate your record or class with attributes from Glesity.Wasm.Data.Abstractions (no partial modifier required):

using System.Text.Json.Serialization;
using Glesity.Wasm.Data.Abstractions;

namespace MyWasiApp;

public sealed record Player(Guid Uuid, string Name);
public readonly record struct WorldId(string Value);
public readonly record struct BlockPos(int X, int Y, int Z);

// Automatically discovered for any WorldId property across the compilation
[DefaultValueConverter]
public sealed class WorldIdConverter : IValueConverter<WorldId, string>
{
    public string ToProvider(WorldId value) => value.Value;
    public WorldId FromProvider(string value) => new(value);
}

// Explicit struct converter (zero-allocation via default(T))
public readonly struct PlayerIdConverter : IValueConverter<Player, Guid>
{
    public Guid ToProvider(Player value) => value.Uuid;
    public Player FromProvider(Guid value) => new(value, "Unknown");
}

// For net10.0 (or matching SDK/ILCompiler.LLVM versions):
[JsonSerializable(typeof(List<string>))]
public partial class AppJsonContext : JsonSerializerContext;

[DataEntity("player_homes")]
[ValueConverter(typeof(PlayerIdConverter))]
public record PlayerHome(
    [property: PrimaryKey(AutoIncrement = true)] long Id,
    [property: Index] Player Owner,
    [property: Index] WorldId World,
    [property: Column("home_name"), Index(IsUnique = true)] string Name,
    [property: Flatten] BlockPos Pos,
    [property: Flatten(Prefix = "bed")] BlockPos? BedPos,
    [property: JsonColumn(typeof(AppJsonContext))] List<string> Tags,
    [property: OrderBy(Descending = true)] long Rating,
    [property: Ignore] string? SessionToken = null
);

Supported attributes (from Glesity.Wasm.Data.Abstractions):

  • [DataEntity("table_name")] — marks a type for table & ISqlRepository<TEntity, TKey> code generation.
  • [PrimaryKey(AutoIncrement = false)] — marks the primary key column and generates Find, Exists, Delete, FindBy<Property>, and DeleteBy<Property>.
  • [Column("custom_name", IsUnique = false)] — overrides the default snake_case column name and adds a UNIQUE constraint if requested.
  • [Index("idx_name", IsUnique = false)] — creates a SQL index and generates ListBy<Property>, DeleteBy<Property>, and FindBy<Property> (when IsUnique = true).
  • [OrderBy(Descending = true)] — generates a TopBy<Property>(int limit) leaderboard query method (DESC or ASC).
  • [DefaultValueConverter] — placed on an IValueConverter<TModel, TProvider> class or struct to register it globally as the default converter for TModel.
  • [ValueConverter(typeof(TConverter))] — explicitly assigns or overrides a converter at assembly, entity, or property scope (supports both struct and class converters).
  • [Flatten(Prefix = "prefix")] — expands struct or struct? fields/properties into individual columns (pos_x, pos_y, pos_z).
  • [JsonColumn(typeof(TJsonSerializerContext))] — serializes complex objects/collections to BLOB using an AOT JsonSerializerContext.
  • [Ignore] — excludes a property from database mapping.

2. Migrate, Query & Persist Data

using Glesity.Wasm.Data.Abstractions;
using Glesity.Wasm.Sqlite;
using MyWasiApp;

// Open a persistent database inside a WASI preopened directory (or ":memory:")
using var db = SqliteDatabase.Open("/data/game.db");

var homes = db.PlayerHomes();

// Creates table/indexes if missing and safely migrates existing schemas to targetVersion
homes.Migrate(targetVersion: 2, step =>
{
    if (step.FromVersion < 2)
    {
        step.ExecuteSql("UPDATE player_homes SET rating = 100 WHERE rating = 0;");
    }
});

var steve = new Player(Guid.NewGuid(), "Steve");
var overworld = new WorldId("minecraft:overworld");
homes.Insert(new PlayerHome(0, steve, overworld, "main", new BlockPos(10, 64, -20), null, ["base"], 500));

// Typed index and leaderboard queries
PlayerHome? mainHome = homes.FindByName("main");
List<PlayerHome> steveHomes = homes.ListByOwner(steve);
List<PlayerHome> topHomes = homes.TopByRating(10);

// Driver-agnostic repository access
ISqlRepository<PlayerHome, long> repo = homes;
long total = repo.Count();

3. Raw SQL, Transactions & Error Handling

For custom queries or multi-statement scripts, use SqliteDatabase and SqliteStatement directly:

using Glesity.Wasm.Data.Abstractions;
using Glesity.Wasm.Sqlite;

using var db = SqliteDatabase.Open(":memory:");

try
{
    db.InTransaction(() =>
    {
        db.Execute("CREATE TABLE kv (k TEXT PRIMARY KEY, v INTEGER);");

        using var stmt = db.Prepare("INSERT INTO kv (k, v) VALUES (?1, ?2);");
        stmt.Bind(1, "apples").Bind(2, 64).ExecuteNonQuery();
    });
}
catch (WasmDataConstraintException ex)
{
    Console.WriteLine($"Constraint violation ({ex.ErrorCode}): {ex.Message}");
}
catch (SqliteException ex)
{
    Console.WriteLine($"SQLite error {ex.ResultCode}: {ex.Message}");
}

Supported Types

C# Type SQLite Storage Class Notes
int, long, bool INTEGER bool stored as 0 / 1
double REAL
string TEXT UTF-8
Guid TEXT Formatted as "D" (xxxxxxxx-xxxx-...)
DateTimeOffset INTEGER Stored as Unix time milliseconds
byte[] BLOB
[DefaultValueConverter] / [ValueConverter] Provider type Mapped via IValueConverter<TModel, TProvider> (struct or class)
[Flatten] structs Expanded columns Each struct field/property becomes <prefix>_<member>
[JsonColumn] types BLOB UTF-8 JSON via AOT JsonSerializerContext
Nullable<T> / T? Nullable column Mapped to SQL NULL

Running with Wasmtime

When using file-backed databases, grant directory access to your WASI runtime:

wasmtime run --dir ./data::/data MyWasiApp.wasm

Building from Source

Native SQLite (libsqlite3.a) is compiled targeting WASI using the Bytecode Alliance WASI SDK (managed automatically via Nix in this repository):

nix develop
just test        # Run Source Generator unit tests
just test-wasi   # Compile to WASI WASM and run integration tests in wasmtime
just pack        # Build the self-contained .nupkg package

License

MIT

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed.  net11.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.4.2-alpha 64 11/30/2026
0.4.0-alpha 61 11/30/2026
0.3.0-alpha 58 11/29/2026
0.2.0-alpha 62 11/29/2026
0.1.0-alpha 63 11/28/2026