source: sipes/cord/includes/database.pgsql.inc @ 52861f4

stableversion-3.0
Last change on this file since 52861f4 was d7a822e, checked in by José Gregorio Puentes <jpuentes@…>, 8 años ago

se agrego el directorio del cord

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