merge: data layer (SQLite binding, PostgreSQL wire client, migrations, repositories)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
56 files changed
+8669
-1
No files matched your search
@@ -0,0 +1,90 @@
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Data.Tests.Core;
|
||||
|
||||
/// <summary>Dialect-independent value handling: parameter normalisation, row conversions, text forms.</summary>
|
||||
public sealed class ValueConversionTests
|
||||
{
|
||||
private static DbRow Row(params object?[] values) =>
|
||||
new(new DbColumns(values.Select((_, i) => "c" + i).ToArray()), values);
|
||||
|
||||
[Test]
|
||||
public void ParametersKeepTheirTypeEvenWhenNull()
|
||||
{
|
||||
Assert.Equal(DbValueType.Uuid, ((DbParam)(Guid?)null).Type);
|
||||
Assert.Equal(DbValueType.LocalDateTime, ((DbParam)(DateTime?)null).Type);
|
||||
Assert.Equal(DbValueType.Auto, DbParam.Null.Type);
|
||||
Assert.Equal(DbValueType.Int64, new DbParam(DayOfWeek.Friday).Type);
|
||||
Assert.Equal(5L, new DbParam(DayOfWeek.Friday).Value);
|
||||
Assert.Equal(DbValueType.Timestamp, ((DbParam)new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Type);
|
||||
Assert.Equal(DbValueType.LocalDateTime, ((DbParam)new DateTime(2020, 1, 1)).Type);
|
||||
Assert.Equal(3, new DbParam((short)3).Value);
|
||||
Assert.Throws<NotSupportedException>(() => new DbParam(new object()));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RowGettersConvertBetweenProviderForms()
|
||||
{
|
||||
var guid = Guid.CreateVersion7();
|
||||
var row = Row(42L, "0190a8b4-5c4e-7a1b-9c3d-0123456789ab", "2026-09-28T16:30:15.123456Z", "2024-02-29T23:59:58.500000", 1L, 3.0, guid, null);
|
||||
Assert.Equal(42, row.GetInt32(0));
|
||||
Assert.Equal(Guid.Parse("0190a8b4-5c4e-7a1b-9c3d-0123456789ab"), row.GetGuid(1));
|
||||
Assert.Equal(new DateTimeOffset(2026, 9, 28, 16, 30, 15, 123, TimeSpan.Zero).AddTicks(4560), row.GetDateTimeOffset(2));
|
||||
Assert.Equal(new DateTime(2024, 2, 29, 23, 59, 58, 500), row.GetDateTime(3));
|
||||
Assert.True(row.GetBool(4));
|
||||
Assert.Equal(3L, row.GetInt64(5));
|
||||
Assert.Equal(guid.ToString(), row.GetString(6));
|
||||
Assert.Null(row.GetInt32OrNull(7));
|
||||
Assert.Equal(DayOfWeek.Wednesday, row.Get<DayOfWeek>(5));
|
||||
Assert.Equal(42, row.Get<int?>(0));
|
||||
Assert.Null(row.Get<string>(7));
|
||||
Assert.Equal(1, row.GetOrdinal("C1"));
|
||||
Assert.Throws<InvalidCastException>(() => row.GetGuid(0));
|
||||
Assert.Throws<OverflowException>(() => Row(long.MaxValue).GetInt32(0));
|
||||
Assert.Throws<IndexOutOfRangeException>(() => row.GetOrdinal("missing"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case("2026-09-28 18:30:15.5+02", "2026-09-28T16:30:15.5000000+00:00")]
|
||||
[Case("2026-09-28 18:30:15+05:30", "2026-09-28T13:00:15.0000000+00:00")]
|
||||
[Case("2026-09-28T18:30:15.1234567Z", "2026-09-28T18:30:15.1234567+00:00")]
|
||||
[Case("2026-09-28T18:30:15.12345678Z", "2026-09-28T18:30:15.1234567+00:00")]
|
||||
[Case("2026-09-28 18:30", "2026-09-28T18:30:00.0000000+00:00")]
|
||||
[Case("2026-09-28", "2026-09-28T00:00:00.0000000+00:00")]
|
||||
[Case("1999-12-31 23:00:00-01", "2000-01-01T00:00:00.0000000+00:00")]
|
||||
public void ParsesTimestampTextForms(string text, string expected) =>
|
||||
Assert.Equal(expected, TextValues.ParseTimestamp(text).ToString("O"));
|
||||
|
||||
[Theory]
|
||||
[Case("2026-02-30")]
|
||||
[Case("2026-09-28 25:00:00")]
|
||||
[Case("26-09-28")]
|
||||
[Case("2026-09-28T10:00:00.Z")]
|
||||
[Case("2026-09-28T10:00:00+1")]
|
||||
public void RejectsMalformedTimestamps(string text) =>
|
||||
Assert.Throws<FormatException>(() => TextValues.ParseTimestamp(text));
|
||||
|
||||
[Test]
|
||||
public void StoredTextFormsSortChronologically()
|
||||
{
|
||||
var a = new DateTimeOffset(2026, 1, 1, 9, 0, 0, TimeSpan.Zero);
|
||||
var values = new[] { a, a.AddTicks(10), a.AddSeconds(1), a.AddYears(-1), a.AddMilliseconds(999) };
|
||||
var sorted = values.Select(TextValues.FormatTimestamp).OrderBy(s => s, StringComparer.Ordinal).ToList();
|
||||
Assert.SequenceEqual(values.OrderBy(v => v).Select(TextValues.FormatTimestamp), sorted);
|
||||
Assert.Equal("2026-01-01T09:00:00.000001Z", TextValues.FormatTimestamp(a.AddTicks(10)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BuildsUpsertsAndPatterns()
|
||||
{
|
||||
Assert.Equal(
|
||||
"INSERT INTO t (a, b, c) VALUES ($1, $2, $3) ON CONFLICT (a) DO UPDATE SET b = excluded.b, c = excluded.c",
|
||||
SqlDialect.Upsert("t", ["a", "b", "c"], 1));
|
||||
Assert.Equal("INSERT INTO t (a, b) VALUES ($1, $2) ON CONFLICT (a, b) DO NOTHING", SqlDialect.Upsert("t", ["a", "b"], 2));
|
||||
Assert.Equal(
|
||||
"INSERT INTO t (a, b, c) VALUES ($1, $2, $3) ON CONFLICT (a) DO UPDATE SET c = excluded.c",
|
||||
SqlDialect.Upsert("t", ["a", "b", "c"], 1, ["b"]));
|
||||
Assert.Equal("%50\\%\\_off\\\\%", SqlDialect.ContainsPattern("50%_off\\"));
|
||||
Assert.Equal("\"we\"\"ird\"", SqlDialect.QuoteIdentifier("we\"ird"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
using Titano.Data.Postgres;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Data.Tests.Infrastructure;
|
||||
|
||||
/// <summary>Engine a dialect-parameterised test class runs against.</summary>
|
||||
public enum Backend
|
||||
{
|
||||
SqliteMemory,
|
||||
SqliteFile,
|
||||
Postgres,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The PostgreSQL server named by <c>TITANO_TEST_PG</c>. Every test gets its own schema (selected through
|
||||
/// <c>Search Path</c>), so classes run in parallel without seeing each other's tables.
|
||||
/// </summary>
|
||||
internal static class PgTestServer
|
||||
{
|
||||
public const string Variable = "TITANO_TEST_PG";
|
||||
|
||||
private static readonly Lazy<PostgresDatabase> Admin = new(() =>
|
||||
new PostgresDatabase(PostgresSettings.Parse(ConnectionString) with { MaxPoolSize = 4 }));
|
||||
|
||||
public static string ConnectionString =>
|
||||
Environment.GetEnvironmentVariable(Variable) is { Length: > 0 } cs ? cs : throw new SkipException($"{Variable} not set");
|
||||
|
||||
/// <summary>A connection string for another role (MD5, cleartext, trust tests), or a skip when not configured.</summary>
|
||||
public static string Optional(string variable) =>
|
||||
Environment.GetEnvironmentVariable(variable) is { Length: > 0 } cs ? cs : throw new SkipException($"{variable} not set");
|
||||
|
||||
public static async Task<string> CreateSchemaAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var name = "titano_t_" + Guid.NewGuid().ToString("N")[..16];
|
||||
await using var session = await Admin.Value.OpenAsync(cancellationToken);
|
||||
await session.ExecuteScriptAsync($"CREATE SCHEMA {name}", cancellationToken);
|
||||
return name;
|
||||
}
|
||||
|
||||
public static async Task DropSchemaAsync(string name)
|
||||
{
|
||||
await using var session = await Admin.Value.OpenAsync(CancellationToken.None);
|
||||
await session.ExecuteScriptAsync($"DROP SCHEMA IF EXISTS {name} CASCADE", CancellationToken.None);
|
||||
}
|
||||
|
||||
public static string With(string connectionString, string extra) => connectionString.TrimEnd(';', ' ') + ";" + extra;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Base of tests that run against a fresh database per test: an in-memory or temporary-file SQLite database, or
|
||||
/// a private schema on the PostgreSQL test server. Everything opened through it is disposed after the test.
|
||||
/// </summary>
|
||||
public abstract class DatabaseTest(TestContext context) : IAsyncDisposable
|
||||
{
|
||||
private readonly List<IAsyncDisposable> _owned = [];
|
||||
private readonly List<string> _schemas = [];
|
||||
|
||||
protected TestContext Context => context;
|
||||
|
||||
protected CancellationToken Ct => context.Cancellation;
|
||||
|
||||
protected abstract Backend Backend { get; }
|
||||
|
||||
protected Dialect Dialect => Backend == Backend.Postgres ? Dialect.Postgres : Dialect.Sqlite;
|
||||
|
||||
/// <summary>Picks the DDL/SQL variant of the current dialect.</summary>
|
||||
protected string ForDialect(string sqlite, string postgres) => Dialect == Dialect.Postgres ? postgres : sqlite;
|
||||
|
||||
/// <summary>Options for a new empty database; <paramref name="multiConnection"/> forces a SQLite file (pooled readers).</summary>
|
||||
protected async Task<DatabaseOptions> NewOptionsAsync(bool multiConnection = false, string? extraPostgres = null)
|
||||
{
|
||||
switch (Backend)
|
||||
{
|
||||
case Backend.SqliteMemory when !multiConnection:
|
||||
return DatabaseOptions.SqliteInMemory();
|
||||
case Backend.SqliteMemory or Backend.SqliteFile:
|
||||
return DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(), "titano.db"));
|
||||
default:
|
||||
var schema = await PgTestServer.CreateSchemaAsync(Ct);
|
||||
_schemas.Add(schema);
|
||||
var cs = PgTestServer.With(PgTestServer.ConnectionString, $"Search Path={schema};Maximum Pool Size=12");
|
||||
return DatabaseOptions.Postgres(extraPostgres is null ? cs : PgTestServer.With(cs, extraPostgres));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Opens a bare database (no migrations).</summary>
|
||||
protected async Task<IDatabase> OpenDatabaseAsync(bool multiConnection = false)
|
||||
{
|
||||
var database = DatabaseFactory.Open(await NewOptionsAsync(multiConnection));
|
||||
return Own(database);
|
||||
}
|
||||
|
||||
protected T Own<T>(T disposable) where T : IAsyncDisposable
|
||||
{
|
||||
_owned.Add(disposable);
|
||||
return disposable;
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
for (var i = _owned.Count - 1; i >= 0; i--) await _owned[i].DisposeAsync();
|
||||
foreach (var schema in _schemas) await PgTestServer.DropSchemaAsync(schema);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Data.Tests.Infrastructure;
|
||||
|
||||
/// <summary>Base of repository tests: a migrated <see cref="TitanoDatabase"/> per test.</summary>
|
||||
public abstract class RepositoryTest(TestContext context) : DatabaseTest(context)
|
||||
{
|
||||
/// <summary>Opens a fresh migrated database; <paramref name="multiConnection"/> forces a SQLite file.</summary>
|
||||
protected async Task<TitanoDatabase> OpenTitanoAsync(bool multiConnection = false) =>
|
||||
Own(await TitanoDatabase.OpenAsync(await NewOptionsAsync(multiConnection), Ct));
|
||||
}
|
||||
|
||||
/// <summary>Builders of valid entities with distinct ids; override fields with <c>with</c>.</summary>
|
||||
internal static class TestData
|
||||
{
|
||||
/// <summary>A fixed reference instant (microsecond precision, like the databases).</summary>
|
||||
public static readonly DateTimeOffset Now = new(2026, 10, 2, 9, 0, 0, TimeSpan.Zero);
|
||||
|
||||
public static Archive Archive(string name = "Main") => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Name = name,
|
||||
RootPath = "/archive/" + name,
|
||||
Created = Now,
|
||||
};
|
||||
|
||||
public static Sequence Sequence(Guid archiveId, DateTime? firstCapture = null, string? title = null, string camera = "EOS R5") => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
ArchiveId = archiveId,
|
||||
Title = title,
|
||||
Folder = $"2026/{Guid.NewGuid():N}",
|
||||
CameraMake = "Canon",
|
||||
CameraModel = camera,
|
||||
FirstCapture = firstCapture,
|
||||
LastCapture = firstCapture?.AddHours(1),
|
||||
UpdatedAt = Now,
|
||||
};
|
||||
|
||||
public static Frame Frame(Guid sequenceId, int index, DateTime? capturedAt = null) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
SequenceId = sequenceId,
|
||||
Index = index,
|
||||
RelativePath = $"2026/seq/originals/IMG_{index:0000}.CR3",
|
||||
FileName = $"IMG_{index:0000}.CR3",
|
||||
Size = 25_000_000 + index,
|
||||
Sha256 = Convert.ToHexStringLower(BitConverter.GetBytes((long)index)).PadLeft(64, '0'),
|
||||
CapturedAt = capturedAt ?? new DateTime(2026, 9, 28, 18, 0, 0).AddSeconds(5 * index),
|
||||
TimestampSource = TimestampSource.ExifOriginal,
|
||||
ExposureTime = 1 / 250.0,
|
||||
FNumber = 8,
|
||||
Iso = 100,
|
||||
FocalLength = 24,
|
||||
Width = 8192,
|
||||
Height = 5464,
|
||||
Format = ImageFileFormat.Cr3,
|
||||
};
|
||||
|
||||
public static Job Job(JobKind kind = JobKind.Scan, JobPriority priority = JobPriority.Normal, DateTimeOffset? created = null) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = kind,
|
||||
Priority = priority,
|
||||
State = JobState.Queued,
|
||||
Created = created ?? Now,
|
||||
};
|
||||
|
||||
public static User User(string username = "alice") => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Username = username,
|
||||
PasswordHash = "pbkdf2-sha512$210000$salt$hash",
|
||||
Role = UserRole.Editor,
|
||||
Permissions = RolePermissions.Default(UserRole.Editor),
|
||||
Created = Now,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using Titano.Data.Migrations;
|
||||
using Titano.Data.Tests.Infrastructure;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Data.Tests.Migrations;
|
||||
|
||||
public abstract class MigrationTests(TestContext context) : RepositoryTest(context)
|
||||
{
|
||||
private static readonly string[] Tables =
|
||||
[
|
||||
"archives", "sequences", "frames", "renders", "jobs", "media_cards", "import_history", "users", "tokens",
|
||||
"render_nodes", "settings", "tags", "sequence_tags", "audit_log", "uploads",
|
||||
];
|
||||
|
||||
[Test]
|
||||
public void EmbeddedScriptsAreFoundForBothDialects()
|
||||
{
|
||||
foreach (var dialect in new[] { Dialect.Sqlite, Dialect.Postgres })
|
||||
{
|
||||
var migrations = MigrationRunner.Load(dialect);
|
||||
Assert.NotEmpty(migrations);
|
||||
Assert.Equal(1, migrations[0].Version);
|
||||
Assert.Equal("initial", migrations[0].Name);
|
||||
Assert.Contains("CREATE TABLE frames", migrations[0].Sql);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CreatesEveryTableAndIsIdempotent()
|
||||
{
|
||||
var titano = await OpenTitanoAsync();
|
||||
var latest = MigrationRunner.Load(Dialect)[^1].Version;
|
||||
Assert.Equal(latest, titano.SchemaVersion);
|
||||
Assert.Equal(latest, await MigrationRunner.MigrateAsync(titano.Database, Ct));
|
||||
|
||||
await using var session = await titano.Database.OpenAsync(Ct);
|
||||
foreach (var table in Tables) Assert.Equal(0L, await session.ScalarAsync<long>($"SELECT count(*) FROM {table}", [], Ct));
|
||||
var recorded = await session.QueryListAsync("SELECT version, name, applied_at FROM schema_migrations ORDER BY version", [], r => r, Ct);
|
||||
Assert.Equal(MigrationRunner.Load(Dialect).Count, recorded.Count);
|
||||
Assert.Equal("initial", recorded[0].GetString(1));
|
||||
Assert.True(recorded[0].GetDateTimeOffset(2) > DateTimeOffset.UtcNow.AddMinutes(-5));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AppliesOnlyPendingMigrations()
|
||||
{
|
||||
var titano = await OpenTitanoAsync();
|
||||
var next = MigrationRunner.Load(Dialect).Append(new Migration(9000, "extra", "CREATE TABLE extra (id integer PRIMARY KEY)")).ToList();
|
||||
Assert.Equal(9000, await MigrationRunner.MigrateAsync(titano.Database, next, Ct));
|
||||
Assert.Equal(9000, await MigrationRunner.MigrateAsync(titano.Database, next, Ct));
|
||||
await using var session = await titano.Database.OpenAsync(Ct);
|
||||
Assert.Equal(1L, await session.ScalarAsync<long>("SELECT count(*) FROM schema_migrations WHERE version = $1", [9000], Ct));
|
||||
Assert.Equal(0L, await session.ScalarAsync<long>("SELECT count(*) FROM extra", [], Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RefusesADatabaseFromANewerBuild()
|
||||
{
|
||||
var titano = await OpenTitanoAsync();
|
||||
await using (var session = await titano.Database.OpenAsync(Ct))
|
||||
await session.ExecuteAsync("INSERT INTO schema_migrations (version, name, applied_at) VALUES ($1, $2, $3)", [9999, "future", DateTimeOffset.UtcNow], Ct);
|
||||
var error = await Assert.ThrowsAsync<SchemaTooNewException>(() => MigrationRunner.MigrateAsync(titano.Database, Ct));
|
||||
Assert.Equal(9999, error.DatabaseVersion);
|
||||
Assert.Equal(MigrationRunner.Load(Dialect)[^1].Version, error.SupportedVersion);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AFailingMigrationLeavesNothingBehind()
|
||||
{
|
||||
var database = await OpenDatabaseAsync();
|
||||
List<Migration> broken =
|
||||
[
|
||||
new(1, "good", "CREATE TABLE good_one (id integer PRIMARY KEY)"),
|
||||
new(2, "bad", "CREATE TABLE good_two (id integer PRIMARY KEY); THIS IS NOT SQL"),
|
||||
];
|
||||
await Assert.ThrowsAsync<DatabaseException>(() => MigrationRunner.MigrateAsync(database, broken, Ct));
|
||||
await using var session = await database.OpenAsync(Ct);
|
||||
var leftovers = await session.ScalarAsync<long>(ForDialect(
|
||||
"SELECT count(*) FROM sqlite_master WHERE name IN ('good_one', 'good_two', 'schema_migrations')",
|
||||
"SELECT count(*) FROM information_schema.tables WHERE table_schema = current_schema() AND table_name IN ('good_one', 'good_two', 'schema_migrations')"),
|
||||
[], Ct);
|
||||
Assert.Equal(0L, leftovers);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SqliteMigrationTests(TestContext context) : MigrationTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.SqliteMemory;
|
||||
}
|
||||
|
||||
[RequiresEnvironment(PgTestServer.Variable)]
|
||||
public sealed class PostgresMigrationTests(TestContext context) : MigrationTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
using System.Buffers;
|
||||
using System.Text;
|
||||
using Titano.Data.Postgres;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Data.Tests.Postgres;
|
||||
|
||||
/// <summary>Protocol pieces that need no server.</summary>
|
||||
public sealed class PgProtocolUnitTests
|
||||
{
|
||||
[Test]
|
||||
public void ScramMatchesTheRfc7677Example()
|
||||
{
|
||||
var scram = new ScramSha256("pencil", "user", "rOprNGfwEbeRWgbNEkqO");
|
||||
Assert.Equal("n,,n=user,r=rOprNGfwEbeRWgbNEkqO", Encoding.UTF8.GetString(scram.ClientFirstMessage()));
|
||||
var final = scram.ClientFinalMessage(Encoding.UTF8.GetBytes(
|
||||
"r=rOprNGfwEbeRWgbNEkqO%hvYDpWUa2RaTCAfuxFIlj)hNlF$k0,s=W22ZaJ0SNY7soEsUEjb6gQ==,i=4096"));
|
||||
Assert.Equal(
|
||||
"c=biws,r=rOprNGfwEbeRWgbNEkqO%hvYDpWUa2RaTCAfuxFIlj)hNlF$k0,p=dHzbZapWIk4jUhN+Ute9ytag9zjfMHgsqmmiz7AndVQ=",
|
||||
Encoding.UTF8.GetString(final));
|
||||
Assert.False(scram.IsServerVerified);
|
||||
Assert.Throws<System.Security.Authentication.AuthenticationException>(() => scram.VerifyServerFinal("v=AAAA"u8));
|
||||
Assert.False(scram.IsServerVerified);
|
||||
scram.VerifyServerFinal("v=6rriTRBi23WpRR/wtup+mMhUZUn/dB5nLTJRsjl95G4="u8);
|
||||
Assert.True(scram.IsServerVerified);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ScramRejectsANonceTheClientDidNotStart()
|
||||
{
|
||||
var scram = new ScramSha256("pencil", "user", "abc");
|
||||
scram.ClientFirstMessage();
|
||||
Assert.Throws<System.Security.Authentication.AuthenticationException>(
|
||||
() => scram.ClientFinalMessage("r=xyz123,s=W22ZaJ0SNY7soEsUEjb6gQ==,i=4096"u8));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case("plain-ascii", "plain-ascii")]
|
||||
[Case("I\u00ADX", "IX")]
|
||||
[Case("a\u00A0b", "a b")]
|
||||
[Case("\u2168", "IX")]
|
||||
[Case("\u00AA", "a")]
|
||||
[Case("bell\u0007", "bell\u0007")]
|
||||
[Case("x\u00ADy\u0007", "x\u00ADy\u0007")]
|
||||
public void SaslPrepMapsNormalisesAndFallsBack(string input, string expected) =>
|
||||
Assert.Equal(expected, ScramSha256.SaslPrep(input));
|
||||
|
||||
[Test]
|
||||
public void Md5ResponseMatchesPostgresFormula() =>
|
||||
Assert.Equal("md534d7feefdad153ddeacb423a9893b99e", PgMd5.Response("titano_md5", "md5-pw", [1, 2, 3, 4]));
|
||||
|
||||
[Test]
|
||||
public void CopyTextEscapesSpecialsAndEncodesValues()
|
||||
{
|
||||
var buffer = new ArrayBufferWriter<byte>();
|
||||
foreach (var value in new object?[] { "a\tb\nc\rd\\e ✓", null, new byte[] { 0, 0xAB }, true, 42L, Guid.Empty, new DateTime(2020, 1, 2, 3, 4, 5), 2.5f })
|
||||
{
|
||||
PgTypes.WriteCopyValue(value, buffer);
|
||||
buffer.Write("|"u8);
|
||||
}
|
||||
Assert.Equal(
|
||||
"a\\tb\\nc\\rd\\\\e ✓|\\N|\\\\x00ab|t|42|00000000-0000-0000-0000-000000000000|2020-01-02T03:04:05.000000|2.5|",
|
||||
Encoding.UTF8.GetString(buffer.WrittenSpan));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DecodesHexByteaAndRejectsOtherForms()
|
||||
{
|
||||
Assert.BytesEqual(new byte[] { 0xDE, 0xAD, 0x01 }, (byte[])PgTypes.Decode(PgTypes.Bytea, "\\xdeAD01"u8));
|
||||
Assert.Equal(0, ((byte[])PgTypes.Decode(PgTypes.Bytea, "\\x"u8)).Length);
|
||||
Assert.Throws<FormatException>(() => PgTypes.Decode(PgTypes.Bytea, "a\\000"u8));
|
||||
Assert.Throws<FormatException>(() => PgTypes.Decode(PgTypes.Bytea, "\\xabc"u8));
|
||||
Assert.Throws<FormatException>(() => PgTypes.Decode(PgTypes.Bytea, "\\xzz"u8));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case("SELECT 1", true)]
|
||||
[Case(" -- comment\n /* block */ select * from t", true)]
|
||||
[Case("VALUES (1)", true)]
|
||||
[Case("SHOW TimeZone", true)]
|
||||
[Case("SELECTED", false)]
|
||||
[Case("UPDATE t SET a = 1", false)]
|
||||
[Case("WITH x AS (DELETE FROM t RETURNING *) SELECT * FROM x", false)]
|
||||
public void RecognisesRepeatableReads(string sql, bool expected) =>
|
||||
Assert.Equal(expected, PostgresSession.IsReadOnlyQuery(sql));
|
||||
|
||||
[Test]
|
||||
public void ParsesConnectionStrings()
|
||||
{
|
||||
var s = PostgresSettings.Parse("Host=db.local; Port=6543; Username=me; Password='p;w''d'; SslMode=verify-full; Maximum Pool Size=7; Search Path=s1");
|
||||
Assert.Equal("db.local", s.Host);
|
||||
Assert.Equal(6543, s.Port);
|
||||
Assert.Equal("me", s.Database);
|
||||
Assert.Equal("p;w'd", s.Password);
|
||||
Assert.Equal(SslMode.VerifyFull, s.SslMode);
|
||||
Assert.Equal(7, s.MaxPoolSize);
|
||||
Assert.Equal("s1", s.SearchPath);
|
||||
Assert.Equal("titano-server", s.ApplicationName);
|
||||
Assert.Throws<FormatException>(() => PostgresSettings.Parse("Host=x;Username=u;SslMode=allowish"));
|
||||
Assert.Throws<FormatException>(() => PostgresSettings.Parse("Host=x;Username=u;Pasword=typo"));
|
||||
Assert.Throws<FormatException>(() => PostgresSettings.Parse("Host=x;Username=u;Minimum Pool Size=5;Maximum Pool Size=2"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InfersTheDialectFromTheConnectionString()
|
||||
{
|
||||
Assert.Equal(Dialect.Postgres, DatabaseOptions.Parse("Server=x;User Id=u").Dialect);
|
||||
Assert.Equal(Dialect.Sqlite, DatabaseOptions.Parse("Data Source=/tmp/a.db").Dialect);
|
||||
Assert.Equal(Dialect.Sqlite, DatabaseOptions.Parse(@"C:\Users\me\titano.db").Dialect);
|
||||
Assert.Throws<FormatException>(() => DatabaseOptions.Parse("Foo=bar"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
using System.Diagnostics;
|
||||
using System.Security.Authentication;
|
||||
using Titano.Data.Postgres;
|
||||
using Titano.Data.Tests.Infrastructure;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Data.Tests.Postgres;
|
||||
|
||||
/// <summary>Protocol-level tests against a live server (TITANO_TEST_PG; optional TITANO_TEST_PG_MD5/_CLEARTEXT/_TRUST).</summary>
|
||||
[RequiresEnvironment(PgTestServer.Variable)]
|
||||
public sealed class PgWireTests(TestContext context) : DatabaseTest(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
|
||||
private async Task<PostgresDatabase> OpenAsync(string? extra = null) =>
|
||||
(PostgresDatabase)Own(DatabaseFactory.Open(await NewOptionsAsync(extraPostgres: extra)));
|
||||
|
||||
private async Task<string> AuthenticateAsync(string connectionString)
|
||||
{
|
||||
var database = Own(new PostgresDatabase(PostgresSettings.Parse(connectionString)));
|
||||
await using var session = await database.OpenAsync(Ct);
|
||||
return (await session.ScalarAsync<string>("SELECT current_user", [], Ct))!;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ScramSha256Login()
|
||||
{
|
||||
var settings = PostgresSettings.Parse(PgTestServer.ConnectionString);
|
||||
Assert.Equal(settings.Username, await AuthenticateAsync(PgTestServer.ConnectionString));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Md5Login() =>
|
||||
Assert.NotNull(await AuthenticateAsync(PgTestServer.Optional("TITANO_TEST_PG_MD5")));
|
||||
|
||||
[Test]
|
||||
public async Task CleartextLogin() =>
|
||||
Assert.NotNull(await AuthenticateAsync(PgTestServer.Optional("TITANO_TEST_PG_CLEARTEXT")));
|
||||
|
||||
[Test]
|
||||
public async Task TrustLogin() =>
|
||||
Assert.NotNull(await AuthenticateAsync(PgTestServer.Optional("TITANO_TEST_PG_TRUST")));
|
||||
|
||||
[Test]
|
||||
public async Task WrongPasswordIsRejected()
|
||||
{
|
||||
var wrong = PgTestServer.With(PgTestServer.ConnectionString, "Password=definitely-wrong");
|
||||
var error = await Assert.ThrowsAsync<PostgresException>(() => AuthenticateAsync(wrong));
|
||||
Assert.Equal("28P01", error.SqlState);
|
||||
Assert.Equal("FATAL", error.Severity);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TlsIsNegotiatedWhenRequired()
|
||||
{
|
||||
PostgresDatabase database;
|
||||
try
|
||||
{
|
||||
database = await OpenAsync("SslMode=Require");
|
||||
await using var probe = await database.OpenAsync(Ct);
|
||||
}
|
||||
catch (DatabaseConnectionException ex) when (ex.Message.Contains("does not support TLS", StringComparison.Ordinal))
|
||||
{
|
||||
TestContext.Skip("server has no TLS");
|
||||
return;
|
||||
}
|
||||
await using var session = await database.OpenAsync(Ct);
|
||||
Assert.True(await session.ScalarAsync<bool>("SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()", [], Ct));
|
||||
|
||||
var plain = await OpenAsync("SslMode=Disable");
|
||||
await using var plainSession = await plain.OpenAsync(Ct);
|
||||
Assert.False(await plainSession.ScalarAsync<bool>("SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()", [], Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task VerifyFullRejectsAnUntrustedCertificate()
|
||||
{
|
||||
var database = await OpenAsync("SslMode=VerifyFull");
|
||||
try
|
||||
{
|
||||
await using var session = await database.OpenAsync(Ct);
|
||||
Assert.Fail("A self-signed server certificate must not pass verify-full.");
|
||||
}
|
||||
catch (DatabaseConnectionException ex) when (ex.Message.Contains("does not support TLS", StringComparison.Ordinal))
|
||||
{
|
||||
TestContext.Skip("server has no TLS");
|
||||
}
|
||||
catch (AuthenticationException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DecodesEveryMappedResultType()
|
||||
{
|
||||
await using var session = await (await OpenAsync()).OpenAsync(Ct);
|
||||
var row = await session.QuerySingleAsync(
|
||||
"SELECT 'txt'::text, 'vc'::varchar(5), 'bp'::bpchar(4), 7::int2, -8::int4, 9000000000::int8, 1.5::float4, " +
|
||||
"-2.25::float8, 'Infinity'::float8, true, '\\x00ff10'::bytea, '2026-09-28 18:30:15.123456+02'::timestamptz, " +
|
||||
"'2024-02-29 23:59:58.5'::timestamp, '2026-01-31'::date, '0190a8b4-5c4e-7a1b-9c3d-0123456789ab'::uuid, " +
|
||||
"'{\"k\": 1}'::json, '{\"k\": [true]}'::jsonb, 12345678901234567890.123::numeric, NULL::int4", [], Ct);
|
||||
Assert.Equal("txt", row.GetString(0));
|
||||
Assert.Equal("vc", row.GetString(1));
|
||||
Assert.Equal("bp ", row.GetString(2));
|
||||
Assert.Equal(7, row.GetInt32(3));
|
||||
Assert.Equal(-8, row.GetInt32(4));
|
||||
Assert.Equal(9000000000L, row.GetInt64(5));
|
||||
Assert.Equal(1.5, row.GetDouble(6));
|
||||
Assert.Equal(-2.25, row.GetDouble(7));
|
||||
Assert.Equal(double.PositiveInfinity, row.GetDouble(8));
|
||||
Assert.True(row.GetBool(9));
|
||||
Assert.BytesEqual(new byte[] { 0, 0xFF, 0x10 }, row.GetBytes(10));
|
||||
Assert.Equal(new DateTimeOffset(2026, 9, 28, 16, 30, 15, 123, TimeSpan.Zero).AddTicks(4560), row.GetDateTimeOffset(11));
|
||||
Assert.Equal(new DateTime(2024, 2, 29, 23, 59, 58, 500), row.GetDateTime(12));
|
||||
Assert.Equal(new DateTime(2026, 1, 31), row.GetDateTime(13));
|
||||
Assert.Equal(Guid.Parse("0190a8b4-5c4e-7a1b-9c3d-0123456789ab"), row.GetGuid(14));
|
||||
Assert.Equal("{\"k\": 1}", row.GetString(15));
|
||||
Assert.Equal("{\"k\": [true]}", row.GetString(16));
|
||||
Assert.Equal("12345678901234567890.123", row.GetString(17));
|
||||
Assert.True(row.IsNull(18));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ByteaTravelsInBinary()
|
||||
{
|
||||
await using var session = await (await OpenAsync()).OpenAsync(Ct);
|
||||
await session.ExecuteScriptAsync("CREATE TABLE blobs (id integer PRIMARY KEY, data bytea)", Ct);
|
||||
var all = Enumerable.Range(0, 256).Select(i => (byte)i).ToArray();
|
||||
var large = new byte[1 << 20];
|
||||
new Random(7).NextBytes(large);
|
||||
await session.ExecuteAsync("INSERT INTO blobs VALUES ($1, $2), ($3, $4), ($5, $6)", [1, all, 2, large, 3, Array.Empty<byte>()], Ct);
|
||||
var readAll = await session.ScalarAsync<byte[]>("SELECT data FROM blobs WHERE id = 1", [], Ct);
|
||||
var readLarge = await session.ScalarAsync<byte[]>("SELECT data FROM blobs WHERE id = 2", [], Ct);
|
||||
Assert.BytesEqual(all, readAll);
|
||||
Assert.BytesEqual(large, readLarge);
|
||||
Assert.Equal(0, (await session.ScalarAsync<byte[]>("SELECT data FROM blobs WHERE id = 3", [], Ct))!.Length);
|
||||
Assert.Equal(1L << 20, await session.ScalarAsync<long>("SELECT length(data) FROM blobs WHERE id = $1", [2], Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ListenReceivesNotifications()
|
||||
{
|
||||
var database = await OpenAsync();
|
||||
var listener = Own(await database.CreateListenerAsync(Ct));
|
||||
var received = new TaskCompletionSource<PgNotification>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
listener.Notification += (_, n) => received.TrySetResult(n);
|
||||
await listener.ListenAsync("titano_jobs", Ct);
|
||||
|
||||
await using (var session = await database.OpenAsync(Ct))
|
||||
await session.ExecuteAsync("SELECT pg_notify($1, $2)", ["titano_jobs", "wake ✓"], Ct);
|
||||
|
||||
var notification = await received.Task.WaitAsync(TimeSpan.FromSeconds(5), Ct);
|
||||
Assert.Equal("titano_jobs", notification.Channel);
|
||||
Assert.Equal("wake ✓", notification.Payload);
|
||||
await listener.UnlistenAsync("titano_jobs", Ct);
|
||||
await Assert.ThrowsAsync<PostgresException>(() => listener.ListenAsync("", Ct));
|
||||
await listener.ListenAsync("still_usable", Ct);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ServerErrorsMapToTypedExceptions()
|
||||
{
|
||||
await using var session = await (await OpenAsync()).OpenAsync(Ct);
|
||||
await session.ExecuteScriptAsync("CREATE TABLE u (id integer PRIMARY KEY, code text CONSTRAINT u_code_key UNIQUE)", Ct);
|
||||
await session.ExecuteAsync("INSERT INTO u VALUES ($1, $2)", [1, "a"], Ct);
|
||||
var unique = await Assert.ThrowsAsync<PostgresException>(() => session.ExecuteAsync("INSERT INTO u VALUES ($1, $2)", [2, "a"], Ct));
|
||||
Assert.Equal("23505", unique.SqlState);
|
||||
Assert.Equal("ERROR", unique.Severity);
|
||||
Assert.Equal("u_code_key", unique.ConstraintName);
|
||||
Assert.Equal("u", unique.TableName);
|
||||
Assert.NotNull(unique.Detail);
|
||||
Assert.True(unique.IsUniqueViolation);
|
||||
|
||||
var syntax = await Assert.ThrowsAsync<PostgresException>(() => session.ExecuteAsync("SELECT * FROM u WHER id = 1", [], Ct));
|
||||
Assert.Equal("42601", syntax.SqlState);
|
||||
Assert.Equal(22, syntax.Position);
|
||||
Assert.Equal(1, await session.ScalarAsync<int>("SELECT 1", [], Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CommitOfAnAbortedTransactionThrows()
|
||||
{
|
||||
await using var session = await (await OpenAsync()).OpenAsync(Ct);
|
||||
await session.ExecuteScriptAsync("CREATE TABLE a (id integer PRIMARY KEY)", Ct);
|
||||
var tx = await session.BeginAsync(Ct);
|
||||
await session.ExecuteAsync("INSERT INTO a VALUES ($1)", [1], Ct);
|
||||
await Assert.ThrowsAsync<PostgresException>(() => session.ExecuteAsync("INSERT INTO a VALUES ($1)", [1], Ct));
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => tx.CommitAsync(Ct));
|
||||
Assert.False(session.InTransaction);
|
||||
Assert.Equal(0L, await session.ScalarAsync<long>("SELECT count(*) FROM a", [], Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PoolReusesConnectionsAndHandsOutDistinctOnesConcurrently()
|
||||
{
|
||||
var database = await OpenAsync("Maximum Pool Size=3;Timeout=2");
|
||||
int first;
|
||||
await using (var s = await database.OpenAsync(Ct)) first = await s.ScalarAsync<int>("SELECT pg_backend_pid()", [], Ct);
|
||||
await using (var s = await database.OpenAsync(Ct)) Assert.Equal(first, await s.ScalarAsync<int>("SELECT pg_backend_pid()", [], Ct));
|
||||
|
||||
var sessions = new List<IDbSession>();
|
||||
for (var i = 0; i < 3; i++) sessions.Add(await database.OpenAsync(Ct));
|
||||
var pids = new HashSet<int>();
|
||||
foreach (var s in sessions) pids.Add(await s.ScalarAsync<int>("SELECT pg_backend_pid()", [], Ct));
|
||||
Assert.Equal(3, pids.Count);
|
||||
var watch = Stopwatch.StartNew();
|
||||
await Assert.ThrowsAsync<DatabaseConnectionException>(() => database.OpenAsync(Ct));
|
||||
Assert.InRange(watch.Elapsed.TotalSeconds, 1.5, 5);
|
||||
foreach (var s in sessions) await s.DisposeAsync();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ReadsRecoverFromATerminatedBackend()
|
||||
{
|
||||
var database = await OpenAsync("Maximum Pool Size=2");
|
||||
int victim;
|
||||
await using (var s = await database.OpenAsync(Ct)) victim = await s.ScalarAsync<int>("SELECT pg_backend_pid()", [], Ct);
|
||||
|
||||
var killer = Own(new PostgresDatabase(PostgresSettings.Parse(PgTestServer.ConnectionString)));
|
||||
await using (var k = await killer.OpenAsync(Ct))
|
||||
Assert.True(await k.ScalarAsync<bool>("SELECT pg_terminate_backend($1)", [victim], Ct));
|
||||
await Task.Delay(200, Ct);
|
||||
|
||||
await using (var s = await database.OpenAsync(Ct))
|
||||
{
|
||||
var pid = await s.ScalarAsync<int>("SELECT pg_backend_pid()", [], Ct);
|
||||
Assert.NotEqual(victim, pid);
|
||||
Assert.Equal(2, await s.ScalarAsync<int>("SELECT 1 + 1", [], Ct));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WritesOnABrokenConnectionFailWithoutRetry()
|
||||
{
|
||||
var database = await OpenAsync("Maximum Pool Size=1");
|
||||
await using var session = await database.OpenAsync(Ct);
|
||||
await session.ExecuteScriptAsync("CREATE TABLE w (id integer)", Ct);
|
||||
var pid = await session.ScalarAsync<int>("SELECT pg_backend_pid()", [], Ct);
|
||||
var killer = Own(new PostgresDatabase(PostgresSettings.Parse(PgTestServer.ConnectionString)));
|
||||
await using (var k = await killer.OpenAsync(Ct)) await k.ExecuteAsync("SELECT pg_terminate_backend($1)", [pid], Ct);
|
||||
await Task.Delay(200, Ct);
|
||||
var error = await Assert.ThrowsAsync<DatabaseException>(() => session.ExecuteAsync("INSERT INTO w VALUES ($1)", [1], Ct));
|
||||
Assert.True(error.IsTransient);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task StatementCacheEvictsAndSurvivesSchemaChanges()
|
||||
{
|
||||
await using var session = await (await OpenAsync("Statement Cache Size=2")).OpenAsync(Ct);
|
||||
await session.ExecuteScriptAsync("CREATE TABLE c (a integer); INSERT INTO c VALUES (1)", Ct);
|
||||
for (var i = 0; i < 5; i++) Assert.Equal(i, await session.ScalarAsync<int>($"SELECT {i} + 0 * $1", [i], Ct));
|
||||
// Evicted statements are closed with the next command: the cache size plus the counting statement remain.
|
||||
Assert.LessOrEqual(await session.ScalarAsync<long>("SELECT count(*) FROM pg_prepared_statements", [], Ct), 3);
|
||||
|
||||
var first = await session.QuerySingleAsync("SELECT * FROM c", [], Ct);
|
||||
Assert.Equal(1, first.FieldCount);
|
||||
await session.ExecuteScriptAsync("ALTER TABLE c ADD COLUMN b text DEFAULT 'x'", Ct);
|
||||
var second = await session.QuerySingleAsync("SELECT * FROM c", [], Ct);
|
||||
Assert.Equal(2, second.FieldCount);
|
||||
Assert.Equal("x", second.GetString("b"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACommandCannotStartWhileARowStreamIsOpen()
|
||||
{
|
||||
await using var session = await (await OpenAsync()).OpenAsync(Ct);
|
||||
var rows = session.QueryAsync("SELECT generate_series(1, 1000)", [], Ct).GetAsyncEnumerator(Ct);
|
||||
Assert.True(await rows.MoveNextAsync());
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => session.ExecuteAsync("SELECT 1", [], Ct));
|
||||
await rows.DisposeAsync();
|
||||
Assert.Equal(1, await session.ScalarAsync<int>("SELECT 1", [], Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DisposingABusySessionInATransactionFreesItsPoolSlot()
|
||||
{
|
||||
var database = await OpenAsync("Maximum Pool Size=1;Timeout=3");
|
||||
var session = await database.OpenAsync(Ct);
|
||||
await session.ExecuteScriptAsync("CREATE TABLE t (id integer)", Ct);
|
||||
var tx = await session.BeginAsync(Ct);
|
||||
await session.ExecuteAsync("INSERT INTO t VALUES ($1)", [1], Ct);
|
||||
var rows = session.QueryAsync("SELECT generate_series(1, 1000)", [], Ct).GetAsyncEnumerator(Ct);
|
||||
Assert.True(await rows.MoveNextAsync());
|
||||
await tx.DisposeAsync();
|
||||
Assert.True(session.InTransaction, "a busy session cannot roll back yet");
|
||||
await session.DisposeAsync();
|
||||
|
||||
await using var next = await database.OpenAsync(Ct);
|
||||
Assert.Equal(0L, await next.ScalarAsync<long>("SELECT count(*) FROM t", [], Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task NoticesAndScriptsDoNotDisturbTheSession()
|
||||
{
|
||||
await using var session = await (await OpenAsync()).OpenAsync(Ct);
|
||||
await session.ExecuteScriptAsync("DO $$ BEGIN RAISE NOTICE 'hello from the server'; END $$; CREATE TABLE n (id integer)", Ct);
|
||||
Assert.Equal(1, await session.ExecuteAsync("INSERT INTO n VALUES ($1)", [1], Ct));
|
||||
await Assert.ThrowsAsync<PostgresException>(() => session.ExecuteScriptAsync("SELECT 1; SELECT * FROM missing_table; SELECT 2", Ct));
|
||||
Assert.Equal(1L, await session.ScalarAsync<long>("SELECT count(*) FROM n", [], Ct));
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,14 @@
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Data.Tests;
|
||||
|
||||
internal static class TestMain
|
||||
{
|
||||
public static Task<int> Main(string[] args) => TestRunner.RunAsync(args, typeof(TestMain).Assembly);
|
||||
public static Task<int> Main(string[] args)
|
||||
{
|
||||
// Migrations and schema drops log at Info for every test database; keep the console for warnings.
|
||||
Log.MinimumLevel = LogLevel.Warning;
|
||||
return TestRunner.RunAsync(args, typeof(TestMain).Assembly);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using System.Diagnostics;
|
||||
using Titano.Data.Tests.Infrastructure;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Data.Tests.Repositories;
|
||||
|
||||
/// <summary>The 100k-frame import of the Phase 2 gate must stay well under 15 s.</summary>
|
||||
public abstract class BulkInsertTests(TestContext context) : RepositoryTest(context)
|
||||
{
|
||||
[Test]
|
||||
[Timeout(60_000)]
|
||||
public async Task HundredThousandFramesInsertQuickly()
|
||||
{
|
||||
var db = await OpenTitanoAsync(multiConnection: true);
|
||||
var archive = TestData.Archive();
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
var sequence = TestData.Sequence(archive.Id);
|
||||
await db.Sequences.UpsertAsync(sequence, Ct);
|
||||
var frames = Enumerable.Range(0, 100_000).Select(i => TestData.Frame(sequence.Id, i)).ToList();
|
||||
|
||||
var watch = Stopwatch.StartNew();
|
||||
Assert.Equal(100_000L, await db.Frames.BulkInsertAsync(frames, Ct));
|
||||
watch.Stop();
|
||||
Context.Log($"{Dialect}: 100k frames in {watch.Elapsed.TotalSeconds:F2} s");
|
||||
Assert.Less(watch.Elapsed.TotalSeconds, 15.0, "bulk insert time");
|
||||
|
||||
var refreshed = await db.Sequences.RefreshStatsAsync(sequence.Id, Ct);
|
||||
Assert.Equal(100_000, refreshed!.FrameCount);
|
||||
Assert.Equal(frames[^1], (await db.Frames.ListBySequenceAsync(sequence.Id, afterIndex: 99_998, cancellationToken: Ct)).Single());
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SqliteBulkInsertTests(TestContext context) : BulkInsertTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.SqliteFile;
|
||||
}
|
||||
|
||||
[RequiresEnvironment(PgTestServer.Variable)]
|
||||
public sealed class PostgresBulkInsertTests(TestContext context) : BulkInsertTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
}
|
||||
@@ -0,0 +1,415 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Repositories;
|
||||
using Titano.Data.Tests.Infrastructure;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Data.Tests.Repositories;
|
||||
|
||||
/// <summary>Archives, sequences, frames, renders and tags on both dialects.</summary>
|
||||
public abstract class CatalogRepositoryTests(TestContext context) : RepositoryTest(context)
|
||||
{
|
||||
[Test]
|
||||
public async Task ArchivesRoundTripAndDelete()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var archive = TestData.Archive() with { ProxyLongEdge = -1, FolderTemplate = "{year}/{title}" };
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
await db.Archives.UpsertAsync(archive with { Name = "Renamed" }, Ct);
|
||||
Assert.Equal(archive with { Name = "Renamed" }, await db.Archives.GetAsync(archive.Id, Ct));
|
||||
Assert.Count(1, await db.Archives.ListAsync(Ct));
|
||||
Assert.True(await db.Archives.DeleteAsync(archive.Id, Ct));
|
||||
Assert.Null(await db.Archives.GetAsync(archive.Id, Ct));
|
||||
Assert.False(await db.Archives.DeleteAsync(archive.Id, Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SequencesRoundTripEveryField()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var archive = TestData.Archive();
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
var sequence = TestData.Sequence(archive.Id, new DateTime(2026, 9, 28, 18, 30, 15, 250), "Harbour sunset") with
|
||||
{
|
||||
CameraSerial = "0123",
|
||||
Lens = "RF 24-70",
|
||||
FrameCount = 1200,
|
||||
MedianInterval = 5.0,
|
||||
TotalBytes = 30_000_000_000,
|
||||
Status = SequenceStatus.AnalyzedLight | SequenceStatus.ThumbsBuilt,
|
||||
RenderedCount = 0,
|
||||
VerifiedAt = TestData.Now,
|
||||
HeroFrameId = Guid.CreateVersion7(),
|
||||
Rating = 4,
|
||||
Notes = "windy",
|
||||
SettingsJson = "{\"fps\": 25, \"deflicker\": true}",
|
||||
AnalysisJson = "{\"ev\": [12.5, 13]}",
|
||||
Origin = SequenceOrigin.Server,
|
||||
SyncState = SyncState.LocalAhead,
|
||||
SettingsVersion = 3,
|
||||
FramesVersion = 7,
|
||||
OwnerUserId = Guid.CreateVersion7(),
|
||||
WarningCount = 2,
|
||||
Tags = ["Sunset", "harbour", "SUNSET"],
|
||||
};
|
||||
await db.Sequences.UpsertAsync(sequence, Ct);
|
||||
|
||||
var read = Assert.NotNull(await db.Sequences.GetAsync(sequence.Id, Ct));
|
||||
Assert.True(JsonNode.DeepEquals(JsonNode.Parse(sequence.SettingsJson!), JsonNode.Parse(read.SettingsJson!)));
|
||||
Assert.True(JsonNode.DeepEquals(JsonNode.Parse(sequence.AnalysisJson!), JsonNode.Parse(read.AnalysisJson!)));
|
||||
Assert.SequenceEqual(["harbour", "Sunset"], read.Tags);
|
||||
Assert.Equal(sequence with { Tags = read.Tags, SettingsJson = read.SettingsJson, AnalysisJson = read.AnalysisJson }, read);
|
||||
|
||||
await db.Sequences.UpsertAsync(sequence with { Title = null, Tags = ["night"], Rating = 1 }, Ct);
|
||||
read = Assert.NotNull(await db.Sequences.GetAsync(sequence.Id, Ct));
|
||||
Assert.Null(read.Title);
|
||||
Assert.Equal("2026-09-28 EOS R5", read.DisplayTitle);
|
||||
Assert.SequenceEqual(["night"], read.Tags);
|
||||
Assert.Equal(1, read.Rating);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DeletingASequenceRemovesItsFramesRendersAndTagLinks()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var archive = TestData.Archive();
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
var sequence = TestData.Sequence(archive.Id) with { Tags = ["a"] };
|
||||
await db.Sequences.UpsertAsync(sequence, Ct);
|
||||
await db.Frames.BulkInsertAsync(Enumerable.Range(0, 10).Select(i => TestData.Frame(sequence.Id, i)), Ct);
|
||||
await db.Renders.InsertAsync(Render(sequence.Id), Ct);
|
||||
|
||||
Assert.True(await db.Sequences.DeleteAsync(sequence.Id, Ct));
|
||||
Assert.Empty(await db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: Ct));
|
||||
Assert.Empty(await db.Renders.ListBySequenceAsync(sequence.Id, Ct));
|
||||
Assert.Equal(0, (await db.Tags.ListAsync(Ct)).Single().SequenceCount);
|
||||
Assert.Equal(1, await db.Tags.DeleteUnusedAsync(Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ListingFiltersCombine()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var main = TestData.Archive();
|
||||
var other = TestData.Archive("Other");
|
||||
await db.Archives.UpsertAsync(main, Ct);
|
||||
await db.Archives.UpsertAsync(other, Ct);
|
||||
var owner = Guid.CreateVersion7();
|
||||
var harbour = TestData.Sequence(main.Id, new DateTime(2024, 6, 1), "Porto di CITTÀ vecchia") with { Status = SequenceStatus.AnalyzedLight, Tags = ["sea"] };
|
||||
var stars = TestData.Sequence(main.Id, new DateTime(2025, 1, 2), "Milky way", "Z8") with { CameraMake = "Nikon", Tags = ["Night Sky"], OwnerUserId = owner };
|
||||
var clouds = TestData.Sequence(main.Id, new DateTime(2024, 12, 31, 23, 59, 59), "50%_clouds") with { Status = SequenceStatus.AnalyzedLight | SequenceStatus.Verified };
|
||||
var elsewhere = TestData.Sequence(other.Id, new DateTime(2024, 3, 3), "Elsewhere");
|
||||
var undated = TestData.Sequence(main.Id, null, "Undated");
|
||||
foreach (var s in new[] { harbour, stars, clouds, elsewhere, undated }) await db.Sequences.UpsertAsync(s, Ct);
|
||||
|
||||
async Task<string[]> Titles(SequenceQuery q) =>
|
||||
[.. (await db.Sequences.ListAsync(q with { Sort = SequenceSort.Title }, Ct)).Items.Select(s => s.Title!)];
|
||||
|
||||
Assert.SequenceEqual(["50%_clouds", "Porto di CITTÀ vecchia"], await Titles(new() { ArchiveId = main.Id, Year = 2024 }));
|
||||
Assert.SequenceEqual(["Milky way"], await Titles(new() { Camera = "Z8" }));
|
||||
Assert.SequenceEqual(["50%_clouds", "Porto di CITTÀ vecchia"], await Titles(new() { WithStatus = SequenceStatus.AnalyzedLight }));
|
||||
Assert.SequenceEqual(["Porto di CITTÀ vecchia"], await Titles(new() { WithStatus = SequenceStatus.AnalyzedLight, WithoutStatus = SequenceStatus.Verified }));
|
||||
Assert.SequenceEqual(["Milky way"], await Titles(new() { Tag = " night SKY " }));
|
||||
Assert.SequenceEqual(["Porto di CITTÀ vecchia"], await Titles(new() { Text = "città" }));
|
||||
Assert.SequenceEqual(["Milky way"], await Titles(new() { Text = "NIKON" }));
|
||||
Assert.SequenceEqual(["Milky way"], await Titles(new() { Text = "ght sk" }));
|
||||
Assert.SequenceEqual(["50%_clouds"], await Titles(new() { Text = "50%_" }));
|
||||
Assert.Empty(await Titles(new() { Text = "5_%" }));
|
||||
Assert.SequenceEqual(["Milky way"], await Titles(new() { OwnerUserId = owner }));
|
||||
Assert.Equal(4, await db.Sequences.CountAsync(new() { ArchiveId = main.Id }, Ct));
|
||||
Assert.Equal(2, await db.Sequences.CountAsync(new() { ArchiveId = main.Id, Year = 2024 }, Ct));
|
||||
Assert.Equal(5, await db.Sequences.CountAsync(new(), Ct));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(SequenceSort.Newest)]
|
||||
[Case(SequenceSort.Oldest)]
|
||||
[Case(SequenceSort.Title)]
|
||||
[Case(SequenceSort.FrameCount)]
|
||||
[Case(SequenceSort.Size)]
|
||||
public async Task KeysetPagesVisitEveryRowOnceInOrderDespiteTies(SequenceSort sort)
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var archive = TestData.Archive();
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
var all = Enumerable.Range(0, 23).Select(i => TestData.Sequence(archive.Id,
|
||||
i % 5 == 4 ? null : new DateTime(2024 + i % 3, 1, 1, 12, 0, 0),
|
||||
i % 4 == 0 ? null : "T" + (i % 6)) with
|
||||
{ FrameCount = i % 3, TotalBytes = i % 4 * 1000L })
|
||||
.ToList();
|
||||
foreach (var s in all) await db.Sequences.UpsertAsync(s, Ct);
|
||||
|
||||
var expected = Expected(all, sort).Select(s => s.Id).ToList();
|
||||
var seen = new List<Guid>();
|
||||
string? cursor = null;
|
||||
var pages = 0;
|
||||
do
|
||||
{
|
||||
var page = await db.Sequences.ListAsync(new SequenceQuery { ArchiveId = archive.Id, Sort = sort, Limit = 4, Cursor = cursor }, Ct);
|
||||
Assert.True(page.Items.Count is > 0 and <= 4);
|
||||
seen.AddRange(page.Items.Select(s => s.Id));
|
||||
cursor = page.NextCursor;
|
||||
pages++;
|
||||
}
|
||||
while (cursor is not null);
|
||||
|
||||
Assert.Equal(6, pages);
|
||||
Assert.SequenceEqual(expected, seen);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CursorsOnlyWorkForTheirOwnSort()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var archive = TestData.Archive();
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
for (var i = 0; i < 3; i++) await db.Sequences.UpsertAsync(TestData.Sequence(archive.Id, new DateTime(2024, 1, 1 + i)), Ct);
|
||||
var page = await db.Sequences.ListAsync(new SequenceQuery { Limit = 1 }, Ct);
|
||||
Assert.NotNull(page.NextCursor);
|
||||
await Assert.ThrowsAsync<FormatException>(() => db.Sequences.ListAsync(new SequenceQuery { Sort = SequenceSort.Size, Cursor = page.NextCursor }, Ct));
|
||||
await Assert.ThrowsAsync<FormatException>(() => db.Sequences.ListAsync(new SequenceQuery { Cursor = "not-a-cursor" }, Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task StatisticsAggregateTheArchive()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var main = TestData.Archive();
|
||||
var other = TestData.Archive("Other");
|
||||
await db.Archives.UpsertAsync(main, Ct);
|
||||
await db.Archives.UpsertAsync(other, Ct);
|
||||
Sequence Seq(Guid archive, DateTime? first, string model, int frames, long bytes, SequenceStatus status) =>
|
||||
TestData.Sequence(archive, first, camera: model) with { FrameCount = frames, TotalBytes = bytes, Status = status };
|
||||
var a = Seq(main.Id, new DateTime(2024, 3, 10), "EOS R5", 10, 1000, SequenceStatus.AnalyzedLight) with { VerifiedAt = TestData.Now };
|
||||
var b = Seq(main.Id, new DateTime(2024, 3, 20), "Z8", 20, 2000, SequenceStatus.HasWarnings) with { CameraMake = "Nikon" };
|
||||
var c = Seq(main.Id, new DateTime(2025, 7, 1), "EOS R5", 30, 3000, SequenceStatus.HasErrors | SequenceStatus.AnalyzedLight);
|
||||
var d = Seq(main.Id, null, "EOS R5", 0, 0, SequenceStatus.None) with { WarningCount = 1 };
|
||||
var e = Seq(other.Id, new DateTime(2023, 1, 1), "X-T5", 5, 500, SequenceStatus.None);
|
||||
foreach (var s in new[] { a, b, c, d, e }) await db.Sequences.UpsertAsync(s, Ct);
|
||||
await db.Frames.BulkInsertAsync(
|
||||
[
|
||||
TestData.Frame(a.Id, 0) with { Flags = FrameFlags.Missing, Size = 100 },
|
||||
TestData.Frame(a.Id, 1) with { Format = ImageFileFormat.Jpeg, Size = 10, Flags = FrameFlags.Duplicate | FrameFlags.Corrupt },
|
||||
TestData.Frame(b.Id, 0) with { Size = 200 },
|
||||
TestData.Frame(e.Id, 0) with { Format = ImageFileFormat.Raf, Flags = FrameFlags.Missing },
|
||||
], Ct);
|
||||
|
||||
var stats = await db.Sequences.GetStatsAsync(main.Id, Ct);
|
||||
Assert.Equal(4, stats.Sequences);
|
||||
Assert.Equal(60L, stats.Photos);
|
||||
Assert.Equal(6000L, stats.Bytes);
|
||||
Assert.SequenceEqual([new YearBucket(2024, 2, 30, 3000), new YearBucket(2025, 1, 30, 3000)], stats.ByYear);
|
||||
Assert.SequenceEqual([new MonthBucket(2024, 3, 2, 30), new MonthBucket(2025, 7, 1, 30)], stats.ByMonth);
|
||||
Assert.SequenceEqual(
|
||||
[new CameraBucket("Canon", "EOS R5", 3, 40, 4000), new CameraBucket("Nikon", "Z8", 1, 20, 2000)],
|
||||
stats.ByCamera);
|
||||
Assert.SequenceEqual([new FormatBucket(ImageFileFormat.Cr3, 2, 300), new FormatBucket(ImageFileFormat.Jpeg, 1, 10)], stats.ByFormat);
|
||||
Assert.Equal(new ArchiveHealth(Unverified: 3, WithWarnings: 2, WithErrors: 1, NotAnalyzed: 2, MissingFrames: 1, CorruptFrames: 1, DuplicateFrames: 1), stats.Health);
|
||||
|
||||
var everything = await db.Sequences.GetStatsAsync(cancellationToken: Ct);
|
||||
Assert.Equal(5, everything.Sequences);
|
||||
Assert.Equal(2L, everything.Health.MissingFrames);
|
||||
Assert.Equal(2023, everything.ByYear[0].Year);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task FramesBulkInsertPageAndFindDuplicates()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var archive = TestData.Archive();
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
var sequence = TestData.Sequence(archive.Id);
|
||||
await db.Sequences.UpsertAsync(sequence, Ct);
|
||||
var frames = Enumerable.Range(0, 250).Select(i => TestData.Frame(sequence.Id, i)).ToList();
|
||||
frames[7] = frames[7] with
|
||||
{
|
||||
OriginalFileName = "DSC_7.NEF",
|
||||
CapturedAt = new DateTime(2026, 9, 28, 18, 0, 35, 123),
|
||||
UtcOffsetMinutes = 120,
|
||||
ExposureBias = -0.3,
|
||||
WhiteBalance = 5600,
|
||||
Orientation = 6,
|
||||
PreviewOffset = 1024,
|
||||
PreviewLength = 65536,
|
||||
MeanLogLuminance = -2.5,
|
||||
ClipLow = 0.01,
|
||||
ClipHigh = 0.02,
|
||||
Flags = FrameFlags.Excluded,
|
||||
Sha256 = "AB" + new string('c', 62),
|
||||
};
|
||||
Assert.Equal(250L, await db.Frames.BulkInsertAsync(frames, Ct));
|
||||
var copy = TestData.Frame(sequence.Id, 1000) with { Sha256 = frames[7].Sha256 };
|
||||
await db.Frames.InsertAsync(copy, Ct);
|
||||
|
||||
Assert.Equal(frames[7] with { Sha256 = frames[7].Sha256!.ToLowerInvariant() }, await db.Frames.GetAsync(frames[7].Id, Ct));
|
||||
var pageOne = await db.Frames.ListBySequenceAsync(sequence.Id, limit: 100, cancellationToken: Ct);
|
||||
var pageThree = await db.Frames.ListBySequenceAsync(sequence.Id, afterIndex: 199, limit: 100, cancellationToken: Ct);
|
||||
Assert.SequenceEqual(Enumerable.Range(0, 100), pageOne.Select(f => f.Index));
|
||||
Assert.SequenceEqual(Enumerable.Range(200, 50).Append(1000), pageThree.Select(f => f.Index));
|
||||
var duplicates = await db.Frames.FindBySha256Async(frames[7].Sha256!.ToUpperInvariant(), Ct);
|
||||
Assert.SequenceEqual([7, 1000], duplicates.Select(f => f.Index));
|
||||
|
||||
var stats = Assert.NotNull(await db.Sequences.RefreshStatsAsync(sequence.Id, Ct));
|
||||
Assert.Equal(251, stats.FrameCount);
|
||||
Assert.Equal(frames.Sum(f => f.Size) + copy.Size, stats.TotalBytes);
|
||||
Assert.Equal(frames[0].CapturedAt, stats.FirstCapture);
|
||||
Assert.Equal(copy.CapturedAt, stats.LastCapture);
|
||||
Assert.Equal(1, stats.FramesVersion);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task FrameAnalysisAndFlagsUpdateInBulk()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var archive = TestData.Archive();
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
var sequence = TestData.Sequence(archive.Id);
|
||||
await db.Sequences.UpsertAsync(sequence, Ct);
|
||||
var frames = Enumerable.Range(0, 1200).Select(i => TestData.Frame(sequence.Id, i) with { Flags = FrameFlags.Missing }).ToList();
|
||||
await db.Frames.BulkInsertAsync(frames, Ct);
|
||||
|
||||
var stats = frames.Select((f, i) => new FrameLightStats(f.Id, -i / 100.0, i % 2 == 0 ? null : 0.5, 0.001 * i)).ToList();
|
||||
Assert.Equal(1200, await db.Frames.UpdateLightStatsAsync(stats, Ct));
|
||||
var ids = frames.Where(f => f.Index % 3 == 0).Select(f => f.Id).ToList();
|
||||
Assert.Equal(400, await db.Frames.UpdateFlagsAsync(ids, FrameFlags.Duplicate | FrameFlags.Excluded, FrameFlags.Missing, Ct));
|
||||
|
||||
var read = new List<Frame>();
|
||||
for (var after = -1; ; after = read[^1].Index)
|
||||
{
|
||||
var page = await db.Frames.ListBySequenceAsync(sequence.Id, after, 500, Ct);
|
||||
if (page.Count == 0) break;
|
||||
read.AddRange(page);
|
||||
}
|
||||
Assert.Equal(1200, read.Count);
|
||||
foreach (var f in read)
|
||||
{
|
||||
Assert.Equal(-f.Index / 100.0, f.MeanLogLuminance);
|
||||
Assert.Equal(f.Index % 2 == 0 ? null : 0.5, f.ClipLow);
|
||||
Assert.Equal(f.Index % 3 == 0 ? FrameFlags.Duplicate | FrameFlags.Excluded : FrameFlags.Missing, f.Flags);
|
||||
}
|
||||
Assert.Equal(1200, await db.Frames.DeleteBySequenceAsync(sequence.Id, Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RendersKeepTheSequenceCountInStep()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var archive = TestData.Archive();
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
var sequence = TestData.Sequence(archive.Id);
|
||||
await db.Sequences.UpsertAsync(sequence, Ct);
|
||||
var first = Render(sequence.Id) with { Created = TestData.Now };
|
||||
var second = Render(sequence.Id) with { Created = TestData.Now.AddMinutes(5), SettingsJson = null, Codec = null };
|
||||
await db.Renders.InsertAsync(first, Ct);
|
||||
await db.Renders.InsertAsync(second, Ct);
|
||||
Assert.Equal(2, (await db.Sequences.GetAsync(sequence.Id, Ct))!.RenderedCount);
|
||||
await db.Sequences.UpsertAsync(sequence with { Title = "Renamed from a stale copy" }, Ct);
|
||||
Assert.Equal(2, (await db.Sequences.GetAsync(sequence.Id, Ct))!.RenderedCount);
|
||||
var list = await db.Renders.ListBySequenceAsync(sequence.Id, Ct);
|
||||
Assert.SequenceEqual([second.Id, first.Id], list.Select(r => r.Id));
|
||||
Assert.Equal(second, list[0]);
|
||||
Assert.True(await db.Renders.DeleteAsync(second.Id, Ct));
|
||||
Assert.False(await db.Renders.DeleteAsync(second.Id, Ct));
|
||||
Assert.Equal(1, (await db.Sequences.GetAsync(sequence.Id, Ct))!.RenderedCount);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TagsCanBeListedRenamedAndDeleted()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var archive = TestData.Archive();
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
var one = TestData.Sequence(archive.Id) with { Tags = ["Alps", "snow"] };
|
||||
var two = TestData.Sequence(archive.Id) with { Tags = ["alps"] };
|
||||
await db.Sequences.UpsertAsync(one, Ct);
|
||||
await db.Sequences.UpsertAsync(two, Ct);
|
||||
Assert.False(await db.Sequences.SetTagsAsync(Guid.CreateVersion7(), ["x"], Ct));
|
||||
|
||||
var tags = await db.Tags.ListAsync(Ct);
|
||||
Assert.SequenceEqual([("Alps", 2), ("snow", 1)], tags.Select(t => (t.Name, t.SequenceCount)));
|
||||
var snow = tags.Single(t => t.Name == "snow");
|
||||
await Assert.ThrowsAsync<DatabaseException>(() => db.Tags.RenameAsync(snow.Id, "ALPS", Ct));
|
||||
Assert.True(await db.Tags.RenameAsync(snow.Id, "Snow fields", Ct));
|
||||
Assert.SequenceEqual(["Alps", "Snow fields"], (await db.Sequences.GetAsync(one.Id, Ct))!.Tags);
|
||||
Assert.True(await db.Tags.DeleteAsync(snow.Id, Ct));
|
||||
Assert.SequenceEqual(["Alps"], (await db.Sequences.GetAsync(one.Id, Ct))!.Tags);
|
||||
Assert.True(await db.Sequences.SetTagsAsync(two.Id, [], Ct));
|
||||
Assert.Equal(1, (await db.Tags.ListAsync(Ct)).Single().SequenceCount);
|
||||
Assert.Throws<ArgumentException>(() => TagRepository.Normalize(" \t "));
|
||||
Assert.Throws<ArgumentException>(() => TagRepository.Normalize("bad\u0001tag"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TransactionsGroupRepositoryCalls()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var archive = TestData.Archive();
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
var sequence = TestData.Sequence(archive.Id);
|
||||
|
||||
await using (var tx = await db.BeginAsync(Ct))
|
||||
{
|
||||
await tx.Sequences.UpsertAsync(sequence, Ct);
|
||||
await tx.Frames.InsertAsync(TestData.Frame(sequence.Id, 0), Ct);
|
||||
Assert.NotNull(await tx.Sequences.GetAsync(sequence.Id, Ct));
|
||||
}
|
||||
Assert.Null(await db.Sequences.GetAsync(sequence.Id, Ct));
|
||||
|
||||
await using (var tx = await db.BeginAsync(Ct))
|
||||
{
|
||||
await tx.Sequences.UpsertAsync(sequence, Ct);
|
||||
await tx.Frames.InsertAsync(TestData.Frame(sequence.Id, 0), Ct);
|
||||
await tx.Sequences.RefreshStatsAsync(sequence.Id, Ct);
|
||||
await tx.CommitAsync(Ct);
|
||||
}
|
||||
Assert.Equal(1, (await db.Sequences.GetAsync(sequence.Id, Ct))!.FrameCount);
|
||||
}
|
||||
|
||||
private static Render Render(Guid sequenceId) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
SequenceId = sequenceId,
|
||||
PresetName = "4K HEVC",
|
||||
SettingsJson = "{\"crf\": 18}",
|
||||
OutputPath = "exports/out.mp4",
|
||||
Codec = "hevc",
|
||||
Width = 3840,
|
||||
Height = 2160,
|
||||
Fps = 29.97,
|
||||
DurationSeconds = 41.5,
|
||||
Bytes = 123_456_789,
|
||||
Created = TestData.Now,
|
||||
ProducedBy = "node-1",
|
||||
};
|
||||
|
||||
/// <summary>The order the database must produce: sort key with NULLS LAST, then id (as text) in the same direction.</summary>
|
||||
private static IEnumerable<Sequence> Expected(List<Sequence> all, SequenceSort sort)
|
||||
{
|
||||
int ById(Sequence a, Sequence b) => string.CompareOrdinal(a.Id.ToString("D"), b.Id.ToString("D"));
|
||||
int NullsLast<T>(T? a, T? b, Comparison<T> compare) where T : struct =>
|
||||
a is null ? (b is null ? 0 : 1) : b is null ? -1 : compare(a.Value, b.Value);
|
||||
Comparison<Sequence> comparison = sort switch
|
||||
{
|
||||
SequenceSort.Newest => (a, b) => NullsLast<DateTime>(a.FirstCapture, b.FirstCapture, (x, y) => y.CompareTo(x)) is var c and not 0 ? c : -ById(a, b),
|
||||
SequenceSort.Oldest => (a, b) => NullsLast<DateTime>(a.FirstCapture, b.FirstCapture, (x, y) => x.CompareTo(y)) is var c and not 0 ? c : ById(a, b),
|
||||
SequenceSort.Title => (a, b) => string.CompareOrdinal(a.DisplayTitle.ToLowerInvariant(), b.DisplayTitle.ToLowerInvariant()) is var c and not 0 ? c : ById(a, b),
|
||||
SequenceSort.FrameCount => (a, b) => b.FrameCount.CompareTo(a.FrameCount) is var c and not 0 ? c : -ById(a, b),
|
||||
_ => (a, b) => b.TotalBytes.CompareTo(a.TotalBytes) is var c and not 0 ? c : -ById(a, b),
|
||||
};
|
||||
var sorted = all.ToList();
|
||||
sorted.Sort(comparison);
|
||||
return sorted;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SqliteCatalogRepositoryTests(TestContext context) : CatalogRepositoryTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.SqliteMemory;
|
||||
}
|
||||
|
||||
[RequiresEnvironment(PgTestServer.Variable)]
|
||||
public sealed class PostgresCatalogRepositoryTests(TestContext context) : CatalogRepositoryTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Tests.Infrastructure;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Data.Tests.Repositories;
|
||||
|
||||
public abstract class JobRepositoryTests(TestContext context) : RepositoryTest(context)
|
||||
{
|
||||
[Test]
|
||||
public async Task JobsRoundTripEveryField()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var job = TestData.Job(JobKind.Render, JobPriority.User) with
|
||||
{
|
||||
TargetIds = [Guid.CreateVersion7(), Guid.CreateVersion7()],
|
||||
TargetLabel = "Harbour sunset",
|
||||
ParametersJson = "{\"preset\": \"4K\"}",
|
||||
ProgressDone = 5,
|
||||
ProgressTotal = 10,
|
||||
ItemsPerSecond = 2.5,
|
||||
Eta = TimeSpan.FromSeconds(2),
|
||||
Checkpoint = "frame:5",
|
||||
LogTail = "line 1\nline 2",
|
||||
CreatedBy = Guid.CreateVersion7(),
|
||||
NodeId = "node-a",
|
||||
Attempts = 1,
|
||||
Error = "boom",
|
||||
State = JobState.Failed,
|
||||
Started = TestData.Now.AddMinutes(1),
|
||||
Finished = TestData.Now.AddMinutes(2),
|
||||
};
|
||||
await db.Jobs.EnqueueAsync(job, Ct);
|
||||
var read = Assert.NotNull(await db.Jobs.GetAsync(job.Id, Ct));
|
||||
Assert.SequenceEqual(job.TargetIds, read.TargetIds);
|
||||
Assert.Equal(job with { TargetIds = read.TargetIds }, read);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ClaimsByPriorityThenAgeAndKind()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var oldBackground = TestData.Job(JobKind.Thumbs, JobPriority.Background, TestData.Now.AddMinutes(-10));
|
||||
var newUser = TestData.Job(JobKind.Render, JobPriority.User, TestData.Now);
|
||||
var oldUser = TestData.Job(JobKind.Import, JobPriority.User, TestData.Now.AddMinutes(-1));
|
||||
var normal = TestData.Job(JobKind.Scan, JobPriority.Normal, TestData.Now.AddMinutes(-5));
|
||||
foreach (var job in new[] { oldBackground, newUser, oldUser, normal }) await db.Jobs.EnqueueAsync(job, Ct);
|
||||
|
||||
var renderOnly = await db.Jobs.ClaimNextAsync("node-gpu", [JobKind.Render], Ct);
|
||||
Assert.Equal(newUser.Id, renderOnly?.Id);
|
||||
Assert.Equal(JobState.Running, renderOnly!.State);
|
||||
Assert.Equal("node-gpu", renderOnly.NodeId);
|
||||
Assert.Equal(1, renderOnly.Attempts);
|
||||
Assert.NotNull(renderOnly.Started);
|
||||
Assert.Null(await db.Jobs.ClaimNextAsync("node-gpu", [JobKind.Render], Ct));
|
||||
|
||||
var order = new List<Guid>();
|
||||
while (await db.Jobs.ClaimNextAsync("server", cancellationToken: Ct) is { } claimed) order.Add(claimed.Id);
|
||||
Assert.SequenceEqual([oldUser.Id, normal.Id, oldBackground.Id], order);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ConcurrentClaimersNeverShareAJob()
|
||||
{
|
||||
var db = await OpenTitanoAsync(multiConnection: true);
|
||||
var jobs = Enumerable.Range(0, 40).Select(i => TestData.Job(created: TestData.Now.AddSeconds(i))).ToList();
|
||||
foreach (var job in jobs) await db.Jobs.EnqueueAsync(job, Ct);
|
||||
|
||||
var claims = new ConcurrentBag<(string Worker, Guid Job)>();
|
||||
await Task.WhenAll(Enumerable.Range(0, 8).Select(w => Task.Run(async () =>
|
||||
{
|
||||
var worker = "worker-" + w;
|
||||
while (await db.Jobs.ClaimNextAsync(worker, cancellationToken: Ct) is { } job) claims.Add((worker, job.Id));
|
||||
})));
|
||||
|
||||
Assert.Equal(40, claims.Count);
|
||||
Assert.Equal(40, claims.Select(c => c.Job).Distinct().Count());
|
||||
foreach (var (worker, id) in claims)
|
||||
{
|
||||
var stored = await db.Jobs.GetAsync(id, Ct);
|
||||
Assert.Equal(worker, stored!.NodeId);
|
||||
Assert.Equal(1, stored.Attempts);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ProgressIsRefusedOnceTheJobStopsRunning()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var job = TestData.Job();
|
||||
await db.Jobs.EnqueueAsync(job, Ct);
|
||||
Assert.False(await db.Jobs.UpdateProgressAsync(job.Id, 1, 10, null, null, null, null, Ct));
|
||||
await db.Jobs.ClaimNextAsync("w", cancellationToken: Ct);
|
||||
Assert.True(await db.Jobs.UpdateProgressAsync(job.Id, 4, 10, 2.0, TimeSpan.FromSeconds(3), "cursor:4", "tail", Ct));
|
||||
var running = await db.Jobs.GetAsync(job.Id, Ct);
|
||||
Assert.Equal((4L, 10L, "cursor:4", "tail"), (running!.ProgressDone, running.ProgressTotal, running.Checkpoint, running.LogTail));
|
||||
Assert.Equal(TimeSpan.FromSeconds(3), running.Eta);
|
||||
|
||||
Assert.True(await db.Jobs.SetStateAsync(job.Id, JobState.Cancelled, cancellationToken: Ct));
|
||||
Assert.False(await db.Jobs.UpdateProgressAsync(job.Id, 5, 10, null, null, "cursor:5", null, Ct));
|
||||
var cancelled = await db.Jobs.GetAsync(job.Id, Ct);
|
||||
Assert.Equal(JobState.Cancelled, cancelled!.State);
|
||||
Assert.NotNull(cancelled.Finished);
|
||||
|
||||
Assert.True(await db.Jobs.SetStateAsync(job.Id, JobState.Queued, cancellationToken: Ct));
|
||||
Assert.Null((await db.Jobs.GetAsync(job.Id, Ct))!.Finished);
|
||||
Assert.Equal(2, (await db.Jobs.ClaimNextAsync("w", cancellationToken: Ct))!.Attempts);
|
||||
Assert.False(await db.Jobs.SetStateAsync(Guid.CreateVersion7(), JobState.Done, cancellationToken: Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ListingPagesByStateNewestFirst()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var jobs = Enumerable.Range(0, 7).Select(i => TestData.Job(created: TestData.Now.AddMinutes(i % 3))).ToList();
|
||||
foreach (var job in jobs) await db.Jobs.EnqueueAsync(job, Ct);
|
||||
await db.Jobs.SetStateAsync(jobs[0].Id, JobState.Done, cancellationToken: Ct);
|
||||
|
||||
var seen = new List<Guid>();
|
||||
string? cursor = null;
|
||||
do
|
||||
{
|
||||
var page = await db.Jobs.ListAsync(JobState.Queued, limit: 2, cursor: cursor, cancellationToken: Ct);
|
||||
seen.AddRange(page.Items.Select(j => j.Id));
|
||||
cursor = page.NextCursor;
|
||||
}
|
||||
while (cursor is not null);
|
||||
|
||||
var expected = jobs.Skip(1)
|
||||
.OrderByDescending(j => j.Created)
|
||||
.ThenByDescending(j => j.Id.ToString("D"), StringComparer.Ordinal)
|
||||
.Select(j => j.Id);
|
||||
Assert.SequenceEqual(expected, seen);
|
||||
Assert.SequenceEqual([jobs[0].Id], (await db.Jobs.ListAsync(JobState.Done, cancellationToken: Ct)).Items.Select(j => j.Id));
|
||||
Assert.Equal(7, (await db.Jobs.ListAsync(cancellationToken: Ct)).Items.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task HistoryPurgeKeepsRecentAndActiveJobs()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var old = TestData.Job() with { State = JobState.Done, Finished = TestData.Now.AddDays(-100) };
|
||||
var oldFailed = TestData.Job() with { State = JobState.Failed, Finished = TestData.Now.AddDays(-91) };
|
||||
var recent = TestData.Job() with { State = JobState.Done, Finished = TestData.Now.AddDays(-10) };
|
||||
var queued = TestData.Job(created: TestData.Now.AddDays(-200));
|
||||
foreach (var job in new[] { old, oldFailed, recent, queued }) await db.Jobs.EnqueueAsync(job, Ct);
|
||||
Assert.Equal(2, await db.Jobs.PurgeHistoryAsync(TestData.Now.AddDays(-90), Ct));
|
||||
Assert.Equal(2, (await db.Jobs.ListAsync(cancellationToken: Ct)).Items.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RunningJobsAreRequeuedAfterACrash()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
for (var i = 0; i < 3; i++) await db.Jobs.EnqueueAsync(TestData.Job(created: TestData.Now.AddSeconds(i)), Ct);
|
||||
var a = await db.Jobs.ClaimNextAsync("node-a", cancellationToken: Ct);
|
||||
var b = await db.Jobs.ClaimNextAsync("node-b", cancellationToken: Ct);
|
||||
await db.Jobs.UpdateProgressAsync(a!.Id, 3, 9, null, null, "resume-here", null, Ct);
|
||||
|
||||
Assert.Equal(1, await db.Jobs.RequeueRunningAsync("node-a", Ct));
|
||||
var requeued = await db.Jobs.GetAsync(a.Id, Ct);
|
||||
Assert.Equal(JobState.Queued, requeued!.State);
|
||||
Assert.Equal("resume-here", requeued.Checkpoint);
|
||||
Assert.Null(requeued.NodeId);
|
||||
Assert.Equal(JobState.Running, (await db.Jobs.GetAsync(b!.Id, Ct))!.State);
|
||||
Assert.Equal(1, await db.Jobs.RequeueRunningAsync(cancellationToken: Ct));
|
||||
Assert.Equal(0, await db.Jobs.RequeueRunningAsync(cancellationToken: Ct));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SqliteJobRepositoryTests(TestContext context) : JobRepositoryTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.SqliteMemory;
|
||||
}
|
||||
|
||||
[RequiresEnvironment(PgTestServer.Variable)]
|
||||
public sealed class PostgresJobRepositoryTests(TestContext context) : JobRepositoryTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Repositories;
|
||||
using Titano.Data.Tests.Infrastructure;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Data.Tests.Repositories;
|
||||
|
||||
public abstract class MediaCardRepositoryTests(TestContext context) : RepositoryTest(context)
|
||||
{
|
||||
[Test]
|
||||
public async Task CardsRoundTripAndAreFoundByIdentity()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var card = Card();
|
||||
await db.MediaCards.UpsertAsync(card, Ct);
|
||||
Assert.Equal(card, await db.MediaCards.GetAsync(card.Id, Ct));
|
||||
Assert.Equal(card, await db.MediaCards.FindByIdentityAsync(card.Identity, Ct));
|
||||
Assert.Null(await db.MediaCards.FindByIdentityAsync("unknown", Ct));
|
||||
|
||||
var seen = TestData.Now.AddDays(2);
|
||||
Assert.True(await db.MediaCards.TouchAsync(card.Id, seen, Ct));
|
||||
await db.MediaCards.UpsertAsync(card with { Nickname = "Card B", LastSeen = seen }, Ct);
|
||||
var other = Card() with { Identity = "1-OTHER-64", LastSeen = TestData.Now.AddDays(5) };
|
||||
await db.MediaCards.UpsertAsync(other, Ct);
|
||||
Assert.SequenceEqual([other.Id, card.Id], (await db.MediaCards.ListAsync(Ct)).Select(c => c.Id));
|
||||
Assert.Equal("Card B", (await db.MediaCards.GetAsync(card.Id, Ct))!.Nickname);
|
||||
|
||||
var clash = await Assert.ThrowsAsync<DatabaseException>(() => db.MediaCards.UpsertAsync(Card() with { Identity = card.Identity }, Ct));
|
||||
Assert.True(clash.IsUniqueViolation);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ImportHistoryLetsReinsertsSkipKnownFiles()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var card = Card();
|
||||
await db.MediaCards.UpsertAsync(card, Ct);
|
||||
var archive = TestData.Archive();
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
var sequence = TestData.Sequence(archive.Id);
|
||||
await db.Sequences.UpsertAsync(sequence, Ct);
|
||||
var frame = TestData.Frame(sequence.Id, 0);
|
||||
await db.Frames.InsertAsync(frame, Ct);
|
||||
|
||||
// File-system times carry 100 ns ticks; keys compare at the database's microsecond precision.
|
||||
var modified = new DateTimeOffset(2026, 9, 28, 18, 0, 0, TimeSpan.FromHours(2)).AddTicks(1234567);
|
||||
var first = new ImportKey("DCIM/100CANON/IMG_0001.CR3", 25_000_000, modified);
|
||||
var reused = new ImportKey("DCIM/100CANON/IMG_0001.CR3", 24_000_000, modified.AddDays(30));
|
||||
var job = Guid.CreateVersion7();
|
||||
await db.MediaCards.RecordImportsAsync(
|
||||
[
|
||||
new ImportRecord(card.Id, first, new string('F', 64), frame.Id, job, TestData.Now),
|
||||
new ImportRecord(card.Id, reused, null, null, job, TestData.Now.AddDays(30)),
|
||||
], Ct);
|
||||
await db.MediaCards.RecordImportsAsync([new ImportRecord(card.Id, first, new string('F', 64), frame.Id, job, TestData.Now)], Ct);
|
||||
|
||||
var keys = await db.MediaCards.GetImportedKeysAsync(card.Id, Ct);
|
||||
Assert.Equal(2, keys.Count);
|
||||
Assert.True(keys.Contains(new ImportKey("DCIM/100CANON/IMG_0001.CR3", 25_000_000, modified.AddTicks(2))));
|
||||
Assert.True(await db.MediaCards.IsImportedAsync(card.Id, first, Ct));
|
||||
Assert.False(await db.MediaCards.IsImportedAsync(card.Id, new ImportKey(first.Path, first.Size + 1, modified), Ct));
|
||||
|
||||
var history = await db.MediaCards.ListImportsAsync(card.Id, cancellationToken: Ct);
|
||||
Assert.Equal(reused, history[0].Key);
|
||||
Assert.Equal(new string('f', 64), history[1].Sha256);
|
||||
Assert.Equal(frame.Id, history[1].FrameId);
|
||||
|
||||
await db.Frames.DeleteBySequenceAsync(sequence.Id, Ct);
|
||||
Assert.Null((await db.MediaCards.ListImportsAsync(card.Id, cancellationToken: Ct))[1].FrameId);
|
||||
Assert.True(await db.MediaCards.DeleteAsync(card.Id, Ct));
|
||||
Assert.Equal(0, (await db.MediaCards.GetImportedKeysAsync(card.Id, Ct)).Count);
|
||||
}
|
||||
|
||||
private static MediaCard Card() => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Identity = "3735928559-EOS_DIGITAL-128043712512",
|
||||
VolumeSerial = 3735928559,
|
||||
Label = "EOS_DIGITAL",
|
||||
Capacity = 128_043_712_512,
|
||||
CameraMake = "Canon",
|
||||
CameraModel = "EOS R5",
|
||||
CameraSerial = "0123",
|
||||
ProfileJson = "{\"auto\": false}",
|
||||
AutoImport = true,
|
||||
FirstSeen = TestData.Now,
|
||||
LastSeen = TestData.Now,
|
||||
};
|
||||
}
|
||||
|
||||
public sealed class SqliteMediaCardRepositoryTests(TestContext context) : MediaCardRepositoryTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.SqliteMemory;
|
||||
}
|
||||
|
||||
[RequiresEnvironment(PgTestServer.Variable)]
|
||||
public sealed class PostgresMediaCardRepositoryTests(TestContext context) : MediaCardRepositoryTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Repositories;
|
||||
using Titano.Data.Tests.Infrastructure;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Data.Tests.Repositories;
|
||||
|
||||
/// <summary>Users, tokens, render nodes, settings, audit log and uploads on both dialects.</summary>
|
||||
public abstract class ServerRepositoryTests(TestContext context) : RepositoryTest(context)
|
||||
{
|
||||
[Test]
|
||||
public async Task UsersAreUniqueIgnoringCase()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var alice = TestData.User("Alice") with { DisplayName = "Alice A.", QuotaBytes = 1L << 40, MustChangePassword = true, Role = UserRole.Admin, Permissions = Permissions.All };
|
||||
await db.Users.CreateAsync(alice, Ct);
|
||||
var duplicate = await Assert.ThrowsAsync<DatabaseException>(() => db.Users.CreateAsync(TestData.User("ALICE"), Ct));
|
||||
Assert.True(duplicate.IsUniqueViolation);
|
||||
|
||||
Assert.Equal(alice, await db.Users.GetByUsernameAsync(" alice ", Ct));
|
||||
Assert.True(await db.Users.UpdateAsync(alice with { Username = "alice2", Disabled = true, MustChangePassword = false }, Ct));
|
||||
Assert.True(await db.Users.RecordLoginAsync(alice.Id, TestData.Now, Ct));
|
||||
Assert.True(await db.Users.AddUsedBytesAsync(alice.Id, 5000, Ct));
|
||||
Assert.True(await db.Users.AddUsedBytesAsync(alice.Id, -1000, Ct));
|
||||
var read = Assert.NotNull(await db.Users.GetAsync(alice.Id, Ct));
|
||||
Assert.Equal(alice with { Username = "alice2", Disabled = true, MustChangePassword = false, LastLogin = TestData.Now, UsedBytes = 4000 }, read);
|
||||
Assert.Null(await db.Users.GetByUsernameAsync("alice", Ct));
|
||||
Assert.Equal(1, await db.Users.CountAsync(Ct));
|
||||
Assert.Count(1, await db.Users.ListAsync(Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DeletingAUserRemovesTheirTokensNodesAndUploads()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var user = TestData.User();
|
||||
await db.Users.CreateAsync(user, Ct);
|
||||
await db.Tokens.InsertAsync(Token(user.Id, "h1"), Ct);
|
||||
await db.RenderNodes.RegisterAsync(Node(user.Id), Ct);
|
||||
await db.Uploads.CreateAsync(Upload(user.Id, 10), Ct);
|
||||
Assert.True(await db.Users.DeleteAsync(user.Id, Ct));
|
||||
Assert.Null(await db.Tokens.GetAsync("h1", Ct));
|
||||
Assert.Empty(await db.RenderNodes.ListAsync(Ct));
|
||||
Assert.Empty(await db.Uploads.ListByUserAsync(user.Id, Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TokensSlideRevokeAndPurge()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var user = TestData.User();
|
||||
await db.Users.CreateAsync(user, Ct);
|
||||
var token = Token(user.Id, "hash-1");
|
||||
await db.Tokens.InsertAsync(token, Ct);
|
||||
await db.Tokens.InsertAsync(Token(user.Id, "hash-2"), Ct);
|
||||
await db.Tokens.InsertAsync(Token(user.Id, "expired") with { Expires = TestData.Now.AddDays(-1) }, Ct);
|
||||
Assert.Equal(token, await db.Tokens.GetAsync("hash-1", Ct));
|
||||
|
||||
var later = TestData.Now.AddDays(3);
|
||||
Assert.True(await db.Tokens.TouchAsync("hash-1", later, later.AddDays(30), Ct));
|
||||
var touched = await db.Tokens.GetAsync("hash-1", Ct);
|
||||
Assert.Equal((later, later.AddDays(30)), (touched!.LastUsed, touched.Expires));
|
||||
Assert.False(await db.Tokens.TouchAsync("expired", TestData.Now, later, Ct));
|
||||
Assert.False(await db.Tokens.TouchAsync("missing", TestData.Now, later, Ct));
|
||||
|
||||
Assert.True(await db.Tokens.RevokeAsync("hash-1", Ct));
|
||||
Assert.False(await db.Tokens.RevokeAsync("hash-1", Ct));
|
||||
Assert.False(await db.Tokens.TouchAsync("hash-1", later, later.AddDays(30), Ct));
|
||||
Assert.True((await db.Tokens.GetAsync("hash-1", Ct))!.Revoked);
|
||||
Assert.Equal(2, await db.Tokens.RevokeAllAsync(user.Id, Ct));
|
||||
Assert.Count(3, await db.Tokens.ListByUserAsync(user.Id, Ct));
|
||||
Assert.Equal(3, await db.Tokens.PurgeAsync(TestData.Now, Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RenderNodesReportHeartbeats()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var user = TestData.User();
|
||||
await db.Users.CreateAsync(user, Ct);
|
||||
var node = Node(user.Id);
|
||||
await db.RenderNodes.RegisterAsync(node, Ct);
|
||||
var stale = Node(user.Id) with { ClientName = "old-pc", LastHeartbeat = TestData.Now.AddHours(-1) };
|
||||
await db.RenderNodes.RegisterAsync(stale, Ct);
|
||||
await db.RenderNodes.RegisterAsync(node with { CapabilitiesJson = "{\"encoders\": [\"nvenc\"]}" }, Ct);
|
||||
Assert.Equal("{\"encoders\": [\"nvenc\"]}", (await db.RenderNodes.GetAsync(node.Id, Ct))!.CapabilitiesJson);
|
||||
|
||||
Assert.SequenceEqual([node.Id], (await db.RenderNodes.ListOnlineAsync(TestData.Now.AddMinutes(-2), Ct)).Select(n => n.Id));
|
||||
Assert.True(await db.RenderNodes.HeartbeatAsync(stale.Id, "rendering", TestData.Now.AddMinutes(1), Ct));
|
||||
var online = await db.RenderNodes.ListOnlineAsync(TestData.Now.AddMinutes(-2), Ct);
|
||||
Assert.SequenceEqual([stale.Id, node.Id], online.Select(n => n.Id));
|
||||
Assert.Equal("rendering", online[0].State);
|
||||
Assert.True(await db.RenderNodes.DeleteAsync(stale.Id, Ct));
|
||||
Assert.False(await db.RenderNodes.HeartbeatAsync(stale.Id, "idle", TestData.Now, Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SettingsAreTypedAndScoped()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var archive = Guid.CreateVersion7();
|
||||
var user = Guid.CreateVersion7();
|
||||
var preferences = new Preferences("it", 4, [1.5, 2]);
|
||||
await db.Settings.SetAsync(SettingScope.App, null, "ui", preferences, TestJson.Default.Preferences, Ct);
|
||||
await db.Settings.SetAsync(SettingScope.User, user, "ui", preferences with { Language = "en" }, TestJson.Default.Preferences, Ct);
|
||||
await db.Settings.SetJsonAsync(SettingScope.Archive, archive, "proxy", "{\"longEdge\": 1920}", Ct);
|
||||
|
||||
Assert.Equal(preferences, await db.Settings.GetAsync(SettingScope.App, null, "ui", TestJson.Default.Preferences, Ct), "app scope");
|
||||
Assert.Equal("en", (await db.Settings.GetAsync(SettingScope.User, user, "ui", TestJson.Default.Preferences, Ct))!.Language);
|
||||
Assert.Null(await db.Settings.GetAsync(SettingScope.User, Guid.CreateVersion7(), "ui", TestJson.Default.Preferences, Ct));
|
||||
Assert.Equal(1920, JsonDocument.Parse((await db.Settings.GetJsonAsync(SettingScope.Archive, archive, "proxy", Ct))!).RootElement.GetProperty("longEdge").GetInt32());
|
||||
|
||||
await db.Settings.SetAsync(SettingScope.App, null, "ui", preferences with { Columns = 6 }, TestJson.Default.Preferences, Ct);
|
||||
Assert.Equal(6, (await db.Settings.GetAsync(SettingScope.App, null, "ui", TestJson.Default.Preferences, Ct))!.Columns);
|
||||
await db.Settings.SetAsync(SettingScope.App, null, "count", 42, TestJson.Default.Int32, Ct);
|
||||
Assert.SequenceEqual(["count", "ui"], (await db.Settings.ListAsync(SettingScope.App, null, Ct)).Keys.Order(StringComparer.Ordinal));
|
||||
Assert.True(await db.Settings.DeleteAsync(SettingScope.App, null, "count", Ct));
|
||||
Assert.False(await db.Settings.DeleteAsync(SettingScope.App, null, "count", Ct));
|
||||
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => db.Settings.GetJsonAsync(SettingScope.User, null, "ui", Ct));
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => db.Settings.GetJsonAsync(SettingScope.App, user, "ui", Ct));
|
||||
await Assert.ThrowsAsync<JsonException>(() => db.Settings.SetJsonAsync(SettingScope.App, null, "bad", "{not json", Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AuditLogPagesNewestFirst()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var user = Guid.CreateVersion7();
|
||||
var entries = Enumerable.Range(0, 9).Select(i => new AuditEntry
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
At = TestData.Now.AddSeconds(i / 2),
|
||||
Action = "sequence.delete",
|
||||
UserId = i % 3 == 0 ? user : null,
|
||||
Username = "alice",
|
||||
TargetKind = "sequence",
|
||||
TargetId = Guid.CreateVersion7().ToString(),
|
||||
Details = "{\"frames\": 10}",
|
||||
RemoteAddress = "10.0.0.1",
|
||||
}).ToList();
|
||||
foreach (var e in entries) await db.Audit.AppendAsync(e, Ct);
|
||||
|
||||
var seen = new List<AuditEntry>();
|
||||
string? cursor = null;
|
||||
do
|
||||
{
|
||||
var page = await db.Audit.ListAsync(limit: 4, cursor: cursor, cancellationToken: Ct);
|
||||
seen.AddRange(page.Items);
|
||||
cursor = page.NextCursor;
|
||||
}
|
||||
while (cursor is not null);
|
||||
Assert.SequenceEqual(
|
||||
entries.OrderByDescending(e => e.At).ThenByDescending(e => e.Id.ToString("D"), StringComparer.Ordinal),
|
||||
seen);
|
||||
Assert.Equal(3, (await db.Audit.ListAsync(user, cancellationToken: Ct)).Items.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task UploadsTrackChunksAndStates()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var user = TestData.User();
|
||||
await db.Users.CreateAsync(user, Ct);
|
||||
var created = await db.Uploads.CreateAsync(Upload(user.Id, 8 * 1024 * 1024 * 9 + 1), Ct);
|
||||
Assert.Equal(10, created.ChunkCount);
|
||||
Assert.Equal(2, created.Received.Length);
|
||||
Assert.Equal(created.Id, (await db.Uploads.FindReceivingAsync(user.Id, created.Sha256.ToUpperInvariant(), Ct))!.Id);
|
||||
|
||||
foreach (var chunk in new[] { 0, 9, 3, 9 })
|
||||
{
|
||||
var updated = await db.Uploads.MarkChunkReceivedAsync(created.Id, chunk, Ct);
|
||||
Assert.True(updated!.HasChunk(chunk));
|
||||
}
|
||||
await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => db.Uploads.MarkChunkReceivedAsync(created.Id, 10, Ct));
|
||||
Assert.Null(await db.Uploads.MarkChunkReceivedAsync(Guid.CreateVersion7(), 0, Ct));
|
||||
|
||||
var stored = Assert.NotNull(await db.Uploads.GetAsync(created.Id, Ct));
|
||||
Assert.Equal(3, stored.ReceivedCount);
|
||||
Assert.SequenceEqual([0, 3, 9], Enumerable.Range(0, 10).Where(stored.HasChunk));
|
||||
Assert.False(stored.IsComplete);
|
||||
|
||||
await Task.WhenAll(Enumerable.Range(0, 10).Select(i => db.Uploads.MarkChunkReceivedAsync(created.Id, i, Ct)));
|
||||
Assert.True((await db.Uploads.GetAsync(created.Id, Ct))!.IsComplete);
|
||||
|
||||
Assert.Count(1, await db.Uploads.ListStaleAsync(TestData.Now.AddYears(10), Ct));
|
||||
var frameId = Guid.CreateVersion7();
|
||||
Assert.True(await db.Uploads.SetStateAsync(created.Id, UploadState.Committed, frameId, Ct));
|
||||
Assert.True(await db.Uploads.SetStateAsync(created.Id, UploadState.Committed, cancellationToken: Ct));
|
||||
var committed = await db.Uploads.GetAsync(created.Id, Ct);
|
||||
Assert.Equal((UploadState.Committed, (Guid?)frameId), (committed!.State, committed.FrameId));
|
||||
Assert.Empty(await db.Uploads.ListStaleAsync(TestData.Now.AddYears(10), Ct));
|
||||
Assert.Null(await db.Uploads.FindReceivingAsync(user.Id, created.Sha256, Ct));
|
||||
Assert.True(await db.Uploads.DeleteAsync(created.Id, Ct));
|
||||
}
|
||||
|
||||
private static SessionToken Token(Guid userId, string hash) => new()
|
||||
{
|
||||
TokenHash = hash,
|
||||
UserId = userId,
|
||||
ClientName = "Titano desktop",
|
||||
Created = TestData.Now,
|
||||
Expires = TestData.Now.AddDays(30),
|
||||
LastUsed = TestData.Now,
|
||||
};
|
||||
|
||||
private static RenderNode Node(Guid userId) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
UserId = userId,
|
||||
ClientName = "studio-pc",
|
||||
CapabilitiesJson = "{\"encoders\": []}",
|
||||
LastHeartbeat = TestData.Now,
|
||||
};
|
||||
|
||||
private static Upload Upload(Guid userId, long size) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
UserId = userId,
|
||||
FileName = "IMG_0001.CR3",
|
||||
Size = size,
|
||||
Sha256 = new string('A', 64),
|
||||
CapturedAt = new DateTime(2026, 9, 28, 18, 0, 0),
|
||||
ChunkSize = 8 * 1024 * 1024,
|
||||
Created = TestData.Now,
|
||||
UpdatedAt = TestData.Now,
|
||||
};
|
||||
}
|
||||
|
||||
public sealed record Preferences(string Language, int Columns, double[] Zoom)
|
||||
{
|
||||
public bool Equals(Preferences? other) =>
|
||||
other is not null && Language == other.Language && Columns == other.Columns && Zoom.SequenceEqual(other.Zoom);
|
||||
|
||||
public override int GetHashCode() => HashCode.Combine(Language, Columns);
|
||||
}
|
||||
|
||||
[JsonSerializable(typeof(Preferences))]
|
||||
[JsonSerializable(typeof(int))]
|
||||
internal sealed partial class TestJson : JsonSerializerContext;
|
||||
|
||||
public sealed class SqliteServerRepositoryTests(TestContext context) : ServerRepositoryTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.SqliteMemory;
|
||||
}
|
||||
|
||||
[RequiresEnvironment(PgTestServer.Variable)]
|
||||
public sealed class PostgresServerRepositoryTests(TestContext context) : ServerRepositoryTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
using System.Diagnostics;
|
||||
using Titano.Data.Tests.Infrastructure;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Data.Tests.Sessions;
|
||||
|
||||
/// <summary>Behaviour every <see cref="IDbSession"/> must share, run once per dialect.</summary>
|
||||
public abstract class SessionTests(TestContext context) : DatabaseTest(context)
|
||||
{
|
||||
private string AllTypesTable => ForDialect(
|
||||
"CREATE TABLE t (id INTEGER PRIMARY KEY, s TEXT, i INTEGER, l INTEGER, d REAL, b INTEGER, g TEXT, ts TEXT, ldt TEXT, bytes BLOB, j TEXT)",
|
||||
"CREATE TABLE t (id integer PRIMARY KEY, s text, i integer, l bigint, d double precision, b boolean, g uuid, ts timestamptz, ldt timestamp, bytes bytea, j jsonb)");
|
||||
|
||||
[Test]
|
||||
public async Task ParametersRoundTripEveryType()
|
||||
{
|
||||
await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct);
|
||||
await session.ExecuteScriptAsync(AllTypesTable, Ct);
|
||||
var guid = Guid.CreateVersion7();
|
||||
var instant = new DateTimeOffset(2026, 9, 28, 18, 30, 15, 123, TimeSpan.FromHours(2)).AddTicks(4560);
|
||||
var wallClock = new DateTime(2024, 2, 29, 23, 59, 58, 999).AddTicks(9990);
|
||||
byte[] bytes = [0, 1, 2, 0x7F, 0x80, 0xFE, 0xFF, (byte)'\\', (byte)'\t'];
|
||||
var text = "Città \"quoted\" 'single' \\ back\ttab\nnewline 🎞️ 時間";
|
||||
await session.ExecuteAsync(
|
||||
"INSERT INTO t (id, s, i, l, d, b, g, ts, ldt, bytes, j) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)",
|
||||
[1, text, int.MinValue, long.MaxValue, Math.PI, true, guid, instant, wallClock, bytes, DbParam.Json("{\"a\": [1, 2]}")],
|
||||
Ct);
|
||||
|
||||
var row = await session.QuerySingleAsync("SELECT s, i, l, d, b, g, ts, ldt, bytes, j FROM t WHERE id = $1", [1], Ct);
|
||||
Assert.Equal(text, row.GetString(0));
|
||||
Assert.Equal(int.MinValue, row.GetInt32(1));
|
||||
Assert.Equal(long.MaxValue, row.GetInt64(2));
|
||||
Assert.Equal(Math.PI, row.GetDouble(3));
|
||||
Assert.True(row.GetBool(4));
|
||||
Assert.Equal(guid, row.GetGuid(5));
|
||||
Assert.Equal(instant, row.GetDateTimeOffset(6));
|
||||
Assert.Equal(TimeSpan.Zero, row.GetDateTimeOffset(6).Offset);
|
||||
Assert.Equal(wallClock, row.GetDateTime(7));
|
||||
Assert.Equal(DateTimeKind.Unspecified, row.GetDateTime(7).Kind);
|
||||
Assert.BytesEqual(bytes, row.GetBytes(8));
|
||||
Assert.Equal("{\"a\": [1, 2]}", row.GetString(9));
|
||||
Assert.Equal(text, row.GetString("S"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TypedNullsRoundTrip()
|
||||
{
|
||||
await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct);
|
||||
await session.ExecuteScriptAsync(AllTypesTable, Ct);
|
||||
await session.ExecuteAsync(
|
||||
"INSERT INTO t (id, s, i, l, d, b, g, ts, ldt, bytes, j) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)",
|
||||
[1, (string?)null, (int?)null, (long?)null, (double?)null, (bool?)null, (Guid?)null, (DateTimeOffset?)null, (DateTime?)null, (byte[]?)null, DbParam.Json(null)],
|
||||
Ct);
|
||||
var row = await session.QuerySingleAsync("SELECT s, i, l, d, b, g, ts, ldt, bytes, j FROM t", [], Ct);
|
||||
for (var i = 0; i < row.FieldCount; i++) Assert.True(row.IsNull(i), $"column {row.GetName(i)} should be NULL");
|
||||
Assert.Null(row.GetGuidOrNull(5));
|
||||
Assert.Null(row.GetDateTimeOffsetOrNull(6));
|
||||
Assert.Throws<InvalidCastException>(() => row.GetInt32(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PlaceholdersBindByNumberNotByOrder()
|
||||
{
|
||||
await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct);
|
||||
var row = await session.QuerySingleAsync("SELECT $2 AS b, $1 AS a, $2 AS b2", [10, "x"], Ct);
|
||||
Assert.Equal("x", row.GetString("b"));
|
||||
Assert.Equal(10, row.GetInt32("a"));
|
||||
Assert.Equal("x", row.GetString(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ExecuteReportsChangedRowsOnly()
|
||||
{
|
||||
await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct);
|
||||
Assert.Equal(0, await session.ExecuteAsync("CREATE TABLE n (id integer PRIMARY KEY, v integer)", [], Ct));
|
||||
for (var i = 0; i < 5; i++) await session.ExecuteAsync("INSERT INTO n (id, v) VALUES ($1, $2)", [i, i % 2], Ct);
|
||||
Assert.Equal(3, await session.ExecuteAsync("UPDATE n SET v = 7 WHERE v = $1", [0], Ct));
|
||||
Assert.Equal(0, await session.ExecuteAsync("CREATE INDEX ix_n ON n (v)", [], Ct));
|
||||
Assert.Equal(2, await session.ExecuteAsync("DELETE FROM n WHERE v = $1", [1], Ct));
|
||||
Assert.Equal(3L, await session.ScalarAsync<long>("SELECT count(*) FROM n", [], Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TransactionsCommitRollBackAndRollBackOnDispose()
|
||||
{
|
||||
var database = await OpenDatabaseAsync();
|
||||
await using var session = await database.OpenAsync(Ct);
|
||||
await session.ExecuteScriptAsync("CREATE TABLE x (id integer PRIMARY KEY)", Ct);
|
||||
|
||||
await using (var tx = await session.BeginAsync(Ct))
|
||||
{
|
||||
Assert.True(session.InTransaction);
|
||||
await session.ExecuteAsync("INSERT INTO x (id) VALUES ($1)", [1], Ct);
|
||||
await tx.CommitAsync(Ct);
|
||||
}
|
||||
Assert.False(session.InTransaction);
|
||||
|
||||
await using (var tx = await session.BeginAsync(Ct))
|
||||
{
|
||||
await session.ExecuteAsync("INSERT INTO x (id) VALUES ($1)", [2], Ct);
|
||||
await tx.RollbackAsync(Ct);
|
||||
}
|
||||
await using (await session.BeginAsync(Ct))
|
||||
{
|
||||
await session.ExecuteAsync("INSERT INTO x (id) VALUES ($1)", [3], Ct);
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => session.BeginAsync(Ct));
|
||||
}
|
||||
|
||||
await using var other = await database.OpenAsync(Ct);
|
||||
Assert.Equal(1L, await other.ScalarAsync<long>("SELECT count(*) FROM x", [], Ct));
|
||||
Assert.Equal(1, await other.ScalarAsync<int>("SELECT max(id) FROM x", [], Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SessionDisposedInsideTransactionRollsBack()
|
||||
{
|
||||
var database = await OpenDatabaseAsync();
|
||||
await using (var setup = await database.OpenAsync(Ct))
|
||||
await setup.ExecuteScriptAsync("CREATE TABLE x (id integer PRIMARY KEY)", Ct);
|
||||
var session = await database.OpenAsync(Ct);
|
||||
await session.BeginAsync(Ct);
|
||||
await session.ExecuteAsync("INSERT INTO x (id) VALUES ($1)", [1], Ct);
|
||||
await session.DisposeAsync();
|
||||
|
||||
await using var check = await database.OpenAsync(Ct);
|
||||
Assert.Equal(0L, await check.ScalarAsync<long>("SELECT count(*) FROM x", [], Ct));
|
||||
await check.ExecuteAsync("INSERT INTO x (id) VALUES ($1)", [2], Ct);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ConstraintViolationsAreTyped()
|
||||
{
|
||||
await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct);
|
||||
await session.ExecuteScriptAsync(
|
||||
"CREATE TABLE p (id integer PRIMARY KEY, code text NOT NULL UNIQUE); " +
|
||||
"CREATE TABLE c (id integer PRIMARY KEY, p_id integer NOT NULL REFERENCES p(id))", Ct);
|
||||
await session.ExecuteAsync("INSERT INTO p (id, code) VALUES ($1, $2)", [1, "a"], Ct);
|
||||
|
||||
var unique = await Assert.ThrowsAsync<DatabaseException>(() => session.ExecuteAsync("INSERT INTO p (id, code) VALUES ($1, $2)", [2, "a"], Ct));
|
||||
Assert.True(unique.IsUniqueViolation);
|
||||
var primary = await Assert.ThrowsAsync<DatabaseException>(() => session.ExecuteAsync("INSERT INTO p (id, code) VALUES ($1, $2)", [1, "b"], Ct));
|
||||
Assert.True(primary.IsUniqueViolation);
|
||||
var foreign = await Assert.ThrowsAsync<DatabaseException>(() => session.ExecuteAsync("INSERT INTO c (id, p_id) VALUES ($1, $2)", [1, 99], Ct));
|
||||
Assert.True(foreign.IsForeignKeyViolation);
|
||||
|
||||
// The session stays usable after errors.
|
||||
Assert.Equal(1L, await session.ScalarAsync<long>("SELECT count(*) FROM p", [], Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task BulkInsertKeepsSpecialCharactersAndNulls()
|
||||
{
|
||||
await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct);
|
||||
await session.ExecuteScriptAsync(ForDialect(
|
||||
"CREATE TABLE b (id INTEGER PRIMARY KEY, s TEXT, bytes BLOB, ts TEXT, ldt TEXT, d REAL, g TEXT, f INTEGER)",
|
||||
"CREATE TABLE b (id integer PRIMARY KEY, s text, bytes bytea, ts timestamptz, ldt timestamp, d double precision, g uuid, f boolean)"), Ct);
|
||||
string?[] texts =
|
||||
[
|
||||
"tab\there", "new\nline", "carriage\rreturn", "back\\slash", "\\N", "", null, "unicode ✓ ñ 漢字 🎉",
|
||||
"mixed \\t\t\\n\n end\\", "trailing tab\t", "x",
|
||||
];
|
||||
var instant = new DateTimeOffset(2025, 1, 2, 3, 4, 5, TimeSpan.Zero);
|
||||
var rows = texts.Select((s, i) => new object?[]
|
||||
{
|
||||
i, s, i % 3 == 0 ? null : new byte[] { (byte)i, (byte)'\\', (byte)'\n', 0 }, instant.AddDays(i),
|
||||
new DateTime(2020, 1, 1).AddHours(i), i / 3.0, Guid.CreateVersion7(), i % 2 == 0,
|
||||
}).ToList();
|
||||
|
||||
var inserted = await session.BulkInsertAsync("b", ["id", "s", "bytes", "ts", "ldt", "d", "g", "f"], rows.ToAsyncEnumerable(), Ct);
|
||||
Assert.Equal(texts.Length, (int)inserted);
|
||||
|
||||
var read = await session.QueryListAsync("SELECT id, s, bytes, ts, ldt, d, g, f FROM b ORDER BY id", [], r => r, Ct);
|
||||
Assert.Equal(texts.Length, read.Count);
|
||||
for (var i = 0; i < texts.Length; i++)
|
||||
{
|
||||
var r = read[i];
|
||||
Assert.Equal(texts[i], r.GetStringOrNull(1), $"row {i}");
|
||||
if (rows[i][2] is byte[] expected) Assert.BytesEqual(expected, r.GetBytes(2));
|
||||
else Assert.True(r.IsNull(2));
|
||||
Assert.Equal(instant.AddDays(i), r.GetDateTimeOffset(3));
|
||||
Assert.Equal(new DateTime(2020, 1, 1).AddHours(i), r.GetDateTime(4));
|
||||
Assert.Equal(i / 3.0, r.GetDouble(5));
|
||||
Assert.Equal((Guid)rows[i][6]!, r.GetGuid(6));
|
||||
Assert.Equal(i % 2 == 0, r.GetBool(7));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task FailingBulkProducerLeavesTableUntouched()
|
||||
{
|
||||
await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct);
|
||||
await session.ExecuteScriptAsync("CREATE TABLE b (id integer PRIMARY KEY)", Ct);
|
||||
async IAsyncEnumerable<object?[]> Rows()
|
||||
{
|
||||
for (var i = 0; i < 1000; i++)
|
||||
{
|
||||
if (i == 700) throw new InvalidDataException("producer failed");
|
||||
yield return [i];
|
||||
await Task.Yield();
|
||||
}
|
||||
}
|
||||
await Assert.ThrowsAsync<InvalidDataException>(() => session.BulkInsertAsync("b", ["id"], Rows(), Ct));
|
||||
Assert.Equal(0L, await session.ScalarAsync<long>("SELECT count(*) FROM b", [], Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AbandonedQueryLeavesSessionUsable()
|
||||
{
|
||||
await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct);
|
||||
await session.ExecuteScriptAsync("CREATE TABLE q (id integer PRIMARY KEY)", Ct);
|
||||
await session.BulkInsertAsync("q", ["id"], Enumerable.Range(0, 2000).Select(i => new object?[] { i }).ToAsyncEnumerable(), Ct);
|
||||
await foreach (var row in session.QueryAsync("SELECT id FROM q ORDER BY id", [], Ct))
|
||||
{
|
||||
Assert.Equal(0, row.GetInt32(0));
|
||||
break;
|
||||
}
|
||||
Assert.Equal(1999, await session.ScalarAsync<int>("SELECT max(id) FROM q", [], Ct));
|
||||
Assert.Equal(2000L, await session.ScalarAsync<long>("SELECT count(*) FROM q", [], Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SingleRowHelpersEnforceCardinality()
|
||||
{
|
||||
await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct);
|
||||
await session.ExecuteScriptAsync("CREATE TABLE s (id integer PRIMARY KEY); INSERT INTO s (id) VALUES (1); INSERT INTO s (id) VALUES (2)", Ct);
|
||||
Assert.Null(await session.QuerySingleOrDefaultAsync("SELECT id FROM s WHERE id = $1", [9], Ct));
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => session.QuerySingleAsync("SELECT id FROM s WHERE id = $1", [9], Ct));
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => session.QuerySingleOrDefaultAsync("SELECT id FROM s", [], Ct));
|
||||
Assert.Equal(0, await session.ScalarAsync<int>("SELECT id FROM s WHERE id = $1", [9], Ct));
|
||||
Assert.Null(await session.ScalarAsync<int?>("SELECT id FROM s WHERE id = $1", [9], Ct));
|
||||
Assert.Equal("2", await session.ScalarAsync<string>("SELECT max(id) FROM s", [], Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CancellationStopsALongQueryQuickly()
|
||||
{
|
||||
var database = await OpenDatabaseAsync();
|
||||
await using var session = await database.OpenAsync(Ct);
|
||||
var sql = ForDialect(
|
||||
"WITH RECURSIVE r(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM r WHERE n < 2000000000) SELECT count(*) FROM r",
|
||||
"SELECT pg_sleep(10)");
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(Ct);
|
||||
cts.CancelAfter(300);
|
||||
var watch = Stopwatch.StartNew();
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => session.ExecuteAsync(sql, [], cts.Token));
|
||||
Assert.Less(watch.Elapsed.TotalSeconds, 2.0, "cancellation latency");
|
||||
Assert.Equal(1, await session.ScalarAsync<int>("SELECT 1", [], Ct));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SqliteSessionTests(TestContext context) : SessionTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.SqliteMemory;
|
||||
}
|
||||
|
||||
[RequiresEnvironment(PgTestServer.Variable)]
|
||||
public sealed class PostgresSessionTests(TestContext context) : SessionTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
using Titano.Data.Sqlite;
|
||||
using Titano.Data.Tests.Infrastructure;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.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 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 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(), "titano.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(), "titano.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));
|
||||
}
|
||||
Reference in new issue
Block a user