PageRenderTime 70ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/classes/fSchema.php

https://bitbucket.org/ZilIsiltk/flourish
PHP | 2884 lines | 2110 code | 265 blank | 509 comment | 241 complexity | bb9290edcd4874e69f25c6cf6f09a915 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * Gets schema information for the selected database
  4. *
  5. * @copyright Copyright (c) 2007-2010 Will Bond
  6. * @author Will Bond [wb] <will@flourishlib.com>
  7. * @license http://flourishlib.com/license
  8. *
  9. * @package Flourish
  10. * @link http://flourishlib.com/fSchema
  11. *
  12. * @version 1.0.0b42
  13. * @changes 1.0.0b42 Fixed a bug with MySQL detecting default `ON DELETE` clauses [wb, 2010-10-19]
  14. * @changes 1.0.0b41 Fixed handling MySQL table names that require quoting [wb, 2010-08-24]
  15. * @changes 1.0.0b40 Fixed bugs in the documentation and error message of ::getColumnInfo() about what are valid elements [wb, 2010-07-21]
  16. * @changes 1.0.0b39 Fixed a regression where key detection SQL was not compatible with PostgreSQL 8.1 [wb, 2010-04-13]
  17. * @changes 1.0.0b38 Added Oracle support to ::getDatabases() [wb, 2010-04-13]
  18. * @changes 1.0.0b37 Fixed ::getDatabases() for MSSQL [wb, 2010-04-09]
  19. * @changes 1.0.0b36 Fixed PostgreSQL to properly report explicit `NULL` default values via ::getColumnInfo() [wb, 2010-03-30]
  20. * @changes 1.0.0b35 Added `max_length` values for various text and blob data types across all databases [wb, 2010-03-29]
  21. * @changes 1.0.0b34 Added `min_value` and `max_value` attributes to ::getColumnInfo() to specify the valid range for numeric columns [wb, 2010-03-16]
  22. * @changes 1.0.0b33 Changed it so that PostgreSQL unique indexes containing functions are ignored since they can't be properly detected at this point [wb, 2010-03-14]
  23. * @changes 1.0.0b32 Fixed ::getTables() to not include views for MySQL [wb, 2010-03-14]
  24. * @changes 1.0.0b31 Fixed the creation of the default caching key for ::enableCaching() [wb, 2010-03-02]
  25. * @changes 1.0.0b30 Fixed the class to work with lower privilege Oracle accounts and added detection of Oracle number columns [wb, 2010-01-25]
  26. * @changes 1.0.0b29 Added on_delete and on_update elements to one-to-one relationship info retrieved by ::getRelationships() [wb, 2009-12-16]
  27. * @changes 1.0.0b28 Fixed a bug with detecting some multi-column unique constraints in SQL Server databases [wb, 2009-11-13]
  28. * @changes 1.0.0b27 Added a parameter to ::enableCaching() to provide a key token that will allow cached values to be shared between multiple databases with the same schema [wb, 2009-10-28]
  29. * @changes 1.0.0b26 Added the placeholder element to the output of ::getColumnInfo(), added support for PostgreSQL, MSSQL and Oracle "schemas", added support for parsing quoted SQLite identifiers [wb, 2009-10-22]
  30. * @changes 1.0.0b25 One-to-one relationships utilizing the primary key as a foreign key are now properly detected [wb, 2009-09-22]
  31. * @changes 1.0.0b24 Fixed MSSQL support to work with ODBC database connections [wb, 2009-09-18]
  32. * @changes 1.0.0b23 Fixed a bug where one-to-one relationships were being listed as many-to-one [wb, 2009-07-21]
  33. * @changes 1.0.0b22 PostgreSQL UNIQUE constraints that are created as indexes and not table constraints are now properly detected [wb, 2009-07-08]
  34. * @changes 1.0.0b21 Added support for the UUID data type in PostgreSQL [wb, 2009-06-18]
  35. * @changes 1.0.0b20 Add caching of merged info, improved performance of ::getColumnInfo() [wb, 2009-06-15]
  36. * @changes 1.0.0b19 Fixed a couple of bugs with ::setKeysOverride() [wb, 2009-06-04]
  37. * @changes 1.0.0b18 Added missing support for MySQL mediumint columns [wb, 2009-05-18]
  38. * @changes 1.0.0b17 Fixed a bug with ::clearCache() not properly reseting the tables and databases list [wb, 2009-05-13]
  39. * @changes 1.0.0b16 Backwards Compatibility Break - ::setCacheFile() changed to ::enableCaching() and now requires an fCache object, ::flushInfo() renamed to ::clearCache(), added Oracle support [wb, 2009-05-04]
  40. * @changes 1.0.0b15 Added support for the three different types of identifier quoting in SQLite [wb, 2009-03-28]
  41. * @changes 1.0.0b14 Added support for MySQL column definitions containing the COLLATE keyword [wb, 2009-03-28]
  42. * @changes 1.0.0b13 Fixed a bug with detecting PostgreSQL columns having both a CHECK constraint and a UNIQUE constraint [wb, 2009-02-27]
  43. * @changes 1.0.0b12 Fixed detection of multi-column primary keys in MySQL [wb, 2009-02-27]
  44. * @changes 1.0.0b11 Fixed an issue parsing MySQL tables with comments [wb, 2009-02-25]
  45. * @changes 1.0.0b10 Added the ::getDatabases() method [wb, 2009-02-24]
  46. * @changes 1.0.0b9 Now detects unsigned and zerofill MySQL data types that do not have a parenthetical part [wb, 2009-02-16]
  47. * @changes 1.0.0b8 Mapped the MySQL data type `'set'` to `'varchar'`, however valid values are not implemented yet [wb, 2009-02-01]
  48. * @changes 1.0.0b7 Fixed a bug with detecting MySQL timestamp columns [wb, 2009-01-28]
  49. * @changes 1.0.0b6 Fixed a bug with detecting MySQL columns that accept `NULL` [wb, 2009-01-19]
  50. * @changes 1.0.0b5 ::setColumnInfo(): fixed a bug with not grabbing the real database schema first, made general improvements [wb, 2009-01-19]
  51. * @changes 1.0.0b4 Added support for MySQL binary data types, numeric data type options unsigned and zerofill, and per-column character set definitions [wb, 2009-01-17]
  52. * @changes 1.0.0b3 Fixed detection of the data type of MySQL timestamp columns, added support for dynamic default date/time values [wb, 2009-01-11]
  53. * @changes 1.0.0b2 Fixed a bug with detecting multi-column unique keys in MySQL [wb, 2009-01-03]
  54. * @changes 1.0.0b The initial implementation [wb, 2007-09-25]
  55. */
  56. class fSchema
  57. {
  58. /**
  59. * The place to cache to
  60. *
  61. * @var fCache
  62. */
  63. private $cache = NULL;
  64. /**
  65. * The cache prefix to use for cache entries
  66. *
  67. * @var string
  68. */
  69. private $cache_prefix;
  70. /**
  71. * The cached column info
  72. *
  73. * @var array
  74. */
  75. private $column_info = array();
  76. /**
  77. * The column info to override
  78. *
  79. * @var array
  80. */
  81. private $column_info_override = array();
  82. /**
  83. * A reference to an instance of the fDatabase class
  84. *
  85. * @var fDatabase
  86. */
  87. private $database = NULL;
  88. /**
  89. * The databases on the current database server
  90. *
  91. * @var array
  92. */
  93. private $databases = NULL;
  94. /**
  95. * The cached key info
  96. *
  97. * @var array
  98. */
  99. private $keys = array();
  100. /**
  101. * The key info to override
  102. *
  103. * @var array
  104. */
  105. private $keys_override = array();
  106. /**
  107. * The merged column info
  108. *
  109. * @var array
  110. */
  111. private $merged_column_info = array();
  112. /**
  113. * The merged key info
  114. *
  115. * @var array
  116. */
  117. private $merged_keys = array();
  118. /**
  119. * The relationships in the database
  120. *
  121. * @var array
  122. */
  123. private $relationships = array();
  124. /**
  125. * The tables in the database
  126. *
  127. * @var array
  128. */
  129. private $tables = NULL;
  130. /**
  131. * Sets the database
  132. *
  133. * @param fDatabase $database The fDatabase instance
  134. * @return fSchema
  135. */
  136. public function __construct($database)
  137. {
  138. $this->database = $database;
  139. }
  140. /**
  141. * All requests that hit this method should be requests for callbacks
  142. *
  143. * @internal
  144. *
  145. * @param string $method The method to create a callback for
  146. * @return callback The callback for the method requested
  147. */
  148. public function __get($method)
  149. {
  150. return array($this, $method);
  151. }
  152. /**
  153. * Checks to see if a column is part of a single-column `UNIQUE` key
  154. *
  155. * @param string $table The table the column is located in
  156. * @param string $column The column to check
  157. * @return boolean If the column is part of a single-column unique key
  158. */
  159. private function checkForSingleColumnUniqueKey($table, $column)
  160. {
  161. foreach ($this->merged_keys[$table]['unique'] as $key) {
  162. if (array($column) == $key) {
  163. return TRUE;
  164. }
  165. }
  166. if (array($column) == $this->merged_keys[$table]['primary']) {
  167. return TRUE;
  168. }
  169. return FALSE;
  170. }
  171. /**
  172. * Clears all of the schema info out of the object and, if set, the fCache object
  173. *
  174. * @internal
  175. *
  176. * @return void
  177. */
  178. public function clearCache()
  179. {
  180. $this->column_info = array();
  181. $this->databases = NULL;
  182. $this->keys = array();
  183. $this->merged_column_info = array();
  184. $this->merged_keys = array();
  185. $this->relationships = array();
  186. $this->tables = NULL;
  187. if ($this->cache) {
  188. $prefix = $this->makeCachePrefix();
  189. $this->cache->delete($prefix . 'column_info');
  190. $this->cache->delete($prefix . 'databases');
  191. $this->cache->delete($prefix . 'keys');
  192. $this->cache->delete($prefix . 'merged_column_info');
  193. $this->cache->delete($prefix . 'merged_keys');
  194. $this->cache->delete($prefix . 'relationships');
  195. $this->cache->delete($prefix . 'tables');
  196. }
  197. }
  198. /**
  199. * Sets the schema to be cached to the fCache object specified
  200. *
  201. * @param fCache $cache The cache to cache to
  202. * @param string $key_token Internal use only! (this will be used in the cache key to uniquely identify the cache for this fSchema object)
  203. * @return void
  204. */
  205. public function enableCaching($cache, $key_token=NULL)
  206. {
  207. $this->cache = $cache;
  208. if ($key_token !== NULL) {
  209. $this->cache_prefix = 'fSchema::' . $this->database->getType() . '::' . $key_token . '::';
  210. }
  211. $prefix = $this->makeCachePrefix();
  212. $this->column_info = $this->cache->get($prefix . 'column_info', array());
  213. $this->databases = $this->cache->get($prefix . 'databases', NULL);
  214. $this->keys = $this->cache->get($prefix . 'keys', array());
  215. if (!$this->column_info_override && !$this->keys_override) {
  216. $this->merged_column_info = $this->cache->get($prefix . 'merged_column_info', array());
  217. $this->merged_keys = $this->cache->get($prefix . 'merged_keys', array());
  218. $this->relationships = $this->cache->get($prefix . 'relationships', array());
  219. }
  220. $this->tables = $this->cache->get($prefix . 'tables', NULL);
  221. }
  222. /**
  223. * Gets the column info from the database for later access
  224. *
  225. * @param string $table The table to fetch the column info for
  226. * @return void
  227. */
  228. private function fetchColumnInfo($table)
  229. {
  230. if (isset($this->column_info[$table])) {
  231. return;
  232. }
  233. switch ($this->database->getType()) {
  234. case 'db2':
  235. $column_info = $this->fetchDB2ColumnInfo($table);
  236. break;
  237. case 'mssql':
  238. $column_info = $this->fetchMSSQLColumnInfo($table);
  239. break;
  240. case 'mysql':
  241. $column_info = $this->fetchMySQLColumnInfo($table);
  242. break;
  243. case 'oracle':
  244. $column_info = $this->fetchOracleColumnInfo($table);
  245. break;
  246. case 'postgresql':
  247. $column_info = $this->fetchPostgreSQLColumnInfo($table);
  248. break;
  249. case 'sqlite':
  250. $column_info = $this->fetchSQLiteColumnInfo($table);
  251. break;
  252. }
  253. if (!$column_info) {
  254. return;
  255. }
  256. $this->column_info[$table] = $column_info;
  257. if ($this->cache) {
  258. $this->cache->set($this->makeCachePrefix() . 'column_info', $this->column_info);
  259. }
  260. }
  261. /**
  262. * Gets the column info from a DB2 database
  263. *
  264. * @param string $table The table to fetch the column info for
  265. * @return array The column info for the table specified - see ::getColumnInfo() for details
  266. */
  267. private function fetchDB2ColumnInfo($table)
  268. {
  269. $column_info = array();
  270. $schema = strtolower($this->database->getUsername());
  271. if (strpos($table, '.') !== FALSE) {
  272. list ($schema, $table) = explode('.', $table);
  273. }
  274. $data_type_mapping = array(
  275. 'smallint' => 'integer',
  276. 'integer' => 'integer',
  277. 'bigint' => 'integer',
  278. 'timestamp' => 'timestamp',
  279. 'date' => 'date',
  280. 'time' => 'time',
  281. 'varchar' => 'varchar',
  282. 'long varchar' => 'varchar',
  283. 'vargraphic' => 'varchar',
  284. 'long vargraphic' => 'varchar',
  285. 'character' => 'char',
  286. 'graphic' => 'char',
  287. 'real' => 'float',
  288. 'decimal' => 'float',
  289. 'numeric' => 'float',
  290. 'blob' => 'blob',
  291. 'clob' => 'text',
  292. 'dbclob' => 'text'
  293. );
  294. $max_min_values = array(
  295. 'smallint' => array('min' => new fNumber(-32768), 'max' => new fNumber(32767)),
  296. 'integer' => array('min' => new fNumber(-2147483648), 'max' => new fNumber(2147483647)),
  297. 'bigint' => array('min' => new fNumber('-9223372036854775808'), 'max' => new fNumber('9223372036854775807'))
  298. );
  299. // Get the column info
  300. $sql = "SELECT
  301. LOWER(C.COLNAME) AS \"COLUMN\",
  302. C.TYPENAME AS TYPE,
  303. C.NULLS AS NULLABLE,
  304. C.DEFAULT,
  305. C.LENGTH AS MAX_LENGTH,
  306. C.SCALE,
  307. CASE WHEN C.IDENTITY = 'Y' AND (C.GENERATED = 'D' OR C.GENERATED = 'A') THEN '1' ELSE '0' END AS AUTO_INCREMENT,
  308. CH.TEXT AS \"CONSTRAINT\"
  309. FROM
  310. SYSCAT.COLUMNS AS C LEFT JOIN
  311. SYSCAT.COLCHECKS AS CC ON C.TABSCHEMA = CC.TABSCHEMA AND C.TABNAME = CC.TABNAME AND C.COLNAME = CC.COLNAME AND CC.USAGE = 'R' LEFT JOIN
  312. SYSCAT.CHECKS AS CH ON C.TABSCHEMA = CH.TABSCHEMA AND C.TABNAME = CH.TABNAME AND CH.TYPE = 'C' AND CH.CONSTNAME = CC.CONSTNAME
  313. WHERE
  314. C.TABSCHEMA = %s AND
  315. C.TABNAME = %s
  316. ORDER BY
  317. C.COLNO ASC";
  318. $result = $this->database->query($sql, strtoupper($schema), strtoupper($table));
  319. foreach ($result as $row) {
  320. $info = array();
  321. foreach ($data_type_mapping as $data_type => $mapped_data_type) {
  322. if (stripos($row['type'], $data_type) === 0) {
  323. if (isset($max_min_values[$data_type])) {
  324. $info['min_value'] = $max_min_values[$data_type]['min'];
  325. $info['max_value'] = $max_min_values[$data_type]['max'];
  326. }
  327. $info['type'] = $mapped_data_type;
  328. break;
  329. }
  330. }
  331. // Handle decimal places and min/max for numeric/decimals
  332. if (in_array(strtolower($row['type']), array('decimal', 'numeric'))) {
  333. $info['decimal_places'] = $row['scale'];
  334. $before_digits = str_pad('', $row['max_length'] - $row['scale'], '9');
  335. $after_digits = str_pad('', $row['scale'], '9');
  336. $max_min = $before_digits . ($after_digits ? '.' : '') . $after_digits;
  337. $info['min_value'] = new fNumber('-' . $max_min);
  338. $info['max_value'] = new fNumber($max_min);
  339. }
  340. if (!isset($info['type'])) {
  341. $info['type'] = $row['type'];
  342. }
  343. // Handle the special data for varchar columns
  344. if (in_array($info['type'], array('char', 'varchar', 'text', 'blob'))) {
  345. $info['max_length'] = $row['max_length'];
  346. }
  347. // The generally accepted practice for boolean on DB2 is a CHAR(1) with a CHECK constraint
  348. if ($info['type'] == 'char' && $info['max_length'] == 1 && !empty($row['constraint'])) {
  349. if (is_resource($row['constraint'])) {
  350. $row['constraint'] = stream_get_contents($row['constraint']);
  351. }
  352. if (preg_match('/^\s*' . preg_quote($row['column'], '/') . '\s+in\s+\(\s*(\'0\',\s*\'1\'|\'1\',\s*\'0\')\s*\)\s*$/i', $row['constraint'])) {
  353. $info['type'] = 'boolean';
  354. $info['max_length'] = NULL;
  355. }
  356. }
  357. // If the column has a constraint, look for valid values
  358. if (in_array($info['type'], array('char', 'varchar')) && !empty($row['constraint'])) {
  359. if (preg_match('/^\s*' . preg_quote($row['column'], '/') . '\s+in\s+\((.*?)\)\s*$/i', $row['constraint'], $match)) {
  360. if (preg_match_all("/(?<!')'((''|[^']+)*)'/", $match[1], $matches, PREG_PATTERN_ORDER)) {
  361. $info['valid_values'] = str_replace("''", "'", $matches[1]);
  362. }
  363. }
  364. }
  365. // Handle auto increment
  366. if ($row['auto_increment']) {
  367. $info['auto_increment'] = TRUE;
  368. }
  369. // Handle default values
  370. if ($row['default'] !== NULL) {
  371. if ($row['default'] == 'NULL') {
  372. $info['default'] = NULL;
  373. } elseif (in_array($info['type'], array('char', 'varchar', 'text', 'timestamp')) ) {
  374. $info['default'] = substr($row['default'], 1, -1);
  375. } elseif ($info['type'] == 'boolean') {
  376. $info['default'] = (boolean) substr($row['default'], 1, -1);
  377. } else {
  378. $info['default'] = $row['default'];
  379. }
  380. }
  381. // Handle not null
  382. $info['not_null'] = ($row['nullable'] == 'N') ? TRUE : FALSE;
  383. $column_info[$row['column']] = $info;
  384. }
  385. return $column_info;
  386. }
  387. /**
  388. * Fetches the key info for a DB2 database
  389. *
  390. * @return array The keys arrays for every table in the database - see ::getKeys() for details
  391. */
  392. private function fetchDB2Keys()
  393. {
  394. $keys = array();
  395. $default_schema = strtolower($this->database->getUsername());
  396. $tables = $this->getTables();
  397. foreach ($tables as $table) {
  398. $keys[$table] = array();
  399. $keys[$table]['primary'] = array();
  400. $keys[$table]['unique'] = array();
  401. $keys[$table]['foreign'] = array();
  402. }
  403. $params = array();
  404. $sql = "(SELECT
  405. LOWER(RTRIM(R.TABSCHEMA)) AS \"SCHEMA\",
  406. LOWER(R.TABNAME) AS \"TABLE\",
  407. R.CONSTNAME AS CONSTRAINT_NAME,
  408. 'foreign' AS \"TYPE\",
  409. LOWER(K.COLNAME) AS \"COLUMN\",
  410. LOWER(RTRIM(R.REFTABSCHEMA)) AS FOREIGN_SCHEMA,
  411. LOWER(R.REFTABNAME) AS FOREIGN_TABLE,
  412. LOWER(FK.COLNAME) AS FOREIGN_COLUMN,
  413. CASE R.DELETERULE WHEN 'C' THEN 'cascade' WHEN 'A' THEN 'no_action' WHEN 'R' THEN 'restrict' ELSE 'set_null' END AS ON_DELETE,
  414. CASE R.UPDATERULE WHEN 'A' THEN 'no_action' WHEN 'R' THEN 'restrict' END AS ON_UPDATE,
  415. K.COLSEQ
  416. FROM
  417. SYSCAT.REFERENCES AS R INNER JOIN
  418. SYSCAT.KEYCOLUSE AS K ON R.CONSTNAME = K.CONSTNAME AND R.TABSCHEMA = K.TABSCHEMA AND R.TABNAME = K.TABNAME INNER JOIN
  419. SYSCAT.KEYCOLUSE AS FK ON R.REFKEYNAME = FK.CONSTNAME AND R.REFTABSCHEMA = FK.TABSCHEMA AND R.REFTABNAME = FK.TABNAME
  420. WHERE ";
  421. $conditions = array();
  422. foreach ($tables as $table) {
  423. if (strpos($table, '.') === FALSE) {
  424. $table = $default_schema . '.' . $table;
  425. }
  426. list ($schema, $table) = explode('.', strtoupper($table));
  427. $conditions[] = "R.TABSCHEMA = %s AND R.TABNAME = %s";
  428. $params[] = $schema;
  429. $params[] = $table;
  430. }
  431. $sql .= '((' . join(') OR( ', $conditions) . '))';
  432. $sql .= "
  433. ) UNION (
  434. SELECT
  435. LOWER(RTRIM(I.TABSCHEMA)) AS \"SCHEMA\",
  436. LOWER(I.TABNAME) AS \"TABLE\",
  437. LOWER(I.INDNAME) AS CONSTRAINT_NAME,
  438. CASE I.UNIQUERULE WHEN 'U' THEN 'unique' ELSE 'primary' END AS \"TYPE\",
  439. LOWER(C.COLNAME) AS \"COLUMN\",
  440. NULL AS FOREIGN_SCHEMA,
  441. NULL AS FOREIGN_TABLE,
  442. NULL AS FOREIGN_COLUMN,
  443. NULL AS ON_DELETE,
  444. NULL AS ON_UPDATE,
  445. C.COLSEQ
  446. FROM
  447. SYSCAT.INDEXES AS I INNER JOIN
  448. SYSCAT.INDEXCOLUSE AS C ON I.INDSCHEMA = C.INDSCHEMA AND I.INDNAME = C.INDNAME
  449. WHERE
  450. I.UNIQUERULE IN ('U', 'P') AND
  451. ";
  452. $conditions = array();
  453. foreach ($tables as $table) {
  454. if (strpos($table, '.') === FALSE) {
  455. $table = $default_schema . '.' . $table;
  456. }
  457. list ($schema, $table) = explode('.', strtoupper($table));
  458. $conditions[] = "I.TABSCHEMA = %s AND I.TABNAME = %s";
  459. $params[] = $schema;
  460. $params[] = $table;
  461. }
  462. $sql .= '((' . join(') OR( ', $conditions) . '))';
  463. $sql .= "
  464. )
  465. ORDER BY 4, 1, 2, 3, 11";
  466. $result = $this->database->query($sql, $params);
  467. $last_name = '';
  468. $last_table = '';
  469. $last_type = '';
  470. foreach ($result as $row) {
  471. if ($row['constraint_name'] != $last_name) {
  472. if ($last_name) {
  473. if ($last_type == 'foreign' || $last_type == 'unique') {
  474. $keys[$last_table][$last_type][] = $temp;
  475. } else {
  476. $keys[$last_table][$last_type] = $temp;
  477. }
  478. }
  479. $temp = array();
  480. if ($row['type'] == 'foreign') {
  481. $temp['column'] = $row['column'];
  482. $temp['foreign_table'] = $row['foreign_table'];
  483. if ($row['foreign_schema'] != $default_schema) {
  484. $temp['foreign_table'] = $row['foreign_schema'] . '.' . $temp['foreign_table'];
  485. }
  486. $temp['foreign_column'] = $row['foreign_column'];
  487. $temp['on_delete'] = 'no_action';
  488. $temp['on_update'] = 'no_action';
  489. if (!empty($row['on_delete'])) {
  490. $temp['on_delete'] = $row['on_delete'];
  491. }
  492. if (!empty($row['on_update'])) {
  493. $temp['on_update'] = $row['on_update'];
  494. }
  495. } else {
  496. $temp[] = $row['column'];
  497. }
  498. $last_table = $row['table'];
  499. if ($row['schema'] != $default_schema) {
  500. $last_table = $row['schema'] . '.' . $last_table;
  501. }
  502. $last_name = $row['constraint_name'];
  503. $last_type = $row['type'];
  504. } else {
  505. $temp[] = $row['column'];
  506. }
  507. }
  508. if (isset($temp)) {
  509. if ($last_type == 'foreign' || $last_type == 'unique') {
  510. $keys[$last_table][$last_type][] = $temp;
  511. } else {
  512. $keys[$last_table][$last_type] = $temp;
  513. }
  514. }
  515. return $keys;
  516. }
  517. /**
  518. * Gets the `PRIMARY KEY`, `FOREIGN KEY` and `UNIQUE` key constraints from the database
  519. *
  520. * @return void
  521. */
  522. private function fetchKeys()
  523. {
  524. if ($this->keys) {
  525. return;
  526. }
  527. switch ($this->database->getType()) {
  528. case 'db2':
  529. $keys = $this->fetchDB2Keys();
  530. break;
  531. case 'mssql':
  532. $keys = $this->fetchMSSQLKeys();
  533. break;
  534. case 'mysql':
  535. $keys = $this->fetchMySQLKeys();
  536. break;
  537. case 'oracle':
  538. $keys = $this->fetchOracleKeys();
  539. break;
  540. case 'postgresql':
  541. $keys = $this->fetchPostgreSQLKeys();
  542. break;
  543. case 'sqlite':
  544. $keys = $this->fetchSQLiteKeys();
  545. break;
  546. }
  547. $this->keys = $keys;
  548. if ($this->cache) {
  549. $this->cache->set($this->makeCachePrefix() . 'keys', $this->keys);
  550. }
  551. }
  552. /**
  553. * Gets the column info from a MSSQL database
  554. *
  555. * @param string $table The table to fetch the column info for
  556. * @return array The column info for the table specified - see ::getColumnInfo() for details
  557. */
  558. private function fetchMSSQLColumnInfo($table)
  559. {
  560. $column_info = array();
  561. $schema = 'dbo';
  562. if (strpos($table, '.') !== FALSE) {
  563. list ($schema, $table) = explode('.', $table);
  564. }
  565. $data_type_mapping = array(
  566. 'bit' => 'boolean',
  567. 'tinyint' => 'integer',
  568. 'smallint' => 'integer',
  569. 'int' => 'integer',
  570. 'bigint' => 'integer',
  571. 'timestamp' => 'integer',
  572. 'datetime' => 'timestamp',
  573. 'smalldatetime' => 'timestamp',
  574. 'datetime2' => 'timestamp',
  575. 'date' => 'date',
  576. 'time' => 'time',
  577. 'varchar' => 'varchar',
  578. 'nvarchar' => 'varchar',
  579. 'uniqueidentifier' => 'varchar',
  580. 'char' => 'char',
  581. 'nchar' => 'char',
  582. 'real' => 'float',
  583. 'float' => 'float',
  584. 'money' => 'float',
  585. 'smallmoney' => 'float',
  586. 'decimal' => 'float',
  587. 'numeric' => 'float',
  588. 'binary' => 'blob',
  589. 'varbinary' => 'blob',
  590. 'image' => 'blob',
  591. 'text' => 'text',
  592. 'ntext' => 'text',
  593. 'xml' => 'text'
  594. );
  595. $max_min_values = array(
  596. 'tinyint' => array('min' => new fNumber(0), 'max' => new fNumber(255)),
  597. 'smallint' => array('min' => new fNumber(-32768), 'max' => new fNumber(32767)),
  598. 'int' => array('min' => new fNumber(-2147483648), 'max' => new fNumber(2147483647)),
  599. 'bigint' => array('min' => new fNumber('-9223372036854775808'), 'max' => new fNumber('9223372036854775807')),
  600. 'smallmoney' => array('min' => new fNumber('-214748.3648'), 'max' => new fNumber('214748.3647')),
  601. 'money' => array('min' => new fNumber('-922337203685477.5808'), 'max' => new fNumber('922337203685477.5807'))
  602. );
  603. // Get the column info
  604. $sql = "SELECT
  605. c.column_name AS 'column',
  606. c.data_type AS 'type',
  607. c.is_nullable AS nullable,
  608. c.column_default AS 'default',
  609. c.character_maximum_length AS max_length,
  610. c.numeric_precision AS precision,
  611. c.numeric_scale AS decimal_places,
  612. CASE
  613. WHEN
  614. COLUMNPROPERTY(OBJECT_ID(QUOTENAME(c.table_schema) + '.' + QUOTENAME(c.table_name)), c.column_name, 'IsIdentity') = 1 AND
  615. OBJECTPROPERTY(OBJECT_ID(QUOTENAME(c.table_schema) + '.' + QUOTENAME(c.table_name)), 'IsMSShipped') = 0
  616. THEN '1'
  617. ELSE '0'
  618. END AS auto_increment,
  619. cc.check_clause AS 'constraint'
  620. FROM
  621. INFORMATION_SCHEMA.COLUMNS AS c LEFT JOIN
  622. INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS ccu ON c.column_name = ccu.column_name AND c.table_name = ccu.table_name AND c.table_catalog = ccu.table_catalog LEFT JOIN
  623. INFORMATION_SCHEMA.CHECK_CONSTRAINTS AS cc ON ccu.constraint_name = cc.constraint_name AND ccu.constraint_catalog = cc.constraint_catalog
  624. WHERE
  625. c.table_name = %s AND
  626. c.table_schema = %s AND
  627. c.table_catalog = DB_NAME()";
  628. $result = $this->database->query($sql, $table, $schema);
  629. foreach ($result as $row) {
  630. $info = array();
  631. foreach ($data_type_mapping as $data_type => $mapped_data_type) {
  632. if (stripos($row['type'], $data_type) === 0) {
  633. if (isset($max_min_values[$data_type])) {
  634. $info['min_value'] = $max_min_values[$data_type]['min'];
  635. $info['max_value'] = $max_min_values[$data_type]['max'];
  636. }
  637. $info['type'] = $mapped_data_type;
  638. break;
  639. }
  640. }
  641. // Handle decimal places and min/max for numeric/decimals
  642. if (in_array(strtolower($row['type']), array('decimal', 'numeric'))) {
  643. $info['decimal_places'] = $row['decimal_places'];
  644. $before_digits = str_pad('', $row['precision'] - $row['decimal_places'], '9');
  645. $after_digits = str_pad('', $row['decimal_places'], '9');
  646. $max_min = $before_digits . ($after_digits ? '.' : '') . $after_digits;
  647. $info['min_value'] = new fNumber('-' . $max_min);
  648. $info['max_value'] = new fNumber($max_min);
  649. }
  650. if (!isset($info['type'])) {
  651. $info['type'] = $row['type'];
  652. }
  653. // Handle decimal places for money/smallmoney
  654. if (in_array($row['type'], array('money', 'smallmoney'))) {
  655. $info['decimal_places'] = 2;
  656. }
  657. // Handle the special data for varchar columns
  658. if (in_array($info['type'], array('char', 'varchar', 'text', 'blob'))) {
  659. if ($row['type'] == 'uniqueidentifier') {
  660. $row['max_length'] = 32;
  661. } elseif ($row['max_length'] == -1) {
  662. $row['max_length'] = $row['type'] == 'nvarchar' ? 1073741823 : 2147483647;
  663. }
  664. $info['max_length'] = $row['max_length'];
  665. }
  666. // If the column has a constraint, look for valid values
  667. if (in_array($info['type'], array('char', 'varchar')) && !empty($row['constraint'])) {
  668. if (preg_match('#^\(((?:(?: OR )?\[[^\]]+\]\s*=\s*\'(?:\'\'|[^\']+)+\')+)\)$#D', $row['constraint'], $matches)) {
  669. $valid_values = explode(' OR ', $matches[1]);
  670. foreach ($valid_values as $key => $value) {
  671. $value = preg_replace('#^\s*\[' . preg_quote($row['column'], '#') . '\]\s*=\s*\'(.*)\'\s*$#', '\1', $value);
  672. $valid_values[$key] = str_replace("''", "'", $value);
  673. }
  674. // SQL Server turns CHECK constraint values into a reversed list, so we fix it here
  675. $info['valid_values'] = array_reverse($valid_values);
  676. }
  677. }
  678. // Handle auto increment
  679. if ($row['auto_increment']) {
  680. $info['auto_increment'] = TRUE;
  681. }
  682. // Handle default values
  683. if ($row['default'] !== NULL) {
  684. if ($row['default'] == '(getdate())') {
  685. $info['default'] = 'CURRENT_TIMESTAMP';
  686. } elseif (in_array($info['type'], array('char', 'varchar', 'text', 'timestamp')) ) {
  687. $info['default'] = substr($row['default'], 2, -2);
  688. } elseif ($info['type'] == 'boolean') {
  689. $info['default'] = (boolean) substr($row['default'], 2, -2);
  690. } elseif (in_array($info['type'], array('integer', 'float')) ) {
  691. $info['default'] = str_replace(array('(', ')'), '', $row['default']);
  692. } else {
  693. $info['default'] = pack('H*', substr($row['default'], 3, -1));
  694. }
  695. }
  696. // Handle not null
  697. $info['not_null'] = ($row['nullable'] == 'NO') ? TRUE : FALSE;
  698. $column_info[$row['column']] = $info;
  699. }
  700. return $column_info;
  701. }
  702. /**
  703. * Fetches the key info for an MSSQL database
  704. *
  705. * @return array The key info arrays for every table in the database - see ::getKeys() for details
  706. */
  707. private function fetchMSSQLKeys()
  708. {
  709. $keys = array();
  710. $tables = $this->getTables();
  711. foreach ($tables as $table) {
  712. $keys[$table] = array();
  713. $keys[$table]['primary'] = array();
  714. $keys[$table]['unique'] = array();
  715. $keys[$table]['foreign'] = array();
  716. }
  717. $sql = "SELECT
  718. c.table_schema AS \"schema\",
  719. c.table_name AS \"table\",
  720. kcu.constraint_name AS constraint_name,
  721. CASE c.constraint_type
  722. WHEN 'PRIMARY KEY' THEN 'primary'
  723. WHEN 'FOREIGN KEY' THEN 'foreign'
  724. WHEN 'UNIQUE' THEN 'unique'
  725. END AS 'type',
  726. kcu.column_name AS 'column',
  727. ccu.table_schema AS foreign_schema,
  728. ccu.table_name AS foreign_table,
  729. ccu.column_name AS foreign_column,
  730. REPLACE(LOWER(rc.delete_rule), ' ', '_') AS on_delete,
  731. REPLACE(LOWER(rc.update_rule), ' ', '_') AS on_update
  732. FROM
  733. INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS c INNER JOIN
  734. INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS kcu ON c.table_name = kcu.table_name AND c.constraint_name = kcu.constraint_name LEFT JOIN
  735. INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS rc ON c.constraint_name = rc.constraint_name LEFT JOIN
  736. INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS ccu ON ccu.constraint_name = rc.unique_constraint_name
  737. WHERE
  738. c.constraint_catalog = DB_NAME() AND
  739. c.table_name != 'sysdiagrams'
  740. ORDER BY
  741. LOWER(c.table_schema),
  742. LOWER(c.table_name),
  743. c.constraint_type,
  744. LOWER(kcu.constraint_name),
  745. kcu.ordinal_position,
  746. LOWER(kcu.column_name)";
  747. $result = $this->database->query($sql);
  748. $last_name = '';
  749. $last_table = '';
  750. $last_type = '';
  751. foreach ($result as $row) {
  752. if ($row['constraint_name'] != $last_name) {
  753. if ($last_name) {
  754. if ($last_type == 'foreign' || $last_type == 'unique') {
  755. if (!isset($keys[$last_table][$last_type])) {
  756. $keys[$last_table][$last_type] = array();
  757. }
  758. $keys[$last_table][$last_type][] = $temp;
  759. } else {
  760. $keys[$last_table][$last_type] = $temp;
  761. }
  762. }
  763. $temp = array();
  764. if ($row['type'] == 'foreign') {
  765. $temp['column'] = $row['column'];
  766. $temp['foreign_table'] = $row['foreign_table'];
  767. if ($row['foreign_schema'] != 'dbo') {
  768. $temp['foreign_table'] = $row['foreign_schema'] . '.' . $temp['foreign_table'];
  769. }
  770. $temp['foreign_column'] = $row['foreign_column'];
  771. $temp['on_delete'] = 'no_action';
  772. $temp['on_update'] = 'no_action';
  773. if (!empty($row['on_delete'])) {
  774. $temp['on_delete'] = $row['on_delete'];
  775. }
  776. if (!empty($row['on_update'])) {
  777. $temp['on_update'] = $row['on_update'];
  778. }
  779. } else {
  780. $temp[] = $row['column'];
  781. }
  782. $last_table = $row['table'];
  783. if ($row['schema'] != 'dbo') {
  784. $last_table = $row['schema'] . '.' . $last_table;
  785. }
  786. $last_name = $row['constraint_name'];
  787. $last_type = $row['type'];
  788. } else {
  789. $temp[] = $row['column'];
  790. }
  791. }
  792. if (isset($temp)) {
  793. if ($last_type == 'foreign' || $last_type == 'unique') {
  794. if (!isset($keys[$last_table][$last_type])) {
  795. $keys[$last_table][$last_type] = array();
  796. }
  797. $keys[$last_table][$last_type][] = $temp;
  798. } else {
  799. $keys[$last_table][$last_type] = $temp;
  800. }
  801. }
  802. return $keys;
  803. }
  804. /**
  805. * Gets the column info from a MySQL database
  806. *
  807. * @param string $table The table to fetch the column info for
  808. * @return array The column info for the table specified - see ::getColumnInfo() for details
  809. */
  810. private function fetchMySQLColumnInfo($table)
  811. {
  812. $data_type_mapping = array(
  813. 'tinyint' => 'integer',
  814. 'smallint' => 'integer',
  815. 'mediumint' => 'integer',
  816. 'int' => 'integer',
  817. 'bigint' => 'integer',
  818. 'datetime' => 'timestamp',
  819. 'timestamp' => 'timestamp',
  820. 'date' => 'date',
  821. 'time' => 'time',
  822. 'enum' => 'varchar',
  823. 'set' => 'varchar',
  824. 'varchar' => 'varchar',
  825. 'char' => 'char',
  826. 'float' => 'float',
  827. 'double' => 'float',
  828. 'decimal' => 'float',
  829. 'binary' => 'blob',
  830. 'varbinary' => 'blob',
  831. 'tinyblob' => 'blob',
  832. 'blob' => 'blob',
  833. 'mediumblob' => 'blob',
  834. 'longblob' => 'blob',
  835. 'tinytext' => 'text',
  836. 'text' => 'text',
  837. 'mediumtext' => 'text',
  838. 'longtext' => 'text'
  839. );
  840. $max_min_values = array(
  841. 'tinyint' => array('min' => new fNumber(-128), 'max' => new fNumber(127)),
  842. 'unsigned tinyint' => array('min' => new fNumber(0), 'max' => new fNumber(255)),
  843. 'smallint' => array('min' => new fNumber(-32768), 'max' => new fNumber(32767)),
  844. 'unsigned smallint' => array('min' => new fNumber(0), 'max' => new fNumber(65535)),
  845. 'mediumint' => array('min' => new fNumber(-8388608), 'max' => new fNumber(8388607)),
  846. 'unsigned mediumint' => array('min' => new fNumber(0), 'max' => new fNumber(16777215)),
  847. 'int' => array('min' => new fNumber(-2147483648), 'max' => new fNumber(2147483647)),
  848. 'unsigned int' => array('min' => new fNumber(0), 'max' => new fNumber('4294967295')),
  849. 'bigint' => array('min' => new fNumber('-9223372036854775808'), 'max' => new fNumber('9223372036854775807')),
  850. 'unsigned bigint' => array('min' => new fNumber(0), 'max' => new fNumber('18446744073709551615'))
  851. );
  852. $column_info = array();
  853. $result = $this->database->query('SHOW CREATE TABLE %r', $table);
  854. try {
  855. $row = $result->fetchRow();
  856. $create_sql = $row['Create Table'];
  857. } catch (fNoRowsException $e) {
  858. return array();
  859. }
  860. preg_match_all('#(?<=,|\()\s+(?:"|\`)(\w+)(?:"|\`)\s+(?:([a-z]+)(?:\(([^)]+)\))?( unsigned)?(?: zerofill)?)(?: character set [^ ]+)?(?: collate [^ ]+)?(?: NULL)?( NOT NULL)?(?: DEFAULT ((?:[^, \']*|\'(?:\'\'|[^\']+)*\')))?( auto_increment)?( COMMENT \'(?:\'\'|[^\']+)*\')?( ON UPDATE CURRENT_TIMESTAMP)?\s*(?:,|\s*(?=\)))#mi', $create_sql, $matches, PREG_SET_ORDER);
  861. foreach ($matches as $match) {
  862. $info = array();
  863. foreach ($data_type_mapping as $data_type => $mapped_data_type) {
  864. if (stripos($match[2], $data_type) === 0) {
  865. if ($match[2] == 'tinyint' && $match[3] == 1) {
  866. $mapped_data_type = 'boolean';
  867. } elseif (preg_match('#((?:unsigned )?(?:tiny|small|medium|big)?int)#', (isset($match[4]) ? $match[4] . ' ' : '') . $data_type, $int_match)) {
  868. if (isset($max_min_values[$int_match[1]])) {
  869. $info['min_value'] = $max_min_values[$int_match[1]]['min'];
  870. $info['max_value'] = $max_min_values[$int_match[1]]['max'];
  871. }
  872. }
  873. $info['type'] = $mapped_data_type;
  874. break;
  875. }
  876. }
  877. if (!isset($info['type'])) {
  878. $info['type'] = preg_replace('#^([a-z ]+).*$#iD', '\1', $match[2]);
  879. }
  880. switch ($match[2]) {
  881. case 'tinyblob':
  882. case 'tinytext':
  883. $info['max_length'] = 255;
  884. break;
  885. case 'blob':
  886. case 'text':
  887. $info['max_length'] = 65535;
  888. break;
  889. case 'mediumblob':
  890. case 'mediumtext':
  891. $info['max_length'] = 16777215;
  892. break;
  893. case 'longblob':
  894. case 'longtext':
  895. $info['max_length'] = 4294967295;
  896. break;
  897. }
  898. if (stripos($match[2], 'enum') === 0) {
  899. $info['valid_values'] = preg_replace("/^'|'\$/D", '', explode(",", $match[3]));
  900. $match[3] = 0;
  901. foreach ($info['valid_values'] as $valid_value) {
  902. if (strlen(utf8_decode($valid_value)) > $match[3]) {
  903. $match[3] = strlen(utf8_decode($valid_value));
  904. }
  905. }
  906. }
  907. // The set data type is currently only supported as a varchar
  908. // with a max length of all valid values concatenated by ,s
  909. if (stripos($match[2], 'set') === 0) {
  910. $values = preg_replace("/^'|'\$/D", '', explode(",", $match[3]));
  911. $match[3] = strlen(join(',', $values));
  912. }
  913. // Type specific information
  914. if (in_array($info['type'], array('char', 'varchar'))) {
  915. $info['max_length'] = $match[3];
  916. }
  917. // Grab the number of decimal places
  918. if (stripos($match[2], 'decimal') === 0) {
  919. if (preg_match('#^\s*(\d+)\s*,\s*(\d+)\s*$#D', $match[3], $data_type_info)) {
  920. $info['decimal_places'] = $data_type_info[2];
  921. $before_digits = str_pad('', $data_type_info[1] - $info['decimal_places'], '9');
  922. $after_digits = str_pad('', $info['decimal_places'], '9');
  923. $max_min = $before_digits . ($after_digits ? '.' : '') . $after_digits;
  924. $info['min_value'] = new fNumber('-' . $max_min);
  925. $info['max_value'] = new fNumber($max_min);
  926. }
  927. }
  928. // Not null
  929. $info['not_null'] = (!empty($match[5])) ? TRUE : FALSE;
  930. // Default values
  931. if (!empty($match[6]) && $match[6] != 'NULL') {
  932. $info['default'] = preg_replace("/^'|'\$/D", '', $match[6]);
  933. }
  934. if ($info['type'] == 'boolean' && isset($info['default'])) {
  935. $info['default'] = (boolean) $info['default'];
  936. }
  937. // Auto increment fields
  938. if (!empty($match[7])) {
  939. $info['auto_increment'] = TRUE;
  940. }
  941. $column_info[$match[1]] = $info;
  942. }
  943. return $column_info;
  944. }
  945. /**
  946. * Fetches the keys for a MySQL database
  947. *
  948. * @return array The keys arrays for every table in the database - see ::getKeys() for details
  949. */
  950. private function fetchMySQLKeys()
  951. {
  952. $tables = $this->getTables();
  953. $keys = array();
  954. foreach ($tables as $table) {
  955. $keys[$table] = array();
  956. $keys[$table]['primary'] = array();
  957. $keys[$table]['foreign'] = array();
  958. $keys[$table]['unique'] = array();
  959. $result = $this->database->query('SHOW CREATE TABLE %r', $table);
  960. $row = $result->fetchRow();
  961. // Primary keys
  962. preg_match_all('/PRIMARY KEY\s+\("(.*?)"\),?\n/U', $row['Create Table'], $matches, PREG_SET_ORDER);
  963. if (!empty($matches)) {
  964. $keys[$table]['primary'] = explode('","', $matches[0][1]);
  965. }
  966. // Unique keys
  967. preg_match_all('/UNIQUE KEY\s+"([^"]+)"\s+\("(.*?)"\),?\n/U', $row['Create Table'], $matches, PREG_SET_ORDER);
  968. foreach ($matches as $match) {
  969. $keys[$table]['unique'][] = explode('","', $match[2]);
  970. }
  971. // Foreign keys
  972. preg_match_all('#FOREIGN KEY \("([^"]+)"\) REFERENCES "([^"]+)" \("([^"]+)"\)(?:\sON\sDELETE\s(SET\sNULL|SET\sDEFAULT|CASCADE|NO\sACTION|RESTRICT))?(?:\sON\sUPDATE\s(SET\sNULL|SET\sDEFAULT|CASCADE|NO\sACTION|RESTRICT))?#', $row['Create Table'], $matches, PREG_SET_ORDER);
  973. foreach ($matches as $match) {
  974. $temp = array('column' => $match[1],
  975. 'foreign_table' => $match[2],
  976. 'foreign_column' => $match[3],
  977. 'on_delete' => 'no_action',
  978. 'on_update' => 'no_action');
  979. if (!empty($match[4])) {
  980. $temp['on_delete'] = strtolower(str_replace(' ', '_', $match[4]));
  981. }
  982. if (!empty($match[5])) {
  983. $temp['on_update'] = strtolower(str_replace(' ', '_', $match[5]));
  984. }
  985. $keys[$table]['foreign'][] = $temp;
  986. }
  987. }
  988. return $keys;
  989. }
  990. /**
  991. * Gets the column info from an Oracle database
  992. *
  993. * @param string $table The table to fetch the column info for
  994. * @return array The column info for the table specified - see ::getColumnInfo() for details
  995. */
  996. private function fetchOracleColumnInfo($table)
  997. {
  998. $table = strtoupper($table);
  999. $schema = strtoupper($this->database->getUsername());
  1000. if (strpos($table, '.') !== FALSE) {
  1001. list ($schema, $table) = explode('.', $table);
  1002. }
  1003. $column_info = array();
  1004. $data_type_mapping = array(
  1005. 'boolean' => 'boolean',
  1006. 'number' => 'integer',
  1007. 'integer' => 'integer',
  1008. 'timestamp' => 'timestamp',
  1009. 'date' => 'date',
  1010. 'varchar2' => 'varchar',
  1011. 'nvarchar2' => 'varchar',
  1012. 'char' => 'char',
  1013. 'nchar' => 'char',
  1014. 'float' => 'float',
  1015. 'binary_float' => 'float',
  1016. 'binary_double' => 'float',
  1017. 'blob' => 'blob',
  1018. 'bfile' => 'varchar',
  1019. 'clob' => 'text',
  1020. 'nclob' => 'text'
  1021. );
  1022. $sql = "SELECT
  1023. LOWER(ATC.COLUMN_NAME) COLUMN_NAME,
  1024. CASE
  1025. WHEN
  1026. ATC.DATA_TYPE = 'NUMBER' AND
  1027. ATC.DATA_PRECISION IS NULL AND
  1028. ATC.DATA_SCALE = 0
  1029. THEN
  1030. 'integer'
  1031. WHEN
  1032. ATC.DATA_TYPE = 'NUMBER' AND
  1033. ATC.DATA_PRECISION = 1 AND
  1034. ATC.DATA_SCALE = 0
  1035. THEN
  1036. 'boolean'
  1037. WHEN
  1038. ATC.DATA_TYPE = 'NUMBER' AND
  1039. ATC.DATA_PRECISION IS NOT NULL AND
  1040. ATC.DATA_SCALE != 0 AND
  1041. ATC.DATA_SCALE IS NOT NULL
  1042. THEN
  1043. 'float'
  1044. ELSE
  1045. LOWER(ATC.DATA_TYPE)
  1046. END DATA_TYPE,
  1047. CASE
  1048. WHEN
  1049. ATC.CHAR_LENGTH <> 0
  1050. THEN
  1051. ATC.CHAR_LENGTH
  1052. WHEN
  1053. ATC.DATA_TYPE = 'NUMBER' AND
  1054. ATC.DATA_PRECISION != 1 AND
  1055. ATC.DATA_SCALE != 0 AND
  1056. ATC.DATA_PRECISION IS NOT NULL
  1057. THEN
  1058. ATC.DATA_SCALE
  1059. ELSE
  1060. NULL
  1061. END LENGTH,
  1062. ATC.DATA_PRECISION PRECISION,
  1063. ATC.NULLABLE,
  1064. ATC.DATA_DEFAULT,
  1065. AC.SEARCH_CONDITION CHECK_CONSTRAINT
  1066. FROM
  1067. ALL_TAB_COLUMNS ATC LEFT JOIN
  1068. ALL_CONS_COLUMNS ACC ON
  1069. ATC.OWNER = ACC.OWNER AND
  1070. ATC.COLUMN_NAME = ACC.COLUMN_NAME AND
  1071. ATC.TABLE_NAME = ACC.TABLE_NAME AND
  1072. ACC.POSITION IS NULL LEFT JOIN
  1073. ALL_CONSTRAINTS AC ON
  1074. AC.OWNER = ACC.OWNER AND
  1075. AC.CONSTRAINT_NAME = ACC.CONSTRAINT_NAME AND
  1076. AC.CONSTRAINT_TYPE = 'C' AND
  1077. AC.STATUS = 'ENABLED'
  1078. WHERE
  1079. ATC.TABLE_NAME = %s AND
  1080. ATC.OWNER = %s
  1081. ORDER BY
  1082. ATC.TABLE_NAME ASC,
  1083. ATC.COLUMN_ID ASC";
  1084. $result = $this->database->query($sql, $table, $schema);
  1085. foreach ($result as $row) {
  1086. $column = $row['column_name'];
  1087. // Since Oracle stores check constraints in LONG columns, it is
  1088. // not possible to check or modify the constraints in SQL which
  1089. // ends up causing multiple rows with duplicate data except for
  1090. // the check constraint
  1091. $duplicate = FALSE;
  1092. if (isset($column_info[$column])) {
  1093. $info = $column_info[$column];
  1094. $duplicate = TRUE;
  1095. } else {
  1096. $info = array();
  1097. }
  1098. if (!$duplicate) {
  1099. // Get the column type
  1100. foreach ($data_type_mapping as $data_type => $mapped_data_type) {
  1101. if (stripos($row['data_type'], $data_type) === 0) {
  1102. $info['type'] = $mapped_data_type;
  1103. break;
  1104. }
  1105. }
  1106. if (!isset($info['type'])) {
  1107. $info['type'] = $row['data_type'];
  1108. }
  1109. if (in_array($info['type'], array('blob', 'text'))) {
  1110. $info['max_length'] = 4294967295;
  1111. }
  1112. if ($row['data_type'] == 'float' && $row['precision']) {
  1113. $row['length'] = (int) $row['length'];
  1114. $before_digits = str_pad('', $row['precision'] - $row['length'], '9');
  1115. $after_digits = str_pad('', $row['length'], '9');
  1116. $max_min = $before_digits . ($after_digits ? '.' : '') . $after_digits;
  1117. $info['min_value'] = new fNumber('-' . $max_min);
  1118. $info['max_value'] = new fNumber($max_min);
  1119. }
  1120. // Handle the length of decimal/numeric fields
  1121. if ($info['type'] == 'float' && $row['length']) {
  1122. $info['decimal_places'] = (int) $row['length'];
  1123. }
  1124. // Handle the special data for varchar fields
  1125. if (in_array($info['type'], array('char', 'varchar'))) {
  1126. $info['max_length'] = (int) $row['length'];
  1127. }
  1128. }
  1129. // Handle check constraints that are just simple lists
  1130. if (in_array($info['type'], array('varchar', 'char')) && $row['check_constraint']) {
  1131. if (preg_match('/^\s*' . preg_quote($column, '/') . '\s+in\s+\((.*?)\)\s*$/i', $row['check_constraint'], $match)) {
  1132. if (preg_match_all("/(?<!')'((''|[^']+)*)'/", $match[1], $matches, PREG_PATTERN_ORDER)) {
  1133. $info['valid_values'] = str_replace("''", "'", $matches[1]);
  1134. }
  1135. }
  1136. }
  1137. if (!$duplicate) {
  1138. // Handle default values
  1139. if ($row['data_default'] !== NULL) {
  1140. if (in_array($info['type'], array('char', 'varchar', 'text'))) {
  1141. $info['default'] = str_replace("''", "'", substr(trim($row['data_default']), 1, -1));
  1142. } elseif ($info['type'] == 'boolean') {
  1143. $info['default'] = (boolean) trim($row['data_default']);
  1144. } elseif (in_array($info['type'], array('integer', 'float'))) {
  1145. $info['default'] = trim($row['data_default']);
  1146. } else {
  1147. $info['default'] = $row['data_default'];
  1148. }
  1149. }
  1150. // Not null values
  1151. $info['not_null'] = ($row['nullable'] == 'N') ? TRUE : FALSE;
  1152. }
  1153. $column_info[$column] = $info;
  1154. }
  1155. $sql = "SELECT
  1156. TRIGGER_BODY
  1157. FROM
  1158. ALL_TRIGGERS
  1159. WHERE
  1160. TRIGGERING_EVENT = 'INSERT' AND
  1161. STATUS = 'ENABLED' AND
  1162. TRIGGER_NAME NOT LIKE 'BIN\$%' AND
  1163. TABLE_NAME = %s AND
  1164. OWNER = %s";
  1165. foreach ($this->database->query($sql, $table, $schema) as $row) {
  1166. if (preg_match('#SELECT\s+(["\w.]+).nextval\s+INTO\s+:new\.(\w+)\s+FROM\s+dual#i', $row['trigger_body'], $matches)) {
  1167. $column = strtolower($matches[2]);
  1168. $column_info[$column]['auto_increment'] = TRUE;
  1169. }
  1170. }
  1171. return $column_info;
  1172. }
  1173. /**
  1174. * Fetches the key info for an Oracle database
  1175. *
  1176. * @return array The keys arrays for every table in the database - see ::getKeys() for details
  1177. */
  1178. private function fetchOracleKeys()
  1179. {
  1180. $keys = array();
  1181. $default_schema = strtolower($this->database->getUsername());
  1182. $tables = $this->getTables();
  1183. foreach ($tables as $table) {
  1184. $keys[$table] = array();
  1185. $keys[$table]['primary'] = array();
  1186. $keys[$table]['unique'] = array();
  1187. $keys[$table]['foreign'] = array();
  1188. }
  1189. $params = array();
  1190. $sql = "SELECT
  1191. LOWER(AC.OWNER) \"SCHEMA\",
  1192. LOWER(AC.TABLE_NAME) \"TABLE\",
  1193. AC.CONSTRAINT_NAME CONSTRAINT_NAME,
  1194. CASE AC.CONSTRAINT_TYPE
  1195. WHEN 'P' THEN 'primary'
  1196. WHEN 'R' THEN 'foreign'
  1197. WHEN 'U' THEN 'unique'
  1198. END TYPE,
  1199. LOWER(ACC.COLUMN_NAME) \"COLUMN\",
  1200. LOWER(FKC.OWNER) FOREIGN_SCHEMA,
  1201. LOWER(FKC.TABLE_NAME) FOREIGN_TABLE,
  1202. LOWER(FKC.COLUMN_NAME) FOREIGN_COLUMN,
  1203. CASE WHEN FKC.TABLE_NAME IS NOT NULL THEN REPLACE(LOWER(AC.DELETE_RULE), ' ', '_') ELSE NULL END ON_DELETE
  1204. FROM
  1205. ALL_CONSTRAINTS AC INNER JOIN
  1206. ALL_CONS_COLUMNS ACC ON AC.CONSTRAINT_NAME = ACC.CONSTRAINT_NAME AND AC.OWNER = ACC.OWNER LEFT JOIN
  1207. ALL_CONSTRAINTS FK ON AC.R_CONSTRAINT_NAME = FK.CONSTRAINT_NAME AND AC.OWNER = FK.OWNER LEFT JOIN
  1208. ALL_CONS_COLUMNS FKC ON FK.CONSTRAINT_NAME = FKC.CONSTRAINT_NAME AND FK.OWNER = FKC.OWNER
  1209. WHERE
  1210. AC.CONSTRAINT_TYPE IN ('U', 'P', 'R') AND ";
  1211. $conditions = array();
  1212. foreach ($tables as $table) {
  1213. if (strpos($table, '.') === FALSE) {
  1214. $table = $default_schema . '.' . $table;
  1215. }
  1216. list ($schema, $table) = explode('.', strtoupper($table));
  1217. $conditions[] = "AC.OWNER = %s AND AC.TABLE_NAME = %s";
  1218. $params[] = $schema;
  1219. $params[] = $table;
  1220. }
  1221. $sql .= '((' . join(') OR( ', $conditions) . '))';
  1222. $sql .= " ORDER BY
  1223. AC.OWNER ASC,
  1224. AC.TABLE_NAME ASC,
  1225. AC.CONSTRAINT_TYPE ASC,
  1226. AC.CONSTRAINT_NAME ASC,
  1227. ACC.POSITION ASC";
  1228. $result = $this->database->query($sql, $params);
  1229. $last_name = '';
  1230. $last_table = '';
  1231. $last_type = '';
  1232. foreach ($result as $row) {
  1233. if ($row['constraint_name'] != $last_name) {
  1234. if ($last_name) {
  1235. if ($last_type == 'foreign' || $last_type == 'unique') {
  1236. $keys[$last_table][$last_type][] = $temp;
  1237. } else {
  1238. $keys[$last_table][$last_type] = $temp;
  1239. }
  1240. }
  1241. $temp = array();
  1242. if ($row['type'] == 'foreign') {
  1243. $temp['column'] = $row['column'];
  1244. $temp['foreign_table'] = $row['foreign_table'];
  1245. if ($row['foreign_schema'] != $default_schema) {
  1246. $temp['foreign_table'] = $row['foreign_schema'] . '.' . $temp['foreign_table'];
  1247. }
  1248. $temp['foreign_column'] = $row['foreign_column'];
  1249. $temp['on_delete'] = 'no_action';
  1250. $temp['on_update'] = 'no_action';
  1251. if (!empty($row['on_delete'])) {
  1252. $temp['on_delete'] = $row['on_delete'];
  1253. }
  1254. } else {
  1255. $temp[] = $row['column'];
  1256. }
  1257. $last_table = $row['table'];
  1258. if ($row['schema'] != $default_schema) {
  1259. $last_table = $row['schema'] . '.' . $last_table;
  1260. }
  1261. $last_name = $row['constraint_name'];
  1262. $last_type = $row['type'];
  1263. } else {
  1264. $temp[] = $row['column'];
  1265. }
  1266. }
  1267. if (isset($temp)) {
  1268. if ($last_type == 'foreign' || $last_type == 'unique') {
  1269. $keys[$last_table][$last_type][] = $temp;
  1270. } else {
  1271. $keys[$last_table][$last_type] = $temp;
  1272. }
  1273. }
  1274. return $keys;
  1275. }
  1276. /**
  1277. * Gets the column info from a PostgreSQL database
  1278. *
  1279. * @param string $table The table to fetch the column info for
  1280. * @return array The column info for the table specified - see ::getColumnInfo() for details
  1281. */
  1282. private function fetchPostgreSQLColumnInfo($table)
  1283. {
  1284. $column_info = array();
  1285. $schema = 'public';
  1286. if (strpos($table, '.') !== FALSE) {
  1287. list ($schema, $table) = explode('.', $table);
  1288. }
  1289. $data_type_mapping = array(
  1290. 'boolean' => 'boolean',
  1291. 'smallint' => 'integer',
  1292. 'int' => 'integer',
  1293. 'bigint' => 'integer',
  1294. 'serial' => 'integer',
  1295. 'bigserial' => 'integer',
  1296. 'timestamp' => 'timestamp',
  1297. 'date' => 'date',
  1298. 'time' => 'time',
  1299. 'uuid' => 'varchar',
  1300. 'character varying' => 'varchar',
  1301. 'character' => 'char',
  1302. 'real' => 'float',
  1303. 'double' => 'float',
  1304. 'numeric' => 'float',
  1305. 'bytea' => 'blob',
  1306. 'text' => 'text',
  1307. 'mediumtext'

Large files files are truncated, but you can click here to view the full file