public void GetDbTransaction_returns_the_DbTransaction()
        {
            var dbConnection = new FakeDbConnection(ConnectionString);
            var dbTransaction = new FakeDbTransaction(dbConnection);

            var connection = new FakeRelationalConnection(
                CreateOptions(new FakeRelationalOptionsExtension { Connection = dbConnection }));

            var transaction = new RelationalTransaction(
                connection,
                dbTransaction,
                new ListLogger(new List<Tuple<LogLevel, string>>()),
                false);

            Assert.Equal(dbTransaction, transaction.GetDbTransaction());
        }
        public async Task Connection_is_opened_and_closed_by_using_transaction_async()
        {
            using (var connection = new FakeRelationalConnection(
                CreateOptions(new FakeRelationalOptionsExtension { ConnectionString = "Database=FrodoLives" })))
            {
                Assert.Equal(0, connection.DbConnections.Count);

                var transaction = await connection.BeginTransactionAsync();

                Assert.Equal(1, connection.DbConnections.Count);
                var dbConnection = connection.DbConnections[0];

                Assert.Equal(1, dbConnection.DbTransactions.Count);
                var dbTransaction = dbConnection.DbTransactions[0];

                Assert.Equal(1, dbConnection.OpenCount);
                Assert.Equal(0, dbConnection.CloseCount);
                Assert.Equal(IsolationLevel.Unspecified, dbTransaction.IsolationLevel);

                transaction.Dispose();

                Assert.Equal(1, dbConnection.OpenCount);
                Assert.Equal(1, dbConnection.CloseCount);
            }
        }
        public void Existing_connection_is_not_disposed_even_after_being_opened_and_closed()
        {
            var dbConnection = new FakeDbConnection("Database=FrodoLives");
            var connection = new FakeRelationalConnection(
                CreateOptions(new FakeRelationalOptionsExtension { Connection = dbConnection }));

            Assert.Equal(0, connection.DbConnections.Count);
            Assert.Same(dbConnection, connection.DbConnection);

            connection.Open();
            connection.Close();
            connection.Dispose();

            Assert.Equal(1, dbConnection.OpenCount);
            Assert.Equal(1, dbConnection.CloseCount);
            Assert.Equal(0, dbConnection.DisposeCount);

            Assert.Equal(0, connection.DbConnections.Count);
            Assert.Same(dbConnection, connection.DbConnection);

            connection.Open();
            connection.Close();
            connection.Dispose();

            Assert.Equal(2, dbConnection.OpenCount);
            Assert.Equal(2, dbConnection.CloseCount);
            Assert.Equal(0, dbConnection.DisposeCount);
        }
        public void Existing_connection_can_be_opened_and_closed_externally()
        {
            var dbConnection = new FakeDbConnection(
                "Database=FrodoLives",
                state: ConnectionState.Closed);

            using (var connection = new FakeRelationalConnection(
                CreateOptions(new FakeRelationalOptionsExtension { Connection = dbConnection })))
            {
                Assert.Equal(0, connection.DbConnections.Count);

                connection.Open();

                Assert.Equal(0, connection.DbConnections.Count);

                Assert.Equal(1, dbConnection.OpenCount);

                connection.Close();

                Assert.Equal(1, dbConnection.OpenCount);
                Assert.Equal(1, dbConnection.CloseCount);

                dbConnection.SetState(ConnectionState.Open);

                connection.Open();

                Assert.Equal(1, dbConnection.OpenCount);
                Assert.Equal(1, dbConnection.CloseCount);

                connection.Close();

                Assert.Equal(1, dbConnection.OpenCount);
                Assert.Equal(1, dbConnection.CloseCount);

                dbConnection.SetState(ConnectionState.Closed);

                connection.Open();

                Assert.Equal(2, dbConnection.OpenCount);
                Assert.Equal(1, dbConnection.CloseCount);

                connection.Close();

                Assert.Equal(2, dbConnection.OpenCount);
                Assert.Equal(2, dbConnection.CloseCount);
            }
        }
        public async Task Reports_command_diagnostic_on_exception(
            Delegate commandDelegate,
            string diagnosticName,
            bool async)
        {
            var exception = new InvalidOperationException();

            var fakeDbConnection = new FakeDbConnection(
                ConnectionString,
                new FakeCommandExecutor(
                    c => { throw exception; },
                    c => { throw exception; },
                    (c, cb) => { throw exception; },
                    (c, ct) => { throw exception; },
                    (c, ct) => { throw exception; },
                    (c, cb, ct) => { throw exception; }));

            var optionsExtension = new FakeRelationalOptionsExtension { Connection = fakeDbConnection };

            var options = CreateOptions(optionsExtension);

            var diagnostic = new List<Tuple<string, object>>();

            var fakeConnection = new FakeRelationalConnection(options);

            var relationalCommand = CreateRelationalCommand(
                diagnosticSource: new ListDiagnosticSource(diagnostic),
                parameters: new[]
                {
                    new TypeMappedRelationalParameter("FirstInvariant", "FirstParameter", new RelationalTypeMapping("int", typeof(int), DbType.Int32), false)
                });

            var parameterValues = new Dictionary<string, object>
            {
                { "FirstInvariant", 17 }
            };

            if (async)
            {
                await Assert.ThrowsAsync<InvalidOperationException>(
                    async ()
                        => await ((CommandFunc)commandDelegate)(fakeConnection, relationalCommand, parameterValues, true));
            }
            else
            {
                Assert.Throws<InvalidOperationException>(()
                    => ((CommandAction)commandDelegate)(fakeConnection, relationalCommand, parameterValues, true));
            }

            Assert.Equal(2, diagnostic.Count);
            Assert.Equal(RelationalDiagnostics.BeforeExecuteCommand, diagnostic[0].Item1);
            Assert.Equal(RelationalDiagnostics.CommandExecutionError, diagnostic[1].Item1);

            var beforeData = (RelationalDiagnosticSourceBeforeMessage)diagnostic[0].Item2;
            var afterData = (RelationalDiagnosticSourceAfterMessage)diagnostic[1].Item2;

            Assert.Equal(fakeDbConnection.DbCommands[0], beforeData.Command);
            Assert.Equal(fakeDbConnection.DbCommands[0], afterData.Command);

            Assert.Equal(diagnosticName, beforeData.ExecuteMethod);
            Assert.Equal(diagnosticName, afterData.ExecuteMethod);

            Assert.Equal(async, beforeData.IsAsync);
            Assert.Equal(async, afterData.IsAsync);

            Assert.Equal(exception, afterData.Exception);
        }
 public void Throws_if_CommandTimeout_out_of_range()
 {
     using (var connection = new FakeRelationalConnection(
         CreateOptions(new FakeRelationalOptionsExtension { ConnectionString = "Database=FrodoLives" })))
     {
         Assert.Throws<ArgumentException>(
             () => connection.CommandTimeout = -1);
     }
 }
 public void Can_create_new_connection_with_CommandTimeout()
 {
     using (var connection = new FakeRelationalConnection(
         CreateOptions(new FakeRelationalOptionsExtension
         {
             ConnectionString = "Database=FrodoLives",
             CommandTimeout = 99
         })))
     {
         Assert.Equal(99, connection.CommandTimeout);
     }
 }
        public void Can_use_existing_transaction()
        {
            var dbConnection = new FakeDbConnection("Database=FrodoLives");

            var dbTransaction = dbConnection.BeginTransaction(IsolationLevel.Unspecified);

            using (var connection = new FakeRelationalConnection(
                CreateOptions(new FakeRelationalOptionsExtension { Connection = dbConnection })))
            {
                using (connection.UseTransaction(dbTransaction))
                {
                    Assert.Equal(dbTransaction, connection.CurrentTransaction.GetDbTransaction());
                }
            }
        }
        public void Lazy_connection_is_recreated_if_used_again_after_being_disposed()
        {
            var connection = new FakeRelationalConnection(
                CreateOptions(new FakeRelationalOptionsExtension { ConnectionString = "Database=FrodoLives" }));

            Assert.Equal(0, connection.DbConnections.Count);
            var dbConnection = (FakeDbConnection)connection.DbConnection;
            Assert.Equal(1, connection.DbConnections.Count);

            connection.Open();

#if NET451
            // On CoreCLR, DbConnection.Dispose() calls DbConnection.Close()
            connection.Close();
#endif

            connection.Dispose();

            Assert.Equal(1, dbConnection.OpenCount);
            Assert.Equal(1, dbConnection.CloseCount);
            Assert.Equal(1, dbConnection.DisposeCount);

            Assert.Equal(1, connection.DbConnections.Count);
            dbConnection = (FakeDbConnection)connection.DbConnection;
            Assert.Equal(2, connection.DbConnections.Count);

            connection.Open();

#if NET451
            connection.Close();
#endif

            connection.Dispose();

            Assert.Equal(1, dbConnection.OpenCount);
            Assert.Equal(1, dbConnection.CloseCount);
            Assert.Equal(1, dbConnection.DisposeCount);
        }
        public async Task Lazy_connection_is_async_opened_and_closed_when_necessary()
        {
            using (var connection = new FakeRelationalConnection(
                CreateOptions(new FakeRelationalOptionsExtension { ConnectionString = "Database=FrodoLives" })))
            {
                Assert.Equal(0, connection.DbConnections.Count);

                var cancellationToken = new CancellationTokenSource().Token;
                await connection.OpenAsync(cancellationToken);

                Assert.Equal(1, connection.DbConnections.Count);

                var dbConnection = connection.DbConnections[0];
                Assert.Equal(1, dbConnection.OpenAsyncCount);

                await connection.OpenAsync(cancellationToken);
                await connection.OpenAsync(cancellationToken);

                Assert.Equal(1, dbConnection.OpenAsyncCount);

                connection.Close();
                connection.Close();

                Assert.Equal(1, dbConnection.OpenAsyncCount);
                Assert.Equal(0, dbConnection.CloseCount);

                connection.Close();

                Assert.Equal(1, dbConnection.OpenAsyncCount);
                Assert.Equal(1, dbConnection.CloseCount);

                await connection.OpenAsync(cancellationToken);

                Assert.Equal(2, dbConnection.OpenAsyncCount);

                connection.Close();

                Assert.Equal(2, dbConnection.OpenAsyncCount);
                Assert.Equal(2, dbConnection.CloseCount);
            }
        }
        public void Lazy_connection_is_opened_and_closed_when_necessary()
        {
            using (var connection = new FakeRelationalConnection(
                CreateOptions(new FakeRelationalOptionsExtension { ConnectionString = "Database=FrodoLives" })))
            {
                Assert.Equal(0, connection.DbConnections.Count);

                connection.Open();

                Assert.Equal(1, connection.DbConnections.Count);

                var dbConnection = connection.DbConnections[0];
                Assert.Equal(1, dbConnection.OpenCount);

                connection.Open();
                connection.Open();

                Assert.Equal(1, dbConnection.OpenCount);

                connection.Close();
                connection.Close();

                Assert.Equal(1, dbConnection.OpenCount);
                Assert.Equal(0, dbConnection.CloseCount);

                connection.Close();

                Assert.Equal(1, dbConnection.OpenCount);
                Assert.Equal(1, dbConnection.CloseCount);

                connection.Open();

                Assert.Equal(2, dbConnection.OpenCount);

                connection.Close();

                Assert.Equal(2, dbConnection.OpenCount);
                Assert.Equal(2, dbConnection.CloseCount);
            }
        }
        public void Can_create_new_connection_lazily_using_given_connection_string()
        {
            using (var connection = new FakeRelationalConnection(
                CreateOptions(new FakeRelationalOptionsExtension { ConnectionString = "Database=FrodoLives" })))
            {
                Assert.Equal(0, connection.DbConnections.Count);

                var dbConnection = connection.DbConnection;

                Assert.Equal(1, connection.DbConnections.Count);
                Assert.Equal("Database=FrodoLives", dbConnection.ConnectionString);
            }
        }
        public async Task Reports_command_diagnostic(
            Delegate commandDelegate,
            string diagnosticName,
            bool async)
        {
            var options = CreateOptions();

            var fakeConnection = new FakeRelationalConnection(options);

            var diagnostic = new List<Tuple<string, object>>();

            var relationalCommand = CreateRelationalCommand(
                diagnosticSource: new ListDiagnosticSource(diagnostic),
                parameters: new[]
                {
                    new TypeMappedRelationalParameter("FirstInvariant", "FirstParameter", new RelationalTypeMapping("int", typeof(int), DbType.Int32), false)
                });

            var parameterValues = new Dictionary<string, object>
            {
                { "FirstInvariant", 17 }
            };

            if (async)
            {
                await ((CommandFunc)commandDelegate)(fakeConnection, relationalCommand, parameterValues, true);
            }
            else
            {
                ((CommandAction)commandDelegate)(fakeConnection, relationalCommand, parameterValues, true);
            }

            Assert.Equal(2, diagnostic.Count);
            Assert.Equal(RelationalDiagnostics.BeforeExecuteCommand, diagnostic[0].Item1);
            Assert.Equal(RelationalDiagnostics.AfterExecuteCommand, diagnostic[1].Item1);

            var beforeData = (RelationalDiagnosticSourceBeforeMessage)diagnostic[0].Item2;
            var afterData = (RelationalDiagnosticSourceAfterMessage)diagnostic[1].Item2;

            Assert.Equal(fakeConnection.DbConnections[0].DbCommands[0], beforeData.Command);
            Assert.Equal(fakeConnection.DbConnections[0].DbCommands[0], afterData.Command);

            Assert.Equal(diagnosticName, beforeData.ExecuteMethod);
            Assert.Equal(diagnosticName, afterData.ExecuteMethod);

            Assert.Equal(async, beforeData.IsAsync);
            Assert.Equal(async, afterData.IsAsync);
        }
        public async Task Logs_commands_parameter_values(
            Delegate commandDelegate,
            string diagnosticName,
            bool async)
        {
            var optionsExtension = new FakeRelationalOptionsExtension { ConnectionString = ConnectionString };

            var options = CreateOptions(optionsExtension, logParameters: true);

            var log = new List<Tuple<LogLevel, string>>();

            var fakeConnection = new FakeRelationalConnection(options);

            var relationalCommand = CreateRelationalCommand(
                logger: new SensitiveDataLogger<RelationalCommand>(
                    new ListLogger<RelationalCommand>(log),
                    options),
                commandText: "Logged Command",
                parameters: new[]
                {
                    new TypeMappedRelationalParameter("FirstInvariant", "FirstParameter", new RelationalTypeMapping("int", typeof(int), DbType.Int32), false)
                });

            var parameterValues = new Dictionary<string, object>
            {
                { "FirstInvariant", 17 }
            };

            if (async)
            {
                await ((CommandFunc)commandDelegate)(fakeConnection, relationalCommand, parameterValues, true);
            }
            else
            {
                ((CommandAction)commandDelegate)(fakeConnection, relationalCommand, parameterValues, true);
            }

            Assert.Equal(2, log.Count);
            Assert.Equal(LogLevel.Warning, log[0].Item1);
            Assert.Equal(CoreStrings.SensitiveDataLoggingEnabled, log[0].Item2);

            Assert.Equal(LogLevel.Information, log[1].Item1);
            Assert.EndsWith(
                @"ms) [Parameters=[FirstParameter='17'], CommandType='0', CommandTimeout='30']
Logged Command",
                log[1].Item2);
        }
        public async Task Does_not_close_unmanaged_connections_on_exception(
            Delegate commandDelegate,
            string telemetryName,
            bool async)
        {
            var exception = new InvalidOperationException();

            var fakeDbConnection = new FakeDbConnection(
                ConnectionString,
                new FakeCommandExecutor(
                    c => { throw exception; },
                    c => { throw exception; },
                    (c, cb) => { throw exception; },
                    (c, ct) => { throw exception; },
                    (c, ct) => { throw exception; },
                    (c, cb, ct) => { throw exception; }));

            var optionsExtension = new FakeRelationalOptionsExtension { Connection = fakeDbConnection };

            var options = CreateOptions(optionsExtension);

            var fakeConnection = new FakeRelationalConnection(options);

            var relationalCommand = CreateRelationalCommand();

            if (async)
            {
                await Assert.ThrowsAsync<InvalidOperationException>(
                    async ()
                        => await ((CommandFunc)commandDelegate)(fakeConnection, relationalCommand, null, false));

                Assert.Equal(0, fakeDbConnection.OpenAsyncCount);
            }
            else
            {
                Assert.Throws<InvalidOperationException>(()
                    => ((CommandAction)commandDelegate)(fakeConnection, relationalCommand, null, false));

                Assert.Equal(0, fakeDbConnection.OpenCount);
            }

            Assert.Equal(0, fakeDbConnection.CloseCount);
        }
        public async Task Transaction_can_begin_with_isolation_level_async()
        {
            using (var connection = new FakeRelationalConnection(
                CreateOptions(new FakeRelationalOptionsExtension { ConnectionString = "Database=FrodoLives" })))
            {
                Assert.Equal(0, connection.DbConnections.Count);

                using (var transaction = await connection.BeginTransactionAsync(IsolationLevel.Chaos))
                {
                    Assert.Equal(1, connection.DbConnections.Count);
                    var dbConnection = connection.DbConnections[0];

                    Assert.Equal(1, dbConnection.DbTransactions.Count);
                    var dbTransaction = dbConnection.DbTransactions[0];

                    Assert.Equal(IsolationLevel.Chaos, dbTransaction.IsolationLevel);
                }
            }
        }
        public void Current_transaction_is_disposed_when_connection_is_disposed()
        {
            var connection = new FakeRelationalConnection(
                CreateOptions(
                    new FakeRelationalOptionsExtension { ConnectionString = "Database=FrodoLives" }));

            Assert.Equal(0, connection.DbConnections.Count);

            var transaction = connection.BeginTransaction();

            Assert.Equal(1, connection.DbConnections.Count);
            var dbConnection = connection.DbConnections[0];

            Assert.Equal(1, dbConnection.DbTransactions.Count);
            var dbTransaction = dbConnection.DbTransactions[0];

            connection.Dispose();

            Assert.Equal(1, dbTransaction.DisposeCount);
            Assert.Null(connection.CurrentTransaction);
        }
        public void Lazy_connection_is_not_created_just_so_it_can_be_disposed()
        {
            var connection = new FakeRelationalConnection(
                CreateOptions(new FakeRelationalOptionsExtension { ConnectionString = "Database=FrodoLives" }));

            connection.Dispose();

            Assert.Equal(0, connection.DbConnections.Count);
        }
        public void Rollback_calls_rollback_on_DbTransaction()
        {
            using (var connection = new FakeRelationalConnection(
                CreateOptions(new FakeRelationalOptionsExtension { ConnectionString = "Database=FrodoLives" })))
            {
                Assert.Equal(0, connection.DbConnections.Count);

                using (var transaction = connection.BeginTransaction())
                {
                    Assert.Equal(1, connection.DbConnections.Count);
                    var dbConnection = connection.DbConnections[0];

                    Assert.Equal(1, dbConnection.DbTransactions.Count);
                    var dbTransaction = dbConnection.DbTransactions[0];

                    connection.RollbackTransaction();

                    Assert.Equal(1, dbTransaction.RollbackCount);
                }
            }
        }
        public void Can_create_new_connection_from_exsting_DbConnection()
        {
            var dbConnection = new FakeDbConnection("Database=FrodoLives");

            using (var connection = new FakeRelationalConnection(
                CreateOptions(new FakeRelationalOptionsExtension { Connection = dbConnection })))
            {
                Assert.Equal(0, connection.DbConnections.Count);

                Assert.Same(dbConnection, connection.DbConnection);

                Assert.Equal(0, connection.DbConnections.Count);
            }
        }
        public void Can_set_CommandTimeout()
        {
            using (var connection = new FakeRelationalConnection(
                CreateOptions(new FakeRelationalOptionsExtension { ConnectionString = "Database=FrodoLives" })))
            {
                connection.CommandTimeout = 88;

                Assert.Equal(88, connection.CommandTimeout);
            }
        }
        public void Existing_connection_is_opened_and_closed_when_necessary()
        {
            var dbConnection = new FakeDbConnection("Database=FrodoLives");

            using (var connection = new FakeRelationalConnection(
                CreateOptions(new FakeRelationalOptionsExtension { Connection = dbConnection })))
            {
                Assert.Equal(0, connection.DbConnections.Count);

                connection.Open();

                Assert.Equal(0, connection.DbConnections.Count);

                Assert.Equal(1, dbConnection.OpenCount);

                connection.Open();
                connection.Open();

                Assert.Equal(1, dbConnection.OpenCount);

                connection.Close();
                connection.Close();

                Assert.Equal(1, dbConnection.OpenCount);
                Assert.Equal(0, dbConnection.CloseCount);

                connection.Close();

                Assert.Equal(1, dbConnection.OpenCount);
                Assert.Equal(1, dbConnection.CloseCount);

                connection.Open();

                Assert.Equal(2, dbConnection.OpenCount);

                connection.Close();

                Assert.Equal(2, dbConnection.OpenCount);
                Assert.Equal(2, dbConnection.CloseCount);
            }
        }
        public void Throws_when_rollback_is_called_without_active_transaction()
        {
            using (var connection = new FakeRelationalConnection(
                CreateOptions(new FakeRelationalOptionsExtension { ConnectionString = "Database=FrodoLives" })))
            {
                Assert.Equal(0, connection.DbConnections.Count);

                Assert.Equal(
                    RelationalStrings.NoActiveTransaction,
                    Assert.Throws<InvalidOperationException>(
                        () => connection.RollbackTransaction()).Message);
            }
        }
        public void Existing_connection_can_start_in_opened_state()
        {
            var dbConnection = new FakeDbConnection(
                "Database=FrodoLives",
                state: ConnectionState.Open);

            using (var connection = new FakeRelationalConnection(
                CreateOptions(new FakeRelationalOptionsExtension { Connection = dbConnection })))
            {
                Assert.Equal(0, connection.DbConnections.Count);

                connection.Open();

                Assert.Equal(0, connection.DbConnections.Count);

                Assert.Equal(0, dbConnection.OpenCount);

                connection.Open();
                connection.Open();

                Assert.Equal(0, dbConnection.OpenCount);

                connection.Close();
                connection.Close();

                Assert.Equal(0, dbConnection.OpenCount);
                Assert.Equal(0, dbConnection.CloseCount);

                connection.Close();

                Assert.Equal(0, dbConnection.OpenCount);
                Assert.Equal(0, dbConnection.CloseCount);

                connection.Open();

                Assert.Equal(0, dbConnection.OpenCount);

                connection.Close();

                Assert.Equal(0, dbConnection.OpenCount);
                Assert.Equal(0, dbConnection.CloseCount);
            }
        }