schema.php 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  1. <?php
  2. // This file is part of GNU social - https://www.gnu.org/software/social
  3. //
  4. // GNU social is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // GNU social is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Database schema
  18. *
  19. * @category Database
  20. * @package GNUsocial
  21. * @author Evan Prodromou <evan@status.net>
  22. * @author Brion Vibber <brion@status.net>
  23. * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
  24. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  25. */
  26. defined('GNUSOCIAL') || die();
  27. /**
  28. * Class representing the database schema
  29. *
  30. * A class representing the database schema. Can be used to
  31. * manipulate the schema -- especially for plugins and upgrade
  32. * utilities.
  33. *
  34. * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
  35. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  36. */
  37. class Schema
  38. {
  39. public static $_static = null;
  40. protected $conn = null;
  41. /**
  42. * Constructor. Only run once for singleton object.
  43. * @param null $conn
  44. */
  45. protected function __construct($conn = null)
  46. {
  47. if (is_null($conn)) {
  48. // XXX: there should be an easier way to do this.
  49. $user = new User();
  50. $conn = $user->getDatabaseConnection();
  51. $user->free();
  52. unset($user);
  53. }
  54. $this->conn = $conn;
  55. }
  56. /**
  57. * Main public entry point. Use this to get
  58. * the schema object.
  59. *
  60. * @param object|null $conn
  61. * @param string|null Force a database type (necessary for installation purposes in which we don't have a config.php)
  62. * @return Schema the Schema object for the connection
  63. */
  64. public static function get($conn = null, $dbtype = null)
  65. {
  66. if (is_null($conn)) {
  67. $key = 'default';
  68. } else {
  69. $key = md5(serialize($conn->dsn));
  70. }
  71. if (is_null($dbtype)) {
  72. $dbtype = common_config('db', 'type');
  73. }
  74. if (empty(self::$_static[$key])) {
  75. $schemaClass = ucfirst($dbtype) . 'Schema';
  76. self::$_static[$key] = new $schemaClass($conn);
  77. }
  78. return self::$_static[$key];
  79. }
  80. /**
  81. * Gets a ColumnDef object for a single column.
  82. *
  83. * Throws an exception if the table is not found.
  84. *
  85. * @param string $table name of the table
  86. * @param string $column name of the column
  87. *
  88. * @return ColumnDef definition of the column or null
  89. * if not found.
  90. */
  91. public function getColumnDef($table, $column)
  92. {
  93. $td = $this->getTableDef($table);
  94. if (!empty($td) && !empty($td->columns)) {
  95. foreach ($td->columns as $cd) {
  96. if ($cd->name == $column) {
  97. return $cd;
  98. }
  99. }
  100. }
  101. return null;
  102. }
  103. /**
  104. * Creates a table with the given names and columns.
  105. *
  106. * @param string $tableName Name of the table
  107. * @param array $def Table definition array listing fields and indexes.
  108. *
  109. * @return bool success flag
  110. * @throws PEAR_Exception
  111. */
  112. public function createTable($tableName, $def)
  113. {
  114. $statements = $this->buildCreateTable($tableName, $def);
  115. return $this->runSqlSet($statements);
  116. }
  117. /**
  118. * Build a set of SQL statements to create a table with the given
  119. * name and columns.
  120. *
  121. * @param string $name Name of the table
  122. * @param array $def Table definition array
  123. *
  124. * @return array success flag
  125. * @throws Exception
  126. */
  127. public function buildCreateTable($name, $def)
  128. {
  129. $def = $this->validateDef($name, $def);
  130. $def = $this->filterDef($def);
  131. $sql = [];
  132. foreach ($def['fields'] as $col => $colDef) {
  133. $this->appendColumnDef($sql, $col, $colDef);
  134. }
  135. // Primary, unique, and foreign keys are constraints, so go within
  136. // the CREATE TABLE statement normally.
  137. if (!empty($def['primary key'])) {
  138. $this->appendPrimaryKeyDef($sql, $def['primary key']);
  139. }
  140. if (!empty($def['unique keys'])) {
  141. foreach ($def['unique keys'] as $col => $colDef) {
  142. $this->appendUniqueKeyDef($sql, $col, $colDef);
  143. }
  144. }
  145. if (!empty($def['foreign keys'])) {
  146. foreach ($def['foreign keys'] as $keyName => $keyDef) {
  147. $this->appendForeignKeyDef($sql, $keyName, $keyDef);
  148. }
  149. }
  150. // Wrap the CREATE TABLE around the main body chunks...
  151. $statements = [];
  152. $statements[] = $this->startCreateTable($name, $def) . "\n" .
  153. implode(",\n", $sql) . "\n" .
  154. $this->endCreateTable($name, $def);
  155. // Multi-value indexes are advisory and for best portability
  156. // should be created as separate statements.
  157. if (!empty($def['indexes'])) {
  158. foreach ($def['indexes'] as $col => $colDef) {
  159. $this->appendCreateIndex($statements, $name, $col, $colDef);
  160. }
  161. }
  162. if (!empty($def['fulltext indexes'])) {
  163. foreach ($def['fulltext indexes'] as $col => $colDef) {
  164. $this->appendCreateFulltextIndex($statements, $name, $col, $colDef);
  165. }
  166. }
  167. return $statements;
  168. }
  169. /**
  170. * Set up a 'create table' SQL statement.
  171. *
  172. * @param string $name table name
  173. * @param array $def table definition
  174. * @return string
  175. */
  176. public function startCreateTable($name, array $def)
  177. {
  178. return 'CREATE TABLE ' . $this->quoteIdentifier($name) . ' (';
  179. }
  180. /**
  181. * Close out a 'create table' SQL statement.
  182. *
  183. * @param string $name table name
  184. * @param array $def table definition
  185. * @return string
  186. */
  187. public function endCreateTable($name, array $def)
  188. {
  189. return ')';
  190. }
  191. /**
  192. * Append an SQL fragment with a column definition in a CREATE TABLE statement.
  193. *
  194. * @param array $sql
  195. * @param string $name
  196. * @param array $def
  197. */
  198. public function appendColumnDef(array &$sql, string $name, array $def)
  199. {
  200. $sql[] = $name . ' ' . $this->columnSql($name, $def);
  201. }
  202. /**
  203. * Append an SQL fragment with a constraint definition for a primary
  204. * key in a CREATE TABLE statement.
  205. *
  206. * @param array $sql
  207. * @param array $def
  208. */
  209. public function appendPrimaryKeyDef(array &$sql, array $def)
  210. {
  211. $sql[] = "PRIMARY KEY " . $this->buildIndexList($def);
  212. }
  213. /**
  214. * Append an SQL fragment with a constraint definition for a unique
  215. * key in a CREATE TABLE statement.
  216. *
  217. * @param array $sql
  218. * @param string $name
  219. * @param array $def
  220. */
  221. public function appendUniqueKeyDef(array &$sql, $name, array $def)
  222. {
  223. $sql[] = "CONSTRAINT $name UNIQUE " . $this->buildIndexList($def);
  224. }
  225. /**
  226. * Append an SQL fragment with a constraint definition for a foreign
  227. * key in a CREATE TABLE statement.
  228. *
  229. * @param array $sql
  230. * @param string $name
  231. * @param array $def
  232. * @throws Exception
  233. */
  234. public function appendForeignKeyDef(array &$sql, $name, array $def)
  235. {
  236. if (count($def) != 2) {
  237. throw new Exception("Invalid foreign key def for $name: " . var_export($def, true));
  238. }
  239. list($refTable, $map) = $def;
  240. $srcCols = array_keys($map);
  241. $refCols = array_values($map);
  242. $sql[] = 'CONSTRAINT ' . $this->quoteIdentifier($name) . ' FOREIGN KEY ' .
  243. $this->buildIndexList($srcCols) .
  244. ' REFERENCES ' .
  245. $this->quoteIdentifier($refTable) .
  246. ' ' .
  247. $this->buildIndexList($refCols);
  248. }
  249. /**
  250. * Append an SQL statement with an index definition for an advisory
  251. * index over one or more columns on a table.
  252. *
  253. * @param array $statements
  254. * @param string $table
  255. * @param string $name
  256. * @param array $def
  257. */
  258. public function appendCreateIndex(array &$statements, $table, $name, array $def)
  259. {
  260. $statements[] = 'CREATE INDEX ' . $name . ' ON ' .
  261. $this->quoteIdentifier($table) . ' ' . $this->buildIndexList($def);
  262. }
  263. /**
  264. * Append an SQL statement with an index definition for a full-text search
  265. * index over one or more columns on a table.
  266. *
  267. * @param array $statements
  268. * @param string $table
  269. * @param string $name
  270. * @param array $def
  271. * @throws Exception
  272. */
  273. public function appendCreateFulltextIndex(array &$statements, $table, $name, array $def)
  274. {
  275. throw new Exception("Fulltext index not supported in this database");
  276. }
  277. /**
  278. * Append an SQL statement to drop an index from a table.
  279. *
  280. * @param array $statements
  281. * @param string $table
  282. * @param string $name
  283. */
  284. public function appendDropIndex(array &$statements, $table, $name)
  285. {
  286. $statements[] = "DROP INDEX $name ON " . $this->quoteIdentifier($table);
  287. }
  288. public function buildIndexList(array $def)
  289. {
  290. // @fixme
  291. return '(' . implode(',', array_map([$this, 'buildIndexItem'], $def)) . ')';
  292. }
  293. public function buildIndexItem($def)
  294. {
  295. if (is_array($def)) {
  296. list($name, $size) = $def;
  297. return $this->quoteIdentifier($name) . '(' . intval($size) . ')';
  298. }
  299. return $this->quoteIdentifier($def);
  300. }
  301. /**
  302. * Drops a table from the schema
  303. *
  304. * Throws an exception if the table is not found.
  305. *
  306. * @param string $name Name of the table to drop
  307. *
  308. * @return bool success flag
  309. * @throws PEAR_Exception
  310. */
  311. public function dropTable($name)
  312. {
  313. global $_PEAR;
  314. $res = $this->conn->query('DROP TABLE ' . $this->quoteIdentifier($name));
  315. if ($_PEAR->isError($res)) {
  316. PEAR_ErrorToPEAR_Exception($res);
  317. }
  318. return true;
  319. }
  320. /**
  321. * Adds an index to a table.
  322. *
  323. * If no name is provided, a name will be made up based
  324. * on the table name and column names.
  325. *
  326. * Throws an exception on database error, esp. if the table
  327. * does not exist.
  328. *
  329. * @param string $table Name of the table
  330. * @param array $columnNames Name of columns to index
  331. * @param string $name (Optional) name of the index
  332. *
  333. * @return bool success flag
  334. * @throws PEAR_Exception
  335. */
  336. public function createIndex($table, $columnNames, $name = null)
  337. {
  338. global $_PEAR;
  339. $qry = [];
  340. if (!is_array($columnNames)) {
  341. $columnNames = [$columnNames];
  342. }
  343. if (empty($name)) {
  344. $name = "{$table}_" . implode("_", $columnNames) . "_idx";
  345. }
  346. $this->appendCreateIndex($qry, $table, $name, $columnNames);
  347. $res = $this->conn->query(implode('; ', $qry));
  348. if ($_PEAR->isError($res)) {
  349. PEAR_ErrorToPEAR_Exception($res);
  350. }
  351. return true;
  352. }
  353. /**
  354. * Drops a named index from a table.
  355. *
  356. * @param string $table name of the table the index is on.
  357. * @param string $name name of the index
  358. *
  359. * @return bool success flag
  360. * @throws PEAR_Exception
  361. */
  362. public function dropIndex($table, $name)
  363. {
  364. global $_PEAR;
  365. $res = $this->conn->query(
  366. 'ALTER TABLE ' . $this->quoteIdentifier($table) .
  367. ' DROP INDEX ' . $name
  368. );
  369. if ($_PEAR->isError($res)) {
  370. PEAR_ErrorToPEAR_Exception($res);
  371. }
  372. return true;
  373. }
  374. /**
  375. * Adds a column to a table
  376. *
  377. * @param string $table name of the table
  378. * @param ColumnDef $columndef Definition of the new
  379. * column.
  380. *
  381. * @return bool success flag
  382. * @throws PEAR_Exception
  383. */
  384. public function addColumn($table, $columndef)
  385. {
  386. global $_PEAR;
  387. $sql = 'ALTER TABLE ' . $this->quoteIdentifier($table) .
  388. ' ADD COLUMN ' . $this->columnSql($name, $columndef);
  389. $res = $this->conn->query($sql);
  390. if ($_PEAR->isError($res)) {
  391. PEAR_ErrorToPEAR_Exception($res);
  392. }
  393. return true;
  394. }
  395. /**
  396. * Modifies a column in the schema.
  397. *
  398. * The name must match an existing column and table.
  399. *
  400. * @param string $table name of the table
  401. * @param ColumnDef $columndef new definition of the column.
  402. *
  403. * @return bool success flag
  404. * @throws PEAR_Exception
  405. */
  406. public function modifyColumn($table, $columndef)
  407. {
  408. global $_PEAR;
  409. $sql = 'ALTER TABLE ' . $this->quoteIdentifier($table) .
  410. ' MODIFY COLUMN ' . $this->columnSql($name, $columndef);
  411. $res = $this->conn->query($sql);
  412. if ($_PEAR->isError($res)) {
  413. PEAR_ErrorToPEAR_Exception($res);
  414. }
  415. return true;
  416. }
  417. /**
  418. * Drops a column from a table
  419. *
  420. * The name must match an existing column.
  421. *
  422. * @param string $table name of the table
  423. * @param string $columnName name of the column to drop
  424. *
  425. * @return bool success flag
  426. * @throws PEAR_Exception
  427. */
  428. public function dropColumn($table, $columnName)
  429. {
  430. global $_PEAR;
  431. $sql = 'ALTER TABLE ' . $this->quoteIdentifier($table) .
  432. ' DROP COLUMN ' . $columnName;
  433. $res = $this->conn->query($sql);
  434. if ($_PEAR->isError($res)) {
  435. PEAR_ErrorToPEAR_Exception($res);
  436. }
  437. return true;
  438. }
  439. /**
  440. * Ensures that a table exists with the given
  441. * name and the given column definitions.
  442. *
  443. * If the table does not yet exist, it will
  444. * create the table. If it does exist, it will
  445. * alter the table to match the column definitions.
  446. *
  447. * @param string $tableName name of the table
  448. * @param array $def Table definition array
  449. *
  450. * @return bool success flag
  451. * @throws PEAR_Exception
  452. */
  453. public function ensureTable($tableName, $def)
  454. {
  455. $statements = $this->buildEnsureTable($tableName, $def);
  456. return $this->runSqlSet($statements);
  457. }
  458. /**
  459. * Run a given set of SQL commands on the connection in sequence.
  460. * Empty input is ok.
  461. *
  462. * @fixme if multiple statements, wrap in a transaction?
  463. * @param array $statements
  464. * @return bool success flag
  465. * @throws PEAR_Exception
  466. */
  467. public function runSqlSet(array $statements)
  468. {
  469. global $_PEAR;
  470. $ok = true;
  471. foreach ($statements as $sql) {
  472. if (defined('DEBUG_INSTALLER')) {
  473. echo "<code>" . htmlspecialchars($sql) . "</code><br/>\n";
  474. }
  475. $res = $this->conn->query($sql);
  476. if ($_PEAR->isError($res)) {
  477. common_debug('PEAR exception on query: ' . $sql);
  478. PEAR_ErrorToPEAR_Exception($res);
  479. }
  480. }
  481. return $ok;
  482. }
  483. /**
  484. * Check a table's status, and if needed build a set
  485. * of SQL statements which change it to be consistent
  486. * with the given table definition.
  487. *
  488. * If the table does not yet exist, statements will
  489. * be returned to create the table. If it does exist,
  490. * statements will be returned to alter the table to
  491. * match the column definitions.
  492. *
  493. * @param string $tableName name of the table
  494. * @param array $def
  495. * @return array of SQL statements
  496. * @throws Exception
  497. */
  498. public function buildEnsureTable($tableName, array $def)
  499. {
  500. try {
  501. $old = $this->getTableDef($tableName);
  502. } catch (SchemaTableMissingException $e) {
  503. return $this->buildCreateTable($tableName, $def);
  504. }
  505. // Filter the DB-independent table definition to match the current
  506. // database engine's features and limitations.
  507. $def = $this->validateDef($tableName, $def);
  508. $def = $this->filterDef($def);
  509. $statements = [];
  510. $fields = $this->diffArrays($old, $def, 'fields', [$this, 'columnsEqual']);
  511. $uniques = $this->diffArrays($old, $def, 'unique keys');
  512. $indexes = $this->diffArrays($old, $def, 'indexes');
  513. $foreign = $this->diffArrays($old, $def, 'foreign keys');
  514. $fulltext = $this->diffArrays($old, $def, 'fulltext indexes');
  515. // Drop any obsolete or modified indexes ahead...
  516. foreach ($indexes['del'] + $indexes['mod'] as $indexName) {
  517. $this->appendDropIndex($statements, $tableName, $indexName);
  518. }
  519. // Drop any obsolete or modified fulltext indexes ahead...
  520. foreach ($fulltext['del'] + $fulltext['mod'] as $indexName) {
  521. $this->appendDropIndex($statements, $tableName, $indexName);
  522. }
  523. // For efficiency, we want this all in one
  524. // query, instead of using our methods.
  525. $phrase = [];
  526. foreach ($foreign['del'] + $foreign['mod'] as $keyName) {
  527. $this->appendAlterDropForeign($phrase, $keyName);
  528. }
  529. foreach ($uniques['del'] + $uniques['mod'] as $keyName) {
  530. $this->appendAlterDropUnique($phrase, $keyName);
  531. }
  532. if (isset($old['primary key']) && (!isset($def['primary key']) || $def['primary key'] != $old['primary key'])) {
  533. $this->appendAlterDropPrimary($phrase, $tableName);
  534. }
  535. foreach ($fields['add'] as $columnName) {
  536. $this->appendAlterAddColumn(
  537. $phrase,
  538. $columnName,
  539. $def['fields'][$columnName]
  540. );
  541. }
  542. foreach ($fields['mod'] as $columnName) {
  543. $this->appendAlterModifyColumn(
  544. $phrase,
  545. $columnName,
  546. $old['fields'][$columnName],
  547. $def['fields'][$columnName]
  548. );
  549. }
  550. foreach ($fields['del'] as $columnName) {
  551. $this->appendAlterDropColumn($phrase, $columnName);
  552. }
  553. if (isset($def['primary key']) && (!isset($old['primary key']) || $old['primary key'] != $def['primary key'])) {
  554. $this->appendAlterAddPrimary($phrase, $def['primary key']);
  555. }
  556. foreach ($uniques['mod'] + $uniques['add'] as $keyName) {
  557. $this->appendAlterAddUnique($phrase, $keyName, $def['unique keys'][$keyName]);
  558. }
  559. foreach ($foreign['mod'] + $foreign['add'] as $keyName) {
  560. $this->appendAlterAddForeign($phrase, $keyName, $def['foreign keys'][$keyName]);
  561. }
  562. $this->appendAlterExtras($phrase, $tableName, $def);
  563. if (count($phrase) > 0) {
  564. $sql = 'ALTER TABLE ' . $this->quoteIdentifier($tableName) .
  565. ' ' . implode(",\n", $phrase);
  566. $statements[] = $sql;
  567. }
  568. // Now create any indexes...
  569. foreach ($indexes['mod'] + $indexes['add'] as $indexName) {
  570. $this->appendCreateIndex($statements, $tableName, $indexName, $def['indexes'][$indexName]);
  571. }
  572. foreach ($fulltext['mod'] + $fulltext['add'] as $indexName) {
  573. $colDef = $def['fulltext indexes'][$indexName];
  574. $this->appendCreateFulltextIndex($statements, $tableName, $indexName, $colDef);
  575. }
  576. return $statements;
  577. }
  578. public function diffArrays($oldDef, $newDef, $section, $compareCallback = null)
  579. {
  580. $old = isset($oldDef[$section]) ? $oldDef[$section] : [];
  581. $new = isset($newDef[$section]) ? $newDef[$section] : [];
  582. $oldKeys = array_keys($old);
  583. $newKeys = array_keys($new);
  584. $toadd = array_diff($newKeys, $oldKeys);
  585. $todrop = array_diff($oldKeys, $newKeys);
  586. $same = array_intersect($newKeys, $oldKeys);
  587. $tomod = [];
  588. $tokeep = [];
  589. // Find which fields have actually changed definition
  590. // in a way that we need to tweak them for this DB type.
  591. foreach ($same as $name) {
  592. if ($compareCallback) {
  593. $same = call_user_func($compareCallback, $old[$name], $new[$name]);
  594. } else {
  595. $same = ($old[$name] == $new[$name]);
  596. }
  597. if ($same) {
  598. $tokeep[] = $name;
  599. continue;
  600. }
  601. $tomod[] = $name;
  602. }
  603. return [
  604. 'add' => $toadd,
  605. 'del' => $todrop,
  606. 'mod' => $tomod,
  607. 'keep' => $tokeep,
  608. 'count' => count($toadd) + count($todrop) + count($tomod)
  609. ];
  610. }
  611. /**
  612. * Append phrase(s) to an array of partial ALTER TABLE chunks in order
  613. * to add the given column definition to the table.
  614. *
  615. * @param array $phrase
  616. * @param string $columnName
  617. * @param array $cd
  618. */
  619. public function appendAlterAddColumn(array &$phrase, string $columnName, array $cd)
  620. {
  621. $phrase[] = 'ADD COLUMN ' .
  622. $this->quoteIdentifier($columnName) .
  623. ' ' .
  624. $this->columnSql($columnName, $cd);
  625. }
  626. /**
  627. * Append phrase(s) to an array of partial ALTER TABLE chunks in order
  628. * to alter the given column from its old state to a new one.
  629. *
  630. * @param array $phrase
  631. * @param string $columnName
  632. * @param array $old previous column definition as found in DB
  633. * @param array $cd current column definition
  634. */
  635. public function appendAlterModifyColumn(array &$phrase, string $columnName, array $old, array $cd)
  636. {
  637. $phrase[] = 'MODIFY COLUMN ' .
  638. $this->quoteIdentifier($columnName) .
  639. ' ' .
  640. $this->columnSql($columnName, $cd);
  641. }
  642. /**
  643. * Append phrase(s) to an array of partial ALTER TABLE chunks in order
  644. * to drop the given column definition from the table.
  645. *
  646. * @param array $phrase
  647. * @param string $columnName
  648. */
  649. public function appendAlterDropColumn(array &$phrase, $columnName)
  650. {
  651. $phrase[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
  652. }
  653. public function appendAlterAddUnique(array &$phrase, $keyName, array $def)
  654. {
  655. $sql = [];
  656. $sql[] = 'ADD';
  657. $this->appendUniqueKeyDef($sql, $keyName, $def);
  658. $phrase[] = implode(' ', $sql);
  659. }
  660. public function appendAlterAddForeign(array &$phrase, $keyName, array $def)
  661. {
  662. $sql = [];
  663. $sql[] = 'ADD';
  664. $this->appendForeignKeyDef($sql, $keyName, $def);
  665. $phrase[] = implode(' ', $sql);
  666. }
  667. public function appendAlterAddPrimary(array &$phrase, array $def)
  668. {
  669. $sql = [];
  670. $sql[] = 'ADD';
  671. $this->appendPrimaryKeyDef($sql, $def);
  672. $phrase[] = implode(' ', $sql);
  673. }
  674. public function appendAlterDropPrimary(array &$phrase, string $tableName)
  675. {
  676. $phrase[] = 'DROP CONSTRAINT PRIMARY KEY';
  677. }
  678. public function appendAlterDropUnique(array &$phrase, $keyName)
  679. {
  680. $phrase[] = 'DROP CONSTRAINT ' . $keyName;
  681. }
  682. public function appendAlterDropForeign(array &$phrase, $keyName)
  683. {
  684. $phrase[] = 'DROP FOREIGN KEY ' . $keyName;
  685. }
  686. public function appendAlterExtras(array &$phrase, $tableName, array $def)
  687. {
  688. // no-op
  689. }
  690. /**
  691. * Quote a db/table/column identifier if necessary.
  692. *
  693. * @param string $name
  694. * @return string
  695. */
  696. public function quoteIdentifier($name)
  697. {
  698. return $this->conn->quoteIdentifier($name);
  699. }
  700. public function quoteDefaultValue($cd)
  701. {
  702. if (in_array($cd['type'], ['datetime', 'timestamp']) && $cd['default'] === 'CURRENT_TIMESTAMP') {
  703. return $cd['default'];
  704. } else {
  705. return $this->quoteValue($cd['default']);
  706. }
  707. }
  708. public function quoteValue($val)
  709. {
  710. return $this->conn->quoteSmart($val);
  711. }
  712. /**
  713. * Check if two column definitions are equivalent.
  714. * The default implementation checks _everything_ but in many cases
  715. * you may be able to discard a bunch of equivalencies.
  716. *
  717. * @param array $a
  718. * @param array $b
  719. * @return bool
  720. */
  721. public function columnsEqual(array $a, array $b)
  722. {
  723. return !array_diff_assoc($a, $b) && !array_diff_assoc($b, $a);
  724. }
  725. /**
  726. * Returns the array of names from an array of
  727. * ColumnDef objects.
  728. *
  729. * @param array $cds array of ColumnDef objects
  730. *
  731. * @return array strings for name values
  732. */
  733. protected function _names($cds)
  734. {
  735. $names = [];
  736. foreach ($cds as $cd) {
  737. $names[] = $cd->name;
  738. }
  739. return $names;
  740. }
  741. /**
  742. * Get a ColumnDef from an array matching
  743. * name.
  744. *
  745. * @param array $cds Array of ColumnDef objects
  746. * @param string $name Name of the column
  747. *
  748. * @return ColumnDef matching item or null if no match.
  749. */
  750. protected function _byName($cds, $name)
  751. {
  752. foreach ($cds as $cd) {
  753. if ($cd->name == $name) {
  754. return $cd;
  755. }
  756. }
  757. return null;
  758. }
  759. /**
  760. * Return the proper SQL for creating or
  761. * altering a column.
  762. *
  763. * Appropriate for use in CREATE TABLE or
  764. * ALTER TABLE statements.
  765. *
  766. * @param string $name column name to create
  767. * @param array $cd column to create
  768. *
  769. * @return string correct SQL for that column
  770. */
  771. public function columnSql(string $name, array $cd)
  772. {
  773. $line = [];
  774. $line[] = $this->typeAndSize($name, $cd);
  775. if (isset($cd['default'])) {
  776. $line[] = 'default';
  777. $line[] = $this->quoteDefaultValue($cd);
  778. } elseif (!empty($cd['not null'])) {
  779. // Can't have both not null AND default!
  780. $line[] = 'not null';
  781. }
  782. return implode(' ', $line);
  783. }
  784. /**
  785. *
  786. * @param string $column canonical type name in defs
  787. * @return string native DB type name
  788. */
  789. public function mapType($column)
  790. {
  791. return $column;
  792. }
  793. public function typeAndSize(string $name, array $column)
  794. {
  795. //$type = $this->mapType($column)['type'];
  796. $type = $column['type'];
  797. if (isset($column['size'])) {
  798. $type = $column['size'] . $type;
  799. }
  800. $lengths = [];
  801. if (isset($column['precision'])) {
  802. $lengths[] = $column['precision'];
  803. if (isset($column['scale'])) {
  804. $lengths[] = $column['scale'];
  805. }
  806. } elseif (isset($column['length'])) {
  807. $lengths[] = $column['length'];
  808. }
  809. if ($lengths) {
  810. return $type . '(' . implode(',', $lengths) . ')';
  811. } else {
  812. return $type;
  813. }
  814. }
  815. /**
  816. * Convert an old-style set of ColumnDef objects into the current
  817. * Drupal-style schema definition array, for backwards compatibility
  818. * with plugins written for 0.9.x.
  819. *
  820. * @param string $tableName
  821. * @param array $defs : array of ColumnDef objects
  822. * @return array
  823. */
  824. protected function oldToNew($tableName, array $defs)
  825. {
  826. $table = [];
  827. $prefixes = [
  828. 'tiny',
  829. 'small',
  830. 'medium',
  831. 'big',
  832. ];
  833. foreach ($defs as $cd) {
  834. $column = [];
  835. $column['type'] = $cd->type;
  836. foreach ($prefixes as $prefix) {
  837. if (substr($cd->type, 0, strlen($prefix)) == $prefix) {
  838. $column['type'] = substr($cd->type, strlen($prefix));
  839. $column['size'] = $prefix;
  840. break;
  841. }
  842. }
  843. if ($cd->size) {
  844. if ($cd->type == 'varchar' || $cd->type == 'char') {
  845. $column['length'] = $cd->size;
  846. }
  847. }
  848. if (!$cd->nullable) {
  849. $column['not null'] = true;
  850. }
  851. if ($cd->auto_increment) {
  852. $column['type'] = 'serial';
  853. }
  854. if ($cd->default) {
  855. $column['default'] = $cd->default;
  856. }
  857. $table['fields'][$cd->name] = $column;
  858. if ($cd->key == 'PRI') {
  859. // If multiple columns are defined as primary key,
  860. // we'll pile them on in sequence.
  861. if (!isset($table['primary key'])) {
  862. $table['primary key'] = [];
  863. }
  864. $table['primary key'][] = $cd->name;
  865. } elseif ($cd->key === 'MUL') {
  866. // Individual multiple-value indexes are only per-column
  867. // using the old ColumnDef syntax.
  868. $idx = "{$tableName}_{$cd->name}_idx";
  869. $table['indexes'][$idx] = [$cd->name];
  870. } elseif ($cd->key === 'UNI') {
  871. // Individual unique-value indexes are only per-column
  872. // using the old ColumnDef syntax.
  873. $idx = "{$tableName}_{$cd->name}_idx";
  874. $table['unique keys'][$idx] = [$cd->name];
  875. }
  876. }
  877. return $table;
  878. }
  879. /**
  880. * Filter the given table definition array to match features available
  881. * in this database.
  882. *
  883. * This lets us strip out unsupported things like comments, foreign keys,
  884. * or type variants that we wouldn't get back from getTableDef().
  885. *
  886. * @param array $tableDef
  887. * @return array
  888. */
  889. public function filterDef(array $tableDef)
  890. {
  891. return $tableDef;
  892. }
  893. /**
  894. * Validate a table definition array, checking for basic structure.
  895. *
  896. * If necessary, converts from an old-style array of ColumnDef objects.
  897. *
  898. * @param string $tableName
  899. * @param array $def : table definition array
  900. * @return array validated table definition array
  901. *
  902. * @throws Exception on wildly invalid input
  903. */
  904. public function validateDef($tableName, array $def)
  905. {
  906. if (isset($def[0]) && $def[0] instanceof ColumnDef) {
  907. $def = $this->oldToNew($tableName, $def);
  908. }
  909. // A few quick checks :D
  910. if (!isset($def['fields'])) {
  911. throw new Exception("Invalid table definition for $tableName: no fields.");
  912. }
  913. return $def;
  914. }
  915. public function isNumericType($type)
  916. {
  917. $type = strtolower($type);
  918. $known = ['int', 'serial', 'numeric'];
  919. return in_array($type, $known);
  920. }
  921. /**
  922. * Pull info from the query into a fun-fun array of dooooom
  923. *
  924. * @param string $sql
  925. * @return array of arrays
  926. * @throws PEAR_Exception
  927. */
  928. protected function fetchQueryData($sql)
  929. {
  930. global $_PEAR;
  931. $res = $this->conn->query($sql);
  932. if ($_PEAR->isError($res)) {
  933. PEAR_ErrorToPEAR_Exception($res);
  934. }
  935. $out = [];
  936. $row = [];
  937. while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
  938. $out[] = $row;
  939. }
  940. $res->free();
  941. return $out;
  942. }
  943. public function renameTable(string $old_name, string $new_name) : bool
  944. {
  945. try {
  946. $this->getTableDef($old_name);
  947. try {
  948. $this->getTableDef($new_name);
  949. // New table exists, can't work
  950. throw new ServerException("Both table {$old_name} and {$new_name} exist. You're on your own.");
  951. } catch (SchemaTableMissingException $e) {
  952. // New table doesn't exist, carry on
  953. }
  954. } catch (SchemaTableMissingException $e) {
  955. // Already renamed, or no previous table, so we're done
  956. return true;
  957. }
  958. return $this->runSqlSet([
  959. 'ALTER TABLE ' . $this->quoteIdentifier($old_name) .
  960. ' RENAME TO ' . $this->quoteIdentifier($new_name) . ';',
  961. ]);
  962. }
  963. }
  964. class SchemaTableMissingException extends Exception
  965. {
  966. // no-op
  967. }