private string GetTableConstraints(IDbTableBinding table) { var str = new StringBuilder(); if (table.PrimaryKey != null) { var columnsList = table.AggregateText(table.PrimaryKey, ", ", c => c.GetSqlColumnName()); // [CONSTRAINT [symbol]] PRIMARY KEY [index_type] (key_part,...) [index_option] ... str.Append(",\n"); str.Append($"{ConstraintKey} {PrimaryKeyKey} ( {columnsList} )"); } if (table.ForeignKeys.Count > 0) { table.CheckConstraints(); foreach (var fk in table.ForeignKeys) { var columnsName = table.AggregateText(fk, "_", c => c.ColumnName); var columnsList = table.AggregateText(fk, ", ", c => c.GetSqlColumnName()); var pkBinding = Setup.GetTableBinding(fk.PrimaryTableTemplate); var primaryList = pkBinding.AggregateText(DbColumnsSelection.PrimaryKey, ", ", c => c.GetSqlColumnName()); // [CONSTRAINT [symbol]] FOREIGN KEY [index_name] (col_name,...) // REFERENCES tbl_name (key_part,...) [MATCH FULL | MATCH PARTIAL | MATCH SIMPLE] [ON DELETE reference_option] [ON UPDATE reference_option] var name = fk.DbName ?? $"fk_{TableName}_{columnsName}"; str.Append(",\n"); str.Append($"{ConstraintKey} {name} {ForeignKeyKey} ( {columnsList} ) "); str.Append($"{ReferecencesKey} {pkBinding.GetSqlTableName()} ( {primaryList} ) ON DELETE NO ACTION ON UPDATE NO ACTION"); // {INDEX|KEY} [index_name] [index_type] (key_part,...) [index_option] ... str.Append(",\n"); str.Append($"{KeyKey} fk_{TableName}_{columnsName}_idx ( {columnsList} )"); } } if (table.UniqueKeys.Count > 0) { foreach (var uk in table.UniqueKeys) { var columnsName = table.AggregateText(uk, "_", c => c.ColumnName); var columnsList = table.AggregateText(uk, ", ", c => c.GetSqlColumnName()); // [CONSTRAINT [symbol]] UNIQUE [INDEX|KEY] [index_name] [index_type] (key_part,...) [index_option] ... var name = uk.DbName ?? $"uk_{TableName}_{columnsName}_idx"; str.Append(",\n"); str.Append($"{ConstraintKey} {UniqueKeyKey} {name} ( {columnsList} )"); } } if (table.Indexes.Count > 0) { foreach (var idx in table.Indexes) { var columnsName = table.AggregateText(idx, "_", c => c.ColumnName); var columnsList = table.AggregateText(idx, ", ", c => c.GetSqlColumnName()); // {INDEX|KEY} [index_name] [index_type] (key_part,...) [index_option] ... var name = idx.DbName ?? $"{TableName}_{columnsName}_idx"; str.Append(",\n"); str.Append($"{IndexKey} {name} ( {columnsList} )"); } } return(str.ToString()); }
/// <summary> /// Get a list from a columns selection. /// </summary> protected string GetColumnsText(DbColumnsSelection selection, string separator, Func <IDbColumnBinding, string> action) { return(Binding.AggregateText(selection, separator, action)); }
/// <summary> /// Get the list of columns defined in a key. /// </summary> public static string AggregateText(this IDbTableBinding binding, IDbTableKeyAttribute key, string separator, Func <IDbColumnBinding, string> action) { return(binding.AggregateText(key.PropertyNames, separator, action)); }