Differences Between: [Versions 310 and 400] [Versions 311 and 400] [Versions 39 and 400] [Versions 400 and 401] [Versions 400 and 402] [Versions 400 and 403]
1 <?php 2 /** 3 * Data Dictionary for PostgreSQL. 4 * 5 * This file is part of ADOdb, a Database Abstraction Layer library for PHP. 6 * 7 * @package ADOdb 8 * @link https://adodb.org Project's web site and documentation 9 * @link https://github.com/ADOdb/ADOdb Source code and issue tracker 10 * 11 * The ADOdb Library is dual-licensed, released under both the BSD 3-Clause 12 * and the GNU Lesser General Public Licence (LGPL) v2.1 or, at your option, 13 * any later version. This means you can use it in proprietary products. 14 * See the LICENSE.md file distributed with this source code for details. 15 * @license BSD-3-Clause 16 * @license LGPL-2.1-or-later 17 * 18 * @copyright 2000-2013 John Lim 19 * @copyright 2014 Damien Regad, Mark Newnham and the ADOdb community 20 */ 21 22 // security - hide paths 23 if (!defined('ADODB_DIR')) die(); 24 25 class ADODB2_postgres extends ADODB_DataDict 26 { 27 var $databaseType = 'postgres'; 28 var $seqField = false; 29 var $seqPrefix = 'SEQ_'; 30 var $addCol = ' ADD COLUMN'; 31 var $quote = '"'; 32 var $renameTable = 'ALTER TABLE %s RENAME TO %s'; // at least since 7.1 33 var $dropTable = 'DROP TABLE %s CASCADE'; 34 35 public $blobAllowsDefaultValue = true; 36 public $blobAllowsNotNull = true; 37 38 function metaType($t, $len=-1, $fieldobj=false) 39 { 40 if (is_object($t)) { 41 $fieldobj = $t; 42 $t = $fieldobj->type; 43 $len = $fieldobj->max_length; 44 } 45 $is_serial = is_object($fieldobj) && !empty($fieldobj->primary_key) && !empty($fieldobj->unique) && 46 !empty($fieldobj->has_default) && substr($fieldobj->default_value,0,8) == 'nextval('; 47 48 switch (strtoupper($t)) { 49 case 'INTERVAL': 50 case 'CHAR': 51 case 'CHARACTER': 52 case 'VARCHAR': 53 case 'NAME': 54 case 'BPCHAR': 55 if ($len <= $this->blobSize) return 'C'; 56 57 case 'TEXT': 58 return 'X'; 59 60 case 'IMAGE': // user defined type 61 case 'BLOB': // user defined type 62 case 'BIT': // This is a bit string, not a single bit, so don't return 'L' 63 case 'VARBIT': 64 case 'BYTEA': 65 return 'B'; 66 67 case 'BOOL': 68 case 'BOOLEAN': 69 return 'L'; 70 71 case 'DATE': 72 return 'D'; 73 74 case 'TIME': 75 case 'DATETIME': 76 case 'TIMESTAMP': 77 case 'TIMESTAMPTZ': 78 return 'T'; 79 80 case 'INTEGER': return !$is_serial ? 'I' : 'R'; 81 case 'SMALLINT': 82 case 'INT2': return !$is_serial ? 'I2' : 'R'; 83 case 'INT4': return !$is_serial ? 'I4' : 'R'; 84 case 'BIGINT': 85 case 'INT8': return !$is_serial ? 'I8' : 'R'; 86 87 case 'OID': 88 case 'SERIAL': 89 return 'R'; 90 91 case 'FLOAT4': 92 case 'FLOAT8': 93 case 'DOUBLE PRECISION': 94 case 'REAL': 95 return 'F'; 96 97 default: 98 return ADODB_DEFAULT_METATYPE; 99 } 100 } 101 102 function actualType($meta) 103 { 104 switch ($meta) { 105 case 'C': return 'VARCHAR'; 106 case 'XL': 107 case 'X': return 'TEXT'; 108 109 case 'C2': return 'VARCHAR'; 110 case 'X2': return 'TEXT'; 111 112 case 'B': return 'BYTEA'; 113 114 case 'D': return 'DATE'; 115 case 'TS': 116 case 'T': return 'TIMESTAMP'; 117 118 case 'L': return 'BOOLEAN'; 119 case 'I': return 'INTEGER'; 120 case 'I1': return 'SMALLINT'; 121 case 'I2': return 'INT2'; 122 case 'I4': return 'INT4'; 123 case 'I8': return 'INT8'; 124 125 case 'F': return 'FLOAT8'; 126 case 'N': return 'NUMERIC'; 127 default: 128 return $meta; 129 } 130 } 131 132 /** 133 * Adding a new Column 134 * 135 * reimplementation of the default function as postgres does NOT allow to set the default in the same statement 136 * 137 * @param string $tabname table-name 138 * @param string $flds column-names and types for the changed columns 139 * @return array with SQL strings 140 */ 141 function addColumnSQL($tabname, $flds) 142 { 143 $tabname = $this->tableName($tabname); 144 $sql = array(); 145 $not_null = false; 146 list($lines,$pkey) = $this->_genFields($flds); 147 $alter = 'ALTER TABLE ' . $tabname . $this->addCol . ' '; 148 foreach($lines as $v) { 149 if (($not_null = preg_match('/NOT NULL/i',$v))) { 150 $v = preg_replace('/NOT NULL/i','',$v); 151 } 152 if (preg_match('/^([^ ]+) .*DEFAULT (\'[^\']+\'|\"[^\"]+\"|[^ ]+)/',$v,$matches)) { 153 list(,$colname,$default) = $matches; 154 $sql[] = $alter . str_replace('DEFAULT '.$default,'',$v); 155 $sql[] = 'UPDATE '.$tabname.' SET '.$colname.'='.$default; 156 $sql[] = 'ALTER TABLE '.$tabname.' ALTER COLUMN '.$colname.' SET DEFAULT ' . $default; 157 } else { 158 $sql[] = $alter . $v; 159 } 160 if ($not_null) { 161 list($colname) = explode(' ',$v); 162 $sql[] = 'ALTER TABLE '.$tabname.' ALTER COLUMN '.$colname.' SET NOT NULL'; 163 } 164 } 165 return $sql; 166 } 167 168 169 function dropIndexSQL($idxname, $tabname = NULL) 170 { 171 return array(sprintf($this->dropIndex, $this->tableName($idxname), $this->tableName($tabname))); 172 } 173 174 /** 175 * Change the definition of one column 176 * 177 * Postgres can't do that on it's own, you need to supply the complete definition of the new table, 178 * to allow, recreating the table and copying the content over to the new table 179 * @param string $tabname table-name 180 * @param string $flds column-name and type for the changed column 181 * @param string $tableflds complete definition of the new table, eg. for postgres, default '' 182 * @param array/ $tableoptions options for the new table see CreateTableSQL, default '' 183 * @return array with SQL strings 184 */ 185 function alterColumnSQL($tabname, $flds, $tableflds='', $tableoptions='') 186 { 187 // Check if alter single column datatype available - works with 8.0+ 188 $has_alter_column = 8.0 <= (float) @$this->serverInfo['version']; 189 190 if ($has_alter_column) { 191 $tabname = $this->tableName($tabname); 192 $sql = array(); 193 list($lines,$pkey) = $this->_genFields($flds); 194 $set_null = false; 195 foreach($lines as $v) { 196 $alter = 'ALTER TABLE ' . $tabname . $this->alterCol . ' '; 197 if ($not_null = preg_match('/NOT NULL/i',$v)) { 198 $v = preg_replace('/NOT NULL/i','',$v); 199 } 200 // this next block doesn't work - there is no way that I can see to 201 // explicitly ask a column to be null using $flds 202 else if ($set_null = preg_match('/NULL/i',$v)) { 203 // if they didn't specify not null, see if they explicitly asked for null 204 // Lookbehind pattern covers the case 'fieldname NULL datatype DEFAULT NULL' 205 // only the first NULL should be removed, not the one specifying 206 // the default value 207 $v = preg_replace('/(?<!DEFAULT)\sNULL/i','',$v); 208 } 209 210 if (preg_match('/^([^ ]+) .*DEFAULT (\'[^\']+\'|\"[^\"]+\"|[^ ]+)/',$v,$matches)) { 211 $existing = $this->metaColumns($tabname); 212 list(,$colname,$default) = $matches; 213 $alter .= $colname; 214 if ($this->connection) { 215 $old_coltype = $this->connection->metaType($existing[strtoupper($colname)]); 216 } else { 217 $old_coltype = $t; 218 } 219 $v = preg_replace('/^' . preg_quote($colname) . '\s/', '', $v); 220 $t = trim(str_replace('DEFAULT '.$default,'',$v)); 221 222 // Type change from bool to int 223 if ( $old_coltype == 'L' && $t == 'INTEGER' ) { 224 $sql[] = $alter . ' DROP DEFAULT'; 225 $sql[] = $alter . " TYPE $t USING ($colname::BOOL)::INT"; 226 $sql[] = $alter . " SET DEFAULT $default"; 227 } 228 // Type change from int to bool 229 else if ( $old_coltype == 'I' && $t == 'BOOLEAN' ) { 230 if( strcasecmp('NULL', trim($default)) != 0 ) { 231 $default = $this->connection->qstr($default); 232 } 233 $sql[] = $alter . ' DROP DEFAULT'; 234 $sql[] = $alter . " TYPE $t USING CASE WHEN $colname = 0 THEN false ELSE true END"; 235 $sql[] = $alter . " SET DEFAULT $default"; 236 } 237 // Any other column types conversion 238 else { 239 $sql[] = $alter . " TYPE $t"; 240 $sql[] = $alter . " SET DEFAULT $default"; 241 } 242 243 } 244 else { 245 // drop default? 246 preg_match ('/^\s*(\S+)\s+(.*)$/',$v,$matches); 247 list (,$colname,$rest) = $matches; 248 $alter .= $colname; 249 $sql[] = $alter . ' TYPE ' . $rest; 250 } 251 252 #list($colname) = explode(' ',$v); 253 if ($not_null) { 254 // this does not error out if the column is already not null 255 $sql[] = $alter . ' SET NOT NULL'; 256 } 257 if ($set_null) { 258 // this does not error out if the column is already null 259 $sql[] = $alter . ' DROP NOT NULL'; 260 } 261 } 262 return $sql; 263 } 264 265 // does not have alter column 266 if (!$tableflds) { 267 if ($this->debug) ADOConnection::outp("AlterColumnSQL needs a complete table-definiton for PostgreSQL"); 268 return array(); 269 } 270 return $this->_recreate_copy_table($tabname, false, $tableflds,$tableoptions); 271 } 272 273 /** 274 * Drop one column 275 * 276 * Postgres < 7.3 can't do that on it's own, you need to supply the complete definition of the new table, 277 * to allow, recreating the table and copying the content over to the new table 278 * @param string $tabname table-name 279 * @param string $flds column-name and type for the changed column 280 * @param string $tableflds complete definition of the new table, eg. for postgres, default '' 281 * @param array/ $tableoptions options for the new table see CreateTableSQL, default '' 282 * @return array with SQL strings 283 */ 284 function dropColumnSQL($tabname, $flds, $tableflds='', $tableoptions='') 285 { 286 $has_drop_column = 7.3 <= (float) @$this->serverInfo['version']; 287 if (!$has_drop_column && !$tableflds) { 288 if ($this->debug) { 289 ADOConnection::outp("dropColumnSQL needs complete table-definiton for PostgreSQL < 7.3"); 290 } 291 return array(); 292 } 293 if ($has_drop_column) { 294 return ADODB_DataDict::dropColumnSQL($tabname, $flds); 295 } 296 return $this->_recreate_copy_table($tabname, $flds, $tableflds, $tableoptions); 297 } 298 299 /** 300 * Save the content into a temp. table, drop and recreate the original table and copy the content back in 301 * 302 * We also take care to set the values of the sequenz and recreate the indexes. 303 * All this is done in a transaction, to not loose the content of the table, if something went wrong! 304 * @internal 305 * @param string $tabname table-name 306 * @param string $dropflds column-names to drop 307 * @param string $tableflds complete definition of the new table, eg. for postgres 308 * @param array/string $tableoptions options for the new table see CreateTableSQL, default '' 309 * @return array with SQL strings 310 */ 311 function _recreate_copy_table($tabname, $dropflds, $tableflds, $tableoptions='') 312 { 313 if ($dropflds && !is_array($dropflds)) $dropflds = explode(',',$dropflds); 314 $copyflds = array(); 315 foreach($this->metaColumns($tabname) as $fld) { 316 if (preg_match('/'.$fld->name.' (\w+)/i', $tableflds, $matches)) { 317 $new_type = strtoupper($matches[1]); 318 // AlterColumn of a char column to a nummeric one needs an explicit conversation 319 if (in_array($new_type, array('I', 'I2', 'I4', 'I8', 'N', 'F')) && 320 in_array($fld->type, array('varchar','char','text','bytea')) 321 ) { 322 $copyflds[] = "to_number($fld->name,'S9999999999999D99')"; 323 } else { 324 // other column-type changes needs explicit decode, encode for bytea or cast otherwise 325 $new_actual_type = $this->actualType($new_type); 326 if (strtoupper($fld->type) != $new_actual_type) { 327 if ($new_actual_type == 'BYTEA' && $fld->type == 'text') { 328 $copyflds[] = "DECODE($fld->name, 'escape')"; 329 } elseif ($fld->type == 'bytea' && $new_actual_type == 'TEXT') { 330 $copyflds[] = "ENCODE($fld->name, 'escape')"; 331 } else { 332 $copyflds[] = "CAST($fld->name AS $new_actual_type)"; 333 } 334 } 335 } 336 } else { 337 $copyflds[] = $fld->name; 338 } 339 // identify the sequence name and the fld its on 340 if ($fld->primary_key && $fld->has_default && 341 preg_match("/nextval\('([^']+)'::(text|regclass)\)/", $fld->default_value, $matches)) { 342 $seq_name = $matches[1]; 343 $seq_fld = $fld->name; 344 } 345 } 346 $copyflds = implode(', ', $copyflds); 347 348 $tempname = $tabname.'_tmp'; 349 $aSql[] = 'BEGIN'; // we use a transaction, to make sure not to loose the content of the table 350 $aSql[] = "SELECT * INTO TEMPORARY TABLE $tempname FROM $tabname"; 351 $aSql = array_merge($aSql,$this->dropTableSQL($tabname)); 352 $aSql = array_merge($aSql,$this->createTableSQL($tabname, $tableflds, $tableoptions)); 353 $aSql[] = "INSERT INTO $tabname SELECT $copyflds FROM $tempname"; 354 if ($seq_name && $seq_fld) { // if we have a sequence we need to set it again 355 $seq_name = $tabname.'_'.$seq_fld.'_seq'; // has to be the name of the new implicit sequence 356 $aSql[] = "SELECT setval('$seq_name', MAX($seq_fld)) FROM $tabname"; 357 } 358 $aSql[] = "DROP TABLE $tempname"; 359 // recreate the indexes, if they not contain one of the dropped columns 360 foreach($this->metaIndexes($tabname) as $idx_name => $idx_data) { 361 if (substr($idx_name,-5) != '_pkey' && (!$dropflds || !count(array_intersect($dropflds,$idx_data['columns'])))) { 362 $aSql = array_merge($aSql,$this->createIndexSQL($idx_name, $tabname, $idx_data['columns'], 363 $idx_data['unique'] ? array('UNIQUE') : false)); 364 } 365 } 366 $aSql[] = 'COMMIT'; 367 return $aSql; 368 } 369 370 function dropTableSQL($tabname) 371 { 372 $sql = ADODB_DataDict::dropTableSQL($tabname); 373 374 $drop_seq = $this->_dropAutoIncrement($tabname); 375 if ($drop_seq) { 376 $sql[] = $drop_seq; 377 } 378 return $sql; 379 } 380 381 // return string must begin with space 382 function _createSuffix($fname, &$ftype, $fnotnull, $fdefault, $fautoinc, $fconstraint, $funsigned) 383 { 384 if ($fautoinc) { 385 $ftype = 'SERIAL'; 386 return ''; 387 } 388 $suffix = ''; 389 if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault"; 390 if ($fnotnull) $suffix .= ' NOT NULL'; 391 if ($fconstraint) $suffix .= ' '.$fconstraint; 392 return $suffix; 393 } 394 395 // search for a sequence for the given table (asumes the seqence-name contains the table-name!) 396 // if yes return sql to drop it 397 // this is still necessary if postgres < 7.3 or the SERIAL was created on an earlier version!!! 398 function _dropAutoIncrement($tabname) 399 { 400 $tabname = $this->connection->quote('%'.$tabname.'%'); 401 402 $seq = $this->connection->getOne("SELECT relname FROM pg_class WHERE NOT relname ~ 'pg_.*' AND relname LIKE $tabname AND relkind='S'"); 403 404 // check if a tables depends on the sequence and it therefore can't and don't need to be dropped separately 405 if (!$seq || $this->connection->getOne("SELECT relname FROM pg_class JOIN pg_depend ON pg_class.relfilenode=pg_depend.objid WHERE relname='$seq' AND relkind='S' AND deptype='i'")) { 406 return false; 407 } 408 return "DROP SEQUENCE ".$seq; 409 } 410 411 function renameTableSQL($tabname, $newname) 412 { 413 if (!empty($this->schema)) { 414 $rename_from = $this->tableName($tabname); 415 $schema_save = $this->schema; 416 $this->schema = false; 417 $rename_to = $this->tableName($newname); 418 $this->schema = $schema_save; 419 return array (sprintf($this->renameTable, $rename_from, $rename_to)); 420 } 421 422 return array (sprintf($this->renameTable, $this->tableName($tabname), $this->tableName($newname))); 423 } 424 425 /* 426 CREATE [ [ LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name ( 427 { column_name data_type [ DEFAULT default_expr ] [ column_constraint [, ... ] ] 428 | table_constraint } [, ... ] 429 ) 430 [ INHERITS ( parent_table [, ... ] ) ] 431 [ WITH OIDS | WITHOUT OIDS ] 432 where column_constraint is: 433 [ CONSTRAINT constraint_name ] 434 { NOT NULL | NULL | UNIQUE | PRIMARY KEY | 435 CHECK (expression) | 436 REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL ] 437 [ ON DELETE action ] [ ON UPDATE action ] } 438 [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ] 439 and table_constraint is: 440 [ CONSTRAINT constraint_name ] 441 { UNIQUE ( column_name [, ... ] ) | 442 PRIMARY KEY ( column_name [, ... ] ) | 443 CHECK ( expression ) | 444 FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] 445 [ MATCH FULL | MATCH PARTIAL ] [ ON DELETE action ] [ ON UPDATE action ] } 446 [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ] 447 */ 448 449 450 /* 451 CREATE [ UNIQUE ] INDEX index_name ON table 452 [ USING acc_method ] ( column [ ops_name ] [, ...] ) 453 [ WHERE predicate ] 454 CREATE [ UNIQUE ] INDEX index_name ON table 455 [ USING acc_method ] ( func_name( column [, ... ]) [ ops_name ] ) 456 [ WHERE predicate ] 457 */ 458 function _indexSQL($idxname, $tabname, $flds, $idxoptions) 459 { 460 $sql = array(); 461 462 if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) { 463 $sql[] = sprintf ($this->dropIndex, $idxname, $tabname); 464 if ( isset($idxoptions['DROP']) ) { 465 return $sql; 466 } 467 } 468 469 if (empty($flds)) { 470 return $sql; 471 } 472 473 $unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : ''; 474 475 $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' '; 476 477 if (isset($idxoptions['HASH'])) { 478 $s .= 'USING HASH '; 479 } 480 481 if (isset($idxoptions[$this->upperName])) { 482 $s .= $idxoptions[$this->upperName]; 483 } 484 485 if (is_array($flds)) { 486 $flds = implode(', ', $flds); 487 } 488 $s .= '(' . $flds . ')'; 489 $sql[] = $s; 490 491 return $sql; 492 } 493 494 function _getSize($ftype, $ty, $fsize, $fprec, $options=false) 495 { 496 if (strlen($fsize) && $ty != 'X' && $ty != 'B' && $ty != 'I' && strpos($ftype,'(') === false) { 497 $ftype .= "(".$fsize; 498 if (strlen($fprec)) $ftype .= ",".$fprec; 499 $ftype .= ')'; 500 } 501 502 /* 503 * Handle additional options 504 */ 505 if (is_array($options)) { 506 foreach($options as $type=>$value) { 507 switch ($type) { 508 case 'ENUM': 509 $ftype .= '(' . $value . ')'; 510 break; 511 default: 512 } 513 } 514 } 515 return $ftype; 516 } 517 518 function changeTableSQL($tablename, $flds, $tableoptions = false, $dropOldFlds=false) 519 { 520 global $ADODB_FETCH_MODE; 521 parent::changeTableSQL($tablename, $flds); 522 $save = $ADODB_FETCH_MODE; 523 $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; 524 if ($this->connection->fetchMode !== false) { 525 $savem = $this->connection->setFetchMode(false); 526 } 527 528 // check table exists 529 $save_handler = $this->connection->raiseErrorFn; 530 $this->connection->raiseErrorFn = ''; 531 $cols = $this->metaColumns($tablename); 532 $this->connection->raiseErrorFn = $save_handler; 533 534 if (isset($savem)) { 535 $this->connection->setFetchMode($savem); 536 } 537 $ADODB_FETCH_MODE = $save; 538 539 $sqlResult=array(); 540 if ( empty($cols)) { 541 $sqlResult=$this->createTableSQL($tablename, $flds, $tableoptions); 542 } else { 543 $sqlResultAdd = $this->addColumnSQL($tablename, $flds); 544 $sqlResultAlter = $this->alterColumnSQL($tablename, $flds, '', $tableoptions); 545 $sqlResult = array_merge((array)$sqlResultAdd, (array)$sqlResultAlter); 546 547 if ($dropOldFlds) { 548 // already exists, alter table instead 549 list($lines,$pkey,$idxs) = $this->_genFields($flds); 550 // genfields can return FALSE at times 551 if ($lines == null) { 552 $lines = array(); 553 } 554 $alter = 'ALTER TABLE ' . $this->tableName($tablename); 555 foreach ( $cols as $id => $v ) { 556 if ( !isset($lines[$id]) ) { 557 $sqlResult[] = $alter . $this->dropCol . ' ' . $v->name; 558 } 559 } 560 } 561 562 } 563 return $sqlResult; 564 } 565 } // end class
title
Description
Body
title
Description
Body
title
Description
Body
title
Body