schema.php 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271
  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 $widgetOpts;
  40. public $scoped;
  41. public static $_static = null;
  42. protected $conn = null;
  43. /**
  44. * Constructor. Only run once for singleton object.
  45. * @param null $conn
  46. */
  47. protected function __construct($conn = null)
  48. {
  49. if (is_null($conn)) {
  50. // XXX: there should be an easier way to do this.
  51. $user = new User();
  52. $conn = $user->getDatabaseConnection();
  53. $user->free();
  54. unset($user);
  55. }
  56. $this->conn = $conn;
  57. }
  58. /**
  59. * Main public entry point. Use this to get
  60. * the schema object.
  61. *
  62. * @param object|null $conn
  63. * @param string|null Force a database type (necessary for installation purposes in which we don't have a config.php)
  64. * @return Schema the Schema object for the connection
  65. */
  66. public static function get($conn = null, $dbtype = null)
  67. {
  68. if (is_null($conn)) {
  69. $key = 'default';
  70. } else {
  71. $key = hash('md5', $conn->getDSN('string'));
  72. }
  73. if (is_null($dbtype)) {
  74. $dbtype = common_config('db', 'type');
  75. }
  76. if (empty(self::$_static[$key])) {
  77. $schemaClass = ucfirst($dbtype) . 'Schema';
  78. self::$_static[$key] = new $schemaClass($conn);
  79. }
  80. return self::$_static[$key];
  81. }
  82. /**
  83. * Gets a ColumnDef object for a single column.
  84. *
  85. * Throws an exception if the table is not found.
  86. *
  87. * @param string $table name of the table
  88. * @param string $column name of the column
  89. *
  90. * @return ColumnDef definition of the column or null
  91. * if not found.
  92. */
  93. public function getColumnDef($table, $column)
  94. {
  95. $td = $this->getTableDef($table);
  96. if (!empty($td) && !empty($td->columns)) {
  97. foreach ($td->columns as $cd) {
  98. if ($cd->name == $column) {
  99. return $cd;
  100. }
  101. }
  102. }
  103. return null;
  104. }
  105. /**
  106. * Creates a table with the given names and columns.
  107. *
  108. * @param string $tableName Name of the table
  109. * @param array $def Table definition array listing fields and indexes.
  110. *
  111. * @return bool success flag
  112. * @throws PEAR_Exception
  113. */
  114. public function createTable($tableName, $def)
  115. {
  116. $statements = $this->buildCreateTable($tableName, $def);
  117. return $this->runSqlSet($statements);
  118. }
  119. /**
  120. * Build a set of SQL statements to create a table with the given
  121. * name and columns.
  122. *
  123. * @param string $name Name of the table
  124. * @param array $def Table definition array
  125. *
  126. * @return array success flag
  127. * @throws Exception
  128. */
  129. public function buildCreateTable($name, $def)
  130. {
  131. $def = $this->validateDef($name, $def);
  132. $def = $this->filterDef($name, $def);
  133. $sql = [];
  134. foreach ($def['fields'] as $col => $colDef) {
  135. $this->appendColumnDef($sql, $col, $colDef);
  136. }
  137. // Primary, unique, and foreign keys are constraints, so go within
  138. // the CREATE TABLE statement normally.
  139. if (!empty($def['primary key'])) {
  140. $this->appendPrimaryKeyDef($sql, $def['primary key']);
  141. }
  142. if (!empty($def['unique keys'])) {
  143. foreach ($def['unique keys'] as $col => $colDef) {
  144. $this->appendUniqueKeyDef($sql, $col, $colDef);
  145. }
  146. }
  147. if (!empty($def['foreign keys'])) {
  148. foreach ($def['foreign keys'] as $keyName => $keyDef) {
  149. $this->appendForeignKeyDef($sql, $keyName, $keyDef);
  150. }
  151. }
  152. // Wrap the CREATE TABLE around the main body chunks...
  153. $statements = [];
  154. $statements[] = $this->startCreateTable($name, $def) . "\n" .
  155. implode(",\n", $sql) . "\n" .
  156. $this->endCreateTable($name, $def);
  157. // Multi-value indexes are advisory and for best portability
  158. // should be created as separate statements.
  159. if (!empty($def['indexes'])) {
  160. foreach ($def['indexes'] as $col => $colDef) {
  161. $this->appendCreateIndex($statements, $name, $col, $colDef);
  162. }
  163. }
  164. if (!empty($def['fulltext indexes'])) {
  165. foreach ($def['fulltext indexes'] as $col => $colDef) {
  166. $this->appendCreateFulltextIndex($statements, $name, $col, $colDef);
  167. }
  168. }
  169. return $statements;
  170. }
  171. /**
  172. * Set up a 'create table' SQL statement.
  173. *
  174. * @param string $name table name
  175. * @param array $def table definition
  176. * @return string
  177. */
  178. public function startCreateTable($name, array $def)
  179. {
  180. return 'CREATE TABLE ' . $this->quoteIdentifier($name) . ' (';
  181. }
  182. /**
  183. * Close out a 'create table' SQL statement.
  184. *
  185. * @param string $name table name
  186. * @param array $def table definition
  187. * @return string
  188. */
  189. public function endCreateTable($name, array $def)
  190. {
  191. return ')';
  192. }
  193. /**
  194. * Append an SQL fragment with a column definition in a CREATE TABLE statement.
  195. *
  196. * @param array $sql
  197. * @param string $name
  198. * @param array $def
  199. */
  200. public function appendColumnDef(array &$sql, string $name, array $def)
  201. {
  202. $sql[] = $name . ' ' . $this->columnSql($name, $def);
  203. }
  204. /**
  205. * Append an SQL fragment with a constraint definition for a primary
  206. * key in a CREATE TABLE statement.
  207. *
  208. * @param array $sql
  209. * @param array $def
  210. */
  211. public function appendPrimaryKeyDef(array &$sql, array $def)
  212. {
  213. $sql[] = "PRIMARY KEY " . $this->buildIndexList($def);
  214. }
  215. /**
  216. * Append an SQL fragment with a constraint definition for a unique
  217. * key in a CREATE TABLE statement.
  218. *
  219. * @param array $sql
  220. * @param string $name
  221. * @param array $def
  222. */
  223. public function appendUniqueKeyDef(array &$sql, $name, array $def)
  224. {
  225. $sql[] = "CONSTRAINT $name UNIQUE " . $this->buildIndexList($def);
  226. }
  227. /**
  228. * Append an SQL fragment with a constraint definition for a foreign
  229. * key in a CREATE TABLE statement.
  230. *
  231. * @param array $sql
  232. * @param string $name
  233. * @param array $def
  234. * @throws Exception
  235. */
  236. public function appendForeignKeyDef(array &$sql, $name, array $def)
  237. {
  238. if (count($def) != 2) {
  239. throw new Exception("Invalid foreign key def for $name: " . var_export($def, true));
  240. }
  241. list($refTable, $map) = $def;
  242. $srcCols = array_keys($map);
  243. $refCols = array_values($map);
  244. $sql[] = 'CONSTRAINT ' . $this->quoteIdentifier($name) . ' FOREIGN KEY ' .
  245. $this->buildIndexList($srcCols) .
  246. ' REFERENCES ' .
  247. $this->quoteIdentifier($refTable) .
  248. ' ' .
  249. $this->buildIndexList($refCols);
  250. }
  251. /**
  252. * Append an SQL statement with an index definition for an advisory
  253. * index over one or more columns on a table.
  254. *
  255. * @param array $statements
  256. * @param string $table
  257. * @param string $name
  258. * @param array $def
  259. */
  260. public function appendCreateIndex(array &$statements, $table, $name, array $def)
  261. {
  262. $statements[] = 'CREATE INDEX ' . $name . ' ON ' .
  263. $this->quoteIdentifier($table) . ' ' . $this->buildIndexList($def);
  264. }
  265. /**
  266. * Append an SQL statement with an index definition for a full-text search
  267. * index over one or more columns on a table.
  268. *
  269. * @param array $statements
  270. * @param string $table
  271. * @param string $name
  272. * @param array $def
  273. * @throws Exception
  274. */
  275. public function appendCreateFulltextIndex(array &$statements, $table, $name, array $def)
  276. {
  277. throw new Exception("Fulltext index not supported in this database");
  278. }
  279. /**
  280. * Append an SQL statement to drop an index from a table.
  281. *
  282. * @param array $statements
  283. * @param string $table
  284. * @param string $name
  285. */
  286. public function appendDropIndex(array &$statements, $table, $name)
  287. {
  288. $statements[] = "DROP INDEX {$name}";
  289. }
  290. public function buildIndexList(array $def)
  291. {
  292. // @fixme
  293. return '(' . implode(',', array_map([$this, 'buildIndexItem'], $def)) . ')';
  294. }
  295. public function buildIndexItem($def)
  296. {
  297. if (is_array($def)) {
  298. list($name, $size) = $def;
  299. return $this->quoteIdentifier($name) . '(' . intval($size) . ')';
  300. }
  301. return $this->quoteIdentifier($def);
  302. }
  303. /**
  304. * Drops a table from the schema
  305. *
  306. * Throws an exception if the table is not found.
  307. *
  308. * @param string $name Name of the table to drop
  309. *
  310. * @return bool success flag
  311. * @throws PEAR_Exception
  312. */
  313. public function dropTable($name)
  314. {
  315. global $_PEAR;
  316. $res = $this->conn->exec('DROP TABLE ' . $this->quoteIdentifier($name));
  317. if ($_PEAR->isError($res)) {
  318. PEAR_ErrorToPEAR_Exception($res);
  319. }
  320. return true;
  321. }
  322. /**
  323. * Adds an index to a table.
  324. *
  325. * If no name is provided, a name will be made up based
  326. * on the table name and column names.
  327. *
  328. * Throws an exception on database error, esp. if the table
  329. * does not exist.
  330. *
  331. * @param string $table Name of the table
  332. * @param array $columnNames Name of columns to index
  333. * @param string $name (Optional) name of the index
  334. *
  335. * @return bool success flag
  336. * @throws PEAR_Exception
  337. */
  338. public function createIndex($table, $columnNames, $name = null)
  339. {
  340. global $_PEAR;
  341. $statements = [];
  342. if (!is_array($columnNames)) {
  343. $columnNames = [$columnNames];
  344. }
  345. if (empty($name)) {
  346. $name = "{$table}_" . implode("_", $columnNames) . "_idx";
  347. }
  348. $this->appendCreateIndex($statements, $table, $name, $columnNames);
  349. $this->conn->beginTransaction();
  350. foreach ($statements as $sql) {
  351. $res = $this->conn->exec($sql);
  352. if ($_PEAR->isError($res)) {
  353. $this->conn->rollback();
  354. PEAR_ErrorToPEAR_Exception($res);
  355. }
  356. }
  357. $this->conn->commit();
  358. return true;
  359. }
  360. /**
  361. * Drops a named index from a table.
  362. *
  363. * @param string $table name of the table the index is on.
  364. * @param string $name name of the index
  365. *
  366. * @return bool success flag
  367. * @throws PEAR_Exception
  368. */
  369. public function dropIndex($table, $name)
  370. {
  371. global $_PEAR;
  372. $statements = [];
  373. $this->appendDropIndex($statements, $table, $name);
  374. $this->conn->beginTransaction();
  375. foreach ($statements as $sql) {
  376. $res = $this->conn->exec($sql);
  377. if ($_PEAR->isError($res)) {
  378. $this->conn->rollback();
  379. PEAR_ErrorToPEAR_Exception($res);
  380. }
  381. }
  382. $this->conn->commit();
  383. return true;
  384. }
  385. /**
  386. * Adds a column to a table
  387. *
  388. * @param string $table name of the table
  389. * @param ColumnDef $columndef Definition of the new
  390. * column.
  391. *
  392. * @return bool success flag
  393. * @throws PEAR_Exception
  394. */
  395. public function addColumn($table, $columndef)
  396. {
  397. global $_PEAR;
  398. $sql = 'ALTER TABLE ' . $this->quoteIdentifier($table) .
  399. ' ADD COLUMN ' . $this->columnSql($name, $columndef);
  400. $res = $this->conn->exec($sql);
  401. if ($_PEAR->isError($res)) {
  402. PEAR_ErrorToPEAR_Exception($res);
  403. }
  404. return true;
  405. }
  406. /**
  407. * Returns the character set of choice for this DBMS (in practice, UTF-8).
  408. *
  409. * @return string
  410. */
  411. public static function charset(): string
  412. {
  413. return 'UTF8';
  414. }
  415. /**
  416. * Modifies a column in the schema.
  417. *
  418. * The name must match an existing column and table.
  419. * @fixme Relies on MODIFY COLUMN, which is specific to MariaDB/MySQL
  420. *
  421. * @param string $table name of the table
  422. * @param ColumnDef $columndef new definition of the column.
  423. *
  424. * @return bool success flag
  425. * @throws PEAR_Exception
  426. */
  427. public function modifyColumn($table, $columndef)
  428. {
  429. global $_PEAR;
  430. $sql = 'ALTER TABLE ' . $this->quoteIdentifier($table) .
  431. ' MODIFY COLUMN ' . $this->columnSql($name, $columndef);
  432. $res = $this->conn->exec($sql);
  433. if ($_PEAR->isError($res)) {
  434. PEAR_ErrorToPEAR_Exception($res);
  435. }
  436. return true;
  437. }
  438. /**
  439. * Drops a column from a table
  440. *
  441. * The name must match an existing column.
  442. *
  443. * @param string $table name of the table
  444. * @param string $columnName name of the column to drop
  445. *
  446. * @return bool success flag
  447. * @throws PEAR_Exception
  448. */
  449. public function dropColumn($table, $columnName)
  450. {
  451. global $_PEAR;
  452. $sql = 'ALTER TABLE ' . $this->quoteIdentifier($table) .
  453. ' DROP COLUMN ' . $columnName;
  454. $res = $this->conn->exec($sql);
  455. if ($_PEAR->isError($res)) {
  456. PEAR_ErrorToPEAR_Exception($res);
  457. }
  458. return true;
  459. }
  460. /**
  461. * Ensures that a table exists with the given
  462. * name and the given column definitions.
  463. *
  464. * If the table does not yet exist, it will
  465. * create the table. If it does exist, it will
  466. * alter the table to match the column definitions.
  467. *
  468. * @param string $tableName name of the table
  469. * @param array $def Table definition array
  470. *
  471. * @return bool success flag
  472. * @throws PEAR_Exception
  473. */
  474. public function ensureTable($tableName, $def)
  475. {
  476. $statements = $this->buildEnsureTable($tableName, $def);
  477. return $this->runSqlSet($statements);
  478. }
  479. /**
  480. * Run a given set of SQL commands on the connection in sequence.
  481. * Empty input is ok.
  482. *
  483. * @fixme if multiple statements, wrap in a transaction?
  484. * @param array $statements
  485. * @return bool success flag
  486. * @throws PEAR_Exception
  487. */
  488. public function runSqlSet(array $statements)
  489. {
  490. global $_PEAR;
  491. $this->conn->beginTransaction();
  492. foreach ($statements as $sql) {
  493. if (defined('DEBUG_INSTALLER')) {
  494. echo "<code>" . htmlspecialchars($sql) . "</code><br/>\n";
  495. }
  496. $res = $this->conn->exec($sql);
  497. if ($_PEAR->isError($res)) {
  498. $this->conn->rollback();
  499. common_debug('PEAR exception on query: ' . $sql);
  500. PEAR_ErrorToPEAR_Exception($res);
  501. }
  502. }
  503. $this->conn->commit();
  504. return true;
  505. }
  506. /**
  507. * Check a table's status, and if needed build a set
  508. * of SQL statements which change it to be consistent
  509. * with the given table definition.
  510. *
  511. * If the table does not yet exist, statements will
  512. * be returned to create the table. If it does exist,
  513. * statements will be returned to alter the table to
  514. * match the column definitions.
  515. *
  516. * @param string $tableName name of the table
  517. * @param array $def
  518. * @return array of SQL statements
  519. * @throws Exception
  520. */
  521. public function buildEnsureTable($tableName, array $def)
  522. {
  523. try {
  524. $old = $this->getTableDef($tableName);
  525. } catch (SchemaTableMissingException $e) {
  526. return $this->buildCreateTable($tableName, $def);
  527. }
  528. // Filter the DB-independent table definition to match the current
  529. // database engine's features and limitations.
  530. $def = $this->validateDef($tableName, $def);
  531. $def = $this->filterDef($tableName, $def);
  532. $statements = [];
  533. $fields = $this->diffArrays($old, $def, 'fields');
  534. $uniques = $this->diffArrays($old, $def, 'unique keys');
  535. $indexes = $this->diffArrays($old, $def, 'indexes');
  536. $foreign = $this->diffArrays($old, $def, 'foreign keys');
  537. $fulltext = $this->diffArrays($old, $def, 'fulltext indexes');
  538. // Drop any obsolete or modified indexes ahead...
  539. foreach ($indexes['del'] + $indexes['mod'] as $indexName) {
  540. $this->appendDropIndex($statements, $tableName, $indexName);
  541. }
  542. // Drop any obsolete or modified fulltext indexes ahead...
  543. foreach ($fulltext['del'] + $fulltext['mod'] as $indexName) {
  544. $this->appendDropIndex($statements, $tableName, $indexName);
  545. }
  546. // For efficiency, we want this all in one
  547. // query, instead of using our methods.
  548. $phrase = [];
  549. foreach ($foreign['del'] + $foreign['mod'] as $keyName) {
  550. $this->appendAlterDropForeign($phrase, $keyName);
  551. }
  552. foreach ($uniques['del'] + $uniques['mod'] as $keyName) {
  553. $this->appendAlterDropUnique($phrase, $keyName);
  554. }
  555. if (isset($old['primary key']) && (!isset($def['primary key']) || $def['primary key'] != $old['primary key'])) {
  556. $this->appendAlterDropPrimary($phrase, $tableName);
  557. }
  558. foreach ($fields['add'] as $columnName) {
  559. $this->appendAlterAddColumn(
  560. $phrase,
  561. $columnName,
  562. $def['fields'][$columnName]
  563. );
  564. }
  565. foreach ($fields['mod'] as $columnName) {
  566. $this->appendAlterModifyColumn(
  567. $phrase,
  568. $columnName,
  569. $old['fields'][$columnName],
  570. $def['fields'][$columnName]
  571. );
  572. }
  573. foreach ($fields['del'] as $columnName) {
  574. $this->appendAlterDropColumn($phrase, $columnName);
  575. }
  576. if (isset($def['primary key']) && (!isset($old['primary key']) || $old['primary key'] != $def['primary key'])) {
  577. $this->appendAlterAddPrimary($phrase, $def['primary key']);
  578. }
  579. foreach ($uniques['mod'] + $uniques['add'] as $keyName) {
  580. $this->appendAlterAddUnique($phrase, $keyName, $def['unique keys'][$keyName]);
  581. }
  582. foreach ($foreign['mod'] + $foreign['add'] as $keyName) {
  583. $this->appendAlterAddForeign($phrase, $keyName, $def['foreign keys'][$keyName]);
  584. }
  585. $this->appendAlterExtras($phrase, $tableName, $def);
  586. if (count($phrase) > 0) {
  587. $sql = 'ALTER TABLE ' . $this->quoteIdentifier($tableName) .
  588. ' ' . implode(",\n", $phrase);
  589. $statements[] = $sql;
  590. }
  591. // Now create any indexes...
  592. foreach ($indexes['mod'] + $indexes['add'] as $indexName) {
  593. $this->appendCreateIndex($statements, $tableName, $indexName, $def['indexes'][$indexName]);
  594. }
  595. foreach ($fulltext['mod'] + $fulltext['add'] as $indexName) {
  596. $colDef = $def['fulltext indexes'][$indexName];
  597. $this->appendCreateFulltextIndex($statements, $tableName, $indexName, $colDef);
  598. }
  599. /*
  600. * Merges all consecutive ALTER TABLE's into one statement.
  601. * This is necessary in MariaDB as foreign keys can disallow removal of
  602. * an index if a replacement isn't provided instantly.
  603. */
  604. [$stmts_orig, $statements] = [$statements, []];
  605. foreach ($stmts_orig as $stmt) {
  606. $prev = array_slice($statements, -1)[0] ?? '';
  607. $prefix = "ALTER TABLE {$this->quoteIdentifier($tableName)} ";
  608. if (mb_substr($stmt, 0, mb_strlen($prefix)) === $prefix
  609. && mb_substr($prev, 0, mb_strlen($prefix)) === $prefix) {
  610. $statements[] = array_pop($statements) . ', '
  611. . mb_substr($stmt, mb_strlen($prefix));
  612. } else {
  613. $statements[] = $stmt;
  614. }
  615. }
  616. return $statements;
  617. }
  618. public function diffArrays($oldDef, $newDef, $section, $compareCallback = null)
  619. {
  620. $old = isset($oldDef[$section]) ? $oldDef[$section] : [];
  621. $new = isset($newDef[$section]) ? $newDef[$section] : [];
  622. $oldKeys = array_keys($old);
  623. $newKeys = array_keys($new);
  624. $toadd = array_diff($newKeys, $oldKeys);
  625. $todrop = array_diff($oldKeys, $newKeys);
  626. $same = array_intersect($newKeys, $oldKeys);
  627. $tomod = [];
  628. $tokeep = [];
  629. // Find which fields have actually changed definition
  630. // in a way that we need to tweak them for this DB type.
  631. foreach ($same as $name) {
  632. if ($compareCallback) {
  633. $same = call_user_func($compareCallback, $old[$name], $new[$name]);
  634. } else {
  635. $same = ($old[$name] == $new[$name]);
  636. }
  637. if ($same) {
  638. $tokeep[] = $name;
  639. continue;
  640. }
  641. $tomod[] = $name;
  642. }
  643. return [
  644. 'add' => $toadd,
  645. 'del' => $todrop,
  646. 'mod' => $tomod,
  647. 'keep' => $tokeep,
  648. 'count' => count($toadd) + count($todrop) + count($tomod)
  649. ];
  650. }
  651. /**
  652. * Append phrase(s) to an array of partial ALTER TABLE chunks in order
  653. * to add the given column definition to the table.
  654. *
  655. * @param array $phrase
  656. * @param string $columnName
  657. * @param array $cd
  658. */
  659. public function appendAlterAddColumn(array &$phrase, string $columnName, array $cd)
  660. {
  661. $phrase[] = 'ADD COLUMN ' .
  662. $this->quoteIdentifier($columnName) .
  663. ' ' .
  664. $this->columnSql($columnName, $cd);
  665. }
  666. /**
  667. * Append phrase(s) to an array of partial ALTER TABLE chunks in order
  668. * to alter the given column from its old state to a new one.
  669. *
  670. * @param array $phrase
  671. * @param string $columnName
  672. * @param array $old previous column definition as found in DB
  673. * @param array $cd current column definition
  674. */
  675. public function appendAlterModifyColumn(
  676. array &$phrase,
  677. string $columnName,
  678. array $old,
  679. array $cd
  680. ): void {
  681. $prefix = 'ALTER COLUMN ' . $this->quoteIdentifier($columnName);
  682. // @fixme TYPE is a PostgreSQL extension
  683. $oldType = $this->typeAndSize($columnName, $old);
  684. $newType = $this->typeAndSize($columnName, $cd);
  685. if ($oldType !== $newType) {
  686. $phrase[] = $prefix . ' TYPE ' . $newType;
  687. }
  688. if (!($old['not null'] ?? false) && ($cd['not null'] ?? false)) {
  689. $phrase[] = $prefix . ' SET NOT NULL';
  690. } elseif (($old['not null'] ?? false) && !($cd['not null'] ?? false)) {
  691. $phrase[] = $prefix . ' DROP NOT NULL';
  692. }
  693. if (!is_null($old['default'] ?? null) && is_null($cd['default'] ?? null)) {
  694. $phrase[] = $prefix . ' DROP DEFAULT';
  695. } elseif (($old['default'] ?? null) !== ($cd['default'] ?? null)) {
  696. $phrase[] = $prefix . ' SET DEFAULT ' . $this->quoteDefaultValue($cd);
  697. }
  698. }
  699. /**
  700. * Append phrase(s) to an array of partial ALTER TABLE chunks in order
  701. * to drop the given column definition from the table.
  702. *
  703. * @param array $phrase
  704. * @param string $columnName
  705. */
  706. public function appendAlterDropColumn(array &$phrase, $columnName)
  707. {
  708. $phrase[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
  709. }
  710. public function appendAlterAddUnique(array &$phrase, $keyName, array $def)
  711. {
  712. $sql = [];
  713. $sql[] = 'ADD';
  714. $this->appendUniqueKeyDef($sql, $keyName, $def);
  715. $phrase[] = implode(' ', $sql);
  716. }
  717. public function appendAlterAddForeign(array &$phrase, $keyName, array $def)
  718. {
  719. $sql = [];
  720. $sql[] = 'ADD';
  721. $this->appendForeignKeyDef($sql, $keyName, $def);
  722. $phrase[] = implode(' ', $sql);
  723. }
  724. public function appendAlterAddPrimary(array &$phrase, array $def)
  725. {
  726. $sql = [];
  727. $sql[] = 'ADD';
  728. $this->appendPrimaryKeyDef($sql, $def);
  729. $phrase[] = implode(' ', $sql);
  730. }
  731. public function appendAlterDropPrimary(array &$phrase, string $tableName)
  732. {
  733. $phrase[] = 'DROP CONSTRAINT PRIMARY KEY';
  734. }
  735. public function appendAlterDropUnique(array &$phrase, $keyName)
  736. {
  737. $phrase[] = 'DROP CONSTRAINT ' . $keyName;
  738. }
  739. public function appendAlterDropForeign(array &$phrase, $keyName)
  740. {
  741. $phrase[] = 'DROP CONSTRAINT ' . $keyName;
  742. }
  743. public function appendAlterExtras(array &$phrase, $tableName, array $def)
  744. {
  745. // no-op
  746. }
  747. /**
  748. * Quote a db/table/column identifier if necessary.
  749. *
  750. * @param string $name
  751. * @return string
  752. */
  753. public function quoteIdentifier($name)
  754. {
  755. return $this->conn->quoteIdentifier($name);
  756. }
  757. public function quoteDefaultValue($cd)
  758. {
  759. if (in_array($cd['type'], ['datetime', 'timestamp']) && $cd['default'] === 'CURRENT_TIMESTAMP') {
  760. return $cd['default'];
  761. } else {
  762. return $this->quoteValue($cd['default']);
  763. }
  764. }
  765. public function quoteValue($val)
  766. {
  767. // MDB2_Driver_Common::quote changes empty strings to "NULL".
  768. if ($val === '') {
  769. return "''";
  770. }
  771. return $this->conn->quote($val);
  772. }
  773. /**
  774. * Returns the array of names from an array of
  775. * ColumnDef objects.
  776. *
  777. * @param array $cds array of ColumnDef objects
  778. *
  779. * @return array strings for name values
  780. */
  781. protected function _names($cds)
  782. {
  783. $names = [];
  784. foreach ($cds as $cd) {
  785. $names[] = $cd->name;
  786. }
  787. return $names;
  788. }
  789. /**
  790. * Get a ColumnDef from an array matching
  791. * name.
  792. *
  793. * @param array $cds Array of ColumnDef objects
  794. * @param string $name Name of the column
  795. *
  796. * @return ColumnDef matching item or null if no match.
  797. */
  798. protected function _byName($cds, $name)
  799. {
  800. foreach ($cds as $cd) {
  801. if ($cd->name == $name) {
  802. return $cd;
  803. }
  804. }
  805. return null;
  806. }
  807. /**
  808. * Is this column a string type?
  809. *
  810. * @param array $cd
  811. * @return bool
  812. */
  813. protected function isStringType(array $cd): bool
  814. {
  815. $strings = ['char', 'varchar', 'text'];
  816. $strings[] = 'bpchar'; // PostgreSQL
  817. $strings[] = 'enum'; // MariaDB
  818. return in_array(strtolower($cd['type']), $strings);
  819. }
  820. /**
  821. * Collation in our format from MariaDB format
  822. *
  823. * @param string $collate
  824. * @return string
  825. */
  826. protected function collationFromMySQL(string $collate): string
  827. {
  828. if (substr($collate, 0, 8) === 'utf8mb4_') {
  829. $collate = 'utf8_' . substr($collate, 8);
  830. }
  831. if (substr($collate, 0, 13) === 'utf8_unicode_') {
  832. $collate = 'utf8_general_' . substr($collate, 13);
  833. }
  834. if (!in_array($collate, [
  835. 'utf8_bin',
  836. 'utf8_general_cs',
  837. 'utf8_general_ci',
  838. ])) {
  839. common_log(
  840. LOG_ERR,
  841. 'Collation not supported: "' . $collate . '"'
  842. );
  843. $collate = 'utf8_bin';
  844. }
  845. return $collate;
  846. }
  847. /**
  848. * Return the proper SQL for creating or
  849. * altering a column.
  850. *
  851. * Appropriate for use in CREATE TABLE or
  852. * ALTER TABLE statements.
  853. *
  854. * @param string $name column name to create
  855. * @param array $cd column to create
  856. *
  857. * @return string correct SQL for that column
  858. */
  859. public function columnSql(string $name, array $cd)
  860. {
  861. $line = [];
  862. $line[] = $this->typeAndSize($name, $cd);
  863. if (isset($cd['default'])) {
  864. $line[] = 'default';
  865. $line[] = $this->quoteDefaultValue($cd);
  866. }
  867. if (!empty($cd['not null'])) {
  868. $line[] = 'NOT NULL';
  869. } else {
  870. $line[] = 'NULL';
  871. }
  872. return implode(' ', $line);
  873. }
  874. /**
  875. *
  876. * @param string $column canonical type name in defs
  877. * @return string native DB type name
  878. */
  879. public function mapType($column)
  880. {
  881. return $column;
  882. }
  883. public function typeAndSize(string $name, array $column)
  884. {
  885. //$type = $this->mapType($column)['type'];
  886. $type = $column['type'];
  887. if (isset($column['size'])) {
  888. $type = $column['size'] . $type;
  889. }
  890. $lengths = [];
  891. if (isset($column['precision'])) {
  892. $lengths[] = $column['precision'];
  893. if (isset($column['scale'])) {
  894. $lengths[] = $column['scale'];
  895. }
  896. } elseif (isset($column['length'])) {
  897. $lengths[] = $column['length'];
  898. }
  899. if ($lengths) {
  900. return $type . '(' . implode(',', $lengths) . ')';
  901. } else {
  902. return $type;
  903. }
  904. }
  905. /**
  906. * Convert an old-style set of ColumnDef objects into the current
  907. * Drupal-style schema definition array, for backwards compatibility
  908. * with plugins written for 0.9.x.
  909. *
  910. * @param string $tableName
  911. * @param array $defs : array of ColumnDef objects
  912. * @return array
  913. */
  914. protected function oldToNew($tableName, array $defs)
  915. {
  916. $table = [];
  917. $prefixes = [
  918. 'tiny',
  919. 'small',
  920. 'medium',
  921. 'big',
  922. ];
  923. foreach ($defs as $cd) {
  924. $column = [];
  925. $column['type'] = $cd->type;
  926. foreach ($prefixes as $prefix) {
  927. if (substr($cd->type, 0, strlen($prefix)) == $prefix) {
  928. $column['type'] = substr($cd->type, strlen($prefix));
  929. $column['size'] = $prefix;
  930. break;
  931. }
  932. }
  933. if ($cd->size) {
  934. if ($cd->type == 'varchar' || $cd->type == 'char') {
  935. $column['length'] = $cd->size;
  936. }
  937. }
  938. if (!$cd->nullable) {
  939. $column['not null'] = true;
  940. }
  941. if ($cd->auto_increment) {
  942. $column['type'] = 'serial';
  943. }
  944. if ($cd->default) {
  945. $column['default'] = $cd->default;
  946. }
  947. $table['fields'][$cd->name] = $column;
  948. if ($cd->key == 'PRI') {
  949. // If multiple columns are defined as primary key,
  950. // we'll pile them on in sequence.
  951. if (!isset($table['primary key'])) {
  952. $table['primary key'] = [];
  953. }
  954. $table['primary key'][] = $cd->name;
  955. } elseif ($cd->key === 'MUL') {
  956. // Individual multiple-value indexes are only per-column
  957. // using the old ColumnDef syntax.
  958. $idx = "{$tableName}_{$cd->name}_idx";
  959. $table['indexes'][$idx] = [$cd->name];
  960. } elseif ($cd->key === 'UNI') {
  961. // Individual unique-value indexes are only per-column
  962. // using the old ColumnDef syntax.
  963. $idx = "{$tableName}_{$cd->name}_idx";
  964. $table['unique keys'][$idx] = [$cd->name];
  965. }
  966. }
  967. return $table;
  968. }
  969. /**
  970. * Filter the given table definition array to match features available
  971. * in this database.
  972. *
  973. * This lets us strip out unsupported things like comments, foreign keys,
  974. * or type variants that we wouldn't get back from getTableDef().
  975. *
  976. * @param string $tableName
  977. * @param array $tableDef
  978. * @return array
  979. */
  980. public function filterDef(string $tableName, array $tableDef)
  981. {
  982. foreach ($tableDef['fields'] as $name => &$col) {
  983. switch ($col['type']) {
  984. case 'timestamp':
  985. $col['type'] = 'datetime';
  986. if (!array_key_exists('default', $col)) {
  987. $col['default'] = 'CURRENT_TIMESTAMP';
  988. }
  989. // no break
  990. case 'datetime':
  991. // Replace archaic MariaDB-specific "zero dates" with NULL
  992. if (($col['default'] ?? null) === '0000-00-00 00:00:00') {
  993. $col['default'] = null;
  994. $col['not null'] = false;
  995. }
  996. break;
  997. }
  998. if (array_key_exists('default', $col) && is_null($col['default'])) {
  999. unset($col['default']);
  1000. }
  1001. if (array_key_exists('not null', $col) && $col['not null'] !== true) {
  1002. unset($col['not null']);
  1003. }
  1004. if ($this->isStringType($col)) {
  1005. // Default collation
  1006. if (empty($col['collate'])) {
  1007. $col['collate'] = 'utf8_bin';
  1008. }
  1009. // Migration from direct MariaDB collations
  1010. $col['collate'] = $this->collationFromMySQL($col['collate']);
  1011. }
  1012. }
  1013. if (common_config('search', 'type') !== 'fulltext') {
  1014. unset($tableDef['fulltext indexes']);
  1015. }
  1016. if (!common_config('db', 'foreign_keys')) {
  1017. unset($tableDef['foreign keys']);
  1018. }
  1019. return $tableDef;
  1020. }
  1021. /**
  1022. * Validate a table definition array, checking for basic structure.
  1023. *
  1024. * If necessary, converts from an old-style array of ColumnDef objects.
  1025. *
  1026. * @param string $tableName
  1027. * @param array $def : table definition array
  1028. * @return array validated table definition array
  1029. *
  1030. * @throws Exception on wildly invalid input
  1031. */
  1032. public function validateDef($tableName, array $def)
  1033. {
  1034. if (isset($def[0]) && $def[0] instanceof ColumnDef) {
  1035. $def = $this->oldToNew($tableName, $def);
  1036. }
  1037. // A few quick checks :D
  1038. if (!array_key_exists('fields', $def)) {
  1039. throw new ServerException(
  1040. "Invalid table definition for {$tableName}: no fields."
  1041. );
  1042. }
  1043. // Invalidate foreign key definitions that lack a specified index
  1044. if (array_key_exists('foreign keys', $def)) {
  1045. foreach ($def['foreign keys'] as $fkey_name => $fkey_def) {
  1046. $fkey_cols = array_keys($fkey_def[1]);
  1047. // A list of all keys/indices
  1048. $keys = array_values(array_merge(
  1049. ($def['unique keys'] ?? []),
  1050. ($def['indexes'] ?? [])
  1051. ));
  1052. if (array_key_exists('primary key', $def)) {
  1053. $keys[] = $def['primary key'];
  1054. }
  1055. $indexed = false;
  1056. foreach ($keys as $key_cols) {
  1057. // Only the beginning of a key counts
  1058. $cols = array_slice($key_cols, 0, count($fkey_cols));
  1059. if ($cols == $fkey_cols) {
  1060. $indexed = true;
  1061. break;
  1062. }
  1063. }
  1064. if (!$indexed) {
  1065. throw new ServerException(
  1066. "Invalid table definition for {$tableName}: "
  1067. . "foreign key {$fkey_name} is not indexed."
  1068. );
  1069. }
  1070. }
  1071. }
  1072. return $def;
  1073. }
  1074. /**
  1075. * Pull info from the query into a fun-fun array of dooooom
  1076. *
  1077. * @param string $sql
  1078. * @return array of arrays
  1079. * @throws PEAR_Exception
  1080. */
  1081. protected function fetchQueryData(string $sql): array
  1082. {
  1083. global $_PEAR;
  1084. $res = $this->conn->query($sql);
  1085. if ($_PEAR->isError($res)) {
  1086. PEAR_ErrorToPEAR_Exception($res);
  1087. }
  1088. $out = [];
  1089. while (!empty($row = $res->fetchRow(MDB2_FETCHMODE_ASSOC))) {
  1090. $out[] = $row;
  1091. }
  1092. $res->free();
  1093. return $out;
  1094. }
  1095. public function renameTable(string $old_name, string $new_name) : bool
  1096. {
  1097. try {
  1098. $this->getTableDef($old_name);
  1099. try {
  1100. $this->getTableDef($new_name);
  1101. // New table exists, can't work
  1102. throw new ServerException("Both table {$old_name} and {$new_name} exist. You're on your own.");
  1103. } catch (SchemaTableMissingException $e) {
  1104. // New table doesn't exist, carry on
  1105. }
  1106. } catch (SchemaTableMissingException $e) {
  1107. // Already renamed, or no previous table, so we're done
  1108. return true;
  1109. }
  1110. return $this->runSqlSet([
  1111. 'ALTER TABLE ' . $this->quoteIdentifier($old_name) .
  1112. ' RENAME TO ' . $this->quoteIdentifier($new_name) . ';',
  1113. ]);
  1114. }
  1115. }
  1116. class SchemaTableMissingException extends Exception
  1117. {
  1118. // no-op
  1119. }