/** * @param object $command * @param callable $next * * @return mixed * @throws \Exception when Transaction fails to commit. */ public function execute($command, callable $next) { $this->connection->begin(); try { $returnValue = $next($command); $isCommitted = $this->connection->commit(); } catch (\Exception $e) { $this->connection->rollback(); throw $e; } if (!$isCommitted) { throw new \Exception('Failed to commit the transaction.'); } return $returnValue; }
/** * Set all sequence's current value to the lowest available field value. * * @return bool */ public function sequences() { $this->out(sprintf('%s - %s', date('H:i:s'), 'Set all sequence\'s current values')); $success = $this->connection->begin() !== false; $schema = Hash::get($this->connection->config(), 'schema') ?: 'public'; $conditions = ["table_schema = '{$schema}'"]; foreach ($this->connection->driver()->sequences($conditions) as $sequence) { $sequence['sequence'] = preg_replace('/^nextval\\(\'(.*)\'.*\\)$/', '\\1', $sequence['sequence']); $sql = "SELECT setval('{$sequence['sequence']}', COALESCE(MAX({$sequence['column']}),0)+1, false) FROM {$sequence['table']};"; $success = $success && $this->connection->query($sql)->fetchAll('assoc') !== false; } if ($success) { $success = $this->connection->commit() !== false && $success; } else { $success = $this->connection->rollback() !== false && $success; } if ($this->command === __FUNCTION__) { $this->_stop($success ? self::SUCCESS : self::ERROR); } return $success; }
/** * Begin a transaction. * * @return void */ public function beginTransaction() { $this->connection->begin(); }