Merge "Use delete_and_move_reason in content language on move over redirect"
[lhc/web/wiklou.git] / maintenance / sqlite.inc
1 <?php
2 /**
3 * Helper class for sqlite-specific scripts
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 Maintenance
22 */
23
24 use Wikimedia\Rdbms\DatabaseSqlite;
25
26 /**
27 * This class contains code common to different SQLite-related maintenance scripts
28 *
29 * @ingroup Maintenance
30 */
31 class Sqlite {
32
33 /**
34 * Checks whether PHP has SQLite support
35 * @return bool
36 */
37 public static function isPresent() {
38 return extension_loaded( 'pdo_sqlite' );
39 }
40
41 /**
42 * Checks given files for correctness of SQL syntax. MySQL DDL will be converted to
43 * SQLite-compatible during processing.
44 * Will throw exceptions on SQL errors
45 * @param array|string $files
46 * @throws MWException
47 * @return bool True if no error or error string in case of errors
48 */
49 public static function checkSqlSyntax( $files ) {
50 if ( !Sqlite::isPresent() ) {
51 throw new MWException( "Can't check SQL syntax: SQLite not found" );
52 }
53 if ( !is_array( $files ) ) {
54 $files = [ $files ];
55 }
56
57 $allowedTypes = array_flip( [
58 'integer',
59 'real',
60 'text',
61 'blob', // NULL type is omitted intentionally
62 ] );
63
64 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
65 try {
66 foreach ( $files as $file ) {
67 $err = $db->sourceFile( $file );
68 if ( $err != true ) {
69 return $err;
70 }
71 }
72
73 $tables = $db->query( "SELECT name FROM sqlite_master WHERE type='table'", __METHOD__ );
74 foreach ( $tables as $table ) {
75 if ( strpos( $table->name, 'sqlite_' ) === 0 ) {
76 continue;
77 }
78
79 $columns = $db->query( "PRAGMA table_info({$table->name})", __METHOD__ );
80 foreach ( $columns as $col ) {
81 if ( !isset( $allowedTypes[strtolower( $col->type )] ) ) {
82 $db->close();
83
84 return "Table {$table->name} has column {$col->name} with non-native type '{$col->type}'";
85 }
86 }
87 }
88 } catch ( DBError $e ) {
89 return $e->getMessage();
90 }
91 $db->close();
92
93 return true;
94 }
95 }