/*!
\note Transaction unsafe. If you call several transaction unsafe methods you must enclose
the calls within a db transaction; thus within db->begin and db->commit.
165522
function copy( $policyID )
    {
        $newParameter = eZPolicyLimitation::createNew( $policyID, $this->attribute( 'identifier' ) );
        foreach( $this->attribute( 'values' ) as $value )
        {
            $value->copy( $newParameter->attribute( 'id' ) );
        }
    }
708607
public function commit()
    {
        if (! sasql_commit($this->connection)) {
            throw SQLAnywhereException::fromSQLAnywhereError($this->connection);
        }

        $this->endTransaction();

        return true;
    }
1242788
function close()
    {
        foreach ($this->cache as $key => $data) {
            // The key has been used
            if ($this->cache_changes[$key]) {
                // Make sure we're not going to write unchanged data
                // by comparing current md5 sum with the sum calculated on DB read
                $data = $this->serialize($data);

                if (!$this->cache_sums[$key] || $this->cache_sums[$key] != md5($data)) {
                    $this->write_record($key, $data);
                }
            }
        }

        if ($this->index_changed) {
            $this->write_index();
        }

        // reset internal cache index, thanks to this we can force index reload
        $this->index         = null;
        $this->index_changed = false;
        $this->cache         = array();
        $this->cache_sums    = array();
        $this->cache_changes = array();
    }
160441
protected function beginQuery()
    {
        $autoSlave = $this->db->isAutoSlave();
        if ($autoSlave) {
            $this->db->switchConnection('slave');
        }

        $reconnect = $this->db->getOption('reconnect');
        $reconnectRetries = $this->db->getOption('reconnect_retries', 3);
        $reconnectDelayMS = $this->db->getOption('reconnect_delay_ms', 1000);

        while (true) {
            $e = null;
            $errorCode = null;
            $errorInfo = null;
            $result = null;

            $isReconnectError = false;
            try {
                $this->prepare();
                $result = $this->statement->execute($this->params ? $this->params : $this->positionParams);
            } catch (\Exception $e) {
            }

            if ($result === false || !$e) {
                $errorCode = $this->statement->errorCode();
                $errorInfo = $this->statement->errorInfo();
            }

            $isReconnectError = Util::checkReconnectError($errorCode, $errorInfo, $e);

            // reconnect
            if ($reconnect && $isReconnectError && $reconnectRetries > 0) {
                $reconnectRetries--;
                $this->statement = null;
                $this->db->close();
                $reconnectDelayMS && usleep($reconnectDelayMS * 1000);
                continue;
            }

            break;
        }

        if ($autoSlave) {
            $this->db->switchConnection();
        }

        if ($e) {
            $this->db->logError(sprintf('Statement exception error #%s: %s', $e->getCode(), $e->getMessage()));
            throw $e;
        }

        if ($result === false) {
            $errorMsg = sprintf('Statement execute error #%s: %s', $errorInfo[0], $errorInfo[2]);
            $this->db->logError($errorMsg);
            throw new Exception($errorMsg);
        }
    }
1205980
static function begin($name = NULL, $mode = NULL)
	{
		$object = static::_instance($name);
		$name = static::instanceName($name);

		if (static::$transactions[$name]) return FALSE;
		static::$transactions[$name] = $object->begin($mode);

		return static::$transactions[$name];
	}
1064463
public function commit() {
		if (!$this->inTransaction) {
			return false;
		}

		$this->inTransaction = false;
		return $this->pdo->commit();
	}
226327
public function delete() {
        $sql = new Sql();
        $transaction = Database::instance()->db()->inTransaction();

        if (!$transaction) {
            Database::instance()->db()->beginTransaction();
        }

        foreach ($this->_fields as $field) {
            if ($field->primary == false) {
                if ($field->foreign != null) {
                    switch ($field->foreign->type()) {
                        case ForeignKey::ONE_TO_ONE :
                            /** if it's a one to one relation, we delete the linked Entity */
                            if ($field->value != null) {
                                if (gettype($field->value) != 'object') {
                                    if ($field->foreign->type() == Builder::JOIN_INNER) {
                                        throw new MissingEntityException('The field "' . $field->name . '" in "' . $this->_name . '" must be an Entity');
                                    }
                                }
                                if (get_class($field->value) != 'System\Collection\Collection') {
                                    throw new MissingEntityException('The field "' . $field->name . '" in "' . $this->_name . '" must be an Entity');
                                }

                                $field->value->delete();
                            }
                            break;

                        case ForeignKey::MANY_TO_ONE :
                            if ($field->value != null) {
                                if ($field->foreign->belong() == ForeignKey::COMPOSITION) {
                                    if (gettype($field->value) != 'object') {
                                        throw new MissingEntityException('The field "' . $field->name . '" in "' . $this->_name . '" must be an Entity');
                                    }
                                    if (get_class($field->value) != 'System\Collection\Collection') {
                                        throw new MissingEntityException('The field "' . $field->name . '" in "' . $this->_name . '" must be an Entity');
                                    }

                                    $field->value->delete();
                                }
                            }
                            break;

                        case ForeignKey::ONE_TO_MANY :
                            if ($field->value != null) {
                                if (gettype($field->value) != 'object') {
                                    throw new MissingEntityException('The field "' . $field->name . '" in "' . $this->_name . '" must be a Collection');
                                }
                                if (get_class($field->value) != 'System\Collection\Collection') {
                                    throw new MissingEntityException('The field "' . $field->name . '" in "' . $this->_name . '" must be a Collection');
                                }

                                if ($field->foreign->belong() == ForeignKey::COMPOSITION) {
                                    /** @var $entity \Gcs\Framework\Core\Orm\Entity\Entity */
                                    foreach ($field->value as $entity) {
                                        if ($entity != null) {
                                            $field->value->delete();
                                        }
                                    }
                                }
                            }
                            break;

                        case ForeignKey::MANY_TO_MANY :
                            /** Here we must delete from the referenced table and the relation table too */
                            if ($field->value != null) {
                                if (gettype($field->value) != 'object') {
                                    throw new MissingEntityException('The field "' . $field->name . '" in "' . $this->_name . '" must be a Collection');
                                }
                                if (get_class($field->value) != 'System\Collection\Collection') {
                                    throw new MissingEntityException('The field "' . $field->name . '" in "' . $this->_name . '" must be a Collection');
                                }

                                if ($field->foreign->belong() == ForeignKey::COMPOSITION) {
                                    $currentEntity = $field->foreign->entity();
                                    $currentField = $field->foreign->field();
                                    $referenceEntity = $field->foreign->referenceEntity();
                                    $referenceField = $field->foreign->referenceField();

                                    $current = strtolower($currentEntity . $currentField);
                                    $reference = strtolower($referenceEntity . $referenceField);
                                    $table = [$current, $reference];
                                    sort($table, SORT_STRING);
                                    $table = ucfirst($table[0] . $table[1]);

                                    $sql = new Sql();
                                    $sql->query('orm-delete-many', 'DELETE FROM ' . $table . ' WHERE ' . $this->name() . '_' . $field->foreign->referenceField() . ' = ' . $this->_fields[$this->_primary]);
                                    $sql->fetch('orm-delete-many');

                                    /** @var $entity \Gcs\Framework\Core\Orm\Entity\Entity */
                                    foreach ($field->value as $entity) {
                                        if ($entity != null) {
                                            $field->value->delete();
                                        }
                                    }
                                }
                            }
                            break;
                    }
                }
                else {
                    switch ($field->type) {
                        case Field::FILE :
                            if ($field->unique) {
                                $field->value->delete();
                            }
                            break;
                    }
                }
            }
        }

        $query = 'DELETE FROM ' . $this->_name . ' WHERE ' . $this->_fields[$this->_primary]->name . ' = ' . $this->_fields[$this->_primary]->value;

        $sql->query('delete_' . $this->_name . '_' . $this->_token, $query);
        $sql->fetch('delete_' . $this->_name . '_' . $this->_token, Sql::PARAM_FETCHDELETE);

        if (!$transaction) {
            Database::instance()->db()->commit();
        }
    }
994114
public function begin()
    {
        // we'll rely on buffer to respond data that has not yet committed, so
        // it must never evict from cache - I'd even rather see the app crash
        $buffer = new Buffer(ini_get('memory_limit'));

        // transactions can be nested: the previous transaction will serve as
        // cache backend for the new cache (so when committing a nested
        // transaction, it will commit to the parent transaction)
        $cache = end($this->transactions);
        $this->transactions[] = new Transaction($buffer, $cache);
    }
358665
protected function safeDbReconnection(){
        if(empty(Yii::$app->db->pdo->getAttribute(constant("PDO::ATTR_PERSISTENT")))){
            Yii::$app->db->close();
            Yii::$app->db->open();
        }
    }
307227
function(startIndex) {
    ("production" !== process.env.NODE_ENV ? invariant(
      this.isInTransaction(),
      'Transaction.closeAll(): Cannot close transaction when none are open.'
    ) : invariant(this.isInTransaction()));
    var transactionWrappers = this.transactionWrappers;
    for (var i = startIndex; i < transactionWrappers.length; i++) {
      var wrapper = transactionWrappers[i];
      var initData = this.wrapperInitData[i];
      var errorThrown;
      try {
        // Catching errors makes debugging more difficult, so we start with
        // errorThrown set to true before setting it to false after calling
        // close -- if it's still set to true in the finally block, it means
        // wrapper.close threw.
        errorThrown = true;
        if (initData !== Transaction.OBSERVED_ERROR && wrapper.close) {
          wrapper.close.call(this, initData);
        }
        errorThrown = false;
      } finally {
        if (errorThrown) {
          // The closer for wrapper i threw an error; close the remaining
          // wrappers but silence any exceptions from them to ensure that the
          // first error is the one to bubble up.
          try {
            this.closeAll(i + 1);
          } catch (e) {
          }
        }
      }
    }
    this.wrapperInitData.length = 0;
  }
371417
public function commit()
    {
        if (!$this->started) {
            throw new \RuntimeException('Cannot commit transaction before start');
        }
        if (!$this->pdo->commit()) {
            throw new \RuntimeException('Failed to commit transaction');
        }

        $this->started = false;
    }
885967
function initializeObjectAttribute( $contentObjectAttribute, $currentVersion, $originalContentObjectAttribute )
    {
        if ( $currentVersion != false )
        {
            $originalContentObjectAttributeID = $originalContentObjectAttribute->attribute( 'id' );
            $contentObjectAttributeID = $contentObjectAttribute->attribute( 'id' );
            $contentObjectAttributeVersion = $contentObjectAttribute->attribute( 'version' );

            $db = eZDB::instance();
            $db->begin();

            // Delete stored object attributes when initialize translated attribute.
            if ( $originalContentObjectAttributeID != $contentObjectAttributeID )
                $this->deleteStoredObjectAttribute( $contentObjectAttribute, $currentVersion );

            $newVersionEnumObject = eZEnumObjectValue::fetchAllElements( $originalContentObjectAttributeID, $currentVersion );

            for ( $i = 0; $i < count( $newVersionEnumObject ); ++$i )
            {
                $enumobjectvalue =  $newVersionEnumObject[$i];
                $enumobjectvalue->setAttribute( 'contentobject_attribute_id', $contentObjectAttribute->attribute( 'id' ) );
                $enumobjectvalue->setAttribute( 'contentobject_attribute_version',  $contentObjectAttributeVersion );
                $enumobjectvalue->store();
            }

            $db->commit();
        }
    }
652994
function _close()
	{
		if ($this->transCnt) $this->RollbackTrans();
		$rez = @mssql_close($this->_connectionID);
		$this->_connectionID = false;
		return $rez;
	}
774478
public function begin()
    {
        $context = $this->_context;

        $this->logger->info('transaction begin', 'db.transaction.begin');

        if ($context->transaction_level === 0) {
            $this->eventsManager->fireEvent('db:beginTransaction', $this);

            try {
                $connection = $this->poolManager->pop($this, $this->_timeout);

                if (!$connection->beginTransaction()) {
                    throw new DbException('beginTransaction failed.');
                }
                $context->connection = $connection;
            } catch (\PDOException $exception) {
                throw new DbException('beginTransaction failed: ' . $exception->getMessage(), $exception->getCode(), $exception);
            } finally {
                if (!$context->connection) {
                    $this->poolManager->push($this, $context);
                }
            }
        }

        $context->transaction_level++;
    }
1276451
public function beginTransaction() {
		if ($this->inTransaction()) {
			throw new Exception('Transaction already is active');
		}
		$this->_inTransaction = true;
		$this->_commitMode = (PHP_VERSION_ID >= 503020) ? OCI_NO_AUTO_COMMIT : OCI_DEFAULT;

		return true;
	}
425981
public function transactionStart()
    {
        if (empty($this->oDb)) {
            $this->connect();
        }

        try {

            $this->oDb->beginTransaction();
            $this->transactionRunning = true;

            return true;

        } catch (\Exception $e) {
            throw new TransactionException($e->getMessage(), $e->getCode());
        }
    }
1076731
function _close()
	{
		if (!$this->_connectionID) {
			return;
		}


		if (!$this->autoCommit) {
			oci_rollback($this->_connectionID);
		}
		if (count($this->_refLOBs) > 0) {
			foreach ($this ->_refLOBs as $key => $value) {
				$this->_refLOBs[$key]['LOB']->free();
				unset($this->_refLOBs[$key]);
			}
		}
		oci_close($this->_connectionID);

		$this->_stmt = false;
		$this->_connectionID = false;
	}