Ejemplo n.º 1
0
 public function beginTransaction()
 {
     if (!$this->transactionCounter++) {
         return $this->pdo->beginTransaction();
     }
     return $this->transactionCounter >= 0;
 }
Ejemplo n.º 2
0
 private function _logCompletedJob(array $job)
 {
     $this->_pdo->beginTransaction();
     $this->_pdo->prepare("INSERT INTO {$this->_table_log} (id,app_id,metric,value,distinct_id,created_at,sent_at) VALUES(?,?,?,?,?,?,?)")->execute(array($job['id'], $job['app_id'], $job['metric'], $job['value'], $job['distinct_id'], $job['created_at'], date("Y-m-d H:i:s")));
     $this->_pdo->prepare("DELETE FROM {$this->_table_jobs} WHERE id = ? LIMIT 1")->execute(array($job['id']));
     $this->_pdo->commit();
 }
Ejemplo n.º 3
0
 /**
  * Executes the critical code within a transaction.
  *
  * It's up to the user to set the correct transaction isolation level.
  * However if the transaction fails, the code will be executed again in a
  * new transaction. Therefore the code must not have any side effects
  * besides SQL statements. Also the isolation level should be conserved for
  * the repeated transaction.
  *
  * A transaction is considered as failed if a PDOException or an exception
  * which has a PDOException as any previous exception was raised.
  *
  * If the code throws any other exception, the transaction is rolled back
  * and won't  be replayed.
  *
  * @param callable $code The synchronized execution block.
  * @return mixed The return value of the execution block.
  * @SuppressWarnings(PHPMD)
  *
  * @throws \Exception The execution block threw an exception.
  * @throws LockAcquireException The transaction was not commited.
  */
 public function synchronized(callable $code)
 {
     return $this->loop->execute(function () use($code) {
         try {
             // BEGIN
             $this->pdo->beginTransaction();
         } catch (\PDOException $e) {
             throw new LockAcquireException("Could not begin transaction.", 0, $e);
         }
         try {
             // Unit of work
             $result = call_user_func($code);
             $this->pdo->commit();
             $this->loop->end();
             return $result;
         } catch (\Exception $e) {
             $this->rollBack($e);
             if ($this->hasPDOException($e)) {
                 return;
                 // Replay
             } else {
                 throw $e;
             }
         }
     });
 }
Ejemplo n.º 4
0
 /**
  * Выполняет запрос миграцию.
  * @param string $migrationName имя миграции
  * @param string $query запрос
  * @param string $type тип миграции
  * @return bool|\Exception|\PDOException
  * @throw \RuntimeException в случае, если не удалось применить
  */
 protected function runMigration($migrationName, $query, $type = 'up')
 {
     if (empty($query)) {
         throw new \RuntimeException('В миграции отсутствует запрос');
     }
     try {
         $this->db->beginTransaction();
         $statement = $this->db->prepare($query);
         $result = $statement->execute();
         if (!$result) {
             throw new \RuntimeException('Запрос не был выполнен');
         }
         $statement->closeCursor();
         if ($type == 'up') {
             $this->addMigrationInfo($migrationName);
         } else {
             $this->removeMigrationInfo($migrationName);
         }
         $this->db->commit();
     } catch (\PDOException $e) {
         $this->db->rollBack();
         throw $e;
     }
     return true;
 }
Ejemplo n.º 5
0
 /**
  * {@inheritdoc}
  */
 public function beginTransaction()
 {
     $this->profiler->startQuery("START TRANSACTION;");
     $result = $this->pdo->beginTransaction();
     $this->profiler->stopQuery();
     return $result;
 }
Ejemplo n.º 6
0
    /**
     * Creates, when necessary, and returns a PDO instance
     * @return PDO
     */
    public static function getInstance($usesTransaction = false) {
        try {
            if (!self::$instance) {
                self::$instance = new \PDO(
                        \core\Config::DATABASE_ADDRESS,
                        \core\Config::DATABASE_USERNAME,
                        \core\Config::DATABASE_PASSWORD,
                        array(
                                \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
                                \PDO::ATTR_PERSISTENT => true
                        )
                );
                self::$instance->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            }
            if ($usesTransaction && !self::$openTransaction) {
                self::$instance->beginTransaction();
                self::$openTransaction = true;
            }
            return self::$instance;

        } catch (\Exception $e) {
            $ex = new RepositoryException($e);
            $ex->setFatal(true);
            throw $ex;
        }
    }
Ejemplo n.º 7
0
 /**
  * executes all the update classes
  */
 private function _performUpdates()
 {
     foreach ($this->_availableUpdates as $rev => $updateList) {
         foreach ($updateList as $u) {
             if (!empty($u[3]) && $this->_conn->getAttribute(PDO::ATTR_DRIVER_NAME) != $u[3]) {
                 continue;
             }
             $updateFormat = $u[5];
             $this->_conn->beginTransaction();
             try {
                 $instance = null;
                 if ($updateFormat == 'sql') {
                     require_once 'Indechse/Maintain/Update/SqlExecute.php';
                     $instance = new Indechse_Maintain_Update_SqlExecute($this->_conn, $rev);
                     $instance->setSql(file_get_contents($this->_updateLocation . '/' . $u[0]));
                 } else {
                     $className = 'Update_' . $u[4];
                     require_once $this->_updateLocation . '/' . $u[0];
                     $instance = new $className($this->_conn, $rev);
                 }
                 $instance->update();
                 $this->_markUpdateComplete($rev, $u[4] . '.' . $u[5]);
                 $this->_conn->commit();
             } catch (Exception $ex) {
                 $this->_conn->rollBack();
                 throw new Exception(sprintf("Update %s (%d) failed with message: %s", $u[0], $rev, $ex->getMessage()), $ex->getCode(), $ex);
             }
         }
     }
 }
Ejemplo n.º 8
0
 /**
  * Process an entity by reading / writing to the DB
  *
  * @param string        $table
  * @param callable|null $callback
  * @param bool          $pretend
  * @param bool          $returnResult
  *
  * @return void|array
  */
 public function processEntity($table, $callback = null, $pretend = true, $returnResult = false)
 {
     $queries = array();
     $actionsOnThatEntity = $this->whatToDoWithEntity($table);
     if ($actionsOnThatEntity & self::TRUNCATE_TABLE) {
         $where = $this->getWhereConditionInConfig($table);
         $query = $this->runDelete($table, $where, $pretend);
         $returnResult === true ? array_push($queries, $query) : '';
     }
     if ($actionsOnThatEntity & self::UPDATE_TABLE) {
         // I need to read line by line if I have to update the table
         // to make sure I do update by update (slower but no other choice for now)
         $i = 0;
         $this->preparedStmt = null;
         $key = $this->getPrimaryKey($table);
         $res = $this->pdo->query("SELECT {$key} FROM {$table}");
         $res->setFetchMode(\PDO::FETCH_ASSOC);
         $this->pdo->beginTransaction();
         while ($row = $res->fetch()) {
             $val = $row['id'];
             $data = $this->generateFakeData($table);
             if ($pretend === false) {
                 $this->runUpdate($table, $data, $key, $val);
             }
             $returnResult === true ? array_push($queries, $this->buildUpdateSQL($table, $data, "{$key} = '{$val}'")) : '';
             if (!is_null($callback)) {
                 $callback(++$i);
             }
         }
         // Commit, even if I am in pretend (that will do ... nothing)
         $this->pdo->commit();
     }
     return $queries;
 }
 public function startTransaction()
 {
     if ($this->pdo->inTransaction()) {
         throw new \RuntimeException('PDO is already in a transaction. Nested transactions are not supported.');
     }
     $this->pdo->beginTransaction();
 }
Ejemplo n.º 10
0
 public function beginTransaction()
 {
     ++$this->transactionsCount;
     if ($this->transactionsCount == 1) {
         $this->pdo->beginTransaction();
     }
 }
Ejemplo n.º 11
0
 /**
  * Démarre une transaction ou créer un point de sauvegarde dans la transaction courante
  * @return bool
  */
 private function beginTransaction()
 {
     if (!$this->transactionCounter++) {
         return $this->pdolink->beginTransaction();
     }
     $this->pdolink->exec('SAVEPOINT trans'.$this->transactionCounter);
     return true;
 }
Ejemplo n.º 12
0
 public function beginTransaction()
 {
     if (!$this->transactionNestable() || $this->transLevel == 0) {
         $this->dbh->beginTransaction();
     } else {
         $this->dbh->exec(sprintf('SAVEPOINT LEVEL%d', $this->transLevel));
     }
     $this->transLevel++;
 }
Ejemplo n.º 13
0
 /**
  * @param string $file
  */
 public function __construct($file)
 {
     $this->db = new \PDO('sqlite:' . $file);
     $this->db->exec('CREATE TABLE metadata (name TEXT, value TEXT);');
     $this->db->exec('CREATE TABLE tiles (zoom_level INTEGER, tile_column INTEGER, tile_row INTEGER, tile_data BLOB);');
     $this->db->exec('CREATE UNIQUE INDEX tile_index ON tiles (zoom_level, tile_column, tile_row);');
     $this->db->beginTransaction();
     $this->addMetaStmt = $this->db->prepare('INSERT INTO metadata (name, value) VALUES (:name, :value)');
     $this->addTileStmt = $this->db->prepare('INSERT INTO tiles (zoom_level, tile_column, tile_row, tile_data) VALUES (:z, :x, :y, :data)');
 }
Ejemplo n.º 14
0
 /**
  * starts transaction
  */
 public function beginTransaction()
 {
     $this->checkConnection();
     try {
         $this->_pdo->beginTransaction();
         $this->_lastCheckTime = time();
     } catch (\PDOException $e) {
         $this->_error($e->getMessage(), FQDBException::PDO_CODE, $e);
     }
 }
Ejemplo n.º 15
0
 /**
  * @param string $script
  */
 public function run($script)
 {
     try {
         $this->pdo->beginTransaction();
         $this->pdo->query($script);
         $this->pdo->commit();
     } catch (\PDOException $e) {
         $this->pdo->rollBack();
     }
 }
Ejemplo n.º 16
0
 /**
  * Replace current token after successful authentication
  * @param $credential
  * @param $token
  * @param $persistentToken
  * @param int $expire
  */
 public function replaceTriplet($credential, $token, $persistentToken, $expire = 0)
 {
     try {
         $this->connection->beginTransaction();
         $this->cleanTriplet($credential, $persistentToken);
         $this->storeTriplet($credential, $token, $persistentToken, $expire);
         $this->connection->commit();
     } catch (\PDOException $e) {
         $this->connection->rollBack();
         throw $e;
     }
 }
Ejemplo n.º 17
0
 public function it_can_rollBack_on_error_during_update_user(User $user)
 {
     $user->getUuid()->willReturn($uuid = Uuid::uuid4());
     $user->getEmailAddress()->willReturn(EmailAddress::get($email = '*****@*****.**'));
     $user->getPassword()->willReturn($password = password_hash('no.jedi.please', PASSWORD_BCRYPT));
     $user->getDisplayName()->willReturn($displayName = 'Nute Gunray');
     $this->pdo->beginTransaction()->shouldBeCalled();
     $exception = new \RuntimeException();
     $this->pdo->prepare(new Argument\Token\StringContainsToken('UPDATE users'))->willThrow($exception);
     $this->pdo->rollBack()->shouldBeCalled();
     $this->shouldThrow($exception)->duringUpdate($user);
 }
Ejemplo n.º 18
0
 /**
  * Executes a function in a transaction.
  *
  * @param callable $callable The function to execute transactionally
  *
  * @return mixed The non-empty value returned from the closure or true instead.
  *
  * @throws \Exception during execution of the function or transaction commit,
  *                    the transaction is rolled back and the exception re-thrown
  */
 public function transactional(callable $callable)
 {
     $this->pdo->beginTransaction();
     try {
         $return = call_user_func($callable, $this);
         $this->pdo->commit();
         return $return ?: true;
     } catch (\Exception $exception) {
         $this->pdo->rollback();
         throw $exception;
     }
 }
Ejemplo n.º 19
0
 /**
  * @param \Closure $queries
  * @return bool
  */
 public function transaction(\Closure $queries)
 {
     $this->connection->beginTransaction();
     try {
         $queries($this);
         $this->connection->commit();
         return true;
     } catch (Exception $e) {
         $this->connection->rollback();
         return false;
     }
 }
Ejemplo n.º 20
0
 public function it_will_rollBack_on_error_during_update(ConfigCollection $collection, \PDOStatement $itemStatement1)
 {
     $uuid = Uuid::uuid4();
     $items = ['k1' => 'v1', 'k2' => 'v2'];
     $collection->getUuid()->willReturn($uuid);
     $collection->getItems()->willReturn($items);
     $this->pdo->beginTransaction()->shouldBeCalled();
     $this->pdo->prepare(new Argument\Token\StringContainsToken('UPDATE config_items'))->willReturn($itemStatement1, false);
     $itemStatement1->execute(['config_collection_uuid' => $uuid->getBytes(), 'name' => 'k1', 'value' => json_encode('v1')])->willThrow(new \RuntimeException());
     $this->pdo->rollBack()->shouldBeCalled();
     $this->shouldThrow(\RuntimeException::class)->duringUpdate($collection);
 }
Ejemplo n.º 21
0
 /**
  * @param $post
  * @return false|Post
  */
 public function create($post)
 {
     $sql = "INSERT INTO posts (user_id, message , created_at ,updated_at)  values (:user_id, :message, now(), now())";
     $stmt = $this->dbh->prepare($sql);
     $stmt->bindParam(':user_id', $post['user_id']);
     $stmt->bindParam(':message', $post['message']);
     $this->dbh->beginTransaction();
     $stmt->execute();
     $post = $this->findByID($this->dbh->lastInsertId());
     $this->dbh->commit();
     return $post;
 }
Ejemplo n.º 22
0
 public function flush()
 {
     $this->pdo->beginTransaction();
     try {
         foreach ($this->stack as $data) {
             $this->statement->execute($data);
         }
         $this->stack = [];
         $this->pdo->commit();
     } catch (\PDOException $e) {
         throw new WriterException('Failed to write to database', null, $e);
     }
 }
Ejemplo n.º 23
0
 /**
  * Materialize a view and then replace the view by its materialized version in the same schema
  * @param $view_name the name of the view to materialize
  */
 public function materializeInPlace($view_name)
 {
     $materialized_view_name = $view_name . "_materialized";
     // select * into materialize_tmp
     $materialize_sql = "select *  into " . $materialized_view_name . " from " . $view_name;
     $this->pdo->exec($materialize_sql);
     // swap the materialized view for original view
     $this->pdo->beginTransaction();
     $this->pdo->exec("drop view {$view_name}");
     $rename_sql = "alter table {$materialized_view_name} rename to {$view_name}";
     $this->pdo->exec($rename_sql);
     $this->pdo->commit();
 }
Ejemplo n.º 24
0
 public function update(ConfigCollection $collection)
 {
     $this->pdo->beginTransaction();
     try {
         $this->updateItems($collection);
         $this->objectRepository->update(ConfigCollection::TYPE, $collection->getUuid());
         $collection->metaDataSetUpdateTimestamp(new \DateTimeImmutable());
         $this->pdo->commit();
     } catch (\Throwable $exception) {
         $this->pdo->rollBack();
         throw $exception;
     }
 }
Ejemplo n.º 25
0
 /**
  * This is run before each unit test; it populates the database.
  */
 protected function setUp()
 {
     parent::setUp();
     if (true !== self::$isInitialized) {
         $file = __DIR__ . '/../../../../Fixtures/bookstore/build/conf/bookstore-conf.php';
         if (!file_exists($file)) {
             return;
         }
         Propel::init(__DIR__ . '/../../../../Fixtures/bookstore/build/conf/bookstore-conf.php');
         self::$isInitialized = true;
     }
     $this->con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
     $this->con->beginTransaction();
 }
Ejemplo n.º 26
0
 /**
  * Read session data
  *
  * @param string $sessionId
  * @return string
  */
 public function read($sessionId)
 {
     try {
         $this->db->exec('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
         $this->db->beginTransaction();
         $this->transaction = true;
         $stmt = $this->db->prepare('SELECT * FROM `sys__sessions` WHERE `id` = :id FOR UPDATE');
         $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
         $stmt->execute();
         return $stmt->rowCount() ? $this->getResult($stmt) : $this->insertRecord($stmt, $sessionId);
     } catch (\PDOException $e) {
         $this->rollback();
         throw $e;
     }
 }
Ejemplo n.º 27
0
 /**
  * Migrationを実行します。
  * 
  */
 public function execute()
 {
     $config = $this->dataSource->getDataSourceConfig();
     foreach ($config as $name => $dsn) {
         print "** start migration for {$name}. \n";
         $conn = $this->dataSource->getConnection($name);
         $this->pdo = $conn->getDB();
         // DBのmigratoin番号を取得
         $remote_num = $this->getRemoteNum();
         print "remote: {$remote_num}\n";
         // ローカルのmigration番号を取得
         $local = new Teeple_Migration_Local(dirname(BASE_DIR) . "/migration/" . $name);
         $local_num = $local->getMaxNum();
         print "local: {$local_num}\n";
         while ($remote_num < $local_num) {
             $remote_num++;
             print "apply {$remote_num}..";
             $ddl = $local->getContent($remote_num);
             $ddllist = explode(';', $ddl);
             try {
                 foreach ($ddllist as $q) {
                     $q = trim($q);
                     if (strlen($q)) {
                         $stmt = $this->pdo->prepare($q);
                         $stmt->execute();
                     }
                 }
             } catch (Exception $e) {
                 print "fail.\n";
                 print $e->getMessage();
                 return;
             }
             $this->pdo->beginTransaction();
             $stmt = $this->pdo->prepare("UPDATE " . self::TABLE_NAME . " SET version = {$remote_num}");
             $stmt->execute();
             $this->pdo->commit();
             print "success.\n";
         }
         print "** finish migration for {$name}. \n";
     }
     // --entityがセットされていたらEntityも更新する
     if (isset($this->_argv) && in_array('--entity', $this->_argv)) {
         print "\n*** update entity class.\n";
         $entityGenerator = Teeple_Container::getInstance()->getComponent('Teeple_EntityGenerator');
         $entityGenerator->_argv = array('--force');
         $entityGenerator->execute();
     }
 }
Ejemplo n.º 28
0
 /**
  * Seed database from configuration
  * 
  * @return void
  */
 public function seedFromConfig()
 {
     // Begin transation
     $this->pdo->beginTransaction();
     // Seed tables
     foreach ($this->schema['seed'] as $schema) {
         if (isset($this->tables[$schema['table']])) {
             $table = $this->tables[$schema['table']];
             if (isset($schema['truncate']) && ($sql = $this->getTruncate($table))) {
                 $this->pdo->exec($sql);
             }
             if (isset($schema['values'])) {
                 $sql = $this->getInsert($table, $schema['values']);
                 $stm = $this->pdo->prepare($sql);
                 $values = array();
                 foreach ($schema['values'] as $k => $v) {
                     $values[] = $this->parseValue($v);
                 }
                 $stm->execute($values);
             }
         }
     }
     // Commit changes
     $this->pdo->commit();
 }
Ejemplo n.º 29
0
 function beginTransaction()
 {
     if (!$this->transactionCounter++) {
         return parent::beginTransaction();
     }
     return $this->transactionCounter >= 0;
 }
Ejemplo n.º 30
0
 private function insertStatsToDb($data)
 {
     $statsDbHostName = $_SERVER['STATS_DB_HOST'];
     $statsDbName = $_SERVER['STATS_DB_NAME'];
     $statsDbUser = $_SERVER['STATS_DB_USER'];
     $statsDbPass = $_SERVER['STATS_DB_PASS'];
     $dbh = null;
     try {
         $dbh = new PDO("mysql:host={$statsDbHostName};dbname={$statsDbName}", $statsDbUser, $statsDbPass);
         $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
         $dbh->beginTransaction();
         $stmt = $dbh->prepare("INSERT IGNORE INTO editorstats (wiki_id, revision_id, editor, user_groups)\n \t\t\t\tVALUES (:wiki_id, :revision_id, :editor, :user_groups)");
         $stmt->bindParam(':wiki_id', $wiki_id);
         $stmt->bindParam(':revision_id', $revision_id);
         $stmt->bindParam(':editor', $editor);
         $stmt->bindParam(':user_groups', $user_groups);
         foreach ($data as $rev) {
             $wiki_id = $rev['wiki_id'];
             $revision_id = $rev['revision_id'];
             $editor = $rev['editor'];
             $user_groups = $rev['user_groups'];
             $stmt->execute();
         }
         $dbh->commit();
     } catch (PDOException $error) {
         $dbh->rollback();
         print $error->getMessage();
     }
 }