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