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