- <?php
-
- * @file
- * Database interface code for MySQL database servers.
- */
-
- * The default character for quoting identifiers in MySQL.
- */
- define('MYSQL_IDENTIFIER_QUOTE_CHARACTER_DEFAULT', '`');
-
- * @addtogroup database
- * @{
- */
-
- class DatabaseConnection_mysql extends DatabaseConnection {
-
- * Flag to indicate if the cleanup function in __destruct() should run.
- *
- * @var boolean
- */
- protected $needsCleanup = FALSE;
-
-
- * Flag set in utf8mb4IsSupported().
- *
- * @var boolean
- */
- protected $utf8mb4Supported;
-
-
- * 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->transactionSupport = !isset($connection_options['transactions']) || ($connection_options['transactions'] !== FALSE);
-
-
- $this->transactionalDDLSupport = FALSE;
-
- $this->connectionOptions = $connection_options;
-
- $charset = 'utf8';
-
- if ($this->utf8mb4IsActive()) {
- $charset = 'utf8mb4';
- }
-
-
- if (isset($connection_options['unix_socket'])) {
- $dsn = 'mysql:unix_socket=' . $connection_options['unix_socket'];
- }
- else {
-
- $dsn = 'mysql:host=' . $connection_options['host'] . ';port=' . (empty($connection_options['port']) ? 3306 : $connection_options['port']);
- }
-
-
-
- $dsn .= ';charset=' . $charset;
- if (!empty($connection_options['database'])) {
- $dsn .= ';dbname=' . $connection_options['database'];
- }
-
- $connection_options += array(
- 'pdo' => array(),
- );
- $connection_options['pdo'] += array(
-
-
-
- PDO::MYSQL_ATTR_FOUND_ROWS => TRUE,
-
- PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE,
-
- PDO::ATTR_EMULATE_PREPARES => TRUE,
- );
- if (defined('PDO::MYSQL_ATTR_MULTI_STATEMENTS')) {
-
-
- $connection_options['pdo'] += array(PDO::MYSQL_ATTR_MULTI_STATEMENTS => FALSE);
- }
-
- parent::__construct($dsn, $connection_options['username'], $connection_options['password'], $connection_options['pdo']);
-
-
-
-
- if (!empty($connection_options['collation'])) {
- $this->pdo->exec('SET NAMES ' . $charset . ' COLLATE ' . $connection_options['collation']);
- }
- else {
- $this->pdo->exec('SET NAMES ' . $charset);
- }
-
-
-
-
-
-
- $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';
-
-
- if (version_compare($this->pdo->getAttribute(PDO::ATTR_SERVER_VERSION), '8.0.11', '<')) {
- $sql_mode .= ',NO_AUTO_CREATE_USER';
- }
- $connection_options['init_commands'] += array(
- 'sql_mode' => "SET sql_mode = '$sql_mode'",
- );
-
-
- foreach ($connection_options['init_commands'] as $sql) {
- $this->pdo->exec($sql);
- }
- }
-
-
- * {@inheritdoc}}
- */
- protected function setPrefix($prefix) {
- parent::setPrefix($prefix);
-
-
-
- $quote_char = MYSQL_IDENTIFIER_QUOTE_CHARACTER_DEFAULT;
- foreach ($this->prefixSearch as $i => $prefixSearch) {
- if (substr($prefixSearch, 0, 1) === '{') {
-
-
-
- $this->prefixReplace[$i] = $quote_char . str_replace($quote_char, '', $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) {
-
-
-
- if (strpos($identifier, '.') !== FALSE) {
- list($table, $identifier) = explode('.', $identifier, 2);
- }
- if (in_array(strtolower($identifier), $this->reservedKeyWords, TRUE)) {
-
- $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();
- }
- }
-
- 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';
- }
-
-
- * Overrides DatabaseConnection::createDatabase().
- *
- * @param string $database
- * The name of the database to create.
- *
- * @throws DatabaseNotFoundException
- */
- public function createDatabase($database) {
- try {
-
- $this->exec("CREATE DATABASE IF NOT EXISTS $database");
- $this->exec("USE $database");
- }
- catch (\Exception $e) {
- throw new DatabaseNotFoundException($e->getMessage());
- }
- }
-
- public function mapConditionOperator($operator) {
-
- return NULL;
- }
-
- public function nextId($existing_id = 0) {
- $new_id = $this->query('INSERT INTO {sequences} () VALUES ()', array(), array('return' => Database::RETURN_INSERT_ID));
-
- if ($existing_id >= $new_id) {
-
-
-
-
-
-
-
- $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() {
-
-
-
-
-
-
-
-
- try {
- $max_id = $this->query('SELECT MAX(value) FROM {sequences}')->fetchField();
-
- $this->query('DELETE FROM {sequences} WHERE value < :value', array(':value' => $max_id));
- }
-
-
-
-
-
-
- catch (PDOException $e) {
- }
- }
-
-
- * Overridden to work around issues to MySQL not supporting transactional DDL.
- */
- protected function popCommittableTransactions() {
-
- foreach (array_reverse($this->transactionLayers) as $name => $active) {
-
- if ($active) {
- break;
- }
-
-
- unset($this->transactionLayers[$name]);
- if (empty($this->transactionLayers)) {
- if (!$this->pdo->commit()) {
- throw new DatabaseTransactionCommitFailedException();
- }
- }
- else {
-
- try {
- $this->query('RELEASE SAVEPOINT ' . $name);
- }
- catch (PDOException $e) {
-
-
-
-
-
-
-
- if ($e->errorInfo[1] == '1305') {
-
-
- $this->transactionLayers = array();
-
-
- $this->pdo->commit();
- }
- else {
- throw $e;
- }
- }
- }
- }
- }
-
- public function utf8mb4IsActive() {
- return isset($this->connectionOptions['charset']) && $this->connectionOptions['charset'] === 'utf8mb4';
- }
-
- public function utf8mb4IsSupported() {
-
- if (isset($this->utf8mb4Supported)) {
- return $this->utf8mb4Supported;
- }
-
-
- $version = $this->pdo->getAttribute(PDO::ATTR_CLIENT_VERSION);
-
- if (strpos($version, 'mysqlnd') !== FALSE) {
-
- $version = preg_replace('/^\D+([\d.]+).*/', '$1', $version);
- if (version_compare($version, '5.0.9', '<')) {
- return FALSE;
- }
- }
- else {
-
- if (version_compare($version, '5.5.3', '<')) {
- return FALSE;
- }
- }
-
-
- try {
- $this->query("DROP TABLE IF EXISTS {backdrop_utf8mb4_test}");
- $this->query("CREATE TABLE {backdrop_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 IF EXISTS {backdrop_utf8mb4_test}");
- return TRUE;
- }
-
- public function setSessionTimezoneOffset($offset) {
- $this->query("SET @@session.time_zone = :offset", array(':offset' => $offset));
- }
-
-
- public function hasTimezoneSupport() {
- $test = db_query("SELECT CONVERT_TZ('2008-02-15 12:00:00', 'UTC', 'US/Central')")->fetchField();
- return ($test == '2008-02-15 06:00:00');
- }
-
- public function dateFieldSql($field, $date_type = DATE_UNIX) {
- switch ($date_type) {
- case 'int':
- watchdog('database', 'Date field type "int" has been deprecated, use DATE_UNIX instead.', array(), WATCHDOG_DEPRECATED);
- case DATE_UNIX:
- $field = "FROM_UNIXTIME($field)";
- break;
-
- case DATE_ISO:
- $field = "STR_TO_DATE($field, '%Y-%m-%dT%T')";
- break;
-
- case DATE_DATETIME:
- break;
- }
-
- return $field;
- }
-
- public function dateMathSql($field, $direction, $count, $granularity) {
- $granularity = strtoupper($granularity);
- switch ($direction) {
- case 'ADD':
- return "DATE_ADD($field, INTERVAL $count $granularity)";
-
- case 'SUB':
- return "DATE_SUB($field, INTERVAL $count $granularity)";
- }
- return $field;
- }
-
- public function dateFormatSql($field, $format) {
- $replace = array(
- 'Y' => '%Y',
- 'y' => '%y',
- 'M' => '%b',
- 'm' => '%m',
- 'n' => '%c',
- 'F' => '%M',
- 'D' => '%a',
- 'd' => '%d',
- 'l' => '%W',
- 'j' => '%e',
- 'W' => '%v',
- 'H' => '%H',
- 'h' => '%h',
- 'i' => '%i',
- 's' => '%s',
- 'A' => '%p',
- );
- $format = strtr($format, $replace);
- return "DATE_FORMAT($field, '$format')";
- }
-
- public function dateExtractSql($field, $extract_type) {
-
-
- switch (strtoupper($extract_type)) {
- case 'DATE':
- return $field;
- case 'YEAR':
- return "EXTRACT(YEAR FROM($field))";
- case 'MONTH':
- return "EXTRACT(MONTH FROM($field))";
- case 'DAY':
- return "EXTRACT(DAY FROM($field))";
- case 'HOUR':
- return "EXTRACT(HOUR FROM($field))";
- case 'MINUTE':
- return "EXTRACT(MINUTE FROM($field))";
- case 'SECOND':
- return "EXTRACT(SECOND FROM($field))";
-
-
- case 'WEEK':
- return "WEEK($field, 3)";
- case 'DOW':
-
-
- return "INTEGER(DAYOFWEEK($field) - 1)";
- case 'DOY':
- return "DAYOFYEAR($field)";
- }
-
-
- return FALSE;
-
- }
-
- public function dateConvertTimezoneSql($field, $source, $target) {
- return "CONVERT_TZ($field, $source, $target)";
- }
- }
-
-
- * @} End of "addtogroup database".
- */