annotate includes/database.pgsql.inc @ 20:e3d20ebd63d1 tip

Added tag 6.9 for changeset 3edae6ecd6c6
author Franck Deroche <franck@defr.org>
date Thu, 15 Jan 2009 10:16:10 +0100
parents 4347c45bb494
children
rev   line source
webmaster@1 1 <?php
webmaster@15 2 // $Id: database.pgsql.inc,v 1.68.2.3 2008/11/17 10:31:41 goba Exp $
webmaster@1 3
webmaster@1 4 /**
webmaster@1 5 * @file
webmaster@1 6 * Database interface code for PostgreSQL database servers.
webmaster@1 7 */
webmaster@1 8
webmaster@1 9 /**
webmaster@1 10 * @ingroup database
webmaster@1 11 * @{
webmaster@1 12 */
webmaster@1 13
webmaster@1 14 /**
webmaster@1 15 * Report database status.
webmaster@1 16 */
webmaster@1 17 function db_status_report() {
webmaster@1 18 $t = get_t();
webmaster@1 19
webmaster@1 20 $version = db_version();
webmaster@1 21
webmaster@1 22 $form['pgsql'] = array(
webmaster@1 23 'title' => $t('PostgreSQL database'),
webmaster@1 24 'value' => $version,
webmaster@1 25 );
webmaster@1 26
webmaster@1 27 if (version_compare($version, DRUPAL_MINIMUM_PGSQL) < 0) {
webmaster@1 28 $form['pgsql']['severity'] = REQUIREMENT_ERROR;
webmaster@1 29 $form['pgsql']['description'] = $t('Your PostgreSQL Server is too old. Drupal requires at least PostgreSQL %version.', array('%version' => DRUPAL_MINIMUM_PGSQL));
webmaster@1 30 }
webmaster@1 31
webmaster@1 32 return $form;
webmaster@1 33 }
webmaster@1 34
webmaster@1 35 /**
webmaster@1 36 * Returns the version of the database server currently in use.
webmaster@1 37 *
webmaster@1 38 * @return Database server version
webmaster@1 39 */
webmaster@1 40 function db_version() {
webmaster@1 41 return db_result(db_query("SHOW SERVER_VERSION"));
webmaster@1 42 }
webmaster@1 43
webmaster@1 44 /**
webmaster@1 45 * Initialize a database connection.
webmaster@1 46 */
webmaster@1 47 function db_connect($url) {
webmaster@1 48 // Check if PostgreSQL support is present in PHP
webmaster@1 49 if (!function_exists('pg_connect')) {
webmaster@1 50 _db_error_page('Unable to use the PostgreSQL database because the PostgreSQL extension for PHP is not installed. Check your <code>php.ini</code> to see how you can enable it.');
webmaster@1 51 }
webmaster@1 52
webmaster@1 53 $url = parse_url($url);
webmaster@1 54 $conn_string = '';
webmaster@1 55
webmaster@1 56 // Decode url-encoded information in the db connection string
webmaster@1 57 if (isset($url['user'])) {
webmaster@1 58 $conn_string .= ' user='. urldecode($url['user']);
webmaster@1 59 }
webmaster@1 60 if (isset($url['pass'])) {
webmaster@1 61 $conn_string .= ' password='. urldecode($url['pass']);
webmaster@1 62 }
webmaster@1 63 if (isset($url['host'])) {
webmaster@1 64 $conn_string .= ' host='. urldecode($url['host']);
webmaster@1 65 }
webmaster@1 66 if (isset($url['path'])) {
webmaster@1 67 $conn_string .= ' dbname='. substr(urldecode($url['path']), 1);
webmaster@1 68 }
webmaster@1 69 if (isset($url['port'])) {
webmaster@1 70 $conn_string .= ' port='. urldecode($url['port']);
webmaster@1 71 }
webmaster@1 72
webmaster@1 73 // pg_last_error() does not return a useful error message for database
webmaster@1 74 // connection errors. We must turn on error tracking to get at a good error
webmaster@1 75 // message, which will be stored in $php_errormsg.
webmaster@1 76 $track_errors_previous = ini_get('track_errors');
webmaster@1 77 ini_set('track_errors', 1);
webmaster@1 78
webmaster@1 79 $connection = @pg_connect($conn_string);
webmaster@1 80 if (!$connection) {
webmaster@1 81 require_once './includes/unicode.inc';
webmaster@1 82 _db_error_page(decode_entities($php_errormsg));
webmaster@1 83 }
webmaster@1 84
webmaster@1 85 // Restore error tracking setting
webmaster@1 86 ini_set('track_errors', $track_errors_previous);
webmaster@1 87
webmaster@15 88 pg_query($connection, "set client_encoding=\"UTF8\"");
webmaster@1 89 return $connection;
webmaster@1 90 }
webmaster@1 91
webmaster@1 92 /**
webmaster@1 93 * Runs a basic query in the active database.
webmaster@1 94 *
webmaster@1 95 * User-supplied arguments to the query should be passed in as separate
webmaster@1 96 * parameters so that they can be properly escaped to avoid SQL injection
webmaster@1 97 * attacks.
webmaster@1 98 *
webmaster@1 99 * @param $query
webmaster@1 100 * A string containing an SQL query.
webmaster@1 101 * @param ...
webmaster@1 102 * A variable number of arguments which are substituted into the query
webmaster@1 103 * using printf() syntax. Instead of a variable number of query arguments,
webmaster@1 104 * you may also pass a single array containing the query arguments.
webmaster@1 105 *
webmaster@1 106 * Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose
webmaster@1 107 * in '') and %%.
webmaster@1 108 *
webmaster@1 109 * NOTE: using this syntax will cast NULL and FALSE values to decimal 0,
webmaster@1 110 * and TRUE values to decimal 1.
webmaster@1 111 *
webmaster@1 112 * @return
webmaster@1 113 * A database query result resource, or FALSE if the query was not
webmaster@1 114 * executed correctly.
webmaster@1 115 */
webmaster@1 116 function db_query($query) {
webmaster@1 117 $args = func_get_args();
webmaster@1 118 array_shift($args);
webmaster@1 119 $query = db_prefix_tables($query);
webmaster@1 120 if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
webmaster@1 121 $args = $args[0];
webmaster@1 122 }
webmaster@1 123 _db_query_callback($args, TRUE);
webmaster@1 124 $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
webmaster@1 125 return _db_query($query);
webmaster@1 126 }
webmaster@1 127
webmaster@1 128 /**
webmaster@1 129 * Helper function for db_query().
webmaster@1 130 */
webmaster@1 131 function _db_query($query, $debug = 0) {
webmaster@1 132 global $active_db, $last_result, $queries;
webmaster@1 133
webmaster@1 134 if (variable_get('dev_query', 0)) {
webmaster@1 135 list($usec, $sec) = explode(' ', microtime());
webmaster@1 136 $timer = (float)$usec + (float)$sec;
webmaster@1 137 }
webmaster@1 138
webmaster@1 139 $last_result = pg_query($active_db, $query);
webmaster@1 140
webmaster@1 141 if (variable_get('dev_query', 0)) {
webmaster@1 142 $bt = debug_backtrace();
webmaster@1 143 $query = $bt[2]['function'] ."\n". $query;
webmaster@1 144 list($usec, $sec) = explode(' ', microtime());
webmaster@1 145 $stop = (float)$usec + (float)$sec;
webmaster@1 146 $diff = $stop - $timer;
webmaster@1 147 $queries[] = array($query, $diff);
webmaster@1 148 }
webmaster@1 149
webmaster@1 150 if ($debug) {
webmaster@1 151 print '<p>query: '. $query .'<br />error:'. pg_last_error($active_db) .'</p>';
webmaster@1 152 }
webmaster@1 153
webmaster@1 154 if ($last_result !== FALSE) {
webmaster@1 155 return $last_result;
webmaster@1 156 }
webmaster@1 157 else {
webmaster@1 158 // Indicate to drupal_error_handler that this is a database error.
webmaster@1 159 ${DB_ERROR} = TRUE;
webmaster@1 160 trigger_error(check_plain(pg_last_error($active_db) ."\nquery: ". $query), E_USER_WARNING);
webmaster@1 161 return FALSE;
webmaster@1 162 }
webmaster@1 163 }
webmaster@1 164
webmaster@1 165 /**
webmaster@1 166 * Fetch one result row from the previous query as an object.
webmaster@1 167 *
webmaster@1 168 * @param $result
webmaster@1 169 * A database query result resource, as returned from db_query().
webmaster@1 170 * @return
webmaster@1 171 * An object representing the next row of the result, or FALSE. The attributes
webmaster@1 172 * of this object are the table fields selected by the query.
webmaster@1 173 */
webmaster@1 174 function db_fetch_object($result) {
webmaster@1 175 if ($result) {
webmaster@1 176 return pg_fetch_object($result);
webmaster@1 177 }
webmaster@1 178 }
webmaster@1 179
webmaster@1 180 /**
webmaster@1 181 * Fetch one result row from the previous query as an array.
webmaster@1 182 *
webmaster@1 183 * @param $result
webmaster@1 184 * A database query result resource, as returned from db_query().
webmaster@1 185 * @return
webmaster@1 186 * An associative array representing the next row of the result, or FALSE.
webmaster@1 187 * The keys of this object are the names of the table fields selected by the
webmaster@1 188 * query, and the values are the field values for this result row.
webmaster@1 189 */
webmaster@1 190 function db_fetch_array($result) {
webmaster@1 191 if ($result) {
webmaster@1 192 return pg_fetch_assoc($result);
webmaster@1 193 }
webmaster@1 194 }
webmaster@1 195
webmaster@1 196 /**
webmaster@1 197 * Return an individual result field from the previous query.
webmaster@1 198 *
webmaster@1 199 * Only use this function if exactly one field is being selected; otherwise,
webmaster@1 200 * use db_fetch_object() or db_fetch_array().
webmaster@1 201 *
webmaster@1 202 * @param $result
webmaster@1 203 * A database query result resource, as returned from db_query().
webmaster@1 204 * @return
webmaster@1 205 * The resulting field or FALSE.
webmaster@1 206 */
webmaster@1 207 function db_result($result) {
webmaster@1 208 if ($result && pg_num_rows($result) > 0) {
webmaster@1 209 $array = pg_fetch_row($result);
webmaster@1 210 return $array[0];
webmaster@1 211 }
webmaster@1 212 return FALSE;
webmaster@1 213 }
webmaster@1 214
webmaster@1 215 /**
webmaster@1 216 * Determine whether the previous query caused an error.
webmaster@1 217 */
webmaster@1 218 function db_error() {
webmaster@1 219 global $active_db;
webmaster@1 220 return pg_last_error($active_db);
webmaster@1 221 }
webmaster@1 222
webmaster@1 223 /**
webmaster@1 224 * Returns the last insert id. This function is thread safe.
webmaster@1 225 *
webmaster@1 226 * @param $table
webmaster@1 227 * The name of the table you inserted into.
webmaster@1 228 * @param $field
webmaster@1 229 * The name of the autoincrement field.
webmaster@1 230 */
webmaster@1 231 function db_last_insert_id($table, $field) {
webmaster@1 232 return db_result(db_query("SELECT CURRVAL('{". db_escape_table($table) ."}_". db_escape_table($field) ."_seq')"));
webmaster@1 233 }
webmaster@1 234
webmaster@1 235 /**
webmaster@1 236 * Determine the number of rows changed by the preceding query.
webmaster@1 237 */
webmaster@1 238 function db_affected_rows() {
webmaster@1 239 global $last_result;
webmaster@1 240 return empty($last_result) ? 0 : pg_affected_rows($last_result);
webmaster@1 241 }
webmaster@1 242
webmaster@1 243 /**
webmaster@1 244 * Runs a limited-range query in the active database.
webmaster@1 245 *
webmaster@1 246 * Use this as a substitute for db_query() when a subset of the query
webmaster@1 247 * is to be returned.
webmaster@1 248 * User-supplied arguments to the query should be passed in as separate
webmaster@1 249 * parameters so that they can be properly escaped to avoid SQL injection
webmaster@1 250 * attacks.
webmaster@1 251 *
webmaster@1 252 * @param $query
webmaster@1 253 * A string containing an SQL query.
webmaster@1 254 * @param ...
webmaster@1 255 * A variable number of arguments which are substituted into the query
webmaster@1 256 * using printf() syntax. Instead of a variable number of query arguments,
webmaster@1 257 * you may also pass a single array containing the query arguments.
webmaster@1 258 * Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose
webmaster@1 259 * in '') and %%.
webmaster@1 260 *
webmaster@1 261 * NOTE: using this syntax will cast NULL and FALSE values to decimal 0,
webmaster@1 262 * and TRUE values to decimal 1.
webmaster@1 263 *
webmaster@1 264 * @param $from
webmaster@1 265 * The first result row to return.
webmaster@1 266 * @param $count
webmaster@1 267 * The maximum number of result rows to return.
webmaster@1 268 * @return
webmaster@1 269 * A database query result resource, or FALSE if the query was not executed
webmaster@1 270 * correctly.
webmaster@1 271 */
webmaster@1 272 function db_query_range($query) {
webmaster@1 273 $args = func_get_args();
webmaster@1 274 $count = array_pop($args);
webmaster@1 275 $from = array_pop($args);
webmaster@1 276 array_shift($args);
webmaster@1 277
webmaster@1 278 $query = db_prefix_tables($query);
webmaster@1 279 if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
webmaster@1 280 $args = $args[0];
webmaster@1 281 }
webmaster@1 282 _db_query_callback($args, TRUE);
webmaster@1 283 $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
webmaster@1 284 $query .= ' LIMIT '. (int)$count .' OFFSET '. (int)$from;
webmaster@1 285 return _db_query($query);
webmaster@1 286 }
webmaster@1 287
webmaster@1 288 /**
webmaster@1 289 * Runs a SELECT query and stores its results in a temporary table.
webmaster@1 290 *
webmaster@1 291 * Use this as a substitute for db_query() when the results need to stored
webmaster@1 292 * in a temporary table. Temporary tables exist for the duration of the page
webmaster@1 293 * request.
webmaster@1 294 * User-supplied arguments to the query should be passed in as separate parameters
webmaster@1 295 * so that they can be properly escaped to avoid SQL injection attacks.
webmaster@1 296 *
webmaster@1 297 * Note that if you need to know how many results were returned, you should do
webmaster@1 298 * a SELECT COUNT(*) on the temporary table afterwards. db_affected_rows() does
webmaster@1 299 * not give consistent result across different database types in this case.
webmaster@1 300 *
webmaster@1 301 * @param $query
webmaster@1 302 * A string containing a normal SELECT SQL query.
webmaster@1 303 * @param ...
webmaster@1 304 * A variable number of arguments which are substituted into the query
webmaster@1 305 * using printf() syntax. The query arguments can be enclosed in one
webmaster@1 306 * array instead.
webmaster@1 307 * Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose
webmaster@1 308 * in '') and %%.
webmaster@1 309 *
webmaster@1 310 * NOTE: using this syntax will cast NULL and FALSE values to decimal 0,
webmaster@1 311 * and TRUE values to decimal 1.
webmaster@1 312 *
webmaster@1 313 * @param $table
webmaster@1 314 * The name of the temporary table to select into. This name will not be
webmaster@1 315 * prefixed as there is no risk of collision.
webmaster@1 316 * @return
webmaster@1 317 * A database query result resource, or FALSE if the query was not executed
webmaster@1 318 * correctly.
webmaster@1 319 */
webmaster@1 320 function db_query_temporary($query) {
webmaster@1 321 $args = func_get_args();
webmaster@1 322 $tablename = array_pop($args);
webmaster@1 323 array_shift($args);
webmaster@1 324
webmaster@1 325 $query = preg_replace('/^SELECT/i', 'CREATE TEMPORARY TABLE '. $tablename .' AS SELECT', db_prefix_tables($query));
webmaster@1 326 if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
webmaster@1 327 $args = $args[0];
webmaster@1 328 }
webmaster@1 329 _db_query_callback($args, TRUE);
webmaster@1 330 $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
webmaster@1 331 return _db_query($query);
webmaster@1 332 }
webmaster@1 333
webmaster@1 334 /**
webmaster@1 335 * Returns a properly formatted Binary Large OBject value.
webmaster@1 336 * In case of PostgreSQL encodes data for insert into bytea field.
webmaster@1 337 *
webmaster@1 338 * @param $data
webmaster@1 339 * Data to encode.
webmaster@1 340 * @return
webmaster@1 341 * Encoded data.
webmaster@1 342 */
webmaster@1 343 function db_encode_blob($data) {
webmaster@1 344 return "'". pg_escape_bytea($data) ."'";
webmaster@1 345 }
webmaster@1 346
webmaster@1 347 /**
webmaster@1 348 * Returns text from a Binary Large OBject value.
webmaster@1 349 * In case of PostgreSQL decodes data after select from bytea field.
webmaster@1 350 *
webmaster@1 351 * @param $data
webmaster@1 352 * Data to decode.
webmaster@1 353 * @return
webmaster@1 354 * Decoded data.
webmaster@1 355 */
webmaster@1 356 function db_decode_blob($data) {
webmaster@1 357 return pg_unescape_bytea($data);
webmaster@1 358 }
webmaster@1 359
webmaster@1 360 /**
webmaster@1 361 * Prepare user input for use in a database query, preventing SQL injection attacks.
webmaster@1 362 * Note: This function requires PostgreSQL 7.2 or later.
webmaster@1 363 */
webmaster@1 364 function db_escape_string($text) {
webmaster@1 365 return pg_escape_string($text);
webmaster@1 366 }
webmaster@1 367
webmaster@1 368 /**
webmaster@1 369 * Lock a table.
webmaster@1 370 * This function automatically starts a transaction.
webmaster@1 371 */
webmaster@1 372 function db_lock_table($table) {
webmaster@1 373 db_query('BEGIN; LOCK TABLE {'. db_escape_table($table) .'} IN EXCLUSIVE MODE');
webmaster@1 374 }
webmaster@1 375
webmaster@1 376 /**
webmaster@1 377 * Unlock all locked tables.
webmaster@1 378 * This function automatically commits a transaction.
webmaster@1 379 */
webmaster@1 380 function db_unlock_tables() {
webmaster@1 381 db_query('COMMIT');
webmaster@1 382 }
webmaster@1 383
webmaster@1 384 /**
webmaster@1 385 * Check if a table exists.
webmaster@1 386 */
webmaster@1 387 function db_table_exists($table) {
webmaster@1 388 return (bool) db_result(db_query("SELECT COUNT(*) FROM pg_class WHERE relname = '{". db_escape_table($table) ."}'"));
webmaster@1 389 }
webmaster@1 390
webmaster@1 391 /**
webmaster@1 392 * Check if a column exists in the given table.
webmaster@1 393 */
webmaster@1 394 function db_column_exists($table, $column) {
webmaster@1 395 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) ."'"));
webmaster@1 396 }
webmaster@1 397
webmaster@1 398 /**
webmaster@1 399 * Verify if the database is set up correctly.
webmaster@1 400 */
webmaster@1 401 function db_check_setup() {
webmaster@1 402 $t = get_t();
webmaster@1 403
webmaster@1 404 $encoding = db_result(db_query('SHOW server_encoding'));
webmaster@1 405 if (!in_array(strtolower($encoding), array('unicode', 'utf8'))) {
webmaster@1 406 drupal_set_message($t('Your PostgreSQL database is set up with the wrong character encoding (%encoding). It is possible it will not work as expected. It is advised to recreate it with UTF-8/Unicode encoding. More information can be found in the <a href="@url">PostgreSQL documentation</a>.', array('%encoding' => $encoding, '@url' => 'http://www.postgresql.org/docs/7.4/interactive/multibyte.html')), 'status');
webmaster@1 407 }
webmaster@1 408 }
webmaster@1 409
webmaster@1 410 /**
webmaster@1 411 * Wraps the given table.field entry with a DISTINCT(). The wrapper is added to
webmaster@1 412 * the SELECT list entry of the given query and the resulting query is returned.
webmaster@1 413 * This function only applies the wrapper if a DISTINCT doesn't already exist in
webmaster@1 414 * the query.
webmaster@1 415 *
webmaster@1 416 * @param $table Table containing the field to set as DISTINCT
webmaster@1 417 * @param $field Field to set as DISTINCT
webmaster@1 418 * @param $query Query to apply the wrapper to
webmaster@1 419 * @return SQL query with the DISTINCT wrapper surrounding the given table.field.
webmaster@1 420 */
webmaster@1 421 function db_distinct_field($table, $field, $query) {
webmaster@7 422 if (!preg_match('/FROM\s+\S+\s+AS/si', $query)
webmaster@7 423 && !preg_match('/DISTINCT\s+ON\s*\(\s*(' . $table . '\s*\.\s*)?' . $field . '\s*\)/si', $query)
webmaster@7 424 && !preg_match('/DISTINCT[ (]' . $field . '/si', $query)
webmaster@7 425 && preg_match('/(.*FROM\s+)(.*?\s)(\s*(WHERE|GROUP|HAVING|ORDER|LIMIT|FOR).*)/Asi', $query, $m)) {
webmaster@7 426 $query = $m[1];
webmaster@7 427 $query .= preg_replace('/([\{\w+\}]+)\s+(' . $table . ')\s/Usi', '(SELECT DISTINCT ON (' . $field . ') * FROM \1) \2 ', $m[2]);
webmaster@7 428 $query .= $m[3];
webmaster@7 429 }
webmaster@1 430 return $query;
webmaster@1 431 }
webmaster@1 432
webmaster@1 433 /**
webmaster@1 434 * @} End of "ingroup database".
webmaster@1 435 */
webmaster@1 436
webmaster@1 437 /**
webmaster@1 438 * @ingroup schemaapi
webmaster@1 439 * @{
webmaster@1 440 */
webmaster@1 441
webmaster@1 442 /**
webmaster@1 443 * This maps a generic data type in combination with its data size
webmaster@1 444 * to the engine-specific data type.
webmaster@1 445 */
webmaster@1 446 function db_type_map() {
webmaster@1 447 // Put :normal last so it gets preserved by array_flip. This makes
webmaster@1 448 // it much easier for modules (such as schema.module) to map
webmaster@1 449 // database types back into schema types.
webmaster@1 450 $map = array(
webmaster@1 451 'varchar:normal' => 'varchar',
webmaster@1 452 'char:normal' => 'character',
webmaster@1 453
webmaster@1 454 'text:tiny' => 'text',
webmaster@1 455 'text:small' => 'text',
webmaster@1 456 'text:medium' => 'text',
webmaster@1 457 'text:big' => 'text',
webmaster@1 458 'text:normal' => 'text',
webmaster@1 459
webmaster@1 460 'int:tiny' => 'smallint',
webmaster@1 461 'int:small' => 'smallint',
webmaster@1 462 'int:medium' => 'int',
webmaster@1 463 'int:big' => 'bigint',
webmaster@1 464 'int:normal' => 'int',
webmaster@1 465
webmaster@1 466 'float:tiny' => 'real',
webmaster@1 467 'float:small' => 'real',
webmaster@1 468 'float:medium' => 'real',
webmaster@1 469 'float:big' => 'double precision',
webmaster@1 470 'float:normal' => 'real',
webmaster@1 471
webmaster@1 472 'numeric:normal' => 'numeric',
webmaster@1 473
webmaster@1 474 'blob:big' => 'bytea',
webmaster@1 475 'blob:normal' => 'bytea',
webmaster@1 476
webmaster@1 477 'datetime:normal' => 'timestamp',
webmaster@1 478
webmaster@1 479 'serial:tiny' => 'serial',
webmaster@1 480 'serial:small' => 'serial',
webmaster@1 481 'serial:medium' => 'serial',
webmaster@1 482 'serial:big' => 'bigserial',
webmaster@1 483 'serial:normal' => 'serial',
webmaster@1 484 );
webmaster@1 485 return $map;
webmaster@1 486 }
webmaster@1 487
webmaster@1 488 /**
webmaster@1 489 * Generate SQL to create a new table from a Drupal schema definition.
webmaster@1 490 *
webmaster@1 491 * @param $name
webmaster@1 492 * The name of the table to create.
webmaster@1 493 * @param $table
webmaster@1 494 * A Schema API table definition array.
webmaster@1 495 * @return
webmaster@1 496 * An array of SQL statements to create the table.
webmaster@1 497 */
webmaster@1 498 function db_create_table_sql($name, $table) {
webmaster@1 499 $sql_fields = array();
webmaster@1 500 foreach ($table['fields'] as $field_name => $field) {
webmaster@1 501 $sql_fields[] = _db_create_field_sql($field_name, _db_process_field($field));
webmaster@1 502 }
webmaster@1 503
webmaster@1 504 $sql_keys = array();
webmaster@1 505 if (isset($table['primary key']) && is_array($table['primary key'])) {
webmaster@1 506 $sql_keys[] = 'PRIMARY KEY ('. implode(', ', $table['primary key']) .')';
webmaster@1 507 }
webmaster@1 508 if (isset($table['unique keys']) && is_array($table['unique keys'])) {
webmaster@1 509 foreach ($table['unique keys'] as $key_name => $key) {
webmaster@1 510 $sql_keys[] = 'CONSTRAINT {'. $name .'}_'. $key_name .'_key UNIQUE ('. implode(', ', $key) .')';
webmaster@1 511 }
webmaster@1 512 }
webmaster@1 513
webmaster@1 514 $sql = "CREATE TABLE {". $name ."} (\n\t";
webmaster@1 515 $sql .= implode(",\n\t", $sql_fields);
webmaster@1 516 if (count($sql_keys) > 0) {
webmaster@1 517 $sql .= ",\n\t";
webmaster@1 518 }
webmaster@1 519 $sql .= implode(",\n\t", $sql_keys);
webmaster@1 520 $sql .= "\n)";
webmaster@1 521 $statements[] = $sql;
webmaster@1 522
webmaster@1 523 if (isset($table['indexes']) && is_array($table['indexes'])) {
webmaster@1 524 foreach ($table['indexes'] as $key_name => $key) {
webmaster@1 525 $statements[] = _db_create_index_sql($name, $key_name, $key);
webmaster@1 526 }
webmaster@1 527 }
webmaster@1 528
webmaster@1 529 return $statements;
webmaster@1 530 }
webmaster@1 531
webmaster@1 532 function _db_create_index_sql($table, $name, $fields) {
webmaster@1 533 $query = 'CREATE INDEX {'. $table .'}_'. $name .'_idx ON {'. $table .'} (';
webmaster@1 534 $query .= _db_create_key_sql($fields) .')';
webmaster@1 535 return $query;
webmaster@1 536 }
webmaster@1 537
webmaster@1 538 function _db_create_key_sql($fields) {
webmaster@1 539 $ret = array();
webmaster@1 540 foreach ($fields as $field) {
webmaster@1 541 if (is_array($field)) {
webmaster@1 542 $ret[] = 'substr('. $field[0] .', 1, '. $field[1] .')';
webmaster@1 543 }
webmaster@1 544 else {
webmaster@1 545 $ret[] = $field;
webmaster@1 546 }
webmaster@1 547 }
webmaster@1 548 return implode(', ', $ret);
webmaster@1 549 }
webmaster@1 550
webmaster@1 551 function _db_create_keys(&$ret, $table, $new_keys) {
webmaster@1 552 if (isset($new_keys['primary key'])) {
webmaster@1 553 db_add_primary_key($ret, $table, $new_keys['primary key']);
webmaster@1 554 }
webmaster@1 555 if (isset($new_keys['unique keys'])) {
webmaster@1 556 foreach ($new_keys['unique keys'] as $name => $fields) {
webmaster@1 557 db_add_unique_key($ret, $table, $name, $fields);
webmaster@1 558 }
webmaster@1 559 }
webmaster@1 560 if (isset($new_keys['indexes'])) {
webmaster@1 561 foreach ($new_keys['indexes'] as $name => $fields) {
webmaster@1 562 db_add_index($ret, $table, $name, $fields);
webmaster@1 563 }
webmaster@1 564 }
webmaster@1 565 }
webmaster@1 566
webmaster@1 567 /**
webmaster@1 568 * Set database-engine specific properties for a field.
webmaster@1 569 *
webmaster@1 570 * @param $field
webmaster@1 571 * A field description array, as specified in the schema documentation.
webmaster@1 572 */
webmaster@1 573 function _db_process_field($field) {
webmaster@1 574 if (!isset($field['size'])) {
webmaster@1 575 $field['size'] = 'normal';
webmaster@1 576 }
webmaster@1 577 // Set the correct database-engine specific datatype.
webmaster@1 578 if (!isset($field['pgsql_type'])) {
webmaster@1 579 $map = db_type_map();
webmaster@1 580 $field['pgsql_type'] = $map[$field['type'] .':'. $field['size']];
webmaster@1 581 }
webmaster@1 582 if ($field['type'] == 'serial') {
webmaster@1 583 unset($field['not null']);
webmaster@1 584 }
webmaster@1 585 return $field;
webmaster@1 586 }
webmaster@1 587
webmaster@1 588 /**
webmaster@1 589 * Create an SQL string for a field to be used in table creation or alteration.
webmaster@1 590 *
webmaster@1 591 * Before passing a field out of a schema definition into this function it has
webmaster@1 592 * to be processed by _db_process_field().
webmaster@1 593 *
webmaster@1 594 * @param $name
webmaster@1 595 * Name of the field.
webmaster@1 596 * @param $spec
webmaster@1 597 * The field specification, as per the schema data structure format.
webmaster@1 598 */
webmaster@1 599 function _db_create_field_sql($name, $spec) {
webmaster@1 600 $sql = $name .' '. $spec['pgsql_type'];
webmaster@1 601
webmaster@1 602 if ($spec['type'] == 'serial') {
webmaster@1 603 unset($spec['not null']);
webmaster@1 604 }
webmaster@1 605 if (!empty($spec['unsigned'])) {
webmaster@1 606 if ($spec['type'] == 'serial') {
webmaster@1 607 $sql .= " CHECK ($name >= 0)";
webmaster@1 608 }
webmaster@1 609 else {
webmaster@1 610 $sql .= '_unsigned';
webmaster@1 611 }
webmaster@1 612 }
webmaster@1 613
webmaster@1 614 if (!empty($spec['length'])) {
webmaster@1 615 $sql .= '('. $spec['length'] .')';
webmaster@1 616 }
webmaster@1 617 elseif (isset($spec['precision']) && isset($spec['scale'])) {
webmaster@1 618 $sql .= '('. $spec['precision'] .', '. $spec['scale'] .')';
webmaster@1 619 }
webmaster@1 620
webmaster@1 621 if (isset($spec['not null']) && $spec['not null']) {
webmaster@1 622 $sql .= ' NOT NULL';
webmaster@1 623 }
webmaster@1 624 if (isset($spec['default'])) {
webmaster@1 625 $default = is_string($spec['default']) ? "'". $spec['default'] ."'" : $spec['default'];
webmaster@1 626 $sql .= " default $default";
webmaster@1 627 }
webmaster@1 628
webmaster@1 629 return $sql;
webmaster@1 630 }
webmaster@1 631
webmaster@1 632 /**
webmaster@1 633 * Rename a table.
webmaster@1 634 *
webmaster@1 635 * @param $ret
webmaster@1 636 * Array to which query results will be added.
webmaster@1 637 * @param $table
webmaster@1 638 * The table to be renamed.
webmaster@1 639 * @param $new_name
webmaster@1 640 * The new name for the table.
webmaster@1 641 */
webmaster@1 642 function db_rename_table(&$ret, $table, $new_name) {
webmaster@1 643 $ret[] = update_sql('ALTER TABLE {'. $table .'} RENAME TO {'. $new_name .'}');
webmaster@1 644 }
webmaster@1 645
webmaster@1 646 /**
webmaster@1 647 * Drop a table.
webmaster@1 648 *
webmaster@1 649 * @param $ret
webmaster@1 650 * Array to which query results will be added.
webmaster@1 651 * @param $table
webmaster@1 652 * The table to be dropped.
webmaster@1 653 */
webmaster@1 654 function db_drop_table(&$ret, $table) {
webmaster@1 655 $ret[] = update_sql('DROP TABLE {'. $table .'}');
webmaster@1 656 }
webmaster@1 657
webmaster@1 658 /**
webmaster@1 659 * Add a new field to a table.
webmaster@1 660 *
webmaster@1 661 * @param $ret
webmaster@1 662 * Array to which query results will be added.
webmaster@1 663 * @param $table
webmaster@1 664 * Name of the table to be altered.
webmaster@1 665 * @param $field
webmaster@1 666 * Name of the field to be added.
webmaster@1 667 * @param $spec
webmaster@1 668 * The field specification array, as taken from a schema definition.
webmaster@1 669 * The specification may also contain the key 'initial', the newly
webmaster@1 670 * created field will be set to the value of the key in all rows.
webmaster@1 671 * This is most useful for creating NOT NULL columns with no default
webmaster@1 672 * value in existing tables.
webmaster@1 673 * @param $keys_new
webmaster@1 674 * Optional keys and indexes specification to be created on the
webmaster@1 675 * table along with adding the field. The format is the same as a
webmaster@1 676 * table specification but without the 'fields' element. If you are
webmaster@1 677 * adding a type 'serial' field, you MUST specify at least one key
webmaster@1 678 * or index including it in this array. @see db_change_field for more
webmaster@1 679 * explanation why.
webmaster@1 680 */
webmaster@1 681 function db_add_field(&$ret, $table, $field, $spec, $new_keys = array()) {
webmaster@1 682 $fixnull = FALSE;
webmaster@1 683 if (!empty($spec['not null']) && !isset($spec['default'])) {
webmaster@1 684 $fixnull = TRUE;
webmaster@1 685 $spec['not null'] = FALSE;
webmaster@1 686 }
webmaster@1 687 $query = 'ALTER TABLE {'. $table .'} ADD COLUMN ';
webmaster@1 688 $query .= _db_create_field_sql($field, _db_process_field($spec));
webmaster@1 689 $ret[] = update_sql($query);
webmaster@1 690 if (isset($spec['initial'])) {
webmaster@1 691 // All this because update_sql does not support %-placeholders.
webmaster@1 692 $sql = 'UPDATE {'. $table .'} SET '. $field .' = '. db_type_placeholder($spec['type']);
webmaster@1 693 $result = db_query($sql, $spec['initial']);
webmaster@1 694 $ret[] = array('success' => $result !== FALSE, 'query' => check_plain($sql .' ('. $spec['initial'] .')'));
webmaster@1 695 }
webmaster@1 696 if ($fixnull) {
webmaster@1 697 $ret[] = update_sql("ALTER TABLE {". $table ."} ALTER $field SET NOT NULL");
webmaster@1 698 }
webmaster@1 699 if (isset($new_keys)) {
webmaster@1 700 _db_create_keys($ret, $table, $new_keys);
webmaster@1 701 }
webmaster@1 702 }
webmaster@1 703
webmaster@1 704 /**
webmaster@1 705 * Drop a field.
webmaster@1 706 *
webmaster@1 707 * @param $ret
webmaster@1 708 * Array to which query results will be added.
webmaster@1 709 * @param $table
webmaster@1 710 * The table to be altered.
webmaster@1 711 * @param $field
webmaster@1 712 * The field to be dropped.
webmaster@1 713 */
webmaster@1 714 function db_drop_field(&$ret, $table, $field) {
webmaster@1 715 $ret[] = update_sql('ALTER TABLE {'. $table .'} DROP COLUMN '. $field);
webmaster@1 716 }
webmaster@1 717
webmaster@1 718 /**
webmaster@1 719 * Set the default value for a field.
webmaster@1 720 *
webmaster@1 721 * @param $ret
webmaster@1 722 * Array to which query results will be added.
webmaster@1 723 * @param $table
webmaster@1 724 * The table to be altered.
webmaster@1 725 * @param $field
webmaster@1 726 * The field to be altered.
webmaster@1 727 * @param $default
webmaster@1 728 * Default value to be set. NULL for 'default NULL'.
webmaster@1 729 */
webmaster@1 730 function db_field_set_default(&$ret, $table, $field, $default) {
webmaster@1 731 if ($default == NULL) {
webmaster@1 732 $default = 'NULL';
webmaster@1 733 }
webmaster@1 734 else {
webmaster@1 735 $default = is_string($default) ? "'$default'" : $default;
webmaster@1 736 }
webmaster@1 737
webmaster@1 738 $ret[] = update_sql('ALTER TABLE {'. $table .'} ALTER COLUMN '. $field .' SET DEFAULT '. $default);
webmaster@1 739 }
webmaster@1 740
webmaster@1 741 /**
webmaster@1 742 * Set a field to have no default value.
webmaster@1 743 *
webmaster@1 744 * @param $ret
webmaster@1 745 * Array to which query results will be added.
webmaster@1 746 * @param $table
webmaster@1 747 * The table to be altered.
webmaster@1 748 * @param $field
webmaster@1 749 * The field to be altered.
webmaster@1 750 */
webmaster@1 751 function db_field_set_no_default(&$ret, $table, $field) {
webmaster@1 752 $ret[] = update_sql('ALTER TABLE {'. $table .'} ALTER COLUMN '. $field .' DROP DEFAULT');
webmaster@1 753 }
webmaster@1 754
webmaster@1 755 /**
webmaster@1 756 * Add a primary key.
webmaster@1 757 *
webmaster@1 758 * @param $ret
webmaster@1 759 * Array to which query results will be added.
webmaster@1 760 * @param $table
webmaster@1 761 * The table to be altered.
webmaster@1 762 * @param $fields
webmaster@1 763 * Fields for the primary key.
webmaster@1 764 */
webmaster@1 765 function db_add_primary_key(&$ret, $table, $fields) {
webmaster@1 766 $ret[] = update_sql('ALTER TABLE {'. $table .'} ADD PRIMARY KEY ('.
webmaster@1 767 implode(',', $fields) .')');
webmaster@1 768 }
webmaster@1 769
webmaster@1 770 /**
webmaster@1 771 * Drop the primary key.
webmaster@1 772 *
webmaster@1 773 * @param $ret
webmaster@1 774 * Array to which query results will be added.
webmaster@1 775 * @param $table
webmaster@1 776 * The table to be altered.
webmaster@1 777 */
webmaster@1 778 function db_drop_primary_key(&$ret, $table) {
webmaster@1 779 $ret[] = update_sql('ALTER TABLE {'. $table .'} DROP CONSTRAINT {'. $table .'}_pkey');
webmaster@1 780 }
webmaster@1 781
webmaster@1 782 /**
webmaster@1 783 * Add a unique key.
webmaster@1 784 *
webmaster@1 785 * @param $ret
webmaster@1 786 * Array to which query results will be added.
webmaster@1 787 * @param $table
webmaster@1 788 * The table to be altered.
webmaster@1 789 * @param $name
webmaster@1 790 * The name of the key.
webmaster@1 791 * @param $fields
webmaster@1 792 * An array of field names.
webmaster@1 793 */
webmaster@1 794 function db_add_unique_key(&$ret, $table, $name, $fields) {
webmaster@1 795 $name = '{'. $table .'}_'. $name .'_key';
webmaster@1 796 $ret[] = update_sql('ALTER TABLE {'. $table .'} ADD CONSTRAINT '.
webmaster@1 797 $name .' UNIQUE ('. implode(',', $fields) .')');
webmaster@1 798 }
webmaster@1 799
webmaster@1 800 /**
webmaster@1 801 * Drop a unique key.
webmaster@1 802 *
webmaster@1 803 * @param $ret
webmaster@1 804 * Array to which query results will be added.
webmaster@1 805 * @param $table
webmaster@1 806 * The table to be altered.
webmaster@1 807 * @param $name
webmaster@1 808 * The name of the key.
webmaster@1 809 */
webmaster@1 810 function db_drop_unique_key(&$ret, $table, $name) {
webmaster@1 811 $name = '{'. $table .'}_'. $name .'_key';
webmaster@1 812 $ret[] = update_sql('ALTER TABLE {'. $table .'} DROP CONSTRAINT '. $name);
webmaster@1 813 }
webmaster@1 814
webmaster@1 815 /**
webmaster@1 816 * Add an index.
webmaster@1 817 *
webmaster@1 818 * @param $ret
webmaster@1 819 * Array to which query results will be added.
webmaster@1 820 * @param $table
webmaster@1 821 * The table to be altered.
webmaster@1 822 * @param $name
webmaster@1 823 * The name of the index.
webmaster@1 824 * @param $fields
webmaster@1 825 * An array of field names.
webmaster@1 826 */
webmaster@1 827 function db_add_index(&$ret, $table, $name, $fields) {
webmaster@1 828 $ret[] = update_sql(_db_create_index_sql($table, $name, $fields));
webmaster@1 829 }
webmaster@1 830
webmaster@1 831 /**
webmaster@1 832 * Drop an index.
webmaster@1 833 *
webmaster@1 834 * @param $ret
webmaster@1 835 * Array to which query results will be added.
webmaster@1 836 * @param $table
webmaster@1 837 * The table to be altered.
webmaster@1 838 * @param $name
webmaster@1 839 * The name of the index.
webmaster@1 840 */
webmaster@1 841 function db_drop_index(&$ret, $table, $name) {
webmaster@1 842 $name = '{'. $table .'}_'. $name .'_idx';
webmaster@1 843 $ret[] = update_sql('DROP INDEX '. $name);
webmaster@1 844 }
webmaster@1 845
webmaster@1 846 /**
webmaster@1 847 * Change a field definition.
webmaster@1 848 *
webmaster@1 849 * IMPORTANT NOTE: To maintain database portability, you have to explicitly
webmaster@1 850 * recreate all indices and primary keys that are using the changed field.
webmaster@1 851 *
webmaster@1 852 * That means that you have to drop all affected keys and indexes with
webmaster@1 853 * db_drop_{primary_key,unique_key,index}() before calling db_change_field().
webmaster@1 854 * To recreate the keys and indices, pass the key definitions as the
webmaster@1 855 * optional $new_keys argument directly to db_change_field().
webmaster@1 856 *
webmaster@1 857 * For example, suppose you have:
webmaster@1 858 * @code
webmaster@1 859 * $schema['foo'] = array(
webmaster@1 860 * 'fields' => array(
webmaster@1 861 * 'bar' => array('type' => 'int', 'not null' => TRUE)
webmaster@1 862 * ),
webmaster@1 863 * 'primary key' => array('bar')
webmaster@1 864 * );
webmaster@1 865 * @endcode
webmaster@1 866 * and you want to change foo.bar to be type serial, leaving it as the
webmaster@1 867 * primary key. The correct sequence is:
webmaster@1 868 * @code
webmaster@1 869 * db_drop_primary_key($ret, 'foo');
webmaster@1 870 * db_change_field($ret, 'foo', 'bar', 'bar',
webmaster@1 871 * array('type' => 'serial', 'not null' => TRUE),
webmaster@1 872 * array('primary key' => array('bar')));
webmaster@1 873 * @endcode
webmaster@1 874 *
webmaster@1 875 * The reasons for this are due to the different database engines:
webmaster@1 876 *
webmaster@1 877 * On PostgreSQL, changing a field definition involves adding a new field
webmaster@1 878 * and dropping an old one which* causes any indices, primary keys and
webmaster@1 879 * sequences (from serial-type fields) that use the changed field to be dropped.
webmaster@1 880 *
webmaster@1 881 * On MySQL, all type 'serial' fields must be part of at least one key
webmaster@1 882 * or index as soon as they are created. You cannot use
webmaster@1 883 * db_add_{primary_key,unique_key,index}() for this purpose because
webmaster@1 884 * the ALTER TABLE command will fail to add the column without a key
webmaster@1 885 * or index specification. The solution is to use the optional
webmaster@1 886 * $new_keys argument to create the key or index at the same time as
webmaster@1 887 * field.
webmaster@1 888 *
webmaster@1 889 * You could use db_add_{primary_key,unique_key,index}() in all cases
webmaster@1 890 * unless you are converting a field to be type serial. You can use
webmaster@1 891 * the $new_keys argument in all cases.
webmaster@1 892 *
webmaster@1 893 * @param $ret
webmaster@1 894 * Array to which query results will be added.
webmaster@1 895 * @param $table
webmaster@1 896 * Name of the table.
webmaster@1 897 * @param $field
webmaster@1 898 * Name of the field to change.
webmaster@1 899 * @param $field_new
webmaster@1 900 * New name for the field (set to the same as $field if you don't want to change the name).
webmaster@1 901 * @param $spec
webmaster@1 902 * The field specification for the new field.
webmaster@1 903 * @param $new_keys
webmaster@1 904 * Optional keys and indexes specification to be created on the
webmaster@1 905 * table along with changing the field. The format is the same as a
webmaster@1 906 * table specification but without the 'fields' element.
webmaster@1 907 */
webmaster@1 908 function db_change_field(&$ret, $table, $field, $field_new, $spec, $new_keys = array()) {
webmaster@1 909 $ret[] = update_sql("ALTER TABLE {". $table ."} RENAME $field TO ". $field ."_old");
webmaster@1 910 $not_null = isset($spec['not null']) ? $spec['not null'] : FALSE;
webmaster@1 911 unset($spec['not null']);
webmaster@1 912
webmaster@1 913 db_add_field($ret, $table, "$field_new", $spec);
webmaster@1 914
webmaster@1 915 $ret[] = update_sql("UPDATE {". $table ."} SET $field_new = ". $field ."_old");
webmaster@1 916
webmaster@1 917 if ($not_null) {
webmaster@1 918 $ret[] = update_sql("ALTER TABLE {". $table ."} ALTER $field_new SET NOT NULL");
webmaster@1 919 }
webmaster@1 920
webmaster@1 921 db_drop_field($ret, $table, $field .'_old');
webmaster@1 922
webmaster@1 923 if (isset($new_keys)) {
webmaster@1 924 _db_create_keys($ret, $table, $new_keys);
webmaster@1 925 }
webmaster@1 926 }
webmaster@1 927
webmaster@1 928 /**
webmaster@1 929 * @} End of "ingroup schemaapi".
webmaster@1 930 */
webmaster@1 931