Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
9.09% covered (danger)
9.09%
10 / 110
0.00% covered (danger)
0.00%
0 / 20
CRAP
0.00% covered (danger)
0.00%
0 / 1
PostgresPlatform
9.09% covered (danger)
9.09%
10 / 110
0.00% covered (danger)
0.00%
0 / 20
2163.44
0.00% covered (danger)
0.00%
0 / 1
 limitResult
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 buildConcat
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 timestamp
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 buildStringCast
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 implicitOrderby
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getCoreSchema
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 setCoreSchema
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 selectSQLText
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
182
 makeSelectOptions
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
56
 getDatabaseAndTableIdentifier
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
5.03
 relationSchemaQualifier
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 buildGroupConcatField
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 makeInsertLists
0.00% covered (danger)
0.00%
0 / 29
0.00% covered (danger)
0.00%
0 / 1
90
 makeInsertNonConflictingVerbAndOptions
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 makeUpdateOptionsArray
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 isTransactableQuery
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 lockSQLText
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 lockIsFreeSQLText
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 unlockSQLText
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 bigintFromLockName
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20namespace Wikimedia\Rdbms\Platform;
21
22use Wikimedia\Rdbms\DBLanguageError;
23use Wikimedia\Rdbms\Query;
24use Wikimedia\Timestamp\ConvertibleTimestamp;
25
26/**
27 * @since 1.39
28 * @see ISQLPlatform
29 */
30class PostgresPlatform extends SQLPlatform {
31    /** @var string */
32    private $coreSchema;
33
34    public function limitResult( $sql, $limit, $offset = false ) {
35        return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
36    }
37
38    public function buildConcat( $stringList ) {
39        return implode( ' || ', $stringList );
40    }
41
42    public function timestamp( $ts = 0 ) {
43        $ct = new ConvertibleTimestamp( $ts );
44
45        return $ct->getTimestamp( TS_POSTGRES );
46    }
47
48    public function buildStringCast( $field ) {
49        return $field . '::text';
50    }
51
52    public function implicitOrderby() {
53        return false;
54    }
55
56    public function getCoreSchema(): string {
57        return $this->coreSchema;
58    }
59
60    public function setCoreSchema( string $coreSchema ): void {
61        $this->coreSchema = $coreSchema;
62    }
63
64    public function selectSQLText(
65        $tables, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
66    ) {
67        if ( is_string( $options ) ) {
68            $options = [ $options ];
69        }
70
71        // Change the FOR UPDATE option as necessary based on the join conditions. Then pass
72        // to the parent function to get the actual SQL text.
73        // In Postgres when using FOR UPDATE, only the main table and tables that are inner joined
74        // can be locked. That means tables in an outer join cannot be FOR UPDATE locked. Trying to
75        // do so causes a DB error. This wrapper checks which tables can be locked and adjusts it
76        // accordingly.
77        // MySQL uses "ORDER BY NULL" as an optimization hint, but that is illegal in PostgreSQL.
78        if ( is_array( $options ) ) {
79            $forUpdateKey = array_search( 'FOR UPDATE', $options, true );
80            if ( $forUpdateKey !== false && $join_conds ) {
81                unset( $options[$forUpdateKey] );
82                $options['FOR UPDATE'] = [];
83
84                $toCheck = $tables;
85                reset( $toCheck );
86                while ( $toCheck ) {
87                    $alias = key( $toCheck );
88                    $table = $toCheck[$alias];
89                    unset( $toCheck[$alias] );
90
91                    if ( !is_string( $alias ) ) {
92                        // No alias? Set it equal to the table name
93                        $alias = $table;
94                    }
95
96                    if ( !isset( $join_conds[$alias] ) ||
97                        !preg_match( '/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_conds[$alias][0] )
98                    ) {
99                        if ( is_array( $table ) ) {
100                            // It's a parenthesized group, process all the tables inside the group.
101                            $toCheck = array_merge( $toCheck, $table );
102                        } else {
103                            // If an alias is declared, then any FOR UPDATE FOR must use it
104                            $options['FOR UPDATE'][] = $alias;
105                        }
106                    }
107                }
108            }
109
110            if (
111                isset( $options['ORDER BY'] ) &&
112                ( $options['ORDER BY'] == 'NULL' || $options['ORDER BY'] == [ 'NULL' ] )
113            ) {
114                unset( $options['ORDER BY'] );
115            }
116        }
117
118        return parent::selectSQLText( $tables, $vars, $conds, $fname, $options, $join_conds );
119    }
120
121    protected function makeSelectOptions( array $options ) {
122        $preLimitTail = $postLimitTail = '';
123        $startOpts = '';
124
125        $noKeyOptions = [];
126        foreach ( $options as $key => $option ) {
127            if ( is_numeric( $key ) ) {
128                $noKeyOptions[$option] = true;
129            }
130        }
131
132        $preLimitTail .= $this->makeGroupByWithHaving( $options );
133
134        $preLimitTail .= $this->makeOrderBy( $options );
135
136        if ( isset( $options['FOR UPDATE'] ) ) {
137            $postLimitTail .= ' FOR UPDATE OF ' . implode(
138                ', ',
139                array_map( [ $this, 'addIdentifierQuotes' ], $options['FOR UPDATE'] )
140            );
141        } elseif ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
142            $postLimitTail .= ' FOR UPDATE';
143        }
144
145        if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
146            $startOpts .= 'DISTINCT';
147        }
148
149        return [ $startOpts, $preLimitTail, $postLimitTail ];
150    }
151
152    public function getDatabaseAndTableIdentifier( string $table ) {
153        $components = $this->qualifiedTableComponents( $table );
154        switch ( count( $components ) ) {
155            case 1:
156                return [ $this->currentDomain->getDatabase(), $components[0] ];
157            case 2:
158                return [ $this->currentDomain->getDatabase(), $components[1] ];
159            case 3:
160                return [ $components[0], $components[2] ];
161            default:
162                throw new DBLanguageError( 'Too many table components' );
163        }
164    }
165
166    protected function relationSchemaQualifier() {
167        if ( $this->coreSchema === $this->currentDomain->getSchema() ) {
168            // The schema to be used is now in the search path; no need for explicit qualification
169            return '';
170        }
171
172        return parent::relationSchemaQualifier();
173    }
174
175    public function buildGroupConcatField(
176        $delim, $tables, $field, $conds = '', $join_conds = []
177    ) {
178        $fld = "array_to_string(array_agg($field)," . $this->quoter->addQuotes( $delim ) . ')';
179
180        return '(' . $this->selectSQLText( $tables, $fld, $conds, static::CALLER_SUBQUERY, [], $join_conds ) . ')';
181    }
182
183    public function makeInsertLists( array $rows, $aliasPrefix = '', array $typeByColumn = [] ) {
184        $firstRow = $rows[0];
185        if ( !is_array( $firstRow ) || !$firstRow ) {
186            throw new DBLanguageError( 'Got an empty row list or empty row' );
187        }
188        // List of columns that define the value tuple ordering
189        $tupleColumns = array_keys( $firstRow );
190
191        $valueTuples = [];
192        foreach ( $rows as $row ) {
193            $rowColumns = array_keys( $row );
194            // VALUES(...) requires a uniform correspondence of (column => value)
195            if ( $rowColumns !== $tupleColumns ) {
196                throw new DBLanguageError(
197                    'Got row columns (' . implode( ', ', $rowColumns ) . ') ' .
198                    'instead of expected (' . implode( ', ', $tupleColumns ) . ')'
199                );
200            }
201            // Make the value tuple that defines this row
202            $typedRowValues = [];
203            foreach ( $row as $column => $value ) {
204                $type = $typeByColumn[$column] ?? null;
205                if ( $value === null ) {
206                    $typedRowValues[] = 'NULL';
207                } elseif ( $type !== null ) {
208                    $typedRowValues[] = $this->quoter->addQuotes( $value ) . '::' . $type;
209                } else {
210                    $typedRowValues[] = $this->quoter->addQuotes( $value );
211                }
212            }
213            $valueTuples[] = '(' . implode( ',', $typedRowValues ) . ')';
214        }
215
216        $magicAliasFields = [];
217        foreach ( $tupleColumns as $column ) {
218            $magicAliasFields[] = $aliasPrefix . $column;
219        }
220
221        return [
222            $this->makeList( $tupleColumns, self::LIST_NAMES ),
223            implode( ',', $valueTuples ),
224            $this->makeList( $magicAliasFields, self::LIST_NAMES )
225        ];
226    }
227
228    protected function makeInsertNonConflictingVerbAndOptions() {
229        return [ 'INSERT INTO', 'ON CONFLICT DO NOTHING' ];
230    }
231
232    protected function makeUpdateOptionsArray( $options ) {
233        $options = $this->normalizeOptions( $options );
234        // PostgreSQL doesn't support anything like "ignore" for UPDATE.
235        $options = array_diff( $options, [ 'IGNORE' ] );
236
237        return parent::makeUpdateOptionsArray( $options );
238    }
239
240    public function isTransactableQuery( Query $sql ) {
241        return parent::isTransactableQuery( $sql ) &&
242            !preg_match( '/^SELECT\s+pg_(try_|)advisory_\w+\(/', $sql->getSQL() );
243    }
244
245    public function lockSQLText( $lockName, $timeout ) {
246        // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
247        $key = $this->quoter->addQuotes( $this->bigintFromLockName( $lockName ) );
248        return "SELECT (CASE WHEN pg_try_advisory_lock($key" .
249            "THEN EXTRACT(epoch from clock_timestamp()) " .
250            "ELSE NULL " .
251            "END) AS acquired";
252    }
253
254    public function lockIsFreeSQLText( $lockName ) {
255        // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
256        $key = $this->quoter->addQuotes( $this->bigintFromLockName( $lockName ) );
257        return "SELECT (CASE(pg_try_advisory_lock($key))
258            WHEN FALSE THEN FALSE ELSE pg_advisory_unlock($key) END) AS unlocked";
259    }
260
261    public function unlockSQLText( $lockName ) {
262        // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
263        $key = $this->quoter->addQuotes( $this->bigintFromLockName( $lockName ) );
264        return "SELECT pg_advisory_unlock($key) AS released";
265    }
266
267    /**
268     * @param string $lockName
269     * @return string Integer
270     */
271    private function bigintFromLockName( $lockName ) {
272        return \Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
273    }
274}