First commit

This commit is contained in:
Theodotos Andreou 2018-01-14 13:10:16 +00:00
commit c6e2478c40
13918 changed files with 2303184 additions and 0 deletions

File diff suppressed because it is too large Load diff

161
includes/database/log.inc Normal file
View file

@ -0,0 +1,161 @@
<?php
/**
* @file
* Logging classes for the database layer.
*/
/**
* Database query logger.
*
* We log queries in a separate object rather than in the connection object
* because we want to be able to see all queries sent to a given database, not
* database target. If we logged the queries in each connection object we
* would not be able to track what queries went to which target.
*
* Every connection has one and only one logging object on it for all targets
* and logging keys.
*/
class DatabaseLog {
/**
* Cache of logged queries. This will only be used if the query logger is enabled.
*
* The structure for the logging array is as follows:
*
* array(
* $logging_key = array(
* array(query => '', args => array(), caller => '', target => '', time => 0),
* array(query => '', args => array(), caller => '', target => '', time => 0),
* ),
* );
*
* @var array
*/
protected $queryLog = array();
/**
* The connection key for which this object is logging.
*
* @var string
*/
protected $connectionKey = 'default';
/**
* Constructor.
*
* @param $key
* The database connection key for which to enable logging.
*/
public function __construct($key = 'default') {
$this->connectionKey = $key;
}
/**
* Begin logging queries to the specified connection and logging key.
*
* If the specified logging key is already running this method does nothing.
*
* @param $logging_key
* The identification key for this log request. By specifying different
* logging keys we are able to start and stop multiple logging runs
* simultaneously without them colliding.
*/
public function start($logging_key) {
if (empty($this->queryLog[$logging_key])) {
$this->clear($logging_key);
}
}
/**
* Retrieve the query log for the specified logging key so far.
*
* @param $logging_key
* The logging key to fetch.
* @return
* An indexed array of all query records for this logging key.
*/
public function get($logging_key) {
return $this->queryLog[$logging_key];
}
/**
* Empty the query log for the specified logging key.
*
* This method does not stop logging, it simply clears the log. To stop
* logging, use the end() method.
*
* @param $logging_key
* The logging key to empty.
*/
public function clear($logging_key) {
$this->queryLog[$logging_key] = array();
}
/**
* Stop logging for the specified logging key.
*
* @param $logging_key
* The logging key to stop.
*/
public function end($logging_key) {
unset($this->queryLog[$logging_key]);
}
/**
* Log a query to all active logging keys.
*
* @param $statement
* The prepared statement object to log.
* @param $args
* The arguments passed to the statement object.
* @param $time
* The time in milliseconds the query took to execute.
*/
public function log(DatabaseStatementInterface $statement, $args, $time) {
foreach (array_keys($this->queryLog) as $key) {
$this->queryLog[$key][] = array(
'query' => $statement->getQueryString(),
'args' => $args,
'target' => $statement->dbh->getTarget(),
'caller' => $this->findCaller(),
'time' => $time,
);
}
}
/**
* Determine the routine that called this query.
*
* We define "the routine that called this query" as the first entry in
* the call stack that is not inside includes/database and does have a file
* (which excludes call_user_func_array(), anonymous functions and similar).
* That makes the climbing logic very simple, and handles the variable stack
* depth caused by the query builders.
*
* @link http://www.php.net/debug_backtrace
* @return
* This method returns a stack trace entry similar to that generated by
* debug_backtrace(). However, it flattens the trace entry and the trace
* entry before it so that we get the function and args of the function that
* called into the database system, not the function and args of the
* database call itself.
*/
public function findCaller() {
$stack = debug_backtrace();
$stack_count = count($stack);
for ($i = 0; $i < $stack_count; ++$i) {
if (!empty($stack[$i]['file']) && strpos($stack[$i]['file'], 'includes' . DIRECTORY_SEPARATOR . 'database') === FALSE) {
$stack[$i] += array('args' => array());
return array(
'file' => $stack[$i]['file'],
'line' => $stack[$i]['line'],
'function' => $stack[$i + 1]['function'],
'class' => isset($stack[$i + 1]['class']) ? $stack[$i + 1]['class'] : NULL,
'type' => isset($stack[$i + 1]['type']) ? $stack[$i + 1]['type'] : NULL,
'args' => $stack[$i + 1]['args'],
);
}
}
}
}

View file

@ -0,0 +1,256 @@
<?php
/**
* @file
* Database interface code for MySQL database servers.
*/
/**
* @addtogroup database
* @{
*/
class DatabaseConnection_mysql extends DatabaseConnection {
/**
* Flag to indicate if the cleanup function in __destruct() should run.
*
* @var boolean
*/
protected $needsCleanup = FALSE;
public function __construct(array $connection_options = array()) {
// This driver defaults to transaction support, except if explicitly passed FALSE.
$this->transactionSupport = !isset($connection_options['transactions']) || ($connection_options['transactions'] !== FALSE);
// MySQL never supports transactional DDL.
$this->transactionalDDLSupport = FALSE;
$this->connectionOptions = $connection_options;
$charset = 'utf8';
// Check if the charset is overridden to utf8mb4 in settings.php.
if ($this->utf8mb4IsActive()) {
$charset = 'utf8mb4';
}
// The DSN should use either a socket or a host/port.
if (isset($connection_options['unix_socket'])) {
$dsn = 'mysql:unix_socket=' . $connection_options['unix_socket'];
}
else {
// Default to TCP connection on port 3306.
$dsn = 'mysql:host=' . $connection_options['host'] . ';port=' . (empty($connection_options['port']) ? 3306 : $connection_options['port']);
}
// Character set is added to dsn to ensure PDO uses the proper character
// set when escaping. This has security implications. See
// https://www.drupal.org/node/1201452 for further discussion.
$dsn .= ';charset=' . $charset;
$dsn .= ';dbname=' . $connection_options['database'];
// Allow PDO options to be overridden.
$connection_options += array(
'pdo' => array(),
);
$connection_options['pdo'] += array(
// So we don't have to mess around with cursors and unbuffered queries by default.
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE,
// Because MySQL's prepared statements skip the query cache, because it's dumb.
PDO::ATTR_EMULATE_PREPARES => TRUE,
);
if (defined('PDO::MYSQL_ATTR_MULTI_STATEMENTS')) {
// An added connection option in PHP 5.5.21+ to optionally limit SQL to a
// single statement like mysqli.
$connection_options['pdo'] += array(PDO::MYSQL_ATTR_MULTI_STATEMENTS => FALSE);
}
parent::__construct($dsn, $connection_options['username'], $connection_options['password'], $connection_options['pdo']);
// Force MySQL to use the UTF-8 character set. Also set the collation, if a
// certain one has been set; otherwise, MySQL defaults to 'utf8_general_ci'
// for UTF-8.
if (!empty($connection_options['collation'])) {
$this->exec('SET NAMES ' . $charset . ' COLLATE ' . $connection_options['collation']);
}
else {
$this->exec('SET NAMES ' . $charset);
}
// Set MySQL init_commands if not already defined. Default Drupal's MySQL
// behavior to conform more closely to SQL standards. This allows Drupal
// to run almost seamlessly on many different kinds of database systems.
// These settings force MySQL to behave the same as postgresql, or sqlite
// in regards to syntax interpretation and invalid data handling. See
// http://drupal.org/node/344575 for further discussion. Also, as MySQL 5.5
// changed the meaning of TRADITIONAL we need to spell out the modes one by
// one.
$connection_options += array(
'init_commands' => array(),
);
$connection_options['init_commands'] += array(
'sql_mode' => "SET sql_mode = 'REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER'",
);
// Execute initial commands.
foreach ($connection_options['init_commands'] as $sql) {
$this->exec($sql);
}
}
public function __destruct() {
if ($this->needsCleanup) {
$this->nextIdDelete();
}
}
public function queryRange($query, $from, $count, array $args = array(), array $options = array()) {
return $this->query($query . ' LIMIT ' . (int) $from . ', ' . (int) $count, $args, $options);
}
public function queryTemporary($query, array $args = array(), array $options = array()) {
$tablename = $this->generateTemporaryTableName();
$this->query('CREATE TEMPORARY TABLE {' . $tablename . '} Engine=MEMORY ' . $query, $args, $options);
return $tablename;
}
public function driver() {
return 'mysql';
}
public function databaseType() {
return 'mysql';
}
public function mapConditionOperator($operator) {
// We don't want to override any of the defaults.
return NULL;
}
public function nextId($existing_id = 0) {
$new_id = $this->query('INSERT INTO {sequences} () VALUES ()', array(), array('return' => Database::RETURN_INSERT_ID));
// This should only happen after an import or similar event.
if ($existing_id >= $new_id) {
// If we INSERT a value manually into the sequences table, on the next
// INSERT, MySQL will generate a larger value. However, there is no way
// of knowing whether this value already exists in the table. MySQL
// provides an INSERT IGNORE which would work, but that can mask problems
// other than duplicate keys. Instead, we use INSERT ... ON DUPLICATE KEY
// UPDATE in such a way that the UPDATE does not do anything. This way,
// duplicate keys do not generate errors but everything else does.
$this->query('INSERT INTO {sequences} (value) VALUES (:value) ON DUPLICATE KEY UPDATE value = value', array(':value' => $existing_id));
$new_id = $this->query('INSERT INTO {sequences} () VALUES ()', array(), array('return' => Database::RETURN_INSERT_ID));
}
$this->needsCleanup = TRUE;
return $new_id;
}
public function nextIdDelete() {
// While we want to clean up the table to keep it up from occupying too
// much storage and memory, we must keep the highest value in the table
// because InnoDB uses an in-memory auto-increment counter as long as the
// server runs. When the server is stopped and restarted, InnoDB
// reinitializes the counter for each table for the first INSERT to the
// table based solely on values from the table so deleting all values would
// be a problem in this case. Also, TRUNCATE resets the auto increment
// counter.
try {
$max_id = $this->query('SELECT MAX(value) FROM {sequences}')->fetchField();
// We know we are using MySQL here, no need for the slower db_delete().
$this->query('DELETE FROM {sequences} WHERE value < :value', array(':value' => $max_id));
}
// During testing, this function is called from shutdown with the
// simpletest prefix stored in $this->connection, and those tables are gone
// by the time shutdown is called so we need to ignore the database
// errors. There is no problem with completely ignoring errors here: if
// these queries fail, the sequence will work just fine, just use a bit
// more database storage and memory.
catch (PDOException $e) {
}
}
/**
* Overridden to work around issues to MySQL not supporting transactional DDL.
*/
protected function popCommittableTransactions() {
// Commit all the committable layers.
foreach (array_reverse($this->transactionLayers) as $name => $active) {
// Stop once we found an active transaction.
if ($active) {
break;
}
// If there are no more layers left then we should commit.
unset($this->transactionLayers[$name]);
if (empty($this->transactionLayers)) {
if (!PDO::commit()) {
throw new DatabaseTransactionCommitFailedException();
}
}
else {
// Attempt to release this savepoint in the standard way.
try {
$this->query('RELEASE SAVEPOINT ' . $name);
}
catch (PDOException $e) {
// However, in MySQL (InnoDB), savepoints are automatically committed
// when tables are altered or created (DDL transactions are not
// supported). This can cause exceptions due to trying to release
// savepoints which no longer exist.
//
// To avoid exceptions when no actual error has occurred, we silently
// succeed for MySQL error code 1305 ("SAVEPOINT does not exist").
if ($e->errorInfo[1] == '1305') {
// If one SAVEPOINT was released automatically, then all were.
// Therefore, clean the transaction stack.
$this->transactionLayers = array();
// We also have to explain to PDO that the transaction stack has
// been cleaned-up.
PDO::commit();
}
else {
throw $e;
}
}
}
}
}
public function utf8mb4IsConfigurable() {
return TRUE;
}
public function utf8mb4IsActive() {
return isset($this->connectionOptions['charset']) && $this->connectionOptions['charset'] === 'utf8mb4';
}
public function utf8mb4IsSupported() {
// Ensure that the MySQL driver supports utf8mb4 encoding.
$version = $this->getAttribute(PDO::ATTR_CLIENT_VERSION);
if (strpos($version, 'mysqlnd') !== FALSE) {
// The mysqlnd driver supports utf8mb4 starting at version 5.0.9.
$version = preg_replace('/^\D+([\d.]+).*/', '$1', $version);
if (version_compare($version, '5.0.9', '<')) {
return FALSE;
}
}
else {
// The libmysqlclient driver supports utf8mb4 starting at version 5.5.3.
if (version_compare($version, '5.5.3', '<')) {
return FALSE;
}
}
// Ensure that the MySQL server supports large prefixes and utf8mb4.
try {
$this->query("CREATE TABLE {drupal_utf8mb4_test} (id VARCHAR(255), PRIMARY KEY(id(255))) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci ROW_FORMAT=DYNAMIC ENGINE=INNODB");
}
catch (Exception $e) {
return FALSE;
}
$this->query("DROP TABLE {drupal_utf8mb4_test}");
return TRUE;
}
}
/**
* @} End of "addtogroup database".
*/

View file

@ -0,0 +1,33 @@
<?php
/**
* @file
* Installation code for MySQL embedded database engine.
*/
/**
* Specifies installation tasks for MySQL and equivalent databases.
*/
class DatabaseTasks_mysql extends DatabaseTasks {
/**
* The PDO driver name for MySQL and equivalent databases.
*
* @var string
*/
protected $pdoDriver = 'mysql';
/**
* Returns a human-readable name string for MySQL and equivalent databases.
*/
public function name() {
return st('MySQL, MariaDB, or equivalent');
}
/**
* Returns the minimum version for MySQL.
*/
public function minimumVersion() {
return '5.0.15';
}
}

View file

@ -0,0 +1,94 @@
<?php
/**
* @addtogroup database
* @{
*/
/**
* @file
* Query code for MySQL embedded database engine.
*/
class InsertQuery_mysql extends InsertQuery {
public function execute() {
if (!$this->preExecute()) {
return NULL;
}
// If we're selecting from a SelectQuery, finish building the query and
// pass it back, as any remaining options are irrelevant.
if (empty($this->fromQuery)) {
$max_placeholder = 0;
$values = array();
foreach ($this->insertValues as $insert_values) {
foreach ($insert_values as $value) {
$values[':db_insert_placeholder_' . $max_placeholder++] = $value;
}
}
}
else {
$values = $this->fromQuery->getArguments();
}
$last_insert_id = $this->connection->query((string) $this, $values, $this->queryOptions);
// Re-initialize the values array so that we can re-use this query.
$this->insertValues = array();
return $last_insert_id;
}
public function __toString() {
// Create a sanitized comment string to prepend to the query.
$comments = $this->connection->makeComment($this->comments);
// Default fields are always placed first for consistency.
$insert_fields = array_merge($this->defaultFields, $this->insertFields);
// If we're selecting from a SelectQuery, finish building the query and
// pass it back, as any remaining options are irrelevant.
if (!empty($this->fromQuery)) {
$insert_fields_string = $insert_fields ? ' (' . implode(', ', $insert_fields) . ') ' : ' ';
return $comments . 'INSERT INTO {' . $this->table . '}' . $insert_fields_string . $this->fromQuery;
}
$query = $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') VALUES ';
$max_placeholder = 0;
$values = array();
if (count($this->insertValues)) {
foreach ($this->insertValues as $insert_values) {
$placeholders = array();
// Default fields aren't really placeholders, but this is the most convenient
// way to handle them.
$placeholders = array_pad($placeholders, count($this->defaultFields), 'default');
$new_placeholder = $max_placeholder + count($insert_values);
for ($i = $max_placeholder; $i < $new_placeholder; ++$i) {
$placeholders[] = ':db_insert_placeholder_' . $i;
}
$max_placeholder = $new_placeholder;
$values[] = '(' . implode(', ', $placeholders) . ')';
}
}
else {
// If there are no values, then this is a default-only query. We still need to handle that.
$placeholders = array_fill(0, count($this->defaultFields), 'default');
$values[] = '(' . implode(', ', $placeholders) . ')';
}
$query .= implode(', ', $values);
return $query;
}
}
class TruncateQuery_mysql extends TruncateQuery { }
/**
* @} End of "addtogroup database".
*/

View file

@ -0,0 +1,544 @@
<?php
/**
* @file
* Database schema code for MySQL database servers.
*/
/**
* @addtogroup schemaapi
* @{
*/
class DatabaseSchema_mysql extends DatabaseSchema {
/**
* Maximum length of a table comment in MySQL.
*/
const COMMENT_MAX_TABLE = 60;
/**
* Maximum length of a column comment in MySQL.
*/
const COMMENT_MAX_COLUMN = 255;
/**
* Get information about the table and database name from the prefix.
*
* @return
* A keyed array with information about the database, table name and prefix.
*/
protected function getPrefixInfo($table = 'default', $add_prefix = TRUE) {
$info = array('prefix' => $this->connection->tablePrefix($table));
if ($add_prefix) {
$table = $info['prefix'] . $table;
}
if (($pos = strpos($table, '.')) !== FALSE) {
$info['database'] = substr($table, 0, $pos);
$info['table'] = substr($table, ++$pos);
}
else {
$db_info = $this->connection->getConnectionOptions();
$info['database'] = $db_info['database'];
$info['table'] = $table;
}
return $info;
}
/**
* Build a condition to match a table name against a standard information_schema.
*
* MySQL uses databases like schemas rather than catalogs so when we build
* a condition to query the information_schema.tables, we set the default
* database as the schema unless specified otherwise, and exclude table_catalog
* from the condition criteria.
*/
protected function buildTableNameCondition($table_name, $operator = '=', $add_prefix = TRUE) {
$info = $this->connection->getConnectionOptions();
$table_info = $this->getPrefixInfo($table_name, $add_prefix);
$condition = new DatabaseCondition('AND');
$condition->condition('table_schema', $table_info['database']);
$condition->condition('table_name', $table_info['table'], $operator);
return $condition;
}
/**
* Generate SQL to create a new table from a Drupal schema definition.
*
* @param $name
* The name of the table to create.
* @param $table
* A Schema API table definition array.
* @return
* An array of SQL statements to create the table.
*/
protected function createTableSql($name, $table) {
$info = $this->connection->getConnectionOptions();
// Provide defaults if needed.
$table += array(
'mysql_engine' => 'InnoDB',
// Allow the default charset to be overridden in settings.php.
'mysql_character_set' => $this->connection->utf8mb4IsActive() ? 'utf8mb4' : 'utf8',
);
$sql = "CREATE TABLE {" . $name . "} (\n";
// Add the SQL statement for each field.
foreach ($table['fields'] as $field_name => $field) {
$sql .= $this->createFieldSql($field_name, $this->processField($field)) . ", \n";
}
// Process keys & indexes.
$keys = $this->createKeysSql($table);
if (count($keys)) {
$sql .= implode(", \n", $keys) . ", \n";
}
// Remove the last comma and space.
$sql = substr($sql, 0, -3) . "\n) ";
$sql .= 'ENGINE = ' . $table['mysql_engine'] . ' DEFAULT CHARACTER SET ' . $table['mysql_character_set'];
// By default, MySQL uses the default collation for new tables, which is
// 'utf8_general_ci' for utf8. If an alternate collation has been set, it
// needs to be explicitly specified.
// @see DatabaseConnection_mysql
if (!empty($info['collation'])) {
$sql .= ' COLLATE ' . $info['collation'];
}
// The row format needs to be either DYNAMIC or COMPRESSED in order to allow
// for the innodb_large_prefix setting to take effect, see
// https://dev.mysql.com/doc/refman/5.6/en/create-table.html
if ($this->connection->utf8mb4IsActive()) {
$sql .= ' ROW_FORMAT=DYNAMIC';
}
// Add table comment.
if (!empty($table['description'])) {
$sql .= ' COMMENT ' . $this->prepareComment($table['description'], self::COMMENT_MAX_TABLE);
}
return array($sql);
}
/**
* Create an SQL string for a field to be used in table creation or alteration.
*
* Before passing a field out of a schema definition into this function it has
* to be processed by _db_process_field().
*
* @param $name
* Name of the field.
* @param $spec
* The field specification, as per the schema data structure format.
*/
protected function createFieldSql($name, $spec) {
$sql = "`" . $name . "` " . $spec['mysql_type'];
if (in_array($spec['mysql_type'], array('VARCHAR', 'CHAR', 'TINYTEXT', 'MEDIUMTEXT', 'LONGTEXT', 'TEXT'))) {
if (isset($spec['length'])) {
$sql .= '(' . $spec['length'] . ')';
}
if (!empty($spec['binary'])) {
$sql .= ' BINARY';
}
}
elseif (isset($spec['precision']) && isset($spec['scale'])) {
$sql .= '(' . $spec['precision'] . ', ' . $spec['scale'] . ')';
}
if (!empty($spec['unsigned'])) {
$sql .= ' unsigned';
}
if (isset($spec['not null'])) {
if ($spec['not null']) {
$sql .= ' NOT NULL';
}
else {
$sql .= ' NULL';
}
}
if (!empty($spec['auto_increment'])) {
$sql .= ' auto_increment';
}
// $spec['default'] can be NULL, so we explicitly check for the key here.
if (array_key_exists('default', $spec)) {
if (is_string($spec['default'])) {
$spec['default'] = "'" . $spec['default'] . "'";
}
elseif (!isset($spec['default'])) {
$spec['default'] = 'NULL';
}
$sql .= ' DEFAULT ' . $spec['default'];
}
if (empty($spec['not null']) && !isset($spec['default'])) {
$sql .= ' DEFAULT NULL';
}
// Add column comment.
if (!empty($spec['description'])) {
$sql .= ' COMMENT ' . $this->prepareComment($spec['description'], self::COMMENT_MAX_COLUMN);
}
return $sql;
}
/**
* Set database-engine specific properties for a field.
*
* @param $field
* A field description array, as specified in the schema documentation.
*/
protected function processField($field) {
if (!isset($field['size'])) {
$field['size'] = 'normal';
}
// Set the correct database-engine specific datatype.
// In case one is already provided, force it to uppercase.
if (isset($field['mysql_type'])) {
$field['mysql_type'] = drupal_strtoupper($field['mysql_type']);
}
else {
$map = $this->getFieldTypeMap();
$field['mysql_type'] = $map[$field['type'] . ':' . $field['size']];
}
if (isset($field['type']) && $field['type'] == 'serial') {
$field['auto_increment'] = TRUE;
}
return $field;
}
public function getFieldTypeMap() {
// Put :normal last so it gets preserved by array_flip. This makes
// it much easier for modules (such as schema.module) to map
// database types back into schema types.
// $map does not use drupal_static as its value never changes.
static $map = array(
'varchar:normal' => 'VARCHAR',
'char:normal' => 'CHAR',
'text:tiny' => 'TINYTEXT',
'text:small' => 'TINYTEXT',
'text:medium' => 'MEDIUMTEXT',
'text:big' => 'LONGTEXT',
'text:normal' => 'TEXT',
'serial:tiny' => 'TINYINT',
'serial:small' => 'SMALLINT',
'serial:medium' => 'MEDIUMINT',
'serial:big' => 'BIGINT',
'serial:normal' => 'INT',
'int:tiny' => 'TINYINT',
'int:small' => 'SMALLINT',
'int:medium' => 'MEDIUMINT',
'int:big' => 'BIGINT',
'int:normal' => 'INT',
'float:tiny' => 'FLOAT',
'float:small' => 'FLOAT',
'float:medium' => 'FLOAT',
'float:big' => 'DOUBLE',
'float:normal' => 'FLOAT',
'numeric:normal' => 'DECIMAL',
'blob:big' => 'LONGBLOB',
'blob:normal' => 'BLOB',
);
return $map;
}
protected function createKeysSql($spec) {
$keys = array();
if (!empty($spec['primary key'])) {
$keys[] = 'PRIMARY KEY (' . $this->createKeysSqlHelper($spec['primary key']) . ')';
}
if (!empty($spec['unique keys'])) {
foreach ($spec['unique keys'] as $key => $fields) {
$keys[] = 'UNIQUE KEY `' . $key . '` (' . $this->createKeysSqlHelper($fields) . ')';
}
}
if (!empty($spec['indexes'])) {
foreach ($spec['indexes'] as $index => $fields) {
$keys[] = 'INDEX `' . $index . '` (' . $this->createKeysSqlHelper($fields) . ')';
}
}
return $keys;
}
protected function createKeySql($fields) {
$return = array();
foreach ($fields as $field) {
if (is_array($field)) {
$return[] = '`' . $field[0] . '`(' . $field[1] . ')';
}
else {
$return[] = '`' . $field . '`';
}
}
return implode(', ', $return);
}
protected function createKeysSqlHelper($fields) {
$return = array();
foreach ($fields as $field) {
if (is_array($field)) {
$return[] = '`' . $field[0] . '`(' . $field[1] . ')';
}
else {
$return[] = '`' . $field . '`';
}
}
return implode(', ', $return);
}
public function renameTable($table, $new_name) {
if (!$this->tableExists($table)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot rename @table to @table_new: table @table doesn't exist.", array('@table' => $table, '@table_new' => $new_name)));
}
if ($this->tableExists($new_name)) {
throw new DatabaseSchemaObjectExistsException(t("Cannot rename @table to @table_new: table @table_new already exists.", array('@table' => $table, '@table_new' => $new_name)));
}
$info = $this->getPrefixInfo($new_name);
return $this->connection->query('ALTER TABLE {' . $table . '} RENAME TO `' . $info['table'] . '`');
}
public function dropTable($table) {
if (!$this->tableExists($table)) {
return FALSE;
}
$this->connection->query('DROP TABLE {' . $table . '}');
return TRUE;
}
public function addField($table, $field, $spec, $keys_new = array()) {
if (!$this->tableExists($table)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add field @table.@field: table doesn't exist.", array('@field' => $field, '@table' => $table)));
}
if ($this->fieldExists($table, $field)) {
throw new DatabaseSchemaObjectExistsException(t("Cannot add field @table.@field: field already exists.", array('@field' => $field, '@table' => $table)));
}
$fixnull = FALSE;
if (!empty($spec['not null']) && !isset($spec['default'])) {
$fixnull = TRUE;
$spec['not null'] = FALSE;
}
$query = 'ALTER TABLE {' . $table . '} ADD ';
$query .= $this->createFieldSql($field, $this->processField($spec));
if ($keys_sql = $this->createKeysSql($keys_new)) {
$query .= ', ADD ' . implode(', ADD ', $keys_sql);
}
$this->connection->query($query);
if (isset($spec['initial'])) {
$this->connection->update($table)
->fields(array($field => $spec['initial']))
->execute();
}
if ($fixnull) {
$spec['not null'] = TRUE;
$this->changeField($table, $field, $field, $spec);
}
}
public function dropField($table, $field) {
if (!$this->fieldExists($table, $field)) {
return FALSE;
}
$this->connection->query('ALTER TABLE {' . $table . '} DROP `' . $field . '`');
return TRUE;
}
public function fieldSetDefault($table, $field, $default) {
if (!$this->fieldExists($table, $field)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot set default value of field @table.@field: field doesn't exist.", array('@table' => $table, '@field' => $field)));
}
if (!isset($default)) {
$default = 'NULL';
}
else {
$default = is_string($default) ? "'$default'" : $default;
}
$this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN `' . $field . '` SET DEFAULT ' . $default);
}
public function fieldSetNoDefault($table, $field) {
if (!$this->fieldExists($table, $field)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot remove default value of field @table.@field: field doesn't exist.", array('@table' => $table, '@field' => $field)));
}
$this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN `' . $field . '` DROP DEFAULT');
}
public function indexExists($table, $name) {
// Returns one row for each column in the index. Result is string or FALSE.
// Details at http://dev.mysql.com/doc/refman/5.0/en/show-index.html
$row = $this->connection->query('SHOW INDEX FROM {' . $table . "} WHERE key_name = '$name'")->fetchAssoc();
return isset($row['Key_name']);
}
public function addPrimaryKey($table, $fields) {
if (!$this->tableExists($table)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add primary key to table @table: table doesn't exist.", array('@table' => $table)));
}
if ($this->indexExists($table, 'PRIMARY')) {
throw new DatabaseSchemaObjectExistsException(t("Cannot add primary key to table @table: primary key already exists.", array('@table' => $table)));
}
$this->connection->query('ALTER TABLE {' . $table . '} ADD PRIMARY KEY (' . $this->createKeySql($fields) . ')');
}
public function dropPrimaryKey($table) {
if (!$this->indexExists($table, 'PRIMARY')) {
return FALSE;
}
$this->connection->query('ALTER TABLE {' . $table . '} DROP PRIMARY KEY');
return TRUE;
}
public function addUniqueKey($table, $name, $fields) {
if (!$this->tableExists($table)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add unique key @name to table @table: table doesn't exist.", array('@table' => $table, '@name' => $name)));
}
if ($this->indexExists($table, $name)) {
throw new DatabaseSchemaObjectExistsException(t("Cannot add unique key @name to table @table: unique key already exists.", array('@table' => $table, '@name' => $name)));
}
$this->connection->query('ALTER TABLE {' . $table . '} ADD UNIQUE KEY `' . $name . '` (' . $this->createKeySql($fields) . ')');
}
public function dropUniqueKey($table, $name) {
if (!$this->indexExists($table, $name)) {
return FALSE;
}
$this->connection->query('ALTER TABLE {' . $table . '} DROP KEY `' . $name . '`');
return TRUE;
}
public function addIndex($table, $name, $fields) {
if (!$this->tableExists($table)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add index @name to table @table: table doesn't exist.", array('@table' => $table, '@name' => $name)));
}
if ($this->indexExists($table, $name)) {
throw new DatabaseSchemaObjectExistsException(t("Cannot add index @name to table @table: index already exists.", array('@table' => $table, '@name' => $name)));
}
$this->connection->query('ALTER TABLE {' . $table . '} ADD INDEX `' . $name . '` (' . $this->createKeySql($fields) . ')');
}
public function dropIndex($table, $name) {
if (!$this->indexExists($table, $name)) {
return FALSE;
}
$this->connection->query('ALTER TABLE {' . $table . '} DROP INDEX `' . $name . '`');
return TRUE;
}
public function changeField($table, $field, $field_new, $spec, $keys_new = array()) {
if (!$this->fieldExists($table, $field)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot change the definition of field @table.@name: field doesn't exist.", array('@table' => $table, '@name' => $field)));
}
if (($field != $field_new) && $this->fieldExists($table, $field_new)) {
throw new DatabaseSchemaObjectExistsException(t("Cannot rename field @table.@name to @name_new: target field already exists.", array('@table' => $table, '@name' => $field, '@name_new' => $field_new)));
}
$sql = 'ALTER TABLE {' . $table . '} CHANGE `' . $field . '` ' . $this->createFieldSql($field_new, $this->processField($spec));
if ($keys_sql = $this->createKeysSql($keys_new)) {
$sql .= ', ADD ' . implode(', ADD ', $keys_sql);
}
$this->connection->query($sql);
}
public function prepareComment($comment, $length = NULL) {
// Work around a bug in some versions of PDO, see http://bugs.php.net/bug.php?id=41125
$comment = str_replace("'", '', $comment);
// Truncate comment to maximum comment length.
if (isset($length)) {
// Add table prefixes before truncating.
$comment = truncate_utf8($this->connection->prefixTables($comment), $length, TRUE, TRUE);
}
return $this->connection->quote($comment);
}
/**
* Retrieve a table or column comment.
*/
public function getComment($table, $column = NULL) {
$condition = $this->buildTableNameCondition($table);
if (isset($column)) {
$condition->condition('column_name', $column);
$condition->compile($this->connection, $this);
// Don't use {} around information_schema.columns table.
return $this->connection->query("SELECT column_comment FROM information_schema.columns WHERE " . (string) $condition, $condition->arguments())->fetchField();
}
$condition->compile($this->connection, $this);
// Don't use {} around information_schema.tables table.
$comment = $this->connection->query("SELECT table_comment FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments())->fetchField();
// Work-around for MySQL 5.0 bug http://bugs.mysql.com/bug.php?id=11379
return preg_replace('/; InnoDB free:.*$/', '', $comment);
}
public function tableExists($table) {
// The information_schema table is very slow to query under MySQL 5.0.
// Instead, we try to select from the table in question. If it fails,
// the most likely reason is that it does not exist. That is dramatically
// faster than using information_schema.
// @link http://bugs.mysql.com/bug.php?id=19588
// @todo: This override should be removed once we require a version of MySQL
// that has that bug fixed.
try {
$this->connection->queryRange("SELECT 1 FROM {" . $table . "}", 0, 1);
return TRUE;
}
catch (Exception $e) {
return FALSE;
}
}
public function fieldExists($table, $column) {
// The information_schema table is very slow to query under MySQL 5.0.
// Instead, we try to select from the table and field in question. If it
// fails, the most likely reason is that it does not exist. That is
// dramatically faster than using information_schema.
// @link http://bugs.mysql.com/bug.php?id=19588
// @todo: This override should be removed once we require a version of MySQL
// that has that bug fixed.
try {
$this->connection->queryRange("SELECT $column FROM {" . $table . "}", 0, 1);
return TRUE;
}
catch (Exception $e) {
return FALSE;
}
}
}
/**
* @} End of "addtogroup schemaapi".
*/

View file

@ -0,0 +1,231 @@
<?php
/**
* @file
* Database interface code for PostgreSQL database servers.
*/
/**
* @addtogroup database
* @{
*/
/**
* The name by which to obtain a lock for retrieving the next insert id.
*/
define('POSTGRESQL_NEXTID_LOCK', 1000);
class DatabaseConnection_pgsql extends DatabaseConnection {
public function __construct(array $connection_options = array()) {
// This driver defaults to transaction support, except if explicitly passed FALSE.
$this->transactionSupport = !isset($connection_options['transactions']) || ($connection_options['transactions'] !== FALSE);
// Transactional DDL is always available in PostgreSQL,
// but we'll only enable it if standard transactions are.
$this->transactionalDDLSupport = $this->transactionSupport;
// Default to TCP connection on port 5432.
if (empty($connection_options['port'])) {
$connection_options['port'] = 5432;
}
// PostgreSQL in trust mode doesn't require a password to be supplied.
if (empty($connection_options['password'])) {
$connection_options['password'] = NULL;
}
// If the password contains a backslash it is treated as an escape character
// http://bugs.php.net/bug.php?id=53217
// so backslashes in the password need to be doubled up.
// The bug was reported against pdo_pgsql 1.0.2, backslashes in passwords
// will break on this doubling up when the bug is fixed, so check the version
//elseif (phpversion('pdo_pgsql') < 'version_this_was_fixed_in') {
else {
$connection_options['password'] = str_replace('\\', '\\\\', $connection_options['password']);
}
$this->connectionOptions = $connection_options;
$dsn = 'pgsql:host=' . $connection_options['host'] . ' dbname=' . $connection_options['database'] . ' port=' . $connection_options['port'];
// Allow PDO options to be overridden.
$connection_options += array(
'pdo' => array(),
);
$connection_options['pdo'] += array(
// Prepared statements are most effective for performance when queries
// are recycled (used several times). However, if they are not re-used,
// prepared statements become inefficient. Since most of Drupal's
// prepared queries are not re-used, it should be faster to emulate
// the preparation than to actually ready statements for re-use. If in
// doubt, reset to FALSE and measure performance.
PDO::ATTR_EMULATE_PREPARES => TRUE,
// Convert numeric values to strings when fetching.
PDO::ATTR_STRINGIFY_FETCHES => TRUE,
);
parent::__construct($dsn, $connection_options['username'], $connection_options['password'], $connection_options['pdo']);
// Force PostgreSQL to use the UTF-8 character set by default.
$this->exec("SET NAMES 'UTF8'");
// Execute PostgreSQL init_commands.
if (isset($connection_options['init_commands'])) {
$this->exec(implode('; ', $connection_options['init_commands']));
}
}
public function prepareQuery($query) {
// mapConditionOperator converts LIKE operations to ILIKE for consistency
// with MySQL. However, Postgres does not support ILIKE on bytea (blobs)
// fields.
// To make the ILIKE operator work, we type-cast bytea fields into text.
// @todo This workaround only affects bytea fields, but the involved field
// types involved in the query are unknown, so there is no way to
// conditionally execute this for affected queries only.
return parent::prepareQuery(preg_replace('/ ([^ ]+) +(I*LIKE|NOT +I*LIKE) /i', ' ${1}::text ${2} ', $query));
}
public function query($query, array $args = array(), $options = array()) {
$options += $this->defaultOptions();
// The PDO PostgreSQL driver has a bug which
// doesn't type cast booleans correctly when
// parameters are bound using associative
// arrays.
// See http://bugs.php.net/bug.php?id=48383
foreach ($args as &$value) {
if (is_bool($value)) {
$value = (int) $value;
}
}
try {
if ($query instanceof DatabaseStatementInterface) {
$stmt = $query;
$stmt->execute(NULL, $options);
}
else {
$this->expandArguments($query, $args);
$stmt = $this->prepareQuery($query);
$stmt->execute($args, $options);
}
switch ($options['return']) {
case Database::RETURN_STATEMENT:
return $stmt;
case Database::RETURN_AFFECTED:
return $stmt->rowCount();
case Database::RETURN_INSERT_ID:
return $this->lastInsertId($options['sequence_name']);
case Database::RETURN_NULL:
return;
default:
throw new PDOException('Invalid return directive: ' . $options['return']);
}
}
catch (PDOException $e) {
if ($options['throw_exception']) {
// Add additional debug information.
if ($query instanceof DatabaseStatementInterface) {
$e->query_string = $stmt->getQueryString();
}
else {
$e->query_string = $query;
}
$e->args = $args;
throw $e;
}
return NULL;
}
}
public function queryRange($query, $from, $count, array $args = array(), array $options = array()) {
return $this->query($query . ' LIMIT ' . (int) $count . ' OFFSET ' . (int) $from, $args, $options);
}
public function queryTemporary($query, array $args = array(), array $options = array()) {
$tablename = $this->generateTemporaryTableName();
$this->query('CREATE TEMPORARY TABLE {' . $tablename . '} AS ' . $query, $args, $options);
return $tablename;
}
public function driver() {
return 'pgsql';
}
public function databaseType() {
return 'pgsql';
}
public function mapConditionOperator($operator) {
static $specials;
// Function calls not allowed in static declarations, thus this method.
if (!isset($specials)) {
$specials = array(
// In PostgreSQL, 'LIKE' is case-sensitive. For case-insensitive LIKE
// statements, we need to use ILIKE instead.
'LIKE' => array('operator' => 'ILIKE'),
'NOT LIKE' => array('operator' => 'NOT ILIKE'),
);
}
return isset($specials[$operator]) ? $specials[$operator] : NULL;
}
/**
* Retrieve the next id in a sequence.
*
* PostgreSQL has built in sequences. We'll use these instead of inserting
* and updating a sequences table.
*/
public function nextId($existing = 0) {
// Retrieve the name of the sequence. This information cannot be cached
// because the prefix may change, for example, like it does in simpletests.
$sequence_name = $this->makeSequenceName('sequences', 'value');
// When PostgreSQL gets a value too small then it will lock the table,
// retry the INSERT and if it's still too small then alter the sequence.
$id = $this->query("SELECT nextval('" . $sequence_name . "')")->fetchField();
if ($id > $existing) {
return $id;
}
// PostgreSQL advisory locks are simply locks to be used by an
// application such as Drupal. This will prevent other Drupal processes
// from altering the sequence while we are.
$this->query("SELECT pg_advisory_lock(" . POSTGRESQL_NEXTID_LOCK . ")");
// While waiting to obtain the lock, the sequence may have been altered
// so lets try again to obtain an adequate value.
$id = $this->query("SELECT nextval('" . $sequence_name . "')")->fetchField();
if ($id > $existing) {
$this->query("SELECT pg_advisory_unlock(" . POSTGRESQL_NEXTID_LOCK . ")");
return $id;
}
// Reset the sequence to a higher value than the existing id.
$this->query("ALTER SEQUENCE " . $sequence_name . " RESTART WITH " . ($existing + 1));
// Retrieve the next id. We know this will be as high as we want it.
$id = $this->query("SELECT nextval('" . $sequence_name . "')")->fetchField();
$this->query("SELECT pg_advisory_unlock(" . POSTGRESQL_NEXTID_LOCK . ")");
return $id;
}
public function utf8mb4IsActive() {
return TRUE;
}
public function utf8mb4IsSupported() {
return TRUE;
}
}
/**
* @} End of "addtogroup database".
*/

View file

@ -0,0 +1,197 @@
<?php
/**
* @file
* Install functions for PostgreSQL embedded database engine.
*/
// PostgreSQL specific install functions
class DatabaseTasks_pgsql extends DatabaseTasks {
protected $pdoDriver = 'pgsql';
public function __construct() {
$this->tasks[] = array(
'function' => 'checkEncoding',
'arguments' => array(),
);
$this->tasks[] = array(
'function' => 'checkPHPVersion',
'arguments' => array(),
);
$this->tasks[] = array(
'function' => 'checkBinaryOutput',
'arguments' => array(),
);
$this->tasks[] = array(
'function' => 'initializeDatabase',
'arguments' => array(),
);
}
public function name() {
return st('PostgreSQL');
}
public function minimumVersion() {
return '8.3';
}
/**
* Check encoding is UTF8.
*/
protected function checkEncoding() {
try {
if (db_query('SHOW server_encoding')->fetchField() == 'UTF8') {
$this->pass(st('Database is encoded in UTF-8'));
}
else {
$replacements = array(
'%encoding' => 'UTF8',
'%driver' => $this->name(),
'!link' => '<a href="INSTALL.pgsql.txt">INSTALL.pgsql.txt</a>'
);
$text = 'The %driver database must use %encoding encoding to work with Drupal.';
$text .= 'Recreate the database with %encoding encoding. See !link for more details.';
$this->fail(st($text, $replacements));
}
}
catch (Exception $e) {
$this->fail(st('Drupal could not determine the encoding of the database was set to UTF-8'));
}
}
/**
* Check PHP version.
*
* There are two bugs in PDO_pgsql affecting Drupal:
*
* - in versions < 5.2.7, PDO_pgsql refuses to insert an empty string into
* a NOT NULL BLOB column. See: http://bugs.php.net/bug.php?id=46249
* - in versions < 5.2.11 and < 5.3.1 that prevents inserting integer values
* into numeric columns that exceed the PHP_INT_MAX value.
* See: http://bugs.php.net/bug.php?id=48924
*/
function checkPHPVersion() {
if (!version_compare(PHP_VERSION, '5.2.11', '>=') || (version_compare(PHP_VERSION, '5.3.0', '>=') && !version_compare(PHP_VERSION, '5.3.1', '>='))) {
$this->fail(st('The version of PHP you are using has known issues with PostgreSQL. You need to upgrade PHP to 5.2.11, 5.3.1 or greater.'));
};
}
/**
* Check Binary Output.
*
* Unserializing does not work on Postgresql 9 when bytea_output is 'hex'.
*/
function checkBinaryOutput() {
// PostgreSQL < 9 doesn't support bytea_output, so verify we are running
// at least PostgreSQL 9.
$database_connection = Database::getConnection();
if (version_compare($database_connection->version(), '9') >= 0) {
if (!$this->checkBinaryOutputSuccess()) {
// First try to alter the database. If it fails, raise an error telling
// the user to do it themselves.
$connection_options = $database_connection->getConnectionOptions();
// It is safe to include the database name directly here, because this
// code is only called when a connection to the database is already
// established, thus the database name is guaranteed to be a correct
// value.
$query = "ALTER DATABASE \"" . $connection_options['database'] . "\" SET bytea_output = 'escape';";
try {
db_query($query);
}
catch (Exception $e) {
// Ignore possible errors when the user doesn't have the necessary
// privileges to ALTER the database.
}
// Close the database connection so that the configuration parameter
// is applied to the current connection.
db_close();
// Recheck, if it fails, finally just rely on the end user to do the
// right thing.
if (!$this->checkBinaryOutputSuccess()) {
$replacements = array(
'%setting' => 'bytea_output',
'%current_value' => 'hex',
'%needed_value' => 'escape',
'!query' => "<code>" . $query . "</code>",
);
$this->fail(st("The %setting setting is currently set to '%current_value', but needs to be '%needed_value'. Change this by running the following query: !query", $replacements));
}
}
}
}
/**
* Verify that a binary data roundtrip returns the original string.
*/
protected function checkBinaryOutputSuccess() {
$bytea_output = db_query("SELECT 'encoding'::bytea AS output")->fetchField();
return ($bytea_output == 'encoding');
}
/**
* Make PostgreSQL Drupal friendly.
*/
function initializeDatabase() {
// We create some functions using global names instead of prefixing them
// like we do with table names. This is so that we don't double up if more
// than one instance of Drupal is running on a single database. We therefore
// avoid trying to create them again in that case.
try {
// Create functions.
db_query('CREATE OR REPLACE FUNCTION "greatest"(numeric, numeric) RETURNS numeric AS
\'SELECT CASE WHEN (($1 > $2) OR ($2 IS NULL)) THEN $1 ELSE $2 END;\'
LANGUAGE \'sql\''
);
db_query('CREATE OR REPLACE FUNCTION "greatest"(numeric, numeric, numeric) RETURNS numeric AS
\'SELECT greatest($1, greatest($2, $3));\'
LANGUAGE \'sql\''
);
// Don't use {} around pg_proc table.
if (!db_query("SELECT COUNT(*) FROM pg_proc WHERE proname = 'rand'")->fetchField()) {
db_query('CREATE OR REPLACE FUNCTION "rand"() RETURNS float AS
\'SELECT random();\'
LANGUAGE \'sql\''
);
}
db_query('CREATE OR REPLACE FUNCTION "substring_index"(text, text, integer) RETURNS text AS
\'SELECT array_to_string((string_to_array($1, $2)) [1:$3], $2);\'
LANGUAGE \'sql\''
);
// Using || to concatenate in Drupal is not recommended because there are
// database drivers for Drupal that do not support the syntax, however
// they do support CONCAT(item1, item2) which we can replicate in
// PostgreSQL. PostgreSQL requires the function to be defined for each
// different argument variation the function can handle.
db_query('CREATE OR REPLACE FUNCTION "concat"(anynonarray, anynonarray) RETURNS text AS
\'SELECT CAST($1 AS text) || CAST($2 AS text);\'
LANGUAGE \'sql\'
');
db_query('CREATE OR REPLACE FUNCTION "concat"(text, anynonarray) RETURNS text AS
\'SELECT $1 || CAST($2 AS text);\'
LANGUAGE \'sql\'
');
db_query('CREATE OR REPLACE FUNCTION "concat"(anynonarray, text) RETURNS text AS
\'SELECT CAST($1 AS text) || $2;\'
LANGUAGE \'sql\'
');
db_query('CREATE OR REPLACE FUNCTION "concat"(text, text) RETURNS text AS
\'SELECT $1 || $2;\'
LANGUAGE \'sql\'
');
$this->pass(st('PostgreSQL has initialized itself.'));
}
catch (Exception $e) {
$this->fail(st('Drupal could not be correctly setup with the existing database. Revise any errors.'));
}
}
}

View file

@ -0,0 +1,210 @@
<?php
/**
* @ingroup database
* @{
*/
/**
* @file
* Query code for PostgreSQL embedded database engine.
*/
class InsertQuery_pgsql extends InsertQuery {
public function execute() {
if (!$this->preExecute()) {
return NULL;
}
$stmt = $this->connection->prepareQuery((string) $this);
// Fetch the list of blobs and sequences used on that table.
$table_information = $this->connection->schema()->queryTableInformation($this->table);
$max_placeholder = 0;
$blobs = array();
$blob_count = 0;
foreach ($this->insertValues as $insert_values) {
foreach ($this->insertFields as $idx => $field) {
if (isset($table_information->blob_fields[$field])) {
$blobs[$blob_count] = fopen('php://memory', 'a');
fwrite($blobs[$blob_count], $insert_values[$idx]);
rewind($blobs[$blob_count]);
$stmt->bindParam(':db_insert_placeholder_' . $max_placeholder++, $blobs[$blob_count], PDO::PARAM_LOB);
// Pre-increment is faster in PHP than increment.
++$blob_count;
}
else {
$stmt->bindParam(':db_insert_placeholder_' . $max_placeholder++, $insert_values[$idx]);
}
}
// Check if values for a serial field has been passed.
if (!empty($table_information->serial_fields)) {
foreach ($table_information->serial_fields as $index => $serial_field) {
$serial_key = array_search($serial_field, $this->insertFields);
if ($serial_key !== FALSE) {
$serial_value = $insert_values[$serial_key];
// Force $last_insert_id to the specified value. This is only done
// if $index is 0.
if ($index == 0) {
$last_insert_id = $serial_value;
}
// Set the sequence to the bigger value of either the passed
// value or the max value of the column. It can happen that another
// thread calls nextval() which could lead to a serial number being
// used twice. However, trying to insert a value into a serial
// column should only be done in very rare cases and is not thread
// safe by definition.
$this->connection->query("SELECT setval('" . $table_information->sequences[$index] . "', GREATEST(MAX(" . $serial_field . "), :serial_value)) FROM {" . $this->table . "}", array(':serial_value' => (int)$serial_value));
}
}
}
}
if (!empty($this->fromQuery)) {
// bindParam stores only a reference to the variable that is followed when
// the statement is executed. We pass $arguments[$key] instead of $value
// because the second argument to bindParam is passed by reference and
// the foreach statement assigns the element to the existing reference.
$arguments = $this->fromQuery->getArguments();
foreach ($arguments as $key => $value) {
$stmt->bindParam($key, $arguments[$key]);
}
}
// PostgreSQL requires the table name to be specified explicitly
// when requesting the last insert ID, so we pass that in via
// the options array.
$options = $this->queryOptions;
if (!empty($table_information->sequences)) {
$options['sequence_name'] = $table_information->sequences[0];
}
// If there are no sequences then we can't get a last insert id.
elseif ($options['return'] == Database::RETURN_INSERT_ID) {
$options['return'] = Database::RETURN_NULL;
}
// Only use the returned last_insert_id if it is not already set.
if (!empty($last_insert_id)) {
$this->connection->query($stmt, array(), $options);
}
else {
$last_insert_id = $this->connection->query($stmt, array(), $options);
}
// Re-initialize the values array so that we can re-use this query.
$this->insertValues = array();
return $last_insert_id;
}
public function __toString() {
// Create a sanitized comment string to prepend to the query.
$comments = $this->connection->makeComment($this->comments);
// Default fields are always placed first for consistency.
$insert_fields = array_merge($this->defaultFields, $this->insertFields);
// If we're selecting from a SelectQuery, finish building the query and
// pass it back, as any remaining options are irrelevant.
if (!empty($this->fromQuery)) {
$insert_fields_string = $insert_fields ? ' (' . implode(', ', $insert_fields) . ') ' : ' ';
return $comments . 'INSERT INTO {' . $this->table . '}' . $insert_fields_string . $this->fromQuery;
}
$query = $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') VALUES ';
$max_placeholder = 0;
$values = array();
if (count($this->insertValues)) {
foreach ($this->insertValues as $insert_values) {
$placeholders = array();
// Default fields aren't really placeholders, but this is the most convenient
// way to handle them.
$placeholders = array_pad($placeholders, count($this->defaultFields), 'default');
$new_placeholder = $max_placeholder + count($insert_values);
for ($i = $max_placeholder; $i < $new_placeholder; ++$i) {
$placeholders[] = ':db_insert_placeholder_' . $i;
}
$max_placeholder = $new_placeholder;
$values[] = '(' . implode(', ', $placeholders) . ')';
}
}
else {
// If there are no values, then this is a default-only query. We still need to handle that.
$placeholders = array_fill(0, count($this->defaultFields), 'default');
$values[] = '(' . implode(', ', $placeholders) . ')';
}
$query .= implode(', ', $values);
return $query;
}
}
class UpdateQuery_pgsql extends UpdateQuery {
public function execute() {
$max_placeholder = 0;
$blobs = array();
$blob_count = 0;
// Because we filter $fields the same way here and in __toString(), the
// placeholders will all match up properly.
$stmt = $this->connection->prepareQuery((string) $this);
// Fetch the list of blobs and sequences used on that table.
$table_information = $this->connection->schema()->queryTableInformation($this->table);
// Expressions take priority over literal fields, so we process those first
// and remove any literal fields that conflict.
$fields = $this->fields;
$expression_fields = array();
foreach ($this->expressionFields as $field => $data) {
if (!empty($data['arguments'])) {
foreach ($data['arguments'] as $placeholder => $argument) {
// We assume that an expression will never happen on a BLOB field,
// which is a fairly safe assumption to make since in most cases
// it would be an invalid query anyway.
$stmt->bindParam($placeholder, $data['arguments'][$placeholder]);
}
}
unset($fields[$field]);
}
foreach ($fields as $field => $value) {
$placeholder = ':db_update_placeholder_' . ($max_placeholder++);
if (isset($table_information->blob_fields[$field])) {
$blobs[$blob_count] = fopen('php://memory', 'a');
fwrite($blobs[$blob_count], $value);
rewind($blobs[$blob_count]);
$stmt->bindParam($placeholder, $blobs[$blob_count], PDO::PARAM_LOB);
++$blob_count;
}
else {
$stmt->bindParam($placeholder, $fields[$field]);
}
}
if (count($this->condition)) {
$this->condition->compile($this->connection, $this);
$arguments = $this->condition->arguments();
foreach ($arguments as $placeholder => $value) {
$stmt->bindParam($placeholder, $arguments[$placeholder]);
}
}
$options = $this->queryOptions;
$options['already_prepared'] = TRUE;
$this->connection->query($stmt, $options);
return $stmt->rowCount();
}
}

View file

@ -0,0 +1,617 @@
<?php
/**
* @file
* Database schema code for PostgreSQL database servers.
*/
/**
* @ingroup schemaapi
* @{
*/
class DatabaseSchema_pgsql extends DatabaseSchema {
/**
* A cache of information about blob columns and sequences of tables.
*
* This is collected by DatabaseConnection_pgsql->queryTableInformation(),
* by introspecting the database.
*
* @see DatabaseConnection_pgsql->queryTableInformation()
* @var array
*/
protected $tableInformation = array();
/**
* Fetch the list of blobs and sequences used on a table.
*
* We introspect the database to collect the information required by insert
* and update queries.
*
* @param $table_name
* The non-prefixed name of the table.
* @return
* An object with two member variables:
* - 'blob_fields' that lists all the blob fields in the table.
* - 'sequences' that lists the sequences used in that table.
*/
public function queryTableInformation($table) {
// Generate a key to reference this table's information on.
$key = $this->connection->prefixTables('{' . $table . '}');
if (!strpos($key, '.')) {
$key = 'public.' . $key;
}
if (!isset($this->tableInformation[$key])) {
// Split the key into schema and table for querying.
list($schema, $table_name) = explode('.', $key);
$table_information = (object) array(
'blob_fields' => array(),
'sequences' => array(),
);
// Don't use {} around information_schema.columns table.
$result = $this->connection->query("SELECT column_name, data_type, column_default FROM information_schema.columns WHERE table_schema = :schema AND table_name = :table AND (data_type = 'bytea' OR (numeric_precision IS NOT NULL AND column_default LIKE :default))", array(
':schema' => $schema,
':table' => $table_name,
':default' => '%nextval%',
));
foreach ($result as $column) {
if ($column->data_type == 'bytea') {
$table_information->blob_fields[$column->column_name] = TRUE;
}
elseif (preg_match("/nextval\('([^']+)'/", $column->column_default, $matches)) {
// We must know of any sequences in the table structure to help us
// return the last insert id. If there is more than 1 sequences the
// first one (index 0 of the sequences array) will be used.
$table_information->sequences[] = $matches[1];
$table_information->serial_fields[] = $column->column_name;
}
}
$this->tableInformation[$key] = $table_information;
}
return $this->tableInformation[$key];
}
/**
* Fetch the list of CHECK constraints used on a field.
*
* We introspect the database to collect the information required by field
* alteration.
*
* @param $table
* The non-prefixed name of the table.
* @param $field
* The name of the field.
* @return
* An array of all the checks for the field.
*/
public function queryFieldInformation($table, $field) {
$prefixInfo = $this->getPrefixInfo($table, TRUE);
// Split the key into schema and table for querying.
$schema = $prefixInfo['schema'];
$table_name = $prefixInfo['table'];
$field_information = (object) array(
'checks' => array(),
);
$checks = $this->connection->query("SELECT conname FROM pg_class cl INNER JOIN pg_constraint co ON co.conrelid = cl.oid INNER JOIN pg_attribute attr ON attr.attrelid = cl.oid AND attr.attnum = ANY (co.conkey) INNER JOIN pg_namespace ns ON cl.relnamespace = ns.oid WHERE co.contype = 'c' AND ns.nspname = :schema AND cl.relname = :table AND attr.attname = :column", array(
':schema' => $schema,
':table' => $table_name,
':column' => $field,
));
$field_information = $checks->fetchCol();
return $field_information;
}
/**
* Generate SQL to create a new table from a Drupal schema definition.
*
* @param $name
* The name of the table to create.
* @param $table
* A Schema API table definition array.
* @return
* An array of SQL statements to create the table.
*/
protected function createTableSql($name, $table) {
$sql_fields = array();
foreach ($table['fields'] as $field_name => $field) {
$sql_fields[] = $this->createFieldSql($field_name, $this->processField($field));
}
$sql_keys = array();
if (isset($table['primary key']) && is_array($table['primary key'])) {
$sql_keys[] = 'PRIMARY KEY (' . implode(', ', $table['primary key']) . ')';
}
if (isset($table['unique keys']) && is_array($table['unique keys'])) {
foreach ($table['unique keys'] as $key_name => $key) {
$sql_keys[] = 'CONSTRAINT ' . $this->prefixNonTable($name, $key_name, 'key') . ' UNIQUE (' . implode(', ', $key) . ')';
}
}
$sql = "CREATE TABLE {" . $name . "} (\n\t";
$sql .= implode(",\n\t", $sql_fields);
if (count($sql_keys) > 0) {
$sql .= ",\n\t";
}
$sql .= implode(",\n\t", $sql_keys);
$sql .= "\n)";
$statements[] = $sql;
if (isset($table['indexes']) && is_array($table['indexes'])) {
foreach ($table['indexes'] as $key_name => $key) {
$statements[] = $this->_createIndexSql($name, $key_name, $key);
}
}
// Add table comment.
if (!empty($table['description'])) {
$statements[] = 'COMMENT ON TABLE {' . $name . '} IS ' . $this->prepareComment($table['description']);
}
// Add column comments.
foreach ($table['fields'] as $field_name => $field) {
if (!empty($field['description'])) {
$statements[] = 'COMMENT ON COLUMN {' . $name . '}.' . $field_name . ' IS ' . $this->prepareComment($field['description']);
}
}
return $statements;
}
/**
* Create an SQL string for a field to be used in table creation or
* alteration.
*
* Before passing a field out of a schema definition into this
* function it has to be processed by _db_process_field().
*
* @param $name
* Name of the field.
* @param $spec
* The field specification, as per the schema data structure format.
*/
protected function createFieldSql($name, $spec) {
$sql = $name . ' ' . $spec['pgsql_type'];
if (isset($spec['type']) && $spec['type'] == 'serial') {
unset($spec['not null']);
}
if (in_array($spec['pgsql_type'], array('varchar', 'character', 'text')) && isset($spec['length'])) {
$sql .= '(' . $spec['length'] . ')';
}
elseif (isset($spec['precision']) && isset($spec['scale'])) {
$sql .= '(' . $spec['precision'] . ', ' . $spec['scale'] . ')';
}
if (!empty($spec['unsigned'])) {
$sql .= " CHECK ($name >= 0)";
}
if (isset($spec['not null'])) {
if ($spec['not null']) {
$sql .= ' NOT NULL';
}
else {
$sql .= ' NULL';
}
}
if (isset($spec['default'])) {
$default = is_string($spec['default']) ? "'" . $spec['default'] . "'" : $spec['default'];
$sql .= " default $default";
}
return $sql;
}
/**
* Set database-engine specific properties for a field.
*
* @param $field
* A field description array, as specified in the schema documentation.
*/
protected function processField($field) {
if (!isset($field['size'])) {
$field['size'] = 'normal';
}
// Set the correct database-engine specific datatype.
// In case one is already provided, force it to lowercase.
if (isset($field['pgsql_type'])) {
$field['pgsql_type'] = drupal_strtolower($field['pgsql_type']);
}
else {
$map = $this->getFieldTypeMap();
$field['pgsql_type'] = $map[$field['type'] . ':' . $field['size']];
}
if (!empty($field['unsigned'])) {
// Unsigned datatypes are not supported in PostgreSQL 8.3. In MySQL,
// they are used to ensure a positive number is inserted and it also
// doubles the maximum integer size that can be stored in a field.
// The PostgreSQL schema in Drupal creates a check constraint
// to ensure that a value inserted is >= 0. To provide the extra
// integer capacity, here, we bump up the column field size.
if (!isset($map)) {
$map = $this->getFieldTypeMap();
}
switch ($field['pgsql_type']) {
case 'smallint':
$field['pgsql_type'] = $map['int:medium'];
break;
case 'int' :
$field['pgsql_type'] = $map['int:big'];
break;
}
}
if (isset($field['type']) && $field['type'] == 'serial') {
unset($field['not null']);
}
return $field;
}
/**
* This maps a generic data type in combination with its data size
* to the engine-specific data type.
*/
function getFieldTypeMap() {
// Put :normal last so it gets preserved by array_flip. This makes
// it much easier for modules (such as schema.module) to map
// database types back into schema types.
// $map does not use drupal_static as its value never changes.
static $map = array(
'varchar:normal' => 'varchar',
'char:normal' => 'character',
'text:tiny' => 'text',
'text:small' => 'text',
'text:medium' => 'text',
'text:big' => 'text',
'text:normal' => 'text',
'int:tiny' => 'smallint',
'int:small' => 'smallint',
'int:medium' => 'int',
'int:big' => 'bigint',
'int:normal' => 'int',
'float:tiny' => 'real',
'float:small' => 'real',
'float:medium' => 'real',
'float:big' => 'double precision',
'float:normal' => 'real',
'numeric:normal' => 'numeric',
'blob:big' => 'bytea',
'blob:normal' => 'bytea',
'serial:tiny' => 'serial',
'serial:small' => 'serial',
'serial:medium' => 'serial',
'serial:big' => 'bigserial',
'serial:normal' => 'serial',
);
return $map;
}
protected function _createKeySql($fields) {
$return = array();
foreach ($fields as $field) {
if (is_array($field)) {
$return[] = 'substr(' . $field[0] . ', 1, ' . $field[1] . ')';
}
else {
$return[] = '"' . $field . '"';
}
}
return implode(', ', $return);
}
function renameTable($table, $new_name) {
if (!$this->tableExists($table)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot rename @table to @table_new: table @table doesn't exist.", array('@table' => $table, '@table_new' => $new_name)));
}
if ($this->tableExists($new_name)) {
throw new DatabaseSchemaObjectExistsException(t("Cannot rename @table to @table_new: table @table_new already exists.", array('@table' => $table, '@table_new' => $new_name)));
}
// Get the schema and tablename for the old table.
$old_full_name = $this->connection->prefixTables('{' . $table . '}');
list($old_schema, $old_table_name) = strpos($old_full_name, '.') ? explode('.', $old_full_name) : array('public', $old_full_name);
// Index names and constraint names are global in PostgreSQL, so we need to
// rename them when renaming the table.
$indexes = $this->connection->query('SELECT indexname FROM pg_indexes WHERE schemaname = :schema AND tablename = :table', array(':schema' => $old_schema, ':table' => $old_table_name));
foreach ($indexes as $index) {
if (preg_match('/^' . preg_quote($old_full_name) . '_(.*)$/', $index->indexname, $matches)) {
$index_name = $matches[1];
$this->connection->query('ALTER INDEX ' . $index->indexname . ' RENAME TO {' . $new_name . '}_' . $index_name);
}
}
// Now rename the table.
// Ensure the new table name does not include schema syntax.
$prefixInfo = $this->getPrefixInfo($new_name);
$this->connection->query('ALTER TABLE {' . $table . '} RENAME TO ' . $prefixInfo['table']);
}
public function dropTable($table) {
if (!$this->tableExists($table)) {
return FALSE;
}
$this->connection->query('DROP TABLE {' . $table . '}');
return TRUE;
}
public function addField($table, $field, $spec, $new_keys = array()) {
if (!$this->tableExists($table)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add field @table.@field: table doesn't exist.", array('@field' => $field, '@table' => $table)));
}
if ($this->fieldExists($table, $field)) {
throw new DatabaseSchemaObjectExistsException(t("Cannot add field @table.@field: field already exists.", array('@field' => $field, '@table' => $table)));
}
$fixnull = FALSE;
if (!empty($spec['not null']) && !isset($spec['default'])) {
$fixnull = TRUE;
$spec['not null'] = FALSE;
}
$query = 'ALTER TABLE {' . $table . '} ADD COLUMN ';
$query .= $this->createFieldSql($field, $this->processField($spec));
$this->connection->query($query);
if (isset($spec['initial'])) {
$this->connection->update($table)
->fields(array($field => $spec['initial']))
->execute();
}
if ($fixnull) {
$this->connection->query("ALTER TABLE {" . $table . "} ALTER $field SET NOT NULL");
}
if (isset($new_keys)) {
$this->_createKeys($table, $new_keys);
}
// Add column comment.
if (!empty($spec['description'])) {
$this->connection->query('COMMENT ON COLUMN {' . $table . '}.' . $field . ' IS ' . $this->prepareComment($spec['description']));
}
}
public function dropField($table, $field) {
if (!$this->fieldExists($table, $field)) {
return FALSE;
}
$this->connection->query('ALTER TABLE {' . $table . '} DROP COLUMN "' . $field . '"');
return TRUE;
}
public function fieldSetDefault($table, $field, $default) {
if (!$this->fieldExists($table, $field)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot set default value of field @table.@field: field doesn't exist.", array('@table' => $table, '@field' => $field)));
}
if (!isset($default)) {
$default = 'NULL';
}
else {
$default = is_string($default) ? "'$default'" : $default;
}
$this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN "' . $field . '" SET DEFAULT ' . $default);
}
public function fieldSetNoDefault($table, $field) {
if (!$this->fieldExists($table, $field)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot remove default value of field @table.@field: field doesn't exist.", array('@table' => $table, '@field' => $field)));
}
$this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN "' . $field . '" DROP DEFAULT');
}
public function indexExists($table, $name) {
// Details http://www.postgresql.org/docs/8.3/interactive/view-pg-indexes.html
$index_name = '{' . $table . '}_' . $name . '_idx';
return (bool) $this->connection->query("SELECT 1 FROM pg_indexes WHERE indexname = '$index_name'")->fetchField();
}
/**
* Helper function: check if a constraint (PK, FK, UK) exists.
*
* @param $table
* The name of the table.
* @param $name
* The name of the constraint (typically 'pkey' or '[constraint]_key').
*/
protected function constraintExists($table, $name) {
$constraint_name = '{' . $table . '}_' . $name;
return (bool) $this->connection->query("SELECT 1 FROM pg_constraint WHERE conname = '$constraint_name'")->fetchField();
}
public function addPrimaryKey($table, $fields) {
if (!$this->tableExists($table)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add primary key to table @table: table doesn't exist.", array('@table' => $table)));
}
if ($this->constraintExists($table, 'pkey')) {
throw new DatabaseSchemaObjectExistsException(t("Cannot add primary key to table @table: primary key already exists.", array('@table' => $table)));
}
$this->connection->query('ALTER TABLE {' . $table . '} ADD PRIMARY KEY (' . implode(',', $fields) . ')');
}
public function dropPrimaryKey($table) {
if (!$this->constraintExists($table, 'pkey')) {
return FALSE;
}
$this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT ' . $this->prefixNonTable($table, 'pkey'));
return TRUE;
}
function addUniqueKey($table, $name, $fields) {
if (!$this->tableExists($table)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add unique key @name to table @table: table doesn't exist.", array('@table' => $table, '@name' => $name)));
}
if ($this->constraintExists($table, $name . '_key')) {
throw new DatabaseSchemaObjectExistsException(t("Cannot add unique key @name to table @table: unique key already exists.", array('@table' => $table, '@name' => $name)));
}
$this->connection->query('ALTER TABLE {' . $table . '} ADD CONSTRAINT "' . $this->prefixNonTable($table, $name, 'key') . '" UNIQUE (' . implode(',', $fields) . ')');
}
public function dropUniqueKey($table, $name) {
if (!$this->constraintExists($table, $name . '_key')) {
return FALSE;
}
$this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT "' . $this->prefixNonTable($table, $name, 'key') . '"');
return TRUE;
}
public function addIndex($table, $name, $fields) {
if (!$this->tableExists($table)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add index @name to table @table: table doesn't exist.", array('@table' => $table, '@name' => $name)));
}
if ($this->indexExists($table, $name)) {
throw new DatabaseSchemaObjectExistsException(t("Cannot add index @name to table @table: index already exists.", array('@table' => $table, '@name' => $name)));
}
$this->connection->query($this->_createIndexSql($table, $name, $fields));
}
public function dropIndex($table, $name) {
if (!$this->indexExists($table, $name)) {
return FALSE;
}
$this->connection->query('DROP INDEX ' . $this->prefixNonTable($table, $name, 'idx'));
return TRUE;
}
public function changeField($table, $field, $field_new, $spec, $new_keys = array()) {
if (!$this->fieldExists($table, $field)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot change the definition of field @table.@name: field doesn't exist.", array('@table' => $table, '@name' => $field)));
}
if (($field != $field_new) && $this->fieldExists($table, $field_new)) {
throw new DatabaseSchemaObjectExistsException(t("Cannot rename field @table.@name to @name_new: target field already exists.", array('@table' => $table, '@name' => $field, '@name_new' => $field_new)));
}
$spec = $this->processField($spec);
// We need to typecast the new column to best be able to transfer the data
// Schema_pgsql::getFieldTypeMap() will return possibilities that are not
// 'cast-able' such as 'serial' - so they need to be casted int instead.
if (in_array($spec['pgsql_type'], array('serial', 'bigserial', 'numeric'))) {
$typecast = 'int';
}
else {
$typecast = $spec['pgsql_type'];
}
if (in_array($spec['pgsql_type'], array('varchar', 'character', 'text')) && isset($spec['length'])) {
$typecast .= '(' . $spec['length'] . ')';
}
elseif (isset($spec['precision']) && isset($spec['scale'])) {
$typecast .= '(' . $spec['precision'] . ', ' . $spec['scale'] . ')';
}
// Remove old check constraints.
$field_info = $this->queryFieldInformation($table, $field);
foreach ($field_info as $check) {
$this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT "' . $check . '"');
}
// Remove old default.
$this->fieldSetNoDefault($table, $field);
$this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" TYPE ' . $typecast . ' USING "' . $field . '"::' . $typecast);
if (isset($spec['not null'])) {
if ($spec['not null']) {
$nullaction = 'SET NOT NULL';
}
else {
$nullaction = 'DROP NOT NULL';
}
$this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" ' . $nullaction);
}
if (in_array($spec['pgsql_type'], array('serial', 'bigserial'))) {
// Type "serial" is known to PostgreSQL, but *only* during table creation,
// not when altering. Because of that, the sequence needs to be created
// and initialized by hand.
$seq = "{" . $table . "}_" . $field_new . "_seq";
$this->connection->query("CREATE SEQUENCE " . $seq);
// Set sequence to maximal field value to not conflict with existing
// entries.
$this->connection->query("SELECT setval('" . $seq . "', MAX(\"" . $field . '")) FROM {' . $table . "}");
$this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" SET DEFAULT nextval(\'' . $seq . '\')');
}
// Rename the column if necessary.
if ($field != $field_new) {
$this->connection->query('ALTER TABLE {' . $table . '} RENAME "' . $field . '" TO "' . $field_new . '"');
}
// Add unsigned check if necessary.
if (!empty($spec['unsigned'])) {
$this->connection->query('ALTER TABLE {' . $table . '} ADD CHECK ("' . $field_new . '" >= 0)');
}
// Add default if necessary.
if (isset($spec['default'])) {
$this->fieldSetDefault($table, $field_new, $spec['default']);
}
// Change description if necessary.
if (!empty($spec['description'])) {
$this->connection->query('COMMENT ON COLUMN {' . $table . '}."' . $field_new . '" IS ' . $this->prepareComment($spec['description']));
}
if (isset($new_keys)) {
$this->_createKeys($table, $new_keys);
}
}
protected function _createIndexSql($table, $name, $fields) {
$query = 'CREATE INDEX "' . $this->prefixNonTable($table, $name, 'idx') . '" ON {' . $table . '} (';
$query .= $this->_createKeySql($fields) . ')';
return $query;
}
protected function _createKeys($table, $new_keys) {
if (isset($new_keys['primary key'])) {
$this->addPrimaryKey($table, $new_keys['primary key']);
}
if (isset($new_keys['unique keys'])) {
foreach ($new_keys['unique keys'] as $name => $fields) {
$this->addUniqueKey($table, $name, $fields);
}
}
if (isset($new_keys['indexes'])) {
foreach ($new_keys['indexes'] as $name => $fields) {
$this->addIndex($table, $name, $fields);
}
}
}
/**
* Retrieve a table or column comment.
*/
public function getComment($table, $column = NULL) {
$info = $this->getPrefixInfo($table);
// Don't use {} around pg_class, pg_attribute tables.
if (isset($column)) {
return $this->connection->query('SELECT col_description(oid, attnum) FROM pg_class, pg_attribute WHERE attrelid = oid AND relname = ? AND attname = ?', array($info['table'], $column))->fetchField();
}
else {
return $this->connection->query('SELECT obj_description(oid, ?) FROM pg_class WHERE relname = ?', array('pg_class', $info['table']))->fetchField();
}
}
}

View file

@ -0,0 +1,108 @@
<?php
/**
* @file
* Select builder for PostgreSQL database engine.
*/
/**
* @addtogroup database
* @{
*/
class SelectQuery_pgsql extends SelectQuery {
public function orderRandom() {
$alias = $this->addExpression('RANDOM()', 'random_field');
$this->orderBy($alias);
return $this;
}
/**
* Overrides SelectQuery::orderBy().
*
* PostgreSQL adheres strictly to the SQL-92 standard and requires that when
* using DISTINCT or GROUP BY conditions, fields and expressions that are
* ordered on also need to be selected. This is a best effort implementation
* to handle the cases that can be automated by adding the field if it is not
* yet selected.
*
* @code
* $query = db_select('node', 'n');
* $query->join('node_revision', 'nr', 'n.vid = nr.vid');
* $query
* ->distinct()
* ->fields('n')
* ->orderBy('timestamp');
* @endcode
*
* In this query, it is not possible (without relying on the schema) to know
* whether timestamp belongs to node_revisions and needs to be added or
* belongs to node and is already selected. Queries like this will need to be
* corrected in the original query by adding an explicit call to
* SelectQuery::addField() or SelectQuery::fields().
*
* Since this has a small performance impact, both by the additional
* processing in this function and in the database that needs to return the
* additional fields, this is done as an override instead of implementing it
* directly in SelectQuery::orderBy().
*/
public function orderBy($field, $direction = 'ASC') {
// Call parent function to order on this.
$return = parent::orderBy($field, $direction);
// If there is a table alias specified, split it up.
if (strpos($field, '.') !== FALSE) {
list($table, $table_field) = explode('.', $field);
}
// Figure out if the field has already been added.
foreach ($this->fields as $existing_field) {
if (!empty($table)) {
// If table alias is given, check if field and table exists.
if ($existing_field['table'] == $table && $existing_field['field'] == $table_field) {
return $return;
}
}
else {
// If there is no table, simply check if the field exists as a field or
// an aliased field.
if ($existing_field['alias'] == $field) {
return $return;
}
}
}
// Also check expression aliases.
foreach ($this->expressions as $expression) {
if ($expression['alias'] == $field) {
return $return;
}
}
// If a table loads all fields, it can not be added again. It would
// result in an ambiguous alias error because that field would be loaded
// twice: Once through table_alias.* and once directly. If the field
// actually belongs to a different table, it must be added manually.
foreach ($this->tables as $table) {
if (!empty($table['all_fields'])) {
return $return;
}
}
// If $field contains an characters which are not allowed in a field name
// it is considered an expression, these can't be handled automatically
// either.
if ($this->connection->escapeField($field) != $field) {
return $return;
}
// This is a case that can be handled automatically, add the field.
$this->addField(NULL, $field);
return $return;
}
}
/**
* @} End of "addtogroup database".
*/

View file

@ -0,0 +1,507 @@
<?php
/**
* @file
* Database interface code for engines that need complete control over their
* result sets. For example, SQLite will prefix some column names by the name
* of the table. We post-process the data, by renaming the column names
* using the same convention as MySQL and PostgreSQL.
*/
/**
* @addtogroup database
* @{
*/
/**
* An implementation of DatabaseStatementInterface that prefetches all data.
*
* This class behaves very similar to a PDOStatement but as it always fetches
* every row it is possible to manipulate those results.
*/
class DatabaseStatementPrefetch implements Iterator, DatabaseStatementInterface {
/**
* The query string.
*
* @var string
*/
protected $queryString;
/**
* Driver-specific options. Can be used by child classes.
*
* @var Array
*/
protected $driverOptions;
/**
* Reference to the database connection object for this statement.
*
* The name $dbh is inherited from PDOStatement.
*
* @var DatabaseConnection
*/
public $dbh;
/**
* Main data store.
*
* @var Array
*/
protected $data = array();
/**
* The current row, retrieved in PDO::FETCH_ASSOC format.
*
* @var Array
*/
protected $currentRow = NULL;
/**
* The key of the current row.
*
* @var int
*/
protected $currentKey = NULL;
/**
* The list of column names in this result set.
*
* @var Array
*/
protected $columnNames = NULL;
/**
* The number of rows affected by the last query.
*
* @var int
*/
protected $rowCount = NULL;
/**
* The number of rows in this result set.
*
* @var int
*/
protected $resultRowCount = 0;
/**
* Holds the current fetch style (which will be used by the next fetch).
* @see PDOStatement::fetch()
*
* @var int
*/
protected $fetchStyle = PDO::FETCH_OBJ;
/**
* Holds supplementary current fetch options (which will be used by the next fetch).
*
* @var Array
*/
protected $fetchOptions = array(
'class' => 'stdClass',
'constructor_args' => array(),
'object' => NULL,
'column' => 0,
);
/**
* Holds the default fetch style.
*
* @var int
*/
protected $defaultFetchStyle = PDO::FETCH_OBJ;
/**
* Holds supplementary default fetch options.
*
* @var Array
*/
protected $defaultFetchOptions = array(
'class' => 'stdClass',
'constructor_args' => array(),
'object' => NULL,
'column' => 0,
);
public function __construct(DatabaseConnection $connection, $query, array $driver_options = array()) {
$this->dbh = $connection;
$this->queryString = $query;
$this->driverOptions = $driver_options;
}
/**
* Executes a prepared statement.
*
* @param $args
* An array of values with as many elements as there are bound parameters in the SQL statement being executed.
* @param $options
* An array of options for this query.
* @return
* TRUE on success, or FALSE on failure.
*/
public function execute($args = array(), $options = array()) {
if (isset($options['fetch'])) {
if (is_string($options['fetch'])) {
// Default to an object. Note: db fields will be added to the object
// before the constructor is run. If you need to assign fields after
// the constructor is run, see http://drupal.org/node/315092.
$this->setFetchMode(PDO::FETCH_CLASS, $options['fetch']);
}
else {
$this->setFetchMode($options['fetch']);
}
}
$logger = $this->dbh->getLogger();
if (!empty($logger)) {
$query_start = microtime(TRUE);
}
// Prepare the query.
$statement = $this->getStatement($this->queryString, $args);
if (!$statement) {
$this->throwPDOException();
}
$return = $statement->execute($args);
if (!$return) {
$this->throwPDOException();
}
// Fetch all the data from the reply, in order to release any lock
// as soon as possible.
$this->rowCount = $statement->rowCount();
$this->data = $statement->fetchAll(PDO::FETCH_ASSOC);
// Destroy the statement as soon as possible. See
// DatabaseConnection_sqlite::PDOPrepare() for explanation.
unset($statement);
$this->resultRowCount = count($this->data);
if ($this->resultRowCount) {
$this->columnNames = array_keys($this->data[0]);
}
else {
$this->columnNames = array();
}
if (!empty($logger)) {
$query_end = microtime(TRUE);
$logger->log($this, $args, $query_end - $query_start);
}
// Initialize the first row in $this->currentRow.
$this->next();
return $return;
}
/**
* Throw a PDO Exception based on the last PDO error.
*/
protected function throwPDOException() {
$error_info = $this->dbh->errorInfo();
// We rebuild a message formatted in the same way as PDO.
$exception = new PDOException("SQLSTATE[" . $error_info[0] . "]: General error " . $error_info[1] . ": " . $error_info[2]);
$exception->errorInfo = $error_info;
throw $exception;
}
/**
* Grab a PDOStatement object from a given query and its arguments.
*
* Some drivers (including SQLite) will need to perform some preparation
* themselves to get the statement right.
*
* @param $query
* The query.
* @param array $args
* An array of arguments.
* @return PDOStatement
* A PDOStatement object.
*/
protected function getStatement($query, &$args = array()) {
return $this->dbh->prepare($query);
}
/**
* Return the object's SQL query string.
*/
public function getQueryString() {
return $this->queryString;
}
/**
* @see PDOStatement::setFetchMode()
*/
public function setFetchMode($fetchStyle, $a2 = NULL, $a3 = NULL) {
$this->defaultFetchStyle = $fetchStyle;
switch ($fetchStyle) {
case PDO::FETCH_CLASS:
$this->defaultFetchOptions['class'] = $a2;
if ($a3) {
$this->defaultFetchOptions['constructor_args'] = $a3;
}
break;
case PDO::FETCH_COLUMN:
$this->defaultFetchOptions['column'] = $a2;
break;
case PDO::FETCH_INTO:
$this->defaultFetchOptions['object'] = $a2;
break;
}
// Set the values for the next fetch.
$this->fetchStyle = $this->defaultFetchStyle;
$this->fetchOptions = $this->defaultFetchOptions;
}
/**
* Return the current row formatted according to the current fetch style.
*
* This is the core method of this class. It grabs the value at the current
* array position in $this->data and format it according to $this->fetchStyle
* and $this->fetchMode.
*
* @return
* The current row formatted as requested.
*/
public function current() {
if (isset($this->currentRow)) {
switch ($this->fetchStyle) {
case PDO::FETCH_ASSOC:
return $this->currentRow;
case PDO::FETCH_BOTH:
// PDO::FETCH_BOTH returns an array indexed by both the column name
// and the column number.
return $this->currentRow + array_values($this->currentRow);
case PDO::FETCH_NUM:
return array_values($this->currentRow);
case PDO::FETCH_LAZY:
// We do not do lazy as everything is fetched already. Fallback to
// PDO::FETCH_OBJ.
case PDO::FETCH_OBJ:
return (object) $this->currentRow;
case PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE:
$class_name = array_unshift($this->currentRow);
// Deliberate no break.
case PDO::FETCH_CLASS:
if (!isset($class_name)) {
$class_name = $this->fetchOptions['class'];
}
if (count($this->fetchOptions['constructor_args'])) {
$reflector = new ReflectionClass($class_name);
$result = $reflector->newInstanceArgs($this->fetchOptions['constructor_args']);
}
else {
$result = new $class_name();
}
foreach ($this->currentRow as $k => $v) {
$result->$k = $v;
}
return $result;
case PDO::FETCH_INTO:
foreach ($this->currentRow as $k => $v) {
$this->fetchOptions['object']->$k = $v;
}
return $this->fetchOptions['object'];
case PDO::FETCH_COLUMN:
if (isset($this->columnNames[$this->fetchOptions['column']])) {
return $this->currentRow[$k][$this->columnNames[$this->fetchOptions['column']]];
}
else {
return;
}
}
}
}
/* Implementations of Iterator. */
public function key() {
return $this->currentKey;
}
public function rewind() {
// Nothing to do: our DatabaseStatement can't be rewound.
}
public function next() {
if (!empty($this->data)) {
$this->currentRow = reset($this->data);
$this->currentKey = key($this->data);
unset($this->data[$this->currentKey]);
}
else {
$this->currentRow = NULL;
}
}
public function valid() {
return isset($this->currentRow);
}
/* Implementations of DatabaseStatementInterface. */
public function rowCount() {
return $this->rowCount;
}
public function fetch($fetch_style = NULL, $cursor_orientation = PDO::FETCH_ORI_NEXT, $cursor_offset = NULL) {
if (isset($this->currentRow)) {
// Set the fetch parameter.
$this->fetchStyle = isset($fetch_style) ? $fetch_style : $this->defaultFetchStyle;
$this->fetchOptions = $this->defaultFetchOptions;
// Grab the row in the format specified above.
$return = $this->current();
// Advance the cursor.
$this->next();
// Reset the fetch parameters to the value stored using setFetchMode().
$this->fetchStyle = $this->defaultFetchStyle;
$this->fetchOptions = $this->defaultFetchOptions;
return $return;
}
else {
return FALSE;
}
}
public function fetchColumn($index = 0) {
if (isset($this->currentRow) && isset($this->columnNames[$index])) {
// We grab the value directly from $this->data, and format it.
$return = $this->currentRow[$this->columnNames[$index]];
$this->next();
return $return;
}
else {
return FALSE;
}
}
public function fetchField($index = 0) {
return $this->fetchColumn($index);
}
public function fetchObject($class_name = NULL, $constructor_args = array()) {
if (isset($this->currentRow)) {
if (!isset($class_name)) {
// Directly cast to an object to avoid a function call.
$result = (object) $this->currentRow;
}
else {
$this->fetchStyle = PDO::FETCH_CLASS;
$this->fetchOptions = array('constructor_args' => $constructor_args);
// Grab the row in the format specified above.
$result = $this->current();
// Reset the fetch parameters to the value stored using setFetchMode().
$this->fetchStyle = $this->defaultFetchStyle;
$this->fetchOptions = $this->defaultFetchOptions;
}
$this->next();
return $result;
}
else {
return FALSE;
}
}
public function fetchAssoc() {
if (isset($this->currentRow)) {
$result = $this->currentRow;
$this->next();
return $result;
}
else {
return FALSE;
}
}
public function fetchAll($fetch_style = NULL, $fetch_column = NULL, $constructor_args = NULL) {
$this->fetchStyle = isset($fetch_style) ? $fetch_style : $this->defaultFetchStyle;
$this->fetchOptions = $this->defaultFetchOptions;
if (isset($fetch_column)) {
$this->fetchOptions['column'] = $fetch_column;
}
if (isset($constructor_args)) {
$this->fetchOptions['constructor_args'] = $constructor_args;
}
$result = array();
// Traverse the array as PHP would have done.
while (isset($this->currentRow)) {
// Grab the row in the format specified above.
$result[] = $this->current();
$this->next();
}
// Reset the fetch parameters to the value stored using setFetchMode().
$this->fetchStyle = $this->defaultFetchStyle;
$this->fetchOptions = $this->defaultFetchOptions;
return $result;
}
public function fetchCol($index = 0) {
if (isset($this->columnNames[$index])) {
$column = $this->columnNames[$index];
$result = array();
// Traverse the array as PHP would have done.
while (isset($this->currentRow)) {
$result[] = $this->currentRow[$this->columnNames[$index]];
$this->next();
}
return $result;
}
else {
return array();
}
}
public function fetchAllKeyed($key_index = 0, $value_index = 1) {
if (!isset($this->columnNames[$key_index]) || !isset($this->columnNames[$value_index]))
return array();
$key = $this->columnNames[$key_index];
$value = $this->columnNames[$value_index];
$result = array();
// Traverse the array as PHP would have done.
while (isset($this->currentRow)) {
$result[$this->currentRow[$key]] = $this->currentRow[$value];
$this->next();
}
return $result;
}
public function fetchAllAssoc($key, $fetch_style = NULL) {
$this->fetchStyle = isset($fetch_style) ? $fetch_style : $this->defaultFetchStyle;
$this->fetchOptions = $this->defaultFetchOptions;
$result = array();
// Traverse the array as PHP would have done.
while (isset($this->currentRow)) {
// Grab the row in its raw PDO::FETCH_ASSOC format.
$row = $this->currentRow;
// Grab the row in the format specified above.
$result_row = $this->current();
$result[$this->currentRow[$key]] = $result_row;
$this->next();
}
// Reset the fetch parameters to the value stored using setFetchMode().
$this->fetchStyle = $this->defaultFetchStyle;
$this->fetchOptions = $this->defaultFetchOptions;
return $result;
}
}
/**
* @} End of "addtogroup database".
*/

1963
includes/database/query.inc Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,733 @@
<?php
/**
* @file
* Generic Database schema code.
*/
require_once dirname(__FILE__) . '/query.inc';
/**
* @defgroup schemaapi Schema API
* @{
* API to handle database schemas.
*
* A Drupal schema definition is an array structure representing one or
* more tables and their related keys and indexes. A schema is defined by
* hook_schema(), which usually lives in a modulename.install file.
*
* By implementing hook_schema() and specifying the tables your module
* declares, you can easily create and drop these tables on all
* supported database engines. You don't have to deal with the
* different SQL dialects for table creation and alteration of the
* supported database engines.
*
* hook_schema() should return an array with a key for each table that
* the module defines.
*
* The following keys are defined:
* - 'description': A string in non-markup plain text describing this table
* and its purpose. References to other tables should be enclosed in
* curly-brackets. For example, the node_revisions table
* description field might contain "Stores per-revision title and
* body data for each {node}."
* - 'fields': An associative array ('fieldname' => specification)
* that describes the table's database columns. The specification
* is also an array. The following specification parameters are defined:
* - 'description': A string in non-markup plain text describing this field
* and its purpose. References to other tables should be enclosed in
* curly-brackets. For example, the node table vid field
* description might contain "Always holds the largest (most
* recent) {node_revision}.vid value for this nid."
* - 'type': The generic datatype: 'char', 'varchar', 'text', 'blob', 'int',
* 'float', 'numeric', or 'serial'. Most types just map to the according
* database engine specific datatypes. Use 'serial' for auto incrementing
* fields. This will expand to 'INT auto_increment' on MySQL.
* - 'mysql_type', 'pgsql_type', 'sqlite_type', etc.: If you need to
* use a record type not included in the officially supported list
* of types above, you can specify a type for each database
* backend. In this case, you can leave out the type parameter,
* but be advised that your schema will fail to load on backends that
* do not have a type specified. A possible solution can be to
* use the "text" type as a fallback.
* - 'serialize': A boolean indicating whether the field will be stored as
* a serialized string.
* - 'size': The data size: 'tiny', 'small', 'medium', 'normal',
* 'big'. This is a hint about the largest value the field will
* store and determines which of the database engine specific
* datatypes will be used (e.g. on MySQL, TINYINT vs. INT vs. BIGINT).
* 'normal', the default, selects the base type (e.g. on MySQL,
* INT, VARCHAR, BLOB, etc.).
* Not all sizes are available for all data types. See
* DatabaseSchema::getFieldTypeMap() for possible combinations.
* - 'not null': If true, no NULL values will be allowed in this
* database column. Defaults to false.
* - 'default': The field's default value. The PHP type of the
* value matters: '', '0', and 0 are all different. If you
* specify '0' as the default value for a type 'int' field it
* will not work because '0' is a string containing the
* character "zero", not an integer.
* - 'length': The maximal length of a type 'char', 'varchar' or 'text'
* field. Ignored for other field types.
* - 'unsigned': A boolean indicating whether a type 'int', 'float'
* and 'numeric' only is signed or unsigned. Defaults to
* FALSE. Ignored for other field types.
* - 'precision', 'scale': For type 'numeric' fields, indicates
* the precision (total number of significant digits) and scale
* (decimal digits right of the decimal point). Both values are
* mandatory. Ignored for other field types.
* - 'binary': A boolean indicating that MySQL should force 'char',
* 'varchar' or 'text' fields to use case-sensitive binary collation.
* This has no effect on other database types for which case sensitivity
* is already the default behavior.
* All parameters apart from 'type' are optional except that type
* 'numeric' columns must specify 'precision' and 'scale', and type
* 'varchar' must specify the 'length' parameter.
* - 'primary key': An array of one or more key column specifiers (see below)
* that form the primary key.
* - 'unique keys': An associative array of unique keys ('keyname' =>
* specification). Each specification is an array of one or more
* key column specifiers (see below) that form a unique key on the table.
* - 'foreign keys': An associative array of relations ('my_relation' =>
* specification). Each specification is an array containing the name of
* the referenced table ('table'), and an array of column mappings
* ('columns'). Column mappings are defined by key pairs ('source_column' =>
* 'referenced_column'). This key is for documentation purposes only; foreign
* keys are not created in the database, nor are they enforced by Drupal.
* - 'indexes': An associative array of indexes ('indexname' =>
* specification). Each specification is an array of one or more
* key column specifiers (see below) that form an index on the
* table.
*
* A key column specifier is either a string naming a column or an
* array of two elements, column name and length, specifying a prefix
* of the named column.
*
* As an example, here is a SUBSET of the schema definition for
* Drupal's 'node' table. It show four fields (nid, vid, type, and
* title), the primary key on field 'nid', a unique key named 'vid' on
* field 'vid', and two indexes, one named 'nid' on field 'nid' and
* one named 'node_title_type' on the field 'title' and the first four
* bytes of the field 'type':
*
* @code
* $schema['node'] = array(
* 'description' => 'The base table for nodes.',
* 'fields' => array(
* 'nid' => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
* 'vid' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE,'default' => 0),
* 'type' => array('type' => 'varchar','length' => 32,'not null' => TRUE, 'default' => ''),
* 'language' => array('type' => 'varchar','length' => 12,'not null' => TRUE,'default' => ''),
* 'title' => array('type' => 'varchar','length' => 255,'not null' => TRUE, 'default' => ''),
* 'uid' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
* 'status' => array('type' => 'int', 'not null' => TRUE, 'default' => 1),
* 'created' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
* 'changed' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
* 'comment' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
* 'promote' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
* 'moderate' => array('type' => 'int', 'not null' => TRUE,'default' => 0),
* 'sticky' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
* 'tnid' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0),
* 'translate' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
* ),
* 'indexes' => array(
* 'node_changed' => array('changed'),
* 'node_created' => array('created'),
* 'node_moderate' => array('moderate'),
* 'node_frontpage' => array('promote', 'status', 'sticky', 'created'),
* 'node_status_type' => array('status', 'type', 'nid'),
* 'node_title_type' => array('title', array('type', 4)),
* 'node_type' => array(array('type', 4)),
* 'uid' => array('uid'),
* 'tnid' => array('tnid'),
* 'translate' => array('translate'),
* ),
* 'unique keys' => array(
* 'vid' => array('vid'),
* ),
* // For documentation purposes only; foreign keys are not created in the
* // database.
* 'foreign keys' => array(
* 'node_revision' => array(
* 'table' => 'node_revision',
* 'columns' => array('vid' => 'vid'),
* ),
* 'node_author' => array(
* 'table' => 'users',
* 'columns' => array('uid' => 'uid'),
* ),
* ),
* 'primary key' => array('nid'),
* );
* @endcode
*
* @see drupal_install_schema()
*/
/**
* Base class for database schema definitions.
*/
abstract class DatabaseSchema implements QueryPlaceholderInterface {
protected $connection;
/**
* The placeholder counter.
*/
protected $placeholder = 0;
/**
* Definition of prefixInfo array structure.
*
* Rather than redefining DatabaseSchema::getPrefixInfo() for each driver,
* by defining the defaultSchema variable only MySQL has to re-write the
* method.
*
* @see DatabaseSchema::getPrefixInfo()
*/
protected $defaultSchema = 'public';
/**
* A unique identifier for this query object.
*/
protected $uniqueIdentifier;
public function __construct($connection) {
$this->uniqueIdentifier = uniqid('', TRUE);
$this->connection = $connection;
}
/**
* Implements the magic __clone function.
*/
public function __clone() {
$this->uniqueIdentifier = uniqid('', TRUE);
}
/**
* Implements QueryPlaceHolderInterface::uniqueIdentifier().
*/
public function uniqueIdentifier() {
return $this->uniqueIdentifier;
}
/**
* Implements QueryPlaceHolderInterface::nextPlaceholder().
*/
public function nextPlaceholder() {
return $this->placeholder++;
}
/**
* Get information about the table name and schema from the prefix.
*
* @param
* Name of table to look prefix up for. Defaults to 'default' because thats
* default key for prefix.
* @param $add_prefix
* Boolean that indicates whether the given table name should be prefixed.
*
* @return
* A keyed array with information about the schema, table name and prefix.
*/
protected function getPrefixInfo($table = 'default', $add_prefix = TRUE) {
$info = array(
'schema' => $this->defaultSchema,
'prefix' => $this->connection->tablePrefix($table),
);
if ($add_prefix) {
$table = $info['prefix'] . $table;
}
// If the prefix contains a period in it, then that means the prefix also
// contains a schema reference in which case we will change the schema key
// to the value before the period in the prefix. Everything after the dot
// will be prefixed onto the front of the table.
if (($pos = strpos($table, '.')) !== FALSE) {
// Grab everything before the period.
$info['schema'] = substr($table, 0, $pos);
// Grab everything after the dot.
$info['table'] = substr($table, ++$pos);
}
else {
$info['table'] = $table;
}
return $info;
}
/**
* Create names for indexes, primary keys and constraints.
*
* This prevents using {} around non-table names like indexes and keys.
*/
function prefixNonTable($table) {
$args = func_get_args();
$info = $this->getPrefixInfo($table);
$args[0] = $info['table'];
return implode('_', $args);
}
/**
* Build a condition to match a table name against a standard information_schema.
*
* The information_schema is a SQL standard that provides information about the
* database server and the databases, schemas, tables, columns and users within
* it. This makes information_schema a useful tool to use across the drupal
* database drivers and is used by a few different functions. The function below
* describes the conditions to be meet when querying information_schema.tables
* for drupal tables or information associated with drupal tables. Even though
* this is the standard method, not all databases follow standards and so this
* method should be overwritten by a database driver if the database provider
* uses alternate methods. Because information_schema.tables is used in a few
* different functions, a database driver will only need to override this function
* to make all the others work. For example see includes/databases/mysql/schema.inc.
*
* @param $table_name
* The name of the table in question.
* @param $operator
* The operator to apply on the 'table' part of the condition.
* @param $add_prefix
* Boolean to indicate whether the table name needs to be prefixed.
*
* @return QueryConditionInterface
* A DatabaseCondition object.
*/
protected function buildTableNameCondition($table_name, $operator = '=', $add_prefix = TRUE) {
$info = $this->connection->getConnectionOptions();
// Retrieve the table name and schema
$table_info = $this->getPrefixInfo($table_name, $add_prefix);
$condition = new DatabaseCondition('AND');
$condition->condition('table_catalog', $info['database']);
$condition->condition('table_schema', $table_info['schema']);
$condition->condition('table_name', $table_info['table'], $operator);
return $condition;
}
/**
* Check if a table exists.
*
* @param $table
* The name of the table in drupal (no prefixing).
*
* @return
* TRUE if the given table exists, otherwise FALSE.
*/
public function tableExists($table) {
$condition = $this->buildTableNameCondition($table);
$condition->compile($this->connection, $this);
// Normally, we would heartily discourage the use of string
// concatenation for conditionals like this however, we
// couldn't use db_select() here because it would prefix
// information_schema.tables and the query would fail.
// Don't use {} around information_schema.tables table.
return (bool) $this->connection->query("SELECT 1 FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments())->fetchField();
}
/**
* Find all tables that are like the specified base table name.
*
* @param $table_expression
* An SQL expression, for example "simpletest%" (without the quotes).
* BEWARE: this is not prefixed, the caller should take care of that.
*
* @return
* Array, both the keys and the values are the matching tables.
*/
public function findTables($table_expression) {
$condition = $this->buildTableNameCondition($table_expression, 'LIKE', FALSE);
$condition->compile($this->connection, $this);
// Normally, we would heartily discourage the use of string
// concatenation for conditionals like this however, we
// couldn't use db_select() here because it would prefix
// information_schema.tables and the query would fail.
// Don't use {} around information_schema.tables table.
return $this->connection->query("SELECT table_name FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments())->fetchAllKeyed(0, 0);
}
/**
* Check if a column exists in the given table.
*
* @param $table
* The name of the table in drupal (no prefixing).
* @param $name
* The name of the column.
*
* @return
* TRUE if the given column exists, otherwise FALSE.
*/
public function fieldExists($table, $column) {
$condition = $this->buildTableNameCondition($table);
$condition->condition('column_name', $column);
$condition->compile($this->connection, $this);
// Normally, we would heartily discourage the use of string
// concatenation for conditionals like this however, we
// couldn't use db_select() here because it would prefix
// information_schema.tables and the query would fail.
// Don't use {} around information_schema.columns table.
return (bool) $this->connection->query("SELECT 1 FROM information_schema.columns WHERE " . (string) $condition, $condition->arguments())->fetchField();
}
/**
* Returns a mapping of Drupal schema field names to DB-native field types.
*
* Because different field types do not map 1:1 between databases, Drupal has
* its own normalized field type names. This function returns a driver-specific
* mapping table from Drupal names to the native names for each database.
*
* @return array
* An array of Schema API field types to driver-specific field types.
*/
abstract public function getFieldTypeMap();
/**
* Rename a table.
*
* @param $table
* The table to be renamed.
* @param $new_name
* The new name for the table.
*
* @throws DatabaseSchemaObjectDoesNotExistException
* If the specified table doesn't exist.
* @throws DatabaseSchemaObjectExistsException
* If a table with the specified new name already exists.
*/
abstract public function renameTable($table, $new_name);
/**
* Drop a table.
*
* @param $table
* The table to be dropped.
*
* @return
* TRUE if the table was successfully dropped, FALSE if there was no table
* by that name to begin with.
*/
abstract public function dropTable($table);
/**
* Add a new field to a table.
*
* @param $table
* Name of the table to be altered.
* @param $field
* Name of the field to be added.
* @param $spec
* The field specification array, as taken from a schema definition.
* The specification may also contain the key 'initial', the newly
* created field will be set to the value of the key in all rows.
* This is most useful for creating NOT NULL columns with no default
* value in existing tables.
* @param $keys_new
* (optional) Keys and indexes specification to be created on the
* table along with adding the field. The format is the same as a
* table specification but without the 'fields' element. If you are
* adding a type 'serial' field, you MUST specify at least one key
* or index including it in this array. See db_change_field() for more
* explanation why.
*
* @throws DatabaseSchemaObjectDoesNotExistException
* If the specified table doesn't exist.
* @throws DatabaseSchemaObjectExistsException
* If the specified table already has a field by that name.
*/
abstract public function addField($table, $field, $spec, $keys_new = array());
/**
* Drop a field.
*
* @param $table
* The table to be altered.
* @param $field
* The field to be dropped.
*
* @return
* TRUE if the field was successfully dropped, FALSE if there was no field
* by that name to begin with.
*/
abstract public function dropField($table, $field);
/**
* Set the default value for a field.
*
* @param $table
* The table to be altered.
* @param $field
* The field to be altered.
* @param $default
* Default value to be set. NULL for 'default NULL'.
*
* @throws DatabaseSchemaObjectDoesNotExistException
* If the specified table or field doesn't exist.
*/
abstract public function fieldSetDefault($table, $field, $default);
/**
* Set a field to have no default value.
*
* @param $table
* The table to be altered.
* @param $field
* The field to be altered.
*
* @throws DatabaseSchemaObjectDoesNotExistException
* If the specified table or field doesn't exist.
*/
abstract public function fieldSetNoDefault($table, $field);
/**
* Checks if an index exists in the given table.
*
* @param $table
* The name of the table in drupal (no prefixing).
* @param $name
* The name of the index in drupal (no prefixing).
*
* @return
* TRUE if the given index exists, otherwise FALSE.
*/
abstract public function indexExists($table, $name);
/**
* Add a primary key.
*
* @param $table
* The table to be altered.
* @param $fields
* Fields for the primary key.
*
* @throws DatabaseSchemaObjectDoesNotExistException
* If the specified table doesn't exist.
* @throws DatabaseSchemaObjectExistsException
* If the specified table already has a primary key.
*/
abstract public function addPrimaryKey($table, $fields);
/**
* Drop the primary key.
*
* @param $table
* The table to be altered.
*
* @return
* TRUE if the primary key was successfully dropped, FALSE if there was no
* primary key on this table to begin with.
*/
abstract public function dropPrimaryKey($table);
/**
* Add a unique key.
*
* @param $table
* The table to be altered.
* @param $name
* The name of the key.
* @param $fields
* An array of field names.
*
* @throws DatabaseSchemaObjectDoesNotExistException
* If the specified table doesn't exist.
* @throws DatabaseSchemaObjectExistsException
* If the specified table already has a key by that name.
*/
abstract public function addUniqueKey($table, $name, $fields);
/**
* Drop a unique key.
*
* @param $table
* The table to be altered.
* @param $name
* The name of the key.
*
* @return
* TRUE if the key was successfully dropped, FALSE if there was no key by
* that name to begin with.
*/
abstract public function dropUniqueKey($table, $name);
/**
* Add an index.
*
* @param $table
* The table to be altered.
* @param $name
* The name of the index.
* @param $fields
* An array of field names.
*
* @throws DatabaseSchemaObjectDoesNotExistException
* If the specified table doesn't exist.
* @throws DatabaseSchemaObjectExistsException
* If the specified table already has an index by that name.
*/
abstract public function addIndex($table, $name, $fields);
/**
* Drop an index.
*
* @param $table
* The table to be altered.
* @param $name
* The name of the index.
*
* @return
* TRUE if the index was successfully dropped, FALSE if there was no index
* by that name to begin with.
*/
abstract public function dropIndex($table, $name);
/**
* Change a field definition.
*
* IMPORTANT NOTE: To maintain database portability, you have to explicitly
* recreate all indices and primary keys that are using the changed field.
*
* That means that you have to drop all affected keys and indexes with
* db_drop_{primary_key,unique_key,index}() before calling db_change_field().
* To recreate the keys and indices, pass the key definitions as the
* optional $keys_new argument directly to db_change_field().
*
* For example, suppose you have:
* @code
* $schema['foo'] = array(
* 'fields' => array(
* 'bar' => array('type' => 'int', 'not null' => TRUE)
* ),
* 'primary key' => array('bar')
* );
* @endcode
* and you want to change foo.bar to be type serial, leaving it as the
* primary key. The correct sequence is:
* @code
* db_drop_primary_key('foo');
* db_change_field('foo', 'bar', 'bar',
* array('type' => 'serial', 'not null' => TRUE),
* array('primary key' => array('bar')));
* @endcode
*
* The reasons for this are due to the different database engines:
*
* On PostgreSQL, changing a field definition involves adding a new field
* and dropping an old one which* causes any indices, primary keys and
* sequences (from serial-type fields) that use the changed field to be dropped.
*
* On MySQL, all type 'serial' fields must be part of at least one key
* or index as soon as they are created. You cannot use
* db_add_{primary_key,unique_key,index}() for this purpose because
* the ALTER TABLE command will fail to add the column without a key
* or index specification. The solution is to use the optional
* $keys_new argument to create the key or index at the same time as
* field.
*
* You could use db_add_{primary_key,unique_key,index}() in all cases
* unless you are converting a field to be type serial. You can use
* the $keys_new argument in all cases.
*
* @param $table
* Name of the table.
* @param $field
* Name of the field to change.
* @param $field_new
* New name for the field (set to the same as $field if you don't want to change the name).
* @param $spec
* The field specification for the new field.
* @param $keys_new
* (optional) Keys and indexes specification to be created on the
* table along with changing the field. The format is the same as a
* table specification but without the 'fields' element.
*
* @throws DatabaseSchemaObjectDoesNotExistException
* If the specified table or source field doesn't exist.
* @throws DatabaseSchemaObjectExistsException
* If the specified destination field already exists.
*/
abstract public function changeField($table, $field, $field_new, $spec, $keys_new = array());
/**
* Create a new table from a Drupal table definition.
*
* @param $name
* The name of the table to create.
* @param $table
* A Schema API table definition array.
*
* @throws DatabaseSchemaObjectExistsException
* If the specified table already exists.
*/
public function createTable($name, $table) {
if ($this->tableExists($name)) {
throw new DatabaseSchemaObjectExistsException(t('Table @name already exists.', array('@name' => $name)));
}
$statements = $this->createTableSql($name, $table);
foreach ($statements as $statement) {
$this->connection->query($statement);
}
}
/**
* Return an array of field names from an array of key/index column specifiers.
*
* This is usually an identity function but if a key/index uses a column prefix
* specification, this function extracts just the name.
*
* @param $fields
* An array of key/index column specifiers.
*
* @return
* An array of field names.
*/
public function fieldNames($fields) {
$return = array();
foreach ($fields as $field) {
if (is_array($field)) {
$return[] = $field[0];
}
else {
$return[] = $field;
}
}
return $return;
}
/**
* Prepare a table or column comment for database query.
*
* @param $comment
* The comment string to prepare.
* @param $length
* Optional upper limit on the returned string length.
*
* @return
* The prepared comment.
*/
public function prepareComment($comment, $length = NULL) {
return $this->connection->quote($comment);
}
}
/**
* Exception thrown if an object being created already exists.
*
* For example, this exception should be thrown whenever there is an attempt to
* create a new database table, field, or index that already exists in the
* database schema.
*/
class DatabaseSchemaObjectExistsException extends Exception {}
/**
* Exception thrown if an object being modified doesn't exist yet.
*
* For example, this exception should be thrown whenever there is an attempt to
* modify a database table, field, or index that does not currently exist in
* the database schema.
*/
class DatabaseSchemaObjectDoesNotExistException extends Exception {}
/**
* @} End of "defgroup schemaapi".
*/

1631
includes/database/select.inc Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,527 @@
<?php
/**
* @file
* Database interface code for SQLite embedded database engine.
*/
/**
* @addtogroup database
* @{
*/
include_once DRUPAL_ROOT . '/includes/database/prefetch.inc';
/**
* Specific SQLite implementation of DatabaseConnection.
*/
class DatabaseConnection_sqlite extends DatabaseConnection {
/**
* Whether this database connection supports savepoints.
*
* Version of sqlite lower then 3.6.8 can't use savepoints.
* See http://www.sqlite.org/releaselog/3_6_8.html
*
* @var boolean
*/
protected $savepointSupport = FALSE;
/**
* Whether or not the active transaction (if any) will be rolled back.
*
* @var boolean
*/
protected $willRollback;
/**
* All databases attached to the current database. This is used to allow
* prefixes to be safely handled without locking the table
*
* @var array
*/
protected $attachedDatabases = array();
/**
* Whether or not a table has been dropped this request: the destructor will
* only try to get rid of unnecessary databases if there is potential of them
* being empty.
*
* This variable is set to public because DatabaseSchema_sqlite needs to
* access it. However, it should not be manually set.
*
* @var boolean
*/
var $tableDropped = FALSE;
public function __construct(array $connection_options = array()) {
// We don't need a specific PDOStatement class here, we simulate it below.
$this->statementClass = NULL;
// This driver defaults to transaction support, except if explicitly passed FALSE.
$this->transactionSupport = $this->transactionalDDLSupport = !isset($connection_options['transactions']) || $connection_options['transactions'] !== FALSE;
$this->connectionOptions = $connection_options;
// Allow PDO options to be overridden.
$connection_options += array(
'pdo' => array(),
);
$connection_options['pdo'] += array(
// Convert numeric values to strings when fetching.
PDO::ATTR_STRINGIFY_FETCHES => TRUE,
);
parent::__construct('sqlite:' . $connection_options['database'], '', '', $connection_options['pdo']);
// Attach one database for each registered prefix.
$prefixes = $this->prefixes;
foreach ($prefixes as $table => &$prefix) {
// Empty prefix means query the main database -- no need to attach anything.
if (!empty($prefix)) {
// Only attach the database once.
if (!isset($this->attachedDatabases[$prefix])) {
$this->attachedDatabases[$prefix] = $prefix;
$this->query('ATTACH DATABASE :database AS :prefix', array(':database' => $connection_options['database'] . '-' . $prefix, ':prefix' => $prefix));
}
// Add a ., so queries become prefix.table, which is proper syntax for
// querying an attached database.
$prefix .= '.';
}
}
// Regenerate the prefixes replacement table.
$this->setPrefix($prefixes);
// Detect support for SAVEPOINT.
$version = $this->query('SELECT sqlite_version()')->fetchField();
$this->savepointSupport = (version_compare($version, '3.6.8') >= 0);
// Create functions needed by SQLite.
$this->sqliteCreateFunction('if', array($this, 'sqlFunctionIf'));
$this->sqliteCreateFunction('greatest', array($this, 'sqlFunctionGreatest'));
$this->sqliteCreateFunction('pow', 'pow', 2);
$this->sqliteCreateFunction('length', 'strlen', 1);
$this->sqliteCreateFunction('md5', 'md5', 1);
$this->sqliteCreateFunction('concat', array($this, 'sqlFunctionConcat'));
$this->sqliteCreateFunction('substring', array($this, 'sqlFunctionSubstring'), 3);
$this->sqliteCreateFunction('substring_index', array($this, 'sqlFunctionSubstringIndex'), 3);
$this->sqliteCreateFunction('rand', array($this, 'sqlFunctionRand'));
// Execute sqlite init_commands.
if (isset($connection_options['init_commands'])) {
$this->exec(implode('; ', $connection_options['init_commands']));
}
}
/**
* Destructor for the SQLite connection.
*
* We prune empty databases on destruct, but only if tables have been
* dropped. This is especially needed when running the test suite, which
* creates and destroy databases several times in a row.
*/
public function __destruct() {
if ($this->tableDropped && !empty($this->attachedDatabases)) {
foreach ($this->attachedDatabases as $prefix) {
// Check if the database is now empty, ignore the internal SQLite tables.
try {
$count = $this->query('SELECT COUNT(*) FROM ' . $prefix . '.sqlite_master WHERE type = :type AND name NOT LIKE :pattern', array(':type' => 'table', ':pattern' => 'sqlite_%'))->fetchField();
// We can prune the database file if it doesn't have any tables.
if ($count == 0) {
// Detach the database.
$this->query('DETACH DATABASE :schema', array(':schema' => $prefix));
// Destroy the database file.
unlink($this->connectionOptions['database'] . '-' . $prefix);
}
}
catch (Exception $e) {
// Ignore the exception and continue. There is nothing we can do here
// to report the error or fail safe.
}
}
}
}
/**
* SQLite compatibility implementation for the IF() SQL function.
*/
public function sqlFunctionIf($condition, $expr1, $expr2 = NULL) {
return $condition ? $expr1 : $expr2;
}
/**
* SQLite compatibility implementation for the GREATEST() SQL function.
*/
public function sqlFunctionGreatest() {
$args = func_get_args();
foreach ($args as $k => $v) {
if (!isset($v)) {
unset($args);
}
}
if (count($args)) {
return max($args);
}
else {
return NULL;
}
}
/**
* SQLite compatibility implementation for the CONCAT() SQL function.
*/
public function sqlFunctionConcat() {
$args = func_get_args();
return implode('', $args);
}
/**
* SQLite compatibility implementation for the SUBSTRING() SQL function.
*/
public function sqlFunctionSubstring($string, $from, $length) {
return substr($string, $from - 1, $length);
}
/**
* SQLite compatibility implementation for the SUBSTRING_INDEX() SQL function.
*/
public function sqlFunctionSubstringIndex($string, $delimiter, $count) {
// If string is empty, simply return an empty string.
if (empty($string)) {
return '';
}
$end = 0;
for ($i = 0; $i < $count; $i++) {
$end = strpos($string, $delimiter, $end + 1);
if ($end === FALSE) {
$end = strlen($string);
}
}
return substr($string, 0, $end);
}
/**
* SQLite compatibility implementation for the RAND() SQL function.
*/
public function sqlFunctionRand($seed = NULL) {
if (isset($seed)) {
mt_srand($seed);
}
return mt_rand() / mt_getrandmax();
}
/**
* SQLite-specific implementation of DatabaseConnection::prepare().
*
* We don't use prepared statements at all at this stage. We just create
* a DatabaseStatement_sqlite object, that will create a PDOStatement
* using the semi-private PDOPrepare() method below.
*/
public function prepare($query, $options = array()) {
return new DatabaseStatement_sqlite($this, $query, $options);
}
/**
* NEVER CALL THIS FUNCTION: YOU MIGHT DEADLOCK YOUR PHP PROCESS.
*
* This is a wrapper around the parent PDO::prepare method. However, as
* the PDO SQLite driver only closes SELECT statements when the PDOStatement
* destructor is called and SQLite does not allow data change (INSERT,
* UPDATE etc) on a table which has open SELECT statements, you should never
* call this function and keep a PDOStatement object alive as that can lead
* to a deadlock. This really, really should be private, but as
* DatabaseStatement_sqlite needs to call it, we have no other choice but to
* expose this function to the world.
*/
public function PDOPrepare($query, array $options = array()) {
return parent::prepare($query, $options);
}
public function queryRange($query, $from, $count, array $args = array(), array $options = array()) {
return $this->query($query . ' LIMIT ' . (int) $from . ', ' . (int) $count, $args, $options);
}
public function queryTemporary($query, array $args = array(), array $options = array()) {
// Generate a new temporary table name and protect it from prefixing.
// SQLite requires that temporary tables to be non-qualified.
$tablename = $this->generateTemporaryTableName();
$prefixes = $this->prefixes;
$prefixes[$tablename] = '';
$this->setPrefix($prefixes);
$this->query('CREATE TEMPORARY TABLE ' . $tablename . ' AS ' . $query, $args, $options);
return $tablename;
}
public function driver() {
return 'sqlite';
}
public function databaseType() {
return 'sqlite';
}
public function mapConditionOperator($operator) {
// We don't want to override any of the defaults.
static $specials = array(
'LIKE' => array('postfix' => " ESCAPE '\\'"),
'NOT LIKE' => array('postfix' => " ESCAPE '\\'"),
);
return isset($specials[$operator]) ? $specials[$operator] : NULL;
}
public function prepareQuery($query) {
return $this->prepare($this->prefixTables($query));
}
public function nextId($existing_id = 0) {
$transaction = $this->startTransaction();
// We can safely use literal queries here instead of the slower query
// builder because if a given database breaks here then it can simply
// override nextId. However, this is unlikely as we deal with short strings
// and integers and no known databases require special handling for those
// simple cases. If another transaction wants to write the same row, it will
// wait until this transaction commits.
$stmt = $this->query('UPDATE {sequences} SET value = GREATEST(value, :existing_id) + 1', array(
':existing_id' => $existing_id,
));
if (!$stmt->rowCount()) {
$this->query('INSERT INTO {sequences} (value) VALUES (:existing_id + 1)', array(
':existing_id' => $existing_id,
));
}
// The transaction gets committed when the transaction object gets destroyed
// because it gets out of scope.
return $this->query('SELECT value FROM {sequences}')->fetchField();
}
public function rollback($savepoint_name = 'drupal_transaction') {
if ($this->savepointSupport) {
return parent::rollBack($savepoint_name);
}
if (!$this->inTransaction()) {
throw new DatabaseTransactionNoActiveException();
}
// A previous rollback to an earlier savepoint may mean that the savepoint
// in question has already been rolled back.
if (!in_array($savepoint_name, $this->transactionLayers)) {
return;
}
// We need to find the point we're rolling back to, all other savepoints
// before are no longer needed.
while ($savepoint = array_pop($this->transactionLayers)) {
if ($savepoint == $savepoint_name) {
// Mark whole stack of transactions as needed roll back.
$this->willRollback = TRUE;
// If it is the last the transaction in the stack, then it is not a
// savepoint, it is the transaction itself so we will need to roll back
// the transaction rather than a savepoint.
if (empty($this->transactionLayers)) {
break;
}
return;
}
}
if ($this->supportsTransactions()) {
PDO::rollBack();
}
}
public function pushTransaction($name) {
if ($this->savepointSupport) {
return parent::pushTransaction($name);
}
if (!$this->supportsTransactions()) {
return;
}
if (isset($this->transactionLayers[$name])) {
throw new DatabaseTransactionNameNonUniqueException($name . " is already in use.");
}
if (!$this->inTransaction()) {
PDO::beginTransaction();
}
$this->transactionLayers[$name] = $name;
}
public function popTransaction($name) {
if ($this->savepointSupport) {
return parent::popTransaction($name);
}
if (!$this->supportsTransactions()) {
return;
}
if (!$this->inTransaction()) {
throw new DatabaseTransactionNoActiveException();
}
// Commit everything since SAVEPOINT $name.
while($savepoint = array_pop($this->transactionLayers)) {
if ($savepoint != $name) continue;
// If there are no more layers left then we should commit or rollback.
if (empty($this->transactionLayers)) {
// If there was any rollback() we should roll back whole transaction.
if ($this->willRollback) {
$this->willRollback = FALSE;
PDO::rollBack();
}
elseif (!PDO::commit()) {
throw new DatabaseTransactionCommitFailedException();
}
}
else {
break;
}
}
}
public function utf8mb4IsActive() {
return TRUE;
}
public function utf8mb4IsSupported() {
return TRUE;
}
}
/**
* Specific SQLite implementation of DatabaseConnection.
*
* See DatabaseConnection_sqlite::PDOPrepare() for reasons why we must prefetch
* the data instead of using PDOStatement.
*
* @see DatabaseConnection_sqlite::PDOPrepare()
*/
class DatabaseStatement_sqlite extends DatabaseStatementPrefetch implements Iterator, DatabaseStatementInterface {
/**
* SQLite specific implementation of getStatement().
*
* The PDO SQLite layer doesn't replace numeric placeholders in queries
* correctly, and this makes numeric expressions (such as COUNT(*) >= :count)
* fail. We replace numeric placeholders in the query ourselves to work
* around this bug.
*
* See http://bugs.php.net/bug.php?id=45259 for more details.
*/
protected function getStatement($query, &$args = array()) {
if (count($args)) {
// Check if $args is a simple numeric array.
if (range(0, count($args) - 1) === array_keys($args)) {
// In that case, we have unnamed placeholders.
$count = 0;
$new_args = array();
foreach ($args as $value) {
if (is_float($value) || is_int($value)) {
if (is_float($value)) {
// Force the conversion to float so as not to loose precision
// in the automatic cast.
$value = sprintf('%F', $value);
}
$query = substr_replace($query, $value, strpos($query, '?'), 1);
}
else {
$placeholder = ':db_statement_placeholder_' . $count++;
$query = substr_replace($query, $placeholder, strpos($query, '?'), 1);
$new_args[$placeholder] = $value;
}
}
$args = $new_args;
}
else {
// Else, this is using named placeholders.
foreach ($args as $placeholder => $value) {
if (is_float($value) || is_int($value)) {
if (is_float($value)) {
// Force the conversion to float so as not to loose precision
// in the automatic cast.
$value = sprintf('%F', $value);
}
// We will remove this placeholder from the query as PDO throws an
// exception if the number of placeholders in the query and the
// arguments does not match.
unset($args[$placeholder]);
// PDO allows placeholders to not be prefixed by a colon. See
// http://marc.info/?l=php-internals&m=111234321827149&w=2 for
// more.
if ($placeholder[0] != ':') {
$placeholder = ":$placeholder";
}
// When replacing the placeholders, make sure we search for the
// exact placeholder. For example, if searching for
// ':db_placeholder_1', do not replace ':db_placeholder_11'.
$query = preg_replace('/' . preg_quote($placeholder) . '\b/', $value, $query);
}
}
}
}
return $this->dbh->PDOPrepare($query);
}
public function execute($args = array(), $options = array()) {
try {
$return = parent::execute($args, $options);
}
catch (PDOException $e) {
if (!empty($e->errorInfo[1]) && $e->errorInfo[1] === 17) {
// The schema has changed. SQLite specifies that we must resend the query.
$return = parent::execute($args, $options);
}
else {
// Rethrow the exception.
throw $e;
}
}
// In some weird cases, SQLite will prefix some column names by the name
// of the table. We post-process the data, by renaming the column names
// using the same convention as MySQL and PostgreSQL.
$rename_columns = array();
foreach ($this->columnNames as $k => $column) {
// In some SQLite versions, SELECT DISTINCT(field) will return "(field)"
// instead of "field".
if (preg_match("/^\((.*)\)$/", $column, $matches)) {
$rename_columns[$column] = $matches[1];
$this->columnNames[$k] = $matches[1];
$column = $matches[1];
}
// Remove "table." prefixes.
if (preg_match("/^.*\.(.*)$/", $column, $matches)) {
$rename_columns[$column] = $matches[1];
$this->columnNames[$k] = $matches[1];
}
}
if ($rename_columns) {
// DatabaseStatementPrefetch already extracted the first row,
// put it back into the result set.
if (isset($this->currentRow)) {
$this->data[0] = &$this->currentRow;
}
// Then rename all the columns across the result set.
foreach ($this->data as $k => $row) {
foreach ($rename_columns as $old_column => $new_column) {
$this->data[$k][$new_column] = $this->data[$k][$old_column];
unset($this->data[$k][$old_column]);
}
}
// Finally, extract the first row again.
$this->currentRow = $this->data[0];
unset($this->data[0]);
}
return $return;
}
}
/**
* @} End of "addtogroup database".
*/

View file

@ -0,0 +1,49 @@
<?php
/**
* @file
* SQLite specific install functions
*/
class DatabaseTasks_sqlite extends DatabaseTasks {
protected $pdoDriver = 'sqlite';
public function name() {
return st('SQLite');
}
/**
* Minimum engine version.
*/
public function minimumVersion() {
return '3.3.7';
}
public function getFormOptions($database) {
$form = parent::getFormOptions($database);
// Remove the options that only apply to client/server style databases.
unset($form['username'], $form['password'], $form['advanced_options']['host'], $form['advanced_options']['port']);
// Make the text more accurate for SQLite.
$form['database']['#title'] = st('Database file');
$form['database']['#description'] = st('The absolute path to the file where @drupal data will be stored. This must be writable by the web server and should exist outside of the web root.', array('@drupal' => drupal_install_profile_distribution_name()));
$default_database = conf_path(FALSE, TRUE) . '/files/.ht.sqlite';
$form['database']['#default_value'] = empty($database['database']) ? $default_database : $database['database'];
return $form;
}
public function validateDatabaseSettings($database) {
// Perform standard validation.
$errors = parent::validateDatabaseSettings($database);
// Verify the database is writable.
$db_directory = new SplFileInfo(dirname($database['database']));
if (!$db_directory->isWritable()) {
$errors[$database['driver'] . '][database'] = st('The directory you specified is not writable by the web server.');
}
return $errors;
}
}

View file

@ -0,0 +1,139 @@
<?php
/**
* @file
* Query code for SQLite embedded database engine.
*/
/**
* @addtogroup database
* @{
*/
/**
* SQLite specific implementation of InsertQuery.
*
* We ignore all the default fields and use the clever SQLite syntax:
* INSERT INTO table DEFAULT VALUES
* for degenerated "default only" queries.
*/
class InsertQuery_sqlite extends InsertQuery {
public function execute() {
if (!$this->preExecute()) {
return NULL;
}
if (count($this->insertFields)) {
return parent::execute();
}
else {
return $this->connection->query('INSERT INTO {' . $this->table . '} DEFAULT VALUES', array(), $this->queryOptions);
}
}
public function __toString() {
// Create a sanitized comment string to prepend to the query.
$comments = $this->connection->makeComment($this->comments);
// Produce as many generic placeholders as necessary.
$placeholders = array_fill(0, count($this->insertFields), '?');
// If we're selecting from a SelectQuery, finish building the query and
// pass it back, as any remaining options are irrelevant.
if (!empty($this->fromQuery)) {
$insert_fields_string = $this->insertFields ? ' (' . implode(', ', $this->insertFields) . ') ' : ' ';
return $comments . 'INSERT INTO {' . $this->table . '}' . $insert_fields_string . $this->fromQuery;
}
return $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $this->insertFields) . ') VALUES (' . implode(', ', $placeholders) . ')';
}
}
/**
* SQLite specific implementation of UpdateQuery.
*
* SQLite counts all the rows that match the conditions as modified, even if they
* will not be affected by the query. We workaround this by ensuring that
* we don't select those rows.
*
* A query like this one:
* UPDATE test SET col1 = 'newcol1', col2 = 'newcol2' WHERE tid = 1
* will become:
* UPDATE test SET col1 = 'newcol1', col2 = 'newcol2' WHERE tid = 1 AND (col1 <> 'newcol1' OR col2 <> 'newcol2')
*/
class UpdateQuery_sqlite extends UpdateQuery {
public function execute() {
if (!empty($this->queryOptions['sqlite_return_matched_rows'])) {
return parent::execute();
}
// Get the fields used in the update query.
$fields = $this->expressionFields + $this->fields;
// Add the inverse of the fields to the condition.
$condition = new DatabaseCondition('OR');
foreach ($fields as $field => $data) {
if (is_array($data)) {
// The field is an expression.
$condition->where($field . ' <> ' . $data['expression']);
$condition->isNull($field);
}
elseif (!isset($data)) {
// The field will be set to NULL.
$condition->isNotNull($field);
}
else {
$condition->condition($field, $data, '<>');
$condition->isNull($field);
}
}
if (count($condition)) {
$condition->compile($this->connection, $this);
$this->condition->where((string) $condition, $condition->arguments());
}
return parent::execute();
}
}
/**
* SQLite specific implementation of DeleteQuery.
*/
class DeleteQuery_sqlite extends DeleteQuery {
public function execute() {
// When the WHERE is omitted from a DELETE statement and the table being
// deleted has no triggers, SQLite uses an optimization to erase the entire
// table content without having to visit each row of the table individually.
// Prior to SQLite 3.6.5, SQLite does not return the actual number of rows
// deleted by that optimized "truncate" optimization. But we want to return
// the number of rows affected, so we calculate it directly.
if (!count($this->condition)) {
$total_rows = $this->connection->query('SELECT COUNT(*) FROM {' . $this->connection->escapeTable($this->table) . '}')->fetchField();
parent::execute();
return $total_rows;
}
else {
return parent::execute();
}
}
}
/**
* SQLite specific implementation of TruncateQuery.
*
* SQLite doesn't support TRUNCATE, but a DELETE query with no condition has
* exactly the effect (it is implemented by DROPing the table).
*/
class TruncateQuery_sqlite extends TruncateQuery {
public function __toString() {
// Create a sanitized comment string to prepend to the query.
$comments = $this->connection->makeComment($this->comments);
return $comments . 'DELETE FROM {' . $this->connection->escapeTable($this->table) . '} ';
}
}
/**
* @} End of "addtogroup database".
*/

View file

@ -0,0 +1,683 @@
<?php
/**
* @file
* Database schema code for SQLite databases.
*/
/**
* @ingroup schemaapi
* @{
*/
class DatabaseSchema_sqlite extends DatabaseSchema {
/**
* Override DatabaseSchema::$defaultSchema
*/
protected $defaultSchema = 'main';
public function tableExists($table) {
$info = $this->getPrefixInfo($table);
// Don't use {} around sqlite_master table.
return (bool) $this->connection->query('SELECT 1 FROM ' . $info['schema'] . '.sqlite_master WHERE type = :type AND name = :name', array(':type' => 'table', ':name' => $info['table']))->fetchField();
}
public function fieldExists($table, $column) {
$schema = $this->introspectSchema($table);
return !empty($schema['fields'][$column]);
}
/**
* Generate SQL to create a new table from a Drupal schema definition.
*
* @param $name
* The name of the table to create.
* @param $table
* A Schema API table definition array.
* @return
* An array of SQL statements to create the table.
*/
public function createTableSql($name, $table) {
$sql = array();
$sql[] = "CREATE TABLE {" . $name . "} (\n" . $this->createColumsSql($name, $table) . "\n);\n";
return array_merge($sql, $this->createIndexSql($name, $table));
}
/**
* Build the SQL expression for indexes.
*/
protected function createIndexSql($tablename, $schema) {
$sql = array();
$info = $this->getPrefixInfo($tablename);
if (!empty($schema['unique keys'])) {
foreach ($schema['unique keys'] as $key => $fields) {
$sql[] = 'CREATE UNIQUE INDEX ' . $info['schema'] . '.' . $info['table'] . '_' . $key . ' ON ' . $info['table'] . ' (' . $this->createKeySql($fields) . "); \n";
}
}
if (!empty($schema['indexes'])) {
foreach ($schema['indexes'] as $key => $fields) {
$sql[] = 'CREATE INDEX ' . $info['schema'] . '.' . $info['table'] . '_' . $key . ' ON ' . $info['table'] . ' (' . $this->createKeySql($fields) . "); \n";
}
}
return $sql;
}
/**
* Build the SQL expression for creating columns.
*/
protected function createColumsSql($tablename, $schema) {
$sql_array = array();
// Add the SQL statement for each field.
foreach ($schema['fields'] as $name => $field) {
if (isset($field['type']) && $field['type'] == 'serial') {
if (isset($schema['primary key']) && ($key = array_search($name, $schema['primary key'])) !== FALSE) {
unset($schema['primary key'][$key]);
}
}
$sql_array[] = $this->createFieldSql($name, $this->processField($field));
}
// Process keys.
if (!empty($schema['primary key'])) {
$sql_array[] = " PRIMARY KEY (" . $this->createKeySql($schema['primary key']) . ")";
}
return implode(", \n", $sql_array);
}
/**
* Build the SQL expression for keys.
*/
protected function createKeySql($fields) {
$return = array();
foreach ($fields as $field) {
if (is_array($field)) {
$return[] = $field[0];
}
else {
$return[] = $field;
}
}
return implode(', ', $return);
}
/**
* Set database-engine specific properties for a field.
*
* @param $field
* A field description array, as specified in the schema documentation.
*/
protected function processField($field) {
if (!isset($field['size'])) {
$field['size'] = 'normal';
}
// Set the correct database-engine specific datatype.
// In case one is already provided, force it to uppercase.
if (isset($field['sqlite_type'])) {
$field['sqlite_type'] = drupal_strtoupper($field['sqlite_type']);
}
else {
$map = $this->getFieldTypeMap();
$field['sqlite_type'] = $map[$field['type'] . ':' . $field['size']];
}
if (isset($field['type']) && $field['type'] == 'serial') {
$field['auto_increment'] = TRUE;
}
return $field;
}
/**
* Create an SQL string for a field to be used in table creation or alteration.
*
* Before passing a field out of a schema definition into this function it has
* to be processed by db_processField().
*
* @param $name
* Name of the field.
* @param $spec
* The field specification, as per the schema data structure format.
*/
protected function createFieldSql($name, $spec) {
if (!empty($spec['auto_increment'])) {
$sql = $name . " INTEGER PRIMARY KEY AUTOINCREMENT";
if (!empty($spec['unsigned'])) {
$sql .= ' CHECK (' . $name . '>= 0)';
}
}
else {
$sql = $name . ' ' . $spec['sqlite_type'];
if (in_array($spec['sqlite_type'], array('VARCHAR', 'TEXT')) && isset($spec['length'])) {
$sql .= '(' . $spec['length'] . ')';
}
if (isset($spec['not null'])) {
if ($spec['not null']) {
$sql .= ' NOT NULL';
}
else {
$sql .= ' NULL';
}
}
if (!empty($spec['unsigned'])) {
$sql .= ' CHECK (' . $name . '>= 0)';
}
if (isset($spec['default'])) {
if (is_string($spec['default'])) {
$spec['default'] = "'" . $spec['default'] . "'";
}
$sql .= ' DEFAULT ' . $spec['default'];
}
if (empty($spec['not null']) && !isset($spec['default'])) {
$sql .= ' DEFAULT NULL';
}
}
return $sql;
}
/**
* This maps a generic data type in combination with its data size
* to the engine-specific data type.
*/
public function getFieldTypeMap() {
// Put :normal last so it gets preserved by array_flip. This makes
// it much easier for modules (such as schema.module) to map
// database types back into schema types.
// $map does not use drupal_static as its value never changes.
static $map = array(
'varchar:normal' => 'VARCHAR',
'char:normal' => 'CHAR',
'text:tiny' => 'TEXT',
'text:small' => 'TEXT',
'text:medium' => 'TEXT',
'text:big' => 'TEXT',
'text:normal' => 'TEXT',
'serial:tiny' => 'INTEGER',
'serial:small' => 'INTEGER',
'serial:medium' => 'INTEGER',
'serial:big' => 'INTEGER',
'serial:normal' => 'INTEGER',
'int:tiny' => 'INTEGER',
'int:small' => 'INTEGER',
'int:medium' => 'INTEGER',
'int:big' => 'INTEGER',
'int:normal' => 'INTEGER',
'float:tiny' => 'FLOAT',
'float:small' => 'FLOAT',
'float:medium' => 'FLOAT',
'float:big' => 'FLOAT',
'float:normal' => 'FLOAT',
'numeric:normal' => 'NUMERIC',
'blob:big' => 'BLOB',
'blob:normal' => 'BLOB',
);
return $map;
}
public function renameTable($table, $new_name) {
if (!$this->tableExists($table)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot rename @table to @table_new: table @table doesn't exist.", array('@table' => $table, '@table_new' => $new_name)));
}
if ($this->tableExists($new_name)) {
throw new DatabaseSchemaObjectExistsException(t("Cannot rename @table to @table_new: table @table_new already exists.", array('@table' => $table, '@table_new' => $new_name)));
}
$schema = $this->introspectSchema($table);
// SQLite doesn't allow you to rename tables outside of the current
// database. So the syntax '...RENAME TO database.table' would fail.
// So we must determine the full table name here rather than surrounding
// the table with curly braces incase the db_prefix contains a reference
// to a database outside of our existing database.
$info = $this->getPrefixInfo($new_name);
$this->connection->query('ALTER TABLE {' . $table . '} RENAME TO ' . $info['table']);
// Drop the indexes, there is no RENAME INDEX command in SQLite.
if (!empty($schema['unique keys'])) {
foreach ($schema['unique keys'] as $key => $fields) {
$this->dropIndex($table, $key);
}
}
if (!empty($schema['indexes'])) {
foreach ($schema['indexes'] as $index => $fields) {
$this->dropIndex($table, $index);
}
}
// Recreate the indexes.
$statements = $this->createIndexSql($new_name, $schema);
foreach ($statements as $statement) {
$this->connection->query($statement);
}
}
public function dropTable($table) {
if (!$this->tableExists($table)) {
return FALSE;
}
$this->connection->tableDropped = TRUE;
$this->connection->query('DROP TABLE {' . $table . '}');
return TRUE;
}
public function addField($table, $field, $specification, $keys_new = array()) {
if (!$this->tableExists($table)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add field @table.@field: table doesn't exist.", array('@field' => $field, '@table' => $table)));
}
if ($this->fieldExists($table, $field)) {
throw new DatabaseSchemaObjectExistsException(t("Cannot add field @table.@field: field already exists.", array('@field' => $field, '@table' => $table)));
}
// SQLite doesn't have a full-featured ALTER TABLE statement. It only
// supports adding new fields to a table, in some simple cases. In most
// cases, we have to create a new table and copy the data over.
if (empty($keys_new) && (empty($specification['not null']) || isset($specification['default']))) {
// When we don't have to create new keys and we are not creating a
// NOT NULL column without a default value, we can use the quicker version.
$query = 'ALTER TABLE {' . $table . '} ADD ' . $this->createFieldSql($field, $this->processField($specification));
$this->connection->query($query);
// Apply the initial value if set.
if (isset($specification['initial'])) {
$this->connection->update($table)
->fields(array($field => $specification['initial']))
->execute();
}
}
else {
// We cannot add the field directly. Use the slower table alteration
// method, starting from the old schema.
$old_schema = $this->introspectSchema($table);
$new_schema = $old_schema;
// Add the new field.
$new_schema['fields'][$field] = $specification;
// Build the mapping between the old fields and the new fields.
$mapping = array();
if (isset($specification['initial'])) {
// If we have a initial value, copy it over.
$mapping[$field] = array(
'expression' => ':newfieldinitial',
'arguments' => array(':newfieldinitial' => $specification['initial']),
);
}
else {
// Else use the default of the field.
$mapping[$field] = NULL;
}
// Add the new indexes.
$new_schema += $keys_new;
$this->alterTable($table, $old_schema, $new_schema, $mapping);
}
}
/**
* Create a table with a new schema containing the old content.
*
* As SQLite does not support ALTER TABLE (with a few exceptions) it is
* necessary to create a new table and copy over the old content.
*
* @param $table
* Name of the table to be altered.
* @param $old_schema
* The old schema array for the table.
* @param $new_schema
* The new schema array for the table.
* @param $mapping
* An optional mapping between the fields of the old specification and the
* fields of the new specification. An associative array, whose keys are
* the fields of the new table, and values can take two possible forms:
* - a simple string, which is interpreted as the name of a field of the
* old table,
* - an associative array with two keys 'expression' and 'arguments',
* that will be used as an expression field.
*/
protected function alterTable($table, $old_schema, $new_schema, array $mapping = array()) {
$i = 0;
do {
$new_table = $table . '_' . $i++;
} while ($this->tableExists($new_table));
$this->createTable($new_table, $new_schema);
// Build a SQL query to migrate the data from the old table to the new.
$select = $this->connection->select($table);
// Complete the mapping.
$possible_keys = array_keys($new_schema['fields']);
$mapping += array_combine($possible_keys, $possible_keys);
// Now add the fields.
foreach ($mapping as $field_alias => $field_source) {
// Just ignore this field (ie. use it's default value).
if (!isset($field_source)) {
continue;
}
if (is_array($field_source)) {
$select->addExpression($field_source['expression'], $field_alias, $field_source['arguments']);
}
else {
$select->addField($table, $field_source, $field_alias);
}
}
// Execute the data migration query.
$this->connection->insert($new_table)
->from($select)
->execute();
$old_count = $this->connection->query('SELECT COUNT(*) FROM {' . $table . '}')->fetchField();
$new_count = $this->connection->query('SELECT COUNT(*) FROM {' . $new_table . '}')->fetchField();
if ($old_count == $new_count) {
$this->dropTable($table);
$this->renameTable($new_table, $table);
}
}
/**
* Find out the schema of a table.
*
* This function uses introspection methods provided by the database to
* create a schema array. This is useful, for example, during update when
* the old schema is not available.
*
* @param $table
* Name of the table.
* @return
* An array representing the schema, from drupal_get_schema().
* @see drupal_get_schema()
*/
protected function introspectSchema($table) {
$mapped_fields = array_flip($this->getFieldTypeMap());
$schema = array(
'fields' => array(),
'primary key' => array(),
'unique keys' => array(),
'indexes' => array(),
);
$info = $this->getPrefixInfo($table);
$result = $this->connection->query('PRAGMA ' . $info['schema'] . '.table_info(' . $info['table'] . ')');
foreach ($result as $row) {
if (preg_match('/^([^(]+)\((.*)\)$/', $row->type, $matches)) {
$type = $matches[1];
$length = $matches[2];
}
else {
$type = $row->type;
$length = NULL;
}
if (isset($mapped_fields[$type])) {
list($type, $size) = explode(':', $mapped_fields[$type]);
$schema['fields'][$row->name] = array(
'type' => $type,
'size' => $size,
'not null' => !empty($row->notnull),
'default' => trim($row->dflt_value, "'"),
);
if ($length) {
$schema['fields'][$row->name]['length'] = $length;
}
if ($row->pk) {
$schema['primary key'][] = $row->name;
}
}
else {
new Exception("Unable to parse the column type " . $row->type);
}
}
$indexes = array();
$result = $this->connection->query('PRAGMA ' . $info['schema'] . '.index_list(' . $info['table'] . ')');
foreach ($result as $row) {
if (strpos($row->name, 'sqlite_autoindex_') !== 0) {
$indexes[] = array(
'schema_key' => $row->unique ? 'unique keys' : 'indexes',
'name' => $row->name,
);
}
}
foreach ($indexes as $index) {
$name = $index['name'];
// Get index name without prefix.
$index_name = substr($name, strlen($info['table']) + 1);
$result = $this->connection->query('PRAGMA ' . $info['schema'] . '.index_info(' . $name . ')');
foreach ($result as $row) {
$schema[$index['schema_key']][$index_name][] = $row->name;
}
}
return $schema;
}
public function dropField($table, $field) {
if (!$this->fieldExists($table, $field)) {
return FALSE;
}
$old_schema = $this->introspectSchema($table);
$new_schema = $old_schema;
unset($new_schema['fields'][$field]);
foreach ($new_schema['indexes'] as $index => $fields) {
foreach ($fields as $key => $field_name) {
if ($field_name == $field) {
unset($new_schema['indexes'][$index][$key]);
}
}
// If this index has no more fields then remove it.
if (empty($new_schema['indexes'][$index])) {
unset($new_schema['indexes'][$index]);
}
}
$this->alterTable($table, $old_schema, $new_schema);
return TRUE;
}
public function changeField($table, $field, $field_new, $spec, $keys_new = array()) {
if (!$this->fieldExists($table, $field)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot change the definition of field @table.@name: field doesn't exist.", array('@table' => $table, '@name' => $field)));
}
if (($field != $field_new) && $this->fieldExists($table, $field_new)) {
throw new DatabaseSchemaObjectExistsException(t("Cannot rename field @table.@name to @name_new: target field already exists.", array('@table' => $table, '@name' => $field, '@name_new' => $field_new)));
}
$old_schema = $this->introspectSchema($table);
$new_schema = $old_schema;
// Map the old field to the new field.
if ($field != $field_new) {
$mapping[$field_new] = $field;
}
else {
$mapping = array();
}
// Remove the previous definition and swap in the new one.
unset($new_schema['fields'][$field]);
$new_schema['fields'][$field_new] = $spec;
// Map the former indexes to the new column name.
$new_schema['primary key'] = $this->mapKeyDefinition($new_schema['primary key'], $mapping);
foreach (array('unique keys', 'indexes') as $k) {
foreach ($new_schema[$k] as &$key_definition) {
$key_definition = $this->mapKeyDefinition($key_definition, $mapping);
}
}
// Add in the keys from $keys_new.
if (isset($keys_new['primary key'])) {
$new_schema['primary key'] = $keys_new['primary key'];
}
foreach (array('unique keys', 'indexes') as $k) {
if (!empty($keys_new[$k])) {
$new_schema[$k] = $keys_new[$k] + $new_schema[$k];
}
}
$this->alterTable($table, $old_schema, $new_schema, $mapping);
}
/**
* Utility method: rename columns in an index definition according to a new mapping.
*
* @param $key_definition
* The key definition.
* @param $mapping
* The new mapping.
*/
protected function mapKeyDefinition(array $key_definition, array $mapping) {
foreach ($key_definition as &$field) {
// The key definition can be an array($field, $length).
if (is_array($field)) {
$field = &$field[0];
}
if (isset($mapping[$field])) {
$field = $mapping[$field];
}
}
return $key_definition;
}
public function addIndex($table, $name, $fields) {
if (!$this->tableExists($table)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add index @name to table @table: table doesn't exist.", array('@table' => $table, '@name' => $name)));
}
if ($this->indexExists($table, $name)) {
throw new DatabaseSchemaObjectExistsException(t("Cannot add index @name to table @table: index already exists.", array('@table' => $table, '@name' => $name)));
}
$schema['indexes'][$name] = $fields;
$statements = $this->createIndexSql($table, $schema);
foreach ($statements as $statement) {
$this->connection->query($statement);
}
}
public function indexExists($table, $name) {
$info = $this->getPrefixInfo($table);
return $this->connection->query('PRAGMA ' . $info['schema'] . '.index_info(' . $info['table'] . '_' . $name . ')')->fetchField() != '';
}
public function dropIndex($table, $name) {
if (!$this->indexExists($table, $name)) {
return FALSE;
}
$info = $this->getPrefixInfo($table);
$this->connection->query('DROP INDEX ' . $info['schema'] . '.' . $info['table'] . '_' . $name);
return TRUE;
}
public function addUniqueKey($table, $name, $fields) {
if (!$this->tableExists($table)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add unique key @name to table @table: table doesn't exist.", array('@table' => $table, '@name' => $name)));
}
if ($this->indexExists($table, $name)) {
throw new DatabaseSchemaObjectExistsException(t("Cannot add unique key @name to table @table: unique key already exists.", array('@table' => $table, '@name' => $name)));
}
$schema['unique keys'][$name] = $fields;
$statements = $this->createIndexSql($table, $schema);
foreach ($statements as $statement) {
$this->connection->query($statement);
}
}
public function dropUniqueKey($table, $name) {
if (!$this->indexExists($table, $name)) {
return FALSE;
}
$info = $this->getPrefixInfo($table);
$this->connection->query('DROP INDEX ' . $info['schema'] . '.' . $info['table'] . '_' . $name);
return TRUE;
}
public function addPrimaryKey($table, $fields) {
if (!$this->tableExists($table)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add primary key to table @table: table doesn't exist.", array('@table' => $table)));
}
$old_schema = $this->introspectSchema($table);
$new_schema = $old_schema;
if (!empty($new_schema['primary key'])) {
throw new DatabaseSchemaObjectExistsException(t("Cannot add primary key to table @table: primary key already exists.", array('@table' => $table)));
}
$new_schema['primary key'] = $fields;
$this->alterTable($table, $old_schema, $new_schema);
}
public function dropPrimaryKey($table) {
$old_schema = $this->introspectSchema($table);
$new_schema = $old_schema;
if (empty($new_schema['primary key'])) {
return FALSE;
}
unset($new_schema['primary key']);
$this->alterTable($table, $old_schema, $new_schema);
return TRUE;
}
public function fieldSetDefault($table, $field, $default) {
if (!$this->fieldExists($table, $field)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot set default value of field @table.@field: field doesn't exist.", array('@table' => $table, '@field' => $field)));
}
$old_schema = $this->introspectSchema($table);
$new_schema = $old_schema;
$new_schema['fields'][$field]['default'] = $default;
$this->alterTable($table, $old_schema, $new_schema);
}
public function fieldSetNoDefault($table, $field) {
if (!$this->fieldExists($table, $field)) {
throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot remove default value of field @table.@field: field doesn't exist.", array('@table' => $table, '@field' => $field)));
}
$old_schema = $this->introspectSchema($table);
$new_schema = $old_schema;
unset($new_schema['fields'][$field]['default']);
$this->alterTable($table, $old_schema, $new_schema);
}
public function findTables($table_expression) {
// Don't add the prefix, $table_expression already includes the prefix.
$info = $this->getPrefixInfo($table_expression, FALSE);
// Can't use query placeholders for the schema because the query would have
// to be :prefixsqlite_master, which does not work.
$result = db_query("SELECT name FROM " . $info['schema'] . ".sqlite_master WHERE type = :type AND name LIKE :table_name", array(
':type' => 'table',
':table_name' => $info['table'],
));
return $result->fetchAllKeyed(0, 0);
}
}

View file

@ -0,0 +1,27 @@
<?php
/**
* @file
* Select builder for SQLite embedded database engine.
*/
/**
* @addtogroup database
* @{
*/
/**
* SQLite specific query builder for SELECT statements.
*/
class SelectQuery_sqlite extends SelectQuery {
public function forUpdate($set = TRUE) {
// SQLite does not support FOR UPDATE so nothing to do.
return $this;
}
}
/**
* @} End of "addtogroup database".
*/