Path: redb/redb.Export/Flat/FlatDdlGenerator.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Export/Flat/FlatDdlGenerator.cs ---- using System.Text; using redb.Export.Flat.Dialects; using redb.Export.Flat.Model; namespace redb.Export.Flat; /// /// Turns a into DDL for one provider. /// /// Tables are created with plain CREATE TABLE - never IF NOT EXISTS - so a name that /// is already taken fails loudly instead of two classes sharing one table. Where the provider /// allows it, foreign keys are separate statements meant to run after the data is loaded. /// /// public sealed class FlatDdlGenerator { private readonly IFlatDialect _dialect; /// Creates a generator for a provider. /// Provider name as reported by IDataProvider.Name: postgres, mssql or sqlite. public FlatDdlGenerator(string providerName) : this(FlatDialects.For(providerName)) { } internal FlatDdlGenerator(IFlatDialect dialect) { _dialect = dialect; } /// The CREATE TABLE statement of . public string CreateTable(FlatTable table) { var lines = new List(); // Every key a writer may leave out comes from the one sequence. A scheme table is the exception: // its key is the id of the header row in `objects`, set by whoever writes that row. var keyDefault = table.Kind == FlatTableKind.Scheme ? null : _dialect.KeyDefault(FlatNaming.IdentitySequence); foreach (var column in table.Columns) { var type = _dialect.ColumnType(FlatStorageTypes.Of(column)); var line = $"{_dialect.Quote(column.Name)} {type} {(column.IsNullable ? "NULL" : "NOT NULL")}"; if (keyDefault != null && column.Role == FlatColumnRole.PrimaryKey) line += " " + keyDefault; lines.Add(line); } lines.Add($"CONSTRAINT {_dialect.Quote(table.PrimaryKeyName)} PRIMARY KEY ({_dialect.Quote(table.PrimaryKey)})"); foreach (var unique in table.UniqueConstraints) lines.Add($"CONSTRAINT {_dialect.Quote(unique.Name)} UNIQUE ({string.Join(", ", unique.Columns.Select(_dialect.Quote))})"); if (_dialect.InlineForeignKeys) { foreach (var foreignKey in table.ForeignKeys) lines.Add($"CONSTRAINT {_dialect.Quote(foreignKey.Name)} {ForeignKeyClause(table, foreignKey)}"); } var sql = new StringBuilder(); sql.Append("CREATE TABLE ").Append(_dialect.Quote(table.Name)).AppendLine(" ("); sql.AppendLine(" " + string.Join("," + Environment.NewLine + " ", lines)); sql.Append(')'); return sql.ToString(); } /// /// The statements that create the plain indexes of (the foreign key indexes). /// Meant to run after the data is loaded, on every provider. /// public IReadOnlyList CreateIndexes(FlatTable table) => table.Indexes .Select(index => $"CREATE INDEX {_dialect.Quote(index.Name)} ON {_dialect.Quote(table.Name)} ({string.Join(", ", index.Columns.Select(_dialect.Quote))})") .ToList(); /// /// The statements that add the foreign keys of . Empty for a provider /// that declares them inside CREATE TABLE. /// public IReadOnlyList AddForeignKeys(FlatTable table) { if (_dialect.InlineForeignKeys) return []; return table.ForeignKeys .Select(foreignKey => $"ALTER TABLE {_dialect.Quote(table.Name)} ADD CONSTRAINT {_dialect.Quote(foreignKey.Name)} {ForeignKeyClause(table, foreignKey)}") .ToList(); } /// /// The statement that creates the key sequence (), starting at 1. /// Null for a provider without sequences, which generates such keys per table by itself. /// public string? CreateSequence() => _dialect.CreateSequence(FlatNaming.IdentitySequence); /// /// The statement that makes the key sequence hand out next: run after the /// data is copied, with a value above every copied key. Null for a provider without sequences. /// public string? RestartSequence(long next) => _dialect.RestartSequence(FlatNaming.IdentitySequence, next); /// /// The whole model as one script: the key sequence, every table, then every foreign key. Run on an /// empty database it gives the flat schema without data, with keys generated by the database. The /// last statement makes the client print what was created, so a run that reached the end says so. /// public string Script(FlatDatabaseModel model) { var sequence = CreateSequence(); var foreignKeys = model.Tables.Sum(table => table.ForeignKeys.Count); var indexes = model.Tables.Sum(table => table.Indexes.Count); var summary = $"redb flat schema created: {model.Tables.Count} tables, {foreignKeys} foreign keys, {indexes} indexes, " + (sequence == null ? "keys generated per table" : $"key sequence {FlatNaming.IdentitySequence}"); var statements = (sequence == null ? Array.Empty() : new[] { sequence }) .Concat(model.Tables.Select(table => CreateTable(table))) .Concat(model.Tables.SelectMany(table => AddForeignKeys(table))) .Concat(model.Tables.SelectMany(table => CreateIndexes(table))) .Append(_dialect.Report(summary)); var header = $"-- redb flat schema: {model.Tables.Count} tables, {foreignKeys} foreign keys, {indexes} indexes. Run on an empty database."; return header + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine + Environment.NewLine, statements.Select(s => s + ";")); } private string ForeignKeyClause(FlatTable table, FlatForeignKey foreignKey) { var rule = foreignKey.OnDelete; // A provider that refuses a cascade from a table to itself gets the key without it; deleting a // parent object there means deleting its children first, as with redb on that provider. if (rule == FlatDeleteRule.Cascade && foreignKey.TargetTable == table.Name && !_dialect.AllowsSelfCascade) rule = FlatDeleteRule.NoAction; var onDelete = rule switch { FlatDeleteRule.Cascade => " ON DELETE CASCADE", FlatDeleteRule.SetNull => " ON DELETE SET NULL", _ => "" }; return $"FOREIGN KEY ({_dialect.Quote(foreignKey.Column)}) " + $"REFERENCES {_dialect.Quote(foreignKey.TargetTable)} ({_dialect.Quote(foreignKey.TargetColumn)}){onDelete}"; } }