refactor!: rename Titano to Chronos and move CI and releases to Gitea
CI / Build and test (pull_request) Failing after 2m3s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / Docker image (pull_request) Skipped
CI / Windows tests and installer (pull_request) Skipped
CI / YAML check (pull_request) Successful in 4s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout. The release cross-compiles the Windows programs, checks their
  icon, version and DPI manifest, packs installers and zips, publishes the
  Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only
  tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow) and
  pe-check.

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-23 11:34:48 +02:00
1 parent c99842cc86
commit 5f27a86406
1799 files changed
+11728 -10668

No files matched your search

@@ -0,0 +1,252 @@
using Chronos.Core.Model;
using Chronos.Data.Repositories;
using Chronos.Testing;
namespace Chronos.Data.Tests.Sqlite;
/// <summary>
/// BRIEF §6.2: a VACUUM INTO copy of the SQLite index once a day, the newest three kept, and a restore from Settings ›
/// Advanced that waits for the next start, runs before the index opens (so it recovers one that no longer opens), checks
/// the copy first (quick_check included) and never replaces a working index with a broken one.
/// </summary>
[Category("sqlite")]
public sealed class DatabaseBackupsTests(TestContext context)
{
/// <summary>A clock the test moves; timers created on it never fire by themselves.</summary>
private sealed class ManualClock(DateTimeOffset now) : TimeProvider
{
public DateTimeOffset Now { get; set; } = now;
public override DateTimeOffset GetUtcNow() => Now;
}
private async Task<(ChronosDatabase Db, string Path)> OpenAsync(string name = "chronos.db")
{
var path = System.IO.Path.Combine(context.CreateTempDirectory("db"), name);
return (await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(path), context.Cancellation), path);
}
private static Task AddArchiveAsync(ChronosDatabase db, string name) =>
db.Archives.UpsertAsync(new Archive { Id = Guid.CreateVersion7(), Name = name, RootPath = "/archives/" + name, Created = DateTimeOffset.UtcNow });
[Test]
public async Task ListsTheCopiesOfThisIndexNewestFirst()
{
var directory = context.CreateTempDirectory("backups");
File.WriteAllText(Path.Combine(directory, "chronos-20261010-030000-000.db"), "a");
File.WriteAllText(Path.Combine(directory, "chronos-20261012-030000-000.db"), "bb");
File.WriteAllText(Path.Combine(directory, "chronos-20261011-030000-000.db"), "ccc");
File.WriteAllText(Path.Combine(directory, "other-20261013-030000-000.db"), "x");
File.WriteAllText(Path.Combine(directory, "chronos-notes.db"), "x");
var backups = DatabaseBackups.List(directory, "/data/chronos.db");
Assert.SequenceEqual(["chronos-20261012-030000-000.db", "chronos-20261011-030000-000.db", "chronos-20261010-030000-000.db"],
backups.Select(b => Path.GetFileName(b.Path)));
Assert.Equal(new DateTimeOffset(2026, 10, 12, 3, 0, 0, TimeSpan.Zero), backups[0].Created);
Assert.Equal(2L, backups[0].Bytes);
Assert.Empty(DatabaseBackups.List(Path.Combine(directory, "missing"), "/data/chronos.db"));
}
[Test]
public void ACopyIsDueWhenTheNewestIsADayOld()
{
var now = new DateTimeOffset(2026, 10, 12, 9, 0, 0, TimeSpan.Zero);
Assert.True(DatabaseBackups.IsDue([], now));
Assert.False(DatabaseBackups.IsDue([new DatabaseBackup("b", now.AddHours(-23), 1)], now));
Assert.True(DatabaseBackups.IsDue([new DatabaseBackup("b", now.AddHours(-24), 1)], now));
}
[Test]
public async Task TheDailyCopyIsMadeAtStartOnlyWhenDue()
{
var (db, _) = await OpenAsync();
await using var _ = db;
var directory = context.CreateTempDirectory("backups");
var clock = new ManualClock(DateTimeOffset.UtcNow);
// No copy yet: one is made at once, then the loop waits for its hourly check until stopped.
using (var stop = new CancellationTokenSource())
{
var loop = DatabaseBackups.RunDailyAsync(db, directory, clock, stop.Token);
var until = DateTime.UtcNow.AddSeconds(20);
while (Directory.GetFiles(directory, "*.db").Length == 0 && DateTime.UtcNow < until) await Task.Delay(20);
await stop.CancelAsync();
await loop.WaitAsync(TimeSpan.FromSeconds(20));
}
Assert.Count(1, Directory.GetFiles(directory, "*.db"));
// A fresh copy exists: starting again makes none.
using (var stop = new CancellationTokenSource())
{
var loop = DatabaseBackups.RunDailyAsync(db, directory, clock, stop.Token);
await Task.Delay(300);
await stop.CancelAsync();
await loop.WaitAsync(TimeSpan.FromSeconds(20));
}
Assert.Count(1, Directory.GetFiles(directory, "*.db"));
}
[Test]
public async Task AStagedRestoreReplacesTheIndexAtTheNextOpen()
{
var (db, path) = await OpenAsync();
var directory = context.CreateTempDirectory("backups");
await AddArchiveAsync(db, "kept");
var backup = await db.BackupAsync(directory, DatabaseBackups.Keep, context.Cancellation);
await AddArchiveAsync(db, "added later");
Assert.Equal(new DatabaseSummary(db.SchemaVersion, 2, 0, 0), await DatabaseBackups.SummarizeAsync(db, context.Cancellation));
// The dry run reads the copy without touching it.
var bytes = await File.ReadAllBytesAsync(backup, context.Cancellation);
var summary = await DatabaseBackups.SummarizeBackupAsync(backup, context.CreateTempDirectory("scratch"), context.Cancellation);
Assert.Equal(1, summary.Archives);
Assert.SequenceEqual(bytes, await File.ReadAllBytesAsync(backup, context.Cancellation));
await DatabaseBackups.StageRestoreAsync(backup, path, context.Cancellation);
Assert.True(DatabaseBackups.HasStagedRestore(path));
await db.DisposeAsync();
// The next start, before the index opens: the index as it was is copied first, then it is the chosen copy and
// the staged file is gone (consumed by the swap, so it can never be applied twice).
Assert.True(await DatabaseBackups.RestoreStagedAsync(path, directory, context.Cancellation));
await using var reopened = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(path), context.Cancellation);
Assert.SequenceEqual(["kept"], (await reopened.Archives.ListAsync(context.Cancellation)).Select(a => a.Name));
Assert.False(DatabaseBackups.HasStagedRestore(path));
var copies = DatabaseBackups.List(directory, path);
Assert.Count(2, copies);
var replaced = await DatabaseBackups.SummarizeBackupAsync(copies[0].Path, context.CreateTempDirectory("scratch"), context.Cancellation);
Assert.Equal(2, replaced.Archives);
Assert.False(await DatabaseBackups.RestoreStagedAsync(path, directory, context.Cancellation), "nothing staged any more");
}
[Test]
public async Task AStagedRestoreRecoversAnIndexThatNoLongerOpens()
{
var (db, path) = await OpenAsync();
var directory = context.CreateTempDirectory("backups");
await AddArchiveAsync(db, "kept");
await db.BackupAsync(directory, DatabaseBackups.Keep, context.Cancellation);
var newest = await db.BackupAsync(directory, DatabaseBackups.Keep, context.Cancellation);
var daily = DatabaseBackups.List(directory, path).Select(b => b.Path).ToList();
await DatabaseBackups.StageRestoreAsync(newest, path, context.Cancellation);
await db.DisposeAsync();
// The index is damaged beyond opening ("file is not a database").
File.Delete(path + "-wal");
File.Delete(path + "-shm");
var garbage = new byte[16384];
new Random(7).NextBytes(garbage);
await File.WriteAllBytesAsync(path, garbage, context.Cancellation);
await Assert.ThrowsAsync<DatabaseException>(async () => await (await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(path), context.Cancellation)).DisposeAsync());
Assert.True(await DatabaseBackups.RestoreStagedAsync(path, directory, context.Cancellation));
await using var reopened = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(path), context.Cancellation);
Assert.SequenceEqual(["kept"], (await reopened.Archives.ListAsync(context.Cancellation)).Select(a => a.Name));
Assert.False(DatabaseBackups.HasStagedRestore(path));
// The damaged index is kept whole beside the daily copies, outside their rotation: none of them was pushed out.
Assert.SequenceEqual(daily, DatabaseBackups.List(directory, path).Select(b => b.Path));
var aside = Assert.Contains(Directory.GetFiles(directory), f => Path.GetFileName(f).StartsWith("chronos-replaced-", StringComparison.Ordinal));
Assert.SequenceEqual(garbage, await File.ReadAllBytesAsync(aside, context.Cancellation));
}
[Test]
public async Task ABrokenStagedCopyIsSetAsideAndTheIndexKept()
{
var (db, path) = await OpenAsync();
await AddArchiveAsync(db, "current");
await db.DisposeAsync();
await File.WriteAllTextAsync(DatabaseBackups.StagedPath(path), "this is not a database", context.Cancellation);
var backups = context.CreateTempDirectory("backups");
await Assert.ThrowsAsync<InvalidDataException>(() => DatabaseBackups.RestoreStagedAsync(path, backups, context.Cancellation));
Assert.False(DatabaseBackups.HasStagedRestore(path));
Assert.FileExists(DatabaseBackups.StagedPath(path) + ".failed");
Assert.Empty(Directory.GetFiles(backups));
await using var reopened = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(path), context.Cancellation);
Assert.SequenceEqual(["current"], (await reopened.Archives.ListAsync(context.Cancellation)).Select(a => a.Name));
await Assert.ThrowsAsync<InvalidDataException>(() =>
DatabaseBackups.SummarizeBackupAsync(DatabaseBackups.StagedPath(path) + ".failed", context.CreateTempDirectory("scratch"), context.Cancellation));
}
[Test]
public async Task AStagedCopyThatFailsItsIntegrityCheckIsSetAsideBeforeAnyCopyIsMade()
{
var (db, path) = await OpenAsync();
var directory = context.CreateTempDirectory("backups");
await AddArchiveAsync(db, "current");
// A table the summary never reads, filled so its pages come last in a VACUUM INTO copy.
await using (var session = await db.Database.OpenAsync(context.Cancellation))
{
await session.ExecuteScriptAsync("""
CREATE TABLE filler (id INTEGER PRIMARY KEY, data BLOB);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 200) INSERT INTO filler (data) SELECT randomblob(1000) FROM n;
""", context.Cancellation);
}
for (var i = 0; i < DatabaseBackups.Keep; i++) await db.BackupAsync(directory, DatabaseBackups.Keep, context.Cancellation);
var daily = DatabaseBackups.List(directory, path).Select(b => b.Path).ToList();
await db.DisposeAsync();
// One damaged page in the filler table of the copy: the header, the schema and every counted table are intact.
var damaged = Path.Combine(context.CreateTempDirectory("damaged"), "copy.db");
File.Copy(daily[0], damaged);
var bytes = await File.ReadAllBytesAsync(damaged, context.Cancellation);
var pageSize = (bytes[16] << 8) | bytes[17];
if (pageSize == 1) pageSize = 65536;
bytes[bytes.Length - pageSize] = 0xFF;
await File.WriteAllBytesAsync(damaged, bytes, context.Cancellation);
// Opening, migrating and counting do not notice it: only quick_check does.
var probe = Path.Combine(context.CreateTempDirectory("probe"), "chronos.db");
File.Copy(damaged, probe);
await using (var opened = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(probe), context.Cancellation))
Assert.Equal(1, (await DatabaseBackups.SummarizeAsync(opened, context.Cancellation)).Archives);
await Assert.ThrowsAsync<InvalidDataException>(() => DatabaseBackups.SummarizeBackupAsync(damaged, context.CreateTempDirectory("scratch"), context.Cancellation));
await DatabaseBackups.StageRestoreAsync(damaged, path, context.Cancellation);
await Assert.ThrowsAsync<InvalidDataException>(() => DatabaseBackups.RestoreStagedAsync(path, directory, context.Cancellation));
Assert.False(DatabaseBackups.HasStagedRestore(path), "set aside: the next start neither retries it nor makes another copy");
Assert.FileExists(DatabaseBackups.StagedPath(path) + ".failed");
Assert.SequenceEqual(daily, DatabaseBackups.List(directory, path).Select(b => b.Path));
Assert.False(await DatabaseBackups.RestoreStagedAsync(path, directory, context.Cancellation));
await using var reopened = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(path), context.Cancellation);
Assert.SequenceEqual(["current"], (await reopened.Archives.ListAsync(context.Cancellation)).Select(a => a.Name));
}
[Test]
public async Task CancellingAStagedRestoreKeepsTheIndex()
{
var (db, path) = await OpenAsync();
var directory = context.CreateTempDirectory("backups");
var backup = await db.BackupAsync(directory, DatabaseBackups.Keep, context.Cancellation);
await DatabaseBackups.StageRestoreAsync(backup, path, context.Cancellation);
await db.DisposeAsync();
DatabaseBackups.CancelStagedRestore(path);
Assert.False(DatabaseBackups.HasStagedRestore(path));
Assert.False(await DatabaseBackups.RestoreStagedAsync(path, directory, context.Cancellation));
Assert.FileExists(backup);
}
[Test]
public async Task ARestoreWaitsWhenTheIndexCannotBeBackedUpFirst()
{
var (db, path) = await OpenAsync();
var backup = await db.BackupAsync(context.CreateTempDirectory("backups"), DatabaseBackups.Keep, context.Cancellation);
await AddArchiveAsync(db, "since the backup");
await DatabaseBackups.StageRestoreAsync(backup, path, context.Cancellation);
await db.DisposeAsync();
// The backups folder cannot be created: a file is in its way.
var blocked = Path.Combine(context.CreateTempDirectory("blocked"), "backups");
await File.WriteAllTextAsync(blocked, "not a folder", context.Cancellation);
await Assert.ThrowsAsync<IOException>(() => DatabaseBackups.RestoreStagedAsync(path, blocked, context.Cancellation));
Assert.True(DatabaseBackups.HasStagedRestore(path), "the restore stays staged for the next start");
await using var reopened = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(path), context.Cancellation);
Assert.SequenceEqual(["since the backup"], (await reopened.Archives.ListAsync(context.Cancellation)).Select(a => a.Name));
}
}
@@ -0,0 +1,220 @@
using Chronos.Data.Sqlite;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Testing;
namespace Chronos.Data.Tests.Sqlite;
public sealed class SqliteBindingTests(TestContext context) : DatabaseTest(context)
{
protected override Backend Backend => Backend.SqliteFile;
[Test]
public void SystemLibraryIsRecentEnough()
{
var parts = SqliteDatabase.LibraryVersion.Split('.').Select(int.Parse).ToArray();
Assert.True(parts[0] > 3 || (parts[0] == 3 && parts[1] >= 31), $"SQLite {SqliteDatabase.LibraryVersion}");
}
[Test]
public async Task CompileOptionsAreProbedOnceAndMatchTheLibrary()
{
await using var database = await OpenDatabaseAsync();
var options = SqliteDatabase.CompileOptions;
// Informational and probed once: the same list on every call, and what any connection reports.
Assert.Same(options, SqliteDatabase.CompileOptions);
await using var session = await database.OpenAsync(Ct);
Assert.SequenceEqual(await session.QueryListAsync("PRAGMA compile_options", [], r => r.GetString(0), Ct), options);
// Linux libraries keep the diagnostics (a Windows build may omit them, which leaves the list empty).
if (!OperatingSystem.IsWindows()) Assert.Contains(options, o => o.StartsWith("THREADSAFE=", StringComparison.Ordinal));
}
[Test]
public void AProbeThatFailsInAnyWayGivesNoOptionsInsteadOfBlockingTheIndex()
{
// A build that returns no statement for the pragma, a column it cannot read, a SQLite error: none escapes.
Assert.Empty(SqliteDatabase.ProbeCompileOptions(() => throw new ArgumentException("No statement in 'PRAGMA compile_options'.")));
Assert.Empty(SqliteDatabase.ProbeCompileOptions(() => throw new InvalidOperationException("Column type 5 is not text.")));
Assert.SequenceEqual(["THREADSAFE=1"], SqliteDatabase.ProbeCompileOptions(() => ["THREADSAFE=1"]));
}
[Test]
public async Task ConnectionsUseTheBriefPragmas()
{
await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct);
Assert.Equal("wal", await session.ScalarAsync<string>("PRAGMA journal_mode", [], Ct));
Assert.Equal(1L, await session.ScalarAsync<long>("PRAGMA synchronous", [], Ct));
Assert.Equal(1L, await session.ScalarAsync<long>("PRAGMA foreign_keys", [], Ct));
Assert.Equal(2L, await session.ScalarAsync<long>("PRAGMA temp_store", [], Ct));
Assert.Equal(-65536L, await session.ScalarAsync<long>("PRAGMA cache_size", [], Ct));
Assert.Equal(268435456L, await session.ScalarAsync<long>("PRAGMA mmap_size", [], Ct));
}
[Test]
public async Task CallsFromAUiThreadReturnBeforeTheStatementRuns()
{
await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct);
using var cts = CancellationTokenSource.CreateLinkedTokenSource(Ct);
Task? query = null;
var ui = new Thread(() =>
{
// A UI thread: has a synchronization context and is not a pool thread.
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
query = session.ExecuteAsync(
"WITH RECURSIVE r(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM r WHERE n < 2000000000) SELECT count(*) FROM r", [], cts.Token);
});
ui.Start();
Assert.True(ui.Join(TimeSpan.FromSeconds(5)), "the calling thread was blocked by the statement");
Assert.False(query!.IsCompleted);
await cts.CancelAsync();
await Assert.ThrowsAsync<OperationCanceledException>(() => query);
}
[Test]
public async Task RejectsScriptsAndWrongParameterCounts()
{
await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct);
await Assert.ThrowsAsync<ArgumentException>(() => session.ExecuteAsync("SELECT 1; SELECT 2", [], Ct));
await Assert.ThrowsAsync<ArgumentException>(() => session.ExecuteAsync("SELECT $1, $2", [1], Ct));
Assert.Equal(1, await session.ScalarAsync<int>("SELECT 1 -- trailing comment", [], Ct));
var error = await Assert.ThrowsAsync<SqliteException>(() => session.ExecuteAsync("SELEC 1", [], Ct));
Assert.Equal(1, error.ResultCode);
}
[Test]
public async Task WritersFromManySessionsAreSerialised()
{
var database = await OpenDatabaseAsync(multiConnection: true);
await using (var setup = await database.OpenAsync(Ct))
await setup.ExecuteScriptAsync("CREATE TABLE counter (id INTEGER PRIMARY KEY, n INTEGER NOT NULL); INSERT INTO counter VALUES (1, 0)", Ct);
await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => Task.Run(async () =>
{
for (var i = 0; i < 25; i++)
{
await using var session = await database.OpenAsync(Ct);
await using var tx = await session.BeginAsync(Ct);
var n = await session.ScalarAsync<long>("SELECT n FROM counter WHERE id = 1", [], Ct);
await session.ExecuteAsync("UPDATE counter SET n = $1 WHERE id = 1", [n + 1], Ct);
await tx.CommitAsync(Ct);
}
})));
await using var check = await database.OpenAsync(Ct);
Assert.Equal(200L, await check.ScalarAsync<long>("SELECT n FROM counter", [], Ct));
}
[Test]
public async Task ReadersSeeTheLastCommitWhileAWriterIsOpen()
{
var database = await OpenDatabaseAsync(multiConnection: true);
await using var writer = await database.OpenAsync(Ct);
await writer.ExecuteScriptAsync("CREATE TABLE r (id INTEGER PRIMARY KEY); INSERT INTO r VALUES (1)", Ct);
await using var tx = await writer.BeginAsync(Ct);
await writer.ExecuteAsync("INSERT INTO r VALUES ($1)", [2], Ct);
await using var reader = await database.OpenAsync(Ct);
Assert.Equal(1L, await reader.ScalarAsync<long>("SELECT count(*) FROM r", [], Ct));
await tx.CommitAsync(Ct);
Assert.Equal(2L, await reader.ScalarAsync<long>("SELECT count(*) FROM r", [], Ct));
}
[Test]
public async Task SameStatementCanRunNestedOnOneSession()
{
await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct);
await session.ExecuteScriptAsync("CREATE TABLE r (id INTEGER PRIMARY KEY); INSERT INTO r VALUES (1); INSERT INTO r VALUES (2)", Ct);
var pairs = 0;
await foreach (var outer in session.QueryAsync("SELECT id FROM r ORDER BY id", [], Ct))
{
await foreach (var inner in session.QueryAsync("SELECT id FROM r ORDER BY id", [], Ct))
{
pairs++;
Assert.True(inner.GetInt32(0) is 1 or 2 && outer.GetInt32(0) is 1 or 2);
}
}
Assert.Equal(4, pairs);
}
[Test]
public async Task BackupKeepsTheThreeNewestAndRestoreBringsDataBack()
{
var path = Path.Combine(Context.CreateTempDirectory(), "chronos.db");
var backups = Context.CreateTempDirectory();
var database = (SqliteDatabase)Own(DatabaseFactory.Open(DatabaseOptions.Sqlite(path)));
await using (var session = await database.OpenAsync(Ct))
await session.ExecuteScriptAsync("CREATE TABLE b (id INTEGER PRIMARY KEY, v TEXT); INSERT INTO b VALUES (1, 'original')", Ct);
var first = await database.BackupAsync(backups, cancellationToken: Ct);
Assert.FileExists(first);
for (var i = 0; i < 4; i++) await database.BackupAsync(backups, cancellationToken: Ct);
var kept = Directory.GetFiles(backups).OrderBy(f => f, StringComparer.Ordinal).ToList();
Assert.Equal(3, kept.Count);
Assert.DoesNotContain(first, kept);
await using (var session = await database.OpenAsync(Ct))
await session.ExecuteAsync("UPDATE b SET v = $1", ["changed"], Ct);
await database.RestoreAsync(kept[^1], Ct);
await using (var session = await database.OpenAsync(Ct))
Assert.Equal("original", await session.ScalarAsync<string>("SELECT v FROM b WHERE id = 1", [], Ct));
}
[Test]
public async Task RestoreWaitsForSessionsThatStillWrite()
{
var path = Path.Combine(Context.CreateTempDirectory(), "chronos.db");
var database = (SqliteDatabase)Own(DatabaseFactory.Open(DatabaseOptions.Sqlite(path)));
await using (var setup = await database.OpenAsync(Ct))
await setup.ExecuteScriptAsync("CREATE TABLE b (id INTEGER PRIMARY KEY)", Ct);
var backup = await database.BackupAsync(Context.CreateTempDirectory(), cancellationToken: Ct);
var session = await database.OpenAsync(Ct);
var restore = database.RestoreAsync(backup, Ct);
await Task.Delay(100, Ct);
Assert.False(restore.IsCompleted, "restore must wait for the open session");
// The session can still take the write lock while the restore waits for its pool slot.
await session.ExecuteAsync("INSERT INTO b VALUES ($1)", [1], Ct);
await using (var tx = await session.BeginAsync(Ct)) await tx.CommitAsync(Ct);
await session.DisposeAsync();
await restore.WaitAsync(TimeSpan.FromSeconds(10), Ct);
await using var check = await database.OpenAsync(Ct);
Assert.Equal(0L, await check.ScalarAsync<long>("SELECT count(*) FROM b", [], Ct));
}
[Test]
public async Task RestoreRefusesAFileThatIsNotADatabase()
{
var database = (SqliteDatabase)await OpenDatabaseAsync();
var bogus = Path.Combine(Context.CreateTempDirectory(), "bogus.db");
await File.WriteAllTextAsync(bogus, "not a database, just text that is long enough to have a header", Ct);
await Assert.ThrowsAsync<InvalidDataException>(() => database.RestoreAsync(bogus, Ct));
await using var session = await database.OpenAsync(Ct);
Assert.Equal(1, await session.ScalarAsync<int>("SELECT 1", [], Ct));
}
[Test]
public async Task InMemoryDatabasesAreIsolated()
{
var a = Own(DatabaseFactory.Open(DatabaseOptions.SqliteInMemory()));
var b = Own(DatabaseFactory.Open(DatabaseOptions.SqliteInMemory()));
await using (var s = await a.OpenAsync(Ct)) await s.ExecuteScriptAsync("CREATE TABLE only_a (id INTEGER)", Ct);
await using var sb = await b.OpenAsync(Ct);
Assert.Equal(0L, await sb.ScalarAsync<long>("SELECT count(*) FROM sqlite_master WHERE name = 'only_a'", [], Ct));
await Assert.ThrowsAsync<NotSupportedException>(() => ((SqliteDatabase)a).RestoreAsync("x.db", Ct));
}
}
public sealed class SqliteSqlTextTests
{
[Theory]
[Case("SELECT $1", "SELECT ?1")]
[Case("SELECT $2, $1, $12", "SELECT ?2, ?1, ?12")]
[Case("SELECT '$1', \"$2\", [$3], `$4` FROM t WHERE a = $5", "SELECT '$1', \"$2\", [$3], `$4` FROM t WHERE a = ?5")]
[Case("SELECT 'it''s $1' || $1", "SELECT 'it''s $1' || ?1")]
[Case("SELECT $1 -- $2\n, $3 /* $4 */", "SELECT ?1 -- $2\n, ?3 /* $4 */")]
[Case("SELECT a$1 FROM t", "SELECT a$1 FROM t")]
[Case("SELECT 'unterminated $1", "SELECT 'unterminated $1")]
public void TranslatesPlaceholdersOutsideLiterals(string sql, string expected) =>
Assert.Equal(expected, SqliteSqlText.TranslatePlaceholders(sql));
}