mirror of
https://github.com/allankoechke/turso.git
synced 2026-11-30 11:12:58 +00:00
Merge 'bindings/dotnet: resolve declared column types without per-cell PRAGMA queries' from Marc-André Moreau
## Problem `Turso.Data.Sqlite.SqliteDataReader.GetValue(ordinal)` resolves each column's declared type, for example to turn `GUID` columns into `System.Guid`. It did this through `GetDeclaredTypeName` → `GetTableColumns`, which ran `PRAGMA table_info`, `PRAGMA index_list` and `PRAGMA index_info` (plus regexes over the SQL text) for **every column of every row**, with no cache. Reading a result set with `GetValues()` or loading a `DataTable` therefore ran dozens of nested statements per row. An external benchmark of the published `Turso.Data.Sqlite.Provider` 0.8.1 package used Remote Desktop Manager's SQLite data source: 10,000 entries with 11 columns each, including about 1.3 KB of XML. Loading every entry took 14.7 s and allocated 2 GB through this path. ## Fix 1. **Ask the engine.** `GetDeclaredTypeName` now calls `TursoBindings.GetDeclaredTypeName` → `turso_statement_column_decltype`. Microsoft.Data.Sqlite gets the declared type the same way, through `sqlite3_column_decltype`, and it costs no query. Like SQLite, it returns the declared type of direct table-column references (including through aliases and joins) and nothing for expressions. 2. **Remove the SQL-parsing heuristics.** The regex + `PRAGMA table_info` / `index_list` / `index_info` path that guessed the declared type from the SQL text is gone. Compared over direct columns, aliases, joins, views, subqueries, CTEs and expressions, it never resolved anything the engine did not, and the test suite passes without it. 3. **Cache per result set.** Resolved declared types are cached per column for the current result set, so `GetValue` does not cross into native code for them on every cell. The cache is keyed on the current statement handle, so `NextResult()` invalidates it and each statement in a batch resolves its own types. An out-of-range ordinal throws `ArgumentOutOfRangeException`. The change is limited to `SqliteDataReader.cs`. It does not change the public API or the native sdk-kit, and the managed remote/replica path is untouched. `GetSchemaTable` still uses its existing schema lookup. One behaviour note: declared types now come from the engine rather than from parsing the SQL. For queries the heuristics got wrong (for example an aliased, table-qualified column in a join), `GetDataTypeName`, `GetFieldType` and the `Guid` conversion in `GetValue` now follow the engine's declared type, as Microsoft.Data.Sqlite does. ## Measurements Our own reproduction, so not directly comparable with the 0.8.1 numbers above: Windows 11, release native build, 10,000 RDM-shaped rows, median of 3 runs. Baseline: `main`. | Scenario | Before | After | | --- | --- | --- | | Load every entry with `GetValues` | 3.5–4.0 s | about 50 ms | | `SELECT DATA FROM Connections WHERE ID = @id` on an open connection, one `GetValue` | 50–90 µs | 21–33 µs | These numbers come from a build that also had a separate connection- pooling change, which is not part of this PR. Both rows are dominated by the reader path changed here, but they were not re-measured on this change alone. ## Testing - New test `SqliteFacadeTests.GetValueResolvesDeclaredTypesForEachResultSet`. In a two-statement batch, it checks that a `GUID` column comes back as `Guid` on every row of the first result set, and that after `NextResult()` a `TEXT` column with the same name comes back as `string`. This confirms that the cache does not leak between result sets. - New test `SqliteFacadeTests.GetValueResolvesDeclaredTypesThroughAliasesAndJoins`. An aliased, table-qualified `GUID` column in a join comes back as `Guid` (the old heuristics reported it as `TEXT`), and an out-of-range ordinal throws. - New test `SqliteFacadeTests.GetValueUsesStorageTypeWhenNoDeclaredTypeI sAvailable`. Expressions over a `GUID` column, a column declared without a type and a constant expression get no declared type, so values come back as stored (not converted to `Guid`) and `GetDataTypeName` reports the storage type. - `dotnet test src/Turso.Tests`: 258 passed, 0 failed, 4 skipped. The skipped tests are the cloud/remote sync tests, which need credentials. - `dotnet format Turso.slnx whitespace --verify-no-changes` reports no changes for the edited files. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Reviewed-by: Mikaël Francoeur (@LeMikaelF) Closes #9536
This commit is contained in:
@@ -31,6 +31,11 @@ public class SqliteDataReader : DbDataReader
|
||||
private int _managedResultIndex;
|
||||
private int _managedRowIndex = -1;
|
||||
|
||||
// Declared types resolved for the current result set, so GetValue does not cross into
|
||||
// native code for them on every cell.
|
||||
private TursoStatementHandle? _declaredTypeStatement;
|
||||
private string?[] _declaredTypeNames = [];
|
||||
|
||||
internal SqliteDataReader(SqliteCommand command, TursoStatementHandle statement, string currentSql, List<string> remainingSql, int recordsAffected, CommandBehavior behavior, Action closeCallback)
|
||||
{
|
||||
_command = command;
|
||||
@@ -1090,35 +1095,28 @@ public class SqliteDataReader : DbDataReader
|
||||
return CurrentManagedResult.Columns[ordinal].DataTypeName;
|
||||
}
|
||||
|
||||
if (TryGetSelectSource(out var tableName, out var selections))
|
||||
{
|
||||
var tableColumns = GetTableColumns(tableName);
|
||||
var columnName = GetName(ordinal);
|
||||
var selection = ordinal < selections.Count ? selections[ordinal] : columnName;
|
||||
var baseColumnName = ResolveBaseColumnName(selection, columnName, tableColumns);
|
||||
if (baseColumnName is not null && tableColumns.TryGetValue(baseColumnName, out var columnInfo))
|
||||
return StripTypeLength(columnInfo.TypeName);
|
||||
}
|
||||
EnsureDeclaredTypeCache();
|
||||
if ((uint)ordinal >= (uint)_declaredTypeNames.Length)
|
||||
throw new ArgumentOutOfRangeException(nameof(ordinal), ordinal, null);
|
||||
|
||||
var match = Regex.Match(_command.CommandText, @"^\s*SELECT\s+(?<column>[\w\[\]""`]+)\s+FROM\s+(?<table>[\w\[\]""`]+)", RegexOptions.IgnoreCase);
|
||||
if (!match.Success || _command.Connection is null)
|
||||
return string.Empty;
|
||||
return _declaredTypeNames[ordinal] ??= ResolveDeclaredTypeName(ordinal);
|
||||
}
|
||||
|
||||
var column = UnquoteIdentifier(match.Groups["column"].Value);
|
||||
if (!string.Equals(column, GetName(ordinal), StringComparison.OrdinalIgnoreCase))
|
||||
return string.Empty;
|
||||
private void EnsureDeclaredTypeCache()
|
||||
{
|
||||
if (_declaredTypeStatement is not null && ReferenceEquals(_declaredTypeStatement, _statement))
|
||||
return;
|
||||
|
||||
var table = UnquoteIdentifier(match.Groups["table"].Value);
|
||||
using var command = _command.Connection.CreateCommand();
|
||||
command.CommandText = $"PRAGMA table_info({QuoteIdentifier(table)});";
|
||||
using var reader = command.ExecuteReader();
|
||||
while (reader.Read())
|
||||
{
|
||||
if (string.Equals(reader.GetString(1), column, StringComparison.OrdinalIgnoreCase))
|
||||
return StripTypeLength(reader.GetString(2));
|
||||
}
|
||||
_declaredTypeStatement = _statement;
|
||||
_declaredTypeNames = _statement is null ? [] : new string?[TursoBindings.GetFieldCount(_statement)];
|
||||
}
|
||||
|
||||
return string.Empty;
|
||||
private string ResolveDeclaredTypeName(int ordinal)
|
||||
{
|
||||
// Like sqlite3_column_decltype: the declared type of a direct table-column reference,
|
||||
// nothing for an expression.
|
||||
var declaredType = TursoBindings.GetDeclaredTypeName(GetStatement(), ordinal);
|
||||
return string.IsNullOrEmpty(declaredType) ? string.Empty : StripTypeLength(declaredType);
|
||||
}
|
||||
|
||||
private static string InferDataTypeName(string expression)
|
||||
|
||||
@@ -1128,6 +1128,77 @@ public class SqliteFacadeTests
|
||||
schema.Rows[2][SchemaTableColumn.DataType].Should().Be(typeof(byte[]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetValueResolvesDeclaredTypesForEachResultSet()
|
||||
{
|
||||
using var connection = new SqliteConnection("Data Source=:memory:");
|
||||
connection.Open();
|
||||
connection.ExecuteNonQuery(
|
||||
"""
|
||||
CREATE TABLE GuidIds (Id GUID);
|
||||
CREATE TABLE TextIds (Id TEXT);
|
||||
INSERT INTO GuidIds VALUES ('dc0d7e0e-365d-4948-ab9b-8ca8056bf93a'), ('0e7e0ddc-5d36-4849-ab9b-8ca8056bf93a');
|
||||
INSERT INTO TextIds VALUES ('dc0d7e0e-365d-4948-ab9b-8ca8056bf93a');
|
||||
""");
|
||||
|
||||
using var reader = connection.ExecuteReader("SELECT Id FROM GuidIds; SELECT Id FROM TextIds;");
|
||||
reader.Read().Should().BeTrue();
|
||||
reader.GetValue(0).Should().BeOfType<Guid>();
|
||||
reader.Read().Should().BeTrue();
|
||||
reader.GetValue(0).Should().Be(new Guid("0e7e0ddc-5d36-4849-ab9b-8ca8056bf93a"));
|
||||
|
||||
reader.NextResult().Should().BeTrue();
|
||||
reader.Read().Should().BeTrue();
|
||||
reader.GetValue(0).Should().Be("dc0d7e0e-365d-4948-ab9b-8ca8056bf93a");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetValueResolvesDeclaredTypesThroughAliasesAndJoins()
|
||||
{
|
||||
using var connection = new SqliteConnection("Data Source=:memory:");
|
||||
connection.Open();
|
||||
connection.ExecuteNonQuery(
|
||||
"""
|
||||
CREATE TABLE GuidIds (Id GUID);
|
||||
CREATE TABLE TextIds (Id TEXT);
|
||||
INSERT INTO GuidIds VALUES ('dc0d7e0e-365d-4948-ab9b-8ca8056bf93a');
|
||||
INSERT INTO TextIds VALUES ('dc0d7e0e-365d-4948-ab9b-8ca8056bf93a');
|
||||
""");
|
||||
|
||||
using var reader = connection.ExecuteReader("SELECT t.Id AS TextId, g.Id AS GuidId FROM TextIds t JOIN GuidIds g ON g.Id = t.Id");
|
||||
reader.Read().Should().BeTrue();
|
||||
reader.GetDataTypeName(0).Should().Be("TEXT");
|
||||
reader.GetValue(0).Should().Be("dc0d7e0e-365d-4948-ab9b-8ca8056bf93a");
|
||||
reader.GetDataTypeName(1).Should().Be("GUID");
|
||||
reader.GetValue(1).Should().Be(new Guid("dc0d7e0e-365d-4948-ab9b-8ca8056bf93a"));
|
||||
reader.Invoking(r => r.GetDataTypeName(2)).Should().Throw<ArgumentOutOfRangeException>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetValueUsesStorageTypeWhenNoDeclaredTypeIsAvailable()
|
||||
{
|
||||
using var connection = new SqliteConnection("Data Source=:memory:");
|
||||
connection.Open();
|
||||
connection.ExecuteNonQuery(
|
||||
"""
|
||||
CREATE TABLE Items (Id GUID, Untyped);
|
||||
INSERT INTO Items VALUES ('dc0d7e0e-365d-4948-ab9b-8ca8056bf93a', 'dc0d7e0e-365d-4948-ab9b-8ca8056bf93a');
|
||||
""");
|
||||
|
||||
// An expression over a GUID column and a column declared without a type have no declared type,
|
||||
// so values are returned as stored instead of being converted to Guid.
|
||||
using var reader = connection.ExecuteReader("SELECT lower(Id), Untyped, Id || '', 1 + 1 FROM Items");
|
||||
reader.Read().Should().BeTrue();
|
||||
reader.GetDataTypeName(0).Should().Be("TEXT");
|
||||
reader.GetValue(0).Should().Be("dc0d7e0e-365d-4948-ab9b-8ca8056bf93a");
|
||||
reader.GetDataTypeName(1).Should().Be("TEXT");
|
||||
reader.GetValue(1).Should().Be("dc0d7e0e-365d-4948-ab9b-8ca8056bf93a");
|
||||
reader.GetDataTypeName(2).Should().Be("TEXT");
|
||||
reader.GetValue(2).Should().Be("dc0d7e0e-365d-4948-ab9b-8ca8056bf93a");
|
||||
reader.GetDataTypeName(3).Should().Be("INTEGER");
|
||||
reader.GetValue(3).Should().Be(2L);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetFieldValueThrowsForNullTypedValues()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user