updated core to 7.80

This commit is contained in:
2021-07-12 10:11:08 +02:00
parent 7b1e954f7f
commit 5656f5a68a
236 changed files with 4149 additions and 888 deletions

View File

@@ -184,7 +184,7 @@
*
* @see http://php.net/manual/book.pdo.php
*/
abstract class DatabaseConnection extends PDO {
abstract class DatabaseConnection {
/**
* The database target this connection is for.
@@ -261,6 +261,13 @@ abstract class DatabaseConnection extends PDO {
*/
protected $temporaryNameIndex = 0;
/**
* The actual PDO connection.
*
* @var \PDO
*/
protected $connection;
/**
* The connection information for this connection object.
*
@@ -310,6 +317,13 @@ abstract class DatabaseConnection extends PDO {
*/
protected $escapedAliases = array();
/**
* List of un-prefixed table names, keyed by prefixed table names.
*
* @var array
*/
protected $unprefixedTablesMap = array();
function __construct($dsn, $username, $password, $driver_options = array()) {
// Initialize and prepare the connection prefix.
$this->setPrefix(isset($this->connectionOptions['prefix']) ? $this->connectionOptions['prefix'] : '');
@@ -318,14 +332,27 @@ abstract class DatabaseConnection extends PDO {
$driver_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
// Call PDO::__construct and PDO::setAttribute.
parent::__construct($dsn, $username, $password, $driver_options);
$this->connection = new PDO($dsn, $username, $password, $driver_options);
// Set a Statement class, unless the driver opted out.
if (!empty($this->statementClass)) {
$this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array($this->statementClass, array($this)));
$this->connection->setAttribute(PDO::ATTR_STATEMENT_CLASS, array($this->statementClass, array($this)));
}
}
/**
* Proxy possible direct calls to the \PDO methods.
*
* Since PHP8.0 the signature of the the \PDO::query() method has changed,
* and this class can't extending \PDO any more.
*
* However, for the BC, proxy any calls to the \PDO methods to the actual
* PDO connection object.
*/
public function __call($name, $arguments) {
return call_user_func_array(array($this->connection, $name), $arguments);
}
/**
* Destroys this Connection object.
*
@@ -338,7 +365,9 @@ abstract class DatabaseConnection extends PDO {
// Destroy all references to this connection by setting them to NULL.
// The Statement class attribute only accepts a new value that presents a
// proper callable, so we reset it to PDOStatement.
$this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('PDOStatement', array()));
if (!empty($this->statementClass)) {
$this->connection->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('PDOStatement', array()));
}
$this->schema = NULL;
}
@@ -442,6 +471,13 @@ abstract class DatabaseConnection extends PDO {
$this->prefixReplace[] = $this->prefixes['default'];
$this->prefixSearch[] = '}';
$this->prefixReplace[] = '';
// Set up a map of prefixed => un-prefixed tables.
foreach ($this->prefixes as $table_name => $prefix) {
if ($table_name !== 'default') {
$this->unprefixedTablesMap[$prefix . $table_name] = $table_name;
}
}
}
/**
@@ -477,6 +513,17 @@ abstract class DatabaseConnection extends PDO {
}
}
/**
* Gets a list of individually prefixed table names.
*
* @return array
* An array of un-prefixed table names, keyed by their fully qualified table
* names (i.e. prefix + table_name).
*/
public function getUnprefixedTablesMap() {
return $this->unprefixedTablesMap;
}
/**
* Prepares a query string and returns the prepared statement.
*
@@ -494,7 +541,7 @@ abstract class DatabaseConnection extends PDO {
$query = $this->prefixTables($query);
// Call PDO::prepare.
return parent::prepare($query);
return $this->connection->prepare($query);
}
/**
@@ -706,7 +753,7 @@ abstract class DatabaseConnection extends PDO {
case Database::RETURN_AFFECTED:
return $stmt->rowCount();
case Database::RETURN_INSERT_ID:
return $this->lastInsertId();
return $this->connection->lastInsertId();
case Database::RETURN_NULL:
return;
default:
@@ -1089,7 +1136,7 @@ abstract class DatabaseConnection extends PDO {
$rolled_back_other_active_savepoints = TRUE;
}
}
parent::rollBack();
$this->connection->rollBack();
if ($rolled_back_other_active_savepoints) {
throw new DatabaseTransactionOutOfOrderException();
}
@@ -1117,7 +1164,7 @@ abstract class DatabaseConnection extends PDO {
$this->query('SAVEPOINT ' . $name);
}
else {
parent::beginTransaction();
$this->connection->beginTransaction();
}
$this->transactionLayers[$name] = $name;
}
@@ -1168,7 +1215,7 @@ abstract class DatabaseConnection extends PDO {
// If there are no more layers left then we should commit.
unset($this->transactionLayers[$name]);
if (empty($this->transactionLayers)) {
if (!parent::commit()) {
if (!$this->connection->commit()) {
throw new DatabaseTransactionCommitFailedException();
}
}
@@ -1252,7 +1299,7 @@ abstract class DatabaseConnection extends PDO {
* Returns the version of the database server.
*/
public function version() {
return $this->getAttribute(PDO::ATTR_SERVER_VERSION);
return $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
}
/**
@@ -1697,12 +1744,16 @@ abstract class Database {
*
* @param $key
* The connection key.
* @param $close
* Whether to close the connection.
* @return
* TRUE in case of success, FALSE otherwise.
*/
final public static function removeConnection($key) {
final public static function removeConnection($key, $close = TRUE) {
if (isset(self::$databaseInfo[$key])) {
self::closeConnection(NULL, $key);
if ($close) {
self::closeConnection(NULL, $key);
}
unset(self::$databaseInfo[$key]);
return TRUE;
}
@@ -2840,7 +2891,6 @@ function db_field_exists($table, $field) {
*
* @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.
@@ -2849,6 +2899,23 @@ function db_find_tables($table_expression) {
return Database::getConnection()->schema()->findTables($table_expression);
}
/**
* Finds all tables that are like the specified base table name. This is a
* backport of the change made to db_find_tables in Drupal 8 to work with
* virtual, un-prefixed table names. The original function is retained for
* Backwards Compatibility.
* @see https://www.drupal.org/node/2552435
*
* @param $table_expression
* An SQL expression, for example "simpletest%" (without the quotes).
*
* @return
* Array, both the keys and the values are the matching tables.
*/
function db_find_tables_d8($table_expression) {
return Database::getConnection()->schema()->findTablesD8($table_expression);
}
function _db_create_keys_sql($spec) {
return Database::getConnection()->schema()->createKeysSql($spec);
}

View File

@@ -5,6 +5,11 @@
* Database interface code for MySQL database servers.
*/
/**
* The default character for quoting identifiers in MySQL.
*/
define('MYSQL_IDENTIFIER_QUOTE_CHARACTER_DEFAULT', '`');
/**
* @addtogroup database
* @{
@@ -19,6 +24,277 @@ class DatabaseConnection_mysql extends DatabaseConnection {
*/
protected $needsCleanup = FALSE;
/**
* The list of MySQL reserved key words.
*
* @link https://dev.mysql.com/doc/refman/8.0/en/keywords.html
*/
private $reservedKeyWords = array(
'accessible',
'add',
'admin',
'all',
'alter',
'analyze',
'and',
'as',
'asc',
'asensitive',
'before',
'between',
'bigint',
'binary',
'blob',
'both',
'by',
'call',
'cascade',
'case',
'change',
'char',
'character',
'check',
'collate',
'column',
'condition',
'constraint',
'continue',
'convert',
'create',
'cross',
'cube',
'cume_dist',
'current_date',
'current_time',
'current_timestamp',
'current_user',
'cursor',
'database',
'databases',
'day_hour',
'day_microsecond',
'day_minute',
'day_second',
'dec',
'decimal',
'declare',
'default',
'delayed',
'delete',
'dense_rank',
'desc',
'describe',
'deterministic',
'distinct',
'distinctrow',
'div',
'double',
'drop',
'dual',
'each',
'else',
'elseif',
'empty',
'enclosed',
'escaped',
'except',
'exists',
'exit',
'explain',
'false',
'fetch',
'first_value',
'float',
'float4',
'float8',
'for',
'force',
'foreign',
'from',
'fulltext',
'function',
'generated',
'get',
'grant',
'group',
'grouping',
'groups',
'having',
'high_priority',
'hour_microsecond',
'hour_minute',
'hour_second',
'if',
'ignore',
'in',
'index',
'infile',
'inner',
'inout',
'insensitive',
'insert',
'int',
'int1',
'int2',
'int3',
'int4',
'int8',
'integer',
'interval',
'into',
'io_after_gtids',
'io_before_gtids',
'is',
'iterate',
'join',
'json_table',
'key',
'keys',
'kill',
'lag',
'last_value',
'lead',
'leading',
'leave',
'left',
'like',
'limit',
'linear',
'lines',
'load',
'localtime',
'localtimestamp',
'lock',
'long',
'longblob',
'longtext',
'loop',
'low_priority',
'master_bind',
'master_ssl_verify_server_cert',
'match',
'maxvalue',
'mediumblob',
'mediumint',
'mediumtext',
'middleint',
'minute_microsecond',
'minute_second',
'mod',
'modifies',
'natural',
'not',
'no_write_to_binlog',
'nth_value',
'ntile',
'null',
'numeric',
'of',
'on',
'optimize',
'optimizer_costs',
'option',
'optionally',
'or',
'order',
'out',
'outer',
'outfile',
'over',
'partition',
'percent_rank',
'persist',
'persist_only',
'precision',
'primary',
'procedure',
'purge',
'range',
'rank',
'read',
'reads',
'read_write',
'real',
'recursive',
'references',
'regexp',
'release',
'rename',
'repeat',
'replace',
'require',
'resignal',
'restrict',
'return',
'revoke',
'right',
'rlike',
'row',
'rows',
'row_number',
'schema',
'schemas',
'second_microsecond',
'select',
'sensitive',
'separator',
'set',
'show',
'signal',
'smallint',
'spatial',
'specific',
'sql',
'sqlexception',
'sqlstate',
'sqlwarning',
'sql_big_result',
'sql_calc_found_rows',
'sql_small_result',
'ssl',
'starting',
'stored',
'straight_join',
'system',
'table',
'terminated',
'then',
'tinyblob',
'tinyint',
'tinytext',
'to',
'trailing',
'trigger',
'true',
'undo',
'union',
'unique',
'unlock',
'unsigned',
'update',
'usage',
'use',
'using',
'utc_date',
'utc_time',
'utc_timestamp',
'values',
'varbinary',
'varchar',
'varcharacter',
'varying',
'virtual',
'when',
'where',
'while',
'window',
'with',
'write',
'xor',
'year_month',
'zerofill',
);
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);
@@ -69,10 +345,10 @@ class DatabaseConnection_mysql extends DatabaseConnection {
// 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']);
$this->connection->exec('SET NAMES ' . $charset . ' COLLATE ' . $connection_options['collation']);
}
else {
$this->exec('SET NAMES ' . $charset);
$this->connection->exec('SET NAMES ' . $charset);
}
// Set MySQL init_commands if not already defined. Default Drupal's MySQL
@@ -86,15 +362,95 @@ class DatabaseConnection_mysql extends DatabaseConnection {
$connection_options += array(
'init_commands' => array(),
);
$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 was removed in MySQL 8.0.11
// https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-11.html#mysqld-8-0-11-deprecation-removal
if (version_compare($this->connection->getAttribute(PDO::ATTR_SERVER_VERSION), '8.0.11', '<')) {
$sql_mode .= ',NO_AUTO_CREATE_USER';
}
$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'",
'sql_mode' => "SET sql_mode = '$sql_mode'",
);
// Execute initial commands.
foreach ($connection_options['init_commands'] as $sql) {
$this->exec($sql);
$this->connection->exec($sql);
}
}
/**
* {@inheritdoc}}
*/
protected function setPrefix($prefix) {
parent::setPrefix($prefix);
// Successive versions of MySQL have become increasingly strict about the
// use of reserved keywords as table names. Drupal 7 uses at least one such
// table (system). Therefore we surround all table names with quotes.
$quote_char = variable_get('mysql_identifier_quote_character', MYSQL_IDENTIFIER_QUOTE_CHARACTER_DEFAULT);
foreach ($this->prefixSearch as $i => $prefixSearch) {
if (substr($prefixSearch, 0, 1) === '{') {
// If the prefix already contains one or more quotes remove them.
// This can happen when - for example - DrupalUnitTestCase sets up a
// "temporary prefixed database". Also if there's a dot in the prefix,
// wrap it in quotes to cater for schema names in prefixes.
$search = array($quote_char, '.');
$replace = array('', $quote_char . '.' . $quote_char);
$this->prefixReplace[$i] = $quote_char . str_replace($search, $replace, $this->prefixReplace[$i]);
}
if (substr($prefixSearch, -1) === '}') {
$this->prefixReplace[$i] .= $quote_char;
}
}
}
/**
* {@inheritdoc}
*/
public function escapeField($field) {
$field = parent::escapeField($field);
return $this->quoteIdentifier($field);
}
public function escapeFields(array $fields) {
foreach ($fields as &$field) {
$field = $this->escapeField($field);
}
return $fields;
}
/**
* {@inheritdoc}
*/
public function escapeAlias($field) {
$field = parent::escapeAlias($field);
return $this->quoteIdentifier($field);
}
/**
* Quotes an identifier if it matches a MySQL reserved keyword.
*
* @param string $identifier
* The field to check.
*
* @return string
* The identifier, quoted if it matches a MySQL reserved keyword.
*/
private function quoteIdentifier($identifier) {
// Quote identifiers so that MySQL reserved words like 'function' can be
// used as column names. Sometimes the 'table.column_name' format is passed
// in. For example, menu_load_links() adds a condition on "ml.menu_name".
if (strpos($identifier, '.') !== FALSE) {
list($table, $identifier) = explode('.', $identifier, 2);
}
if (in_array(strtolower($identifier), $this->reservedKeyWords, TRUE)) {
// Quote the string for MySQL reserved keywords.
$quote_char = variable_get('mysql_identifier_quote_character', MYSQL_IDENTIFIER_QUOTE_CHARACTER_DEFAULT);
$identifier = $quote_char . $identifier . $quote_char;
}
return isset($table) ? $table . '.' . $identifier : $identifier;
}
public function __destruct() {
if ($this->needsCleanup) {
$this->nextIdDelete();
@@ -180,7 +536,7 @@ class DatabaseConnection_mysql extends DatabaseConnection {
// If there are no more layers left then we should commit.
unset($this->transactionLayers[$name]);
if (empty($this->transactionLayers)) {
if (!PDO::commit()) {
if (!$this->doCommit()) {
throw new DatabaseTransactionCommitFailedException();
}
}
@@ -203,7 +559,7 @@ class DatabaseConnection_mysql extends DatabaseConnection {
$this->transactionLayers = array();
// We also have to explain to PDO that the transaction stack has
// been cleaned-up.
PDO::commit();
$this->doCommit();
}
else {
throw $e;
@@ -213,6 +569,53 @@ class DatabaseConnection_mysql extends DatabaseConnection {
}
}
/**
* Do the actual commit, including a workaround for PHP 8 behaviour changes.
*
* @return bool
* Success or otherwise of the commit.
*/
protected function doCommit() {
if ($this->connection->inTransaction()) {
return $this->connection->commit();
}
else {
// In PHP 8.0 a PDOException is thrown when a commit is attempted with no
// transaction active. In previous PHP versions this failed silently.
return TRUE;
}
}
/**
* {@inheritdoc}
*/
public function rollback($savepoint_name = 'drupal_transaction') {
// MySQL will automatically commit transactions when tables are altered or
// created (DDL transactions are not supported). Prevent triggering an
// exception to ensure that the error that has caused the rollback is
// properly reported.
if (!$this->connection->inTransaction()) {
// Before PHP 8 $this->connection->inTransaction() will return TRUE and
// $this->connection->rollback() does not throw an exception; the
// following code is unreachable.
// If \DatabaseConnection::rollback() would throw an
// exception then continue to throw an exception.
if (!$this->inTransaction()) {
throw new DatabaseTransactionNoActiveException();
}
// A previous rollback to an earlier savepoint may mean that the savepoint
// in question has already been accidentally committed.
if (!isset($this->transactionLayers[$savepoint_name])) {
throw new DatabaseTransactionNoActiveException();
}
trigger_error('Rollback attempted when there is no active transaction. This can cause data integrity issues.', E_USER_WARNING);
return;
}
return parent::rollback($savepoint_name);
}
public function utf8mb4IsConfigurable() {
return TRUE;
}
@@ -223,7 +626,7 @@ class DatabaseConnection_mysql extends DatabaseConnection {
public function utf8mb4IsSupported() {
// Ensure that the MySQL driver supports utf8mb4 encoding.
$version = $this->getAttribute(PDO::ATTR_CLIENT_VERSION);
$version = $this->connection->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);

View File

@@ -48,6 +48,10 @@ class InsertQuery_mysql extends InsertQuery {
// Default fields are always placed first for consistency.
$insert_fields = array_merge($this->defaultFields, $this->insertFields);
if (method_exists($this->connection, 'escapeFields')) {
$insert_fields = $this->connection->escapeFields($insert_fields);
}
// 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)) {
@@ -89,6 +93,20 @@ class InsertQuery_mysql extends InsertQuery {
class TruncateQuery_mysql extends TruncateQuery { }
class UpdateQuery_mysql extends UpdateQuery {
public function __toString() {
if (method_exists($this->connection, 'escapeField')) {
$escapedFields = array();
foreach ($this->fields as $field => $data) {
$field = $this->connection->escapeField($field);
$escapedFields[$field] = $data;
}
$this->fields = $escapedFields;
}
return parent::__toString();
}
}
/**
* @} End of "addtogroup database".
*/

View File

@@ -57,6 +57,11 @@ class DatabaseSchema_mysql extends DatabaseSchema {
protected function buildTableNameCondition($table_name, $operator = '=', $add_prefix = TRUE) {
$info = $this->connection->getConnectionOptions();
// Ensure the table name is not surrounded with quotes as that is not
// appropriate for schema queries.
$quote_char = variable_get('mysql_identifier_quote_character', MYSQL_IDENTIFIER_QUOTE_CHARACTER_DEFAULT);
$table_name = str_replace($quote_char, '', $table_name);
$table_info = $this->getPrefixInfo($table_name, $add_prefix);
$condition = new DatabaseCondition('AND');
@@ -494,11 +499,11 @@ class DatabaseSchema_mysql extends DatabaseSchema {
$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();
return $this->connection->query("SELECT column_comment AS 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();
$comment = $this->connection->query("SELECT table_comment AS 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);
}

View File

@@ -66,11 +66,11 @@ class DatabaseConnection_pgsql extends DatabaseConnection {
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'");
$this->connection->exec("SET NAMES 'UTF8'");
// Execute PostgreSQL init_commands.
if (isset($connection_options['init_commands'])) {
$this->exec(implode('; ', $connection_options['init_commands']));
$this->connection->exec(implode('; ', $connection_options['init_commands']));
}
}
@@ -117,7 +117,7 @@ class DatabaseConnection_pgsql extends DatabaseConnection {
case Database::RETURN_AFFECTED:
return $stmt->rowCount();
case Database::RETURN_INSERT_ID:
return $this->lastInsertId($options['sequence_name']);
return $this->connection->lastInsertId($options['sequence_name']);
case Database::RETURN_NULL:
return;
default:

View File

@@ -169,6 +169,11 @@ require_once dirname(__FILE__) . '/query.inc';
*/
abstract class DatabaseSchema implements QueryPlaceholderInterface {
/**
* The database connection.
*
* @var DatabaseConnection
*/
protected $connection;
/**
@@ -343,7 +348,70 @@ abstract class DatabaseSchema implements QueryPlaceholderInterface {
// 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);
return $this->connection->query("SELECT table_name AS table_name FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments())->fetchAllKeyed(0, 0);
}
/**
* Finds all tables that are like the specified base table name. This is a
* backport of the change made to findTables in Drupal 8 to work with virtual,
* un-prefixed table names. The original function is retained for Backwards
* Compatibility.
* @see https://www.drupal.org/node/2552435
*
* @param string $table_expression
* An SQL expression, for example "cache_%" (without the quotes).
*
* @return array
* Both the keys and the values are the matching tables.
*/
public function findTablesD8($table_expression) {
// Load all the tables up front in order to take into account per-table
// prefixes. The actual matching is done at the bottom of the method.
$condition = $this->buildTableNameCondition('%', 'LIKE');
$condition->compile($this->connection, $this);
$individually_prefixed_tables = $this->connection->getUnprefixedTablesMap();
$default_prefix = $this->connection->tablePrefix();
$default_prefix_length = strlen($default_prefix);
$tables = array();
// 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.
$results = $this->connection->query("SELECT table_name AS table_name FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments());
foreach ($results as $table) {
// Take into account tables that have an individual prefix.
if (isset($individually_prefixed_tables[$table->table_name])) {
$prefix_length = strlen($this->connection->tablePrefix($individually_prefixed_tables[$table->table_name]));
}
elseif ($default_prefix && substr($table->table_name, 0, $default_prefix_length) !== $default_prefix) {
// This table name does not start the default prefix, which means that
// it is not managed by Drupal so it should be excluded from the result.
continue;
}
else {
$prefix_length = $default_prefix_length;
}
// Remove the prefix from the returned tables.
$unprefixed_table_name = substr($table->table_name, $prefix_length);
// The pattern can match a table which is the same as the prefix. That
// will become an empty string when we remove the prefix, which will
// probably surprise the caller, besides not being a prefixed table. So
// remove it.
if (!empty($unprefixed_table_name)) {
$tables[$unprefixed_table_name] = $unprefixed_table_name;
}
}
// Convert the table expression from its SQL LIKE syntax to a regular
// expression and escape the delimiter that will be used for matching.
$table_expression = str_replace(array('%', '_'), array('.*?', '.'), preg_quote($table_expression, '/'));
$tables = preg_grep('/^' . $table_expression . '$/i', $tables);
return $tables;
}
/**

View File

@@ -964,7 +964,7 @@ class SelectQuery extends Query implements SelectQueryInterface {
*/
protected $forUpdate = FALSE;
public function __construct($table, $alias = NULL, DatabaseConnection $connection, $options = array()) {
public function __construct($table, $alias, DatabaseConnection $connection, $options = array()) {
$options['return'] = Database::RETURN_STATEMENT;
parent::__construct($connection, $options);
$this->where = new DatabaseCondition('AND');
@@ -1520,13 +1520,16 @@ class SelectQuery extends Query implements SelectQueryInterface {
$fields = array();
foreach ($this->tables as $alias => $table) {
if (!empty($table['all_fields'])) {
$fields[] = $this->connection->escapeTable($alias) . '.*';
$fields[] = $this->connection->escapeAlias($alias) . '.*';
}
}
foreach ($this->fields as $alias => $field) {
// Note that $field['table'] holds the table alias.
// @see \SelectQuery::addField
$table = isset($field['table']) ? $this->connection->escapeAlias($field['table']) . '.' : '';
// Always use the AS keyword for field aliases, as some
// databases require it (e.g., PostgreSQL).
$fields[] = (isset($field['table']) ? $this->connection->escapeTable($field['table']) . '.' : '') . $this->connection->escapeField($field['field']) . ' AS ' . $this->connection->escapeAlias($field['alias']);
$fields[] = $table . $this->connection->escapeField($field['field']) . ' AS ' . $this->connection->escapeAlias($field['alias']);
}
foreach ($this->expressions as $alias => $expression) {
$fields[] = $expression['expression'] . ' AS ' . $this->connection->escapeAlias($expression['alias']);
@@ -1555,7 +1558,7 @@ class SelectQuery extends Query implements SelectQueryInterface {
// Don't use the AS keyword for table aliases, as some
// databases don't support it (e.g., Oracle).
$query .= $table_string . ' ' . $this->connection->escapeTable($table['alias']);
$query .= $table_string . ' ' . $this->connection->escapeAlias($table['alias']);
if (!empty($table['condition'])) {
$query .= ' ON ' . $table['condition'];

View File

@@ -107,9 +107,21 @@ class DatabaseConnection_sqlite extends DatabaseConnection {
$this->sqliteCreateFunction('substring_index', array($this, 'sqlFunctionSubstringIndex'), 3);
$this->sqliteCreateFunction('rand', array($this, 'sqlFunctionRand'));
// Enable the Write-Ahead Logging (WAL) option for SQLite if supported.
// @see https://www.drupal.org/node/2348137
// @see https://sqlite.org/wal.html
if (version_compare($version, '3.7') >= 0) {
$connection_options += array(
'init_commands' => array(),
);
$connection_options['init_commands'] += array(
'wal' => "PRAGMA journal_mode=WAL",
);
}
// Execute sqlite init_commands.
if (isset($connection_options['init_commands'])) {
$this->exec(implode('; ', $connection_options['init_commands']));
$this->connection->exec(implode('; ', $connection_options['init_commands']));
}
}
@@ -128,10 +140,10 @@ class DatabaseConnection_sqlite extends DatabaseConnection {
$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.
if ($count == 0 && $this->connectionOptions['database'] != ':memory:') {
// Detaching the database fails at this point, but no other queries
// are executed after the connection is destructed so we can simply
// remove the database file.
unlink($this->connectionOptions['database'] . '-' . $prefix);
}
}
@@ -143,6 +155,18 @@ class DatabaseConnection_sqlite extends DatabaseConnection {
}
}
/**
* Gets all the attached databases.
*
* @return array
* An array of attached database names.
*
* @see DatabaseConnection_sqlite::__construct().
*/
public function getAttachedDatabases() {
return $this->attachedDatabases;
}
/**
* SQLite compatibility implementation for the IF() SQL function.
*/
@@ -235,7 +259,7 @@ class DatabaseConnection_sqlite extends DatabaseConnection {
* expose this function to the world.
*/
public function PDOPrepare($query, array $options = array()) {
return parent::prepare($query, $options);
return $this->connection->prepare($query, $options);
}
public function queryRange($query, $from, $count, array $args = array(), array $options = array()) {
@@ -326,7 +350,7 @@ class DatabaseConnection_sqlite extends DatabaseConnection {
}
}
if ($this->supportsTransactions()) {
PDO::rollBack();
$this->connection->rollBack();
}
}
@@ -341,7 +365,7 @@ class DatabaseConnection_sqlite extends DatabaseConnection {
throw new DatabaseTransactionNameNonUniqueException($name . " is already in use.");
}
if (!$this->inTransaction()) {
PDO::beginTransaction();
$this->connection->beginTransaction();
}
$this->transactionLayers[$name] = $name;
}
@@ -366,9 +390,9 @@ class DatabaseConnection_sqlite extends DatabaseConnection {
// If there was any rollback() we should roll back whole transaction.
if ($this->willRollback) {
$this->willRollback = FALSE;
PDO::rollBack();
$this->connection->rollBack();
}
elseif (!PDO::commit()) {
elseif (!$this->connection->commit()) {
throw new DatabaseTransactionCommitFailedException();
}
}

View File

@@ -23,7 +23,7 @@ class InsertQuery_sqlite extends InsertQuery {
if (!$this->preExecute()) {
return NULL;
}
if (count($this->insertFields)) {
if (count($this->insertFields) || !empty($this->fromQuery)) {
return parent::execute();
}
else {
@@ -36,7 +36,10 @@ class InsertQuery_sqlite extends InsertQuery {
$comments = $this->connection->makeComment($this->comments);
// Produce as many generic placeholders as necessary.
$placeholders = array_fill(0, count($this->insertFields), '?');
$placeholders = array();
if (!empty($this->insertFields)) {
$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.

View File

@@ -668,6 +668,9 @@ class DatabaseSchema_sqlite extends DatabaseSchema {
$this->alterTable($table, $old_schema, $new_schema);
}
/**
* {@inheritdoc}
*/
public function findTables($table_expression) {
// Don't add the prefix, $table_expression already includes the prefix.
$info = $this->getPrefixInfo($table_expression, FALSE);
@@ -680,4 +683,32 @@ class DatabaseSchema_sqlite extends DatabaseSchema {
));
return $result->fetchAllKeyed(0, 0);
}
/**
* {@inheritdoc}
*/
public function findTablesD8($table_expression) {
$tables = array();
// The SQLite implementation doesn't need to use the same filtering strategy
// as the parent one because individually prefixed tables live in their own
// schema (database), which means that neither the main database nor any
// attached one will contain a prefixed table name, so we just need to loop
// over all known schemas and filter by the user-supplied table expression.
$attached_dbs = $this->connection->getAttachedDatabases();
foreach ($attached_dbs as $schema) {
// Can't use query placeholders for the schema because the query would
// have to be :prefixsqlite_master, which does not work. We also need to
// ignore the internal SQLite tables.
$result = db_query("SELECT name FROM " . $schema . ".sqlite_master WHERE type = :type AND name LIKE :table_name AND name NOT LIKE :pattern", array(
':type' => 'table',
':table_name' => $table_expression,
':pattern' => 'sqlite_%',
));
$tables += $result->fetchAllKeyed(0, 0);
}
return $tables;
}
}