Debian Codegraph @

maintenance/includes/SchemaMaintenance.php

raw symbols SCIP
1 <?php
2
3 /**
4 * Base script for schema maintenance
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 * @ingroup Maintenance
23 */
24
25 namespace MediaWiki\Maintenance;
26
27 use Doctrine\SqlFormatter\NullHighlighter;
28 use Doctrine\SqlFormatter\SqlFormatter;
29 use MediaWiki\DB\AbstractSchemaValidationError;
30 use MediaWiki\DB\AbstractSchemaValidator;
31
32 // @codeCoverageIgnoreStart
33 require_once __DIR__ . '/../Maintenance.php';
34 // @codeCoverageIgnoreEnd
35
36 abstract class SchemaMaintenance extends Maintenance {
37 public const SUPPORTED_PLATFORMS = [
38 'mysql',
39 'sqlite',
40 'postgres'
41 ];
42
43 /**
44 * Name of the script.
45 * @var string
46 */
47 protected $scriptName;
48
49 public function __construct() {
50 parent::__construct();
51
52 $types = implode( ', ', array_map( static function ( string $type ): string {
53 return "'$type'";
54 }, self::SUPPORTED_PLATFORMS ) );
55
56 $this->addOption(
57 'json',
58 'Path to the json file. Default: tables.json',
59 false,
60 true
61 );
62 $this->addOption(
63 'sql',
64 'Path to output. If --type=all is given, ' .
65 'the output will be placed in a directory named after the dbms. ' .
66 'For mysql, a directory will only be used if it already exists. Default: tables-generated.sql',
67 false,
68 true
69 );
70 $this->addOption(
71 'type',
72 "Can be either $types, or 'all'. Default: mysql",
73 false,
74 true
75 );
76 $this->addOption(
77 'validate',
78 'Validate the schema instead of generating sql files.'
79 );
80 }
81
82 public function canExecuteWithoutLocalSettings(): bool {
83 return true;
84 }
85
86 public function execute() {
87 global $IP;
88
89 $platform = $this->getOption( 'type', 'mysql' );
90 $jsonPath = $this->getOption( 'json', dirname( __DIR__ ) );
91
92 $installPath = $IP;
93
94 // For windows
95 if ( DIRECTORY_SEPARATOR === '\\' ) {
96 $installPath = strtr( $installPath, '\\', '/' );
97 $jsonPath = strtr( $jsonPath, '\\', '/' );
98 }
99
100 if ( $this->hasOption( 'validate' ) ) {
101 $this->getSchema( $jsonPath );
102
103 return;
104 }
105
106 // Allow to specify a folder and use a default name
107 if ( is_dir( $jsonPath ) ) {
108 $jsonPath .= '/tables.json';
109 }
110
111 $relativeJsonPath = str_replace(
112 [ "$installPath/extensions/", "$installPath/" ],
113 '',
114 $jsonPath
115 );
116
117 if ( in_array( $platform, self::SUPPORTED_PLATFORMS, true ) ) {
118 $platforms = [ $platform ];
119 } elseif ( $platform === 'all' ) {
120 $platforms = self::SUPPORTED_PLATFORMS;
121 } else {
122 $this->fatalError( "'$platform' is not a supported platform!" );
123 }
124
125 foreach ( $platforms as $platform ) {
126 $sqlPath = $this->getOption( 'sql', dirname( $jsonPath ) );
127
128 // MediaWiki, and some extensions place mysql .sql files in the directory root, instead of a dedicated
129 // sub directory. If mysql/ doesn't exist, assume that the .sql files should be in the directory root.
130 if ( $platform === 'mysql' && !is_dir( $sqlPath . '/mysql' ) ) {
131 // Allow to specify a folder and build the name from the json filename
132 if ( is_dir( $sqlPath ) ) {
133 $sqlPath = $this->getSqlPathWithFileName( $relativeJsonPath, $sqlPath );
134 }
135 } else {
136 // Allow to specify a folder and build the name from the json filename
137 if ( is_dir( $sqlPath ) ) {
138 $sqlPath .= '/' . $platform;
139 $directory = $sqlPath;
140 $sqlPath = $this->getSqlPathWithFileName( $relativeJsonPath, $sqlPath );
141 } elseif ( count( $platforms ) > 1 ) {
142 $directory = dirname( $sqlPath ) . '/' . $platform;
143 $sqlPath = $directory . '/' . pathinfo( $sqlPath, PATHINFO_FILENAME ) . '.sql';
144 } else {
145 $directory = false;
146 }
147
148 // The directory for the platform might not exist.
149 if ( $directory !== false && !is_dir( $directory )
150 && !mkdir( $directory ) && !is_dir( $directory )
151 ) {
152 $this->error( "Cannot create $directory for $platform" );
153
154 continue;
155 }
156 }
157
158 $this->writeSchema( $platform, $jsonPath, $relativeJsonPath, $sqlPath );
159 }
160 }
161
162 /**
163 * Determine the name of the generated SQL file when only a directory has been provided to --sql.
164 * When --json is given tables.json, tables-generates.sql will be the name, otherwise it will be the name of the
165 * .json file, minus the extension.
166 *
167 * @param string $relativeJsonPath
168 * @param string $sqlPath
169 * @return string
170 */
171 private function getSqlPathWithFileName( string $relativeJsonPath, string $sqlPath ): string {
172 $jsonFilename = pathinfo( $relativeJsonPath, PATHINFO_FILENAME );
173 if ( str_starts_with( $jsonFilename, 'tables' ) ) {
174 $sqlFileName = $jsonFilename . '-generated.sql';
175 } else {
176 $sqlFileName = $jsonFilename . '.sql';
177 }
178
179 return $sqlPath . '/' . $sqlFileName;
180 }
181
182 private function writeSchema(
183 string $platform,
184 string $jsonPath,
185 string $relativeJsonPath,
186 string $sqlPath
187 ): void {
188 $abstractSchemaChange = $this->getSchema( $jsonPath );
189
190 $sql =
191 "-- This file is automatically generated using maintenance/$this->scriptName.\n" .
192 "-- Source: $relativeJsonPath\n" .
193 "-- Do not modify this file directly.\n" .
194 "-- See https://www.mediawiki.org/wiki/Manual:Schema_changes\n";
195
196 $sql .= $this->generateSchema( $platform, $abstractSchemaChange );
197
198 // Give a hint, if nothing changed
199 if ( is_readable( $sqlPath ) ) {
200 $oldSql = file_get_contents( $sqlPath );
201 if ( $oldSql === $sql ) {
202 $this->output( "Schema change is unchanged.\n" );
203 }
204 }
205
206 file_put_contents( $sqlPath, $sql );
207 $this->output( 'Schema change generated and written to ' . $sqlPath . "\n" );
208 }
209
210 abstract protected function generateSchema( string $platform, array $schema ): string;
211
212 /**
213 * Takes the output of DoctrineSchemaBuilder::getSql() or
214 * DoctrineSchemaChangeBuilder::getSchemaChangeSql() and applies presentational changes.
215 *
216 * @param string $platform DB engine identifier
217 * @param array $sqlArray Array of SQL statements
218 * @return string
219 */
220 protected function cleanupSqlArray( string $platform, array $sqlArray ): string {
221 if ( !$sqlArray ) {
222 return '';
223 }
224
225 // Temporary
226 $sql = implode( ";\n\n", $sqlArray ) . ';';
227 $sql = ( new SqlFormatter( new NullHighlighter() ) )->format( $sql );
228
229 // Postgres hacks
230 if ( $platform === 'postgres' ) {
231 // FIXME: Fix a lot of weird formatting issues caused by
232 // presence of partial index's WHERE clause, this should probably
233 // be done in some better way, but for now this can work temporarily
234 $sql = str_replace(
235 [ "WHERE\n ", "\n /*_*/\n ", " ", " );", "KEY(\n " ],
236 [ "WHERE", ' ', " ", ');', "KEY(\n " ],
237 $sql
238 );
239 }
240
241 // Temporary fixes until the linting issues are resolved upstream.
242 // https://github.com/doctrine/sql-formatter/issues/53
243
244 $sql = preg_replace( "!\s+/\*_\*/\s+!", " /*_*/", $sql );
245 $sql = preg_replace(
246 '!\s+/\*\$wgDBTableOptions\*/\s+;!',
247 ' /*$wgDBTableOptions*/;',
248 $sql
249 );
250
251 $sql = str_replace( "; CREATE ", ";\n\nCREATE ", $sql );
252 $sql = str_replace( ";\n\nCREATE TABLE ", ";\n\n\nCREATE TABLE ", $sql );
253 $sql = preg_replace( '/^(CREATE|DROP|ALTER)\s+(TABLE|VIEW|INDEX)\s+/m', '$1 $2 ', $sql );
254 $sql = preg_replace( '/(?<!\s|;)\s+(ADD|DROP|ALTER|MODIFY|CHANGE|RENAME)\s+/', "\n \$1 ", $sql );
255
256 $sql = str_replace( "; ", ";\n", $sql );
257
258 if ( !str_ends_with( $sql, "\n" ) ) {
259 $sql .= "\n";
260 }
261
262 // Sqlite hacks
263 if ( $platform === 'sqlite' ) {
264 // Doctrine prepends __temp__ to the table name and we set the table with the schema prefix causing invalid
265 // sqlite.
266 $sql = preg_replace( '/__temp__\s*\/\*_\*\//', '/*_*/__temp__', $sql );
267 }
268
269 return $sql;
270 }
271
272 /**
273 * Fetches the abstract schema.
274 *
275 * @param string $jsonPath
276 * @return array
277 */
278 private function getSchema( string $jsonPath ): array {
279 $json = file_get_contents( $jsonPath );
280
281 if ( !$json ) {
282 $this->fatalError(
283 "'$jsonPath' does not exist!\n"
284 );
285 }
286
287 $abstractSchema = json_decode( $json, true );
288
289 if ( json_last_error() !== JSON_ERROR_NONE ) {
290 $this->fatalError(
291 "'$jsonPath' seems to be invalid json. Check the syntax and try again!\n" . json_last_error_msg()
292 );
293 }
294
295 $validator = new AbstractSchemaValidator( function ( string $msg ): void {
296 $this->fatalError( $msg );
297 } );
298 try {
299 $validator->validate( $jsonPath );
300 } catch ( AbstractSchemaValidationError $e ) {
301 $this->fatalError( $e->getMessage() );
302 }
303
304 return $abstractSchema;
305 }
306 }
307
308 /** @deprecated class alias since 1.43 */
309 class_alias( SchemaMaintenance::class, 'SchemaMaintenance' );