mirror of
https://github.com/allankoechke/turso.git
synced 2026-11-30 11:12:58 +00:00
bindings/dotnet: enable EF Core remote and replica backends
Route EF Core connection, creator, migration, and helper behavior through the merged Turso.Data.Sqlite backend modes so direct remote and embedded-replica connection strings work without changing local semantics. Reject client-only SQLite helper SQL before direct-remote execution and keep replica deletion limited to local database sidecars. Tests: net8/net9/net10 solution build; focused EF local/remote/replica tests; full .NET suite; live Cloud direct/replica EF smoke
This commit is contained in:
@@ -280,7 +280,7 @@ Supported common connection string keywords include:
|
||||
|
||||
## 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.
|
||||
`Turso.EntityFrameworkCore.Sqlite` adds a `UseTurso` provider hook for local, direct remote, and embedded-replica Turso databases. It reuses EF Core SQLite's LINQ translation pipeline and executes generated SQL through the `Turso.Data.Sqlite` facade.
|
||||
|
||||
```bash
|
||||
dotnet add package Turso.EntityFrameworkCore.Sqlite
|
||||
@@ -310,6 +310,6 @@ var options = new DbContextOptionsBuilder<AppDbContext>()
|
||||
.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.
|
||||
The provider supports normal EF Core CRUD, generated keys, transactions, migrations, and schema creation through `EnsureCreated` and `EnsureCreatedAsync`. Use the same remote and replica connection strings shown above with `UseTurso`.
|
||||
|
||||
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.
|
||||
Direct remote connections cannot run EF's client-side SQLite helpers, including `REGEXP`, decimal `ef_*` functions, and the `EF_DECIMAL` collation; queries that need them fail before SQL is sent. `EnsureDeleted` cannot delete a direct remote database and points callers to the Turso platform API. For embedded replicas, `EnsureDeleted` removes only the local replica and its sidecar files, never the remote database.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Data;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Sqlite.Migrations.Internal;
|
||||
using Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal;
|
||||
using Microsoft.EntityFrameworkCore.Storage;
|
||||
using TursoSqliteConnection = Turso.Data.Sqlite.SqliteConnection;
|
||||
@@ -17,21 +18,26 @@ public class TursoSqliteDatabaseCreator(
|
||||
: RelationalDatabaseCreator(dependencies)
|
||||
{
|
||||
private const int SQLITE_CANTOPEN = 14;
|
||||
private const string ProbeSql = "SELECT 1;";
|
||||
private const string HasTablesSql =
|
||||
"SELECT COUNT(*) FROM \"sqlite_master\" "
|
||||
+ "WHERE \"type\" = 'table' AND \"rootpage\" IS NOT NULL "
|
||||
+ "AND \"name\" NOT LIKE 'sqlite_%' "
|
||||
+ "AND \"name\" NOT LIKE 'turso_%' "
|
||||
+ "AND \"name\" NOT LIKE '__turso_%';";
|
||||
private const string EnableWalSql = "PRAGMA journal_mode = 'wal';";
|
||||
|
||||
public override void Create()
|
||||
{
|
||||
var options = GetConnectionOptions();
|
||||
if (options.IsDirectRemote)
|
||||
return;
|
||||
|
||||
Dependencies.Connection.Open();
|
||||
try
|
||||
{
|
||||
rawSqlCommandBuilder.Build("PRAGMA journal_mode = 'wal';")
|
||||
.ExecuteNonQuery(
|
||||
new RelationalCommandParameterObject(
|
||||
Dependencies.Connection,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
Dependencies.CommandLogger,
|
||||
CommandSource.Migrations));
|
||||
if (options.IsLocal)
|
||||
ExecuteNonQuery(EnableWalSql, Dependencies.Connection);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -39,19 +45,42 @@ public class TursoSqliteDatabaseCreator(
|
||||
}
|
||||
}
|
||||
|
||||
public override async Task CreateAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var options = GetConnectionOptions();
|
||||
if (options.IsDirectRemote)
|
||||
return;
|
||||
|
||||
await Dependencies.Connection.OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (options.IsLocal)
|
||||
{
|
||||
await ExecuteNonQueryAsync(EnableWalSql, Dependencies.Connection, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
await Dependencies.Connection.CloseAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
public override bool Exists()
|
||||
{
|
||||
var connectionOptions = new TursoSqliteConnectionStringBuilder(connection.ConnectionString);
|
||||
if (connectionOptions.DataSource.Equals(":memory:", StringComparison.OrdinalIgnoreCase)
|
||||
|| connectionOptions.Mode == TursoSqliteOpenMode.Memory)
|
||||
{
|
||||
var options = GetConnectionOptions();
|
||||
if (IsMemory(options))
|
||||
return true;
|
||||
}
|
||||
if (options.IsReplica)
|
||||
return File.Exists(options.ReplicaPath);
|
||||
|
||||
using var readOnlyConnection = connection.CreateReadOnlyConnection();
|
||||
try
|
||||
{
|
||||
readOnlyConnection.Open(errorsExpected: true);
|
||||
if (options.IsDirectRemote)
|
||||
_ = ExecuteScalar(ProbeSql, readOnlyConnection);
|
||||
}
|
||||
catch (TursoSqliteException ex) when (ex.SqliteErrorCode == SQLITE_CANTOPEN)
|
||||
{
|
||||
@@ -65,46 +94,306 @@ public class TursoSqliteDatabaseCreator(
|
||||
return true;
|
||||
}
|
||||
|
||||
public override bool HasTables()
|
||||
public override async Task<bool> ExistsAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var count = (long)rawSqlCommandBuilder
|
||||
.Build("SELECT COUNT(*) FROM \"sqlite_master\" WHERE \"type\" = 'table' AND \"rootpage\" IS NOT NULL;")
|
||||
.ExecuteScalar(
|
||||
new RelationalCommandParameterObject(
|
||||
Dependencies.Connection,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
Dependencies.CommandLogger,
|
||||
CommandSource.Migrations))!;
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var options = GetConnectionOptions();
|
||||
if (IsMemory(options))
|
||||
return true;
|
||||
if (options.IsReplica)
|
||||
return File.Exists(options.ReplicaPath);
|
||||
|
||||
return count != 0;
|
||||
await using var readOnlyConnection = connection.CreateReadOnlyConnection();
|
||||
try
|
||||
{
|
||||
await readOnlyConnection.OpenAsync(cancellationToken, errorsExpected: true).ConfigureAwait(false);
|
||||
if (options.IsDirectRemote)
|
||||
{
|
||||
_ = await ExecuteScalarAsync(ProbeSql, readOnlyConnection, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (TursoSqliteException ex) when (ex.SqliteErrorCode == SQLITE_CANTOPEN)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
await readOnlyConnection.CloseAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public override bool HasTables()
|
||||
=> Convert.ToInt64(ExecuteScalar(HasTablesSql, Dependencies.Connection)) != 0;
|
||||
|
||||
public override async Task<bool> HasTablesAsync(CancellationToken cancellationToken = default)
|
||||
=> Convert.ToInt64(
|
||||
await ExecuteScalarAsync(HasTablesSql, Dependencies.Connection, cancellationToken)
|
||||
.ConfigureAwait(false)) != 0;
|
||||
|
||||
public override void Delete()
|
||||
{
|
||||
var options = GetConnectionOptions();
|
||||
ThrowIfDirectRemoteDelete(options);
|
||||
|
||||
var dbConnection = Dependencies.Connection.DbConnection;
|
||||
var wasOpen = dbConnection.State == ConnectionState.Open;
|
||||
var path = options.IsReplica
|
||||
? options.ReplicaPath
|
||||
: GetOpenLocalPath();
|
||||
|
||||
if (!wasOpen)
|
||||
Dependencies.Connection.Open();
|
||||
|
||||
var path = dbConnection.DataSource;
|
||||
Dependencies.Connection.Close();
|
||||
if (dbConnection.State != ConnectionState.Closed)
|
||||
dbConnection.Close();
|
||||
DeleteDatabaseFiles(path, options.IsReplica);
|
||||
|
||||
if (!string.IsNullOrEmpty(path) && !path.Equals(":memory:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
TursoSqliteConnection.ClearAllPools();
|
||||
File.Delete(path);
|
||||
File.Delete(path + "-wal");
|
||||
File.Delete(path + "-shm");
|
||||
}
|
||||
else if (wasOpen)
|
||||
{
|
||||
TursoSqliteConnection.ClearPool(new TursoSqliteConnection(Dependencies.Connection.ConnectionString));
|
||||
}
|
||||
|
||||
if (wasOpen)
|
||||
if (wasOpen && options.IsLocal)
|
||||
Dependencies.Connection.Open();
|
||||
}
|
||||
|
||||
public override async Task DeleteAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var options = GetConnectionOptions();
|
||||
ThrowIfDirectRemoteDelete(options);
|
||||
|
||||
var dbConnection = Dependencies.Connection.DbConnection;
|
||||
var wasOpen = dbConnection.State == ConnectionState.Open;
|
||||
string path;
|
||||
if (options.IsReplica)
|
||||
{
|
||||
path = options.ReplicaPath;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!wasOpen)
|
||||
await Dependencies.Connection.OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
path = dbConnection.DataSource;
|
||||
}
|
||||
|
||||
await Dependencies.Connection.CloseAsync().ConfigureAwait(false);
|
||||
if (dbConnection.State != ConnectionState.Closed)
|
||||
await dbConnection.CloseAsync().ConfigureAwait(false);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
DeleteDatabaseFiles(path, options.IsReplica);
|
||||
|
||||
if (wasOpen && options.IsLocal)
|
||||
await Dependencies.Connection.OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private TursoSqliteConnectionStringBuilder GetConnectionOptions()
|
||||
=> new(connection.ConnectionString);
|
||||
|
||||
private string GetOpenLocalPath()
|
||||
{
|
||||
var dbConnection = Dependencies.Connection.DbConnection;
|
||||
if (dbConnection.State != ConnectionState.Open)
|
||||
Dependencies.Connection.Open();
|
||||
return dbConnection.DataSource;
|
||||
}
|
||||
|
||||
private object? ExecuteScalar(string sql, IRelationalConnection relationalConnection)
|
||||
=> rawSqlCommandBuilder.Build(sql)
|
||||
.ExecuteScalar(CreateCommandParameters(relationalConnection));
|
||||
|
||||
private Task<object?> ExecuteScalarAsync(
|
||||
string sql,
|
||||
IRelationalConnection relationalConnection,
|
||||
CancellationToken cancellationToken)
|
||||
=> rawSqlCommandBuilder.Build(sql)
|
||||
.ExecuteScalarAsync(CreateCommandParameters(relationalConnection), cancellationToken);
|
||||
|
||||
private void ExecuteNonQuery(string sql, IRelationalConnection relationalConnection)
|
||||
=> rawSqlCommandBuilder.Build(sql)
|
||||
.ExecuteNonQuery(CreateCommandParameters(relationalConnection));
|
||||
|
||||
private Task<int> ExecuteNonQueryAsync(
|
||||
string sql,
|
||||
IRelationalConnection relationalConnection,
|
||||
CancellationToken cancellationToken)
|
||||
=> rawSqlCommandBuilder.Build(sql)
|
||||
.ExecuteNonQueryAsync(CreateCommandParameters(relationalConnection), cancellationToken);
|
||||
|
||||
private RelationalCommandParameterObject CreateCommandParameters(IRelationalConnection relationalConnection)
|
||||
=> new(
|
||||
relationalConnection,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
Dependencies.CommandLogger,
|
||||
CommandSource.Migrations);
|
||||
|
||||
private static bool IsMemory(TursoSqliteConnectionStringBuilder options)
|
||||
=> options.IsLocal
|
||||
&& (options.DataSource.Equals(":memory:", StringComparison.OrdinalIgnoreCase)
|
||||
|| options.Mode == TursoSqliteOpenMode.Memory)
|
||||
|| options.IsReplica
|
||||
&& options.ReplicaPath.Equals(":memory:", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private static void ThrowIfDirectRemoteDelete(TursoSqliteConnectionStringBuilder options)
|
||||
{
|
||||
if (options.IsDirectRemote)
|
||||
{
|
||||
throw new NotSupportedException(
|
||||
"Deleting a direct remote Turso database is not supported. "
|
||||
+ "Use the Turso platform API to delete the remote database.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void DeleteDatabaseFiles(string path, bool includeReplicaSidecars)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path)
|
||||
|| path.Equals(":memory:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
TursoSqliteConnection.ClearAllPools();
|
||||
var fullPath = Path.GetFullPath(path);
|
||||
File.Delete(fullPath);
|
||||
File.Delete(fullPath + "-journal");
|
||||
File.Delete(fullPath + "-wal");
|
||||
File.Delete(fullPath + "-shm");
|
||||
|
||||
if (!includeReplicaSidecars)
|
||||
return;
|
||||
|
||||
File.Delete(Path.ChangeExtension(fullPath, ".db-log"));
|
||||
File.Delete(fullPath + "-wal-revert");
|
||||
File.Delete(fullPath + "-info");
|
||||
File.Delete(fullPath + "-changes");
|
||||
File.Delete(fullPath + "-replace-base-apply");
|
||||
|
||||
var directory = Path.GetDirectoryName(fullPath);
|
||||
if (directory is null || !Directory.Exists(directory))
|
||||
return;
|
||||
|
||||
var fileName = Path.GetFileName(fullPath);
|
||||
foreach (var backup in Directory.EnumerateFiles(
|
||||
directory,
|
||||
fileName + "-replace-base-apply-*.backup",
|
||||
SearchOption.TopDirectoryOnly))
|
||||
{
|
||||
File.Delete(backup);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class TursoSqliteHistoryRepository(HistoryRepositoryDependencies dependencies)
|
||||
: SqliteHistoryRepository(dependencies)
|
||||
{
|
||||
private static readonly TimeSpan MigrationLockRetryDelay = TimeSpan.FromSeconds(1);
|
||||
|
||||
protected override string LockTableName { get; } = "__EFMigrationsLock";
|
||||
|
||||
protected override string ExistsSql
|
||||
{
|
||||
get
|
||||
{
|
||||
var stringTypeMapping = Dependencies.TypeMappingSource.GetMapping(typeof(string));
|
||||
return "SELECT COUNT(*) FROM \"sqlite_master\" WHERE \"name\" = "
|
||||
+ stringTypeMapping.GenerateSqlLiteral(TableName)
|
||||
+ " COLLATE NOCASE AND \"type\" = 'table';";
|
||||
}
|
||||
}
|
||||
|
||||
public override IMigrationsDatabaseLock AcquireDatabaseLock()
|
||||
{
|
||||
if (!IsDirectRemote)
|
||||
return base.AcquireDatabaseLock();
|
||||
|
||||
Dependencies.MigrationsLogger.AcquiringMigrationLock();
|
||||
CreateLockTableCommand().ExecuteNonQuery(CreateCommandParameters());
|
||||
|
||||
var retryDelay = MigrationLockRetryDelay;
|
||||
while (true)
|
||||
{
|
||||
var relationalCommandParameters = CreateCommandParameters();
|
||||
var migrationLock = new SqliteMigrationDatabaseLock(
|
||||
CreateDeleteLockCommand(),
|
||||
relationalCommandParameters,
|
||||
this);
|
||||
if (CreateInsertLockCommand(DateTimeOffset.UtcNow)
|
||||
.ExecuteScalar(relationalCommandParameters) is not null)
|
||||
{
|
||||
return migrationLock;
|
||||
}
|
||||
|
||||
Thread.Sleep(retryDelay);
|
||||
if (retryDelay < TimeSpan.FromMinutes(1))
|
||||
retryDelay += retryDelay;
|
||||
}
|
||||
}
|
||||
|
||||
public override async Task<IMigrationsDatabaseLock> AcquireDatabaseLockAsync(
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!IsDirectRemote)
|
||||
return await base.AcquireDatabaseLockAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
Dependencies.MigrationsLogger.AcquiringMigrationLock();
|
||||
await CreateLockTableCommand()
|
||||
.ExecuteNonQueryAsync(CreateCommandParameters(), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var retryDelay = MigrationLockRetryDelay;
|
||||
while (true)
|
||||
{
|
||||
var relationalCommandParameters = CreateCommandParameters();
|
||||
var migrationLock = new SqliteMigrationDatabaseLock(
|
||||
CreateDeleteLockCommand(),
|
||||
relationalCommandParameters,
|
||||
this);
|
||||
if (await CreateInsertLockCommand(DateTimeOffset.UtcNow)
|
||||
.ExecuteScalarAsync(relationalCommandParameters, cancellationToken)
|
||||
.ConfigureAwait(false) is not null)
|
||||
{
|
||||
return migrationLock;
|
||||
}
|
||||
|
||||
await Task.Delay(retryDelay, cancellationToken).ConfigureAwait(false);
|
||||
if (retryDelay < TimeSpan.FromMinutes(1))
|
||||
retryDelay += retryDelay;
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsDirectRemote
|
||||
=> Dependencies.Connection.DbConnection is TursoSqliteConnection { IsDirectRemote: true };
|
||||
|
||||
private IRelationalCommand CreateLockTableCommand()
|
||||
=> Dependencies.RawSqlCommandBuilder.Build(
|
||||
$"""
|
||||
CREATE TABLE IF NOT EXISTS "{LockTableName}" (
|
||||
"Id" INTEGER NOT NULL CONSTRAINT "PK_{LockTableName}" PRIMARY KEY,
|
||||
"Timestamp" TEXT NOT NULL
|
||||
);
|
||||
""");
|
||||
|
||||
private IRelationalCommand CreateInsertLockCommand(DateTimeOffset timestamp)
|
||||
{
|
||||
var timestampLiteral = Dependencies.TypeMappingSource.GetMapping(typeof(DateTimeOffset))
|
||||
.GenerateSqlLiteral(timestamp);
|
||||
return Dependencies.RawSqlCommandBuilder.Build(
|
||||
$"""
|
||||
INSERT OR IGNORE INTO "{LockTableName}"("Id", "Timestamp") VALUES(1, {timestampLiteral})
|
||||
RETURNING "Id";
|
||||
""");
|
||||
}
|
||||
|
||||
private IRelationalCommand CreateDeleteLockCommand()
|
||||
=> Dependencies.RawSqlCommandBuilder.Build(
|
||||
$"""
|
||||
DELETE FROM "{LockTableName}";
|
||||
""");
|
||||
|
||||
private RelationalCommandParameterObject CreateCommandParameters()
|
||||
=> new(
|
||||
Dependencies.Connection,
|
||||
null,
|
||||
null,
|
||||
Dependencies.CurrentContext.Context,
|
||||
Dependencies.CommandLogger,
|
||||
CommandSource.Migrations);
|
||||
}
|
||||
|
||||
@@ -63,6 +63,9 @@ public class TursoSqliteRelationalConnection : SqliteRelationalConnection
|
||||
if (_commandTimeout.HasValue)
|
||||
connection.DefaultTimeout = _commandTimeout.Value;
|
||||
|
||||
if (connection.IsDirectRemote)
|
||||
return;
|
||||
|
||||
connection.CreateFunction<string, string, bool?>(
|
||||
"regexp",
|
||||
(pattern, input) => input is null || pattern is null
|
||||
@@ -150,3 +153,246 @@ public class TursoSqliteRelationalConnection : SqliteRelationalConnection
|
||||
decimal.Parse(right, NumberStyles.Number, CultureInfo.InvariantCulture)));
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class TursoSqliteCommandInterceptor : DbCommandInterceptor
|
||||
{
|
||||
public static TursoSqliteCommandInterceptor Instance { get; } = new();
|
||||
|
||||
public override InterceptionResult<int> NonQueryExecuting(
|
||||
DbCommand command,
|
||||
CommandEventData eventData,
|
||||
InterceptionResult<int> result)
|
||||
{
|
||||
Validate(command);
|
||||
return result;
|
||||
}
|
||||
|
||||
public override ValueTask<InterceptionResult<int>> NonQueryExecutingAsync(
|
||||
DbCommand command,
|
||||
CommandEventData eventData,
|
||||
InterceptionResult<int> result,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
Validate(command);
|
||||
return ValueTask.FromResult(result);
|
||||
}
|
||||
|
||||
public override InterceptionResult<object> ScalarExecuting(
|
||||
DbCommand command,
|
||||
CommandEventData eventData,
|
||||
InterceptionResult<object> result)
|
||||
{
|
||||
Validate(command);
|
||||
return result;
|
||||
}
|
||||
|
||||
public override ValueTask<InterceptionResult<object>> ScalarExecutingAsync(
|
||||
DbCommand command,
|
||||
CommandEventData eventData,
|
||||
InterceptionResult<object> result,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
Validate(command);
|
||||
return ValueTask.FromResult(result);
|
||||
}
|
||||
|
||||
public override InterceptionResult<DbDataReader> ReaderExecuting(
|
||||
DbCommand command,
|
||||
CommandEventData eventData,
|
||||
InterceptionResult<DbDataReader> result)
|
||||
{
|
||||
Validate(command);
|
||||
return result;
|
||||
}
|
||||
|
||||
public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
|
||||
DbCommand command,
|
||||
CommandEventData eventData,
|
||||
InterceptionResult<DbDataReader> result,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
Validate(command);
|
||||
return ValueTask.FromResult(result);
|
||||
}
|
||||
|
||||
private static void Validate(DbCommand command)
|
||||
{
|
||||
if (command.Connection is not TursoSqliteConnection { IsDirectRemote: true })
|
||||
return;
|
||||
|
||||
var unsupportedToken = FindUnsupportedToken(command.CommandText);
|
||||
if (unsupportedToken is not null)
|
||||
{
|
||||
throw new NotSupportedException(
|
||||
$"Direct remote Turso connections do not support the client-side SQLite helper '{unsupportedToken}'. "
|
||||
+ "Use SQL supported by the remote database or use a local database.");
|
||||
}
|
||||
}
|
||||
|
||||
private static string? FindUnsupportedToken(string sql)
|
||||
{
|
||||
string? previousIdentifier = null;
|
||||
for (var index = 0; index < sql.Length;)
|
||||
{
|
||||
if (TrySkipTriviaOrString(sql, ref index))
|
||||
continue;
|
||||
|
||||
if (!IsIdentifierStart(sql[index]))
|
||||
{
|
||||
index++;
|
||||
continue;
|
||||
}
|
||||
|
||||
var start = index++;
|
||||
while (index < sql.Length && IsIdentifierPart(sql[index]))
|
||||
index++;
|
||||
|
||||
var token = sql[start..index];
|
||||
var next = NextSignificantCharacter(sql, index);
|
||||
if ((IsDecimalHelper(token) && next == '(')
|
||||
|| (token.Equals("EF_DECIMAL", StringComparison.OrdinalIgnoreCase)
|
||||
&& previousIdentifier?.Equals("COLLATE", StringComparison.OrdinalIgnoreCase) == true)
|
||||
|| (token.Equals("REGEXP", StringComparison.OrdinalIgnoreCase)
|
||||
&& IsRegexpOperator(sql, start, previousIdentifier, next)))
|
||||
{
|
||||
return token;
|
||||
}
|
||||
|
||||
previousIdentifier = token;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static char NextSignificantCharacter(string sql, int index)
|
||||
{
|
||||
while (index < sql.Length && char.IsWhiteSpace(sql[index]))
|
||||
index++;
|
||||
return index < sql.Length ? sql[index] : '\0';
|
||||
}
|
||||
|
||||
private static bool IsRegexpOperator(
|
||||
string sql,
|
||||
int tokenStart,
|
||||
string? previousIdentifier,
|
||||
char next)
|
||||
{
|
||||
if (next == '(')
|
||||
return true;
|
||||
|
||||
var previousIndex = tokenStart - 1;
|
||||
while (previousIndex >= 0 && char.IsWhiteSpace(sql[previousIndex]))
|
||||
previousIndex--;
|
||||
if (previousIndex < 0 || sql[previousIndex] is ',' or '.' or '(')
|
||||
return false;
|
||||
if (sql[previousIndex] is '"' or ']' or '`' or '\'' or ')' or '?'
|
||||
|| char.IsAsciiDigit(sql[previousIndex]))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return previousIdentifier is not null
|
||||
&& !IsExpressionIntroducer(previousIdentifier);
|
||||
}
|
||||
|
||||
private static bool IsExpressionIntroducer(string token)
|
||||
=> token.Equals("SELECT", StringComparison.OrdinalIgnoreCase)
|
||||
|| token.Equals("WHERE", StringComparison.OrdinalIgnoreCase)
|
||||
|| token.Equals("AND", StringComparison.OrdinalIgnoreCase)
|
||||
|| token.Equals("OR", StringComparison.OrdinalIgnoreCase)
|
||||
|| token.Equals("ON", StringComparison.OrdinalIgnoreCase)
|
||||
|| token.Equals("WHEN", StringComparison.OrdinalIgnoreCase)
|
||||
|| token.Equals("THEN", StringComparison.OrdinalIgnoreCase)
|
||||
|| token.Equals("ELSE", StringComparison.OrdinalIgnoreCase)
|
||||
|| token.Equals("AS", StringComparison.OrdinalIgnoreCase)
|
||||
|| token.Equals("BY", StringComparison.OrdinalIgnoreCase)
|
||||
|| token.Equals("SET", StringComparison.OrdinalIgnoreCase)
|
||||
|| token.Equals("VALUES", StringComparison.OrdinalIgnoreCase)
|
||||
|| token.Equals("RETURNING", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private static bool TrySkipTriviaOrString(string sql, ref int index)
|
||||
{
|
||||
if (sql[index] == '\'')
|
||||
{
|
||||
SkipDelimited(sql, ref index, '\'');
|
||||
return true;
|
||||
}
|
||||
|
||||
if (sql[index] == '"')
|
||||
{
|
||||
SkipDelimited(sql, ref index, '"');
|
||||
return true;
|
||||
}
|
||||
|
||||
if (sql[index] == '`')
|
||||
{
|
||||
SkipDelimited(sql, ref index, '`');
|
||||
return true;
|
||||
}
|
||||
|
||||
if (sql[index] == '[')
|
||||
{
|
||||
SkipDelimited(sql, ref index, ']');
|
||||
return true;
|
||||
}
|
||||
|
||||
if (sql[index] == '-' && index + 1 < sql.Length && sql[index + 1] == '-')
|
||||
{
|
||||
index += 2;
|
||||
while (index < sql.Length && sql[index] is not ('\r' or '\n'))
|
||||
index++;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (sql[index] == '/' && index + 1 < sql.Length && sql[index + 1] == '*')
|
||||
{
|
||||
index += 2;
|
||||
while (index + 1 < sql.Length && (sql[index] != '*' || sql[index + 1] != '/'))
|
||||
index++;
|
||||
index = Math.Min(index + 2, sql.Length);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void SkipDelimited(string sql, ref int index, char closing)
|
||||
{
|
||||
index++;
|
||||
while (index < sql.Length)
|
||||
{
|
||||
if (sql[index] != closing)
|
||||
{
|
||||
index++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (index + 1 < sql.Length && sql[index + 1] == closing)
|
||||
{
|
||||
index += 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
index++;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsDecimalHelper(string token)
|
||||
=> token.Equals("ef_mod", StringComparison.OrdinalIgnoreCase)
|
||||
|| token.Equals("ef_add", StringComparison.OrdinalIgnoreCase)
|
||||
|| token.Equals("ef_divide", StringComparison.OrdinalIgnoreCase)
|
||||
|| token.Equals("ef_compare", StringComparison.OrdinalIgnoreCase)
|
||||
|| token.Equals("ef_multiply", StringComparison.OrdinalIgnoreCase)
|
||||
|| token.Equals("ef_negate", StringComparison.OrdinalIgnoreCase)
|
||||
|| token.Equals("ef_avg", StringComparison.OrdinalIgnoreCase)
|
||||
|| token.Equals("ef_max", StringComparison.OrdinalIgnoreCase)
|
||||
|| token.Equals("ef_min", StringComparison.OrdinalIgnoreCase)
|
||||
|| token.Equals("ef_sum", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private static bool IsIdentifierStart(char value)
|
||||
=> value is '_' || char.IsLetter(value);
|
||||
|
||||
private static bool IsIdentifierPart(char value)
|
||||
=> value is '_' || char.IsLetterOrDigit(value);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
<PackageId>Turso.EntityFrameworkCore.Sqlite</PackageId>
|
||||
<Title>Turso Entity Framework Core SQLite Provider</Title>
|
||||
<Description>Entity Framework Core integration for Turso local databases using EF Core SQLite translation and Turso.Data.Sqlite execution.</Description>
|
||||
<Description>Entity Framework Core integration for Turso local, direct remote, and embedded-replica databases using EF Core SQLite translation and Turso.Data.Sqlite execution.</Description>
|
||||
<Authors>Turso authors</Authors>
|
||||
<PackageTags>turso;sqlite;database;entity-framework-core;efcore;linq</PackageTags>
|
||||
<PackageLicenseExpression>MIT</PackageLicenseExpression>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Query;
|
||||
using Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal;
|
||||
using Microsoft.EntityFrameworkCore.Storage;
|
||||
@@ -62,10 +63,14 @@ public static class TursoDbContextOptionsBuilderExtensions
|
||||
=> (DbContextOptionsBuilder<TContext>)UseTurso((DbContextOptionsBuilder)optionsBuilder, connection, contextOwnsConnection, sqliteOptionsAction);
|
||||
|
||||
private static DbContextOptionsBuilder UseTursoServices(DbContextOptionsBuilder optionsBuilder)
|
||||
=> optionsBuilder
|
||||
{
|
||||
optionsBuilder.AddInterceptors(TursoSqliteCommandInterceptor.Instance);
|
||||
return optionsBuilder
|
||||
.ReplaceService<ISqliteRelationalConnection, TursoSqliteRelationalConnection>()
|
||||
.ReplaceService<IRelationalDatabaseCreator, TursoSqliteDatabaseCreator>()
|
||||
.ReplaceService<IHistoryRepository, TursoSqliteHistoryRepository>()
|
||||
.ReplaceService<IQuerySqlGeneratorFactory, TursoSqliteQuerySqlGeneratorFactory>()
|
||||
.ReplaceService<IQueryableMethodTranslatingExpressionVisitorFactory, TursoSqliteQueryableMethodTranslatingExpressionVisitorFactory>()
|
||||
.ReplaceService<IUpdateSqlGenerator, TursoSqliteUpdateSqlGenerator>();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
using System.Data;
|
||||
using AwesomeAssertions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using FacadeConnection = Turso.Data.Sqlite.SqliteConnection;
|
||||
|
||||
namespace Turso.Tests;
|
||||
|
||||
@@ -10,7 +13,7 @@ public sealed class TursoCloudAcceptanceTests
|
||||
{
|
||||
var (remoteUrl, authToken) = GetCloudCredentials();
|
||||
var tableName = "dotnet_interval_" + Guid.NewGuid().ToString("N");
|
||||
var replicaDirectory = NewReplicaDirectory();
|
||||
var replicaDirectory = NewReplicaDirectory("interval");
|
||||
var replicaPath = Path.Combine(replicaDirectory, "replica.db");
|
||||
var remoteConnectionString = $"Data Source={remoteUrl};Auth Token={authToken}";
|
||||
|
||||
@@ -47,6 +50,74 @@ public sealed class TursoCloudAcceptanceTests
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SqliteFacadeAndEfQueryDirectRemoteAndReplica()
|
||||
{
|
||||
var (remoteUrl, authToken) = GetCloudCredentials();
|
||||
var tableName = "dotnet_facade_" + Guid.NewGuid().ToString("N");
|
||||
var replicaDirectory = NewReplicaDirectory("facade-ef");
|
||||
var replicaPath = Path.Combine(replicaDirectory, "replica.db");
|
||||
var remoteConnectionString = $"Data Source={remoteUrl};Auth Token={authToken}";
|
||||
var replicaConnectionString =
|
||||
remoteConnectionString + $";Replica Path={replicaPath};Pooling=True";
|
||||
|
||||
await using var remote = new TursoConnection(remoteConnectionString);
|
||||
await remote.OpenAsync();
|
||||
try
|
||||
{
|
||||
await ExecuteNonQueryAsync(remote, $"CREATE TABLE {tableName}(value TEXT)");
|
||||
await ExecuteNonQueryAsync(remote, $"INSERT INTO {tableName} VALUES ('facade-ef')");
|
||||
|
||||
await using (var facadeRemote = new FacadeConnection(remoteConnectionString))
|
||||
{
|
||||
await facadeRemote.OpenAsync();
|
||||
await using var command = facadeRemote.CreateCommand();
|
||||
command.CommandText = $"SELECT value FROM {tableName}";
|
||||
(await command.ExecuteScalarAsync()).Should().Be("facade-ef");
|
||||
}
|
||||
|
||||
await using (var remoteContext = new DbContext(
|
||||
new DbContextOptionsBuilder()
|
||||
.UseTurso(remoteConnectionString)
|
||||
.Options))
|
||||
{
|
||||
#pragma warning disable EF1002 // tableName is generated from a fixed prefix and Guid("N").
|
||||
var value = await remoteContext.Database
|
||||
.SqlQueryRaw<string>($"SELECT value AS Value FROM {tableName}")
|
||||
.SingleAsync();
|
||||
#pragma warning restore EF1002
|
||||
value.Should().Be("facade-ef");
|
||||
}
|
||||
|
||||
await using (var facadeReplica = new FacadeConnection(replicaConnectionString))
|
||||
{
|
||||
await facadeReplica.OpenAsync();
|
||||
await using var command = facadeReplica.CreateCommand();
|
||||
command.CommandText = $"SELECT value FROM {tableName}";
|
||||
(await command.ExecuteScalarAsync()).Should().Be("facade-ef");
|
||||
}
|
||||
|
||||
await using (var replicaContext = new DbContext(
|
||||
new DbContextOptionsBuilder()
|
||||
.UseTurso(replicaConnectionString)
|
||||
.Options))
|
||||
{
|
||||
#pragma warning disable EF1002 // tableName is generated from a fixed prefix and Guid("N").
|
||||
var value = await replicaContext.Database
|
||||
.SqlQueryRaw<string>($"SELECT value AS Value FROM {tableName}")
|
||||
.SingleAsync();
|
||||
#pragma warning restore EF1002
|
||||
value.Should().Be("facade-ef");
|
||||
}
|
||||
}
|
||||
|
||||
finally
|
||||
{
|
||||
await DropTableAsync(remote, tableName);
|
||||
Directory.Delete(replicaDirectory, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task ExecuteNonQueryAsync(TursoConnection connection, string sql)
|
||||
{
|
||||
await using var command = connection.CreateCommand();
|
||||
@@ -54,6 +125,13 @@ public sealed class TursoCloudAcceptanceTests
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
private static async Task DropTableAsync(TursoConnection remote, string tableName)
|
||||
{
|
||||
if (remote.State != ConnectionState.Open)
|
||||
await remote.OpenAsync();
|
||||
await ExecuteNonQueryAsync(remote, $"DROP TABLE IF EXISTS {tableName}");
|
||||
}
|
||||
|
||||
private static (string RemoteUrl, string AuthToken) GetCloudCredentials()
|
||||
{
|
||||
var remoteUrl = Environment.GetEnvironmentVariable("TURSO_REMOTE_URL");
|
||||
@@ -64,11 +142,11 @@ public sealed class TursoCloudAcceptanceTests
|
||||
return (remoteUrl, authToken);
|
||||
}
|
||||
|
||||
private static string NewReplicaDirectory()
|
||||
private static string NewReplicaDirectory(string suffix)
|
||||
{
|
||||
var path = Path.Combine(
|
||||
TestContext.CurrentContext.WorkDirectory,
|
||||
"turso-cloud-interval-" + Guid.NewGuid().ToString("N"));
|
||||
$"turso-cloud-{suffix}-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(path);
|
||||
return path;
|
||||
}
|
||||
|
||||
842
bindings/dotnet/src/Turso.Tests/TursoEfRemoteReplicaTests.cs
Normal file
842
bindings/dotnet/src/Turso.Tests/TursoEfRemoteReplicaTests.cs
Normal file
@@ -0,0 +1,842 @@
|
||||
using System.Data.Common;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Text.RegularExpressions;
|
||||
using AwesomeAssertions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal;
|
||||
using Microsoft.EntityFrameworkCore.Storage;
|
||||
using Turso.Data.Sqlite;
|
||||
using Turso.EntityFrameworkCore.Sqlite.Storage.Internal;
|
||||
|
||||
namespace Turso.Tests;
|
||||
|
||||
[NonParallelizable]
|
||||
public sealed class TursoEfRemoteReplicaTests
|
||||
{
|
||||
[Test]
|
||||
public async Task DirectRemoteClonesAllSettingsAndRejectsLocalSqlHelpers()
|
||||
{
|
||||
using var handler = new ScriptedEfRemoteHandler();
|
||||
using var handlerScope = UseRemoteHandler(handler);
|
||||
var builder = new SqliteConnectionStringBuilder
|
||||
{
|
||||
DataSource = "https://example.test",
|
||||
AuthToken = "secret",
|
||||
ReadYourWrites = false,
|
||||
DefaultTimeout = 17,
|
||||
Tls = true,
|
||||
};
|
||||
await using var context = CreateContext(builder.ConnectionString);
|
||||
|
||||
var connection = context.Database.GetDbConnection().Should().BeOfType<SqliteConnection>().Subject;
|
||||
connection.IsDirectRemote.Should().BeTrue();
|
||||
connection.IsManaged.Should().BeTrue();
|
||||
|
||||
#pragma warning disable EF1001
|
||||
var relationalConnection = context.GetService<ISqliteRelationalConnection>();
|
||||
await using (var clone = relationalConnection.CreateReadOnlyConnection())
|
||||
#pragma warning restore EF1001
|
||||
{
|
||||
var cloneOptions = new SqliteConnectionStringBuilder(clone.ConnectionString);
|
||||
cloneOptions.DataSource.Should().Be(builder.DataSource);
|
||||
cloneOptions.AuthToken.Should().Be(builder.AuthToken);
|
||||
cloneOptions.ReadYourWrites.Should().Be(builder.ReadYourWrites);
|
||||
cloneOptions.DefaultTimeout.Should().Be(builder.DefaultTimeout);
|
||||
cloneOptions.Tls.Should().Be(builder.Tls);
|
||||
cloneOptions.Mode.Should().Be(SqliteOpenMode.ReadOnly);
|
||||
cloneOptions.Pooling.Should().BeFalse();
|
||||
clone.DbConnection.Should().BeOfType<SqliteConnection>()
|
||||
.Which.IsDirectRemote.Should().BeTrue();
|
||||
}
|
||||
|
||||
await context.Items
|
||||
.Where(item => Regex.IsMatch(item.Name, "^remote"))
|
||||
.Invoking(query => query.ToListAsync())
|
||||
.Should().ThrowAsync<NotSupportedException>()
|
||||
.WithMessage("*REGEXP*");
|
||||
|
||||
await context.Items
|
||||
.Where(item => item.Amount + 1m > 2m)
|
||||
.Invoking(query => query.ToListAsync())
|
||||
.Should().ThrowAsync<NotSupportedException>()
|
||||
.WithMessage("*ef_*");
|
||||
|
||||
await context.Items
|
||||
.OrderBy(item => item.Amount)
|
||||
.Invoking(query => query.ToListAsync())
|
||||
.Should().ThrowAsync<NotSupportedException>()
|
||||
.WithMessage("*EF_DECIMAL*");
|
||||
|
||||
handler.SqlStatements.Should().BeEmpty();
|
||||
|
||||
await context.Database.ExecuteSqlRawAsync("SELECT ef_sum FROM data");
|
||||
await context.Database.ExecuteSqlRawAsync("SELECT EF_DECIMAL FROM data");
|
||||
await context.Database.ExecuteSqlRawAsync("SELECT REGEXP FROM data");
|
||||
handler.SqlStatements.Should().Equal(
|
||||
"SELECT ef_sum FROM data",
|
||||
"SELECT EF_DECIMAL FROM data",
|
||||
"SELECT REGEXP FROM data");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DirectRemoteSupportsMigrationsGeneratedKeysCrudAndTransactions()
|
||||
{
|
||||
using var handler = new ScriptedEfRemoteHandler();
|
||||
using var handlerScope = UseRemoteHandler(handler);
|
||||
await using var context = CreateContext(
|
||||
"Data Source=https://example.test;Auth Token=secret;Read Your Writes=False");
|
||||
var creator = context.GetService<IRelationalDatabaseCreator>();
|
||||
|
||||
await creator.CreateAsync();
|
||||
handler.SqlStatements.Should().BeEmpty();
|
||||
(await creator.ExistsAsync()).Should().BeTrue();
|
||||
handler.SqlStatements.Should().Equal("SELECT 1");
|
||||
|
||||
await context.Database.MigrateAsync();
|
||||
(await context.Database.GetAppliedMigrationsAsync())
|
||||
.Should().ContainSingle()
|
||||
.Which.Should().Be(EfRemoteReplicaMigration.MigrationId);
|
||||
|
||||
var item = new EfRemoteReplicaItem { Name = "one", Amount = 1.25m };
|
||||
context.Items.Add(item);
|
||||
await context.SaveChangesAsync();
|
||||
item.Id.Should().BeGreaterThan(0);
|
||||
|
||||
item.Name = "updated";
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
(await context.Items.SingleAsync()).Name.Should().Be("updated");
|
||||
|
||||
await using (var transaction = await context.Database.BeginTransactionAsync())
|
||||
{
|
||||
context.Items.Add(new EfRemoteReplicaItem { Name = "rolled back", Amount = 2m });
|
||||
await context.SaveChangesAsync();
|
||||
await transaction.RollbackAsync();
|
||||
}
|
||||
|
||||
context.ChangeTracker.Clear();
|
||||
(await context.Items.CountAsync(item => item.Name == "rolled back")).Should().Be(0);
|
||||
|
||||
var stored = await context.Items.SingleAsync();
|
||||
context.Items.Remove(stored);
|
||||
await context.SaveChangesAsync();
|
||||
(await context.Items.CountAsync()).Should().Be(0);
|
||||
|
||||
var requestCount = handler.SqlStatements.Count;
|
||||
await creator.Invoking(value => value.DeleteAsync())
|
||||
.Should().ThrowAsync<NotSupportedException>()
|
||||
.WithMessage("*platform API*");
|
||||
handler.SqlStatements.Should().HaveCount(requestCount);
|
||||
|
||||
handler.SqlStatements.Should().Contain(sql => sql.Contains("__EFMigrationsHistory", StringComparison.Ordinal));
|
||||
handler.SqlStatements.Should().Contain(sql => sql.Contains("RETURNING", StringComparison.OrdinalIgnoreCase));
|
||||
handler.SqlStatements.Should().Contain(sql => sql.StartsWith("BEGIN", StringComparison.OrdinalIgnoreCase));
|
||||
handler.SqlStatements.Should().Contain(sql => sql.StartsWith("SAVEPOINT", StringComparison.OrdinalIgnoreCase));
|
||||
handler.SqlStatements.Should().Contain(sql => sql.StartsWith("RELEASE SAVEPOINT", StringComparison.OrdinalIgnoreCase));
|
||||
handler.SqlStatements.Should().Contain(sql => sql.StartsWith("ROLLBACK", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DirectRemoteEnsureCreatedCreatesTablesAndEnsureDeletedRejectsRemoteDeletion()
|
||||
{
|
||||
using var handler = new ScriptedEfRemoteHandler();
|
||||
using var handlerScope = UseRemoteHandler(handler);
|
||||
await using var context = CreateContext(
|
||||
"Data Source=https://example.test;Auth Token=secret;Read Your Writes=False");
|
||||
|
||||
(await context.Database.EnsureCreatedAsync()).Should().BeTrue();
|
||||
(await context.Database.EnsureCreatedAsync()).Should().BeFalse();
|
||||
(await context.Database.GetService<IRelationalDatabaseCreator>().HasTablesAsync()).Should().BeTrue();
|
||||
|
||||
await context.Database.Invoking(database => database.EnsureDeletedAsync())
|
||||
.Should().ThrowAsync<NotSupportedException>()
|
||||
.WithMessage("*platform API*");
|
||||
|
||||
handler.SqlStatements.Should().Contain(sql => sql.StartsWith("CREATE TABLE", StringComparison.OrdinalIgnoreCase));
|
||||
handler.SqlStatements.Should().NotContain(sql => sql.Contains("PRAGMA journal_mode", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ExternalDirectRemoteConnectionHonorsContextOwnership()
|
||||
{
|
||||
using var handler = new ScriptedEfRemoteHandler();
|
||||
using var handlerScope = UseRemoteHandler(handler);
|
||||
const string connectionString =
|
||||
"Data Source=https://example.test;Auth Token=secret;Read Your Writes=False";
|
||||
|
||||
await using var unownedConnection = new SqliteConnection(connectionString);
|
||||
await unownedConnection.OpenAsync();
|
||||
await using (var context = CreateContext(unownedConnection, contextOwnsConnection: false))
|
||||
(await context.Database.CanConnectAsync()).Should().BeTrue();
|
||||
unownedConnection.State.Should().Be(System.Data.ConnectionState.Open);
|
||||
|
||||
var ownedConnection = new SqliteConnection(connectionString);
|
||||
await ownedConnection.OpenAsync();
|
||||
await using (var context = CreateContext(ownedConnection, contextOwnsConnection: true))
|
||||
(await context.Database.CanConnectAsync()).Should().BeTrue();
|
||||
ownedConnection.State.Should().Be(System.Data.ConnectionState.Closed);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DeferredBootstrapReplicaSupportsMigrationsCrudAndDeletesOnlyReplicaFiles()
|
||||
{
|
||||
var directory = Path.Combine(
|
||||
TestContext.CurrentContext.WorkDirectory,
|
||||
"ef-replica-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(directory);
|
||||
var replicaPath = Path.Combine(directory, "replica.db");
|
||||
var unrelatedPath = Path.Combine(directory, "keep.txt");
|
||||
using var syncScope = RejectSyncRequests();
|
||||
try
|
||||
{
|
||||
var builder = new SqliteConnectionStringBuilder
|
||||
{
|
||||
DataSource = "https://example.test",
|
||||
ReplicaPath = replicaPath,
|
||||
BootstrapIfEmpty = false,
|
||||
Pooling = false,
|
||||
SyncClientName = "ef-replica-test",
|
||||
};
|
||||
await using var context = CreateContext(builder.ConnectionString);
|
||||
var connection = context.Database.GetDbConnection().Should().BeOfType<SqliteConnection>().Subject;
|
||||
connection.IsReplica.Should().BeTrue();
|
||||
connection.IsManaged.Should().BeTrue();
|
||||
|
||||
#pragma warning disable EF1001
|
||||
var relationalConnection = context.GetService<ISqliteRelationalConnection>();
|
||||
await using (var clone = relationalConnection.CreateReadOnlyConnection())
|
||||
#pragma warning restore EF1001
|
||||
{
|
||||
var cloneOptions = new SqliteConnectionStringBuilder(clone.ConnectionString);
|
||||
cloneOptions.DataSource.Should().Be(builder.DataSource);
|
||||
cloneOptions.ReplicaPath.Should().Be(builder.ReplicaPath);
|
||||
cloneOptions.BootstrapIfEmpty.Should().BeFalse();
|
||||
cloneOptions.SyncClientName.Should().Be(builder.SyncClientName);
|
||||
clone.DbConnection.Should().BeOfType<SqliteConnection>()
|
||||
.Which.IsReplica.Should().BeTrue();
|
||||
}
|
||||
|
||||
var creator = context.GetService<IRelationalDatabaseCreator>();
|
||||
(await creator.ExistsAsync()).Should().BeFalse();
|
||||
await creator.CreateAsync();
|
||||
(await creator.ExistsAsync()).Should().BeTrue();
|
||||
(await creator.HasTablesAsync()).Should().BeFalse();
|
||||
|
||||
await context.Database.MigrateAsync();
|
||||
context.Database.GetMigrations()
|
||||
.Should().ContainSingle()
|
||||
.Which.Should().Be(EfRemoteReplicaMigration.MigrationId);
|
||||
File.Exists(replicaPath).Should().BeTrue();
|
||||
(await context.Database.GetAppliedMigrationsAsync())
|
||||
.Should().ContainSingle()
|
||||
.Which.Should().Be(EfRemoteReplicaMigration.MigrationId);
|
||||
|
||||
var item = new EfRemoteReplicaItem { Name = "replica", Amount = 3.5m };
|
||||
context.Items.Add(item);
|
||||
await context.SaveChangesAsync();
|
||||
item.Id.Should().BeGreaterThan(0);
|
||||
|
||||
item.Name = "updated replica";
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
(await context.Items.SingleAsync()).Name.Should().Be("updated replica");
|
||||
(await context.Items
|
||||
.Where(value => value.Amount > 3m)
|
||||
.OrderBy(value => value.Amount)
|
||||
.SingleAsync())
|
||||
.Amount.Should().Be(3.5m);
|
||||
(await context.Items
|
||||
.Where(value => Regex.IsMatch(value.Name, "^updated"))
|
||||
.SingleAsync())
|
||||
.Name.Should().Be("updated replica");
|
||||
|
||||
await using (var transaction = await context.Database.BeginTransactionAsync())
|
||||
{
|
||||
context.Items.Add(new EfRemoteReplicaItem { Name = "rolled back", Amount = 4m });
|
||||
await context.SaveChangesAsync();
|
||||
await transaction.RollbackAsync();
|
||||
}
|
||||
|
||||
context.ChangeTracker.Clear();
|
||||
(await context.Items.CountAsync(item => item.Name == "rolled back")).Should().Be(0);
|
||||
|
||||
await context.Database.CloseConnectionAsync();
|
||||
await File.WriteAllTextAsync(unrelatedPath, "keep");
|
||||
var sidecars = CreateReplicaSidecars(replicaPath);
|
||||
|
||||
(await context.Database.EnsureDeletedAsync()).Should().BeTrue();
|
||||
|
||||
File.Exists(replicaPath).Should().BeFalse();
|
||||
sidecars.Should().OnlyContain(path => !File.Exists(path));
|
||||
File.Exists(unrelatedPath).Should().BeTrue();
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (Directory.Exists(directory))
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task MemoryReplicaExistsWithoutTouchingTheNetworkOrFiles()
|
||||
{
|
||||
var directory = Path.Combine(
|
||||
TestContext.CurrentContext.WorkDirectory,
|
||||
"ef-memory-replica-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(directory);
|
||||
var unrelatedPath = Path.Combine(directory, "keep.txt");
|
||||
await File.WriteAllTextAsync(unrelatedPath, "keep");
|
||||
using var syncScope = RejectSyncRequests();
|
||||
try
|
||||
{
|
||||
var builder = new SqliteConnectionStringBuilder
|
||||
{
|
||||
DataSource = "https://example.test",
|
||||
ReplicaPath = ":memory:",
|
||||
BootstrapIfEmpty = false,
|
||||
Pooling = false,
|
||||
};
|
||||
await using var context = CreateContext(builder.ConnectionString);
|
||||
context.Database.GetDbConnection().Should().BeOfType<SqliteConnection>()
|
||||
.Which.IsReplica.Should().BeTrue();
|
||||
|
||||
var creator = context.GetService<IRelationalDatabaseCreator>();
|
||||
creator.Exists().Should().BeTrue();
|
||||
(await creator.ExistsAsync()).Should().BeTrue();
|
||||
|
||||
creator.Delete();
|
||||
await creator.DeleteAsync();
|
||||
|
||||
File.Exists(unrelatedPath).Should().BeTrue();
|
||||
Directory.EnumerateFiles(directory).Should().ContainSingle();
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (Directory.Exists(directory))
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task LocalDatabaseKeepsSqliteHelpersAndTursoHistoryRepository()
|
||||
{
|
||||
var directory = Path.Combine(
|
||||
TestContext.CurrentContext.WorkDirectory,
|
||||
"ef-local-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(directory);
|
||||
var databasePath = Path.Combine(directory, "local.db");
|
||||
var unrelatedPath = Path.Combine(directory, "keep.txt");
|
||||
try
|
||||
{
|
||||
await using var context = CreateContext($"Data Source={databasePath};Pooling=False");
|
||||
context.Database.GetDbConnection().Should().BeOfType<SqliteConnection>()
|
||||
.Which.IsLocal.Should().BeTrue();
|
||||
|
||||
#pragma warning disable EF1001
|
||||
context.GetService<IHistoryRepository>().Should().BeOfType<TursoSqliteHistoryRepository>();
|
||||
#pragma warning restore EF1001
|
||||
|
||||
var creator = context.GetService<IRelationalDatabaseCreator>();
|
||||
(await creator.ExistsAsync()).Should().BeFalse();
|
||||
await creator.CreateAsync();
|
||||
(await creator.ExistsAsync()).Should().BeTrue();
|
||||
(await creator.HasTablesAsync()).Should().BeFalse();
|
||||
|
||||
await context.Database.MigrateAsync();
|
||||
(await creator.HasTablesAsync()).Should().BeTrue();
|
||||
|
||||
context.Items.Add(new EfRemoteReplicaItem { Name = "local", Amount = 3.5m });
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
(await context.Items
|
||||
.Where(item => Regex.IsMatch(item.Name, "^loc"))
|
||||
.SingleAsync())
|
||||
.Name.Should().Be("local");
|
||||
(await context.Items
|
||||
.Where(item => item.Amount + 1m > 4m)
|
||||
.OrderBy(item => item.Amount)
|
||||
.SingleAsync())
|
||||
.Amount.Should().Be(3.5m);
|
||||
|
||||
await context.Database.CloseConnectionAsync();
|
||||
await File.WriteAllTextAsync(unrelatedPath, "keep");
|
||||
(await context.Database.EnsureDeletedAsync()).Should().BeTrue();
|
||||
|
||||
File.Exists(databasePath).Should().BeFalse();
|
||||
File.Exists(databasePath + "-wal").Should().BeFalse();
|
||||
File.Exists(databasePath + "-shm").Should().BeFalse();
|
||||
File.Exists(unrelatedPath).Should().BeTrue();
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (Directory.Exists(directory))
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
private static EfRemoteReplicaDbContext CreateContext(string connectionString)
|
||||
{
|
||||
var options = new DbContextOptionsBuilder<EfRemoteReplicaDbContext>()
|
||||
.UseTurso(
|
||||
connectionString,
|
||||
sqlite => sqlite.MigrationsAssembly(typeof(EfRemoteReplicaMigration).Assembly.FullName))
|
||||
.Options;
|
||||
return new EfRemoteReplicaDbContext(options);
|
||||
}
|
||||
|
||||
private static EfRemoteReplicaDbContext CreateContext(
|
||||
SqliteConnection connection,
|
||||
bool contextOwnsConnection)
|
||||
{
|
||||
var options = new DbContextOptionsBuilder<EfRemoteReplicaDbContext>()
|
||||
.UseTurso(
|
||||
connection,
|
||||
contextOwnsConnection,
|
||||
sqlite => sqlite.MigrationsAssembly(typeof(EfRemoteReplicaMigration).Assembly.FullName))
|
||||
.Options;
|
||||
return new EfRemoteReplicaDbContext(options);
|
||||
}
|
||||
|
||||
private static string[] CreateReplicaSidecars(string replicaPath)
|
||||
{
|
||||
var sidecars = new[]
|
||||
{
|
||||
replicaPath + "-journal",
|
||||
replicaPath + "-wal",
|
||||
replicaPath + "-shm",
|
||||
Path.ChangeExtension(replicaPath, ".db-log"),
|
||||
replicaPath + "-wal-revert",
|
||||
replicaPath + "-info",
|
||||
replicaPath + "-changes",
|
||||
replicaPath + "-replace-base-apply",
|
||||
replicaPath + "-replace-base-apply-test.backup",
|
||||
};
|
||||
foreach (var sidecar in sidecars)
|
||||
File.WriteAllText(sidecar, "sidecar");
|
||||
return sidecars;
|
||||
}
|
||||
|
||||
private static IDisposable UseRemoteHandler(HttpMessageHandler handler)
|
||||
{
|
||||
global::Turso.TursoConnection.RemoteMessageHandlerFactory = () => handler;
|
||||
return new Scope(() => global::Turso.TursoConnection.RemoteMessageHandlerFactory = null);
|
||||
}
|
||||
|
||||
private static IDisposable RejectSyncRequests()
|
||||
{
|
||||
global::Turso.TursoConnection.SyncHttpClientFactory =
|
||||
() => new HttpClient(new UnexpectedSyncHandler());
|
||||
return new Scope(() => global::Turso.TursoConnection.SyncHttpClientFactory = null);
|
||||
}
|
||||
|
||||
private sealed class UnexpectedSyncHandler : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(
|
||||
HttpRequestMessage request,
|
||||
CancellationToken cancellationToken)
|
||||
=> throw new AssertionException($"Deferred bootstrap unexpectedly requested {request.RequestUri}.");
|
||||
}
|
||||
|
||||
private sealed class Scope(Action dispose) : IDisposable
|
||||
{
|
||||
public void Dispose() => dispose();
|
||||
}
|
||||
|
||||
private sealed class ScriptedEfRemoteHandler : HttpMessageHandler
|
||||
{
|
||||
private readonly HashSet<string> _tables = new(StringComparer.Ordinal);
|
||||
private readonly List<RemoteItem> _items = [];
|
||||
private List<RemoteItem>? _transactionItems;
|
||||
private long _nextId = 1;
|
||||
private int _lastAffected;
|
||||
private string? _migrationId;
|
||||
|
||||
public List<string> SqlStatements { get; } = [];
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(
|
||||
HttpRequestMessage request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var requestBody = await request.Content!.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
|
||||
using var document = JsonDocument.Parse(requestBody);
|
||||
var results = new JsonArray();
|
||||
foreach (var pipelineRequest in document.RootElement.GetProperty("requests").EnumerateArray())
|
||||
{
|
||||
var type = pipelineRequest.GetProperty("type").GetString();
|
||||
results.Add(type switch
|
||||
{
|
||||
"execute" => Ok(
|
||||
"execute",
|
||||
new JsonObject
|
||||
{
|
||||
["result"] = Execute(pipelineRequest.GetProperty("stmt")),
|
||||
}),
|
||||
"close" => Ok("close"),
|
||||
_ => throw new AssertionException($"Unexpected remote pipeline request '{type}'."),
|
||||
});
|
||||
}
|
||||
|
||||
var response = new JsonObject
|
||||
{
|
||||
["baton"] = "ef-session",
|
||||
["results"] = results,
|
||||
};
|
||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent(response.ToJsonString(), Encoding.UTF8, "application/json"),
|
||||
};
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
}
|
||||
|
||||
private JsonObject Execute(JsonElement statement)
|
||||
{
|
||||
var sql = statement.GetProperty("sql").GetString()!.Trim();
|
||||
SqlStatements.Add(sql);
|
||||
var arguments = GetArguments(statement);
|
||||
|
||||
if (sql.StartsWith("SELECT 1", StringComparison.OrdinalIgnoreCase))
|
||||
return Scalar("value", "INTEGER", Integer(1));
|
||||
|
||||
if (sql.Contains("sqlite_master", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var count = sql.Contains("__EFMigrationsHistory", StringComparison.Ordinal)
|
||||
? (_tables.Contains("__EFMigrationsHistory") ? 1 : 0)
|
||||
: _tables.Count;
|
||||
return Scalar("COUNT(*)", "INTEGER", Integer(count));
|
||||
}
|
||||
|
||||
if (sql.StartsWith("CREATE TABLE", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var table = Regex.Match(
|
||||
sql,
|
||||
"CREATE TABLE(?: IF NOT EXISTS)?\\s+\"(?<name>[^\"]+)\"",
|
||||
RegexOptions.IgnoreCase).Groups["name"].Value;
|
||||
table.Should().NotBeEmpty();
|
||||
_tables.Add(table);
|
||||
return Empty();
|
||||
}
|
||||
|
||||
if (sql.StartsWith("DROP TABLE", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var table = Regex.Match(
|
||||
sql,
|
||||
"DROP TABLE(?: IF EXISTS)?\\s+\"(?<name>[^\"]+)\"",
|
||||
RegexOptions.IgnoreCase).Groups["name"].Value;
|
||||
_tables.Remove(table);
|
||||
return Empty();
|
||||
}
|
||||
|
||||
if (sql.StartsWith("BEGIN", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_transactionItems = _items.Select(static item => item with { }).ToList();
|
||||
return Empty();
|
||||
}
|
||||
|
||||
if (sql.StartsWith("ROLLBACK", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (_transactionItems is not null)
|
||||
{
|
||||
_items.Clear();
|
||||
_items.AddRange(_transactionItems);
|
||||
}
|
||||
_transactionItems = null;
|
||||
return Empty();
|
||||
}
|
||||
|
||||
if (sql.StartsWith("COMMIT", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_transactionItems = null;
|
||||
return Empty();
|
||||
}
|
||||
|
||||
if (sql.StartsWith("SAVEPOINT", StringComparison.OrdinalIgnoreCase)
|
||||
|| sql.StartsWith("RELEASE SAVEPOINT", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return Empty();
|
||||
}
|
||||
|
||||
if (sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase)
|
||||
&& sql.Contains("__EFMigrationsLock", StringComparison.Ordinal))
|
||||
{
|
||||
_lastAffected = 1;
|
||||
return Scalar("Id", "INTEGER", Integer(1), affectedRows: 1, lastInsertRowId: "1");
|
||||
}
|
||||
|
||||
if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase)
|
||||
&& sql.Contains("__EFMigrationsLock", StringComparison.Ordinal))
|
||||
{
|
||||
_lastAffected = 1;
|
||||
return Empty(1);
|
||||
}
|
||||
|
||||
if (sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase)
|
||||
&& sql.Contains("__EFMigrationsHistory", StringComparison.Ordinal))
|
||||
{
|
||||
_migrationId = EfRemoteReplicaMigration.MigrationId;
|
||||
_lastAffected = 1;
|
||||
return Empty(1);
|
||||
}
|
||||
|
||||
if (sql.Contains("FROM \"__EFMigrationsHistory\"", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return _migrationId is null
|
||||
? Result(
|
||||
[("MigrationId", "TEXT"), ("ProductVersion", "TEXT")],
|
||||
[])
|
||||
: Result(
|
||||
[("MigrationId", "TEXT"), ("ProductVersion", "TEXT")],
|
||||
[[Text(_migrationId), Text("9.0.9")]]);
|
||||
}
|
||||
|
||||
if (sql.StartsWith("INSERT INTO \"RemoteItems\"", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var values = GetColumnValues(sql, arguments);
|
||||
var item = new RemoteItem(
|
||||
_nextId++,
|
||||
values["Name"],
|
||||
decimal.Parse(values["Amount"], CultureInfo.InvariantCulture));
|
||||
_items.Add(item);
|
||||
_lastAffected = 1;
|
||||
return sql.Contains("RETURNING", StringComparison.OrdinalIgnoreCase)
|
||||
? Scalar("Id", "INTEGER", Integer(item.Id), 1, item.Id.ToString(CultureInfo.InvariantCulture))
|
||||
: Empty(1, item.Id.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
if (sql.StartsWith("UPDATE \"RemoteItems\"", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var item = _items.Single();
|
||||
var name = arguments.Values.First(value => value.Type == "text").Value;
|
||||
_items[_items.IndexOf(item)] = item with { Name = name };
|
||||
_lastAffected = 1;
|
||||
return sql.Contains("RETURNING", StringComparison.OrdinalIgnoreCase)
|
||||
? Scalar("1", "INTEGER", Integer(1), affectedRows: 1)
|
||||
: Empty(1);
|
||||
}
|
||||
|
||||
if (sql.StartsWith("DELETE FROM \"RemoteItems\"", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_lastAffected = _items.Count == 0 ? 0 : 1;
|
||||
if (_items.Count > 0)
|
||||
_items.RemoveAt(0);
|
||||
return sql.Contains("RETURNING", StringComparison.OrdinalIgnoreCase)
|
||||
? Scalar("1", "INTEGER", Integer(1), affectedRows: _lastAffected)
|
||||
: Empty(_lastAffected);
|
||||
}
|
||||
|
||||
if (sql.Contains("FROM \"RemoteItems\"", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (sql.Contains("COUNT(*)", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var nameFilter = arguments.Values.FirstOrDefault()?.Value;
|
||||
if (nameFilter is null
|
||||
&& sql.Contains("'rolled back'", StringComparison.Ordinal))
|
||||
{
|
||||
nameFilter = "rolled back";
|
||||
}
|
||||
var count = nameFilter is null ? _items.Count : _items.Count(item => item.Name == nameFilter);
|
||||
return Scalar("COUNT(*)", "INTEGER", Integer(count));
|
||||
}
|
||||
|
||||
var item = _items.Single();
|
||||
return Result(
|
||||
[("Id", "INTEGER"), ("Amount", "TEXT"), ("Name", "TEXT")],
|
||||
[[
|
||||
Integer(item.Id),
|
||||
Text(item.Amount.ToString(CultureInfo.InvariantCulture)),
|
||||
Text(item.Name),
|
||||
]]);
|
||||
}
|
||||
|
||||
if (sql.StartsWith("SELECT changes()", StringComparison.OrdinalIgnoreCase))
|
||||
return Scalar("changes()", "INTEGER", Integer(_lastAffected));
|
||||
if (sql.StartsWith("SELECT last_insert_rowid()", StringComparison.OrdinalIgnoreCase))
|
||||
return Scalar("last_insert_rowid()", "INTEGER", Integer(_nextId - 1));
|
||||
if (sql.StartsWith("CREATE INDEX", StringComparison.OrdinalIgnoreCase))
|
||||
return Empty();
|
||||
if (sql is "SELECT ef_sum FROM data"
|
||||
or "SELECT EF_DECIMAL FROM data"
|
||||
or "SELECT REGEXP FROM data")
|
||||
{
|
||||
return Empty();
|
||||
}
|
||||
|
||||
throw new AssertionException($"Unexpected EF SQL:\n{sql}");
|
||||
}
|
||||
|
||||
private static Dictionary<string, RemoteValue> GetArguments(JsonElement statement)
|
||||
=> statement.GetProperty("named_args")
|
||||
.EnumerateArray()
|
||||
.ToDictionary(
|
||||
argument => argument.GetProperty("name").GetString()!,
|
||||
argument =>
|
||||
{
|
||||
var value = argument.GetProperty("value");
|
||||
var type = value.GetProperty("type").GetString()!;
|
||||
var text = type == "null"
|
||||
? string.Empty
|
||||
: value.GetProperty("value").ToString();
|
||||
return new RemoteValue(type, text);
|
||||
},
|
||||
StringComparer.Ordinal);
|
||||
|
||||
private static Dictionary<string, string> GetColumnValues(
|
||||
string sql,
|
||||
IReadOnlyDictionary<string, RemoteValue> arguments)
|
||||
{
|
||||
var match = Regex.Match(
|
||||
sql,
|
||||
"INSERT INTO \"RemoteItems\"\\s*\\((?<columns>[^)]+)\\)\\s*VALUES\\s*\\((?<values>[^)]+)\\)",
|
||||
RegexOptions.IgnoreCase);
|
||||
match.Success.Should().BeTrue();
|
||||
var columns = match.Groups["columns"].Value
|
||||
.Split(',')
|
||||
.Select(value => value.Trim().Trim('"'))
|
||||
.ToArray();
|
||||
var values = match.Groups["values"].Value
|
||||
.Split(',')
|
||||
.Select(value => value.Trim())
|
||||
.ToArray();
|
||||
return columns.Zip(values).ToDictionary(
|
||||
pair => pair.First,
|
||||
pair => arguments[pair.Second].Value,
|
||||
StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
private static JsonObject Ok(string responseType, JsonObject? content = null)
|
||||
{
|
||||
var response = content ?? new JsonObject();
|
||||
response["type"] = responseType;
|
||||
return new JsonObject
|
||||
{
|
||||
["type"] = "ok",
|
||||
["response"] = response,
|
||||
};
|
||||
}
|
||||
|
||||
private static JsonObject Empty(int affectedRows = 0, string? lastInsertRowId = null)
|
||||
=> Result([], [], affectedRows, lastInsertRowId);
|
||||
|
||||
private static JsonObject Scalar(
|
||||
string name,
|
||||
string declaredType,
|
||||
JsonObject value,
|
||||
int affectedRows = 0,
|
||||
string? lastInsertRowId = null)
|
||||
=> Result([(name, declaredType)], [[value]], affectedRows, lastInsertRowId);
|
||||
|
||||
private static JsonObject Result(
|
||||
IReadOnlyList<(string Name, string DeclaredType)> columns,
|
||||
IReadOnlyList<IReadOnlyList<JsonObject>> rows,
|
||||
int affectedRows = 0,
|
||||
string? lastInsertRowId = null)
|
||||
{
|
||||
var jsonColumns = new JsonArray();
|
||||
foreach (var column in columns)
|
||||
{
|
||||
jsonColumns.Add(
|
||||
new JsonObject
|
||||
{
|
||||
["name"] = column.Name,
|
||||
["decltype"] = column.DeclaredType,
|
||||
});
|
||||
}
|
||||
|
||||
var jsonRows = new JsonArray();
|
||||
foreach (var row in rows)
|
||||
{
|
||||
var jsonRow = new JsonArray();
|
||||
foreach (var value in row)
|
||||
jsonRow.Add(value);
|
||||
jsonRows.Add(jsonRow);
|
||||
}
|
||||
|
||||
return new JsonObject
|
||||
{
|
||||
["cols"] = jsonColumns,
|
||||
["rows"] = jsonRows,
|
||||
["affected_row_count"] = affectedRows,
|
||||
["last_insert_rowid"] = lastInsertRowId,
|
||||
};
|
||||
}
|
||||
|
||||
private static JsonObject Integer(long value)
|
||||
=> new()
|
||||
{
|
||||
["type"] = "integer",
|
||||
["value"] = value.ToString(CultureInfo.InvariantCulture),
|
||||
};
|
||||
|
||||
private static JsonObject Text(string value)
|
||||
=> new()
|
||||
{
|
||||
["type"] = "text",
|
||||
["value"] = value,
|
||||
};
|
||||
|
||||
private sealed record RemoteValue(string Type, string Value);
|
||||
|
||||
private sealed record RemoteItem(long Id, string Name, decimal Amount);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class EfRemoteReplicaDbContext(DbContextOptions<EfRemoteReplicaDbContext> options)
|
||||
: DbContext(options)
|
||||
{
|
||||
public DbSet<EfRemoteReplicaItem> Items => Set<EfRemoteReplicaItem>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.Entity<EfRemoteReplicaItem>(
|
||||
entity =>
|
||||
{
|
||||
entity.ToTable("RemoteItems");
|
||||
entity.HasKey(item => item.Id);
|
||||
entity.Property(item => item.Id).ValueGeneratedOnAdd();
|
||||
entity.Property(item => item.Name).IsRequired();
|
||||
entity.Property(item => item.Amount).HasColumnType("TEXT");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class EfRemoteReplicaItem
|
||||
{
|
||||
public long Id { get; set; }
|
||||
|
||||
public string Name { get; set; } = "";
|
||||
|
||||
public decimal Amount { get; set; }
|
||||
}
|
||||
|
||||
[DbContext(typeof(EfRemoteReplicaDbContext))]
|
||||
[Migration(MigrationId)]
|
||||
public sealed class EfRemoteReplicaMigration : Migration
|
||||
{
|
||||
public const string MigrationId = "20260825153300_RemoteReplica";
|
||||
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "RemoteItems",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<long>(type: "INTEGER", nullable: false)
|
||||
.Annotation("Sqlite:Autoincrement", true),
|
||||
Name = table.Column<string>(type: "TEXT", nullable: false),
|
||||
Amount = table.Column<decimal>(type: "TEXT", nullable: false),
|
||||
},
|
||||
constraints: table => table.PrimaryKey("PK_RemoteItems", value => value.Id));
|
||||
}
|
||||
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
=> migrationBuilder.DropTable(name: "RemoteItems");
|
||||
}
|
||||
Reference in New Issue
Block a user