Overrides the save method to allow temporal models to be
@param boolean $cascade
@param boolean $use_transaction
@param boolean $skip_temporal Skips temporal filtering on initial inserts. Should not be used!
@return boolean
968545
public function save($cascade = null, $use_transaction = false)
	{
		// Load temporal properties.
		$timestamp_start_name = static::temporal_property('start_column');
		$timestamp_end_name = static::temporal_property('end_column');
		$mysql_timestamp = static::temporal_property('mysql_timestamp');

		$max_timestamp = static::temporal_property('max_timestamp');
		$current_timestamp = $mysql_timestamp ?
			\Date::forge()->format('mysql') :
			\Date::forge()->get_timestamp();

		// If this is new then just call the parent and let everything happen as normal
		if ($this->is_new())
		{
			static::disable_primary_key_check();
			$this->{$timestamp_start_name} = $current_timestamp;
			$this->{$timestamp_end_name} = $max_timestamp;
			static::enable_primary_key_check();

			// Make sure save will populate the PK
			static::enable_id_only_primary_key();
			$result = parent::save($cascade, $use_transaction);
			static::disable_id_only_primary_key();

			return $result;
		}
		// If this is an update then set a new PK, save and then insert a new row
		else
		{
			// run the before save observers before checking the diff
			$this->observe('before_save');

			// then disable it so it doesn't get executed by parent::save()
			$this->disable_event('before_save');

			$diff = $this->get_diff();

			if (count($diff[0]) > 0)
			{
				// Take a copy of this model
				$revision = clone $this;

				// Give that new model an end time of the current time after resetting back to the old data
				$revision->set($this->_original);

				self::disable_primary_key_check();
				$revision->{$timestamp_end_name} = $current_timestamp;
				self::enable_primary_key_check();

				// Make sure relations stay the same
				$revision->_original_relations = $this->_data_relations;

				// save that, now we have our archive
				self::enable_id_only_primary_key();
				$revision_result = $revision->overwrite(false, $use_transaction);
				self::disable_id_only_primary_key();

				if ( ! $revision_result)
				{
					// If the revision did not save then stop the process so the user can do something.
					return false;
				}

				// Now that the old data is saved update the current object so its end timestamp is now
				self::disable_primary_key_check();
				$this->{$timestamp_start_name} = $current_timestamp;
				self::enable_primary_key_check();

				$result = parent::save($cascade, $use_transaction);
			}
			else
			{
				// If nothing has changed call parent::save() to insure relations are saved too
				$result = parent::save($cascade, $use_transaction);
			}

			// make sure the before save event is enabled again
			$this->enable_event('before_save');

			return $result;
		}
	}
1355548
public void writeObjects(boolean reuse) throws TransactionAbortedException, LockNotGrantedException
    {
        PersistenceBroker broker = transaction.getBroker();
        ConnectionManagerIF connMan = broker.serviceConnectionManager();
        boolean saveBatchMode = connMan.isBatchMode();

        try
        {
            if(log.isDebugEnabled())
            {
                log.debug(
                        "PB is in internal tx: "
                                + broker.isInTransaction()
                                + "  broker was: "
                                + broker);
            }
            // all neccessary db operations are executed within a PersistenceBroker transaction:
            if(!broker.isInTransaction())
            {
                log.error("PB associated with current odmg-tx is not in tx");
                throw new TransactionAbortedException("Underlying PB is not in tx, was begin call done before commit?");
            }

            // Committing has to be done in two phases. First implicitly upgrade to lock on all related
            // objects of objects in this transaction. Then the list of locked objects has to be
            // reordered to solve referential integrity dependencies, then the objects are
            // written into the database.

            // 0. turn on the batch mode
            connMan.setBatchMode(true);

            // 1. mark objects no longer available in collection
            // for delete and add new found objects
            checkAllEnvelopes(broker);

            // 2. mark all dependend objects for cascading insert/delete
            cascadingDependents();

            // 3. upgrade implicit locks.
            //upgradeImplicitLocksAndCheckIfCommitIsNeeded();
            upgradeLockIfNeeded();

            // 4. Reorder objects
            reorder();
//            System.out.println("## ordering: ");
//            for(int i = 0; i < mvOrderOfIds.size(); i++)
//            {
//                System.out.println("" + mvOrderOfIds.get(i));
//            }
//            System.out.println("## ordering end");

            // 5. write objects.
            writeAllEnvelopes(reuse);

            // 6. execute batch
            connMan.executeBatch();

            // 7. Update all Envelopes to new CleanState
            prepareForReuse(reuse);

            // 6. commit cleanup
            afterWriteCleanup();

        }
        catch(Exception e)
        {
            connMan.clearBatch();
            /*
            arminw:
            log only a warn message, because in top-level methods
            a error log will be done ditto
            */
            if(e instanceof OptimisticLockException)
            {
                // make error log to show the full stack trace one time
                log.error("Optimistic lock exception while write objects", e);
                // PB OptimisticLockException should be clearly signalled to the user
                Object sourceObject = ((OptimisticLockException) e).getSourceObject();
                throw new LockNotGrantedException("Optimistic lock exception occur, source object was (" + sourceObject + ")," +
                        " message was (" + e.getMessage() + ")");
            }
            else if(!(e instanceof RuntimeException))
            {
                log.warn("Error while write objects for tx " + transaction, e);
                throw new ODMGRuntimeException("Unexpected error while write objects: " + e.getMessage());
            }
            else
            {
                log.warn("Error while write objects for tx " + transaction, e);
                throw (RuntimeException) e;
            }
        }
        finally
        {
            needsCommit = false;
            connMan.setBatchMode(saveBatchMode);
        }
    }
764036
private CommitResult commitTransaction(TransactionScope<K> transactionScope) {
    TransactionLog<MapUpdate<K, byte[]>> transactionLog = transactionScope.transactionLog();
    boolean retainTombstones = !activeTransactions.isEmpty();

    List<AtomicMapEvent<K, byte[]>> eventsToPublish = Lists.newArrayList();
    for (MapUpdate<K, byte[]> record : transactionLog.records()) {
      if (record.type() == MapUpdate.Type.VERSION_MATCH) {
        continue;
      }

      K key = record.key();
      checkState(preparedKeys.remove(key), "key is not prepared");

      if (record.type() == MapUpdate.Type.LOCK) {
        continue;
      }

      MapEntryValue previousValue = entries().remove(key);

      // Cancel the previous timer if set.
      cancelTtl(previousValue);

      MapEntryValue newValue = null;

      // If the record is not a delete, create a transactional commit.
      if (record.type() != MapUpdate.Type.REMOVE_IF_VERSION_MATCH) {
        newValue = new MapEntryValue(MapEntryValue.Type.VALUE, currentVersion, record.value(), 0, 0);
      } else if (retainTombstones) {
        // For deletes, if tombstones need to be retained then create and store a tombstone commit.
        newValue = new MapEntryValue(MapEntryValue.Type.TOMBSTONE, currentVersion, null, 0, 0);
      }

      AtomicMapEvent<K, byte[]> event;
      if (newValue != null) {
        entries().put(key, newValue);
        if (!valueIsNull(newValue)) {
          if (!valueIsNull(previousValue)) {
            event = new AtomicMapEvent<>(
                AtomicMapEvent.Type.UPDATE,
                key,
                toVersioned(newValue),
                toVersioned(previousValue));
          } else {
            event = new AtomicMapEvent<>(
                AtomicMapEvent.Type.INSERT,
                key,
                toVersioned(newValue),
                null);
          }
        } else {
          event = new AtomicMapEvent<>(
              AtomicMapEvent.Type.REMOVE,
              key,
              null,
              toVersioned(previousValue));
        }
      } else {
        event = new AtomicMapEvent<>(
            AtomicMapEvent.Type.REMOVE,
            key,
            null,
            toVersioned(previousValue));
      }
      eventsToPublish.add(event);
    }
    publish(eventsToPublish);
    return CommitResult.OK;
  }
1269191
public function otherTrans(array $transaction = null)
    {
        // morph Transaction extension - will read the type of transaction
        // and instantiate the correct class extending Transaction.
        $morphed = Transaction::create($transaction ?: $this->getAttribute("otherTrans"));

        if ($morphed->type === TransactionType::MULTISIG) {
            // cannot nest multisig in another multisig.
            throw new InvalidArgumentException("It is forbidden to nest a Multisig transaction in another Multisig transaction.");
        }
        elseif ($morphed->type === TransactionType::MULTISIG_SIGNATURE) {
            // cannot nest multisig in another multisig.
            throw new InvalidArgumentException("It is forbidden to nest a Signature transaction in the inner transaction of a Multisig transaction.");
        }

        return $morphed;
    }
632317
public function replayTransactionLog($fromDate = null, $toDate = null)
    {
        return $this->getDataUpdater()->replayTransactionLog($fromDate, $toDate);
    }
1150078
public function toBytes(bool $skipSignature = true, bool $skipSecondSignature = true): Buffer
    {
        $buffer = new Writer();
        $buffer->writeUInt8($this->type);
        $buffer->writeUInt32($this->timestamp);
        $buffer->writeHex($this->senderPublicKey);

        $skipRecipientId = $this->type === Types::SECOND_SIGNATURE_REGISTRATION || $this->type === Types::MULTI_SIGNATURE_REGISTRATION;
        if (isset($this->recipientId) && ! $skipRecipientId) {
            $buffer->writeHex(Base58::decodeCheck($this->recipientId)->getHex());
        } else {
            $buffer->fill(21);
        }

        if (isset($this->vendorField) && strlen($this->vendorField) <= 64) {
            $buffer->writeString($this->vendorField);
            $vendorFieldLength = strlen($this->vendorField);

            if ($vendorFieldLength < 64) {
                $buffer->fill(64 - $vendorFieldLength);
            }
        } else {
            $buffer->fill(64);
        }

        $buffer->writeUInt64($this->amount);
        $buffer->writeUInt64($this->fee);

        if (Types::SECOND_SIGNATURE_REGISTRATION === $this->type) {
            $buffer->writeHex($this->asset['signature']['publicKey']);
        }

        if (Types::DELEGATE_REGISTRATION === $this->type) {
            $buffer->writeString($this->asset['delegate']['username']);
        }

        if (Types::VOTE === $this->type) {
            $buffer->writeString(implode('', $this->asset['votes']));
        }

        if (Types::MULTI_SIGNATURE_REGISTRATION === $this->type) {
            $buffer->writeUInt8($this->asset['multisignature']['min']);
            $buffer->writeUInt8($this->asset['multisignature']['lifetime']);
            $buffer->writeString(implode('', $this->asset['multisignature']['keysgroup']));
        }

        if (! $skipSignature && $this->signature) {
            $buffer->writeHex($this->signature);
        }

        if (! $skipSecondSignature && isset($this->signSignature)) {
            $buffer->writeHex($this->signSignature);
        }

        return new Buffer($buffer->toBytes());
    }
624599
protected void doCleanupAfterCompletion(Object transaction) {
        ContextSourceAndHibernateTransactionObject actualTransactionObject = (ContextSourceAndHibernateTransactionObject) transaction;

        super.doCleanupAfterCompletion(actualTransactionObject
                .getHibernateTransactionObject());
        ldapManagerDelegate.doCleanupAfterCompletion(actualTransactionObject
                .getLdapTransactionObject());
    }
953534
public static void transaction(Runnable action, boolean readOnly) {
		Ctx ctx = Ctxs.get();
		boolean newContext = ctx == null;

		if (newContext) {
			ctx = Ctxs.open("transaction");
		}

		try {
			EntityManager em = ctx.persister();
			JPA.with(em).transactional(action, readOnly);

		} finally {
			if (newContext) {
				Ctxs.close();
			}
		}
	}
303618
public function removeTransaction( $transaction = self::TRANSACTION_LAST_USED, $throwExceptionIfNotFound = true )
    {

        // remove all transactions
        if( $transaction === self::TRANSACTIONS_ALL ) {
            $numTransactions = count( $this->queue );
            $this->queue = array();
            $this->lastTransaction = null;
            return $numTransactions;
        }

        // last created transaction
        if( $transaction === self::TRANSACTION_LAST_CREATED ) {
            $keys = array_keys( $this->queue );
            if( $transaction = array_pop( $keys ) ) {
                if( $this->lastTransaction === $transaction ) {
                    $this->lastTransaction = null;
                }
                unset( $this->queue[$transaction] );
                return 1;
            }
            return 0;
        }

        // last used
        if( $transaction === self::TRANSACTION_LAST_USED ) {
            if( $this->lastTransaction ) {
                unset( $this->queue[$this->lastTransaction] );
                $this->lastTransaction = null;
                return 0;
            }
            return 0;
        }

        // array of transactions
        if( is_array( $transaction ) ) {
            $output = 0;
            foreach( $transaction as $name ) {
                if( array_key_exists( $name, $this->queue ) ) {
                    if( $this->lastTransaction === $name ) {
                        $this->lastTransaction = null;
                    }
                    unset( $this->queue[$name] );
                    $output++;
                } elseif ( $throwExceptionIfNotFound ) {
                    throw new TransactionDoesNotExistException(
                        "Transaction with this name `{$name}` doesn't exist. Sorry."
                    );
                }
            }
            return $output;
        }

        if( is_scalar($transaction) ) {
            if( array_key_exists( $transaction, $this->queue ) ) {
                if( $this->lastTransaction === $transaction ) {
                    $this->lastTransaction = null;
                }
                unset( $this->queue[$name] );
                return 1;
            } elseif ( $throwExceptionIfNotFound ) {
                throw new TransactionDoesNotExistException(
                    "Transaction with this name `{$transaction}` doesn't exist. Sorry."
                );
            }
            return 0;
        }

        throw new \InvalidArgumentException(
            sprintf(
                "Not sure how to remove transaction `%s`",
                print_r( $transaction, true )
            )
        );

    }
791100
public function transactionStart($transactionMode = false, $sessionCharacteristics = false)
    {
        if ($this->transactionNesting > 0) {
            $this->transactionSavepoint('NESTEDTRANSACTION' . $this->transactionNesting);
        } elseif ($this->connector instanceof SQLServerConnector) {
            $this->connector->transactionStart();
        } else {
            $this->query('BEGIN TRANSACTION');
        }
        ++$this->transactionNesting;
    }
408992
protected function _validateTransaction(Transaction $transaction)
    {
        if (!$transaction->getParent() && in_array($transaction->getType()->getValue(), array(
            Transaction\TransactionType::CAPTURE,
            Transaction\TransactionType::REFUND
        ))) {
            throw ValidationException::parentTransactionRequired();
        }
    }
132460
protected function removeExpiredJobs($transaction, $from, $time)
    {
        $transaction->multi();

        $transaction->zremrangebyscore($from, '-inf', $time);
    }
497611
public final void persist(BatchingContext batchingContext, TransactionState tranState)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "persist", new Object[] { batchingContext, tranState});

        if ((tranState == TransactionState.STATE_COMMITTED) || (tranState == TransactionState.STATE_COMMITTING_1PC))
        {
            batchingContext.updateRedeliveredCountOnly(getPersistable());
        }
        else
        {
            throw new IllegalStateException(nls.getFormattedMessage("INVALID_TASK_OPERATION_SIMS1520", new Object[] {tranState}, null));
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "persist");
    }
1144606
public function persist( $object, $transaction = self::TRANSACTION_LAST_USED )
    {
        if( !is_object( $object ) ) {
            throw new \InvalidArgumentException("I can only persist objects.");
        }

        if( !( $object instanceof Task) ) {
            $object = $this->getTask( $object, Task::PERSIST );
        }

        $transaction = $this->getTransaction($transaction, true);
        $this->queue[$transaction][] = $object;

        return $this;
    }
100384
def skip_tree_node(self, tree_node, tx_context=None):
        
        if not tx_context:
            # create transaction context if one was not provided
            # format: {process_name: {timeperiod: AbstractTreeNode} }
            tx_context = collections.defaultdict(dict)

        if tree_node.timeperiod in tx_context[tree_node.process_name]:
            # the node has already been marked for skipping
            return tx_context

        if tree_node.job_record.is_finished:
            # the node is finished and does not require skipping
            pass
        else:
            state_machine_name = context.process_context[tree_node.process_name].state_machine_name
            state_machine = self.state_machines[state_machine_name]
            state_machine.skip_job(tree_node.job_record)

        tx_context[tree_node.process_name][tree_node.timeperiod] = tree_node
        for timeperiod, node in tree_node.children.items():
            self.skip_tree_node(node, tx_context)

        dependant_nodes = self._find_dependant_tree_nodes(tree_node)
        for node in dependant_nodes:
            self.skip_tree_node(node, tx_context)

        return tx_context
1294861
public function save(TransactionInterface $transaction = null, bool $queueRelations = true): int
    {
        /*
         * First, per interface agreement calculate entity state after save command being called.
         */
        if (!$this->isLoaded()) {
            $state = self::CREATED;
        } elseif (!$this->hasChanges()) {
            $state = self::UPDATED;
        } else {
            $state = self::UNCHANGED;
        }

        if (empty($transaction)) {
            /*
             * When no transaction is given we will create our own and run it immediately.
             */
            $transaction = $transaction ?? new Transaction();
            $transaction->store($this, $queueRelations);
            $transaction->run();
        } else {
            $transaction->addCommand($this->queueStore($queueRelations));
        }

        return $state;
    }
1167173
private SynchronizationAdapter createSynchronizationAdapter(Transaction transaction) {
      SynchronizationAdapter adapter = new SynchronizationAdapter(transaction, RemoteXid.create(uuid));
      try {
         transaction.registerSynchronization(adapter);
      } catch (RollbackException | SystemException e) {
         throw new CacheException(e);
      }
      if (trace) {
         log.tracef("Registered synchronization for transaction %s. Sync=%s", transaction, adapter);
      }
      return adapter;
   }