]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/pgsqlschema.php
Start reworking things to build create table stuff (can view via dumpschema.php ...
[quix0rs-gnu-social.git] / lib / pgsqlschema.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Database schema utilities
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  Database
23  * @package   StatusNet
24  * @author    Evan Prodromou <evan@status.net>
25  * @copyright 2009 StatusNet, Inc.
26  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27  * @link      http://status.net/
28  */
29
30 if (!defined('STATUSNET')) {
31     exit(1);
32 }
33
34 /**
35  * Class representing the database schema
36  *
37  * A class representing the database schema. Can be used to
38  * manipulate the schema -- especially for plugins and upgrade
39  * utilities.
40  *
41  * @category Database
42  * @package  StatusNet
43  * @author   Evan Prodromou <evan@status.net>
44  * @author   Brenda Wallace <shiny@cpan.org>
45  * @author   Brion Vibber <brion@status.net>
46  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
47  * @link     http://status.net/
48  */
49
50 class PgsqlSchema extends Schema
51 {
52
53     /**
54      * Returns a table definition array for the table
55      * in the schema with the given name.
56      *
57      * Throws an exception if the table is not found.
58      *
59      * @param string $table Name of the table to get
60      *
61      * @return array tabledef for that table.
62      */
63
64     public function getTableDef($table)
65     {
66         $def = array();
67         $hasKeys = false;
68
69         // Pull column data from INFORMATION_SCHEMA
70         $columns = $this->fetchMetaInfo($table, 'columns', 'ordinal_position');
71         if (count($columns) == 0) {
72             throw new SchemaTableMissingException("No such table: $table");
73         }
74
75         // We'll need to match up fields by ordinal reference
76         $orderedFields = array();
77
78         foreach ($columns as $row) {
79
80             $name = $row['column_name'];
81             $orderedFields[$row['ordinal_position']] = $name;
82
83             $field = array();
84
85             // ??
86             list($type, $size) = $this->reverseMapType($row['udt_name']);
87             $field['type'] = $type;
88             if ($size !== null) {
89                 $field['size'] = $size;
90             }
91
92             if ($type == 'char' || $type == 'varchar') {
93                 if ($row['character_maximum_length'] !== null) {
94                     $field['length'] = intval($row['character_maximum_length']);
95                 }
96             }
97             if ($type == 'numeric') {
98                 // Other int types may report these values, but they're irrelevant.
99                 // Just ignore them!
100                 if ($row['numeric_precision'] !== null) {
101                     $field['precision'] = intval($row['numeric_precision']);
102                 }
103                 if ($row['numeric_scale'] !== null) {
104                     $field['scale'] = intval($row['numeric_scale']);
105                 }
106             }
107             if ($row['is_nullable'] == 'NO') {
108                 $field['not null'] = true;
109             }
110             if ($row['column_default'] !== null) {
111                 $field['default'] = $row['column_default'];
112                 if ($this->isNumericType($type)) {
113                     $field['default'] = intval($field['default']);
114                 }
115             }
116
117             $def['fields'][$name] = $field;
118         }
119
120         // Pulling index info from pg_class & pg_index
121         // This can give us primary & unique key info, but not foreign key constraints
122         // so we exclude them and pick them up later.
123         $indexInfo = $this->getIndexInfo($table);
124         foreach ($indexInfo as $row) {
125             $keyName = $row['key_name'];
126
127             // Dig the column references out!
128             //
129             // These are inconvenient arrays with partial references to the
130             // pg_att table, but since we've already fetched up the column
131             // info on the current table, we can look those up locally.
132             $cols = array();
133             $colPositions = explode(' ', $row['indkey']);
134             foreach ($colPositions as $ord) {
135                 if ($ord == 0) {
136                     $cols[] = 'FUNCTION'; // @fixme
137                 } else {
138                     $cols[] = $orderedFields[$ord];
139                 }
140             }
141
142             $def['indexes'][$keyName] = $cols;
143         }
144
145         // Pull constraint data from INFORMATION_SCHEMA:
146         // Primary key, unique keys, foreign keys
147         $keyColumns = $this->fetchMetaInfo($table, 'key_column_usage', 'constraint_name,ordinal_position');
148         $keys = array();
149
150         foreach ($keyColumns as $row) {
151             $keyName = $row['constraint_name'];
152             $keyCol = $row['column_name'];
153             if (!isset($keys[$keyName])) {
154                 $keys[$keyName] = array();
155             }
156             $keys[$keyName][] = $keyCol;
157         }
158
159         foreach ($keys as $keyName => $cols) {
160             // name hack -- is this reliable?
161             if ($keyName == "{$table}_pkey") {
162                 $def['primary key'] = $cols;
163             } else if (preg_match("/^{$table}_(.*)_fkey$/", $keyName, $matches)) {
164                 $fkey = $this->getForeignKeyInfo($table, $keyName);
165                 $colMap = array_combine($cols, $fkey['col_names']);
166                 $def['foreign keys'][$keyName] = array($fkey['table_name'], $colMap);
167             } else {
168                 $def['unique keys'][$keyName] = $cols;
169             }
170         }
171         return $def;
172     }
173
174     /**
175      * Pull some INFORMATION.SCHEMA data for the given table.
176      *
177      * @param string $table
178      * @return array of arrays
179      */
180     function fetchMetaInfo($table, $infoTable, $orderBy=null)
181     {
182         $query = "SELECT * FROM information_schema.%s " .
183                  "WHERE table_name='%s'";
184         $sql = sprintf($query, $infoTable, $table);
185         if ($orderBy) {
186             $sql .= ' ORDER BY ' . $orderBy;
187         }
188         return $this->fetchQueryData($sql);
189     }
190
191     /**
192      * Pull some PG-specific index info
193      * @param string $table
194      * @return array of arrays
195      */
196     function getIndexInfo($table)
197     {
198         $query = 'SELECT ' .
199                  '(SELECT relname FROM pg_class WHERE oid=indexrelid) AS key_name, ' .
200                  '* FROM pg_index ' .
201                  'WHERE indrelid=(SELECT oid FROM pg_class WHERE relname=\'%s\') ' .
202                  'AND indisprimary=\'f\' AND indisunique=\'f\' ' .
203                  'ORDER BY indrelid, indexrelid';
204         $sql = sprintf($query, $table);
205         return $this->fetchQueryData($sql);
206     }
207
208     /**
209      * Column names from the foreign table can be resolved with a call to getTableColumnNames()
210      * @param <type> $table
211      * @return array array of rows with keys: fkey_name, table_name, table_id, col_names (array of strings)
212      */
213     function getForeignKeyInfo($table, $constraint_name)
214     {
215         // In a sane world, it'd be easier to query the column names directly.
216         // But it's pretty hard to work with arrays such as col_indexes in direct SQL here.
217         $query = 'SELECT ' .
218                  '(SELECT relname FROM pg_class WHERE oid=confrelid) AS table_name, ' .
219                  'confrelid AS table_id, ' .
220                  '(SELECT indkey FROM pg_index WHERE indexrelid=conindid) AS col_indexes ' .
221                  'FROM pg_constraint ' .
222                  'WHERE conrelid=(SELECT oid FROM pg_class WHERE relname=\'%s\') ' .
223                  'AND conname=\'%s\' ' .
224                  'AND contype=\'f\'';
225         $sql = sprintf($query, $table, $constraint_name);
226         $data = $this->fetchQueryData($sql);
227         if (count($data) < 1) {
228             throw new Exception("Could not find foreign key " . $constraint_name . " on table " . $table);
229         }
230
231         $row = $data[0];
232         return array(
233             'table_name' => $row['table_name'],
234             'col_names' => $this->getTableColumnNames($row['table_id'], $row['col_indexes'])
235         );
236     }
237
238     /**
239      *
240      * @param int $table_id
241      * @param array $col_indexes
242      * @return array of strings
243      */
244     function getTableColumnNames($table_id, $col_indexes)
245     {
246         $indexes = array_map('intval', explode(' ', $col_indexes));
247         $query = 'SELECT attnum AS col_index, attname AS col_name ' .
248                  'FROM pg_attribute where attrelid=%d ' .
249                  'AND attnum IN (%s)';
250         $sql = sprintf($query, $table_id, implode(',', $indexes));
251         $data = $this->fetchQueryData($sql);
252
253         $byId = array();
254         foreach ($data as $row) {
255             $byId[$row['col_index']] = $row['col_name'];
256         }
257
258         $out = array();
259         foreach ($indexes as $id) {
260             $out[] = $byId[$id];
261         }
262         return $out;
263     }
264
265     /**
266      * Translate the (mostly) mysql-ish column types into somethings more standard
267      * @param string column type
268      *
269      * @return string postgres happy column type
270      */
271     private function _columnTypeTranslation($type) {
272       $map = array(
273       'datetime' => 'timestamp',
274       );
275       if(!empty($map[$type])) {
276         return $map[$type];
277       }
278       return $type;
279     }
280
281     /**
282      * Return the proper SQL for creating or
283      * altering a column.
284      *
285      * Appropriate for use in CREATE TABLE or
286      * ALTER TABLE statements.
287      *
288      * @param array $cd column to create
289      *
290      * @return string correct SQL for that column
291      */
292
293     function columnSql(array $cd)
294     {
295         $line = array();
296         $line[] = parent::columnSql($cd);
297
298         /*
299         if ($table['foreign keys'][$name]) {
300             foreach ($table['foreign keys'][$name] as $foreignTable => $foreignColumn) {
301                 $line[] = 'references';
302                 $line[] = $this->quoteIdentifier($foreignTable);
303                 $line[] = '(' . $this->quoteIdentifier($foreignColumn) . ')';
304             }
305         }
306         */
307
308         return implode(' ', $line);
309     }
310
311     /**
312      * Append phrase(s) to an array of partial ALTER TABLE chunks in order
313      * to alter the given column from its old state to a new one.
314      *
315      * @param array $phrase
316      * @param string $columnName
317      * @param array $old previous column definition as found in DB
318      * @param array $cd current column definition
319      */
320     function appendAlterModifyColumn(array &$phrase, $columnName, array $old, array $cd)
321     {
322         $prefix = 'ALTER COLUMN ' . $this->quoteIdentifier($columnName) . ' ';
323
324         $oldType = $this->mapType($old);
325         $newType = $this->mapType($cd);
326         if ($oldType != $newType) {
327             $phrase[] = $prefix . 'TYPE ' . $newType;
328         }
329
330         if (!empty($old['not null']) && empty($cd['not null'])) {
331             $phrase[] = $prefix . 'DROP NOT NULL';
332         } else if (empty($old['not null']) && !empty($cd['not null'])) {
333             $phrase[] = $prefix . 'SET NOT NULL';
334         }
335
336         if (isset($old['default']) && !isset($cd['default'])) {
337             $phrase[] = $prefix . 'DROP DEFAULT';
338         } else if (!isset($old['default']) && isset($cd['default'])) {
339             $phrase[] = $prefix . 'SET DEFAULT ' . $this->quoteDefaultValue($cd);
340         }
341     }
342
343     /**
344      * Quote a db/table/column identifier if necessary.
345      *
346      * @param string $name
347      * @return string
348      */
349     function quoteIdentifier($name)
350     {
351         return '"' . $name . '"';
352     }
353
354     function mapType($column)
355     {
356         $map = array('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.
357                      'numeric' => 'decimal',
358                      'datetime' => 'timestamp',
359                      'blob' => 'bytea');
360
361         $type = $column['type'];
362         if (isset($map[$type])) {
363             $type = $map[$type];
364         }
365
366         if (!empty($column['size'])) {
367             $size = $column['size'];
368             if ($type == 'integer' &&
369                        in_array($size, array('small', 'big'))) {
370                 $type = $size . 'int';
371             }
372         }
373
374         return $type;
375     }
376
377     // @fixme need name... :P
378     function typeAndSize($column)
379     {
380         if ($column['type'] == 'enum') {
381             $vals = array_map(array($this, 'quote'), $column['enum']);
382             return "text check ($name in " . implode(',', $vals) . ')';
383         } else {
384             return parent::typeAndSize($column);
385         }
386     }
387
388     /**
389      * Map a native type back to an independent type + size
390      *
391      * @param string $type
392      * @return array ($type, $size) -- $size may be null
393      */
394     protected function reverseMapType($type)
395     {
396         $type = strtolower($type);
397         $map = array(
398             'int4' => array('int', null),
399             'int8' => array('int', 'big'),
400             'bytea' => array('blob', null),
401         );
402         if (isset($map[$type])) {
403             return $map[$type];
404         } else {
405             return array($type, null);
406         }
407     }
408
409 }