PageRenderTime 44ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/includes/pear/MDB2/Driver/Reverse/pgsql.php

https://bitbucket.org/Yason/armory
PHP | 573 lines | 409 code | 40 blank | 124 comment | 57 complexity | c042d6bad241aae0e7474dae8367ab00 MD5 | raw file
Possible License(s): GPL-3.0
  1. <?php
  2. // +----------------------------------------------------------------------+
  3. // | PHP versions 4 and 5 |
  4. // +----------------------------------------------------------------------+
  5. // | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, |
  6. // | Stig. S. Bakken, Lukas Smith |
  7. // | All rights reserved. |
  8. // +----------------------------------------------------------------------+
  9. // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
  10. // | API as well as database abstraction for PHP applications. |
  11. // | This LICENSE is in the BSD license style. |
  12. // | |
  13. // | Redistribution and use in source and binary forms, with or without |
  14. // | modification, are permitted provided that the following conditions |
  15. // | are met: |
  16. // | |
  17. // | Redistributions of source code must retain the above copyright |
  18. // | notice, this list of conditions and the following disclaimer. |
  19. // | |
  20. // | Redistributions in binary form must reproduce the above copyright |
  21. // | notice, this list of conditions and the following disclaimer in the |
  22. // | documentation and/or other materials provided with the distribution. |
  23. // | |
  24. // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
  25. // | Lukas Smith nor the names of his contributors may be used to endorse |
  26. // | or promote products derived from this software without specific prior|
  27. // | written permission. |
  28. // | |
  29. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
  30. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
  31. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
  32. // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
  33. // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
  34. // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
  35. // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
  36. // | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
  37. // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
  38. // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
  39. // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
  40. // | POSSIBILITY OF SUCH DAMAGE. |
  41. // +----------------------------------------------------------------------+
  42. // | Authors: Paul Cooper <pgc@ucecom.com> |
  43. // | Lorenzo Alberton <l.alberton@quipo.it> |
  44. // +----------------------------------------------------------------------+
  45. //
  46. // $Id: pgsql.php,v 1.75 2008/08/22 16:36:20 quipo Exp $
  47. require_once 'MDB2/Driver/Reverse/Common.php';
  48. /**
  49. * MDB2 PostGreSQL driver for the schema reverse engineering module
  50. *
  51. * @package MDB2
  52. * @category Database
  53. * @author Paul Cooper <pgc@ucecom.com>
  54. * @author Lorenzo Alberton <l.alberton@quipo.it>
  55. */
  56. class MDB2_Driver_Reverse_pgsql extends MDB2_Driver_Reverse_Common
  57. {
  58. // {{{ getTableFieldDefinition()
  59. /**
  60. * Get the structure of a field into an array
  61. *
  62. * @param string $table_name name of table that should be used in method
  63. * @param string $field_name name of field that should be used in method
  64. * @return mixed data array on success, a MDB2 error on failure
  65. * @access public
  66. */
  67. function getTableFieldDefinition($table_name, $field_name)
  68. {
  69. $db =& $this->getDBInstance();
  70. if (PEAR::isError($db)) {
  71. return $db;
  72. }
  73. $result = $db->loadModule('Datatype', null, true);
  74. if (PEAR::isError($result)) {
  75. return $result;
  76. }
  77. list($schema, $table) = $this->splitTableSchema($table_name);
  78. $query = "SELECT a.attname AS name,
  79. t.typname AS type,
  80. CASE a.attlen
  81. WHEN -1 THEN
  82. CASE t.typname
  83. WHEN 'numeric' THEN (a.atttypmod / 65536)
  84. WHEN 'decimal' THEN (a.atttypmod / 65536)
  85. WHEN 'money' THEN (a.atttypmod / 65536)
  86. ELSE CASE a.atttypmod
  87. WHEN -1 THEN NULL
  88. ELSE a.atttypmod - 4
  89. END
  90. END
  91. ELSE a.attlen
  92. END AS length,
  93. CASE t.typname
  94. WHEN 'numeric' THEN (a.atttypmod % 65536) - 4
  95. WHEN 'decimal' THEN (a.atttypmod % 65536) - 4
  96. WHEN 'money' THEN (a.atttypmod % 65536) - 4
  97. ELSE 0
  98. END AS scale,
  99. a.attnotnull,
  100. a.atttypmod,
  101. a.atthasdef,
  102. (SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128)
  103. FROM pg_attrdef d
  104. WHERE d.adrelid = a.attrelid
  105. AND d.adnum = a.attnum
  106. AND a.atthasdef
  107. ) as default
  108. FROM pg_attribute a,
  109. pg_class c,
  110. pg_type t
  111. WHERE c.relname = ".$db->quote($table, 'text')."
  112. AND a.atttypid = t.oid
  113. AND c.oid = a.attrelid
  114. AND NOT a.attisdropped
  115. AND a.attnum > 0
  116. AND a.attname = ".$db->quote($field_name, 'text')."
  117. ORDER BY a.attnum";
  118. $column = $db->queryRow($query, null, MDB2_FETCHMODE_ASSOC);
  119. if (PEAR::isError($column)) {
  120. return $column;
  121. }
  122. if (empty($column)) {
  123. return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  124. 'it was not specified an existing table column', __FUNCTION__);
  125. }
  126. $column = array_change_key_case($column, CASE_LOWER);
  127. $mapped_datatype = $db->datatype->mapNativeDatatype($column);
  128. if (PEAR::isError($mapped_datatype)) {
  129. return $mapped_datatype;
  130. }
  131. list($types, $length, $unsigned, $fixed) = $mapped_datatype;
  132. $notnull = false;
  133. if (!empty($column['attnotnull']) && $column['attnotnull'] == 't') {
  134. $notnull = true;
  135. }
  136. $default = null;
  137. if ($column['atthasdef'] === 't'
  138. && !preg_match("/nextval\('([^']+)'/", $column['default'])
  139. ) {
  140. $pattern = '/^\'(.*)\'::[\w ]+$/i';
  141. $default = $column['default'];#substr($column['adsrc'], 1, -1);
  142. if (is_null($default) && $notnull) {
  143. $default = '';
  144. } elseif (!empty($default) && preg_match($pattern, $default)) {
  145. //remove data type cast
  146. $default = preg_replace ($pattern, '\\1', $default);
  147. }
  148. }
  149. $autoincrement = false;
  150. if (preg_match("/nextval\('([^']+)'/", $column['default'], $nextvals)) {
  151. $autoincrement = true;
  152. }
  153. $definition[0] = array('notnull' => $notnull, 'nativetype' => $column['type']);
  154. if (!is_null($length)) {
  155. $definition[0]['length'] = $length;
  156. }
  157. if (!is_null($unsigned)) {
  158. $definition[0]['unsigned'] = $unsigned;
  159. }
  160. if (!is_null($fixed)) {
  161. $definition[0]['fixed'] = $fixed;
  162. }
  163. if ($default !== false) {
  164. $definition[0]['default'] = $default;
  165. }
  166. if ($autoincrement !== false) {
  167. $definition[0]['autoincrement'] = $autoincrement;
  168. }
  169. foreach ($types as $key => $type) {
  170. $definition[$key] = $definition[0];
  171. if ($type == 'clob' || $type == 'blob') {
  172. unset($definition[$key]['default']);
  173. }
  174. $definition[$key]['type'] = $type;
  175. $definition[$key]['mdb2type'] = $type;
  176. }
  177. return $definition;
  178. }
  179. // }}}
  180. // {{{ getTableIndexDefinition()
  181. /**
  182. * Get the structure of an index into an array
  183. *
  184. * @param string $table_name name of table that should be used in method
  185. * @param string $index_name name of index that should be used in method
  186. * @return mixed data array on success, a MDB2 error on failure
  187. * @access public
  188. */
  189. function getTableIndexDefinition($table_name, $index_name)
  190. {
  191. $db =& $this->getDBInstance();
  192. if (PEAR::isError($db)) {
  193. return $db;
  194. }
  195. list($schema, $table) = $this->splitTableSchema($table_name);
  196. $query = 'SELECT relname, indkey FROM pg_index, pg_class';
  197. $query.= ' WHERE pg_class.oid = pg_index.indexrelid';
  198. $query.= " AND indisunique != 't' AND indisprimary != 't'";
  199. $query.= ' AND pg_class.relname = %s';
  200. $index_name_mdb2 = $db->getIndexName($index_name);
  201. $row = $db->queryRow(sprintf($query, $db->quote($index_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
  202. if (PEAR::isError($row) || empty($row)) {
  203. // fallback to the given $index_name, without transformation
  204. $row = $db->queryRow(sprintf($query, $db->quote($index_name, 'text')), null, MDB2_FETCHMODE_ASSOC);
  205. }
  206. if (PEAR::isError($row)) {
  207. return $row;
  208. }
  209. if (empty($row)) {
  210. return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  211. 'it was not specified an existing table index', __FUNCTION__);
  212. }
  213. $row = array_change_key_case($row, CASE_LOWER);
  214. $db->loadModule('Manager', null, true);
  215. $columns = $db->manager->listTableFields($table_name);
  216. $definition = array();
  217. $index_column_numbers = explode(' ', $row['indkey']);
  218. $colpos = 1;
  219. foreach ($index_column_numbers as $number) {
  220. $definition['fields'][$columns[($number - 1)]] = array(
  221. 'position' => $colpos++,
  222. 'sorting' => 'ascending',
  223. );
  224. }
  225. return $definition;
  226. }
  227. // }}}
  228. // {{{ getTableConstraintDefinition()
  229. /**
  230. * Get the structure of a constraint into an array
  231. *
  232. * @param string $table_name name of table that should be used in method
  233. * @param string $constraint_name name of constraint that should be used in method
  234. * @return mixed data array on success, a MDB2 error on failure
  235. * @access public
  236. */
  237. function getTableConstraintDefinition($table_name, $constraint_name)
  238. {
  239. $db =& $this->getDBInstance();
  240. if (PEAR::isError($db)) {
  241. return $db;
  242. }
  243. list($schema, $table) = $this->splitTableSchema($table_name);
  244. $query = "SELECT c.oid,
  245. c.conname AS constraint_name,
  246. CASE WHEN c.contype = 'c' THEN 1 ELSE 0 END AS \"check\",
  247. CASE WHEN c.contype = 'f' THEN 1 ELSE 0 END AS \"foreign\",
  248. CASE WHEN c.contype = 'p' THEN 1 ELSE 0 END AS \"primary\",
  249. CASE WHEN c.contype = 'u' THEN 1 ELSE 0 END AS \"unique\",
  250. CASE WHEN c.condeferrable = 'f' THEN 0 ELSE 1 END AS deferrable,
  251. CASE WHEN c.condeferred = 'f' THEN 0 ELSE 1 END AS initiallydeferred,
  252. --array_to_string(c.conkey, ' ') AS constraint_key,
  253. t.relname AS table_name,
  254. t2.relname AS references_table,
  255. CASE confupdtype
  256. WHEN 'a' THEN 'NO ACTION'
  257. WHEN 'r' THEN 'RESTRICT'
  258. WHEN 'c' THEN 'CASCADE'
  259. WHEN 'n' THEN 'SET NULL'
  260. WHEN 'd' THEN 'SET DEFAULT'
  261. END AS onupdate,
  262. CASE confdeltype
  263. WHEN 'a' THEN 'NO ACTION'
  264. WHEN 'r' THEN 'RESTRICT'
  265. WHEN 'c' THEN 'CASCADE'
  266. WHEN 'n' THEN 'SET NULL'
  267. WHEN 'd' THEN 'SET DEFAULT'
  268. END AS ondelete,
  269. CASE confmatchtype
  270. WHEN 'u' THEN 'UNSPECIFIED'
  271. WHEN 'f' THEN 'FULL'
  272. WHEN 'p' THEN 'PARTIAL'
  273. END AS match,
  274. --array_to_string(c.confkey, ' ') AS fk_constraint_key,
  275. consrc
  276. FROM pg_constraint c
  277. LEFT JOIN pg_class t ON c.conrelid = t.oid
  278. LEFT JOIN pg_class t2 ON c.confrelid = t2.oid
  279. WHERE c.conname = %s
  280. AND t.relname = " . $db->quote($table, 'text');
  281. $constraint_name_mdb2 = $db->getIndexName($constraint_name);
  282. $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
  283. if (PEAR::isError($row) || empty($row)) {
  284. // fallback to the given $index_name, without transformation
  285. $constraint_name_mdb2 = $constraint_name;
  286. $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
  287. }
  288. if (PEAR::isError($row)) {
  289. return $row;
  290. }
  291. $uniqueIndex = false;
  292. if (empty($row)) {
  293. // We might be looking for a UNIQUE index that was not created
  294. // as a constraint but should be treated as such.
  295. $query = 'SELECT relname AS constraint_name,
  296. indkey,
  297. 0 AS "check",
  298. 0 AS "foreign",
  299. 0 AS "primary",
  300. 1 AS "unique",
  301. 0 AS deferrable,
  302. 0 AS initiallydeferred,
  303. NULL AS references_table,
  304. NULL AS onupdate,
  305. NULL AS ondelete,
  306. NULL AS match
  307. FROM pg_index, pg_class
  308. WHERE pg_class.oid = pg_index.indexrelid
  309. AND indisunique = \'t\'
  310. AND pg_class.relname = %s';
  311. $constraint_name_mdb2 = $db->getIndexName($constraint_name);
  312. $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
  313. if (PEAR::isError($row) || empty($row)) {
  314. // fallback to the given $index_name, without transformation
  315. $constraint_name_mdb2 = $constraint_name;
  316. $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
  317. }
  318. if (PEAR::isError($row)) {
  319. return $row;
  320. }
  321. if (empty($row)) {
  322. return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  323. $constraint_name . ' is not an existing table constraint', __FUNCTION__);
  324. }
  325. $uniqueIndex = true;
  326. }
  327. $row = array_change_key_case($row, CASE_LOWER);
  328. $definition = array(
  329. 'primary' => (boolean)$row['primary'],
  330. 'unique' => (boolean)$row['unique'],
  331. 'foreign' => (boolean)$row['foreign'],
  332. 'check' => (boolean)$row['check'],
  333. 'fields' => array(),
  334. 'references' => array(
  335. 'table' => $row['references_table'],
  336. 'fields' => array(),
  337. ),
  338. 'deferrable' => (boolean)$row['deferrable'],
  339. 'initiallydeferred' => (boolean)$row['initiallydeferred'],
  340. 'onupdate' => $row['onupdate'],
  341. 'ondelete' => $row['ondelete'],
  342. 'match' => $row['match'],
  343. );
  344. if ($uniqueIndex) {
  345. $db->loadModule('Manager', null, true);
  346. $columns = $db->manager->listTableFields($table_name);
  347. $index_column_numbers = explode(' ', $row['indkey']);
  348. $colpos = 1;
  349. foreach ($index_column_numbers as $number) {
  350. $definition['fields'][$columns[($number - 1)]] = array(
  351. 'position' => $colpos++,
  352. 'sorting' => 'ascending',
  353. );
  354. }
  355. return $definition;
  356. }
  357. $query = 'SELECT a.attname
  358. FROM pg_constraint c
  359. LEFT JOIN pg_class t ON c.conrelid = t.oid
  360. LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(c.conkey)
  361. WHERE c.conname = %s
  362. AND t.relname = ' . $db->quote($table, 'text');
  363. $fields = $db->queryCol(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null);
  364. if (PEAR::isError($fields)) {
  365. return $fields;
  366. }
  367. $colpos = 1;
  368. foreach ($fields as $field) {
  369. $definition['fields'][$field] = array(
  370. 'position' => $colpos++,
  371. 'sorting' => 'ascending',
  372. );
  373. }
  374. if ($definition['foreign']) {
  375. $query = 'SELECT a.attname
  376. FROM pg_constraint c
  377. LEFT JOIN pg_class t ON c.confrelid = t.oid
  378. LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(c.confkey)
  379. WHERE c.conname = %s
  380. AND t.relname = ' . $db->quote($definition['references']['table'], 'text');
  381. $foreign_fields = $db->queryCol(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null);
  382. if (PEAR::isError($foreign_fields)) {
  383. return $foreign_fields;
  384. }
  385. $colpos = 1;
  386. foreach ($foreign_fields as $foreign_field) {
  387. $definition['references']['fields'][$foreign_field] = array(
  388. 'position' => $colpos++,
  389. );
  390. }
  391. }
  392. if ($definition['check']) {
  393. $check_def = $db->queryOne("SELECT pg_get_constraintdef(" . $row['oid'] . ", 't')");
  394. // ...
  395. }
  396. return $definition;
  397. }
  398. // }}}
  399. // {{{ getTriggerDefinition()
  400. /**
  401. * Get the structure of a trigger into an array
  402. *
  403. * EXPERIMENTAL
  404. *
  405. * WARNING: this function is experimental and may change the returned value
  406. * at any time until labelled as non-experimental
  407. *
  408. * @param string $trigger name of trigger that should be used in method
  409. * @return mixed data array on success, a MDB2 error on failure
  410. * @access public
  411. *
  412. * @TODO: add support for plsql functions and functions with args
  413. */
  414. function getTriggerDefinition($trigger)
  415. {
  416. $db =& $this->getDBInstance();
  417. if (PEAR::isError($db)) {
  418. return $db;
  419. }
  420. $query = "SELECT trg.tgname AS trigger_name,
  421. tbl.relname AS table_name,
  422. CASE
  423. WHEN p.proname IS NOT NULL THEN 'EXECUTE PROCEDURE ' || p.proname || '();'
  424. ELSE ''
  425. END AS trigger_body,
  426. CASE trg.tgtype & cast(2 as int2)
  427. WHEN 0 THEN 'AFTER'
  428. ELSE 'BEFORE'
  429. END AS trigger_type,
  430. CASE trg.tgtype & cast(28 as int2)
  431. WHEN 16 THEN 'UPDATE'
  432. WHEN 8 THEN 'DELETE'
  433. WHEN 4 THEN 'INSERT'
  434. WHEN 20 THEN 'INSERT, UPDATE'
  435. WHEN 28 THEN 'INSERT, UPDATE, DELETE'
  436. WHEN 24 THEN 'UPDATE, DELETE'
  437. WHEN 12 THEN 'INSERT, DELETE'
  438. END AS trigger_event,
  439. CASE trg.tgenabled
  440. WHEN 'O' THEN 't'
  441. ELSE trg.tgenabled
  442. END AS trigger_enabled,
  443. obj_description(trg.oid, 'pg_trigger') AS trigger_comment
  444. FROM pg_trigger trg,
  445. pg_class tbl,
  446. pg_proc p
  447. WHERE trg.tgrelid = tbl.oid
  448. AND trg.tgfoid = p.oid
  449. AND trg.tgname = ". $db->quote($trigger, 'text');
  450. $types = array(
  451. 'trigger_name' => 'text',
  452. 'table_name' => 'text',
  453. 'trigger_body' => 'text',
  454. 'trigger_type' => 'text',
  455. 'trigger_event' => 'text',
  456. 'trigger_comment' => 'text',
  457. 'trigger_enabled' => 'boolean',
  458. );
  459. return $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);
  460. }
  461. // }}}
  462. // {{{ tableInfo()
  463. /**
  464. * Returns information about a table or a result set
  465. *
  466. * NOTE: only supports 'table' and 'flags' if <var>$result</var>
  467. * is a table name.
  468. *
  469. * @param object|string $result MDB2_result object from a query or a
  470. * string containing the name of a table.
  471. * While this also accepts a query result
  472. * resource identifier, this behavior is
  473. * deprecated.
  474. * @param int $mode a valid tableInfo mode
  475. *
  476. * @return array an associative array with the information requested.
  477. * A MDB2_Error object on failure.
  478. *
  479. * @see MDB2_Driver_Common::tableInfo()
  480. */
  481. function tableInfo($result, $mode = null)
  482. {
  483. if (is_string($result)) {
  484. return parent::tableInfo($result, $mode);
  485. }
  486. $db =& $this->getDBInstance();
  487. if (PEAR::isError($db)) {
  488. return $db;
  489. }
  490. $resource = MDB2::isResultCommon($result) ? $result->getResource() : $result;
  491. if (!is_resource($resource)) {
  492. return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  493. 'Could not generate result resource', __FUNCTION__);
  494. }
  495. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  496. if ($db->options['field_case'] == CASE_LOWER) {
  497. $case_func = 'strtolower';
  498. } else {
  499. $case_func = 'strtoupper';
  500. }
  501. } else {
  502. $case_func = 'strval';
  503. }
  504. $count = @pg_num_fields($resource);
  505. $res = array();
  506. if ($mode) {
  507. $res['num_fields'] = $count;
  508. }
  509. $db->loadModule('Datatype', null, true);
  510. for ($i = 0; $i < $count; $i++) {
  511. $res[$i] = array(
  512. 'table' => function_exists('pg_field_table') ? @pg_field_table($resource, $i) : '',
  513. 'name' => $case_func(@pg_field_name($resource, $i)),
  514. 'type' => @pg_field_type($resource, $i),
  515. 'length' => @pg_field_size($resource, $i),
  516. 'flags' => '',
  517. );
  518. $mdb2type_info = $db->datatype->mapNativeDatatype($res[$i]);
  519. if (PEAR::isError($mdb2type_info)) {
  520. return $mdb2type_info;
  521. }
  522. $res[$i]['mdb2type'] = $mdb2type_info[0][0];
  523. if ($mode & MDB2_TABLEINFO_ORDER) {
  524. $res['order'][$res[$i]['name']] = $i;
  525. }
  526. if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
  527. $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
  528. }
  529. }
  530. return $res;
  531. }
  532. }
  533. ?>