MediaWiki  1.27.2
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 ) {
63 
64  $this->dbDir = isset( $p['dbDirectory'] ) ? $p['dbDirectory'] : $wgSQLiteDataDir;
65 
66  if ( isset( $p['dbFilePath'] ) ) {
67  parent::__construct( $p );
68  // Standalone .sqlite file mode.
69  // Super doesn't open when $user is false, but we can work with $dbName,
70  // which is derived from the file path in this case.
71  $this->openFile( $p['dbFilePath'] );
72  } else {
73  $this->mDBname = $p['dbname'];
74  // Stock wiki mode using standard file names per DB.
75  parent::__construct( $p );
76  // Super doesn't open when $user is false, but we can work with $dbName
77  if ( $p['dbname'] && !$this->isOpen() ) {
78  if ( $this->open( $p['host'], $p['user'], $p['password'], $p['dbname'] ) ) {
79  if ( $wgSharedDB ) {
80  $this->attachDatabase( $wgSharedDB );
81  }
82  }
83  }
84  }
85 
86  $this->trxMode = isset( $p['trxMode'] ) ? strtoupper( $p['trxMode'] ) : null;
87  if ( $this->trxMode &&
88  !in_array( $this->trxMode, [ 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE' ] )
89  ) {
90  $this->trxMode = null;
91  wfWarn( "Invalid SQLite transaction mode provided." );
92  }
93 
94  $this->lockMgr = new FSLockManager( [ 'lockDirectory' => "{$this->dbDir}/locks" ] );
95  }
96 
106  public static function newStandaloneInstance( $filename, array $p = [] ) {
107  $p['dbFilePath'] = $filename;
108  $p['schema'] = false;
109  $p['tablePrefix'] = '';
110 
111  return DatabaseBase::factory( 'sqlite', $p );
112  }
113 
117  function getType() {
118  return 'sqlite';
119  }
120 
126  function implicitGroupby() {
127  return false;
128  }
129 
141  function open( $server, $user, $pass, $dbName ) {
142  $this->close();
143  $fileName = self::generateFileName( $this->dbDir, $dbName );
144  if ( !is_readable( $fileName ) ) {
145  $this->mConn = false;
146  throw new DBConnectionError( $this, "SQLite database not accessible" );
147  }
148  $this->openFile( $fileName );
149 
150  return $this->mConn;
151  }
152 
160  protected function openFile( $fileName ) {
161  $err = false;
162 
163  $this->dbPath = $fileName;
164  try {
165  if ( $this->mFlags & DBO_PERSISTENT ) {
166  $this->mConn = new PDO( "sqlite:$fileName", '', '',
167  [ PDO::ATTR_PERSISTENT => true ] );
168  } else {
169  $this->mConn = new PDO( "sqlite:$fileName", '', '' );
170  }
171  } catch ( PDOException $e ) {
172  $err = $e->getMessage();
173  }
174 
175  if ( !$this->mConn ) {
176  wfDebug( "DB connection error: $err\n" );
177  throw new DBConnectionError( $this, $err );
178  }
179 
180  $this->mOpened = !!$this->mConn;
181  if ( $this->mOpened ) {
182  # Set error codes only, don't raise exceptions
183  $this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
184  # Enforce LIKE to be case sensitive, just like MySQL
185  $this->query( 'PRAGMA case_sensitive_like = 1' );
186 
187  return $this->mConn;
188  }
189 
190  return false;
191  }
192 
197  public function getDbFilePath() {
198  return $this->dbPath;
199  }
200 
205  protected function closeConnection() {
206  $this->mConn = null;
207 
208  return true;
209  }
210 
217  public static function generateFileName( $dir, $dbName ) {
218  return "$dir/$dbName.sqlite";
219  }
220 
226  if ( self::$fulltextEnabled === null ) {
227  self::$fulltextEnabled = false;
228  $table = $this->tableName( 'searchindex' );
229  $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__ );
230  if ( $res ) {
231  $row = $res->fetchRow();
232  self::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
233  }
234  }
235 
236  return self::$fulltextEnabled;
237  }
238 
243  static function getFulltextSearchModule() {
244  static $cachedResult = null;
245  if ( $cachedResult !== null ) {
246  return $cachedResult;
247  }
248  $cachedResult = false;
249  $table = 'dummy_search_test';
250 
251  $db = self::newStandaloneInstance( ':memory:' );
252  if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
253  $cachedResult = 'FTS3';
254  }
255  $db->close();
256 
257  return $cachedResult;
258  }
259 
271  function attachDatabase( $name, $file = false, $fname = __METHOD__ ) {
272  if ( !$file ) {
273  $file = self::generateFileName( $this->dbDir, $name );
274  }
275  $file = $this->addQuotes( $file );
276 
277  return $this->query( "ATTACH DATABASE $file AS $name", $fname );
278  }
279 
286  function isWriteQuery( $sql ) {
287  return parent::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
288  }
289 
296  protected function doQuery( $sql ) {
297  $res = $this->mConn->query( $sql );
298  if ( $res === false ) {
299  return false;
300  } else {
301  $r = $res instanceof ResultWrapper ? $res->result : $res;
302  $this->mAffectedRows = $r->rowCount();
303  $res = new ResultWrapper( $this, $r->fetchAll() );
304  }
305 
306  return $res;
307  }
308 
312  function freeResult( $res ) {
313  if ( $res instanceof ResultWrapper ) {
314  $res->result = null;
315  } else {
316  $res = null;
317  }
318  }
319 
324  function fetchObject( $res ) {
325  if ( $res instanceof ResultWrapper ) {
326  $r =& $res->result;
327  } else {
328  $r =& $res;
329  }
330 
331  $cur = current( $r );
332  if ( is_array( $cur ) ) {
333  next( $r );
334  $obj = new stdClass;
335  foreach ( $cur as $k => $v ) {
336  if ( !is_numeric( $k ) ) {
337  $obj->$k = $v;
338  }
339  }
340 
341  return $obj;
342  }
343 
344  return false;
345  }
346 
351  function fetchRow( $res ) {
352  if ( $res instanceof ResultWrapper ) {
353  $r =& $res->result;
354  } else {
355  $r =& $res;
356  }
357  $cur = current( $r );
358  if ( is_array( $cur ) ) {
359  next( $r );
360 
361  return $cur;
362  }
363 
364  return false;
365  }
366 
373  function numRows( $res ) {
374  $r = $res instanceof ResultWrapper ? $res->result : $res;
375 
376  return count( $r );
377  }
378 
383  function numFields( $res ) {
384  $r = $res instanceof ResultWrapper ? $res->result : $res;
385  if ( is_array( $r ) && count( $r ) > 0 ) {
386  // The size of the result array is twice the number of fields. (Bug: 65578)
387  return count( $r[0] ) / 2;
388  } else {
389  // If the result is empty return 0
390  return 0;
391  }
392  }
393 
399  function fieldName( $res, $n ) {
400  $r = $res instanceof ResultWrapper ? $res->result : $res;
401  if ( is_array( $r ) ) {
402  $keys = array_keys( $r[0] );
403 
404  return $keys[$n];
405  }
406 
407  return false;
408  }
409 
417  function tableName( $name, $format = 'quoted' ) {
418  // table names starting with sqlite_ are reserved
419  if ( strpos( $name, 'sqlite_' ) === 0 ) {
420  return $name;
421  }
422 
423  return str_replace( '"', '', parent::tableName( $name, $format ) );
424  }
425 
432  protected function indexName( $index ) {
433  return $index;
434  }
435 
441  function insertId() {
442  // PDO::lastInsertId yields a string :(
443  return intval( $this->mConn->lastInsertId() );
444  }
445 
450  function dataSeek( $res, $row ) {
451  if ( $res instanceof ResultWrapper ) {
452  $r =& $res->result;
453  } else {
454  $r =& $res;
455  }
456  reset( $r );
457  if ( $row > 0 ) {
458  for ( $i = 0; $i < $row; $i++ ) {
459  next( $r );
460  }
461  }
462  }
463 
467  function lastError() {
468  if ( !is_object( $this->mConn ) ) {
469  return "Cannot return last error, no db connection";
470  }
471  $e = $this->mConn->errorInfo();
472 
473  return isset( $e[2] ) ? $e[2] : '';
474  }
475 
479  function lastErrno() {
480  if ( !is_object( $this->mConn ) ) {
481  return "Cannot return last error, no db connection";
482  } else {
483  $info = $this->mConn->errorInfo();
484 
485  return $info[1];
486  }
487  }
488 
492  function affectedRows() {
493  return $this->mAffectedRows;
494  }
495 
506  function indexInfo( $table, $index, $fname = __METHOD__ ) {
507  $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
508  $res = $this->query( $sql, $fname );
509  if ( !$res ) {
510  return null;
511  }
512  if ( $res->numRows() == 0 ) {
513  return false;
514  }
515  $info = [];
516  foreach ( $res as $row ) {
517  $info[] = $row->name;
518  }
519 
520  return $info;
521  }
522 
529  function indexUnique( $table, $index, $fname = __METHOD__ ) {
530  $row = $this->selectRow( 'sqlite_master', '*',
531  [
532  'type' => 'index',
533  'name' => $this->indexName( $index ),
534  ], $fname );
535  if ( !$row || !isset( $row->sql ) ) {
536  return null;
537  }
538 
539  // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
540  $indexPos = strpos( $row->sql, 'INDEX' );
541  if ( $indexPos === false ) {
542  return null;
543  }
544  $firstPart = substr( $row->sql, 0, $indexPos );
545  $options = explode( ' ', $firstPart );
546 
547  return in_array( 'UNIQUE', $options );
548  }
549 
557  foreach ( $options as $k => $v ) {
558  if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' || $v == 'LOCK IN SHARE MODE' ) ) {
559  $options[$k] = '';
560  }
561  }
562 
563  return parent::makeSelectOptions( $options );
564  }
565 
570  protected function makeUpdateOptionsArray( $options ) {
571  $options = parent::makeUpdateOptionsArray( $options );
572  $options = self::fixIgnore( $options );
573 
574  return $options;
575  }
576 
581  static function fixIgnore( $options ) {
582  # SQLite uses OR IGNORE not just IGNORE
583  foreach ( $options as $k => $v ) {
584  if ( $v == 'IGNORE' ) {
585  $options[$k] = 'OR IGNORE';
586  }
587  }
588 
589  return $options;
590  }
591 
597  $options = self::fixIgnore( $options );
598 
599  return parent::makeInsertOptions( $options );
600  }
601 
610  function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
611  if ( !count( $a ) ) {
612  return true;
613  }
614 
615  # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
616  if ( isset( $a[0] ) && is_array( $a[0] ) ) {
617  $ret = true;
618  foreach ( $a as $v ) {
619  if ( !parent::insert( $table, $v, "$fname/multi-row", $options ) ) {
620  $ret = false;
621  }
622  }
623  } else {
624  $ret = parent::insert( $table, $a, "$fname/single-row", $options );
625  }
626 
627  return $ret;
628  }
629 
637  function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
638  if ( !count( $rows ) ) {
639  return true;
640  }
641 
642  # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
643  if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
644  $ret = true;
645  foreach ( $rows as $v ) {
646  if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
647  $ret = false;
648  }
649  }
650  } else {
651  $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
652  }
653 
654  return $ret;
655  }
656 
665  function textFieldSize( $table, $field ) {
666  return -1;
667  }
668 
673  return false;
674  }
675 
681  function unionQueries( $sqls, $all ) {
682  $glue = $all ? ' UNION ALL ' : ' UNION ';
683 
684  return implode( $glue, $sqls );
685  }
686 
690  function wasDeadlock() {
691  return $this->lastErrno() == 5; // SQLITE_BUSY
692  }
693 
697  function wasErrorReissuable() {
698  return $this->lastErrno() == 17; // SQLITE_SCHEMA;
699  }
700 
704  function wasReadOnlyError() {
705  return $this->lastErrno() == 8; // SQLITE_READONLY;
706  }
707 
711  public function getSoftwareLink() {
712  return "[{{int:version-db-sqlite-url}} SQLite]";
713  }
714 
718  function getServerVersion() {
719  $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
720 
721  return $ver;
722  }
723 
727  public function getServerInfo() {
728  return wfMessage( self::getFulltextSearchModule()
729  ? 'sqlite-has-fts'
730  : 'sqlite-no-fts', $this->getServerVersion() )->text();
731  }
732 
741  function fieldInfo( $table, $field ) {
742  $tableName = $this->tableName( $table );
743  $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
744  $res = $this->query( $sql, __METHOD__ );
745  foreach ( $res as $row ) {
746  if ( $row->name == $field ) {
747  return new SQLiteField( $row, $tableName );
748  }
749  }
750 
751  return false;
752  }
753 
754  protected function doBegin( $fname = '' ) {
755  if ( $this->trxMode ) {
756  $this->query( "BEGIN {$this->trxMode}", $fname );
757  } else {
758  $this->query( 'BEGIN', $fname );
759  }
760  $this->mTrxLevel = 1;
761  }
762 
767  function strencode( $s ) {
768  return substr( $this->addQuotes( $s ), 1, -1 );
769  }
770 
775  function encodeBlob( $b ) {
776  return new Blob( $b );
777  }
778 
783  function decodeBlob( $b ) {
784  if ( $b instanceof Blob ) {
785  $b = $b->fetch();
786  }
787 
788  return $b;
789  }
790 
795  function addQuotes( $s ) {
796  if ( $s instanceof Blob ) {
797  return "x'" . bin2hex( $s->fetch() ) . "'";
798  } elseif ( is_bool( $s ) ) {
799  return (int)$s;
800  } elseif ( strpos( $s, "\0" ) !== false ) {
801  // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
802  // This is a known limitation of SQLite's mprintf function which PDO
803  // should work around, but doesn't. I have reported this to php.net as bug #63419:
804  // https://bugs.php.net/bug.php?id=63419
805  // There was already a similar report for SQLite3::escapeString, bug #62361:
806  // https://bugs.php.net/bug.php?id=62361
807  // There is an additional bug regarding sorting this data after insert
808  // on older versions of sqlite shipped with ubuntu 12.04
809  // https://phabricator.wikimedia.org/T74367
810  wfDebugLog(
811  __CLASS__,
812  __FUNCTION__ .
813  ': Quoting value containing null byte. ' .
814  'For consistency all binary data should have been ' .
815  'first processed with self::encodeBlob()'
816  );
817  return "x'" . bin2hex( $s ) . "'";
818  } else {
819  return $this->mConn->quote( $s );
820  }
821  }
822 
826  function buildLike() {
827  $params = func_get_args();
828  if ( count( $params ) > 0 && is_array( $params[0] ) ) {
829  $params = $params[0];
830  }
831 
832  return parent::buildLike( $params ) . "ESCAPE '\' ";
833  }
834 
838  public function getSearchEngine() {
839  return "SearchSqlite";
840  }
841 
847  public function deadlockLoop( /*...*/ ) {
848  $args = func_get_args();
849  $function = array_shift( $args );
850 
851  return call_user_func_array( $function, $args );
852  }
853 
858  protected function replaceVars( $s ) {
859  $s = parent::replaceVars( $s );
860  if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
861  // CREATE TABLE hacks to allow schema file sharing with MySQL
862 
863  // binary/varbinary column type -> blob
864  $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
865  // no such thing as unsigned
866  $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
867  // INT -> INTEGER
868  $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
869  // floating point types -> REAL
870  $s = preg_replace(
871  '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
872  'REAL',
873  $s
874  );
875  // varchar -> TEXT
876  $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
877  // TEXT normalization
878  $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
879  // BLOB normalization
880  $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
881  // BOOL -> INTEGER
882  $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
883  // DATETIME -> TEXT
884  $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
885  // No ENUM type
886  $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
887  // binary collation type -> nothing
888  $s = preg_replace( '/\bbinary\b/i', '', $s );
889  // auto_increment -> autoincrement
890  $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
891  // No explicit options
892  $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
893  // AUTOINCREMENT should immedidately follow PRIMARY KEY
894  $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
895  } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
896  // No truncated indexes
897  $s = preg_replace( '/\(\d+\)/', '', $s );
898  // No FULLTEXT
899  $s = preg_replace( '/\bfulltext\b/i', '', $s );
900  } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
901  // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
902  $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
903  } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
904  // INSERT IGNORE --> INSERT OR IGNORE
905  $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
906  }
907 
908  return $s;
909  }
910 
911  public function lock( $lockName, $method, $timeout = 5 ) {
912  if ( !is_dir( "{$this->dbDir}/locks" ) ) { // create dir as needed
913  if ( !is_writable( $this->dbDir ) || !mkdir( "{$this->dbDir}/locks" ) ) {
914  throw new DBError( "Cannot create directory \"{$this->dbDir}/locks\"." );
915  }
916  }
917 
918  return $this->lockMgr->lock( [ $lockName ], LockManager::LOCK_EX, $timeout )->isOK();
919  }
920 
921  public function unlock( $lockName, $method ) {
922  return $this->lockMgr->unlock( [ $lockName ], LockManager::LOCK_EX )->isOK();
923  }
924 
931  function buildConcat( $stringList ) {
932  return '(' . implode( ') || (', $stringList ) . ')';
933  }
934 
935  public function buildGroupConcatField(
936  $delim, $table, $field, $conds = '', $join_conds = []
937  ) {
938  $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
939 
940  return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
941  }
942 
951  function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
952  $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
953  $this->addQuotes( $oldName ) . " AND type='table'", $fname );
954  $obj = $this->fetchObject( $res );
955  if ( !$obj ) {
956  throw new MWException( "Couldn't retrieve structure for table $oldName" );
957  }
958  $sql = $obj->sql;
959  $sql = preg_replace(
960  '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/',
961  $this->addIdentifierQuotes( $newName ),
962  $sql,
963  1
964  );
965  if ( $temporary ) {
966  if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
967  wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
968  } else {
969  $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
970  }
971  }
972 
973  $res = $this->query( $sql, $fname );
974 
975  // Take over indexes
976  $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
977  foreach ( $indexList as $index ) {
978  if ( strpos( $index->name, 'sqlite_autoindex' ) === 0 ) {
979  continue;
980  }
981 
982  if ( $index->unique ) {
983  $sql = 'CREATE UNIQUE INDEX';
984  } else {
985  $sql = 'CREATE INDEX';
986  }
987  // Try to come up with a new index name, given indexes have database scope in SQLite
988  $indexName = $newName . '_' . $index->name;
989  $sql .= ' ' . $indexName . ' ON ' . $newName;
990 
991  $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name ) . ')' );
992  $fields = [];
993  foreach ( $indexInfo as $indexInfoRow ) {
994  $fields[$indexInfoRow->seqno] = $indexInfoRow->name;
995  }
996 
997  $sql .= '(' . implode( ',', $fields ) . ')';
998 
999  $this->query( $sql );
1000  }
1001 
1002  return $res;
1003  }
1004 
1013  function listTables( $prefix = null, $fname = __METHOD__ ) {
1014  $result = $this->select(
1015  'sqlite_master',
1016  'name',
1017  "type='table'"
1018  );
1019 
1020  $endArray = [];
1021 
1022  foreach ( $result as $table ) {
1023  $vars = get_object_vars( $table );
1024  $table = array_pop( $vars );
1025 
1026  if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1027  if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1028  $endArray[] = $table;
1029  }
1030  }
1031  }
1032 
1033  return $endArray;
1034  }
1035 
1039  public function __toString() {
1040  return 'SQLite ' . (string)$this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
1041  }
1042 
1043 } // end DatabaseSqlite class
1044 
1048 class SQLiteField implements Field {
1049  private $info, $tableName;
1050 
1051  function __construct( $info, $tableName ) {
1052  $this->info = $info;
1053  $this->tableName = $tableName;
1054  }
1055 
1056  function name() {
1057  return $this->info->name;
1058  }
1059 
1060  function tableName() {
1061  return $this->tableName;
1062  }
1063 
1064  function defaultValue() {
1065  if ( is_string( $this->info->dflt_value ) ) {
1066  // Typically quoted
1067  if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
1068  return str_replace( "''", "'", $this->info->dflt_value );
1069  }
1070  }
1071 
1072  return $this->info->dflt_value;
1073  }
1074 
1078  function isNullable() {
1079  return !$this->info->notnull;
1080  }
1081 
1082  function type() {
1083  return $this->info->type;
1084  }
1085 } // end SQLiteField
select($table, $vars, $conds= '', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
Definition: Database.php:1230
$wgSQLiteDataDir
To override default SQLite data directory ($docroot/../data)
Database error base class.
the array() calling protocol came about after MediaWiki 1.4rc1.
Utility classThis allows us to distinguish a blob from a normal string and an array of strings...
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...
type()
Database type.
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1932
const DBO_PERSISTENT
Definition: Defines.php:35
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:1798
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)
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 just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing after in associative array form externallinks including delete and insert
Definition: hooks.txt:1798
tableName($name, $format= 'quoted')
Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks.
string $dbDir
Directory.
Base for all database-specific classes representing information about database fields.
insert($table, $a, $fname=__METHOD__, $options=[])
Based on generic method (parent) with some prior SQLite-sepcific adjustments.
doBegin($fname= '')
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
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
close()
Closes a database connection.
Definition: Database.php:694
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:1237
listTables($prefix=null, $fname=__METHOD__)
List all tables on the database.
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
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':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:1796
static newStandaloneInstance($filename, array $p=[])
if($line===false) $args
Definition: cdb.php:64
__construct($info, $tableName)
wfDebugLog($logGroup, $text, $dest= 'all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not...
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.
wfWarn($msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
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:1004
static bool $fulltextEnabled
Whether full text is enabled.
const LOCK_EX
Definition: LockManager.php:62
$res
Definition: database.txt:21
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 just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock()-offset Set to overwrite offset parameter in $wgRequest set to ''to unsetoffset-wrap String Wrap the message in html(usually something like"&lt
$params
$wgSharedDB
Shared database for multiple wikis.
static factory($dbType, $p=[])
Given a DB type, construct the name of the appropriate child class of DatabaseBase.
Definition: Database.php:580
makeInsertOptions($options)
checkForEnabledSearch()
Check if the searchindext table is FTS enabled.
addIdentifierQuotes($s)
Quotes an identifier using backticks or "double quotes" depending on the database type...
Definition: Database.php:1982
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
selectRow($table, $vars, $conds, $fname=__METHOD__, $options=[], $join_conds=[])
Single row SELECT wrapper.
Definition: Database.php:1288
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.
name()
Field name.
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:35
tableName()
Name of table this field belongs to.
lock($lockName, $method, $timeout=5)
Acquire a named lock.
query($sql, $fname=__METHOD__, $tempIgnore=false)
Run an SQL query and return the result.
Definition: Database.php:780
indexName($index)
Index names have DB scope.
replace($table, $uniqueIndexes, $rows, $fname=__METHOD__)
indexUnique($table, $index, $fname=__METHOD__)
numRows($res)
The PDO::Statement class implements the array interface so count() will work.
Result wrapper for grabbing data queried by someone else.
fieldName($res, $n)
nativeReplace($table, $rows, $fname)
REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE statement.
Definition: Database.php:2111
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
isOpen()
Is a connection to the database open?
Definition: Database.php:404
int $mAffectedRows
The number of rows affected as an integer.
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:1996
unionQueries($sqls, $all)
Simple version of LockManager based on using FS lock files.
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:310