schema.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  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($name, $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($tableName, $def);
  509. $statements = [];
  510. $fields = $this->diffArrays($old, $def, 'fields');
  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. * Returns the array of names from an array of
  714. * ColumnDef objects.
  715. *
  716. * @param array $cds array of ColumnDef objects
  717. *
  718. * @return array strings for name values
  719. */
  720. protected function _names($cds)
  721. {
  722. $names = [];
  723. foreach ($cds as $cd) {
  724. $names[] = $cd->name;
  725. }
  726. return $names;
  727. }
  728. /**
  729. * Get a ColumnDef from an array matching
  730. * name.
  731. *
  732. * @param array $cds Array of ColumnDef objects
  733. * @param string $name Name of the column
  734. *
  735. * @return ColumnDef matching item or null if no match.
  736. */
  737. protected function _byName($cds, $name)
  738. {
  739. foreach ($cds as $cd) {
  740. if ($cd->name == $name) {
  741. return $cd;
  742. }
  743. }
  744. return null;
  745. }
  746. /**
  747. * Return the proper SQL for creating or
  748. * altering a column.
  749. *
  750. * Appropriate for use in CREATE TABLE or
  751. * ALTER TABLE statements.
  752. *
  753. * @param string $name column name to create
  754. * @param array $cd column to create
  755. *
  756. * @return string correct SQL for that column
  757. */
  758. public function columnSql(string $name, array $cd)
  759. {
  760. $line = [];
  761. $line[] = $this->typeAndSize($name, $cd);
  762. if (isset($cd['default'])) {
  763. $line[] = 'default';
  764. $line[] = $this->quoteDefaultValue($cd);
  765. }
  766. if (!empty($cd['not null'])) {
  767. $line[] = 'NOT NULL';
  768. } else {
  769. $line[] = 'NULL';
  770. }
  771. return implode(' ', $line);
  772. }
  773. /**
  774. *
  775. * @param string $column canonical type name in defs
  776. * @return string native DB type name
  777. */
  778. public function mapType($column)
  779. {
  780. return $column;
  781. }
  782. public function typeAndSize(string $name, array $column)
  783. {
  784. //$type = $this->mapType($column)['type'];
  785. $type = $column['type'];
  786. if (isset($column['size'])) {
  787. $type = $column['size'] . $type;
  788. }
  789. $lengths = [];
  790. if (isset($column['precision'])) {
  791. $lengths[] = $column['precision'];
  792. if (isset($column['scale'])) {
  793. $lengths[] = $column['scale'];
  794. }
  795. } elseif (isset($column['length'])) {
  796. $lengths[] = $column['length'];
  797. }
  798. if ($lengths) {
  799. return $type . '(' . implode(',', $lengths) . ')';
  800. } else {
  801. return $type;
  802. }
  803. }
  804. /**
  805. * Convert an old-style set of ColumnDef objects into the current
  806. * Drupal-style schema definition array, for backwards compatibility
  807. * with plugins written for 0.9.x.
  808. *
  809. * @param string $tableName
  810. * @param array $defs : array of ColumnDef objects
  811. * @return array
  812. */
  813. protected function oldToNew($tableName, array $defs)
  814. {
  815. $table = [];
  816. $prefixes = [
  817. 'tiny',
  818. 'small',
  819. 'medium',
  820. 'big',
  821. ];
  822. foreach ($defs as $cd) {
  823. $column = [];
  824. $column['type'] = $cd->type;
  825. foreach ($prefixes as $prefix) {
  826. if (substr($cd->type, 0, strlen($prefix)) == $prefix) {
  827. $column['type'] = substr($cd->type, strlen($prefix));
  828. $column['size'] = $prefix;
  829. break;
  830. }
  831. }
  832. if ($cd->size) {
  833. if ($cd->type == 'varchar' || $cd->type == 'char') {
  834. $column['length'] = $cd->size;
  835. }
  836. }
  837. if (!$cd->nullable) {
  838. $column['not null'] = true;
  839. }
  840. if ($cd->auto_increment) {
  841. $column['type'] = 'serial';
  842. }
  843. if ($cd->default) {
  844. $column['default'] = $cd->default;
  845. }
  846. $table['fields'][$cd->name] = $column;
  847. if ($cd->key == 'PRI') {
  848. // If multiple columns are defined as primary key,
  849. // we'll pile them on in sequence.
  850. if (!isset($table['primary key'])) {
  851. $table['primary key'] = [];
  852. }
  853. $table['primary key'][] = $cd->name;
  854. } elseif ($cd->key === 'MUL') {
  855. // Individual multiple-value indexes are only per-column
  856. // using the old ColumnDef syntax.
  857. $idx = "{$tableName}_{$cd->name}_idx";
  858. $table['indexes'][$idx] = [$cd->name];
  859. } elseif ($cd->key === 'UNI') {
  860. // Individual unique-value indexes are only per-column
  861. // using the old ColumnDef syntax.
  862. $idx = "{$tableName}_{$cd->name}_idx";
  863. $table['unique keys'][$idx] = [$cd->name];
  864. }
  865. }
  866. return $table;
  867. }
  868. /**
  869. * Filter the given table definition array to match features available
  870. * in this database.
  871. *
  872. * This lets us strip out unsupported things like comments, foreign keys,
  873. * or type variants that we wouldn't get back from getTableDef().
  874. *
  875. * @param string $tableName
  876. * @param array $tableDef
  877. * @return array
  878. */
  879. public function filterDef(string $tableName, array $tableDef)
  880. {
  881. foreach ($tableDef['fields'] as $name => &$col) {
  882. switch ($col['type']) {
  883. case 'timestamp':
  884. $col['type'] = 'datetime';
  885. if (!array_key_exists('default', $col)) {
  886. $col['default'] = 'CURRENT_TIMESTAMP';
  887. // FIXME: PostgreSQL support.
  888. $col['auto_update_timestamp'] = true;
  889. }
  890. // no break
  891. case 'datetime':
  892. // Replace archaic MariaDB-specific "zero dates" with NULL
  893. if (($col['default'] ?? null) === '0000-00-00 00:00:00') {
  894. $col['default'] = null;
  895. $col['not null'] = false;
  896. }
  897. break;
  898. }
  899. if (array_key_exists('default', $col) && is_null($col['default'])) {
  900. unset($col['default']);
  901. }
  902. if (array_key_exists('not null', $col) && $col['not null'] !== true) {
  903. unset($col['not null']);
  904. }
  905. }
  906. return $tableDef;
  907. }
  908. /**
  909. * Validate a table definition array, checking for basic structure.
  910. *
  911. * If necessary, converts from an old-style array of ColumnDef objects.
  912. *
  913. * @param string $tableName
  914. * @param array $def : table definition array
  915. * @return array validated table definition array
  916. *
  917. * @throws Exception on wildly invalid input
  918. */
  919. public function validateDef($tableName, array $def)
  920. {
  921. if (isset($def[0]) && $def[0] instanceof ColumnDef) {
  922. $def = $this->oldToNew($tableName, $def);
  923. }
  924. // A few quick checks :D
  925. if (!isset($def['fields'])) {
  926. throw new Exception("Invalid table definition for $tableName: no fields.");
  927. }
  928. return $def;
  929. }
  930. /**
  931. * Pull info from the query into a fun-fun array of dooooom
  932. *
  933. * @param string $sql
  934. * @return array of arrays
  935. * @throws PEAR_Exception
  936. */
  937. protected function fetchQueryData($sql)
  938. {
  939. global $_PEAR;
  940. $res = $this->conn->query($sql);
  941. if ($_PEAR->isError($res)) {
  942. PEAR_ErrorToPEAR_Exception($res);
  943. }
  944. $out = [];
  945. $row = [];
  946. while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
  947. $out[] = $row;
  948. }
  949. $res->free();
  950. return $out;
  951. }
  952. public function renameTable(string $old_name, string $new_name) : bool
  953. {
  954. try {
  955. $this->getTableDef($old_name);
  956. try {
  957. $this->getTableDef($new_name);
  958. // New table exists, can't work
  959. throw new ServerException("Both table {$old_name} and {$new_name} exist. You're on your own.");
  960. } catch (SchemaTableMissingException $e) {
  961. // New table doesn't exist, carry on
  962. }
  963. } catch (SchemaTableMissingException $e) {
  964. // Already renamed, or no previous table, so we're done
  965. return true;
  966. }
  967. return $this->runSqlSet([
  968. 'ALTER TABLE ' . $this->quoteIdentifier($old_name) .
  969. ' RENAME TO ' . $this->quoteIdentifier($new_name) . ';',
  970. ]);
  971. }
  972. }
  973. class SchemaTableMissingException extends Exception
  974. {
  975. // no-op
  976. }