public TableScript(DirectoryInfo sourceDirectory, FullTableName tableName, StringCollection sqlScripts)
            {
                _tableName = tableName;
                var allScripts = sqlScripts.Cast <string>().ToList();

                _singleSqlScript = String.Join(string.Format("\r\n{0}\r\n", SqlExecuteSafe.SqlBatchSeparator), allScripts);
                _tableScriptFile = CalculateTableFileInfo(tableName, sourceDirectory);
            }
Beispiel #2
0
        private void FixOnModelCreatingForTable(CreateTableOperation table, [CanBeNull] GetModelTableNameDelegate getModelTableName)
        {
            if (table == null)
            {
                throw new ArgumentNullException(nameof(table));
            }
            if (_info == null)
            {
                throw new NullReferenceException(nameof(_info));
            }
            var tn = new FullTableName(table.Name, table.Schema).WithDefaultSchema(_info.DefaultSchema);

            if (getModelTableName != null)
            {
                tn = getModelTableName(tn);
            }
            var entity = _info.GetByTableName(tn);

            if (entity == null)
            {
                Log(nameof(FixOnModelCreatingForTable),
                    $"Table {table.Name} not found. Skipping.");
                return;
            }

            var colsDic = entity
                          .Properites
                          .Where(info => !info.IsNotMapped && !info.IsNavigationProperty)
                          .ToDictionary(a => a.ColumnName, StringComparer.OrdinalIgnoreCase);
            var natural = Enumerable.Range(0, table.Columns.Count).ToDictionary(a => table.Columns[a].Name, a => a);

            string GetSortColumns()
            {
                return("(" + string.Join(",", table.Columns.Select(a => a.Name)) + ")");
            }

            var sortBefore = GetSortColumns();

            table.Columns.Sort((a, b) =>
            {
                colsDic.TryGetValue(a.Name, out var aWrapper);
                colsDic.TryGetValue(b.Name, out var bWrapper);
                var compareResult = ComparePropertyWrapper(aWrapper, bWrapper);
                if (compareResult != 0)
                {
                    return(compareResult);
                }
                return(natural[a.Name].CompareTo(natural[b.Name])); // bez zmian
            });
            var sortAfter = GetSortColumns();

            if (sortBefore != sortAfter)
            {
                Log(nameof(FixOnModelCreatingForTable),
                    $"Table {table.Name} change column order {sortBefore} => {sortAfter}.");
            }
        }
        internal override string generateCreateSql()
        {
            /*
             * CREATE [UNIQUE] INDEX index_name ON
             * table_name(column_name[, column_name...])
             * TABLESPACE table_space;
             */

            StringBuilder sb    = new StringBuilder();
            StringBuilder sbPKs = new StringBuilder();

            sb.Append("CREATE ")
            .Append((IndexKind == null ? "" : IndexKind))
            .Append(" INDEX ")
            .Append((IndexName == null ? "" : FullIndexName.ToUpper()))
            .Append(" ");
            sb.Append(" ON ")
            .Append(FullTableName.ToUpper())
            .Append(" (");

            foreach (FieldInfo fi in Fields)
            {
//				sb.Append(@"""").Append(fi.Name).Append(@""", ");
                sb.Append(fi.Name).Append(", ");
            }
            if (Fields.Count > 0)
            {
                sb.Remove(sb.Length - 2, 2);
            }

            sb.Append(")");

            string ret = sb.ToString();

            return(ret);
        }
        internal override string generateCreateSql()
        {
            /*
             * Oracle> ALTER TABLE aact ADD CONSTRAINT FK_AACT_ACID FOREIGN KEY (ACID) REFERENCES ACC (ACID)
             */

            StringBuilder sb = new StringBuilder();

            sb.Append("ALTER TABLE ")
            .Append(FullTableName.ToUpper())
            .Append(@" ADD CONSTRAINT ")
            .Append(ConstraintName.ToUpper())      // oracle doesn't like the schema name put here, so we use the constraint name only
            .Append(@" FOREIGN KEY (");

            foreach (FieldInfo fi in this.SourceFields)
            {
                sb.Append(fi.Name).Append(@", ");
            }
            sb.Remove(sb.Length - 2, 2);

            sb.Append(@") REFERENCES ")
            .Append(this.ReferencesFullTableName.ToUpper())
            .Append(@" (");

            foreach (FieldInfo fi2 in this.ReferencesFields)
            {
                sb.Append(fi2.Name).Append(", ");
            }
            sb.Remove(sb.Length - 2, 2);
            sb.Append(")");             // ON DELETE RESTRICT ON UPDATE RESTRICT)");


            string ret = sb.ToString();

            return(ret);
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            var connectionString = args[0];


            var logger = new ConsoleLogger();

            using (var tfs = new ThreadsFrames())
            {
                //var sf = new ConsoleCollectionSaverFactory(
                //    );

                var ftn = new FullTableName("_ss");

                var tfnc = new TargetFileNameController(
                    1,
                    @"_bbin",
                    500
                    );

                var sf = new SqlServerCollectionSaverFactory(
                    connectionString,
                    ftn,
                    tfnc
                    );
                sf.PrepareDatabase();

                var r = new SqlServerReader(
                    connectionString,
                    ftn,
                    tfnc
                    );

                using (var pq = new PublishQueue(
                           sf,
                           logger
                           ))
                {
                    var p = new Publisher(
                        pq,
                        tfs
                        );

                    var iec = new Common.IEC(tfs, p, r);

                    iec.Publisher.PublishedEvent +=
                        (
                            collections,
                            count
                        ) =>
                    {
                        var read = iec.Reader.ReadBetween(
                            new DateTime(2000, 1, 1),
                            new DateTime(2030, 1, 1)
                            );

                        Console.WriteLine(read.Last().Body);
                    };

                    ProcessMutable(iec);
                    //ProcessImmutable(iec);
                }
            }

            Console.WriteLine("Finished!");
        }
 private static FileInfo CalculateTableFileInfo(FullTableName currentTable, DirectoryInfo sourceDirectory)
 {
     return(new FileInfo(Path.Combine(sourceDirectory.FullName, string.Format("{0}.{1}.sql", currentTable.Schema, currentTable.TableName))));
 }
 protected override string generateDropSql()
 {
     return("ALTER TABLE " + FullTableName.ToUpper() + " DROP CONSTRAINT " + FullConstraintName.ToUpper());
 }
        public void FixMigrationUp(MigrationBuilder migrationBuilder, ModelInfo info)
        {
            if (!MsSqlUtils.IsSupportedProvider(migrationBuilder.ActiveProvider))
            {
                return;
            }
            var logger = info.UsedShamanOptions.Logger ?? EmptyShamanLogger.Instance;
            var log    = logger.CreateMethod(typeof(SqlServerFixerService), nameof(FixMigrationUp));

            log("Begin");
            var createTableOperations = new Dictionary <FullTableName, CreateTableOperation>();

            foreach (var i in migrationBuilder.Operations.OfType <CreateTableOperation>())
            {
                var tn = new FullTableName(i.Name, i.Schema).WithDefaultSchema(info.DefaultSchema);
                createTableOperations[tn] = i;
            }

            foreach (var dbSetInfo in info.DbSets)
            {
                // looking for create operation
                var tn = new FullTableName(dbSetInfo.TableName, dbSetInfo.Schema).WithDefaultSchema(info.DefaultSchema);
                if (!createTableOperations.TryGetValue(tn, out var createTableOperation))
                {
                    continue;
                }
                log($"Fixing create table {tn}");
                // var tableCollation = GetCollation(dbSetInfo.Annotations);
                var columns = createTableOperation.Columns.ToDictionary(a => a.Name, a => a,
                                                                        StringComparer.OrdinalIgnoreCase);
                foreach (var columnInfo in dbSetInfo.Properites.Where(q => !q.IsNotMapped && !q.IsNavigationProperty))
                {
                    if (!columns.TryGetValue(columnInfo.ColumnName, out var addColumnOperation))
                    {
                        continue;
                    }
                    if (addColumnOperation.ClrType == typeof(string))
                    {
                        // fix collation and unicode for text field
                        var usedIsUnicode   = MsSqlUtils.IsUnicodeTextField(addColumnOperation.ColumnType);
                        var expectedUnicode = addColumnOperation.IsUnicode ?? usedIsUnicode;

                        var columnCollation = SqlServerReflectionService.GetCollation(columnInfo, dbSetInfo, info);
                        if (string.IsNullOrEmpty(columnCollation) && usedIsUnicode == expectedUnicode)
                        {
                            continue;
                        }
                        var escapedTableName  = MsSqlUtils.Escape(dbSetInfo.Schema, dbSetInfo.TableName);
                        var escapedColumnName = MsSqlUtils.Escape(columnInfo.ColumnName);
                        if (!string.IsNullOrEmpty(columnCollation))
                        {
                            log($"Change collation {escapedTableName}.{escapedColumnName} => {columnCollation}");
                        }
                        if (usedIsUnicode != expectedUnicode)
                        {
                            log($"Change unicode {escapedTableName}.{escapedColumnName} => {expectedUnicode}");
                        }
                        var sql = CreateChangeCollationSql(escapedTableName, escapedColumnName, columnCollation,
                                                           expectedUnicode, addColumnOperation.MaxLength, addColumnOperation.IsNullable);
                        migrationBuilder.Sql(sql);
                        MoveSqlBeforeIndexCreation(migrationBuilder, createTableOperation, columnInfo.ColumnName);
                    }
                }
            }

            log("End");
        }