Files
Chronos/src/Titano.Data/SqlDialect.cs
T
Claude fb42423346 fix(data): close concurrency and cleanup gaps found in review
- SQLite restore holds every pool slot instead of the write lock first,
  removing a lock-order deadlock with sessions that begin to write.
- PostgreSQL sessions always return their connection on dispose, a
  rollback while disposing never masks the original exception, and a
  busy session keeps its transaction until it is discarded.
- The pool disposes a connection whose health check the caller cancels.
- Listener commands keep their lock until the server answers and never
  tear a write with the caller's token; closing and pending no longer race.
- Tag replacement locks the sequence and the tag row; unused-tag cleanup
  locks candidates and re-checks them with a fresh snapshot; render
  counts and stats refreshes lock the sequence row on PostgreSQL.
- Sequence upserts keep rendered_count, which renders maintain.
- AuthenticationOk after an unfinished SCRAM exchange is rejected.
- Oversized read buffers are released; failed backups leave no .tmp;
  a zero idle lifetime is rejected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-02 10:27:19 +00:00

80 lines
4.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Text;
namespace Titano.Data;
/// <summary>
/// The few SQL fragments that differ between SQLite (≥ 3.31) and PostgreSQL. Everything else in the
/// repositories is plain SQL that both accept: <c>$n</c> placeholders, <c>ON CONFLICT … DO UPDATE</c>,
/// <c>TRUE</c>/<c>FALSE</c>, <c>NULLS LAST</c>, <c>LIKE … ESCAPE</c>.
/// </summary>
public sealed class SqlDialect
{
/// <summary>Separator of <see cref="StringAgg"/> lists (ASCII unit separator, never part of a tag).</summary>
public const char ListSeparator = '\u001f';
private SqlDialect(Dialect dialect) => Dialect = dialect;
public static SqlDialect Sqlite { get; } = new(Dialect.Sqlite);
public static SqlDialect Postgres { get; } = new(Dialect.Postgres);
public Dialect Dialect { get; }
public bool IsPostgres => Dialect == Dialect.Postgres;
public static SqlDialect For(Dialect dialect) => dialect == Dialect.Postgres ? Postgres : Sqlite;
/// <summary>Row lock for read-modify-write inside a transaction; empty on SQLite, whose <c>BEGIN IMMEDIATE</c> already holds the write lock.</summary>
public string ForUpdate => IsPostgres ? " FOR UPDATE" : string.Empty;
/// <summary>Like <see cref="ForUpdate"/>, but rows another transaction has locked are skipped instead of awaited.</summary>
public string ForUpdateSkipLocked => IsPostgres ? " FOR UPDATE SKIP LOCKED" : string.Empty;
/// <summary>Calendar year of a timestamp column (SQLite stores ISO-8601 text).</summary>
public string Year(string expression) => IsPostgres
? $"CAST(EXTRACT(YEAR FROM {expression}) AS integer)"
: $"CAST(substr({expression}, 1, 4) AS INTEGER)";
/// <summary>Month (1–12) of a timestamp column.</summary>
public string Month(string expression) => IsPostgres
? $"CAST(EXTRACT(MONTH FROM {expression}) AS integer)"
: $"CAST(substr({expression}, 6, 2) AS INTEGER)";
/// <summary>Aggregate that joins the group's values with <see cref="ListSeparator"/> (order unspecified).</summary>
public string StringAgg(string expression) => IsPostgres
? $"string_agg({expression}, chr(31))"
: $"group_concat({expression}, char(31))";
/// <summary>
/// <c>INSERT … VALUES ($1…$n) ON CONFLICT (keys) DO UPDATE SET …</c>; the first <paramref name="keyCount"/>
/// columns form the conflict target and <paramref name="insertOnly"/> columns keep their stored value on
/// conflict. The syntax is shared by SQLite ≥ 3.24 and PostgreSQL ≥ 9.5.
/// </summary>
public static string Upsert(string table, IReadOnlyList<string> columns, int keyCount, IReadOnlyCollection<string>? insertOnly = null)
{
ArgumentOutOfRangeException.ThrowIfLessThan(keyCount, 1);
ArgumentOutOfRangeException.ThrowIfGreaterThan(keyCount, columns.Count);
var sb = new StringBuilder("INSERT INTO ").Append(table).Append(" (").AppendJoin(", ", columns).Append(") VALUES (");
for (var i = 1; i <= columns.Count; i++) sb.Append(i > 1 ? ", $" : "$").Append(i);
sb.Append(") ON CONFLICT (").AppendJoin(", ", columns.Take(keyCount)).Append(')');
var updated = columns.Skip(keyCount).Where(c => insertOnly is null || !insertOnly.Contains(c)).ToList();
if (updated.Count == 0) return sb.Append(" DO NOTHING").ToString();
return sb.Append(" DO UPDATE SET ").AppendJoin(", ", updated.Select(c => $"{c} = excluded.{c}")).ToString();
}
/// <summary>Double-quotes an identifier (both dialects).</summary>
public static string QuoteIdentifier(string name) => "\"" + name.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"";
/// <summary>A <c>LIKE … ESCAPE '\'</c> pattern that matches <paramref name="text"/> anywhere.</summary>
public static string ContainsPattern(string text)
{
var sb = new StringBuilder(text.Length + 2).Append('%');
foreach (var c in text)
{
if (c is '%' or '_' or '\\') sb.Append('\\');
sb.Append(c);
}
return sb.Append('%').ToString();
}
}