Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 692
0.00% covered (danger)
0.00%
0 / 28
CRAP
0.00% covered (danger)
0.00%
0 / 1
PostgresUpdater
0.00% covered (danger)
0.00%
0 / 692
0.00% covered (danger)
0.00%
0 / 28
9312
0.00% covered (danger)
0.00%
0 / 1
 getCoreUpdateList
0.00% covered (danger)
0.00%
0 / 378
0.00% covered (danger)
0.00%
0 / 1
2
 getInitialUpdateKeys
0.00% covered (danger)
0.00%
0 / 8
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
 migrateSearchindex
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
42
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 MediaWiki\Maintenance\FixAutoblockLogTitles;
28use MigrateExternallinks;
29use MigrateRevisionActorTemp;
30use MigrateRevisionCommentTemp;
31use PopulateUserIsTemp;
32use UpdateRestrictions;
33use Wikimedia\Rdbms\DatabasePostgres;
34
35/**
36 * Class for handling updates to Postgres databases.
37 *
38 * @ingroup Installer
39 * @since 1.17
40 */
41class PostgresUpdater extends DatabaseUpdater {
42
43    /**
44     * @var DatabasePostgres
45     */
46    protected $db;
47
48    /**
49     * @return array
50     */
51    protected function getCoreUpdateList() {
52        return [
53            // Exception to the sequential updates. Renaming pagecontent and mwuser.
54            // Introduced in 1.36.
55            [ 'renameTable', 'pagecontent', 'text' ],
56            // Introduced in 1.37.
57            [ 'renameTable', 'mwuser', 'user' ],
58
59            // 1.36
60            [ 'setDefault', 'bot_passwords', 'bp_token', '' ],
61            [ 'changeField', 'comment', 'comment_id', 'BIGINT', '' ],
62            [ 'changeField', 'slots', 'slot_revision_id', 'BIGINT', '' ],
63            [ 'changeField', 'slots', 'slot_content_id', 'BIGINT', '' ],
64            [ 'changeField', 'slots', 'slot_origin', 'BIGINT', '' ],
65            [ 'changeField', 'site_stats', 'ss_total_edits', 'BIGINT', '' ],
66            [ 'changeField', 'site_stats', 'ss_good_articles', 'BIGINT', '' ],
67            [ 'changeField', 'site_stats', 'ss_total_pages', 'BIGINT', '' ],
68            [ 'changeField', 'site_stats', 'ss_users', 'BIGINT', '' ],
69            [ 'changeField', 'site_stats', 'ss_active_users', 'BIGINT', '' ],
70            [ 'changeField', 'site_stats', 'ss_images', 'BIGINT', '' ],
71            [ 'dropFkey', 'user_properties', 'up_user' ],
72            [ 'addIndex', 'user_properties', 'user_properties_pkey', 'patch-user_properties-pk.sql' ],
73            [ 'changeField', 'log_search', 'ls_value', 'VARCHAR(255)', '' ],
74            [ 'changeField', 'content', 'content_id', 'BIGINT', '' ],
75            [ 'changeField', 'l10n_cache', 'lc_value', 'TEXT', '' ],
76            [ 'changeField', 'l10n_cache', 'lc_key', 'VARCHAR(255)', '' ],
77            [ 'addIndex', 'l10n_cache', 'l10n_cache_pkey', 'patch-l10n_cache-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            [ 'addPostDatabaseUpdateMaintenance', FixAutoblockLogTitles::class ],
443            [ 'migrateSearchindex' ],
444
445            // 1.44
446            [ 'addTable', 'file', 'patch-file.sql' ],
447            [ 'addField', 'categorylinks', 'cl_target_id', 'patch-categorylinks-target_id.sql' ],
448            [ 'addTable', 'collation', 'patch-collation.sql' ],
449            [ 'dropTable', 'module_deps' ],
450
451            // 1.45
452            [ 'addTable', 'existencelinks', 'patch-existencelinks.sql' ],
453        ];
454    }
455
456    protected function getInitialUpdateKeys() {
457        return [
458            'filearchive-fa_major_mime-patch-fa_major_mime-chemical.sql',
459            'image-img_major_mime-patch-img_major_mime-chemical.sql',
460            'oldimage-oi_major_mime-patch-oi_major_mime-chemical.sql',
461            'user_groups-ug_group-patch-ug_group-length-increase-255.sql',
462            'user_former_groups-ufg_group-patch-ufg_group-length-increase-255.sql',
463            'user_properties-up_property-patch-up_property.sql',
464        ];
465    }
466
467    protected function describeTable( $table ) {
468        $q = <<<END
469SELECT attname, attnum FROM pg_namespace, pg_class, pg_attribute
470    WHERE pg_class.relnamespace = pg_namespace.oid
471        AND attrelid=pg_class.oid AND attnum > 0
472        AND relname=%s AND nspname=%s
473END;
474        $res = $this->db->query(
475            sprintf( $q,
476                $this->db->addQuotes( $table ),
477                $this->db->addQuotes( $this->db->getCoreSchema() )
478            ),
479            __METHOD__
480        );
481        if ( !$res ) {
482            return null;
483        }
484
485        $cols = [];
486        foreach ( $res as $r ) {
487            $cols[] = [
488                "name" => $r[0],
489                "ord" => $r[1],
490            ];
491        }
492
493        return $cols;
494    }
495
496    protected function describeIndex( $idx ) {
497        // first fetch the key (which is a list of columns ords) and
498        // the table the index applies to (an oid)
499        $q = <<<END
500SELECT indkey, indrelid FROM pg_namespace, pg_class, pg_index
501    WHERE nspname=%s
502        AND pg_class.relnamespace = pg_namespace.oid
503        AND relname=%s
504        AND indexrelid=pg_class.oid
505END;
506        $res = $this->db->query(
507            sprintf(
508                $q,
509                $this->db->addQuotes( $this->db->getCoreSchema() ),
510                $this->db->addQuotes( $idx )
511            ),
512            __METHOD__
513        );
514        if ( !$res ) {
515            return null;
516        }
517        $r = $res->fetchRow();
518        if ( !$r ) {
519            return null;
520        }
521
522        $indkey = $r[0];
523        $relid = intval( $r[1] );
524        $indkeys = explode( ' ', $indkey );
525
526        $colnames = [];
527        foreach ( $indkeys as $rid ) {
528            $query = <<<END
529SELECT attname FROM pg_class, pg_attribute
530    WHERE attrelid=$relid
531        AND attnum=%d
532        AND attrelid=pg_class.oid
533END;
534            $r2 = $this->db->query( sprintf( $query, $rid ), __METHOD__ );
535            if ( !$r2 ) {
536                return null;
537            }
538            $row2 = $r2->fetchRow();
539            if ( !$row2 ) {
540                return null;
541            }
542            $colnames[] = $row2[0];
543        }
544
545        return $colnames;
546    }
547
548    protected function fkeyDeltype( $fkey ) {
549        $q = <<<END
550SELECT confdeltype FROM pg_constraint, pg_namespace
551    WHERE connamespace=pg_namespace.oid
552        AND nspname=%s
553        AND conname=%s;
554END;
555        $r = $this->db->query(
556            sprintf(
557                $q,
558                $this->db->addQuotes( $this->db->getCoreSchema() ),
559                $this->db->addQuotes( $fkey )
560            ),
561            __METHOD__
562        );
563        $row = $r->fetchRow();
564        return $row ? $row[0] : null;
565    }
566
567    protected function ruleDef( $table, $rule ) {
568        $q = <<<END
569SELECT definition FROM pg_rules
570    WHERE schemaname = %s
571        AND tablename = %s
572        AND rulename = %s
573END;
574        $r = $this->db->query(
575            sprintf(
576                $q,
577                $this->db->addQuotes( $this->db->getCoreSchema() ),
578                $this->db->addQuotes( $table ),
579                $this->db->addQuotes( $rule )
580            ),
581            __METHOD__
582        );
583        $row = $r->fetchRow();
584        if ( !$row ) {
585            return null;
586        }
587        $d = $row[0];
588
589        return $d;
590    }
591
592    protected function addSequence( $table, $pkey, $ns ) {
593        if ( !$this->db->sequenceExists( $ns ) ) {
594            $this->output( "Creating sequence $ns\n" );
595            if ( $pkey !== false ) {
596                $table = $this->db->addIdentifierQuotes( $table );
597                $this->db->query( "CREATE SEQUENCE $ns OWNED BY $table.$pkey", __METHOD__ );
598                $this->setDefault( $table, $pkey, '"nextval"(\'"' . $ns . '"\'::"regclass")' );
599            } else {
600                $this->db->query( "CREATE SEQUENCE $ns", __METHOD__ );
601            }
602        }
603    }
604
605    protected function dropSequence( $table, $ns ) {
606        if ( $this->db->sequenceExists( $ns ) ) {
607            $this->output( "Dropping sequence $ns\n" );
608            $this->db->query( "DROP SEQUENCE $ns CASCADE", __METHOD__ );
609        }
610    }
611
612    protected function renameSequence( $old, $new ) {
613        if ( $this->db->sequenceExists( $new ) ) {
614            $this->output( "...sequence $new already exists.\n" );
615
616            return;
617        }
618        if ( $this->db->sequenceExists( $old ) ) {
619            $this->output( "Renaming sequence $old to $new\n" );
620            $this->db->query( "ALTER SEQUENCE $old RENAME TO $new", __METHOD__ );
621        }
622    }
623
624    protected function setSequenceOwner( $table, $pkey, $seq ) {
625        if ( $this->db->sequenceExists( $seq ) ) {
626            $this->output( "Setting sequence $seq owner to $table.$pkey\n" );
627            $table = $this->db->addIdentifierQuotes( $table );
628            $this->db->query( "ALTER SEQUENCE $seq OWNED BY $table.$pkey", __METHOD__ );
629        }
630    }
631
632    protected function renameTable( $old, $new, $patch = false ) {
633        if ( $this->db->tableExists( $old, __METHOD__ ) ) {
634            $this->output( "Renaming table $old to $new\n" );
635            $old = $this->db->addIdentifierQuotes( $old );
636            $new = $this->db->addIdentifierQuotes( $new );
637            $this->db->query( "ALTER TABLE $old RENAME TO $new", __METHOD__ );
638            if ( $patch !== false ) {
639                $this->applyPatch( $patch );
640            }
641        }
642    }
643
644    protected function renameIndex(
645        $table, $old, $new, $skipBothIndexExistWarning = false, $a = false, $b = false
646    ) {
647        // First requirement: the table must exist
648        if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
649            $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
650
651            return true;
652        }
653
654        // Second requirement: the new index must be missing
655        if ( $this->db->indexExists( $table, $new, __METHOD__ ) ) {
656            $this->output( "...index $new already set on $table table.\n" );
657            if ( !$skipBothIndexExistWarning
658                && $this->db->indexExists( $table, $old, __METHOD__ )
659            ) {
660                $this->output( "...WARNING: $old still exists, despite it has been " .
661                    "renamed into $new (which also exists).\n" .
662                    "            $old should be manually removed if not needed anymore.\n" );
663            }
664
665            return true;
666        }
667
668        // Third requirement: the old index must exist
669        if ( !$this->db->indexExists( $table, $old, __METHOD__ ) ) {
670            $this->output( "...skipping: index $old doesn't exist.\n" );
671
672            return true;
673        }
674
675        $this->db->query( "ALTER INDEX $old RENAME TO $new", __METHOD__ );
676        return true;
677    }
678
679    protected function dropPgField( $table, $field ) {
680        $fi = $this->db->fieldInfo( $table, $field );
681        if ( $fi === null ) {
682            $this->output( "...$table table does not contain $field field.\n" );
683        } else {
684            $this->output( "Dropping column '$table.$field'\n" );
685            $table = $this->db->addIdentifierQuotes( $table );
686            $this->db->query( "ALTER TABLE $table DROP COLUMN $field", __METHOD__ );
687        }
688    }
689
690    protected function addPgField( $table, $field, $type ) {
691        $fi = $this->db->fieldInfo( $table, $field );
692        if ( $fi !== null ) {
693            $this->output( "...column '$table.$field' already exists\n" );
694        } else {
695            $this->output( "Adding column '$table.$field'\n" );
696            $table = $this->db->addIdentifierQuotes( $table );
697            $this->db->query( "ALTER TABLE $table ADD $field $type", __METHOD__ );
698        }
699    }
700
701    protected function changeField( $table, $field, $newtype, $default ) {
702        if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
703            $this->output( "...$table table does not exist, skipping default change.\n" );
704            return;
705        }
706        $fi = $this->db->fieldInfo( $table, $field );
707        if ( $fi === null ) {
708            $this->output( "...ERROR: expected column $table.$field to exist\n" );
709            exit( 1 );
710        }
711
712        if ( $fi->type() === strtolower( $newtype ) ) {
713            $this->output( "...column '$table.$field' is already of type '$newtype'\n" );
714        } else {
715            $this->output( "Changing column type of '$table.$field' from '{$fi->type()}' to '$newtype'\n" );
716            $table = $this->db->addIdentifierQuotes( $table );
717            $sql = "ALTER TABLE $table ALTER $field TYPE $newtype";
718            if ( $default !== '' ) {
719                $res = [];
720                if ( preg_match( '/DEFAULT (.+)/', $default, $res ) ) {
721                    $sqldef = "ALTER TABLE $table ALTER $field SET DEFAULT $res[1]";
722                    $this->db->query( $sqldef, __METHOD__ );
723                    $default = preg_replace( '/\s*DEFAULT .+/', '', $default );
724                }
725                $sql .= " USING $default";
726            }
727            $this->db->query( $sql, __METHOD__ );
728        }
729    }
730
731    protected function changeFieldPurgeTable( $table, $field, $newtype, $default ) {
732        # # For a cache table, empty it if the field needs to be changed, because the old contents
733        # # may be corrupted.  If the column is already the desired type, refrain from purging.
734        $fi = $this->db->fieldInfo( $table, $field );
735        if ( $fi === null ) {
736            $this->output( "...ERROR: expected column $table.$field to exist\n" );
737            exit( 1 );
738        }
739
740        if ( $fi->type() === $newtype ) {
741            $this->output( "...column '$table.$field' is already of type '$newtype'\n" );
742        } else {
743            $this->output( "Purging data from cache table '$table'\n" );
744            $table = $this->db->addIdentifierQuotes( $table );
745            $this->db->query( "DELETE from $table", __METHOD__ );
746            $this->output( "Changing column type of '$table.$field' from '{$fi->type()}' to '$newtype'\n" );
747            $sql = "ALTER TABLE $table ALTER $field TYPE $newtype";
748            if ( strlen( $default ) ) {
749                $res = [];
750                if ( preg_match( '/DEFAULT (.+)/', $default, $res ) ) {
751                    $sqldef = "ALTER TABLE $table ALTER $field SET DEFAULT $res[1]";
752                    $this->db->query( $sqldef, __METHOD__ );
753                    $default = preg_replace( '/\s*DEFAULT .+/', '', $default );
754                }
755                $sql .= " USING $default";
756            }
757            $this->db->query( $sql, __METHOD__ );
758        }
759    }
760
761    protected function setDefault( $table, $field, $default ) {
762        if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
763            $this->output( "...$table table does not exist, skipping default change.\n" );
764            return;
765        }
766        $info = $this->db->fieldInfo( $table, $field );
767        if ( $info && $info->defaultValue() !== $default ) {
768            $this->output( "Changing '$table.$field' default value\n" );
769            $table = $this->db->addIdentifierQuotes( $table );
770            $this->db->query( "ALTER TABLE $table ALTER $field SET DEFAULT "
771                . $this->db->addQuotes( $default ), __METHOD__ );
772        }
773    }
774
775    /**
776     * Drop a default value from a field
777     * @since 1.32
778     * @param string $table
779     * @param string $field
780     */
781    protected function dropDefault( $table, $field ) {
782        $info = $this->db->fieldInfo( $table, $field );
783        if ( $info->defaultValue() !== false ) {
784            $this->output( "Removing '$table.$field' default value\n" );
785            $table = $this->db->addIdentifierQuotes( $table );
786            $this->db->query( "ALTER TABLE $table ALTER $field DROP DEFAULT", __METHOD__ );
787        }
788    }
789
790    protected function changeNullableField( $table, $field, $null, $update = false ) {
791        $fi = $this->db->fieldInfo( $table, $field );
792        if ( $fi === null ) {
793            return;
794        }
795        if ( $fi->isNullable() ) {
796            # # It's NULL - does it need to be NOT NULL?
797            if ( $null === 'NOT NULL' ) {
798                $this->output( "Changing '$table.$field' to not allow NULLs\n" );
799                $table = $this->db->addIdentifierQuotes( $table );
800                if ( $update ) {
801                    $this->db->query( "UPDATE $table SET $field = DEFAULT WHERE $field IS NULL", __METHOD__ );
802                }
803                $this->db->query( "ALTER TABLE $table ALTER $field SET NOT NULL", __METHOD__ );
804            } else {
805                $this->output( "...column '$table.$field' is already set as NULL\n" );
806            }
807        } else {
808            # # It's NOT NULL - does it need to be NULL?
809            if ( $null === 'NULL' ) {
810                $this->output( "Changing '$table.$field' to allow NULLs\n" );
811                $table = $this->db->addIdentifierQuotes( $table );
812                $this->db->query( "ALTER TABLE $table ALTER $field DROP NOT NULL", __METHOD__ );
813            } else {
814                $this->output( "...column '$table.$field' is already set as NOT NULL\n" );
815            }
816        }
817    }
818
819    protected function addPgIndex( $table, $index, $type, $unique = false ) {
820        if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
821            $this->output( "...$table table does not exist, skipping index.\n" );
822        } elseif ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
823            $this->output( "...index '$index' on table '$table' already exists\n" );
824        } else {
825            $this->output( "Creating index '$index' on table '$table$type\n" );
826            $table = $this->db->addIdentifierQuotes( $table );
827            $unique = $unique ? 'UNIQUE' : '';
828            $this->db->query( "CREATE $unique INDEX $index ON $table $type", __METHOD__ );
829        }
830    }
831
832    protected function addPgExtIndex( $table, $index, $type ) {
833        if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
834            $this->output( "...index '$index' on table '$table' already exists\n" );
835        } elseif ( preg_match( '/^\(/', $type ) ) {
836            $this->output( "Creating index '$index' on table '$table'\n" );
837            $table = $this->db->addIdentifierQuotes( $table );
838            $this->db->query( "CREATE INDEX $index ON $table $type", __METHOD__ );
839        } else {
840            $this->applyPatch( $type, true, "Creating index '$index' on table '$table'" );
841        }
842    }
843
844    protected function dropFkey( $table, $field ) {
845        if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
846            $this->output( "...$table table does not exist, skipping constraint change.\n" );
847            return;
848        }
849        $fi = $this->db->fieldInfo( $table, $field );
850        if ( $fi === null ) {
851            $this->output( "WARNING! Column '$table.$field' does not exist but it should! " .
852                "Please report this.\n" );
853            return;
854        }
855
856        if ( $this->dropConstraint( $table, $field, 'foreignkey', $fi->conname() ) ) {
857            $this->output( "Dropping foreign key constraint on '$table.$field'\n" );
858        } else {
859            $this->output( "...foreign key constraint on '$table.$field' already does not exist\n" );
860        }
861    }
862
863    protected function changeFkeyDeferrable( $table, $field, $clause ) {
864        $fi = $this->db->fieldInfo( $table, $field );
865        if ( $fi === null ) {
866            $this->output( "WARNING! Column '$table.$field' does not exist but it should! " .
867                "Please report this.\n" );
868
869            return;
870        }
871        if ( $fi->is_deferred() && $fi->is_deferrable() ) {
872            return;
873        }
874        $this->output( "Altering column '$table.$field' to be DEFERRABLE INITIALLY DEFERRED\n" );
875
876        $conname = $fi->conname();
877        $conclause = "CONSTRAINT \"$conname\"";
878
879        if ( !$this->dropConstraint( $table, $field, 'foreignkey', $conname ) ) {
880            $this->output( "Column '$table.$field' does not have a foreign key " .
881                "constraint, will be added\n" );
882            $conclause = "";
883        }
884
885        $command =
886            "ALTER TABLE $table ADD $conclause " .
887            "FOREIGN KEY ($field) REFERENCES $clause DEFERRABLE INITIALLY DEFERRED";
888        $this->db->query( $command, __METHOD__ );
889    }
890
891    protected function dropPgIndex( $table, $index ) {
892        if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
893            $this->output( "Dropping obsolete index '$index'\n" );
894            $this->db->query( "DROP INDEX \"" . $index . "\"", __METHOD__ );
895        }
896    }
897
898    protected function checkIndex( $index, $should_be, $good_def ) {
899        $pu = $this->db->indexAttributes( $index );
900        if ( $pu && $pu != $should_be ) {
901            $this->output( "Dropping obsolete version of index '$index'\n" );
902            $this->db->query( "DROP INDEX \"" . $index . "\"", __METHOD__ );
903            $pu = [];
904        } else {
905            $this->output( "...no need to drop index '$index'\n" );
906        }
907
908        if ( !$pu ) {
909            $this->output( "Creating index '$index'\n" );
910            $this->db->query( $good_def, __METHOD__ );
911        } else {
912            $this->output( "...index '$index' exists\n" );
913        }
914    }
915
916    protected function changePrimaryKey( $table, $shouldBe, $constraintName = null ) {
917        // https://wiki.postgresql.org/wiki/Retrieve_primary_key_columns
918        $result = $this->db->query(
919            "SELECT a.attname as column " .
920                "FROM pg_index i " .
921                "JOIN pg_attribute a ON a.attrelid = i.indrelid " .
922                "AND a.attnum = ANY(i.indkey) " .
923                "WHERE i.indrelid = '\"$table\"'::regclass " .
924                "AND i.indisprimary",
925            __METHOD__
926        );
927        $currentColumns = [];
928        foreach ( $result as $row ) {
929            $currentColumns[] = $row->column;
930        }
931
932        if ( $currentColumns == $shouldBe ) {
933            $this->output( "...no need to change primary key of '$table'\n" );
934            return true;
935        }
936
937        $this->dropConstraint( $table, '', 'primary', $constraintName );
938
939        $table = $this->db->addIdentifierQuotes( $table );
940        $this->db->query(
941            "ALTER TABLE $table" .
942            " ADD PRIMARY KEY (" . implode( ',', $shouldBe ) . ');',
943            __METHOD__
944        );
945    }
946
947    /**
948     * Drop generic constraint. If the constraint was created with a custom name,
949     * then the name must be queried and supplied as $conname, otherwise standard
950     * system suffixes and format would be assumed.
951     *
952     * @param string $table
953     * @param string $field
954     * @param string $type
955     * @param string|null $conname
956     * @return bool
957     */
958    protected function dropConstraint( $table, $field, $type, $conname = null ) {
959        if ( $conname === null ) {
960            if ( $type == 'primary' ) {
961                $conname = "{$table}_pkey";
962            } else {
963                $map = [ 'unique' => 'key', 'check' => 'check', 'foreignkey' => 'fkey' ];
964                $conname = "{$table}_{$field}_{$map[$type]}";
965            }
966        }
967
968        if ( $this->db->constraintExists( $table, $conname ) ) {
969            $table = $this->db->addIdentifierQuotes( $table );
970            $this->db->query(
971                "ALTER TABLE $table DROP CONSTRAINT $conname;",
972                __METHOD__
973            );
974
975            return true;
976        }
977
978        return false;
979    }
980
981    /**
982     * Replaces unique index with primary key,modifies si_title length
983     *
984     * @since 1.43
985     * @return void
986     */
987    protected function migrateSearchindex() {
988        $updateKey = 'searchindex-pk-titlelength';
989        if ( !$this->tableExists( 'searchindex' ) ) {
990            return;
991        }
992
993        $primaryIndexExists = $this->db->indexExists( 'searchindex', 'searchindex_pkey' );
994        if ( $this->updateRowExists( $updateKey ) || ( $primaryIndexExists ) ) {
995            $this->output( "...searchindex table has already been migrated.\n" );
996            if ( !$this->updateRowExists( $updateKey ) ) {
997                $this->insertUpdateRow( $updateKey );
998            }
999            return;
1000        }
1001
1002        $apply = $this->applyPatch( 'patch-searchindex-pk-titlelength.sql', false, '...migrating searchindex table' );
1003
1004        if ( $apply ) {
1005            $this->insertUpdateRow( $updateKey );
1006        }
1007    }
1008}