schema.php 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268
  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 = hash('md5', $conn->getDSN('string'));
  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}";
  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->exec('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. $statements = [];
  340. if (!is_array($columnNames)) {
  341. $columnNames = [$columnNames];
  342. }
  343. if (empty($name)) {
  344. $name = "{$table}_" . implode("_", $columnNames) . "_idx";
  345. }
  346. $this->appendCreateIndex($statements, $table, $name, $columnNames);
  347. $this->conn->beginTransaction();
  348. foreach ($statements as $sql) {
  349. $res = $this->conn->exec($sql);
  350. if ($_PEAR->isError($res)) {
  351. $this->conn->rollback();
  352. PEAR_ErrorToPEAR_Exception($res);
  353. }
  354. }
  355. $this->conn->commit();
  356. return true;
  357. }
  358. /**
  359. * Drops a named index from a table.
  360. *
  361. * @param string $table name of the table the index is on.
  362. * @param string $name name of the index
  363. *
  364. * @return bool success flag
  365. * @throws PEAR_Exception
  366. */
  367. public function dropIndex($table, $name)
  368. {
  369. global $_PEAR;
  370. $statements = [];
  371. $this->appendDropIndex($statements, $table, $name);
  372. $this->conn->beginTransaction();
  373. foreach ($statements as $sql) {
  374. $res = $this->conn->exec($sql);
  375. if ($_PEAR->isError($res)) {
  376. $this->conn->rollback();
  377. PEAR_ErrorToPEAR_Exception($res);
  378. }
  379. }
  380. $this->conn->commit();
  381. return true;
  382. }
  383. /**
  384. * Adds a column to a table
  385. *
  386. * @param string $table name of the table
  387. * @param ColumnDef $columndef Definition of the new
  388. * column.
  389. *
  390. * @return bool success flag
  391. * @throws PEAR_Exception
  392. */
  393. public function addColumn($table, $columndef)
  394. {
  395. global $_PEAR;
  396. $sql = 'ALTER TABLE ' . $this->quoteIdentifier($table) .
  397. ' ADD COLUMN ' . $this->columnSql($name, $columndef);
  398. $res = $this->conn->exec($sql);
  399. if ($_PEAR->isError($res)) {
  400. PEAR_ErrorToPEAR_Exception($res);
  401. }
  402. return true;
  403. }
  404. /**
  405. * Returns the character set of choice for this DBMS (in practice, UTF-8).
  406. *
  407. * @return string
  408. */
  409. public static function charset(): string
  410. {
  411. return 'UTF8';
  412. }
  413. /**
  414. * Modifies a column in the schema.
  415. *
  416. * The name must match an existing column and table.
  417. * @fixme Relies on MODIFY COLUMN, which is specific to MariaDB/MySQL
  418. *
  419. * @param string $table name of the table
  420. * @param ColumnDef $columndef new definition of the column.
  421. *
  422. * @return bool success flag
  423. * @throws PEAR_Exception
  424. */
  425. public function modifyColumn($table, $columndef)
  426. {
  427. global $_PEAR;
  428. $sql = 'ALTER TABLE ' . $this->quoteIdentifier($table) .
  429. ' MODIFY COLUMN ' . $this->columnSql($name, $columndef);
  430. $res = $this->conn->exec($sql);
  431. if ($_PEAR->isError($res)) {
  432. PEAR_ErrorToPEAR_Exception($res);
  433. }
  434. return true;
  435. }
  436. /**
  437. * Drops a column from a table
  438. *
  439. * The name must match an existing column.
  440. *
  441. * @param string $table name of the table
  442. * @param string $columnName name of the column to drop
  443. *
  444. * @return bool success flag
  445. * @throws PEAR_Exception
  446. */
  447. public function dropColumn($table, $columnName)
  448. {
  449. global $_PEAR;
  450. $sql = 'ALTER TABLE ' . $this->quoteIdentifier($table) .
  451. ' DROP COLUMN ' . $columnName;
  452. $res = $this->conn->exec($sql);
  453. if ($_PEAR->isError($res)) {
  454. PEAR_ErrorToPEAR_Exception($res);
  455. }
  456. return true;
  457. }
  458. /**
  459. * Ensures that a table exists with the given
  460. * name and the given column definitions.
  461. *
  462. * If the table does not yet exist, it will
  463. * create the table. If it does exist, it will
  464. * alter the table to match the column definitions.
  465. *
  466. * @param string $tableName name of the table
  467. * @param array $def Table definition array
  468. *
  469. * @return bool success flag
  470. * @throws PEAR_Exception
  471. */
  472. public function ensureTable($tableName, $def)
  473. {
  474. $statements = $this->buildEnsureTable($tableName, $def);
  475. return $this->runSqlSet($statements);
  476. }
  477. /**
  478. * Run a given set of SQL commands on the connection in sequence.
  479. * Empty input is ok.
  480. *
  481. * @fixme if multiple statements, wrap in a transaction?
  482. * @param array $statements
  483. * @return bool success flag
  484. * @throws PEAR_Exception
  485. */
  486. public function runSqlSet(array $statements)
  487. {
  488. global $_PEAR;
  489. $this->conn->beginTransaction();
  490. foreach ($statements as $sql) {
  491. if (defined('DEBUG_INSTALLER')) {
  492. echo "<code>" . htmlspecialchars($sql) . "</code><br/>\n";
  493. }
  494. $res = $this->conn->exec($sql);
  495. if ($_PEAR->isError($res)) {
  496. $this->conn->rollback();
  497. common_debug('PEAR exception on query: ' . $sql);
  498. PEAR_ErrorToPEAR_Exception($res);
  499. }
  500. }
  501. $this->conn->commit();
  502. return true;
  503. }
  504. /**
  505. * Check a table's status, and if needed build a set
  506. * of SQL statements which change it to be consistent
  507. * with the given table definition.
  508. *
  509. * If the table does not yet exist, statements will
  510. * be returned to create the table. If it does exist,
  511. * statements will be returned to alter the table to
  512. * match the column definitions.
  513. *
  514. * @param string $tableName name of the table
  515. * @param array $def
  516. * @return array of SQL statements
  517. * @throws Exception
  518. */
  519. public function buildEnsureTable($tableName, array $def)
  520. {
  521. try {
  522. $old = $this->getTableDef($tableName);
  523. } catch (SchemaTableMissingException $e) {
  524. return $this->buildCreateTable($tableName, $def);
  525. }
  526. // Filter the DB-independent table definition to match the current
  527. // database engine's features and limitations.
  528. $def = $this->validateDef($tableName, $def);
  529. $def = $this->filterDef($tableName, $def);
  530. $statements = [];
  531. $fields = $this->diffArrays($old, $def, 'fields');
  532. $uniques = $this->diffArrays($old, $def, 'unique keys');
  533. $indexes = $this->diffArrays($old, $def, 'indexes');
  534. $foreign = $this->diffArrays($old, $def, 'foreign keys');
  535. $fulltext = $this->diffArrays($old, $def, 'fulltext indexes');
  536. // Drop any obsolete or modified indexes ahead...
  537. foreach ($indexes['del'] + $indexes['mod'] as $indexName) {
  538. $this->appendDropIndex($statements, $tableName, $indexName);
  539. }
  540. // Drop any obsolete or modified fulltext indexes ahead...
  541. foreach ($fulltext['del'] + $fulltext['mod'] as $indexName) {
  542. $this->appendDropIndex($statements, $tableName, $indexName);
  543. }
  544. // For efficiency, we want this all in one
  545. // query, instead of using our methods.
  546. $phrase = [];
  547. foreach ($foreign['del'] + $foreign['mod'] as $keyName) {
  548. $this->appendAlterDropForeign($phrase, $keyName);
  549. }
  550. foreach ($uniques['del'] + $uniques['mod'] as $keyName) {
  551. $this->appendAlterDropUnique($phrase, $keyName);
  552. }
  553. if (isset($old['primary key']) && (!isset($def['primary key']) || $def['primary key'] != $old['primary key'])) {
  554. $this->appendAlterDropPrimary($phrase, $tableName);
  555. }
  556. foreach ($fields['add'] as $columnName) {
  557. $this->appendAlterAddColumn(
  558. $phrase,
  559. $columnName,
  560. $def['fields'][$columnName]
  561. );
  562. }
  563. foreach ($fields['mod'] as $columnName) {
  564. $this->appendAlterModifyColumn(
  565. $phrase,
  566. $columnName,
  567. $old['fields'][$columnName],
  568. $def['fields'][$columnName]
  569. );
  570. }
  571. foreach ($fields['del'] as $columnName) {
  572. $this->appendAlterDropColumn($phrase, $columnName);
  573. }
  574. if (isset($def['primary key']) && (!isset($old['primary key']) || $old['primary key'] != $def['primary key'])) {
  575. $this->appendAlterAddPrimary($phrase, $def['primary key']);
  576. }
  577. foreach ($uniques['mod'] + $uniques['add'] as $keyName) {
  578. $this->appendAlterAddUnique($phrase, $keyName, $def['unique keys'][$keyName]);
  579. }
  580. foreach ($foreign['mod'] + $foreign['add'] as $keyName) {
  581. $this->appendAlterAddForeign($phrase, $keyName, $def['foreign keys'][$keyName]);
  582. }
  583. $this->appendAlterExtras($phrase, $tableName, $def);
  584. if (count($phrase) > 0) {
  585. $sql = 'ALTER TABLE ' . $this->quoteIdentifier($tableName) .
  586. ' ' . implode(",\n", $phrase);
  587. $statements[] = $sql;
  588. }
  589. // Now create any indexes...
  590. foreach ($indexes['mod'] + $indexes['add'] as $indexName) {
  591. $this->appendCreateIndex($statements, $tableName, $indexName, $def['indexes'][$indexName]);
  592. }
  593. foreach ($fulltext['mod'] + $fulltext['add'] as $indexName) {
  594. $colDef = $def['fulltext indexes'][$indexName];
  595. $this->appendCreateFulltextIndex($statements, $tableName, $indexName, $colDef);
  596. }
  597. /*
  598. * Merges all consecutive ALTER TABLE's into one statement.
  599. * This is necessary in MariaDB as foreign keys can disallow removal of
  600. * an index if a replacement isn't provided instantly.
  601. */
  602. [$stmts_orig, $statements] = [$statements, []];
  603. foreach ($stmts_orig as $stmt) {
  604. $prev = array_slice($statements, -1)[0] ?? '';
  605. $prefix = "ALTER TABLE {$this->quoteIdentifier($tableName)} ";
  606. if (mb_substr($stmt, 0, mb_strlen($prefix)) === $prefix
  607. && mb_substr($prev, 0, mb_strlen($prefix)) === $prefix) {
  608. $statements[] = array_pop($statements) . ', '
  609. . mb_substr($stmt, mb_strlen($prefix));
  610. } else {
  611. $statements[] = $stmt;
  612. }
  613. }
  614. return $statements;
  615. }
  616. public function diffArrays($oldDef, $newDef, $section, $compareCallback = null)
  617. {
  618. $old = isset($oldDef[$section]) ? $oldDef[$section] : [];
  619. $new = isset($newDef[$section]) ? $newDef[$section] : [];
  620. $oldKeys = array_keys($old);
  621. $newKeys = array_keys($new);
  622. $toadd = array_diff($newKeys, $oldKeys);
  623. $todrop = array_diff($oldKeys, $newKeys);
  624. $same = array_intersect($newKeys, $oldKeys);
  625. $tomod = [];
  626. $tokeep = [];
  627. // Find which fields have actually changed definition
  628. // in a way that we need to tweak them for this DB type.
  629. foreach ($same as $name) {
  630. if ($compareCallback) {
  631. $same = call_user_func($compareCallback, $old[$name], $new[$name]);
  632. } else {
  633. $same = ($old[$name] == $new[$name]);
  634. }
  635. if ($same) {
  636. $tokeep[] = $name;
  637. continue;
  638. }
  639. $tomod[] = $name;
  640. }
  641. return [
  642. 'add' => $toadd,
  643. 'del' => $todrop,
  644. 'mod' => $tomod,
  645. 'keep' => $tokeep,
  646. 'count' => count($toadd) + count($todrop) + count($tomod)
  647. ];
  648. }
  649. /**
  650. * Append phrase(s) to an array of partial ALTER TABLE chunks in order
  651. * to add the given column definition to the table.
  652. *
  653. * @param array $phrase
  654. * @param string $columnName
  655. * @param array $cd
  656. */
  657. public function appendAlterAddColumn(array &$phrase, string $columnName, array $cd)
  658. {
  659. $phrase[] = 'ADD COLUMN ' .
  660. $this->quoteIdentifier($columnName) .
  661. ' ' .
  662. $this->columnSql($columnName, $cd);
  663. }
  664. /**
  665. * Append phrase(s) to an array of partial ALTER TABLE chunks in order
  666. * to alter the given column from its old state to a new one.
  667. *
  668. * @param array $phrase
  669. * @param string $columnName
  670. * @param array $old previous column definition as found in DB
  671. * @param array $cd current column definition
  672. */
  673. public function appendAlterModifyColumn(
  674. array &$phrase,
  675. string $columnName,
  676. array $old,
  677. array $cd
  678. ): void {
  679. $prefix = 'ALTER COLUMN ' . $this->quoteIdentifier($columnName);
  680. // @fixme TYPE is a PostgreSQL extension
  681. $oldType = $this->typeAndSize($columnName, $old);
  682. $newType = $this->typeAndSize($columnName, $cd);
  683. if ($oldType !== $newType) {
  684. $phrase[] = $prefix . ' TYPE ' . $newType;
  685. }
  686. if (!($old['not null'] ?? false) && ($cd['not null'] ?? false)) {
  687. $phrase[] = $prefix . ' SET NOT NULL';
  688. } elseif (($old['not null'] ?? false) && !($cd['not null'] ?? false)) {
  689. $phrase[] = $prefix . ' DROP NOT NULL';
  690. }
  691. if (!is_null($old['default'] ?? null) && is_null($cd['default'] ?? null)) {
  692. $phrase[] = $prefix . ' DROP DEFAULT';
  693. } elseif (($old['default'] ?? null) !== ($cd['default'] ?? null)) {
  694. $phrase[] = $prefix . ' SET DEFAULT ' . $this->quoteDefaultValue($cd);
  695. }
  696. }
  697. /**
  698. * Append phrase(s) to an array of partial ALTER TABLE chunks in order
  699. * to drop the given column definition from the table.
  700. *
  701. * @param array $phrase
  702. * @param string $columnName
  703. */
  704. public function appendAlterDropColumn(array &$phrase, $columnName)
  705. {
  706. $phrase[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
  707. }
  708. public function appendAlterAddUnique(array &$phrase, $keyName, array $def)
  709. {
  710. $sql = [];
  711. $sql[] = 'ADD';
  712. $this->appendUniqueKeyDef($sql, $keyName, $def);
  713. $phrase[] = implode(' ', $sql);
  714. }
  715. public function appendAlterAddForeign(array &$phrase, $keyName, array $def)
  716. {
  717. $sql = [];
  718. $sql[] = 'ADD';
  719. $this->appendForeignKeyDef($sql, $keyName, $def);
  720. $phrase[] = implode(' ', $sql);
  721. }
  722. public function appendAlterAddPrimary(array &$phrase, array $def)
  723. {
  724. $sql = [];
  725. $sql[] = 'ADD';
  726. $this->appendPrimaryKeyDef($sql, $def);
  727. $phrase[] = implode(' ', $sql);
  728. }
  729. public function appendAlterDropPrimary(array &$phrase, string $tableName)
  730. {
  731. $phrase[] = 'DROP CONSTRAINT PRIMARY KEY';
  732. }
  733. public function appendAlterDropUnique(array &$phrase, $keyName)
  734. {
  735. $phrase[] = 'DROP CONSTRAINT ' . $keyName;
  736. }
  737. public function appendAlterDropForeign(array &$phrase, $keyName)
  738. {
  739. $phrase[] = 'DROP CONSTRAINT ' . $keyName;
  740. }
  741. public function appendAlterExtras(array &$phrase, $tableName, array $def)
  742. {
  743. // no-op
  744. }
  745. /**
  746. * Quote a db/table/column identifier if necessary.
  747. *
  748. * @param string $name
  749. * @return string
  750. */
  751. public function quoteIdentifier($name)
  752. {
  753. return $this->conn->quoteIdentifier($name);
  754. }
  755. public function quoteDefaultValue($cd)
  756. {
  757. if (in_array($cd['type'], ['datetime', 'timestamp']) && $cd['default'] === 'CURRENT_TIMESTAMP') {
  758. return $cd['default'];
  759. } else {
  760. return $this->quoteValue($cd['default']);
  761. }
  762. }
  763. public function quoteValue($val)
  764. {
  765. // MDB2_Driver_Common::quote changes empty strings to "NULL".
  766. if ($val === '') {
  767. return "''";
  768. }
  769. return $this->conn->quote($val);
  770. }
  771. /**
  772. * Returns the array of names from an array of
  773. * ColumnDef objects.
  774. *
  775. * @param array $cds array of ColumnDef objects
  776. *
  777. * @return array strings for name values
  778. */
  779. protected function _names($cds)
  780. {
  781. $names = [];
  782. foreach ($cds as $cd) {
  783. $names[] = $cd->name;
  784. }
  785. return $names;
  786. }
  787. /**
  788. * Get a ColumnDef from an array matching
  789. * name.
  790. *
  791. * @param array $cds Array of ColumnDef objects
  792. * @param string $name Name of the column
  793. *
  794. * @return ColumnDef matching item or null if no match.
  795. */
  796. protected function _byName($cds, $name)
  797. {
  798. foreach ($cds as $cd) {
  799. if ($cd->name == $name) {
  800. return $cd;
  801. }
  802. }
  803. return null;
  804. }
  805. /**
  806. * Is this column a string type?
  807. *
  808. * @param array $cd
  809. * @return bool
  810. */
  811. protected function isStringType(array $cd): bool
  812. {
  813. $strings = ['char', 'varchar', 'text'];
  814. $strings[] = 'bpchar'; // PostgreSQL
  815. $strings[] = 'enum'; // MariaDB
  816. return in_array(strtolower($cd['type']), $strings);
  817. }
  818. /**
  819. * Collation in our format from MariaDB format
  820. *
  821. * @param string $collate
  822. * @return string
  823. */
  824. protected function collationFromMySQL(string $collate): string
  825. {
  826. if (substr($collate, 0, 8) === 'utf8mb4_') {
  827. $collate = 'utf8_' . substr($collate, 8);
  828. }
  829. if (substr($collate, 0, 13) === 'utf8_unicode_') {
  830. $collate = 'utf8_general_' . substr($collate, 13);
  831. }
  832. if (!in_array($collate, [
  833. 'utf8_bin',
  834. 'utf8_general_cs',
  835. 'utf8_general_ci',
  836. ])) {
  837. common_log(
  838. LOG_ERR,
  839. 'Collation not supported: "' . $collate . '"'
  840. );
  841. $collate = 'utf8_bin';
  842. }
  843. return $collate;
  844. }
  845. /**
  846. * Return the proper SQL for creating or
  847. * altering a column.
  848. *
  849. * Appropriate for use in CREATE TABLE or
  850. * ALTER TABLE statements.
  851. *
  852. * @param string $name column name to create
  853. * @param array $cd column to create
  854. *
  855. * @return string correct SQL for that column
  856. */
  857. public function columnSql(string $name, array $cd)
  858. {
  859. $line = [];
  860. $line[] = $this->typeAndSize($name, $cd);
  861. if (isset($cd['default'])) {
  862. $line[] = 'default';
  863. $line[] = $this->quoteDefaultValue($cd);
  864. }
  865. if (!empty($cd['not null'])) {
  866. $line[] = 'NOT NULL';
  867. } else {
  868. $line[] = 'NULL';
  869. }
  870. return implode(' ', $line);
  871. }
  872. /**
  873. *
  874. * @param string $column canonical type name in defs
  875. * @return string native DB type name
  876. */
  877. public function mapType($column)
  878. {
  879. return $column;
  880. }
  881. public function typeAndSize(string $name, array $column)
  882. {
  883. //$type = $this->mapType($column)['type'];
  884. $type = $column['type'];
  885. if (isset($column['size'])) {
  886. $type = $column['size'] . $type;
  887. }
  888. $lengths = [];
  889. if (isset($column['precision'])) {
  890. $lengths[] = $column['precision'];
  891. if (isset($column['scale'])) {
  892. $lengths[] = $column['scale'];
  893. }
  894. } elseif (isset($column['length'])) {
  895. $lengths[] = $column['length'];
  896. }
  897. if ($lengths) {
  898. return $type . '(' . implode(',', $lengths) . ')';
  899. } else {
  900. return $type;
  901. }
  902. }
  903. /**
  904. * Convert an old-style set of ColumnDef objects into the current
  905. * Drupal-style schema definition array, for backwards compatibility
  906. * with plugins written for 0.9.x.
  907. *
  908. * @param string $tableName
  909. * @param array $defs : array of ColumnDef objects
  910. * @return array
  911. */
  912. protected function oldToNew($tableName, array $defs)
  913. {
  914. $table = [];
  915. $prefixes = [
  916. 'tiny',
  917. 'small',
  918. 'medium',
  919. 'big',
  920. ];
  921. foreach ($defs as $cd) {
  922. $column = [];
  923. $column['type'] = $cd->type;
  924. foreach ($prefixes as $prefix) {
  925. if (substr($cd->type, 0, strlen($prefix)) == $prefix) {
  926. $column['type'] = substr($cd->type, strlen($prefix));
  927. $column['size'] = $prefix;
  928. break;
  929. }
  930. }
  931. if ($cd->size) {
  932. if ($cd->type == 'varchar' || $cd->type == 'char') {
  933. $column['length'] = $cd->size;
  934. }
  935. }
  936. if (!$cd->nullable) {
  937. $column['not null'] = true;
  938. }
  939. if ($cd->auto_increment) {
  940. $column['type'] = 'serial';
  941. }
  942. if ($cd->default) {
  943. $column['default'] = $cd->default;
  944. }
  945. $table['fields'][$cd->name] = $column;
  946. if ($cd->key == 'PRI') {
  947. // If multiple columns are defined as primary key,
  948. // we'll pile them on in sequence.
  949. if (!isset($table['primary key'])) {
  950. $table['primary key'] = [];
  951. }
  952. $table['primary key'][] = $cd->name;
  953. } elseif ($cd->key === 'MUL') {
  954. // Individual multiple-value indexes are only per-column
  955. // using the old ColumnDef syntax.
  956. $idx = "{$tableName}_{$cd->name}_idx";
  957. $table['indexes'][$idx] = [$cd->name];
  958. } elseif ($cd->key === 'UNI') {
  959. // Individual unique-value indexes are only per-column
  960. // using the old ColumnDef syntax.
  961. $idx = "{$tableName}_{$cd->name}_idx";
  962. $table['unique keys'][$idx] = [$cd->name];
  963. }
  964. }
  965. return $table;
  966. }
  967. /**
  968. * Filter the given table definition array to match features available
  969. * in this database.
  970. *
  971. * This lets us strip out unsupported things like comments, foreign keys,
  972. * or type variants that we wouldn't get back from getTableDef().
  973. *
  974. * @param string $tableName
  975. * @param array $tableDef
  976. * @return array
  977. */
  978. public function filterDef(string $tableName, array $tableDef)
  979. {
  980. foreach ($tableDef['fields'] as $name => &$col) {
  981. switch ($col['type']) {
  982. case 'timestamp':
  983. $col['type'] = 'datetime';
  984. if (!array_key_exists('default', $col)) {
  985. $col['default'] = 'CURRENT_TIMESTAMP';
  986. }
  987. // no break
  988. case 'datetime':
  989. // Replace archaic MariaDB-specific "zero dates" with NULL
  990. if (($col['default'] ?? null) === '0000-00-00 00:00:00') {
  991. $col['default'] = null;
  992. $col['not null'] = false;
  993. }
  994. break;
  995. }
  996. if (array_key_exists('default', $col) && is_null($col['default'])) {
  997. unset($col['default']);
  998. }
  999. if (array_key_exists('not null', $col) && $col['not null'] !== true) {
  1000. unset($col['not null']);
  1001. }
  1002. if ($this->isStringType($col)) {
  1003. // Default collation
  1004. if (empty($col['collate'])) {
  1005. $col['collate'] = 'utf8_bin';
  1006. }
  1007. // Migration from direct MariaDB collations
  1008. $col['collate'] = $this->collationFromMySQL($col['collate']);
  1009. }
  1010. }
  1011. if (common_config('search', 'type') !== 'fulltext') {
  1012. unset($tableDef['fulltext indexes']);
  1013. }
  1014. if (!common_config('db', 'foreign_keys')) {
  1015. unset($tableDef['foreign keys']);
  1016. }
  1017. return $tableDef;
  1018. }
  1019. /**
  1020. * Validate a table definition array, checking for basic structure.
  1021. *
  1022. * If necessary, converts from an old-style array of ColumnDef objects.
  1023. *
  1024. * @param string $tableName
  1025. * @param array $def : table definition array
  1026. * @return array validated table definition array
  1027. *
  1028. * @throws Exception on wildly invalid input
  1029. */
  1030. public function validateDef($tableName, array $def)
  1031. {
  1032. if (isset($def[0]) && $def[0] instanceof ColumnDef) {
  1033. $def = $this->oldToNew($tableName, $def);
  1034. }
  1035. // A few quick checks :D
  1036. if (!array_key_exists('fields', $def)) {
  1037. throw new ServerException(
  1038. "Invalid table definition for {$tableName}: no fields."
  1039. );
  1040. }
  1041. // Invalidate foreign key definitions that lack a specified index
  1042. if (array_key_exists('foreign keys', $def)) {
  1043. foreach ($def['foreign keys'] as $fkey_name => $fkey_def) {
  1044. $fkey_cols = array_keys($fkey_def[1]);
  1045. // A list of all keys/indices
  1046. $keys = array_values(array_merge(
  1047. ($def['unique keys'] ?? []),
  1048. ($def['indexes'] ?? [])
  1049. ));
  1050. if (array_key_exists('primary key', $def)) {
  1051. $keys[] = $def['primary key'];
  1052. }
  1053. $indexed = false;
  1054. foreach ($keys as $key_cols) {
  1055. // Only the beginning of a key counts
  1056. $cols = array_slice($key_cols, 0, count($fkey_cols));
  1057. if ($cols == $fkey_cols) {
  1058. $indexed = true;
  1059. break;
  1060. }
  1061. }
  1062. if (!$indexed) {
  1063. throw new ServerException(
  1064. "Invalid table definition for {$tableName}: "
  1065. . "foreign key {$fkey_name} is not indexed."
  1066. );
  1067. }
  1068. }
  1069. }
  1070. return $def;
  1071. }
  1072. /**
  1073. * Pull info from the query into a fun-fun array of dooooom
  1074. *
  1075. * @param string $sql
  1076. * @return array of arrays
  1077. * @throws PEAR_Exception
  1078. */
  1079. protected function fetchQueryData(string $sql): array
  1080. {
  1081. global $_PEAR;
  1082. $res = $this->conn->query($sql);
  1083. if ($_PEAR->isError($res)) {
  1084. PEAR_ErrorToPEAR_Exception($res);
  1085. }
  1086. $out = [];
  1087. while (!empty($row = $res->fetchRow(MDB2_FETCHMODE_ASSOC))) {
  1088. $out[] = $row;
  1089. }
  1090. $res->free();
  1091. return $out;
  1092. }
  1093. public function renameTable(string $old_name, string $new_name) : bool
  1094. {
  1095. try {
  1096. $this->getTableDef($old_name);
  1097. try {
  1098. $this->getTableDef($new_name);
  1099. // New table exists, can't work
  1100. throw new ServerException("Both table {$old_name} and {$new_name} exist. You're on your own.");
  1101. } catch (SchemaTableMissingException $e) {
  1102. // New table doesn't exist, carry on
  1103. }
  1104. } catch (SchemaTableMissingException $e) {
  1105. // Already renamed, or no previous table, so we're done
  1106. return true;
  1107. }
  1108. return $this->runSqlSet([
  1109. 'ALTER TABLE ' . $this->quoteIdentifier($old_name) .
  1110. ' RENAME TO ' . $this->quoteIdentifier($new_name) . ';',
  1111. ]);
  1112. }
  1113. }
  1114. class SchemaTableMissingException extends Exception
  1115. {
  1116. // no-op
  1117. }