Example #1
0
 public function beginTran()
 {
     echo "Beginning a transaction\n";
     if (!$this->db->beginTransaction()) {
         throw new \Exception('Beginning transaction failed');
     }
     return $this;
 }
Example #2
0
 /**
  * Constructor
  *
  * @access public
  * @param  object  $pdo         PDO database object
  * @param  boolean $transaction Use database transactions [optional]
  * @param  boolean $sessionName Session name [optional]
  * @return void
  */
 public function __construct($pdo, $transaction = false, $sessionName = 'PDOSESSID')
 {
     // Set database connection
     $this->db = $pdo;
     if ($transaction) {
         $this->transaction = true;
         $this->db->beginTransaction();
     }
     // Start session
     session_set_save_handler(array(__CLASS__, '_open'), array(__CLASS__, '_close'), array(__CLASS__, '_read'), array(__CLASS__, '_write'), array(__CLASS__, '_destroy'), array(__CLASS__, '_gc'));
     session_name($sessionName);
     session_start();
 }
Example #3
0
 /**
  * (non-PHPdoc)
  * @see PDO::beginTransaction()
  */
 public function beginTransaction()
 {
     if (!$this->pdo->inTransaction) {
         $this->pdo->beginTransaction();
     }
     return true;
 }
Example #4
0
 /**
  * 开启事务处理
  *
  * @access public
  * @return boolean
  */
 public function startTrans()
 {
     if ($this->Transactions == false) {
         $this->db_link->beginTransaction();
         $this->Transactions = true;
     }
     return true;
 }
 /**
         This method begins the transaction
         @access public
  		@throws PDOException object
         @return void
 */
 public function begin_transaction()
 {
     try {
         if (!$this->DBHandler->inTransaction()) {
             $this->DBHandler->beginTransaction();
         }
     } catch (PDOException $e) {
         throw $e;
     }
 }
 /**
  * 开启事务处理
  *
  * @access public
  *
  * @return boolean
  */
 public function startTrans()
 {
     if ($this->_transactions == false) {
         $this->_dbLink->beginTransaction();
         $this->_transactions = true;
         //SQL日志记录
         $this->_logQuery('BEGIN');
     }
     return true;
 }
Example #7
0
 public static function beginTransaction()
 {
     try {
         if (!self::$instance instanceof \PDO) {
             throw new \PDOException(self::$exception['no-instance']);
         }
         if (!self::$instance->beginTransaction()) {
             throw new \PDOException(current(self::$instance->errorInfo()) . ' ' . end(self::$instance->errorInfo()));
         }
     } catch (\PDOException $e) {
         self::stackTrace($e);
     }
 }
Example #8
0
 /**
  * Initiates a transaction
  * 
  * @return	boolean
  */
 public function beginTransaction()
 {
     if ($this->supportTransaction == false) {
         throw new LikePDOException("This driver doesn't support transactions");
         return false;
     } elseif ($this->inTransaction == true) {
         throw new LikePDOException("There is already an active transaction");
         return false;
     } else {
         if (!$this->driver->beginTransaction()) {
             throw new LikePDOException("Failed to begin transaction");
             return false;
         }
         return true;
     }
 }
Example #9
0
 /**
  * Write data associated with a given unique ID to container
  *
  * @access public
  * @param  string  $uniqueId  IP address or other unique ID.
  * @param  array   $data      The data associated with a given unique ID.
  * @return void
  * @throws HTTP_FloodControl_Exception if an error occured during writing process.
  */
 public function write($uniqueId, $data)
 {
     $quotedTblName = $this->_db->quoteIdentifier($this->_options['table']);
     $this->_db->beginTransaction();
     $query = sprintf("DELETE FROM %s WHERE unique_id = %s", $quotedTblName, $this->_db->quote($uniqueId, 'text'));
     $result = $this->_db->exec($query);
     if (PEAR::isError($result)) {
         throw new HTTP_FloodControl_Exception($result->getMessage(), $result->getCode());
     }
     $query = sprintf("INSERT INTO %s (unique_id, data, access) VALUES (%s, %s, %d)", $quotedTblName, $this->_db->quote($uniqueId, 'text'), $this->_db->quote(serialize($data), 'text'), time());
     $result = $this->_db->exec($query);
     if (PEAR::isError($result)) {
         $this->_db->rollback();
         throw new HTTP_FloodControl_Exception($result->getMessage(), $result->getCode());
     }
     $this->_db->commit();
 }
Example #10
0
 /**
  * Flush the write cache to db
  *
  * @access public
  */
 public function flushWriteCache()
 {
     if ($this->writeCacheData !== null) {
         $trans = $this->db->beginTransaction();
         /** can't create a prepared sql because some parameters can be null ??? */
         foreach ($this->writeCacheData as $key1 => $value1) {
             foreach ($value1 as $key2 => $value) {
                 $fields = array('do_id' => $this->absOrNull($this->do_id), 'app_id' => $this->absOrNull($this->app_id), 'us_id' => $this->absOrNull($this->us_id), 'se_section' => $key1, 'se_param' => $key2);
                 $sql = "UPDATE " . $this->options['settings_table'] . " SET \n" . "  se_value = " . $this->db->quote($this->writeCacheData[$key1][$key2]) . " \n" . "WHERE \n" . $this->array2Where($fields);
                 $affectedRows = $this->db->exec($sql);
                 $this->checkDBError($affectedRows, __LINE__);
                 if ($affectedRows == 0) {
                     $sql = "INSERT INTO " . $this->options['settings_table'] . " " . "  (do_id, app_id, us_id,se_section, se_param, se_value) " . "VALUES " . "  (" . $this->db->quote($this->absOrNull($this->do_id)) . ", " . $this->db->quote($this->absOrNull($this->app_id)) . ", " . $this->db->quote($this->absOrNull($this->us_id)) . ", " . $this->db->quote($key1) . ", " . $this->db->quote($key2) . ", " . $this->db->quote($this->writeCacheData[$key1][$key2]) . ")";
                     $res = $this->db->exec($sql);
                     $this->checkDBError($res, __LINE__);
                 }
             }
         }
         $trans = $this->db->commit();
         $this->writeCacheData = null;
     }
 }
Example #11
0
File: PDO.php Project: b091/mkphp-1
 /**
  * Rozpoczęcie głównego bloku transakcji: DB->StartTrans()
  *
  * 1. Bloki transakcji można zagnieżdzać, ale nie jest wtedy uruchamiana nowa transakcja.
  * Inkrementowana jest jedynie wartość $this->transOff.
  * Podczas wywoływania CompleteTrans() wartość $this->transOff jest pomniejszana o 1.
  *
  * 2. Dopóki nie uruchomimy metody CompleteTrans(), to cała zawartość bloku będzie
  * uruchomiona z domyślnym Rollback-iem (sekwencje zostaną "przebite",
  * ale operacje na wierszach zostaną przywrócone).
  *
  * 3. Pomiędzy StartTrans() a CompleteTrans() metody BeginTrans/CommitTrans/RollbackTrans
  * zostaną zablokowane (nieaktywne).
  *
  * 4. Wywołanie metody CompleteTrans() śledzi błędy, więc jeśli wystąpił jakiś błąd SQL
  * lub została wywołana wcześniej metoda FailTrans(), to zostanie uruchomiony ROLLBACK.
  *
  * @throws MK_Db_Exception
  * @return bool
  */
 public function transStart()
 {
     // Zwrócenie szczegółowego komunikatu w konsoli FireBug-a
     if (MK_DEBUG_FIREPHP) {
         $this->fireBugSqlDump("transStart");
     }
     if (MK_Db_PDO_Singleton::transCount() > 0) {
         MK_Db_PDO_Singleton::transCount(1);
         return true;
     }
     /**
      *   true  - transakcja została utworzona
      *   false - baza danych nie obsługuje transakcji
      */
     MK_Db_PDO_Singleton::transOk(false);
     $transOk = $this->db->beginTransaction();
     if (!$transOk) {
         throw new MK_Db_Exception('Baza danych nie obsługuje transakcji');
     }
     MK_Db_PDO_Singleton::transOk(true);
     MK_Db_PDO_Singleton::transCount(1, true);
     return $transOk;
 }
Example #12
0
 /**
  * Delete a node and it's children
  *
  * @param int $keyValue Primary key of node
  * @return bool If it happend or not
  */
 public function deleteNode($keyValue)
 {
     try {
         $this->_pdoInstance->beginTransaction();
         $this->_lockTables();
         $node = $this->getSimpleNode($keyValue);
         // Delete the node
         $deleteSql = "DELETE FROM `" . $this->getTable() . "`\n                          WHERE\n                              `" . $this->getLeftColumn() . "`\n                                  BETWEEN '" . $node[$this->getLeftColumn()] . "'\n                                  AND '" . $node[$this->getRightColumn()] . "'";
         $this->_pdoInstance->exec($deleteSql);
         // Update left values of other nodes
         $updateSql = "UPDATE `" . $this->getTable() . "`\n                          SET `" . $this->getLeftColumn() . "` = `" . $this->getLeftColumn() . "` - ROUND(\n                              ('" . $node[$this->getRightColumn()] . "' - '" . $node[$this->getLeftColumn()] . "' + 1)\n                          )\n                          WHERE `" . $this->getLeftColumn() . "` > '" . $node[$this->getRightColumn()] . "'";
         $this->_pdoInstance->exec($updateSql);
         // Update right values of other nodes
         $updateSql = "UPDATE `" . $this->getTable() . "`\n                          SET `" . $this->getRightColumn() . "` = `" . $this->getRightColumn() . "` - ROUND(\n                              ('" . $node[$this->getRightColumn()] . "' - '" . $node[$this->getLeftColumn()] . "' + 1)\n                          )\n                          WHERE `" . $this->getRightColumn() . "` > '" . $node[$this->getRightColumn()] . "'";
         $this->_pdoInstance->exec($updateSql);
         $this->_pdoInstance->exec("UNLOCK TABLES");
         $this->_pdoInstance->commit();
         return true;
     } catch (\PDOException $e) {
         $this->_pdoInstance->rollBack();
         return false;
     }
 }
Example #13
0
 /**
  * Delete element with number $ID from the tree and all it childret.
  *
  * @param integer $ID Number of element
  * @param array $condition Array structure: array('and' => array('id = 0', 'id2 >= 3'), 'or' => array('sec = \'www\'', 'sec2 <> \'erere\'')), etc where array key - condition (AND, OR, etc), value - condition string
  * @return bool TRUE if successful, FALSE otherwise.
  */
 function DeleteAll($ID, $condition = '')
 {
     $node_info = $this->GetNodeInfo($ID);
     if (FALSE === $node_info) {
         return FALSE;
     }
     list($leftId, $rightId) = $node_info;
     if (!empty($condition)) {
         $condition = $this->_PrepareCondition($condition);
     }
     $sql = 'DELETE FROM ' . $this->table . ' WHERE ' . $this->table_left . ' BETWEEN ' . $leftId . ' AND ' . $rightId;
     $this->db->beginTransaction();
     try {
         $res = $this->db->query($sql);
         $deltaId = $rightId - $leftId + 1;
         $sql = 'UPDATE ' . $this->table . ' SET ' . $this->table_left . ' = CASE WHEN ' . $this->table_left . ' > ' . $leftId . ' THEN ' . $this->table_left . ' - ' . $deltaId . ' ELSE ' . $this->table_left . ' END, ' . $this->table_right . ' = CASE WHEN ' . $this->table_right . ' > ' . $leftId . ' THEN ' . $this->table_right . ' - ' . $deltaId . ' ELSE ' . $this->table_right . ' END ' . 'WHERE ' . $this->table_right . ' > ' . $rightId;
         $sql .= $condition;
         $res = $this->db->query($sql);
         $this->db->commit();
         return TRUE;
     } catch (Exception $e) {
         $this->db->rollBack();
     }
 }
Example #14
0
 /**
  * Démarre le mode transactionnel
  * 
  * @access public
  * @return boolean
  */
 function beginTransaction()
 {
     return $this->pdo->beginTransaction();
 }
Example #15
0
/**
 * Procedimiento que almacena el item de menú como parte del historial de 
 * navegación del usuario indicado por $uid. El historial del usuario debe 
 * cumplir las siguientes propiedades:
 * - El historial es una lista con un máximo número de items (5), parecido, pero
 *   no idéntico, a una cola FIFO.
 * - Los items están ordenados por su ID de inserción. El item más reciente es
 *   el item de mayor número de inserción.
 * - Repetidas llamadas sucesivas a esta función con el mismo valor de $uid y 
 *   $menu deben dejar la lista inalterada, asumiendo que no hayan otras 
 *   ventanas de navegación abierta.
 * - Si la lista tiene su número máximo de items y se agrega un nuevo item que
 *   no estaba previamente presente en la lista, el item más antiguo se olvida.
 * - Si el item resulta idéntico en menú a uno que ya existe, debe de quitarse
 *   de su posición actual y colocarse en la parte superior de la lista. El 
 *   número de items debe quedar inalterado.
 * 
 * @param   object  $pdbACL     Objeto paloDB conectado a las tablas de ACL.
 * @param   object  $pACL       Objeto paloACL para consultar IDs de menú.
 * @param   integer $uid        ID de usuario para el historial
 * @param   string  $menu       Item de menú a insertar en el historial
 * 
 * @return  bool    VERDADERO si se inserta el item, FALSO en error.  
 */
function putMenuAsHistory($pdbACL, $pACL, $uid, $menu)
{
    global $arrConf;
    $pDB = new paloDB($arrConf['elastix_dsn']['settings']);
    if (empty($pDB->errMsg)) {
        $uelastix = get_key_settings($pDB, 'uelastix');
        if ((int) $uelastix != 0) {
            return TRUE;
        }
    }
    $id_resource = $pACL->getResourceId($menu);
    if (is_null($id_resource)) {
        return FALSE;
    }
    // Leer historial actual. El item 0 es el más reciente
    $sqlselect = <<<SQL_LEER_HISTORIAL
SELECT aus.id AS id, ar.id AS id_menu FROM acl_user_shortcut aus, acl_resource ar
WHERE id_user = ? AND type = 'history' AND ar.id = aus.id_resource
ORDER BY aus.id DESC    
SQL_LEER_HISTORIAL;
    $historial = $pdbACL->fetchTable($sqlselect, TRUE, array($uid));
    if (!is_array($historial)) {
        return FALSE;
    }
    if (count($historial) > 0 && $historial[0]['id_menu'] == $id_resource) {
        return TRUE;
    }
    // Idempotencia
    for ($i = 0; $i < count($historial); $i++) {
        $historial[$i]['modified'] = FALSE;
    }
    // Procesar la lista según las reglas requeridas
    $shiftindex = NULL;
    for ($i = 0; $i < count($historial); $i++) {
        if ($historial[$i]['id_menu'] == $id_resource) {
            $shiftindex = $i;
            break;
        }
    }
    if (is_null($shiftindex) && count($historial) >= 5) {
        $shiftindex = count($historial);
    }
    // Insertar nuevo item al inicio, corriendo los items si es necesario
    if (!is_null($shiftindex)) {
        for ($i = $shiftindex; $i > 0; $i--) {
            if ($i < count($historial)) {
                $historial[$i]['id_menu'] = $historial[$i - 1]['id_menu'];
                $historial[$i]['modified'] = TRUE;
            }
        }
        $historial[0]['id_menu'] = $id_resource;
        $historial[0]['modified'] = TRUE;
    } else {
        array_unshift($historial, array('id' => NULL, 'id_menu' => $id_resource, 'modified' => TRUE));
    }
    // Guardar en la DB todas las modificaciones
    $pdbACL->beginTransaction();
    foreach ($historial as $item) {
        if ($item['modified']) {
            if (is_null($item['id'])) {
                $sqlupdate = 'INSERT INTO acl_user_shortcut (id_resource, id_user, type) VALUES (?, ?, ?)';
                $paramsql = array($item['id_menu'], $uid, 'history');
            } else {
                $sqlupdate = 'UPDATE acl_user_shortcut SET id_resource = ? WHERE id_user = ? AND type = ? AND id = ?';
                $paramsql = array($item['id_menu'], $uid, 'history', $item['id']);
            }
            if (!$pdbACL->genQuery($sqlupdate, $paramsql)) {
                $pdbACL->rollBack();
                return FALSE;
            }
        }
    }
    $pdbACL->commit();
    return TRUE;
}
Example #16
0
 /**
  * Begin transaction.
  *
  * @return bool
  */
 public function beginTransaction()
 {
     return $this->dbHandle->beginTransaction();
 }
Example #17
0
 /**
  * 事务开始
  */
 public function beginTransaction()
 {
     $this->_getChoiceDbConnect(true);
     $this->_db->beginTransaction();
 }
Example #18
0
 /**
  * Begin Transaction 
  * 
  * @access public
  * @return void
  */
 public function begin()
 {
     $this->dbh->beginTransaction();
 }
Example #19
0
 /**
  * @return boolean
  */
 public function beginTransaction()
 {
     return $this->pdoConn->beginTransaction();
 }
Example #20
0
 /**
  * 
  * Leave autocommit mode and begin a transaction.
  * 
  * @return void
  * 
  */
 public function begin()
 {
     $this->connect();
     $time = microtime(true);
     $result = $this->_pdo->beginTransaction();
     $this->_addProfile($time, '__BEGIN');
     return $result;
 }
Example #21
0
 /**
  * Method to begin a transaction.
  * Use a transaction where you are performing multiple inserts and/or updates as part
  * of a single conceptual operation.
  *
  * @access public
  * @param  void
  * @return void
  */
 public function beginTransaction()
 {
     if ($this->_db->supports('transactions')) {
         $this->_db->beginTransaction();
         $this->_inTransaction = TRUE;
     }
 }
Example #22
0
 /**
  * transBegin : start a transaction
  * @return boolean       Operation result
  */
 public function transBegin()
 {
     if (empty($this->_db)) {
         return false;
     }
     $result = true;
     try {
         // turn off autocommit and start a transaction
         $result = $this->_db->beginTransaction();
         if ($this->_debug_mode) {
             $this->log_last_query();
         }
     } catch (PDOException $e) {
         $this->log_last_query();
         $result = false;
         log_message('error', 'Failed to start transaction : ' . $e->getMessage() . ' [ ' . $e->getCode() . ' ]');
     }
     return $result;
 }
Example #23
0
File: Pdo.php Project: mwyatt/core
 public function beginTransaction()
 {
     return $this->connection->beginTransaction();
 }
Example #24
0
 /**
  * Import phpcs CSV results file
  *
  * @param string $csv CSV filename
  * @param string $paths Paths of file just sniffed
  * @return void
  */
 protected function _importCsv($csv, $paths = null)
 {
     if (null === $paths) {
         $paths = $this->_paths;
     }
     $sql = "DELETE FROM snif_results";
     // FIXME: This only correctly works if you are re-running
     // the sniff on a specific file, not a subdirectory
     if ($paths != $this->_paths) {
         // We ran the sniff for a specific file
         foreach ($paths as $path) {
             $sqlString = $sql . " WHERE file = '" . realpath($path) . "';";
             $this->_db->executeQuery($sqlString);
         }
     } else {
         // Yes, just delete everything.
         $this->_db->executeQuery($sql);
     }
     $row = 0;
     $handle = fopen($csv, 'r');
     $cols = fgetcsv($handle, 1000, ',');
     if (substr($cols[0], 0, 5) == 'ERROR') {
         throw new Exception("Error importing csv: " . $cols[0]);
     }
     if ($this->_qis->isVerbose()) {
         $this->_qis->log("Writing results to db");
     } else {
         echo "Writing results to db...";
     }
     $sqlPre = "INSERT INTO snif_results ('file', 'line', 'column', " . "'severity', 'message', 'sniffcode') VALUES ";
     $this->_db->beginTransaction();
     while (($data = fgetcsv($handle, 1000, ',')) !== false) {
         // only add the row if there was a 1,
         // otherwise there was probably an error in the csv file
         if (!isset($data[1])) {
             continue;
         }
         if ($data[0] == $cols[0]) {
             // No data, we got the headers again.
             if ($this->_qis->isVerbose()) {
                 $this->_qis->log('No sniff results found.');
             }
             break;
         }
         if ($this->_includeSniffCodes) {
             $sniffCode = $this->_db->escape($data[5]);
         } else {
             $sniffCode = '';
         }
         $sqlRow = "('" . $this->_db->escape($data[0]) . "'," . $this->_db->escape($data[1]) . "," . $this->_db->escape($data[2]) . "," . "'" . $this->_db->escape($data[3]) . "'," . "'" . $this->_db->escape($data[4]) . "'," . "'" . $sniffCode . "')";
         $sql = $sqlPre . $sqlRow;
         $this->_db->executeQuery($sql);
         if ($this->_qis->isVerbose()) {
             echo '.';
         }
         $row++;
     }
     $this->_db->commit();
     if ($this->_qis->isVerbose()) {
         $this->_qis->log('Finished writing results to db.');
     } else {
         echo "done\n";
     }
     return true;
 }
Example #25
0
 /**
  * 开始一个事务
  * @access public
  */
 public function beginTransaction()
 {
     $this->connect();
     return $this->link->beginTransaction();
 }
Example #26
0
 /**
  * Begin a transaction.
  */
 protected function _beginTransaction()
 {
     $this->_connect();
     $this->connection->beginTransaction();
 }