示例#1
0
        public void NestedWrapper_DeleteChildAndParent_AllStatementsPersist()
        {
            DbHelper.DeleteDb("test.db");
            var connection = DbHelper.GetDbConnection("test.db");

            using (var wrapper = new DbConnectionWrapper(connection))
            {
                wrapper.Connection.Execute("CREATE TABLE Parent (ID INTEGER PRIMARY KEY)");
                wrapper.Connection.Execute("CREATE TABLE Child (ID INTEGER PRIMARY KEY)");
                wrapper.Connection.Execute("INSERT INTO Parent(ID) VALUES (1)");
                wrapper.Connection.Execute("INSERT INTO Child(ID) VALUES (1)");
            }

            connection = DbHelper.GetDbConnection("test.db");
            int childRows, parentRows;

            using (var wrapper = new DbConnectionWrapper(connection))
            {
                wrapper.StartTransaction();

                childRows = wrapper.Connection.Execute("DELETE FROM Child WHERE ID = 1");

                using (wrapper.AddScope())
                {
                    parentRows = wrapper.Connection.Execute("DELETE FROM Parent WHERE ID = 1");
                }

                wrapper.Commit();
            }

            Assert.Equal(1, childRows);
            Assert.Equal(1, parentRows);
        }
        /// <summary>
        /// Clones a new DbConnection supported by this provider.
        /// </summary>
        /// <param name="connection">The connection to clone.</param>
        /// <returns>A new DbConnection.</returns>
        public override IDbConnection CloneDbConnection(IDbConnection connection)
        {
            if (connection == null)
            {
                throw new ArgumentNullException("connection");
            }

            // clone the inner connection
            var innerConnection       = GetInnerConnection(connection);
            var innerProvider         = InsightDbProvider.For(innerConnection);
            var clonedInnerConnection = innerProvider.CloneDbConnection(innerConnection);

            var wrapper = new DbConnectionWrapper();

            try
            {
                var clone = (DbConnectionWrapper)wrapper;
                clone.InnerConnection = (DbConnection)clonedInnerConnection;
                return(clone);
            }
            catch
            {
                wrapper.Dispose();
                throw;
            }
        }
示例#3
0
        public IDbConnection GetDbConnection()
        {
            // Generate a random db name
            var dbName = "test-" + new string(chars.OrderBy(c => random.Next()).ToArray());

            var connectionString = $"Server=(localdb)\\mssqllocaldb;Integrated Security=true;MultipleActiveResultSets=true;Database={dbName}";

            // Ensure the database exists
            EnsureDatabase.For.SqlDatabase(connectionString);

            var upgrader = DeployChanges.To
                           .SqlDatabase(connectionString)
                           .WithScriptsEmbeddedInAssembly(typeof(Person).GetTypeInfo().Assembly)
                           .LogToConsole()
                           .Build();

            var upgradeResult = upgrader.PerformUpgrade();

            var sqlConnection          = new SqlConnection(connectionString);
            var autoDroppingConnection = new DbConnectionWrapper(sqlConnection, () =>
            {
                // Drop the database when we're done with it
                DropDatabase.For.SqlDatabase(connectionString);
            });

            return(autoDroppingConnection);
        }
示例#4
0
 public void TestInsertWithIDReturn_ScopeIdentity_SQL()
 {
     using (DbConnectionWrapper c = Connection().OpenWithTransaction())
     {
         var beer = Beer.GetSample();
         c.InsertSql("INSERT INTO[dbo].[Beer] ([Name], [Style]) VALUES(@Name , @Style ); SELECT SCOPE_IDENTITY() AS [Id]", beer);
         beer.VerifySample();
     }
 }
#pragma warning restore CA2213

        /// <summary>
        /// Initializes a new instance of the NpgsqlCommandWithRecordsets class.
        /// </summary>
        /// <param name="connection">The connection to use.</param>
        /// <param name="innerCommand">The inner command to wrap.</param>
        public NpgsqlCommandWithRecordsets(DbConnectionWrapper connection, DbCommand innerCommand) : base(connection, innerCommand)
        {
            if (connection == null)
            {
                throw new ArgumentNullException("connection");
            }

            _innerConnection = (NpgsqlConnection)connection.InnerConnection;
        }
示例#6
0
        private static DbConnection CreateConnection(string nameOrConnectionString, string providerInvariantName)
        {
            string       connectionString = NormalizeConnectionString(nameOrConnectionString);
            DbConnection connection       = DbProviderFactories.GetFactory(providerInvariantName).CreateConnection();

            connection.ConnectionString = connectionString;
            connection = DbConnectionWrapper.WrapConnection(providerInvariantName, connection, WrapperProviders);
            return(connection);
        }
        public CustomDbContext()
        {
            _connection = new SqlConnection(DbConfig.ConnectionString);
            _connection.Open();
            _transaction = _connection.BeginTransaction();

            // the connection is managed externally in this case because WE commit and dispose it
            var connectionWrapper = new DbConnectionWrapper(_connection, _transaction, managedExternally: true);

            AsyncLocalDbConnection.Value = connectionWrapper;
        }
示例#8
0
        public CustomDbContext()
        {
            _connection = new SqlConnection(DbConfig.ConnectionString);
            _connection.Open();
            _transaction = _connection.BeginTransaction();

            // the connection is managed externally in this case because WE commit and dispose it
            var connectionWrapper = new DbConnectionWrapper(_connection, _transaction, managedExternally: true);

            CallContext.LogicalSetData(CustomDbContextKey, connectionWrapper);
        }
示例#9
0
        public void SingleLevelWrapper_UncomittedTransactionRolledBack()
        {
            DbHelper.DeleteDb("test.db");
            var connection = DbHelper.GetDbConnection("test.db");

            using (var wrapper = new DbConnectionWrapper(connection))
            {
                wrapper.Connection.Execute("CREATE TABLE TestTable (ID INTEGER PRIMARY KEY)");
                // Uncomitted
            }

            Assert.False(DbHelper.TableExists("TestTable"));
        }
示例#10
0
        public void SingleLevelWrapper_ComittedStatementsPersist()
        {
            DbHelper.DeleteDb("test.db");
            var connection = DbHelper.GetDbConnection("test.db");

            using (var wrapper = new DbConnectionWrapper(connection))
            {
                wrapper.Connection.Execute("CREATE TABLE TestTable (ID INTEGER PRIMARY KEY)");
                wrapper.Commit();
            }

            Assert.True(DbHelper.TableExists("TestTable", "test.db"));
        }
示例#11
0
        public void SingleLevelWrapper_CorrectlyDisposed()
        {
            DbHelper.DeleteDb("test.db");
            var connection = DbHelper.GetDbConnection("test.db");
            DbConnectionWrapper wrapper;

            using (wrapper = new DbConnectionWrapper(connection))
            {
                wrapper.Connection.Execute("SELECT 'TEST'");
            }

            Assert.True(wrapper.IsDisposed);
            Assert.Null(wrapper.Connection);
        }
示例#12
0
        private void TestConnection <T>(Func <T> opener, bool checkTransaction = false) where T : IDisposable, IDbConnection
        {
            using (var c = opener())
            {
                AssertConnection(c);
                Assert.IsInstanceOf <T>(c);

                if (checkTransaction)
                {
                    DbConnectionWrapper wrapper = (DbConnectionWrapper)(object)c;
                    Assert.IsNotNull(wrapper.InnerTransaction);
                }
            }
        }
示例#13
0
        /// <summary>
        /// Wraps the connection.
        /// </summary>
        /// <param name="connection">The connection.</param>
        /// <param name="wrapperProviderInvariantNames">The wrapper provider invariant names.</param>
        /// <returns>Wrapped connection.</returns>
        internal static DbConnection WrapConnection(DbConnection connection, string connectionString, string providerInvariantName, params string[] wrapperProviderInvariantNames)
        {
            foreach (string invariantName in wrapperProviderInvariantNames)
            {
                DbProviderFactory factory = DbProviderFactories.GetFactory(invariantName);
                var connectionWrapper     = factory.CreateConnection();
                //connectionWrapper.ConnectionString = String.Format(@"wrappedProvider={0};{1}", providerInvariantName, connectionString);
                DbConnectionWrapper wrapper = (DbConnectionWrapper)connectionWrapper;
                wrapper.WrappedConnection = connection;
                connection = connectionWrapper;
            }

            return(connection);
        }
示例#14
0
        public void NestedWrapper_CommittedOuterTransaction_AllStatementsPersist()
        {
            DbHelper.DeleteDb("test.db");
            var connection = DbHelper.GetDbConnection("test.db");

            using (var wrapper = new DbConnectionWrapper(connection))
            {
                wrapper.Connection.Execute("CREATE TABLE OuterTable (ID INTEGER PRIMARY KEY)");

                using (wrapper.AddScope())
                {
                    wrapper.Connection.Execute("CREATE TABLE InnerTable (ID INTEGER PRIMARY KEY)");
                }

                wrapper.Commit();
            }

            Assert.True(DbHelper.TableExists("InnerTable", "test.db"));
            Assert.True(DbHelper.TableExists("OuterTable", "test.db"));
        }
    public Task Send(string destinationAddress, TransportMessage message, ITransactionContext context)
    {
        var connection = context.GetOrNull <OutboxConnection>(OutboxExtensions.CurrentOutboxConnectionKey);

        if (connection == null)
        {
            return(_transport.Send(destinationAddress, message, context));
        }

        var outgoingMessages = context.GetOrAdd(OutgoingMessagesKey, () =>
        {
            var queue = new ConcurrentQueue <AbstractRebusTransport.OutgoingMessage>();
            var dbConnectionWrapper = new DbConnectionWrapper(connection.Connection, connection.Transaction, managedExternally: true);
            context.OnCommitted(async _ => await _outboxStorage.Save(queue, dbConnectionWrapper));
            return(queue);
        });

        outgoingMessages.Enqueue(new AbstractRebusTransport.OutgoingMessage(message, destinationAddress));

        return(Task.CompletedTask);
    }
		/// <summary>
		/// Clones a new DbConnection supported by this provider.
		/// </summary>
		/// <param name="connection">The connection to clone.</param>
		/// <returns>A new DbConnection.</returns>
		public override IDbConnection CloneDbConnection(IDbConnection connection)
		{
			if (connection == null) throw new ArgumentNullException("connection");

			// clone the inner connection
			var innerConnection = GetInnerConnection(connection);
			var innerProvider = InsightDbProvider.For(innerConnection);
			var clonedInnerConnection = innerProvider.CloneDbConnection(innerConnection);

			var wrapper = new DbConnectionWrapper();
			try
			{
				var clone = (DbConnectionWrapper)wrapper;
				clone.InnerConnection = (DbConnection)clonedInnerConnection;
				return clone;
			}
			catch
			{
				wrapper.Dispose();
				throw;
			}
		}
    public async Task CanStoreBatchOfMessages_ManagedExternally(bool commitAndExpectTheMessagesToBeThere)
    {
        await using (var connection = new SqlConnection(SqlTestHelper.ConnectionString))
        {
            await connection.OpenAsync();

            await using var transaction = connection.BeginTransaction();

            var dbConnection = new DbConnectionWrapper(connection, transaction, managedExternally: true);

            var transportMessage = new TransportMessage(new Dictionary <string, string>(), new byte[] { 1, 2, 3 });
            var outgoingMessage  = new AbstractRebusTransport.OutgoingMessage(transportMessage, "wherever");

            await _storage.Save(new[] { outgoingMessage }, dbConnection);

            if (commitAndExpectTheMessagesToBeThere)
            {
                await transaction.CommitAsync();
            }
        }

        if (commitAndExpectTheMessagesToBeThere)
        {
            using var batch1 = await _storage.GetNextMessageBatch();

            await batch1.Complete();

            using var batch2 = await _storage.GetNextMessageBatch();

            Assert.That(batch1.Count, Is.EqualTo(1));
            Assert.That(batch2.Count, Is.EqualTo(0));
        }
        else
        {
            using var batch = await _storage.GetNextMessageBatch();

            Assert.That(batch.Count, Is.EqualTo(0));
        }
    }
示例#18
0
 public BackupDestinationRepository(DbConnectionWrapper dbConnectionWrapper) : base("BackupDestinations", dbConnectionWrapper)
 {
 }
示例#19
0
 /// <summary>
 /// Gets an opened connection.
 /// </summary>
 /// <returns>an instance of <see cref="LX.EasyDb.IConnection"/></returns>
 public IConnection OpenConnection()
 {
     DbConnectionWrapper conn = new DbConnectionWrapper(_factory.CreateConnection());
     conn.Factory = this;
     conn.ConnectionString = ConnectionString;
     conn.Open();
     return conn;
 }
示例#20
0
 public BackupSourceConfigRepository(DbConnectionWrapper dbConnectionWrapper) : base("BackupSourceConfigItems", dbConnectionWrapper)
 {
 }
        /// <inheritdoc/>
        public override Task BulkCopyAsync(IDbConnection connection, string tableName, IDataReader reader, Action <InsightBulkCopy> configure, InsightBulkCopyOptions options, IDbTransaction transaction, CancellationToken cancellationToken)
        {
            DbConnectionWrapper wrapped = (DbConnectionWrapper)connection;

            return(base.BulkCopyAsync(connection, tableName, reader, configure, options, transaction ?? wrapped.InnerTransaction, cancellationToken));
        }
示例#22
0
 public BackupDestinationConfigRepository(DbConnectionWrapper dbConnectionWrapper) : base("BackupDestinationConfigItems", dbConnectionWrapper)
 {
 }
示例#23
0
        /// <summary>
        /// Unwraps the given connection and returns the inner command.
        /// </summary>
        /// <param name="connection">The outer connection.</param>
        /// <returns>The inner connection.</returns>
        public override IDbConnection GetInnerConnection(IDbConnection connection)
        {
            DbConnectionWrapper wrapped = (DbConnectionWrapper)connection;

            return(wrapped.InnerConnection);
        }
示例#24
0
 public BackupSourceRepository(DbConnectionWrapper dbConnectionWrapper) : base("BackupSources", dbConnectionWrapper)
 {
 }
示例#25
0
        /// <inheritdoc/>
        public override void BulkCopy(IDbConnection connection, string tableName, IDataReader reader, Action <InsightBulkCopy> configure, InsightBulkCopyOptions options, IDbTransaction transaction)
        {
            DbConnectionWrapper wrapped = (DbConnectionWrapper)connection;

            base.BulkCopy(connection, tableName, reader, configure, options, transaction ?? wrapped.InnerTransaction);
        }
示例#26
0
        private ScriptExecutionResult DoBatchExecutionImpl(IDbConnection connection, string script)
        {
            Validate.IsNotNull(nameof(connection), connection);

            lock (this)
            {
                if (state == BatchState.Cancelling)
                {
                    state = BatchState.Initial;
                    return(ScriptExecutionResult.Cancel);
                }
            }

            ScriptExecutionResult result = ScriptExecutionResult.Success;

            // SqlClient event handlers setup
            SqlInfoMessageEventHandler     messageHandler            = new SqlInfoMessageEventHandler(OnSqlInfoMessageCallback);
            StatementCompletedEventHandler statementCompletedHandler = null;

            DbConnectionWrapper connectionWrapper = new DbConnectionWrapper(connection);

            connectionWrapper.InfoMessage += messageHandler;

            IDbCommand command = connection.CreateCommand();

            command.CommandText    = script;
            command.CommandTimeout = execTimeout;

            DbCommandWrapper commandWrapper = null;

            if (isScriptExecutionTracked && DbCommandWrapper.IsSupportedCommand(command))
            {
                statementCompletedHandler          = new StatementCompletedEventHandler(OnStatementExecutionFinished);
                commandWrapper                     = new DbCommandWrapper(command);
                commandWrapper.StatementCompleted += statementCompletedHandler;
            }

            lock (this)
            {
                state        = BatchState.Executing;
                this.command = command;
                command      = null;
            }

            try
            {
                result = this.ExecuteCommand();
            }
            catch (OutOfMemoryException)
            {
                throw;
            }
            catch (SqlException sqlEx)
            {
                result = HandleSqlException(sqlEx);
            }
            catch (Exception ex)
            {
                result = ScriptExecutionResult.Failure;
                HandleExceptionMessage(ex);
            }
            finally
            {
                if (messageHandler == null)
                {
                    Logger.Write(TraceEventType.Error, "Expected handler to be declared");
                }

                if (null != connectionWrapper)
                {
                    connectionWrapper.InfoMessage -= messageHandler;
                }

                if (commandWrapper != null)
                {
                    if (statementCompletedHandler == null)
                    {
                        Logger.Write(TraceEventType.Error, "Expect handler to be declared if we have a command wrapper");
                    }
                    commandWrapper.StatementCompleted -= statementCompletedHandler;
                }

                lock (this)
                {
                    state = BatchState.Initial;
                    if (command != null)
                    {
                        command.Dispose();
                        command = null;
                    }
                }
            }

            return(result);
        }