Glesity.Wasm.Sqlite
0.4.2-alpha
dotnet add package Glesity.Wasm.Sqlite --version 0.4.2-alpha
NuGet\Install-Package Glesity.Wasm.Sqlite -Version 0.4.2-alpha
<PackageReference Include="Glesity.Wasm.Sqlite" Version="0.4.2-alpha" />
<PackageVersion Include="Glesity.Wasm.Sqlite" Version="0.4.2-alpha" />
<PackageReference Include="Glesity.Wasm.Sqlite" />
paket add Glesity.Wasm.Sqlite --version 0.4.2-alpha
#r "nuget: Glesity.Wasm.Sqlite, 0.4.2-alpha"
#:package Glesity.Wasm.Sqlite@0.4.2-alpha
#addin nuget:?package=Glesity.Wasm.Sqlite&version=0.4.2-alpha&prerelease
#tool nuget:?package=Glesity.Wasm.Sqlite&version=0.4.2-alpha&prerelease
Glesity.Wasm.Sqlite
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]andIIncrementalGenerator, compatible with<PublishTrimmed>true</PublishTrimmed>and<TrimMode>full</TrimMode>. - Self-Contained WASI Native Library: Ships
runtimes/wasi-wasm/native/libsqlite3.aand MSBuildbuildTransitivetargets that automatically wireDirectPInvokeandNativeLibraryintoilcandwasm-ld. - Rich Source-Generated Repositories: Supports
[DataEntity],[PrimaryKey],[Column],[Index],[OrderBy],[ValueConverter],[DefaultValueConverter],[Flatten],[JsonColumn], and[Ignore]to generateFindBy<Prop>,ListBy<Prop>,DeleteBy<Prop>,TopBy<Prop>(limit), andMigrate(...). - 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_migrationsand safely adds missing columns and indexes viaSqliteMigrationStep. - Unified Exception Hierarchy: Maps SQLite result codes to
WasmDataConstraintException,WasmDataConnectionException, andSqliteException : 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.aforwasi-wasmis bundled inside the package — consumers do not need to install Bytecode Alliancewasi-sdkmanually. 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 generatesFind,Exists,Delete,FindBy<Property>, andDeleteBy<Property>.[Column("custom_name", IsUnique = false)]— overrides the defaultsnake_casecolumn name and adds aUNIQUEconstraint if requested.[Index("idx_name", IsUnique = false)]— creates a SQL index and generatesListBy<Property>,DeleteBy<Property>, andFindBy<Property>(whenIsUnique = true).[OrderBy(Descending = true)]— generates aTopBy<Property>(int limit)leaderboard query method (DESCorASC).[DefaultValueConverter]— placed on anIValueConverter<TModel, TProvider>classorstructto register it globally as the default converter forTModel.[ValueConverter(typeof(TConverter))]— explicitly assigns or overrides a converter at assembly, entity, or property scope (supports bothstructandclassconverters).[Flatten(Prefix = "prefix")]— expandsstructorstruct?fields/properties into individual columns (pos_x,pos_y,pos_z).[JsonColumn(typeof(TJsonSerializerContext))]— serializes complex objects/collections toBLOBusing an AOTJsonSerializerContext.[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 | Versions 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. |
-
net10.0
- Glesity.Wasm.Data.Abstractions (>= 0.3.0-alpha.2)
-
net11.0
- Glesity.Wasm.Data.Abstractions (>= 0.3.0-alpha.2)
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 |