schema.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238
  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}";
  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. $statements = [];
  366. $this->appendDropIndex($statements, $table, $name);
  367. $res = $this->conn->query(implode(";\n", $statements));
  368. if ($_PEAR->isError($res)) {
  369. PEAR_ErrorToPEAR_Exception($res);
  370. }
  371. return true;
  372. }
  373. /**
  374. * Adds a column to a table
  375. *
  376. * @param string $table name of the table
  377. * @param ColumnDef $columndef Definition of the new
  378. * column.
  379. *
  380. * @return bool success flag
  381. * @throws PEAR_Exception
  382. */
  383. public function addColumn($table, $columndef)
  384. {
  385. global $_PEAR;
  386. $sql = 'ALTER TABLE ' . $this->quoteIdentifier($table) .
  387. ' ADD COLUMN ' . $this->columnSql($name, $columndef);
  388. $res = $this->conn->query($sql);
  389. if ($_PEAR->isError($res)) {
  390. PEAR_ErrorToPEAR_Exception($res);
  391. }
  392. return true;
  393. }
  394. /**
  395. * Modifies a column in the schema.
  396. *
  397. * The name must match an existing column and table.
  398. * @fixme Relies on MODIFY COLUMN, which is specific to MariaDB/MySQL
  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. /*
  577. * Merges all consecutive ALTER TABLE's into one statement.
  578. * This is necessary in MariaDB as foreign keys can disallow removal of
  579. * an index if a replacement isn't provided instantly.
  580. */
  581. [$stmts_orig, $statements] = [$statements, []];
  582. foreach ($stmts_orig as $stmt) {
  583. $prev = array_slice($statements, -1)[0] ?? '';
  584. $prefix = "ALTER TABLE {$this->quoteIdentifier($tableName)} ";
  585. if (mb_substr($stmt, 0, mb_strlen($prefix)) === $prefix
  586. && mb_substr($prev, 0, mb_strlen($prefix)) === $prefix) {
  587. $statements[] = array_pop($statements) . ', '
  588. . mb_substr($stmt, mb_strlen($prefix));
  589. } else {
  590. $statements[] = $stmt;
  591. }
  592. }
  593. return $statements;
  594. }
  595. public function diffArrays($oldDef, $newDef, $section, $compareCallback = null)
  596. {
  597. $old = isset($oldDef[$section]) ? $oldDef[$section] : [];
  598. $new = isset($newDef[$section]) ? $newDef[$section] : [];
  599. $oldKeys = array_keys($old);
  600. $newKeys = array_keys($new);
  601. $toadd = array_diff($newKeys, $oldKeys);
  602. $todrop = array_diff($oldKeys, $newKeys);
  603. $same = array_intersect($newKeys, $oldKeys);
  604. $tomod = [];
  605. $tokeep = [];
  606. // Find which fields have actually changed definition
  607. // in a way that we need to tweak them for this DB type.
  608. foreach ($same as $name) {
  609. if ($compareCallback) {
  610. $same = call_user_func($compareCallback, $old[$name], $new[$name]);
  611. } else {
  612. $same = ($old[$name] == $new[$name]);
  613. }
  614. if ($same) {
  615. $tokeep[] = $name;
  616. continue;
  617. }
  618. $tomod[] = $name;
  619. }
  620. return [
  621. 'add' => $toadd,
  622. 'del' => $todrop,
  623. 'mod' => $tomod,
  624. 'keep' => $tokeep,
  625. 'count' => count($toadd) + count($todrop) + count($tomod)
  626. ];
  627. }
  628. /**
  629. * Append phrase(s) to an array of partial ALTER TABLE chunks in order
  630. * to add the given column definition to the table.
  631. *
  632. * @param array $phrase
  633. * @param string $columnName
  634. * @param array $cd
  635. */
  636. public function appendAlterAddColumn(array &$phrase, string $columnName, array $cd)
  637. {
  638. $phrase[] = 'ADD COLUMN ' .
  639. $this->quoteIdentifier($columnName) .
  640. ' ' .
  641. $this->columnSql($columnName, $cd);
  642. }
  643. /**
  644. * Append phrase(s) to an array of partial ALTER TABLE chunks in order
  645. * to alter the given column from its old state to a new one.
  646. *
  647. * @param array $phrase
  648. * @param string $columnName
  649. * @param array $old previous column definition as found in DB
  650. * @param array $cd current column definition
  651. */
  652. public function appendAlterModifyColumn(
  653. array &$phrase,
  654. string $columnName,
  655. array $old,
  656. array $cd
  657. ): void {
  658. $prefix = 'ALTER COLUMN ' . $this->quoteIdentifier($columnName);
  659. // @fixme TYPE is a PostgreSQL extension
  660. $oldType = $this->typeAndSize($columnName, $old);
  661. $newType = $this->typeAndSize($columnName, $cd);
  662. if ($oldType !== $newType) {
  663. $phrase[] = $prefix . ' TYPE ' . $newType;
  664. }
  665. if (!($old['not null'] ?? false) && ($cd['not null'] ?? false)) {
  666. $phrase[] = $prefix . ' SET NOT NULL';
  667. } elseif (($old['not null'] ?? false) && !($cd['not null'] ?? false)) {
  668. $phrase[] = $prefix . ' DROP NOT NULL';
  669. }
  670. if (!is_null($old['default'] ?? null) && is_null($cd['default'] ?? null)) {
  671. $phrase[] = $prefix . ' DROP DEFAULT';
  672. } elseif (($old['default'] ?? null) !== ($cd['default'] ?? null)) {
  673. $phrase[] = $prefix . ' SET DEFAULT ' . $this->quoteDefaultValue($cd);
  674. }
  675. }
  676. /**
  677. * Append phrase(s) to an array of partial ALTER TABLE chunks in order
  678. * to drop the given column definition from the table.
  679. *
  680. * @param array $phrase
  681. * @param string $columnName
  682. */
  683. public function appendAlterDropColumn(array &$phrase, $columnName)
  684. {
  685. $phrase[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
  686. }
  687. public function appendAlterAddUnique(array &$phrase, $keyName, array $def)
  688. {
  689. $sql = [];
  690. $sql[] = 'ADD';
  691. $this->appendUniqueKeyDef($sql, $keyName, $def);
  692. $phrase[] = implode(' ', $sql);
  693. }
  694. public function appendAlterAddForeign(array &$phrase, $keyName, array $def)
  695. {
  696. $sql = [];
  697. $sql[] = 'ADD';
  698. $this->appendForeignKeyDef($sql, $keyName, $def);
  699. $phrase[] = implode(' ', $sql);
  700. }
  701. public function appendAlterAddPrimary(array &$phrase, array $def)
  702. {
  703. $sql = [];
  704. $sql[] = 'ADD';
  705. $this->appendPrimaryKeyDef($sql, $def);
  706. $phrase[] = implode(' ', $sql);
  707. }
  708. public function appendAlterDropPrimary(array &$phrase, string $tableName)
  709. {
  710. $phrase[] = 'DROP CONSTRAINT PRIMARY KEY';
  711. }
  712. public function appendAlterDropUnique(array &$phrase, $keyName)
  713. {
  714. $phrase[] = 'DROP CONSTRAINT ' . $keyName;
  715. }
  716. public function appendAlterDropForeign(array &$phrase, $keyName)
  717. {
  718. $phrase[] = 'DROP CONSTRAINT ' . $keyName;
  719. }
  720. public function appendAlterExtras(array &$phrase, $tableName, array $def)
  721. {
  722. // no-op
  723. }
  724. /**
  725. * Quote a db/table/column identifier if necessary.
  726. *
  727. * @param string $name
  728. * @return string
  729. */
  730. public function quoteIdentifier($name)
  731. {
  732. return $this->conn->quoteIdentifier($name);
  733. }
  734. public function quoteDefaultValue($cd)
  735. {
  736. if (in_array($cd['type'], ['datetime', 'timestamp']) && $cd['default'] === 'CURRENT_TIMESTAMP') {
  737. return $cd['default'];
  738. } else {
  739. return $this->quoteValue($cd['default']);
  740. }
  741. }
  742. public function quoteValue($val)
  743. {
  744. return $this->conn->quoteSmart($val);
  745. }
  746. /**
  747. * Returns the array of names from an array of
  748. * ColumnDef objects.
  749. *
  750. * @param array $cds array of ColumnDef objects
  751. *
  752. * @return array strings for name values
  753. */
  754. protected function _names($cds)
  755. {
  756. $names = [];
  757. foreach ($cds as $cd) {
  758. $names[] = $cd->name;
  759. }
  760. return $names;
  761. }
  762. /**
  763. * Get a ColumnDef from an array matching
  764. * name.
  765. *
  766. * @param array $cds Array of ColumnDef objects
  767. * @param string $name Name of the column
  768. *
  769. * @return ColumnDef matching item or null if no match.
  770. */
  771. protected function _byName($cds, $name)
  772. {
  773. foreach ($cds as $cd) {
  774. if ($cd->name == $name) {
  775. return $cd;
  776. }
  777. }
  778. return null;
  779. }
  780. /**
  781. * Is this column a string type?
  782. *
  783. * @param array $cd
  784. * @return bool
  785. */
  786. protected function isStringType(array $cd): bool
  787. {
  788. $strings = ['char', 'varchar', 'text'];
  789. $strings[] = 'bpchar'; // PostgreSQL
  790. $strings[] = 'enum'; // MariaDB
  791. return in_array(strtolower($cd['type']), $strings);
  792. }
  793. /**
  794. * Collation in our format from MariaDB format
  795. *
  796. * @param string $collate
  797. * @return string
  798. */
  799. protected function collationFromMySQL(string $collate): string
  800. {
  801. if (substr($collate, 0, 8) === 'utf8mb4_') {
  802. $collate = 'utf8_' . substr($collate, 8);
  803. }
  804. if (substr($collate, 0, 13) === 'utf8_unicode_') {
  805. $collate = 'utf8_general_' . substr($collate, 13);
  806. }
  807. if (!in_array($collate, [
  808. 'utf8_bin',
  809. 'utf8_general_cs',
  810. 'utf8_general_ci',
  811. ])) {
  812. common_log(
  813. LOG_ERR,
  814. 'Collation not supported: "' . $collate . '"'
  815. );
  816. $collate = 'utf8_bin';
  817. }
  818. return $collate;
  819. }
  820. /**
  821. * Return the proper SQL for creating or
  822. * altering a column.
  823. *
  824. * Appropriate for use in CREATE TABLE or
  825. * ALTER TABLE statements.
  826. *
  827. * @param string $name column name to create
  828. * @param array $cd column to create
  829. *
  830. * @return string correct SQL for that column
  831. */
  832. public function columnSql(string $name, array $cd)
  833. {
  834. $line = [];
  835. $line[] = $this->typeAndSize($name, $cd);
  836. if (isset($cd['default'])) {
  837. $line[] = 'default';
  838. $line[] = $this->quoteDefaultValue($cd);
  839. }
  840. if (!empty($cd['not null'])) {
  841. $line[] = 'NOT NULL';
  842. } else {
  843. $line[] = 'NULL';
  844. }
  845. return implode(' ', $line);
  846. }
  847. /**
  848. *
  849. * @param string $column canonical type name in defs
  850. * @return string native DB type name
  851. */
  852. public function mapType($column)
  853. {
  854. return $column;
  855. }
  856. public function typeAndSize(string $name, array $column)
  857. {
  858. //$type = $this->mapType($column)['type'];
  859. $type = $column['type'];
  860. if (isset($column['size'])) {
  861. $type = $column['size'] . $type;
  862. }
  863. $lengths = [];
  864. if (isset($column['precision'])) {
  865. $lengths[] = $column['precision'];
  866. if (isset($column['scale'])) {
  867. $lengths[] = $column['scale'];
  868. }
  869. } elseif (isset($column['length'])) {
  870. $lengths[] = $column['length'];
  871. }
  872. if ($lengths) {
  873. return $type . '(' . implode(',', $lengths) . ')';
  874. } else {
  875. return $type;
  876. }
  877. }
  878. /**
  879. * Convert an old-style set of ColumnDef objects into the current
  880. * Drupal-style schema definition array, for backwards compatibility
  881. * with plugins written for 0.9.x.
  882. *
  883. * @param string $tableName
  884. * @param array $defs : array of ColumnDef objects
  885. * @return array
  886. */
  887. protected function oldToNew($tableName, array $defs)
  888. {
  889. $table = [];
  890. $prefixes = [
  891. 'tiny',
  892. 'small',
  893. 'medium',
  894. 'big',
  895. ];
  896. foreach ($defs as $cd) {
  897. $column = [];
  898. $column['type'] = $cd->type;
  899. foreach ($prefixes as $prefix) {
  900. if (substr($cd->type, 0, strlen($prefix)) == $prefix) {
  901. $column['type'] = substr($cd->type, strlen($prefix));
  902. $column['size'] = $prefix;
  903. break;
  904. }
  905. }
  906. if ($cd->size) {
  907. if ($cd->type == 'varchar' || $cd->type == 'char') {
  908. $column['length'] = $cd->size;
  909. }
  910. }
  911. if (!$cd->nullable) {
  912. $column['not null'] = true;
  913. }
  914. if ($cd->auto_increment) {
  915. $column['type'] = 'serial';
  916. }
  917. if ($cd->default) {
  918. $column['default'] = $cd->default;
  919. }
  920. $table['fields'][$cd->name] = $column;
  921. if ($cd->key == 'PRI') {
  922. // If multiple columns are defined as primary key,
  923. // we'll pile them on in sequence.
  924. if (!isset($table['primary key'])) {
  925. $table['primary key'] = [];
  926. }
  927. $table['primary key'][] = $cd->name;
  928. } elseif ($cd->key === 'MUL') {
  929. // Individual multiple-value indexes are only per-column
  930. // using the old ColumnDef syntax.
  931. $idx = "{$tableName}_{$cd->name}_idx";
  932. $table['indexes'][$idx] = [$cd->name];
  933. } elseif ($cd->key === 'UNI') {
  934. // Individual unique-value indexes are only per-column
  935. // using the old ColumnDef syntax.
  936. $idx = "{$tableName}_{$cd->name}_idx";
  937. $table['unique keys'][$idx] = [$cd->name];
  938. }
  939. }
  940. return $table;
  941. }
  942. /**
  943. * Filter the given table definition array to match features available
  944. * in this database.
  945. *
  946. * This lets us strip out unsupported things like comments, foreign keys,
  947. * or type variants that we wouldn't get back from getTableDef().
  948. *
  949. * @param string $tableName
  950. * @param array $tableDef
  951. * @return array
  952. */
  953. public function filterDef(string $tableName, array $tableDef)
  954. {
  955. foreach ($tableDef['fields'] as $name => &$col) {
  956. switch ($col['type']) {
  957. case 'timestamp':
  958. $col['type'] = 'datetime';
  959. if (!array_key_exists('default', $col)) {
  960. $col['default'] = 'CURRENT_TIMESTAMP';
  961. }
  962. // no break
  963. case 'datetime':
  964. // Replace archaic MariaDB-specific "zero dates" with NULL
  965. if (($col['default'] ?? null) === '0000-00-00 00:00:00') {
  966. $col['default'] = null;
  967. $col['not null'] = false;
  968. }
  969. break;
  970. }
  971. if (array_key_exists('default', $col) && is_null($col['default'])) {
  972. unset($col['default']);
  973. }
  974. if (array_key_exists('not null', $col) && $col['not null'] !== true) {
  975. unset($col['not null']);
  976. }
  977. if ($this->isStringType($col)) {
  978. // Default collation
  979. if (empty($col['collate'])) {
  980. $col['collate'] = 'utf8_bin';
  981. }
  982. // Migration from direct MariaDB collations
  983. $col['collate'] = $this->collationFromMySQL($col['collate']);
  984. }
  985. }
  986. if (common_config('search', 'type') !== 'fulltext') {
  987. unset($tableDef['fulltext indexes']);
  988. }
  989. if (!common_config('db', 'foreign_keys')) {
  990. unset($tableDef['foreign keys']);
  991. }
  992. return $tableDef;
  993. }
  994. /**
  995. * Validate a table definition array, checking for basic structure.
  996. *
  997. * If necessary, converts from an old-style array of ColumnDef objects.
  998. *
  999. * @param string $tableName
  1000. * @param array $def : table definition array
  1001. * @return array validated table definition array
  1002. *
  1003. * @throws Exception on wildly invalid input
  1004. */
  1005. public function validateDef($tableName, array $def)
  1006. {
  1007. if (isset($def[0]) && $def[0] instanceof ColumnDef) {
  1008. $def = $this->oldToNew($tableName, $def);
  1009. }
  1010. // A few quick checks :D
  1011. if (!array_key_exists('fields', $def)) {
  1012. throw new ServerException(
  1013. "Invalid table definition for {$tableName}: no fields."
  1014. );
  1015. }
  1016. // Invalidate foreign key definitions that lack a specified index
  1017. if (array_key_exists('foreign keys', $def)) {
  1018. foreach ($def['foreign keys'] as $fkey_name => $fkey_def) {
  1019. $fkey_cols = array_keys($fkey_def[1]);
  1020. // A list of all keys/indices
  1021. $keys = array_values(array_merge(
  1022. ($def['unique keys'] ?? []),
  1023. ($def['indexes'] ?? [])
  1024. ));
  1025. if (array_key_exists('primary key', $def)) {
  1026. $keys[] = $def['primary key'];
  1027. }
  1028. $indexed = false;
  1029. foreach ($keys as $key_cols) {
  1030. // Only the beginning of a key counts
  1031. $cols = array_slice($key_cols, 0, count($fkey_cols));
  1032. if ($cols == $fkey_cols) {
  1033. $indexed = true;
  1034. break;
  1035. }
  1036. }
  1037. if (!$indexed) {
  1038. throw new ServerException(
  1039. "Invalid table definition for {$tableName}: "
  1040. . "foreign key {$fkey_name} is not indexed."
  1041. );
  1042. }
  1043. }
  1044. }
  1045. return $def;
  1046. }
  1047. /**
  1048. * Pull info from the query into a fun-fun array of dooooom
  1049. *
  1050. * @param string $sql
  1051. * @return array of arrays
  1052. * @throws PEAR_Exception
  1053. */
  1054. protected function fetchQueryData($sql)
  1055. {
  1056. global $_PEAR;
  1057. $res = $this->conn->query($sql);
  1058. if ($_PEAR->isError($res)) {
  1059. PEAR_ErrorToPEAR_Exception($res);
  1060. }
  1061. $out = [];
  1062. $row = [];
  1063. while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
  1064. $out[] = $row;
  1065. }
  1066. $res->free();
  1067. return $out;
  1068. }
  1069. public function renameTable(string $old_name, string $new_name) : bool
  1070. {
  1071. try {
  1072. $this->getTableDef($old_name);
  1073. try {
  1074. $this->getTableDef($new_name);
  1075. // New table exists, can't work
  1076. throw new ServerException("Both table {$old_name} and {$new_name} exist. You're on your own.");
  1077. } catch (SchemaTableMissingException $e) {
  1078. // New table doesn't exist, carry on
  1079. }
  1080. } catch (SchemaTableMissingException $e) {
  1081. // Already renamed, or no previous table, so we're done
  1082. return true;
  1083. }
  1084. return $this->runSqlSet([
  1085. 'ALTER TABLE ' . $this->quoteIdentifier($old_name) .
  1086. ' RENAME TO ' . $this->quoteIdentifier($new_name) . ';',
  1087. ]);
  1088. }
  1089. }
  1090. class SchemaTableMissingException extends Exception
  1091. {
  1092. // no-op
  1093. }