PageRenderTime 44ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/adodb/datadict/datadict-postgres.inc.php

http://github.com/moodle/moodle
PHP | 484 lines | 369 code | 34 blank | 81 comment | 50 complexity | fa4838d2a9484733e42a1b0ca776a0e8 MD5 | raw file
Possible License(s): MIT, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, Apache-2.0, LGPL-2.1, BSD-3-Clause
  1. <?php
  2. /**
  3. @version v5.20.16 12-Jan-2020
  4. @copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
  5. @copyright (c) 2014 Damien Regad, Mark Newnham and the ADOdb community
  6. Released under both BSD license and Lesser GPL library license.
  7. Whenever there is any discrepancy between the two licenses,
  8. the BSD license will take precedence.
  9. Set tabs to 4 for best viewing.
  10. */
  11. // security - hide paths
  12. if (!defined('ADODB_DIR')) die();
  13. class ADODB2_postgres extends ADODB_DataDict {
  14. var $databaseType = 'postgres';
  15. var $seqField = false;
  16. var $seqPrefix = 'SEQ_';
  17. var $addCol = ' ADD COLUMN';
  18. var $quote = '"';
  19. var $renameTable = 'ALTER TABLE %s RENAME TO %s'; // at least since 7.1
  20. var $dropTable = 'DROP TABLE %s CASCADE';
  21. function MetaType($t,$len=-1,$fieldobj=false)
  22. {
  23. if (is_object($t)) {
  24. $fieldobj = $t;
  25. $t = $fieldobj->type;
  26. $len = $fieldobj->max_length;
  27. }
  28. $is_serial = is_object($fieldobj) && !empty($fieldobj->primary_key) && !empty($fieldobj->unique) &&
  29. !empty($fieldobj->has_default) && substr($fieldobj->default_value,0,8) == 'nextval(';
  30. switch (strtoupper($t)) {
  31. case 'INTERVAL':
  32. case 'CHAR':
  33. case 'CHARACTER':
  34. case 'VARCHAR':
  35. case 'NAME':
  36. case 'BPCHAR':
  37. if ($len <= $this->blobSize) return 'C';
  38. case 'TEXT':
  39. return 'X';
  40. case 'IMAGE': // user defined type
  41. case 'BLOB': // user defined type
  42. case 'BIT': // This is a bit string, not a single bit, so don't return 'L'
  43. case 'VARBIT':
  44. case 'BYTEA':
  45. return 'B';
  46. case 'BOOL':
  47. case 'BOOLEAN':
  48. return 'L';
  49. case 'DATE':
  50. return 'D';
  51. case 'TIME':
  52. case 'DATETIME':
  53. case 'TIMESTAMP':
  54. case 'TIMESTAMPTZ':
  55. return 'T';
  56. case 'INTEGER': return !$is_serial ? 'I' : 'R';
  57. case 'SMALLINT':
  58. case 'INT2': return !$is_serial ? 'I2' : 'R';
  59. case 'INT4': return !$is_serial ? 'I4' : 'R';
  60. case 'BIGINT':
  61. case 'INT8': return !$is_serial ? 'I8' : 'R';
  62. case 'OID':
  63. case 'SERIAL':
  64. return 'R';
  65. case 'FLOAT4':
  66. case 'FLOAT8':
  67. case 'DOUBLE PRECISION':
  68. case 'REAL':
  69. return 'F';
  70. default:
  71. return 'N';
  72. }
  73. }
  74. function ActualType($meta)
  75. {
  76. switch($meta) {
  77. case 'C': return 'VARCHAR';
  78. case 'XL':
  79. case 'X': return 'TEXT';
  80. case 'C2': return 'VARCHAR';
  81. case 'X2': return 'TEXT';
  82. case 'B': return 'BYTEA';
  83. case 'D': return 'DATE';
  84. case 'TS':
  85. case 'T': return 'TIMESTAMP';
  86. case 'L': return 'BOOLEAN';
  87. case 'I': return 'INTEGER';
  88. case 'I1': return 'SMALLINT';
  89. case 'I2': return 'INT2';
  90. case 'I4': return 'INT4';
  91. case 'I8': return 'INT8';
  92. case 'F': return 'FLOAT8';
  93. case 'N': return 'NUMERIC';
  94. default:
  95. return $meta;
  96. }
  97. }
  98. /**
  99. * Adding a new Column
  100. *
  101. * reimplementation of the default function as postgres does NOT allow to set the default in the same statement
  102. *
  103. * @param string $tabname table-name
  104. * @param string $flds column-names and types for the changed columns
  105. * @return array with SQL strings
  106. */
  107. function AddColumnSQL($tabname, $flds)
  108. {
  109. $tabname = $this->TableName ($tabname);
  110. $sql = array();
  111. $not_null = false;
  112. list($lines,$pkey) = $this->_GenFields($flds);
  113. $alter = 'ALTER TABLE ' . $tabname . $this->addCol . ' ';
  114. foreach($lines as $v) {
  115. if (($not_null = preg_match('/NOT NULL/i',$v))) {
  116. $v = preg_replace('/NOT NULL/i','',$v);
  117. }
  118. if (preg_match('/^([^ ]+) .*DEFAULT (\'[^\']+\'|\"[^\"]+\"|[^ ]+)/',$v,$matches)) {
  119. list(,$colname,$default) = $matches;
  120. $sql[] = $alter . str_replace('DEFAULT '.$default,'',$v);
  121. $sql[] = 'UPDATE '.$tabname.' SET '.$colname.'='.$default;
  122. $sql[] = 'ALTER TABLE '.$tabname.' ALTER COLUMN '.$colname.' SET DEFAULT ' . $default;
  123. } else {
  124. $sql[] = $alter . $v;
  125. }
  126. if ($not_null) {
  127. list($colname) = explode(' ',$v);
  128. $sql[] = 'ALTER TABLE '.$tabname.' ALTER COLUMN '.$colname.' SET NOT NULL';
  129. }
  130. }
  131. return $sql;
  132. }
  133. function DropIndexSQL ($idxname, $tabname = NULL)
  134. {
  135. return array(sprintf($this->dropIndex, $this->TableName($idxname), $this->TableName($tabname)));
  136. }
  137. /**
  138. * Change the definition of one column
  139. *
  140. * Postgres can't do that on it's own, you need to supply the complete defintion of the new table,
  141. * to allow, recreating the table and copying the content over to the new table
  142. * @param string $tabname table-name
  143. * @param string $flds column-name and type for the changed column
  144. * @param string $tableflds complete defintion of the new table, eg. for postgres, default ''
  145. * @param array/ $tableoptions options for the new table see CreateTableSQL, default ''
  146. * @return array with SQL strings
  147. */
  148. /*
  149. function AlterColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
  150. {
  151. if (!$tableflds) {
  152. if ($this->debug) ADOConnection::outp("AlterColumnSQL needs a complete table-definiton for PostgreSQL");
  153. return array();
  154. }
  155. return $this->_recreate_copy_table($tabname,False,$tableflds,$tableoptions);
  156. }*/
  157. function AlterColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
  158. {
  159. // Check if alter single column datatype available - works with 8.0+
  160. $has_alter_column = 8.0 <= (float) @$this->serverInfo['version'];
  161. if ($has_alter_column) {
  162. $tabname = $this->TableName($tabname);
  163. $sql = array();
  164. list($lines,$pkey) = $this->_GenFields($flds);
  165. $set_null = false;
  166. foreach($lines as $v) {
  167. $alter = 'ALTER TABLE ' . $tabname . $this->alterCol . ' ';
  168. if ($not_null = preg_match('/NOT NULL/i',$v)) {
  169. $v = preg_replace('/NOT NULL/i','',$v);
  170. }
  171. // this next block doesn't work - there is no way that I can see to
  172. // explicitly ask a column to be null using $flds
  173. else if ($set_null = preg_match('/NULL/i',$v)) {
  174. // if they didn't specify not null, see if they explicitely asked for null
  175. // Lookbehind pattern covers the case 'fieldname NULL datatype DEFAULT NULL'
  176. // only the first NULL should be removed, not the one specifying
  177. // the default value
  178. $v = preg_replace('/(?<!DEFAULT)\sNULL/i','',$v);
  179. }
  180. if (preg_match('/^([^ ]+) .*DEFAULT (\'[^\']+\'|\"[^\"]+\"|[^ ]+)/',$v,$matches)) {
  181. $existing = $this->MetaColumns($tabname);
  182. list(,$colname,$default) = $matches;
  183. $alter .= $colname;
  184. if ($this->connection) {
  185. $old_coltype = $this->connection->MetaType($existing[strtoupper($colname)]);
  186. }
  187. else {
  188. $old_coltype = $t;
  189. }
  190. $v = preg_replace('/^' . preg_quote($colname) . '\s/', '', $v);
  191. $t = trim(str_replace('DEFAULT '.$default,'',$v));
  192. // Type change from bool to int
  193. if ( $old_coltype == 'L' && $t == 'INTEGER' ) {
  194. $sql[] = $alter . ' DROP DEFAULT';
  195. $sql[] = $alter . " TYPE $t USING ($colname::BOOL)::INT";
  196. $sql[] = $alter . " SET DEFAULT $default";
  197. }
  198. // Type change from int to bool
  199. else if ( $old_coltype == 'I' && $t == 'BOOLEAN' ) {
  200. if( strcasecmp('NULL', trim($default)) != 0 ) {
  201. $default = $this->connection->qstr($default);
  202. }
  203. $sql[] = $alter . ' DROP DEFAULT';
  204. $sql[] = $alter . " TYPE $t USING CASE WHEN $colname = 0 THEN false ELSE true END";
  205. $sql[] = $alter . " SET DEFAULT $default";
  206. }
  207. // Any other column types conversion
  208. else {
  209. $sql[] = $alter . " TYPE $t";
  210. $sql[] = $alter . " SET DEFAULT $default";
  211. }
  212. }
  213. else {
  214. // drop default?
  215. preg_match ('/^\s*(\S+)\s+(.*)$/',$v,$matches);
  216. list (,$colname,$rest) = $matches;
  217. $alter .= $colname;
  218. $sql[] = $alter . ' TYPE ' . $rest;
  219. }
  220. # list($colname) = explode(' ',$v);
  221. if ($not_null) {
  222. // this does not error out if the column is already not null
  223. $sql[] = $alter . ' SET NOT NULL';
  224. }
  225. if ($set_null) {
  226. // this does not error out if the column is already null
  227. $sql[] = $alter . ' DROP NOT NULL';
  228. }
  229. }
  230. return $sql;
  231. }
  232. // does not have alter column
  233. if (!$tableflds) {
  234. if ($this->debug) ADOConnection::outp("AlterColumnSQL needs a complete table-definiton for PostgreSQL");
  235. return array();
  236. }
  237. return $this->_recreate_copy_table($tabname,False,$tableflds,$tableoptions);
  238. }
  239. /**
  240. * Drop one column
  241. *
  242. * Postgres < 7.3 can't do that on it's own, you need to supply the complete defintion of the new table,
  243. * to allow, recreating the table and copying the content over to the new table
  244. * @param string $tabname table-name
  245. * @param string $flds column-name and type for the changed column
  246. * @param string $tableflds complete defintion of the new table, eg. for postgres, default ''
  247. * @param array/ $tableoptions options for the new table see CreateTableSQL, default ''
  248. * @return array with SQL strings
  249. */
  250. function DropColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
  251. {
  252. $has_drop_column = 7.3 <= (float) @$this->serverInfo['version'];
  253. if (!$has_drop_column && !$tableflds) {
  254. if ($this->debug) ADOConnection::outp("DropColumnSQL needs complete table-definiton for PostgreSQL < 7.3");
  255. return array();
  256. }
  257. if ($has_drop_column) {
  258. return ADODB_DataDict::DropColumnSQL($tabname, $flds);
  259. }
  260. return $this->_recreate_copy_table($tabname,$flds,$tableflds,$tableoptions);
  261. }
  262. /**
  263. * Save the content into a temp. table, drop and recreate the original table and copy the content back in
  264. *
  265. * We also take care to set the values of the sequenz and recreate the indexes.
  266. * All this is done in a transaction, to not loose the content of the table, if something went wrong!
  267. * @internal
  268. * @param string $tabname table-name
  269. * @param string $dropflds column-names to drop
  270. * @param string $tableflds complete defintion of the new table, eg. for postgres
  271. * @param array/string $tableoptions options for the new table see CreateTableSQL, default ''
  272. * @return array with SQL strings
  273. */
  274. function _recreate_copy_table($tabname,$dropflds,$tableflds,$tableoptions='')
  275. {
  276. if ($dropflds && !is_array($dropflds)) $dropflds = explode(',',$dropflds);
  277. $copyflds = array();
  278. foreach($this->MetaColumns($tabname) as $fld) {
  279. if (!$dropflds || !in_array($fld->name,$dropflds)) {
  280. // we need to explicit convert varchar to a number to be able to do an AlterColumn of a char column to a nummeric one
  281. if (preg_match('/'.$fld->name.' (I|I2|I4|I8|N|F)/i',$tableflds,$matches) &&
  282. in_array($fld->type,array('varchar','char','text','bytea'))) {
  283. $copyflds[] = "to_number($fld->name,'S9999999999999D99')";
  284. } else {
  285. $copyflds[] = $fld->name;
  286. }
  287. // identify the sequence name and the fld its on
  288. if ($fld->primary_key && $fld->has_default &&
  289. preg_match("/nextval\('([^']+)'::text\)/",$fld->default_value,$matches)) {
  290. $seq_name = $matches[1];
  291. $seq_fld = $fld->name;
  292. }
  293. }
  294. }
  295. $copyflds = implode(', ',$copyflds);
  296. $tempname = $tabname.'_tmp';
  297. $aSql[] = 'BEGIN'; // we use a transaction, to make sure not to loose the content of the table
  298. $aSql[] = "SELECT * INTO TEMPORARY TABLE $tempname FROM $tabname";
  299. $aSql = array_merge($aSql,$this->DropTableSQL($tabname));
  300. $aSql = array_merge($aSql,$this->CreateTableSQL($tabname,$tableflds,$tableoptions));
  301. $aSql[] = "INSERT INTO $tabname SELECT $copyflds FROM $tempname";
  302. if ($seq_name && $seq_fld) { // if we have a sequence we need to set it again
  303. $seq_name = $tabname.'_'.$seq_fld.'_seq'; // has to be the name of the new implicit sequence
  304. $aSql[] = "SELECT setval('$seq_name',MAX($seq_fld)) FROM $tabname";
  305. }
  306. $aSql[] = "DROP TABLE $tempname";
  307. // recreate the indexes, if they not contain one of the droped columns
  308. foreach($this->MetaIndexes($tabname) as $idx_name => $idx_data)
  309. {
  310. if (substr($idx_name,-5) != '_pkey' && (!$dropflds || !count(array_intersect($dropflds,$idx_data['columns'])))) {
  311. $aSql = array_merge($aSql,$this->CreateIndexSQL($idx_name,$tabname,$idx_data['columns'],
  312. $idx_data['unique'] ? array('UNIQUE') : False));
  313. }
  314. }
  315. $aSql[] = 'COMMIT';
  316. return $aSql;
  317. }
  318. function DropTableSQL($tabname)
  319. {
  320. $sql = ADODB_DataDict::DropTableSQL($tabname);
  321. $drop_seq = $this->_DropAutoIncrement($tabname);
  322. if ($drop_seq) $sql[] = $drop_seq;
  323. return $sql;
  324. }
  325. // return string must begin with space
  326. function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
  327. {
  328. if ($fautoinc) {
  329. $ftype = 'SERIAL';
  330. return '';
  331. }
  332. $suffix = '';
  333. if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
  334. if ($fnotnull) $suffix .= ' NOT NULL';
  335. if ($fconstraint) $suffix .= ' '.$fconstraint;
  336. return $suffix;
  337. }
  338. // search for a sequece for the given table (asumes the seqence-name contains the table-name!)
  339. // if yes return sql to drop it
  340. // this is still necessary if postgres < 7.3 or the SERIAL was created on an earlier version!!!
  341. function _DropAutoIncrement($tabname)
  342. {
  343. $tabname = $this->connection->quote('%'.$tabname.'%');
  344. $seq = $this->connection->GetOne("SELECT relname FROM pg_class WHERE NOT relname ~ 'pg_.*' AND relname LIKE $tabname AND relkind='S'");
  345. // check if a tables depends on the sequenz and it therefor cant and dont need to be droped separatly
  346. 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'")) {
  347. return False;
  348. }
  349. return "DROP SEQUENCE ".$seq;
  350. }
  351. function RenameTableSQL($tabname,$newname)
  352. {
  353. if (!empty($this->schema)) {
  354. $rename_from = $this->TableName($tabname);
  355. $schema_save = $this->schema;
  356. $this->schema = false;
  357. $rename_to = $this->TableName($newname);
  358. $this->schema = $schema_save;
  359. return array (sprintf($this->renameTable, $rename_from, $rename_to));
  360. }
  361. return array (sprintf($this->renameTable, $this->TableName($tabname),$this->TableName($newname)));
  362. }
  363. /*
  364. CREATE [ [ LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name (
  365. { column_name data_type [ DEFAULT default_expr ] [ column_constraint [, ... ] ]
  366. | table_constraint } [, ... ]
  367. )
  368. [ INHERITS ( parent_table [, ... ] ) ]
  369. [ WITH OIDS | WITHOUT OIDS ]
  370. where column_constraint is:
  371. [ CONSTRAINT constraint_name ]
  372. { NOT NULL | NULL | UNIQUE | PRIMARY KEY |
  373. CHECK (expression) |
  374. REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL ]
  375. [ ON DELETE action ] [ ON UPDATE action ] }
  376. [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
  377. and table_constraint is:
  378. [ CONSTRAINT constraint_name ]
  379. { UNIQUE ( column_name [, ... ] ) |
  380. PRIMARY KEY ( column_name [, ... ] ) |
  381. CHECK ( expression ) |
  382. FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ]
  383. [ MATCH FULL | MATCH PARTIAL ] [ ON DELETE action ] [ ON UPDATE action ] }
  384. [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
  385. */
  386. /*
  387. CREATE [ UNIQUE ] INDEX index_name ON table
  388. [ USING acc_method ] ( column [ ops_name ] [, ...] )
  389. [ WHERE predicate ]
  390. CREATE [ UNIQUE ] INDEX index_name ON table
  391. [ USING acc_method ] ( func_name( column [, ... ]) [ ops_name ] )
  392. [ WHERE predicate ]
  393. */
  394. function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
  395. {
  396. $sql = array();
  397. if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
  398. $sql[] = sprintf ($this->dropIndex, $idxname, $tabname);
  399. if ( isset($idxoptions['DROP']) )
  400. return $sql;
  401. }
  402. if ( empty ($flds) ) {
  403. return $sql;
  404. }
  405. $unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';
  406. $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' ';
  407. if (isset($idxoptions['HASH']))
  408. $s .= 'USING HASH ';
  409. if ( isset($idxoptions[$this->upperName]) )
  410. $s .= $idxoptions[$this->upperName];
  411. if ( is_array($flds) )
  412. $flds = implode(', ',$flds);
  413. $s .= '(' . $flds . ')';
  414. $sql[] = $s;
  415. return $sql;
  416. }
  417. function _GetSize($ftype, $ty, $fsize, $fprec)
  418. {
  419. if (strlen($fsize) && $ty != 'X' && $ty != 'B' && $ty != 'I' && strpos($ftype,'(') === false) {
  420. $ftype .= "(".$fsize;
  421. if (strlen($fprec)) $ftype .= ",".$fprec;
  422. $ftype .= ')';
  423. }
  424. return $ftype;
  425. }
  426. }