using System.Globalization;
namespace Khaemhat.Data.PostgreSql;
///
/// Yearly range partitioning for the large tables (SPEC ยง5.2: gl_entry_lines, inventory_entry_lines,
/// audit_log, sys_log). Prepared, not active: tables record their partition column with
/// TableBuilder.PartitionByYear; when one exceeds 50 million rows a migration (through
/// ISchemaBuilder.Sql) recreates it partitioned using these statements and moves the rows.
///
public static class PostgresPartitioning
{
/// The clause that makes a CREATE TABLE partitioned by range of .
/// The date or timestamp column.
/// The clause, starting with a space.
public static string PartitionClause(string column) => " PARTITION BY RANGE (" + PostgresDialect.Instance.Quote(column) + ")";
/// The name of the partition of a year, for example gl_entry_lines_2026.
/// The partitioned table.
/// The year.
/// The partition name.
public static string PartitionName(string table, int year) => table + "_" + year.ToString(CultureInfo.InvariantCulture);
/// The statement creating the partition of one year if it does not exist.
/// The partitioned table.
/// The year.
/// The statement.
public static string CreateYearPartition(string table, int year)
{
ArgumentOutOfRangeException.ThrowIfLessThan(year, 1900);
ArgumentOutOfRangeException.ThrowIfGreaterThan(year, 9998);
var dialect = PostgresDialect.Instance;
return string.Create(
CultureInfo.InvariantCulture,
$"CREATE TABLE IF NOT EXISTS {dialect.Quote(PartitionName(table, year))} PARTITION OF {dialect.Quote(table)} FOR VALUES FROM ('{year:D4}-01-01') TO ('{year + 1:D4}-01-01')");
}
/// The statement creating the default partition, for rows outside the yearly ones.
/// The partitioned table.
/// The statement.
public static string CreateDefaultPartition(string table)
{
var dialect = PostgresDialect.Instance;
return $"CREATE TABLE IF NOT EXISTS {dialect.Quote(table + "_default")} PARTITION OF {dialect.Quote(table)} DEFAULT";
}
}