PageRenderTime 49ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/concreteOLD/libraries/3rdparty/adodb/datadict/datadict-postgres.inc.php

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