Implements sqlite3_sql, sqlite3_expanded_sql and sqlite3_stmt_busy
(backing SQLite3Stmt::getSQL() and busy() in PHP's ext/sqlite3), SQLite
conversion semantics for the column accessors, and a randomized
differential oracle for the C API.
Introspection:
- sqlite3_sql: original text, retained on the statement, valid until
finalize.
- sqlite3_expanded_sql: SQL with each parameter marker replaced by its
bound value's literal (NULL when unbound). Implemented in core as
Statement::expanded_sql so any binding can expose it; the text is
re-tokenized with the lexer, and each TK_VARIABLE resolves its index
from its own text (?N carries the number, names are looked up, bare ?
is largest-so-far + 1). Does not reuse Value::exec_quote: SQLite
renders quote() and expanded SQL differently (X'..' vs x'..' blobs).
- sqlite3_stmt_busy: delegates to the statement's busy state in core.
Column accessors: column_int64/int/double/text/blob/bytes apply SQLite's
conversion table when the requested representation differs from the
stored type, via Value::exec_cast and the SQLite-compatible text
rendering. Converted results are cached per column for pointer
stability; column_blob returns NULL for zero-length results.
C API semantics:
- sqlite3_last_insert_rowid returns int64 per its prototype.
- sqlite3_bind_parameter_name returns NULL for anonymous ? and "?N" for
numbered markers; numbered markers are tracked by a flag on the AST
variable and in the parameter table, their "?N" name derived from the
index on demand, so registering one allocates nothing and prepare cost
for ?N-heavy statements stays flat. bind_parameter_index("?N")
resolves, as in SQLite. Returned names
are cached on the statement (valid until finalize).
- The prepare tail points at the first byte past the terminating ';'.
- sqlite3_data_count returns 0 when no row is available.
Oracle: tests/oracle.rs dlopens the system libsqlite3 and the built
cdylib side by side (verifying the export table via dlsym) and drives
both through identical seeded scenarios, comparing every observable in
lockstep. Failures abort with seed + operation trace;
TURSO_ORACLE_SEED/TURSO_ORACLE_ITERS reproduce and extend. Not
exercised (reference behavior is build-dependent, noted in the oracle):
step after SQLITE_DONE (auto-reset vs SQLITE_OMIT_AUTORESET; core
auto-reset is follow-up work) and long values in expanded SQL
(SQLITE_TRACE_SIZE_LIMIT).
Directed tests in sqlite3_tests.c pin the introspection contracts
byte-for-byte against both libraries; a core unit test covers
expanded_sql.
Numbered parameters remain pattern placeholders: index-method patterns
use ?N to share one captured argument across call sites (an FTS pattern
binds the same query text to fts_score and fts_match), and the
placeholder guards in try_capture_parameters/try_substitute_parameters
accept positional markers (Variable::is_positional). The .NET binding's
missing-parameter message takes its position branch for anonymous
markers, which its test asserts. The oracle is excluded on Windows like
the compat suite: no system SQLite to compare against.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Turso .NET
ADO.NET bindings for Turso local and remote databases.
The Turso.Data.Sqlite.Provider package includes a SQLite-compatible Turso.Data.Sqlite facade. It depends on the implementation packages Turso.Data.Common and Turso.Data.Native, which provide the shared managed ADO.NET types and native runtime.
Install
dotnet add package Turso.Data.Sqlite.Provider
Application code only needs to install Turso.Data.Sqlite.Provider and reference the Turso.Data.Sqlite namespace.
The package targets net8.0, net9.0, and net10.0. Its Turso.Data.Native dependency supplies native runtime assets for Windows, Linux, macOS, Android (android-arm64, android-arm, android-x64, and android-x86), and iOS as an XCFramework with device and simulator slices.
NativeAOT static linking
NativeAOT apps can opt into statically linking the Turso native library so publish output does not include a sidecar turso_sdk_kit DLL, .so, or .dylib. Reference the neutral RID-specific static package alongside Turso.Data.Sqlite.Provider:
<ItemGroup>
<PackageReference Include="Turso.Data.Sqlite.Provider" Version="0.8.0-pre.2" />
<PackageReference Include="Turso.Data.NativeAot.win-x64" Version="0.8.0-pre.2" PrivateAssets="all" />
</ItemGroup>
Then enable static linking:
<PropertyGroup>
<PublishAot>true</PublishAot>
<SelfContained>true</SelfContained>
<TursoUseStaticNativeLibrary>true</TursoUseStaticNativeLibrary>
</PropertyGroup>
Publish with a supported runtime identifier, for example:
dotnet publish -c Release -r win-x64
Static native packages are published for win-x64, win-arm64, linux-x64, linux-arm64, osx-x64, and osx-arm64. The dynamic native assets remain the default for non-AOT apps and for mobile targets. See samples/NativeAot for a complete executable sample.
Getting started
using Turso;
using var connection = new TursoConnection("Data Source=:memory:");
connection.Open();
connection.ExecuteNonQuery("CREATE TABLE t(a, b)");
var rowsAffected = connection.ExecuteNonQuery("INSERT INTO t(a, b) VALUES (1, 2), (3, 4)");
Console.WriteLine($"RowsAffected: {rowsAffected}");
using var command = connection.CreateCommand();
command.CommandText = "SELECT * FROM t";
using var reader = command.ExecuteReader();
while (reader.Read())
{
var a = reader.GetInt32(0);
var b = reader.GetInt32(1);
Console.WriteLine($"Value1: {a}, Value2: {b}");
}
ADO.NET usage
Code written against DbConnection can use TursoConnection directly:
using System.Data.Common;
using Turso;
await using DbConnection connection = new TursoConnection("Data Source=app.db");
connection.Open();
await using var command = connection.CreateCommand();
command.CommandText = "SELECT $value";
var parameter = command.CreateParameter();
parameter.ParameterName = "$value";
parameter.Value = 42;
command.Parameters.Add(parameter);
var value = command.ExecuteScalar();
Remote Turso/libSQL databases can use the same TursoConnection surface with a remote URL and auth token:
await using var connection = new TursoConnection(
"Data Source=libsql://example-org.turso.io;Auth Token=eyJ...");
await connection.OpenAsync();
await using var command = connection.CreateCommand();
command.CommandText = "SELECT name FROM customers WHERE id = $id";
command.Parameters.Add(new TursoParameter("$id", 42));
var name = await command.ExecuteScalarAsync();
Remote mode uses the Hrana HTTP /v2/pipeline protocol. libsql:// URLs default to HTTPS; Tls=False maps them to HTTP for local development. ws:// and wss:// URLs are accepted and mapped to the equivalent HTTP pipeline endpoint. Auth Token requires HTTPS unless the host is localhost or loopback.
Remote mode also supports ADO.NET DbBatch for latency-sensitive workloads that should be sent in one Hrana batch:
await using var batch = connection.CreateBatch();
var insert = batch.CreateBatchCommand();
insert.CommandText = "INSERT INTO customers(name) VALUES ($name)";
var name = insert.CreateParameter();
name.ParameterName = "$name";
name.Value = "Alice";
insert.Parameters.Add(name);
batch.BatchCommands.Add(insert);
var select = batch.CreateBatchCommand();
select.CommandText = "SELECT COUNT(*) FROM customers";
batch.BatchCommands.Add(select);
await using var reader = await batch.ExecuteReaderAsync();
Embedded replicas are not enabled yet in the .NET provider. Replica Path and Sync Interval are parsed so applications fail early with clear errors, and TursoConnection.Sync() / SyncAsync(CancellationToken) are reserved for that mode once turso_sync_sdk_kit is packaged and wired through .NET.
Provider factories are available through TursoFactory.Instance:
DbProviderFactory factory = TursoFactory.Instance;
using var connection = factory.CreateConnection();
connection!.ConnectionString = "Data Source=:memory:";
connection.Open();
Migrating from Microsoft.Data.Sqlite
For common embedded SQLite usage, the Turso.Data.Sqlite.Provider package exposes a SQLite-compatible Turso.Data.Sqlite facade over the Turso engine:
- using Microsoft.Data.Sqlite;
+ using Turso.Data.Sqlite;
- using var connection = new SqliteConnection("Data Source=app.db");
+ using var connection = new SqliteConnection("Data Source=app.db");
Supported common connection string keywords include:
| Keyword | Notes |
|---|---|
Data Source |
Database path or :memory:. Aliases include DataSource and Filename. |
Mode |
Parsed and preserved for compatibility. |
Cache |
Parsed and preserved for compatibility. |
Foreign Keys |
Parsed and preserved for compatibility. |
Recursive Triggers |
Parsed and preserved for compatibility. |
Default Timeout |
Used as the default command timeout. Aliases include Command Timeout. |
Pooling |
Parsed and preserved for compatibility. |
Vfs |
Parsed and preserved for compatibility. |
Encryption Cipher |
Turso local encryption cipher. |
Encryption Key |
Hex-encoded encryption key used with Encryption Cipher. |
Auth Token |
Bearer token for remote Turso/libSQL URLs. Aliases include AuthToken and Authentication Token. |
Replica Path |
Reserved for embedded replicas. The .NET provider currently fails early with a clear unsupported error. |
Read Your Writes |
Keeps the remote Hrana session baton across commands. Defaults to True. Set False for stateless one-shot remote requests. |
Sync Interval |
Reserved for embedded replicas. Automatic sync is not enabled yet. |
Tls |
Optional override for libsql:// development URLs. Conflicting values with explicit http:// or https:// schemes fail early. |
SQLite-compatible facade coverage
Turso.Data.Sqliteis the migration-oriented facade. It includes SQLite-style connection strings, commands, readers, schema metadata, transactions and savepoints, backup, SQL-backed blob streams, scalar and aggregate UDFs, custom collations, and disabled-by-default extension loading.- Raw SQLitePCL
sqlite3*handle interop is intentionally unsupported.SqliteConnection.Handlereturnsnullrather than exposing a fake SQLite handle. PRAGMA read_uncommittedis tracked as connection-local state for API compatibility, but Turso does not currently implement SQLite shared-cache dirty reads.SqliteBlobpreserves fixed-length blob stream behavior through SQL reads and writes. It is not yet backed by a native incremental-blob storage handle.- SQLite virtual-table modules such as FTS3/FTS5 are not built in unless provided by a Turso extension/module.
- Async methods currently use the base ADO.NET behavior rather than a dedicated async native path.
Entity Framework Core
Turso.EntityFrameworkCore.Sqlite adds a UseTurso provider hook for local and embedded Turso databases. It reuses EF Core SQLite's LINQ translation pipeline and executes generated SQL through the Turso.Data.Sqlite facade.
dotnet add package Turso.EntityFrameworkCore.Sqlite
using Microsoft.EntityFrameworkCore;
public sealed class AppDbContext : DbContext
{
public DbSet<Customer> Customers => Set<Customer>();
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseTurso("Data Source=app.db");
}
You can also pass an existing Turso SQLite-compatible connection:
using Microsoft.EntityFrameworkCore;
using Turso.Data.Sqlite;
await using var connection = new SqliteConnection("Data Source=app.db");
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseTurso(connection)
.Options;
The local provider supports the normal EF Core SQLite query pipeline, including composed IQueryable<T> filters, navigation-property joins, ordering, paging, grouping, aggregates, async materialization, and SaveChangesAsync. Schema creation can use the standard EF Core SQLite mechanisms such as EnsureCreated, EnsureCreatedAsync, and migrations against local database files.
Remote libsql:///auth-token EF Core support is not part of the local provider. Use the local/embedded provider for EF Core today; remote/serverless EF support needs a separate connection, retry, and transaction design.