Ejemplo n.º 1
0
        public void GenerateDatabase(bool disableTriggers, bool dryRun)
        {
            var tablePrescriptions = GetOrderedTableDescriptions()
                                     .Select(_ => _Project.Prescriptor.TablePrescriptions.SingleOrDefault(tablePrescription => tablePrescription.TableDescription == _))
                                     .ToArray();

            using var source                = new InternalGenerator(this).Generate();
            using var destination           = _SqlFactory.Open(_Project.Descriptor.ConnectionString);
            using var sourceConnection      = source.CreateConnection();
            using var destinationConnection = destination.CreateConnection();
            sourceConnection.Open();
            destinationConnection.Open();
            using var transaction   = destinationConnection.BeginTransaction("DATAFACTORY");
            using var deleteCommand = destinationConnection.CreateCommand();
            var deletions = tablePrescriptions
                            .Select(t => t.TableName())
                            .Reverse()
                            .Select(tableName => "DELETE FROM {0};".FormatInvariant(tableName));

            deleteCommand.CommandText = string.Concat(deletions);
            deleteCommand.Transaction = transaction;
            _ = deleteCommand.ExecuteNonQuery();
            var copyOptions = CreateCopyOptions(disableTriggers);

            foreach (var tablePrescription in tablePrescriptions)
            {
                var tableName   = tablePrescription.TableName();
                var columnNames = tablePrescription.ColumnPrescriptions.Select(c => c.ColumnDescription.Name);
                ExecuteSqlBulkCopy(transaction, sourceConnection, destinationConnection, copyOptions, tableName, columnNames);
            }

            if (dryRun)
            {
                transaction.Rollback();
            }
            else
            {
                transaction.Commit();
            }
        }