PageRenderTime 82ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/inc/flourish/fSQLSchemaTranslation.php

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