| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
use Wikimedia\Rdbms\DatabaseSqlite; |
| 25 |
use Wikimedia\Rdbms\DBError; |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
class Sqlite { |
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
public static function isPresent() { |
| 39 |
return extension_loaded( 'pdo_sqlite' ); |
| 40 |
} |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
public static function checkSqlSyntax( $files ) { |
| 50 |
if ( !self::isPresent() ) { |
| 51 |
throw new RuntimeException( "Can't check SQL syntax: SQLite not found" ); |
| 52 |
} |
| 53 |
if ( !is_array( $files ) ) { |
| 54 |
$files = [ $files ]; |
| 55 |
} |
| 56 |
|
| 57 |
$allowedTypes = array_fill_keys( [ |
| 58 |
'integer', |
| 59 |
'real', |
| 60 |
'text', |
| 61 |
'blob', |
| 62 |
|
| 63 |
], true ); |
| 64 |
|
| 65 |
$db = DatabaseSqlite::newStandaloneInstance( ':memory:' ); |
| 66 |
try { |
| 67 |
foreach ( $files as $file ) { |
| 68 |
$err = $db->sourceFile( $file ); |
| 69 |
if ( $err ) { |
| 70 |
return $err; |
| 71 |
} |
| 72 |
} |
| 73 |
|
| 74 |
$tables = $db->query( "SELECT name FROM sqlite_master WHERE type='table'", __METHOD__ ); |
| 75 |
foreach ( $tables as $table ) { |
| 76 |
if ( strpos( $table->name, 'sqlite_' ) === 0 ) { |
| 77 |
continue; |
| 78 |
} |
| 79 |
|
| 80 |
$columns = $db->query( |
| 81 |
'PRAGMA table_info(' . $db->addIdentifierQuotes( $table->name ) . ')', |
| 82 |
__METHOD__ |
| 83 |
); |
| 84 |
foreach ( $columns as $col ) { |
| 85 |
if ( !isset( $allowedTypes[strtolower( $col->type )] ) ) { |
| 86 |
$db->close( __METHOD__ ); |
| 87 |
|
| 88 |
return "Table {$table->name} has column {$col->name} with non-native type '{$col->type}'"; |
| 89 |
} |
| 90 |
} |
| 91 |
} |
| 92 |
} catch ( DBError $e ) { |
| 93 |
return $e->getMessage(); |
| 94 |
} |
| 95 |
$db->close( __METHOD__ ); |
| 96 |
|
| 97 |
return true; |
| 98 |
} |
| 99 |
} |