summaryrefslogtreecommitdiff
path: root/maintenance/sqlite.inc
blob: 238fe82bce5a30ab09134eb6fc5ff85651c85899 (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
<?php

/**
 * 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;
	}
 };