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

/base/lib/flourishlib/fSchema.php

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

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