PageRenderTime 89ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/classes/fSQLSchemaTranslation.php

https://bitbucket.org/dsqmoore/flourish
PHP | 5398 lines | 4183 code | 653 blank | 562 comment | 586 complexity | a8aad10581b20a1048ad1fa146027bbb MD5 | raw file
  1. <?php
  2. /**
  3. * Adds cross-database `CREATE TABLE`, `ALTER TABLE` and `COMMENT ON COLUMN` statements to fSQLTranslation
  4. *
  5. * @copyright Copyright (c) 2011-2012 Will Bond
  6. * @author Will Bond [wb] <will@flourishlib.com>
  7. * @license http://flourishlib.com/license
  8. *
  9. * @package Flourish
  10. * @link http://flourishlib.com/fSQLSchemaTranslation
  11. *
  12. * @version 1.0.0b3
  13. * @changes 1.0.0b3 Fixed associating a sequence with a column in PostgreSQL when setting auto-increment, fixed detection of some Oracle CHECK(IN) constraints, fixed default values for SQLite `ON DELETE` and `ON UPDATE` clauses [wb, 2012-01-12]
  14. * @changes 1.0.0b2 Fixed detection of explicitly named SQLite foreign key constraints [wb, 2011-08-23]
  15. * @changes 1.0.0b The initial implementation [wb, 2011-05-09]
  16. */
  17. class fSQLSchemaTranslation
  18. {
  19. /**
  20. * Converts a SQL identifier to lower case and removes double quotes
  21. *
  22. * @param string $identifier The SQL identifier
  23. * @return string The unescaped identifier
  24. */
  25. static private function unescapeIdentifier($identifier)
  26. {
  27. return str_replace('"', '', strtolower($identifier));
  28. }
  29. /**
  30. * Composes text using fText if loaded
  31. *
  32. * @param string $message The message to compose
  33. * @param mixed $component A string or number to insert into the message
  34. * @param mixed ...
  35. * @return string The composed and possible translated message
  36. */
  37. static protected function compose($message)
  38. {
  39. $args = array_slice(func_get_args(), 1);
  40. if (class_exists('fText', FALSE)) {
  41. return call_user_func_array(
  42. array('fText', 'compose'),
  43. array($message, $args)
  44. );
  45. } else {
  46. return vsprintf($message, $args);
  47. }
  48. }
  49. /**
  50. * Accepts a CREATE TABLE statement and parses out the column definitions
  51. *
  52. * The return value is an associative array with the keys being column
  53. * names and the values being arrays containing the following keys:
  54. * - definition: (string) the complete column definition
  55. * - pieces: (array) an associative array that can be joined back together to make the definition
  56. * - beginning
  57. * - column_name
  58. * - data_type
  59. * - not_null
  60. * - null
  61. * - default
  62. * - unique
  63. * - primary_key
  64. * - check_constraint
  65. * - foreign_key
  66. * - deferrable
  67. * - comment/end
  68. *
  69. * @param string $sql The SQL `CREATE TABLE` statement
  70. * @return array An associative array of information for each column - see method description for details
  71. */
  72. static private function parseSQLiteColumnDefinitions($sql)
  73. {
  74. preg_match_all(
  75. '#(?<=,|\(|\*/|\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))?)?((?:\s*(?:/\*\s*((?:(?!\*/).)*?)\s*\*/))?\s*(?:,[ \t]*(?:--[ \t]*([^\n]*?)[ \t]*(?=\n)|/\*\s*((?:(?!\*/).)*?)\s*\*/)?|(?:--[ \t]*([^\n]*?)[ \t]*(?=\n))?\s*(?=\))))#msi',
  76. $sql,
  77. $matches,
  78. PREG_SET_ORDER
  79. );
  80. $output = array();
  81. foreach ($matches as $match) {
  82. $comment = '';
  83. foreach (array(16, 17, 18, 19) as $key) {
  84. if (isset($match[$key])) {
  85. $comment .= $match[$key];
  86. }
  87. }
  88. $output[strtolower($match[2])] = array(
  89. 'definition' => $match[0],
  90. 'pieces' => array(
  91. 'beginning' => $match[1],
  92. 'column_name' => $match[2],
  93. 'data_type' => $match[3],
  94. 'not_null' => $match[6],
  95. 'null' => $match[7],
  96. 'default' => $match[8],
  97. 'unique' => $match[10],
  98. 'primary_key' => $match[11],
  99. 'check_constraint' => $match[12],
  100. 'foreign_key' => $match[13],
  101. 'deferrable' => $match[14],
  102. 'comment/end' => $match[15]
  103. )
  104. );
  105. }
  106. return $output;
  107. }
  108. /**
  109. * Removes a search string from a `CREATE TABLE` statement
  110. *
  111. * @param string $create_table_sql The SQL `CREATE TABLE` statement
  112. * @param string $search The string to remove
  113. * @return string The modified `CREATE TABLE` statement
  114. */
  115. static private function removeFromSQLiteCreateTable($create_table_sql, $search)
  116. {
  117. if (preg_match('#,(\s*--.*)?\s*$#D', $search)) {
  118. $regex = '#' . preg_quote($search, '#') . '#';
  119. } else {
  120. $regex = '#,(\s*/\*.*?\*/\s*|\s*--[^\n]+\n\s*)?\s*' . preg_quote($search, '#') . '\s*#';
  121. }
  122. return preg_replace($regex, "\\1\n", $create_table_sql);
  123. }
  124. /**
  125. * The fDatabase instance
  126. *
  127. * @var fDatabase
  128. */
  129. private $database;
  130. /**
  131. * Database-specific schema information needed for translation
  132. *
  133. * @var array
  134. */
  135. private $schema_info;
  136. /**
  137. * Sets up the class
  138. *
  139. * @param fDatabase $database The database being translated for
  140. * @return fSQLSchemaTranslation
  141. */
  142. public function __construct($database)
  143. {
  144. $this->database = $database;
  145. $this->schema_info = array();
  146. }
  147. /**
  148. * All requests that hit this method should be requests for callbacks
  149. *
  150. * @internal
  151. *
  152. * @param string $method The method to create a callback for
  153. * @return callback The callback for the method requested
  154. */
  155. public function __get($method)
  156. {
  157. return array($this, $method);
  158. }
  159. /**
  160. * Adds a SQLite index to the internal schema tracker
  161. *
  162. * @param string $name The index name
  163. * @param string $table The table the index applies to
  164. * @param string $sql The SQL definition of the index
  165. * @return void
  166. */
  167. private function addSQLiteIndex($name, $table, $sql)
  168. {
  169. if (!isset($this->schema_info['sqlite_indexes'])) {
  170. $this->schema_info['sqlite_indexes'] = array();
  171. }
  172. $this->schema_info['sqlite_indexes'][$name] = array(
  173. 'table' => $table,
  174. 'sql' => $sql
  175. );
  176. }
  177. /**
  178. * Stores the SQL used to create a table
  179. *
  180. * @param string $table The table to set the `CREATE TABLE` statement for
  181. * @param string $sql The SQL used to create the table
  182. * @return void
  183. */
  184. private function addSQLiteTable($table, $sql)
  185. {
  186. if (!isset($this->schema_info['sqlite_create_tables'])) {
  187. $this->getSQLiteTables();
  188. }
  189. $this->schema_info['sqlite_create_tables'][$table] = $sql;
  190. }
  191. /**
  192. * Adds a SQLite trigger to the internal schema tracker
  193. *
  194. * @param string $name The trigger name
  195. * @param string $table The table the trigger applies to
  196. * @param string $sql The SQL definition of the trigger
  197. * @return void
  198. */
  199. private function addSQLiteTrigger($name, $table, $sql)
  200. {
  201. if (!isset($this->schema_info['sqlite_triggers'])) {
  202. $this->schema_info['sqlite_triggers'] = array();
  203. }
  204. $this->schema_info['sqlite_triggers'][$name] = array(
  205. 'table' => $table,
  206. 'sql' => $sql
  207. );
  208. }
  209. /**
  210. * Creates a trigger for SQLite that handles an on delete clause
  211. *
  212. * @param array &$extra_statements An array of extra SQL statements to be added to the SQL
  213. * @param string $referencing_table The table that contains the foreign key
  214. * @param string $referencing_column The column the foreign key constraint is on
  215. * @param string $referenced_table The table the foreign key references
  216. * @param string $referenced_column The column the foreign key references
  217. * @param string $delete_clause What is to be done on a delete
  218. * @return string The trigger
  219. */
  220. private function createSQLiteForeignKeyTriggerOnDelete(&$extra_statements, $referencing_table, $referencing_column, $referenced_table, $referenced_column, $delete_clause)
  221. {
  222. switch (strtolower($delete_clause)) {
  223. case 'no action':
  224. case 'restrict':
  225. $name = 'fkd_res_' . $referencing_table . '_' . $referencing_column;
  226. $extra_statements[] = 'CREATE TRIGGER ' . $name . '
  227. BEFORE DELETE ON "' . $referenced_table . '"
  228. FOR EACH ROW BEGIN
  229. SELECT RAISE(ROLLBACK, \'delete on table "' . $referenced_table . '" can not be executed because it would violate the foreign key constraint on column "' . $referencing_column . '" of table "' . $referencing_table . '"\')
  230. WHERE (SELECT "' . $referencing_column . '" FROM "' . $referencing_table . '" WHERE "' . $referencing_column . '" = OLD."' . $referenced_table . '") IS NOT NULL;
  231. END';
  232. $this->addSQLiteTrigger($name, $referenced_table, end($extra_statements));
  233. break;
  234. case 'set null':
  235. $name = 'fkd_nul_' . $referencing_table . '_' . $referencing_column;
  236. $extra_statements[] = 'CREATE TRIGGER ' . $name . '
  237. BEFORE DELETE ON "' . $referenced_table . '"
  238. FOR EACH ROW BEGIN
  239. UPDATE "' . $referencing_table . '" SET "' . $referencing_column . '" = NULL WHERE "' . $referencing_column . '" = OLD."' . $referenced_column . '";
  240. END';
  241. $this->addSQLiteTrigger($name, $referenced_table, end($extra_statements));
  242. break;
  243. case 'cascade':
  244. $name = 'fkd_cas_' . $referencing_table . '_' . $referencing_column;
  245. $extra_statements[] = 'CREATE TRIGGER ' . $name . '
  246. BEFORE DELETE ON "' . $referenced_table . '"
  247. FOR EACH ROW BEGIN
  248. DELETE FROM "' . $referencing_table . '" WHERE "' . $referencing_column . '" = OLD."' . $referenced_column . '";
  249. END';
  250. $this->addSQLiteTrigger($name, $referenced_table, end($extra_statements));
  251. break;
  252. }
  253. }
  254. /**
  255. * Creates a trigger for SQLite that handles an on update clause
  256. *
  257. * @param array &$extra_statements An array of extra SQL statements to be added to the SQL
  258. * @param string $referencing_table The table that contains the foreign key
  259. * @param string $referencing_column The column the foreign key constraint is on
  260. * @param string $referenced_table The table the foreign key references
  261. * @param string $referenced_column The column the foreign key references
  262. * @param string $update_clause What is to be done on an update
  263. * @return string The trigger
  264. */
  265. private function createSQLiteForeignKeyTriggerOnUpdate(&$extra_statements, $referencing_table, $referencing_column, $referenced_table, $referenced_column, $update_clause)
  266. {
  267. switch (strtolower($update_clause)) {
  268. case 'no action':
  269. case 'restrict':
  270. $name = 'fku_res_' . $referencing_table . '_' . $referencing_column;
  271. $extra_statements[] = 'CREATE TRIGGER ' . $name . '
  272. BEFORE UPDATE ON "' . $referenced_table . '"
  273. FOR EACH ROW BEGIN
  274. SELECT RAISE(ROLLBACK, \'update on table "' . $referenced_table . '" can not be executed because it would violate the foreign key constraint on column "' . $referencing_column . '" of table "' . $referencing_table . '"\')
  275. WHERE (SELECT "' . $referencing_column . '" FROM "' . $referencing_table . '" WHERE "' . $referencing_column . '" = OLD."' . $referenced_column . '") IS NOT NULL;
  276. END';
  277. $this->addSQLiteTrigger($name, $referenced_table, end($extra_statements));
  278. break;
  279. case 'set null':
  280. $name = 'fku_nul_' . $referencing_table . '_' . $referencing_column;
  281. $extra_statements[] = 'CREATE TRIGGER ' . $name . '
  282. BEFORE UPDATE ON "' . $referenced_table . '"
  283. FOR EACH ROW BEGIN
  284. UPDATE "' . $referencing_table . '" SET "' . $referencing_column . '" = NULL WHERE OLD."' . $referenced_column . '" <> NEW."' . $referenced_column . '" AND "' . $referencing_column . '" = OLD."' . $referenced_column . '";
  285. END';
  286. $this->addSQLiteTrigger($name, $referenced_table, end($extra_statements));
  287. break;
  288. case 'cascade':
  289. $name = 'fku_cas_' . $referencing_table . '_' . $referencing_column;
  290. $extra_statements[] = 'CREATE TRIGGER ' . $name . '
  291. BEFORE UPDATE ON "' . $referenced_table . '"
  292. FOR EACH ROW BEGIN
  293. UPDATE "' . $referencing_table . '" SET "' . $referencing_column . '" = NEW."' . $referenced_column . '" WHERE OLD."' . $referenced_column . '" <> NEW."' . $referenced_column . '" AND "' . $referencing_column . '" = OLD."' . $referenced_column . '";
  294. END';
  295. $this->addSQLiteTrigger($name, $referenced_table, end($extra_statements));
  296. break;
  297. }
  298. }
  299. /**
  300. * Creates a trigger for SQLite that prevents inserting or updating to values the violate a `FOREIGN KEY` constraint
  301. *
  302. * @param array &$extra_statements An array of extra SQL statements to be added to the SQL
  303. * @param string $referencing_table The table that contains the foreign key
  304. * @param string $referencing_column The column the foriegn key constraint is on
  305. * @param string $referenced_table The table the foreign key references
  306. * @param string $referenced_column The column the foreign key references
  307. * @param boolean $referencing_not_null If the referencing columns is set to not null
  308. * @return string The trigger
  309. */
  310. private function createSQLiteForeignKeyTriggerValidInsertUpdate(&$extra_statements, $referencing_table, $referencing_column, $referenced_table, $referenced_column, $referencing_not_null)
  311. {
  312. // Verify key on inserts
  313. $name = 'fki_ver_' . $referencing_table . '_' . $referencing_column;
  314. $sql = 'CREATE TRIGGER ' . $name . '
  315. BEFORE INSERT ON "' . $referencing_table . '"
  316. FOR EACH ROW BEGIN
  317. SELECT RAISE(ROLLBACK, \'insert on table "' . $referencing_table . '" violates foreign key constraint on column "' . $referencing_column . '"\')
  318. WHERE ';
  319. if (!$referencing_not_null) {
  320. $sql .= 'NEW."' . $referencing_column . '" IS NOT NULL AND ';
  321. }
  322. $sql .= ' (SELECT "' . $referenced_column . '" FROM "' . $referenced_table . '" WHERE "' . $referenced_column . '" = NEW."' . $referencing_column . '") IS NULL;
  323. END';
  324. $extra_statements[] = $sql;
  325. $this->addSQLiteTrigger($name, $referencing_table, end($extra_statements));
  326. // Verify key on updates
  327. $name = 'fku_ver_' . $referencing_table . '_' . $referencing_column;
  328. $sql = 'CREATE TRIGGER ' . $name . '
  329. BEFORE UPDATE ON "' . $referencing_table . '"
  330. FOR EACH ROW BEGIN
  331. SELECT RAISE(ROLLBACK, \'update on table "' . $referencing_table . '" violates foreign key constraint on column "' . $referencing_column . '"\')
  332. WHERE ';
  333. if (!$referencing_not_null) {
  334. $sql .= 'NEW."' . $referencing_column . '" IS NOT NULL AND ';
  335. }
  336. $sql .= ' (SELECT "' . $referenced_column . '" FROM "' . $referenced_table . '" WHERE "' . $referenced_column . '" = NEW."' . $referencing_column . '") IS NULL;
  337. END';
  338. $extra_statements[] = $sql;
  339. $this->addSQLiteTrigger($name, $referencing_table, end($extra_statements));
  340. }
  341. /**
  342. * Generates a 30 character constraint name for use with `ALTER TABLE` statements
  343. *
  344. * @param string $sql The `ALTER TABLE` statement
  345. * @param string $type A 2-character string representing the type of constraint
  346. */
  347. private function generateConstraintName($sql, $type)
  348. {
  349. $constraint = '_' . $type;
  350. $constraint = '_' . substr(time(), -8) . $constraint;
  351. return substr(md5(strtolower($sql)), 0, 30 - strlen($constraint)) . $constraint;
  352. }
  353. /**
  354. * Returns the check constraint for a table and column
  355. *
  356. * @param string $schema The schema the table is in
  357. * @param string $table The table the column is in
  358. * @param string $column The column to get the check constraint for
  359. * @return array|NULL An associative array with the keys: `name` and `definition` or `NULL`
  360. */
  361. private function getDB2CheckConstraint($schema, $table, $column)
  362. {
  363. $constraint = $this->database->query(
  364. "SELECT
  365. CH.TEXT,
  366. CH.CONSTNAME
  367. FROM
  368. SYSCAT.COLUMNS AS C INNER JOIN
  369. SYSCAT.COLCHECKS AS CC ON
  370. C.TABSCHEMA = CC.TABSCHEMA AND
  371. C.TABNAME = CC.TABNAME AND
  372. C.COLNAME = CC.COLNAME AND
  373. CC.USAGE = 'R' INNER JOIN
  374. SYSCAT.CHECKS AS CH ON
  375. C.TABSCHEMA = CH.TABSCHEMA AND
  376. C.TABNAME = CH.TABNAME AND
  377. CH.TYPE = 'C' AND
  378. CH.CONSTNAME = CC.CONSTNAME
  379. WHERE
  380. LOWER(C.TABSCHEMA) = %s AND
  381. LOWER(C.TABNAME) = %s AND
  382. LOWER(C.COLNAME) = %s",
  383. $schema,
  384. $table,
  385. $column
  386. );
  387. if (!$constraint->countReturnedRows()) {
  388. return NULL;
  389. }
  390. $row = $constraint->fetchRow();
  391. return array(
  392. 'name' => $row['constname'],
  393. 'definition' => $row['text']
  394. );
  395. }
  396. /**
  397. * Returns the foreign key constraints that involve a specific table or table and column
  398. *
  399. * @param string $schema The schema the table is in
  400. * @param string $table The table the column is in
  401. * @param string $column The column to get the foreign keys for and the foreign keys that point to
  402. * @return array An associative array of the key being the constraint name and the value being an associative array containing the keys: `schema`, `table`, `column`, `foreign_schema`, `foreign_table`, `foreign_column`, `on_delete` and `on_cascade`
  403. */
  404. private function getDB2ForeignKeyConstraints($schema, $table, $column=NULL)
  405. {
  406. if ($column) {
  407. $where_conditions = "((
  408. LOWER(R.TABSCHEMA) = %s AND
  409. LOWER(R.TABNAME) = %s AND
  410. LOWER(K.COLNAME) = %s
  411. ) OR (
  412. LOWER(R.REFTABSCHEMA) = %s AND
  413. LOWER(R.REFTABNAME) = %s AND
  414. LOWER(FK.COLNAME) = %s
  415. ))";
  416. $params = array(
  417. strtolower($schema),
  418. strtolower($table),
  419. strtolower($column),
  420. strtolower($schema),
  421. strtolower($table),
  422. strtolower($column)
  423. );
  424. } else {
  425. $where_conditions = "LOWER(R.REFTABSCHEMA) = %s AND LOWER(R.REFTABNAME) = %s";
  426. $params = array(
  427. strtolower($schema),
  428. strtolower($table)
  429. );
  430. }
  431. array_unshift(
  432. $params,
  433. "SELECT
  434. R.CONSTNAME AS CONSTRAINT_NAME,
  435. TRIM(LOWER(R.TABSCHEMA)) AS \"SCHEMA\",
  436. LOWER(R.TABNAME) AS \"TABLE\",
  437. LOWER(K.COLNAME) AS \"COLUMN\",
  438. TRIM(LOWER(R.REFTABSCHEMA)) AS FOREIGN_SCHEMA,
  439. LOWER(R.REFTABNAME) AS FOREIGN_TABLE,
  440. LOWER(FK.COLNAME) AS FOREIGN_COLUMN,
  441. CASE R.DELETERULE WHEN 'C' THEN 'CASCADE' WHEN 'A' THEN 'NO ACTION' WHEN 'R' THEN 'RESTRICT' ELSE 'SET NULL' END AS ON_DELETE,
  442. CASE R.UPDATERULE WHEN 'A' THEN 'NO ACTION' WHEN 'R' THEN 'RESTRICT' END AS ON_UPDATE
  443. FROM
  444. SYSCAT.REFERENCES AS R INNER JOIN
  445. SYSCAT.KEYCOLUSE AS K ON
  446. R.CONSTNAME = K.CONSTNAME AND
  447. R.TABSCHEMA = K.TABSCHEMA AND
  448. R.TABNAME = K.TABNAME INNER JOIN
  449. SYSCAT.KEYCOLUSE AS FK ON
  450. R.REFKEYNAME = FK.CONSTNAME AND
  451. R.REFTABSCHEMA = FK.TABSCHEMA AND
  452. R.REFTABNAME = FK.TABNAME
  453. WHERE
  454. $where_conditions
  455. ORDER BY
  456. LOWER(R.CONSTNAME) ASC"
  457. );
  458. $constraints = call_user_func_array($this->database->query, $params);
  459. $keys = array();
  460. foreach ($constraints as $constraint) {
  461. $name = $constraint['constraint_name'] . $constraint['table'];
  462. $keys[$name] = $constraint;
  463. }
  464. return $keys;
  465. }
  466. /**
  467. * Returns the primary key for a table
  468. *
  469. * @param string $schema The schema the table is in
  470. * @param string $table The table to get the primary key for
  471. * @return array The columns in the primary key
  472. */
  473. private function getDB2PrimaryKeyConstraint($schema, $table)
  474. {
  475. $constraints = $this->database->query(
  476. "SELECT
  477. LOWER(C.COLNAME) AS \"COLUMN\"
  478. FROM
  479. SYSCAT.INDEXES AS I INNER JOIN
  480. SYSCAT.INDEXCOLUSE AS C ON
  481. I.INDSCHEMA = C.INDSCHEMA AND
  482. I.INDNAME = C.INDNAME
  483. WHERE
  484. I.UNIQUERULE IN ('P') AND
  485. LOWER(I.TABSCHEMA) = %s AND
  486. LOWER(I.TABNAME) = %s
  487. ORDER BY
  488. LOWER(I.INDNAME) ASC
  489. ",
  490. strtolower($schema),
  491. strtolower($table)
  492. );
  493. $key = array();
  494. foreach ($constraints as $constraint) {
  495. $key[] = $constraint['column'];
  496. }
  497. return $key;
  498. }
  499. /**
  500. * Returns the unique keys for a table and column
  501. *
  502. * @param string $schema The schema the table is in
  503. * @param string $table The table to get the unique keys for
  504. * @param string $column The column to filter the unique keys by
  505. * @return array An associative array of the key being the constraint name and the value being the columns in the unique key
  506. */
  507. private function getDB2UniqueConstraints($schema, $table, $column)
  508. {
  509. $constraints = $this->database->query(
  510. "SELECT
  511. CD.CONSTNAME AS CONSTRAINT_NAME,
  512. LOWER(C.COLNAME) AS \"COLUMN\"
  513. FROM
  514. SYSCAT.INDEXES AS I INNER JOIN
  515. SYSCAT.CONSTDEP AS CD ON
  516. I.TABSCHEMA = CD.TABSCHEMA AND
  517. I.TABNAME = CD.TABNAME AND
  518. CD.BTYPE = 'I' AND
  519. CD.BNAME = I.INDNAME INNER JOIN
  520. SYSCAT.INDEXCOLUSE AS C ON
  521. I.INDSCHEMA = C.INDSCHEMA AND
  522. I.INDNAME = C.INDNAME
  523. WHERE
  524. I.UNIQUERULE IN ('U') AND
  525. LOWER(I.TABSCHEMA) = %s AND
  526. LOWER(I.TABNAME) = %s
  527. ORDER BY
  528. LOWER(I.INDNAME) ASC
  529. ",
  530. strtolower($schema),
  531. strtolower($table)
  532. );
  533. $keys = array();
  534. foreach ($constraints as $constraint) {
  535. if (!isset($keys[$constraint['constraint_name']])) {
  536. $keys[$constraint['constraint_name']] = array();
  537. }
  538. $keys[$constraint['constraint_name']][] = $constraint['column'];
  539. }
  540. $new_keys = array();
  541. $column = strtolower($column);
  542. foreach ($keys as $name => $columns) {
  543. if (!in_array($column, $columns)) {
  544. continue;
  545. }
  546. $new_keys[$name] = $columns;
  547. }
  548. $keys = $new_keys;
  549. return $keys;
  550. }
  551. /**
  552. * Returns the check constraint for a column, if it exists
  553. *
  554. * @param string $schema The schema the column is inside of
  555. * @param string $table The table the column is part of
  556. * @param string $column The column name
  557. * @return array|NULL An associative array with the keys `name` and `definition`, or `NULL`
  558. */
  559. private function getMSSQLCheckConstraint($schema, $table, $column)
  560. {
  561. $constraint = $this->database->query(
  562. "SELECT
  563. cc.check_clause AS 'constraint',
  564. ccu.constraint_name
  565. FROM
  566. INFORMATION_SCHEMA.COLUMNS AS c INNER JOIN
  567. INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS ccu ON
  568. c.column_name = ccu.column_name AND
  569. c.table_name = ccu.table_name AND
  570. c.table_catalog = ccu.table_catalog INNER JOIN
  571. INFORMATION_SCHEMA.CHECK_CONSTRAINTS AS cc ON
  572. ccu.constraint_name = cc.constraint_name AND
  573. ccu.constraint_catalog = cc.constraint_catalog
  574. WHERE
  575. LOWER(c.table_schema) = %s AND
  576. LOWER(c.table_name) = %s AND
  577. LOWER(c.column_name) = %s AND
  578. c.table_catalog = DB_NAME()",
  579. strtolower($schema),
  580. strtolower($table),
  581. strtolower($column)
  582. );
  583. if (!$constraint->countReturnedRows()) {
  584. return NULL;
  585. }
  586. $row = $constraint->fetchRow();
  587. return array(
  588. 'name' => $row['constraint_name'],
  589. 'definition' => $row['constraint']
  590. );
  591. }
  592. /**
  593. * Returns the foreign key constraints that a column is part of
  594. *
  595. * @param string $schema The schema the column is inside of
  596. * @param string $table The table the column is part of
  597. * @param string|array $column The column name(s)
  598. * @return array An array of constraint names that reference the column(s)
  599. */
  600. private function getMSSQLForeignKeyConstraints($schema, $table, $column)
  601. {
  602. settype($column, 'array');
  603. $constraints = $this->database->query(
  604. "SELECT
  605. LOWER(tc.table_schema + '.' + tc.table_name) AS 'table',
  606. LOWER(tc.table_schema) AS 'schema',
  607. LOWER(tc.table_name) AS 'table_without_schema',
  608. LOWER(kcu.column_name) AS 'column',
  609. kcu.constraint_name AS name
  610. FROM
  611. information_schema.table_constraints AS tc INNER JOIN
  612. information_schema.key_column_usage AS kcu ON
  613. tc.constraint_name = kcu.constraint_name AND
  614. tc.constraint_catalog = kcu.constraint_catalog AND
  615. tc.constraint_schema = kcu.constraint_schema AND
  616. tc.table_name = kcu.table_name INNER JOIN
  617. information_schema.referential_constraints AS rc ON
  618. kcu.constraint_name = rc.constraint_name AND
  619. kcu.constraint_catalog = rc.constraint_catalog AND
  620. kcu.constraint_schema = rc.constraint_schema INNER JOIN
  621. information_schema.constraint_column_usage AS ccu ON
  622. ccu.constraint_name = rc.unique_constraint_name AND
  623. ccu.constraint_catalog = rc.constraint_catalog AND
  624. ccu.constraint_schema = rc.constraint_schema
  625. WHERE
  626. tc.constraint_type = 'FOREIGN KEY' AND
  627. (
  628. LOWER(tc.table_schema) = %s AND
  629. LOWER(ccu.table_name) = %s AND
  630. LOWER(ccu.column_name) IN (%s)
  631. ) OR (
  632. LOWER(tc.table_schema) = %s AND
  633. LOWER(kcu.table_name) = %s AND
  634. LOWER(kcu.column_name) IN (%s)
  635. ) AND
  636. tc.constraint_catalog = DB_NAME()",
  637. strtolower($schema),
  638. strtolower($table),
  639. array_map('strtolower', $column),
  640. strtolower($schema),
  641. strtolower($table),
  642. array_map('strtolower', $column)
  643. );
  644. return $constraints->fetchAllRows();
  645. }
  646. /**
  647. * Returns the default constraint for a column, if it exists
  648. *
  649. * @param string $schema The schema the column is inside of
  650. * @param string $table The table the column is part of
  651. * @param string $column The column name
  652. * @return array|NULL An associative array with the keys `name` and `definition`, or `NULL`
  653. */
  654. private function getMSSQLDefaultConstraint($schema, $table, $column)
  655. {
  656. $constraint = $this->database->query(
  657. "SELECT
  658. dc.name,
  659. CAST(dc.definition AS VARCHAR(MAX)) AS definition
  660. FROM
  661. information_schema.columns AS c INNER JOIN
  662. sys.default_constraints AS dc ON
  663. OBJECT_ID(QUOTENAME(c.table_schema) + '.' + QUOTENAME(c.table_name)) = dc.parent_object_id AND
  664. COLUMNPROPERTY(OBJECT_ID(QUOTENAME(c.table_schema) + '.' + QUOTENAME(c.table_name)), c.column_name, 'ColumnId') = dc.parent_column_id
  665. WHERE
  666. LOWER(c.table_schema) = %s AND
  667. LOWER(c.table_name) = %s AND
  668. LOWER(c.column_name) = %s AND
  669. c.table_catalog = DB_NAME()",
  670. strtolower($schema),
  671. strtolower($table),
  672. strtolower($column)
  673. );
  674. if (!$constraint->countReturnedRows()) {
  675. return NULL;
  676. }
  677. $row = $constraint->fetchRow();
  678. return array(
  679. 'name' => $row['name'],
  680. 'definition' => $row['definition']
  681. );
  682. }
  683. /**
  684. * Returns the primary key constraints for a table
  685. *
  686. * @param string $schema The schema the table is inside of
  687. * @param string $table The table to get the constraint for
  688. * @return array|NULL An associative array with the keys `name`, `columns` and `autoincrement` or `NULL`
  689. */
  690. private function getMSSQLPrimaryKeyConstraint($schema, $table)
  691. {
  692. $column_info = $this->database->query(
  693. "SELECT
  694. kcu.constraint_name AS constraint_name,
  695. LOWER(kcu.column_name) AS column_name,
  696. CASE
  697. WHEN
  698. COLUMNPROPERTY(OBJECT_ID(QUOTENAME(c.table_schema) + '.' + QUOTENAME(c.table_name)), c.column_name, 'IsIdentity') = 1 AND
  699. OBJECTPROPERTY(OBJECT_ID(QUOTENAME(c.table_schema) + '.' + QUOTENAME(c.table_name)), 'IsMSShipped') = 0
  700. THEN '1'
  701. ELSE '0'
  702. END AS auto_increment
  703. FROM
  704. information_schema.table_constraints AS con INNER JOIN
  705. information_schema.key_column_usage AS kcu ON
  706. con.table_name = kcu.table_name AND
  707. con.table_schema = kcu.table_schema AND
  708. con.constraint_name = kcu.constraint_name INNER JOIN
  709. information_schema.columns AS c ON
  710. c.table_name = kcu.table_name AND
  711. c.table_schema = kcu.table_schema AND
  712. c.column_name = kcu.column_name
  713. WHERE
  714. con.constraint_type = 'PRIMARY KEY' AND
  715. LOWER(con.table_schema) = %s AND
  716. LOWER(con.table_name) = %s AND
  717. con.table_catalog = DB_NAME()",
  718. strtolower($schema),
  719. strtolower($table)
  720. );
  721. if (!$column_info->countReturnedRows()) {
  722. return NULL;
  723. }
  724. $output = array(
  725. 'columns' => array()
  726. );
  727. foreach ($column_info as $row) {
  728. $output['columns'][] = $row['column_name'];
  729. $output['name'] = $row['constraint_name'];
  730. $output['autoincrement'] = (boolean) $row['auto_increment'];
  731. }
  732. return $output;
  733. }
  734. /**
  735. * Returns the unique constraints that a column is part of
  736. *
  737. * @param string $schema The schema the column is inside of
  738. * @param string $table The table the column is part of
  739. * @param string $column The column name
  740. * @return array An associative array of constraint_name => columns
  741. */
  742. private function getMSSQLUniqueConstraints($schema, $table, $column)
  743. {
  744. $constraint_columns = $this->database->query(
  745. "SELECT
  746. c.constraint_name,
  747. LOWER(kcu.column_name) AS column_name
  748. FROM
  749. information_schema.table_constraints AS c INNER JOIN
  750. information_schema.key_column_usage AS kcu ON
  751. c.table_name = kcu.table_name AND
  752. c.constraint_name = kcu.constraint_name
  753. WHERE
  754. c.constraint_name IN (
  755. SELECT
  756. c.constraint_name
  757. FROM
  758. information_schema.table_constraints AS c INNER JOIN
  759. information_schema.key_column_usage AS kcu ON
  760. c.table_name = kcu.table_name AND
  761. c.constraint_name = kcu.constraint_name
  762. WHERE
  763. c.constraint_type = 'UNIQUE' AND
  764. LOWER(c.table_schema) = %s AND
  765. LOWER(c.table_name) = %s AND
  766. LOWER(kcu.column_name) = %s AND
  767. c.table_catalog = DB_NAME()
  768. ) AND
  769. LOWER(c.table_schema) = %s AND
  770. c.table_catalog = DB_NAME()
  771. ORDER BY
  772. c.constraint_name
  773. ",
  774. strtolower($schema),
  775. strtolower($table),
  776. strtolower($column),
  777. strtolower($schema)
  778. );
  779. $unique_constraints = array();
  780. foreach ($constraint_columns as $row) {
  781. if (!isset($unique_constraints[$row['constraint_name']])) {
  782. $unique_constraints[$row['constraint_name']] = array();
  783. }
  784. $unique_constraints[$row['constraint_name']][] = $row['column_name'];
  785. }
  786. return $unique_constraints;
  787. }
  788. /**
  789. * Returns info about all foreign keys that involve the table and one of the columns specified
  790. *
  791. * @param string $table The table
  792. * @param string|array $columns The column, or an array of valid column names
  793. * @column array An array of associative arrays containing the keys `constraint_name`, `table`, `column`, `foreign_table` and `foreign_column`
  794. */
  795. private function getMySQLForeignKeys($table, $columns)
  796. {
  797. if (is_string($columns)) {
  798. $columns = array($columns);
  799. }
  800. $columns = array_map('strtolower', $columns);
  801. $tables = $this->getMySQLTables();
  802. $keys = array();
  803. foreach ($tables as $_table) {
  804. $row = $this->database->query("SHOW CREATE TABLE %r", $_table)->fetchRow();
  805. preg_match_all(
  806. '#CONSTRAINT\s+"(\w+)"\s+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))?#',
  807. $row['Create Table'],
  808. $matches,
  809. PREG_SET_ORDER
  810. );
  811. foreach ($matches as $match) {
  812. $points_to_column = strtolower($match[3]) == strtolower($table) && in_array(strtolower($match[4]), $columns);
  813. $is_column = strtolower($_table) == strtolower($table) && in_array(strtolower($match[2]), $columns);
  814. if (!$points_to_column && !$is_column) {
  815. continue;
  816. }
  817. $temp = array(
  818. 'constraint_name' => $match[1],
  819. 'table' => $_table,
  820. 'column' => $match[2],
  821. 'foreign_table' => $match[3],
  822. 'foreign_column' => $match[4],
  823. 'on_delete' => 'NO ACTION',
  824. 'on_update' => 'NO ACTION'
  825. );
  826. if (!empty($match[5])) {
  827. $temp['on_delete'] = $match[5];
  828. }
  829. if (!empty($match[6])) {
  830. $temp['on_update'] = $match[6];
  831. }
  832. $keys[] = $temp;
  833. }
  834. }
  835. return $keys;
  836. }
  837. /**
  838. * Returns a list of all tables in the database
  839. *
  840. * @return array An array of table names
  841. */
  842. private function getMySQLTables()
  843. {
  844. if (!isset($this->schema_info['version'])) {
  845. $version = $this->database->query("SELECT version()")->fetchScalar();
  846. $this->schema_info['version'] = substr($version, 0, strpos($version, '.'));
  847. }
  848. if ($this->schema_info['version'] <= 4) {
  849. $sql = 'SHOW TABLES';
  850. } else {
  851. $sql = "SHOW FULL TABLES WHERE table_type = 'BASE TABLE'";
  852. }
  853. $result = $this->database->query($sql);
  854. $tables = array();
  855. foreach ($result as $row) {
  856. $keys = array_keys($row);
  857. $tables[] = $row[$keys[0]];
  858. }
  859. return $tables;
  860. }
  861. /**
  862. * Returns an an array of the column name for a table
  863. *
  864. * @param string $table The table to retrieve the column names for
  865. * @return array The column names for the table
  866. */
  867. private function getSQLiteColumns($table)
  868. {
  869. $create_sql = $this->getSQLiteCreateTable($table);
  870. return array_keys(self::parseSQLiteColumnDefinitions($create_sql));
  871. }
  872. /**
  873. * Returns the SQL used to create a table
  874. *
  875. * @param string $table The table to retrieve the `CREATE TABLE` statement for
  876. * @return string The `CREATE TABLE` SQL statement
  877. */
  878. private function getSQLiteCreateTable($table)
  879. {
  880. if (!isset($this->schema_info['sqlite_create_tables'])) {
  881. $this->getSQLiteTables();
  882. }
  883. if (!isset($this->schema_info['sqlite_create_tables'][$table])) {
  884. return NULL;
  885. }
  886. return $this->schema_info['sqlite_create_tables'][$table];
  887. }
  888. /**
  889. * Returns a list of all foreign keys that reference the table, and optionally, column specified
  890. *
  891. * @param string $table All foreign keys returned will point to this table
  892. * @param string $column Only foreign keys pointing to this column will be returned
  893. * @return array An array of arrays containing they keys: `table`, `column`, `foreign_table`, `foreign_column`, `on_delete` and `on_update`
  894. */
  895. private function getSQLiteForeignKeys($table, $column=NULL)
  896. {
  897. $output = array();
  898. foreach ($this->getSQLiteTables() as $_table) {
  899. $create_sql = $this->getSQLiteCreateTable($_table);
  900. if (stripos($create_sql, 'references') === FALSE) {
  901. continue;
  902. }
  903. preg_match_all('#(?<=,|\(|\*/|\n)\s*[`"\[\']?(\w+)[`"\]\']?\s+(?:[a-z]+)(?:\([^)]*\))?(?:(?:\s+NOT\s+NULL)|(?:\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*(?:,|/\*|(?:--[^\n]*\n)?\s*(?=\)))#mis', $create_sql, $matches, PREG_SET_ORDER);
  904. preg_match_all('#(?<=,|\(|\*/|\n)\s*(?:CONSTRAINT\s+["`\[]?\w+["`\]]?\s+)?FOREIGN\s+KEY\s*\(?\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*(?:,|/\*|(?:--[^\n]*\n)?\s*(?=\)))#mis', $create_sql, $matches2, PREG_SET_ORDER);
  905. foreach (array_merge($matches, $matches2) as $match) {
  906. $_column = $match[1];
  907. $foreign_table = $match[2];
  908. $foreign_column = $match[3];
  909. $on_delete = empty($match[4]) ? 'RESTRICT' : $match[4];
  910. $on_update = empty($match[5]) ? 'RESTRICT' : $match[5];
  911. if ($foreign_table != $table || ($column !== NULL && $column != $foreign_column)) {
  912. continue;
  913. }
  914. if (!$on_delete) {
  915. $on_delete = 'RESTRICT';
  916. }
  917. if (!$on_update) {
  918. $on_update = 'RESTRICT';
  919. }
  920. $output[] = array(
  921. 'table' => $_table,
  922. 'column' => $_column,
  923. 'foreign_table' => $foreign_table,
  924. 'foreign_column' => $foreign_column,
  925. 'on_delete' => $on_delete,
  926. 'on_update' => $on_update
  927. );
  928. }
  929. }
  930. return $output;
  931. }
  932. /**
  933. * Returns the indexes in the current SQLite database
  934. *
  935. * @return array An associative array with the key being the index name and the value an associative arrays, each containing the keys: `table`, `sql`
  936. */
  937. private function getSQLiteIndexes($table=NULL)
  938. {
  939. if (!isset($this->schema_info['sqlite_indexes'])) {
  940. $this->schema_info['sqlite_indexes'] = array();
  941. $rows = $this->database->query(
  942. "SELECT tbl_name AS \"table\", name, sql FROM sqlite_master WHERE type = 'index' AND sql <> ''"
  943. )->fetchAllRows();
  944. foreach ($rows as $row) {
  945. $this->schema_info['sqlite_indexes'][$row['name']] = array(
  946. 'table' => $row['table'],
  947. 'sql' => $row['sql']
  948. );
  949. }
  950. }
  951. $output = $this->schema_info['sqlite_indexes'];
  952. if ($table) {
  953. $new_output = array();
  954. foreach ($output as $name => $index) {
  955. if ($index['table'] != $table) {
  956. continue;
  957. }
  958. $new_output[$name] = $index;
  959. }
  960. $output = $new_output;
  961. }
  962. return $output;
  963. }
  964. /**
  965. * Returns the tables in the current SQLite database
  966. *
  967. * @return array
  968. */
  969. private function getSQLiteTables()
  970. {
  971. if (!isset($this->schema_info['sqlite_create_tables'])) {
  972. $this->schema_info['sqlite_create_tables'] = array();
  973. $res = $this->database->query(
  974. "SELECT name, sql FROM sqlite_master WHERE type = 'table'"
  975. )->fetchAllRows();
  976. foreach ($res as $row) {
  977. $this->schema_info['sqlite_create_tables'][$row['name']] = $row['sql'];
  978. }
  979. }
  980. $tables = array_keys($this->schema_info['sqlite_create_tables']);
  981. natcasesort($tables);
  982. return $tables;
  983. }
  984. /**
  985. * Returns the triggers in the current SQLite database
  986. *
  987. * @return array An associative array with the key being the trigger name and the value an associative arrays, each containing the keys: `table`, `sql`
  988. */
  989. private function getSQLiteTriggers($exclude_table=NULL)
  990. {
  991. if (!isset($this->schema_info['sqlite_triggers'])) {
  992. $this->schema_info['sqlite_triggers'] = array();
  993. $rows = $this->database->query(
  994. "SELECT tbl_name AS \"table\", name, sql FROM sqlite_master WHERE type = 'trigger'"
  995. )->fetchAllRows();
  996. foreach ($rows as $row) {
  997. $this->schema_info['sqlite_triggers'][$row['name']] = array(
  998. 'table' => $row['table'],
  999. 'sql' => $row['sql']
  1000. );
  1001. }
  1002. }
  1003. $output = $this->schema_info['sqlite_triggers'];
  1004. if ($exclude_table) {
  1005. $new_output = array();
  1006. foreach ($output as $name => $trigger) {
  1007. if ($trigger['table'] == $exclude_table) {
  1008. continue;
  1009. }
  1010. $new_output[$name] = $trigger;
  1011. }
  1012. $output = $new_output;
  1013. }
  1014. return $output;
  1015. }
  1016. /**
  1017. * Removes the SQLite indexes from the internal schema tracker
  1018. *
  1019. * @param string $table The table to remove the indexes for
  1020. * @return void
  1021. */
  1022. private function removeSQLiteIndexes($table)
  1023. {
  1024. if (!isset($this->schema_info['sqlite_indexes'])) {
  1025. return;
  1026. }
  1027. $indexes = $this->schema_info['sqlite_indexes'];
  1028. $new_indexes = array();
  1029. foreach ($indexes as $name => $index) {
  1030. if ($index['table'] == $table) {
  1031. continue;
  1032. }
  1033. $new_indexes[$name] = $index;
  1034. }
  1035. $this->schema_info['sqlite_indexes'] = $new_indexes;
  1036. }
  1037. /**
  1038. * Removes a table from the list of SQLite table
  1039. *
  1040. * @param string $table The table to remove
  1041. * @return void
  1042. */
  1043. private function removeSQLiteTable($table)
  1044. {
  1045. if (!isset($this->schema_info['sqlite_create_tables'])) {
  1046. return;
  1047. }
  1048. unset($this->schema_info['sqlite_create_tables'][$table]);
  1049. }
  1050. /**
  1051. * Removes a SQLite trigger from the internal schema tracker
  1052. *
  1053. * @param string $name The trigger name
  1054. * @return void
  1055. */
  1056. private function removeSQLiteTrigger($name)
  1057. {
  1058. if (!isset($this->schema_info['sqlite_triggers'])) {
  1059. return;
  1060. }
  1061. unset($this->schema_info['sqlite_triggers'][$name]);
  1062. }
  1063. /**
  1064. * Removes the SQLite triggers for a table from the internal schema tracker
  1065. *
  1066. * @param string $table The table to remove the triggers for
  1067. * @return void
  1068. */
  1069. private function removeSQLiteTriggers($table)
  1070. {
  1071. if (!isset($this->schema_info['sqlite_triggers'])) {
  1072. return;
  1073. }
  1074. $triggers = $this->schema_info['sqlite_triggers'];
  1075. $new_triggers = array();
  1076. foreach ($triggers as $name => $trigger) {
  1077. if ($trigger['table'] == $table) {
  1078. continue;
  1079. }
  1080. $new_triggers[$name] = $trigger;
  1081. }
  1082. $this->schema_info['sqlite_triggers'] = $new_triggers;
  1083. }
  1084. /**
  1085. * Throws an fSQLException with the information provided
  1086. *
  1087. * @param string $error The error that occured
  1088. * @param string $sql The SQL statement that caused the error
  1089. * @return void
  1090. */
  1091. private function throwException($error, $sql)
  1092. {
  1093. $db_type_map = array(
  1094. 'db2' => 'DB2',
  1095. 'mssql' => 'MSSQL',
  1096. 'mysql' => 'MySQL',
  1097. 'oracle' => 'Oracle',
  1098. 'postgresql' => 'PostgreSQL',
  1099. 'sqlite' => 'SQLite'
  1100. );
  1101. throw new fSQLException(
  1102. '%1$s error (%2$s) in %3$s',
  1103. $db_type_map[$this->database->getType()],
  1104. $error,
  1105. $sql
  1106. );
  1107. }
  1108. /**
  1109. * Translates a Flourish SQL DDL statement into the dialect for the current database
  1110. *
  1111. * @internal
  1112. *
  1113. * @param string $sql The SQL statement to translate
  1114. * @param array &$rollback_statements SQL statements to rollback the returned SQL statements if something goes wrong - only applicable for MySQL `ALTER TABLE` statements
  1115. * @return array An array containing the translated `$sql` statement and an array of extra statements
  1116. */
  1117. public function translate($sql, &$rollback_statements=NULL)
  1118. {
  1119. $reset_sqlite_info = FALSE;
  1120. if (!isset($this->schema_info['sqlite_schema_info'])) {
  1121. $this->schema_info['sqlite_schema_info'] = TRUE;
  1122. $reset_sqlite_info = TRUE;
  1123. }
  1124. $new_sql = $sql;
  1125. $exception = NULL;
  1126. try {
  1127. $extra_statements = array();
  1128. if (!is_array($rollback_statements)) {
  1129. $rollback_statements = array();
  1130. }
  1131. $new_sql = $this->translateCreateTableStatements($new_sql, $extra_statements);
  1132. $new_sql = $this->translateAlterTableStatements($new_sql, $extra_statements, $rollback_statements);
  1133. if ($this->database->getType() == 'sqlite') {
  1134. $new_sql = $this->translateSQLiteDropTableStatements($new_sql, $extra_statements);
  1135. }
  1136. } catch (Exception $e) {
  1137. $exception = $e;
  1138. }
  1139. if ($reset_sqlite_info) {
  1140. unset($this->schema_info['sqlite_schema_info']);
  1141. unset($this->schema_info['sqlite_create_tables']);
  1142. unset($this->schema_info['sqlite_indexes']);
  1143. unset($this->schema_info['sqlite_triggers']);
  1144. }
  1145. if ($exception) {
  1146. throw $exception;
  1147. }
  1148. return array($new_sql, $extra_statements);
  1149. }
  1150. /**
  1151. * Translates the structure of `CREATE TABLE` statements to the database specific syntax
  1152. *
  1153. * @param string $sql The SQL to translate
  1154. * @param array &$extra_statements Any extra SQL statements that need to be added
  1155. * @param array &$rollback_statements SQL statements to rollback `$sql` and `$extra_statements` if something goes wrong
  1156. * @return string The translated SQL
  1157. */
  1158. private function translateAlterTableStatements($sql, &$extra_statements, &$rollback_statements=NULL)
  1159. {
  1160. if (!preg_match('#^\s*ALTER\s+TABLE\s+(\w+|"[^"]+")\s+(.*)$#siD', $sql, $table_matches) && !preg_match('#^\s*COMMENT\s+ON\s+COLUMN\s+"?((?:\w+"?\."?)?\w+)"?\.("?\w+"?\s+IS\s+(?:\'.*\'|%\d+\$s))\s*$#Dis', $sql, $table_matches)) {
  1161. return $sql;
  1162. }
  1163. $statement = $table_matches[2];
  1164. $data = array(
  1165. 'table' => $table_matches[1]
  1166. );
  1167. if (preg_match('#"?(\w+)"?\s+IS\s+(\'.*\'|:string\w+|%\d+\$s)\s*$#Dis', $statement, $statement_matches)) {
  1168. $data['type'] = 'column_comment';
  1169. $data['column_name'] = trim($statement_matches[1], '"');
  1170. $data['comment'] = $statement_matches[2];
  1171. } elseif (preg_match('#RENAME\s+TO\s+(\w+|"[^"]+")\s*$#isD', $statement, $statement_matches)) {
  1172. $data['type'] = 'rename_table';
  1173. $data['new_table_name'] = trim($statement_matches[1], '"');
  1174. } elseif (preg_match('#RENAME\s+COLUMN\s+(\w+|"[^"]+")\s+TO\s+(\w+|"[^"]+")\s*$#isD', $statement, $statement_matches)) {
  1175. $data['type'] = 'rename_column';
  1176. $data['column_name'] = trim($statement_matches[1], '"');
  1177. $data['new_column_name'] = trim($statement_matches[2], '"');
  1178. } elseif (preg_match('#ADD\s+COLUMN\s+("?(\w+)"?.*)$#isD', $statement, $statement_matches)) {
  1179. $data['type'] = 'add_column';
  1180. $data['column_definition'] = $statement_matches[1];
  1181. $data['column_name'] = $statement_matches[2];
  1182. } elseif (preg_match('#DROP\s+COLUMN\s+(\w+|"[^"]+")\s*$#isD', $statement, $statement_matches)) {
  1183. $data['type'] = 'drop_column';
  1184. $data['column_name'] = trim($statement_matches[1], '"');
  1185. } elseif (preg_match('#ALTER\s+COLUMN\s+(\w+|"[^"]+")\s+TYPE\s+(.*?)\s*$#isD', $statement, $statement_matches)) {
  1186. $data['type'] = 'alter_type';
  1187. $data['column_name'] = trim($statement_matches[1], '"');
  1188. $data['data_type'] = $statement_matches[2];
  1189. } elseif (preg_match('#ALTER\s+COLUMN\s+(\w+|"[^"]+")\s+DROP\s+DEFAULT\s*$#isD', $statement, $statement_matches)) {
  1190. $data['type'] = 'drop_default';
  1191. $data['column_name'] = trim($statement_matches[1], '"');
  1192. } elseif (preg_match('#ALTER\s+COLUMN\s+(\w+|"[^"]+")\s+SET\s+DEFAULT\s+(.*?)\s*$#isD', $statement, $statement_matches)) {
  1193. $data['type'] = 'set_default';
  1194. $data['column_name'] = trim($statement_matches[1], '"');
  1195. $data['default_value'] = trim($statement_matches[2], '"');
  1196. } elseif (preg_match('#ALTER\s+COLUMN\s+(\w+|"[^"]+")\s+DROP\s+NOT\s+NULL\s*$#isD', $statement, $statement_matches)) {
  1197. $data['type'] = 'drop_not_null';
  1198. $data['column_name'] = trim($statement_matches[1], '"');
  1199. } elseif (preg_match('#ALTER\s+COLUMN\s+(\w+|"[^"]+")\s+SET\s+NOT\s+NULL(\s+DEFAULT\s+(.*))?\s*$#isD', $statement, $statement_matches)) {
  1200. $data['type'] = 'set_not_null';
  1201. $data['column_name'] = trim($statement_matches[1], '"');
  1202. if (isset($statement_matches[2])) {
  1203. $data['default'] = $statement_matches[3];
  1204. }
  1205. } elseif (preg_match('#ALTER\s+COLUMN\s+(\w+|"[^"]+")\s+DROP\s+CHECK\s*$#isD', $statement, $statement_matches)) {
  1206. $data['type'] = 'drop_check_constraint';
  1207. $data['column_name'] = trim($statement_matches[1], '"');
  1208. } elseif (preg_match('#ALTER\s+COLUMN\s+(\w+|"[^"]+")\s+SET\s+CHECK\s+IN\s+(\(.*?\))\s*$#isD', $statement, $statement_matches)) {
  1209. $data['type'] = 'set_check_constraint';
  1210. $data['column_name'] = trim($statement_matches[1], '"');
  1211. $data['constraint'] = ' CHECK(' . $statement_matches[1] . ' IN ' . $statement_matches[2] . ')';
  1212. } elseif (preg_match('#DROP\s+PRIMARY\s+KEY\s*$#isD', $statement, $statement_matches)) {
  1213. $data['type'] = 'drop_primary_key';
  1214. } elseif (preg_match('#ADD\s+PRIMARY\s+KEY\s*\(\s*([^\)]+?)\s*\)(\s+AUTOINCREMENT)?\s*$#isD', $statement, $statement_matches)) {
  1215. $data['type'] = 'add_primary_key';
  1216. $data['column_names'] = preg_split(
  1217. '#"?\s*,\s*"?#',
  1218. trim($statement_matches[1], '"'),
  1219. -1,
  1220. PREG_SPLIT_NO_EMPTY
  1221. );
  1222. $data['autoincrement'] = count($data['column_names']) == 1 && !empty($statement_matches[2]);
  1223. if (count($data['column_names']) == 1) {
  1224. $data['column_name'] = reset($data['column_names']);
  1225. }
  1226. } elseif (preg_match('#DROP\s+FOREIGN\s+KEY\s*\(\s*(\w+|"[^"]+")\s*\)\s*$#isD', $statement, $statement_matches)) {
  1227. $data['type'] = 'drop_foreign_key';
  1228. $data['column_name'] = trim($statement_matches[1], '"');
  1229. } elseif (preg_match('#ADD\s+FOREIGN\s+KEY\s*\((\w+|"[^"]+")\)\s+REFERENCES\s+("?(\w+)"?\s*\(\s*"?(\w+)"?\s*\)\s*.*)\s*$#isD', $statement, $statement_matches)) {
  1230. $data['type'] = 'add_foreign_key';
  1231. $data['column_name'] = trim($statement_matches[1], '"');
  1232. $data['references'] = $statement_matches[2];
  1233. $data['foreign_table'] = self::unescapeIdentifier($statement_matches[3]);
  1234. $data['foreign_column'] = self::unescapeIdentifier($statement_matches[4]);
  1235. } elseif (preg_match('#DROP\s+UNIQUE\s*\(\s*([^\)]+?)\s*\)\s*$#isD', $statement, $statement_matches)) {
  1236. $data['type'] = 'drop_unique';
  1237. $data['column_names'] = preg_split(
  1238. '#"?\s*,\s*"?#',
  1239. trim($statement_matches[1], '"'),
  1240. -1,
  1241. PREG_SPLIT_NO_EMPTY
  1242. );
  1243. if (count($data['column_names']) == 1) {
  1244. $data['column_name'] = reset($data['column_names']);
  1245. }
  1246. } elseif (preg_match('#ADD\s+UNIQUE\s*\(\s*([^\)]+?)\s*\)\s*$#isD', $statement, $statement_matches)) {
  1247. $data['type'] = 'add_unique';
  1248. $data['column_names'] = preg_split(
  1249. '#"?\s*,\s*"?#',
  1250. trim($statement_matches[1], '"'),
  1251. -1,
  1252. PREG_SPLIT_NO_EMPTY
  1253. );
  1254. if (count($data['column_names']) == 1) {
  1255. $data['column_name'] = reset($data['column_names']);
  1256. }
  1257. } else {
  1258. return $sql;
  1259. }
  1260. $data['table'] = self::unescapeIdentifier($data['table']);
  1261. if (isset($data['new_table_name'])) {
  1262. $data['new_table_name'] = self::unescapeIdentifier($data['new_table_name']);
  1263. }
  1264. if (isset($data['column_name'])) {
  1265. $data['column_name'] = self::unescapeIdentifier($data['column_name']);
  1266. }
  1267. if (isset($data['column_names'])) {
  1268. $data['column_names'] = array_map(
  1269. array('fSQLSchemaTranslation', 'unescapeIdentifier'),
  1270. $data['column_names']
  1271. );
  1272. }
  1273. if (isset($data['new_column_name'])) {
  1274. $data['new_column_name'] = self::unescapeIdentifier($data['new_column_name']);
  1275. }
  1276. if ($this->database->getType() == 'db2') {
  1277. $sql = $this->translateDB2AlterTableStatements($sql, $extra_statements, $data);
  1278. }
  1279. if ($this->database->getType() == 'mssql') {
  1280. $sql = $this->translateMSSQLAlterTableStatements($sql, $extra_statements, $data);
  1281. }
  1282. if ($this->database->getType() == 'mysql') {
  1283. $sql = $this->translateMySQLAlterTableStatements($sql, $extra_statements, $rollback_statements, $data);
  1284. }
  1285. if ($this->database->getType() == 'oracle') {
  1286. $sql = $this->translateOracleAlterTableStatements($sql, $extra_statements, $data);
  1287. }
  1288. if ($this->database->getType() == 'postgresql') {
  1289. $sql = $this->translatePostgreSQLAlterTableStatements($sql, $extra_statements, $data);
  1290. }
  1291. if ($this->database->getType() == 'sqlite') {
  1292. if ($data['type'] == 'rename_table') {
  1293. $sql = $this->translateSQLiteRenameTableStatements($sql, $extra_statements, $data);
  1294. } else {
  1295. $sql = $this->translateSQLiteAlterTableStatements($sql, $extra_statements, $data);
  1296. }
  1297. }
  1298. // All databases except for MySQL and Oracle support transactions around data definition queries
  1299. // All of the Oracle statements will fail on the first query, if at all, so we don't need to
  1300. // worry too much. MySQL is a huge pain though.
  1301. if (!in_array($this->database->getType(), array('mysql', 'oracle'))) {
  1302. array_unshift($extra_statements, $sql);
  1303. if (!$this->database->isInsideTransaction()) {
  1304. $sql = "BEGIN";
  1305. $extra_statements[] = "COMMIT";
  1306. $rollback_statements[] = "ROLLBACK";
  1307. } else {
  1308. $sql = array_shift($extra_statements);
  1309. }
  1310. }
  1311. return $sql;
  1312. }/**
  1313. * Translates the structure of `CREATE TABLE` statements to the database specific syntax
  1314. *
  1315. * @param string $sql The SQL to translate
  1316. * @param array &$extra_statements Any extra SQL statements that need to be added
  1317. * @return string The translated SQL
  1318. */
  1319. private function translateCreateTableStatements($sql, &$extra_statements)
  1320. {
  1321. if (!preg_match('#^\s*CREATE\s+TABLE\s+["`\[]?(\w+)["`\]]?#i', $sql, $table_matches) ) {
  1322. return $sql;
  1323. }
  1324. $table = $table_matches[1];
  1325. $sql = $this->translateDataTypes($sql);
  1326. if ($this->database->getType() == 'db2') {
  1327. $regex = array(
  1328. '#("[^"]+"|\w+)\s+boolean(.*?)(,|\)|$)#im' => '\1 CHAR(1)\2 CHECK(\1 IN (\'0\', \'1\'))\3',
  1329. '#\binteger(?:\(\d+\))?\s+autoincrement\b#i' => 'INTEGER GENERATED BY DEFAULT AS IDENTITY',
  1330. '#\)\s*$#D' => ') CCSID UNICODE'
  1331. );
  1332. $sql = preg_replace(array_keys($regex), array_values($regex), $sql);
  1333. // DB2 only supports some ON UPDATE clauses
  1334. $sql = preg_replace('#(\sON\s+UPDATE\s+(CASCADE|SET\s+NULL))#i', '', $sql);
  1335. } elseif ($this->database->getType() == 'mssql') {
  1336. $sql = preg_replace('#\binteger(?:\(\d+\))?\s+autoincrement\b#i', 'INTEGER IDENTITY', $sql);
  1337. } elseif ($this->database->getType() == 'mysql') {
  1338. $sql = preg_replace('#\binteger(?:\(\d+\))?\s+autoincrement\b#i', 'INTEGER AUTO_INCREMENT', $sql);
  1339. // Make sure MySQL uses InnoDB tables, translate check constraints to enums and fix column-level foreign key definitions
  1340. preg_match_all('#(?<=,|\()\s*(["`]?\w+["`]?)\s+(?:[a-z]+)(?:\(\d+\))?(?:\s+unsigned|\s+zerofill|\s+character\s+set\s+[^ ]+|\s+collate\s+[^ ]+|\s+NULL|\s+NOT\s+NULL|(\s+DEFAULT\s+(?:[^, \']*|\'(?:\'\'|[^\']+)*\'))|\s+UNIQUE|\s+PRIMARY\s+KEY|(\s+CHECK\s*\(\w+\s+IN\s+(\(\s*(?:(?:[^, \']+|\'(?:\'\'|[^\']+)*\')\s*,\s*)*\s*(?:[^, \']+|\'(?:\'\'|[^\']+)*\')\))\)))*(\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*(,|\s*(?=\))|$)#miD', $sql, $matches, PREG_SET_ORDER);
  1341. foreach ($matches as $match) {
  1342. // MySQL has the enum data type, so we switch check constraints to that
  1343. if (!empty($match[3])) {
  1344. $replacement = "\n " . $match[1] . ' enum' . $match[4] . $match[2] . $match[5] . $match[6];
  1345. $sql = str_replace($match[0], $replacement, $sql);
  1346. // This allows us to do a str_replace below for converting foreign key syntax
  1347. $match[0] = $replacement;
  1348. }
  1349. // Even InnoDB table types don't allow specify foreign key constraints in the column
  1350. // definition, so we move it to its own definition on the next line
  1351. if (!empty($match[5])) {
  1352. $updated_match_0 = str_replace($match[5], ",\nFOREIGN KEY (" . $match[1] . ') ' . $match[5], $match[0]);
  1353. $sql = str_replace($match[0], $updated_match_0, $sql);
  1354. }
  1355. }
  1356. $sql = preg_replace('#\)\s*;?\s*$#D', ')ENGINE=InnoDB, CHARACTER SET utf8', $sql);
  1357. } elseif ($this->database->getType() == 'oracle') {
  1358. // If NOT NULL DEFAULT '' is present, both are removed since Oracle converts '' to NULL
  1359. $sql = preg_replace('#(\bNOT\s+NULL\s+DEFAULT\s+\'\'|\bDEFAULT\s+\'\'\s+NOT\s+NULL)#', '', $sql);
  1360. // Oracle does not support ON UPDATE clauses
  1361. $sql = preg_replace('#(\sON\s+UPDATE\s+(CASCADE|SET\s+NULL|NO\s+ACTION|RESTRICT))#i', '', $sql);
  1362. // Create sequences and triggers for Oracle
  1363. if (stripos($sql, 'autoincrement') !== FALSE && preg_match('#(?<=,|\(|^)\s*("?\w+"?)\s+(?:[a-z]+)(?:\((?:\d+)\))?.*?\bAUTOINCREMENT\b[^,\)]*(?:,|\s*(?=\)))#mi', $sql, $matches)) {
  1364. $column = $matches[1];
  1365. $table_column = substr(str_replace('"' , '', $table) . '_' . str_replace('"', '', $column), 0, 26);
  1366. $sequence_name = $table_column . '_seq';
  1367. $trigger_name = $table_column . '_trg';
  1368. $sequence = 'CREATE SEQUENCE ' . $sequence_name;
  1369. $trigger = 'CREATE OR REPLACE TRIGGER '. $trigger_name . "\n";
  1370. $trigger .= "BEFORE INSERT ON " . $table . "\n";
  1371. $trigger .= "FOR EACH ROW\n";
  1372. $trigger .= "BEGIN\n";
  1373. $trigger .= " IF :new." . $column . " IS NULL THEN\n";
  1374. $trigger .= " SELECT " . $sequence_name . ".nextval INTO :new." . $column . " FROM dual;\n";
  1375. $trigger .= " END IF;\n";
  1376. $trigger .= "END;";
  1377. $extra_statements[] = $sequence;
  1378. $extra_statements[] = $trigger;
  1379. $sql = preg_replace('#\s+autoincrement\b#i', '', $sql);
  1380. }
  1381. } elseif ($this->database->getType() == 'postgresql') {
  1382. $sql = preg_replace('#\binteger(?:\(\d+\))?\s+autoincrement\b#i', 'SERIAL', $sql);
  1383. } elseif ($this->database->getType() == 'sqlite') {
  1384. // Data type translation
  1385. if (version_compare($this->database->getVersion(), 3, '>=')) {
  1386. $sql = preg_replace('#\binteger(?:\(\d+\))?\s+autoincrement\s+primary\s+key\b#i', 'INTEGER PRIMARY KEY AUTOINCREMENT', $sql);
  1387. $sql = preg_replace("#datetime\(\s*CURRENT_TIMESTAMP\s*,\s*'localtime'\s*\)#i", 'CURRENT_TIMESTAMP', $sql);
  1388. } else {
  1389. $sql = preg_replace('#\binteger(?:\(\d+\))?\s+autoincrement\s+primary\s+key\b#i', 'INTEGER PRIMARY KEY', $sql);
  1390. $sql = preg_replace('#CURRENT_TIMESTAMP\(\)#i', 'CURRENT_TIMESTAMP', $sql);
  1391. }
  1392. // SQLite 3.6.19 and newer, may or may not have native foreign key support
  1393. $toggle_foreign_key_support = FALSE;
  1394. if (!isset($this->schema_info['foreign_keys_enabled'])) {
  1395. $toggle_foreign_key_support = TRUE;
  1396. $foreign_keys_res = $this->database->query('PRAGMA foreign_keys');
  1397. if ($foreign_keys_res->countReturnedRows() && $foreign_keys_res->fetchScalar()) {
  1398. $this->schema_info['foreign_keys_enabled'] = TRUE;
  1399. } else {
  1400. $this->schema_info['foreign_keys_enabled'] = FALSE;
  1401. }
  1402. }
  1403. // Create foreign key triggers for SQLite
  1404. if (stripos($sql, 'REFERENCES') !== FALSE && !$this->schema_info['foreign_keys_enabled']) {
  1405. preg_match_all('#(?:(?<=,|\(|\*/|\n)\s*(?:`|"|\[)?(\w+)(?:`|"|\])?\s+(?:[a-z]+)(?:\(\s*(?:\d+)(?:\s*,\s*(?:\d+))?\s*\))?(?:(\s+NOT\s+NULL)|(?:\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*(?:,(?:[ \t]*--[^\n]*\n)?|(?:--[^\n]*\n)?\s*(?=\))))|(?:(?<=,|\(|\*/|\n)\s*(?:CONSTRAINT\s+["`\[]?\w+["`\]]?\s+)?FOREIGN\s+KEY\s*\(?\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*(?:,(?:[ \t]*--[^\n]*\n)?|(?:--[^\n]*\n)?\s*(?=\))))#mis', $sql, $matches, PREG_SET_ORDER);
  1406. $not_null_columns = array();
  1407. foreach ($matches as $match) {
  1408. // Find all of the not null columns
  1409. if (!empty($match[2])) {
  1410. $not_null_columns[] = $match[1];
  1411. }
  1412. // If neither of these fields is matched, we don't have a foreign key
  1413. if (empty($match[3]) && empty($match[7])) {
  1414. continue;
  1415. }
  1416. if (!empty($match[1])) {
  1417. $column = $match[1];
  1418. $foreign_table = $match[3];
  1419. $foreign_column = $match[4];
  1420. $on_delete = isset($match[5]) ? $match[5] : NULL;
  1421. $on_update = isset($match[6]) ? $match[6] : NULL;
  1422. } else {
  1423. $column = $match[7];
  1424. $foreign_table = $match[8];
  1425. $foreign_column = $match[9];
  1426. $on_delete = isset($match[10]) ? $match[10] : NULL;
  1427. $on_update = isset($match[11]) ? $match[11] : NULL;
  1428. }
  1429. if (!$on_delete) {
  1430. $on_delete = 'NO ACTION';
  1431. }
  1432. if (!$on_update) {
  1433. $on_update = 'NO ACTION';
  1434. }
  1435. $this->createSQLiteForeignKeyTriggerValidInsertUpdate(
  1436. $extra_statements,
  1437. $table,
  1438. $column,
  1439. $foreign_table,
  1440. $foreign_column,
  1441. in_array($column, $not_null_columns)
  1442. );
  1443. $this->createSQLiteForeignKeyTriggerOnDelete(
  1444. $extra_statements,
  1445. $table,
  1446. $column,
  1447. $foreign_table,
  1448. $foreign_column,
  1449. $on_delete
  1450. );
  1451. $this->createSQLiteForeignKeyTriggerOnUpdate(
  1452. $extra_statements,
  1453. $table,
  1454. $column,
  1455. $foreign_table,
  1456. $foreign_column,
  1457. $on_update
  1458. );
  1459. }
  1460. }
  1461. if ($toggle_foreign_key_support) {
  1462. unset($this->schema_info['foreign_keys_enabled']);
  1463. }
  1464. }
  1465. return $sql;
  1466. }
  1467. /**
  1468. * Translates basic data types
  1469. *
  1470. * @param string $sql The SQL to translate
  1471. * @return string The translated SQL
  1472. */
  1473. private function translateDataTypes($sql)
  1474. {
  1475. switch ($this->database->getType()) {
  1476. case 'db2':
  1477. $regex = array(
  1478. '#\btext\b#i' => 'CLOB(1 G)',
  1479. '#\bblob\b(?!\()#i' => 'BLOB(2 G)'
  1480. );
  1481. break;
  1482. case 'mssql':
  1483. $regex = array(
  1484. '#\bblob\b#i' => 'IMAGE',
  1485. '#\btimestamp\b#i' => 'DATETIME',
  1486. '#\btime\b#i' => 'DATETIME',
  1487. '#\bdate\b#i' => 'DATETIME',
  1488. '#\bboolean\b#i' => 'BIT',
  1489. '#\bvarchar\b#i' => 'NVARCHAR',
  1490. '#\bchar\b#i' => 'NCHAR',
  1491. '#\btext\b#i' => 'NTEXT'
  1492. );
  1493. break;
  1494. case 'mysql':
  1495. $regex = array(
  1496. '#\btext\b#i' => 'LONGTEXT',
  1497. '#\bblob\b#i' => 'LONGBLOB',
  1498. '#\btimestamp\b#i' => 'DATETIME'
  1499. );
  1500. break;
  1501. case 'oracle':
  1502. $regex = array(
  1503. '#\bbigint\b#i' => 'INTEGER',
  1504. '#\bboolean\b#i' => 'NUMBER(1)',
  1505. '#\btext\b#i' => 'CLOB',
  1506. '#\bvarchar\b#i' => 'VARCHAR2',
  1507. '#\btime\b#i' => 'TIMESTAMP'
  1508. );
  1509. break;
  1510. case 'postgresql':
  1511. $regex = array(
  1512. '#\bblob\b#i' => 'BYTEA'
  1513. );
  1514. break;
  1515. case 'sqlite':
  1516. // SQLite doesn't have ALTER TABLE statements, so everything for data
  1517. // types is handled via ::translateCreateTableStatements()
  1518. $regex = array();
  1519. break;
  1520. }
  1521. return preg_replace(array_keys($regex), array_values($regex), $sql);
  1522. }
  1523. /**
  1524. * Translates Flourish SQL `ALTER TABLE` statements to the appropriate
  1525. * statements for DB2
  1526. *
  1527. * @param string $sql The SQL statements that will be executed against the database
  1528. * @param array &$extra_statements Any extra SQL statements required for DB2
  1529. * @param array $data Data parsed from the `ALTER TABLE` statement
  1530. * @return strin The modified SQL statement
  1531. */
  1532. private function translateDB2AlterTableStatements($sql, &$extra_statements, $data)
  1533. {
  1534. $data['schema'] = strtolower($this->database->getUsername());
  1535. $data['table_without_schema'] = $data['table'];
  1536. if (strpos($data['table'], '.') !== FALSE) {
  1537. list ($data['schema'], $data['table_without_schema']) = explode('.', $data['table']);
  1538. }
  1539. if (in_array($data['type'], array('drop_check_constraint', 'drop_primary_key', 'drop_foreign_key', 'drop_unique'))) {
  1540. $column_info = $this->database->query(
  1541. "SELECT
  1542. C.COLNAME
  1543. FROM
  1544. SYSCAT.TABLES AS T LEFT JOIN
  1545. SYSCAT.COLUMNS AS C ON
  1546. T.TABSCHEMA = C.TABSCHEMA AND
  1547. T.TABNAME = C.TABNAME AND
  1548. LOWER(C.COLNAME) = %s
  1549. WHERE
  1550. LOWER(T.TABSCHEMA) = %s AND
  1551. LOWER(T.TABNAME) = %s",
  1552. isset($data['column_name']) ? $data['column_name'] : '',
  1553. $data['schema'],
  1554. $data['table_without_schema']
  1555. );
  1556. if (!$column_info->countReturnedRows()) {
  1557. $this->throwException(
  1558. self::compose(
  1559. 'The table "%1$s" does not exist',
  1560. $data['table']
  1561. ),
  1562. $sql
  1563. );
  1564. }
  1565. if (isset($data['column_name'])) {
  1566. $row = $column_info->fetchRow();
  1567. if (!strlen($row['colname'])) {
  1568. $this->throwException(
  1569. self::compose(
  1570. 'The column "%1$s" does not exist in the table "%2$s"',
  1571. $data['column_name'],
  1572. $data['table']
  1573. ),
  1574. $sql
  1575. );
  1576. }
  1577. }
  1578. }
  1579. if ($data['type'] == 'column_comment') {
  1580. // DB2 handles the normalized syntax
  1581. } elseif ($data['type'] == 'rename_table') {
  1582. $foreign_key_constraints = $this->getDB2ForeignKeyConstraints(
  1583. $data['schema'],
  1584. $data['table_without_schema']
  1585. );
  1586. foreach ($foreign_key_constraints as $constraint) {
  1587. $extra_statements[] = $this->database->escape(
  1588. "ALTER TABLE %r DROP CONSTRAINT %r",
  1589. $constraint['schema'] . '.' . $constraint['table'],
  1590. $constraint['constraint_name']
  1591. );
  1592. }
  1593. $sql = $this->database->escape(
  1594. "RENAME TABLE %r TO %r",
  1595. $data['table'],
  1596. $data['new_table_name']
  1597. );
  1598. $extra_statements[] = $sql;
  1599. $sql = array_shift($extra_statements);
  1600. foreach ($foreign_key_constraints as $constraint) {
  1601. $extra_statements[] = $this->database->escape(
  1602. "ALTER TABLE %r ADD FOREIGN KEY (%r) REFERENCES %r(%r) ON DELETE " . $constraint['on_delete'] . ' ON UPDATE ' . $constraint['on_update'],
  1603. $constraint['schema'] . '.' . $constraint['table'],
  1604. $constraint['column'],
  1605. $constraint['foreign_schema'] . '.' . $data['new_table_name'],
  1606. $constraint['foreign_column']
  1607. );
  1608. }
  1609. } elseif ($data['type'] == 'rename_column') {
  1610. $data['column_name'] = strtolower($data['column_name']);
  1611. $foreign_key_constraints = $this->getDB2ForeignKeyConstraints(
  1612. $data['schema'],
  1613. $data['table_without_schema'],
  1614. $data['column_name']
  1615. );
  1616. foreach ($foreign_key_constraints as $constraint) {
  1617. $extra_statements[] = $this->database->escape(
  1618. "ALTER TABLE %r DROP CONSTRAINT %r",
  1619. $constraint['schema'] . '.' . $constraint['table'],
  1620. $constraint['constraint_name']
  1621. );
  1622. }
  1623. $unique_constraints = $this->getDB2UniqueConstraints(
  1624. $data['schema'],
  1625. $data['table_without_schema'],
  1626. $data['column_name']
  1627. );
  1628. foreach ($unique_constraints as $name => $columns) {
  1629. $extra_statements[] = $this->database->escape(
  1630. "ALTER TABLE %r DROP UNIQUE %r",
  1631. $data['table'],
  1632. $name
  1633. );
  1634. }
  1635. $check_constraint = $this->getDB2CheckConstraint(
  1636. $data['schema'],
  1637. $data['table_without_schema'],
  1638. $data['column_name']
  1639. );
  1640. if ($check_constraint) {
  1641. $extra_statements[] = $this->database->escape(
  1642. "ALTER TABLE %r DROP CONSTRAINT %r",
  1643. $data['table'],
  1644. $check_constraint['name']
  1645. );
  1646. }
  1647. $primary_key_columns = $this->getDB2PrimaryKeyConstraint(
  1648. $data['schema'],
  1649. $data['table_without_schema']
  1650. );
  1651. if (in_array($data['column_name'], $primary_key_columns)) {
  1652. $extra_statements[] = $this->database->escape(
  1653. "ALTER TABLE %r DROP PRIMARY KEY",
  1654. $data['table']
  1655. );
  1656. }
  1657. $extra_statements[] = $sql;
  1658. $sql = array_shift($extra_statements);
  1659. if (in_array($data['column_name'], $primary_key_columns)) {
  1660. $key = array_search($data['column_name'], $primary_key_columns);
  1661. $primary_key_columns[$key] = $data['new_column_name'];
  1662. $extra_statements[] = $this->database->escape(
  1663. "ALTER TABLE %r ADD PRIMARY KEY (%r)",
  1664. $data['table'],
  1665. $primary_key_columns
  1666. );
  1667. }
  1668. if ($check_constraint) {
  1669. $check_constraint['definition'] = preg_replace(
  1670. '#^\s*"?' . preg_quote($data['column_name'], '#') . '"?#i',
  1671. $this->database->escape('%r', $data['new_column_name']),
  1672. $check_constraint['definition']
  1673. );
  1674. $constraint_name = $this->generateConstraintName($sql, 'ck');
  1675. $extra_statements[] = $this->database->escape(
  1676. "ALTER TABLE %r ADD CONSTRAINT %r CHECK(",
  1677. $data['table'],
  1678. $constraint_name
  1679. ) . $check_constraint['definition'] . ')';
  1680. }
  1681. foreach ($unique_constraints as $name => $columns) {
  1682. $key = array_search($data['column_name'], $columns);
  1683. $columns[$key] = $data['new_column_name'];
  1684. $extra_statements[] = $this->database->escape(
  1685. "ALTER TABLE %r ADD UNIQUE (%r)",
  1686. $data['table'],
  1687. $columns
  1688. );
  1689. }
  1690. foreach ($foreign_key_constraints as $constraint) {
  1691. if ($constraint['table'] == $data['table_without_schema'] && $constraint['column'] == $data['column_name']) {
  1692. $constraint['column'] = $data['new_column_name'];
  1693. } else {
  1694. $constraint['foreign_column'] = $data['new_column_name'];
  1695. }
  1696. $extra_statements[] = $this->database->escape(
  1697. "ALTER TABLE %r ADD FOREIGN KEY (%r) REFERENCES %r(%r) ON DELETE " . $constraint['on_delete'] . ' ON UPDATE ' . $constraint['on_update'],
  1698. $constraint['schema'] . '.' . $constraint['table'],
  1699. $constraint['column'],
  1700. $constraint['foreign_schema'] . '.' . $constraint['foreign_table'],
  1701. $constraint['foreign_column']
  1702. );
  1703. }
  1704. } elseif ($data['type'] == 'add_column') {
  1705. $sql = $this->translateDataTypes($sql);
  1706. // DB2 only supports some ON UPDATE clauses
  1707. $sql = preg_replace('#(\sON\s+UPDATE\s+(CASCADE|SET\s+NULL))#i', '', $sql);
  1708. // Boolean translation is more context-sensitive, hence it is not part of translateDataTypes()
  1709. $sql = preg_replace('#("[^"]+"|\w+)\s+boolean\b(.*)$#iD', '\1 CHAR(1)\2 CHECK(\1 IN (\'0\', \'1\'))', $sql);
  1710. if (preg_match('#\binteger(?:\(\d+\))?\s+autoincrement\b#i', $sql)) {
  1711. $sql = preg_replace('# autoincrement\b#i', '', $sql);
  1712. $sql = preg_replace('# PRIMARY\s+KEY\b#i', ' NOT NULL DEFAULT 0', $sql);
  1713. $extra_statements[] = $this->database->escape(
  1714. "ALTER TABLE %r ALTER COLUMN %r DROP DEFAULT",
  1715. $data['table'],
  1716. $data['column_name']
  1717. );
  1718. $extra_statements[] = $this->database->escape(
  1719. "ALTER TABLE %r ALTER COLUMN %r SET GENERATED BY DEFAULT AS IDENTITY",
  1720. $data['table'],
  1721. $data['column_name']
  1722. );
  1723. //$extra_statements[] = "CALL SYSPROC.ADMIN_CMD('REORG TABLE " . $this->database->escape('%r', $data['table']) . "')";
  1724. // REORGE implicitly commits
  1725. //$extra_statements[] = "BEGIN";
  1726. $extra_statements[] = $this->database->escape(
  1727. "UPDATE %r SET %r = DEFAULT",
  1728. $data['table'],
  1729. $data['column_name']
  1730. );
  1731. $extra_statements[] = $this->database->escape(
  1732. "ALTER TABLE %r ADD PRIMARY KEY (%r)",
  1733. $data['table'],
  1734. $data['column_name']
  1735. );
  1736. }
  1737. } elseif ($data['type'] == 'drop_column') {
  1738. $sql .= ' CASCADE';
  1739. // Certain operations in DB2 require calling REORG
  1740. $extra_statements[] = "CALL SYSPROC.ADMIN_CMD('REORG TABLE " . $this->database->escape('%r', $data['table']) . "')";
  1741. // REORGE implicitly commits
  1742. $extra_statements[] = "BEGIN";
  1743. } elseif ($data['type'] == 'alter_type') {
  1744. $data['data_type'] = $this->translateDataTypes($data['data_type']);
  1745. $sql = $this->database->escape(
  1746. "ALTER TABLE %r ALTER COLUMN %r SET DATA TYPE " . $data['data_type'],
  1747. $data['table'],
  1748. $data['column_name']
  1749. );
  1750. // Certain operations in DB2 require calling REORG
  1751. $extra_statements[] = "CALL SYSPROC.ADMIN_CMD('REORG TABLE " . $this->database->escape('%r', $data['table']) . "')";
  1752. // REORGE implicitly commits
  1753. $extra_statements[] = "BEGIN";
  1754. } elseif ($data['type'] == 'set_default') {
  1755. // DB2 handles the normalized syntax
  1756. } elseif ($data['type'] == 'drop_default') {
  1757. // DB2 complains if you try to drop the default for a column without a default
  1758. $column_info = $this->database->query(
  1759. "SELECT
  1760. C.DEFAULT
  1761. FROM
  1762. SYSCAT.COLUMNS AS C
  1763. WHERE
  1764. LOWER(C.TABSCHEMA) = %s AND
  1765. LOWER(C.TABNAME) = %s AND
  1766. LOWER(C.COLNAME) = %s",
  1767. $data['schema'],
  1768. $data['table_without_schema'],
  1769. $data['column_name']
  1770. );
  1771. if ($column_info->countReturnedRows()) {
  1772. $default = $column_info->fetchScalar();
  1773. if ($default === NULL) {
  1774. $sql = "SELECT 'noop - no constraint to drop' FROM SYSIBM.SYSDUMMY1";
  1775. }
  1776. }
  1777. } elseif ($data['type'] == 'set_not_null') {
  1778. $extra_statements[] = "CALL SYSPROC.ADMIN_CMD('REORG TABLE " . $this->database->escape('%r', $data['table']) . "')";
  1779. // REORGE implicitly commits
  1780. $extra_statements[] = "BEGIN";
  1781. if (isset($data['default'])) {
  1782. $sql = $this->database->escape(
  1783. "ALTER TABLE %r ALTER COLUMN %r SET NOT NULL",
  1784. $data['table'],
  1785. $data['column_name']
  1786. );
  1787. $extra_statements[] = $this->database->escape(
  1788. "ALTER TABLE %r ALTER COLUMN %r SET DEFAULT ",
  1789. $data['table'],
  1790. $data['column_name']
  1791. ) . $data['default'];
  1792. }
  1793. } elseif ($data['type'] == 'drop_not_null') {
  1794. // DB2 handles the normalized syntax
  1795. // Certain operations in DB2 require calling REORG
  1796. $extra_statements[] = "CALL SYSPROC.ADMIN_CMD('REORG TABLE " . $this->database->escape('%r', $data['table']) . "')";
  1797. // REORGE implicitly commits
  1798. $extra_statements[] = "BEGIN";
  1799. } elseif ($data['type'] == 'drop_check_constraint') {
  1800. $check_constraint = $this->getDB2CheckConstraint(
  1801. $data['schema'],
  1802. $data['table_without_schema'],
  1803. $data['column_name']
  1804. );
  1805. if (!$check_constraint) {
  1806. $this->throwException(
  1807. self::compose(
  1808. 'The column "%1$s" in the table "%2$s" does not have a check constraint',
  1809. $data['column_name'],
  1810. $data['table']
  1811. ),
  1812. $sql
  1813. );
  1814. }
  1815. $sql = $this->database->escape(
  1816. "ALTER TABLE %r DROP CONSTRAINT %r",
  1817. $data['table'],
  1818. $check_constraint['name']
  1819. );
  1820. } elseif ($data['type'] == 'set_check_constraint') {
  1821. $check_constraint = $this->getDB2CheckConstraint(
  1822. $data['schema'],
  1823. $data['table_without_schema'],
  1824. $data['column_name']
  1825. );
  1826. if ($check_constraint) {
  1827. $extra_statements[] = $this->database->escape(
  1828. "ALTER TABLE %r DROP CONSTRAINT %r",
  1829. $data['table'],
  1830. $check_constraint['name']
  1831. );
  1832. }
  1833. $sql = $this->database->escape(
  1834. "ALTER TABLE %r ADD CONSTRAINT %r",
  1835. $data['table'],
  1836. $this->generateConstraintName($sql, 'ck')
  1837. ) . $data['constraint'];
  1838. $extra_statements[] = $sql;
  1839. $sql = array_shift($extra_statements);
  1840. } elseif ($data['type'] == 'drop_primary_key') {
  1841. // We drop the default value when dropping primary keys to get
  1842. // rid of autoincrementing functionality
  1843. $primary_key_columns = $this->getDB2PrimaryKeyConstraint(
  1844. $data['schema'],
  1845. $data['table_without_schema']
  1846. );
  1847. if (count($primary_key_columns) == 1) {
  1848. $is_identity = (boolean) $this->database->query(
  1849. "SELECT
  1850. CASE WHEN C.IDENTITY = 'Y' AND (C.GENERATED = 'D' OR C.GENERATED = 'A') THEN '1' ELSE '0' END AS AUTO_INCREMENT
  1851. FROM
  1852. SYSCAT.COLUMNS AS C
  1853. WHERE
  1854. LOWER(C.TABSCHEMA) = %s AND
  1855. LOWER(C.TABNAME) = %s AND
  1856. LOWER(C.COLNAME) = %s",
  1857. $data['schema'],
  1858. $data['table_without_schema'],
  1859. reset($primary_key_columns)
  1860. )->fetchScalar();
  1861. if ($is_identity) {
  1862. $extra_statements[] = $this->database->escape(
  1863. "ALTER TABLE %r ALTER COLUMN %r DROP IDENTITY",
  1864. $data['table'],
  1865. reset($primary_key_columns)
  1866. );
  1867. }
  1868. }
  1869. } elseif ($data['type'] == 'add_primary_key') {
  1870. if ($data['autoincrement']) {
  1871. $extra_statements[] = $this->database->escape(
  1872. "ALTER TABLE %r ALTER COLUMN %r SET GENERATED BY DEFAULT AS IDENTITY",
  1873. $data['table'],
  1874. $data['column_name']
  1875. );
  1876. //$extra_statements[] = "CALL SYSPROC.ADMIN_CMD('REORG TABLE " . $this->database->escape('%r', $data['table']) . "')";
  1877. // REORGE implicitly commits
  1878. //$extra_statements[] = "BEGIN";
  1879. $extra_statements[] = $this->database->escape(
  1880. "UPDATE %r SET %r = DEFAULT",
  1881. $data['table'],
  1882. $data['column_name']
  1883. );
  1884. $extra_statements[] = $this->database->escape(
  1885. "ALTER TABLE %r ADD PRIMARY KEY (%r)",
  1886. $data['table'],
  1887. $data['column_name']
  1888. );
  1889. $sql = array_shift($extra_statements);
  1890. }
  1891. } elseif ($data['type'] == 'drop_foreign_key') {
  1892. $constraint = $this->database->query(
  1893. "SELECT
  1894. R.CONSTNAME AS CONSTRAINT_NAME
  1895. FROM
  1896. SYSCAT.REFERENCES AS R INNER JOIN
  1897. SYSCAT.KEYCOLUSE AS K ON
  1898. R.CONSTNAME = K.CONSTNAME AND
  1899. R.TABSCHEMA = K.TABSCHEMA AND
  1900. R.TABNAME = K.TABNAME INNER JOIN
  1901. SYSCAT.KEYCOLUSE AS FK ON
  1902. R.REFKEYNAME = FK.CONSTNAME AND
  1903. R.REFTABSCHEMA = FK.TABSCHEMA AND
  1904. R.REFTABNAME = FK.TABNAME
  1905. WHERE
  1906. LOWER(R.TABSCHEMA) = %s AND
  1907. LOWER(R.TABNAME) = %s AND
  1908. LOWER(K.COLNAME) = %s",
  1909. $data['schema'],
  1910. $data['table_without_schema'],
  1911. $data['column_name']
  1912. );
  1913. if (!$constraint->countReturnedRows()) {
  1914. $this->throwException(
  1915. self::compose(
  1916. 'The column "%1$s" in the table "%2$s" does not have a foreign key constraint',
  1917. $data['column_name'],
  1918. $data['table']
  1919. ),
  1920. $sql
  1921. );
  1922. }
  1923. $sql = $this->database->escape(
  1924. "ALTER TABLE %r DROP CONSTRAINT %r",
  1925. $data['table'],
  1926. $constraint->fetchScalar()
  1927. );
  1928. } elseif ($data['type'] == 'add_foreign_key') {
  1929. // DB2 only supports some ON UPDATE clauses
  1930. $sql = preg_replace('#(\sON\s+UPDATE\s+(CASCADE|SET\s+NULL))#i', '', $sql);
  1931. } elseif ($data['type'] == 'drop_unique') {
  1932. $constraint_rows = $this->database->query(
  1933. "SELECT
  1934. CD.CONSTNAME AS CONSTRAINT_NAME,
  1935. LOWER(C.COLNAME) AS COLUMN
  1936. FROM
  1937. SYSCAT.INDEXES AS I INNER JOIN
  1938. SYSCAT.CONSTDEP AS CD ON
  1939. I.TABSCHEMA = CD.TABSCHEMA AND
  1940. I.TABNAME = CD.TABNAME AND
  1941. CD.BTYPE = 'I' AND
  1942. CD.BNAME = I.INDNAME INNER JOIN
  1943. SYSCAT.INDEXCOLUSE AS C ON
  1944. I.INDSCHEMA = C.INDSCHEMA AND
  1945. I.INDNAME = C.INDNAME
  1946. WHERE
  1947. LOWER(I.TABSCHEMA) = %s AND
  1948. LOWER(I.TABNAME) = %s AND
  1949. I.UNIQUERULE = 'U'",
  1950. $data['schema'],
  1951. $data['table_without_schema']
  1952. );
  1953. $constraints = array();
  1954. foreach ($constraint_rows as $row) {
  1955. if (!isset($constraints[$row['constraint_name']])) {
  1956. $constraints[$row['constraint_name']] = array();
  1957. }
  1958. $constraints[$row['constraint_name']][] = $row['column'];
  1959. }
  1960. $constraint_name = NULL;
  1961. sort($data['column_names']);
  1962. foreach ($constraints as $name => $columns) {
  1963. sort($columns);
  1964. if ($columns == $data['column_names']) {
  1965. $constraint_name = $name;
  1966. break;
  1967. }
  1968. }
  1969. if (!$constraint_name) {
  1970. if (count($data['column_names']) > 1) {
  1971. $message = self::compose(
  1972. 'The columns "%1$s" in the table "%2$s" do not have a unique constraint',
  1973. join('", "', $data['column_names']),
  1974. $data['table']
  1975. );
  1976. } else {
  1977. $message = self::compose(
  1978. 'The column "%1$s" in the table "%2$s" does not have a unique constraint',
  1979. reset($data['column_names']),
  1980. $data['table']
  1981. );
  1982. }
  1983. $this->throwException($message, $sql);
  1984. }
  1985. $sql = $this->database->escape(
  1986. "ALTER TABLE %r DROP UNIQUE %r",
  1987. $data['table'],
  1988. $constraint_name
  1989. );
  1990. } elseif ($data['type'] == 'add_unique') {
  1991. // DB2 handles the normalized syntax
  1992. }
  1993. return $sql;
  1994. }
  1995. /**
  1996. * Translates Flourish SQL `ALTER TABLE` statements to the appropriate
  1997. * statements for MSSQL
  1998. *
  1999. * @param string $sql The SQL statements that will be executed against the database
  2000. * @param array &$extra_statements Any extra SQL statements required for MSSQL
  2001. * @param array $data Data parsed from the `ALTER TABLE` statement
  2002. * @return string The modified SQL statement
  2003. */
  2004. private function translateMSSQLAlterTableStatements($sql, &$extra_statements, $data)
  2005. {
  2006. $data['schema'] = 'dbo';
  2007. $data['table_without_schema'] = $data['table'];
  2008. if (strpos($data['table'], '.') !== FALSE) {
  2009. list ($data['schema'], $data['table_without_schema']) = explode('.', $data['table']);
  2010. }
  2011. if (in_array($data['type'], array('set_not_null', 'drop_not_null', 'drop_default', 'drop_check_constraint', 'drop_primary_key', 'drop_foreign_key', 'drop_unique'))) {
  2012. $column_info = $this->database->query(
  2013. "SELECT
  2014. t.table_name,
  2015. c.column_name
  2016. FROM
  2017. information_schema.tables AS t LEFT JOIN
  2018. information_schema.columns AS c ON
  2019. c.table_name = t.table_name AND
  2020. c.table_schema = t.table_schema AND
  2021. LOWER(c.column_name) = %s
  2022. WHERE
  2023. LOWER(t.table_name) = %s AND
  2024. LOWER(t.table_schema) = %s AND
  2025. t.table_catalog = DB_NAME()",
  2026. isset($data['column_name']) ? $data['column_name'] : '',
  2027. $data['table_without_schema'],
  2028. $data['schema']
  2029. );
  2030. if (!$column_info->countReturnedRows()) {
  2031. $this->throwException(
  2032. self::compose(
  2033. 'The table "%1$s" does not exist',
  2034. $data['table']
  2035. ),
  2036. $sql
  2037. );
  2038. }
  2039. if (isset($data['column_name'])) {
  2040. $row = $column_info->fetchRow();
  2041. if (!strlen($row['column_name'])) {
  2042. $this->throwException(
  2043. self::compose(
  2044. 'The column "%1$s" does not exist in the table "%2$s"',
  2045. $data['column_name'],
  2046. $data['table']
  2047. ),
  2048. $sql
  2049. );
  2050. }
  2051. }
  2052. }
  2053. if (in_array($data['type'], array('set_not_null', 'drop_not_null'))) {
  2054. $column_info = $this->database->query(
  2055. "SELECT
  2056. c.data_type AS 'type',
  2057. c.character_maximum_length AS max_length,
  2058. c.numeric_precision AS precision,
  2059. c.numeric_scale AS decimal_places
  2060. FROM
  2061. information_schema.columns AS c
  2062. WHERE
  2063. LOWER(c.table_name) = %s AND
  2064. LOWER(c.table_schema) = %s AND
  2065. LOWER(c.column_name) = %s AND
  2066. c.table_catalog = DB_NAME()",
  2067. $data['table_without_schema'],
  2068. $data['schema'],
  2069. $data['column_name']
  2070. );
  2071. $row = $column_info->fetchRow();
  2072. $data_type = $row['type'];
  2073. if ($row['max_length']) {
  2074. $data_type .= '(' . $row['max_length'] . ')';
  2075. }
  2076. if (!preg_match('#^\s*int#i', $row['type']) && $row['precision']) {
  2077. $data_type .= '(' . $row['precision'];
  2078. if ($row['decimal_places']) {
  2079. $data_type .= ', ' . $row['decimal_places'];
  2080. }
  2081. $data_type .= ')';
  2082. }
  2083. }
  2084. if ($data['type'] == 'column_comment') {
  2085. $get_sql = "SELECT
  2086. CAST(ex.value AS VARCHAR(7500)) AS 'comment'
  2087. FROM
  2088. INFORMATION_SCHEMA.COLUMNS AS c";
  2089. if (version_compare($this->database->getVersion(), 9, '<')) {
  2090. $get_sql .= " INNER 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 ";
  2091. } else {
  2092. $get_sql .= " INNER 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 ";
  2093. }
  2094. $get_sql .= "WHERE
  2095. LOWER(c.table_name) = %s AND
  2096. LOWER(c.table_schema) = %s AND
  2097. LOWER(c.column_name) = %s AND
  2098. c.table_catalog = DB_NAME()";
  2099. $result = $this->database->query($get_sql, $data['table_without_schema'], $data['schema'], $data['column_name']);
  2100. $stored_procedure = 'sys.sp_addextendedproperty';
  2101. if ($result->countReturnedRows()) {
  2102. $stored_procedure = 'sys.sp_updateextendedproperty';
  2103. }
  2104. $sql = "EXECUTE " . $stored_procedure . " @name='MS_Description', @value=" . $data['comment'] . $this->database->escape(
  2105. ", @level0type='SCHEMA', @level0name=%s, @level1type='TABLE', @level1name=%s, @level2type='COLUMN', @level2name=%s",
  2106. $data['schema'],
  2107. $data['table_without_schema'],
  2108. $data['column_name']
  2109. );
  2110. } elseif ($data['type'] == 'rename_table') {
  2111. $sql = $this->database->escape(
  2112. "EXECUTE sp_rename %r, %r",
  2113. $data['table'],
  2114. $data['new_table_name']
  2115. );
  2116. } elseif ($data['type'] == 'rename_column') {
  2117. // Find any check constraints and remove them, they will be re-added after the rename
  2118. $check_constraint = $this->getMSSQLCheckConstraint(
  2119. $data['schema'],
  2120. $data['table_without_schema'],
  2121. $data['column_name']
  2122. );
  2123. if ($check_constraint) {
  2124. $check_constraint['definition'] = preg_replace(
  2125. '#(\[)' . $data['column_name'] . '(\]\s*=\s*\')#i',
  2126. '\1' . $data['new_column_name'] . '\2',
  2127. $check_constraint['definition']
  2128. );
  2129. $extra_statements[] = $this->database->escape(
  2130. "ALTER TABLE %r DROP CONSTRAINT %r",
  2131. $data['table'],
  2132. $check_constraint['name']
  2133. );
  2134. }
  2135. $sql = $this->database->escape(
  2136. 'EXECUTE sp_rename "' . $data['table'] . '.' . $data['column_name'] . '", %r',
  2137. $data['new_column_name']
  2138. );
  2139. $extra_statements[] = $sql;
  2140. $sql = array_shift($extra_statements);
  2141. if ($check_constraint) {
  2142. $extra_statements[] = $this->database->escape(
  2143. "ALTER TABLE %r ADD CONSTRAINT %r CHECK",
  2144. $data['table'],
  2145. $this->generateConstraintName($sql, 'ck')
  2146. ) . $check_constraint['definition'];
  2147. }
  2148. } elseif ($data['type'] == 'add_column') {
  2149. $sql = $this->database->escape(
  2150. 'ALTER TABLE %r ADD ',
  2151. $data['table']
  2152. ) . $data['column_definition'];
  2153. $sql = $this->translateDataTypes($sql);
  2154. $sql = preg_replace('#\binteger(?:\(\d+\))?\s+autoincrement\b#i', 'INTEGER IDENTITY', $sql);
  2155. } elseif ($data['type'] == 'drop_column') {
  2156. // We must find all constraints that reference this column and drop them first
  2157. $foreign_key_constraints = $this->getMSSQLForeignKeyConstraints(
  2158. $data['schema'],
  2159. $data['table_without_schema'],
  2160. $data['column_name']
  2161. );
  2162. foreach ($foreign_key_constraints as $constraint) {
  2163. $extra_statements[] = $this->database->escape(
  2164. "ALTER TABLE %r DROP CONSTRAINT %r",
  2165. $constraint['table'],
  2166. $constraint['name']
  2167. );
  2168. }
  2169. $unique_constraints = $this->getMSSQLUniqueConstraints(
  2170. $data['schema'],
  2171. $data['table_without_schema'],
  2172. $data['column_name']
  2173. );
  2174. foreach ($unique_constraints as $constraint_name => $constraint) {
  2175. $extra_statements[] = $this->database->escape(
  2176. "ALTER TABLE %r DROP CONSTRAINT %r",
  2177. $data['table'],
  2178. $constraint_name
  2179. );
  2180. }
  2181. $check_constraint = $this->getMSSQLCheckConstraint(
  2182. $data['schema'],
  2183. $data['table_without_schema'],
  2184. $data['column_name']
  2185. );
  2186. if ($check_constraint) {
  2187. $extra_statements[] = $this->database->escape(
  2188. "ALTER TABLE %r DROP CONSTRAINT %r",
  2189. $data['table'],
  2190. $check_constraint['name']
  2191. );
  2192. }
  2193. $default_constraint = $this->getMSSQLDefaultConstraint(
  2194. $data['schema'],
  2195. $data['table_without_schema'],
  2196. $data['column_name']
  2197. );
  2198. if ($default_constraint) {
  2199. $extra_statements[] = $this->database->escape(
  2200. "ALTER TABLE %r DROP CONSTRAINT %r",
  2201. $data['table'],
  2202. $default_constraint['name']
  2203. );
  2204. }
  2205. $primary_key_constraint = $this->getMSSQLPrimaryKeyConstraint(
  2206. $data['schema'],
  2207. $data['table_without_schema']
  2208. );
  2209. if ($primary_key_constraint && in_array($data['column_name'], $primary_key_constraint['columns'])) {
  2210. $extra_statements[] = $this->database->escape(
  2211. "ALTER TABLE %r DROP CONSTRAINT %r",
  2212. $data['table'],
  2213. $primary_key_constraint['name']
  2214. );
  2215. }
  2216. $extra_statements[] = $sql;
  2217. $sql = array_shift($extra_statements);
  2218. } elseif ($data['type'] == 'alter_type') {
  2219. $default_constraint = $this->getMSSQLDefaultConstraint(
  2220. $data['schema'],
  2221. $data['table_without_schema'],
  2222. $data['column_name']
  2223. );
  2224. if ($default_constraint) {
  2225. $extra_statements[] = $this->database->escape(
  2226. "ALTER TABLE %r DROP CONSTRAINT %r",
  2227. $data['table'],
  2228. $default_constraint['name']
  2229. );
  2230. }
  2231. $check_constraint = $this->getMSSQLCheckConstraint(
  2232. $data['schema'],
  2233. $data['table_without_schema'],
  2234. $data['column_name']
  2235. );
  2236. if ($check_constraint) {
  2237. $extra_statements[] = $this->database->escape(
  2238. "ALTER TABLE %r DROP CONSTRAINT %r",
  2239. $data['table'],
  2240. $check_constraint['name']
  2241. );
  2242. }
  2243. // Check if the column is NOT NULL since we have to specify that when changing the type
  2244. $column_info = $this->database->query(
  2245. "SELECT
  2246. c.is_nullable
  2247. FROM
  2248. INFORMATION_SCHEMA.COLUMNS AS c
  2249. WHERE
  2250. LOWER(c.table_schema) = %s AND
  2251. LOWER(c.table_name) = %s AND
  2252. LOWER(c.column_name) = %s AND
  2253. c.table_catalog = DB_NAME()",
  2254. $data['schema'],
  2255. $data['table_without_schema'],
  2256. $data['column_name']
  2257. );
  2258. $not_null = FALSE;
  2259. if ($column_info->countReturnedRows()) {
  2260. $row = $column_info->fetchRow();
  2261. $not_null = $row['is_nullable'] == 'NO';
  2262. }
  2263. $unique_constraints = $this->getMSSQLUniqueConstraints(
  2264. $data['schema'],
  2265. $data['table_without_schema'],
  2266. $data['column_name']
  2267. );
  2268. foreach ($unique_constraints as $constraint_name => $columns) {
  2269. $extra_statements[] = $this->database->escape(
  2270. "ALTER TABLE %r DROP CONSTRAINT %r",
  2271. $data['table'],
  2272. $constraint_name
  2273. );
  2274. }
  2275. $primary_key_constraint = $this->getMSSQLPrimaryKeyConstraint(
  2276. $data['schema'],
  2277. $data['table_without_schema']
  2278. );
  2279. if ($primary_key_constraint && in_array($data['column_name'], $primary_key_constraint['columns'])) {
  2280. $extra_statements[] = $this->database->escape(
  2281. "ALTER TABLE %r DROP CONSTRAINT %r",
  2282. $data['table'],
  2283. $primary_key_constraint['name']
  2284. );
  2285. }
  2286. $data['data_type'] = $this->translateDataTypes($data['data_type']);
  2287. $sql = $this->database->escape(
  2288. "ALTER TABLE %r ALTER COLUMN %r " . $data['data_type'] . ($not_null ? ' NOT NULL' : ''),
  2289. $data['table'],
  2290. $data['column_name']
  2291. );
  2292. $extra_statements[] = $sql;
  2293. $sql = array_shift($extra_statements);
  2294. if ($default_constraint) {
  2295. $extra_statements[] =$this->database->escape("ALTER TABLE %r ADD DEFAULT ", $data['table']) .
  2296. $default_constraint['definition'] .
  2297. $this->database->escape(" FOR %r", $data['column_name']);
  2298. }
  2299. if ($check_constraint) {
  2300. $extra_statements[] = $this->database->escape(
  2301. "ALTER TABLE %r ADD CONSTRAINT %r CHECK",
  2302. $data['table'],
  2303. $this->generateConstraintName($sql, 'ck')
  2304. ) . $check_constraint['definition'];
  2305. }
  2306. foreach ($unique_constraints as $constraint_name => $columns) {
  2307. $extra_statements[] = $this->database->escape(
  2308. "ALTER TABLE %r ADD UNIQUE (%r)",
  2309. $data['table'],
  2310. $columns
  2311. );
  2312. }
  2313. if ($primary_key_constraint && in_array($data['column_name'], $primary_key_constraint['columns'])) {
  2314. $extra_statements[] = $this->database->escape(
  2315. "ALTER TABLE %r ADD PRIMARY KEY (%r)",
  2316. $data['table'],
  2317. $primary_key_constraint['columns']
  2318. );
  2319. }
  2320. } elseif ($data['type'] == 'set_default') {
  2321. // SQL Server requires removing any existing default constraint
  2322. $default_constraint = $this->getMSSQLDefaultConstraint(
  2323. $data['schema'],
  2324. $data['table_without_schema'],
  2325. $data['column_name']
  2326. );
  2327. if ($default_constraint) {
  2328. $extra_statements[] = $this->database->escape(
  2329. "ALTER TABLE %r DROP CONSTRAINT %r",
  2330. $data['table'],
  2331. $default_constraint['name']
  2332. );
  2333. }
  2334. $sql = $this->database->escape("ALTER TABLE %r ADD DEFAULT ", $data['table']) .
  2335. $data['default_value'] .
  2336. $this->database->escape(" FOR %r", $data['column_name']);
  2337. $extra_statements[] = $sql;
  2338. $sql = array_shift($extra_statements);
  2339. } elseif ($data['type'] == 'drop_default') {
  2340. $default_constraint = $this->getMSSQLDefaultConstraint(
  2341. $data['schema'],
  2342. $data['table_without_schema'],
  2343. $data['column_name']
  2344. );
  2345. if (!$default_constraint) {
  2346. $sql = "SELECT 'noop - no constraint to drop'";
  2347. } else {
  2348. $sql = $this->database->escape(
  2349. "ALTER TABLE %r DROP CONSTRAINT %r",
  2350. $data['table'],
  2351. $default_constraint['name']
  2352. );
  2353. }
  2354. } elseif ($data['type'] == 'set_not_null') {
  2355. $sql = $this->database->escape(
  2356. "ALTER TABLE %r ALTER COLUMN %r " . $data_type . " NOT NULL",
  2357. $data['table'],
  2358. $data['column_name']
  2359. );
  2360. if (isset($data['default'])) {
  2361. $default_constraint = $this->getMSSQLDefaultConstraint(
  2362. $data['schema'],
  2363. $data['table_without_schema'],
  2364. $data['column_name']
  2365. );
  2366. if ($default_constraint) {
  2367. $extra_statements[] = $this->database->escape(
  2368. "ALTER TABLE %r DROP CONSTRAINT %r",
  2369. $data['table'],
  2370. $default_constraint['name']
  2371. );
  2372. }
  2373. $extra_statements[] = $this->database->escape("ALTER TABLE %r ADD DEFAULT ", $data['table']) .
  2374. $data['default'] .
  2375. $this->database->escape(" FOR %r", $data['column_name']);
  2376. }
  2377. } elseif ($data['type'] == 'drop_not_null') {
  2378. $sql = $this->database->escape(
  2379. "ALTER TABLE %r ALTER COLUMN %r " . $data_type . " NULL",
  2380. $data['table'],
  2381. $data['column_name']
  2382. );
  2383. } elseif ($data['type'] == 'drop_check_constraint') {
  2384. $check_constraint = $this->getMSSQLCheckConstraint(
  2385. $data['schema'],
  2386. $data['table_without_schema'],
  2387. $data['column_name']
  2388. );
  2389. if (!$check_constraint) {
  2390. $this->throwException(
  2391. self::compose(
  2392. 'The column "%1$s" in the table "%2$s" does not have a check constraint',
  2393. $data['column_name'],
  2394. $data['table']
  2395. ),
  2396. $sql
  2397. );
  2398. }
  2399. $sql = $this->database->escape(
  2400. "ALTER TABLE %r DROP CONSTRAINT %r",
  2401. $data['table'],
  2402. $check_constraint['name']
  2403. );
  2404. } elseif ($data['type'] == 'set_check_constraint') {
  2405. $check_constraint = $this->getMSSQLCheckConstraint(
  2406. $data['schema'],
  2407. $data['table_without_schema'],
  2408. $data['column_name']
  2409. );
  2410. if ($check_constraint) {
  2411. $extra_statements[] = $this->database->escape(
  2412. "ALTER TABLE %r DROP CONSTRAINT %r",
  2413. $data['table'],
  2414. $check_constraint['name']
  2415. );
  2416. }
  2417. $sql = $this->database->escape(
  2418. "ALTER TABLE %r ADD CONSTRAINT %r",
  2419. $data['table'],
  2420. $this->generateConstraintName($sql, 'ck')
  2421. ) . $data['constraint'];
  2422. $extra_statements[] = $sql;
  2423. $sql = array_shift($extra_statements);
  2424. } elseif ($data['type'] == 'drop_primary_key') {
  2425. $primary_key_constraint = $this->getMSSQLPrimaryKeyConstraint(
  2426. $data['schema'],
  2427. $data['table_without_schema']
  2428. );
  2429. if (!$primary_key_constraint) {
  2430. $this->throwException(
  2431. self::compose(
  2432. 'The table "%1$s" does not have a primary key constraint',
  2433. $data['table']
  2434. ),
  2435. $sql
  2436. );
  2437. }
  2438. $foreign_key_constraints = $this->getMSSQLForeignKeyConstraints(
  2439. $data['schema'],
  2440. $data['table_without_schema'],
  2441. $primary_key_constraint['columns']
  2442. );
  2443. foreach ($foreign_key_constraints as $foreign_key_constraint) {
  2444. // Don't drop the constraints on the primary key columns themselves since that isn't necessary
  2445. $same_schema = $foreign_key_constraint['table_without_schema'] == $data['table_without_schema'];
  2446. $same_table = $foreign_key_constraint['schema'] == $data['schema'];
  2447. if ($same_schema && $same_table && in_array($foreign_key_constraint['column'], $primary_key_constraint['columns'])) {
  2448. continue;
  2449. }
  2450. $extra_statements[] = $this->database->escape(
  2451. "ALTER TABLE %r DROP CONSTRAINT %r",
  2452. $foreign_key_constraint['table'],
  2453. $foreign_key_constraint['name']
  2454. );
  2455. }
  2456. $sql = $this->database->escape(
  2457. "ALTER TABLE %r DROP CONSTRAINT %r",
  2458. $data['table'],
  2459. $primary_key_constraint['name']
  2460. );
  2461. $extra_statements[] = $sql;
  2462. $sql = array_shift($extra_statements);
  2463. if ($primary_key_constraint['autoincrement']) {
  2464. $primary_key_column = reset($primary_key_constraint['columns']);
  2465. $unique_constraints = $this->getMSSQLUniqueConstraints(
  2466. $data['schema'],
  2467. $data['table_without_schema'],
  2468. $primary_key_column
  2469. );
  2470. foreach ($unique_constraints as $constraint_name => $columns) {
  2471. $extra_statements[] = $this->database->escape(
  2472. "ALTER TABLE %r DROP CONSTRAINT %r",
  2473. $data['table'],
  2474. $constraint_name
  2475. );
  2476. }
  2477. $extra_statements[] = $this->database->escape(
  2478. "ALTER TABLE %r ADD %r INTEGER",
  2479. $data['table'],
  2480. 'fl_tmp_identity_col'
  2481. );
  2482. $extra_statements[] = $this->database->escape(
  2483. "UPDATE %r SET %r = %r",
  2484. $data['table'],
  2485. 'fl_tmp_identity_col',
  2486. $primary_key_column
  2487. );
  2488. $extra_statements[] = $this->database->escape(
  2489. "ALTER TABLE %r ALTER COLUMN %r INTEGER NOT NULL",
  2490. $data['table'],
  2491. 'fl_tmp_identity_col'
  2492. );
  2493. $extra_statements[] = $this->database->escape(
  2494. "ALTER TABLE %r DROP COLUMN %r",
  2495. $data['table'],
  2496. $primary_key_column
  2497. );
  2498. $extra_statements[] = $this->database->escape(
  2499. 'EXEC sp_rename "' . $data['table'] . '.fl_tmp_identity_col", %r',
  2500. $primary_key_column
  2501. );
  2502. foreach ($unique_constraints as $constraint_name => $columns) {
  2503. $extra_statements[] = $this->database->escape(
  2504. "ALTER TABLE %r ADD UNIQUE (%r)",
  2505. $data['table'],
  2506. $columns
  2507. );
  2508. }
  2509. }
  2510. } elseif ($data['type'] == 'add_primary_key') {
  2511. if ($data['autoincrement']) {
  2512. $unique_constraints = $this->getMSSQLUniqueConstraints(
  2513. $data['schema'],
  2514. $data['table_without_schema'],
  2515. $data['column_name']
  2516. );
  2517. foreach ($unique_constraints as $constraint_name => $columns) {
  2518. $extra_statements[] = $this->database->escape(
  2519. "ALTER TABLE %r DROP CONSTRAINT %r",
  2520. $data['table'],
  2521. $constraint_name
  2522. );
  2523. }
  2524. $extra_statements[] = $this->database->escape(
  2525. "ALTER TABLE %r ADD %r INTEGER IDENTITY",
  2526. $data['table'],
  2527. 'fl_tmp_identity_col'
  2528. );
  2529. $extra_statements[] = $this->database->escape(
  2530. "ALTER TABLE %r DROP COLUMN %r",
  2531. $data['table'],
  2532. $data['column_name']
  2533. );
  2534. $extra_statements[] = $this->database->escape(
  2535. 'EXEC sp_rename "' . $data['table'] . '.fl_tmp_identity_col", %r',
  2536. $data['column_name']
  2537. );
  2538. $extra_statements[] = $this->database->escape(
  2539. "ALTER TABLE %r ADD PRIMARY KEY (%r)",
  2540. $data['table'],
  2541. $data['column_name']
  2542. );
  2543. foreach ($unique_constraints as $constraint_name => $columns) {
  2544. $extra_statements[] = $this->database->escape(
  2545. "ALTER TABLE %r ADD UNIQUE (%r)",
  2546. $data['table'],
  2547. $columns
  2548. );
  2549. }
  2550. $sql = array_shift($extra_statements);
  2551. }
  2552. } elseif ($data['type'] == 'drop_foreign_key') {
  2553. $constraint = $this->database->query(
  2554. "SELECT
  2555. kcu.constraint_name AS constraint_name
  2556. FROM
  2557. information_schema.table_constraints AS c INNER JOIN
  2558. information_schema.key_column_usage AS kcu ON
  2559. c.table_name = kcu.table_name AND
  2560. c.constraint_name = kcu.constraint_name
  2561. WHERE
  2562. c.constraint_type = 'FOREIGN KEY' AND
  2563. LOWER(c.table_name) = %s AND
  2564. LOWER(c.table_schema) = %s AND
  2565. LOWER(kcu.column_name) = %s AND
  2566. c.table_catalog = DB_NAME()",
  2567. $data['table_without_schema'],
  2568. $data['schema'],
  2569. $data['column_name']
  2570. );
  2571. if (!$constraint->countReturnedRows()) {
  2572. $this->throwException(
  2573. self::compose(
  2574. 'The column "%1$s" in the table "%2$s" does not have a foreign key constraint',
  2575. $data['column_name'],
  2576. $data['table']
  2577. ),
  2578. $sql
  2579. );
  2580. }
  2581. $sql = $this->database->escape(
  2582. "ALTER TABLE %r DROP CONSTRAINT %r",
  2583. $data['table'],
  2584. $constraint->fetchScalar()
  2585. );
  2586. } elseif ($data['type'] == 'add_foreign_key') {
  2587. // MSSQL handles the normalized syntax
  2588. } elseif ($data['type'] == 'drop_unique') {
  2589. $constraint_rows = $this->database->query(
  2590. "SELECT
  2591. c.constraint_name,
  2592. LOWER(kcu.column_name) AS \"column\"
  2593. FROM
  2594. information_schema.table_constraints AS c INNER JOIN
  2595. information_schema.key_column_usage AS kcu ON
  2596. c.table_name = kcu.table_name AND
  2597. c.constraint_name = kcu.constraint_name
  2598. WHERE
  2599. c.constraint_type = 'UNIQUE' AND
  2600. LOWER(c.table_name) = %s AND
  2601. LOWER(c.table_schema) = %s AND
  2602. c.table_catalog = DB_NAME()",
  2603. $data['table_without_schema'],
  2604. $data['schema']
  2605. );
  2606. $constraints = array();
  2607. foreach ($constraint_rows as $row) {
  2608. if (!isset($constraints[$row['constraint_name']])) {
  2609. $constraints[$row['constraint_name']] = array();
  2610. }
  2611. $constraints[$row['constraint_name']][] = $row['column'];
  2612. }
  2613. $constraint_name = NULL;
  2614. sort($data['column_names']);
  2615. foreach ($constraints as $name => $columns) {
  2616. sort($columns);
  2617. if ($columns == $data['column_names']) {
  2618. $constraint_name = $name;
  2619. break;
  2620. }
  2621. }
  2622. if (!$constraint_name) {
  2623. if (count($data['column_names']) > 1) {
  2624. $message = self::compose(
  2625. 'The columns "%1$s" in the table "%2$s" do not have a unique constraint',
  2626. join('", "', $data['column_names']),
  2627. $data['table']
  2628. );
  2629. } else {
  2630. $message = self::compose(
  2631. 'The column "%1$s" in the table "%2$s" does not have a unique constraint',
  2632. reset($data['column_names']),
  2633. $data['table']
  2634. );
  2635. }
  2636. $this->throwException($message, $sql);
  2637. }
  2638. $sql = $this->database->escape(
  2639. "ALTER TABLE %r DROP CONSTRAINT %r",
  2640. $data['table'],
  2641. $constraint_name
  2642. );
  2643. } elseif ($data['type'] == 'add_unique') {
  2644. // MSSQL handles the normalized syntax
  2645. }
  2646. return $sql;
  2647. }
  2648. /**
  2649. * Translates Flourish SQL `ALTER TABLE` statements to the appropriate
  2650. * statements for MySQL
  2651. *
  2652. * @param string $sql The SQL statements that will be executed against the database
  2653. * @param array &$extra_statements Any extra SQL statements required for MySQL
  2654. * @param array &$rollback_statements SQL statements to rollback `$sql` and `$extra_statements` if something goes wrong
  2655. * @param array $data Data parsed from the `ALTER TABLE` statement
  2656. * @return string The modified SQL statement
  2657. */
  2658. private function translateMySQLAlterTableStatements($sql, &$extra_statements, &$rollback_statements, $data)
  2659. {
  2660. if ($data['type'] == 'rename_table') {
  2661. $sql = $this->database->escape(
  2662. "RENAME TABLE %r TO %r",
  2663. $data['table'],
  2664. $data['new_table_name']
  2665. );
  2666. }
  2667. $before_statements = array();
  2668. $after_statements = array();
  2669. if (in_array($data['type'], array('drop_column', 'rename_column', 'alter_type', 'set_not_null', 'drop_not_null', 'column_comment', 'drop_primary_key', 'drop_foreign_key', 'drop_unique', 'add_primary_key', 'drop_check_constraint', 'set_check_constraint'))) {
  2670. // This fetches the original column definition to use with the CHANGE statement
  2671. try {
  2672. $row = $this->database->query("SHOW CREATE TABLE %r", $data['table'])->fetchRow();
  2673. } catch (fSQLException $e) {
  2674. // We catch and throw a new exception so the exception message
  2675. // references the SQL statement passed to this method
  2676. $this->throwException(
  2677. self::compose(
  2678. 'The table "%1$s" does not exist',
  2679. $data['table']
  2680. ),
  2681. $sql
  2682. );
  2683. }
  2684. $create_sql = $row['Create Table'];
  2685. }
  2686. if ($data['type'] == 'drop_primary_key') {
  2687. $data['column_names'] = array();
  2688. if (preg_match('/PRIMARY KEY\s+\("(.*?)"\),?\n/U', $create_sql, $match)) {
  2689. $data['column_names'] = explode('","', $match[1]);
  2690. }
  2691. if (count($data['column_names']) == 1) {
  2692. $data['column_name'] = reset($data['column_names']);
  2693. }
  2694. }
  2695. if (in_array($data['type'], array('rename_column', 'alter_type', 'set_not_null', 'drop_not_null', 'column_comment', 'add_primary_key', 'drop_primary_key', 'drop_foreign_key', 'drop_check_constraint', 'set_check_constraint', 'drop_unique')) && isset($data['column_name'])) {
  2696. $found = preg_match(
  2697. '#(?<=,|\()\s+(?:"|\`)' . $data['column_name'] . '(?:"|\`)(\s+(?:[a-z]+)(?:\([^)]+\))?(?: unsigned)?(?: zerofill)?(?: character set [^ ]+)?(?: collate [^ ]+)?)( NULL)?( NOT NULL)?( DEFAULT (?:(?:[^, \']*|\'(?:\'\'|[^\']+)*\')))?( auto_increment)?( COMMENT \'(?:\'\'|[^\']+)*\')?( ON UPDATE CURRENT_TIMESTAMP)?\s*(?:,|\s*(?=\)))#mi',
  2698. $create_sql,
  2699. $column_match
  2700. );
  2701. if (!$found) {
  2702. $this->throwException(
  2703. self::compose(
  2704. 'The column "%1$s" does not exist in the table "%2$s"',
  2705. $data['column_name'],
  2706. $data['table']
  2707. ),
  2708. $sql
  2709. );
  2710. }
  2711. if (isset($column_match[4]) && strtolower($column_match[4]) == ' default null') {
  2712. $column_match[4] = '';
  2713. }
  2714. }
  2715. if ($data['type'] == 'column_comment') {
  2716. $column_match[6] = ' COMMENT ' . $data['comment'];
  2717. $column_def = join('', array_slice($column_match, 1));
  2718. $sql = $this->database->escape(
  2719. "ALTER TABLE %r MODIFY %r ",
  2720. $data['table'],
  2721. $data['column_name']
  2722. ) . $column_def;
  2723. } elseif ($data['type'] == 'rename_column') {
  2724. $column_def = join('', array_slice($column_match, 1));
  2725. $sql = $this->database->escape(
  2726. "ALTER TABLE %r CHANGE %r %r ",
  2727. $data['table'],
  2728. $data['column_name'],
  2729. $data['new_column_name']
  2730. ) . $column_def;
  2731. } elseif ($data['type'] == 'add_column') {
  2732. $not_null = preg_match('#\bNOT\s+NULL(\b|$)#iD', $data['column_definition']);
  2733. $no_default = !preg_match('#\bDEFAULT\s+|\s+AUTOINCREMENT#i', $data['column_definition']);
  2734. if ($not_null && $no_default && $this->database->query("SELECT COUNT(*) FROM %r", $data['table'])->fetchScalar()) {
  2735. $this->throwException(
  2736. self::compose(
  2737. "It is not possible to add a column with a NOT NULL constraint that does not contain a DEFAULT value and is not an AUTOINCREMENT column for tables with existing rows"
  2738. ),
  2739. $sql
  2740. );
  2741. }
  2742. $sql = $this->translateDataTypes($sql);
  2743. $sql = preg_replace('#\binteger(?:\(\d+\))?\s+autoincrement\b#i', 'INTEGER AUTO_INCREMENT', $sql);
  2744. // Translate check constraints to enums and split out foreign key definitions
  2745. preg_match_all(
  2746. '#^\s*(["`]?\w+["`]?)(\s+(?:[a-z]+)(?:\(\d+\))?(?:\s+unsigned|\s+zerofill)*)((?:\s+character\s+set\s+[^ ]+|\s+collate\s+[^ ]+|\s+NULL|\s+NOT\s+NULL|(\s+DEFAULT\s+(?:[^, \']*|\'(?:\'\'|[^\']+)*\'))|\s+UNIQUE|\s+PRIMARY\s+KEY)*)(\s+CHECK\s*\(\w+\s+IN\s+(\(\s*(?:(?:[^, \']+|\'(?:\'\'|[^\']+)*\')\s*,\s*)*\s*(?:[^, \']+|\'(?:\'\'|[^\']+)*\')\))\))?(\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*$#iD',
  2747. $data['column_definition'],
  2748. $matches,
  2749. PREG_SET_ORDER
  2750. );
  2751. foreach ($matches as $match) {
  2752. // MySQL has the enum data type, so we switch check constraints to that
  2753. if (!empty($match[5])) {
  2754. $replacement = ' enum' . $match[6];
  2755. $sql = str_replace($match[2], $replacement, $sql);
  2756. $sql = str_replace($match[5], '', $sql);
  2757. }
  2758. // Even InnoDB table types don't allow specify foreign key constraints in the column
  2759. // definition, so we have to create an extra statement
  2760. if (!empty($match[7])) {
  2761. $after_statements[] = $this->database->escape(
  2762. "ALTER TABLE %r ADD FOREIGN KEY (%r) " . $match[7],
  2763. $data['table'],
  2764. $data['column_name']
  2765. );
  2766. $sql = str_replace($match[7], '', $sql);
  2767. }
  2768. }
  2769. } elseif ($data['type'] == 'drop_column') {
  2770. preg_match_all('/\bUNIQUE\s+KEY\s+"([^"]+)"\s+\("(.*?)"\),?\n/i', $create_sql, $matches, PREG_SET_ORDER);
  2771. foreach ($matches as $match) {
  2772. $columns = explode('","', $match[2]);
  2773. if (in_array($data['column_name'], $columns)) {
  2774. // Set up an array of column names we need to drop the keys for
  2775. if (!isset($data['column_names'])) {
  2776. $data['column_names'] = $columns;
  2777. } else {
  2778. $data['column_names'] = array_merge($data['column_names'], $columns);
  2779. }
  2780. $before_statements[] = $this->database->escape(
  2781. "ALTER TABLE %r DROP INDEX %r",
  2782. $data['table'],
  2783. $match[1]
  2784. );
  2785. }
  2786. }
  2787. } elseif ($data['type'] == 'alter_type') {
  2788. // We ignore changes from enum to varchar since that will just destroy the check constraint functionality
  2789. if (!(preg_match('#\s*enum\(#i', $column_match[1]) && preg_match('#\s*varchar(\(\d+\))?\s*$#iD', $data['data_type']))) {
  2790. $data['data_type'] = $this->translateDataTypes($data['data_type']);
  2791. $column_match[1] = ' ' . $data['data_type'];
  2792. }
  2793. $column_def = join('', array_slice($column_match, 1));
  2794. $sql = $this->database->escape(
  2795. "ALTER TABLE %r MODIFY %r ",
  2796. $data['table'],
  2797. $data['column_name']
  2798. ) . $column_def;
  2799. } elseif ($data['type'] == 'set_default') {
  2800. // MySQL handles the normalized syntax
  2801. } elseif ($data['type'] == 'drop_default') {
  2802. // MySQL handles the normalized syntax
  2803. } elseif ($data['type'] == 'set_not_null') {
  2804. $column_match[2] = '';
  2805. $column_match[3] = ' NOT NULL';
  2806. if (isset($data['default'])) {
  2807. $column_match[4] = ' DEFAULT ' . $data['default'];
  2808. // If the column is being set to NOT NULL we have to drop NULL default values
  2809. } elseif (preg_match('#^\s*DEFAULT\s+NULL\s*$#i', $column_match[4])) {
  2810. $column_match[4] = '';
  2811. }
  2812. $column_def = join('', array_slice($column_match, 1));
  2813. $sql = $this->database->escape(
  2814. "ALTER TABLE %r MODIFY %r ",
  2815. $data['table'],
  2816. $data['column_name']
  2817. ) . $column_def;
  2818. } elseif ($data['type'] == 'drop_not_null') {
  2819. $column_match[2] = '';
  2820. $column_match[3] = '';
  2821. $column_def = join('', array_slice($column_match, 1));
  2822. $sql = $this->database->escape(
  2823. "ALTER TABLE %r MODIFY %r ",
  2824. $data['table'],
  2825. $data['column_name']
  2826. ) . $column_def;
  2827. } elseif ($data['type'] == 'set_check_constraint') {
  2828. preg_match("/^\s*CHECK\s*\(\s*\"?\w+\"?\s+IN\s+(\(\s*(?:(?<!')'(?:''|[^']+)*'|%\d+\\\$s)(?:\s*,\s*(?:(?<!')'(?:''|[^']+)*'|%\d+\\\$s))*\s*\))\s*\)\s*$/i", $data['constraint'], $match);
  2829. $valid_values = $match[1];
  2830. $column_match[1] = ' ENUM' . $valid_values;
  2831. $column_def = join('', array_slice($column_match, 1));
  2832. $sql = $this->database->escape(
  2833. "ALTER TABLE %r MODIFY %r ",
  2834. $data['table'],
  2835. $data['column_name']
  2836. ) . $column_def;
  2837. } elseif ($data['type'] == 'drop_check_constraint') {
  2838. $found = preg_match_all("/(?<!')'((''|[^']+)*)'/", $column_match[1], $matches, PREG_PATTERN_ORDER);
  2839. if (!$found) {
  2840. $this->throwException(
  2841. self::compose(
  2842. 'The column "%1$s" in the table "%2$s" is not an ENUM column',
  2843. $data['column_name'],
  2844. $data['table']
  2845. ),
  2846. $sql
  2847. );
  2848. }
  2849. $valid_values = str_replace("''", "'", $matches[1]);
  2850. $lengths = array_map(array('fUTF8', 'len'), $valid_values);
  2851. $longest = max($lengths);
  2852. $column_match[1] = ' VARCHAR(' . $longest . ')';
  2853. $column_def = join('', array_slice($column_match, 1));
  2854. $sql = $this->database->escape(
  2855. "ALTER TABLE %r MODIFY %r ",
  2856. $data['table'],
  2857. $data['column_name']
  2858. ) . $column_def;
  2859. } elseif ($data['type'] == 'drop_primary_key') {
  2860. // MySQL doesn't allow a column to be auto_increment if it is not a primary key
  2861. if (count($data['column_names']) == 1) {
  2862. $column_match[3] = ' NOT NULL';
  2863. if (!empty($column_match[5])) {
  2864. $column_match[5] = '';
  2865. }
  2866. $column_def = join('', array_slice($column_match, 1));
  2867. $before_statements[] = $this->database->escape(
  2868. "ALTER TABLE %r MODIFY %r ",
  2869. $data['table'],
  2870. $data['column_names'][0]
  2871. ) . $column_def;
  2872. }
  2873. } elseif ($data['type'] == 'add_primary_key') {
  2874. if ($data['autoincrement']) {
  2875. $sql = preg_replace('#\s+autoincrement#i', '', $sql);
  2876. $column_match[5] = ' AUTO_INCREMENT';
  2877. $column_def = join('', array_slice($column_match, 1));
  2878. $after_statements[] = $this->database->escape(
  2879. "ALTER TABLE %r MODIFY %r " . $column_def,
  2880. $data['table'],
  2881. $data['column_name']
  2882. );
  2883. }
  2884. } elseif ($data['type'] == 'drop_foreign_key') {
  2885. $found = preg_match(
  2886. '#CONSTRAINT\s+"(\w+)"\s+FOREIGN KEY \("' . preg_quote($data['column_name'], '#') . '"\) REFERENCES "([^"]+)" \("([^"]+)"\)(?:\sON\sDELETE\s(SET\sNULL|SET\sDEFAULT|CASCADE|NO\sACTION|RESTRICT))?(?:\sON\sUPDATE\s(SET\sNULL|SET\sDEFAULT|CASCADE|NO\sACTION|RESTRICT))?#',
  2887. $create_sql,
  2888. $match
  2889. );
  2890. if (!$found) {
  2891. $this->throwException(
  2892. self::compose(
  2893. 'The column "%1$s" in the table "%2$s" does not have a foreign key constraint',
  2894. $data['column_name'],
  2895. $data['table']
  2896. ),
  2897. $sql
  2898. );
  2899. }
  2900. $sql = $this->database->escape(
  2901. "ALTER TABLE %r DROP FOREIGN KEY %r",
  2902. $data['table'],
  2903. $match[1]
  2904. );
  2905. } elseif ($data['type'] == 'add_foreign_key') {
  2906. // MySQL has terrible error messages for non-existent foreign tables and columns
  2907. try {
  2908. $row = $this->database->query("SHOW CREATE TABLE %r", $data['foreign_table'])->fetchRow();
  2909. } catch (fSQLException $e) {
  2910. // We catch and throw a new exception so the exception message
  2911. // references the SQL statement passed to this method
  2912. $this->throwException(
  2913. self::compose(
  2914. 'The referenced table "%1$s" does not exist',
  2915. $data['foreign_table']
  2916. ),
  2917. $sql
  2918. );
  2919. }
  2920. $foreign_create_sql = $row['Create Table'];
  2921. $found = preg_match(
  2922. '#(?<=,|\()\s+(?:"|\`)' . $data['foreign_column'] . '(?:"|\`)(\s+(?:[a-z]+)(?:\([^)]+\))?(?: unsigned)?(?: zerofill)?(?: character set [^ ]+)?(?: collate [^ ]+)?)( NULL)?( NOT NULL)?( DEFAULT (?:(?:[^, \']*|\'(?:\'\'|[^\']+)*\')))?( auto_increment)?( COMMENT \'(?:\'\'|[^\']+)*\')?( ON UPDATE CURRENT_TIMESTAMP)?\s*(?:,|\s*(?=\)))#mi',
  2923. $foreign_create_sql,
  2924. $column_match
  2925. );
  2926. if (!$found) {
  2927. $this->throwException(
  2928. self::compose(
  2929. 'The referenced column "%1$s" does not exist in the referenced table "%2$s"',
  2930. $data['foreign_column'],
  2931. $data['foreign_table']
  2932. ),
  2933. $sql
  2934. );
  2935. }
  2936. } elseif ($data['type'] == 'drop_unique') {
  2937. preg_match_all('/\bUNIQUE\s+KEY\s+"([^"]+)"\s+\("(.*?)"\),?\n/i', $create_sql, $matches, PREG_SET_ORDER);
  2938. $matched = FALSE;
  2939. foreach ($matches as $match) {
  2940. $columns = explode('","', $match[2]);
  2941. sort($columns);
  2942. sort($data['column_names']);
  2943. if ($columns != $data['column_names']) {
  2944. continue;
  2945. }
  2946. $matched = TRUE;
  2947. $sql = $this->database->escape(
  2948. "ALTER TABLE %r DROP INDEX %r",
  2949. $data['table'],
  2950. $match[1]
  2951. );
  2952. }
  2953. if (!$matched) {
  2954. if (count($data['column_names']) > 1) {
  2955. $message = self::compose(
  2956. 'The columns "%1$s" in the table "%2$s" do not have a unique constraint',
  2957. join('", "', $data['column_names']),
  2958. $data['table']
  2959. );
  2960. } else {
  2961. $message = self::compose(
  2962. 'The column "%1$s" in the table "%2$s" does not have a unique constraint',
  2963. reset($data['column_names']),
  2964. $data['table']
  2965. );
  2966. }
  2967. $this->throwException($message, $sql);
  2968. }
  2969. } elseif ($data['type'] == 'add_unique') {
  2970. // MySQL handles the normalized syntax
  2971. }
  2972. $foreign_keys = array();
  2973. $recreate_foreign_keys = FALSE;
  2974. if (in_array($data['type'], array('drop_column', 'rename_column', 'alter_type', 'set_not_null', 'drop_not_null', 'drop_primary_key', 'drop_unique'))) {
  2975. $foreign_keys = $this->getMySQLForeignKeys($data['table'], isset($data['column_names']) ? $data['column_names'] : $data['column_name']);
  2976. $new_foreign_keys = array();
  2977. foreach ($foreign_keys as $foreign_key) {
  2978. $extra_statements[] = $this->database->escape(
  2979. "ALTER TABLE %r DROP FOREIGN KEY %r",
  2980. $foreign_key['table'],
  2981. $foreign_key['constraint_name']
  2982. );
  2983. $rollback_statements[] = $this->database->escape(
  2984. "ALTER TABLE %r ADD FOREIGN KEY (%r) REFERENCES %r(%r) ON DELETE " . $foreign_key['on_delete'] . " ON UPDATE " . $foreign_key['on_update'],
  2985. $foreign_key['table'],
  2986. $foreign_key['column'],
  2987. $foreign_key['foreign_table'],
  2988. $foreign_key['foreign_column']
  2989. );
  2990. if ($data['type'] == 'rename_column') {
  2991. if ($foreign_key['foreign_table'] == $data['table']) {
  2992. $foreign_key['foreign_column'] = $data['new_column_name'];
  2993. } elseif ($foreign_key['table'] == $data['table']) {
  2994. $foreign_key['column'] = $data['new_column_name'];
  2995. }
  2996. }
  2997. $new_foreign_keys[] = $foreign_key;
  2998. }
  2999. $foreign_keys = $new_foreign_keys;
  3000. $recreate_foreign_keys = TRUE;
  3001. }
  3002. // Put the original SQL into the middle of the extra statements to ensure
  3003. // the column change is not made until all of the foreign keys have been dropped
  3004. $extra_statements = array_merge($extra_statements, $before_statements);
  3005. $extra_statements[] = $sql;
  3006. $extra_statements = array_merge($extra_statements, $after_statements);
  3007. $sql = array_shift($extra_statements);
  3008. if ($recreate_foreign_keys) {
  3009. foreach ($foreign_keys as $foreign_key) {
  3010. // Once a primary key is dropped, it can no longer be references by foreign
  3011. // keys since the values can't be guaranteed to be unique
  3012. if ($data['type'] == 'drop_primary_key' && $foreign_key['foreign_table'] == $data['table']) {
  3013. continue;
  3014. }
  3015. // For a dropped column we want to recreate the foreign keys that
  3016. // reference other columns in unique contraints, but we need
  3017. // to skip those referncing the column specifically
  3018. if ($data['type'] == 'drop_column') {
  3019. $referenced_column = $foreign_key['foreign_table'] == $data['table'] && $foreign_key['foreign_column'] == $data['column_name'];
  3020. $column_itself = $foreign_key['table'] == $data['table'] && $foreign_key['column'] == $data['column_name'];
  3021. if ($referenced_column || $column_itself) {
  3022. continue;
  3023. }
  3024. }
  3025. $extra_statements[] = $this->database->escape(
  3026. "ALTER TABLE %r ADD FOREIGN KEY (%r) REFERENCES %r(%r) ON DELETE " . $foreign_key['on_delete'] . " ON UPDATE " . $foreign_key['on_update'],
  3027. $foreign_key['table'],
  3028. $foreign_key['column'],
  3029. $foreign_key['foreign_table'],
  3030. $foreign_key['foreign_column']
  3031. );
  3032. }
  3033. }
  3034. return $sql;
  3035. }
  3036. /**
  3037. * Translates Flourish SQL `ALTER TABLE` statements to the appropriate
  3038. * statements for Oracle
  3039. *
  3040. * @param string $sql The SQL statements that will be executed against the database
  3041. * @param array &$extra_statements Any extra SQL statements required for Oracle
  3042. * @param array $data Data parsed from the `ALTER TABLE` statement
  3043. * @return string The modified SQL statement
  3044. */
  3045. private function translateOracleAlterTableStatements($sql, &$extra_statements, $data)
  3046. {
  3047. $data['schema'] = strtolower($this->database->getUsername());
  3048. $data['table_without_schema'] = $data['table'];
  3049. if (strpos($data['table'], '.') !== FALSE) {
  3050. list ($data['schema'], $data['table_without_schema']) = explode('.', $data['table']);
  3051. }
  3052. if (in_array($data['type'], array('drop_check_constraint', 'drop_primary_key', 'drop_foreign_key', 'drop_unique'))) {
  3053. $column_info = $this->database->query(
  3054. "SELECT
  3055. ATC.COLUMN_NAME
  3056. FROM
  3057. ALL_TABLES AT LEFT JOIN
  3058. ALL_TAB_COLUMNS ATC ON
  3059. ATC.OWNER = AT.OWNER AND
  3060. ATC.TABLE_NAME = AT.TABLE_NAME AND
  3061. LOWER(ATC.COLUMN_NAME) = %s
  3062. WHERE
  3063. LOWER(AT.OWNER) = %s AND
  3064. LOWER(AT.TABLE_NAME) = %s",
  3065. isset($data['column_name']) ? $data['column_name'] : '',
  3066. $data['schema'],
  3067. $data['table_without_schema']
  3068. );
  3069. if (!$column_info->countReturnedRows()) {
  3070. $this->throwException(
  3071. self::compose(
  3072. 'The table "%1$s" does not exist',
  3073. $data['table']
  3074. ),
  3075. $sql
  3076. );
  3077. }
  3078. if (isset($data['column_name'])) {
  3079. $row = $column_info->fetchRow();
  3080. if (!strlen($row['column_name'])) {
  3081. $this->throwException(
  3082. self::compose(
  3083. 'The column "%1$s" does not exist in the table "%2$s"',
  3084. $data['column_name'],
  3085. $data['table']
  3086. ),
  3087. $sql
  3088. );
  3089. }
  3090. }
  3091. }
  3092. if ($data['type'] == 'drop_check_constraint' || $data['type'] == 'set_check_constraint') {
  3093. $constraints = $this->database->query(
  3094. "SELECT
  3095. AC.CONSTRAINT_NAME,
  3096. AC.SEARCH_CONDITION
  3097. FROM
  3098. ALL_TAB_COLUMNS ATC INNER JOIN
  3099. ALL_CONS_COLUMNS ACC ON
  3100. ATC.OWNER = ACC.OWNER AND
  3101. ATC.COLUMN_NAME = ACC.COLUMN_NAME AND
  3102. ATC.TABLE_NAME = ACC.TABLE_NAME AND
  3103. ACC.POSITION IS NULL INNER JOIN
  3104. ALL_CONSTRAINTS AC ON
  3105. AC.OWNER = ACC.OWNER AND
  3106. AC.CONSTRAINT_NAME = ACC.CONSTRAINT_NAME AND
  3107. AC.CONSTRAINT_TYPE = 'C' AND
  3108. AC.STATUS = 'ENABLED'
  3109. WHERE
  3110. LOWER(ATC.OWNER) = %s AND
  3111. LOWER(ATC.TABLE_NAME) = %s AND
  3112. LOWER(ATC.COLUMN_NAME) = %s",
  3113. $data['schema'],
  3114. $data['table_without_schema'],
  3115. $data['column_name']
  3116. );
  3117. $constraint_name = NULL;
  3118. foreach ($constraints as $row) {
  3119. if (preg_match("#^\s*\"?\w+\"?\s+IN\s+(\(\s*(?:(?<!')'(?:''|[^']+)*'|%\d+\\\$s)(?:\s*,\s*(?:(?<!')'(?:''|[^']+)*'|%\d+\\\$s))*\s*\))\s*$#i", $row['search_condition'])) {
  3120. $constraint_name = $row['constraint_name'];
  3121. break;
  3122. } elseif (preg_match('/^\s*"?' . preg_quote($data['column_name'], '/') . '"?\s*=\s*\'((\'\'|[^\']+)*)\'(\s+OR\s+"?' . preg_quote($data['column_name'], '/') . '"?\s*=\s*\'((\'\'|[^\']+)*)\')*\s*$/i', $row['search_condition'])) {
  3123. $constraint_name = $row['constraint_name'];
  3124. break;
  3125. }
  3126. }
  3127. }
  3128. if ($data['type'] == 'set_not_null' || $data['type'] == 'drop_not_null') {
  3129. $not_null_result = $this->database->query(
  3130. "SELECT
  3131. ATC.NULLABLE
  3132. FROM
  3133. ALL_TAB_COLUMNS ATC
  3134. WHERE
  3135. LOWER(ATC.OWNER) = %s AND
  3136. LOWER(ATC.TABLE_NAME) = %s AND
  3137. LOWER(ATC.COLUMN_NAME) = %s",
  3138. $data['schema'],
  3139. $data['table_without_schema'],
  3140. $data['column_name']
  3141. );
  3142. $not_null = $not_null_result->countReturnedRows() && $not_null_result->fetchScalar() == 'N';
  3143. }
  3144. if ($data['type'] == 'set_not_null' && isset($data['default']) && $data['default'] == "''") {
  3145. $data['type'] = 'drop_not_null';
  3146. $data['default'] = ' NULL';
  3147. }
  3148. if ($data['type'] == 'column_comment') {
  3149. // Oracle handles the normalized syntax
  3150. } elseif ($data['type'] == 'rename_table') {
  3151. // Oracle handles the normalized syntax
  3152. } elseif ($data['type'] == 'rename_column') {
  3153. // When renaming a primary key column we need to check
  3154. // for triggers that implement autoincrement
  3155. $res = $this->database->query(
  3156. "SELECT
  3157. TRIGGER_NAME,
  3158. TRIGGER_BODY
  3159. FROM
  3160. ALL_TRIGGERS
  3161. WHERE
  3162. TRIGGERING_EVENT LIKE 'INSERT%' AND
  3163. STATUS = 'ENABLED' AND
  3164. TRIGGER_NAME NOT LIKE 'BIN\$%' AND
  3165. LOWER(TABLE_NAME) = %s AND
  3166. LOWER(OWNER) = %s",
  3167. $data['table_without_schema'],
  3168. $data['schema']
  3169. );
  3170. foreach ($res as $row) {
  3171. if (!preg_match('#\s+:new\."?' . preg_quote($data['column_name'], '#') . '"?\s+FROM\s+DUAL#i', $row['trigger_body'])) {
  3172. continue;
  3173. }
  3174. $trigger = 'CREATE OR REPLACE TRIGGER '. $row['trigger_name'] . "\n";
  3175. $trigger .= "BEFORE INSERT ON " . $data['table_without_schema'] . "\n";
  3176. $trigger .= "FOR EACH ROW\n";
  3177. $trigger .= preg_replace(
  3178. '#( :new\.)' . preg_quote($data['column_name'], '#') . '( )#i',
  3179. '\1' . $data['new_column_name'] . '\2',
  3180. $row['trigger_body']
  3181. );
  3182. $extra_statements[] = $trigger;
  3183. }
  3184. } elseif ($data['type'] == 'add_column') {
  3185. // If NOT NULL DEFAULT '' is present, both are removed since Oracle converts '' to NULL
  3186. $data['column_definition'] = preg_replace('#(\bNOT\s+NULL\s+DEFAULT\s+\'\'|\bDEFAULT\s+\'\'\s+NOT\s+NULL)#', '', $data['column_definition']);
  3187. // Oracle does not support ON UPDATE clauses
  3188. $data['column_definition'] = preg_replace('#(\sON\s+UPDATE\s+(CASCADE|SET\s+NULL|NO\s+ACTION|RESTRICT))#i', '', $data['column_definition']);
  3189. // Oracle requires NOT NULL to come after the DEFAULT value or UNIQUE constraint
  3190. $data['column_definition'] = preg_replace('#(\s+NOT\s+NULL)((?:\s+UNIQUE|\s+DEFAULT\s+(?:[^, \'\n]*|\'(?:\'\'|[^\']+)*\'))+)#i', '\2\1', $data['column_definition']);
  3191. $sql = $this->database->escape(
  3192. 'ALTER TABLE %r ADD ',
  3193. $data['table']
  3194. ) . $data['column_definition'];
  3195. $sql = $this->translateDataTypes($sql);
  3196. // Create sequences and triggers for Oracle
  3197. if (stripos($sql, 'autoincrement') !== FALSE && preg_match('#^\s*(?:[a-z]+)(?:\((?:\d+)\))?.*?\bAUTOINCREMENT\b.*$#iD', $sql, $matches)) {
  3198. // If we are creating a new autoincrementing primary key on an existing
  3199. // table we have to take some extra steps to pre-populate the
  3200. // auto-incrementing column, otherwise Oracle will error out
  3201. if (preg_match('#\bPRIMARY\s+KEY\b#i', $sql)) {
  3202. $sql = preg_replace('# PRIMARY\s+KEY\b#i', '', $sql);
  3203. $extra_statements[] = $this->database->escape(
  3204. "UPDATE %r SET %r = ROWNUM",
  3205. $data['table'],
  3206. $data['column_name']
  3207. );
  3208. $extra_statements[] = $this->database->escape(
  3209. "ALTER TABLE %r ADD CONSTRAINT %r PRIMARY KEY (%r)",
  3210. $data['table'],
  3211. $this->generateConstraintName($sql, 'pk'),
  3212. $data['column_name']
  3213. );
  3214. }
  3215. $table_column = substr(str_replace('"' , '', $data['table']) . '_' . str_replace('"', '', $data['column_name']), 0, 26);
  3216. $sequence_name = $table_column . '_seq';
  3217. $trigger_name = $table_column . '_trg';
  3218. $sequence = "DECLARE
  3219. create_seq_sql VARCHAR2(200);
  3220. BEGIN
  3221. SELECT
  3222. 'CREATE SEQUENCE " . $sequence_name . " START WITH ' || (SQ.TOTAL_ROWS + 1)
  3223. INTO
  3224. create_seq_sql
  3225. FROM
  3226. (SELECT COUNT(*) TOTAL_ROWS FROM " . $data['table'] . ") SQ \;
  3227. EXECUTE IMMEDIATE create_seq_sql\;
  3228. END\;";
  3229. $trigger = 'CREATE OR REPLACE TRIGGER '. $trigger_name . "\n";
  3230. $trigger .= "BEFORE INSERT ON " . $data['table'] . "\n";
  3231. $trigger .= "FOR EACH ROW\n";
  3232. $trigger .= "BEGIN\n";
  3233. $trigger .= " IF :new." . $data['column_name'] . " IS NULL THEN\n";
  3234. $trigger .= " SELECT " . $sequence_name . ".nextval INTO :new." . $data['column_name'] . " FROM dual;\n";
  3235. $trigger .= " END IF;\n";
  3236. $trigger .= "END;";
  3237. $extra_statements[] = $sequence;
  3238. $extra_statements[] = $trigger;
  3239. $sql = preg_replace('#\s+autoincrement\b#i', '', $sql);
  3240. }
  3241. } elseif ($data['type'] == 'drop_column') {
  3242. $sql .= ' CASCADE CONSTRAINTS';
  3243. // Drop any triggers and sequences that implement autoincrement for the column
  3244. $res = $this->database->query(
  3245. "SELECT
  3246. TRIGGER_NAME,
  3247. TRIGGER_BODY
  3248. FROM
  3249. ALL_TRIGGERS
  3250. WHERE
  3251. TRIGGERING_EVENT LIKE 'INSERT%' AND
  3252. STATUS = 'ENABLED' AND
  3253. TRIGGER_NAME NOT LIKE 'BIN\$%' AND
  3254. LOWER(TABLE_NAME) = %s AND
  3255. LOWER(OWNER) = %s",
  3256. $data['table_without_schema'],
  3257. $data['schema']
  3258. );
  3259. foreach ($res as $row) {
  3260. if (!preg_match('#SELECT\s+"?(\w+)"?\.nextval\s+INTO\s+:new\."?' . preg_quote($data['column_name'], '#') . '"?\s+FROM\s+dual#i', $row['trigger_body'], $match)) {
  3261. continue;
  3262. }
  3263. $extra_statements[] = $this->database->escape("DROP SEQUENCE %r", $match[1]);
  3264. $extra_statements[] = $this->database->escape("DROP TRIGGER %r", $row['trigger_name']);
  3265. }
  3266. } elseif ($data['type'] == 'alter_type') {
  3267. $data['data_type'] = $this->translateDataTypes($data['data_type']);
  3268. $sql = $this->database->escape(
  3269. "ALTER TABLE %r MODIFY (%r ",
  3270. $data['table'],
  3271. $data['column_name']
  3272. ) . $data['data_type'] . ')';
  3273. } elseif ($data['type'] == 'set_default') {
  3274. $sql = $this->database->escape(
  3275. "ALTER TABLE %r MODIFY (%r DEFAULT ",
  3276. $data['table'],
  3277. $data['column_name']
  3278. ) . $data['default_value'] . ')';
  3279. } elseif ($data['type'] == 'drop_default') {
  3280. $sql = $this->database->escape(
  3281. "ALTER TABLE %r MODIFY (%r DEFAULT NULL)",
  3282. $data['table'],
  3283. $data['column_name']
  3284. );
  3285. } elseif ($data['type'] == 'set_not_null') {
  3286. // If it is already NOT NULL, don't set it again since it will cause an error
  3287. if ($not_null_result->countReturnedRows() && $not_null) {
  3288. if (isset($data['default'])) {
  3289. $sql = $this->database->escape(
  3290. "ALTER TABLE %r MODIFY (%r DEFAULT ",
  3291. $data['table'],
  3292. $data['column_name']
  3293. ) . $data['default'] . ')';
  3294. } else {
  3295. $sql = "SELECT 'noop - no NOT NULL to set' FROM dual";
  3296. }
  3297. } else {
  3298. $sql = $this->database->escape(
  3299. "ALTER TABLE %r MODIFY (%r",
  3300. $data['table'],
  3301. $data['column_name']
  3302. );
  3303. if (isset($data['default'])) {
  3304. $sql .= ' DEFAULT ' . $data['default'];
  3305. }
  3306. $sql .= ' NOT NULL)';
  3307. }
  3308. } elseif ($data['type'] == 'drop_not_null') {
  3309. if (!$not_null_result->countReturnedRows() || $not_null) {
  3310. $sql = $this->database->escape(
  3311. "ALTER TABLE %r MODIFY (%r",
  3312. $data['table'],
  3313. $data['column_name']
  3314. );
  3315. if (isset($data['default'])) {
  3316. $sql .= ' DEFAULT ' . $data['default'];
  3317. }
  3318. $sql .= ' NULL)';
  3319. // If it is already NULL, don't set it again since it will cause an error
  3320. } else {
  3321. if (isset($data['default'])) {
  3322. $sql = $this->database->escape(
  3323. "ALTER TABLE %r MODIFY (%r DEFAULT",
  3324. $data['table'],
  3325. $data['column_name']
  3326. ) . $data['default'] . ')';
  3327. } else {
  3328. $sql = "SELECT 'noop - no NOT NULL to drop' FROM dual";
  3329. }
  3330. }
  3331. } elseif ($data['type'] == 'drop_check_constraint') {
  3332. if (!$constraint_name) {
  3333. $this->throwException(
  3334. self::compose(
  3335. 'The column "%1$s" in the table "%2$s" does not have a check constraint',
  3336. $data['column_name'],
  3337. $data['table']
  3338. ),
  3339. $sql
  3340. );
  3341. }
  3342. $sql = $this->database->escape(
  3343. "ALTER TABLE %r DROP CONSTRAINT %r",
  3344. $data['table'],
  3345. $constraint_name
  3346. );
  3347. } elseif ($data['type'] == 'set_check_constraint') {
  3348. if ($constraint_name) {
  3349. $extra_statements[] = $this->database->escape(
  3350. "ALTER TABLE %r DROP CONSTRAINT %r",
  3351. $data['table'],
  3352. $constraint_name
  3353. );
  3354. }
  3355. $sql = $this->database->escape(
  3356. "ALTER TABLE %r ADD CONSTRAINT %r",
  3357. $data['table'],
  3358. $this->generateConstraintName($sql, 'ck')
  3359. ) . $data['constraint'];
  3360. $extra_statements[] = $sql;
  3361. $sql = array_shift($extra_statements);
  3362. } elseif ($data['type'] == 'drop_primary_key') {
  3363. $constraint_columns = $this->database->query(
  3364. "SELECT
  3365. AC.CONSTRAINT_NAME CONSTRAINT_NAME,
  3366. LOWER(ACC.COLUMN_NAME) \"COLUMN\",
  3367. ANC.SEARCH_CONDITION
  3368. FROM
  3369. ALL_CONSTRAINTS AC INNER JOIN
  3370. ALL_CONS_COLUMNS ACC ON
  3371. AC.CONSTRAINT_NAME = ACC.CONSTRAINT_NAME AND
  3372. AC.OWNER = ACC.OWNER LEFT JOIN
  3373. ALL_CONS_COLUMNS ANCC ON
  3374. ACC.OWNER = ANCC.OWNER AND
  3375. ACC.TABLE_NAME = ANCC.TABLE_NAME AND
  3376. ACC.COLUMN_NAME = ANCC.COLUMN_NAME LEFT JOIN
  3377. ALL_CONSTRAINTS ANC ON
  3378. ANC.CONSTRAINT_NAME = ANCC.CONSTRAINT_NAME AND
  3379. ANC.OWNER = ANCC.OWNER AND
  3380. ANC.CONSTRAINT_TYPE = 'C' AND
  3381. ANC.STATUS = 'ENABLED'
  3382. WHERE
  3383. AC.CONSTRAINT_TYPE = 'P' AND
  3384. LOWER(AC.OWNER) = %s AND
  3385. LOWER(AC.TABLE_NAME) = %s",
  3386. $data['schema'],
  3387. $data['table_without_schema']
  3388. );
  3389. $constraint_name = NULL;
  3390. $primary_key_columns = array();
  3391. $nullable = FALSE;
  3392. foreach ($constraint_columns as $row) {
  3393. $constraint_name = $row['constraint_name'];
  3394. $primary_key_columns[] = $row['column'];
  3395. $nullable = strtolower($row['search_condition']) != '"' . $row['column'] . '" is not null';
  3396. }
  3397. if (!$constraint_name) {
  3398. $this->throwException(
  3399. self::compose(
  3400. 'The table "%1$s" does not have a primary key constraint',
  3401. $data['table']
  3402. ),
  3403. $sql
  3404. );
  3405. }
  3406. $sql = $this->database->escape(
  3407. "ALTER TABLE %r DROP CONSTRAINT %r CASCADE",
  3408. $data['table'],
  3409. $constraint_name
  3410. );
  3411. // When dropping a primary key we want to drop any trigger
  3412. // and sequence used to implement autoincrement
  3413. $res = $this->database->query(
  3414. "SELECT
  3415. TRIGGER_NAME,
  3416. TRIGGER_BODY
  3417. FROM
  3418. ALL_TRIGGERS
  3419. WHERE
  3420. TRIGGERING_EVENT LIKE 'INSERT%' AND
  3421. STATUS = 'ENABLED' AND
  3422. TRIGGER_NAME NOT LIKE 'BIN\$%' AND
  3423. LOWER(TABLE_NAME) = %s AND
  3424. LOWER(OWNER) = %s",
  3425. $data['table_without_schema'],
  3426. $data['schema']
  3427. );
  3428. foreach ($res as $row) {
  3429. if (!preg_match('#SELECT\s+"?(\w+)"?\.nextval\s+INTO\s+:new\.("?\w+"?)\s+FROM\s+DUAL#i', $row['trigger_body'], $match)) {
  3430. continue;
  3431. }
  3432. $extra_statements[] = $this->database->escape(
  3433. "DROP TRIGGER %r",
  3434. $data['schema'] . '.' . $row['trigger_name']
  3435. );
  3436. $extra_statements[] = $this->database->escape(
  3437. "DROP SEQUENCE %r",
  3438. $data['schema'] . '.' . $match[1]
  3439. );
  3440. }
  3441. if (count($primary_key_columns) == 1 && $nullable) {
  3442. $extra_statements[] = $this->database->escape(
  3443. "ALTER TABLE %r MODIFY (%r NOT NULL)",
  3444. $data['table'],
  3445. reset($primary_key_columns)
  3446. );
  3447. }
  3448. } elseif ($data['type'] == 'add_primary_key') {
  3449. $sql = $this->database->escape(
  3450. "ALTER TABLE %r ADD CONSTRAINT %r PRIMARY KEY (%r)",
  3451. $data['table'],
  3452. $this->generateConstraintName($sql, 'pk'),
  3453. $data['column_names']
  3454. );
  3455. if ($data['autoincrement']) {
  3456. $extra_statements[] = $sql;
  3457. $sql = $this->database->escape(
  3458. "UPDATE %r SET %r = ROWNUM",
  3459. $data['table'],
  3460. $data['column_name']
  3461. );
  3462. $table_column = substr(str_replace('"' , '', $data['table']) . '_' . str_replace('"', '', $data['column_name']), 0, 26);
  3463. $sequence_name = $table_column . '_seq';
  3464. $trigger_name = $table_column . '_trg';
  3465. $sequence = "DECLARE
  3466. create_seq_sql VARCHAR2(200);
  3467. BEGIN
  3468. SELECT
  3469. 'CREATE SEQUENCE " . $sequence_name . " START WITH ' || (SQ.TOTAL_ROWS + 1)
  3470. INTO
  3471. create_seq_sql
  3472. FROM
  3473. (SELECT COUNT(*) TOTAL_ROWS FROM " . $data['table'] . ") SQ \;
  3474. EXECUTE IMMEDIATE create_seq_sql\;
  3475. END\;";
  3476. $trigger = 'CREATE OR REPLACE TRIGGER '. $trigger_name . "\n";
  3477. $trigger .= "BEFORE INSERT ON " . $data['table'] . "\n";
  3478. $trigger .= "FOR EACH ROW\n";
  3479. $trigger .= "BEGIN\n";
  3480. $trigger .= " IF :new." . $data['column_name'] . " IS NULL THEN\n";
  3481. $trigger .= " SELECT " . $sequence_name . ".nextval INTO :new." . $data['column_name'] . " FROM dual;\n";
  3482. $trigger .= " END IF;\n";
  3483. $trigger .= "END;";
  3484. $extra_statements[] = $sequence;
  3485. $extra_statements[] = $trigger;
  3486. }
  3487. } elseif ($data['type'] == 'drop_foreign_key') {
  3488. $constraint = $this->database->query(
  3489. "SELECT
  3490. AC.CONSTRAINT_NAME CONSTRAINT_NAME
  3491. FROM
  3492. ALL_CONSTRAINTS AC INNER JOIN
  3493. ALL_CONS_COLUMNS ACC ON
  3494. AC.CONSTRAINT_NAME = ACC.CONSTRAINT_NAME AND
  3495. AC.OWNER = ACC.OWNER
  3496. WHERE
  3497. AC.CONSTRAINT_TYPE = 'R' AND
  3498. LOWER(AC.OWNER) = %s AND
  3499. LOWER(AC.TABLE_NAME) = %s AND
  3500. LOWER(ACC.COLUMN_NAME) = %s",
  3501. $data['schema'],
  3502. $data['table_without_schema'],
  3503. $data['column_name']
  3504. );
  3505. if (!$constraint->countReturnedRows()) {
  3506. $this->throwException(
  3507. self::compose(
  3508. 'The column "%1$s" in the table "%2$s" does not have a foreign key constraint',
  3509. $data['column_name'],
  3510. $data['table']
  3511. ),
  3512. $sql
  3513. );
  3514. }
  3515. $sql = $this->database->escape(
  3516. "ALTER TABLE %r DROP CONSTRAINT %r",
  3517. $data['table'],
  3518. $constraint->fetchScalar()
  3519. );
  3520. } elseif ($data['type'] == 'add_foreign_key') {
  3521. // Oracle does not support ON UPDATE clauses
  3522. $data['references'] = preg_replace('#(\sON\s+UPDATE\s+(CASCADE|SET\s+NULL|NO\s+ACTION|RESTRICT))#i', '', $data['references']);
  3523. $sql = $this->database->escape(
  3524. "ALTER TABLE %r ADD CONSTRAINT %r FOREIGN KEY (%r) REFERENCES " . $data['references'],
  3525. $data['table'],
  3526. $this->generateConstraintName($sql, 'fk'),
  3527. $data['column_name']
  3528. );
  3529. } elseif ($data['type'] == 'drop_unique') {
  3530. $constraint_rows = $this->database->query(
  3531. "SELECT
  3532. AC.CONSTRAINT_NAME,
  3533. LOWER(ACC.COLUMN_NAME) \"COLUMN\"
  3534. FROM
  3535. ALL_CONSTRAINTS AC INNER JOIN
  3536. ALL_CONS_COLUMNS ACC ON
  3537. AC.CONSTRAINT_NAME = ACC.CONSTRAINT_NAME AND
  3538. AC.OWNER = ACC.OWNER
  3539. WHERE
  3540. AC.CONSTRAINT_TYPE = 'U' AND
  3541. LOWER(AC.OWNER) = %s AND
  3542. LOWER(AC.TABLE_NAME) = %s",
  3543. $data['schema'],
  3544. $data['table_without_schema']
  3545. );
  3546. $constraints = array();
  3547. foreach ($constraint_rows as $row) {
  3548. if (!isset($constraints[$row['constraint_name']])) {
  3549. $constraints[$row['constraint_name']] = array();
  3550. }
  3551. $constraints[$row['constraint_name']][] = $row['column'];
  3552. }
  3553. $constraint_name = NULL;
  3554. sort($data['column_names']);
  3555. foreach ($constraints as $name => $columns) {
  3556. sort($columns);
  3557. if ($columns == $data['column_names']) {
  3558. $constraint_name = $name;
  3559. break;
  3560. }
  3561. }
  3562. if (!$constraint_name) {
  3563. if (count($data['column_names']) > 1) {
  3564. $message = self::compose(
  3565. 'The columns "%1$s" in the table "%2$s" do not have a unique constraint',
  3566. join('", "', $data['column_names']),
  3567. $data['table']
  3568. );
  3569. } else {
  3570. $message = self::compose(
  3571. 'The column "%1$s" in the table "%2$s" does not have a unique constraint',
  3572. reset($data['column_names']),
  3573. $data['table']
  3574. );
  3575. }
  3576. $this->throwException($message, $sql);
  3577. }
  3578. $sql = $this->database->escape(
  3579. "ALTER TABLE %r DROP CONSTRAINT %r CASCADE",
  3580. $data['table'],
  3581. $constraint_name
  3582. );
  3583. } elseif ($data['type'] == 'add_unique') {
  3584. $sql = $this->database->escape(
  3585. "ALTER TABLE %r ADD CONSTRAINT %r UNIQUE (%r)",
  3586. $data['table'],
  3587. $this->generateConstraintName($sql, 'uc'),
  3588. $data['column_names']
  3589. );
  3590. }
  3591. return $sql;
  3592. }
  3593. /**
  3594. * Translates Flourish SQL `ALTER TABLE` statements to the appropriate
  3595. * statements for PostgreSQL
  3596. *
  3597. * @param string $sql The SQL statements that will be executed against the database
  3598. * @param array &$extra_statements Any extra SQL statements required for PostgreSQL
  3599. * @param array $data Data parsed from the `ALTER TABLE` statement
  3600. * @return string The modified SQL statement
  3601. */
  3602. private function translatePostgreSQLAlterTableStatements($sql, &$extra_statements, $data)
  3603. {
  3604. $data['schema'] = 'public';
  3605. $data['table_without_schema'] = $data['table'];
  3606. if (strpos($data['table'], '.') !== FALSE) {
  3607. list ($data['schema'], $data['table_without_schema']) = explode('.', $data['table']);
  3608. }
  3609. if (in_array($data['type'], array('drop_check_constraint', 'drop_primary_key', 'drop_foreign_key', 'drop_unique'))) {
  3610. $column_info = $this->database->query(
  3611. "SELECT
  3612. col.attname AS column_name
  3613. FROM
  3614. pg_namespace AS n INNER JOIN
  3615. pg_class AS t ON
  3616. t.relnamespace = n.oid LEFT JOIN
  3617. pg_attribute AS col ON
  3618. col.attrelid = t.oid AND
  3619. LOWER(col.attname) = %s AND
  3620. col.attisdropped = FALSE
  3621. WHERE
  3622. LOWER(n.nspname) = %s AND
  3623. LOWER(t.relname) = %s",
  3624. isset($data['column_name']) ? $data['column_name'] : '',
  3625. $data['schema'],
  3626. $data['table_without_schema']
  3627. );
  3628. if (!$column_info->countReturnedRows()) {
  3629. $this->throwException(
  3630. self::compose(
  3631. 'The table "%1$s" does not exist',
  3632. $data['table']
  3633. ),
  3634. $sql
  3635. );
  3636. }
  3637. if (isset($data['column_name'])) {
  3638. $row = $column_info->fetchRow();
  3639. if (!strlen($row['column_name'])) {
  3640. $this->throwException(
  3641. self::compose(
  3642. 'The column "%1$s" does not exist in the table "%2$s"',
  3643. $data['column_name'],
  3644. $data['table']
  3645. ),
  3646. $sql
  3647. );
  3648. }
  3649. }
  3650. }
  3651. if ($data['type'] == 'drop_check_constraint' || $data['type'] == 'set_check_constraint') {
  3652. $constraint = $this->database->query(
  3653. "SELECT
  3654. con.conname AS constraint_name
  3655. FROM
  3656. pg_attribute AS col INNER JOIN
  3657. pg_class AS t ON col.attrelid = t.oid INNER JOIN
  3658. pg_namespace AS n ON t.relnamespace = n.oid INNER JOIN
  3659. pg_constraint AS con ON
  3660. col.attnum = ANY (con.conkey) AND
  3661. con.conrelid = t.oid
  3662. WHERE
  3663. NOT col.attisdropped AND
  3664. (con.contype = 'c') AND
  3665. LOWER(n.nspname) = %s AND
  3666. LOWER(t.relname) = %s AND
  3667. LOWER(col.attname) = %s",
  3668. $data['schema'],
  3669. $data['table_without_schema'],
  3670. $data['column_name']
  3671. );
  3672. $constraint_name = NULL;
  3673. if ($constraint->countReturnedRows()) {
  3674. $constraint_name = $constraint->fetchScalar();
  3675. }
  3676. }
  3677. if ($data['type'] == 'column_comment') {
  3678. // PostgreSQL handles the normalized syntax
  3679. } elseif ($data['type'] == 'rename_table') {
  3680. // PostgreSQL handles the normalized syntax
  3681. } elseif ($data['type'] == 'rename_column') {
  3682. // PostgreSQL handles the normalized syntax
  3683. } elseif ($data['type'] == 'add_column') {
  3684. $sql = $this->translateDataTypes($sql);
  3685. $sql = preg_replace('#\binteger(?:\(\d+\))?\s+autoincrement\b#i', 'SERIAL', $sql);
  3686. } elseif ($data['type'] == 'drop_column') {
  3687. $sql .= ' CASCADE';
  3688. } elseif ($data['type'] == 'alter_type') {
  3689. $sql = $this->translateDataTypes($sql);
  3690. } elseif ($data['type'] == 'set_default') {
  3691. // PostgreSQL handles the normalized syntax
  3692. } elseif ($data['type'] == 'drop_default') {
  3693. // PostgreSQL handles the normalized syntax
  3694. } elseif ($data['type'] == 'set_not_null') {
  3695. if (isset($data['default'])) {
  3696. $sql = $this->database->escape(
  3697. "ALTER TABLE %r ALTER COLUMN %r SET NOT NULL",
  3698. $data['table'],
  3699. $data['column_name']
  3700. );
  3701. $extra_statements[] = $this->database->escape(
  3702. "ALTER TABLE %r ALTER COLUMN %r SET DEFAULT ",
  3703. $data['table'],
  3704. $data['column_name']
  3705. ) . $data['default'];
  3706. }
  3707. } elseif ($data['type'] == 'drop_not_null') {
  3708. // PostgreSQL handles the normalized syntax
  3709. } elseif ($data['type'] == 'set_check_constraint') {
  3710. if ($constraint_name) {
  3711. $extra_statements[] = $this->database->escape(
  3712. "ALTER TABLE %r DROP CONSTRAINT %r",
  3713. $data['table'],
  3714. $constraint_name
  3715. );
  3716. }
  3717. $sql = $this->database->escape(
  3718. "ALTER TABLE %r ADD ",
  3719. $data['table']
  3720. ) . $data['constraint'];
  3721. $extra_statements[] = $sql;
  3722. $sql = array_shift($extra_statements);
  3723. } elseif ($data['type'] == 'drop_check_constraint') {
  3724. if (!$constraint_name) {
  3725. $this->throwException(
  3726. self::compose(
  3727. 'The column "%1$s" in the table "%2$s" does not have a check constraint',
  3728. $data['column_name'],
  3729. $data['table']
  3730. ),
  3731. $sql
  3732. );
  3733. }
  3734. $sql = $this->database->escape(
  3735. "ALTER TABLE %r DROP CONSTRAINT %r",
  3736. $data['table'],
  3737. $constraint_name
  3738. );
  3739. } elseif ($data['type'] == 'drop_primary_key') {
  3740. $column_info = $this->database->query(
  3741. "SELECT
  3742. con.conname AS constraint_name,
  3743. col.attname AS column,
  3744. format_type(col.atttypid, col.atttypmod) AS data_type,
  3745. ad.adsrc AS default
  3746. FROM
  3747. pg_attribute AS col INNER JOIN
  3748. pg_class AS t ON col.attrelid = t.oid INNER JOIN
  3749. pg_namespace AS s ON t.relnamespace = s.oid INNER JOIN
  3750. pg_constraint AS con ON
  3751. col.attnum = ANY (con.conkey) AND
  3752. con.conrelid = t.oid LEFT JOIN
  3753. pg_attrdef AS ad ON t.oid = ad.adrelid AND
  3754. col.attnum = ad.adnum
  3755. WHERE
  3756. NOT col.attisdropped AND
  3757. con.contype = 'p' AND
  3758. LOWER(t.relname) = %s AND
  3759. LOWER(s.nspname) = %s",
  3760. $data['table_without_schema'],
  3761. $data['schema']
  3762. );
  3763. if (!$column_info->countReturnedRows()) {
  3764. $this->throwException(
  3765. self::compose(
  3766. 'The table "%1$s" does not have a primary key constraint',
  3767. $data['table']
  3768. ),
  3769. $sql
  3770. );
  3771. }
  3772. $row = $column_info->fetchRow();
  3773. $sql = $this->database->escape(
  3774. "ALTER TABLE %r DROP CONSTRAINT %r CASCADE",
  3775. $data['table'],
  3776. $row['constraint_name']
  3777. );
  3778. // Change serial columns to integers when removing the primary key
  3779. if ($column_info->countReturnedRows() == 1) {
  3780. if (preg_match('#^(int|bigint)#i', $row['data_type']) && preg_match('#^\s*nextval\(\'([^\']+)\'#i', $row['default'], $match)) {
  3781. $extra_statements[] = $this->database->escape(
  3782. "ALTER TABLE %r ALTER COLUMN %r DROP DEFAULT",
  3783. $data['table'],
  3784. $row['column']
  3785. );
  3786. $extra_statements[] = $this->database->escape(
  3787. "DROP SEQUENCE %r",
  3788. $match[1]
  3789. );
  3790. }
  3791. }
  3792. } elseif ($data['type'] == 'add_primary_key') {
  3793. if ($data['autoincrement']) {
  3794. $sequence_name = $this->generateConstraintName($sql, 'seq');
  3795. $extra_statements[] = $this->database->escape(
  3796. "CREATE SEQUENCE %r",
  3797. $sequence_name
  3798. );
  3799. $extra_statements[] = $this->database->escape(
  3800. "ALTER SEQUENCE %r OWNED BY %r.%r",
  3801. $sequence_name,
  3802. $data['table'],
  3803. $data['column_name']
  3804. );
  3805. $extra_statements[] = $this->database->escape(
  3806. "SELECT setval(%s, MAX(%r)) FROM %r",
  3807. $sequence_name,
  3808. $data['column_name'],
  3809. $data['table']
  3810. );
  3811. $extra_statements[] = $this->database->escape(
  3812. "ALTER TABLE %r ALTER COLUMN %r SET DEFAULT nextval(%s::regclass)",
  3813. $data['table'],
  3814. $data['column_name'],
  3815. $sequence_name
  3816. );
  3817. $sql = preg_replace('#\s+autoincrement#i', '', $sql);
  3818. }
  3819. } elseif ($data['type'] == 'drop_foreign_key') {
  3820. $constraint = $this->database->query(
  3821. "SELECT
  3822. con.conname AS constraint_name
  3823. FROM
  3824. pg_attribute AS col INNER JOIN
  3825. pg_class AS t ON col.attrelid = t.oid INNER JOIN
  3826. pg_namespace AS n ON t.relnamespace = n.oid INNER JOIN
  3827. pg_constraint AS con ON
  3828. col.attnum = ANY (con.conkey) AND
  3829. con.conrelid = t.oid
  3830. WHERE
  3831. NOT col.attisdropped AND
  3832. (con.contype = 'f') AND
  3833. LOWER(n.nspname) = %s AND
  3834. LOWER(t.relname) = %s AND
  3835. LOWER(col.attname) = %s",
  3836. $data['schema'],
  3837. $data['table_without_schema'],
  3838. $data['column_name']
  3839. );
  3840. if (!$constraint->countReturnedRows()) {
  3841. $this->throwException(
  3842. self::compose(
  3843. 'The column "%1$s" in the table "%2$s" does not have a foreign key constraint',
  3844. $data['column_name'],
  3845. $data['table']
  3846. ),
  3847. $sql
  3848. );
  3849. }
  3850. $sql = $this->database->escape(
  3851. "ALTER TABLE %r DROP CONSTRAINT %r",
  3852. $data['table'],
  3853. $constraint->fetchScalar()
  3854. );
  3855. } elseif ($data['type'] == 'add_foreign_key') {
  3856. // PostgreSQL handles the normalized syntax
  3857. } elseif ($data['type'] == 'drop_unique') {
  3858. $constraint_rows = $this->database->query(
  3859. "SELECT
  3860. con.conname AS constraint_name,
  3861. LOWER(col.attname) AS column
  3862. FROM
  3863. pg_attribute AS col INNER JOIN
  3864. pg_class AS t ON col.attrelid = t.oid INNER JOIN
  3865. pg_namespace AS n ON t.relnamespace = n.oid INNER JOIN
  3866. pg_constraint AS con ON
  3867. col.attnum = ANY (con.conkey) AND
  3868. con.conrelid = t.oid
  3869. WHERE
  3870. NOT col.attisdropped AND
  3871. (con.contype = 'u') AND
  3872. LOWER(n.nspname) = %s AND
  3873. LOWER(t.relname) = %s",
  3874. $data['schema'],
  3875. $data['table_without_schema']
  3876. );
  3877. $constraints = array();
  3878. foreach ($constraint_rows as $row) {
  3879. if (!isset($constraints[$row['constraint_name']])) {
  3880. $constraints[$row['constraint_name']] = array();
  3881. }
  3882. $constraints[$row['constraint_name']][] = $row['column'];
  3883. }
  3884. $constraint_name = NULL;
  3885. sort($data['column_names']);
  3886. foreach ($constraints as $name => $columns) {
  3887. sort($columns);
  3888. if ($columns == $data['column_names']) {
  3889. $constraint_name = $name;
  3890. break;
  3891. }
  3892. }
  3893. if (!$constraint_name) {
  3894. if (count($data['column_names']) > 1) {
  3895. $message = self::compose(
  3896. 'The columns "%1$s" in the table "%2$s" do not have a unique constraint',
  3897. join('", "', $data['column_names']),
  3898. $data['table']
  3899. );
  3900. } else {
  3901. $message = self::compose(
  3902. 'The column "%1$s" in the table "%2$s" does not have a unique constraint',
  3903. reset($data['column_names']),
  3904. $data['table']
  3905. );
  3906. }
  3907. $this->throwException($message, $sql);
  3908. }
  3909. $sql = $this->database->escape(
  3910. "ALTER TABLE %r DROP CONSTRAINT %r",
  3911. $data['table'],
  3912. $constraint_name
  3913. );
  3914. } elseif ($data['type'] == 'add_unique') {
  3915. // PostgreSQL handles the normalized syntax
  3916. }
  3917. return $sql;
  3918. }
  3919. /**
  3920. * Translates Flourish SQL `ALTER TABLE` statements to the appropriate
  3921. * statements for SQLite
  3922. *
  3923. * @param string $sql The SQL statements that will be executed against the database
  3924. * @param array &$extra_statements Any extra SQL statements required for SQLite
  3925. * @param array $data Data parsed from the `ALTER TABLE` statement
  3926. * @return string The modified SQL statement
  3927. */
  3928. private function translateSQLiteAlterTableStatements($sql, &$extra_statements, $data)
  3929. {
  3930. $toggle_foreign_key_support = FALSE;
  3931. if (!isset($this->schema_info['foreign_keys_enabled'])) {
  3932. $toggle_foreign_key_support = TRUE;
  3933. $foreign_keys_res = $this->database->query('PRAGMA foreign_keys');
  3934. if ($foreign_keys_res->countReturnedRows() && $foreign_keys_res->fetchScalar()) {
  3935. $this->schema_info['foreign_keys_enabled'] = TRUE;
  3936. $this->database->query("PRAGMA foreign_keys = 0");
  3937. } else {
  3938. $this->schema_info['foreign_keys_enabled'] = FALSE;
  3939. }
  3940. }
  3941. $temp_create_table_sql = $this->getSQLiteCreateTable($data['table']);
  3942. if ($temp_create_table_sql === NULL) {
  3943. $this->throwException(
  3944. self::compose(
  3945. 'The table "%1$s" does not exist',
  3946. $data['table']
  3947. ),
  3948. $sql
  3949. );
  3950. }
  3951. $temp_create_table_sql = preg_replace(
  3952. '#(^\s*CREATE\s+TABLE\s+)(?:`|\'|"|\[)?(\w+)(?:`|\'|"|\])?(\s*\()#i',
  3953. '\1"fl_tmp_' . $data['table'] . '"\3',
  3954. $temp_create_table_sql
  3955. );
  3956. if ($data['type'] == 'drop_primary_key' && !preg_match('#\bPRIMARY\s+KEY\b#', $temp_create_table_sql)) {
  3957. $this->throwException(
  3958. self::compose(
  3959. 'The table "%1$s" does not have a primary key constraint',
  3960. $data['table']
  3961. ),
  3962. $sql
  3963. );
  3964. }
  3965. if ($data['type'] == 'add_primary_key' && preg_match('#\bPRIMARY\s+KEY\b#', $temp_create_table_sql)) {
  3966. $this->throwException(
  3967. self::compose(
  3968. 'The table "%1$s" already has a primary key constraint',
  3969. $data['table']
  3970. ),
  3971. $sql
  3972. );
  3973. }
  3974. if ($data['type'] == 'drop_unique') {
  3975. $dropped_unique = FALSE;
  3976. }
  3977. if ($data['type'] == 'drop_foreign_key') {
  3978. $dropped_foreign_key = FALSE;
  3979. }
  3980. if (in_array($data['type'], array('column_comment', 'alter_type', 'set_not_null', 'drop_not_null', 'drop_default', 'set_default', 'drop_primary_key', 'add_primary_key', 'drop_foreign_key', 'add_foreign_key', 'drop_unique', 'add_unique', 'set_check_constraint', 'drop_check_constraint'))) {
  3981. $column_info = self::parseSQLiteColumnDefinitions($temp_create_table_sql);
  3982. if (isset($data['column_name']) && !isset($column_info[$data['column_name']])) {
  3983. $this->throwException(
  3984. self::compose(
  3985. 'The column "%1$s" does not exist in the table "%2$s"',
  3986. $data['column_name'],
  3987. $data['table']
  3988. ),
  3989. $sql
  3990. );
  3991. }
  3992. foreach ($column_info as $column => $info) {
  3993. if (isset($data['column_name']) && $column == $data['column_name']) {
  3994. if ($data['type'] == 'alter_type') {
  3995. $info['pieces']['data_type'] = ' ' . $data['data_type'];
  3996. } elseif ($data['type'] == 'set_not_null') {
  3997. $info['pieces']['not_null'] = ' NOT NULL';
  3998. $info['pieces']['null'] = '';
  3999. if (isset($data['default'])) {
  4000. $info['pieces']['default'] = ' DEFAULT ' . $data['default'];
  4001. }
  4002. } elseif ($data['type'] == 'drop_not_null') {
  4003. $info['pieces']['not_null'] = '';
  4004. $info['pieces']['null'] = '';
  4005. } elseif ($data['type'] == 'set_default') {
  4006. $info['pieces']['default'] = ' DEFAULT ' . $data['default_value'];
  4007. } elseif ($data['type'] == 'drop_default') {
  4008. $info['pieces']['default'] = '';
  4009. } elseif ($data['type'] == 'set_check_constraint') {
  4010. $info['pieces']['check_constraint'] = $data['constraint'];
  4011. } elseif ($data['type'] == 'drop_check_constraint') {
  4012. $info['pieces']['check_constraint'] = '';
  4013. } elseif ($data['type'] == 'add_primary_key') {
  4014. $info['pieces']['primary_key'] = ' PRIMARY KEY' . (version_compare($this->database->getVersion(), 3, '>=') && $data['autoincrement'] ? ' AUTOINCREMENT' : '');
  4015. } elseif ($data['type'] == 'drop_foreign_key') {
  4016. if (trim($info['pieces']['foreign_key'])) {
  4017. $dropped_foreign_key = TRUE;
  4018. }
  4019. $info['pieces']['foreign_key'] = '';
  4020. } elseif ($data['type'] == 'add_foreign_key') {
  4021. $foreign_create_table = $this->getSQLiteCreateTable($data['foreign_table']);
  4022. if ($foreign_create_table === NULL) {
  4023. $this->throwException(
  4024. self::compose(
  4025. 'The referenced table "%1$s" does not exist',
  4026. $data['foreign_table']
  4027. ),
  4028. $sql
  4029. );
  4030. }
  4031. $foreign_column_info = self::parseSQLiteColumnDefinitions($foreign_create_table);
  4032. if (!isset($foreign_column_info[$data['foreign_column']])) {
  4033. $this->throwException(
  4034. self::compose(
  4035. 'The referenced column "%1$s" does not exist in the referenced table "%2$s"',
  4036. $data['foreign_column'],
  4037. $data['foreign_table']
  4038. ),
  4039. $sql
  4040. );
  4041. }
  4042. $info['pieces']['foreign_key'] = ' REFERENCES ' . $data['references'];
  4043. } elseif ($data['type'] == 'drop_unique') {
  4044. if (trim($info['pieces']['unique'])) {
  4045. $dropped_unique = TRUE;
  4046. }
  4047. $info['pieces']['unique'] = '';
  4048. } elseif ($data['type'] == 'add_unique') {
  4049. $info['pieces']['unique'] = ' UNIQUE';
  4050. } elseif ($data['type'] == 'column_comment') {
  4051. if (preg_match('#(^\s*,)|(^\s*/\*\s*((?:(?!\*/).)*?)\s*\*/\s*,)#', $info['pieces']['comment/end'])) {
  4052. $info['pieces']['comment/end'] = ',';
  4053. }
  4054. $comment = str_replace("''", "'", substr($data['comment'], 1, -1));
  4055. if (strlen(trim($comment))) {
  4056. $info['pieces']['comment/end'] .= ' -- ' . $comment . "\n";
  4057. }
  4058. }
  4059. } elseif ($data['type'] == 'drop_primary_key') {
  4060. if (trim($info['pieces']['primary_key'])) {
  4061. $data['column_name'] = $column;
  4062. }
  4063. $info['pieces']['not_null'] = ' NOT NULL';
  4064. $info['pieces']['primary_key'] = '';
  4065. }
  4066. $temp_create_table_sql = str_replace(
  4067. $info['definition'],
  4068. join('', $info['pieces']),
  4069. $temp_create_table_sql
  4070. );
  4071. }
  4072. }
  4073. $primary_key_regex = '#(?<=,|\()\s*(?:CONSTRAINT\s+["`\[]?\w+["`\]]?\s+)?PRIMARY\s+KEY\s*\(\s*((?:\s*[\'"`\[]?\w+[\'"`\]]?\s*,\s*)*[\'"`\[]?\w+[\'"`\]]?)\s*\)\s*(?:,|\s*(?=\)))#mi';
  4074. $foreign_key_regex = '#(?<=,|\(|\*/|\n)(\s*(?:CONSTRAINT\s+["`\[]?\w+["`\]]?\s+)?FOREIGN\s+KEY\s*\(?\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*(?:,(?:[ \t]*--[^\n]*\n)?|(?:--[^\n]*\n)?\s*(?=\)))#mis';
  4075. $unique_constraint_regex = '#(?<=,|\()\s*(?:CONSTRAINT\s+["`\[]?\w+["`\]]?\s+)?UNIQUE\s*\(\s*((?:\s*[\'"`\[]?\w+[\'"`\]]?\s*,\s*)*[\'"`\[]?\w+[\'"`\]]?)\s*\)\s*(?:,|\s*(?=\)))#mi';
  4076. if (isset($data['column_name'])) {
  4077. $column_regex = '#(?:`|\'|"|\[|\b)' . preg_quote($data['column_name'], '#') . '(?:`|\'|"|\]|\b)#i';
  4078. }
  4079. if ($data['type'] == 'drop_primary_key' || $data['type'] == 'drop_column') {
  4080. // Drop any table-level primary keys
  4081. preg_match_all($primary_key_regex, $temp_create_table_sql, $matches, PREG_SET_ORDER);
  4082. foreach ($matches as $match) {
  4083. $columns = preg_split('#[\'"`\]]?\s*,\s*[\'"`\[]?#', strtolower(trim($match[1], '\'[]`"')));
  4084. sort($columns);
  4085. if ($data['type'] == 'drop_primary_key' && count($columns) == 1) {
  4086. $data['column_name'] = reset($columns);
  4087. } elseif ($data['type'] == 'drop_column') {
  4088. if (!in_array($data['column_name'], $columns)) {
  4089. continue;
  4090. }
  4091. }
  4092. $temp_create_table_sql = self::removeFromSQLiteCreateTable($temp_create_table_sql, $match[0]);
  4093. }
  4094. }
  4095. if ($data['type'] == 'drop_foreign_key' || $data['type'] == 'drop_column') {
  4096. // Drop any table-level foreign keys
  4097. preg_match_all($foreign_key_regex, $temp_create_table_sql, $matches, PREG_SET_ORDER);
  4098. foreach ($matches as $match) {
  4099. // Ignore foreign keys for other columns
  4100. if (strtolower($match[2]) != $data['column_name']) {
  4101. continue;
  4102. }
  4103. $dropped_foreign_key = TRUE;
  4104. $temp_create_table_sql = self::removeFromSQLiteCreateTable($temp_create_table_sql, $match[0]);
  4105. }
  4106. }
  4107. if ($data['type'] == 'drop_foreign_key' && !$dropped_foreign_key) {
  4108. $this->throwException(
  4109. self::compose(
  4110. 'The column "%1$s" in the table "%2$s" does not have a foreign key constraint',
  4111. $data['column_name'],
  4112. $data['table']
  4113. ),
  4114. $sql
  4115. );
  4116. }
  4117. if ($data['type'] == 'drop_unique' || $data['type'] == 'drop_column') {
  4118. // Drop any table-level unique keys
  4119. preg_match_all($unique_constraint_regex, $temp_create_table_sql, $matches, PREG_SET_ORDER);
  4120. foreach ($matches as $match) {
  4121. $columns = preg_split('#[\'"`\]]?\s*,\s*[\'"`\[]?#', strtolower(trim($match[1], '\'[]`"')));
  4122. sort($columns);
  4123. if ($data['type'] == 'drop_column') {
  4124. if (!in_array($data['column_name'], $columns)) {
  4125. continue;
  4126. }
  4127. } else {
  4128. sort($data['column_names']);
  4129. if ($columns != $data['column_names']) {
  4130. continue;
  4131. }
  4132. $dropped_unique = TRUE;
  4133. }
  4134. $temp_create_table_sql = self::removeFromSQLiteCreateTable($temp_create_table_sql, $match[0]);
  4135. }
  4136. }
  4137. if ($data['type'] == 'rename_column') {
  4138. // Rename the column in the column definition and check constraint
  4139. $column_info = self::parseSQLiteColumnDefinitions($temp_create_table_sql);
  4140. if (!isset($column_info[$data['column_name']])) {
  4141. $this->throwException(
  4142. self::compose(
  4143. 'The column "%1$s" does not exist in the table "%2$s"',
  4144. $data['column_name'],
  4145. $data['table']
  4146. ),
  4147. $sql
  4148. );
  4149. }
  4150. if (isset($column_info[$data['new_column_name']])) {
  4151. $this->throwException(
  4152. self::compose(
  4153. 'The column "%1$s" already exists in the table "%2$s"',
  4154. $data['new_column_name'],
  4155. $data['table']
  4156. ),
  4157. $sql
  4158. );
  4159. }
  4160. $info = $column_info[$data['column_name']];
  4161. $temp_create_table_sql = str_replace(
  4162. $info['definition'],
  4163. preg_replace(
  4164. '#^(\s*)[`"\'\[]?' . preg_quote($data['column_name'], '#') . '[`"\'\]]?(\s+)#i',
  4165. '\1"' . $data['new_column_name'] . '"\2',
  4166. $info['definition']
  4167. ),
  4168. $temp_create_table_sql
  4169. );
  4170. if ($info['pieces']['check_constraint']) {
  4171. $temp_create_table_sql = str_replace(
  4172. $info['pieces']['check_constraint'],
  4173. preg_replace(
  4174. '#^(\s*CHECK\s*\(\s*)[`"\'\[]?' . preg_quote($data['column_name'], '#') . '[`"\'\]]?(\s+)#i',
  4175. '\1"' . $data['new_column_name'] . '"\2',
  4176. $info['pieces']['check_constraint']
  4177. ),
  4178. $temp_create_table_sql
  4179. );
  4180. }
  4181. // Rename the column in table-level primary key
  4182. preg_match_all($primary_key_regex, $temp_create_table_sql, $matches, PREG_SET_ORDER);
  4183. foreach ($matches as $match) {
  4184. $temp_create_table_sql = str_replace(
  4185. $match[0],
  4186. preg_replace($column_regex, '"' . $data['new_column_name'] . '"', $match[0]),
  4187. $temp_create_table_sql
  4188. );
  4189. }
  4190. // Rename the column in table-level foreign key definitions
  4191. preg_match_all($foreign_key_regex, $temp_create_table_sql, $matches, PREG_SET_ORDER);
  4192. foreach ($matches as $match) {
  4193. $temp_create_table_sql = str_replace(
  4194. $match[0],
  4195. str_replace(
  4196. $match[1],
  4197. preg_replace($column_regex, '"' . $data['new_column_name'] . '"', $match[1]),
  4198. $match[0]
  4199. ),
  4200. $temp_create_table_sql
  4201. );
  4202. }
  4203. // Rename the column in table-level unique constraints
  4204. preg_match_all($unique_constraint_regex, $temp_create_table_sql, $matches, PREG_SET_ORDER);
  4205. foreach ($matches as $match) {
  4206. $temp_create_table_sql = str_replace(
  4207. $match[0],
  4208. preg_replace($column_regex, '"' . $data['new_column_name'] . '"', $match[0]),
  4209. $temp_create_table_sql
  4210. );
  4211. }
  4212. }
  4213. if ($data['type'] == 'drop_column') {
  4214. $column_info = self::parseSQLiteColumnDefinitions($temp_create_table_sql);
  4215. if (!isset($column_info[$data['column_name']])) {
  4216. $this->throwException(
  4217. self::compose(
  4218. 'The column "%1$s" does not exist in the table "%2$s"',
  4219. $data['column_name'],
  4220. $data['table']
  4221. ),
  4222. $sql
  4223. );
  4224. }
  4225. $temp_create_table_sql = self::removeFromSQLiteCreateTable(
  4226. $temp_create_table_sql,
  4227. $column_info[$data['column_name']]['definition']
  4228. );
  4229. }
  4230. if ($data['type'] == 'add_primary_key' && count($data['column_names']) > 1) {
  4231. $temp_create_table_sql = preg_replace(
  4232. '#\s*\)\s*$#D',
  4233. $this->database->escape(",\n PRIMARY KEY(%r)\n)", $data['column_names']),
  4234. $temp_create_table_sql
  4235. );
  4236. }
  4237. if ($data['type'] == 'add_unique' && count($data['column_names']) > 1) {
  4238. $temp_create_table_sql = preg_replace(
  4239. '#\s*\)\s*$#D',
  4240. $this->database->escape(",\n UNIQUE(%r)\n)", $data['column_names']),
  4241. $temp_create_table_sql
  4242. );
  4243. }
  4244. if ($data['type'] == 'add_column') {
  4245. if (!preg_match('#\s*"?\w+"?\s+\w+#', $data['column_definition'])) {
  4246. $this->throwException(
  4247. self::compose(
  4248. 'Please specify a data type for the column "%1$s"',
  4249. $data['column_name']
  4250. ),
  4251. $sql
  4252. );
  4253. }
  4254. preg_match(
  4255. '#^(.*?)((?:(?<=,|\*/|\n)\s*(?:CONSTRAINT\s+["`\[]?\w+["`\]]?\s+)?\b(?:FOREIGN\s+KEY\b|PRIMARY\s+KEY\b|UNIQUE\b).*)|(?:\s*\)\s*))$#Dis',
  4256. $temp_create_table_sql,
  4257. $match
  4258. );
  4259. if (trim($match[2]) != ')') {
  4260. $prefix = '';
  4261. $suffix = ',';
  4262. } else {
  4263. $prefix = ',';
  4264. $suffix = '';
  4265. }
  4266. // Be sure to add any necessary comma before a single-line SQL comment
  4267. // because if it is placed after, the comma will be part of the comment
  4268. if ($prefix) {
  4269. $original_match_1 = $match[1];
  4270. $match[1] = preg_replace('#(\s*--[^\n]+)(\s*)?$#Di', ',\1\2', $match[1]);
  4271. if ($match[1] != $original_match_1) {
  4272. $prefix = '';
  4273. }
  4274. }
  4275. if (version_compare($this->database->getVersion(), 3, '>=')) {
  4276. $data['column_definition'] = preg_replace('#\binteger(?:\(\d+\))?\s+autoincrement\s+primary\s+key\b#i', 'INTEGER PRIMARY KEY AUTOINCREMENT', $data['column_definition']);
  4277. $data['column_definition'] = preg_replace("#datetime\(\s*CURRENT_TIMESTAMP\s*,\s*'localtime'\s*\)#i", 'CURRENT_TIMESTAMP', $data['column_definition']);
  4278. } else {
  4279. $data['column_definition'] = preg_replace('#\binteger(?:\(\d+\))?\s+autoincrement\s+primary\s+key\b#i', 'INTEGER PRIMARY KEY', $data['column_definition']);
  4280. $data['column_definition'] = preg_replace('#CURRENT_TIMESTAMP\(\)#i', 'CURRENT_TIMESTAMP', $data['column_definition']);
  4281. }
  4282. $match[1] .= $prefix . "\n\t" . $data['column_definition'] . $suffix;
  4283. $temp_create_table_sql = $match[1] . $match[2];
  4284. }
  4285. // Clean up extra line breaks
  4286. $temp_create_table_sql = preg_replace('#\n([ \t]*\n)+#', "\n", $temp_create_table_sql);
  4287. // SQLite 3 supports renaming a table, so we need the full create
  4288. // table with all of the translated triggers, etc
  4289. if (version_compare($this->database->getVersion(), 3, '>=')) {
  4290. // We rename string placeholders to prevent confusion with
  4291. // string placeholders that are added by call to fDatabase
  4292. $temp_create_table_sql = str_replace(
  4293. '%',
  4294. '%%',
  4295. $temp_create_table_sql
  4296. );
  4297. $extra_statements = array_merge(
  4298. $extra_statements,
  4299. str_replace(
  4300. '%%',
  4301. '%',
  4302. $this->database->preprocess(
  4303. $temp_create_table_sql,
  4304. array(),
  4305. TRUE
  4306. )
  4307. )
  4308. );
  4309. // For SQLite 2 we can't rename the table, so we end up needing to
  4310. // create a new one so the temporary table doesn't need triggers
  4311. } else {
  4312. $extra_statements[] = $temp_create_table_sql;
  4313. }
  4314. $this->addSQLiteTable('fl_tmp_' . $data['table'], $temp_create_table_sql);
  4315. // Next we copy the data from the original table to the temp table
  4316. if ($data['type'] == 'rename_column') {
  4317. $column_names = $this->getSQLiteColumns($data['table']);
  4318. $new_column_names = $column_names;
  4319. $column_position = array_search($data['column_name'], $new_column_names);
  4320. $new_column_names[$column_position] = $data['new_column_name'];
  4321. } elseif ($data['type'] == 'drop_column') {
  4322. $column_names = array_diff(
  4323. $this->getSQLiteColumns($data['table']),
  4324. array($data['column_name'])
  4325. );
  4326. $new_column_names = $column_names;
  4327. } else {
  4328. $column_names = $this->getSQLiteColumns($data['table']);
  4329. $new_column_names = $column_names;
  4330. }
  4331. $extra_statements[] = $this->database->escape(
  4332. "INSERT INTO %r (%r) SELECT %r FROM %r",
  4333. 'fl_tmp_' . $data['table'],
  4334. $new_column_names,
  4335. $column_names,
  4336. $data['table']
  4337. );
  4338. // Recreate the indexes for the temp table
  4339. $indexes = $this->getSQLiteIndexes($data['table']);
  4340. foreach ($indexes as $name => $index) {
  4341. $create_sql = $index['sql'];
  4342. preg_match(
  4343. '#^\s*CREATE\s+(UNIQUE\s+)?INDEX\s+(?:[\'"`\[]?\w+[\'"`\]]?\.)?[\'"`\[]?\w+[\'"`\]]?\s+(ON\s+[\'"`\[]?\w+[\'"`\]]?)\s*(\((\s*(?:\s*[\'"`\[]?\w+[\'"`\]]?\s*,\s*)*[\'"`\[]?\w+[\'"`\]]?\s*)\))\s*$#Di',
  4344. $create_sql,
  4345. $match
  4346. );
  4347. $columns = preg_split(
  4348. '#[\'"`\]]?\s*,\s*[\'"`\[]?#',
  4349. strtolower(trim($match[4], '\'[]`"'))
  4350. );
  4351. if ($data['type'] == 'rename_column') {
  4352. $create_sql = str_replace(
  4353. $match[3],
  4354. preg_replace($column_regex, '"' . $data['new_column_name'] . '"', $match[3]),
  4355. $create_sql
  4356. );
  4357. } elseif ($data['type'] == 'drop_column') {
  4358. if (in_array($data['column_name'], $columns)) {
  4359. continue;
  4360. }
  4361. } elseif ($data['type'] == 'drop_unique') {
  4362. sort($columns);
  4363. sort($data['column_names']);
  4364. if ($columns == $data['column_names']) {
  4365. $dropped_unique = TRUE;
  4366. continue;
  4367. }
  4368. }
  4369. // The index needs to be altered to be created on the new table
  4370. $create_sql = str_replace(
  4371. $match[2],
  4372. preg_replace(
  4373. '#(?:`|\'|"|\[|\b)?' . preg_quote($data['table'], '#') . '(?:`|\'|"|\]|\b)?#',
  4374. '"fl_tmp_' . $data['table'] . '"',
  4375. $match[2]
  4376. ),
  4377. $create_sql
  4378. );
  4379. // We fix the name of the index to keep in sync with the table name
  4380. if (version_compare($this->database->getVersion(), 3, '>=')) {
  4381. $new_name = $name;
  4382. } else {
  4383. $new_name = preg_replace(
  4384. '#^' . preg_quote($data['table'], '#') . '#',
  4385. 'fl_tmp_' . $data['table'],
  4386. $name
  4387. );
  4388. }
  4389. // Ensure we have a unique index name
  4390. while (isset($indexes[$new_name])) {
  4391. if (preg_match('#(?<=_)(\d+)$#D', $new_name, $match)) {
  4392. $new_name = preg_replace('#(?<=_)\d+$#D', $match[1] + 1, $new_name);
  4393. } else {
  4394. $new_name .= '_2';
  4395. }
  4396. }
  4397. $create_sql = preg_replace(
  4398. '#[\'"`\[]?' . preg_quote($name, '#') . '[\'"`\]]?(\s+ON\s+)#i',
  4399. '"' . $new_name . '"\1',
  4400. $create_sql
  4401. );
  4402. $this->addSQLiteIndex($new_name, 'fl_tmp_' . $data['table'], $create_sql);
  4403. $extra_statements[] = $create_sql;
  4404. }
  4405. if ($data['type'] == 'drop_unique' && !$dropped_unique) {
  4406. if (count($data['column_names']) > 1) {
  4407. $message = self::compose(
  4408. 'The columns "%1$s" in the table "%2$s" do not have a unique constraint',
  4409. join('", "', $data['column_names']),
  4410. $data['table']
  4411. );
  4412. } else {
  4413. $message = self::compose(
  4414. 'The column "%1$s" in the table "%2$s" does not have a unique constraint',
  4415. reset($data['column_names']),
  4416. $data['table']
  4417. );
  4418. }
  4419. $this->throwException($message, $sql);
  4420. }
  4421. if (in_array($data['type'], array('rename_column', 'drop_column')) || ($data['type'] == 'drop_primary_key' && isset($data['column_name']))) {
  4422. $foreign_keys = $this->getSQLiteForeignKeys($data['table'], $data['column_name']);
  4423. foreach ($foreign_keys as $key) {
  4424. $extra_statements = array_merge(
  4425. $extra_statements,
  4426. $this->database->preprocess(
  4427. "ALTER TABLE %r DROP FOREIGN KEY (%r)",
  4428. array($key['table'], $key['column']),
  4429. TRUE
  4430. )
  4431. );
  4432. }
  4433. }
  4434. // Drop the original table
  4435. $extra_statements = array_merge(
  4436. $extra_statements,
  4437. $this->database->preprocess(
  4438. "DROP TABLE %r",
  4439. array($data['table']),
  4440. TRUE
  4441. )
  4442. );
  4443. // Rename the temp table to the original name
  4444. $extra_statements = array_merge(
  4445. $extra_statements,
  4446. $this->database->preprocess(
  4447. "ALTER TABLE %r RENAME TO %r",
  4448. array('fl_tmp_' . $data['table'], $data['table']),
  4449. TRUE
  4450. )
  4451. );
  4452. // Re-add the foreign key constraints for renamed columns
  4453. if ($data['type'] == 'rename_column') {
  4454. foreach ($foreign_keys as $key) {
  4455. $extra_statements = array_merge(
  4456. $extra_statements,
  4457. $this->database->preprocess(
  4458. "ALTER TABLE %r ADD FOREIGN KEY (%r) REFERENCES %r(%r) ON UPDATE " . $key['on_update'] . " ON DELETE " . $key['on_delete'],
  4459. array($key['table'], $key['column'], $data['table'], $data['new_column_name']),
  4460. TRUE
  4461. )
  4462. );
  4463. }
  4464. }
  4465. // Finally, we turn back on foreign keys
  4466. if ($toggle_foreign_key_support) {
  4467. if ($this->schema_info['foreign_keys_enabled']) {
  4468. $this->database->query("PRAGMA foreign_keys = 1");
  4469. }
  4470. unset($this->schema_info['foreign_keys_enabled']);
  4471. }
  4472. // Remove any nested transactions
  4473. $extra_statements = array_diff($extra_statements, array("BEGIN", "COMMIT"));
  4474. // Overwrite the original ALTER TABLE SQL
  4475. $sql = array_shift($extra_statements);
  4476. return $sql;
  4477. }
  4478. /**
  4479. * Translates `DROP TABLE` statements for SQLite
  4480. *
  4481. * @param string $sql The SQL to translate
  4482. * @param array &$extra_statements Any extra SQL statements that need to be added
  4483. * @return string The translated SQL
  4484. */
  4485. private function translateSQLiteDropTableStatements($sql, &$extra_statements)
  4486. {
  4487. if (preg_match('#^\s*DROP\s+TABLE\s+[["\'`]?(\w+)["\'`\]]?\s*$#iD', $sql, $match)) {
  4488. $dependent_tables = array();
  4489. $foreign_keys = $this->getSQLiteForeignKeys($match[1]);
  4490. foreach ($foreign_keys as $foreign_key) {
  4491. $dependent_tables[] = $foreign_key['table'];
  4492. }
  4493. $dependent_tables = array_unique($dependent_tables);
  4494. // We want to find triggers on tables that this table relies on and drop them
  4495. $triggers = $this->getSQLiteTriggers($match[1]);
  4496. foreach ($triggers as $name => $trigger) {
  4497. if (in_array($trigger['table'], $dependent_tables)) {
  4498. continue;
  4499. }
  4500. $matched_from_update = preg_match(
  4501. '#(\s+(?:FROM|UPDATE)\s+)(`' . $match[1] . '`|"' . $match[1] . '"|\'' . $match[1] . '\'|' . $match[1] . '|\[' . $match[1] . '\])#i',
  4502. $trigger['sql']
  4503. );
  4504. if ($matched_from_update) {
  4505. $extra_statements[] = "DROP TRIGGER " . $name;
  4506. $this->removeSQLiteTrigger($name);
  4507. }
  4508. }
  4509. $this->removeSQLiteIndexes($match[1]);
  4510. $this->removeSQLiteTriggers($match[1]);
  4511. $this->removeSQLiteTable($match[1]);
  4512. }
  4513. return $sql;
  4514. }
  4515. /**
  4516. * Translates Flourish SQL `ALTER TABLE * RENAME TO` statements to the appropriate
  4517. * statements for SQLite
  4518. *
  4519. * @param string $sql The SQL statements that will be executed against the database
  4520. * @param array &$extra_statements Any extra SQL statements required for SQLite
  4521. * @param array $data Data parsed from the `ALTER TABLE` statement
  4522. * @return string The modified SQL statement
  4523. */
  4524. private function translateSQLiteRenameTableStatements($sql, &$extra_statements, $data)
  4525. {
  4526. $tables = $this->getSQLiteTables();
  4527. if (in_array($data['new_table_name'], $tables)) {
  4528. $this->throwException(
  4529. self::compose(
  4530. 'A table with the name "%1$s" already exists',
  4531. $data['new_table_name']
  4532. ),
  4533. $sql
  4534. );
  4535. }
  4536. if (!in_array($data['table'], $tables)) {
  4537. $this->throwException(
  4538. self::compose(
  4539. 'The table specified, "%1$s", does not exist',
  4540. $data['table']
  4541. ),
  4542. $sql
  4543. );
  4544. }
  4545. // We start by dropping all references to this table
  4546. $foreign_keys = $this->getSQLiteForeignKeys($data['table']);
  4547. foreach ($foreign_keys as $foreign_key) {
  4548. $extra_statements = array_merge(
  4549. $extra_statements,
  4550. $this->database->preprocess(
  4551. "ALTER TABLE %r DROP FOREIGN KEY (%r)",
  4552. array(
  4553. $foreign_key['table'],
  4554. $foreign_key['column']
  4555. ),
  4556. TRUE
  4557. )
  4558. );
  4559. }
  4560. // SQLite 2 does not natively support renaming tables, so we have to do
  4561. // it by creating a new table name and copying all data and indexes
  4562. if (version_compare($this->database->getVersion(), 3, '<')) {
  4563. $renamed_create_sql = preg_replace(
  4564. '#^\s*CREATE\s+TABLE\s+["\[`\']?\w+["\]`\']?\s+#i',
  4565. 'CREATE TABLE "' . $data['new_table_name'] . '" ',
  4566. $this->getSQLiteCreateTable($data['table'])
  4567. );
  4568. $this->addSQLiteTable($data['new_table_name'], $renamed_create_sql);
  4569. // We rename string placeholders to prevent confusion with
  4570. // string placeholders that are added by call to fDatabase
  4571. $renamed_create_sql = str_replace(
  4572. ':string_',
  4573. ':sub_string_',
  4574. $renamed_create_sql
  4575. );
  4576. $create_statements = str_replace(
  4577. ':sub_string_',
  4578. ':string_',
  4579. $this->database->preprocess(
  4580. $renamed_create_sql,
  4581. array(),
  4582. TRUE
  4583. )
  4584. );
  4585. $extra_statements[] = array_shift($create_statements);
  4586. // Recreate the indexes on the new table
  4587. $indexes = $this->getSQLiteIndexes($data['table']);
  4588. foreach ($indexes as $name => $index) {
  4589. $create_sql = $index['sql'];
  4590. preg_match(
  4591. '#^\s*CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:[\'"`\[]?\w+[\'"`\]]?\.)?[\'"`\[]?\w+[\'"`\]]?\s+(ON\s+[\'"`\[]?\w+[\'"`\]]?)\s*(\((\s*(?:\s*[\'"`\[]?\w+[\'"`\]]?\s*,\s*)*[\'"`\[]?\w+[\'"`\]]?\s*)\))\s*$#Di',
  4592. $create_sql,
  4593. $match
  4594. );
  4595. // Fix the table name to the new table
  4596. $create_sql = str_replace(
  4597. $match[1],
  4598. preg_replace(
  4599. '#(?:`|\'|"|\[|\b)?' . preg_quote($data['table'], '#') . '(?:`|\'|"|\]|\b)?#i',
  4600. '"' . $data['new_table_name'] . '"',
  4601. $match[1]
  4602. ),
  4603. $create_sql
  4604. );
  4605. // We change the name of the index to keep it in sync
  4606. // with the new table name
  4607. $new_name = preg_replace(
  4608. '#^' . preg_quote($data['table'], '#') . '_#i',
  4609. $data['new_table_name'] . '_',
  4610. $name
  4611. );
  4612. $create_sql = preg_replace(
  4613. '#[\'"`\[]?' . preg_quote($name, '#') . '[\'"`\]]?(\s+ON\s+)#i',
  4614. '"' . $new_name . '"\1',
  4615. $create_sql
  4616. );
  4617. $extra_statements[] = $create_sql;
  4618. $this->addSQLiteIndex($new_name, $data['new_table_name'], $create_sql);
  4619. }
  4620. $column_names = $this->getSQLiteColumns($data['table']);
  4621. $extra_statements[] = $this->database->escape(
  4622. "INSERT INTO %r (%r) SELECT %r FROM %r",
  4623. $data['new_table_name'],
  4624. $column_names,
  4625. $column_names,
  4626. $data['table']
  4627. );
  4628. $extra_statements = array_merge(
  4629. $extra_statements,
  4630. $create_statements
  4631. );
  4632. $extra_statements = array_merge(
  4633. $extra_statements,
  4634. $this->database->preprocess(
  4635. "DROP TABLE %r",
  4636. array($data['table']),
  4637. TRUE
  4638. )
  4639. );
  4640. // SQLite 3 natively supports renaming tables, but it does not fix
  4641. // references to the old table name inside of trigger bodies
  4642. } else {
  4643. // We add the rename SQL in the middle so it happens after we drop the
  4644. // foreign key constraints and before we re-add them
  4645. $extra_statements[] = $sql;
  4646. $this->addSQLiteTable(
  4647. $data['new_table_name'],
  4648. preg_replace(
  4649. '#^\s*CREATE\s+TABLE\s+[\'"\[`]?\w+[\'"\]`]?\s+#i',
  4650. 'CREATE TABLE "' . $data['new_table_name'] . '" ',
  4651. $this->getSQLiteCreateTable($data['table'])
  4652. )
  4653. );
  4654. $this->removeSQLiteTable($data['table']);
  4655. // Copy the trigger definitions to the new table name
  4656. foreach ($this->getSQLiteTriggers() as $name => $trigger) {
  4657. if ($trigger['table'] == $data['table']) {
  4658. $this->addSQLiteTrigger($name, $data['new_table_name'], $trigger['sql']);
  4659. }
  4660. }
  4661. // Move the index definitions to the new table name
  4662. foreach ($this->getSQLiteIndexes($data['table']) as $name => $index) {
  4663. $this->addSQLiteIndex(
  4664. $name,
  4665. $data['new_table_name'],
  4666. preg_replace(
  4667. '#(\s+ON\s+)["\'`\[]?\w+["\'`\]]?#',
  4668. '\1"' . preg_quote($data['new_table_name'], '#') . '"',
  4669. $index['sql']
  4670. )
  4671. );
  4672. }
  4673. foreach ($this->getSQLiteTriggers() as $name => $trigger) {
  4674. $create_sql = $trigger['sql'];
  4675. $create_sql = preg_replace(
  4676. '#( on table )"' . $data['table'] . '"#i',
  4677. '\1"' . $data['new_table_name'] . '"',
  4678. $create_sql
  4679. );
  4680. $create_sql = preg_replace(
  4681. '#(\s+FROM\s+)(`' . $data['table'] . '`|"' . $data['table'] . '"|\'' . $data['table'] . '\'|' . $data['table'] . '|\[' . $data['table'] . '\])#i',
  4682. '\1"' . $data['new_table_name'] . '"',
  4683. $create_sql
  4684. );
  4685. if ($create_sql != $trigger['sql']) {
  4686. $extra_statements[] = $this->database->escape("DROP TRIGGER %r", $name);
  4687. $this->removeSQLiteTrigger($name);
  4688. $this->addSQLiteTrigger($name, $data['new_table_name'], $create_sql);
  4689. $extra_statements[] = $create_sql;
  4690. }
  4691. }
  4692. }
  4693. // Here we recreate the references that we dropped at the beginning
  4694. foreach ($foreign_keys as $foreign_key) {
  4695. $extra_statements = array_merge(
  4696. $extra_statements,
  4697. $this->database->preprocess(
  4698. "ALTER TABLE %r ADD FOREIGN KEY (%r) REFERENCES %r(%r) ON UPDATE " . $foreign_key['on_update'] . " ON DELETE " . $foreign_key['on_delete'],
  4699. array(
  4700. $foreign_key['table'],
  4701. $foreign_key['column'],
  4702. $data['new_table_name'],
  4703. $foreign_key['foreign_column']
  4704. ),
  4705. TRUE
  4706. )
  4707. );
  4708. }
  4709. // Remove any nested transactions
  4710. $extra_statements = array_diff($extra_statements, array("BEGIN", "COMMIT"));
  4711. // Since the actual rename or create/drop has to happen after adjusting
  4712. // foreign keys, we previously added it in the appropriate place and
  4713. // now need to provide the first statement to be run
  4714. return array_shift($extra_statements);
  4715. }
  4716. }
  4717. /**
  4718. * Copyright (c) 2011-2012 Will Bond <will@flourishlib.com>
  4719. *
  4720. * Permission is hereby granted, free of charge, to any person obtaining a copy
  4721. * of this software and associated documentation files (the "Software"), to deal
  4722. * in the Software without restriction, including without limitation the rights
  4723. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  4724. * copies of the Software, and to permit persons to whom the Software is
  4725. * furnished to do so, subject to the following conditions:
  4726. *
  4727. * The above copyright notice and this permission notice shall be included in
  4728. * all copies or substantial portions of the Software.
  4729. *
  4730. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4731. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4732. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4733. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  4734. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  4735. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  4736. * THE SOFTWARE.
  4737. */