Index: INSTALL.oracle.txt =================================================================== RCS file: INSTALL.oracle.txt diff -N INSTALL.oracle.txt --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ INSTALL.oracle.txt 3 Apr 2008 07:55:00 -0000 @@ -0,0 +1,71 @@ +// $Id: INSTALL.oracle.txt,v 1.1 2007/12/09 17:45:21 hswong3i Exp $ + +CREATE THE Oracle DATABASE +-------------------------- + +This file describes how to create a Oracle database for Drupal. + +If you control your databases through a web-based control panel, +check its documentation, as the following instructions are for the +command line only. + +This step is only necessary if you don't already have a database +set-up (e.g. by your host). In the following examples, 'dba_user' is +an example Oracle user which has the CREATE and GRANT privileges. Use +the appropriate user name for your system. + +Optionally, you can create a new tablespace for your Drupal site +datebase. Log into sqlplus by following command: + + sqlplus dba_user + +sqlplus will prompt for the 'dba_user' database password. At the +sqlplus prompt, enter following command: + + CREATE TABLESPACE tablespace_name + DATAFILE 'file_directory_path' + SIZE filesize AUTOEXTEND ON NEXT extend_size; + +where + + 'tablespace_name' is the name of you new tablespace + 'file_directory_path' is the file location in database server + 'filesize' is the initial file size, e.g. 50K, 1000M. + 'extend_size' is the volumn for extension when data file is full + +First, you must create a new user for your Drupal site. At the +sqlplus prompt, enter the following command: + + CREATE USER username + IDENTIFIED BY "password"; + DEFAULT TABLESPACE tablespace_name; + GRANT CONNECT, RESOURCE TO username; + +where + + 'tablespace_name' is the name of you tablespace + 'username' is the username of your Oracle account + 'password' is the password required for that username + + Note: Unless your database user has all of the privileges listed + above, you will not be able to run Drupal. + +Oracle SPECIAL REQUIREMENTS +--------------------------- + +1. SYSTEM REQUIREMENT + + Oracle driver for Drupal is fully tested with below softwares: + Oracle Database 10g Release 2 (10.2.0.1.0) for Linux x86, + Zend Core for Oracle v.2 Linux x86, + Zend Framework 1.0.0, + PHP Version 5.2.3, + Apache 2.2.3 (Debian) + + You may use something newer than above, but there is no guarantee for + backward compatible. + +2. TABLE PREFIX LIMITATION + + Table prefix are limited in maximum 12 characters. Proved by testing, it + is suggested to use table prefix within 10 characters. Index: INSTALL.pgsql.txt =================================================================== RCS file: INSTALL.pgsql.txt diff -N INSTALL.pgsql.txt --- INSTALL.pgsql.txt 26 Nov 2007 16:36:42 -0000 1.7 +++ /dev/null 1 Jan 1970 00:00:00 -0000 @@ -1,28 +0,0 @@ -// $Id: INSTALL.pgsql.txt,v 1.7 2007/11/26 16:36:42 dries Exp $ - -CREATE THE PostgreSQL DATABASE ------------------------------- - -Note that the database must be created with UTF-8 (Unicode) encoding. - -1. CREATE DATABASE USER - - This step is only necessary if you don't already have a user set up (e.g. - by your host) or you want to create new user for use with Drupal only. The - following command creates a new user named "username" and asks for a - password for that user: - - createuser --pwprompt --encrypted --no-adduser --no-createdb username - - If everything works correctly, you'll see a "CREATE USER" notice. - -2. CREATE THE DRUPAL DATABASE - - This step is only necessary if you don't already have a database set up (e.g. - by your host) or you want to create new database for use with Drupal only. - The following command creates a new database named "databasename", which is - owned by previously created "username": - - createdb --encoding=UNICODE --owner=username databasename - - If everything works correctly, you'll see a "CREATE DATABASE" notice. Index: INSTALL.postgresql.txt =================================================================== RCS file: INSTALL.postgresql.txt diff -N INSTALL.postgresql.txt --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ INSTALL.postgresql.txt 3 Apr 2008 07:55:00 -0000 @@ -0,0 +1,28 @@ +// $Id: INSTALL.postgresql.txt,v 1.1 2007/12/09 17:45:21 hswong3i Exp $ + +CREATE THE PostgreSQL DATABASE +------------------------------ + +Note that the database must be created with UTF-8 (Unicode) encoding. + +1. CREATE DATABASE USER + + This step is only necessary if you don't already have a user set up (e.g. + by your host) or you want to create new user for use with Drupal only. The + following command creates a new user named "username" and asks for a + password for that user: + + createuser --pwprompt --encrypted --no-adduser --no-createdb username + + If everything works correctly, you'll see a "CREATE USER" notice. + +2. CREATE THE DRUPAL DATABASE + + This step is only necessary if you don't already have a database set up (e.g. + by your host) or you want to create new database for use with Drupal only. + The following command creates a new database named "databasename", which is + owned by previously created "username": + + createdb --encoding=UNICODE --owner=username databasename + + If everything works correctly, you'll see a "CREATE DATABASE" notice. Index: INSTALL.txt =================================================================== RCS file: /cvs/drupal/drupal/INSTALL.txt,v retrieving revision 1.61.2.2 diff -u -p -r1.61.2.2 INSTALL.txt --- INSTALL.txt 7 Feb 2008 20:46:56 -0000 1.61.2.2 +++ INSTALL.txt 3 Apr 2008 07:55:00 -0000 @@ -182,7 +182,7 @@ INSTALLATION unexpected problems on an existing site. If you modify the file system path on an existing site, remember to copy all files from the original location to the new location. - + Some administrators suggest making the documentation files, especially CHANGELOG.txt, non-readable so that the exact version of Drupal you are running is slightly more difficult to determine. If you wish to implement Index: MAINTAINERS.siren.txt =================================================================== RCS file: MAINTAINERS.siren.txt diff -N MAINTAINERS.siren.txt --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ MAINTAINERS.siren.txt 3 Apr 2008 07:55:00 -0000 @@ -0,0 +1,24 @@ +// $Id$ + +List of maintainers +-------------------------------------------------------------------------------- + +LEGEND +====== + +- M: the maintainer +- S: status: + "supported" : someone is actually paid to look after this. + "maintained" : someone actually looks after it. + "fixes/patches" : it has a maintainer but they don't have time to + do much other than throw the odd patch in. + "orphan" : no current maintainer, but maybe you could take + the role as you write new code? +- W: website with status or information + +-------------------------------------------------------------------------------- + +Siren +M: Edison Wong +S: maintained +W: http://edin.no-ip.com/project/siren/ Index: README.siren.txt =================================================================== RCS file: README.siren.txt diff -N README.siren.txt --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ README.siren.txt 3 Apr 2008 07:55:00 -0000 @@ -0,0 +1,60 @@ +// $Id$ + +WHAT IS SIREN? +-------------- + +This is my personal project besides Drupal, which try to research the +possibility of other database supporting for Drupal, e.g. Oracle, IBM DB2, +MSSQL, SQLite, etc; on the other hand, I will provide unofficial database +supporting during Drupal-6.x life cycle, and further more contribute the +research progress for Drupal-7.x. + +For more information on Siren visit +the Siren project homepage at http://edin.no-ip.com/project/siren/ + +CURRENT RESEARCH PROGRESS +------------------------- + +Besides official Drupal-6.x mysql, mysqli and pgsql, Siren also provide +pdo_mysql, pdo_pgsql and oci8 database driver supporting. According to the +needs of PDO and Oracle drivers implementation, ALL core queries and some +APIs are hacked for compatibility concern. + +3rd PARTY MODULE HACK HOWTO +--------------------------- + +Based on cross database compatibility concern, Siren come with lots of core +queries hack. Most works are done for you, and it should run across +MySQl/PgSQL/Oracle without any critical problem. + +Anyway, you will also need to apply some 3rd party module. So how to let them +work together with this unofficial core? + +1. ENCLOSE ALL TABLE/COLUMN/CONSTRAINT NAME WITH [] + + Go though you target module, and enclose all table/column/constraint name + with [] syntax, which similar as {} syntax for all table. + + This can be helped by using VI + regex: /{[A-Za-z0-9_]*} + +2. REPLACE ALL '%s' SYNTAX WITH %s + + This is very important for unofficial PDO supporting. + + This can be helped by using VI + regex: :%s/'%s'/%s/gc + +3. REMOVE ANY %% SYNTAX + + PDO don't allow inline % syntax when using with ? placeholder. + + This can be helped by using VI + regex: /%% + +4. UTILIZE ALL DB_* ABSTRACTION IF POSSIBLE + + These abstraction are mainly duel with syntax different among different DB. + +5. USE %s EVEN IT IS AN EMPTY STRING + + Using empty string as placeholder will cause problem among Oracle and + MSSQL. Escape it by using %s. Oracle and MSSQL driver will able to catch + them and replace it as required empty string placeholder internally. Index: UPGRADE.siren.txt =================================================================== RCS file: UPGRADE.siren.txt diff -N UPGRADE.siren.txt --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ UPGRADE.siren.txt 3 Apr 2008 07:55:00 -0000 @@ -0,0 +1,12 @@ +// $Id$ + +UPGRADING FOR SIREN +------------------- + +As a flash new research project, Siren 1.x remove the direct upgrade handling +from Drupal 5.x. You should always use Siren for flash install. + +On the other hand, you may first upgrade your site from Drupal 5.x to +Drupal 6.x, and handle the convert from Drupal 6.x to Siren 1.x manually. +There is no guarantee about this handling, and please backup and do this with +your own risk. Index: install.php =================================================================== RCS file: /cvs/drupal/drupal/install.php,v retrieving revision 1.113.2.2 diff -u -p -r1.113.2.2 install.php --- install.php 8 Feb 2008 22:00:45 -0000 1.113.2.2 +++ install.php 3 Apr 2008 07:55:00 -0000 @@ -136,7 +136,7 @@ function install_main() { */ function install_verify_drupal() { // Read the variable manually using the @ so we don't trigger an error if it fails. - $result = @db_query("SELECT value FROM {variable} WHERE name = '%s'", 'install_task'); + $result = @db_query("SELECT [value] FROM [{variable}] WHERE [name] = %s", 'install_task'); if ($result) { return unserialize(db_result($result)); } @@ -153,16 +153,16 @@ function install_verify_settings() { // We need this because we want to run form_get_errors. include_once './includes/form.inc'; - $url = parse_url(is_array($db_url) ? $db_url['default'] : $db_url); - $db_user = urldecode($url['user']); - $db_pass = isset($url['pass']) ? urldecode($url['pass']) : NULL; - $db_host = urldecode($url['host']); - $db_port = isset($url['port']) ? urldecode($url['port']) : ''; - $db_path = ltrim(urldecode($url['path']), '/'); + $url = isset($db_url['default']) ? $db_url['default'] : $db_url; + $db_user = $url['db_user']; + $db_pass = isset($url['db_pass']) ? $url['db_pass'] : NULL; + $db_host = $url['db_host']; + $db_port = isset($url['db_port']) ? $url['db_port'] : ''; + $db_name = $url['db_name']; $settings_file = './'. conf_path(FALSE, TRUE) .'/settings.php'; $form_state = array(); - _install_settings_form_validate($db_prefix, $db_type, $db_user, $db_pass, $db_host, $db_port, $db_path, $settings_file, $form_state); + _install_settings_form_validate($db_prefix, $db_type, $db_user, $db_pass, $db_host, $db_port, $db_name, $settings_file, $form_state); if (!form_get_errors()) { return TRUE; } @@ -176,12 +176,12 @@ function install_verify_settings() { function install_change_settings($profile = 'default', $install_locale = '') { global $db_url, $db_type, $db_prefix; - $url = parse_url(is_array($db_url) ? $db_url['default'] : $db_url); - $db_user = isset($url['user']) ? urldecode($url['user']) : ''; - $db_pass = isset($url['pass']) ? urldecode($url['pass']) : ''; - $db_host = isset($url['host']) ? urldecode($url['host']) : ''; - $db_port = isset($url['port']) ? urldecode($url['port']) : ''; - $db_path = ltrim(urldecode($url['path']), '/'); + $url = isset($db_url['default']) ? $db_url['default'] : $db_url; + $db_user = isset($url['db_user']) ? $url['db_user'] : ''; + $db_pass = isset($url['db_pass']) ? $url['db_pass'] : ''; + $db_host = isset($url['db_host']) ? $url['db_host'] : ''; + $db_port = isset($url['db_port']) ? $url['db_port'] : ''; + $db_name = $url['db_name']; $conf_path = './'. conf_path(FALSE, TRUE); $settings_file = $conf_path .'/settings.php'; @@ -189,15 +189,15 @@ function install_change_settings($profil include_once './includes/form.inc'; install_task_list('database'); - if ($db_url == 'mysql://username:password@localhost/databasename') { - $db_user = $db_pass = $db_path = ''; + if ($db_url == array()) { + $db_user = $db_pass = $db_name = ''; } elseif (!empty($db_url)) { // Do not install over a configured settings.php. install_already_done_error(); } - $output = drupal_get_form('install_settings_form', $profile, $install_locale, $settings_file, $db_url, $db_type, $db_prefix, $db_user, $db_pass, $db_host, $db_port, $db_path); + $output = drupal_get_form('install_settings_form', $profile, $install_locale, $settings_file, $db_url, $db_type, $db_prefix, $db_user, $db_pass, $db_host, $db_port, $db_name); drupal_set_title(st('Database configuration')); print theme('install_page', $output); exit; @@ -207,7 +207,7 @@ function install_change_settings($profil /** * Form API array definition for install_settings. */ -function install_settings_form(&$form_state, $profile, $install_locale, $settings_file, $db_url, $db_type, $db_prefix, $db_user, $db_pass, $db_host, $db_port, $db_path) { +function install_settings_form(&$form_state, $profile, $install_locale, $settings_file, $db_url, $db_type, $db_prefix, $db_user, $db_pass, $db_host, $db_port, $db_name) { if (empty($db_host)) { $db_host = 'localhost'; } @@ -217,6 +217,15 @@ function install_settings_form(&$form_st if (isset($db_types['mysqli'])) { unset($db_types['mysql']); } + // If both 'mysqli' and 'pdo_mysql' are available, we disable 'mysqli': + if (isset($db_types['pdo_mysql'])) { + unset($db_types['mysqli']); + } + + // If both 'pgsql' and 'pdo_pgsql' are available, we disable 'pgsql': + if (isset($db_types['pdo_pgsql'])) { + unset($db_types['pgsql']); + } if (count($db_types) == 0) { $form['no_db_types'] = array( @@ -239,7 +248,7 @@ function install_settings_form(&$form_st '#default_value' => ($db_type ? $db_type : current($db_types)), '#description' => st('The type of database your @drupal data will be stored in.', array('@drupal' => drupal_install_profile_name())), ); - $db_path_description = st('The name of the database your @drupal data will be stored in. It must exist on your server before @drupal can be installed.', array('@drupal' => drupal_install_profile_name())); + $db_name_description = st('The name of the database your @drupal data will be stored in. It must exist on your server before @drupal can be installed.', array('@drupal' => drupal_install_profile_name())); } else { if (count($db_types) == 1) { @@ -248,19 +257,19 @@ function install_settings_form(&$form_st '#type' => 'hidden', '#value' => $db_types[0], ); - $db_path_description = st('The name of the %db_type database your @drupal data will be stored in. It must exist on your server before @drupal can be installed.', array('%db_type' => $db_types[0], '@drupal' => drupal_install_profile_name())); + $db_name_description = st('The name of the %db_type database your @drupal data will be stored in. It must exist on your server before @drupal can be installed.', array('%db_type' => $db_types[0], '@drupal' => drupal_install_profile_name())); } } // Database name - $form['basic_options']['db_path'] = array( + $form['basic_options']['db_name'] = array( '#type' => 'textfield', '#title' => st('Database name'), - '#default_value' => $db_path, + '#default_value' => $db_name, '#size' => 45, '#maxlength' => 45, '#required' => TRUE, - '#description' => $db_path_description + '#description' => $db_name_description ); // Database username @@ -341,13 +350,13 @@ function install_settings_form(&$form_st */ function install_settings_form_validate($form, &$form_state) { global $db_url; - _install_settings_form_validate($form_state['values']['db_prefix'], $form_state['values']['db_type'], $form_state['values']['db_user'], $form_state['values']['db_pass'], $form_state['values']['db_host'], $form_state['values']['db_port'], $form_state['values']['db_path'], $form_state['values']['settings_file'], $form_state, $form); + _install_settings_form_validate($form_state['values']['db_prefix'], $form_state['values']['db_type'], $form_state['values']['db_user'], $form_state['values']['db_pass'], $form_state['values']['db_host'], $form_state['values']['db_port'], $form_state['values']['db_name'], $form_state['values']['settings_file'], $form_state, $form); } /** * Helper function for install_settings_validate. */ -function _install_settings_form_validate($db_prefix, $db_type, $db_user, $db_pass, $db_host, $db_port, $db_path, $settings_file, &$form_state, $form = NULL) { +function _install_settings_form_validate($db_prefix, $db_type, $db_user, $db_pass, $db_host, $db_port, $db_name, $settings_file, &$form_state, $form = NULL) { global $db_url; // Verify the table prefix @@ -361,8 +370,7 @@ function _install_settings_form_validate // Check database type if (!isset($form)) { - $_db_url = is_array($db_url) ? $db_url['default'] : $db_url; - $db_type = substr($_db_url, 0, strpos($_db_url, '://')); + $db_type = $db_url['db_type']; } $databases = drupal_detect_database_types(); if (!in_array($db_type, $databases)) { @@ -370,7 +378,15 @@ function _install_settings_form_validate } else { // Verify - $db_url = $db_type .'://'. urlencode($db_user) . ($db_pass ? ':'. urlencode($db_pass) : '') .'@'. ($db_host ? urlencode($db_host) : 'localhost') . ($db_port ? ":$db_port" : '') .'/'. urlencode($db_path); + $db_url = array( + 'db_host' => $db_host ? $db_host : 'localhost', + 'db_port' => $db_port ? $db_port : '', + 'db_name' => $db_name, + 'db_user' => $db_user, + 'db_pass' => $db_pass ? $db_pass : '', + 'db_type' => $db_type, + 'db_prefix' => $db_prefix, + ); if (isset($form)) { form_set_value($form['_db_url'], $db_url, $form_state); } @@ -399,10 +415,6 @@ function install_settings_form_submit($f 'value' => $form_state['values']['_db_url'], 'required' => TRUE, ); - $settings['db_prefix'] = array( - 'value' => $form_state['values']['db_prefix'], - 'required' => TRUE, - ); drupal_rewrite_settings($settings); // Continue to install profile step @@ -916,7 +928,7 @@ function install_check_requirements($pro drupal_set_message($message, 'warning'); } } - } + } } /** Index: update.php =================================================================== RCS file: /cvs/drupal/drupal/update.php,v retrieving revision 1.252 diff -u -p -r1.252 update.php --- update.php 3 Feb 2008 18:41:16 -0000 1.252 +++ update.php 3 Apr 2008 07:55:00 -0000 @@ -55,26 +55,26 @@ function db_add_column(&$ret, $table, $c if (array_key_exists('default', $attributes)) { if (is_null($attributes['default'])) { $default_val = 'NULL'; - $default = 'default NULL'; + $default = 'DEFAULT NULL'; } elseif ($attributes['default'] === FALSE) { $default = ''; } else { - $default_val = "$attributes[default]"; - $default = "default $attributes[default]"; + $default_val = $attributes['default']; + $default = "DEFAULT ". $attributes['default']; } } - $ret[] = update_sql("ALTER TABLE {". $table ."} ADD $column $type"); + $ret[] = update_sql("ALTER TABLE [{". $table ."}] ADD [$column] $type"); if (!empty($default)) { - $ret[] = update_sql("ALTER TABLE {". $table ."} ALTER $column SET $default"); + $ret[] = update_sql("ALTER TABLE [{". $table ."}] ALTER [$column] SET $default"); } if (!empty($not_null)) { if (!empty($default)) { - $ret[] = update_sql("UPDATE {". $table ."} SET $column = $default_val"); + $ret[] = update_sql("UPDATE [{". $table ."}] SET [$column] = $default_val"); } - $ret[] = update_sql("ALTER TABLE {". $table ."} ALTER $column SET NOT NULL"); + $ret[] = update_sql("ALTER TABLE [{". $table ."}] ALTER [$column] SET NOT NULL"); } } @@ -111,23 +111,23 @@ function db_change_column(&$ret, $table, if (array_key_exists('default', $attributes)) { if (is_null($attributes['default'])) { $default_val = 'NULL'; - $default = 'default NULL'; + $default = 'DEFAULT NULL'; } elseif ($attributes['default'] === FALSE) { $default = ''; } else { - $default_val = "$attributes[default]"; - $default = "default $attributes[default]"; + $default_val = $attributes['default']; + $default = "DEFAULT ". $attributes['default']; } } - $ret[] = update_sql("ALTER TABLE {". $table ."} RENAME $column TO ". $column ."_old"); - $ret[] = update_sql("ALTER TABLE {". $table ."} ADD $column_new $type"); - $ret[] = update_sql("UPDATE {". $table ."} SET $column_new = ". $column ."_old"); - if ($default) { $ret[] = update_sql("ALTER TABLE {". $table ."} ALTER $column_new SET $default"); } - if ($not_null) { $ret[] = update_sql("ALTER TABLE {". $table ."} ALTER $column_new SET NOT NULL"); } - $ret[] = update_sql("ALTER TABLE {". $table ."} DROP ". $column ."_old"); + $ret[] = update_sql("ALTER TABLE [{". $table ."}] RENAME [$column] TO [". $column ."_old]"); + $ret[] = update_sql("ALTER TABLE [{". $table ."}] ADD [$column_new] $type"); + $ret[] = update_sql("UPDATE [{". $table ."}] SET [$column_new] = [". $column ."_old]"); + if ($default) { $ret[] = update_sql("ALTER TABLE [{". $table ."}] ALTER [$column_new] SET $default"); } + if ($not_null) { $ret[] = update_sql("ALTER TABLE [{". $table ."}] ALTER [$column_new] SET NOT NULL"); } + $ret[] = update_sql("ALTER TABLE [{". $table ."}] DROP [". $column ."_old]"); } /** @@ -428,14 +428,14 @@ function update_create_batch_table() { function update_fix_compatibility() { $ret = array(); $incompatible = array(); - $query = db_query("SELECT name, type, status FROM {system} WHERE status = 1 AND type IN ('module','theme')"); + $query = db_query("SELECT [name], [type], [status] FROM [{system}] WHERE [status] = 1 AND [type] IN ('module', 'theme')"); while ($result = db_fetch_object($query)) { if (update_check_incompatibility($result->name, $result->type)) { $incompatible[] = $result->name; } } if (!empty($incompatible)) { - $ret[] = update_sql("UPDATE {system} SET status = 0 WHERE name IN ('". implode("','", $incompatible) ."')"); + $ret[] = update_sql("UPDATE [{system}] SET [status] = 0 WHERE [name] IN ('". implode("', '", $incompatible) ."')"); } return $ret; } Index: includes/actions.inc =================================================================== RCS file: /cvs/drupal/drupal/includes/actions.inc,v retrieving revision 1.8 diff -u -p -r1.8 actions.inc --- includes/actions.inc 31 Dec 2007 14:51:04 -0000 1.8 +++ includes/actions.inc 3 Apr 2008 07:55:01 -0000 @@ -54,7 +54,7 @@ function actions_do($action_ids, &$objec $where_values = array(); foreach ($action_ids as $action_id) { if (is_numeric($action_id)) { - $where[] = 'OR aid = %d'; + $where[] = 'OR [aid] = %d'; $where_values[] = $action_id; } elseif (isset($available_actions[$action_id])) { @@ -68,7 +68,7 @@ function actions_do($action_ids, &$objec $where_clause = implode(' ', $where); // Strip off leading 'OR '. $where_clause = '('. strstr($where_clause, " ") .')'; - $result_db = db_query('SELECT * FROM {actions} WHERE '. $where_clause, $where_values); + $result_db = db_query('SELECT * FROM [{actions}] WHERE '. $where_clause, $where_values); while ($action = db_fetch_object($result_db)) { $actions[$action->aid] = $action->parameters ? unserialize($action->parameters) : array(); $actions[$action->aid]['callback'] = $action->callback; @@ -93,7 +93,7 @@ function actions_do($action_ids, &$objec else { // If it's a configurable action, retrieve stored parameters. if (is_numeric($action_ids)) { - $action = db_fetch_object(db_query("SELECT * FROM {actions} WHERE aid = %d", $action_ids)); + $action = db_fetch_object(db_query("SELECT * FROM [{actions}] WHERE [aid] = %d", $action_ids)); $function = $action->callback; $context = array_merge($context, unserialize($action->parameters)); $result[$action_ids] = $function($object, $context, $a1, $a2); @@ -177,7 +177,7 @@ function actions_list($reset = FALSE) { */ function actions_get_all_actions() { $actions = array(); - $result = db_query("SELECT * FROM {actions}"); + $result = db_query("SELECT * FROM [{actions}]"); while ($action = db_fetch_object($result)) { $actions[$action->aid] = array( 'callback' => $action->callback, @@ -238,7 +238,7 @@ function actions_function_lookup($hash) } // Must be an instance; must check database. - $aid = db_result(db_query("SELECT aid FROM {actions} WHERE MD5(aid) = '%s' AND parameters != ''", $hash)); + $aid = db_result(db_query("SELECT [aid] FROM [{actions}] WHERE MD5([aid]) = %s AND [parameters] <> %s", $hash, '')); return $aid; } @@ -255,7 +255,7 @@ function actions_synchronize($actions_in $actions_in_code = actions_list(); } $actions_in_db = array(); - $result = db_query("SELECT * FROM {actions} WHERE parameters = ''"); + $result = db_query("SELECT * FROM [{actions}] WHERE [parameters] = %s", ''); while ($action = db_fetch_object($result)) { $actions_in_db[$action->callback] = array('aid' => $action->aid, 'description' => $action->description); } @@ -271,7 +271,7 @@ function actions_synchronize($actions_in } else { // This is a new singleton that we don't have an aid for; assign one. - db_query("INSERT INTO {actions} (aid, type, callback, parameters, description) VALUES ('%s', '%s', '%s', '%s', '%s')", $callback, $array['type'], $callback, '', $array['description']); + db_query("INSERT INTO [{actions}] ([aid], [type], [callback], [parameters], [description]) VALUES (%s, %s, %s, %s, %s)", $callback, $array['type'], $callback, '', $array['description']); watchdog('actions', "Action '%action' added.", array('%action' => filter_xss_admin($array['description']))); } } @@ -284,14 +284,14 @@ function actions_synchronize($actions_in foreach ($actions_in_db as $callback => $array) { $orphaned[] = $callback; - $placeholder[] = "'%s'"; + $placeholder[] = "%s"; } $orphans = implode(', ', $orphaned); if ($delete_orphans) { $placeholders = implode(', ', $placeholder); - $results = db_query("SELECT a.aid, a.description FROM {actions} a WHERE callback IN ($placeholders)", $orphaned); + $results = db_query("SELECT a.[aid], a.[description] FROM [{actions}] a WHERE [callback] IN ($placeholders)", $orphaned); while ($action = db_fetch_object($results)) { actions_delete($action->aid); watchdog('actions', "Removed orphaned action '%action' from database.", array('%action' => filter_xss_admin($action->description))); @@ -325,15 +325,15 @@ function actions_synchronize($actions_in function actions_save($function, $type, $params, $desc, $aid = NULL) { $serialized = serialize($params); if ($aid) { - db_query("UPDATE {actions} SET callback = '%s', type = '%s', parameters = '%s', description = '%s' WHERE aid = %d", $function, $type, $serialized, $desc, $aid); + db_query("UPDATE [{actions}] SET [callback] = %s, [type] = %s, [parameters] = %s, [description] = %s WHERE [aid] = %d", $function, $type, $serialized, $desc, $aid); watchdog('actions', 'Action %action saved.', array('%action' => $desc)); } else { // aid is the callback for singleton actions so we need to keep a // separate table for numeric aids. - db_query('INSERT INTO {actions_aid} VALUES (default)'); + db_query('INSERT INTO [{actions_aid}] VALUES (default)'); $aid = db_last_insert_id('actions_aid', 'aid'); - db_query("INSERT INTO {actions} (aid, callback, type, parameters, description) VALUES (%d, '%s', '%s', '%s', '%s')", $aid, $function, $type, $serialized, $desc); + db_query("INSERT INTO [{actions}] ([aid], [callback], [type], [parameters], [description]) VALUES (%d, %s, %s, %s, %s)", $aid, $function, $type, $serialized, $desc); watchdog('actions', 'Action %action created.', array('%action' => $desc)); } @@ -350,7 +350,7 @@ function actions_save($function, $type, * The appropriate action row from the database as an object. */ function actions_load($aid) { - return db_fetch_object(db_query("SELECT * FROM {actions} WHERE aid = %d", $aid)); + return db_fetch_object(db_query("SELECT * FROM [{actions}] WHERE [aid] = %d", $aid)); } /** @@ -360,6 +360,6 @@ function actions_load($aid) { * integer The ID of the action to delete. */ function actions_delete($aid) { - db_query("DELETE FROM {actions} WHERE aid = %d", $aid); + db_query("DELETE FROM [{actions}] WHERE [aid] = %d", $aid); module_invoke_all('actions_delete', $aid); } Index: includes/batch.inc =================================================================== RCS file: /cvs/drupal/drupal/includes/batch.inc,v retrieving revision 1.14 diff -u -p -r1.14 batch.inc --- includes/batch.inc 20 Dec 2007 11:57:20 -0000 1.14 +++ includes/batch.inc 3 Apr 2008 07:55:01 -0000 @@ -12,7 +12,7 @@ function _batch_page() { $batch =& batch_get(); // Retrieve the current state of batch from db. - if (isset($_REQUEST['id']) && $data = db_result(db_query("SELECT batch FROM {batch} WHERE bid = %d AND token = '%s'", $_REQUEST['id'], drupal_get_token($_REQUEST['id'])))) { + if (isset($_REQUEST['id']) && $data = db_result(db_query("SELECT [batch] FROM [{batch}] WHERE [bid] = %d AND [token] = %s", $_REQUEST['id'], drupal_get_token($_REQUEST['id'])))) { $batch = unserialize($data); } else { @@ -305,7 +305,7 @@ function _batch_finished() { // Cleanup the batch table and unset the global $batch variable. if ($batch['progressive']) { - db_query("DELETE FROM {batch} WHERE bid = %d", $batch['id']); + db_query("DELETE FROM [{batch}] WHERE [bid] = %d", $batch['id']); } $_batch = $batch; $batch = NULL; @@ -349,6 +349,6 @@ function _batch_finished() { */ function _batch_shutdown() { if ($batch = batch_get()) { - db_query("UPDATE {batch} SET batch = '%s' WHERE bid = %d", serialize($batch), $batch['id']); + db_query("UPDATE [{batch}] SET [batch] = %s WHERE [bid] = %d", serialize($batch), $batch['id']); } } Index: includes/bootstrap.inc =================================================================== RCS file: /cvs/drupal/drupal/includes/bootstrap.inc,v retrieving revision 1.206.2.2 diff -u -p -r1.206.2.2 bootstrap.inc --- includes/bootstrap.inc 11 Feb 2008 14:36:21 -0000 1.206.2.2 +++ includes/bootstrap.inc 3 Apr 2008 07:55:01 -0000 @@ -384,7 +384,7 @@ function drupal_get_filename($type, $nam // the database. This is required because this function is called both // before we have a database connection (i.e. during installation) and // when a database connection fails. - elseif (db_is_active() && (($file = db_result(db_query("SELECT filename FROM {system} WHERE name = '%s' AND type = '%s'", $name, $type))) && file_exists($file))) { + elseif (db_is_active() && (($file = db_result(db_query("SELECT [filename] FROM [{system}] WHERE [name] = %s AND [type] = %s", $name, $type))) && file_exists($file))) { $files[$type][$name] = $file; } else { @@ -420,7 +420,7 @@ function variable_init($conf = array()) $variables = $cached->data; } else { - $result = db_query('SELECT * FROM {variable}'); + $result = db_query('SELECT * FROM [{variable}]'); while ($variable = db_fetch_object($result)) { $variables[$variable->name] = unserialize($variable->value); } @@ -463,9 +463,9 @@ function variable_set($name, $value) { global $conf; $serialized_value = serialize($value); - db_query("UPDATE {variable} SET value = '%s' WHERE name = '%s'", $serialized_value, $name); + db_query("UPDATE [{variable}] SET [value] = %s WHERE [name] = %s", $serialized_value, $name); if (!db_affected_rows()) { - @db_query("INSERT INTO {variable} (name, value) VALUES ('%s', '%s')", $name, $serialized_value); + @db_query("INSERT INTO [{variable}] ([name], [value]) VALUES (%s, %s)", $name, $serialized_value); } cache_clear_all('variables', 'cache'); @@ -482,7 +482,7 @@ function variable_set($name, $value) { function variable_del($name) { global $conf; - db_query("DELETE FROM {variable} WHERE name = '%s'", $name); + db_query("DELETE FROM [{variable}] WHERE [name] = %s", $name); cache_clear_all('variables', 'cache'); unset($conf[$name]); @@ -874,13 +874,19 @@ function drupal_get_messages($type = NUL * TRUE if access is denied, FALSE if access is allowed. */ function drupal_is_denied($type, $mask) { - // Because this function is called for every page request, both cached - // and non-cached pages, we tried to optimize it as much as possible. - // We deny access if the only matching records in the {access} table have - // status 0 (deny). If any have status 1 (allow), or if there are no - // matching records, we allow access. - $sql = "SELECT 1 FROM {access} WHERE type = '%s' AND LOWER('%s') LIKE LOWER(mask) AND status = %d"; - return db_result(db_query_range($sql, $type, $mask, 0, 0, 1)) && !db_result(db_query_range($sql, $type, $mask, 1, 0, 1)); + switch ($GLOBALS['db_type']) { + case 'ibm_db2': + case 'pdo_ibm': + return FALSE; + default: + // Because this function is called for every page request, both cached + // and non-cached pages, we tried to optimize it as much as possible. + // We deny access if the only matching records in the {access} table have + // status 0 (deny). If any have status 1 (allow), or if there are no + // matching records, we allow access. + $sql = "SELECT 1 FROM [{access}] WHERE [type] = %s AND LOWER(%s) LIKE LOWER([mask]) AND [status] = %d"; + return db_result(db_query_range($sql, $type, $mask, 0, 0, 1)) && !db_result(db_query_range($sql, $type, $mask, 1, 0, 1)); + } } /** @@ -1078,7 +1084,7 @@ function language_list($field = 'languag // Init language list if (!isset($languages)) { if (variable_get('language_count', 1) > 1 || module_exists('locale')) { - $result = db_query('SELECT * FROM {languages} ORDER BY weight ASC, name ASC'); + $result = db_query('SELECT * FROM [{languages}] ORDER BY [weight] ASC, [name] ASC'); while ($row = db_fetch_object($result)) { $languages['language'][$row->language] = $row; } Index: includes/cache.inc =================================================================== RCS file: /cvs/drupal/drupal/includes/cache.inc,v retrieving revision 1.17 diff -u -p -r1.17 cache.inc --- includes/cache.inc 29 Jan 2008 11:36:06 -0000 1.17 +++ includes/cache.inc 3 Apr 2008 07:55:01 -0000 @@ -20,10 +20,10 @@ function cache_get($cid, $table = 'cache // Reset the variable immediately to prevent a meltdown in heavy load situations. variable_set('cache_flush', 0); // Time to flush old cache data - db_query("DELETE FROM {". $table ."} WHERE expire != %d AND expire <= %d", CACHE_PERMANENT, $cache_flush); + db_query("DELETE FROM [{". $table ."}] WHERE [expire] <> %d AND [expire] <= %d", CACHE_PERMANENT, $cache_flush); } - $cache = db_fetch_object(db_query("SELECT data, created, headers, expire, serialized FROM {". $table ."} WHERE cid = '%s'", $cid)); + $cache = db_fetch_object(db_query("SELECT [data], [created], [headers], [expire], [serialized] FROM [{". $table ."}] WHERE [cid] = %s", $cid)); if (isset($cache->data)) { // If the data is permanent or we're not enforcing a minimum cache lifetime // always return the cached data. @@ -106,9 +106,17 @@ function cache_set($cid, $data, $table = $serialized = 1; } $created = time(); - db_query("UPDATE {". $table ."} SET data = %b, created = %d, expire = %d, headers = '%s', serialized = %d WHERE cid = '%s'", $data, $created, $expire, $headers, $serialized, $cid); + $values = array( + array('field' => 'data', 'placeholder' => '%b', 'data' => $data), + array('field' => 'created', 'placeholder' => '%d', 'data' => $created), + array('field' => 'expire', 'placeholder' => '%d', 'data' => $expire), + array('field' => 'headers', 'placeholder' => "%s", 'data' => $headers), + array('field' => 'serialized', 'placeholder' => '%d', 'data' => $serialized), + ); + db_query_update($table, $values, "[cid] = %s", $cid); if (!db_affected_rows()) { - @db_query("INSERT INTO {". $table ."} (cid, data, created, expire, headers, serialized) VALUES ('%s', %b, %d, %d, '%s', %d)", $cid, $data, $created, $expire, $headers, $serialized); + $values[] = array('field' => 'cid', 'placeholder' => "%s", 'data' => $cid); + db_query_insert($table, $values); } } @@ -157,26 +165,26 @@ function cache_clear_all($cid = NULL, $t else if (time() > ($cache_flush + variable_get('cache_lifetime', 0))) { // Clear the cache for everyone, cache_flush_delay seconds have // passed since the first request to clear the cache. - db_query("DELETE FROM {". $table ."} WHERE expire != %d AND expire < %d", CACHE_PERMANENT, time()); + db_query("DELETE FROM [{". $table ."}] WHERE [expire] <> %d AND [expire] < %d", CACHE_PERMANENT, time()); variable_set('cache_flush', 0); } } else { // No minimum cache lifetime, flush all temporary cache entries now. - db_query("DELETE FROM {". $table ."} WHERE expire != %d AND expire < %d", CACHE_PERMANENT, time()); + db_query("DELETE FROM [{". $table ."}] WHERE [expire] <> %d AND [expire] < %d", CACHE_PERMANENT, time()); } } else { if ($wildcard) { if ($cid == '*') { - db_query("DELETE FROM {". $table ."}"); + db_query("DELETE FROM [{". $table ."}]"); } else { - db_query("DELETE FROM {". $table ."} WHERE cid LIKE '%s%%'", $cid); + db_query("DELETE FROM [{". $table ."}] WHERE [cid] LIKE %s", $cid ."%"); } } else { - db_query("DELETE FROM {". $table ."} WHERE cid = '%s'", $cid); + db_query("DELETE FROM [{". $table ."}] WHERE [cid] = %s", $cid); } } } Index: includes/common.db2.inc =================================================================== RCS file: includes/common.db2.inc diff -N includes/common.db2.inc --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ includes/common.db2.inc 3 Apr 2008 07:55:01 -0000 @@ -0,0 +1,397 @@ + $t('DB2 database'), + 'value' => $version, + ); + + if (version_compare($version, DRUPAL_MINIMUM_DB2) < 0) { + $form['db2']['severity'] = REQUIREMENT_ERROR; + $form['db2']['description'] = $t('Your DB2 Server is too old. Drupal requires at least DB2 %version.', array('%version' => DRUPAL_MINIMUM_DB2)); + } + + return $form; +} + +/** + * Returns the version of the database server currently in use. + * + * @return Database server version + */ +function db_version() { + $banner = db_result(db_query("SELECT SERVICE_LEVEL FROM TABLE (SYSPROC.ENV_GET_INST_INFO()) AS INSTANCEINFO")); + preg_match('/\s*v([0-9.]+)\s*/', $banner, $version); + return array_pop($version); +} + +/** + * Insert a row of record into database. + * + * @param $table + * Table to insert. + * @param $values + * An array containing the insert values. Each element of the array + * should be an associatie array with the following keys: + * - "field": The database field represented in the table column. + * - "placeholder": The placeholder of the table column, using printf() + * syntax. Valid %-modifiers are: %d, %f, %s and %b. + * - "data": The data to insert into the table column. + * @return + * A database query result resource, or FALSE if the query was not + * executed correctly. + */ +function db_query_insert($table, $values) { + $fields = array(); + $placeholders = array(); + $data = array(); + foreach ($values as $value) { + $fields[] = $value['field']; + $placeholders[] = $value['placeholder']; + $data[] = $value['data']; + } + + if (!count($fields)) { + return FALSE; + } + + $query = "INSERT INTO [{". $table ."}] ([". implode('], [', $fields) ."]) VALUES (". implode(', ', $placeholders) .")"; + return db_query($query, $data); +} + +/** + * Update a row of record in database. + * + * @param $table + * Table to update. + * @param $values + * An array containing the update values. Each element of the array + * should be an associatie array with the following keys: + * - "field": The database field represented in the table column. + * - "placeholder": The placeholder of the table column, using printf() + * syntax. Valid %-modifiers are: %d, %f, %s and %b. + * - "data": The data to insert into the table column. + * @param $where_clause + * A string containing an update condition query (where clause). + * @param ... + * A variable number of arguments which are substituted into the query + * WHERE condition, using printf() syntax. Instead of a variable number + * of query arguments, you may also pass a single array containing the + * query arguments. + * + * Valid %-modifiers are: %d, %f and %s. + * + * NOTE: using this syntax will cast NULL and FALSE values to decimal 0, + * and TRUE values to decimal 1. + * + * @return + * A database query result resource, or FALSE if the query was not + * executed correctly. + */ +function db_query_update($table, $values, $where_clause = NULL) { + $args = func_get_args(); + $args = array_slice($args, 3); + if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax + $args = $args[0]; + } + + $fields = array(); + $data = array(); + foreach ($values as $value) { + $fields[] = '['. $value['field'] .'] = '. $value['placeholder']; + $data[] = $value['data']; + } + + if (!count($fields)) { + return FALSE; + } + + $query = "UPDATE [{". $table ."}] SET ". implode(', ', $fields); + if ($where_clause) { + $query .= " WHERE ". $where_clause; + $data = array_merge($data, $args); + } + return db_query($query, $data); +} + +/** + * Delete a row of record from database. + * + * @param $table + * Table to delete. + * @param $where_clause + * A string containing an update condition query (where clause). + * @param ... + * A variable number of arguments which are substituted into the query + * WHERE condition, using printf() syntax. Instead of a variable number + * of query arguments, you may also pass a single array containing the + * query arguments. + * + * Valid %-modifiers are: %d, %f and %s. + * + * NOTE: using this syntax will cast NULL and FALSE values to decimal 0, + * and TRUE values to decimal 1. + * + * @return + * A database query result resource, or FALSE if the query was not + * executed correctly. + */ +function db_query_delete($table, $where_clause = NULL) { + $args = func_get_args(); + $args = array_slice($args, 2); + if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax + $args = $args[0]; + } + + $data = array(); + + $query = "DELETE FROM [{". $table ."}]"; + if ($where_clause) { + $query .= " WHERE ". $where_clause; + $data = $args; + } + return db_query($query, $data); +} + +/** + * Returns the last insert id. This function is thread safe. + * + * @param $table + * The name of the table you inserted into. + * @param $field + * The name of the autoincrement field. + */ +function db_last_insert_id($table, $field) { + return db_result(db_query("SELECT SYSIBM.IDENTITY_VAL_LOCAL() FROM [{". $table ."}]")); +} + +/** + * Runs a limited-range query in the active database. + * + * Use this as a substitute for db_query() when a subset of the query + * is to be returned. + * User-supplied arguments to the query should be passed in as separate + * parameters so that they can be properly escaped to avoid SQL injection + * attacks. + * + * @param $query + * A string containing an SQL query. + * @param ... + * A variable number of arguments which are substituted into the query + * using printf() syntax. Instead of a variable number of query arguments, + * you may also pass a single array containing the query arguments. + * Valid %-modifiers are: %s, %d, %f and %b (binary data, do not enclose + * in ''). + * + * NOTE: use NULL as arguments substitution for %b and %c. This will be + * replaced as corresponding empty LOB value placeholder, based on the + * database specific representation. + * + * NOTE: using this syntax will cast NULL and FALSE values to decimal 0, + * and TRUE values to decimal 1. + * + * @param $from + * The first result row to return. + * @param $count + * The maximum number of result rows to return. + * @return + * A database query result resource, or FALSE if the query was not executed + * correctly. + */ +function db_query_range($query) { + $args = func_get_args(); + $count = array_pop($args); + $from = array_pop($args); + array_shift($args); + + $query = 'SELECT * FROM (SELECT [sub1].*, ROW_NUMBER() OVER() AS [line2] FROM ('. $query .') AS [sub1]) AS [sub2] WHERE [line2] BETWEEN '. $from .' AND '. ($from + $count); + if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax + $args = $args[0]; + } + return db_query($query, $args); +} + +/** + * Runs a SELECT query and stores its results in a temporary table. + * + * Use this as a substitute for db_query() when the results need to stored + * in a temporary table. Temporary tables exist for the duration of the page + * request. + * User-supplied arguments to the query should be passed in as separate parameters + * so that they can be properly escaped to avoid SQL injection attacks. + * + * Note that if you need to know how many results were returned, you should do + * a SELECT COUNT(*) on the temporary table afterwards. db_affected_rows() do + * not give consistent result across different database types in this case. + * + * @param $query + * A string containing a normal SELECT SQL query. + * @param ... + * A variable number of arguments which are substituted into the query + * using printf() syntax. The query arguments can be enclosed in one + * array instead. + * Valid %-modifiers are: %s, %d, %f and %b (binary data, do not enclose + * in ''). + * + * NOTE: use NULL as arguments substitution for %b and %c. This will be + * replaced as corresponding empty LOB value placeholder, based on the + * database specific representation. + * + * NOTE: using this syntax will cast NULL and FALSE values to decimal 0, + * and TRUE values to decimal 1. + * + * @param $table + * The name of the temporary table to select into. This name will not be + * prefixed as there is no risk of collision. + * @return + * A database query result resource, or FALSE if the query was not executed + * correctly. + */ +function db_query_temporary($query) { + $args = func_get_args(); + $tablename = array_pop($args); + array_shift($args); + + $query = 'DECLARE GLOBAL TEMPORARY TABLE ['. $tablename .'] AS ('. $query .') DEFINITION ONLY INCLUDING IDENTITY COLUMN ATTRIBUTES INCLUDING COLUMN DEFAULTS ON COMMIT PRESERVE ROWS NOT LOGGED'; + if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax + $args = $args[0]; + } + return db_query($query, $args); +} + +/** + * Lock a table. + * This function automatically starts a transaction. + */ +function db_lock_table($table) { + db_query('LOCK TABLE [{'. db_escape_table($table) .'}] IN EXCLUSIVE MODE'); +} + +/** + * Unlock all locked tables. + * This function automatically commits a transaction. + */ +function db_unlock_tables() { + db_query('COMMIT'); +} + +/** + * Check if a table exists. + */ +function db_table_exists($table) { + return (bool) db_result(db_query("SELECT COUNT(TABLE_NAME) FROM SYSIBM.TABLES WHERE TABLE_NAME LIKE '{". db_escape_table($table) ."}'")); +} + +/** + * Check if a column exists in the given table. + */ +function db_column_exists($table, $column) { + return (bool) db_result(db_query("SELECT COUNT(COLUMN_NAME) FROM SYSIBM.COLUMNS WHERE TABLE_NAME LIKE '{". db_escape_table($table) ."}' AND COLUMN_NAME LIKE '" . db_escape_table($column) ."'")); +} + +/** + * Wraps the given table.field entry with a DISTINCT(). The wrapper is added to + * the SELECT list entry of the given query and the resulting query is returned. + * This function only applies the wrapper if a DISTINCT doesn't already exist in + * the query. + * + * @param $table Table containing the field to set as DISTINCT + * @param $field Field to set as DISTINCT + * @param $query Query to apply the wrapper to + * @return SQL query with the DISTINCT wrapper surrounding the given table.field. + */ +function db_distinct_field($table, $field, $query) { + $field_to_select = 'DISTINCT (['. $table .'].['. $field .'])'; + // (? %d", $name, ip_address(), time() - 3600)); + $number = db_result(db_query("SELECT COUNT(*) FROM [{flood}] WHERE [event] = %s AND [hostname] = %s AND [timestamp] > %d", $name, ip_address(), time() - 3600)); return ($number < $threshold ? TRUE : FALSE); } @@ -3183,7 +3183,9 @@ function _drupal_initialize_schema($modu **/ function drupal_schema_fields_sql($table, $prefix = NULL) { $schema = drupal_get_schema($table); - $fields = array_keys($schema['fields']); + foreach ($schema['fields'] as $key => $value) { + $fields[] = '['. $key .']'; + } if ($prefix) { $columns = array(); foreach ($fields as $field) { @@ -3208,7 +3210,7 @@ function drupal_schema_fields_sql($table * The object to write. This is a reference, as defaults according to * the schema may be filled in on the object, as well as ID on the serial * type(s). Both array an object types may be passed. - * @param $update + * @param primary_keys * If this is an update, specify the primary keys' field names. It is the * caller's responsibility to know if a record for this object already * exists in the database. If there is only 1 key, you may pass a simple string. @@ -3219,10 +3221,10 @@ function drupal_schema_fields_sql($table * the $table. For example, $object->nid will be populated after inserting * a new node. */ -function drupal_write_record($table, &$object, $update = array()) { - // Standardize $update to an array. - if (is_string($update)) { - $update = array($update); +function drupal_write_record($table, &$object, $primary_keys = array()) { + // Standardize $primary_keys to an array. + if (!is_array($primary_keys)) { + $primary_keys = array($primary_keys); } // Convert to an object if needed. @@ -3239,18 +3241,19 @@ function drupal_write_record($table, &$o return FALSE; } - $fields = $defs = $values = $serials = $placeholders = array(); + $values = array(); + $serials = array(); // Go through our schema, build SQL, and when inserting, fill in defaults for // fields that are not set. foreach ($schema['fields'] as $field => $info) { // Special case -- skip serial types if we are updating. - if ($info['type'] == 'serial' && count($update)) { + if ($info['type'] == 'serial' && count($primary_keys)) { continue; } // For inserts, populate defaults from Schema if not already provided - if (!isset($object->$field) && !count($update) && isset($info['default'])) { + if (!isset($object->$field) && !count($primary_keys) && isset($info['default'])) { $object->$field = $info['default']; } @@ -3263,44 +3266,52 @@ function drupal_write_record($table, &$o // Build arrays for the fields, placeholders, and values in our query. if (isset($object->$field)) { - $fields[] = $field; - $placeholders[] = db_type_placeholder($info['type']); + $value['field'] = $field; + $value['placeholder'] = db_type_placeholder($info['type']); if (empty($info['serialize'])) { - $values[] = $object->$field; + $value['data'] = $object->$field; + } + elseif (!empty($object->$field)) { + $value['data'] = serialize($object->$field); } else { - $values[] = serialize($object->$field); + $value['data'] = ''; } + + $values[] = $value; + } + } + + if (empty($values)) { + // No changes requested. + // If we began with an array, convert back so we don't surprise the caller. + if ($array) { + $object = (array) $object; } + return; } - // Build the SQL. - $query = ''; - if (!count($update)) { - $query = "INSERT INTO {". $table ."} (". implode(', ', $fields) .') VALUES ('. implode(', ', $placeholders) .')'; + // Execute the SQL. + if (!count($primary_keys)) { + $result = db_query_insert($table, $values); $return = SAVED_NEW; } else { - $query = ''; - foreach ($fields as $id => $field) { - if ($query) { - $query .= ', '; + foreach ($primary_keys as $key => $value){ + // $primary_key is NOT in key-value pair format. + if (!isset($schema['fields'][$key]) && isset($schema['fields'][$value])) { + $key = $value; + $value = $object->$key; } - $query .= $field .' = '. $placeholders[$id]; - } - - foreach ($update as $key){ - $conditions[] = "$key = ". db_type_placeholder($schema['fields'][$key]['type']); - $values[] = $object->$key; + $conditions[] = "[$key] = ". db_type_placeholder($schema['fields'][$key]['type']); + $args[] = $value; } - - $query = "UPDATE {". $table ."} SET $query WHERE ". implode(' AND ', $conditions); + $result = db_query_update($table, $values, implode(' AND ', $conditions), $args); $return = SAVED_UPDATED; } - // Execute the SQL. - if (db_query($query, $values)) { + if ($result) { if ($serials) { // Get last insert ids and fill them in. foreach ($serials as $field) { @@ -3320,6 +3331,47 @@ function drupal_write_record($table, &$o } /** + * Drop a record from the database based upon the schema. + * + * @param $table + * The name of the table; this must exist in schema API. + * @param $object + * The object to drop. This is a reference, as defaults according to + * the schema may be filled in on the object, as well as ID on the serial + * type(s). Both array an object types may be passed. + * @param primary_keys + * Specify the primary keys' field names. If there is only 1 key, you may + * pass a simple string. + * @return (boolean) Failure to write a record will return FALSE. Otherwise, + * TRUE is returned. + */ +function drupal_drop_record($table, $object, $primary_keys = array()) { + // Standardize $primary_keys to an array. + if (!is_array($primary_keys)) { + $primary_keys = array($primary_keys); + } + + // Convert to an object if needed. + if ($array = is_array($object)) { + $object = (object) $object; + } + + $schema = drupal_get_schema($table); + if (empty($schema)) { + return FALSE; + } + + // Execute the request. + foreach ($primary_keys as $key){ + $conditions[] = "[$key] = ". db_type_placeholder($schema['fields'][$key]['type']); + $args[] = $object->$key; + } + db_query_delete($table, implode(' AND ', $conditions), $args); + + return SAVED_DELETED; +} + +/** * @} End of "ingroup schemaapi". */ Index: includes/common.mysql.inc =================================================================== RCS file: includes/common.mysql.inc diff -N includes/common.mysql.inc --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ includes/common.mysql.inc 3 Apr 2008 07:55:01 -0000 @@ -0,0 +1,385 @@ + 0) ? "CONCAT($return)" : ''; +} + +/** + * Returns a string that is the equivalent of MySQL IFNULL or Oracle NVL. + * + * @return + * If $expr1 is not NULL, returns $expr1; otherwise it returns $expr2. + */ +function db_if_null($expr1, $expr2) { + return " IFNULL($expr1, $expr2) "; +} + +/** + * Report database status. + */ +function db_status_report($phase) { + $t = get_t(); + + $version = db_version(); + + $form['mysql'] = array( + 'title' => $t('MySQL database'), + 'value' => ($phase == 'runtime') ? l($version, 'admin/reports/status/sql') : $version, + ); + + if (version_compare($version, DRUPAL_MINIMUM_MYSQL) < 0) { + $form['mysql']['severity'] = REQUIREMENT_ERROR; + $form['mysql']['description'] = $t('Your MySQL Server is too old. Drupal requires at least MySQL %version.', array('%version' => DRUPAL_MINIMUM_MYSQL)); + } + + return $form; +} + +/** + * Returns the version of the database server currently in use. + * + * @return Database server version + */ +function db_version() { + global $active_db; + list($version) = explode('-', db_result(db_query("SELECT VERSION();"))); + return $version; +} + +/** + * Insert a row of record into database. + * + * @param $table + * Table to insert. + * @param $values + * An array containing the insert values. Each element of the array + * should be an associatie array with the following keys: + * - "field": The database field represented in the table column. + * - "placeholder": The placeholder of the table column, using printf() + * syntax. Valid %-modifiers are: %d, %f, %s and %b. + * - "data": The data to insert into the table column. + * @return + * A database query result resource, or FALSE if the query was not + * executed correctly. + */ +function db_query_insert($table, $values) { + $fields = array(); + $placeholders = array(); + $data = array(); + foreach ($values as $value) { + $fields[] = $value['field']; + $placeholders[] = $value['placeholder']; + $data[] = $value['data']; + } + + if (!count($fields)) { + return FALSE; + } + + $query = "INSERT INTO [{". $table ."}] ([". implode('], [', $fields) ."]) VALUES (". implode(', ', $placeholders) .")"; + return db_query($query, $data); +} + +/** + * Update a row of record in database. + * + * @param $table + * Table to update. + * @param $values + * An array containing the update values. Each element of the array + * should be an associatie array with the following keys: + * - "field": The database field represented in the table column. + * - "placeholder": The placeholder of the table column, using printf() + * syntax. Valid %-modifiers are: %d, %f, %s and %b. + * - "data": The data to insert into the table column. + * @param $where_clause + * A string containing an update condition query (where clause). + * @param ... + * A variable number of arguments which are substituted into the query + * WHERE condition, using printf() syntax. Instead of a variable number + * of query arguments, you may also pass a single array containing the + * query arguments. + * + * Valid %-modifiers are: %d, %f and %s. + * + * NOTE: using this syntax will cast NULL and FALSE values to decimal 0, + * and TRUE values to decimal 1. + * + * @return + * A database query result resource, or FALSE if the query was not + * executed correctly. + */ +function db_query_update($table, $values, $where_clause = NULL) { + $args = func_get_args(); + $args = array_slice($args, 3); + if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax + $args = $args[0]; + } + + $fields = array(); + $data = array(); + foreach ($values as $value) { + $fields[] = '['. $value['field'] .'] = '. $value['placeholder']; + $data[] = $value['data']; + } + + if (!count($fields)) { + return FALSE; + } + + $query = "UPDATE [{". $table ."}] SET ". implode(', ', $fields); + if ($where_clause) { + $query .= " WHERE ". $where_clause; + $data = array_merge($data, $args); + } + return db_query($query, $data); +} + +/** + * Delete a row of record from database. + * + * @param $table + * Table to delete. + * @param $where_clause + * A string containing an update condition query (where clause). + * @param ... + * A variable number of arguments which are substituted into the query + * WHERE condition, using printf() syntax. Instead of a variable number + * of query arguments, you may also pass a single array containing the + * query arguments. + * + * Valid %-modifiers are: %d, %f and %s. + * + * NOTE: using this syntax will cast NULL and FALSE values to decimal 0, + * and TRUE values to decimal 1. + * + * @return + * A database query result resource, or FALSE if the query was not + * executed correctly. + */ +function db_query_delete($table, $where_clause = NULL) { + $args = func_get_args(); + $args = array_slice($args, 2); + if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax + $args = $args[0]; + } + + $data = array(); + + $query = "DELETE FROM [{". $table ."}]"; + if ($where_clause) { + $query .= " WHERE ". $where_clause; + $data = $args; + } + return db_query($query, $data); +} + +/** + * Returns the last insert id. + * + * @param $table + * The name of the table you inserted into. + * @param $field + * The name of the autoincrement field. + */ +function db_last_insert_id($table, $field) { + return db_result(db_query('SELECT LAST_INSERT_ID()')); +} + +/** + * Runs a limited-range query in the active database. + * + * Use this as a substitute for db_query() when a subset of the query is to be + * returned. + * User-supplied arguments to the query should be passed in as separate parameters + * so that they can be properly escaped to avoid SQL injection attacks. + * + * @param $query + * A string containing an SQL query. + * @param ... + * A variable number of arguments which are substituted into the query + * using printf() syntax. The query arguments can be enclosed in one + * array instead. + * Valid %-modifiers are: %s, %d, %f and %b (binary data, do not enclose + * in ''). + * + * NOTE: using this syntax will cast NULL and FALSE values to decimal 0, + * and TRUE values to decimal 1. + * + * @param $from + * The first result row to return. + * @param $count + * The maximum number of result rows to return. + * @return + * A database query result resource, or FALSE if the query was not executed + * correctly. + */ +function db_query_range($query) { + $args = func_get_args(); + $count = array_pop($args); + $from = array_pop($args); + array_shift($args); + + $query .= ' LIMIT '. (int) $from .', '. (int) $count; + if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax + $args = $args[0]; + } + return db_query($query, $args); +} + +/** + * Runs a SELECT query and stores its results in a temporary table. + * + * Use this as a substitute for db_query() when the results need to stored + * in a temporary table. Temporary tables exist for the duration of the page + * request. + * User-supplied arguments to the query should be passed in as separate parameters + * so that they can be properly escaped to avoid SQL injection attacks. + * + * Note that if you need to know how many results were returned, you should do + * a SELECT COUNT(*) on the temporary table afterwards. db_affected_rows() does + * not give consistent result across different database types in this case. + * + * @param $query + * A string containing a normal SELECT SQL query. + * @param ... + * A variable number of arguments which are substituted into the query + * using printf() syntax. The query arguments can be enclosed in one + * array instead. + * Valid %-modifiers are: %s, %d, %f and %b (binary data, do not enclose + * in ''). + * + * NOTE: using this syntax will cast NULL and FALSE values to decimal 0, + * and TRUE values to decimal 1. + * + * @param $table + * The name of the temporary table to select into. This name will not be + * prefixed as there is no risk of collision. + * @return + * A database query result resource, or FALSE if the query was not executed + * correctly. + */ +function db_query_temporary($query) { + $args = func_get_args(); + $tablename = array_pop($args); + array_shift($args); + + $query = preg_replace('/^SELECT/i', 'CREATE TEMPORARY TABLE '. $tablename .' Engine=HEAP SELECT', $query); + if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax + $args = $args[0]; + } + return db_query($query, $args); +} + +/** + * Lock a table. + */ +function db_lock_table($table) { + db_query('LOCK TABLES [{'. db_escape_table($table) .'}] WRITE'); +} + +/** + * Unlock all locked tables. + */ +function db_unlock_tables() { + db_query('UNLOCK TABLES'); +} + +/** + * Check if a table exists. + */ +function db_table_exists($table) { + return (bool) db_fetch_object(db_query("SHOW TABLES LIKE '{". db_escape_table($table) ."}'")); +} + +/** + * Check if a column exists in the given table. + */ +function db_column_exists($table, $column) { + return (bool) db_fetch_object(db_query("SHOW COLUMNS FROM [{". db_escape_table($table) ."}] LIKE '". db_escape_table($column) ."'")); +} + +/** + * Wraps the given table.field entry with a DISTINCT(). The wrapper is added to + * the SELECT list entry of the given query and the resulting query is returned. + * This function only applies the wrapper if a DISTINCT doesn't already exist in + * the query. + * + * @param $table Table containing the field to set as DISTINCT + * @param $field Field to set as DISTINCT + * @param $query Query to apply the wrapper to + * @return SQL query with the DISTINCT wrapper surrounding the given table.field. + */ +function db_distinct_field($table, $field, $query) { + $field_to_select = 'DISTINCT(['. $table .'].['. $field .'])'; + // (? 30) { + // Try to fetch mapping, if not exists, set it up. + $trim = variable_get('oracle_'. $match, NULL); + if (!$trim) { + // Fetch last counter, and +1 for next mapping. + $count = variable_get('_db_escape_quote', 0) + 1; + variable_set('_db_escape_quote', $count); + // Setup mapping and reverse mapping. + $trim = substr($match, 0, 30 - strlen($count)) . $count; + variable_set('oracle_'. $match, $trim); + variable_set('oracle_'. $trim, $match); + $match = $trim; + } + } + return DB_QUOTE_OPERATOR . $match . DB_QUOTE_OPERATOR; +} + +/** + * Return a portably concatenate strings. + * + * @param ... + * Variable number of string parameters. + * @return + * Portably concatenate strings. + */ +function db_concat() { + $args = func_get_args(); + return implode(DB_CONCAT_OPERATOR, $args); +} + +/** + * Returns a string that is the equivalent of MySQL IFNULL or Oracle NVL. + * + * @return + * If $expr1 is not NULL, returns $expr1; otherwise it returns $expr2. + */ +function db_if_null($expr1, $expr2) { + return " NVL($expr1, $expr2) "; +} + +/** + * Report database status. + */ +function db_status_report($phase) { + $t = get_t(); + + $version = db_version(); + + $form['oracle'] = array( + 'title' => $t('Oracle database'), + 'value' => $version, + ); + + if (version_compare($version, DRUPAL_MINIMUM_ORACLE) < 0) { + $form['oracle']['severity'] = REQUIREMENT_ERROR; + $form['oracle']['description'] = $t('Your Oracle Server is too old. Drupal requires at least Oracle %version.', array('%version' => DRUPAL_MINIMUM_ORACLE)); + } + + return $form; +} + +/** + * Returns the version of the database server currently in use. + * + * @return Database server version + */ +function db_version() { + $banner = db_result(db_query('SELECT BANNER FROM SYS.V_$VERSION')); + preg_match('/\s([0-9.]+)\s/', $banner, $version); + return array_pop($version); +} + +/** + * Insert a row of record into database. + * + * @param $table + * Table to insert. + * @param $values + * An array containing the insert values. Each element of the array + * should be an associatie array with the following keys: + * - "field": The database field represented in the table column. + * - "placeholder": The placeholder of the table column, using printf() + * syntax. Valid %-modifiers are: %d, %f, %s and %b. + * - "data": The data to insert into the table column. + * @return + * A database query result resource, or FALSE if the query was not + * executed correctly. + */ +function db_query_insert($table, $values) { + $fields = array(); + $placeholders = array(); + $args = array(); + $lob_fields = array(); + $lob_placeholders = array(); + $lob_args = array(); + foreach ($values as $value) { + $fields[] = $value['field']; + switch ($value['placeholder']) { + case '%b': + $placeholders[] = 'EMPTY_BLOB()'; + $lob_fields[] = $value['field']; + $lob_placeholders[] = $value['placeholder']; + $lob_args[] = $value['data']; + break; + case '%c': + $placeholders[] = 'EMPTY_CLOB()'; + $lob_fields[] = $value['field']; + $lob_placeholders[] = $value['placeholder']; + $lob_args[] = $value['data']; + break; + default: + $placeholders[] = $value['placeholder']; + $args[] = $value['data']; + } + } + + $query = "INSERT INTO [{". $table ."}] ([". implode('], [', $fields) ."]) VALUES (". implode(', ', $placeholders) .")"; + if (count($lob_fields)) { + $query .= " RETURNING [". implode('], [', $lob_fields) ."] INTO ". implode(', ', $lob_placeholders); + $args = array_merge($args, $lob_args); + } + return db_query($query, $args); +} + +/** + * Update a row of record in database. + * + * @param $table + * Table to update. + * @param $values + * An array containing the update values. Each element of the array + * should be an associatie array with the following keys: + * - "field": The database field represented in the table column. + * - "placeholder": The placeholder of the table column, using printf() + * syntax. Valid %-modifiers are: %d, %f, %s and %b. + * - "data": The data to insert into the table column. + * @param $where_clause + * A string containing an update condition query (where clause). + * @param ... + * A variable number of arguments which are substituted into the query + * WHERE condition, using printf() syntax. Instead of a variable number + * of query arguments, you may also pass a single array containing the + * query arguments. + * + * Valid %-modifiers are: %d, %f and %s. + * + * NOTE: using this syntax will cast NULL and FALSE values to decimal 0, + * and TRUE values to decimal 1. + * + * @return + * A database query result resource, or FALSE if the query was not + * executed correctly. + */ +function db_query_update($table, $values, $where_clause = NULL) { + global $active_db, $last_result, $queries; + + $where_args = func_get_args(); + $where_args = array_slice($where_args, 3); + if (isset($where_args[0]) and is_array($where_args[0])) { // 'All arguments in one array' syntax + $where_args = $where_args[0]; + } + + $fields = array(); + $args = array(); + $lob_fields = array(); + $lob_placeholders = array(); + $lob_args = array(); + foreach ($values as $value) { + switch ($value['placeholder']) { + case '%b': + $fields[] = '['. $value['field'] .'] = EMPTY_BLOB()'; + $lob_fields[] = $value['field']; + $lob_placeholders[] = $value['placeholder']; + $lob_args[] = $value['data']; + break; + case '%c': + $fields[] = '['. $value['field'] .'] = EMPTY_CLOB()'; + $lob_fields[] = $value['field']; + $lob_placeholders[] = $value['placeholder']; + $lob_args[] = $value['data']; + break; + default: + $fields[] = '['. $value['field'] .'] = '. $value['placeholder']; + $args[] = $value['data']; + } + } + + $query = "UPDATE [{". $table ."}] SET ". implode(', ', $fields); + if ($where_clause) { + $query .= " WHERE ". $where_clause; + $args = array_merge($args, $where_args); + } + if (count($lob_fields)) { + $query .= " RETURNING [". implode('], [', $lob_fields) ."] INTO ". implode(', ', $lob_placeholders); + $args = array_merge($args, $lob_args); + } + return db_query($query, $args); +} + +/** + * Delete a row of record from database. + * + * @param $table + * Table to delete. + * @param $where_clause + * A string containing an update condition query (where clause). + * @param ... + * A variable number of arguments which are substituted into the query + * WHERE condition, using printf() syntax. Instead of a variable number + * of query arguments, you may also pass a single array containing the + * query arguments. + * + * Valid %-modifiers are: %d, %f and %s. + * + * NOTE: using this syntax will cast NULL and FALSE values to decimal 0, + * and TRUE values to decimal 1. + * + * @return + * A database query result resource, or FALSE if the query was not + * executed correctly. + */ +function db_query_delete($table, $where_clause = NULL) { + $args = func_get_args(); + $args = array_slice($args, 2); + if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax + $args = $args[0]; + } + + $query['query'] = "DELETE FROM [{". $table ."}]"; + if ($where_clause) { + $query['query'] .= " WHERE ". $where_clause; + } + return db_query($query, $args); +} + +/** + * Returns the last insert id. This function is thread safe. + * + * @param $table + * The name of the table you inserted into. + * @param $field + * The name of the autoincrement field. + */ +function db_last_insert_id($table, $field) { + return db_result(db_query("SELECT [seq_{". $table ."}_" . $field ."].CURRVAL FROM DUAL")); +} + +/** + * Runs a limited-range query in the active database. + * + * Use this as a substitute for db_query() when a subset of the query + * is to be returned. + * User-supplied arguments to the query should be passed in as separate + * parameters so that they can be properly escaped to avoid SQL injection + * attacks. + * + * @param $query + * A string containing an SQL query. + * @param ... + * A variable number of arguments which are substituted into the query + * using printf() syntax. Instead of a variable number of query arguments, + * you may also pass a single array containing the query arguments. + * Valid %-modifiers are: %s, %d, %f and %b (binary data, do not enclose + * in ''). + * + * NOTE: use NULL as arguments substitution for %b and %c. This will be + * replaced as corresponding empty LOB value placeholder, based on the + * database specific representation. + * + * NOTE: using this syntax will cast NULL and FALSE values to decimal 0, + * and TRUE values to decimal 1. + * + * @param $from + * The first result row to return. + * @param $count + * The maximum number of result rows to return. + * @return + * A database query result resource, or FALSE if the query was not executed + * correctly. + */ +function db_query_range($query) { + $args = func_get_args(); + $count = array_pop($args); + $from = array_pop($args); + array_shift($args); + + $query = 'SELECT * FROM (SELECT [sub1].*, ROWNUM AS [line2] FROM ('. $query .') [sub1]) WHERE [line2] BETWEEN '. ($from + 1) .' AND '. ($from + $count); + if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax + $args = $args[0]; + } + return db_query($query, $args); +} + +/** + * Runs a SELECT query and stores its results in a temporary table. + * + * Use this as a substitute for db_query() when the results need to stored + * in a temporary table. Temporary tables exist for the duration of the page + * request. + * User-supplied arguments to the query should be passed in as separate parameters + * so that they can be properly escaped to avoid SQL injection attacks. + * + * Note that if you need to know how many results were returned, you should do + * a SELECT COUNT(*) on the temporary table afterwards. db_affected_rows() do + * not give consistent result across different database types in this case. + * + * @param $query + * A string containing a normal SELECT SQL query. + * @param ... + * A variable number of arguments which are substituted into the query + * using printf() syntax. The query arguments can be enclosed in one + * array instead. + * Valid %-modifiers are: %s, %d, %f and %b (binary data, do not enclose + * in ''). + * + * NOTE: use NULL as arguments substitution for %b and %c. This will be + * replaced as corresponding empty LOB value placeholder, based on the + * database specific representation. + * + * NOTE: using this syntax will cast NULL and FALSE values to decimal 0, + * and TRUE values to decimal 1. + * + * @param $table + * The name of the temporary table to select into. This name will not be + * prefixed as there is no risk of collision. + * @return + * A database query result resource, or FALSE if the query was not executed + * correctly. + */ +function db_query_temporary($query) { + $args = func_get_args(); + $tablename = array_pop($args); + array_shift($args); + + $query = preg_replace('/^SELECT/i', 'CREATE GLOBAL TEMPORARY TABLE ['. $tablename .'] ON COMMIT PRESERVE ROWS AS SELECT', $query); + if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax + $args = $args[0]; + } + return db_query($query, $args); +} + +/** + * Lock a table. + * This function automatically starts a transaction. + */ +function db_lock_table($table) { + db_query('LOCK TABLE [{'. db_escape_table($table) .'}] IN EXCLUSIVE MODE'); +} + +/** + * Unlock all locked tables. + * This function automatically commits a transaction. + */ +function db_unlock_tables() { + db_query('COMMIT'); +} + +/** + * Check if a table exists. + */ +function db_table_exists($table) { + return db_result(db_query("SELECT COUNT(TABLE_NAME) FROM USER_TABLES WHERE TABLE_NAME LIKE '{". db_escape_table($table) ."}'")) ? TRUE : FALSE; +} + +/** + * Check if a column exists in the given table. + */ +function db_column_exists($table, $column) { + return db_result(db_query("SELECT COUNT(COLUMN_NAME) FROM USER_TAB_COLS WHERE TABLE_NAME LIKE '{". db_escape_table($table) ."}' AND COLUMN_NAME LIKE '". db_escape_table($column) ."'")) ? TRUE : FALSE; +} + +/** + * Check if constraint exists in the given table. + */ +function db_constraint_exists($table, $fields) { + $queries = array(); + foreach ($fields as $key => $value) { + $queries[] = "SELECT CONSTRAINT_NAME FROM USER_CONS_COLUMNS WHERE TABLE_NAME LIKE '{". db_escape_table($table) ."}' AND COLUMN_NAME LIKE '". db_escape_table($value) ."'"; + } + return db_result(db_query(implode(' INTERSECT ', $queries))) ? TRUE : FALSE; +} + +/** + * Wraps the given table.field entry with a DISTINCT(). The wrapper is added to + * the SELECT list entry of the given query and the resulting query is returned. + * This function only applies the wrapper if a DISTINCT doesn't already exist in + * the query. + * + * @param $table Table containing the field to set as DISTINCT + * @param $field Field to set as DISTINCT + * @param $query Query to apply the wrapper to + * @return SQL query with the DISTINCT wrapper surrounding the given table.field. + */ +function db_distinct_field($table, $field, $query) { + $field_to_select = 'DISTINCT (['. $table .'].['. $field .'])'; + // (? $t('PostgreSQL database'), + 'value' => $version, + ); + + if (version_compare($version, DRUPAL_MINIMUM_POSTGRESQL) < 0) { + $form['postgresql']['severity'] = REQUIREMENT_ERROR; + $form['postgresql']['description'] = $t('Your PostgreSQL Server is too old. Drupal requires at least PostgreSQL %version.', array('%version' => DRUPAL_MINIMUM_POSTGRESQL)); + } + + return $form; +} + +/** + * Returns the version of the database server currently in use. + * + * @return Database server version + */ +function db_version() { + return db_result(db_query("SHOW SERVER_VERSION")); +} + +/** + * Insert a row of record into database. + * + * @param $table + * Table to insert. + * @param $values + * An array containing the insert values. Each element of the array + * should be an associatie array with the following keys: + * - "field": The database field represented in the table column. + * - "placeholder": The placeholder of the table column, using printf() + * syntax. Valid %-modifiers are: %d, %f, %s and %b. + * - "data": The data to insert into the table column. + * @return + * A database query result resource, or FALSE if the query was not + * executed correctly. + */ +function db_query_insert($table, $values) { + $fields = array(); + $placeholders = array(); + $data = array(); + foreach ($values as $value) { + $fields[] = $value['field']; + $placeholders[] = $value['placeholder']; + $data[] = $value['data']; + } + + if (!count($fields)) { + return FALSE; + } + + $query = "INSERT INTO [{". $table ."}] ([". implode('], [', $fields) ."]) VALUES (". implode(', ', $placeholders) .")"; + return db_query($query, $data); +} + +/** + * Update a row of record in database. + * + * @param $table + * Table to update. + * @param $values + * An array containing the update values. Each element of the array + * should be an associatie array with the following keys: + * - "field": The database field represented in the table column. + * - "placeholder": The placeholder of the table column, using printf() + * syntax. Valid %-modifiers are: %d, %f, %s and %b. + * - "data": The data to insert into the table column. + * @param $where_clause + * A string containing an update condition query (where clause). + * @param ... + * A variable number of arguments which are substituted into the query + * WHERE condition, using printf() syntax. Instead of a variable number + * of query arguments, you may also pass a single array containing the + * query arguments. + * + * Valid %-modifiers are: %d, %f and %s. + * + * NOTE: using this syntax will cast NULL and FALSE values to decimal 0, + * and TRUE values to decimal 1. + * + * @return + * A database query result resource, or FALSE if the query was not + * executed correctly. + */ +function db_query_update($table, $values, $where_clause = NULL) { + $args = func_get_args(); + $args = array_slice($args, 3); + if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax + $args = $args[0]; + } + + $fields = array(); + $data = array(); + foreach ($values as $value) { + $fields[] = '['. $value['field'] .'] = '. $value['placeholder']; + $data[] = $value['data']; + } + + if (!count($fields)) { + return FALSE; + } + + $query = "UPDATE [{". $table ."}] SET ". implode(', ', $fields); + if ($where_clause) { + $query .= " WHERE ". $where_clause; + $data = array_merge($data, $args); + } + return db_query($query, $data); +} + +/** + * Delete a row of record from database. + * + * @param $table + * Table to delete. + * @param $where_clause + * A string containing an update condition query (where clause). + * @param ... + * A variable number of arguments which are substituted into the query + * WHERE condition, using printf() syntax. Instead of a variable number + * of query arguments, you may also pass a single array containing the + * query arguments. + * + * Valid %-modifiers are: %d, %f and %s. + * + * NOTE: using this syntax will cast NULL and FALSE values to decimal 0, + * and TRUE values to decimal 1. + * + * @return + * A database query result resource, or FALSE if the query was not + * executed correctly. + */ +function db_query_delete($table, $where_clause = NULL) { + $args = func_get_args(); + $args = array_slice($args, 2); + if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax + $args = $args[0]; + } + + $data = array(); + + $query = "DELETE FROM [{". $table ."}]"; + if ($where_clause) { + $query .= " WHERE ". $where_clause; + $data = $args; + } + return db_query($query, $data); +} + +/** + * Returns the last insert id. This function is thread safe. + * + * @param $table + * The name of the table you inserted into. + * @param $field + * The name of the autoincrement field. + */ +function db_last_insert_id($table, $field) { + return db_result(db_query("SELECT CURRVAL('{". db_escape_table($table) ."}_". db_escape_table($field) ."_seq')")); +} + +/** + * Runs a limited-range query in the active database. + * + * Use this as a substitute for db_query() when a subset of the query + * is to be returned. + * User-supplied arguments to the query should be passed in as separate + * parameters so that they can be properly escaped to avoid SQL injection + * attacks. + * + * @param $query + * A string containing an SQL query. + * @param ... + * A variable number of arguments which are substituted into the query + * using printf() syntax. Instead of a variable number of query arguments, + * you may also pass a single array containing the query arguments. + * Valid %-modifiers are: %s, %d, %f and %b (binary data, do not enclose + * in ''). + * + * NOTE: using this syntax will cast NULL and FALSE values to decimal 0, + * and TRUE values to decimal 1. + * + * @param $from + * The first result row to return. + * @param $count + * The maximum number of result rows to return. + * @return + * A database query result resource, or FALSE if the query was not executed + * correctly. + */ +function db_query_range($query) { + $args = func_get_args(); + $count = array_pop($args); + $from = array_pop($args); + array_shift($args); + + $query .= ' LIMIT '. (int) $count .' OFFSET '. (int) $from; + if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax + $args = $args[0]; + } + return db_query($query, $args); +} + +/** + * Runs a SELECT query and stores its results in a temporary table. + * + * Use this as a substitute for db_query() when the results need to stored + * in a temporary table. Temporary tables exist for the duration of the page + * request. + * User-supplied arguments to the query should be passed in as separate parameters + * so that they can be properly escaped to avoid SQL injection attacks. + * + * Note that if you need to know how many results were returned, you should do + * a SELECT COUNT(*) on the temporary table afterwards. db_affected_rows() does + * not give consistent result across different database types in this case. + * + * @param $query + * A string containing a normal SELECT SQL query. + * @param ... + * A variable number of arguments which are substituted into the query + * using printf() syntax. The query arguments can be enclosed in one + * array instead. + * Valid %-modifiers are: %s, %d, %f and %b (binary data, do not enclose + * in ''). + * + * NOTE: using this syntax will cast NULL and FALSE values to decimal 0, + * and TRUE values to decimal 1. + * + * @param $table + * The name of the temporary table to select into. This name will not be + * prefixed as there is no risk of collision. + * @return + * A database query result resource, or FALSE if the query was not executed + * correctly. + */ +function db_query_temporary($query) { + $args = func_get_args(); + $tablename = array_pop($args); + array_shift($args); + + $query = preg_replace('/^SELECT/i', 'CREATE TEMPORARY TABLE '. $tablename .' AS SELECT', $query); + if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax + $args = $args[0]; + } + return db_query($query, $args); +} + +/** + * Lock a table. + * This function automatically starts a transaction. + */ +function db_lock_table($table) { + db_query('LOCK TABLE [{'. db_escape_table($table) .'}] IN EXCLUSIVE MODE'); +} + +/** + * Unlock all locked tables. + * This function automatically commits a transaction. + */ +function db_unlock_tables() { + db_query('COMMIT'); +} + +/** + * Check if a table exists. + */ +function db_table_exists($table) { + return (bool) db_result(db_query("SELECT COUNT(*) FROM [pg_class] WHERE [relname] = '{". db_escape_table($table) ."}'")); +} + +/** + * Check if a column exists in the given table. + */ +function db_column_exists($table, $column) { + return (bool) db_result(db_query("SELECT COUNT([pg_attribute].[attname]) FROM [pg_class], [pg_attribute] WHERE [pg_attribute].[attrelid] = [pg_class].[oid] AND [pg_class].[relname] = '{". db_escape_table($table) ."}' AND [attname] = '". db_escape_table($column) ."'")); +} + +/** + * Wraps the given table.field entry with a DISTINCT(). The wrapper is added to + * the SELECT list entry of the given query and the resulting query is returned. + * This function only applies the wrapper if a DISTINCT doesn't already exist in + * the query. + * + * @param $table Table containing the field to set as DISTINCT + * @param $field Field to set as DISTINCT + * @param $query Query to apply the wrapper to + * @return SQL query with the DISTINCT wrapper surrounding the given table.field. + */ +function db_distinct_field($table, $field, $query) { + $field_to_select = 'DISTINCT ON (['. $table .'].['. $field ."]) [$table].[$field]"; + // (?PostgreSQL documentation.', array('%encoding' => $encoding, '@url' => 'http://www.postgresql.org/docs/7.4/interactive/multibyte.html')), 'status'); + } +} + +/** + * @} End of "ingroup database". + */ Index: includes/common.sqlite.inc =================================================================== RCS file: includes/common.sqlite.inc diff -N includes/common.sqlite.inc --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ includes/common.sqlite.inc 3 Apr 2008 07:55:01 -0000 @@ -0,0 +1,393 @@ + $t('SQLite database'), + 'value' => $version, + ); + + if (version_compare($version, DRUPAL_MINIMUM_SQLITE) < 0) { + $form['sqlite']['severity'] = REQUIREMENT_ERROR; + $form['sqlite']['description'] = $t('Your SQLite Server is too old. Drupal requires at least SQLite %version.', array('%version' => DRUPAL_MINIMUM_SQLITE)); + } + + return $form; +} + +/** + * Returns the version of the database server currently in use. + * + * @return Database server version + */ +function db_version() { + return db_result(db_query("SELECT SQLITE_VERSION()")); +} + +/** + * Insert a row of record into database. + * + * @param $table + * Table to insert. + * @param $values + * An array containing the insert values. Each element of the array + * should be an associatie array with the following keys: + * - "field": The database field represented in the table column. + * - "placeholder": The placeholder of the table column, using printf() + * syntax. Valid %-modifiers are: %d, %f, %s and %b. + * - "data": The data to insert into the table column. + * @return + * A database query result resource, or FALSE if the query was not + * executed correctly. + */ +function db_query_insert($table, $values) { + $fields = array(); + $placeholders = array(); + $data = array(); + foreach ($values as $value) { + $fields[] = $value['field']; + $placeholders[] = $value['placeholder']; + $data[] = $value['data']; + } + + if (!count($fields)) { + return FALSE; + } + + $query = "INSERT INTO [{". $table ."}] ([". implode('], [', $fields) ."]) VALUES (". implode(', ', $placeholders) .")"; + return db_query($query, $data); +} + +/** + * Update a row of record in database. + * + * @param $table + * Table to update. + * @param $values + * An array containing the update values. Each element of the array + * should be an associatie array with the following keys: + * - "field": The database field represented in the table column. + * - "placeholder": The placeholder of the table column, using printf() + * syntax. Valid %-modifiers are: %d, %f, %s and %b. + * - "data": The data to insert into the table column. + * @param $where_clause + * A string containing an update condition query (where clause). + * @param ... + * A variable number of arguments which are substituted into the query + * WHERE condition, using printf() syntax. Instead of a variable number + * of query arguments, you may also pass a single array containing the + * query arguments. + * + * Valid %-modifiers are: %d, %f and %s. + * + * NOTE: using this syntax will cast NULL and FALSE values to decimal 0, + * and TRUE values to decimal 1. + * + * @return + * A database query result resource, or FALSE if the query was not + * executed correctly. + */ +function db_query_update($table, $values, $where_clause = NULL) { + $args = func_get_args(); + $args = array_slice($args, 3); + if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax + $args = $args[0]; + } + + $fields = array(); + $data = array(); + foreach ($values as $value) { + $fields[] = '['. $value['field'] .'] = '. $value['placeholder']; + $data[] = $value['data']; + } + + if (!count($fields)) { + return FALSE; + } + + $query = "UPDATE [{". $table ."}] SET ". implode(', ', $fields); + if ($where_clause) { + $query .= " WHERE ". $where_clause; + $data = array_merge($data, $args); + } + return db_query($query, $data); +} + +/** + * Delete a row of record from database. + * + * @param $table + * Table to delete. + * @param $where_clause + * A string containing an update condition query (where clause). + * @param ... + * A variable number of arguments which are substituted into the query + * WHERE condition, using printf() syntax. Instead of a variable number + * of query arguments, you may also pass a single array containing the + * query arguments. + * + * Valid %-modifiers are: %d, %f and %s. + * + * NOTE: using this syntax will cast NULL and FALSE values to decimal 0, + * and TRUE values to decimal 1. + * + * @return + * A database query result resource, or FALSE if the query was not + * executed correctly. + */ +function db_query_delete($table, $where_clause = NULL) { + $args = func_get_args(); + $args = array_slice($args, 2); + if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax + $args = $args[0]; + } + + $data = array(); + + $query = "DELETE FROM [{". $table ."}]"; + if ($where_clause) { + $query .= " WHERE ". $where_clause; + $data = $args; + } + return db_query($query, $data); +} + +/** + * Returns the last insert id. This function is thread safe. + * + * @param $table + * The name of the table you inserted into. + * @param $field + * The name of the autoincrement field. + */ +function db_last_insert_id($table, $field) { + return db_result(db_query("SELECT LAST_INSERT_ROWID()")); +} + +/** + * Runs a limited-range query in the active database. + * + * Use this as a substitute for db_query() when a subset of the query + * is to be returned. + * User-supplied arguments to the query should be passed in as separate + * parameters so that they can be properly escaped to avoid SQL injection + * attacks. + * + * @param $query + * A string containing an SQL query. + * @param ... + * A variable number of arguments which are substituted into the query + * using printf() syntax. Instead of a variable number of query arguments, + * you may also pass a single array containing the query arguments. + * Valid %-modifiers are: %s, %d, %f and %b (binary data, do not enclose + * in ''). + * + * NOTE: using this syntax will cast NULL and FALSE values to decimal 0, + * and TRUE values to decimal 1. + * + * @param $from + * The first result row to return. + * @param $count + * The maximum number of result rows to return. + * @return + * A database query result resource, or FALSE if the query was not executed + * correctly. + */ +function db_query_range($query) { + $args = func_get_args(); + $count = array_pop($args); + $from = array_pop($args); + array_shift($args); + + $query .= ' LIMIT '. (int) $count .' OFFSET '. (int) $from; + if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax + $args = $args[0]; + } + return db_query($query, $args); +} + +/** + * Runs a SELECT query and stores its results in a temporary table. + * + * Use this as a substitute for db_query() when the results need to stored + * in a temporary table. Temporary tables exist for the duration of the page + * request. + * User-supplied arguments to the query should be passed in as separate parameters + * so that they can be properly escaped to avoid SQL injection attacks. + * + * Note that if you need to know how many results were returned, you should do + * a SELECT COUNT(*) on the temporary table afterwards. db_affected_rows() does + * not give consistent result across different database types in this case. + * + * @param $query + * A string containing a normal SELECT SQL query. + * @param ... + * A variable number of arguments which are substituted into the query + * using printf() syntax. The query arguments can be enclosed in one + * array instead. + * Valid %-modifiers are: %s, %d, %f and %b (binary data, do not enclose + * in ''). + * + * NOTE: using this syntax will cast NULL and FALSE values to decimal 0, + * and TRUE values to decimal 1. + * + * @param $table + * The name of the temporary table to select into. This name will not be + * prefixed as there is no risk of collision. + * @return + * A database query result resource, or FALSE if the query was not executed + * correctly. + */ +function db_query_temporary($query) { + $args = func_get_args(); + $tablename = array_pop($args); + array_shift($args); + + $query = preg_replace('/^SELECT/i', 'CREATE TEMPORARY TABLE '. $tablename .' AS SELECT', $query); + if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax + $args = $args[0]; + } + return db_query($query, $args); +} + +/** + * Lock a table. + * This function automatically starts a transaction. + */ +function db_lock_table($table) { + db_query('BEGIN'); +} + +/** + * Unlock all locked tables. + * This function automatically commits a transaction. + */ +function db_unlock_tables() { + db_query('COMMIT'); +} + +/** + * Check if a table exists. + */ +function db_table_exists($table) { + return (bool) db_result(db_query("SELECT COUNT(*) FROM SQLITE_MASTER WHERE TBL_NAME LIKE '{". db_escape_table($table) ."}'")); +} + +/** + * Check if a column exists in the given table. + */ +function db_column_exists($table, $column) { + $result = db_query("PRAGMA TABLE_INFO('{". db_escape_table($table) ."}')"); + while ($column = db_fetch_array($result)) { + if ($column['name'] == $column) { + return TRUE; + } + } + return FALSE; +} + +/** + * Wraps the given table.field entry with a DISTINCT(). The wrapper is added to + * the SELECT list entry of the given query and the resulting query is returned. + * This function only applies the wrapper if a DISTINCT doesn't already exist in + * the query. + * + * @param $table Table containing the field to set as DISTINCT + * @param $field Field to set as DISTINCT + * @param $query Query to apply the wrapper to + * @return SQL query with the DISTINCT wrapper surrounding the given table.field. + */ +function db_distinct_field($table, $field, $query) { + $field_to_select = 'DISTINCT ON (['. $table .'].['. $field ."]) [$table].[$field]"; + // (? $field) { - $sql .= _db_create_field_sql($field_name, _db_process_field($field)) .", \n"; - } - - // Process keys & indexes. - $keys = _db_create_keys_sql($table); - if (count($keys)) { - $sql .= implode(", \n", $keys) .", \n"; - } - - // Remove the last comma and space. - $sql = substr($sql, 0, -3) ."\n) "; - - $sql .= $table['mysql_suffix']; - - return array($sql); -} - -function _db_create_keys_sql($spec) { - $keys = array(); - - if (!empty($spec['primary key'])) { - $keys[] = 'PRIMARY KEY ('. _db_create_key_sql($spec['primary key']) .')'; - } - if (!empty($spec['unique keys'])) { - foreach ($spec['unique keys'] as $key => $fields) { - $keys[] = 'UNIQUE KEY '. $key .' ('. _db_create_key_sql($fields) .')'; - } - } - if (!empty($spec['indexes'])) { - foreach ($spec['indexes'] as $index => $fields) { - $keys[] = 'INDEX '. $index .' ('. _db_create_key_sql($fields) .')'; - } - } - - return $keys; -} - -function _db_create_key_sql($fields) { - $ret = array(); - foreach ($fields as $field) { - if (is_array($field)) { - $ret[] = $field[0] .'('. $field[1] .')'; - } - else { - $ret[] = $field; - } - } - return implode(', ', $ret); -} - -/** - * Set database-engine specific properties for a field. - * - * @param $field - * A field description array, as specified in the schema documentation. - */ -function _db_process_field($field) { - - if (!isset($field['size'])) { - $field['size'] = 'normal'; - } - - // Set the correct database-engine specific datatype. - if (!isset($field['mysql_type'])) { - $map = db_type_map(); - $field['mysql_type'] = $map[$field['type'] .':'. $field['size']]; - } - - if ($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_process_field(). - * - * @param $name - * Name of the field. - * @param $spec - * The field specification, as per the schema data structure format. - */ -function _db_create_field_sql($name, $spec) { - $sql = "`". $name ."` ". $spec['mysql_type']; - - if (isset($spec['length'])) { - $sql .= '('. $spec['length'] .')'; - } - elseif (isset($spec['precision']) && isset($spec['scale'])) { - $sql .= '('. $spec['scale'] .', '. $spec['precision'] .')'; - } - - if (!empty($spec['unsigned'])) { - $sql .= ' unsigned'; - } - - if (!empty($spec['not null'])) { - $sql .= ' NOT NULL'; - } - - if (!empty($spec['auto_increment'])) { - $sql .= ' auto_increment'; - } - - 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. - */ -function db_type_map() { - // 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 = array( - 'varchar:normal' => 'VARCHAR', - 'char:normal' => 'CHAR', - - 'text:tiny' => 'TINYTEXT', - 'text:small' => 'TINYTEXT', - 'text:medium' => 'MEDIUMTEXT', - 'text:big' => 'LONGTEXT', - 'text:normal' => 'TEXT', - - 'serial:tiny' => 'TINYINT', - 'serial:small' => 'SMALLINT', - 'serial:medium' => 'MEDIUMINT', - 'serial:big' => 'BIGINT', - 'serial:normal' => 'INT', - - 'int:tiny' => 'TINYINT', - 'int:small' => 'SMALLINT', - 'int:medium' => 'MEDIUMINT', - 'int:big' => 'BIGINT', - 'int:normal' => 'INT', - - 'float:tiny' => 'FLOAT', - 'float:small' => 'FLOAT', - 'float:medium' => 'FLOAT', - 'float:big' => 'DOUBLE', - 'float:normal' => 'FLOAT', - - 'numeric:normal' => 'DECIMAL', - - 'blob:big' => 'LONGBLOB', - 'blob:normal' => 'BLOB', - - 'datetime:normal' => 'DATETIME', - ); - return $map; -} - -/** - * Rename a table. - * - * @param $ret - * Array to which query results will be added. - * @param $table - * The table to be renamed. - * @param $new_name - * The new name for the table. - */ -function db_rename_table(&$ret, $table, $new_name) { - $ret[] = update_sql('ALTER TABLE {'. $table .'} RENAME TO {'. $new_name .'}'); -} - -/** - * Drop a table. - * - * @param $ret - * Array to which query results will be added. - * @param $table - * The table to be dropped. - */ -function db_drop_table(&$ret, $table) { - $ret[] = update_sql('DROP TABLE {'. $table .'}'); -} - -/** - * Add a new field to a table. - * - * @param $ret - * Array to which query results will be added. - * @param $table - * Name of the table to be altered. - * @param $field - * Name of the field to be added. - * @param $spec - * The field specification array, as taken from a schema definition. - * The specification may also contain the key 'initial', the newly - * created field will be set to the value of the key in all rows. - * This is most useful for creating NOT NULL columns with no default - * value in existing tables. - * @param $keys_new - * Optional keys and indexes specification to be created on the - * table along with adding the field. The format is the same as a - * table specification but without the 'fields' element. If you are - * adding a type 'serial' field, you MUST specify at least one key - * or index including it in this array. @see db_change_field for more - * explanation why. - */ -function db_add_field(&$ret, $table, $field, $spec, $keys_new = array()) { - $fixnull = FALSE; - if (!empty($spec['not null']) && !isset($spec['default'])) { - $fixnull = TRUE; - $spec['not null'] = FALSE; - } - $query = 'ALTER TABLE {'. $table .'} ADD '; - $query .= _db_create_field_sql($field, _db_process_field($spec)); - if (count($keys_new)) { - $query .= ', ADD '. implode(', ADD ', _db_create_keys_sql($keys_new)); - } - $ret[] = update_sql($query); - if (isset($spec['initial'])) { - // All this because update_sql does not support %-placeholders. - $sql = 'UPDATE {'. $table .'} SET '. $field .' = '. db_type_placeholder($spec['type']); - $result = db_query($sql, $spec['initial']); - $ret[] = array('success' => $result !== FALSE, 'query' => check_plain($sql .' ('. $spec['initial'] .')')); - } - if ($fixnull) { - $spec['not null'] = TRUE; - db_change_field($ret, $table, $field, $field, $spec); - } -} - -/** - * Drop a field. - * - * @param $ret - * Array to which query results will be added. - * @param $table - * The table to be altered. - * @param $field - * The field to be dropped. - */ -function db_drop_field(&$ret, $table, $field) { - $ret[] = update_sql('ALTER TABLE {'. $table .'} DROP '. $field); -} - -/** - * Set the default value for a field. - * - * @param $ret - * Array to which query results will be added. - * @param $table - * The table to be altered. - * @param $field - * The field to be altered. - * @param $default - * Default value to be set. NULL for 'default NULL'. - */ -function db_field_set_default(&$ret, $table, $field, $default) { - if ($default == NULL) { - $default = 'NULL'; - } - else { - $default = is_string($default) ? "'$default'" : $default; - } - - $ret[] = update_sql('ALTER TABLE {'. $table .'} ALTER COLUMN '. $field .' SET DEFAULT '. $default); -} - -/** - * Set a field to have no default value. - * - * @param $ret - * Array to which query results will be added. - * @param $table - * The table to be altered. - * @param $field - * The field to be altered. - */ -function db_field_set_no_default(&$ret, $table, $field) { - $ret[] = update_sql('ALTER TABLE {'. $table .'} ALTER COLUMN '. $field .' DROP DEFAULT'); -} - -/** - * Add a primary key. - * - * @param $ret - * Array to which query results will be added. - * @param $table - * The table to be altered. - * @param $fields - * Fields for the primary key. - */ -function db_add_primary_key(&$ret, $table, $fields) { - $ret[] = update_sql('ALTER TABLE {'. $table .'} ADD PRIMARY KEY ('. - _db_cr