PageRenderTime 68ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/classes/fSchema.php

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

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