示例#1
0
 public static void ExecuteLeaves(this SqlPreCommand preCommand, CommandType commandType = CommandType.Text)
 {
     foreach (var simple in preCommand.Leaves())
     {
         simple.ExecuteNonQuery(commandType);
     }
 }
示例#2
0
        public static SqlPreCommand?SnapshotIsolation()
        {
            if (!Connector.Current.AllowsSetSnapshotIsolation)
            {
                return(null);
            }


            var list = Schema.Current.DatabaseNames().Select(a => a?.ToString()).ToList();

            if (list.Contains(null))
            {
                list.Remove(null);
                list.Add(Connector.Current.DatabaseName());
            }

            var cmd = list.NotNull()
                      .Where(db => !SnapshotIsolationEnabled(db))
                      .Select(db => SqlPreCommand.Combine(Spacing.Simple,
                                                          SqlBuilder.SetSingleUser(db),
                                                          SqlBuilder.SetSnapshotIsolation(db, true),
                                                          SqlBuilder.MakeSnapshotIsolationDefault(db, true),
                                                          SqlBuilder.SetMultiUser(db))
                              ).Combine(Spacing.Double);

            return(cmd);
        }
示例#3
0
        private static SqlPreCommand AlterTableAddColumnDefault(ITable table, IColumn column, Replacements rep)
        {
            bool temporalDefault = !column.Nullable && !column.Identity && column.Default == null;

            if (!temporalDefault)
            {
                return(SqlBuilder.AlterTableAddColumn(table, column));
            }

            try
            {
                var defaultValue = GetDefaultValue(table, column, rep);
                if (defaultValue == "force")
                {
                    return(SqlBuilder.AlterTableAddColumn(table, column));
                }

                column.Default = defaultValue;

                return(SqlPreCommand.Combine(Spacing.Simple,
                                             SqlBuilder.AlterTableAddColumn(table, column),
                                             SqlBuilder.DropDefaultConstraint(table.Name, column.Name)));
            }
            finally
            {
                column.Default = null;
            }
        }
示例#4
0
        public static void OpenSqlFileRetry(this SqlPreCommand command)
        {
            SafeConsole.WriteLineColor(ConsoleColor.Yellow, "There are changes!");
            var fileName = "Sync {0:dd-MM-yyyy HH_mm_ss}.sql".FormatWith(DateTime.Now);

            Save(command, fileName);
            SafeConsole.WriteLineColor(ConsoleColor.DarkYellow, command.PlainSql());

            Console.WriteLine("Script saved in:  " + Path.Combine(Directory.GetCurrentDirectory(), fileName));
            var answer = SafeConsole.AskRetry("Open or run?", "open", "run", "exit");

            if (answer == "open")
            {
                Thread.Sleep(1000);
                Open(fileName);
                if (SafeConsole.Ask("run now?"))
                {
                    ExecuteRetry(fileName);
                }
            }
            else if (answer == "run")
            {
                ExecuteRetry(fileName);
            }
        }
示例#5
0
        public static SqlPreCommand SnapshotIsolation(Replacements replacements)
        {
            if (replacements.SchemaOnly)
            {
                return(null);
            }

            var list = Schema.Current.DatabaseNames().Select(a => a?.ToString()).ToList();

            if (list.Contains(null))
            {
                list.Remove(null);
                list.Add(Connector.Current.DatabaseName());
            }

            var results = Database.View <SysDatabases>()
                          .Where(d => list.Contains(d.name))
                          .Select(d => new { d.name, d.snapshot_isolation_state, d.is_read_committed_snapshot_on }).ToList();

            var cmd = replacements.WithReplacedDatabaseName().Using(_ => results.Select((a, i) =>
                                                                                        SqlPreCommand.Combine(Spacing.Simple,
                                                                                                              !a.snapshot_isolation_state || !a.is_read_committed_snapshot_on ? DisconnectUsers(a.name, "SPID" + i) : null,
                                                                                                              !a.snapshot_isolation_state ? SqlBuilder.SetSnapshotIsolation(a.name, true) : null,
                                                                                                              !a.is_read_committed_snapshot_on ? SqlBuilder.MakeSnapshotIsolationDefault(a.name, true) : null)).Combine(Spacing.Double));

            if (cmd == null)
            {
                return(null);
            }

            return(SqlPreCommand.Combine(Spacing.Double,
                                         new SqlPreCommandSimple("use master -- Start Snapshot"),
                                         cmd,
                                         new SqlPreCommandSimple("use {0} -- Stop Snapshot".FormatWith(Connector.Current.DatabaseName()))));
        }
示例#6
0
        public static SqlPreCommand SnapshotIsolation()
        {
            if (!Connector.Current.AllowsSetSnapshotIsolation)
            {
                return(null);
            }

            var list = Schema.Current.DatabaseNames().Select(a => a?.ToString()).ToList();

            if (list.Contains(null))
            {
                list.Remove(null);
                list.Add(Connector.Current.DatabaseName());
            }

            var cmd = list.Select(a =>
                                  SqlPreCommand.Combine(Spacing.Simple,
                                                        //DisconnectUsers(a.name, "SPID" + i) : null,
                                                        SqlBuilder.SetSingleUser(a),
                                                        SqlBuilder.SetSnapshotIsolation(a, true),
                                                        SqlBuilder.MakeSnapshotIsolationDefault(a, true),
                                                        SqlBuilder.SetMultiUser(a))
                                  ).Combine(Spacing.Double);

            return(cmd);
        }
示例#7
0
        public static SqlPreCommand CreateIndex(Index index)
        {
            string columns = index.Columns.ToString(c => c.Name.SqlEscape(), ", ");

            if (index is PrimaryClusteredIndex)
            {
                return(new SqlPreCommandSimple("ALTER TABLE {0} ADD CONSTRAINT {1} PRIMARY KEY CLUSTERED({2})".FormatWith(
                                                   index.Table.Name,
                                                   index.IndexName,
                                                   columns)));
            }

            if (index is UniqueIndex uIndex && uIndex.ViewName != null)
            {
                ObjectName viewName = new ObjectName(uIndex.Table.Name.Schema, uIndex.ViewName);

                SqlPreCommandSimple viewSql = new SqlPreCommandSimple(@"CREATE VIEW {0} WITH SCHEMABINDING AS SELECT {1} FROM {2} WHERE {3}"
                                                                      .FormatWith(viewName, columns, uIndex.Table.Name.ToString(), uIndex.Where))
                {
                    GoBefore = true, GoAfter = true
                };

                SqlPreCommandSimple indexSql = new SqlPreCommandSimple(@"CREATE UNIQUE CLUSTERED INDEX {0} ON {1}({2})"
                                                                       .FormatWith(uIndex.IndexName, viewName, uIndex.Columns.ToString(c => c.Name.SqlEscape(), ", ")));

                return(SqlPreCommand.Combine(Spacing.Simple, viewSql, indexSql));
            }
示例#8
0
        public static SqlPreCommand?CreateTablesScript()
        {
            var           sqlBuilder = Connector.Current.SqlBuilder;
            Schema        s          = Schema.Current;
            List <ITable> tables     = s.GetDatabaseTables().Where(t => !s.IsExternalDatabase(t.Name.Schema.Database)).ToList();

            SqlPreCommand?createTables = tables.Select(t => sqlBuilder.CreateTableSql(t)).Combine(Spacing.Double)?.PlainSqlCommand();

            SqlPreCommand?foreignKeys = tables.Select(sqlBuilder.AlterTableForeignKeys).Combine(Spacing.Double)?.PlainSqlCommand();

            SqlPreCommand?indices = tables.Select(t =>
            {
                var allIndexes = t.GeneratAllIndexes().Where(a => !(a is PrimaryKeyIndex));;

                var mainIndices = allIndexes.Select(ix => sqlBuilder.CreateIndex(ix, checkUnique: null)).Combine(Spacing.Simple);

                var historyIndices = t.SystemVersioned == null ? null :
                                     allIndexes.Where(a => a.GetType() == typeof(TableIndex)).Select(mix => sqlBuilder.CreateIndexBasic(mix, forHistoryTable: true)).Combine(Spacing.Simple);

                return(SqlPreCommand.Combine(Spacing.Double, mainIndices, historyIndices));
            }).NotNull().Combine(Spacing.Double)?.PlainSqlCommand();


            return(SqlPreCommand.Combine(Spacing.Triple, createTables, foreignKeys, indices));
        }
示例#9
0
        public static SqlPreCommand?SnapshotIsolation()
        {
            var connector = Connector.Current;

            if (!connector.AllowsSetSnapshotIsolation)
            {
                return(null);
            }


            var list = connector.Schema.DatabaseNames().Select(a => a?.ToString()).ToList();

            if (list.Contains(null))
            {
                list.Remove(null);
                list.Add(connector.DatabaseName());
            }

            var sqlBuilder = connector.SqlBuilder;

            var cmd = list.NotNull()
                      .Select(dbn => new DatabaseName(null, dbn, connector.Schema.Settings.IsPostgres))
                      .Where(db => !SnapshotIsolationEnabled(db))
                      .Select(db => SqlPreCommand.Combine(Spacing.Simple,
                                                          sqlBuilder.SetSingleUser(db),
                                                          sqlBuilder.SetSnapshotIsolation(db, true),
                                                          sqlBuilder.MakeSnapshotIsolationDefault(db, true),
                                                          sqlBuilder.SetMultiUser(db))
                              ).Combine(Spacing.Double);

            return(cmd);
        }
示例#10
0
        public static void OpenSqlFileRetry(this SqlPreCommand command)
        {
            SafeConsole.WriteLineColor(ConsoleColor.Yellow, "There are changes!");
            string file = command.OpenSqlFile();

            if (!AvoidOpenOpenSqlFileRetry && SafeConsole.Ask("Open again?"))
            {
                Process.Start(file);
            }
        }
示例#11
0
        public static string OpenSqlFile(this SqlPreCommand command, string fileName)
        {
            Save(command, fileName);

            Thread.Sleep(1000);

            Process.Start(fileName);

            return(fileName);
        }
示例#12
0
        public static SqlPreCommand PlainSqlCommand(this SqlPreCommand command)
        {
            if (command == null)
            {
                return(null);
            }

            return(command.PlainSql().SplitNoEmpty("GO\r\n")
                   .Select(s => new SqlPreCommandSimple(s))
                   .Combine(Spacing.Simple));
        }
示例#13
0
        public static SqlPreCommand RenameOrMove(DiffTable oldTable, ITable newTable)
        {
            if (object.Equals(oldTable.Name.Schema.Database, newTable.Name.Schema.Database))
            {
                return(RenameOrChangeSchema(oldTable.Name, newTable.Name));
            }

            return(SqlPreCommand.Combine(Spacing.Simple,
                                         CreateTableSql(newTable),
                                         MoveRows(oldTable.Name, newTable.Name, newTable.Columns.Keys),
                                         DropTable(oldTable)) !);
        }
示例#14
0
        public static SqlPreCommand RemoveAllScript(DatabaseName databaseName)
        {
            var schemas = SqlBuilder.SystemSchemas.ToString(a => "'" + a + "'", ", ");

            return(SqlPreCommand.Combine(Spacing.Double,
                                         new SqlPreCommandSimple(Use(databaseName, RemoveAllProceduresScript)),
                                         new SqlPreCommandSimple(Use(databaseName, RemoveAllViewsScript)),
                                         new SqlPreCommandSimple(Use(databaseName, RemoveAllConstraintsScript)),
                                         new SqlPreCommandSimple(Use(databaseName, RemoveAllTablesScript)),
                                         new SqlPreCommandSimple(Use(databaseName, RemoveAllSchemasScript.FormatWith(schemas)))
                                         ));
        }
示例#15
0
        public static SqlPreCommand CreateTablesScript()
        {
            List <ITable> tables = Schema.Current.GetDatabaseTables().ToList();

            SqlPreCommand createTables = tables.Select(SqlBuilder.CreateTableSql).Combine(Spacing.Double).PlainSqlCommand();

            SqlPreCommand foreignKeys = tables.Select(SqlBuilder.AlterTableForeignKeys).Combine(Spacing.Double).PlainSqlCommand();

            SqlPreCommand indices = tables.Select(SqlBuilder.CreateAllIndices).NotNull().Combine(Spacing.Double).PlainSqlCommand();

            return(SqlPreCommand.Combine(Spacing.Triple, createTables, foreignKeys, indices));
        }
示例#16
0
        public static SqlPreCommand RemoveAllScript(DatabaseName databaseName)
        {
            var schemas = SqlBuilder.SystemSchemas.ToString(a => "'" + a + "'", ", ");

            return(SqlPreCommand.Combine(Spacing.Double,
                                         new SqlPreCommandSimple(Use(databaseName, RemoveAllProceduresScript)),
                                         new SqlPreCommandSimple(Use(databaseName, RemoveAllViewsScript)),
                                         new SqlPreCommandSimple(Use(databaseName, RemoveAllConstraintsScript)),
                                         Connector.Current.SupportsTemporalTables ? new SqlPreCommandSimple(Use(databaseName, StopSystemVersioning)) : null,
                                         new SqlPreCommandSimple(Use(databaseName, RemoveAllTablesScript)),
                                         new SqlPreCommandSimple(Use(databaseName, RemoveAllSchemasScript.FormatWith(schemas)))
                                         ));
        }
示例#17
0
        public static SqlPreCommand?RemoveDuplicatedIndices()
        {
            var isPostgres = Schema.Current.Settings.IsPostgres;
            var sqlBuilder = Connector.Current.SqlBuilder;
            var plainData  = (from s in Database.View <SysSchemas>()
                              from t in s.Tables()
                              from ix in t.Indices()
                              from ic in ix.IndexColumns()
                              from c in t.Columns()
                              where ic.column_id == c.column_id
                              select new
            {
                table = new ObjectName(new SchemaName(null, s.name, isPostgres), t.name, isPostgres),
                index = ix.name,
                ix.is_unique,
                column = c.name,
                ic.is_descending_key,
                ic.is_included_column,
                ic.index_column_id
            }).ToList();

            var tables = plainData.AgGroupToDictionary(a => a.table,
                                                       gr => gr.AgGroupToDictionary(a => new { a.index, a.is_unique },
                                                                                    gr2 => gr2.OrderBy(a => a.index_column_id)
                                                                                    .Select(a => a.column + (a.is_included_column ? "(K)" : "(I)") + (a.is_descending_key ? "(D)" : "(A)"))
                                                                                    .ToString("|")));

            var result = tables.SelectMany(t =>
                                           t.Value.GroupBy(a => a.Value, a => a.Key)
                                           .Where(gr => gr.Count() > 1)
                                           .Select(gr =>
            {
                var best = gr.OrderByDescending(a => a.is_unique).ThenByDescending(a => a.index !/*CSBUG*/.StartsWith("IX")).ThenByDescending(a => a.index).First();

                return(gr.Where(g => g != best)
                       .Select(g => sqlBuilder.DropIndex(t.Key !, g.index !))
                       .PreAnd(new SqlPreCommandSimple("-- DUPLICATIONS OF {0}".FormatWith(best.index))).Combine(Spacing.Simple));
            })
                                           ).Combine(Spacing.Double);

            if (result == null)
            {
                return(null);
            }

            return(SqlPreCommand.Combine(Spacing.Double,
                                         new SqlPreCommandSimple("use {0}".FormatWith(Connector.Current.DatabaseName())),
                                         result));
        }
示例#18
0
        public static SqlPreCommand CreateIndex(Index index)
        {
            string columns = index.Columns.ToString(c => c.Name.SqlEscape(), ", ");

            if (!(index is UniqueIndex))
            {
                return(new SqlPreCommandSimple("CREATE INDEX {0} ON {1}({2})".FormatWith(
                                                   index.IndexName,
                                                   index.Table.Name,
                                                   columns)));
            }
            else
            {
                var uIndex = (UniqueIndex)index;

                if (string.IsNullOrEmpty(uIndex.Where))
                {
                    return(new SqlPreCommandSimple("CREATE {0}INDEX {1} ON {2}({3})".FormatWith(
                                                       uIndex is UniqueIndex ? "UNIQUE " : null,
                                                       uIndex.IndexName,
                                                       uIndex.Table.Name,
                                                       columns)));
                }

                if (uIndex.ViewName != null)
                {
                    ObjectName viewName = new ObjectName(uIndex.Table.Name.Schema, uIndex.ViewName);

                    SqlPreCommandSimple viewSql = new SqlPreCommandSimple(@"CREATE VIEW {0} WITH SCHEMABINDING AS SELECT {1} FROM {2} WHERE {3}"
                                                                          .FormatWith(viewName, columns, uIndex.Table.Name.ToString(), uIndex.Where))
                    {
                        GoBefore = true, GoAfter = true
                    };

                    SqlPreCommandSimple indexSql = new SqlPreCommandSimple(@"CREATE UNIQUE CLUSTERED INDEX {0} ON {1}({2})"
                                                                           .FormatWith(uIndex.IndexName, viewName, uIndex.Columns.ToString(c => c.Name.SqlEscape(), ", ")));

                    return(SqlPreCommand.Combine(Spacing.Simple, viewSql, indexSql));
                }
                else
                {
                    return(new SqlPreCommandSimple("CREATE UNIQUE INDEX {0} ON {1}({2}) WHERE {3}".FormatWith(
                                                       uIndex.IndexName,
                                                       uIndex.Table.Name,
                                                       columns, uIndex.Where)));
                }
            }
        }
示例#19
0
        public static SqlPreCommand TotalSynchronizeScript(bool interactive = true, bool schemaOnly = false)
        {
            var command = Schema.Current.SynchronizationScript(interactive, schemaOnly);

            if (command == null)
            {
                return(null);
            }

            return(SqlPreCommand.Combine(Spacing.Double,
                                         new SqlPreCommandSimple(SynchronizerMessage.StartOfSyncScriptGeneratedOn0.NiceToString().FormatWith(DateTime.Now)),

                                         new SqlPreCommandSimple("use {0}".FormatWith(Connector.Current.DatabaseName())),
                                         command,
                                         new SqlPreCommandSimple(SynchronizerMessage.EndOfSyncScript.NiceToString())));
        }
示例#20
0
        public static string OpenSqlFile(this SqlPreCommand command, string fileName)
        {
            Save(command, fileName);

            Thread.Sleep(1000);

            new Process
            {
                StartInfo = new ProcessStartInfo(Path.Combine(Directory.GetCurrentDirectory(), fileName))
                {
                    UseShellExecute = true
                }
            }.Start();

            return(fileName);
        }
示例#21
0
        public static SqlPreCommand MoveRows(ObjectName oldTable, ObjectName newTable, IEnumerable <string> columnNames)
        {
            SqlPreCommandSimple command = new SqlPreCommandSimple(
                @"INSERT INTO {0} ({2})
SELECT {3}
FROM {1} as [table]".FormatWith(
                    newTable,
                    oldTable,
                    columnNames.ToString(a => a.SqlEscape(), ", "),
                    columnNames.ToString(a => "[table]." + a.SqlEscape(), ", ")));

            return(SqlPreCommand.Combine(Spacing.Simple,
                                         new SqlPreCommandSimple("SET IDENTITY_INSERT {0} ON".FormatWith(newTable)),
                                         command,
                                         new SqlPreCommandSimple("SET IDENTITY_INSERT {0} OFF".FormatWith(newTable))));
        }
示例#22
0
        public static SqlPreCommand AlterTableAlterColumn(ITable table, IColumn column, string?defaultConstraintName = null, ObjectName?forceTableName = null)
        {
            var alterColumn = new SqlPreCommandSimple("ALTER TABLE {0} ALTER COLUMN {1}".FormatWith(forceTableName ?? table.Name, CreateColumn(column, null, isChange: true)));

            if (column.Default == null)
            {
                return(alterColumn);
            }

            var defCons = GetDefaultConstaint(table, column) !;

            return(SqlPreCommand.Combine(Spacing.Simple,
                                         AlterTableDropConstraint(table.Name, defaultConstraintName ?? defCons.Name),
                                         alterColumn,
                                         AlterTableAddDefaultConstraint(table.Name, defCons)
                                         ) !);
        }
示例#23
0
        public static SqlPreCommand RenameOrChangeSchema(ObjectName oldTableName, ObjectName newTableName)
        {
            if (!object.Equals(oldTableName.Schema.Database, newTableName.Schema.Database))
            {
                throw new InvalidOperationException("Different database");
            }

            if (object.Equals(oldTableName.Schema, newTableName.Schema))
            {
                return(RenameTable(oldTableName, newTableName.Name));
            }

            var oldNewSchema = oldTableName.OnSchema(newTableName.Schema);

            return(SqlPreCommand.Combine(Spacing.Simple,
                                         AlterSchema(oldTableName, newTableName.Schema),
                                         oldNewSchema.Equals(newTableName) ? null : RenameTable(oldNewSchema, newTableName.Name)) !);
        }
示例#24
0
        private static SqlPreCommand SyncEnums(Schema schema, Table table, Dictionary <string, Entity> current, Dictionary <string, Entity> should)
        {
            var deletes = Synchronizer.SynchronizeScript(
                should,
                current,
                null,
                (str, c) => table.DeleteSqlSync(c, comment: c.toStr),
                null, Spacing.Double);

            var moves = Synchronizer.SynchronizeScript(
                should,
                current,
                null,
                null,
                (str, s, c) =>
            {
                if (s.id == c.id)
                {
                    return(table.UpdateSqlSync(c, comment: c.toStr));
                }

                var insert = table.InsertSqlSync(s);

                var move = (from t in schema.GetDatabaseTables()
                            from col in t.Columns.Values
                            where col.ReferenceTable == table
                            select new SqlPreCommandSimple("UPDATE {0} SET {1} = {2} WHERE {1} = {3} -- {4} re-indexed"
                                                           .FormatWith(t.Name, col.Name, s.Id, c.Id, c.toStr)))
                           .Combine(Spacing.Simple);

                var delete = table.DeleteSqlSync(c, comment: c.toStr);

                return(SqlPreCommand.Combine(Spacing.Simple, insert, move, delete));
            }, Spacing.Double);

            var creates = Synchronizer.SynchronizeScript(
                should,
                current,
                (str, s) => table.InsertSqlSync(s),
                null,
                null, Spacing.Double);

            return(SqlPreCommand.Combine(Spacing.Double, deletes, moves, creates));
        }
示例#25
0
        private static SqlPreCommand AlterTableAddColumnDefault(ITable table, IColumn column, Replacements rep)
        {
            bool temporalDefault = !column.Nullable && !column.Identity && column.Default == null;

            if (!temporalDefault)
            {
                return(SqlBuilder.AlterTableAddColumn(table, column));
            }

            string defaultValue = rep.Interactive ? SafeConsole.AskString("Default value for '{0}.{1}'? (or press enter) ".FormatWith(table.Name.Name, column.Name), stringValidator: str => null) : "";

            if (defaultValue == "null")
            {
                return(SqlBuilder.AlterTableAddColumn(table, column));
            }

            try
            {
                column.Default = defaultValue;

                if (column.Default.HasText() && SqlBuilder.IsString(column.SqlDbType) && !column.Default.Contains("'"))
                {
                    column.Default = "'" + column.Default + "'";
                }

                if (string.IsNullOrEmpty(column.Default))
                {
                    column.Default = SqlBuilder.IsNumber(column.SqlDbType) ? "0" :
                                     SqlBuilder.IsString(column.SqlDbType) ? "''" :
                                     SqlBuilder.IsDate(column.SqlDbType) ? "GetDate()" :
                                     "?";
                }

                return(SqlPreCommand.Combine(Spacing.Simple,
                                             SqlBuilder.AlterTableAddColumn(table, column),
                                             SqlBuilder.DropDefaultConstraint(table.Name, column.Name)));
            }
            finally
            {
                column.Default = null;
            }
        }
示例#26
0
        public static SqlPreCommand CreateIndex(Index index, Replacements?checkUnique)
        {
            if (index is PrimaryClusteredIndex)
            {
                var columns = index.Columns.ToString(c => c.Name.SqlEscape(), ", ");

                return(new SqlPreCommandSimple($"ALTER TABLE {index.Table.Name} ADD CONSTRAINT {index.IndexName} PRIMARY KEY CLUSTERED({columns})"));
            }

            if (index is UniqueIndex uIndex)
            {
                if (uIndex.ViewName != null)
                {
                    ObjectName viewName = new ObjectName(uIndex.Table.Name.Schema, uIndex.ViewName);

                    var columns = index.Columns.ToString(c => c.Name.SqlEscape(), ", ");

                    SqlPreCommandSimple viewSql = new SqlPreCommandSimple($"CREATE VIEW {viewName} WITH SCHEMABINDING AS SELECT {columns} FROM {uIndex.Table.Name.ToString()} WHERE {uIndex.Where}")
                    {
                        GoBefore = true, GoAfter = true
                    };

                    SqlPreCommandSimple indexSql = new SqlPreCommandSimple($"CREATE UNIQUE CLUSTERED INDEX {uIndex.IndexName} ON {viewName}({columns})");

                    return(SqlPreCommand.Combine(Spacing.Simple,
                                                 checkUnique != null ? RemoveDuplicatesIfNecessary(uIndex, checkUnique) : null,
                                                 viewSql,
                                                 indexSql) !);
                }
                else
                {
                    return(SqlPreCommand.Combine(Spacing.Double,
                                                 checkUnique != null ? RemoveDuplicatesIfNecessary(uIndex, checkUnique) : null,
                                                 CreateIndexBasic(index, false)) !);
                }
            }
            else
            {
                return(CreateIndexBasic(index, forHistoryTable: false));
            }
        }
示例#27
0
        public static SqlPreCommand RenameOrMove(DiffTable oldTable, ITable newTable)
        {
            if (object.Equals(oldTable.Name.Schema, newTable.Name.Schema))
            {
                return(RenameTable(oldTable.Name, newTable.Name.Name));
            }

            if (object.Equals(oldTable.Name.Schema.Database, newTable.Name.Schema.Database))
            {
                var oldNewSchema = oldTable.Name.OnSchema(newTable.Name.Schema);

                return(SqlPreCommand.Combine(Spacing.Simple,
                                             AlterSchema(oldTable.Name, newTable.Name.Schema),
                                             oldNewSchema.Equals(newTable.Name) ? null : RenameTable(oldNewSchema, newTable.Name.Name)));
            }

            return(SqlPreCommand.Combine(Spacing.Simple,
                                         CreateTableSql(newTable),
                                         MoveRows(oldTable.Name, newTable.Name, newTable.Columns.Keys),
                                         DropTable(oldTable.Name)));
        }
示例#28
0
        internal static SqlPreCommand CopyData(ITable newTable, DiffTable oldTable, Replacements rep)
        {
            var selectColumns = newTable.Columns
                                .Select(col => oldTable.Columns.TryGetC(col.Key)?.Name ?? GetDefaultValue(newTable, col.Value, rep))
                                .ToString(", ");

            var insertSelect = new SqlPreCommandSimple(
                $@"INSERT INTO {newTable.Name} ({newTable.Columns.Values.ToString(a => a.Name, ", ")})
SELECT {selectColumns}
FROM {oldTable.Name}");

            if (!newTable.PrimaryKey.Identity)
            {
                return(insertSelect);
            }

            return(SqlPreCommand.Combine(Spacing.Simple,
                                         SqlBuilder.SetIdentityInsert(newTable.Name, true),
                                         insertSelect,
                                         SqlBuilder.SetIdentityInsert(newTable.Name, false)
                                         ));
        }
示例#29
0
 public static SqlPreCommand Combine(this IEnumerable <SqlPreCommand> preCommands, Spacing spacing)
 {
     return(SqlPreCommand.Combine(spacing, preCommands.ToArray()));
 }
示例#30
0
        public static void Save(this SqlPreCommand command, string fileName)
        {
            string content = command.PlainSql();

            File.WriteAllText(fileName, content, Encoding.GetEncoding(1252));
        }
示例#31
0
 internal SqlPreCommandConcat(Spacing spacing, SqlPreCommand[] commands)
 {
     this.Spacing = spacing;
     this.Commands = commands;
 }