PageRenderTime 71ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/inc/flourish/fSchema.php

https://github.com/trbs/Graphite-Tattle
PHP | 3153 lines | 2247 code | 319 blank | 587 comment | 314 complexity | 45c080c223156ed8b16871645b454a99 MD5 | raw file
Possible License(s): Apache-2.0
  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.0b50
  13. * @changes 1.0.0b50 Fixed detection of explicitly named SQLite foreign key constraints [wb, 2011-08-23]
  14. * @changes 1.0.0b49 Added support for spatial/geometric data types in MySQL and PostgreSQL [wb, 2011-05-26]
  15. * @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]
  16. * @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]
  17. * @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]
  18. * @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]
  19. * @changes 1.0.0b44 Fixed the list of valid elements for ::getColumnInfo() [wb, 2010-11-28]
  20. * @changes 1.0.0b43 Added the `comment` element to the information returned by ::getColumnInfo() [wb, 2010-11-28]
  21. * @changes 1.0.0b42 Fixed a bug with MySQL detecting default `ON DELETE` clauses [wb, 2010-10-19]
  22. * @changes 1.0.0b41 Fixed handling MySQL table names that require quoting [wb, 2010-08-24]
  23. * @changes 1.0.0b40 Fixed bugs in the documentation and error message of ::getColumnInfo() about what are valid elements [wb, 2010-07-21]
  24. * @changes 1.0.0b39 Fixed a regression where key detection SQL was not compatible with PostgreSQL 8.1 [wb, 2010-04-13]
  25. * @changes 1.0.0b38 Added Oracle support to ::getDatabases() [wb, 2010-04-13]
  26. * @changes 1.0.0b37 Fixed ::getDatabases() for MSSQL [wb, 2010-04-09]
  27. * @changes 1.0.0b36 Fixed PostgreSQL to properly report explicit `NULL` default values via ::getColumnInfo() [wb, 2010-03-30]
  28. * @changes 1.0.0b35 Added `max_length` values for various text and blob data types across all databases [wb, 2010-03-29]
  29. * @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]
  30. * @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]
  31. * @changes 1.0.0b32 Fixed ::getTables() to not include views for MySQL [wb, 2010-03-14]
  32. * @changes 1.0.0b31 Fixed the creation of the default caching key for ::enableCaching() [wb, 2010-03-02]
  33. * @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]
  34. * @changes 1.0.0b29 Added on_delete and on_update elements to one-to-one relationship info retrieved by ::getRelationships() [wb, 2009-12-16]
  35. * @changes 1.0.0b28 Fixed a bug with detecting some multi-column unique constraints in SQL Server databases [wb, 2009-11-13]
  36. * @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]
  37. * @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]
  38. * @changes 1.0.0b25 One-to-one relationships utilizing the primary key as a foreign key are now properly detected [wb, 2009-09-22]
  39. * @changes 1.0.0b24 Fixed MSSQL support to work with ODBC database connections [wb, 2009-09-18]
  40. * @changes 1.0.0b23 Fixed a bug where one-to-one relationships were being listed as many-to-one [wb, 2009-07-21]
  41. * @changes 1.0.0b22 PostgreSQL UNIQUE constraints that are created as indexes and not table constraints are now properly detected [wb, 2009-07-08]
  42. * @changes 1.0.0b21 Added support for the UUID data type in PostgreSQL [wb, 2009-06-18]
  43. * @changes 1.0.0b20 Add caching of merged info, improved performance of ::getColumnInfo() [wb, 2009-06-15]
  44. * @changes 1.0.0b19 Fixed a couple of bugs with ::setKeysOverride() [wb, 2009-06-04]
  45. * @changes 1.0.0b18 Added missing support for MySQL mediumint columns [wb, 2009-05-18]
  46. * @changes 1.0.0b17 Fixed a bug with ::clearCache() not properly reseting the tables and databases list [wb, 2009-05-13]
  47. * @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]
  48. * @changes 1.0.0b15 Added support for the three different types of identifier quoting in SQLite [wb, 2009-03-28]
  49. * @changes 1.0.0b14 Added support for MySQL column definitions containing the COLLATE keyword [wb, 2009-03-28]
  50. * @changes 1.0.0b13 Fixed a bug with detecting PostgreSQL columns having both a CHECK constraint and a UNIQUE constraint [wb, 2009-02-27]
  51. * @changes 1.0.0b12 Fixed detection of multi-column primary keys in MySQL [wb, 2009-02-27]
  52. * @changes 1.0.0b11 Fixed an issue parsing MySQL tables with comments [wb, 2009-02-25]
  53. * @changes 1.0.0b10 Added the ::getDatabases() method [wb, 2009-02-24]
  54. * @changes 1.0.0b9 Now detects unsigned and zerofill MySQL data types that do not have a parenthetical part [wb, 2009-02-16]
  55. * @changes 1.0.0b8 Mapped the MySQL data type `'set'` to `'varchar'`, however valid values are not implemented yet [wb, 2009-02-01]
  56. * @changes 1.0.0b7 Fixed a bug with detecting MySQL timestamp columns [wb, 2009-01-28]
  57. * @changes 1.0.0b6 Fixed a bug with detecting MySQL columns that accept `NULL` [wb, 2009-01-19]
  58. * @changes 1.0.0b5 ::setColumnInfo(): fixed a bug with not grabbing the real database schema first, made general improvements [wb, 2009-01-19]
  59. * @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]
  60. * @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]
  61. * @changes 1.0.0b2 Fixed a bug with detecting multi-column unique keys in MySQL [wb, 2009-01-03]
  62. * @changes 1.0.0b The initial implementation [wb, 2007-09-25]
  63. */
  64. class fSchema
  65. {
  66. /**
  67. * The place to cache to
  68. *
  69. * @var fCache
  70. */
  71. private $cache = NULL;
  72. /**
  73. * The cache prefix to use for cache entries
  74. *
  75. * @var string
  76. */
  77. private $cache_prefix;
  78. /**
  79. * The cached column info
  80. *
  81. * @var array
  82. */
  83. private $column_info = array();
  84. /**
  85. * The column info to override
  86. *
  87. * @var array
  88. */
  89. private $column_info_override = array();
  90. /**
  91. * A reference to an instance of the fDatabase class
  92. *
  93. * @var fDatabase
  94. */
  95. private $database = NULL;
  96. /**
  97. * The databases on the current database server
  98. *
  99. * @var array
  100. */
  101. private $databases = NULL;
  102. /**
  103. * The cached key info
  104. *
  105. * @var array
  106. */
  107. private $keys = array();
  108. /**
  109. * The key info to override
  110. *
  111. * @var array
  112. */
  113. private $keys_override = array();
  114. /**
  115. * The merged column info
  116. *
  117. * @var array
  118. */
  119. private $merged_column_info = array();
  120. /**
  121. * The merged key info
  122. *
  123. * @var array
  124. */
  125. private $merged_keys = array();
  126. /**
  127. * The relationships in the database
  128. *
  129. * @var array
  130. */
  131. private $relationships = array();
  132. /**
  133. * The tables in the database
  134. *
  135. * @var array
  136. */
  137. private $tables = NULL;
  138. /**
  139. * Sets the database
  140. *
  141. * @param fDatabase $database The fDatabase instance
  142. * @return fSchema
  143. */
  144. public function __construct($database)
  145. {
  146. $this->database = $database;
  147. }
  148. /**
  149. * All requests that hit this method should be requests for callbacks
  150. *
  151. * @internal
  152. *
  153. * @param string $method The method to create a callback for
  154. * @return callback The callback for the method requested
  155. */
  156. public function __get($method)
  157. {
  158. return array($this, $method);
  159. }
  160. /**
  161. * Checks to see if a column is part of a single-column `UNIQUE` key
  162. *
  163. * @param string $table The table the column is located in
  164. * @param string $column The column to check
  165. * @return boolean If the column is part of a single-column unique key
  166. */
  167. private function checkForSingleColumnUniqueKey($table, $column)
  168. {
  169. foreach ($this->merged_keys[$table]['unique'] as $key) {
  170. if (array($column) == $key) {
  171. return TRUE;
  172. }
  173. }
  174. if (array($column) == $this->merged_keys[$table]['primary']) {
  175. return TRUE;
  176. }
  177. return FALSE;
  178. }
  179. /**
  180. * Clears all of the schema info out of the object and, if set, the fCache object
  181. *
  182. * @internal
  183. *
  184. * @return void
  185. */
  186. public function clearCache()
  187. {
  188. $this->column_info = array();
  189. $this->databases = NULL;
  190. $this->keys = array();
  191. $this->merged_column_info = array();
  192. $this->merged_keys = array();
  193. $this->relationships = array();
  194. $this->tables = NULL;
  195. if ($this->cache) {
  196. $prefix = $this->makeCachePrefix();
  197. $this->cache->delete($prefix . 'column_info');
  198. $this->cache->delete($prefix . 'databases');
  199. $this->cache->delete($prefix . 'keys');
  200. $this->cache->delete($prefix . 'merged_column_info');
  201. $this->cache->delete($prefix . 'merged_keys');
  202. $this->cache->delete($prefix . 'relationships');
  203. $this->cache->delete($prefix . 'tables');
  204. }
  205. }
  206. /**
  207. * Returns an ordered array of table names, in a valid table creation order
  208. *
  209. * @param string $filter_table The only return this table and tables that rely on it
  210. * @return array An array of table names
  211. */
  212. private function determineTableCreationOrder($filter_table=NULL)
  213. {
  214. $found = array();
  215. $ignored_found = array();
  216. $current_tables = $this->getTables();
  217. while ($current_tables) {
  218. $remaining_tables = array();
  219. foreach ($current_tables as $table) {
  220. $foreign_keys = $this->getKeys($table, 'foreign');
  221. if (!$foreign_keys) {
  222. if ($filter_table !== NULL) {
  223. if ($table == $filter_table) {
  224. $found[] = $table;
  225. } else {
  226. $ignored_found[] = $table;
  227. }
  228. } else {
  229. $found[] = $table;
  230. }
  231. } else {
  232. $all_dependencies_met = TRUE;
  233. $found_dependencies = 0;
  234. foreach ($foreign_keys as $foreign_key) {
  235. if (!in_array($foreign_key['foreign_table'], $found) && !in_array($foreign_key['foreign_table'], $ignored_found)) {
  236. $all_dependencies_met = FALSE;
  237. break;
  238. } elseif (in_array($foreign_key['foreign_table'], $found)) {
  239. $found_dependencies++;
  240. }
  241. }
  242. if ($all_dependencies_met) {
  243. if ($filter_table !== NULL) {
  244. if ($found_dependencies || $table == $filter_table) {
  245. $found[] = $table;
  246. } else {
  247. $ignored_found[] = $table;
  248. }
  249. } else {
  250. $found[] = $table;
  251. }
  252. } else {
  253. $remaining_tables[] = $table;
  254. }
  255. }
  256. }
  257. $current_tables = $remaining_tables;
  258. }
  259. return $found;
  260. }
  261. /**
  262. * Sets the schema to be cached to the fCache object specified
  263. *
  264. * @param fCache $cache The cache to cache to
  265. * @param string $key_token Internal use only! (this will be used in the cache key to uniquely identify the cache for this fSchema object)
  266. * @return void
  267. */
  268. public function enableCaching($cache, $key_token=NULL)
  269. {
  270. $this->cache = $cache;
  271. if ($key_token !== NULL) {
  272. $this->cache_prefix = 'fSchema::' . $this->database->getType() . '::' . $key_token . '::';
  273. }
  274. $prefix = $this->makeCachePrefix();
  275. $this->column_info = $this->cache->get($prefix . 'column_info', array());
  276. $this->databases = $this->cache->get($prefix . 'databases', NULL);
  277. $this->keys = $this->cache->get($prefix . 'keys', array());
  278. if (!$this->column_info_override && !$this->keys_override) {
  279. $this->merged_column_info = $this->cache->get($prefix . 'merged_column_info', array());
  280. $this->merged_keys = $this->cache->get($prefix . 'merged_keys', array());
  281. $this->relationships = $this->cache->get($prefix . 'relationships', array());
  282. }
  283. $this->tables = $this->cache->get($prefix . 'tables', NULL);
  284. }
  285. /**
  286. * Gets the column info from the database for later access
  287. *
  288. * @param string $table The table to fetch the column info for
  289. * @return void
  290. */
  291. private function fetchColumnInfo($table)
  292. {
  293. if (isset($this->column_info[$table])) {
  294. return;
  295. }
  296. switch ($this->database->getType()) {
  297. case 'db2':
  298. $column_info = $this->fetchDB2ColumnInfo($table);
  299. break;
  300. case 'mssql':
  301. $column_info = $this->fetchMSSQLColumnInfo($table);
  302. break;
  303. case 'mysql':
  304. $column_info = $this->fetchMySQLColumnInfo($table);
  305. break;
  306. case 'oracle':
  307. $column_info = $this->fetchOracleColumnInfo($table);
  308. break;
  309. case 'postgresql':
  310. $column_info = $this->fetchPostgreSQLColumnInfo($table);
  311. break;
  312. case 'sqlite':
  313. $column_info = $this->fetchSQLiteColumnInfo($table);
  314. break;
  315. }
  316. if (!$column_info) {
  317. return;
  318. }
  319. $this->column_info[$table] = $column_info;
  320. if ($this->cache) {
  321. $this->cache->set($this->makeCachePrefix() . 'column_info', $this->column_info);
  322. }
  323. }
  324. /**
  325. * Gets the column info from a DB2 database
  326. *
  327. * @param string $table The table to fetch the column info for
  328. * @return array The column info for the table specified - see ::getColumnInfo() for details
  329. */
  330. private function fetchDB2ColumnInfo($table)
  331. {
  332. $column_info = array();
  333. $schema = strtolower($this->database->getUsername());
  334. if (strpos($table, '.') !== FALSE) {
  335. list ($schema, $table) = explode('.', $table);
  336. }
  337. $data_type_mapping = array(
  338. 'smallint' => 'integer',
  339. 'integer' => 'integer',
  340. 'bigint' => 'integer',
  341. 'timestamp' => 'timestamp',
  342. 'date' => 'date',
  343. 'time' => 'time',
  344. 'varchar' => 'varchar',
  345. 'long varchar' => 'varchar',
  346. 'vargraphic' => 'varchar',
  347. 'long vargraphic' => 'varchar',
  348. 'character' => 'char',
  349. 'graphic' => 'char',
  350. 'real' => 'float',
  351. 'decimal' => 'float',
  352. 'numeric' => 'float',
  353. 'blob' => 'blob',
  354. 'clob' => 'text',
  355. 'dbclob' => 'text'
  356. );
  357. $max_min_values = array(
  358. 'smallint' => array('min' => new fNumber(-32768), 'max' => new fNumber(32767)),
  359. 'integer' => array('min' => new fNumber(-2147483648), 'max' => new fNumber(2147483647)),
  360. 'bigint' => array('min' => new fNumber('-9223372036854775808'), 'max' => new fNumber('9223372036854775807'))
  361. );
  362. // Get the column info
  363. $sql = "SELECT
  364. LOWER(C.COLNAME) AS \"COLUMN\",
  365. C.TYPENAME AS TYPE,
  366. C.NULLS AS NULLABLE,
  367. C.DEFAULT,
  368. C.LENGTH AS MAX_LENGTH,
  369. C.SCALE,
  370. CASE WHEN C.IDENTITY = 'Y' AND (C.GENERATED = 'D' OR C.GENERATED = 'A') THEN '1' ELSE '0' END AS AUTO_INCREMENT,
  371. CH.TEXT AS \"CONSTRAINT\",
  372. C.REMARKS AS \"COMMENT\"
  373. FROM
  374. SYSCAT.COLUMNS AS C LEFT JOIN
  375. SYSCAT.COLCHECKS AS CC ON
  376. C.TABSCHEMA = CC.TABSCHEMA AND
  377. C.TABNAME = CC.TABNAME AND
  378. C.COLNAME = CC.COLNAME AND
  379. CC.USAGE = 'R' LEFT JOIN
  380. SYSCAT.CHECKS AS CH ON
  381. C.TABSCHEMA = CH.TABSCHEMA AND
  382. C.TABNAME = CH.TABNAME AND
  383. CH.TYPE = 'C' AND
  384. CH.CONSTNAME = CC.CONSTNAME
  385. WHERE
  386. LOWER(C.TABSCHEMA) = %s AND
  387. LOWER(C.TABNAME) = %s
  388. ORDER BY
  389. C.COLNO ASC";
  390. $result = $this->database->query($sql, strtolower($schema), strtolower($table));
  391. foreach ($result as $row) {
  392. $info = array();
  393. foreach ($data_type_mapping as $data_type => $mapped_data_type) {
  394. if (stripos($row['type'], $data_type) === 0) {
  395. if (isset($max_min_values[$data_type])) {
  396. $info['min_value'] = $max_min_values[$data_type]['min'];
  397. $info['max_value'] = $max_min_values[$data_type]['max'];
  398. }
  399. $info['type'] = $mapped_data_type;
  400. break;
  401. }
  402. }
  403. // Handle decimal places and min/max for numeric/decimals
  404. if (in_array(strtolower($row['type']), array('decimal', 'numeric'))) {
  405. $info['decimal_places'] = $row['scale'];
  406. $before_digits = str_pad('', $row['max_length'] - $row['scale'], '9');
  407. $after_digits = str_pad('', $row['scale'], '9');
  408. $max_min = $before_digits . ($after_digits ? '.' : '') . $after_digits;
  409. $info['min_value'] = new fNumber('-' . $max_min);
  410. $info['max_value'] = new fNumber($max_min);
  411. }
  412. if (!isset($info['type'])) {
  413. $info['type'] = $row['type'];
  414. }
  415. // Handle the special data for varchar columns
  416. if (in_array($info['type'], array('char', 'varchar', 'text', 'blob'))) {
  417. $info['max_length'] = $row['max_length'];
  418. }
  419. // The generally accepted practice for boolean on DB2 is a CHAR(1) with a CHECK constraint
  420. if ($info['type'] == 'char' && $info['max_length'] == 1 && !empty($row['constraint'])) {
  421. if (is_resource($row['constraint'])) {
  422. $row['constraint'] = stream_get_contents($row['constraint']);
  423. }
  424. if (preg_match('/^\s*"?' . preg_quote($row['column'], '/') . '"?\s+in\s+\(\s*(\'0\',\s*\'1\'|\'1\',\s*\'0\')\s*\)\s*$/i', $row['constraint'])) {
  425. $info['type'] = 'boolean';
  426. $info['max_length'] = NULL;
  427. }
  428. }
  429. // If the column has a constraint, look for valid values
  430. if (in_array($info['type'], array('char', 'varchar')) && !empty($row['constraint'])) {
  431. if (preg_match('/^\s*"?' . preg_quote($row['column'], '/') . '"?\s+in\s+\((.*?)\)\s*$/i', $row['constraint'], $match)) {
  432. if (preg_match_all("/(?<!')'((''|[^']+)*)'/", $match[1], $matches, PREG_PATTERN_ORDER)) {
  433. $info['valid_values'] = str_replace("''", "'", $matches[1]);
  434. }
  435. }
  436. }
  437. // Handle auto increment
  438. if ($row['auto_increment']) {
  439. $info['auto_increment'] = TRUE;
  440. }
  441. // Handle default values
  442. if ($row['default'] !== NULL) {
  443. if ($row['default'] == 'NULL') {
  444. $info['default'] = NULL;
  445. } elseif (in_array($info['type'], array('timestamp', 'date', 'time')) && $row['default'][0] != "'") {
  446. $info['default'] = str_replace(' ', '_', $row['default']);
  447. } elseif (in_array($info['type'], array('char', 'varchar', 'text', 'timestamp', 'date', 'time')) ) {
  448. $info['default'] = substr($row['default'], 1, -1);
  449. } elseif ($info['type'] == 'boolean') {
  450. $info['default'] = (boolean) substr($row['default'], 1, -1);
  451. } else {
  452. $info['default'] = $row['default'];
  453. }
  454. }
  455. // Handle not null
  456. $info['not_null'] = ($row['nullable'] == 'N') ? TRUE : FALSE;
  457. $info['comment'] = $row['comment'];
  458. $column_info[$row['column']] = $info;
  459. }
  460. return $column_info;
  461. }
  462. /**
  463. * Fetches the key info for a DB2 database
  464. *
  465. * @return array The keys arrays for every table in the database - see ::getKeys() for details
  466. */
  467. private function fetchDB2Keys()
  468. {
  469. $keys = array();
  470. $default_schema = strtolower($this->database->getUsername());
  471. $tables = $this->getTables();
  472. foreach ($tables as $table) {
  473. $keys[$table] = array();
  474. $keys[$table]['primary'] = array();
  475. $keys[$table]['unique'] = array();
  476. $keys[$table]['foreign'] = array();
  477. }
  478. $params = array();
  479. $sql = "(SELECT
  480. LOWER(RTRIM(R.TABSCHEMA)) AS \"SCHEMA\",
  481. LOWER(R.TABNAME) AS \"TABLE\",
  482. R.CONSTNAME AS CONSTRAINT_NAME,
  483. 'foreign' AS \"TYPE\",
  484. LOWER(K.COLNAME) AS \"COLUMN\",
  485. LOWER(RTRIM(R.REFTABSCHEMA)) AS FOREIGN_SCHEMA,
  486. LOWER(R.REFTABNAME) AS FOREIGN_TABLE,
  487. LOWER(FK.COLNAME) AS FOREIGN_COLUMN,
  488. CASE R.DELETERULE WHEN 'C' THEN 'cascade' WHEN 'A' THEN 'no_action' WHEN 'R' THEN 'restrict' ELSE 'set_null' END AS ON_DELETE,
  489. CASE R.UPDATERULE WHEN 'A' THEN 'no_action' WHEN 'R' THEN 'restrict' END AS ON_UPDATE,
  490. K.COLSEQ
  491. FROM
  492. SYSCAT.REFERENCES AS R INNER JOIN
  493. SYSCAT.KEYCOLUSE AS K ON
  494. R.CONSTNAME = K.CONSTNAME AND
  495. R.TABSCHEMA = K.TABSCHEMA AND
  496. R.TABNAME = K.TABNAME INNER JOIN
  497. SYSCAT.KEYCOLUSE AS FK ON
  498. R.REFKEYNAME = FK.CONSTNAME AND
  499. R.REFTABSCHEMA = FK.TABSCHEMA AND
  500. R.REFTABNAME = FK.TABNAME
  501. WHERE ";
  502. $conditions = array();
  503. foreach ($tables as $table) {
  504. if (strpos($table, '.') === FALSE) {
  505. $table = $default_schema . '.' . $table;
  506. }
  507. list ($schema, $table) = explode('.', strtolower($table));
  508. $conditions[] = "LOWER(R.TABSCHEMA) = %s AND LOWER(R.TABNAME) = %s";
  509. $params[] = $schema;
  510. $params[] = $table;
  511. }
  512. $sql .= '((' . join(') OR( ', $conditions) . '))';
  513. $sql .= "
  514. ) UNION (
  515. SELECT
  516. LOWER(RTRIM(I.TABSCHEMA)) AS \"SCHEMA\",
  517. LOWER(I.TABNAME) AS \"TABLE\",
  518. LOWER(I.INDNAME) AS CONSTRAINT_NAME,
  519. CASE I.UNIQUERULE WHEN 'U' THEN 'unique' ELSE 'primary' END AS \"TYPE\",
  520. LOWER(C.COLNAME) AS \"COLUMN\",
  521. NULL AS FOREIGN_SCHEMA,
  522. NULL AS FOREIGN_TABLE,
  523. NULL AS FOREIGN_COLUMN,
  524. NULL AS ON_DELETE,
  525. NULL AS ON_UPDATE,
  526. C.COLSEQ
  527. FROM
  528. SYSCAT.INDEXES AS I INNER JOIN
  529. SYSCAT.INDEXCOLUSE AS C ON I.INDSCHEMA = C.INDSCHEMA AND I.INDNAME = C.INDNAME
  530. WHERE
  531. I.UNIQUERULE IN ('U', 'P') AND
  532. ";
  533. $conditions = array();
  534. foreach ($tables as $table) {
  535. if (strpos($table, '.') === FALSE) {
  536. $table = $default_schema . '.' . $table;
  537. }
  538. list ($schema, $table) = explode('.', strtolower($table));
  539. $conditions[] = "LOWER(I.TABSCHEMA) = %s AND LOWER(I.TABNAME) = %s";
  540. $params[] = $schema;
  541. $params[] = $table;
  542. }
  543. $sql .= '((' . join(') OR( ', $conditions) . '))';
  544. $sql .= "
  545. )
  546. ORDER BY 4, 1, 2, 3, 11";
  547. $result = $this->database->query($sql, $params);
  548. $last_name = '';
  549. $last_table = '';
  550. $last_type = '';
  551. foreach ($result as $row) {
  552. if ($row['constraint_name'] != $last_name) {
  553. if ($last_name) {
  554. if ($last_type == 'foreign' || $last_type == 'unique') {
  555. $keys[$last_table][$last_type][] = $temp;
  556. } else {
  557. $keys[$last_table][$last_type] = $temp;
  558. }
  559. }
  560. $temp = array();
  561. if ($row['type'] == 'foreign') {
  562. $temp['column'] = $row['column'];
  563. $temp['foreign_table'] = $row['foreign_table'];
  564. if ($row['foreign_schema'] != $default_schema) {
  565. $temp['foreign_table'] = $row['foreign_schema'] . '.' . $temp['foreign_table'];
  566. }
  567. $temp['foreign_column'] = $row['foreign_column'];
  568. $temp['on_delete'] = 'no_action';
  569. $temp['on_update'] = 'no_action';
  570. if (!empty($row['on_delete'])) {
  571. $temp['on_delete'] = $row['on_delete'];
  572. }
  573. if (!empty($row['on_update'])) {
  574. $temp['on_update'] = $row['on_update'];
  575. }
  576. } else {
  577. $temp[] = $row['column'];
  578. }
  579. $last_table = $row['table'];
  580. if ($row['schema'] != $default_schema) {
  581. $last_table = $row['schema'] . '.' . $last_table;
  582. }
  583. $last_name = $row['constraint_name'];
  584. $last_type = $row['type'];
  585. } else {
  586. $temp[] = $row['column'];
  587. }
  588. }
  589. if (isset($temp)) {
  590. if ($last_type == 'foreign' || $last_type == 'unique') {
  591. $keys[$last_table][$last_type][] = $temp;
  592. } else {
  593. $keys[$last_table][$last_type] = $temp;
  594. }
  595. }
  596. return $keys;
  597. }
  598. /**
  599. * Gets the `PRIMARY KEY`, `FOREIGN KEY` and `UNIQUE` key constraints from the database
  600. *
  601. * @return void
  602. */
  603. private function fetchKeys()
  604. {
  605. if ($this->keys) {
  606. return;
  607. }
  608. switch ($this->database->getType()) {
  609. case 'db2':
  610. $keys = $this->fetchDB2Keys();
  611. break;
  612. case 'mssql':
  613. $keys = $this->fetchMSSQLKeys();
  614. break;
  615. case 'mysql':
  616. $keys = $this->fetchMySQLKeys();
  617. break;
  618. case 'oracle':
  619. $keys = $this->fetchOracleKeys();
  620. break;
  621. case 'postgresql':
  622. $keys = $this->fetchPostgreSQLKeys();
  623. break;
  624. case 'sqlite':
  625. $keys = $this->fetchSQLiteKeys();
  626. break;
  627. }
  628. $this->keys = $keys;
  629. if ($this->cache) {
  630. $this->cache->set($this->makeCachePrefix() . 'keys', $this->keys);
  631. }
  632. }
  633. /**
  634. * Gets the column info from a MSSQL database
  635. *
  636. * @param string $table The table to fetch the column info for
  637. * @return array The column info for the table specified - see ::getColumnInfo() for details
  638. */
  639. private function fetchMSSQLColumnInfo($table)
  640. {
  641. $column_info = array();
  642. $schema = 'dbo';
  643. if (strpos($table, '.') !== FALSE) {
  644. list ($schema, $table) = explode('.', $table);
  645. }
  646. $data_type_mapping = array(
  647. 'bit' => 'boolean',
  648. 'tinyint' => 'integer',
  649. 'smallint' => 'integer',
  650. 'int' => 'integer',
  651. 'bigint' => 'integer',
  652. 'timestamp' => 'integer',
  653. 'datetime' => 'timestamp',
  654. 'smalldatetime' => 'timestamp',
  655. 'datetime2' => 'timestamp',
  656. 'date' => 'date',
  657. 'time' => 'time',
  658. 'varchar' => 'varchar',
  659. 'nvarchar' => 'varchar',
  660. 'uniqueidentifier' => 'varchar',
  661. 'char' => 'char',
  662. 'nchar' => 'char',
  663. 'real' => 'float',
  664. 'float' => 'float',
  665. 'money' => 'float',
  666. 'smallmoney' => 'float',
  667. 'decimal' => 'float',
  668. 'numeric' => 'float',
  669. 'binary' => 'blob',
  670. 'varbinary' => 'blob',
  671. 'image' => 'blob',
  672. 'text' => 'text',
  673. 'ntext' => 'text',
  674. 'xml' => 'text'
  675. );
  676. $max_min_values = array(
  677. 'tinyint' => array('min' => new fNumber(0), 'max' => new fNumber(255)),
  678. 'smallint' => array('min' => new fNumber(-32768), 'max' => new fNumber(32767)),
  679. 'int' => array('min' => new fNumber(-2147483648), 'max' => new fNumber(2147483647)),
  680. 'bigint' => array('min' => new fNumber('-9223372036854775808'), 'max' => new fNumber('9223372036854775807')),
  681. 'smallmoney' => array('min' => new fNumber('-214748.3648'), 'max' => new fNumber('214748.3647')),
  682. 'money' => array('min' => new fNumber('-922337203685477.5808'), 'max' => new fNumber('922337203685477.5807'))
  683. );
  684. // Get the column info
  685. $sql = "SELECT
  686. LOWER(c.column_name) AS 'column',
  687. c.data_type AS 'type',
  688. c.is_nullable AS nullable,
  689. c.column_default AS 'default',
  690. c.character_maximum_length AS max_length,
  691. c.numeric_precision AS precision,
  692. c.numeric_scale AS decimal_places,
  693. CASE
  694. WHEN
  695. COLUMNPROPERTY(OBJECT_ID(QUOTENAME(c.table_schema) + '.' + QUOTENAME(c.table_name)), c.column_name, 'IsIdentity') = 1 AND
  696. OBJECTPROPERTY(OBJECT_ID(QUOTENAME(c.table_schema) + '.' + QUOTENAME(c.table_name)), 'IsMSShipped') = 0
  697. THEN '1'
  698. ELSE '0'
  699. END AS auto_increment,
  700. cc.check_clause AS 'constraint',
  701. CAST(ex.value AS VARCHAR(7500)) AS 'comment'
  702. FROM
  703. INFORMATION_SCHEMA.COLUMNS AS c LEFT JOIN
  704. INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS ccu ON
  705. c.column_name = ccu.column_name AND
  706. c.table_name = ccu.table_name AND
  707. c.table_catalog = ccu.table_catalog LEFT JOIN
  708. INFORMATION_SCHEMA.CHECK_CONSTRAINTS AS cc ON
  709. ccu.constraint_name = cc.constraint_name AND
  710. ccu.constraint_catalog = cc.constraint_catalog";
  711. if (version_compare($this->database->getVersion(), 9, '<')) {
  712. $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 ";
  713. } else {
  714. $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 ";
  715. }
  716. $sql .= "
  717. WHERE
  718. LOWER(c.table_name) = %s AND
  719. LOWER(c.table_schema) = %s AND
  720. c.table_catalog = DB_NAME()";
  721. $result = $this->database->query($sql, strtolower($table), strtolower($schema));
  722. foreach ($result as $row) {
  723. $info = array();
  724. foreach ($data_type_mapping as $data_type => $mapped_data_type) {
  725. if (stripos($row['type'], $data_type) === 0) {
  726. if (isset($max_min_values[$data_type])) {
  727. $info['min_value'] = $max_min_values[$data_type]['min'];
  728. $info['max_value'] = $max_min_values[$data_type]['max'];
  729. }
  730. $info['type'] = $mapped_data_type;
  731. break;
  732. }
  733. }
  734. // Handle decimal places and min/max for numeric/decimals
  735. if (in_array(strtolower($row['type']), array('decimal', 'numeric'))) {
  736. $info['decimal_places'] = $row['decimal_places'];
  737. $before_digits = str_pad('', $row['precision'] - $row['decimal_places'], '9');
  738. $after_digits = str_pad('', $row['decimal_places'], '9');
  739. $max_min = $before_digits . ($after_digits ? '.' : '') . $after_digits;
  740. $info['min_value'] = new fNumber('-' . $max_min);
  741. $info['max_value'] = new fNumber($max_min);
  742. }
  743. if (!isset($info['type'])) {
  744. $info['type'] = $row['type'];
  745. }
  746. // Handle decimal places for money/smallmoney
  747. if (in_array($row['type'], array('money', 'smallmoney'))) {
  748. $info['decimal_places'] = 2;
  749. }
  750. // Handle the special data for varchar columns
  751. if (in_array($info['type'], array('char', 'varchar', 'text', 'blob'))) {
  752. if ($row['type'] == 'uniqueidentifier') {
  753. $row['max_length'] = 32;
  754. } elseif ($row['max_length'] == -1) {
  755. $row['max_length'] = $row['type'] == 'nvarchar' ? 1073741823 : 2147483647;
  756. }
  757. $info['max_length'] = $row['max_length'];
  758. }
  759. // If the column has a constraint, look for valid values
  760. if (in_array($info['type'], array('char', 'varchar')) && !empty($row['constraint'])) {
  761. if (preg_match('#^\(((?:(?: OR )?\[[^\]]+\]\s*=\s*\'(?:\'\'|[^\']+)*\')+)\)$#D', $row['constraint'], $matches)) {
  762. $valid_values = explode(' OR ', $matches[1]);
  763. foreach ($valid_values as $key => $value) {
  764. $value = preg_replace('#^\s*\[' . preg_quote($row['column'], '#') . '\]\s*=\s*\'(.*)\'\s*$#', '\1', $value);
  765. $valid_values[$key] = str_replace("''", "'", $value);
  766. }
  767. // SQL Server turns CHECK constraint values into a reversed list, so we fix it here
  768. $info['valid_values'] = array_reverse($valid_values);
  769. }
  770. }
  771. // Handle auto increment
  772. if ($row['auto_increment']) {
  773. $info['auto_increment'] = TRUE;
  774. }
  775. // Handle default values
  776. if ($row['default'] !== NULL) {
  777. if ($row['default'] == '(getdate())') {
  778. $info['default'] = 'CURRENT_TIMESTAMP';
  779. } elseif (in_array($info['type'], array('char', 'varchar', 'text', 'timestamp')) ) {
  780. $info['default'] = substr($row['default'], 2, -2);
  781. } elseif ($info['type'] == 'boolean') {
  782. $info['default'] = (boolean) substr($row['default'], 2, -2);
  783. } elseif (in_array($info['type'], array('integer', 'float')) ) {
  784. $info['default'] = str_replace(array('(', ')'), '', $row['default']);
  785. } else {
  786. $info['default'] = pack('H*', substr($row['default'], 3, -1));
  787. }
  788. }
  789. // Handle not null
  790. $info['not_null'] = ($row['nullable'] == 'NO') ? TRUE : FALSE;
  791. $info['comment'] = $row['comment'];
  792. $column_info[$row['column']] = $info;
  793. }
  794. return $column_info;
  795. }
  796. /**
  797. * Fetches the key info for an MSSQL database
  798. *
  799. * @return array The key info arrays for every table in the database - see ::getKeys() for details
  800. */
  801. private function fetchMSSQLKeys()
  802. {
  803. $keys = array();
  804. $tables = $this->getTables();
  805. foreach ($tables as $table) {
  806. $keys[$table] = array();
  807. $keys[$table]['primary'] = array();
  808. $keys[$table]['unique'] = array();
  809. $keys[$table]['foreign'] = array();
  810. }
  811. $sql = "SELECT
  812. LOWER(c.table_schema) AS \"schema\",
  813. LOWER(c.table_name) AS \"table\",
  814. kcu.constraint_name AS constraint_name,
  815. CASE c.constraint_type
  816. WHEN 'PRIMARY KEY' THEN 'primary'
  817. WHEN 'FOREIGN KEY' THEN 'foreign'
  818. WHEN 'UNIQUE' THEN 'unique'
  819. END AS 'type',
  820. LOWER(kcu.column_name) AS 'column',
  821. LOWER(ccu.table_schema) AS foreign_schema,
  822. LOWER(ccu.table_name) AS foreign_table,
  823. LOWER(ccu.column_name) AS foreign_column,
  824. REPLACE(LOWER(rc.delete_rule), ' ', '_') AS on_delete,
  825. REPLACE(LOWER(rc.update_rule), ' ', '_') AS on_update
  826. FROM
  827. INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS c INNER JOIN
  828. INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS kcu ON
  829. c.table_name = kcu.table_name AND
  830. c.constraint_name = kcu.constraint_name LEFT JOIN
  831. INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS rc ON
  832. c.constraint_name = rc.constraint_name LEFT JOIN
  833. INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS ccu ON
  834. ccu.constraint_name = rc.unique_constraint_name
  835. WHERE
  836. c.constraint_catalog = DB_NAME() AND
  837. c.table_name != 'sysdiagrams'
  838. ORDER BY
  839. LOWER(c.table_schema),
  840. LOWER(c.table_name),
  841. c.constraint_type,
  842. LOWER(kcu.constraint_name),
  843. kcu.ordinal_position,
  844. LOWER(kcu.column_name)";
  845. $result = $this->database->query($sql);
  846. $last_name = '';
  847. $last_table = '';
  848. $last_type = '';
  849. foreach ($result as $row) {
  850. if ($row['constraint_name'] != $last_name) {
  851. if ($last_name) {
  852. if ($last_type == 'foreign' || $last_type == 'unique') {
  853. if (!isset($keys[$last_table][$last_type])) {
  854. $keys[$last_table][$last_type] = array();
  855. }
  856. $keys[$last_table][$last_type][] = $temp;
  857. } else {
  858. $keys[$last_table][$last_type] = $temp;
  859. }
  860. }
  861. $temp = array();
  862. if ($row['type'] == 'foreign') {
  863. $temp['column'] = $row['column'];
  864. $temp['foreign_table'] = $row['foreign_table'];
  865. if ($row['foreign_schema'] != 'dbo') {
  866. $temp['foreign_table'] = $row['foreign_schema'] . '.' . $temp['foreign_table'];
  867. }
  868. $temp['foreign_column'] = $row['foreign_column'];
  869. $temp['on_delete'] = 'no_action';
  870. $temp['on_update'] = 'no_action';
  871. if (!empty($row['on_delete'])) {
  872. $temp['on_delete'] = $row['on_delete'];
  873. }
  874. if (!empty($row['on_update'])) {
  875. $temp['on_update'] = $row['on_update'];
  876. }
  877. } else {
  878. $temp[] = $row['column'];
  879. }
  880. $last_table = $row['table'];
  881. if ($row['schema'] != 'dbo') {
  882. $last_table = $row['schema'] . '.' . $last_table;
  883. }
  884. $last_name = $row['constraint_name'];
  885. $last_type = $row['type'];
  886. } else {
  887. $temp[] = $row['column'];
  888. }
  889. }
  890. if (isset($temp)) {
  891. if ($last_type == 'foreign' || $last_type == 'unique') {
  892. if (!isset($keys[$last_table][$last_type])) {
  893. $keys[$last_table][$last_type] = array();
  894. }
  895. $keys[$last_table][$last_type][] = $temp;
  896. } else {
  897. $keys[$last_table][$last_type] = $temp;
  898. }
  899. }
  900. return $keys;
  901. }
  902. /**
  903. * Gets the column info from a MySQL database
  904. *
  905. * @param string $table The table to fetch the column info for
  906. * @return array The column info for the table specified - see ::getColumnInfo() for details
  907. */
  908. private function fetchMySQLColumnInfo($table)
  909. {
  910. $data_type_mapping = array(
  911. 'tinyint' => 'integer',
  912. 'smallint' => 'integer',
  913. 'mediumint' => 'integer',
  914. 'int' => 'integer',
  915. 'bigint' => 'integer',
  916. 'datetime' => 'timestamp',
  917. 'timestamp' => 'timestamp',
  918. 'date' => 'date',
  919. 'time' => 'time',
  920. 'enum' => 'varchar',
  921. 'set' => 'varchar',
  922. 'varchar' => 'varchar',
  923. 'char' => 'char',
  924. 'float' => 'float',
  925. 'double' => 'float',
  926. 'decimal' => 'float',
  927. 'binary' => 'blob',
  928. 'varbinary' => 'blob',
  929. 'tinyblob' => 'blob',
  930. 'blob' => 'blob',
  931. 'mediumblob' => 'blob',
  932. 'longblob' => 'blob',
  933. 'tinytext' => 'text',
  934. 'text' => 'text',
  935. 'mediumtext' => 'text',
  936. 'longtext' => 'text',
  937. 'geometry' => 'blob',
  938. 'point' => 'blob',
  939. 'linestring' => 'blob',
  940. 'polygon' => 'blob'
  941. );
  942. $max_min_values = array(
  943. 'tinyint' => array('min' => new fNumber(-128), 'max' => new fNumber(127)),
  944. 'unsigned tinyint' => array('min' => new fNumber(0), 'max' => new fNumber(255)),
  945. 'smallint' => array('min' => new fNumber(-32768), 'max' => new fNumber(32767)),
  946. 'unsigned smallint' => array('min' => new fNumber(0), 'max' => new fNumber(65535)),
  947. 'mediumint' => array('min' => new fNumber(-8388608), 'max' => new fNumber(8388607)),
  948. 'unsigned mediumint' => array('min' => new fNumber(0), 'max' => new fNumber(16777215)),
  949. 'int' => array('min' => new fNumber(-2147483648), 'max' => new fNumber(2147483647)),
  950. 'unsigned int' => array('min' => new fNumber(0), 'max' => new fNumber('4294967295')),
  951. 'bigint' => array('min' => new fNumber('-9223372036854775808'), 'max' => new fNumber('9223372036854775807')),
  952. 'unsigned bigint' => array('min' => new fNumber(0), 'max' => new fNumber('18446744073709551615'))
  953. );
  954. $column_info = array();
  955. $result = $this->database->query('SHOW CREATE TABLE %r', $table);
  956. try {
  957. $row = $result->fetchRow();
  958. $create_sql = $row['Create Table'];
  959. } catch (fNoRowsException $e) {
  960. return array();
  961. }
  962. 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);
  963. foreach ($matches as $match) {
  964. $info = array();
  965. foreach ($data_type_mapping as $data_type => $mapped_data_type) {
  966. if (stripos($match[2], $data_type) === 0) {
  967. if ($match[2] == 'tinyint' && $match[3] == 1) {
  968. $mapped_data_type = 'boolean';
  969. } elseif (preg_match('#((?:unsigned )?(?:tiny|small|medium|big)?int)#', (isset($match[4]) ? $match[4] . ' ' : '') . $data_type, $int_match)) {
  970. if (isset($max_min_values[$int_match[1]])) {
  971. $info['min_value'] = $max_min_values[$int_match[1]]['min'];
  972. $info['max_value'] = $max_min_values[$int_match[1]]['max'];
  973. }
  974. }
  975. $info['type'] = $mapped_data_type;
  976. break;
  977. }
  978. }
  979. if (!isset($info['type'])) {
  980. $info['type'] = preg_replace('#^([a-z ]+).*$#iD', '\1', $match[2]);
  981. }
  982. switch ($match[2]) {
  983. case 'tinyblob':
  984. case 'tinytext':
  985. $info['max_length'] = 255;
  986. break;
  987. case 'blob':
  988. case 'text':
  989. $info['max_length'] = 65535;
  990. break;
  991. case 'mediumblob':
  992. case 'mediumtext':
  993. $info['max_length'] = 16777215;
  994. break;
  995. case 'longblob':
  996. case 'longtext':
  997. $info['max_length'] = 4294967295;
  998. break;
  999. }
  1000. if (stripos($match[2], 'enum') === 0) {
  1001. $info['valid_values'] = preg_replace("/^'|'\$/D", '', explode(",", $match[3]));
  1002. $match[3] = 0;
  1003. foreach ($info['valid_values'] as $valid_value) {
  1004. if (strlen(utf8_decode($valid_value)) > $match[3]) {
  1005. $match[3] = strlen(utf8_decode($valid_value));
  1006. }
  1007. }
  1008. }
  1009. // The set data type is currently only supported as a varchar
  1010. // with a max length of all valid values concatenated by ,s
  1011. if (stripos($match[2], 'set') === 0) {
  1012. $values = preg_replace("/^'|'\$/D", '', explode(",", $match[3]));
  1013. $match[3] = strlen(join(',', $values));
  1014. }
  1015. // Type specific information
  1016. if (in_array($info['type'], array('char', 'varchar'))) {
  1017. $info['max_length'] = $match[3];
  1018. }
  1019. // Grab the number of decimal places
  1020. if (stripos($match[2], 'decimal') === 0) {
  1021. if (preg_match('#^\s*(\d+)\s*,\s*(\d+)\s*$#D', $match[3], $data_type_info)) {
  1022. $info['decimal_places'] = $data_type_info[2];
  1023. $before_digits = str_pad('', $data_type_info[1] - $info['decimal_places'], '9');
  1024. $after_digits = str_pad('', $info['decimal_places'], '9');
  1025. $max_min = $before_digits . ($after_digits ? '.' : '') . $after_digits;
  1026. $info['min_value'] = new fNumber('-' . $max_min);
  1027. $info['max_value'] = new fNumber($max_min);
  1028. }
  1029. }
  1030. // Not null
  1031. $info['not_null'] = (!empty($match[5])) ? TRUE : FALSE;
  1032. // Default values
  1033. if (!empty($match[6]) && $match[6] != 'NULL') {
  1034. $info['default'] = preg_replace("/^'|'\$/D", '', $match[6]);
  1035. }
  1036. if ($info['type'] == 'boolean' && isset($info['default'])) {
  1037. $info['default'] = (boolean) $info['default'];
  1038. }
  1039. // Auto increment fields
  1040. if (!empty($match[7])) {
  1041. $info['auto_increment'] = TRUE;
  1042. }
  1043. // Column comments
  1044. if (!empty($match[8])) {
  1045. $info['comment'] = str_replace("''", "'", substr($match[8], 10, -1));
  1046. }
  1047. $column_info[strtolower($match[1])] = $info;
  1048. }
  1049. return $column_info;
  1050. }
  1051. /**
  1052. * Fetches the keys for a MySQL database
  1053. *
  1054. * @return array The keys arrays for every table in the database - see ::getKeys() for details
  1055. */
  1056. private function fetchMySQLKeys()
  1057. {
  1058. $tables = $this->getTables();
  1059. $keys = array();
  1060. foreach ($tables as $table) {
  1061. $keys[$table] = array();
  1062. $keys[$table]['primary'] = array();
  1063. $keys[$table]['foreign'] = array();
  1064. $keys[$table]['unique'] = array();
  1065. $result = $this->database->query('SHOW CREATE TABLE %r', $table);
  1066. $row = $result->fetchRow();
  1067. // Primary keys
  1068. preg_match_all('/PRIMARY KEY\s+\("(.*?)"\),?\n/U', $row['Create Table'], $matches, PREG_SET_ORDER);
  1069. if (!empty($matches)) {
  1070. $keys[$table]['primary'] = explode('","', strtolower($matches[0][1]));
  1071. }
  1072. // Unique keys
  1073. preg_match_all('/UNIQUE KEY\s+"([^"]+)"\s+\("(.*?)"\),?\n/U', $row['Create Table'], $matches, PREG_SET_ORDER);
  1074. foreach ($matches as $match) {
  1075. $keys[$table]['unique'][] = explode('","', strtolower($match[2]));
  1076. }
  1077. // Foreign keys
  1078. 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);
  1079. foreach ($matches as $match) {
  1080. $temp = array(
  1081. 'column' => strtolower($match[1]),
  1082. 'foreign_table' => strtolower($match[2]),
  1083. 'foreign_column' => strtolower($match[3]),
  1084. 'on_delete' => 'no_action',
  1085. 'on_update' => 'no_action'
  1086. );
  1087. if (!empty($match[4])) {
  1088. $temp['on_delete'] = strtolower(str_replace(' ', '_', $match[4]));
  1089. }
  1090. if (!empty($match[5])) {
  1091. $temp['on_update'] = strtolower(str_replace(' ', '_', $match[5]));
  1092. }
  1093. $keys[$table]['foreign'][] = $temp;
  1094. }
  1095. }
  1096. return $keys;
  1097. }
  1098. /**
  1099. * Gets the column info from an Oracle database
  1100. *
  1101. * @param string $table The table to fetch the column info for
  1102. * @return array The column info for the table specified - see ::getColumnInfo() for details
  1103. */
  1104. private function fetchOracleColumnInfo($table)
  1105. {
  1106. $table = strtolower($table);
  1107. $schema = strtolower($this->database->getUsername());
  1108. if (strpos($table, '.') !== FALSE) {
  1109. list ($schema, $table) = explode('.', $table);
  1110. }
  1111. $column_info = array();
  1112. $data_type_mapping = array(
  1113. 'boolean' => 'boolean',
  1114. 'number' => 'integer',
  1115. 'integer' => 'integer',
  1116. 'timestamp' => 'timestamp',
  1117. 'date' => 'date',
  1118. 'varchar2' => 'varchar',
  1119. 'nvarchar2' => 'varchar',
  1120. 'char' => 'char',
  1121. 'nchar' => 'char',
  1122. 'float' => 'float',
  1123. 'binary_float' => 'float',
  1124. 'binary_double' => 'float',
  1125. 'blob' => 'blob',
  1126. 'bfile' => 'varchar',
  1127. 'clob' => 'text',
  1128. 'nclob' => 'text'
  1129. );
  1130. $sql = "SELECT
  1131. LOWER(ATC.COLUMN_NAME) COLUMN_NAME,
  1132. CASE
  1133. WHEN
  1134. ATC.DATA_TYPE = 'NUMBER' AND
  1135. ATC.DATA_PRECISION IS NULL AND
  1136. ATC.DATA_SCALE = 0
  1137. THEN
  1138. 'integer'
  1139. WHEN
  1140. ATC.DATA_TYPE = 'NUMBER' AND
  1141. ATC.DATA_PRECISION = 1 AND
  1142. ATC.DATA_SCALE = 0
  1143. THEN
  1144. 'boolean'
  1145. WHEN
  1146. ATC.DATA_TYPE = 'NUMBER' AND
  1147. ATC.DATA_PRECISION IS NOT NULL AND
  1148. ATC.DATA_SCALE != 0 AND
  1149. ATC.DATA_SCALE IS NOT NULL
  1150. THEN
  1151. 'float'
  1152. ELSE
  1153. LOWER(ATC.DATA_TYPE)
  1154. END DATA_TYPE,
  1155. CASE
  1156. WHEN
  1157. ATC.CHAR_LENGTH <> 0
  1158. THEN
  1159. ATC.CHAR_LENGTH
  1160. WHEN
  1161. ATC.DATA_TYPE = 'NUMBER' AND
  1162. ATC.DATA_PRECISION != 1 AND
  1163. ATC.DATA_SCALE != 0 AND
  1164. ATC.DATA_PRECISION IS NOT NULL
  1165. THEN
  1166. ATC.DATA_SCALE
  1167. ELSE
  1168. NULL
  1169. END LENGTH,
  1170. ATC.DATA_PRECISION PRECISION,
  1171. ATC.NULLABLE,
  1172. ATC.DATA_DEFAULT,
  1173. AC.SEARCH_CONDITION CHECK_CONSTRAINT,
  1174. ACCM.COMMENTS
  1175. FROM
  1176. ALL_TAB_COLUMNS ATC LEFT JOIN
  1177. ALL_CONS_COLUMNS ACC ON
  1178. ATC.OWNER = ACC.OWNER AND
  1179. ATC.COLUMN_NAME = ACC.COLUMN_NAME AND
  1180. ATC.TABLE_NAME = ACC.TABLE_NAME AND
  1181. ACC.POSITION IS NULL LEFT JOIN
  1182. ALL_CONSTRAINTS AC ON
  1183. AC.OWNER = ACC.OWNER AND
  1184. AC.CONSTRAINT_NAME = ACC.CONSTRAINT_NAME AND
  1185. AC.CONSTRAINT_TYPE = 'C' AND
  1186. AC.STATUS = 'ENABLED' LEFT JOIN
  1187. ALL_COL_COMMENTS ACCM ON
  1188. ATC.OWNER = ACCM.OWNER AND
  1189. ATC.COLUMN_NAME = ACCM.COLUMN_NAME AND
  1190. ATC.TABLE_NAME = ACCM.TABLE_NAME
  1191. WHERE
  1192. LOWER(ATC.TABLE_NAME) = %s AND
  1193. LOWER(ATC.OWNER) = %s
  1194. ORDER BY
  1195. ATC.TABLE_NAME ASC,
  1196. ATC.COLUMN_ID ASC";
  1197. $result = $this->database->query($sql, $table, $schema);
  1198. foreach ($result as $row) {
  1199. $column = $row['column_name'];
  1200. // Since Oracle stores check constraints in LONG columns, it is
  1201. // not possible to check or modify the constraints in SQL which
  1202. // ends up causing multiple rows with duplicate data except for
  1203. // the check constraint
  1204. $duplicate = FALSE;
  1205. if (isset($column_info[$column])) {
  1206. $info = $column_info[$column];
  1207. $duplicate = TRUE;
  1208. } else {
  1209. $info = array();
  1210. }
  1211. if (!$duplicate) {
  1212. // Get the column type
  1213. foreach ($data_type_mapping as $data_type => $mapped_data_type) {
  1214. if (stripos($row['data_type'], $data_type) === 0) {
  1215. $info['type'] = $mapped_data_type;
  1216. break;
  1217. }
  1218. }
  1219. if (!isset($info['type'])) {
  1220. $info['type'] = $row['data_type'];
  1221. }
  1222. if (in_array($info['type'], array('blob', 'text'))) {
  1223. $info['max_length'] = 4294967295;
  1224. }
  1225. if ($row['data_type'] == 'float' && $row['precision']) {
  1226. $row['length'] = (int) $row['length'];
  1227. $before_digits = str_pad('', $row['precision'] - $row['length'], '9');
  1228. $after_digits = str_pad('', $row['length'], '9');
  1229. $max_min = $before_digits . ($after_digits ? '.' : '') . $after_digits;
  1230. $info['min_value'] = new fNumber('-' . $max_min);
  1231. $info['max_value'] = new fNumber($max_min);
  1232. }
  1233. // Handle the length of decimal/numeric fields
  1234. if ($info['type'] == 'float' && $row['length']) {
  1235. $info['decimal_places'] = (int) $row['length'];
  1236. }
  1237. // Handle the special data for varchar fields
  1238. if (in_array($info['type'], array('char', 'varchar'))) {
  1239. $info['max_length'] = (int) $row['length'];
  1240. }
  1241. }
  1242. // Handle check constraints that are just simple lists
  1243. if (in_array($info['type'], array('varchar', 'char')) && $row['check_constraint']) {
  1244. if (preg_match('/^\s*"?' . preg_quote($column, '/') . '"?\s+in\s+\((.*?)\)\s*$/i', $row['check_constraint'], $match)) {
  1245. if (preg_match_all("/(?<!')'((''|[^']+)*)'/", $match[1], $matches, PREG_PATTERN_ORDER)) {
  1246. $info['valid_values'] = str_replace("''", "'", $matches[1]);
  1247. }
  1248. } elseif (preg_match('/^\s*"?' . preg_quote($column, '/') . '"?\s*=\s*\'((\'\'|[^\']+)*)\'(\s+OR\s+"?' . preg_quote($column, '/') . '"?\s*=\s*\'((\'\'|[^\']+)*)\')*\s*$/i', $row['check_constraint'], $match)) {
  1249. if (preg_match_all("/(?<!')'((''|[^']+)*)'/", $row['check_constraint'], $matches, PREG_PATTERN_ORDER)) {
  1250. $info['valid_values'] = str_replace("''", "'", $matches[1]);
  1251. }
  1252. }
  1253. }
  1254. if (!$duplicate) {
  1255. // Handle default values
  1256. if ($row['data_default'] !== NULL && trim($row['data_default']) != 'NULL') {
  1257. if (in_array($info['type'], array('date', 'time', 'timestamp')) && $row['data_default'][0] != "'") {
  1258. $info['default'] = trim(preg_replace('#^SYS#', 'CURRENT_', $row['data_default']));
  1259. } elseif (in_array($info['type'], array('char', 'varchar', 'text', 'date', 'time', 'timestamp'))) {
  1260. $info['default'] = str_replace("''", "'", substr(trim($row['data_default']), 1, -1));
  1261. } elseif ($info['type'] == 'boolean') {
  1262. $info['default'] = (boolean) trim($row['data_default']);
  1263. } elseif (in_array($info['type'], array('integer', 'float'))) {
  1264. $info['default'] = trim($row['data_default']);
  1265. } else {
  1266. $info['default'] = $row['data_default'];
  1267. }
  1268. }
  1269. // Not null values
  1270. $info['not_null'] = ($row['nullable'] == 'N') ? TRUE : FALSE;
  1271. $info['comment'] = $row['comments'];
  1272. }
  1273. $column_info[$column] = $info;
  1274. }
  1275. $sql = "SELECT
  1276. TRIGGER_BODY
  1277. FROM
  1278. ALL_TRIGGERS
  1279. WHERE
  1280. TRIGGERING_EVENT LIKE 'INSERT%' AND
  1281. STATUS = 'ENABLED' AND
  1282. TRIGGER_NAME NOT LIKE 'BIN\$%' AND
  1283. LOWER(TABLE_NAME) = %s AND
  1284. LOWER(OWNER) = %s";
  1285. foreach ($this->database->query($sql, $table, $schema) as $row) {
  1286. if (preg_match('#SELECT\s+(["\w.]+).nextval\s+INTO\s+:new\.(\w+)\s+FROM\s+dual#i', $row['trigger_body'], $matches)) {
  1287. $column = strtolower($matches[2]);
  1288. $column_info[$column]['auto_increment'] = TRUE;
  1289. }
  1290. }
  1291. return $column_info;
  1292. }
  1293. /**
  1294. * Fetches the key info for an Oracle database
  1295. *
  1296. * @return array The keys arrays for every table in the database - see ::getKeys() for details
  1297. */
  1298. private function fetchOracleKeys()
  1299. {
  1300. $keys = array();
  1301. $default_schema = strtolower($this->database->getUsername());
  1302. $tables = $this->getTables();
  1303. foreach ($tables as $table) {
  1304. $keys[$table] = array();
  1305. $keys[$table]['primary'] = array();
  1306. $keys[$table]['unique'] = array();
  1307. $keys[$table]['foreign'] = array();
  1308. }
  1309. $params = array();
  1310. $sql = "SELECT
  1311. LOWER(AC.OWNER) \"SCHEMA\",
  1312. LOWER(AC.TABLE_NAME) \"TABLE\",
  1313. AC.CONSTRAINT_NAME CONSTRAINT_NAME,
  1314. CASE AC.CONSTRAINT_TYPE
  1315. WHEN 'P' THEN 'primary'
  1316. WHEN 'R' THEN 'foreign'
  1317. WHEN 'U' THEN 'unique'
  1318. END TYPE,
  1319. LOWER(ACC.COLUMN_NAME) \"COLUMN\",
  1320. LOWER(FKC.OWNER) FOREIGN_SCHEMA,
  1321. LOWER(FKC.TABLE_NAME) FOREIGN_TABLE,
  1322. LOWER(FKC.COLUMN_NAME) FOREIGN_COLUMN,
  1323. CASE WHEN FKC.TABLE_NAME IS NOT NULL THEN REPLACE(LOWER(AC.DELETE_RULE), ' ', '_') ELSE NULL END ON_DELETE
  1324. FROM
  1325. ALL_CONSTRAINTS AC INNER JOIN
  1326. ALL_CONS_COLUMNS ACC ON AC.CONSTRAINT_NAME = ACC.CONSTRAINT_NAME AND AC.OWNER = ACC.OWNER LEFT JOIN
  1327. ALL_CONSTRAINTS FK ON AC.R_CONSTRAINT_NAME = FK.CONSTRAINT_NAME AND AC.OWNER = FK.OWNER LEFT JOIN
  1328. ALL_CONS_COLUMNS FKC ON FK.CONSTRAINT_NAME = FKC.CONSTRAINT_NAME AND FK.OWNER = FKC.OWNER
  1329. WHERE
  1330. AC.CONSTRAINT_TYPE IN ('U', 'P', 'R') AND ";
  1331. $conditions = array();
  1332. foreach ($tables as $table) {
  1333. if (strpos($table, '.') === FALSE) {
  1334. $table = $default_schema . '.' . $table;
  1335. }
  1336. list ($schema, $table) = explode('.', strtolower($table));
  1337. $conditions[] = "LOWER(AC.OWNER) = %s AND LOWER(AC.TABLE_NAME) = %s";
  1338. $params[] = $schema;
  1339. $params[] = $table;
  1340. }
  1341. $sql .= '((' . join(') OR( ', $conditions) . '))';
  1342. $sql .= " ORDER BY
  1343. AC.OWNER ASC,
  1344. AC.TABLE_NAME ASC,
  1345. AC.CONSTRAINT_TYPE ASC,
  1346. AC.CONSTRAINT_NAME ASC,
  1347. ACC.POSITION ASC";
  1348. $result = $this->database->query($sql, $params);
  1349. $last_name = '';
  1350. $last_table = '';
  1351. $last_type = '';
  1352. foreach ($result as $row) {
  1353. if ($row['constraint_name'] != $last_name) {
  1354. if ($last_name) {
  1355. if ($last_type == 'foreign' || $last_type == 'unique') {
  1356. $keys[$last_table][$last_type][] = $temp;
  1357. } else {
  1358. $keys[$last_table][$last_type] = $temp;
  1359. }
  1360. }
  1361. $temp = array();
  1362. if ($row['type'] == 'foreign') {
  1363. $temp['column'] = $row['column'];
  1364. $temp['foreign_table'] = $row['foreign_table'];
  1365. if ($row['foreign_schema'] != $default_schema) {
  1366. $temp['foreign_table'] = $row['foreign_schema'] . '.' . $temp['foreign_table'];
  1367. }
  1368. $temp['foreign_column'] = $row['foreign_column'];
  1369. $temp['on_delete'] = 'no_action';
  1370. $temp['on_update'] = 'no_action';
  1371. if (!empty($row['on_delete'])) {
  1372. $temp['on_delete'] = $row['on_delete'];
  1373. }
  1374. } else {
  1375. $temp[] = $row['column'];
  1376. }
  1377. $last_table = $row['table'];
  1378. if ($row['schema'] != $default_schema) {
  1379. $last_table = $row['schema'] . '.' . $last_table;
  1380. }
  1381. $last_name = $row['constraint_name'];
  1382. $last_type = $row['type'];
  1383. } else {
  1384. $temp[] = $row['column'];
  1385. }
  1386. }
  1387. if (isset($temp)) {
  1388. if ($last_type == 'foreign' || $last_type == 'unique') {
  1389. $keys[$last_table][$last_type][] = $temp;
  1390. } else {
  1391. $keys[$last_table][$last_type] = $temp;
  1392. }
  1393. }
  1394. return $keys;
  1395. }
  1396. /**
  1397. * Gets the column info from a PostgreSQL database
  1398. *
  1399. * @param string $table The table to fetch the column info for
  1400. * @return array The column info for the table specified - see ::getColumnInfo() for details
  1401. */
  1402. private function fetchPostgreSQLColumnInfo($table)
  1403. {
  1404. $column_info = array();
  1405. $schema = 'public';
  1406. if (strpos($table, '.') !== FALSE) {
  1407. list ($schema, $table) = explode('.', $table);
  1408. }
  1409. $data_type_mapping = array(
  1410. 'boolean' => 'boolean',
  1411. 'smallint' => 'integer',
  1412. 'int' => 'integer',
  1413. 'bigint' => 'integer',
  1414. 'serial' => 'integer',
  1415. 'bigserial' => 'integer',
  1416. 'timestamp' => 'timestamp',
  1417. 'date' => 'date',
  1418. 'time' => 'time',
  1419. 'uuid' => 'varchar',
  1420. 'character varying' => 'varchar',
  1421. 'character' => 'char',
  1422. 'real' => 'float',
  1423. 'double' => 'float',
  1424. 'numeric' => 'float',
  1425. 'bytea' => 'blob',
  1426. 'text' => 'text',
  1427. 'mediumtext' => 'text',
  1428. 'longtext' => 'text',
  1429. 'point' => 'varchar',
  1430. 'line' => 'varchar',
  1431. 'lseg' => 'varchar',
  1432. 'box' => 'varchar',
  1433. 'path' => 'varchar',
  1434. 'polygon' => 'varchar',
  1435. 'circle' => 'varchar'
  1436. );
  1437. $max_min_values = array(
  1438. 'smallint' => array('min' => new fNumber(-32768), 'max' => new fNumber(32767)),
  1439. 'int' => array('min' => new fNumber(-2147483648), 'max' => new fNumber(2147483647)),
  1440. 'bigint' => array('min' => new fNumber('-9223372036854775808'), 'max' => new fNumber('9223372036854775807')),
  1441. 'serial' => array('min' => new fNumber(-2147483648), 'max' => new fNumber(2147483647)),
  1442. 'bigserial' => array('min' => new fNumber('-9223372036854775808'), 'max' => new fNumber('9223372036854775807'))
  1443. );
  1444. // PgSQL required this complicated SQL to get the column info
  1445. $sql = "SELECT
  1446. LOWER(pg_attribute.attname) AS column,
  1447. format_type(pg_attribute.atttypid, pg_attribute.atttypmod) AS data_type,
  1448. pg_attribute.attnotnull AS not_null,
  1449. pg_attrdef.adsrc AS default,
  1450. pg_get_constraintdef(pg_constraint.oid) AS constraint,
  1451. col_description(pg_class.oid, pg_attribute.attnum) AS comment
  1452. FROM
  1453. pg_attribute LEFT JOIN
  1454. pg_class ON pg_attribute.attrelid = pg_class.oid LEFT JOIN
  1455. pg_namespace ON pg_class.relnamespace = pg_namespace.oid LEFT JOIN
  1456. pg_type ON pg_type.oid = pg_attribute.atttypid LEFT JOIN
  1457. pg_constraint ON pg_constraint.conrelid = pg_class.oid AND
  1458. pg_attribute.attnum = ANY (pg_constraint.conkey) AND
  1459. pg_constraint.contype = 'c' LEFT JOIN
  1460. pg_attrdef ON pg_class.oid = pg_attrdef.adrelid AND
  1461. pg_attribute.attnum = pg_attrdef.adnum
  1462. WHERE
  1463. NOT pg_attribute.attisdropped AND
  1464. LOWER(pg_class.relname) = %s AND
  1465. LOWER(pg_namespace.nspname) = %s AND
  1466. pg_type.typname NOT IN ('oid', 'cid', 'xid', 'cid', 'xid', 'tid')
  1467. ORDER BY
  1468. pg_attribute.attnum,
  1469. pg_constraint.contype";
  1470. $result = $this->database->query($sql, strtolower($table), strtolower($schema));
  1471. foreach ($result as $row) {
  1472. $info = array();
  1473. // Get the column type
  1474. preg_match('#([\w ]+)\s*(?:\(\s*(\d+)(?:\s*,\s*(\d+))?\s*\))?#', $row['data_type'], $column_data_type);
  1475. foreach ($data_type_mapping as $data_type => $mapped_data_type) {
  1476. if (stripos($column_data_type[1], $data_type) === 0) {
  1477. $info['type'] = $mapped_data_type;
  1478. if (isset($max_min_values[$data_type])) {
  1479. $info['min_value'] = $max_min_values[$data_type]['min'];
  1480. $info['max_value'] = $max_min_values[$data_type]['max'];
  1481. }
  1482. break;
  1483. }
  1484. }
  1485. if (!isset($info['type'])) {
  1486. $info['type'] = $column_data_type[1];
  1487. }
  1488. if ($info['type'] == 'blob' || $info['type'] == 'text') {
  1489. $info['max_length'] = 1073741824;
  1490. }
  1491. // Handle the length of decimal/numeric fields
  1492. if ($info['type'] == 'float' && isset($column_data_type[3]) && strlen($column_data_type[3]) > 0) {
  1493. $info['decimal_places'] = (int) $column_data_type[3];
  1494. $before_digits = str_pad('', $column_data_type[2] - $info['decimal_places'], '9');
  1495. $after_digits = str_pad('', $info['decimal_places'], '9');
  1496. $max_min = $before_digits . ($after_digits ? '.' : '') . $after_digits;
  1497. $info['min_value'] = new fNumber('-' . $max_min);
  1498. $info['max_value'] = new fNumber($max_min);
  1499. }
  1500. // Handle the special data for varchar fields
  1501. if (in_array($info['type'], array('char', 'varchar'))) {
  1502. if (!empty($column_data_type[2])) {
  1503. $info['max_length'] = $column_data_type[2];
  1504. } else {
  1505. $info['max_length'] = 1073741824;
  1506. }
  1507. }
  1508. // In PostgreSQL, a UUID can be the 32 digits, 32 digits plus 4 hyphens or 32 digits plus 4 hyphens and 2 curly braces
  1509. if ($row['data_type'] == 'uuid') {
  1510. $info['max_length'] = 38;
  1511. }
  1512. // Handle check constraints that are just simple lists
  1513. if (in_array($info['type'], array('varchar', 'char')) && !empty($row['constraint'])) {
  1514. if (preg_match('/CHECK[\( "]+' . $row['column'] . '[a-z\) ":]+\s+=\s+/i', $row['constraint'])) {
  1515. if (preg_match_all("/(?!').'((''|[^']+)*)'/", $row['constraint'], $matches, PREG_PATTERN_ORDER)) {
  1516. $info['valid_values'] = str_replace("''", "'", $matches[1]);
  1517. }
  1518. }
  1519. }
  1520. // Handle default values and serial data types
  1521. if ($info['type'] == 'integer' && stripos($row['default'], 'nextval(') !== FALSE) {
  1522. $info['auto_increment'] = TRUE;
  1523. } elseif ($row['default'] !== NULL) {
  1524. if (preg_match('#^NULL::[\w\s]+$#', $row['default'])) {
  1525. $info['default'] = NULL;
  1526. } elseif ($row['default'] == 'now()') {
  1527. $info['default'] = 'CURRENT_TIMESTAMP';
  1528. } elseif ($row['default'] == "('now'::text)::date") {
  1529. $info['default'] = 'CURRENT_DATE';
  1530. } elseif ($row['default'] == "('now'::text)::time with time zone") {
  1531. $info['default'] = 'CURRENT_TIME';
  1532. } else {
  1533. $info['default'] = str_replace("''", "'", preg_replace("/^'(.*)'::[a-z ]+\$/iD", '\1', $row['default']));
  1534. if ($info['type'] == 'boolean') {
  1535. $info['default'] = ($info['default'] == 'false' || !$info['default']) ? FALSE : TRUE;
  1536. }
  1537. }
  1538. }
  1539. // Not null values
  1540. $info['not_null'] = ($row['not_null'] == 't') ? TRUE : FALSE;
  1541. $info['comment'] = $row['comment'];
  1542. $column_info[$row['column']] = $info;
  1543. }
  1544. return $column_info;
  1545. }
  1546. /**
  1547. * Fetches the key info for a PostgreSQL database
  1548. *
  1549. * @return array The keys arrays for every table in the database - see ::getKeys() for details
  1550. */
  1551. private function fetchPostgreSQLKeys()
  1552. {
  1553. $keys = array();
  1554. $tables = $this->getTables();
  1555. foreach ($tables as $table) {
  1556. $keys[$table] = array();
  1557. $keys[$table]['primary'] = array();
  1558. $keys[$table]['unique'] = array();
  1559. $keys[$table]['foreign'] = array();
  1560. }
  1561. $sql = "(
  1562. SELECT
  1563. LOWER(s.nspname) AS \"schema\",
  1564. LOWER(t.relname) AS \"table\",
  1565. con.conname AS constraint_name,
  1566. CASE con.contype
  1567. WHEN 'f' THEN 'foreign'
  1568. WHEN 'p' THEN 'primary'
  1569. WHEN 'u' THEN 'unique'
  1570. END AS type,
  1571. LOWER(col.attname) AS column,
  1572. LOWER(fs.nspname) AS foreign_schema,
  1573. LOWER(ft.relname) AS foreign_table,
  1574. LOWER(fc.attname) AS foreign_column,
  1575. CASE con.confdeltype
  1576. WHEN 'c' THEN 'cascade'
  1577. WHEN 'a' THEN 'no_action'
  1578. WHEN 'r' THEN 'restrict'
  1579. WHEN 'n' THEN 'set_null'
  1580. WHEN 'd' THEN 'set_default'
  1581. END AS on_delete,
  1582. CASE con.confupdtype
  1583. WHEN 'c' THEN 'cascade'
  1584. WHEN 'a' THEN 'no_action'
  1585. WHEN 'r' THEN 'restrict'
  1586. WHEN 'n' THEN 'set_null'
  1587. WHEN 'd' THEN 'set_default'
  1588. END AS on_update,
  1589. CASE WHEN con.conkey IS NOT NULL THEN position('-'||col.attnum||'-' in '-'||array_to_string(con.conkey, '-')||'-') ELSE 0 END AS column_order
  1590. FROM
  1591. pg_attribute AS col INNER JOIN
  1592. pg_class AS t ON
  1593. col.attrelid = t.oid INNER JOIN
  1594. pg_namespace AS s ON
  1595. t.relnamespace = s.oid INNER JOIN
  1596. pg_constraint AS con ON
  1597. col.attnum = ANY (con.conkey) AND
  1598. con.conrelid = t.oid LEFT JOIN
  1599. pg_class AS ft ON
  1600. con.confrelid = ft.oid LEFT JOIN
  1601. pg_namespace AS fs ON
  1602. ft.relnamespace = fs.oid LEFT JOIN
  1603. pg_attribute AS fc ON
  1604. fc.attnum = ANY (con.confkey) AND
  1605. ft.oid = fc.attrelid
  1606. WHERE
  1607. NOT col.attisdropped AND
  1608. (con.contype = 'p' OR
  1609. con.contype = 'f' OR
  1610. con.contype = 'u')
  1611. ) UNION (
  1612. SELECT
  1613. LOWER(n.nspname) AS \"schema\",
  1614. LOWER(t.relname) AS \"table\",
  1615. ic.relname AS constraint_name,
  1616. 'unique' AS type,
  1617. LOWER(col.attname) AS column,
  1618. NULL AS foreign_schema,
  1619. NULL AS foreign_table,
  1620. NULL AS foreign_column,
  1621. NULL AS on_delete,
  1622. NULL AS on_update,
  1623. CASE WHEN ind.indkey IS NOT NULL THEN position('-'||col.attnum||'-' in '-'||array_to_string(ind.indkey, '-')||'-') ELSE 0 END AS column_order
  1624. FROM
  1625. pg_class AS t INNER JOIN
  1626. pg_index AS ind ON
  1627. ind.indrelid = t.oid INNER JOIN
  1628. pg_namespace AS n ON
  1629. t.relnamespace = n.oid INNER JOIN
  1630. pg_class AS ic ON
  1631. ind.indexrelid = ic.oid LEFT JOIN
  1632. pg_constraint AS con ON
  1633. con.conrelid = t.oid AND
  1634. con.contype = 'u' AND
  1635. con.conname = ic.relname INNER JOIN
  1636. pg_attribute AS col ON
  1637. col.attrelid = t.oid AND
  1638. col.attnum = ANY (ind.indkey)
  1639. WHERE
  1640. n.nspname NOT IN ('pg_catalog', 'pg_toast') AND
  1641. indisunique = TRUE AND
  1642. indisprimary = FALSE AND
  1643. con.oid IS NULL AND
  1644. 0 != ALL ((ind.indkey)::int[])
  1645. ) ORDER BY 1, 2, 4, 3, 11";
  1646. $result = $this->database->query($sql);
  1647. $last_name = '';
  1648. $last_table = '';
  1649. $last_type = '';
  1650. foreach ($result as $row) {
  1651. if ($row['constraint_name'] != $last_name) {
  1652. if ($last_name) {
  1653. if ($last_type == 'foreign' || $last_type == 'unique') {
  1654. $keys[$last_table][$last_type][] = $temp;
  1655. } else {
  1656. $keys[$last_table][$last_type] = $temp;
  1657. }
  1658. }
  1659. $temp = array();
  1660. if ($row['type'] == 'foreign') {
  1661. $temp['column'] = $row['column'];
  1662. $temp['foreign_table'] = $row['foreign_table'];
  1663. if ($row['foreign_schema'] != 'public') {
  1664. $temp['foreign_table'] = $row['foreign_schema'] . '.' . $temp['foreign_table'];
  1665. }
  1666. $temp['foreign_column'] = $row['foreign_column'];
  1667. $temp['on_delete'] = 'no_action';
  1668. $temp['on_update'] = 'no_action';
  1669. if (!empty($row['on_delete'])) {
  1670. $temp['on_delete'] = $row['on_delete'];
  1671. }
  1672. if (!empty($row['on_update'])) {
  1673. $temp['on_update'] = $row['on_update'];
  1674. }
  1675. } else {
  1676. $temp[] = $row['column'];
  1677. }
  1678. $last_table = $row['table'];
  1679. if ($row['schema'] != 'public') {
  1680. $last_table = $row['schema'] . '.' . $last_table;
  1681. }
  1682. $last_name = $row['constraint_name'];
  1683. $last_type = $row['type'];
  1684. } else {
  1685. $temp[] = $row['column'];
  1686. }
  1687. }
  1688. if (isset($temp)) {
  1689. if ($last_type == 'foreign' || $last_type == 'unique') {
  1690. $keys[$last_table][$last_type][] = $temp;
  1691. } else {
  1692. $keys[$last_table][$last_type] = $temp;
  1693. }
  1694. }
  1695. return $keys;
  1696. }
  1697. /**
  1698. * Gets the column info from a SQLite database
  1699. *
  1700. * @param string $table The table to fetch the column info for
  1701. * @return array The column info for the table specified - see ::getColumnInfo() for details
  1702. */
  1703. private function fetchSQLiteColumnInfo($table)
  1704. {
  1705. $column_info = array();
  1706. $data_type_mapping = array(
  1707. 'boolean' => 'boolean',
  1708. 'serial' => 'integer',
  1709. 'smallint' => 'integer',
  1710. 'int' => 'integer',
  1711. 'integer' => 'integer',
  1712. 'bigint' => 'integer',
  1713. 'timestamp' => 'timestamp',
  1714. 'date' => 'date',
  1715. 'time' => 'time',
  1716. 'varchar' => 'varchar',
  1717. 'char' => 'char',
  1718. 'real' => 'float',
  1719. 'numeric' => 'float',
  1720. 'float' => 'float',
  1721. 'double' => 'float',
  1722. 'decimal' => 'float',
  1723. 'blob' => 'blob',
  1724. 'text' => 'text'
  1725. );
  1726. $result = $this->database->query("SELECT sql FROM sqlite_master WHERE type = 'table' AND LOWER(name) = %s", strtolower($table));
  1727. try {
  1728. $row = $result->fetchRow();
  1729. $create_sql = $row['sql'];
  1730. } catch (fNoRowsException $e) {
  1731. return array();
  1732. }
  1733. preg_match_all('#(?<=,|\(|\*/|\n)\s*(?:`|"|\[)?(\w+)(?:`|"|\])?\s+([a-z]+)(?:\(\s*(\d+)(?:\s*,\s*(\d+))?\s*\))?(?:(\s+NOT\s+NULL)|(?:\s+NULL)|(?:\s+DEFAULT\s+([^, \'\n]*|\'(?:\'\'|[^\']+)*\'))|(\s+UNIQUE)|(\s+PRIMARY\s+KEY(?:\s+AUTOINCREMENT)?)|(\s+CHECK\s*\("?\w+"?\s+IN\s+\(\s*(?:(?:[^, \'\n]+|\'(?:\'\'|[^\']+)*\')\s*,\s*)*\s*(?:[^, \'\n]+|\'(?:\'\'|[^\']+)*\')\)\)))*(\s+REFERENCES\s+["`\[]?\w+["`\]]?\s*\(\s*["`\[]?\w+["`\]]?\s*\)\s*(?:\s+(?:ON\s+DELETE|ON\s+UPDATE)\s+(?:CASCADE|NO\s+ACTION|RESTRICT|SET\s+NULL|SET\s+DEFAULT))*(?:\s+(?:DEFERRABLE|NOT\s+DEFERRABLE))?)?([ \t]*(?:/\*(?:(?!\*/).)*\*/))?\s*(?:,([ \t]*--[^\n]*\n)?|(--[^\n]*\n)?\s*(?:/\*(?:(?!\*/).)*\*/)?\s*(?=\)))#msi', $create_sql, $matches, PREG_SET_ORDER);
  1734. foreach ($matches as $match) {
  1735. $info = array();
  1736. foreach ($data_type_mapping as $data_type => $mapped_data_type) {
  1737. if (stripos($match[2], $data_type) === 0) {
  1738. $info['type'] = $mapped_data_type;
  1739. break;
  1740. }
  1741. }
  1742. // Type specific information
  1743. if (in_array($info['type'], array('char', 'varchar'))) {
  1744. if (!empty($match[3])) {
  1745. $info['max_length'] = $match[3];
  1746. } else {
  1747. $info['max_length'] = 1000000000;
  1748. }
  1749. }
  1750. if ($info['type'] == 'text' || $info['type'] == 'blob') {
  1751. $info['max_length'] = 1000000000;
  1752. }
  1753. // Figure out how many decimal places for a decimal
  1754. if (in_array(strtolower($match[2]), array('decimal', 'numeric')) && !empty($match[4])) {
  1755. $info['decimal_places'] = $match[4];
  1756. $before_digits = str_pad('', $match[3] - $match[4], '9');
  1757. $after_digits = str_pad('', $match[4], '9');
  1758. $max_min = $before_digits . ($after_digits ? '.' : '') . $after_digits;
  1759. $info['min_value'] = new fNumber('-' . $max_min);
  1760. $info['max_value'] = new fNumber($max_min);
  1761. }
  1762. // Not null
  1763. $info['not_null'] = (!empty($match[5]) || !empty($match[8])) ? TRUE : FALSE;
  1764. // Default values
  1765. if (isset($match[6]) && $match[6] != '' && $match[6] != 'NULL') {
  1766. $info['default'] = preg_replace("/^'|'\$/D", '', $match[6]);
  1767. }
  1768. if ($info['type'] == 'boolean' && isset($info['default'])) {
  1769. $info['default'] = ($info['default'] == 'f' || $info['default'] == 0 || $info['default'] == 'false') ? FALSE : TRUE;
  1770. }
  1771. // Check constraints
  1772. if (isset($match[9]) && preg_match('/CHECK\s*\(\s*"?' . $match[1] . '"?\s+IN\s+\(\s*((?:(?:[^, \']*|\'(?:\'\'|[^\']+)*\')\s*,\s*)*(?:[^, \']*|\'(?:\'\'|[^\']+)*\'))\s*\)/i', $match[9], $check_match)) {
  1773. $info['valid_values'] = str_replace("''", "'", preg_replace("/^'|'\$/D", '', preg_split("#\s*,\s*#", $check_match[1])));
  1774. }
  1775. // Auto increment fields
  1776. if (!empty($match[8]) && (stripos($match[8], 'autoincrement') !== FALSE || $info['type'] == 'integer')) {
  1777. $info['auto_increment'] = TRUE;
  1778. }
  1779. // Column comments
  1780. if (!empty($match[11]) || !empty($match[12]) || !empty($match[13])) {
  1781. if (!empty($match[11])) {
  1782. $comment = $match[11];
  1783. } elseif (!empty($match[12])) {
  1784. $comment = $match[12];
  1785. } else {
  1786. $comment = $match[13];
  1787. }
  1788. $comment = trim($comment);
  1789. $comment = substr($comment, 0, 2) == '--' ? substr($comment, 2) : substr($comment, 2, -2);
  1790. $info['comment'] = trim($comment);
  1791. }
  1792. $column_info[strtolower($match[1])] = $info;
  1793. }
  1794. return $column_info;
  1795. }
  1796. /**
  1797. * Fetches the key info for an SQLite database
  1798. *
  1799. * @return array The keys arrays for every table in the database - see ::getKeys() for details
  1800. */
  1801. private function fetchSQLiteKeys()
  1802. {
  1803. $tables = $this->getTables();
  1804. $keys = array();
  1805. foreach ($tables as $table) {
  1806. $keys[$table] = array();
  1807. $keys[$table]['primary'] = array();
  1808. $keys[$table]['foreign'] = array();
  1809. $keys[$table]['unique'] = array();
  1810. $result = $this->database->query("SELECT sql FROM sqlite_master WHERE type = 'table' AND LOWER(name) = %s", strtolower($table));
  1811. $row = $result->fetchRow();
  1812. $create_sql = $row['sql'];
  1813. // Collapse strings into empty string to make the matching simpler
  1814. $create_sql = preg_replace('#\'(?:\'\'|[^\']+)*\'#', "''", $create_sql);
  1815. // Remove single-line comments
  1816. $create_sql = preg_replace('#--[^\n]*\n#', "\n", $create_sql);
  1817. // Remove multi-line comments
  1818. $create_sql = preg_replace('#/\*((?!\*/).)*\*/#', '', $create_sql);
  1819. // Get column level key definitions
  1820. preg_match_all('#(?<=,|\()\s*["`\[]?(\w+)["`\]]?\s+(?:[a-z]+)(?:\((?:\d+)\))?(?:(?:\s+NOT\s+NULL)|(?:\s+DEFAULT\s+(?:[^, \']*|\'(?:\'\'|[^\']+)*\'))|(\s+UNIQUE)|(\s+PRIMARY\s+KEY(?:\s+AUTOINCREMENT)?)|(?:\s+CHECK\s*\("?\w+"?\s+IN\s+\(\s*(?:(?:[^, \']+|\'(?:\'\'|[^\']+)*\')\s*,\s*)*\s*(?:[^, \']+|\'(?:\'\'|[^\']+)*\')\)\)))*(\s+REFERENCES\s+["`\[]?(\w+)["`\]]?\s*\(\s*["`\[]?(\w+)["`\]]?\s*\)\s*(?:(?:\s+(?:ON\s+DELETE\s+(CASCADE|NO\s+ACTION|RESTRICT|SET\s+NULL|SET\s+DEFAULT)))|(?:\s+(?:ON\s+UPDATE\s+(CASCADE|NO\s+ACTION|RESTRICT|SET\s+NULL|SET\s+DEFAULT))))*(?:\s+(?:DEFERRABLE|NOT\s+DEFERRABLE))?)?\s*(?:,|\s*(?=\)))#mi', $create_sql, $matches, PREG_SET_ORDER);
  1821. foreach ($matches as $match) {
  1822. if (!empty($match[2])) {
  1823. $keys[$table]['unique'][] = array(strtolower($match[1]));
  1824. }
  1825. if (!empty($match[3])) {
  1826. $keys[$table]['primary'] = array(strtolower($match[1]));
  1827. }
  1828. if (!empty($match[4])) {
  1829. $temp = array(
  1830. 'column' => strtolower($match[1]),
  1831. 'foreign_table' => strtolower($match[5]),
  1832. 'foreign_column' => strtolower($match[6]),
  1833. 'on_delete' => 'no_action',
  1834. 'on_update' => 'no_action'
  1835. );
  1836. if (isset($match[7])) {
  1837. $temp['on_delete'] = strtolower(str_replace(' ', '_', $match[7]));
  1838. }
  1839. if (isset($match[8])) {
  1840. $temp['on_update'] = strtolower(str_replace(' ', '_', $match[8]));
  1841. }
  1842. $keys[$table]['foreign'][] = $temp;
  1843. }
  1844. }
  1845. // Get table level primary key definitions
  1846. preg_match_all('#(?<=,|\()\s*(?:CONSTRAINT\s+["`\[]?\w+["`\]]?\s+)?PRIMARY\s+KEY\s*\(\s*((?:\s*["`\[]?\w+["`\]]?\s*,\s*)*["`\[]?\w+["`\]]?)\s*\)\s*(?:,|\s*(?=\)))#mi', $create_sql, $matches, PREG_SET_ORDER);
  1847. foreach ($matches as $match) {
  1848. $columns = preg_split('#\s*,\s*#', strtolower($match[1]));
  1849. foreach ($columns as $column) {
  1850. $keys[$table]['primary'][] = str_replace(array('[', '"', '`', ']'), '', $column);
  1851. }
  1852. }
  1853. // Get table level foreign key definitions
  1854. preg_match_all('#(?<=,|\()\s*(?:CONSTRAINT\s+["`\[]?\w+["`\]]?\s+)?FOREIGN\s+KEY\s*(?:["`\[]?(\w+)["`\]]?|\(\s*["`\[]?(\w+)["`\]]?\s*\))\s+REFERENCES\s+["`\[]?(\w+)["`\]]?\s*\(\s*["`\[]?(\w+)["`\]]?\s*\)\s*(?:\s+(?:ON\s+DELETE\s+(CASCADE|NO\s+ACTION|RESTRICT|SET\s+NULL|SET\s+DEFAULT))|\s+(?:ON\s+UPDATE\s+(CASCADE|NO\s+ACTION|RESTRICT|SET\s+NULL|SET\s+DEFAULT)))*(?:\s+(?:DEFERRABLE|NOT\s+DEFERRABLE))?\s*(?:,|\s*(?=\)))#mis', $create_sql, $matches, PREG_SET_ORDER);
  1855. foreach ($matches as $match) {
  1856. if (empty($match[1])) { $match[1] = $match[2]; }
  1857. $temp = array(
  1858. 'column' => strtolower($match[1]),
  1859. 'foreign_table' => strtolower($match[3]),
  1860. 'foreign_column' => strtolower($match[4]),
  1861. 'on_delete' => 'no_action',
  1862. 'on_update' => 'no_action'
  1863. );
  1864. if (isset($match[5])) {
  1865. $temp['on_delete'] = strtolower(str_replace(' ', '_', $match[5]));
  1866. }
  1867. if (isset($match[6])) {
  1868. $temp['on_update'] = strtolower(str_replace(' ', '_', $match[6]));
  1869. }
  1870. $keys[$table]['foreign'][] = $temp;
  1871. }
  1872. // Get table level unique key definitions
  1873. preg_match_all('#(?<=,|\()\s*(?:CONSTRAINT\s+["`\[]?\w+["`\]]?\s+)?UNIQUE\s*\(\s*((?:\s*["`\[]?\w+["`\]]?\s*,\s*)*["`\[]?\w+["`\]]?)\s*\)\s*(?:,|\s*(?=\)))#mi', $create_sql, $matches, PREG_SET_ORDER);
  1874. foreach ($matches as $match) {
  1875. $columns = preg_split('#\s*,\s*#', strtolower($match[1]));
  1876. $key = array();
  1877. foreach ($columns as $column) {
  1878. $key[] = str_replace(array('[', '"', '`', ']'), '', $column);
  1879. }
  1880. $keys[$table]['unique'][] = $key;
  1881. }
  1882. // Get all CREATE UNIQUE INDEX statements
  1883. $result = $this->database->query("SELECT sql FROM sqlite_master WHERE type = 'index' AND sql <> '' AND LOWER(tbl_name) = %s", strtolower($table));
  1884. foreach ($result as $row) {
  1885. $create_sql = $row['sql'];
  1886. if (!preg_match('#^\s*CREATE\s+UNIQUE\s+INDEX\s+(?:["`\[]?\w+["`\]]?\.)?["`\[]?\w+["`\]]?\s+ON\s+[\'"`\[]?\w+[\'"`\]]?\s*\(\s*((?:\s*["`\[]?\w+["`\]]?\s*,\s*)*["`\[]?\w+["`\]]?)\s*\)\s*$#Di', $create_sql, $match)) {
  1887. continue;
  1888. }
  1889. $columns = preg_split('#\s*,\s*#', strtolower($match[1]));
  1890. $key = array();
  1891. foreach ($columns as $column) {
  1892. $key[] = str_replace(array('[', '"', '`', ']'), '', $column);
  1893. }
  1894. $keys[$table]['unique'][] = $key;
  1895. }
  1896. }
  1897. return $keys;
  1898. }
  1899. /**
  1900. * Finds many-to-many relationship for the table specified
  1901. *
  1902. * @param string $table The table to find the relationships on
  1903. * @return void
  1904. */
  1905. private function findManyToManyRelationships($table)
  1906. {
  1907. if (!$this->isJoiningTable($table)) {
  1908. return;
  1909. }
  1910. list ($key1, $key2) = $this->merged_keys[$table]['foreign'];
  1911. $temp = array();
  1912. $temp['table'] = $key1['foreign_table'];
  1913. $temp['column'] = $key1['foreign_column'];
  1914. $temp['related_table'] = $key2['foreign_table'];
  1915. $temp['related_column'] = $key2['foreign_column'];
  1916. $temp['join_table'] = $table;
  1917. $temp['join_column'] = $key1['column'];
  1918. $temp['join_related_column'] = $key2['column'];
  1919. $temp['on_update'] = $key1['on_update'];
  1920. $temp['on_delete'] = $key1['on_delete'];
  1921. $this->relationships[$key1['foreign_table']]['many-to-many'][] = $temp;
  1922. $temp = array();
  1923. $temp['table'] = $key2['foreign_table'];
  1924. $temp['column'] = $key2['foreign_column'];
  1925. $temp['related_table'] = $key1['foreign_table'];
  1926. $temp['related_column'] = $key1['foreign_column'];
  1927. $temp['join_table'] = $table;
  1928. $temp['join_column'] = $key2['column'];
  1929. $temp['join_related_column'] = $key1['column'];
  1930. $temp['on_update'] = $key2['on_update'];
  1931. $temp['on_delete'] = $key2['on_delete'];
  1932. $this->relationships[$key2['foreign_table']]['many-to-many'][] = $temp;
  1933. }
  1934. /**
  1935. * Finds one-to-many relationship for the table specified
  1936. *
  1937. * @param string $table The table to find the relationships on
  1938. * @return void
  1939. */
  1940. private function findOneToManyRelationships($table)
  1941. {
  1942. foreach ($this->merged_keys[$table]['foreign'] as $key) {
  1943. $type = ($this->checkForSingleColumnUniqueKey($table, $key['column'])) ? 'one-to-one' : 'one-to-many';
  1944. $temp = array();
  1945. $temp['table'] = $key['foreign_table'];
  1946. $temp['column'] = $key['foreign_column'];
  1947. $temp['related_table'] = $table;
  1948. $temp['related_column'] = $key['column'];
  1949. $temp['on_delete'] = $key['on_delete'];
  1950. $temp['on_update'] = $key['on_update'];
  1951. $this->relationships[$key['foreign_table']][$type][] = $temp;
  1952. }
  1953. }
  1954. /**
  1955. * Finds one-to-one and many-to-one relationship for the table specified
  1956. *
  1957. * @param string $table The table to find the relationships on
  1958. * @return void
  1959. */
  1960. private function findStarToOneRelationships($table)
  1961. {
  1962. foreach ($this->merged_keys[$table]['foreign'] as $key) {
  1963. $temp = array();
  1964. $temp['table'] = $table;
  1965. $temp['column'] = $key['column'];
  1966. $temp['related_table'] = $key['foreign_table'];
  1967. $temp['related_column'] = $key['foreign_column'];
  1968. $type = ($this->checkForSingleColumnUniqueKey($table, $key['column'])) ? 'one-to-one' : 'many-to-one';
  1969. if ($type == 'one-to-one') {
  1970. $temp['on_delete'] = $key['on_delete'];
  1971. $temp['on_update'] = $key['on_update'];
  1972. }
  1973. $this->relationships[$table][$type][] = $temp;
  1974. }
  1975. }
  1976. /**
  1977. * Finds the one-to-one, many-to-one, one-to-many and many-to-many relationships in the database
  1978. *
  1979. * @return void
  1980. */
  1981. private function findRelationships()
  1982. {
  1983. $this->relationships = array();
  1984. $tables = $this->getTables();
  1985. foreach ($tables as $table) {
  1986. $this->relationships[$table]['one-to-one'] = array();
  1987. $this->relationships[$table]['many-to-one'] = array();
  1988. $this->relationships[$table]['one-to-many'] = array();
  1989. $this->relationships[$table]['many-to-many'] = array();
  1990. }
  1991. // Calculate the relationships
  1992. foreach ($this->merged_keys as $table => $keys) {
  1993. $this->findManyToManyRelationships($table);
  1994. if ($this->isJoiningTable($table)) {
  1995. continue;
  1996. }
  1997. $this->findStarToOneRelationships($table);
  1998. $this->findOneToManyRelationships($table);
  1999. }
  2000. if ($this->cache) {
  2001. $this->cache->set($this->makeCachePrefix() . 'relationships', $this->relationships);
  2002. }
  2003. }
  2004. /**
  2005. * Returns column information for the table specified
  2006. *
  2007. * If only a table is specified, column info is in the following format:
  2008. *
  2009. * {{{
  2010. * array(
  2011. * (string) {column name} => array(
  2012. * 'type' => (string) {data type},
  2013. * 'placeholder' => (string) {fDatabase::escape() placeholder for this data type},
  2014. * 'not_null' => (boolean) {if value can't be null},
  2015. * 'default' => (mixed) {the default value},
  2016. * 'valid_values' => (array) {the valid values for a varchar field},
  2017. * 'max_length' => (integer) {the maximum length in a varchar field},
  2018. * 'min_value' => (numeric) {the minimum value for an integer/float field},
  2019. * 'max_value' => (numeric) {the maximum value for an integer/float field},
  2020. * 'decimal_places' => (integer) {the number of decimal places for a decimal/numeric/money/smallmoney field},
  2021. * 'auto_increment' => (boolean) {if the integer primary key column is a serial/autoincrement/auto_increment/indentity column},
  2022. * 'comment' => (string) {the SQL comment/description for the column}
  2023. * ), ...
  2024. * )
  2025. * }}}
  2026. *
  2027. * If a table and column are specified, column info is in the following format:
  2028. *
  2029. * {{{
  2030. * array(
  2031. * 'type' => (string) {data type},
  2032. * 'placeholder' => (string) {fDatabase::escape() placeholder for this data type},
  2033. * 'not_null' => (boolean) {if value can't be null},
  2034. * 'default' => (mixed) {the default value-may contain special strings CURRENT_TIMESTAMP, CURRENT_TIME or CURRENT_DATE},
  2035. * 'valid_values' => (array) {the valid values for a varchar field},
  2036. * 'max_length' => (integer) {the maximum length in a char/varchar field},
  2037. * 'min_value' => (fNumber) {the minimum value for an integer/float field},
  2038. * 'max_value' => (fNumber) {the maximum value for an integer/float field},
  2039. * 'decimal_places' => (integer) {the number of decimal places for a decimal/numeric/money/smallmoney field},
  2040. * 'auto_increment' => (boolean) {if the integer primary key column is a serial/autoincrement/auto_increment/indentity column},
  2041. * 'comment' => (string) {the SQL comment/description for the column}
  2042. * )
  2043. * }}}
  2044. *
  2045. * If a table, column and element are specified, returned value is the single element specified.
  2046. *
  2047. * The `'type'` element is homogenized to a value from the following list:
  2048. *
  2049. * - `'varchar'`
  2050. * - `'char'`
  2051. * - `'text'`
  2052. * - `'integer'`
  2053. * - `'float'`
  2054. * - `'timestamp'`
  2055. * - `'date'`
  2056. * - `'time'`
  2057. * - `'boolean'`
  2058. * - `'blob'`
  2059. *
  2060. * Please note that MySQL reports boolean data types as `tinyint(1)`, so
  2061. * all `tinyint(1)` columns will be listed as `boolean`. This can be fixed
  2062. * by calling:
  2063. *
  2064. * {{{
  2065. * #!php
  2066. * $schema->setColumnInfoOverride(
  2067. * array(
  2068. * 'type' => 'integer',
  2069. * 'placeholder' => '%i',
  2070. * 'default' => {default integer},
  2071. * 'min_value' => new fNumber(-128),
  2072. * 'max_value' => new fNumber(127)
  2073. * ),
  2074. * '{table name}',
  2075. * '{column name}'
  2076. * );
  2077. * }}}
  2078. *
  2079. * The `'comment'` element pulls from the database's column comment facility
  2080. * with the exception of MSSQL and SQLite.
  2081. *
  2082. * For MSSQL, the comment is pulled from the `MS_Description` extended
  2083. * property, which can be added via the `Description` field in SQL Server
  2084. * Management Studio, or via the `sp_addextendedproperty` stored procedure.
  2085. *
  2086. * For SQLite, the comment is extracted from any SQL comment that is placed
  2087. * at the end of the line on which the column is defined:
  2088. *
  2089. * {{{
  2090. * #!sql
  2091. * CREATE TABLE users (
  2092. * user_id INTEGER PRIMARY KEY AUTOINCREMENT,
  2093. * name VARCHAR(200) NOT NULL -- This is the full name
  2094. * );
  2095. * }}}
  2096. *
  2097. * For the SQLite `users` table defined above, the `name` column will have
  2098. * the comment `This is the full name`.
  2099. *
  2100. * @param string $table The table to get the column info for
  2101. * @param string $column The column to get the info for
  2102. * @param string $element The element to return: `'type'`, `'placeholder'`, `'not_null'`, `'default'`, `'valid_values'`, `'max_length'`, `'min_value'`, `'max_value'`, `'decimal_places'`, `'auto_increment'`, `'comment'`
  2103. * @return mixed The column info for the table/column/element specified - see method description for format
  2104. */
  2105. public function getColumnInfo($table, $column=NULL, $element=NULL)
  2106. {
  2107. $table = strtolower($table);
  2108. if ($column !== NULL) {
  2109. $column = strtolower($column);
  2110. }
  2111. // Return the saved column info if possible
  2112. if (!$column && isset($this->merged_column_info[$table])) {
  2113. return $this->merged_column_info[$table];
  2114. }
  2115. if ($column && isset($this->merged_column_info[$table][$column])) {
  2116. if ($element !== NULL) {
  2117. if (!isset($this->merged_column_info[$table][$column][$element]) && !array_key_exists($element, $this->merged_column_info[$table][$column])) {
  2118. throw new fProgrammerException(
  2119. 'The element specified, %1$s, is invalid. Must be one of: %2$s.',
  2120. $element,
  2121. join(', ', array('type', 'placeholder', 'not_null', 'default', 'valid_values', 'max_length', 'min_value', 'max_value', 'decimal_places', 'auto_increment'))
  2122. );
  2123. }
  2124. return $this->merged_column_info[$table][$column][$element];
  2125. }
  2126. return $this->merged_column_info[$table][$column];
  2127. }
  2128. if (!in_array($table, $this->getTables())) {
  2129. throw new fProgrammerException(
  2130. 'The table specified, %s, does not exist in the database',
  2131. $table
  2132. );
  2133. }
  2134. $this->fetchColumnInfo($table);
  2135. $this->mergeColumnInfo();
  2136. if ($column && !isset($this->merged_column_info[$table][$column])) {
  2137. throw new fProgrammerException(
  2138. 'The column specified, %1$s, does not exist in the table %2$s',
  2139. $column,
  2140. $table
  2141. );
  2142. }
  2143. if ($column) {
  2144. if ($element) {
  2145. return $this->merged_column_info[$table][$column][$element];
  2146. }
  2147. return $this->merged_column_info[$table][$column];
  2148. }
  2149. return $this->merged_column_info[$table];
  2150. }
  2151. /**
  2152. * Returns the databases on the current server
  2153. *
  2154. * @return array The databases on the current server
  2155. */
  2156. public function getDatabases()
  2157. {
  2158. if ($this->databases !== NULL) {
  2159. return $this->databases;
  2160. }
  2161. $this->databases = array();
  2162. switch ($this->database->getType()) {
  2163. case 'mssql':
  2164. $sql = 'EXECUTE sp_databases';
  2165. break;
  2166. case 'mysql':
  2167. $sql = 'SHOW DATABASES';
  2168. break;
  2169. case 'oracle':
  2170. $sql = 'SELECT ora_database_name FROM dual';
  2171. case 'postgresql':
  2172. $sql = "SELECT
  2173. datname
  2174. FROM
  2175. pg_database
  2176. ORDER BY
  2177. LOWER(datname)";
  2178. break;
  2179. case 'db2':
  2180. $this->databases[] = strtolower($this->database->getDatabase());
  2181. return $this->databases;
  2182. case 'sqlite':
  2183. $this->databases[] = $this->database->getDatabase();
  2184. return $this->databases;
  2185. }
  2186. $result = $this->database->query($sql);
  2187. foreach ($result as $row) {
  2188. $keys = array_keys($row);
  2189. $this->databases[] = strtolower($row[$keys[0]]);
  2190. }
  2191. if ($this->cache) {
  2192. $this->cache->set($this->makeCachePrefix() . 'databases', $this->databases);
  2193. }
  2194. return $this->databases;
  2195. }
  2196. /**
  2197. * Returns a list of primary key, foreign key and unique key constraints for the table specified
  2198. *
  2199. * The structure of the returned array is:
  2200. *
  2201. * {{{
  2202. * array(
  2203. * 'primary' => array(
  2204. * {column name}, ...
  2205. * ),
  2206. * 'unique' => array(
  2207. * array(
  2208. * {column name}, ...
  2209. * ), ...
  2210. * ),
  2211. * 'foreign' => array(
  2212. * array(
  2213. * 'column' => {column name},
  2214. * 'foreign_table' => {foreign table name},
  2215. * 'foreign_column' => {foreign column name},
  2216. * 'on_delete' => {the ON DELETE action: 'no_action', 'restrict', 'cascade', 'set_null', or 'set_default'},
  2217. * 'on_update' => {the ON UPDATE action: 'no_action', 'restrict', 'cascade', 'set_null', or 'set_default'}
  2218. * ), ...
  2219. * )
  2220. * )
  2221. * }}}
  2222. *
  2223. * @param string $table The table to return the keys for
  2224. * @param string $key_type The type of key to return: `'primary'`, `'foreign'`, `'unique'`
  2225. * @return array An array of all keys, or just the type specified - see method description for format
  2226. */
  2227. public function getKeys($table, $key_type=NULL)
  2228. {
  2229. $table = strtolower($table);
  2230. $valid_key_types = array('primary', 'foreign', 'unique');
  2231. if ($key_type !== NULL && !in_array($key_type, $valid_key_types)) {
  2232. throw new fProgrammerException(
  2233. 'The key type specified, %1$s, is invalid. Must be one of: %2$s.',
  2234. $key_type,
  2235. join(', ', $valid_key_types)
  2236. );
  2237. }
  2238. // Return the saved column info if possible
  2239. if (!$key_type && isset($this->merged_keys[$table])) {
  2240. reset($this->merged_keys[$table]);
  2241. return $this->merged_keys[$table];
  2242. }
  2243. if ($key_type && isset($this->merged_keys[$table][$key_type])) {
  2244. reset($this->merged_keys[$table][$key_type]);
  2245. return $this->merged_keys[$table][$key_type];
  2246. }
  2247. if (!in_array($table, $this->getTables())) {
  2248. throw new fProgrammerException(
  2249. 'The table specified, %s, does not exist in the database',
  2250. $table
  2251. );
  2252. }
  2253. $this->fetchKeys();
  2254. $this->mergeKeys();
  2255. if ($key_type) {
  2256. reset($this->merged_keys[$table][$key_type]);
  2257. return $this->merged_keys[$table][$key_type];
  2258. }
  2259. reset($this->merged_keys[$table]);
  2260. return $this->merged_keys[$table];
  2261. }
  2262. /**
  2263. * Returns a list of one-to-one, many-to-one, one-to-many and many-to-many relationships for the table specified
  2264. *
  2265. * The structure of the returned array is:
  2266. *
  2267. * {{{
  2268. * array(
  2269. * 'one-to-one' => array(
  2270. * array(
  2271. * 'table' => (string) {the name of the table this relationship is for},
  2272. * 'column' => (string) {the column in the specified table},
  2273. * 'related_table' => (string) {the related table},
  2274. * 'related_column' => (string) {the related column},
  2275. * 'on_delete' => (string) {the ON DELETE action: 'no_action', 'restrict', 'cascade', 'set_null', or 'set_default'},
  2276. * 'on_update' => (string) {the ON UPDATE action: 'no_action', 'restrict', 'cascade', 'set_null', or 'set_default'}
  2277. * ), ...
  2278. * ),
  2279. * 'many-to-one' => array(
  2280. * array(
  2281. * 'table' => (string) {the name of the table this relationship is for},
  2282. * 'column' => (string) {the column in the specified table},
  2283. * 'related_table' => (string) {the related table},
  2284. * 'related_column' => (string) {the related column}
  2285. * ), ...
  2286. * ),
  2287. * 'one-to-many' => array(
  2288. * array(
  2289. * 'table' => (string) {the name of the table this relationship is for},
  2290. * 'column' => (string) {the column in the specified table},
  2291. * 'related_table' => (string) {the related table},
  2292. * 'related_column' => (string) {the related column},
  2293. * 'on_delete' => (string) {the ON DELETE action: 'no_action', 'restrict', 'cascade', 'set_null', or 'set_default'},
  2294. * 'on_update' => (string) {the ON UPDATE action: 'no_action', 'restrict', 'cascade', 'set_null', or 'set_default'}
  2295. * ), ...
  2296. * ),
  2297. * 'many-to-many' => array(
  2298. * array(
  2299. * 'table' => (string) {the name of the table this relationship is for},
  2300. * 'column' => (string) {the column in the specified table},
  2301. * 'related_table' => (string) {the related table},
  2302. * 'related_column' => (string) {the related column},
  2303. * 'join_table' => (string) {the table that joins the specified table to the related table},
  2304. * 'join_column' => (string) {the column in the join table that references 'column'},
  2305. * 'join_related_column' => (string) {the column in the join table that references 'related_column'},
  2306. * 'on_delete' => (string) {the ON DELETE action: 'no_action', 'restrict', 'cascade', 'set_null', or 'set_default'},
  2307. * 'on_update' => (string) {the ON UPDATE action: 'no_action', 'restrict', 'cascade', 'set_null', or 'set_default'}
  2308. * ), ...
  2309. * )
  2310. * )
  2311. * }}}
  2312. *
  2313. * @param string $table The table to return the relationships for
  2314. * @param string $relationship_type The type of relationship to return: `'one-to-one'`, `'many-to-one'`, `'one-to-many'`, `'many-to-many'`
  2315. * @return array An array of all relationships, or just the type specified - see method description for format
  2316. */
  2317. public function getRelationships($table, $relationship_type=NULL)
  2318. {
  2319. $table = strtolower($table);
  2320. $valid_relationship_types = array('one-to-one', 'many-to-one', 'one-to-many', 'many-to-many');
  2321. if ($relationship_type !== NULL && !in_array($relationship_type, $valid_relationship_types)) {
  2322. throw new fProgrammerException(
  2323. 'The relationship type specified, %1$s, is invalid. Must be one of: %2$s.',
  2324. $relationship_type,
  2325. join(', ', $valid_relationship_types)
  2326. );
  2327. }
  2328. // Return the saved column info if possible
  2329. if (!$relationship_type && isset($this->relationships[$table])) {
  2330. return $this->relationships[$table];
  2331. }
  2332. if ($relationship_type && isset($this->relationships[$table][$relationship_type])) {
  2333. return $this->relationships[$table][$relationship_type];
  2334. }
  2335. if (!in_array($table, $this->getTables())) {
  2336. throw new fProgrammerException(
  2337. 'The table specified, %s, does not exist in the database',
  2338. $table
  2339. );
  2340. }
  2341. $this->fetchKeys();
  2342. $this->mergeKeys();
  2343. if ($relationship_type) {
  2344. return $this->relationships[$table][$relationship_type];
  2345. }
  2346. return $this->relationships[$table];
  2347. }
  2348. /**
  2349. * Returns the tables in the current database
  2350. *
  2351. * @param boolean|string $creation_order `TRUE` to return in a valid table creation order, or a table name to return that table and any tables that depend on it, in table creation order
  2352. * @return array The tables in the current database, all converted to lowercase
  2353. */
  2354. public function getTables($creation_order=NULL)
  2355. {
  2356. if ($creation_order) {
  2357. return $this->determineTableCreationOrder(is_bool($creation_order) ? NULL : $creation_order);
  2358. }
  2359. if ($this->tables !== NULL) {
  2360. return $this->tables;
  2361. }
  2362. switch ($this->database->getType()) {
  2363. case 'db2':
  2364. $sql = "SELECT
  2365. LOWER(RTRIM(TABSCHEMA)) AS \"schema\",
  2366. LOWER(TABNAME) AS \"table\"
  2367. FROM
  2368. SYSCAT.TABLES
  2369. WHERE
  2370. TYPE = 'T' AND
  2371. TABSCHEMA != 'SYSIBM' AND
  2372. DEFINER != 'SYSIBM' AND
  2373. TABSCHEMA != 'SYSTOOLS' AND
  2374. DEFINER != 'SYSTOOLS'
  2375. ORDER BY
  2376. LOWER(TABNAME)";
  2377. break;
  2378. case 'mssql':
  2379. $sql = "SELECT
  2380. TABLE_SCHEMA AS \"schema\",
  2381. TABLE_NAME AS \"table\"
  2382. FROM
  2383. INFORMATION_SCHEMA.TABLES
  2384. WHERE
  2385. TABLE_NAME != 'sysdiagrams'
  2386. ORDER BY
  2387. LOWER(TABLE_NAME)";
  2388. break;
  2389. case 'mysql':
  2390. if (version_compare($this->database->getVersion(), 5, '<')) {
  2391. $sql = 'SHOW TABLES';
  2392. } else {
  2393. $sql = "SHOW FULL TABLES WHERE table_type = 'BASE TABLE'";
  2394. }
  2395. break;
  2396. case 'oracle':
  2397. $sql = "SELECT
  2398. LOWER(OWNER) AS \"SCHEMA\",
  2399. LOWER(TABLE_NAME) AS \"TABLE\"
  2400. FROM
  2401. ALL_TABLES
  2402. WHERE
  2403. OWNER NOT IN (
  2404. 'SYS',
  2405. 'SYSTEM',
  2406. 'OUTLN',
  2407. 'ANONYMOUS',
  2408. 'AURORA\$ORB\$UNAUTHENTICATED',
  2409. 'AWR_STAGE',
  2410. 'CSMIG',
  2411. 'CTXSYS',
  2412. 'DBSNMP',
  2413. 'DIP',
  2414. 'DMSYS',
  2415. 'DSSYS',
  2416. 'EXFSYS',
  2417. 'FLOWS_020100',
  2418. 'FLOWS_FILES',
  2419. 'LBACSYS',
  2420. 'MDSYS',
  2421. 'ORACLE_OCM',
  2422. 'ORDPLUGINS',
  2423. 'ORDSYS',
  2424. 'PERFSTAT',
  2425. 'TRACESVR',
  2426. 'TSMSYS',
  2427. 'XDB'
  2428. ) AND
  2429. DROPPED = 'NO'
  2430. ORDER BY
  2431. TABLE_NAME ASC";
  2432. break;
  2433. case 'postgresql':
  2434. $sql = "SELECT
  2435. schemaname AS \"schema\",
  2436. tablename as \"table\"
  2437. FROM
  2438. pg_tables
  2439. WHERE
  2440. tablename !~ '^(pg|sql)_'
  2441. ORDER BY
  2442. LOWER(tablename)";
  2443. break;
  2444. case 'sqlite':
  2445. $sql = "SELECT
  2446. name
  2447. FROM
  2448. sqlite_master
  2449. WHERE
  2450. type = 'table' AND
  2451. name NOT LIKE 'sqlite_%'
  2452. ORDER BY
  2453. name ASC";
  2454. break;
  2455. }
  2456. $result = $this->database->query($sql);
  2457. $this->tables = array();
  2458. // For databases with schemas we only include the schema
  2459. // name if there are conflicting table names
  2460. if (!in_array($this->database->getType(), array('mysql', 'sqlite'))) {
  2461. $default_schema_map = array(
  2462. 'db2' => strtolower($this->database->getUsername()),
  2463. 'mssql' => 'dbo',
  2464. 'oracle' => strtolower($this->database->getUsername()),
  2465. 'postgresql' => 'public'
  2466. );
  2467. $default_schema = $default_schema_map[$this->database->getType()];
  2468. foreach ($result as $row) {
  2469. if ($row['schema'] == $default_schema) {
  2470. $this->tables[] = strtolower($row['table']);
  2471. } else {
  2472. $this->tables[] = strtolower($row['schema'] . '.' . $row['table']);
  2473. }
  2474. }
  2475. // SQLite and MySQL don't support schemas
  2476. } else {
  2477. foreach ($result as $row) {
  2478. $keys = array_keys($row);
  2479. $this->tables[] = strtolower($row[$keys[0]]);
  2480. }
  2481. }
  2482. sort($this->tables);
  2483. if ($this->cache) {
  2484. $this->cache->set($this->makeCachePrefix() . 'tables', $this->tables);
  2485. }
  2486. return $this->tables;
  2487. }
  2488. /**
  2489. * Determines if a table is a joining table
  2490. *
  2491. * @param string $table The table to check
  2492. * @return boolean If the table is a joining table
  2493. */
  2494. private function isJoiningTable($table)
  2495. {
  2496. $primary_key_columns = $this->merged_keys[$table]['primary'];
  2497. if (sizeof($primary_key_columns) != 2) {
  2498. return FALSE;
  2499. }
  2500. if (empty($this->merged_column_info[$table])) {
  2501. $this->getColumnInfo($table);
  2502. }
  2503. if (sizeof($this->merged_column_info[$table]) != 2) {
  2504. return FALSE;
  2505. }
  2506. $foreign_key_columns = array();
  2507. foreach ($this->merged_keys[$table]['foreign'] as $key) {
  2508. $foreign_key_columns[] = $key['column'];
  2509. }
  2510. return sizeof($foreign_key_columns) == 2 && !array_diff($foreign_key_columns, $primary_key_columns);
  2511. }
  2512. /**
  2513. * Creates a unique cache prefix to help prevent cache conflicts
  2514. *
  2515. * @return string The cache prefix to use
  2516. */
  2517. private function makeCachePrefix()
  2518. {
  2519. if (!$this->cache_prefix) {
  2520. $prefix = 'fSchema::' . $this->database->getType() . '::';
  2521. if ($this->database->getHost()) {
  2522. $prefix .= $this->database->getHost() . '::';
  2523. }
  2524. if ($this->database->getPort()) {
  2525. $prefix .= $this->database->getPort() . '::';
  2526. }
  2527. $prefix .= $this->database->getDatabase() . '::';
  2528. if ($this->database->getUsername()) {
  2529. $prefix .= $this->database->getUsername() . '::';
  2530. }
  2531. $this->cache_prefix = $prefix;
  2532. }
  2533. return $this->cache_prefix;
  2534. }
  2535. /**
  2536. * Merges the column info with the column info override
  2537. *
  2538. * @return void
  2539. */
  2540. private function mergeColumnInfo()
  2541. {
  2542. $this->merged_column_info = $this->column_info;
  2543. foreach ($this->column_info_override as $table => $columns) {
  2544. // Remove a table if the columns are set to NULL
  2545. if ($columns === NULL) {
  2546. unset($this->merged_column_info[$table]);
  2547. continue;
  2548. }
  2549. if (!isset($this->merged_column_info[$table])) {
  2550. $this->merged_column_info[$table] = array();
  2551. }
  2552. foreach ($columns as $column => $info) {
  2553. // Remove a column if it is set to NULL
  2554. if ($info === NULL) {
  2555. unset($this->merged_column_info[$table][$column]);
  2556. continue;
  2557. }
  2558. if (!isset($this->merged_column_info[$table][$column])) {
  2559. $this->merged_column_info[$table][$column] = array();
  2560. }
  2561. $this->merged_column_info[$table][$column] = array_merge($this->merged_column_info[$table][$column], $info);
  2562. }
  2563. }
  2564. $optional_elements = array(
  2565. 'not_null',
  2566. 'default',
  2567. 'valid_values',
  2568. 'max_length',
  2569. 'max_value',
  2570. 'min_value',
  2571. 'decimal_places',
  2572. 'auto_increment',
  2573. 'comment'
  2574. );
  2575. foreach ($this->merged_column_info as $table => $column_array) {
  2576. foreach ($column_array as $column => $info) {
  2577. if (empty($info['type'])) {
  2578. throw new fProgrammerException('The data type for the column %1$s is empty', $column);
  2579. }
  2580. if (empty($this->merged_column_info[$table][$column]['placeholder'])) {
  2581. $this->merged_column_info[$table][$column]['placeholder'] = strtr(
  2582. $info['type'],
  2583. array(
  2584. 'blob' => '%l',
  2585. 'boolean' => '%b',
  2586. 'date' => '%d',
  2587. 'float' => '%f',
  2588. 'integer' => '%i',
  2589. 'char' => '%s',
  2590. 'text' => '%s',
  2591. 'varchar' => '%s',
  2592. 'time' => '%t',
  2593. 'timestamp' => '%p'
  2594. )
  2595. );
  2596. }
  2597. foreach ($optional_elements as $element) {
  2598. if (!isset($this->merged_column_info[$table][$column][$element])) {
  2599. $this->merged_column_info[$table][$column][$element] = ($element == 'auto_increment') ? FALSE : NULL;
  2600. }
  2601. }
  2602. }
  2603. }
  2604. if ($this->cache) {
  2605. $this->cache->set($this->makeCachePrefix() . 'merged_column_info', $this->merged_column_info);
  2606. }
  2607. }
  2608. /**
  2609. * Merges the keys with the keys override
  2610. *
  2611. * @return void
  2612. */
  2613. private function mergeKeys()
  2614. {
  2615. // Handle the database and override key info
  2616. $this->merged_keys = $this->keys;
  2617. foreach ($this->keys_override as $table => $info) {
  2618. if (!isset($this->merged_keys[$table])) {
  2619. $this->merged_keys[$table] = array();
  2620. }
  2621. $this->merged_keys[$table] = array_merge($this->merged_keys[$table], $info);
  2622. }
  2623. if ($this->cache) {
  2624. $this->cache->set($this->makeCachePrefix() . 'merged_keys', $this->merged_keys);
  2625. }
  2626. $this->findRelationships();
  2627. }
  2628. /**
  2629. * Allows overriding of column info
  2630. *
  2631. * Performs an array merge with the column info detected from the database.
  2632. *
  2633. * To erase a whole table, set the `$column_info` to `NULL`. To erase a
  2634. * column, set the `$column_info` for that column to `NULL`.
  2635. *
  2636. * If the `$column_info` parameter is not `NULL`, it should be an
  2637. * associative array containing one or more of the following keys. Please
  2638. * see ::getColumnInfo() for a description of each.
  2639. * - `'type'`
  2640. * - `'placeholder'`
  2641. * - `'not_null'`
  2642. * - `'default'`
  2643. * - `'valid_values'`
  2644. * - `'max_length'`
  2645. * - `'min_value'`
  2646. * - `'max_value'`
  2647. * - `'decimal_places'`
  2648. * - `'auto_increment'`
  2649. * - `'comment'`
  2650. *
  2651. * The following keys may be set to `NULL`:
  2652. * - `'not_null'`
  2653. * - `'default'`
  2654. * - `'valid_values'`
  2655. * - `'max_length'`
  2656. * - `'min_value'`
  2657. * - `'max_value'`
  2658. * - `'decimal_places'`
  2659. * - `'comment'`
  2660. *
  2661. * The key `'auto_increment'` should be a boolean.
  2662. *
  2663. * The `'type'` key should be one of:
  2664. * - `'blob'`
  2665. * - `'boolean'`
  2666. * - `'char'`
  2667. * - `'date'`
  2668. * - `'float'`
  2669. * - `'integer'`
  2670. * - `'text'`
  2671. * - `'time'`
  2672. * - `'timestamp'`
  2673. * - `'varchar'`
  2674. *
  2675. * @param array $column_info The modified column info - see method description for format
  2676. * @param string $table The table to override
  2677. * @param string $column The column to override
  2678. * @return void
  2679. */
  2680. public function setColumnInfoOverride($column_info, $table, $column=NULL)
  2681. {
  2682. $table = strotlower($table);
  2683. if ($column !== NULL) {
  2684. $column = strtolower($column);
  2685. }
  2686. if (!isset($this->column_info_override[$table])) {
  2687. $this->column_info_override[$table] = array();
  2688. }
  2689. if (!empty($column)) {
  2690. $this->column_info_override[$table][$column] = $column_info;
  2691. } else {
  2692. $this->column_info_override[$table] = $column_info;
  2693. }
  2694. $this->fetchColumnInfo($table);
  2695. $this->mergeColumnInfo();
  2696. }
  2697. /**
  2698. * Allows overriding of key info. Replaces existing info, so be sure to provide full key info for type selected or all types.
  2699. *
  2700. * @param array $keys The modified keys - see ::getKeys() for format
  2701. * @param string $table The table to override
  2702. * @param string $key_type The key type to override: `'primary'`, `'foreign'`, `'unique'`
  2703. * @return void
  2704. */
  2705. public function setKeysOverride($keys, $table, $key_type=NULL)
  2706. {
  2707. $table = strtolower($table);
  2708. $valid_key_types = array('primary', 'foreign', 'unique');
  2709. if (!in_array($key_type, $valid_key_types)) {
  2710. throw new fProgrammerException(
  2711. 'The key type specified, %1$s, is invalid. Must be one of: %2$s.',
  2712. $key_type,
  2713. join(', ', $valid_key_types)
  2714. );
  2715. }
  2716. if (!isset($this->keys_override[$table])) {
  2717. $this->keys_override[$table] = array();
  2718. }
  2719. if (!empty($key_type)) {
  2720. $this->keys_override[$table][$key_type] = $keys;
  2721. } else {
  2722. $this->keys_override[$table] = $keys;
  2723. }
  2724. $this->fetchKeys();
  2725. $this->mergeKeys();
  2726. }
  2727. }
  2728. /**
  2729. * Copyright (c) 2007-2011 Will Bond <will@flourishlib.com>
  2730. *
  2731. * Permission is hereby granted, free of charge, to any person obtaining a copy
  2732. * of this software and associated documentation files (the "Software"), to deal
  2733. * in the Software without restriction, including without limitation the rights
  2734. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  2735. * copies of the Software, and to permit persons to whom the Software is
  2736. * furnished to do so, subject to the following conditions:
  2737. *
  2738. * The above copyright notice and this permission notice shall be included in
  2739. * all copies or substantial portions of the Software.
  2740. *
  2741. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  2742. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  2743. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  2744. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  2745. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  2746. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  2747. * THE SOFTWARE.
  2748. */