Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 666
0.00% covered (danger)
0.00%
0 / 26
CRAP
0.00% covered (danger)
0.00%
0 / 1
PostgresUpdater
0.00% covered (danger)
0.00%
0 / 666
0.00% covered (danger)
0.00%
0 / 26
8010
0.00% covered (danger)
0.00%
0 / 1
 getCoreUpdateList
0.00% covered (danger)
0.00%
0 / 372
0.00% covered (danger)
0.00%
0 / 1
2
 describeTable
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
12
 describeIndex
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
42
 fkeyDeltype
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
6
 ruleDef
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
6
 addSequence
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 dropSequence
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 renameSequence
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 setSequenceOwner
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 renameTable
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 renameIndex
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
42
 dropPgField
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 addPgField
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 changeField
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
42
 changeFieldPurgeTable
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
30
 setDefault
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 dropDefault
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 changeNullableField
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
42
 addPgIndex
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 addPgExtIndex
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 dropFkey
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
 changeFkeyDeferrable
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
30
 dropPgIndex
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 checkIndex
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
 changePrimaryKey
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
12
 dropConstraint
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
1<?php
2/**
3 * PostgreSQL-specific updater.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Installer
22 */
23
24namespace MediaWiki\Installer;
25
26use FixInconsistentRedirects;
27use MigrateExternallinks;
28use MigrateRevisionActorTemp;
29use MigrateRevisionCommentTemp;
30use PopulateUserIsTemp;
31use UpdateRestrictions;
32use Wikimedia\Rdbms\DatabasePostgres;
33
34/**
35 * Class for handling updates to Postgres databases.
36 *
37 * @ingroup Installer
38 * @since 1.17
39 */
40class PostgresUpdater extends DatabaseUpdater {
41
42    /**
43     * @var DatabasePostgres
44     */
45    protected $db;
46
47    /**
48     * @return array
49     */
50    protected function getCoreUpdateList() {
51        return [
52            // Exception to the sequential updates. Renaming pagecontent and mwuser.
53            // Introduced in 1.36.
54            [ 'renameTable', 'pagecontent', 'text' ],
55            // Introduced in 1.37.
56            [ 'renameTable', 'mwuser', 'user' ],
57
58            // 1.36
59            [ 'setDefault', 'bot_passwords', 'bp_token', '' ],
60            [ 'changeField', 'comment', 'comment_id', 'BIGINT', '' ],
61            [ 'changeField', 'slots', 'slot_revision_id', 'BIGINT', '' ],
62            [ 'changeField', 'slots', 'slot_content_id', 'BIGINT', '' ],
63            [ 'changeField', 'slots', 'slot_origin', 'BIGINT', '' ],
64            [ 'changeField', 'site_stats', 'ss_total_edits', 'BIGINT', '' ],
65            [ 'changeField', 'site_stats', 'ss_good_articles', 'BIGINT', '' ],
66            [ 'changeField', 'site_stats', 'ss_total_pages', 'BIGINT', '' ],
67            [ 'changeField', 'site_stats', 'ss_users', 'BIGINT', '' ],
68            [ 'changeField', 'site_stats', 'ss_active_users', 'BIGINT', '' ],
69            [ 'changeField', 'site_stats', 'ss_images', 'BIGINT', '' ],
70            [ 'dropFkey', 'user_properties', 'up_user' ],
71            [ 'addIndex', 'user_properties', 'user_properties_pkey', 'patch-user_properties-pk.sql' ],
72            [ 'changeField', 'log_search', 'ls_value', 'VARCHAR(255)', '' ],
73            [ 'changeField', 'content', 'content_id', 'BIGINT', '' ],
74            [ 'changeField', 'l10n_cache', 'lc_value', 'TEXT', '' ],
75            [ 'changeField', 'l10n_cache', 'lc_key', 'VARCHAR(255)', '' ],
76            [ 'addIndex', 'l10n_cache', 'l10n_cache_pkey', 'patch-l10n_cache-pk.sql' ],
77            [ 'addIndex', 'module_deps', 'module_deps_pkey', 'patch-module_deps-pk.sql' ],
78            [ 'changeField', 'redirect', 'rd_namespace', 'INT', 'rd_namespace::INT DEFAULT 0' ],
79            [ 'setDefault', 'redirect', 'rd_title', '' ],
80            [ 'setDefault', 'redirect', 'rd_from', 0 ],
81            [ 'dropFkey', 'redirect', 'rd_from' ],
82            [ 'changeField', 'redirect', 'rd_interwiki', 'VARCHAR(32)', '' ],
83            [ 'dropFkey', 'pagelinks', 'pl_from' ],
84            [ 'dropPgIndex', 'pagelinks', 'pagelink_unique' ],
85            [ 'dropPgIndex', 'pagelinks', 'pagelinks_title' ],
86            [ 'dropFkey', 'templatelinks', 'tl_from' ],
87            [ 'dropPgIndex', 'templatelinks', 'templatelinks_unique' ],
88            [ 'dropPgIndex', 'templatelinks', 'templatelinks_from' ],
89            [ 'dropFkey', 'imagelinks', 'il_from' ],
90            [ 'setDefault', 'imagelinks', 'il_to', '' ],
91            [ 'addPgIndex', 'imagelinks', 'il_to', '(il_to, il_from)' ],
92            [ 'addPgIndex', 'imagelinks', 'il_backlinks_namespace',
93                '(il_from_namespace, il_to, il_from)' ],
94            [ 'dropPgIndex', 'imagelinks', 'il_from' ],
95            [ 'dropFkey', 'langlinks', 'll_from' ],
96            [ 'addIndex', 'langlinks', 'langlinks_pkey', 'patch-langlinks-pk.sql' ],
97            [ 'renameIndex', 'langlinks', 'langlinks_lang_title', 'll_lang' ],
98            [ 'setDefault', 'langlinks', 'll_lang', '' ],
99            [ 'setDefault', 'langlinks', 'll_from', 0 ],
100            [ 'setDefault', 'langlinks', 'll_title', '' ],
101            [ 'changeNullableField', 'langlinks', 'll_lang', 'NOT NULL', true ],
102            [ 'changeNullableField', 'langlinks', 'll_title', 'NOT NULL', true ],
103            [ 'addIndex', 'iwlinks', 'iwlinks_pkey', 'patch-iwlinks-pk.sql' ],
104            [ 'renameIndex', 'category', 'category_title', 'cat_title' ],
105            [ 'renameIndex', 'category', 'category_pages', 'cat_pages' ],
106            [ 'dropSequence', 'watchlist_expiry', 'watchlist_expiry_we_item_seq' ],
107            [ 'changeField', 'change_tag_def', 'ctd_count', 'BIGINT', 'ctd_count::BIGINT DEFAULT 0' ],
108            [ 'dropDefault', 'change_tag_def', 'ctd_user_defined' ],
109            [ 'dropFkey', 'ipblocks_restrictions', 'ir_ipb_id' ],
110            [ 'setDefault', 'querycache', 'qc_value', 0 ],
111            [ 'changeField', 'querycache', 'qc_namespace', 'INT', 'qc_namespace::INT DEFAULT 0' ],
112            [ 'setDefault', 'querycache', 'qc_title', '' ],
113            [ 'renameIndex', 'querycache', 'querycache_type_value', 'qc_type' ],
114            [ 'renameIndex', 'querycachetwo', 'querycachetwo_type_value', 'qcc_type' ],
115            [ 'renameIndex', 'querycachetwo', 'querycachetwo_title', 'qcc_title' ],
116            [ 'renameIndex', 'querycachetwo', 'querycachetwo_titletwo', 'qcc_titletwo' ],
117            [ 'dropFkey', 'page_restrictions', 'pr_page' ],
118            [ 'addPgIndex', 'page_restrictions', 'pr_pagetype', '(pr_page, pr_type)', true ],
119            [ 'addPgIndex', 'page_restrictions', 'pr_typelevel', '(pr_type, pr_level)' ],
120            [ 'addPgIndex', 'page_restrictions', 'pr_level', '(pr_level)' ],
121            [ 'addPgIndex', 'page_restrictions', 'pr_cascade', '(pr_cascade)' ],
122            [ 'changePrimaryKey', 'page_restrictions', [ 'pr_id' ], 'page_restrictions_pk' ],
123            [ 'changeNullableField', 'page_restrictions', 'pr_page', 'NOT NULL', true ],
124            [ 'dropFkey', 'user_groups', 'ug_user' ],
125            [ 'setDefault', 'user_groups', 'ug_user', 0 ],
126            [ 'setDefault', 'user_groups', 'ug_group', '' ],
127            [ 'renameIndex', 'user_groups', 'user_groups_group', 'ug_group' ],
128            [ 'renameIndex', 'user_groups', 'user_groups_expiry', 'ug_expiry' ],
129            [ 'setDefault', 'querycache_info', 'qci_type', '' ],
130            [ 'setDefault', 'querycache_info', 'qci_timestamp', '1970-01-01 00:00:00+00' ],
131            [ 'changeNullableField', 'querycache_info', 'qci_type', 'NOT NULL', true ],
132            [ 'changeNullableField', 'querycache_info', 'qci_timestamp', 'NOT NULL', true ],
133            [ 'addIndex', 'querycache_info', 'querycache_info_pkey', 'patch-querycache_info-pk.sql' ],
134            [ 'setDefault', 'watchlist', 'wl_title', '' ],
135            [ 'changeField', 'watchlist', 'wl_namespace', 'INT', 'wl_namespace::INT DEFAULT 0' ],
136            [ 'dropFkey', 'watchlist', 'wl_user' ],
137            [ 'dropPgIndex', 'watchlist', 'wl_user_namespace_title' ],
138            [ 'addPgIndex', 'watchlist', 'namespace_title', '(wl_namespace, wl_title)' ],
139            [ 'checkIndex', 'wl_user', [
140                    [ 'wl_user', 'text_ops', 'btree', 1 ],
141                    [ 'wl_namespace', 'int4_ops', 'btree', 1 ],
142                    [ 'wl_title', 'text_ops', 'btree', 1 ],
143                ],
144                'CREATE UNIQUE INDEX "wl_user" ON "watchlist" (wl_user, wl_namespace, wl_title)'
145            ],
146            [ 'changeField', 'sites', 'site_domain', 'VARCHAR(255)', '' ],
147            [ 'renameIndex', 'sites', 'site_global_key', 'sites_global_key' ],
148            [ 'renameIndex', 'sites', 'site_type', 'sites_type' ],
149            [ 'renameIndex', 'sites', 'site_group', 'sites_group' ],
150            [ 'renameIndex', 'sites', 'site_source', 'sites_source' ],
151            [ 'renameIndex', 'sites', 'site_language', 'sites_language' ],
152            [ 'renameIndex', 'sites', 'site_protocol', 'sites_protocol' ],
153            [ 'renameIndex', 'sites', 'site_domain', 'sites_domain' ],
154            [ 'renameIndex', 'sites', 'site_forward', 'sites_forward' ],
155            [ 'dropFkey', 'user_newtalk', 'user_id' ],
156            [ 'renameIndex', 'user_newtalk', 'user_newtalk_id', 'un_user_id' ],
157            [ 'renameIndex', 'user_newtalk', 'user_newtalk_ip', 'un_user_ip' ],
158            [ 'changeField', 'interwiki', 'iw_prefix', 'VARCHAR(32)', '' ],
159            [ 'changeField', 'interwiki', 'iw_wikiid', 'VARCHAR(64)', '' ],
160            [ 'dropFkey', 'protected_titles', 'pt_user' ],
161            [ 'changeNullableField', 'protected_titles', 'pt_user', 'NOT NULL', true ],
162            [ 'changeNullableField', 'protected_titles', 'pt_expiry', 'NOT NULL', true ],
163            [ 'changeField', 'protected_titles', 'pt_reason_id', 'BIGINT', '' ],
164            [ 'dropDefault', 'protected_titles', 'pt_create_perm' ],
165            [ 'dropFkey', 'externallinks', 'el_from' ],
166            [ 'renameIndex', 'externallinks', 'externallinks_from_to', 'el_from' ],
167            [ 'renameIndex', 'externallinks', 'externallinks_index', 'el_index' ],
168            [ 'dropSequence', 'ip_changes', 'ip_changes_ipc_rev_id_seq' ],
169            [ 'changeField', 'ip_changes', 'ipc_hex', 'TEXT', "ipc_hex::TEXT DEFAULT ''" ],
170            [ 'setDefault', 'ip_changes', 'ipc_rev_id', 0 ],
171            [ 'renameIndex', 'watchlist', 'namespace_title', 'wl_namespace_title' ],
172            [ 'dropFkey', 'page_props', 'pp_page' ],
173            // page_props primary key change moved from the Schema SQL file to here in 1.36
174            [ 'changePrimaryKey', 'page_props', [ 'pp_page', 'pp_propname' ], 'page_props_pk' ],
175            [ 'setDefault', 'job', 'job_cmd', '' ],
176            [ 'changeField', 'job', 'job_namespace', 'INTEGER', '' ],
177            [ 'dropPgIndex', 'job', 'job_cmd_namespace_title' ],
178            [ 'addPgIndex', 'job', 'job_cmd', '(job_cmd, job_namespace, job_title, job_params)' ],
179            [ 'renameIndex', 'job', 'job_timestamp_idx', 'job_timestamp' ],
180            [ 'changeField', 'slot_roles', 'role_id', 'INTEGER', '' ],
181            [ 'changeField', 'content_models', 'model_id', 'INTEGER', '' ],
182            [ 'renameIndex', 'page', 'page_len_idx', 'page_len' ],
183            [ 'renameIndex', 'page', 'page_random_idx', 'page_random' ],
184            [ 'renameIndex', 'page', 'page_unique_name', 'page_name_title' ],
185            [ 'addPGIndex', 'page', 'page_redirect_namespace_len', '(page_is_redirect, page_namespace, page_len)' ],
186            [ 'dropFkey', 'categorylinks', 'cl_from' ],
187            [ 'setDefault', 'categorylinks', 'cl_from', 0 ],
188            [ 'setDefault', 'categorylinks', 'cl_to', '' ],
189            [ 'setDefault', 'categorylinks', 'cl_sortkey', '' ],
190            [ 'setDefault', 'categorylinks', 'cl_collation', '' ],
191            [ 'changeNullableField', 'categorylinks', 'cl_sortkey', 'NOT NULL', true ],
192            [ 'addIndex', 'categorylinks', 'categorylinks_pkey', 'patch-categorylinks-pk.sql' ],
193            [ 'addPgIndex', 'categorylinks', 'cl_timestamp', '(cl_to, cl_timestamp)' ],
194            [ 'addPgIndex', 'categorylinks', 'cl_collation_ext', '(cl_collation, cl_to, cl_type, cl_from)' ],
195            [ 'checkIndex', 'cl_sortkey', [
196                    [ 'cl_to', 'text_ops', 'btree', 1 ],
197                    [ 'cl_type', 'text_ops', 'btree', 1 ],
198                    [ 'cl_sortkey', 'text_ops', 'btree', 1 ],
199                    [ 'cl_from', 'text_ops', 'btree', 1 ],
200                ],
201                'CREATE INDEX cl_sortkey ON categorylinks (cl_to, cl_type, cl_sortkey, cl_from)'
202            ],
203            [ 'renameIndex', 'logging', 'logging_type_name', 'type_time' ],
204            [ 'renameIndex', 'logging', 'logging_actor_time_backwards', 'actor_time' ],
205            [ 'renameIndex', 'logging', 'logging_page_time', 'page_time' ],
206            [ 'renameIndex', 'logging', 'logging_times', 'times' ],
207            [ 'renameIndex', 'logging', 'logging_actor_type_time', 'log_actor_type_time' ],
208            [ 'renameIndex', 'logging', 'logging_page_id_time', 'log_page_id_time' ],
209            [ 'renameIndex', 'logging', 'logging_type_action', 'log_type_action' ],
210            [ 'changeNullableField', 'logging', 'log_params', 'NOT NULL', true ],
211            [ 'setDefault', 'logging', 'log_action', '' ],
212            [ 'setDefault', 'logging', 'log_type', '' ],
213            [ 'setDefault', 'logging', 'log_title', '' ],
214            [ 'setDefault', 'logging', 'log_timestamp', '1970-01-01 00:00:00+00' ],
215            [ 'changeField', 'logging', 'log_actor', 'BIGINT', '' ],
216            [ 'changeField', 'logging', 'log_comment_id', 'BIGINT', '' ],
217            [ 'changeField', 'logging', 'log_namespace', 'INT', 'log_namespace::INT DEFAULT 0' ],
218            [ 'dropPgIndex', 'logging', 'logging_actor_time' ],
219            [ 'changeField', 'uploadstash', 'us_key', 'VARCHAR(255)', '' ],
220            [ 'changeField', 'uploadstash', 'us_orig_path', 'VARCHAR(255)', '' ],
221            [ 'changeField', 'uploadstash', 'us_path', 'VARCHAR(255)', '' ],
222            [ 'changeField', 'uploadstash', 'us_source_type', 'VARCHAR(50)', '' ],
223            [ 'changeField', 'uploadstash', 'us_props', 'TEXT', '' ],
224            [ 'changeField', 'uploadstash', 'us_status', 'VARCHAR(50)', '' ],
225            [ 'changeField', 'uploadstash', 'us_sha1', 'VARCHAR(31)', '' ],
226            [ 'changeField', 'uploadstash', 'us_mime', 'VARCHAR(255)', '' ],
227            [ 'changeNullableField', 'uploadstash', 'us_key', 'NOT NULL', true ],
228            [ 'changeNullableField', 'uploadstash', 'us_user', 'NOT NULL', true ],
229            [ 'changeNullableField', 'uploadstash', 'us_orig_path', 'NOT NULL', true ],
230            [ 'changeNullableField', 'uploadstash', 'us_path', 'NOT NULL', true ],
231            [ 'changeNullableField', 'uploadstash', 'us_timestamp', 'NOT NULL', true ],
232            [ 'changeNullableField', 'uploadstash', 'us_status', 'NOT NULL', true ],
233            [ 'changeNullableField', 'uploadstash', 'us_size', 'NOT NULL', true ],
234            [ 'changeNullableField', 'uploadstash', 'us_sha1', 'NOT NULL', true ],
235            [ 'renameIndex', 'uploadstash', 'us_user_idx', 'us_user' ],
236            [ 'renameIndex', 'uploadstash', 'us_key_idx', 'us_key' ],
237            [ 'renameIndex', 'uploadstash', 'us_timestamp_idx', 'us_timestamp' ],
238            [ 'renameIndex', 'user_properties', 'user_properties_property', 'up_property' ],
239            [ 'renameIndex', 'sites', 'sites_global_key', 'site_global_key' ],
240            [ 'renameIndex', 'sites', 'sites_type', 'site_type' ],
241            [ 'renameIndex', 'sites', 'sites_group, ', 'site_group' ],
242            [ 'renameIndex', 'sites', 'sites_source', 'site_source' ],
243            [ 'renameIndex', 'sites', 'sites_language', 'site_language' ],
244            [ 'renameIndex', 'sites', 'sites_protocol', 'site_protocol' ],
245            [ 'renameIndex', 'sites', 'sites_domain', 'site_domain' ],
246            [ 'renameIndex', 'sites', 'sites_forward', 'site_forward' ],
247            [ 'renameIndex', 'logging', 'type_name', 'log_type_time' ],
248            [ 'renameIndex', 'logging', 'actor_time', 'log_actor_time' ],
249            [ 'renameIndex', 'logging', 'page_time', 'log_page_time' ],
250            [ 'renameIndex', 'logging', 'times', 'log_times' ],
251            [ 'setDefault', 'filearchive', 'fa_name', '' ],
252            [ 'setDefault', 'filearchive', 'fa_archive_name', '' ],
253            [ 'setDefault', 'filearchive', 'fa_storage_key', '' ],
254            [ 'dropFkey', 'filearchive', 'fa_deleted_user' ],
255            [ 'changeField', 'filearchive', 'fa_deleted_reason_id', 'BIGINT', '' ],
256            [ 'changeField', 'filearchive', 'fa_metadata', 'TEXT', '' ],
257            [ 'changeField', 'filearchive', 'fa_bits', 'INTEGER', '' ],
258            [ 'changeField', 'filearchive', 'fa_description_id', 'BIGINT', '' ],
259            [ 'changeField', 'filearchive', 'fa_actor', 'BIGINT', '' ],
260            [ 'renameIndex', 'filearchive', 'fa_name_time', 'fa_name' ],
261            [ 'renameIndex', 'filearchive', 'fa_dupe', 'fa_storage_group' ],
262            [ 'renameIndex', 'filearchive', 'fa_notime', 'fa_deleted_timestamp' ],
263            [ 'dropPgIndex', 'filearchive', 'fa_nouser' ],
264            [ 'addPgIndex', 'filearchive', 'fa_actor_timestamp', '(fa_actor, fa_timestamp)' ],
265            [ 'addPgIndex', 'ipblocks', 'ipb_expiry', '(ipb_expiry)' ],
266            [ 'addPgIndex', 'ipblocks', 'ipb_timestamp', '(ipb_timestamp)' ],
267            [ 'renameIndex', 'text', 'pagecontent_pkey', 'text_pkey' ],
268            [ 'changeNullableField', 'text', 'old_text', 'NOT NULL', true ],
269            [ 'changeNullableField', 'text', 'old_flags', 'NOT NULL', true ],
270            [ 'setDefault', 'oldimage', 'oi_name', '' ],
271            [ 'setDefault', 'oldimage', 'oi_archive_name', '' ],
272            [ 'setDefault', 'oldimage', 'oi_size', 0 ],
273            [ 'setDefault', 'oldimage', 'oi_width', 0 ],
274            [ 'setDefault', 'oldimage', 'oi_height', 0 ],
275            [ 'setDefault', 'oldimage', 'oi_bits', 0 ],
276            [ 'setDefault', 'oldimage', 'oi_name', '' ],
277            [ 'changeField', 'oldimage', 'oi_bits', 'INTEGER', '' ],
278            [ 'changeField', 'oldimage', 'oi_description_id', 'BIGINT', '' ],
279            [ 'changeField', 'oldimage', 'oi_actor', 'BIGINT', '' ],
280            [ 'changeField', 'oldimage', 'oi_metadata', 'TEXT', '' ],
281            [ 'dropDefault', 'oldimage', 'oi_metadata' ],
282            [ 'changeNullableField', 'oldimage', 'oi_minor_mime', 'NOT NULL', true ],
283            [ 'changeNullableField', 'oldimage', 'oi_minor_mime', 'NOT NULL', true ],
284            [ 'dropFkey', 'oldimage', 'oi_name' ],
285            [ 'addPgIndex', 'oldimage', 'oi_actor_timestamp', '(oi_actor, oi_timestamp)' ],
286            [ 'dropPgIndex', 'recentchanges', 'rc_timestamp_bot' ],
287            [ 'addPgIndex', 'recentchanges', 'rc_ns_actor', '(rc_namespace, rc_actor)' ],
288            [ 'addPgIndex', 'recentchanges', 'rc_actor', '(rc_actor, rc_timestamp)' ],
289            [ 'dropIndex', 'objectcache', 'keyname', 'patch-objectcache_keyname-pk.sql' ],
290            [ 'changeField', 'objectcache', 'value', 'TEXT', '' ],
291            [ 'changeNullableField', 'objectcache', 'value', 'NULL', true ],
292            [ 'dropFkey', 'ipblocks', 'ipb_user' ],
293            [ 'dropFkey', 'ipblocks', 'ipb_parent_block_id' ],
294            [ 'setDefault', 'ipblocks', 'ipb_user', 0 ],
295            [ 'changeNullableField', 'ipblocks', 'ipb_user', 'NOT NULL', true ],
296            [ 'changeNullableField', 'ipblocks', 'ipb_range_start', 'NOT NULL', true ],
297            [ 'changeNullableField', 'ipblocks', 'ipb_range_end', 'NOT NULL', true ],
298            [ 'changeField', 'ipblocks', 'ipb_by_actor', 'BIGINT', '' ],
299            [ 'changeField', 'ipblocks', 'ipb_reason_id', 'BIGINT', '' ],
300            [ 'renameIndex', 'archive', 'archive_name_title_timestamp', 'ar_name_title_timestamp' ],
301            [ 'dropPgIndex', 'archive', 'archive_actor' ],
302            [ 'addPgIndex', 'archive', 'ar_actor_timestamp', '(ar_actor,ar_timestamp)' ],
303            [ 'setDefault', 'image', 'img_name', '' ],
304            [ 'setDefault', 'image', 'img_size', 0 ],
305            [ 'setDefault', 'image', 'img_width', 0 ],
306            [ 'setDefault', 'image', 'img_height', 0 ],
307            [ 'setDefault', 'image', 'img_bits', 0 ],
308            [ 'changeField', 'image', 'img_bits', 'INTEGER', '' ],
309            [ 'changeField', 'image', 'img_description_id', 'BIGINT', '' ],
310            [ 'changeField', 'image', 'img_actor', 'BIGINT', '' ],
311            [ 'changeField', 'image', 'img_metadata', 'TEXT', '' ],
312            [ 'dropDefault', 'image', 'img_metadata' ],
313            [ 'changeNullableField', 'image', 'img_major_mime', 'NOT NULL', true ],
314            [ 'changeNullableField', 'image', 'img_minor_mime', 'NOT NULL', true ],
315            [ 'changeNullableField', 'image', 'img_timestamp', 'NOT NULL', true ],
316            [ 'renameIndex', 'image', 'img_size_idx', 'img_size' ],
317            [ 'renameIndex', 'image', 'img_timestamp_idx', 'img_timestamp' ],
318            [ 'addPgIndex', 'image', 'img_actor_timestamp', '(img_actor, img_timestamp)' ],
319            [ 'addPgIndex', 'image', 'img_media_mime', '(img_media_type, img_major_mime, img_minor_mime)' ],
320            [ 'renameIndex', 'site_identifiers', 'site_ids_site', 'si_site' ],
321            [ 'renameIndex', 'site_identifiers', 'site_ids_key', 'si_key' ],
322            [ 'changeField', 'recentchanges', 'rc_actor', 'BIGINT', '' ],
323            [ 'changeField', 'recentchanges', 'rc_comment_id', 'BIGINT', '' ],
324            [ 'changeField', 'recentchanges', 'rc_ip', 'TEXT', '' ],
325            [ 'changeField', 'recentchanges', 'rc_namespace', 'INTEGER', '' ],
326            [ 'setDefault', 'recentchanges', 'rc_title', '' ],
327            [ 'setDefault', 'recentchanges', 'rc_source', '' ],
328            [ 'setDefault', 'recentchanges', 'rc_ip', '' ],
329            [ 'setDefault', 'recentchanges', 'rc_namespace', 0 ],
330            [ 'setDefault', 'recentchanges', 'rc_cur_id', 0 ],
331            [ 'setDefault', 'recentchanges', 'rc_this_oldid', 0 ],
332            [ 'setDefault', 'recentchanges', 'rc_last_oldid', 0 ],
333            [ 'changeNullableField', 'recentchanges', 'rc_cur_id', 'NOT NULL', true ],
334            [ 'changeNullableField', 'recentchanges', 'rc_ip', 'NOT NULL', true ],
335            [ 'renameIndex', 'recentchanges', 'new_name_timestamp', 'rc_new_name_timestamp', false,
336                'patch-recentchanges-rc_new_name_timestamp.sql' ],
337            [ 'changeField', 'archive', 'ar_namespace', 'INTEGER', '' ],
338            [ 'setDefault', 'archive', 'ar_namespace', 0 ],
339            [ 'setDefault', 'archive', 'ar_title', '' ],
340            [ 'changeField', 'archive', 'ar_comment_id', 'BIGINT', '' ],
341            [ 'changeField', 'archive', 'ar_actor', 'BIGINT', '' ],
342            [ 'renameIndex', 'user', 'user_email_token_idx', 'user_email_token' ],
343            [ 'addPgIndex', 'user', 'user_email', '(user_email)' ],
344            [ 'addPgIndex', 'user', 'user_name', '(user_name)', true ],
345            [ 'changeField', 'page', 'page_namespace', 'INTEGER', '' ],
346            [ 'changeNullableField', 'page', 'page_touched', 'NOT NULL', true ],
347            [ 'changeField', 'page', 'page_random', 'FLOAT', '' ],
348            [ 'renameIndex', 'revision', 'revision_unique', 'rev_page_id' ],
349            [ 'renameIndex', 'revision', 'rev_timestamp_idx', 'rev_timestamp' ],
350            [ 'addPgIndex', 'revision', 'rev_page_timestamp', '(rev_page,rev_timestamp)' ],
351            [ 'changeNullableField', 'user', 'user_touched', 'NOT NULL', true ],
352
353            // 1.37
354            [ 'setDefault', 'user', 'user_name', '' ],
355            [ 'setDefault', 'user', 'user_token', '' ],
356            [ 'setDefault', 'user', 'user_real_name', '' ],
357            [ 'setDefault', 'user', 'user_email', '' ],
358            [ 'setDefault', 'user', 'user_newpassword', '' ],
359            [ 'setDefault', 'user', 'user_password', '' ],
360            [ 'changeNullableField', 'user', 'user_token', 'NOT NULL', true ],
361            [ 'changeNullableField', 'user', 'user_real_name', 'NOT NULL', true ],
362            [ 'changeNullableField', 'user', 'user_email', 'NOT NULL', true ],
363            [ 'changeNullableField', 'user', 'user_newpassword', 'NOT NULL', true ],
364            [ 'changeNullableField', 'user', 'user_password', 'NOT NULL', true ],
365            [ 'dropDefault', 'user', 'user_email' ],
366            [ 'dropDefault', 'user', 'user_newpassword' ],
367            [ 'dropDefault', 'user', 'user_password' ],
368            [ 'dropConstraint', 'user', 'user_name', 'unique' ],
369            [ 'addField', 'objectcache', 'modtoken', 'patch-objectcache-modtoken.sql' ],
370            [ 'dropFkey', 'revision', 'rev_page' ],
371            [ 'changeNullableField', 'revision', 'rev_page', 'NOT NULL', true ],
372            [ 'changeField', 'revision', 'rev_comment_id', 'BIGINT', 'rev_comment_id::BIGINT DEFAULT 0' ],
373            [ 'changeField', 'revision', 'rev_actor', 'BIGINT', 'rev_actor::BIGINT DEFAULT 0' ],
374            [ 'checkIndex', 'rev_page_id', [
375                    [ 'rev_page', 'int4_ops', 'btree', 1 ],
376                    [ 'rev_id', 'int4_ops', 'btree', 1 ],
377                ],
378                'CREATE INDEX rev_page_id ON revision (rev_page,rev_id)'
379            ],
380            [ 'addTable', 'searchindex', 'patch-searchindex-table.sql' ],
381            [ 'addPgIndex', 'oldimage', 'oi_timestamp', '(oi_timestamp)' ],
382            [ 'renameIndex', 'page', 'name_title', 'page_name_title' ],
383            [ 'renameIndex', 'change_tag', 'change_tag_rc_tag_id', 'ct_rc_tag_id' ],
384            [ 'renameIndex', 'change_tag', 'change_tag_log_tag_id', 'ct_log_tag_id' ],
385            [ 'renameIndex', 'change_tag', 'change_tag_rev_tag_id', 'ct_rev_tag_id' ],
386            [ 'renameIndex', 'change_tag', 'change_tag_tag_id_id', 'ct_tag_id_id' ],
387
388            // 1.38
389            [ 'doConvertDjvuMetadata' ],
390            [ 'dropPgField', 'page_restrictions', 'pr_user' ],
391            [ 'addTable', 'linktarget', 'patch-linktarget.sql' ],
392            [ 'dropIndex', 'revision', 'rev_page_id', 'patch-drop-rev_page_id.sql' ],
393            [ 'addField', 'templatelinks', 'tl_target_id', 'patch-templatelinks-target_id.sql' ],
394
395            // 1.39
396            [ 'addTable', 'user_autocreate_serial', 'patch-user_autocreate_serial.sql' ],
397            [ 'runMaintenance', MigrateRevisionActorTemp::class ],
398            [ 'dropTable', 'revision_actor_temp' ],
399            [ 'runMaintenance', UpdateRestrictions::class ],
400            [ 'dropPgField', 'page', 'page_restrictions' ],
401            [ 'migrateTemplatelinks' ],
402            [ 'changeNullableField', 'templatelinks', 'tl_target_id', 'NOT NULL', true ],
403            [ 'changePrimaryKey', 'templatelinks', [ 'tl_from', 'tl_target_id' ] ],
404            [ 'dropField', 'templatelinks', 'tl_title', 'patch-templatelinks-drop-tl_title.sql' ],
405
406            // 1.40
407            [ 'addField', 'externallinks', 'el_to_path', 'patch-externallinks-el_to_path.sql' ],
408
409            // 1.41
410            [ 'addField', 'user', 'user_is_temp', 'patch-user-user_is_temp.sql' ],
411            [ 'runMaintenance', MigrateRevisionCommentTemp::class ],
412            [ 'dropTable', 'revision_comment_temp' ],
413            [ 'runMaintenance', MigrateExternallinks::class ],
414            [ 'modifyField', 'externallinks', 'el_to', 'patch-externallinks-el_to_default.sql' ],
415            [ 'addField', 'pagelinks', 'pl_target_id', 'patch-pagelinks-target_id.sql' ],
416            [ 'dropField', 'externallinks', 'el_to', 'patch-externallinks-drop-el_to.sql' ],
417            [ 'runMaintenance', FixInconsistentRedirects::class ],
418            [ 'modifyField', 'image', 'img_size', 'patch-image-img_size_to_bigint.sql' ],
419            [ 'modifyField', 'filearchive', 'fa_size', 'patch-filearchive-fa_size_to_bigint.sql' ],
420            [ 'modifyField', 'oldimage', 'oi_size', 'patch-oldimage-oi_size_to_bigint.sql' ],
421            [ 'modifyField', 'uploadstash', 'us_size', 'patch-uploadstash-us_size_to_bigint.sql' ],
422
423            // 1.42
424            [ 'addField', 'user_autocreate_serial', 'uas_year', 'patch-user_autocreate_serial-uas_year.sql' ],
425            [ 'addTable', 'block_target', 'patch-block_target.sql' ],
426            [ 'dropIndex', 'categorylinks', 'cl_collation_ext', 'patch-drop-cl_collation_ext.sql' ],
427            [ 'runMaintenance', PopulateUserIsTemp::class ],
428            [ 'dropIndex', 'sites', 'site_type', 'patch-sites-drop_indexes.sql' ],
429            [ 'dropIndex', 'iwlinks', 'iwl_prefix_from_title', 'patch-iwlinks-drop-iwl_prefix_from_title.sql' ],
430
431            // 1.43
432            [ 'migratePagelinks' ],
433            [ 'dropDefault', 'revision', 'rev_actor' ],
434            [ 'dropDefault', 'revision', 'rev_comment_id' ],
435            [ 'changeField', 'revision', 'rev_id', 'BIGINT', '' ],
436            [ 'changeField', 'revision', 'rev_parent_id', 'BIGINT', '' ],
437            [ 'changeField', 'recentchanges', 'rc_id', 'BIGINT', '' ],
438            [ 'changeField', 'change_tag', 'ct_rc_id', 'BIGINT', '' ],
439            [ 'runMaintenance', \MigrateBlocks::class ],
440            [ 'dropTable', 'ipblocks' ],
441            [ 'dropField', 'pagelinks', 'pl_title', 'patch-pagelinks-drop-pl_title.sql' ],
442        ];
443    }
444
445    protected function describeTable( $table ) {
446        $q = <<<END
447SELECT attname, attnum FROM pg_namespace, pg_class, pg_attribute
448    WHERE pg_class.relnamespace = pg_namespace.oid
449        AND attrelid=pg_class.oid AND attnum > 0
450        AND relname=%s AND nspname=%s
451END;
452        $res = $this->db->query(
453            sprintf( $q,
454                $this->db->addQuotes( $table ),
455                $this->db->addQuotes( $this->db->getCoreSchema() )
456            ),
457            __METHOD__
458        );
459        if ( !$res ) {
460            return null;
461        }
462
463        $cols = [];
464        foreach ( $res as $r ) {
465            $cols[] = [
466                "name" => $r[0],
467                "ord" => $r[1],
468            ];
469        }
470
471        return $cols;
472    }
473
474    protected function describeIndex( $idx ) {
475        // first fetch the key (which is a list of columns ords) and
476        // the table the index applies to (an oid)
477        $q = <<<END
478SELECT indkey, indrelid FROM pg_namespace, pg_class, pg_index
479    WHERE nspname=%s
480        AND pg_class.relnamespace = pg_namespace.oid
481        AND relname=%s
482        AND indexrelid=pg_class.oid
483END;
484        $res = $this->db->query(
485            sprintf(
486                $q,
487                $this->db->addQuotes( $this->db->getCoreSchema() ),
488                $this->db->addQuotes( $idx )
489            ),
490            __METHOD__
491        );
492        if ( !$res ) {
493            return null;
494        }
495        $r = $res->fetchRow();
496        if ( !$r ) {
497            return null;
498        }
499
500        $indkey = $r[0];
501        $relid = intval( $r[1] );
502        $indkeys = explode( ' ', $indkey );
503
504        $colnames = [];
505        foreach ( $indkeys as $rid ) {
506            $query = <<<END
507SELECT attname FROM pg_class, pg_attribute
508    WHERE attrelid=$relid
509        AND attnum=%d
510        AND attrelid=pg_class.oid
511END;
512            $r2 = $this->db->query( sprintf( $query, $rid ), __METHOD__ );
513            if ( !$r2 ) {
514                return null;
515            }
516            $row2 = $r2->fetchRow();
517            if ( !$row2 ) {
518                return null;
519            }
520            $colnames[] = $row2[0];
521        }
522
523        return $colnames;
524    }
525
526    protected function fkeyDeltype( $fkey ) {
527        $q = <<<END
528SELECT confdeltype FROM pg_constraint, pg_namespace
529    WHERE connamespace=pg_namespace.oid
530        AND nspname=%s
531        AND conname=%s;
532END;
533        $r = $this->db->query(
534            sprintf(
535                $q,
536                $this->db->addQuotes( $this->db->getCoreSchema() ),
537                $this->db->addQuotes( $fkey )
538            ),
539            __METHOD__
540        );
541        $row = $r->fetchRow();
542        return $row ? $row[0] : null;
543    }
544
545    protected function ruleDef( $table, $rule ) {
546        $q = <<<END
547SELECT definition FROM pg_rules
548    WHERE schemaname = %s
549        AND tablename = %s
550        AND rulename = %s
551END;
552        $r = $this->db->query(
553            sprintf(
554                $q,
555                $this->db->addQuotes( $this->db->getCoreSchema() ),
556                $this->db->addQuotes( $table ),
557                $this->db->addQuotes( $rule )
558            ),
559            __METHOD__
560        );
561        $row = $r->fetchRow();
562        if ( !$row ) {
563            return null;
564        }
565        $d = $row[0];
566
567        return $d;
568    }
569
570    protected function addSequence( $table, $pkey, $ns ) {
571        if ( !$this->db->sequenceExists( $ns ) ) {
572            $this->output( "Creating sequence $ns\n" );
573            if ( $pkey !== false ) {
574                $table = $this->db->addIdentifierQuotes( $table );
575                $this->db->query( "CREATE SEQUENCE $ns OWNED BY $table.$pkey", __METHOD__ );
576                $this->setDefault( $table, $pkey, '"nextval"(\'"' . $ns . '"\'::"regclass")' );
577            } else {
578                $this->db->query( "CREATE SEQUENCE $ns", __METHOD__ );
579            }
580        }
581    }
582
583    protected function dropSequence( $table, $ns ) {
584        if ( $this->db->sequenceExists( $ns ) ) {
585            $this->output( "Dropping sequence $ns\n" );
586            $this->db->query( "DROP SEQUENCE $ns CASCADE", __METHOD__ );
587        }
588    }
589
590    protected function renameSequence( $old, $new ) {
591        if ( $this->db->sequenceExists( $new ) ) {
592            $this->output( "...sequence $new already exists.\n" );
593
594            return;
595        }
596        if ( $this->db->sequenceExists( $old ) ) {
597            $this->output( "Renaming sequence $old to $new\n" );
598            $this->db->query( "ALTER SEQUENCE $old RENAME TO $new", __METHOD__ );
599        }
600    }
601
602    protected function setSequenceOwner( $table, $pkey, $seq ) {
603        if ( $this->db->sequenceExists( $seq ) ) {
604            $this->output( "Setting sequence $seq owner to $table.$pkey\n" );
605            $table = $this->db->addIdentifierQuotes( $table );
606            $this->db->query( "ALTER SEQUENCE $seq OWNED BY $table.$pkey", __METHOD__ );
607        }
608    }
609
610    protected function renameTable( $old, $new, $patch = false ) {
611        if ( $this->db->tableExists( $old, __METHOD__ ) ) {
612            $this->output( "Renaming table $old to $new\n" );
613            $old = $this->db->addIdentifierQuotes( $old );
614            $new = $this->db->addIdentifierQuotes( $new );
615            $this->db->query( "ALTER TABLE $old RENAME TO $new", __METHOD__ );
616            if ( $patch !== false ) {
617                $this->applyPatch( $patch );
618            }
619        }
620    }
621
622    protected function renameIndex(
623        $table, $old, $new, $skipBothIndexExistWarning = false, $a = false, $b = false
624    ) {
625        // First requirement: the table must exist
626        if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
627            $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
628
629            return true;
630        }
631
632        // Second requirement: the new index must be missing
633        if ( $this->db->indexExists( $table, $new, __METHOD__ ) ) {
634            $this->output( "...index $new already set on $table table.\n" );
635            if ( !$skipBothIndexExistWarning
636                && $this->db->indexExists( $table, $old, __METHOD__ )
637            ) {
638                $this->output( "...WARNING: $old still exists, despite it has been " .
639                    "renamed into $new (which also exists).\n" .
640                    "            $old should be manually removed if not needed anymore.\n" );
641            }
642
643            return true;
644        }
645
646        // Third requirement: the old index must exist
647        if ( !$this->db->indexExists( $table, $old, __METHOD__ ) ) {
648            $this->output( "...skipping: index $old doesn't exist.\n" );
649
650            return true;
651        }
652
653        $this->db->query( "ALTER INDEX $old RENAME TO $new", __METHOD__ );
654        return true;
655    }
656
657    protected function dropPgField( $table, $field ) {
658        $fi = $this->db->fieldInfo( $table, $field );
659        if ( $fi === null ) {
660            $this->output( "...$table table does not contain $field field.\n" );
661        } else {
662            $this->output( "Dropping column '$table.$field'\n" );
663            $table = $this->db->addIdentifierQuotes( $table );
664            $this->db->query( "ALTER TABLE $table DROP COLUMN $field", __METHOD__ );
665        }
666    }
667
668    protected function addPgField( $table, $field, $type ) {
669        $fi = $this->db->fieldInfo( $table, $field );
670        if ( $fi !== null ) {
671            $this->output( "...column '$table.$field' already exists\n" );
672        } else {
673            $this->output( "Adding column '$table.$field'\n" );
674            $table = $this->db->addIdentifierQuotes( $table );
675            $this->db->query( "ALTER TABLE $table ADD $field $type", __METHOD__ );
676        }
677    }
678
679    protected function changeField( $table, $field, $newtype, $default ) {
680        if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
681            $this->output( "...$table table does not exist, skipping default change.\n" );
682            return;
683        }
684        $fi = $this->db->fieldInfo( $table, $field );
685        if ( $fi === null ) {
686            $this->output( "...ERROR: expected column $table.$field to exist\n" );
687            exit( 1 );
688        }
689
690        if ( $fi->type() === strtolower( $newtype ) ) {
691            $this->output( "...column '$table.$field' is already of type '$newtype'\n" );
692        } else {
693            $this->output( "Changing column type of '$table.$field' from '{$fi->type()}' to '$newtype'\n" );
694            $table = $this->db->addIdentifierQuotes( $table );
695            $sql = "ALTER TABLE $table ALTER $field TYPE $newtype";
696            if ( strlen( $default ) ) {
697                $res = [];
698                if ( preg_match( '/DEFAULT (.+)/', $default, $res ) ) {
699                    $sqldef = "ALTER TABLE $table ALTER $field SET DEFAULT $res[1]";
700                    $this->db->query( $sqldef, __METHOD__ );
701                    $default = preg_replace( '/\s*DEFAULT .+/', '', $default );
702                }
703                $sql .= " USING $default";
704            }
705            $this->db->query( $sql, __METHOD__ );
706        }
707    }
708
709    protected function changeFieldPurgeTable( $table, $field, $newtype, $default ) {
710        # # For a cache table, empty it if the field needs to be changed, because the old contents
711        # # may be corrupted.  If the column is already the desired type, refrain from purging.
712        $fi = $this->db->fieldInfo( $table, $field );
713        if ( $fi === null ) {
714            $this->output( "...ERROR: expected column $table.$field to exist\n" );
715            exit( 1 );
716        }
717
718        if ( $fi->type() === $newtype ) {
719            $this->output( "...column '$table.$field' is already of type '$newtype'\n" );
720        } else {
721            $this->output( "Purging data from cache table '$table'\n" );
722            $table = $this->db->addIdentifierQuotes( $table );
723            $this->db->query( "DELETE from $table", __METHOD__ );
724            $this->output( "Changing column type of '$table.$field' from '{$fi->type()}' to '$newtype'\n" );
725            $sql = "ALTER TABLE $table ALTER $field TYPE $newtype";
726            if ( strlen( $default ) ) {
727                $res = [];
728                if ( preg_match( '/DEFAULT (.+)/', $default, $res ) ) {
729                    $sqldef = "ALTER TABLE $table ALTER $field SET DEFAULT $res[1]";
730                    $this->db->query( $sqldef, __METHOD__ );
731                    $default = preg_replace( '/\s*DEFAULT .+/', '', $default );
732                }
733                $sql .= " USING $default";
734            }
735            $this->db->query( $sql, __METHOD__ );
736        }
737    }
738
739    protected function setDefault( $table, $field, $default ) {
740        if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
741            $this->output( "...$table table does not exist, skipping default change.\n" );
742            return;
743        }
744        $info = $this->db->fieldInfo( $table, $field );
745        if ( $info && $info->defaultValue() !== $default ) {
746            $this->output( "Changing '$table.$field' default value\n" );
747            $table = $this->db->addIdentifierQuotes( $table );
748            $this->db->query( "ALTER TABLE $table ALTER $field SET DEFAULT "
749                . $this->db->addQuotes( $default ), __METHOD__ );
750        }
751    }
752
753    /**
754     * Drop a default value from a field
755     * @since 1.32
756     * @param string $table
757     * @param string $field
758     */
759    protected function dropDefault( $table, $field ) {
760        $info = $this->db->fieldInfo( $table, $field );
761        if ( $info->defaultValue() !== false ) {
762            $this->output( "Removing '$table.$field' default value\n" );
763            $table = $this->db->addIdentifierQuotes( $table );
764            $this->db->query( "ALTER TABLE $table ALTER $field DROP DEFAULT", __METHOD__ );
765        }
766    }
767
768    protected function changeNullableField( $table, $field, $null, $update = false ) {
769        $fi = $this->db->fieldInfo( $table, $field );
770        if ( $fi === null ) {
771            return;
772        }
773        if ( $fi->isNullable() ) {
774            # # It's NULL - does it need to be NOT NULL?
775            if ( $null === 'NOT NULL' ) {
776                $this->output( "Changing '$table.$field' to not allow NULLs\n" );
777                $table = $this->db->addIdentifierQuotes( $table );
778                if ( $update ) {
779                    $this->db->query( "UPDATE $table SET $field = DEFAULT WHERE $field IS NULL", __METHOD__ );
780                }
781                $this->db->query( "ALTER TABLE $table ALTER $field SET NOT NULL", __METHOD__ );
782            } else {
783                $this->output( "...column '$table.$field' is already set as NULL\n" );
784            }
785        } else {
786            # # It's NOT NULL - does it need to be NULL?
787            if ( $null === 'NULL' ) {
788                $this->output( "Changing '$table.$field' to allow NULLs\n" );
789                $table = $this->db->addIdentifierQuotes( $table );
790                $this->db->query( "ALTER TABLE $table ALTER $field DROP NOT NULL", __METHOD__ );
791            } else {
792                $this->output( "...column '$table.$field' is already set as NOT NULL\n" );
793            }
794        }
795    }
796
797    protected function addPgIndex( $table, $index, $type, $unique = false ) {
798        if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
799            $this->output( "...$table table does not exist, skipping index.\n" );
800        } elseif ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
801            $this->output( "...index '$index' on table '$table' already exists\n" );
802        } else {
803            $this->output( "Creating index '$index' on table '$table$type\n" );
804            $table = $this->db->addIdentifierQuotes( $table );
805            $unique = $unique ? 'UNIQUE' : '';
806            $this->db->query( "CREATE $unique INDEX $index ON $table $type", __METHOD__ );
807        }
808    }
809
810    protected function addPgExtIndex( $table, $index, $type ) {
811        if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
812            $this->output( "...index '$index' on table '$table' already exists\n" );
813        } elseif ( preg_match( '/^\(/', $type ) ) {
814            $this->output( "Creating index '$index' on table '$table'\n" );
815            $table = $this->db->addIdentifierQuotes( $table );
816            $this->db->query( "CREATE INDEX $index ON $table $type", __METHOD__ );
817        } else {
818            $this->applyPatch( $type, true, "Creating index '$index' on table '$table'" );
819        }
820    }
821
822    protected function dropFkey( $table, $field ) {
823        if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
824            $this->output( "...$table table does not exist, skipping constraint change.\n" );
825            return;
826        }
827        $fi = $this->db->fieldInfo( $table, $field );
828        if ( $fi === null ) {
829            $this->output( "WARNING! Column '$table.$field' does not exist but it should! " .
830                "Please report this.\n" );
831            return;
832        }
833
834        if ( $this->dropConstraint( $table, $field, 'foreignkey', $fi->conname() ) ) {
835            $this->output( "Dropping foreign key constraint on '$table.$field'\n" );
836        } else {
837            $this->output( "...foreign key constraint on '$table.$field' already does not exist\n" );
838        }
839    }
840
841    protected function changeFkeyDeferrable( $table, $field, $clause ) {
842        $fi = $this->db->fieldInfo( $table, $field );
843        if ( $fi === null ) {
844            $this->output( "WARNING! Column '$table.$field' does not exist but it should! " .
845                "Please report this.\n" );
846
847            return;
848        }
849        if ( $fi->is_deferred() && $fi->is_deferrable() ) {
850            return;
851        }
852        $this->output( "Altering column '$table.$field' to be DEFERRABLE INITIALLY DEFERRED\n" );
853
854        $conname = $fi->conname();
855        $conclause = "CONSTRAINT \"$conname\"";
856
857        if ( !$this->dropConstraint( $table, $field, 'foreignkey', $conname ) ) {
858            $this->output( "Column '$table.$field' does not have a foreign key " .
859                "constraint, will be added\n" );
860            $conclause = "";
861        }
862
863        $command =
864            "ALTER TABLE $table ADD $conclause " .
865            "FOREIGN KEY ($field) REFERENCES $clause DEFERRABLE INITIALLY DEFERRED";
866        $this->db->query( $command, __METHOD__ );
867    }
868
869    protected function dropPgIndex( $table, $index ) {
870        if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
871            $this->output( "Dropping obsolete index '$index'\n" );
872            $this->db->query( "DROP INDEX \"" . $index . "\"", __METHOD__ );
873        }
874    }
875
876    protected function checkIndex( $index, $should_be, $good_def ) {
877        $pu = $this->db->indexAttributes( $index );
878        if ( $pu && $pu != $should_be ) {
879            $this->output( "Dropping obsolete version of index '$index'\n" );
880            $this->db->query( "DROP INDEX \"" . $index . "\"", __METHOD__ );
881            $pu = [];
882        } else {
883            $this->output( "...no need to drop index '$index'\n" );
884        }
885
886        if ( !$pu ) {
887            $this->output( "Creating index '$index'\n" );
888            $this->db->query( $good_def, __METHOD__ );
889        } else {
890            $this->output( "...index '$index' exists\n" );
891        }
892    }
893
894    protected function changePrimaryKey( $table, $shouldBe, $constraintName = null ) {
895        // https://wiki.postgresql.org/wiki/Retrieve_primary_key_columns
896        $result = $this->db->query(
897            "SELECT a.attname as column " .
898                "FROM pg_index i " .
899                "JOIN pg_attribute a ON a.attrelid = i.indrelid " .
900                "AND a.attnum = ANY(i.indkey) " .
901                "WHERE i.indrelid = '\"$table\"'::regclass " .
902                "AND i.indisprimary",
903            __METHOD__
904        );
905        $currentColumns = [];
906        foreach ( $result as $row ) {
907            $currentColumns[] = $row->column;
908        }
909
910        if ( $currentColumns == $shouldBe ) {
911            $this->output( "...no need to change primary key of '$table'\n" );
912            return true;
913        }
914
915        $this->dropConstraint( $table, '', 'primary', $constraintName );
916
917        $table = $this->db->addIdentifierQuotes( $table );
918        $this->db->query(
919            "ALTER TABLE $table" .
920            " ADD PRIMARY KEY (" . implode( ',', $shouldBe ) . ');',
921            __METHOD__
922        );
923    }
924
925    /**
926     * Drop generic constraint. If the constraint was created with a custom name,
927     * then the name must be queried and supplied as $conname, otherwise standard
928     * system suffixes and format would be assumed.
929     *
930     * @param string $table
931     * @param string $field
932     * @param string $type
933     * @param string|null $conname
934     * @return bool
935     */
936    protected function dropConstraint( $table, $field, $type, $conname = null ) {
937        if ( $conname === null ) {
938            if ( $type == 'primary' ) {
939                $conname = "{$table}_pkey";
940            } else {
941                $map = [ 'unique' => 'key', 'check' => 'check', 'foreignkey' => 'fkey' ];
942                $conname = "{$table}_{$field}_{$map[$type]}";
943            }
944        }
945
946        if ( $this->db->constraintExists( $table, $conname ) ) {
947            $table = $this->db->addIdentifierQuotes( $table );
948            $this->db->query(
949                "ALTER TABLE $table DROP CONSTRAINT $conname;",
950                __METHOD__
951            );
952
953            return true;
954        }
955
956        return false;
957    }
958}