Пример #1
0
 /**
  * Returns the integer value of the generated identifier for the new object.
  * Called right after execution of the insert query.
  * Dispatches to {@link ezcPersistentNativeGenerator} for MySQL.
  *
  * @param ezcPersistentObjectDefinition $def
  * @param ezcDbHandler $db
  * @return int
  */
 public function postSave(ezcPersistentObjectDefinition $def, ezcDbHandler $db)
 {
     if ($db->getName() == "mysql" || $db->getName() == "sqlite") {
         $native = new ezcPersistentNativeGenerator();
         return $native->postSave($def, $db);
     }
     $id = null;
     if (array_key_exists('sequence', $def->idProperty->generator->params) && $def->idProperty->generator->params['sequence'] !== null) {
         switch ($db->getName()) {
             case "oracle":
                 $idRes = $db->query("SELECT " . $db->quoteIdentifier($def->idProperty->generator->params['sequence']) . ".CURRVAL AS id FROM " . $db->quoteIdentifier($def->table))->fetch();
                 $id = (int) $idRes["id"];
                 break;
             default:
                 $id = (int) $db->lastInsertId($db->quoteIdentifier($def->idProperty->generator->params['sequence']));
                 break;
         }
     } else {
         $id = (int) $db->lastInsertId();
     }
     // check that the value was in fact successfully received.
     if ($db->errorCode() != 0) {
         return null;
     }
     return $id;
 }
Пример #2
0
 /**
  * Applies the differences defined in $dbSchemaDiff to the database referenced by $db.
  *
  * This method uses {@link convertDiffToDDL} to create SQL for the
  * differences and then executes the returned SQL statements on the
  * database handler $db.
  *
  * @todo check for failed transaction
  *
  * @param ezcDbHandler    $db
  * @param ezcDbSchemaDiff $dbSchemaDiff
  */
 public function applyDiffToDb(ezcDbHandler $db, ezcDbSchemaDiff $dbSchemaDiff)
 {
     $db->beginTransaction();
     foreach ($this->convertDiffToDDL($dbSchemaDiff) as $query) {
         $db->exec($query);
     }
     $db->commit();
 }
Пример #3
0
 /**
  * Sets the correct id on the insert query.
  *
  * @param ezcPersistentObjectDefinition $def
  * @param ezcDbHandler $db
  * @param ezcQueryInsert $q
  * @return void
  */
 public function preSave(ezcPersistentObjectDefinition $def, ezcDbHandler $db, ezcQueryInsert $q)
 {
     // Sanity check.
     // ID must have been stored during the persistence check before inserting the object.
     if ($this->id === null) {
         throw new ezcPersistentIdentifierGenerationException($def->class, 'ezcPersistentManualGenerator expects the ID to be present before saving.');
     }
     $q->set($db->quoteIdentifier($def->idProperty->columnName), $q->bindValue($this->id, null, $def->idProperty->databaseType));
 }
 /**
  * Returns the integer value of the generated identifier for the new object.
  * Called right after execution of the insert query.
  *
  * @param ezcPersistentObjectDefinition $def
  * @param ezcDbHandler $db
  * @return int
  */
 public function postSave(ezcPersistentObjectDefinition $def, ezcDbHandler $db)
 {
     $id = (int) $db->lastInsertId();
     // check that the value was in fact successfully received.
     if ($db->errorCode() != 0) {
         return null;
     }
     return $id;
 }
Пример #5
0
 public static function deleteNonce(ezcDbHandler $db, $nonce)
 {
     $options = new ezcAuthenticationOpenidDbStoreOptions();
     $nonces = $options->tableNonces;
     $query = new ezcQueryDelete($db);
     $e = $query->expr;
     $query->deleteFrom($db->quoteIdentifier($nonces['name']))->where($e->eq($db->quoteIdentifier($nonces['fields']['nonce']), $query->bindValue($nonce)));
     $query = $query->prepare();
     $query->execute();
 }
 /**
  * Creates the tables contained in $schema in the database that is related to $db
  *
  * This method takes the table definitions from $schema and will create the
  * tables according to this definition in the database that is references
  * by the $db handler. If tables with the same name as contained in the
  * definitions already exist they will be removed and recreated with the
  * new definition.
  *
  * @param ezcDbHandler $db
  * @param ezcDbSchema  $dbSchema
  */
 public function saveToDb(ezcDbHandler $db, ezcDbSchema $dbSchema)
 {
     $db->beginTransaction();
     foreach ($this->convertToDDL($dbSchema) as $query) {
         if ($this->isQueryAllowed($db, $query)) {
             $db->exec($query);
         }
     }
     $db->commit();
 }
Пример #7
0
 /**
  * Constructs a handler object from the parameters $dbParams.
  *
  * Supported database parameters are:
  * - dbname|database: Database name
  * - port:            If "memory" is used then the driver will use an
  *                    in-memory database, and the database name is ignored.
  *
  * @throws ezcDbMissingParameterException if the database name was not specified.
  * @param array $dbParams Database connection parameters (key=>value pairs).
  */
 public function __construct($dbParams)
 {
     $database = false;
     foreach ($dbParams as $key => $val) {
         switch ($key) {
             case 'database':
             case 'dbname':
                 $database = $val;
                 if (!empty($database) && $database[0] != '/' && ezcBaseFeatures::os() != 'Windows') {
                     $database = '/' . $database;
                 }
                 break;
         }
     }
     // If the "port" is set then we use "sqlite::memory:" as DSN, otherwise we fallback
     // to the database name.
     if (!empty($dbParams['port']) && $dbParams['port'] == 'memory') {
         $dsn = "sqlite::memory:";
     } else {
         if ($database === false) {
             throw new ezcDbMissingParameterException('database', 'dbParams');
         }
         $dsn = "sqlite:{$database}";
     }
     parent::__construct($dbParams, $dsn);
     /* Register PHP implementations of missing functions in SQLite */
     $this->sqliteCreateFunction('md5', array('ezcQuerySqliteFunctions', 'md5Impl'), 1);
     $this->sqliteCreateFunction('mod', array('ezcQuerySqliteFunctions', 'modImpl'), 2);
     $this->sqliteCreateFunction('locate', array('ezcQuerySqliteFunctions', 'positionImpl'), 2);
     $this->sqliteCreateFunction('floor', array('ezcQuerySqliteFunctions', 'floorImpl'), 1);
     $this->sqliteCreateFunction('ceil', array('ezcQuerySqliteFunctions', 'ceilImpl'), 1);
     $this->sqliteCreateFunction('concat', array('ezcQuerySqliteFunctions', 'concatImpl'));
     $this->sqliteCreateFunction('toUnixTimestamp', array('ezcQuerySqliteFunctions', 'toUnixTimestampImpl'), 1);
     $this->sqliteCreateFunction('now', 'time', 0);
 }
Пример #8
0
 /**
  * Constructs a handler object from the parameters $dbParams.
  *
  * Supported database parameters are:
  * - dbname|database: Database name
  * - user|username:   Database user name
  * - pass|password:   Database user password
  * - host|hostspec:   Name of the host database is running on
  * - port:            TCP port
  *
  * @throws ezcDbMissingParameterException if the database name was not specified.
  * @param array $dbParams Database connection parameters (key=>value pairs).
  */
 public function __construct($dbParams)
 {
     $database = null;
     $charset = null;
     $host = null;
     $port = null;
     $socket = null;
     foreach ($dbParams as $key => $val) {
         switch ($key) {
             case 'database':
             case 'dbname':
                 $database = $val;
                 break;
             case 'host':
             case 'hostspec':
                 $host = $val;
                 break;
             case 'port':
                 $port = $val;
                 break;
         }
     }
     if (!isset($database)) {
         throw new ezcDbMissingParameterException('database', 'dbParams');
     }
     $dsn = "pgsql:dbname={$database}";
     if (isset($host) && $host) {
         $dsn .= " host={$host}";
     }
     if (isset($port) && $port) {
         $dsn .= " port={$port}";
     }
     parent::__construct($dbParams, $dsn);
 }
Пример #9
0
 /**
  * Constructs a handler object from the parameters $dbParams.
  *
  * Supported database parameters are:
  * - dbname|database: Database name
  * - user|username:   Database user name
  * - pass|password:   Database user password
  * - charset:         Client character set
  *
  * @param array $dbParams Database connection parameters (key=>value pairs).
  * @throws ezcDbMissingParameterException if the database name was not specified.
  */
 public function __construct($dbParams)
 {
     if ($dbParams instanceof PDO) {
         parent::__construct($dbParams);
         return;
     }
     $database = null;
     $charset = null;
     foreach ($dbParams as $key => $val) {
         switch ($key) {
             case 'database':
             case 'dbname':
                 $database = $val;
                 break;
             case 'charset':
                 $charset = $val;
                 break;
         }
     }
     if (!isset($database)) {
         throw new ezcDbMissingParameterException('database', 'dbParams');
     }
     $dsn = "oci:dbname={$database}";
     if (isset($charset) && $charset) {
         $dsn .= ";charset={$charset}";
     }
     $db = parent::createPDO($dbParams, $dsn);
     parent::__construct($db);
 }
Пример #10
0
 public function execute(array $input_parameters = null)
 {
     $time = microtime(true);
     if ($input_parameters === null) {
         $query = parent::execute();
     } else {
         $query = parent::execute($input_parameters);
     }
     if (method_exists($this->connection, 'log')) {
         $logger = $this->connection->log($this, $time);
         if ($input_parameters) {
             // $logger = $this->connection->getLogger();
             $logger->debug('[SQL]:: ==> execute parameters: ', array_values($input_parameters));
         }
     }
     return $query;
 }
Пример #11
0
 /**
  * Loads all autogenerated entries with given $parentId with optionally included history entries.
  *
  * @param mixed $parentId
  * @param boolean $includeHistory
  *
  * @return array
  */
 public function loadAutogeneratedEntries($parentId, $includeHistory = false)
 {
     /** @var $query \ezcQuerySelect */
     $query = $this->dbHandler->createSelectQuery();
     $query->select("*")->from($this->dbHandler->quoteTable("ezurlalias_ml"))->where($query->expr->lAnd($query->expr->eq($this->dbHandler->quoteColumn("parent"), $query->bindValue($parentId, null, \PDO::PARAM_INT)), $query->expr->eq($this->dbHandler->quoteColumn("action_type"), $query->bindValue("eznode", null, \PDO::PARAM_STR)), $query->expr->eq($this->dbHandler->quoteColumn("is_alias"), $query->bindValue(0, null, \PDO::PARAM_INT))));
     if (!$includeHistory) {
         $query->where($query->expr->eq($this->dbHandler->quoteColumn("is_original"), $query->bindValue(1, null, \PDO::PARAM_INT)));
     }
     $statement = $query->prepare();
     $statement->execute();
     return $statement->fetchAll(\PDO::FETCH_ASSOC);
 }
Пример #12
0
 /**
  * Returns the current version number for a given workflow name.
  *
  * @param  string $workflowName
  * @return int
  * @throws ezcDbException
  */
 protected function getCurrentVersionNumber($workflowName)
 {
     $query = $this->db->createSelectQuery();
     $query->select($query->alias($query->expr->max($this->db->quoteIdentifier('workflow_version')), 'version'))->from($this->db->quoteIdentifier($this->options['prefix'] . 'workflow'))->where($query->expr->eq($this->db->quoteIdentifier('workflow_name'), $query->bindValue($workflowName)));
     $stmt = $query->prepare();
     $stmt->execute();
     $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
     if ($result !== false && isset($result[0]['version']) && $result[0]['version'] !== null) {
         return $result[0]['version'];
     } else {
         return 0;
     }
 }
Пример #13
0
 public static function deleteById(ezcDbHandler $db, $id, $prefix = '')
 {
     //$db->beginTransaction();
     $q = $db->createDeleteQuery();
     $q->deleteFrom($db->quoteIdentifier($prefix . 'pipe_execution'))->where($q->expr->eq($db->quoteIdentifier('id'), $q->bindValue((int) $id)));
     $stmt = $q->prepare();
     $stmt->execute();
     $q = $db->createDeleteQuery();
     $q->deleteFrom($db->quoteIdentifier($prefix . 'pipe_execution_state'))->where($q->expr->eq($db->quoteIdentifier('execution_id'), $q->bindValue((int) $id)));
     $stmt = $q->prepare();
     $stmt->execute();
     //$db->commit();
 }
 /**
  * Creates a simple JOIN to fetch the objects defined by $relation.
  *
  * Creates a simple LEFT JOIN using the aliases defined in $relation and
  * the $srcTableAlias, to fetch all objects defined by $relation, which are
  * related to the source object, fetched by $srcTableAlias.
  * 
  * @param ezcQuerySelect $q 
  * @param string $srcTableAlias 
  * @param string $dstTableAlias 
  * @param ezcPersistentRelationFindDefinition $relation 
  */
 protected function createSimpleJoin(ezcQuerySelect $q, $srcTableAlias, $dstTableAlias, ezcPersistentRelationFindDefinition $relation)
 {
     $relationDefinition = $relation->relationDefinition;
     $first = true;
     $joinCond = null;
     foreach ($relationDefinition->columnMap as $mapping) {
         $srcColumn = $this->getColumnName($srcTableAlias, $mapping->sourceColumn);
         $destColumn = $this->getColumnName($dstTableAlias, $mapping->destinationColumn);
         if ($first) {
             $joinCond = $q->expr->eq($srcColumn, $destColumn);
             $first = false;
         } else {
             $joinCond = $q->expr->and($joinCond, $q->expr->eq($srcColumn, $destColumn));
         }
     }
     $q->leftJoin($q->alias($this->db->quoteIdentifier($relationDefinition->destinationTable), $this->db->quoteIdentifier($dstTableAlias)), $joinCond);
 }
Пример #15
0
 /**
  * Constructs a handler object from the parameters $dbParams.
  *
  * Supported database parameters are:
  * - dbname|database: Database name
  * - host|hostspec:   Name of the host database is running on
  * - port:            TCP port
  * - user|username:   Database user name
  * - pass|password:   Database user password
  *
  * @param mixed $dbParams Database connection parameters (key=>value pairs).
  * @throws ezcDbMissingParameterException if the database name was not specified.
  */
 public function __construct($dbParams)
 {
     if ($dbParams instanceof PDO) {
         parent::__construct($dbParams);
         return;
     }
     $database = null;
     $host = null;
     $port = null;
     foreach ($dbParams as $key => $val) {
         switch ($key) {
             case 'database':
             case 'dbname':
                 $database = $val;
                 break;
             case 'host':
             case 'hostspec':
                 $host = $val;
                 break;
             case 'port':
                 $port = $val;
                 break;
         }
     }
     if (!isset($database)) {
         throw new ezcDbMissingParameterException('database', 'dbParams');
     }
     if (ezcBaseFeatures::os() === 'Windows') {
         $dsn = "mssql:dbname={$database}";
     } else {
         // uses FreeTDS
         $dsn = "dblib:dbname={$database}";
     }
     if (isset($host) && $host) {
         $dsn .= ";host={$host}";
         if (isset($port) && $port) {
             $dsn .= ":{$port}";
         }
     }
     $db = parent::createPDO($dbParams, $dsn);
     parent::__construct($db);
     // setup options
     $this->setOptions(new ezcDbMssqlOptions());
 }
Пример #16
0
 /**
  * Load execution state.
  *
  * @param int $executionId  ID of the execution to load.
  * @throws ezcWorkflowExecutionException
  */
 protected function loadExecution($executionId)
 {
     $query = $this->db->createSelectQuery();
     $query->select($this->db->quoteIdentifier('workflow_id'))->select($this->db->quoteIdentifier('execution_variables'))->select($this->db->quoteIdentifier('execution_threads'))->select($this->db->quoteIdentifier('execution_next_thread_id'))->select($this->db->quoteIdentifier('execution_waiting_for'))->from($this->db->quoteIdentifier($this->options['prefix'] . 'execution'))->where($query->expr->eq($this->db->quoteIdentifier('execution_id'), $query->bindValue((int) $executionId)));
     $stmt = $query->prepare();
     $stmt->execute();
     $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
     if ($result === false || empty($result)) {
         throw new ezcWorkflowExecutionException('Could not load execution state.');
     }
     $this->id = $executionId;
     $this->nextThreadId = $result[0]['execution_next_thread_id'];
     $this->threads = ezcWorkflowDatabaseUtil::unserialize($result[0]['execution_threads']);
     $this->variables = ezcWorkflowDatabaseUtil::unserialize($result[0]['execution_variables']);
     $this->waitingFor = ezcWorkflowDatabaseUtil::unserialize($result[0]['execution_waiting_for']);
     $workflowId = $result[0]['workflow_id'];
     $this->workflow = $this->properties['definitionStorage']->loadById($workflowId);
     $query = $this->db->createSelectQuery();
     $query->select($this->db->quoteIdentifier('node_id'))->select($this->db->quoteIdentifier('node_state'))->select($this->db->quoteIdentifier('node_activated_from'))->select($this->db->quoteIdentifier('node_thread_id'))->from($this->db->quoteIdentifier($this->options['prefix'] . 'execution_state'))->where($query->expr->eq($this->db->quoteIdentifier('execution_id'), $query->bindValue((int) $executionId)));
     $stmt = $query->prepare();
     $stmt->execute();
     $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
     $active = array();
     foreach ($result as $row) {
         $active[$row['node_id']] = array('activated_from' => ezcWorkflowDatabaseUtil::unserialize($row['node_activated_from']), 'state' => ezcWorkflowDatabaseUtil::unserialize($row['node_state'], null), 'thread_id' => $row['node_thread_id']);
     }
     foreach ($this->workflow->nodes as $node) {
         $nodeId = $node->getId();
         if (isset($active[$nodeId])) {
             $node->setActivationState(ezcWorkflowNode::WAITING_FOR_EXECUTION);
             $node->setThreadId($active[$nodeId]['thread_id']);
             $node->setState($active[$nodeId]['state'], null);
             $node->setActivatedFrom($active[$nodeId]['activated_from']);
             $this->activate($node, false);
         }
     }
     $this->cancelled = false;
     $this->ended = false;
     $this->loaded = true;
     $this->resumed = false;
     $this->suspended = true;
 }
Пример #17
0
 /**
  * Performs droping field from SQLite table using temporary table
  * (workaround for "ALTER TABLE table DROP field" that not alowed in SQLite ).
  *
  * @param ezcDbHandler    $db
  * @param string          $tableName
  * @param string          $dropFieldName
  */
 private function dropField($db, $tableName, $dropFieldName)
 {
     $tmpTableName = $tableName . '_ezcbackup';
     $resultArray = $db->query("PRAGMA TABLE_INFO( {$tableName} )");
     $resultArray->setFetchMode(PDO::FETCH_NUM);
     $fieldsDefinitions = array();
     $fieldsList = array();
     foreach ($resultArray as $row) {
         $fieldSql = array();
         $fieldSql[] = "'{$row[1]}'";
         // name
         if ($row[1] == $dropFieldName) {
             continue;
             // don't include droped fileld in temporary table
         }
         $fieldSql[] = $row[2];
         // type
         if ($row[3] == '99') {
             $fieldSql[] = 'NOT NULL';
         }
         $fieldDefault = null;
         if ($row[4] != '') {
             $fieldSql[] = "DEFAULT '{$row[4]}'";
         }
         if ($row[5] == '1') {
             $fieldSql[] = 'PRIMARY KEY AUTOINCREMENT';
         }
         // FIXME: unsigned needs to be implemented
         $fieldUnsigned = false;
         $fieldsDefinitions[] = join(' ', $fieldSql);
         $fieldsList[] = $fieldSql[0];
     }
     $fields = join(', ', $fieldsDefinitions);
     $tmpTableCreateSql = "CREATE TEMPORARY TABLE '{$tmpTableName}'( {$fields}  );";
     $newTableCreateSql = "CREATE TABLE '{$tableName}'( {$fields} )";
     if (count($fieldsList) > 0) {
         $db->exec($tmpTableCreateSql);
         $db->exec("INSERT INTO '{$tmpTableName}' SELECT " . join(', ', $fieldsList) . " FROM '{$tableName}';");
         $db->exec("DROP TABLE '{$tableName}';");
         $db->exec($newTableCreateSql);
         $db->exec("INSERT INTO '{$tableName}' SELECT " . join(', ', $fieldsList) . " FROM '{$tmpTableName}';");
         $db->exec("DROP TABLE '{$tmpTableName}';");
     } else {
         throw new ezcDbSchemaDropAllColumnsException("Trying to delete all columns in table: {$tableName}");
     }
 }
Пример #18
0
 /**
  * @param   PDO|ezcDbHandler  $db
  * @return  ezcDbHandler
  */
 public static function wrapper($db)
 {
     // if (( $db instanceof ezcDbHandler) || ( $db instanceof ezcDbHandler)) {
     if ($db instanceof ezcDbInterface) {
         return $db;
     }
     if (!$db instanceof PDO) {
         throw new ezcBaseValueException('db', $db, ' is not PDO', 'parameter');
     }
     $impName = $db->getAttribute(PDO::ATTR_DRIVER_NAME);
     $className = 'ezcDbHandler' . strtoupper(substr($impName, 0, 1)) . substr($impName, 1);
     $instance = new $className($db);
     return $instance;
 }
Пример #19
0
 /**
  * Upgrades the database $db with the differences.
  *
  * @throws ezcDbSchemaInvalidWriterClassException if the handler associated
  *         with the $format is not a database schema writer.
  *
  * @param ezcDbHandler $db
  */
 public function applyToDb(ezcDbHandler $db)
 {
     $className = ezcDbSchemaHandlerManager::getDiffWriterByFormat($db->getName());
     $writer = new $className();
     self::checkSchemaDiffWriter($writer, ezcDbSchema::DATABASE);
     $writer->applyDiffToDb($db, $this);
 }
Пример #20
0
 /**
  * Drop specified temporary table
  * in a portable way.
  *
  * Developers should use this method instead of dropping temporary
  * tables with the appropriate SQL queries
  * to maintain inter-DBMS portability.
  *
  * @see createTemporaryTable()
  *
  * @param   string  $tableName Name of temporary table to drop.
  * @return void
  */
 public function dropTemporaryTable($tableName)
 {
     $this->db->exec("DROP TABLE {$tableName}");
 }
Пример #21
0
 /**
  * Creates the tables defined in the schema into the database specified through $db.
  *
  * @throws ezcDbSchemaInvalidWriterClassException if the handler associated
  *         with the $format is not a database schema writer.
  *
  * @param ezcDbHandler $db
  */
 public function writeToDb(ezcDbHandler $db)
 {
     self::initOptions();
     $className = ezcDbSchemaHandlerManager::getWriterByFormat($db->getName());
     $writer = new $className();
     self::checkSchemaWriter($writer, self::DATABASE);
     $writer->saveToDb($db, $this);
 }
Пример #22
0
 /**
  * Creates an array of select columns for $tableName.
  *
  * @param \ezcQuerySelect $q
  * @param string $tableName
  */
 protected function selectColumns(ezcQuerySelect $q, $tableName)
 {
     foreach ($this->columns[$tableName] as $col) {
         $q->select($this->dbHandler->aliasedColumn($q, $col, $tableName));
     }
 }
Пример #23
0
 /**
  * Performs adding field in PostgreSQL table.
  * ( workaround for "ALTER TABLE table ADD field fieldDefinition NOT NULL" 
  * that not alowed in PostgreSQL 7.x but works in PostgreSQL 8.x ).
  * 
  * @param ezcDbHandler    $db
  * @param string          $tableName
  * @param string          $fieldName
  * @param string          $fieldType
  *
  */
 private function addField(ezcDbHandler $db, $tableName, $fieldName, $fieldType)
 {
     $db->exec("ALTER TABLE \"{$tableName}\" ADD \"{$fieldName}\" {$fieldType}");
     $db->exec("ALTER TABLE \"{$tableName}\" ALTER \"{$fieldName}\" SET NOT NULL");
 }
Пример #24
0
 /**
  * Sets up opened connection according to options.
  */
 private function setupConnection()
 {
     $requiredMode = $this->options->quoteIdentifier;
     if ($requiredMode == ezcDbMssqlOptions::QUOTES_GUESS) {
         $result = parent::query("SELECT sessionproperty('QUOTED_IDENTIFIER')");
         $rows = $result->fetchAll();
         $mode = (int) $rows[0][0];
         if ($mode == 0) {
             $this->identifierQuoteChars = array('start' => '[', 'end' => ']');
         } else {
             $this->identifierQuoteChars = array('start' => '"', 'end' => '"');
         }
     } else {
         if ($requiredMode == ezcDbMssqlOptions::QUOTES_COMPLIANT) {
             parent::exec('SET QUOTED_IDENTIFIER ON');
             $this->identifierQuoteChars = array('start' => '"', 'end' => '"');
         } else {
             if ($requiredMode == ezcDbMssqlOptions::QUOTES_LEGACY) {
                 parent::exec('SET QUOTED_IDENTIFIER OFF');
                 $this->identifierQuoteChars = array('start' => '[', 'end' => ']');
             }
         }
     }
 }
Пример #25
0
 /**
  * Performs changing field in Oracle table.
  * (workaround for "ALTER TABLE table MODIFY field fieldType AUTO_INCREMENT " that not alowed in Oracle ).
  * 
  * @param ezcDbHandler    $db
  * @param string          $tableName
  * @param string          $autoIncrementFieldName
  * @param string          $autoIncrementFieldType
  */
 private function addAutoIncrementField($db, $tableName, $autoIncrementFieldName, $autoIncrementFieldType)
 {
     // fetching field info from Oracle, getting column position of autoincrement field
     // @apichange This code piece would become orphan, with the new
     // implementation. We still need it to drop the old sequences.
     // Remove until --END-- to not take care of them.
     $resultArray = $db->query("SELECT   a.column_name AS field, " . "         a.column_id AS field_pos " . "FROM     user_tab_columns a " . "WHERE    a.table_name = '{$tableName}' AND a.column_name = '{$autoIncrementFieldName}'" . "ORDER BY a.column_id");
     $resultArray->setFetchMode(PDO::FETCH_ASSOC);
     if (count($resultArray) != 1) {
         return;
     }
     $result = $resultArray->fetch();
     $fieldPos = $result['field_pos'];
     // emulation of autoincrement through adding sequence, trigger and constraint
     $oldName = ezcDbSchemaOracleHelper::generateSuffixCompositeIdentName($tableName, $fieldPos, "seq");
     $oldNameTrigger = ezcDbSchemaOracleHelper::generateSuffixCompositeIdentName($tableName, $fieldPos, "trg");
     $sequence = $db->query("SELECT sequence_name FROM user_sequences WHERE sequence_name = '{$oldName}'")->fetchAll();
     if (count($sequence) > 0) {
         // assuming that if the seq exists, the trigger exists too
         $db->query("DROP SEQUENCE \"{$oldName}\"");
         $db->query("DROP TRIGGER \"{$oldNameTrigger}\"");
     }
     // --END--
     // New sequence names, using field names
     $newName = ezcDbSchemaOracleHelper::generateSuffixCompositeIdentName($tableName, $fieldPos, "seq");
     $newNameTrigger = ezcDbSchemaOracleHelper::generateSuffixCompositeIdentName($tableName, $fieldPos, "seq");
     // Emulation of autoincrement through adding sequence, trigger and constraint
     $sequences = $db->query("SELECT sequence_name FROM user_sequences WHERE sequence_name = '{$newName}'")->fetchAll();
     if (count($sequences) > 0) {
         $db->query("DROP SEQUENCE \"{$newName}\"");
     }
     $db->exec("CREATE SEQUENCE \"{$newName}\" start with 1 increment by 1 nomaxvalue");
     $db->exec("CREATE OR REPLACE TRIGGER \"{$newNameTrigger}\" " . "before insert on \"{$tableName}\" for each row " . "begin " . "select \"{$newName}\".nextval into :new.\"{$autoIncrementFieldName}\" from dual; " . "end;");
     $constraintName = ezcDbSchemaOracleHelper::generateSuffixedIdentName(array($tableName), "pkey");
     $constraint = $db->query("SELECT constraint_name FROM user_cons_columns WHERE constraint_name = '{$constraintName}'")->fetchAll();
     if (count($constraint) > 0) {
         $db->query("ALTER TABLE \"{$tableName}\" DROP CONSTRAINT \"{$constraintName}\"");
     }
     $db->exec("ALTER TABLE \"{$tableName}\" ADD CONSTRAINT \"{$constraintName}\" PRIMARY KEY ( \"{$autoIncrementFieldName}\" )");
     $this->context['skip_primary'] = true;
 }
Пример #26
0
 /**
  * Constructs a handler object from the parameters $dbParams.
  *
  * Supported database parameters are:
  * - dbname|database: Database name
  * - user|username:   Database user name
  * - pass|password:   Database user password
  * - host|hostspec:   Name of the host database is running on
  * - port:            TCP port
  * - charset:         Client character set
  * - socket:          UNIX socket path
  *
  * @throws ezcDbMissingParameterException if the database name was not specified.
  * @param array $dbParams Database connection parameters (key=>value pairs).
  */
 public function __construct($dbParams)
 {
     if ($dbParams instanceof PDO) {
         parent::__construct($dbParams);
         return;
     }
     $database = null;
     $charset = null;
     $host = null;
     $port = null;
     $socket = null;
     foreach ($dbParams as $key => $val) {
         switch ($key) {
             case 'database':
             case 'dbname':
                 $database = $val;
                 break;
             case 'charset':
                 $charset = $val;
                 break;
             case 'host':
             case 'hostspec':
                 $host = $val;
                 break;
             case 'port':
                 $port = $val;
                 break;
             case 'socket':
                 $socket = $val;
                 break;
         }
     }
     if (!isset($database)) {
         throw new ezcDbMissingParameterException('database', 'dbParams');
     }
     $dsn = "mysql:dbname={$database}";
     if (isset($host) && $host) {
         $dsn .= ";host={$host}";
     }
     if (isset($port) && $port) {
         $dsn .= ";port={$port}";
     }
     if (isset($charset) && $charset) {
         $dsn .= ";charset={$charset}";
     }
     if (isset($socket) && $socket) {
         $dsn .= ";unix_socket={$socket}";
     }
     $db = parent::createPDO($dbParams, $dsn);
     parent::__construct($db);
 }