コード例 #1
0
        protected override object Execute(IRelationalConnection connection, string executeMethod, IReadOnlyDictionary <string, object> parameterValues, bool closeConnection)
        {
            ThrowIf.Argument.IsNull(connection, nameof(connection));
            ThrowIf.Argument.IsNull(executeMethod, nameof(executeMethod));
            var    dbCommand = CreateCommand(connection, parameterValues);
            object result    = null;

            if (connection.DbConnection.State != ConnectionState.Open)
            {
                connection.Open();
            }

            if (executeMethod.Equals(nameof(ExecuteReader)))
            {
                try
                {
                    result = new MySQLRelationalDataReader(connection, dbCommand, new MySQLDataReader(((MySqlCommand)dbCommand).ExecuteReader() as MySqlDataReader));
                    return(result);
                }
                catch
                {
                    dbCommand.Dispose();
                    throw;
                }
            }

            return(base.Execute(connection, executeMethod, parameterValues, closeConnection));
        }
コード例 #2
0
ファイル: BatchExecutor.cs プロジェクト: lodejard/AllNetCore
        public virtual int Execute(
            IEnumerable <ModificationCommandBatch> commandBatches,
            IRelationalConnection connection)
        {
            var rowsAffected = 0;

            connection.Open();
            IDbContextTransaction startedTransaction = null;

            try
            {
                if (connection.CurrentTransaction == null)
                {
                    startedTransaction = connection.BeginTransaction();
                }

                foreach (var commandbatch in commandBatches)
                {
                    commandbatch.Execute(connection);
                    rowsAffected += commandbatch.ModificationCommands.Count;
                }

                startedTransaction?.Commit();
            }
            finally
            {
                startedTransaction?.Dispose();
                connection.Close();
            }

            return(rowsAffected);
        }
コード例 #3
0
        public virtual object Execute(
            IRelationalConnection connection,
            Func <object> action)
        {
            Check.NotNull(connection, nameof(connection));

            // TODO Deal with suppressing transactions etc.

            var connectionWasOpen = connection.DbConnection.State == ConnectionState.Open;

            if (!connectionWasOpen)
            {
                Logger.OpeningConnection(connection.ConnectionString);

                connection.Open();
            }

            try
            {
                return(action());
            }
            finally
            {
                if (!connectionWasOpen)
                {
                    Logger.ClosingConnection(connection.ConnectionString);

                    connection.Close();
                }
            }
        }
コード例 #4
0
        protected override void OpenConnection(IRelationalConnection connection)
        {
            connection.Open();

            ((SqliteConnection)connection.DbConnection).EnableExtensions();
            SpatialiteLoader.TryLoad(connection.DbConnection);
        }
コード例 #5
0
        public virtual IReadOnlyList <HistoryRow> GetAppliedMigrations()
        {
            var rows = new List <HistoryRow>();

            if (Exists())
            {
                _connection.Open();
                try
                {
                    using (var reader = _executor.ExecuteReader(_connection, GetAppliedMigrationsSql))
                    {
                        while (reader.Read())
                        {
                            rows.Add(new HistoryRow(reader.GetString(0), reader.GetString(1)));
                        }
                    }
                }
                finally
                {
                    _connection.Close();
                }
            }

            return(rows);
        }
コード例 #6
0
        public virtual int Execute(
            IEnumerable<ModificationCommandBatch> commandBatches,
            IRelationalConnection connection)
        {
            var rowsAffected = 0;
            connection.Open();
            IRelationalTransaction startedTransaction = null;
            try
            {
                if (connection.Transaction == null)
                {
                    startedTransaction = connection.BeginTransaction();
                }

                foreach (var commandbatch in commandBatches)
                {
                    commandbatch.Execute(connection);
                    rowsAffected += commandbatch.ModificationCommands.Count;
                }

                startedTransaction?.Commit();
            }
            finally
            {
                startedTransaction?.Dispose();
                connection.Close();
            }

            return rowsAffected;
        }
コード例 #7
0
        /// <summary>
        ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
        ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
        ///     any release. You should only use it directly in your code with extreme caution and knowing that
        ///     doing so can result in application failures when updating to a new Entity Framework Core release.
        /// </summary>
        public virtual void ExecuteNonQuery(
            IEnumerable <MigrationCommand> migrationCommands,
            IRelationalConnection connection)
        {
            Check.NotNull(migrationCommands, nameof(migrationCommands));
            Check.NotNull(connection, nameof(connection));

            var userTransaction = connection.CurrentTransaction;

            if (userTransaction is not null && migrationCommands.Any(x => x.TransactionSuppressed))
            {
                throw new NotSupportedException(RelationalStrings.TransactionSuppressedMigrationInUserTransaction);
            }

            using (new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled))
            {
                connection.Open();

                try
                {
                    IDbContextTransaction?transaction = null;

                    try
                    {
                        foreach (var command in migrationCommands)
                        {
                            if (transaction == null &&
                                !command.TransactionSuppressed &&
                                userTransaction is null)
                            {
                                transaction = connection.BeginTransaction();
                            }

                            if (transaction != null &&
                                command.TransactionSuppressed)
                            {
                                transaction.Commit();
                                transaction.Dispose();
                                transaction = null;
                            }

                            command.ExecuteNonQuery(connection);
                        }

                        transaction?.Commit();
                    }
                    finally
                    {
                        transaction?.Dispose();
                    }
                }
                finally
                {
                    connection.Close();
                }
            }
        }
コード例 #8
0
        /// <summary>
        ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
        ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
        ///     any release. You should only use it directly in your code with extreme caution and knowing that
        ///     doing so can result in application failures when updating to a new Entity Framework Core release.
        /// </summary>
        public virtual void ExecuteNonQuery(
            IEnumerable <MigrationCommand> migrationCommands,
            IRelationalConnection connection)
        {
            Check.NotNull(migrationCommands, nameof(migrationCommands));
            Check.NotNull(connection, nameof(connection));

            using (new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled))
            {
                connection.Open();

                try
                {
                    IDbContextTransaction transaction = null;

                    try
                    {
                        foreach (var command in migrationCommands)
                        {
                            if (transaction == null &&
                                !command.TransactionSuppressed)
                            {
                                transaction = connection.BeginTransaction();
                            }

                            if (transaction != null &&
                                command.TransactionSuppressed)
                            {
                                transaction.Commit();
                                transaction.Dispose();
                                transaction = null;
                            }

                            command.ExecuteNonQuery(connection);
                        }

                        transaction?.Commit();
                    }
                    finally
                    {
                        transaction?.Dispose();
                    }
                }
                finally
                {
                    connection.Close();
                }
            }
        }
 public void ExecuteNonQuery(IEnumerable <MigrationCommand> migrationCommands, IRelationalConnection connection)
 {
     connection.Open();
     try
     {
         foreach (var command in migrationCommands)
         {
             command.ExecuteNonQuery(connection);
         }
     }
     finally
     {
         connection.Close();
     }
 }
コード例 #10
0
 public override bool Exists()
 {
     try
     {
         return(_relationalConnection.Open());
     }
     catch (Exception)
     {
         return(false);
     }
     finally
     {
         _relationalConnection.Close();
     }
 }
 public async Task ExecuteNonQueryAsync(IEnumerable <MigrationCommand> migrationCommands, IRelationalConnection connection, CancellationToken cancellationToken = default)
 {
     connection.Open();
     try
     {
         foreach (var command in migrationCommands)
         {
             await command.ExecuteNonQueryAsync(connection);
         }
     }
     finally
     {
         connection.Close();
     }
 }
コード例 #12
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public virtual int Execute(
            IEnumerable <ModificationCommandBatch> commandBatches,
            IRelationalConnection connection)
        {
            var rowsAffected = 0;

            connection.Open();
            IDbContextTransaction startedTransaction = null;

            try
            {
                if (connection.CurrentTransaction == null)
                {
                    startedTransaction = connection.BeginTransaction();
                }

                foreach (var commandbatch in commandBatches)
                {
                    commandbatch.Execute(connection);
                    // Fixed Issue #1: DataReader conflicted when added multiple entities
                    try
                    {
                        lock (this)
                        {
                            var reader = (connection.DbConnection as MySqlConnection).Reader.LastOrDefault();
                            if (reader != null)
                            {
                                reader.Dispose();
                                (connection.DbConnection as MySqlConnection).Reader.Remove(reader);
                            }
                        }
                    }
                    catch
                    {
                    }
                    rowsAffected += commandbatch.ModificationCommands.Count;
                }

                startedTransaction?.Commit();
            }
            finally
            {
                startedTransaction?.Dispose();
                connection.Close();
            }

            return(rowsAffected);
        }
コード例 #13
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used 
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public virtual void ExecuteNonQuery(
            IEnumerable<MigrationCommand> migrationCommands,
            IRelationalConnection connection)
        {
            Check.NotNull(migrationCommands, nameof(migrationCommands));
            Check.NotNull(connection, nameof(connection));

            connection.Open();

            try
            {
                IDbContextTransaction transaction = null;

                try
                {
                    foreach (var command in migrationCommands)
                    {
                        if (transaction == null
                            && !command.TransactionSuppressed)
                        {
                            transaction = connection.BeginTransaction();
                        }

                        if (transaction != null
                            && command.TransactionSuppressed)
                        {
                            transaction.Commit();
                            transaction.Dispose();
                            transaction = null;
                        }

                        command.ExecuteNonQuery(connection);
                    }

                    transaction?.Commit();
                }
                finally
                {
                    transaction?.Dispose();
                }
            }
            finally
            {
                connection.Close();
            }
        }
コード例 #14
0
        public int Execute(
            IEnumerable <ModificationCommandBatch> commandBatches,
            IRelationalConnection connection)
        {
            var registrosAfetados = 0;

            connection.Open();
            IDbContextTransaction startedTransaction = null;

            try
            {
                if (connection.CurrentTransaction == null)
                {
                    startedTransaction = connection.BeginTransaction();
                }


                foreach (var commandbatch in commandBatches)
                {
                    commandbatch.Execute(connection);
                    registrosAfetados += commandbatch.ModificationCommands.Count;
                }
                startedTransaction?.Commit();
                startedTransaction?.Dispose();
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                try
                {
                    startedTransaction?.Rollback();
                    startedTransaction?.Dispose();
                }
                catch
                {
                    // if the connection was lost, rollback command will fail.  prefer to throw original exception in that case
                }
                throw;
            }
            finally
            {
                connection.Close();
            }

            return(registrosAfetados);
        }
コード例 #15
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used 
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public virtual int Execute(
            IEnumerable<ModificationCommandBatch> commandBatches,
            IRelationalConnection connection)
        {
            var rowsAffected = 0;
            connection.Open();
            IDbContextTransaction startedTransaction = null;
            try
            {
                if (connection.CurrentTransaction == null)
                {
                    startedTransaction = connection.BeginTransaction();
                }

                foreach (var commandbatch in commandBatches)
                {
                    commandbatch.Execute(connection);
                    // Fixed Issue #1: DataReader conflicted when added multiple entities
                    try
                    {
                        lock (this)
                        {
                            var reader = (connection.DbConnection as MySqlConnection).Reader.LastOrDefault();
                            if (reader != null)
                            {
                                reader.Dispose();
                                (connection.DbConnection as MySqlConnection).Reader.Remove(reader);
                            }
                        }
                    }
                    catch
                    {
                    }
                    rowsAffected += commandbatch.ModificationCommands.Count;
                }

                startedTransaction?.Commit();
            }
            finally
            {
                startedTransaction?.Dispose();
                connection.Close();
            }

            return rowsAffected;
        }
コード例 #16
0
        public int Execute(IEnumerable <ModificationCommandBatch> commandBatches, IRelationalConnection connection)
        {
            var recordAffecteds = 0;

            if (connection?.DbConnection?.State != System.Data.ConnectionState.Open)
            {
                connection.Open();
            }

            IDbContextTransaction currentTransaction = null;

            try
            {
                if (connection.CurrentTransaction == null)
                {
                    currentTransaction = connection.BeginTransaction();
                }

                foreach (var commandbatch in commandBatches)
                {
                    commandbatch.Execute(connection);
                    recordAffecteds += commandbatch.ModificationCommands.Count;
                }
                currentTransaction?.Commit();
                currentTransaction?.Dispose();
            }
            catch (Exception ex)
            {
                try
                {
                    currentTransaction?.Rollback();
                    currentTransaction?.Dispose();
                }
                catch
                {
                    //
                }
                throw ex;
            }
            finally
            {
                connection?.Close();
            }
            return(recordAffecteds);
        }
コード例 #17
0
        protected virtual object Execute(
            IRelationalConnection connection,
            Func <object> action)
        {
            Check.NotNull(connection, nameof(connection));

            // TODO Deal with suppressing transactions etc.
            connection.Open();

            try
            {
                return(action());
            }
            finally
            {
                connection.Close();
            }
        }
コード例 #18
0
        /// <summary>
        ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
        ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
        ///     any release. You should only use it directly in your code with extreme caution and knowing that
        ///     doing so can result in application failures when updating to a new Entity Framework Core release.
        /// </summary>
        public virtual int Execute(
            IEnumerable <ModificationCommandBatch> commandBatches,
            IRelationalConnection connection)
        {
            var rowsAffected = 0;
            IDbContextTransaction startedTransaction = null;

            try
            {
                if (connection.CurrentTransaction == null &&
                    (connection as ITransactionEnlistmentManager)?.EnlistedTransaction == null &&
                    Transaction.Current == null &&
                    CurrentContext.Context.Database.AutoTransactionsEnabled)
                {
                    startedTransaction = connection.BeginTransaction();
                }
                else
                {
                    connection.Open();
                }

                foreach (var batch in commandBatches)
                {
                    batch.Execute(connection);
                    rowsAffected += batch.ModificationCommands.Count;
                }

                startedTransaction?.Commit();
            }
            finally
            {
                if (startedTransaction != null)
                {
                    startedTransaction.Dispose();
                }
                else
                {
                    connection.Close();
                }
            }

            return(rowsAffected);
        }
コード例 #19
0
        /// <summary>
        ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
        ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
        ///     any release. You should only use it directly in your code with extreme caution and knowing that
        ///     doing so can result in application failures when updating to a new Entity Framework Core release.
        /// </summary>
        public virtual int Execute(
            IEnumerable <ModificationCommandBatch> commandBatches,
            IRelationalConnection connection)
        {
            var rowsAffected     = 0;
            var transaction      = connection.CurrentTransaction;
            var beganTransaction = false;
            var createdSavepoint = false;

            try
            {
                var transactionEnlistManager = connection as ITransactionEnlistmentManager;
                if (transaction == null &&
                    transactionEnlistManager?.EnlistedTransaction is null &&
                    transactionEnlistManager?.CurrentAmbientTransaction is null &&
                    CurrentContext.Context.Database.AutoTransactionsEnabled)
                {
                    transaction      = connection.BeginTransaction();
                    beganTransaction = true;
                }
                else
                {
                    connection.Open();

                    if (transaction?.SupportsSavepoints == true &&
                        CurrentContext.Context.Database.AutoSavepointsEnabled)
                    {
                        transaction.CreateSavepoint(SavepointName);
                        createdSavepoint = true;
                    }
                }

                foreach (var batch in commandBatches)
                {
                    batch.Execute(connection);
                    rowsAffected += batch.ModificationCommands.Count;
                }

                if (beganTransaction)
                {
                    transaction.Commit();
                }
            }
コード例 #20
0
        protected virtual T Execute <T>(
            [NotNull] IRelationalConnection connection,
            [NotNull] RelationalCommand command,
            [NotNull] Func <DbCommand, T> action)
        {
            // TODO Deal with suppressing transactions etc.
            connection.Open();

            try
            {
                using (var dbCommand = command.CreateCommand(connection))
                {
                    Logger.LogCommand(dbCommand);

                    return(action(dbCommand));
                }
            }
            finally
            {
                connection.Close();
            }
        }
コード例 #21
0
        public virtual int Execute(
            IEnumerable <ModificationCommandBatch> commandBatches,
            IRelationalConnection connection)
        {
            Check.NotNull(commandBatches, nameof(commandBatches));
            Check.NotNull(connection, nameof(connection));

            var rowsAffected = 0;

            connection.Open();
            IRelationalTransaction startedTransaction = null;

            try
            {
                if (connection.Transaction == null)
                {
                    startedTransaction = connection.BeginTransaction();
                }

                foreach (var commandbatch in commandBatches)
                {
                    commandbatch.Execute(
                        connection.Transaction,
                        _typeMapper,
                        _context,
                        Logger);
                    rowsAffected += commandbatch.ModificationCommands.Count;
                }

                startedTransaction?.Commit();
            }
            finally
            {
                startedTransaction?.Dispose();
                connection.Close();
            }

            return(rowsAffected);
        }
コード例 #22
0
        public static void ExecuteNonQuery(
            [NotNull] this IEnumerable <IRelationalCommand> commands,
            [NotNull] IRelationalConnection connection)
        {
            Check.NotNull(commands, nameof(commands));
            Check.NotNull(connection, nameof(connection));

            connection.Open();

            try
            {
                foreach (var command in commands)
                {
                    command.ExecuteNonQuery(
                        connection,
                        manageConnection: false);
                }
            }
            finally
            {
                connection.Close();
            }
        }
コード例 #23
0
        public virtual int Execute(
            IEnumerable<ModificationCommandBatch> commandBatches,
            IRelationalConnection connection)
        {
            Check.NotNull(commandBatches, nameof(commandBatches));
            Check.NotNull(connection, nameof(connection));

            var rowsAffected = 0;
            connection.Open();
            RelationalTransaction startedTransaction = null;
            try
            {
                if (connection.Transaction == null)
                {
                    startedTransaction = connection.BeginTransaction();
                }

                foreach (var commandbatch in commandBatches)
                {
                    rowsAffected += commandbatch.Execute(
                        connection.Transaction,
                        _typeMapper,
                        _context,
                        Logger);
                }

                startedTransaction?.Commit();
            }
            finally
            {
                startedTransaction?.Dispose();
                connection.Close();
            }

            return rowsAffected;
        }
コード例 #24
0
        public virtual void ExecuteNonQuery(
            IRelationalConnection connection,
            IEnumerable <RelationalCommand> relationalCommands)
        {
            Check.NotNull(connection, nameof(connection));
            Check.NotNull(relationalCommands, nameof(relationalCommands));

            connection.Open();

            try
            {
                foreach (var command in relationalCommands)
                {
                    Execute <object>(
                        connection,
                        command,
                        c => c.ExecuteNonQuery());
                }
            }
            finally
            {
                connection.Close();
            }
        }
コード例 #25
0
 protected virtual void OpenConnection(IRelationalConnection connection) => connection.Open();
コード例 #26
0
ファイル: BatchExecutor.cs プロジェクト: yangmaomao86/efcore
        /// <summary>
        ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
        ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
        ///     any release. You should only use it directly in your code with extreme caution and knowing that
        ///     doing so can result in application failures when updating to a new Entity Framework Core release.
        /// </summary>
        public virtual int Execute(
            IEnumerable <ModificationCommandBatch> commandBatches,
            IRelationalConnection connection)
        {
            var rowsAffected     = 0;
            var transaction      = connection.CurrentTransaction;
            var beganTransaction = false;
            var createdSavepoint = false;

            try
            {
                if (transaction == null &&
                    (connection as ITransactionEnlistmentManager)?.EnlistedTransaction == null &&
                    Transaction.Current == null &&
                    CurrentContext.Context.Database.AutoTransactionsEnabled)
                {
                    transaction      = connection.BeginTransaction();
                    beganTransaction = true;
                }
                else
                {
                    connection.Open();

                    if (transaction?.SupportsSavepoints == true &&
                        CurrentContext.Context.Database.AutoSavepointsEnabled)
                    {
                        transaction.CreateSavepoint(SavepointName);
                        createdSavepoint = true;
                    }
                }

                foreach (var batch in commandBatches)
                {
                    batch.Execute(connection);
                    rowsAffected += batch.ModificationCommands.Count;
                }

                if (beganTransaction)
                {
                    transaction.Commit();
                }
            }
            catch
            {
                if (createdSavepoint && connection.DbConnection.State == ConnectionState.Open)
                {
                    try
                    {
                        transaction.RollbackToSavepoint(SavepointName);
                    }
                    catch (Exception e)
                    {
                        UpdateLogger.BatchExecutorFailedToRollbackToSavepoint(CurrentContext.GetType(), e);
                    }
                }

                throw;
            }
            finally
            {
                if (beganTransaction)
                {
                    transaction.Dispose();
                }
                else
                {
                    if (createdSavepoint)
                    {
                        if (connection.DbConnection.State == ConnectionState.Open)
                        {
                            try
                            {
                                transaction.ReleaseSavepoint(SavepointName);
                            }
                            catch (Exception e)
                            {
                                UpdateLogger.BatchExecutorFailedToReleaseSavepoint(CurrentContext.GetType(), e);
                            }
                        }
                    }

                    connection.Close();
                }
            }

            return(rowsAffected);
        }
コード例 #27
0
                // TODO: Copy and paste base code again in 3.0.
                //       Then replace "RelationalDataReader" with "MySqlConverterRelationalDataReader".
                // TODO: Remove entire method in 3.1.
                //       Replace with overridden implementation of "CreateRelationalDataReader".
                /// <summary>
                /// Uses the same code as in it's base class, except for returning a
                /// ConverterRelationalDataReader instead of a RelationalDataReader.
                /// </summary>
                protected override object Execute(
                    IRelationalConnection connection,
                    DbCommandMethod executeMethod,
                    IReadOnlyDictionary <string, object> parameterValues)
                {
                    if (connection == null)
                    {
                        throw new ArgumentNullException(nameof(connection));
                    }

                    var dbCommand = CreateCommand(connection, parameterValues);

                    connection.Open();

                    var commandId = Guid.NewGuid();

                    var startTime = DateTimeOffset.UtcNow;
                    var stopwatch = Stopwatch.StartNew();

                    Logger.CommandExecuting(
                        dbCommand,
                        executeMethod,
                        commandId,
                        connection.ConnectionId,
                        async: false,
                        startTime: startTime);

                    object result;
                    var    readerOpen = false;

                    try
                    {
                        switch (executeMethod)
                        {
                        case DbCommandMethod.ExecuteNonQuery:
                        {
                            result = dbCommand.ExecuteNonQuery();

                            break;
                        }

                        case DbCommandMethod.ExecuteScalar:
                        {
                            result = dbCommand.ExecuteScalar();

                            break;
                        }

                        case DbCommandMethod.ExecuteReader:
                        {
                            result
                                = new MySqlConverterRelationalDataReader(
                                      connection,
                                      dbCommand,
                                      dbCommand.ExecuteReader(),
                                      commandId,
                                      Logger);
                            readerOpen = true;

                            break;
                        }

                        default:
                        {
                            throw new NotSupportedException();
                        }
                        }

                        Logger.CommandExecuted(
                            dbCommand,
                            executeMethod,
                            commandId,
                            connection.ConnectionId,
                            result,
                            false,
                            startTime,
                            stopwatch.Elapsed);
                    }
                    catch (Exception exception)
                    {
                        Logger.CommandError(
                            dbCommand,
                            executeMethod,
                            commandId,
                            connection.ConnectionId,
                            exception,
                            false,
                            startTime,
                            stopwatch.Elapsed);

                        throw;
                    }
                    finally
                    {
                        if (!readerOpen)
                        {
                            dbCommand.Parameters.Clear();
                            dbCommand.Dispose();
                            connection.Close();
                        }
                    }

                    return(result);
                }
コード例 #28
0
        /// <summary>
        ///    The method called by other methods on this type to execute synchronously.
        /// </summary>
        /// <param name="connection"> The connection to use. </param>
        /// <param name="executeMethod"> The method type. </param>
        /// <param name="parameterValues"> The parameter values. </param>
        /// <param name="logger"> The command logger. </param>
        /// <returns> The result of the execution. </returns>
        protected virtual object Execute(
            [NotNull] IRelationalConnection connection,
            DbCommandMethod executeMethod,
            [CanBeNull] IReadOnlyDictionary <string, object> parameterValues,
            [CanBeNull] IDiagnosticsLogger <DbLoggerCategory.Database.Command> logger)
        {
            Check.NotNull(connection, nameof(connection));

            var dbCommand = CreateCommand(connection, parameterValues);

            connection.Open();

            var commandId = Guid.NewGuid();

            var startTime = DateTimeOffset.UtcNow;
            var stopwatch = Stopwatch.StartNew();

            logger?.CommandExecuting(
                dbCommand,
                executeMethod,
                commandId,
                connection.ConnectionId,
                async: false,
                startTime: startTime);

            object result;
            var    readerOpen = false;

            try
            {
                switch (executeMethod)
                {
                case DbCommandMethod.ExecuteNonQuery:
                {
                    result = dbCommand.ExecuteNonQuery();

                    break;
                }

                case DbCommandMethod.ExecuteScalar:
                {
                    result = dbCommand.ExecuteScalar();

                    break;
                }

                case DbCommandMethod.ExecuteReader:
                {
                    result
                        = new RelationalDataReader(
                              connection,
                              dbCommand,
                              dbCommand.ExecuteReader(),
                              commandId,
                              logger);
                    readerOpen = true;

                    break;
                }

                default:
                {
                    throw new NotSupportedException();
                }
                }

                logger?.CommandExecuted(
                    dbCommand,
                    executeMethod,
                    commandId,
                    connection.ConnectionId,
                    result,
                    false,
                    startTime,
                    stopwatch.Elapsed);
            }
            catch (Exception exception)
            {
                logger?.CommandError(
                    dbCommand,
                    executeMethod,
                    commandId,
                    connection.ConnectionId,
                    exception,
                    false,
                    startTime,
                    stopwatch.Elapsed);

                throw;
            }
            finally
            {
                if (!readerOpen)
                {
                    dbCommand.Parameters.Clear();
                    dbCommand.Dispose();
                    connection.Close();
                }
            }

            return(result);
        }
コード例 #29
0
 public override void Create()
 {
     _connection.Open();
     _connection.Close();
 }
コード例 #30
0
        protected virtual object Execute(
            [NotNull] IRelationalConnection connection,
            [NotNull] string executeMethod,
            bool openConnection,
            bool closeConnection,
            [CanBeNull] IReadOnlyDictionary <string, object> parameterValues = null)
        {
            var dbCommand = CreateCommand(connection, parameterValues);

            WriteDiagnostic(
                RelationalDiagnostics.BeforeExecuteCommand,
                dbCommand,
                executeMethod);

            object result;

            if (openConnection)
            {
                connection.Open();
            }

            Stopwatch stopwatch = null;

            try
            {
                if (Logger.IsEnabled(LogLevel.Information))
                {
                    stopwatch = Stopwatch.StartNew();
                }

                switch (executeMethod)
                {
                case nameof(ExecuteNonQuery):
                {
                    using (dbCommand)
                    {
                        result = dbCommand.ExecuteNonQuery();
                    }

                    break;
                }

                case nameof(ExecuteScalar):
                {
                    using (dbCommand)
                    {
                        result = dbCommand.ExecuteScalar();
                    }

                    break;
                }

                case nameof(ExecuteReader):
                {
                    try
                    {
                        result
                            = new RelationalDataReader(
                                  openConnection ? connection : null,
                                  dbCommand,
                                  dbCommand.ExecuteReader());
                    }
                    catch
                    {
                        dbCommand.Dispose();

                        throw;
                    }

                    break;
                }

                default:
                {
                    throw new NotSupportedException();
                }
                }

                stopwatch?.Stop();

                Logger.LogCommandExecuted(dbCommand, stopwatch?.ElapsedMilliseconds);
            }
            catch (Exception exception)
            {
                stopwatch?.Stop();

                Logger.LogCommandExecuted(dbCommand, stopwatch?.ElapsedMilliseconds);

                DiagnosticSource
                .WriteCommandError(
                    dbCommand,
                    executeMethod,
                    async: false,
                    exception: exception);

                if (openConnection && !closeConnection)
                {
                    connection.Close();
                }

                throw;
            }
            finally
            {
                if (closeConnection)
                {
                    connection.Close();
                }
            }

            WriteDiagnostic(
                RelationalDiagnostics.AfterExecuteCommand,
                dbCommand,
                executeMethod);

            return(result);
        }
コード例 #31
0
        public virtual object Execute(
            IRelationalConnection connection,
            Func<object> action)
        {
            Check.NotNull(connection, nameof(connection));

            // TODO Deal with suppressing transactions etc.

            var connectionWasOpen = connection.DbConnection.State == ConnectionState.Open;
            if (!connectionWasOpen)
            {
                Logger.OpeningConnection(connection.ConnectionString);

                connection.Open();
            }

            try
            {
                return action();
            }
            finally
            {
                if (!connectionWasOpen)
                {
                    Logger.ClosingConnection(connection.ConnectionString);

                    connection.Close();
                }
            }
        }
コード例 #32
0
        protected override void OpenConnection(IRelationalConnection connection)
        {
            connection.Open();

            SpatialiteLoader.TryLoad(connection.DbConnection);
        }
        private async Task <object> ExecuteAsync(
            IOBehavior ioBehavior,
            [NotNull] IRelationalConnection connection,
            [NotNull] string executeMethod,
            [CanBeNull] IReadOnlyDictionary <string, object> parameterValues,
            bool openConnection,
            bool closeConnection,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            Check.NotNull(connection, nameof(connection));
            Check.NotEmpty(executeMethod, nameof(executeMethod));
            var    dbCommand = CreateCommand(connection, parameterValues);
            object result;

            if (openConnection)
            {
                if (ioBehavior == IOBehavior.Asynchronous)
                {
                    await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    connection.Open();
                }
            }

            cancellationToken.ThrowIfCancellationRequested();
            var mySqlConnection = connection as MySqlRelationalConnection;
            var locked          = false;

            try
            {
                if (ioBehavior == IOBehavior.Asynchronous)
                {
                    // ReSharper disable once PossibleNullReferenceException
                    await mySqlConnection.PoolingOpenAsync(cancellationToken).ConfigureAwait(false);

                    await mySqlConnection.Lock.WaitAsync(cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    // ReSharper disable once PossibleNullReferenceException
                    mySqlConnection.PoolingOpen();
                    mySqlConnection.Lock.Wait(cancellationToken);
                }
                locked = true;
                switch (executeMethod)
                {
                case nameof(ExecuteNonQuery):
                {
                    using (dbCommand)
                    {
                        if (ioBehavior == IOBehavior.Asynchronous)
                        {
                            result = await dbCommand.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
                        }
                        else
                        {
                            result = dbCommand.ExecuteNonQuery();
                        }
                    }
                    break;
                }

                case nameof(ExecuteScalar):
                {
                    using (dbCommand)
                    {
                        if (ioBehavior == IOBehavior.Asynchronous)
                        {
                            result = await dbCommand.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false);
                        }
                        else
                        {
                            result = dbCommand.ExecuteScalar();
                        }
                    }
                    break;
                }

                case nameof(ExecuteReader):
                {
                    try
                    {
                        MySqlDataReader dataReader;
                        if (ioBehavior == IOBehavior.Asynchronous)
                        {
                            dataReader = await dbCommand.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false) as MySqlDataReader;
                        }
                        else
                        {
                            dataReader = dbCommand.ExecuteReader() as MySqlDataReader;
                        }

                        result = new RelationalDataReader(openConnection ? connection : null, dbCommand,
                                                          new SynchronizedMySqlDataReader(dataReader, mySqlConnection));
                    }
                    catch (Exception)
                    {
                        dbCommand.Dispose();
                        throw;
                    }
                    break;
                }

                default:
                {
                    throw new NotSupportedException();
                }
                }
            }
            catch (Exception)
            {
                if (openConnection && !closeConnection)
                {
                    connection.Close();
                }
                throw;
            }
            finally
            {
                if (closeConnection)
                {
                    connection.Close();
                }
                if (locked && executeMethod != nameof(ExecuteReader))
                {
                    // if calling any other method, the command has finished executing and the lock can be released immediately
                    // ReSharper disable once PossibleNullReferenceException
                    mySqlConnection.Lock.Release();
                    mySqlConnection.PoolingClose();
                }
            }
            return(result);
        }
コード例 #34
0
        protected virtual object Execute(
            IRelationalConnection connection,
            Func<object> action)
        {
            Check.NotNull(connection, nameof(connection));

            // TODO Deal with suppressing transactions etc.
            connection.Open();

            try
            {
                return action();
            }
            finally
            {
                connection.Close();
            }
        }
コード例 #35
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        protected virtual object Execute(
            [NotNull] IRelationalConnection connection,
            [NotNull] string executeMethod,
            [CanBeNull] IReadOnlyDictionary <string, object> parameterValues,
            bool closeConnection = true)
        {
            Check.NotNull(connection, nameof(connection));
            Check.NotEmpty(executeMethod, nameof(executeMethod));

            var dbCommand = CreateCommand(connection, parameterValues);

            connection.Open();

            var startTimestamp = Stopwatch.GetTimestamp();
            var instanceId     = Guid.NewGuid();

            DiagnosticSource.WriteCommandBefore(
                dbCommand,
                executeMethod,
                instanceId,
                startTimestamp,
                async: false);

            object result;

            try
            {
                switch (executeMethod)
                {
                case nameof(ExecuteNonQuery):
                {
                    using (dbCommand)
                    {
                        result = dbCommand.ExecuteNonQuery();
                    }

                    break;
                }

                case nameof(ExecuteScalar):
                {
                    using (dbCommand)
                    {
                        result = dbCommand.ExecuteScalar();
                    }

                    break;
                }

                case nameof(ExecuteReader):
                {
                    try
                    {
                        result
                            = new RelationalDataReader(
                                  connection,
                                  dbCommand,
                                  dbCommand.ExecuteReader());
                    }
                    catch
                    {
                        dbCommand.Dispose();

                        throw;
                    }

                    break;
                }

                default:
                {
                    throw new NotSupportedException();
                }
                }

                var currentTimestamp = Stopwatch.GetTimestamp();

                Logger.LogCommandExecuted(dbCommand, startTimestamp, currentTimestamp);

                DiagnosticSource.WriteCommandAfter(
                    dbCommand,
                    executeMethod,
                    instanceId,
                    startTimestamp,
                    currentTimestamp);

                if (closeConnection)
                {
                    connection.Close();
                }
            }
            catch (Exception exception)
            {
                var currentTimestamp = Stopwatch.GetTimestamp();

                Logger.LogCommandExecuted(dbCommand, startTimestamp, currentTimestamp);

                DiagnosticSource.WriteCommandError(
                    dbCommand,
                    executeMethod,
                    instanceId,
                    startTimestamp,
                    currentTimestamp,
                    exception,
                    async: false);

                connection.Close();

                throw;
            }
            finally
            {
                dbCommand.Parameters.Clear();
            }

            return(result);
        }
                protected override object Execute(
                    IRelationalConnection connection,
                    DbCommandMethod executeMethod,
                    IReadOnlyDictionary <string, object> parameterValues)
                {
                    GaxPreconditions.CheckNotNull(connection, nameof(connection));

                    var dbCommand = CreateCommand(connection, parameterValues);

                    connection.Open();

                    var commandId = Guid.NewGuid();
                    var startTime = DateTimeOffset.UtcNow;
                    var stopwatch = Stopwatch.StartNew();

                    Logger.CommandExecuting(
                        dbCommand,
                        executeMethod,
                        commandId,
                        connection.ConnectionId,
                        false,
                        startTime);

                    object result;
                    var    readerOpen = false;

                    try
                    {
                        //Note that adds/updates/deletes get intercepted at the
                        //modificationcommandbatch level and normally do not get translated
                        //into ADO.NET commands here.  However, there are features in EF that
                        //allow raw DML to be sent to the database which end up here and we need
                        //to create the proper command and throw a useful exception.
                        //TODO(benwu): there may be a way we can accept a non-DML text version of updates
                        // but we'll need to send it thru detailed design review.
                        switch (executeMethod)
                        {
                        case DbCommandMethod.ExecuteNonQuery:
                        {
                            result = dbCommand.ExecuteNonQuery();

                            break;
                        }

                        case DbCommandMethod.ExecuteScalar:
                        {
                            result = dbCommand.ExecuteScalar();

                            break;
                        }

                        case DbCommandMethod.ExecuteReader:
                        {
                            result
                                = new RelationalDataReader(
                                      connection,
                                      dbCommand,
                                      dbCommand.ExecuteReader(),
                                      commandId,
                                      Logger);

                            readerOpen = true;

                            break;
                        }

                        default:
                        {
                            throw new NotSupportedException();
                        }
                        }

                        Logger.CommandExecuted(
                            dbCommand,
                            executeMethod,
                            commandId,
                            connection.ConnectionId,
                            result,
                            false,
                            startTime,
                            stopwatch.Elapsed);
                    }
                    catch (Exception exception)
                    {
                        Logger.CommandError(
                            dbCommand,
                            executeMethod,
                            commandId,
                            connection.ConnectionId,
                            exception,
                            false,
                            startTime,
                            stopwatch.Elapsed);

                        throw;
                    }
                    finally
                    {
                        if (!readerOpen)
                        {
                            dbCommand.Dispose();
                            connection.Close();
                        }

                        dbCommand.Parameters.Clear();
                    }

                    return(result);
                }