using System.Text;
namespace Titano.Data;
///
/// The few SQL fragments that differ between SQLite (≥ 3.31) and PostgreSQL. Everything else in the
/// repositories is plain SQL that both accept: $n placeholders, ON CONFLICT … DO UPDATE,
/// TRUE/FALSE, NULLS LAST, LIKE … ESCAPE.
///
public sealed class SqlDialect
{
/// Separator of lists (ASCII unit separator, never part of a tag).
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;
/// Row lock for read-modify-write inside a transaction; empty on SQLite, whose BEGIN IMMEDIATE already holds the write lock.
public string ForUpdate => IsPostgres ? " FOR UPDATE" : string.Empty;
/// Like , but rows another transaction has locked are skipped instead of awaited.
public string ForUpdateSkipLocked => IsPostgres ? " FOR UPDATE SKIP LOCKED" : string.Empty;
/// Calendar year of a timestamp column (SQLite stores ISO-8601 text).
public string Year(string expression) => IsPostgres
? $"CAST(EXTRACT(YEAR FROM {expression}) AS integer)"
: $"CAST(substr({expression}, 1, 4) AS INTEGER)";
/// Month (1–12) of a timestamp column.
public string Month(string expression) => IsPostgres
? $"CAST(EXTRACT(MONTH FROM {expression}) AS integer)"
: $"CAST(substr({expression}, 6, 2) AS INTEGER)";
/// Aggregate that joins the group's values with (order unspecified).
public string StringAgg(string expression) => IsPostgres
? $"string_agg({expression}, chr(31))"
: $"group_concat({expression}, char(31))";
///
/// INSERT … VALUES ($1…$n) ON CONFLICT (keys) DO UPDATE SET …; the first
/// columns form the conflict target and columns keep their stored value on
/// conflict. The syntax is shared by SQLite ≥ 3.24 and PostgreSQL ≥ 9.5.
///
public static string Upsert(string table, IReadOnlyList columns, int keyCount, IReadOnlyCollection? 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();
}
/// Double-quotes an identifier (both dialects).
public static string QuoteIdentifier(string name) => "\"" + name.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"";
/// A LIKE … ESCAPE '\' pattern that matches anywhere.
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();
}
}