pgsqlschema.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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 for PostgreSQL
  18. *
  19. * @category Database
  20. * @package GNUsocial
  21. * @author Evan Prodromou <evan@status.net>
  22. * @author Brenda Wallace <shiny@cpan.org>
  23. * @author Brion Vibber <brion@status.net>
  24. * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
  25. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  26. */
  27. defined('GNUSOCIAL') || die();
  28. /**
  29. * Class representing the database schema for PostgreSQL
  30. *
  31. * A class representing the database schema. Can be used to
  32. * manipulate the schema -- especially for plugins and upgrade
  33. * utilities.
  34. *
  35. * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
  36. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  37. */
  38. class PgsqlSchema extends Schema
  39. {
  40. public static $_single = null;
  41. /**
  42. * Main public entry point. Use this to get
  43. * the singleton object.
  44. *
  45. * @param object|null $conn
  46. * @param string|null dummy param
  47. * @return Schema the (single) Schema object
  48. */
  49. public static function get($conn = null, $_ = 'pgsql')
  50. {
  51. if (empty(self::$_single)) {
  52. self::$_single = new Schema($conn, 'pgsql');
  53. }
  54. return self::$_single;
  55. }
  56. /**
  57. * Returns a table definition array for the table
  58. * in the schema with the given name.
  59. *
  60. * Throws an exception if the table is not found.
  61. *
  62. * @param string $table Name of the table to get
  63. *
  64. * @return array tabledef for that table.
  65. * @throws SchemaTableMissingException
  66. */
  67. public function getTableDef($table)
  68. {
  69. $def = [];
  70. $hasKeys = false;
  71. // Pull column data from INFORMATION_SCHEMA
  72. $columns = $this->fetchMetaInfo($table, 'columns', 'ordinal_position');
  73. if (count($columns) == 0) {
  74. throw new SchemaTableMissingException("No such table: $table");
  75. }
  76. // We'll need to match up fields by ordinal reference
  77. $orderedFields = [];
  78. foreach ($columns as $row) {
  79. $name = $row['column_name'];
  80. $orderedFields[$row['ordinal_position']] = $name;
  81. $field = [];
  82. $field['type'] = $type = $row['udt_name'];
  83. if ($type == 'char' || $type == 'varchar') {
  84. if ($row['character_maximum_length'] !== null) {
  85. $field['length'] = intval($row['character_maximum_length']);
  86. }
  87. }
  88. if ($type == 'numeric') {
  89. // Other int types may report these values, but they're irrelevant.
  90. // Just ignore them!
  91. if ($row['numeric_precision'] !== null) {
  92. $field['precision'] = intval($row['numeric_precision']);
  93. }
  94. if ($row['numeric_scale'] !== null) {
  95. $field['scale'] = intval($row['numeric_scale']);
  96. }
  97. }
  98. if ($row['is_nullable'] == 'NO') {
  99. $field['not null'] = true;
  100. }
  101. if ($row['column_default'] !== null) {
  102. $field['default'] = $row['column_default'];
  103. if ($this->isNumericType($type)) {
  104. $field['default'] = intval($field['default']);
  105. }
  106. }
  107. $def['fields'][$name] = $field;
  108. }
  109. // Pulling index info from pg_class & pg_index
  110. // This can give us primary & unique key info, but not foreign key constraints
  111. // so we exclude them and pick them up later.
  112. $indexInfo = $this->getIndexInfo($table);
  113. foreach ($indexInfo as $row) {
  114. $keyName = $row['key_name'];
  115. $keyDef = $row['key_def'];
  116. // Dig the column references out!
  117. //
  118. // These are inconvenient arrays with partial references to the
  119. // pg_att table, but since we've already fetched up the column
  120. // info on the current table, we can look those up locally.
  121. $cols = [];
  122. $colPositions = explode(' ', $row['indkey']);
  123. foreach ($colPositions as $ord) {
  124. if ($ord == 0) {
  125. $cols[] = 'FUNCTION'; // @fixme
  126. } else {
  127. $cols[] = $orderedFields[$ord];
  128. }
  129. }
  130. if (preg_match('/^[^\(]+ USING gin \(/i', $keyDef)) {
  131. $def['fulltext indexes'][$keyName] = $cols;
  132. } else {
  133. $def['indexes'][$keyName] = $cols;
  134. }
  135. }
  136. // Pull constraint data from INFORMATION_SCHEMA:
  137. // Primary key, unique keys, foreign keys
  138. $keyColumns = $this->fetchMetaInfo($table, 'key_column_usage', 'constraint_name,ordinal_position');
  139. $keys = [];
  140. foreach ($keyColumns as $row) {
  141. $keyName = $row['constraint_name'];
  142. $keyCol = $row['column_name'];
  143. if (!isset($keys[$keyName])) {
  144. $keys[$keyName] = [];
  145. }
  146. $keys[$keyName][] = $keyCol;
  147. }
  148. foreach ($keys as $keyName => $cols) {
  149. // name hack -- is this reliable?
  150. if ($keyName == "{$table}_pkey") {
  151. $def['primary key'] = $cols;
  152. } elseif (preg_match("/^{$table}_(.+)_fkey$/", $keyName)) {
  153. $fkey = $this->getForeignKeyInfo($table, $keyName);
  154. $colMap = array_combine($cols, $fkey['col_names']);
  155. $def['foreign keys'][$keyName] = [$fkey['table_name'], $colMap];
  156. } else {
  157. $def['unique keys'][$keyName] = $cols;
  158. }
  159. }
  160. return $def;
  161. }
  162. /**
  163. * Pull some INFORMATION.SCHEMA data for the given table.
  164. *
  165. * @param string $table
  166. * @param $infoTable
  167. * @param null $orderBy
  168. * @return array of arrays
  169. * @throws PEAR_Exception
  170. */
  171. public function fetchMetaInfo($table, $infoTable, $orderBy = null)
  172. {
  173. $query = "SELECT * FROM information_schema.%s " .
  174. "WHERE table_name='%s'";
  175. $sql = sprintf($query, $infoTable, $table);
  176. if ($orderBy) {
  177. $sql .= ' ORDER BY ' . $orderBy;
  178. }
  179. return $this->fetchQueryData($sql);
  180. }
  181. /**
  182. * Pull some PG-specific index info
  183. * @param string $table
  184. * @return array of arrays
  185. * @throws PEAR_Exception
  186. */
  187. public function getIndexInfo($table)
  188. {
  189. $sql = sprintf('SELECT relname AS key_name, indexdef AS key_def, pg_index.* ' .
  190. 'FROM pg_index ' .
  191. 'JOIN pg_class ON pg_index.indexrelid = pg_class.oid ' .
  192. 'JOIN pg_indexes ON pg_class.relname = pg_indexes.indexname ' .
  193. 'WHERE indrelid = (SELECT oid FROM pg_class WHERE relname = \'%s\') ' .
  194. 'AND indisprimary = false AND indisunique = false ' .
  195. 'ORDER BY indrelid, indexrelid',
  196. $table
  197. );
  198. return $this->fetchQueryData($sql);
  199. }
  200. /**
  201. * Column names from the foreign table can be resolved with a call to getTableColumnNames()
  202. * @param string $table
  203. * @param $constraint_name
  204. * @return array array of rows with keys: fkey_name, table_name, table_id, col_names (array of strings)
  205. * @throws PEAR_Exception
  206. */
  207. public function getForeignKeyInfo($table, $constraint_name)
  208. {
  209. // In a sane world, it'd be easier to query the column names directly.
  210. // But it's pretty hard to work with arrays such as col_indexes in direct SQL here.
  211. $query = 'SELECT ' .
  212. '(SELECT relname FROM pg_class WHERE oid=confrelid) AS table_name, ' .
  213. 'confrelid AS table_id, ' .
  214. '(SELECT indkey FROM pg_index WHERE indexrelid=conindid) AS col_indexes ' .
  215. 'FROM pg_constraint ' .
  216. 'WHERE conrelid=(SELECT oid FROM pg_class WHERE relname=\'%s\') ' .
  217. 'AND conname=\'%s\' ' .
  218. 'AND contype=\'f\'';
  219. $sql = sprintf($query, $table, $constraint_name);
  220. $data = $this->fetchQueryData($sql);
  221. if (count($data) < 1) {
  222. throw new Exception("Could not find foreign key " . $constraint_name . " on table " . $table);
  223. }
  224. $row = $data[0];
  225. return [
  226. 'table_name' => $row['table_name'],
  227. 'col_names' => $this->getTableColumnNames($row['table_id'], $row['col_indexes'])
  228. ];
  229. }
  230. /**
  231. *
  232. * @param int $table_id
  233. * @param array $col_indexes
  234. * @return array of strings
  235. * @throws PEAR_Exception
  236. */
  237. public function getTableColumnNames($table_id, $col_indexes)
  238. {
  239. $indexes = array_map('intval', explode(' ', $col_indexes));
  240. $query = 'SELECT attnum AS col_index, attname AS col_name ' .
  241. 'FROM pg_attribute where attrelid=%d ' .
  242. 'AND attnum IN (%s)';
  243. $sql = sprintf($query, $table_id, implode(',', $indexes));
  244. $data = $this->fetchQueryData($sql);
  245. $byId = [];
  246. foreach ($data as $row) {
  247. $byId[$row['col_index']] = $row['col_name'];
  248. }
  249. $out = [];
  250. foreach ($indexes as $id) {
  251. $out[] = $byId[$id];
  252. }
  253. return $out;
  254. }
  255. /**
  256. * Translate the (mostly) mysql-ish column types into somethings more standard
  257. * @param string column type
  258. *
  259. * @return string postgres happy column type
  260. */
  261. private function _columnTypeTranslation($type)
  262. {
  263. $map = [
  264. 'datetime' => 'timestamp',
  265. ];
  266. if (!empty($map[$type])) {
  267. return $map[$type];
  268. }
  269. return $type;
  270. }
  271. /**
  272. * Return the proper SQL for creating or
  273. * altering a column.
  274. *
  275. * Appropriate for use in CREATE TABLE or
  276. * ALTER TABLE statements.
  277. *
  278. * @param string $name column name to create
  279. * @param array $cd column to create
  280. *
  281. * @return string correct SQL for that column
  282. */
  283. public function columnSql(string $name, array $cd)
  284. {
  285. $line = [];
  286. $line[] = parent::columnSql($name, $cd);
  287. /*
  288. if ($table['foreign keys'][$name]) {
  289. foreach ($table['foreign keys'][$name] as $foreignTable => $foreignColumn) {
  290. $line[] = 'references';
  291. $line[] = $this->quoteIdentifier($foreignTable);
  292. $line[] = '(' . $this->quoteIdentifier($foreignColumn) . ')';
  293. }
  294. }
  295. */
  296. // This'll have been added from our transform of 'serial' type
  297. if (!empty($cd['auto_increment'])) {
  298. $line[] = 'GENERATED BY DEFAULT AS IDENTITY';
  299. } elseif (!empty($cd['enum'])) {
  300. foreach ($cd['enum'] as &$val) {
  301. $vals[] = "'" . $val . "'";
  302. }
  303. $line[] = 'CHECK (' . $name . ' IN (' . implode(',', $vals) . '))';
  304. }
  305. return implode(' ', $line);
  306. }
  307. /**
  308. * Append phrase(s) to an array of partial ALTER TABLE chunks in order
  309. * to alter the given column from its old state to a new one.
  310. *
  311. * @param array $phrase
  312. * @param string $columnName
  313. * @param array $old previous column definition as found in DB
  314. * @param array $cd current column definition
  315. */
  316. public function appendAlterModifyColumn(array &$phrase, $columnName, array $old, array $cd)
  317. {
  318. $prefix = 'ALTER COLUMN ' . $this->quoteIdentifier($columnName) . ' ';
  319. $oldType = $this->typeAndSize($columnName, $old);
  320. $newType = $this->typeAndSize($columnName, $cd);
  321. if ($oldType != $newType) {
  322. $phrase[] = $prefix . 'TYPE ' . $newType;
  323. }
  324. if (!empty($old['not null']) && empty($cd['not null'])) {
  325. $phrase[] = $prefix . 'DROP NOT NULL';
  326. } elseif (empty($old['not null']) && !empty($cd['not null'])) {
  327. $phrase[] = $prefix . 'SET NOT NULL';
  328. }
  329. if (isset($old['default']) && !isset($cd['default'])) {
  330. $phrase[] = $prefix . 'DROP DEFAULT';
  331. } elseif (!isset($old['default']) && isset($cd['default'])) {
  332. $phrase[] = $prefix . 'SET DEFAULT ' . $this->quoteDefaultValue($cd);
  333. }
  334. }
  335. public function appendAlterDropPrimary(array &$phrase, string $tableName)
  336. {
  337. $phrase[] = 'DROP CONSTRAINT ' . $this->quoteIdentifier($tableName . '_pkey');
  338. }
  339. /**
  340. * Append an SQL statement with an index definition for a full-text search
  341. * index over one or more columns on a table.
  342. *
  343. * @param array $statements
  344. * @param string $table
  345. * @param string $name
  346. * @param array $def
  347. */
  348. public function appendCreateFulltextIndex(array &$statements, $table, $name, array $def)
  349. {
  350. $statements[] = "CREATE INDEX $name ON $table USING gin " . $this->buildFulltextIndexList($table, $def);
  351. }
  352. /**
  353. * Append an SQL statement to drop an index from a table.
  354. * Note that in PostgreSQL, index names are DB-unique.
  355. *
  356. * @param array $statements
  357. * @param string $table
  358. * @param string $name
  359. */
  360. public function appendDropIndex(array &$statements, $table, $name)
  361. {
  362. $statements[] = "DROP INDEX $name";
  363. }
  364. /**
  365. * Quote a db/table/column identifier if necessary.
  366. *
  367. * @param string $name
  368. * @return string
  369. */
  370. public function quoteIdentifier($name)
  371. {
  372. return $this->conn->quoteIdentifier($name);
  373. }
  374. public function mapType($column)
  375. {
  376. $map = [
  377. 'serial' => 'int',
  378. 'bool' => 'boolean',
  379. 'numeric' => 'decimal',
  380. 'datetime' => 'timestamp',
  381. 'blob' => 'bytea',
  382. 'enum' => 'text',
  383. ];
  384. $type = $column['type'];
  385. if (isset($map[$type])) {
  386. $type = $map[$type];
  387. }
  388. if ($type == 'int' && !empty($column['size'])) {
  389. $size = $column['size'];
  390. if (in_array($size, ['small', 'big'])) {
  391. $type = $size . $type;
  392. } elseif ($size == 'tiny') {
  393. $type = 'small' . $type;
  394. }
  395. }
  396. return $type;
  397. }
  398. /**
  399. * Filter the given table definition array to match features available
  400. * in this database.
  401. *
  402. * This lets us strip out unsupported things like comments, foreign keys,
  403. * or type variants that we wouldn't get back from getTableDef().
  404. *
  405. * @param array $tableDef
  406. * @return array
  407. */
  408. public function filterDef(array $tableDef)
  409. {
  410. foreach ($tableDef['fields'] as $name => &$col) {
  411. // No convenient support for field descriptions
  412. unset($col['description']);
  413. switch ($col['type']) {
  414. case 'serial':
  415. $col['type'] = 'int';
  416. $col['auto_increment'] = true;
  417. break;
  418. case 'datetime':
  419. // '0000-00-00' is a permitted special value (zero-date) in
  420. // MariaDB, replace it with epoch in PostgreSQL
  421. if (($col['default'] ?? null) == '0000-00-00 00:00:00') {
  422. $col['default'] = '1970-01-01 00:00:00';
  423. }
  424. break;
  425. case 'timestamp':
  426. // In MariaDB: If the column does not permit NULL values,
  427. // assigning NULL (or not referencing the column at all
  428. // when inserting) will set the column to CURRENT_TIMESTAMP
  429. if ($col['not null'] && !isset($col['default'])) {
  430. $col['default'] = 'CURRENT_TIMESTAMP';
  431. }
  432. break;
  433. }
  434. $col['type'] = $this->mapType($col);
  435. unset($col['size']);
  436. }
  437. if (!empty($tableDef['primary key'])) {
  438. $tableDef['primary key'] = $this->filterKeyDef($tableDef['primary key']);
  439. }
  440. if (!empty($tableDef['unique keys'])) {
  441. foreach ($tableDef['unique keys'] as $i => $def) {
  442. $tableDef['unique keys'][$i] = $this->filterKeyDef($def);
  443. }
  444. }
  445. return $tableDef;
  446. }
  447. /**
  448. * Filter the given key/index definition to match features available
  449. * in this database.
  450. *
  451. * @param array $def
  452. * @return array
  453. */
  454. public function filterKeyDef(array $def)
  455. {
  456. // PostgreSQL doesn't like prefix lengths specified on keys...?
  457. foreach ($def as $i => $item) {
  458. if (is_array($item)) {
  459. $def[$i] = $item[0];
  460. }
  461. }
  462. return $def;
  463. }
  464. }