MediaWiki  1.28.1
DatabaseSqlite.php
Go to the documentation of this file.
1 <?php
28 class DatabaseSqlite extends Database {
30  private static $fulltextEnabled = null;
31 
33  protected $dbDir;
34 
36  protected $dbPath;
37 
39  protected $trxMode;
40 
42  protected $mAffectedRows;
43 
45  protected $mLastResult;
46 
48  protected $mConn;
49 
51  protected $lockMgr;
52 
61  function __construct( array $p ) {
62  if ( isset( $p['dbFilePath'] ) ) {
63  parent::__construct( $p );
64  // Standalone .sqlite file mode.
65  // Super doesn't open when $user is false, but we can work with $dbName,
66  // which is derived from the file path in this case.
67  $this->openFile( $p['dbFilePath'] );
68  $lockDomain = md5( $p['dbFilePath'] );
69  } elseif ( !isset( $p['dbDirectory'] ) ) {
70  throw new InvalidArgumentException( "Need 'dbDirectory' or 'dbFilePath' parameter." );
71  } else {
72  $this->dbDir = $p['dbDirectory'];
73  $this->mDBname = $p['dbname'];
74  $lockDomain = $this->mDBname;
75  // Stock wiki mode using standard file names per DB.
76  parent::__construct( $p );
77  // Super doesn't open when $user is false, but we can work with $dbName
78  if ( $p['dbname'] && !$this->isOpen() ) {
79  if ( $this->open( $p['host'], $p['user'], $p['password'], $p['dbname'] ) ) {
80  $done = [];
81  foreach ( $this->tableAliases as $params ) {
82  if ( isset( $done[$params['dbname']] ) ) {
83  continue;
84  }
85  $this->attachDatabase( $params['dbname'] );
86  $done[$params['dbname']] = 1;
87  }
88  }
89  }
90  }
91 
92  $this->trxMode = isset( $p['trxMode'] ) ? strtoupper( $p['trxMode'] ) : null;
93  if ( $this->trxMode &&
94  !in_array( $this->trxMode, [ 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE' ] )
95  ) {
96  $this->trxMode = null;
97  $this->queryLogger->warning( "Invalid SQLite transaction mode provided." );
98  }
99 
100  $this->lockMgr = new FSLockManager( [
101  'domain' => $lockDomain,
102  'lockDirectory' => "{$this->dbDir}/locks"
103  ] );
104  }
105 
115  public static function newStandaloneInstance( $filename, array $p = [] ) {
116  $p['dbFilePath'] = $filename;
117  $p['schema'] = false;
118  $p['tablePrefix'] = '';
119 
120  return Database::factory( 'sqlite', $p );
121  }
122 
126  function getType() {
127  return 'sqlite';
128  }
129 
135  function implicitGroupby() {
136  return false;
137  }
138 
150  function open( $server, $user, $pass, $dbName ) {
151  $this->close();
152  $fileName = self::generateFileName( $this->dbDir, $dbName );
153  if ( !is_readable( $fileName ) ) {
154  $this->mConn = false;
155  throw new DBConnectionError( $this, "SQLite database not accessible" );
156  }
157  $this->openFile( $fileName );
158 
159  return $this->mConn;
160  }
161 
169  protected function openFile( $fileName ) {
170  $err = false;
171 
172  $this->dbPath = $fileName;
173  try {
174  if ( $this->mFlags & self::DBO_PERSISTENT ) {
175  $this->mConn = new PDO( "sqlite:$fileName", '', '',
176  [ PDO::ATTR_PERSISTENT => true ] );
177  } else {
178  $this->mConn = new PDO( "sqlite:$fileName", '', '' );
179  }
180  } catch ( PDOException $e ) {
181  $err = $e->getMessage();
182  }
183 
184  if ( !$this->mConn ) {
185  $this->queryLogger->debug( "DB connection error: $err\n" );
186  throw new DBConnectionError( $this, $err );
187  }
188 
189  $this->mOpened = !!$this->mConn;
190  if ( $this->mOpened ) {
191  # Set error codes only, don't raise exceptions
192  $this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
193  # Enforce LIKE to be case sensitive, just like MySQL
194  $this->query( 'PRAGMA case_sensitive_like = 1' );
195 
196  return $this->mConn;
197  }
198 
199  return false;
200  }
201 
206  public function getDbFilePath() {
207  return $this->dbPath;
208  }
209 
214  protected function closeConnection() {
215  $this->mConn = null;
216 
217  return true;
218  }
219 
226  public static function generateFileName( $dir, $dbName ) {
227  return "$dir/$dbName.sqlite";
228  }
229 
235  if ( self::$fulltextEnabled === null ) {
236  self::$fulltextEnabled = false;
237  $table = $this->tableName( 'searchindex' );
238  $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__ );
239  if ( $res ) {
240  $row = $res->fetchRow();
241  self::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
242  }
243  }
244 
245  return self::$fulltextEnabled;
246  }
247 
252  static function getFulltextSearchModule() {
253  static $cachedResult = null;
254  if ( $cachedResult !== null ) {
255  return $cachedResult;
256  }
257  $cachedResult = false;
258  $table = 'dummy_search_test';
259 
260  $db = self::newStandaloneInstance( ':memory:' );
261  if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
262  $cachedResult = 'FTS3';
263  }
264  $db->close();
265 
266  return $cachedResult;
267  }
268 
280  function attachDatabase( $name, $file = false, $fname = __METHOD__ ) {
281  if ( !$file ) {
282  $file = self::generateFileName( $this->dbDir, $name );
283  }
284  $file = $this->addQuotes( $file );
285 
286  return $this->query( "ATTACH DATABASE $file AS $name", $fname );
287  }
288 
289  function isWriteQuery( $sql ) {
290  return parent::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
291  }
292 
299  protected function doQuery( $sql ) {
300  $res = $this->mConn->query( $sql );
301  if ( $res === false ) {
302  return false;
303  }
304 
305  $r = $res instanceof ResultWrapper ? $res->result : $res;
306  $this->mAffectedRows = $r->rowCount();
307  $res = new ResultWrapper( $this, $r->fetchAll() );
308 
309  return $res;
310  }
311 
315  function freeResult( $res ) {
316  if ( $res instanceof ResultWrapper ) {
317  $res->result = null;
318  } else {
319  $res = null;
320  }
321  }
322 
327  function fetchObject( $res ) {
328  if ( $res instanceof ResultWrapper ) {
329  $r =& $res->result;
330  } else {
331  $r =& $res;
332  }
333 
334  $cur = current( $r );
335  if ( is_array( $cur ) ) {
336  next( $r );
337  $obj = new stdClass;
338  foreach ( $cur as $k => $v ) {
339  if ( !is_numeric( $k ) ) {
340  $obj->$k = $v;
341  }
342  }
343 
344  return $obj;
345  }
346 
347  return false;
348  }
349 
354  function fetchRow( $res ) {
355  if ( $res instanceof ResultWrapper ) {
356  $r =& $res->result;
357  } else {
358  $r =& $res;
359  }
360  $cur = current( $r );
361  if ( is_array( $cur ) ) {
362  next( $r );
363 
364  return $cur;
365  }
366 
367  return false;
368  }
369 
376  function numRows( $res ) {
377  $r = $res instanceof ResultWrapper ? $res->result : $res;
378 
379  return count( $r );
380  }
381 
386  function numFields( $res ) {
387  $r = $res instanceof ResultWrapper ? $res->result : $res;
388  if ( is_array( $r ) && count( $r ) > 0 ) {
389  // The size of the result array is twice the number of fields. (Bug: 65578)
390  return count( $r[0] ) / 2;
391  } else {
392  // If the result is empty return 0
393  return 0;
394  }
395  }
396 
402  function fieldName( $res, $n ) {
403  $r = $res instanceof ResultWrapper ? $res->result : $res;
404  if ( is_array( $r ) ) {
405  $keys = array_keys( $r[0] );
406 
407  return $keys[$n];
408  }
409 
410  return false;
411  }
412 
420  function tableName( $name, $format = 'quoted' ) {
421  // table names starting with sqlite_ are reserved
422  if ( strpos( $name, 'sqlite_' ) === 0 ) {
423  return $name;
424  }
425 
426  return str_replace( '"', '', parent::tableName( $name, $format ) );
427  }
428 
435  protected function indexName( $index ) {
436  return $index;
437  }
438 
444  function insertId() {
445  // PDO::lastInsertId yields a string :(
446  return intval( $this->mConn->lastInsertId() );
447  }
448 
453  function dataSeek( $res, $row ) {
454  if ( $res instanceof ResultWrapper ) {
455  $r =& $res->result;
456  } else {
457  $r =& $res;
458  }
459  reset( $r );
460  if ( $row > 0 ) {
461  for ( $i = 0; $i < $row; $i++ ) {
462  next( $r );
463  }
464  }
465  }
466 
470  function lastError() {
471  if ( !is_object( $this->mConn ) ) {
472  return "Cannot return last error, no db connection";
473  }
474  $e = $this->mConn->errorInfo();
475 
476  return isset( $e[2] ) ? $e[2] : '';
477  }
478 
482  function lastErrno() {
483  if ( !is_object( $this->mConn ) ) {
484  return "Cannot return last error, no db connection";
485  } else {
486  $info = $this->mConn->errorInfo();
487 
488  return $info[1];
489  }
490  }
491 
495  function affectedRows() {
496  return $this->mAffectedRows;
497  }
498 
509  function indexInfo( $table, $index, $fname = __METHOD__ ) {
510  $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
511  $res = $this->query( $sql, $fname );
512  if ( !$res ) {
513  return null;
514  }
515  if ( $res->numRows() == 0 ) {
516  return false;
517  }
518  $info = [];
519  foreach ( $res as $row ) {
520  $info[] = $row->name;
521  }
522 
523  return $info;
524  }
525 
532  function indexUnique( $table, $index, $fname = __METHOD__ ) {
533  $row = $this->selectRow( 'sqlite_master', '*',
534  [
535  'type' => 'index',
536  'name' => $this->indexName( $index ),
537  ], $fname );
538  if ( !$row || !isset( $row->sql ) ) {
539  return null;
540  }
541 
542  // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
543  $indexPos = strpos( $row->sql, 'INDEX' );
544  if ( $indexPos === false ) {
545  return null;
546  }
547  $firstPart = substr( $row->sql, 0, $indexPos );
548  $options = explode( ' ', $firstPart );
549 
550  return in_array( 'UNIQUE', $options );
551  }
552 
560  foreach ( $options as $k => $v ) {
561  if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' || $v == 'LOCK IN SHARE MODE' ) ) {
562  $options[$k] = '';
563  }
564  }
565 
566  return parent::makeSelectOptions( $options );
567  }
568 
573  protected function makeUpdateOptionsArray( $options ) {
574  $options = parent::makeUpdateOptionsArray( $options );
575  $options = self::fixIgnore( $options );
576 
577  return $options;
578  }
579 
584  static function fixIgnore( $options ) {
585  # SQLite uses OR IGNORE not just IGNORE
586  foreach ( $options as $k => $v ) {
587  if ( $v == 'IGNORE' ) {
588  $options[$k] = 'OR IGNORE';
589  }
590  }
591 
592  return $options;
593  }
594 
600  $options = self::fixIgnore( $options );
601 
602  return parent::makeInsertOptions( $options );
603  }
604 
613  function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
614  if ( !count( $a ) ) {
615  return true;
616  }
617 
618  # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
619  if ( isset( $a[0] ) && is_array( $a[0] ) ) {
620  $ret = true;
621  foreach ( $a as $v ) {
622  if ( !parent::insert( $table, $v, "$fname/multi-row", $options ) ) {
623  $ret = false;
624  }
625  }
626  } else {
627  $ret = parent::insert( $table, $a, "$fname/single-row", $options );
628  }
629 
630  return $ret;
631  }
632 
640  function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
641  if ( !count( $rows ) ) {
642  return true;
643  }
644 
645  # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
646  if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
647  $ret = true;
648  foreach ( $rows as $v ) {
649  if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
650  $ret = false;
651  }
652  }
653  } else {
654  $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
655  }
656 
657  return $ret;
658  }
659 
668  function textFieldSize( $table, $field ) {
669  return -1;
670  }
671 
676  return false;
677  }
678 
684  function unionQueries( $sqls, $all ) {
685  $glue = $all ? ' UNION ALL ' : ' UNION ';
686 
687  return implode( $glue, $sqls );
688  }
689 
693  function wasDeadlock() {
694  return $this->lastErrno() == 5; // SQLITE_BUSY
695  }
696 
700  function wasErrorReissuable() {
701  return $this->lastErrno() == 17; // SQLITE_SCHEMA;
702  }
703 
707  function wasReadOnlyError() {
708  return $this->lastErrno() == 8; // SQLITE_READONLY;
709  }
710 
714  public function getSoftwareLink() {
715  return "[{{int:version-db-sqlite-url}} SQLite]";
716  }
717 
721  function getServerVersion() {
722  $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
723 
724  return $ver;
725  }
726 
735  function fieldInfo( $table, $field ) {
736  $tableName = $this->tableName( $table );
737  $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
738  $res = $this->query( $sql, __METHOD__ );
739  foreach ( $res as $row ) {
740  if ( $row->name == $field ) {
741  return new SQLiteField( $row, $tableName );
742  }
743  }
744 
745  return false;
746  }
747 
748  protected function doBegin( $fname = '' ) {
749  if ( $this->trxMode ) {
750  $this->query( "BEGIN {$this->trxMode}", $fname );
751  } else {
752  $this->query( 'BEGIN', $fname );
753  }
754  $this->mTrxLevel = 1;
755  }
756 
761  function strencode( $s ) {
762  return substr( $this->addQuotes( $s ), 1, -1 );
763  }
764 
769  function encodeBlob( $b ) {
770  return new Blob( $b );
771  }
772 
777  function decodeBlob( $b ) {
778  if ( $b instanceof Blob ) {
779  $b = $b->fetch();
780  }
781 
782  return $b;
783  }
784 
789  function addQuotes( $s ) {
790  if ( $s instanceof Blob ) {
791  return "x'" . bin2hex( $s->fetch() ) . "'";
792  } elseif ( is_bool( $s ) ) {
793  return (int)$s;
794  } elseif ( strpos( $s, "\0" ) !== false ) {
795  // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
796  // This is a known limitation of SQLite's mprintf function which PDO
797  // should work around, but doesn't. I have reported this to php.net as bug #63419:
798  // https://bugs.php.net/bug.php?id=63419
799  // There was already a similar report for SQLite3::escapeString, bug #62361:
800  // https://bugs.php.net/bug.php?id=62361
801  // There is an additional bug regarding sorting this data after insert
802  // on older versions of sqlite shipped with ubuntu 12.04
803  // https://phabricator.wikimedia.org/T74367
804  $this->queryLogger->debug(
805  __FUNCTION__ .
806  ': Quoting value containing null byte. ' .
807  'For consistency all binary data should have been ' .
808  'first processed with self::encodeBlob()'
809  );
810  return "x'" . bin2hex( $s ) . "'";
811  } else {
812  return $this->mConn->quote( $s );
813  }
814  }
815 
819  function buildLike() {
820  $params = func_get_args();
821  if ( count( $params ) > 0 && is_array( $params[0] ) ) {
822  $params = $params[0];
823  }
824 
825  return parent::buildLike( $params ) . "ESCAPE '\' ";
826  }
827 
833  public function buildStringCast( $field ) {
834  return 'CAST ( ' . $field . ' AS TEXT )';
835  }
836 
842  public function deadlockLoop( /*...*/ ) {
843  $args = func_get_args();
844  $function = array_shift( $args );
845 
846  return call_user_func_array( $function, $args );
847  }
848 
853  protected function replaceVars( $s ) {
854  $s = parent::replaceVars( $s );
855  if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
856  // CREATE TABLE hacks to allow schema file sharing with MySQL
857 
858  // binary/varbinary column type -> blob
859  $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
860  // no such thing as unsigned
861  $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
862  // INT -> INTEGER
863  $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
864  // floating point types -> REAL
865  $s = preg_replace(
866  '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
867  'REAL',
868  $s
869  );
870  // varchar -> TEXT
871  $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
872  // TEXT normalization
873  $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
874  // BLOB normalization
875  $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
876  // BOOL -> INTEGER
877  $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
878  // DATETIME -> TEXT
879  $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
880  // No ENUM type
881  $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
882  // binary collation type -> nothing
883  $s = preg_replace( '/\bbinary\b/i', '', $s );
884  // auto_increment -> autoincrement
885  $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
886  // No explicit options
887  $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
888  // AUTOINCREMENT should immedidately follow PRIMARY KEY
889  $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
890  } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
891  // No truncated indexes
892  $s = preg_replace( '/\(\d+\)/', '', $s );
893  // No FULLTEXT
894  $s = preg_replace( '/\bfulltext\b/i', '', $s );
895  } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
896  // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
897  $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
898  } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
899  // INSERT IGNORE --> INSERT OR IGNORE
900  $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
901  }
902 
903  return $s;
904  }
905 
906  public function lock( $lockName, $method, $timeout = 5 ) {
907  if ( !is_dir( "{$this->dbDir}/locks" ) ) { // create dir as needed
908  if ( !is_writable( $this->dbDir ) || !mkdir( "{$this->dbDir}/locks" ) ) {
909  throw new DBError( $this, "Cannot create directory \"{$this->dbDir}/locks\"." );
910  }
911  }
912 
913  return $this->lockMgr->lock( [ $lockName ], LockManager::LOCK_EX, $timeout )->isOK();
914  }
915 
916  public function unlock( $lockName, $method ) {
917  return $this->lockMgr->unlock( [ $lockName ], LockManager::LOCK_EX )->isOK();
918  }
919 
926  function buildConcat( $stringList ) {
927  return '(' . implode( ') || (', $stringList ) . ')';
928  }
929 
930  public function buildGroupConcatField(
931  $delim, $table, $field, $conds = '', $join_conds = []
932  ) {
933  $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
934 
935  return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
936  }
937 
946  function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
947  $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
948  $this->addQuotes( $oldName ) . " AND type='table'", $fname );
949  $obj = $this->fetchObject( $res );
950  if ( !$obj ) {
951  throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
952  }
953  $sql = $obj->sql;
954  $sql = preg_replace(
955  '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/',
956  $this->addIdentifierQuotes( $newName ),
957  $sql,
958  1
959  );
960  if ( $temporary ) {
961  if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
962  $this->queryLogger->debug(
963  "Table $oldName is virtual, can't create a temporary duplicate.\n" );
964  } else {
965  $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
966  }
967  }
968 
969  $res = $this->query( $sql, $fname );
970 
971  // Take over indexes
972  $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
973  foreach ( $indexList as $index ) {
974  if ( strpos( $index->name, 'sqlite_autoindex' ) === 0 ) {
975  continue;
976  }
977 
978  if ( $index->unique ) {
979  $sql = 'CREATE UNIQUE INDEX';
980  } else {
981  $sql = 'CREATE INDEX';
982  }
983  // Try to come up with a new index name, given indexes have database scope in SQLite
984  $indexName = $newName . '_' . $index->name;
985  $sql .= ' ' . $indexName . ' ON ' . $newName;
986 
987  $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name ) . ')' );
988  $fields = [];
989  foreach ( $indexInfo as $indexInfoRow ) {
990  $fields[$indexInfoRow->seqno] = $indexInfoRow->name;
991  }
992 
993  $sql .= '(' . implode( ',', $fields ) . ')';
994 
995  $this->query( $sql );
996  }
997 
998  return $res;
999  }
1000 
1009  function listTables( $prefix = null, $fname = __METHOD__ ) {
1010  $result = $this->select(
1011  'sqlite_master',
1012  'name',
1013  "type='table'"
1014  );
1015 
1016  $endArray = [];
1017 
1018  foreach ( $result as $table ) {
1019  $vars = get_object_vars( $table );
1020  $table = array_pop( $vars );
1021 
1022  if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1023  if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1024  $endArray[] = $table;
1025  }
1026  }
1027  }
1028 
1029  return $endArray;
1030  }
1031 
1040  public function dropTable( $tableName, $fName = __METHOD__ ) {
1041  if ( !$this->tableExists( $tableName, $fName ) ) {
1042  return false;
1043  }
1044  $sql = "DROP TABLE " . $this->tableName( $tableName );
1045 
1046  return $this->query( $sql, $fName );
1047  }
1048 
1049  protected function requiresDatabaseUser() {
1050  return false; // just a file
1051  }
1052 
1056  public function __toString() {
1057  return 'SQLite ' . (string)$this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
1058  }
1059 }
tableExists($table, $fname=__METHOD__)
Query whether a given table exists.
Definition: Database.php:1418
Database error base class.
Definition: DBError.php:26
the array() calling protocol came about after MediaWiki 1.4rc1.
select($table, $vars, $conds= '', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
Definition: Database.php:1250
Utility classThis allows us to distinguish a blob from a normal string and an array of strings...
Definition: Blob.php:8
addIdentifierQuotes($s)
Quotes an identifier using backticks or "double quotes" depending on the database type...
Definition: Database.php:1998
string $mDBname
Definition: Database.php:65
static factory($dbType, $p=[])
Construct a Database subclass instance given a database type and parameters.
Definition: Database.php:325
if(count($args)==0) $dir
attachDatabase($name, $file=false, $fname=__METHOD__)
Attaches external database to our connection, see http://sqlite.org/lang_attach.html for details...
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1936
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:2102
buildGroupConcatField($delim, $table, $field, $conds= '', $join_conds=[])
Build a GROUP_CONCAT or equivalent statement for a query.
static generateFileName($dir, $dbName)
Generates a database file name.
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition: hooks.txt:177
static getFulltextSearchModule()
Returns version of currently supported SQLite fulltext search module or false if none present...
FSLockManager $lockMgr
(hopefully on the same server as the DB)
tableName($name, $format= 'quoted')
Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks.
buildStringCast($field)
string $dbDir
Directory.
insert($table, $a, $fname=__METHOD__, $options=[])
Based on generic method (parent) with some prior SQLite-sepcific adjustments.
doBegin($fname= '')
insertId()
This must be called after nextSequenceVal.
open($server, $user, $pass, $dbName)
Open an SQLite database and return a resource handle to it NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases.
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like please read the documentation for tableName() and addQuotes().You will need both of them.------------------------------------------------------------------------Basic query optimisation------------------------------------------------------------------------MediaWiki developers who need to write DB queries should have some understanding of databases and the performance issues associated with them.Patches containing unacceptably slow features will not be accepted.Unindexed queries are generally not welcome in MediaWiki
selectRow($table, $vars, $conds, $fname=__METHOD__, $options=[], $join_conds=[])
Single row SELECT wrapper.
Definition: Database.php:1317
listTables($prefix=null, $fname=__METHOD__)
List all tables on the database.
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message.Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item.Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page.Return false to stop further processing of the tag $reader:XMLReader object &$pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision.Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag.Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload.Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports.&$fullInterwikiPrefix:Interwiki prefix, may contain colons.&$pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable.Can be used to lazy-load the import sources list.&$importSources:The value of $wgImportSources.Modify as necessary.See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page.$context:IContextSource object &$pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect.&$title:Title object for the current page &$request:WebRequest &$ignoreRedirect:boolean to skip redirect check &$target:Title/string of redirect target &$article:Article object 'InternalParseBeforeLinks':during Parser's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InternalParseBeforeSanitize':during Parser's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings.Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not.Return true without providing an interwiki to continue interwiki search.$prefix:interwiki prefix we are looking for.&$iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user's email has been invalidated successfully.$user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification.Callee may modify $url and $query, URL will be constructed as $url.$query &$url:URL to index.php &$query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) &$article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() &$ip:IP being check &$result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from &$allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn't match your organization.$addr:The e-mail address entered by the user &$result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user &$result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we're looking for a messages file for &$file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED!Use $magicWords in a file listed in $wgExtensionMessagesFiles instead.Use this to define synonyms of magic words depending of the language &$magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces.Do not use this hook to add namespaces.Use CanonicalNamespaces for that.&$namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED!Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead.Use to define aliases of special pages names depending of the language &$specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names.&$names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page's language links.This is called in various places to allow extensions to define the effective language links for a page.$title:The page's Title.&$links:Associative array mapping language codes to prefixed links of the form"language:title".&$linkFlags:Associative array mapping prefixed links to arrays of flags.Currently unused, but planned to provide support for marking individual language links in the UI, e.g.for featured articles. 'LanguageSelector':Hook to change the language selector available on a page.$out:The output page.$cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED!Use HtmlPageLinkRendererBegin instead.Used when generating internal and interwiki links in Linker::link(), before processing starts.Return false to skip default processing and return $ret.See documentation for Linker::link() for details on the expected meanings of parameters.$skin:the Skin object $target:the Title that the link is pointing to &$html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1934
static newStandaloneInstance($filename, array $p=[])
const DBO_PERSISTENT
Definition: defines.php:11
if($line===false) $args
Definition: cdb.php:64
nativeReplace($table, $rows, $fname)
REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE statement.
Definition: Database.php:2141
openFile($fileName)
Opens a database file.
unlock($lockName, $method)
Release a lock.
makeSelectOptions($options)
Filter the options used in SELECT statements.
string $trxMode
Transaction mode.
close()
Closes a database connection.
Definition: Database.php:705
fieldInfo($table, $field)
Get information about a given field Returns false if the field does not exist.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1046
static bool $fulltextEnabled
Whether full text is enabled.
const LOCK_EX
Definition: LockManager.php:70
$res
Definition: database.txt:21
$params
isOpen()
Is a connection to the database open?
Definition: Database.php:577
makeInsertOptions($options)
selectSQLText($table, $vars, $conds= '', $fname=__METHOD__, $options=[], $join_conds=[])
The equivalent of IDatabase::select() except that the constructed SQL is returned, instead of being immediately executed.
Definition: Database.php:1257
checkForEnabledSearch()
Check if the searchindext table is FTS enabled.
duplicateTableStructure($oldName, $newName, $temporary=false, $fname=__METHOD__)
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
string $dbPath
File name for SQLite database file.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:242
doQuery($sql)
SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result...
deadlockLoop()
No-op version of deadlockLoop.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
indexInfo($table, $index, $fname=__METHOD__)
Returns information about an index Returns false if the index does not exist.
makeUpdateOptionsArray($options)
dataSeek($res, $row)
closeConnection()
Does not actually close the connection, just destroys the reference for GC to do its work...
__construct(array $p)
Additional params include:
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined...
Definition: Setup.php:36
lock($lockName, $method, $timeout=5)
Acquire a named lock.
dropTable($tableName, $fName=__METHOD__)
Override due to no CASCADE support.
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and insert
Definition: hooks.txt:2005
indexName($index)
Index names have DB scope.
replace($table, $uniqueIndexes, $rows, $fname=__METHOD__)
indexUnique($table, $index, $fname=__METHOD__)
$mConn $mConn
PDO.
numRows($res)
The PDO::Statement class implements the array interface so count() will work.
Result wrapper for grabbing data queried from an IDatabase object.
fieldName($res, $n)
textFieldSize($table, $field)
Returns the size of a text field, or -1 for "unlimited" In SQLite this is SQLITE_MAX_LENGTH, by default 1GB.
static fixIgnore($options)
resource $mLastResult
int $mAffectedRows
The number of rows affected as an integer.
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:2159
unionQueries($sqls, $all)
Simple version of LockManager based on using FS lock files.
query($sql, $fname=__METHOD__, $tempIgnore=false)
Run an SQL query and return the result.
Definition: Database.php:829
buildConcat($stringList)
Build a concatenation list to feed into a SQL query.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:300