summaryrefslogtreecommitdiff
path: root/maintenance/sqlite.inc
blob: 1f821917c1b63770853184aaec1a3ae4060e956d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
/**
 * Helper class for sqlite-specific scripts
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @ingroup Maintenance
 */

/**
 * This class contains code common to different SQLite-related maintenance scripts
 */
class Sqlite {

	/**
	 * Checks whether PHP has SQLite support
	 * @return bool
	 */
	public static function isPresent() {
		wfSuppressWarnings();
		$compiled = wfDl( 'pdo_sqlite' );
		wfRestoreWarnings();
		return $compiled;
	}

	/**
	 * Checks given files for correctness of SQL syntax. MySQL DDL will be converted to
	 * SQLite-compatible during processing.
	 * Will throw exceptions on SQL errors
	 * @return mixed true if no error or error string in case of errors
	 */
	public static function checkSqlSyntax( $files ) {
		if ( !Sqlite::isPresent() ) {
			throw new MWException( "Can't check SQL syntax: SQLite not found" );
		}
		if ( !is_array( $files ) ) {
			$files = array( $files );
		}

		$allowedTypes = array_flip( array(
			'integer',
			'real',
			'text',
			'blob', // NULL type is omitted intentionally
		) );

		$db = new DatabaseSqliteStandalone( ':memory:' );
		try {
			foreach ( $files as $file ) {
				$err = $db->sourceFile( $file );
				if ( $err != true ) {
					return $err;
				}
			}

			$tables = $db->query( "SELECT name FROM sqlite_master WHERE type='table'", __METHOD__ );
			foreach ( $tables as $table ) {
				if ( strpos( $table->name, 'sqlite_' ) === 0 ) continue;

				$columns = $db->query( "PRAGMA table_info({$table->name})", __METHOD__ );
				foreach ( $columns as $col ) {
					if ( !isset( $allowedTypes[strtolower( $col->type )] ) ) {
						$db->close();
						return "Table {$table->name} has column {$col->name} with non-native type '{$col->type}'";
					}
				}
			}
		} catch ( DBError $e ) {
			return $e->getMessage();
		}
		$db->close();
		return true;
	}
 };