Пример #1
0
        public void Delete <T>(T instance)
        {
            var tableName = _conventionReader.GetTableName <T>();

            var primaryKeyColumnName = _conventionReader.GetPrimaryKeyColumnName <T>();
            var primaryKeyValue      = _conventionReader.GetPrimaryKeyValue(instance);

            var constraintExpression = QueryExpression.Create(new EqualsExpression(primaryKeyColumnName, primaryKeyValue));

            var command = _sqlGenerator.CreateDeleteCommand(tableName, constraintExpression);

            _dbCommandExecutor.ExecuteNonQuery(command, ConnectionString);
        }
Пример #2
0
        internal void Execute(IDbConnection connection, IDbTransaction transaction, MigrationDirection direction, IDbCommandExecutor commandExecutor)
        {
            Debug.Assert(connection.State == ConnectionState.Open);

            var context = new RuntimeContext(connection, transaction, commandExecutor, _providerMetadata);
            Database database = GetDatabaseContainingMigrationChanges(direction, context);
            var translator = new CommandsToSqlTranslator(_provider);
            foreach (string commandText in translator.TranslateToSql(database, context))
            {
                //MigSharp uses ADO, not SMO to run SQL. ADO does not support the 'GO' statement in SQL as it is not TSQL.
                //We split SQL on 'GO' and run as individual statements
                var separatedByGoStatements = new List<string>(goStatementRegex.Split(commandText));
                separatedByGoStatements.RemoveAll(r => String.IsNullOrEmpty(r.Trim()));

                foreach (var statement in separatedByGoStatements)
                {
                    IDbCommand command = connection.CreateCommand();
                    command.CommandTimeout = 0; // do not timeout; the client is responsible for not causing lock-outs
                    command.Transaction = transaction;
                    command.CommandText = statement;
                    try
                    {
                        commandExecutor.ExecuteNonQuery(command);
                    }
                    catch (DbException x)
                    {
                        Log.Error("An error occurred: {0}{1}while trying to execute:{1}{2}", x.Message, Environment.NewLine, command.CommandText);
                        throw;
                    }
                }
            }
        }
        internal void Execute(IDbConnection connection, IDbTransaction transaction, MigrationDirection direction, IDbCommandExecutor commandExecutor)
        {
            Debug.Assert(connection.State == ConnectionState.Open);

            var      context    = new RuntimeContext(connection, transaction, commandExecutor, _providerMetadata);
            Database database   = GetDatabaseContainingMigrationChanges(direction, context);
            var      translator = new CommandsToSqlTranslator(_provider);

            foreach (string commandText in translator.TranslateToSql(database, context))
            {
                IDbCommand command = connection.CreateCommand();
                command.CommandTimeout = 0; // do not timeout; the client is responsible for not causing lock-outs
                command.Transaction    = transaction;
                command.CommandText    = commandText;
                try
                {
                    commandExecutor.ExecuteNonQuery(command);
                }
                catch (DbException x)
                {
                    Log.Error("An error occurred: {0}{1}while trying to execute:{1}{2}", x.Message, Environment.NewLine, command.CommandText);
                    throw;
                }
            }
        }
Пример #4
0
        public void Store(IDbConnection connection, IDbTransaction transaction, IDbCommandExecutor executor)
        {
            Debug.Assert(connection.State == ConnectionState.Open);

            DateTime start = DateTime.Now;

            foreach (IMigrationMetadata entry in _entriesToDelete)
            {
                IDbCommand command = connection.CreateCommand();
                command.Transaction = transaction;
                string         moduleName          = entry.ModuleName;
                IDataParameter moduleNameParameter = command.AddParameter("@ModuleName", DbType.String, moduleName);
                long           timestamp           = entry.Timestamp;
                command.CommandText = string.Format(CultureInfo.InvariantCulture, "DELETE FROM \"{0}\" WHERE \"{1}\" = {2} AND \"{3}\" = {4}",
                                                    _tableName,
                                                    BootstrapMigration.TimestampColumnName,
                                                    timestamp.ToString(CultureInfo.InvariantCulture),
                                                    BootstrapMigration.ModuleColumnName,
                                                    _providerMetadata.GetParameterSpecifier(moduleNameParameter));
                // note: we do not provide the timestamp as a parameter as the OracleOdbcProvider has an issue with it
                executor.ExecuteNonQuery(command);
                Predicate <IMigrationMetadata> match = m => m.Timestamp == timestamp && m.ModuleName == moduleName;
                Debug.Assert(_actualEntries.FindAll(match).Count == 1, "There should be one existing entry if it is deleted.");
                _actualEntries.RemoveAll(match);
            }
            _entriesToDelete.Clear();
            foreach (IMigrationMetadata entry in _entriesToInsert)
            {
                IDbCommand command = connection.CreateCommand();
                command.Transaction = transaction;
                IDataParameter moduleNameParameter = command.AddParameter("@ModuleName", DbType.String, entry.ModuleName);
                IDataParameter tagParameter        = command.AddParameter("@Tag", DbType.String, !string.IsNullOrEmpty(entry.Tag) ? (object)entry.Tag : DBNull.Value);
                command.CommandText = string.Format(CultureInfo.InvariantCulture, @"INSERT INTO ""{0}"" (""{1}"", ""{2}"", ""{3}"") VALUES ({4}, {5}, {6})",
                                                    _tableName,
                                                    BootstrapMigration.TimestampColumnName,
                                                    BootstrapMigration.ModuleColumnName,
                                                    BootstrapMigration.TagColumnName,
                                                    entry.Timestamp.ToString(CultureInfo.InvariantCulture),
                                                    _providerMetadata.GetParameterSpecifier(moduleNameParameter),
                                                    _providerMetadata.GetParameterSpecifier(tagParameter));
                // note: we do not provide the timestamp as a parameter as the OracleOdbcProvider has an issue with it
                executor.ExecuteNonQuery(command);
                _actualEntries.Add(entry);
            }
            _entriesToInsert.Clear();
            Log.Verbose(LogCategory.Performance, "Version update took {0}s", (DateTime.Now - start).TotalSeconds);
        }
Пример #5
0
        public void Insert <T>(IEnumerable <T> entities)
        {
            var entityList = entities.ToList();

            if (_conventionReader.HasIdentityId(typeof(T)))
            {
                var commands = CreateIdentityInsertCommands(entities);

                var ids = _dbCommandExecutor.ExecuteScalarList <int>(commands, ConnectionString);

                for (int i = 0; i < ids.Count; i++)
                {
                    _conventionReader.SetId(entityList[i], ids[i]);
                }
            }
            else
            {
                var commands = CreateInsertCommands(entities);

                _dbCommandExecutor.ExecuteNonQuery(commands, ConnectionString);
            }
        }
        internal void Execute(IDbConnection connection, IDbTransaction transaction, MigrationDirection direction, IDbCommandExecutor commandExecutor)
        {
            Debug.Assert(connection.State == ConnectionState.Open);

            var context = new RuntimeContext(connection, transaction, commandExecutor, _providerMetadata);
            Database database = GetDatabaseContainingMigrationChanges(direction, context);
            var translator = new CommandsToSqlTranslator(_provider);
            foreach (string commandText in translator.TranslateToSql(database, context))
            {
                IDbCommand command = connection.CreateCommand();
                command.CommandTimeout = 0; // do not timeout; the client is responsible for not causing lock-outs
                command.Transaction = transaction;
                command.CommandText = commandText;
                try
                {
                    commandExecutor.ExecuteNonQuery(command);
                }
                catch (DbException x)
                {
                    Log.Error("An error occurred: {0}{1}while trying to execute:{1}{2}{1}{3}", x.Message, Environment.NewLine, command.CommandText,_migration.GetType().ToString());
                    throw new Exception(String.Format("An error occurred: {0}{1}while trying to execute:{1}{2}{1}Migration: {3}", x.Message, Environment.NewLine, command.CommandText, _migration.GetType()));
                }
            }
        }
Пример #7
0
        /// <summary>
        /// Runs ADO.NET test suite for the specified <see cref="IDbCommandExecutor"/>.
        /// </summary>
        /// <param name="connection">The <see cref="IDbConnection"/> to use to connect to the database.</param>
        /// <param name="commandFactory">A <see cref="DbCommandFactory"/> implementation specific to an ADO.NET provider, e.g. SqlCommand, NpgsqlCommand.</param>
        /// <param name="commandExecutor">A <see cref="IDbCommandExecutor"/> used to call DbCommand methods.</param>
        /// <param name="cancellationToken">A cancellation token passed into downstream async methods.</param>
        /// <returns>A task representing the asynchronous operation.</returns>
        private static async Task RunAsync(
            IDbConnection connection,
            DbCommandFactory commandFactory,
            IDbCommandExecutor commandExecutor,
            CancellationToken cancellationToken)
        {
            string commandName = commandExecutor.CommandTypeName;

            Console.WriteLine(commandName);

            using (var parentScope = Tracer.Instance.StartActive("command"))
            {
                parentScope.Span.ResourceName = commandName;
                IDbCommand command;

                using (var scope = Tracer.Instance.StartActive("sync"))
                {
                    scope.Span.ResourceName = commandName;

                    Console.WriteLine("  Synchronous");
                    Console.WriteLine();
                    await Task.Delay(100, cancellationToken);

                    command = commandFactory.GetCreateTableCommand(connection);
                    commandExecutor.ExecuteNonQuery(command);

                    command = commandFactory.GetInsertRowCommand(connection);
                    commandExecutor.ExecuteNonQuery(command);

                    command = commandFactory.GetSelectScalarCommand(connection);
                    commandExecutor.ExecuteScalar(command);

                    command = commandFactory.GetUpdateRowCommand(connection);
                    commandExecutor.ExecuteNonQuery(command);

                    command = commandFactory.GetSelectRowCommand(connection);
                    commandExecutor.ExecuteReader(command);

                    command = commandFactory.GetSelectRowCommand(connection);
                    commandExecutor.ExecuteReader(command, CommandBehavior.Default);

                    command = commandFactory.GetDeleteRowCommand(connection);
                    commandExecutor.ExecuteNonQuery(command);
                }

                if (commandExecutor.SupportsAsyncMethods)
                {
                    await Task.Delay(100, cancellationToken);

                    using (var scope = Tracer.Instance.StartActive("async"))
                    {
                        scope.Span.ResourceName = commandName;

                        Console.WriteLine("  Asynchronous");
                        Console.WriteLine();
                        await Task.Delay(100, cancellationToken);

                        command = commandFactory.GetCreateTableCommand(connection);
                        await commandExecutor.ExecuteNonQueryAsync(command);

                        command = commandFactory.GetInsertRowCommand(connection);
                        await commandExecutor.ExecuteNonQueryAsync(command);

                        command = commandFactory.GetSelectScalarCommand(connection);
                        await commandExecutor.ExecuteScalarAsync(command);

                        command = commandFactory.GetUpdateRowCommand(connection);
                        await commandExecutor.ExecuteNonQueryAsync(command);

                        command = commandFactory.GetSelectRowCommand(connection);
                        await commandExecutor.ExecuteReaderAsync(command);

                        command = commandFactory.GetSelectRowCommand(connection);
                        await commandExecutor.ExecuteReaderAsync(command, CommandBehavior.Default);

                        command = commandFactory.GetDeleteRowCommand(connection);
                        await commandExecutor.ExecuteNonQueryAsync(command);
                    }

                    await Task.Delay(100, cancellationToken);

                    using (var scope = Tracer.Instance.StartActive("async-with-cancellation"))
                    {
                        scope.Span.ResourceName = commandName;

                        Console.WriteLine("  Asynchronous with cancellation");
                        Console.WriteLine();
                        await Task.Delay(100, cancellationToken);

                        command = commandFactory.GetCreateTableCommand(connection);
                        await commandExecutor.ExecuteNonQueryAsync(command, cancellationToken);

                        command = commandFactory.GetInsertRowCommand(connection);
                        await commandExecutor.ExecuteNonQueryAsync(command, cancellationToken);

                        command = commandFactory.GetSelectScalarCommand(connection);
                        await commandExecutor.ExecuteScalarAsync(command, cancellationToken);

                        command = commandFactory.GetUpdateRowCommand(connection);
                        await commandExecutor.ExecuteNonQueryAsync(command, cancellationToken);

                        command = commandFactory.GetSelectRowCommand(connection);
                        await commandExecutor.ExecuteReaderAsync(command, cancellationToken);

                        command = commandFactory.GetSelectRowCommand(connection);
                        await commandExecutor.ExecuteReaderAsync(command, CommandBehavior.Default, cancellationToken);

                        command = commandFactory.GetDeleteRowCommand(connection);
                        await commandExecutor.ExecuteNonQueryAsync(command, cancellationToken);
                    }
                }
            }

            await Task.Delay(100, cancellationToken);
        }
Пример #8
0
        public void Store(IDbConnection connection, IDbTransaction transaction, IDbCommandExecutor executor)
        {
            Debug.Assert(connection.State == ConnectionState.Open);

            DateTime start = DateTime.Now;
            foreach (IMigrationMetadata entry in _entriesToDelete)
            {
                IDbCommand command = connection.CreateCommand();
                command.Transaction = transaction;
                string moduleName = entry.ModuleName;
                IDataParameter moduleNameParameter = command.AddParameter("@ModuleName", DbType.String, moduleName);
                long timestamp = entry.Timestamp;
                command.CommandText = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0} WHERE  {1}  = {2} AND  {3}  = {4}",
                    _tableName,
                    BootstrapMigration.TimestampColumnName,
                    timestamp.ToString(CultureInfo.InvariantCulture),
                    BootstrapMigration.ModuleColumnName,
                    _providerMetadata.GetParameterSpecifier(moduleNameParameter));
                // note: we do not provide the timestamp as a parameter as the OracleOdbcProvider has an issue with it
                executor.ExecuteNonQuery(command);
                Predicate<IMigrationMetadata> match = m => m.Timestamp == timestamp && m.ModuleName == moduleName;
                Debug.Assert(_actualEntries.FindAll(match).Count == 1, "There should be one existing entry if it is deleted.");
                _actualEntries.RemoveAll(match);
            }
            _entriesToDelete.Clear();
            foreach (IMigrationMetadata entry in _entriesToInsert)
            {
                IDbCommand command = connection.CreateCommand();
                command.Transaction = transaction;
                IDataParameter moduleNameParameter = command.AddParameter("@ModuleName", DbType.String, entry.ModuleName);
                IDataParameter tagParameter = command.AddParameter("@Tag", DbType.String, !string.IsNullOrEmpty(entry.Tag) ? (object)entry.Tag : DBNull.Value);
                command.CommandText = string.Format(CultureInfo.InvariantCulture, @"INSERT INTO {0} ({1}, {2}, {3}) VALUES ({4}, {5}, {6})",
                    _tableName,
                    BootstrapMigration.TimestampColumnName,
                    BootstrapMigration.ModuleColumnName,
                    BootstrapMigration.TagColumnName,
                    entry.Timestamp.ToString(CultureInfo.InvariantCulture),
                    _providerMetadata.GetParameterSpecifier(moduleNameParameter),
                    _providerMetadata.GetParameterSpecifier(tagParameter));
                // note: we do not provide the timestamp as a parameter as the OracleOdbcProvider has an issue with it
                executor.ExecuteNonQuery(command);
                _actualEntries.Add(entry);
            }
            _entriesToInsert.Clear();
            Log.Verbose(LogCategory.Performance, "Version update took {0}s", (DateTime.Now - start).TotalSeconds);
        }
Пример #9
0
        private static async Task RunAsync(
            ITransaction transaction,
            DbCommandFactory commandFactory,
            IDbCommandExecutor commandExecutor,
            CancellationToken cancellationToken
            )
        {
            var commandName = commandExecutor.CommandTypeName;

            Console.WriteLine(commandName);

            await transaction.CaptureSpan($"{commandName} command", "command", async span =>
            {
                IDbCommand command;

                await span.CaptureSpan($"{commandName} sync", "sync", async childSpan =>
                {
                    Console.WriteLine("  synchronous");
                    await Task.Delay(100, cancellationToken);

                    command = commandFactory.GetCreateTableCommand();
                    commandExecutor.ExecuteNonQuery(command);

                    command = commandFactory.GetInsertRowCommand();
                    commandExecutor.ExecuteNonQuery(command);

                    command = commandFactory.GetSelectScalarCommand();
                    commandExecutor.ExecuteScalar(command);

                    command = commandFactory.GetUpdateRowCommand();
                    commandExecutor.ExecuteNonQuery(command);

                    command = commandFactory.GetSelectRowCommand();
                    commandExecutor.ExecuteReader(command);

                    command = commandFactory.GetSelectRowCommand();
                    commandExecutor.ExecuteReader(command, CommandBehavior.Default);

                    command = commandFactory.GetDeleteRowCommand();
                    commandExecutor.ExecuteNonQuery(command);
                });

                if (commandExecutor.SupportsAsyncMethods)
                {
                    await Task.Delay(100, cancellationToken);

                    await span.CaptureSpan($"{commandName} async", "async", async childSpan =>
                    {
                        Console.WriteLine("  asynchronous");
                        await Task.Delay(100, cancellationToken);

                        command = commandFactory.GetCreateTableCommand();
                        await commandExecutor.ExecuteNonQueryAsync(command);

                        command = commandFactory.GetInsertRowCommand();
                        await commandExecutor.ExecuteNonQueryAsync(command);

                        command = commandFactory.GetSelectScalarCommand();
                        await commandExecutor.ExecuteScalarAsync(command);

                        command = commandFactory.GetUpdateRowCommand();
                        await commandExecutor.ExecuteNonQueryAsync(command);

                        command = commandFactory.GetSelectRowCommand();
                        await commandExecutor.ExecuteReaderAsync(command);

                        command = commandFactory.GetSelectRowCommand();
                        await commandExecutor.ExecuteReaderAsync(command, CommandBehavior.Default);

                        command = commandFactory.GetDeleteRowCommand();
                        await commandExecutor.ExecuteNonQueryAsync(command);
                    });

                    await Task.Delay(100, cancellationToken);

                    await span.CaptureSpan($"{commandName} async with cancellation", "async-cancellation", async childSpan =>
                    {
                        Console.WriteLine("  asynchronous with cancellation");
                        await Task.Delay(100, cancellationToken);

                        command = commandFactory.GetCreateTableCommand();
                        await commandExecutor.ExecuteNonQueryAsync(command, cancellationToken);

                        command = commandFactory.GetInsertRowCommand();
                        await commandExecutor.ExecuteNonQueryAsync(command, cancellationToken);

                        command = commandFactory.GetSelectScalarCommand();
                        await commandExecutor.ExecuteScalarAsync(command, cancellationToken);

                        command = commandFactory.GetUpdateRowCommand();
                        await commandExecutor.ExecuteNonQueryAsync(command, cancellationToken);

                        command = commandFactory.GetSelectRowCommand();
                        await commandExecutor.ExecuteReaderAsync(command, cancellationToken);

                        command = commandFactory.GetSelectRowCommand();
                        await commandExecutor.ExecuteReaderAsync(command, CommandBehavior.Default, cancellationToken);

                        command = commandFactory.GetDeleteRowCommand();
                        await commandExecutor.ExecuteNonQueryAsync(command, cancellationToken);
                    });
                }
            });

            await Task.Delay(100, cancellationToken);
        }
Пример #10
0
        public void Store(IDbConnection connection, IDbTransaction transaction, IDbCommandExecutor executor)
        {
            Debug.Assert(connection.State == ConnectionState.Open);

            DateTime start = DateTime.Now;
            foreach (HistoryEntryId entryId in _entriesToDelete)
            {
                IDbCommand command = connection.CreateCommand();
                command.Transaction = transaction;
                IDataParameter moduleNameParameter = command.AddParameter("@ModuleName", DbType.String, entryId.ModuleName);
                command.CommandText = string.Format(CultureInfo.InvariantCulture, "DELETE FROM \"{0}\" WHERE \"{1}\" = {2} AND \"{3}\" = {4}",
                    _tableName,
                    BootstrapMigration.TimestampColumnName,
                    entryId.Timestamp.ToString(CultureInfo.InvariantCulture),
                    BootstrapMigration.ModuleColumnName,
                    _providerMetadata.GetParameterSpecifier(moduleNameParameter));
                // note: we do not provide the timestamp as a parameter as the OracleOdbcProvider has an issue with it
                executor.ExecuteNonQuery(command);
                RemoveFromActualEntries(entryId);
            }
            _entriesToDelete.Clear();
            foreach (HistoryEntry entry in _entriesToInsert)
            {
                IDbCommand command = connection.CreateCommand();
                command.Transaction = transaction;
                IDataParameter moduleNameParameter = command.AddParameter("@ModuleName", DbType.String, entry.ModuleName);
                IDataParameter tagParameter = command.AddParameter("@Tag", DbType.String, !string.IsNullOrEmpty(entry.Tag) ? (object)entry.Tag : DBNull.Value);
                command.CommandText = string.Format(CultureInfo.InvariantCulture, @"INSERT INTO ""{0}"" (""{1}"", ""{2}"", ""{3}"") VALUES ({4}, {5}, {6})",
                    _tableName,
                    BootstrapMigration.TimestampColumnName,
                    BootstrapMigration.ModuleColumnName,
                    BootstrapMigration.TagColumnName,
                    entry.Timestamp.ToString(CultureInfo.InvariantCulture),
                    _providerMetadata.GetParameterSpecifier(moduleNameParameter),
                    _providerMetadata.GetParameterSpecifier(tagParameter));
                // note: we do not provide the timestamp as a parameter as the OracleOdbcProvider has an issue with it
                executor.ExecuteNonQuery(command);
                AddToActualEntries(entry);
            }
            _entriesToInsert.Clear();
            Log.Verbose(LogCategory.Performance, "Version update took {0}s", (DateTime.Now - start).TotalSeconds);
        }