Example #1
1
        /// <summary>
        /// Begins a database transaction with the specified isolation level.
        /// </summary>
        /// <param name="level">The <see cref="System.Data.IsolationLevel">isolation level</see> under which the transaction should run.</param>
        /// <returns>A <see cref="NpgsqlTransaction">NpgsqlTransaction</see>
        /// object representing the new transaction.</returns>
        /// <remarks>
        /// Currently the IsolationLevel ReadCommitted and Serializable are supported by the PostgreSQL backend.
        /// There's no support for nested transactions.
        /// </remarks>
        public new NpgsqlTransaction BeginTransaction(IsolationLevel level)
        {
            _log.Debug("Beginning transaction with isolation level " + level);
            CheckConnectionOpen();

            if (Connector.Transaction != null) {
                throw new InvalidOperationException(L10N.NoNestedTransactions);
            }

            return new NpgsqlTransaction(this, level);
        }
        internal SqlDelegatedTransaction(SqlInternalConnection connection, System.Transactions.Transaction tx)
        {
            this._connection = connection;
            this._atomicTransaction = tx;
            this._active = false;
            System.Transactions.IsolationLevel isolationLevel = tx.IsolationLevel;
            switch (isolationLevel)
            {
                case System.Transactions.IsolationLevel.Serializable:
                    this._isolationLevel = System.Data.IsolationLevel.Serializable;
                    return;

                case System.Transactions.IsolationLevel.RepeatableRead:
                    this._isolationLevel = System.Data.IsolationLevel.RepeatableRead;
                    return;

                case System.Transactions.IsolationLevel.ReadCommitted:
                    this._isolationLevel = System.Data.IsolationLevel.ReadCommitted;
                    return;

                case System.Transactions.IsolationLevel.ReadUncommitted:
                    this._isolationLevel = System.Data.IsolationLevel.ReadUncommitted;
                    return;

                case System.Transactions.IsolationLevel.Snapshot:
                    this._isolationLevel = System.Data.IsolationLevel.Snapshot;
                    return;
            }
            throw SQL.UnknownSysTxIsolationLevel(isolationLevel);
        }
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         OdbcConnectionHandle hrHandle = this._handle;
         this._handle = null;
         if (hrHandle != null)
         {
             try
             {
                 ODBC32.RetCode retcode = hrHandle.CompleteTransaction(1);
                 if ((retcode == ODBC32.RetCode.ERROR) && (this._connection != null))
                 {
                     ADP.TraceExceptionWithoutRethrow(this._connection.HandleErrorNoThrow(hrHandle, retcode));
                 }
             }
             catch (Exception exception)
             {
                 if (!ADP.IsCatchableExceptionType(exception))
                 {
                     throw;
                 }
             }
         }
         if ((this._connection != null) && this._connection.IsOpen)
         {
             this._connection.LocalTransaction = null;
         }
         this._connection = null;
         this._isolevel = System.Data.IsolationLevel.Unspecified;
     }
     base.Dispose(disposing);
 }
 internal OracleTransaction(OracleConnection connection, System.Data.IsolationLevel isolationLevel)
 {
     this._isolationLevel = System.Data.IsolationLevel.ReadCommitted;
     this._objectID = Interlocked.Increment(ref _objectTypeCount);
     TransactionState transactionState = connection.TransactionState;
     if (TransactionState.GlobalStarted == transactionState)
     {
         throw System.Data.Common.ADP.NoLocalTransactionInDistributedContext();
     }
     this._connection = connection;
     this._connectionCloseCount = connection.CloseCount;
     this._isolationLevel = isolationLevel;
     this._connection.TransactionState = TransactionState.LocalStarted;
     try
     {
         System.Data.IsolationLevel level = isolationLevel;
         if (level == System.Data.IsolationLevel.Unspecified)
         {
             return;
         }
         if (level != System.Data.IsolationLevel.ReadCommitted)
         {
             if (level == System.Data.IsolationLevel.Serializable)
             {
                 goto Label_009A;
             }
             goto Label_00C4;
         }
         using (OracleCommand command2 = this.Connection.CreateCommand())
         {
             command2.CommandText = "set transaction isolation level read committed";
             command2.ExecuteNonQuery();
             return;
         }
     Label_009A:
         using (OracleCommand command = this.Connection.CreateCommand())
         {
             command.CommandText = "set transaction isolation level serializable";
             command.ExecuteNonQuery();
             return;
         }
     Label_00C4:
         throw System.Data.Common.ADP.UnsupportedIsolationLevel();
     }
     catch
     {
         this._connection.TransactionState = transactionState;
         throw;
     }
 }
 internal SqlTransaction(SqlInternalConnection internalConnection, SqlConnection con, System.Data.IsolationLevel iso, SqlInternalTransaction internalTransaction)
 {
     this._isolationLevel = iso;
     this._connection = con;
     if (internalTransaction == null)
     {
         this._internalTransaction = new SqlInternalTransaction(internalConnection, TransactionType.LocalFromAPI, this);
     }
     else
     {
         this._internalTransaction = internalTransaction;
         this._internalTransaction.InitParent(this);
     }
 }
Example #6
0
 internal void ExecuteTransaction(SqlInternalConnection.TransactionRequest transactionRequest, string name, System.Data.IsolationLevel iso)
 {
     this.ExecuteTransaction(transactionRequest, name, iso, null, false);
 }
Example #7
0
 public MelhoresPraticas.CrossCutting.Transaction.IDbTransaction CreateTransaction(System.Data.IsolationLevel isolationLevel)
 {
     return(new MelhoresPraticas.CrossCutting.Transaction.DbTransaction(this.Context.Database.BeginTransaction(isolationLevel)));
 }
Example #8
0
 public System.Data.IDbTransaction BeginTransaction(System.Data.IsolationLevel il)
 {
     WriteDebugPrint("BeginTransaction2");
     return(_aDbConnection.BeginTransaction(il));
 }
 public DataMappingTransactionScope CreateTransactionScope(System.Data.IsolationLevel isolationLevel)
 {
     return(new DataMappingTransaction(this, isolationLevel));
 }
 private int BeginServerTransaction(IsolationLevel isolationLevel)
 {
     lock (this) {
         try {
             return Client.BeginTransaction(isolationLevel);
         } catch (Exception ex) {
             throw new DeveelDbException("Could not begin a transaction.", ex);
         }
     }
 }
        public new DeveelDbTransaction BeginTransaction(IsolationLevel isolationLevel)
        {
            if (Transaction != null)
                throw new DeveelDbException("A transaction is already open on this connection.");

            if (isolationLevel == IsolationLevel.Unspecified)
                isolationLevel = IsolationLevel.Serializable;

            if (isolationLevel != IsolationLevel.Serializable)
                throw new NotSupportedException(String.Format("Isolation Level '{0}' is not supported yet.", isolationLevel));

            var commitId = BeginServerTransaction(isolationLevel);
            return new DeveelDbTransaction(this, isolationLevel, commitId);
        }
Example #12
0
    public Task<MySqlTransaction> BeginTransactionAsync(IsolationLevel iso, CancellationToken cancellationToken)
    {
      var result = new TaskCompletionSource<MySqlTransaction>();
      if (cancellationToken == CancellationToken.None || !cancellationToken.IsCancellationRequested)
      {
        try
        {
          MySqlTransaction tranResult = BeginTransaction(iso);
          result.SetResult(tranResult);
        }
        catch (Exception ex)
        {
          result.SetException(ex);
        }
      }
      else
      {
        result.SetCanceled();
      }

      return result.Task;
    }
 public SQLSetTransactionIsolationLevel(System.Data.IsolationLevel eIsolationLevel)
 {
     peIsolationLevel = eIsolationLevel;
 }
 public NuoDbTransaction(NuoDbConnection nuoDBConnection, System.Data.IsolationLevel isolationLevel)
 {
     this.connection = nuoDBConnection;
     this.isolationLevel = isolationLevel;
 }
Example #15
0
		/// <summary>
		/// Begins a database transaction with the specified isolation level.
		/// </summary>
		/// <param name="level">The <see cref="System.Data.IsolationLevel">isolation level</see> under which the transaction should run.</param>
		/// <returns>A <see cref="Npgsql.NpgsqlTransaction">NpgsqlTransaction</see>
		/// object representing the new transaction.</returns>
		/// <remarks>
		/// Currently the IsolationLevel ReadCommitted and Serializable are supported by the PostgreSQL backend.
		/// There's no support for nested transactions.
		/// </remarks>
		public new NpgsqlTransaction BeginTransaction(IsolationLevel level)
		{
			CheckConnectionOpen();

			if (connector.Transaction != null)
			{
				throw new InvalidOperationException(resman.GetString("Exception_NoNestedTransactions"));
			}

			return new NpgsqlTransaction(this, level);
		}
Example #16
0
 /// <summary>
 /// Async version of BeginTransaction
 /// </summary>
 /// <param name="iso">The isolation level under which the transaction should run. </param>
 /// <returns>An object representing the new transaction.</returns>
 public Task<MySqlTransaction> BeginTransactionAsync(IsolationLevel iso)
 {
   return BeginTransactionAsync(iso, CancellationToken.None);
 }
Example #17
0
 protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
 {
     return ProxiedConnection.BeginTransaction(isolationLevel);
 }
 IDbTransaction IDbConnection.BeginTransaction(System.Data.IsolationLevel isolationLevel)
 {
     return(this.BeginDbTransaction(isolationLevel));
 }
Example #19
0
        /// <summary>
        /// Begins the <see cref="IDbTransaction"/> on the <see cref="IDbConnection"/>
        /// used by the <see cref="ISession"/>.
        /// </summary>
        /// <exception cref="System.Transactions.TransactionException">
        /// Thrown if there is any problems encountered while trying to create
        /// the <see cref="IDbTransaction"/>.
        /// </exception>
        public void Begin(IsolationLevel isolationLevel)
        {
            using (new SessionIdLoggingContext(sessionId))
            {
                if (begun)
                {
                    return;
                }

                if (commitFailed)
                {
                    throw new TransactionException("Cannot restart transaction after failed commit");
                }

                log.Debug(string.Format("Begin ({0})", isolationLevel));

                try
                {
                    if (isolationLevel == IsolationLevel.Unspecified)
                    {
                        isolationLevel = session.Factory.Settings.IsolationLevel;
                    }

                    if (isolationLevel == IsolationLevel.Unspecified)
                    {
                        trans = session.Connection.BeginTransaction();
                    }
                    else
                    {
                        trans = session.Connection.BeginTransaction(isolationLevel);
                    }
                }
                //catch (HibernateException)
                //{
                //    // Don't wrap HibernateExceptions
                //    throw;
                //}
                catch (Exception e)
                {
                    log.Error("Begin transaction failed", e);
                    throw new TransactionException("Begin failed with SQL exception", e);
                }

                begun = true;
                committed = false;
                rolledBack = false;

                session.AfterTransactionBegin(this);
            }
        }
 protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
 {
     return BeginTransaction(isolationLevel);
 }
Example #21
0
        /*
        ** Name: sendTransactionQuery
        **
        ** Description:
        **	Build and send "set session" query that includes both isolation
        **	level and "read only" or "read/write" components.  Query will be in
        **	this form:
        **	     SET SESSION [READ ONLY|WRITE] [,ISOLATION LEVEL isolation_level]
        **
        ** Input:
        **      readOnly        True if read-only, false if read/write
        **      isolationLevel  One of four values:
        **                      TRANSACTION_SERIALIZABLE
        **                      TRANSACTION_READ_UNCOMMITTED
        **                      TRANSACTION_READ_COMMITTED
        **                      TRANSACTION_REPEATABLE_READ
        **
        ** Output:
        **	None.
        **
        ** Returns:
        **	None.
        **
        ** History:
        **	27-Jul-01 (loera01)
        **	    Created.
        **	30-sep-02 (loera01) Bug 108833
        **	    Since the intention of the setTransactionIsolaton and
        **	    setReadOnly methods is for the "set" query to persist in the
        **	    session, change "set transaction" to "set session".
        */
        private void sendTransactionQuery(
				bool readOnly, System.Data.IsolationLevel isolationLevel)
        {
            lock(this)
            {
                if (trace.enabled())
                    trace.log(title + ".sendTransactionQuery( " + readOnly + " , " + isolationLevel + " )");

                String sql = "set session read ";
                sql += readOnly?"only":" write";
                sql += ", isolation level ";

                try
                {
                    switch (isolationLevel)
                    {
                        case System.Data.IsolationLevel.ReadUncommitted:
                            sql += "read uncommitted"; break;

                        case System.Data.IsolationLevel.ReadCommitted:
                            sql += "read committed"; break;

                        case System.Data.IsolationLevel.RepeatableRead:
                            sql += "repeatable read"; break;

                        case System.Data.IsolationLevel.Serializable:
                            sql += "serializable"; break;

                        default:
                            throw SqlEx.get( ERR_GC4010_PARAM_VALUE );

                    }

                    // assume that the command will work OK and
                    // set isolation level now to avoid looping recursive calls of
                    // Execute->setIsolationLevel->sendTransactionQuery->Execute->...
                    this.readOnly = readOnly;
                    this.isolationLevel = isolationLevel;

                    IDbCommand cmd = providerConnection.CreateCommand();
                    cmd.CommandText = sql;
                    cmd.ExecuteNonQuery();
            //TODO move errors to connection object
            //		warnings = stmt.warnings;
                    cmd.Dispose();
                }
                catch (SqlEx ex)
                {
                    if (trace.enabled())
                        trace.log(title + ".sendTransactionQuery(): failed!");
                    if (trace.enabled(1))
                        ex.trace(trace);
                    throw ex;
                }
                return ;
            }
        }
 public void BeginTransaction(System.Data.IsolationLevel isolationLevel)
 {
     this._context.Writer.BeginTransaction(isolationLevel);
 }
Example #23
0
        /*
        ** Name AdvanConnect
        **
        ** Description:
        **	Class constructor.  Common functionality for other
        **	constructors.  Initialize tracing.
        **
        ** Input:
        **	providerConnection	IngresConnection
        **	host              	Target host and port.
        **	trace             	Connection tracing.
        **
        ** Output:
        **	None.
        **
        ** Returns:
        **	None.
        **
        ** History:
        **	18-Apr-01 (gordy)
        **	    Extracted from other constructors.*/
        internal AdvanConnect(
			IDbConnection providerConnection,
			String host,
			ITrace trace)
            : base(trace)
        {
            isolationLevel = System.Data.IsolationLevel.Serializable;
            type_map       = new System.Collections.Hashtable();

            this.providerConnection = providerConnection;  // IngresConnection
            this.host = host;
            title = DrvConst.shortTitle + "-Connect";
            tr_id = "Conn";
        }
Example #24
0
 public void BeginTransaction(System.Data.IsolationLevel _isolationLevel)
 {
     this.DbTransaction = this.DbConnection.BeginTransaction(_isolationLevel);
 }
 internal OdbcTransaction(OdbcConnection connection, System.Data.IsolationLevel isolevel, OdbcConnectionHandle handle)
 {
     this._connection = connection;
     this._isolevel = isolevel;
     this._handle = handle;
 }
Example #26
0
 /// <summary>
 /// Starts a database transaction.
 /// </summary>
 /// <param name="isolationLevel">Specifies the isolation level for the transaction.</param>
 /// <returns>
 /// An object representing the new transaction.
 /// </returns>
 protected override DbTransaction BeginDbTransaction(System.Data.IsolationLevel isolationLevel)
 {
     return(this.wrappedConnection.BeginTransaction(isolationLevel));
 }
Example #27
0
		internal MySqlTransaction( MySqlConnection c, System.Data.IsolationLevel il ) {
			mConnection = c;
			mLevel = il;
			mOpen = true;
		}
Example #28
0
 public OdbcTransaction BeginTransaction(System.Data.IsolationLevel isolevel)
 {
     return((OdbcTransaction)this.InnerConnection.BeginTransaction(isolevel));
 }
Example #29
0
 internal override void ExecuteTransaction(SqlInternalConnection.TransactionRequest transactionRequest, string name, System.Data.IsolationLevel iso, SqlInternalTransaction internalTransaction, bool isDelegateControlRequest)
 {
     if (base.IsConnectionDoomed)
     {
         if ((transactionRequest != SqlInternalConnection.TransactionRequest.Rollback) && (transactionRequest != SqlInternalConnection.TransactionRequest.IfRollback))
         {
             throw SQL.ConnectionDoomed();
         }
     }
     else
     {
         if ((((transactionRequest == SqlInternalConnection.TransactionRequest.Commit) || (transactionRequest == SqlInternalConnection.TransactionRequest.Rollback)) || (transactionRequest == SqlInternalConnection.TransactionRequest.IfRollback)) && (!this.Parser.MARSOn && this.Parser._physicalStateObj.BcpLock))
         {
             throw SQL.ConnectionLockedForBcpEvent();
         }
         string transactionName = (name == null) ? string.Empty : name;
         if (!this._parser.IsYukonOrNewer)
         {
             this.ExecuteTransactionPreYukon(transactionRequest, transactionName, iso, internalTransaction);
         }
         else
         {
             this.ExecuteTransactionYukon(transactionRequest, transactionName, iso, internalTransaction, isDelegateControlRequest);
         }
     }
 }
Example #30
0
 protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
 {
     if (isolationLevel == IsolationLevel.Unspecified)
         return BeginTransaction();
     return BeginTransaction(isolationLevel);
 }
Example #31
0
        internal void ExecuteTransactionPreYukon(SqlInternalConnection.TransactionRequest transactionRequest, string transactionName, System.Data.IsolationLevel iso, SqlInternalTransaction internalTransaction)
        {
            StringBuilder builder = new StringBuilder();

            switch (iso)
            {
            case System.Data.IsolationLevel.Unspecified:
                break;

            case System.Data.IsolationLevel.Chaos:
                throw SQL.NotSupportedIsolationLevel(iso);

            case System.Data.IsolationLevel.ReadUncommitted:
                builder.Append("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED");
                builder.Append(";");
                break;

            case System.Data.IsolationLevel.Serializable:
                builder.Append("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
                builder.Append(";");
                break;

            case System.Data.IsolationLevel.Snapshot:
                throw SQL.SnapshotNotSupported(System.Data.IsolationLevel.Snapshot);

            case System.Data.IsolationLevel.ReadCommitted:
                builder.Append("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");
                builder.Append(";");
                break;

            case System.Data.IsolationLevel.RepeatableRead:
                builder.Append("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ");
                builder.Append(";");
                break;

            default:
                throw ADP.InvalidIsolationLevel(iso);
            }
            if (!ADP.IsEmpty(transactionName))
            {
                transactionName = " " + SqlConnection.FixupDatabaseTransactionName(transactionName);
            }
            switch (transactionRequest)
            {
            case SqlInternalConnection.TransactionRequest.Begin:
                builder.Append("BEGIN TRANSACTION");
                builder.Append(transactionName);
                break;

            case SqlInternalConnection.TransactionRequest.Commit:
                builder.Append("COMMIT TRANSACTION");
                builder.Append(transactionName);
                break;

            case SqlInternalConnection.TransactionRequest.Rollback:
                builder.Append("ROLLBACK TRANSACTION");
                builder.Append(transactionName);
                break;

            case SqlInternalConnection.TransactionRequest.IfRollback:
                builder.Append("IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION");
                builder.Append(transactionName);
                break;

            case SqlInternalConnection.TransactionRequest.Save:
                builder.Append("SAVE TRANSACTION");
                builder.Append(transactionName);
                break;
            }
            this._parser.TdsExecuteSQLBatch(builder.ToString(), base.ConnectionOptions.ConnectTimeout, null, this._parser._physicalStateObj);
            this._parser.Run(RunBehavior.UntilDone, null, null, null, this._parser._physicalStateObj);
            if (transactionRequest == SqlInternalConnection.TransactionRequest.Begin)
            {
                this._parser.CurrentTransaction = internalTransaction;
            }
        }
Example #32
0
        /// <summary>
        /// Begins a database transaction with the specified isolation level.
        /// </summary>
        /// <param name="isolationLevel">The <see cref="System.Data.IsolationLevel">isolation level</see> under which the transaction should run.</param>
        /// <returns>An <see cref="System.Data.Common.DbTransaction">DbTransaction</see>
        /// object representing the new transaction.</returns>
        /// <remarks>
        /// Currently the IsolationLevel ReadCommitted and Serializable are supported by the PostgreSQL backend.
        /// There's no support for nested transactions.
        /// </remarks>
        protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
        {
            NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "BeginDbTransaction", isolationLevel);

            return BeginTransaction(isolationLevel);
        }
Example #33
0
        /// <include file='docs/MySqlConnection.xml' path='docs/BeginTransaction1/*'/>
        public new MySqlTransaction BeginTransaction(IsolationLevel iso)
        {
            //TODO: check note in help
            if (State != ConnectionState.Open)
                throw new InvalidOperationException(Resources.ConnectionNotOpen);

            // First check to see if we are in a current transaction
            if ((driver.ServerStatus & ServerStatusFlags.InTransaction) != 0)
                throw new InvalidOperationException(Resources.NoNestedTransactions);

            MySqlTransaction t = new MySqlTransaction(this, iso);

            MySqlCommand cmd = new MySqlCommand("", this);

            cmd.CommandText = "SET SESSION TRANSACTION ISOLATION LEVEL ";
            switch (iso)
            {
                case IsolationLevel.ReadCommitted:
                    cmd.CommandText += "READ COMMITTED";
                    break;
                case IsolationLevel.ReadUncommitted:
                    cmd.CommandText += "READ UNCOMMITTED";
                    break;
                case IsolationLevel.RepeatableRead:
                    cmd.CommandText += "REPEATABLE READ";
                    break;
                case IsolationLevel.Serializable:
                    cmd.CommandText += "SERIALIZABLE";
                    break;
                case IsolationLevel.Chaos:
                    throw new NotSupportedException(Resources.ChaosNotSupported);
            }

            cmd.ExecuteNonQuery();

            cmd.CommandText = "BEGIN";
            cmd.ExecuteNonQuery();

            return t;
        }
Example #34
0
 protected override DbTransaction BeginDbTransaction(System.Data.IsolationLevel isolationLevel) => throw new NotImplementedException();
        public virtual async Task<IDbContextTransaction> BeginTransactionAsync(
            IsolationLevel isolationLevel,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (CurrentTransaction != null)
            {
                throw new InvalidOperationException(RelationalStrings.TransactionAlreadyStarted);
            }

            await OpenAsync(cancellationToken);

            return BeginTransactionWithNoPreconditions(isolationLevel);
        }
        internal OleDbTransaction(OleDbConnection connection, OleDbTransaction transaction, IsolationLevel isolevel) {
            OleDbConnection.VerifyExecutePermission();

            _parentConnection = connection;
            _parentTransaction = transaction;

            switch(isolevel) {
            case IsolationLevel.Unspecified: // OLE DB doesn't support this isolevel on local transactions
                isolevel = IsolationLevel.ReadCommitted;
                break;
            case IsolationLevel.Chaos:
            case IsolationLevel.ReadUncommitted:
            case IsolationLevel.ReadCommitted:
            case IsolationLevel.RepeatableRead:
            case IsolationLevel.Serializable:
            case IsolationLevel.Snapshot:
                break;
            default:
                throw ADP.InvalidIsolationLevel(isolevel); // MDAC 74269
            }
            _isolationLevel = isolevel;
        }
Example #37
0
 public IDbContextTransaction BeginTransaction(System.Data.IsolationLevel isolationLevel) => throw new NotImplementedException();
Example #38
0
 /// <summary>
 /// Wrapper for multiple Sql calls (Single database) within a transaction
 /// </summary>
 /// <typeparam name="T">Return type of the complete transaction</typeparam>
 /// <param name="logger">The logger for the transaction sequence</param>
 /// <param name="cnnStr">The connection string to use for all calls within the transaction</param>
 /// <param name="method">The actual SQL calls</param>
 /// <param name="isolation">Default = ReadCommitted. Isolation level for the transaction.</param>
 /// <param name="defaultValue">Default = Default(T). If an exception is thrown during "method", and it is not rethrowing the exception, this will instead be returned</param>
 /// <returns>The result from the SQL calls (method) - or possibly default(T) if there was an exception</returns>
 public static Task <T> Run <T>(ILogger logger, string cnnStr,
                                Func <IDbTransaction, Task <TransactionResponse <T> > > method, IsolationLevel isolation, T defaultValue)
 => Run(logger, cnnStr, method, isolation, ExceptionDefaultVal, defaultValue);
Example #39
0
 /// <summary>
 /// Wrapper for multiple Sql calls (Single database) within a transaction
 /// </summary>
 /// <param name="logger">The logger for the transaction sequence</param>
 /// <param name="cnnStr">The connection string to use for all calls within the transaction</param>
 /// <param name="method">The actual SQL calls</param>
 /// <param name="isolation">Default = ReadCommitted. Isolation level for the transaction.</param>
 /// <returns>True if the transaction was committed, false if rolled back</returns>
 public static Task <bool> Run(ILogger logger, string cnnStr,
                               Func <IDbTransaction, Task <TransactionResponse> > method, IsolationLevel isolation)
 => Run(logger, cnnStr, method, isolation, ExceptionRethrow);
 protected override DbTransaction BeginDbTransaction(System.Data.IsolationLevel isolationLevel)
 {
     return(new DbTransactionEx(this.inner.BeginTransaction(isolationLevel), this.appender, this));
 }
Example #41
0
 public abstract DbTransaction BeginTransaction(System.Data.IsolationLevel il);
        internal void BeginTransaction(IsolationLevel isolationLevel)
        {
            _transactionDepth++;

            if (SupportsNestedTransactions)
            {
                if (CSConfig.UseTransactionScope)
                {
                    _currentTransactionScope = new TransactionScope();

                    _transactionScopeStack.Push(_currentTransactionScope);
                }
                else
                {
                    _currentTransaction = Connection.BeginTransaction(isolationLevel);

                    _transactionStack.Push(_currentTransaction);
                }

                _newTransactionStack.Push(true);
            }
            else
            {
                if (CSConfig.UseTransactionScope)
                {
                    if (_currentTransactionScope != null)
                    {
                        _newTransactionStack.Push(false);
                    }
                    else
                    {
                        _currentTransactionScope = new TransactionScope();

                        _newTransactionStack.Push(true);
                    }

                    _transactionScopeStack.Push(_currentTransactionScope);
                }
                else
                {
                    if (_currentTransaction != null)
                    {
                        _newTransactionStack.Push(false);
                    }
                    else
                    {
                        _currentTransaction = Connection.BeginTransaction();

                        _newTransactionStack.Push(true);
                    }

                    _transactionStack.Push(_currentTransaction);
                }
            }
        }
Example #43
0
        /// <inheritdoc cref="EnsureInTransaction()"/>
        /// <param name="isolationLevel">
        /// Specifies the isolation level for the transaction. This parameter is ignored when using
        /// an existing transaction.
        /// </param>

        public IDbTransaction EnsureInTransaction(IsolationLevel isolationLevel)
        {
            return(new WrappedTransaction(this, isolationLevel));
        }
Example #44
0
        internal void ExecuteTransactionYukon(SqlInternalConnection.TransactionRequest transactionRequest, string transactionName, System.Data.IsolationLevel iso, SqlInternalTransaction internalTransaction, bool isDelegateControlRequest)
        {
            TdsEnums.TransactionManagerRequestType    begin         = TdsEnums.TransactionManagerRequestType.Begin;
            TdsEnums.TransactionManagerIsolationLevel readCommitted = TdsEnums.TransactionManagerIsolationLevel.ReadCommitted;
            switch (iso)
            {
            case System.Data.IsolationLevel.Unspecified:
                readCommitted = TdsEnums.TransactionManagerIsolationLevel.Unspecified;
                break;

            case System.Data.IsolationLevel.Chaos:
                throw SQL.NotSupportedIsolationLevel(iso);

            case System.Data.IsolationLevel.ReadUncommitted:
                readCommitted = TdsEnums.TransactionManagerIsolationLevel.ReadUncommitted;
                break;

            case System.Data.IsolationLevel.Serializable:
                readCommitted = TdsEnums.TransactionManagerIsolationLevel.Serializable;
                break;

            case System.Data.IsolationLevel.Snapshot:
                readCommitted = TdsEnums.TransactionManagerIsolationLevel.Snapshot;
                break;

            case System.Data.IsolationLevel.ReadCommitted:
                readCommitted = TdsEnums.TransactionManagerIsolationLevel.ReadCommitted;
                break;

            case System.Data.IsolationLevel.RepeatableRead:
                readCommitted = TdsEnums.TransactionManagerIsolationLevel.RepeatableRead;
                break;

            default:
                throw ADP.InvalidIsolationLevel(iso);
            }
            TdsParserStateObject session = this._parser._physicalStateObj;
            TdsParser            parser  = this._parser;
            bool flag      = false;
            bool lockTaken = false;

            try
            {
                switch (transactionRequest)
                {
                case SqlInternalConnection.TransactionRequest.Begin:
                    begin = TdsEnums.TransactionManagerRequestType.Begin;
                    break;

                case SqlInternalConnection.TransactionRequest.Promote:
                    begin = TdsEnums.TransactionManagerRequestType.Promote;
                    break;

                case SqlInternalConnection.TransactionRequest.Commit:
                    begin = TdsEnums.TransactionManagerRequestType.Commit;
                    break;

                case SqlInternalConnection.TransactionRequest.Rollback:
                case SqlInternalConnection.TransactionRequest.IfRollback:
                    begin = TdsEnums.TransactionManagerRequestType.Rollback;
                    break;

                case SqlInternalConnection.TransactionRequest.Save:
                    begin = TdsEnums.TransactionManagerRequestType.Save;
                    break;
                }
                if ((internalTransaction != null) && internalTransaction.IsDelegated)
                {
                    if (!this._parser.MARSOn)
                    {
                        if (internalTransaction.OpenResultsCount != 0)
                        {
                            throw SQL.CannotCompleteDelegatedTransactionWithOpenResults();
                        }
                        Monitor.Enter(session, ref lockTaken);
                        if (internalTransaction.OpenResultsCount != 0)
                        {
                            throw SQL.CannotCompleteDelegatedTransactionWithOpenResults();
                        }
                    }
                    else
                    {
                        session = this._parser.GetSession(this);
                        flag    = true;
                    }
                }
                this._parser.TdsExecuteTransactionManagerRequest(null, begin, transactionName, readCommitted, base.ConnectionOptions.ConnectTimeout, internalTransaction, session, isDelegateControlRequest);
            }
            finally
            {
                if (flag)
                {
                    parser.PutSession(session);
                }
                if (lockTaken)
                {
                    Monitor.Exit(session);
                }
            }
        }
Example #45
0
 internal SQLiteEnlistment(SQLiteConnection cnn, System.Transactions.Transaction scope, System.Data.IsolationLevel defaultIsolationLevel, bool throwOnUnavailable, bool throwOnUnsupported)
 {
     this._transaction = cnn.BeginTransaction(this.GetSystemDataIsolationLevel(cnn, scope, defaultIsolationLevel, throwOnUnavailable, throwOnUnsupported));
     this._scope       = scope;
     this._scope.EnlistVolatile(this, EnlistmentOptions.None);
 }
Example #46
0
        /// <summary>
        /// Wrapper for multiple Sql calls (Single database) within a transaction
        /// </summary>
        /// <param name="logger">The logger for the transaction sequence</param>
        /// <param name="cnnStr">The connection string to use for all calls within the transaction</param>
        /// <param name="method">The actual SQL calls</param>
        /// <param name="isolation">Default = ReadCommitted. Isolation level for the transaction.</param>
        /// <param name="exceptionMethod">Default = ExceptionRethrow. If an exception is thrown during "method", how will it be handled (besides being rolled back)</param>
        /// <returns>True if the transaction was committed, false if rolled back</returns>
        public static async Task <bool> Run(ILogger logger, string cnnStr,
                                            Func <IDbTransaction, Task <TransactionResponse> > method, IsolationLevel isolation,
                                            Func <Exception, bool> exceptionMethod)
        {
            DatabaseInformation info = null;

            if (logger != null)
            {
                info = logger.DatabaseEntry(cnnStr, "Action Transaction");
            }

            await using var cnn = new TC { ConnectionString = $"{cnnStr};MultipleActiveResultSets=True" };
            if (cnn.State != ConnectionState.Open)
            {
                await cnn.OpenAsync();
            }
            await using var transaction = await cnn.BeginTransactionAsync(isolation);

            var success = await SafeTry.OnException(
                async() =>
            {
                var response = await method(transaction);
                if (response.Success)
                {
                    await transaction.CommitAsync();
                }
                else
                {
                    await transaction.RollbackAsync();
                }
                return(response.Success);
            },
                async ex =>
            {
                await transaction.RollbackAsync();
                return(exceptionMethod(ex));
            });

            if (logger != null)
            {
                logger.DatabaseExit(info);
            }
            return(success);
        }
Example #47
0
        private System.Data.IsolationLevel GetSystemDataIsolationLevel(SQLiteConnection connection, System.Transactions.Transaction transaction, System.Data.IsolationLevel defaultIsolationLevel, bool throwOnUnavailable, bool throwOnUnsupported)
        {
            if (transaction == null)
            {
                if (connection != null)
                {
                    return(connection.GetDefaultIsolationLevel());
                }
                if (throwOnUnavailable)
                {
                    throw new InvalidOperationException("isolation level is unavailable");
                }
                return(defaultIsolationLevel);
            }
            System.Transactions.IsolationLevel isolationLevel = transaction.IsolationLevel;
            switch (isolationLevel)
            {
            case System.Transactions.IsolationLevel.Serializable:
            {
                return(System.Data.IsolationLevel.Serializable);
            }

            case System.Transactions.IsolationLevel.RepeatableRead:
            {
                return(System.Data.IsolationLevel.RepeatableRead);
            }

            case System.Transactions.IsolationLevel.ReadCommitted:
            {
                return(System.Data.IsolationLevel.ReadCommitted);
            }

            case System.Transactions.IsolationLevel.ReadUncommitted:
            {
                return(System.Data.IsolationLevel.ReadUncommitted);
            }

            case System.Transactions.IsolationLevel.Snapshot:
            {
                return(System.Data.IsolationLevel.Snapshot);
            }

            case System.Transactions.IsolationLevel.Chaos:
            {
                return(System.Data.IsolationLevel.Chaos);
            }

            case System.Transactions.IsolationLevel.Unspecified:
            {
                return(System.Data.IsolationLevel.Unspecified);
            }
            }
            if (throwOnUnsupported)
            {
                CultureInfo currentCulture = CultureInfo.CurrentCulture;
                object[]    objArray       = new object[] { isolationLevel };
                throw new InvalidOperationException(HelperMethods.StringFormat(currentCulture, "unsupported isolation level {0}", objArray));
            }
            return(defaultIsolationLevel);
        }
Example #48
0
        internal OleDbTransaction(OleDbConnection connection, OleDbTransaction transaction, System.Data.IsolationLevel isolevel)
        {
            this._parentConnection  = connection;
            this._parentTransaction = transaction;
            switch (isolevel)
            {
            case System.Data.IsolationLevel.Unspecified:
                isolevel = System.Data.IsolationLevel.ReadCommitted;
                break;

            case System.Data.IsolationLevel.Chaos:
            case System.Data.IsolationLevel.ReadUncommitted:
            case System.Data.IsolationLevel.Serializable:
            case System.Data.IsolationLevel.Snapshot:
            case System.Data.IsolationLevel.ReadCommitted:
            case System.Data.IsolationLevel.RepeatableRead:
                break;

            default:
                throw ADP.InvalidIsolationLevel(isolevel);
            }
            this._isolationLevel = isolevel;
        }
Example #49
0
 /// <summary>
 /// Async version of BeginTransaction
 /// </summary>
 /// <param name="iso">The isolation level under which the transaction should run. </param>
 /// <returns>An object representing the new transaction.</returns>
 public Task <MySqlTransaction> BeginTransactionAsync(IsolationLevel iso)
 {
     return(BeginTransactionAsync(iso, CancellationToken.None));
 }
Example #50
0
 public DataConnectionTransaction BeginTransaction(System.Data.IsolationLevel isolationLevel)
 {
     return(new DataConnectionTransaction(new DataConnection(new FakeDataProvider(), String.Empty)));
 }
Example #51
0
 public Task <IDbContextTransaction> BeginTransactionAsync(
     System.Data.IsolationLevel isolationLevel, CancellationToken cancellationToken = default) => throw new NotImplementedException();
Example #52
0
 /// <summary>
 /// 根据事务的锁定级别开始一个新事务
 /// </summary>
 /// <param name="isoLevel">事务锁定级别</param>
 /// <returns>事务对象</returns>
 public IDbTransaction BeginTransaction(System.Data.IsolationLevel isoLevel)
 {
     m_Transaction = m_Connection.BeginTransaction(isoLevel);
     return(m_Transaction);
 }
        public virtual IDbContextTransaction BeginTransaction(IsolationLevel isolationLevel)
        {
            if (CurrentTransaction != null)
            {
                throw new InvalidOperationException(RelationalStrings.TransactionAlreadyStarted);
            }

            Open();

            return BeginTransactionWithNoPreconditions(isolationLevel);
        }
Example #54
0
 public UtlTransaction(UtlConnection connection, System.Data.IsolationLevel isolationLevel, bool readOnly)
 {
     this.BeginTransaction(connection, isolationLevel, readOnly);
 }
        private IDbContextTransaction BeginTransactionWithNoPreconditions(IsolationLevel isolationLevel)
        {
            Check.NotNull(_logger, nameof(_logger));

            _logger.LogDebug(
                RelationalLoggingEventId.BeginningTransaction,
                isolationLevel,
                il => RelationalStrings.RelationalLoggerBeginningTransaction(il.ToString("G")));

            CurrentTransaction
                = new RelationalTransaction(
                    this,
                    DbConnection.BeginTransaction(isolationLevel),
                    _logger,
                    transactionOwned: true);

            return CurrentTransaction;
        }
Example #56
0
        /// <summary>
        /// Begins a database transaction with the specified isolation level.
        /// </summary>
        /// <param name="isolationLevel">The <see cref="System.Data.IsolationLevel">isolation level</see> under which the transaction should run.</param>
        /// <returns>An <see cref="System.Data.Common.DbTransaction">DbTransaction</see>
        /// object representing the new transaction.</returns>
        /// <remarks>
        /// Currently the IsolationLevel ReadCommitted and Serializable are supported by the PostgreSQL backend.
        /// There's no support for nested transactions.
        /// </remarks>
        protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
        {
            NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "BeginDbTransaction", isolationLevel);

            return(BeginTransaction(isolationLevel));
        }
Example #57
0
        /// <summary>
        /// Begins a database transaction with the specified isolation level.
        /// </summary>
        /// <param name="level">The <see cref="System.Data.IsolationLevel">isolation level</see> under which the transaction should run.</param>
        /// <returns>A <see cref="Npgsql.NpgsqlTransaction">NpgsqlTransaction</see>
        /// object representing the new transaction.</returns>
        /// <remarks>
        /// Currently the IsolationLevel ReadCommitted and Serializable are supported by the PostgreSQL backend.
        /// There's no support for nested transactions.
        /// </remarks>
        public new NpgsqlTransaction BeginTransaction(IsolationLevel level)
        {
            NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "BeginTransaction", level);

            CheckConnectionOpen();

            if (connector.Transaction != null)
            {
                throw new InvalidOperationException(resman.GetString("Exception_NoNestedTransactions"));
            }

            return new NpgsqlTransaction(this, level);
        }
 public IDbTransaction BeginTransaction(System.Data.IsolationLevel il)
 {
     throw new NotImplementedException("BeginTransaction method not supported.");
 }
        internal OleDbTransaction(OleDbConnection connection, OleDbTransaction transaction, System.Data.IsolationLevel isolevel)
        {
            this._parentConnection = connection;
            this._parentTransaction = transaction;
            switch (isolevel)
            {
                case System.Data.IsolationLevel.Unspecified:
                    isolevel = System.Data.IsolationLevel.ReadCommitted;
                    break;

                case System.Data.IsolationLevel.Chaos:
                case System.Data.IsolationLevel.ReadUncommitted:
                case System.Data.IsolationLevel.Serializable:
                case System.Data.IsolationLevel.Snapshot:
                case System.Data.IsolationLevel.ReadCommitted:
                case System.Data.IsolationLevel.RepeatableRead:
                    break;

                default:
                    throw ADP.InvalidIsolationLevel(isolevel);
            }
            this._isolationLevel = isolevel;
        }
Example #60
-1
		internal MySqlTransaction(MySqlConnection c, System.Data.IsolationLevel il) {
			this.conn = c;
			this.level = il;
			this.open = true;
		}