summaryrefslogtreecommitdiffstatshomepage
path: root/includes/database/sqlite
diff options
context:
space:
mode:
Diffstat (limited to 'includes/database/sqlite')
-rw-r--r--includes/database/sqlite/database.inc511
-rw-r--r--includes/database/sqlite/install.inc51
-rw-r--r--includes/database/sqlite/query.inc160
-rw-r--r--includes/database/sqlite/schema.inc683
-rw-r--r--includes/database/sqlite/select.inc27
5 files changed, 0 insertions, 1432 deletions
diff --git a/includes/database/sqlite/database.inc b/includes/database/sqlite/database.inc
deleted file mode 100644
index 3e2490b00cab..000000000000
--- a/includes/database/sqlite/database.inc
+++ /dev/null
@@ -1,511 +0,0 @@
-<?php
-
-/**
- * @file
- * Database interface code for SQLite embedded database engine.
- */
-
-/**
- * @ingroup 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 = !isset($connection_options['transactions']) || $connection_options['transactions'] !== FALSE;
-
- $this->connectionOptions = $connection_options;
-
- parent::__construct('sqlite:' . $connection_options['database'], '', '', array(
- // Force column names to lower case.
- PDO::ATTR_CASE => PDO::CASE_LOWER,
- // Convert numeric values to strings when fetching.
- PDO::ATTR_STRINGIFY_FETCHES => TRUE,
- ));
-
- // 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'));
- }
-
- /**
- * 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(preg_replace('/^SELECT/i', 'CREATE TEMPORARY TABLE ' . $tablename . ' AS SELECT', $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;
- }
- }
- }
-
-}
-
-/**
- * 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 "ingroup database".
- */
diff --git a/includes/database/sqlite/install.inc b/includes/database/sqlite/install.inc
deleted file mode 100644
index 62cbac381f17..000000000000
--- a/includes/database/sqlite/install.inc
+++ /dev/null
@@ -1,51 +0,0 @@
-<?php
-
-/**
- * @file
- * SQLite specific install functions
- */
-
-class DatabaseTasks_sqlite extends DatabaseTasks {
- protected $pdoDriver = 'sqlite';
-
- public function name() {
- return st('SQLite');
- }
-
- /**
- * Minimum engine version.
- *
- * @todo: consider upping to 3.6.8 in Drupal 8 to get SAVEPOINT support.
- */
- 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;
- }
-}
-
diff --git a/includes/database/sqlite/query.inc b/includes/database/sqlite/query.inc
deleted file mode 100644
index 6b8a72f2ab46..000000000000
--- a/includes/database/sqlite/query.inc
+++ /dev/null
@@ -1,160 +0,0 @@
-<?php
-
-/**
- * @file
- * Query code for SQLite embedded database engine.
- */
-
-/**
- * @ingroup 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)) {
- return $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $this->insertFields) . ') ' . $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 name = 'newname' WHERE tid = 1
- * will become:
- * UPDATE test SET name = 'newname' WHERE tid = 1 AND name <> 'newname'
- */
-class UpdateQuery_sqlite extends UpdateQuery {
- /**
- * Helper function that removes the fields that are already in a condition.
- *
- * @param $fields
- * The fields.
- * @param QueryConditionInterface $condition
- * A database condition.
- */
- protected function removeFieldsInCondition(&$fields, QueryConditionInterface $condition) {
- foreach ($condition->conditions() as $child_condition) {
- if ($child_condition['field'] instanceof QueryConditionInterface) {
- $this->removeFieldsInCondition($fields, $child_condition['field']);
- }
- else {
- unset($fields[$child_condition['field']]);
- }
- }
- }
-
- public function execute() {
- if (!empty($this->queryOptions['sqlite_return_matched_rows'])) {
- return parent::execute();
- }
-
- // Get the fields used in the update query, and remove those that are already
- // in the condition.
- $fields = $this->expressionFields + $this->fields;
- $this->removeFieldsInCondition($fields, $this->condition);
-
- // 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.
- *
- * 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.
- */
-class DeleteQuery_sqlite extends DeleteQuery {
- public function execute() {
- 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 "ingroup database".
- */
diff --git a/includes/database/sqlite/schema.inc b/includes/database/sqlite/schema.inc
deleted file mode 100644
index c5882f12715d..000000000000
--- a/includes/database/sqlite/schema.inc
+++ /dev/null
@@ -1,683 +0,0 @@
-<?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 existsing 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);
- }
-}
diff --git a/includes/database/sqlite/select.inc b/includes/database/sqlite/select.inc
deleted file mode 100644
index fb926ef04d31..000000000000
--- a/includes/database/sqlite/select.inc
+++ /dev/null
@@ -1,27 +0,0 @@
-<?php
-
-/**
- * @file
- * Select builder for SQLite embedded database engine.
- */
-
-/**
- * @ingroup 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 "ingroup database".
- */
-
-