DatabaseSqlite.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  1. <?php
  2. /**
  3. * This is the SQLite database abstraction layer.
  4. * See maintenance/sqlite/README for development notes and other specific information
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License along
  17. * with this program; if not, write to the Free Software Foundation, Inc.,
  18. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. * http://www.gnu.org/copyleft/gpl.html
  20. *
  21. * @file
  22. * @ingroup Database
  23. */
  24. namespace Wikimedia\Rdbms;
  25. use NullLockManager;
  26. use PDO;
  27. use PDOException;
  28. use Exception;
  29. use LockManager;
  30. use FSLockManager;
  31. use RuntimeException;
  32. use stdClass;
  33. /**
  34. * @ingroup Database
  35. */
  36. class DatabaseSqlite extends Database {
  37. /** @var string|null Directory for SQLite database files listed under their DB name */
  38. protected $dbDir;
  39. /** @var string|null Explicit path for the SQLite database file */
  40. protected $dbPath;
  41. /** @var string Transaction mode */
  42. protected $trxMode;
  43. /** @var int The number of rows affected as an integer */
  44. protected $lastAffectedRowCount;
  45. /** @var resource */
  46. protected $lastResultHandle;
  47. /** @var PDO */
  48. protected $conn;
  49. /** @var FSLockManager (hopefully on the same server as the DB) */
  50. protected $lockMgr;
  51. /** @var array List of shared database already attached to this connection */
  52. private $sessionAttachedDbs = [];
  53. /** @var string[] See https://www.sqlite.org/lang_transaction.html */
  54. private static $VALID_TRX_MODES = [ '', 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE' ];
  55. /**
  56. * Additional params include:
  57. * - dbDirectory : directory containing the DB and the lock file directory
  58. * - dbFilePath : use this to force the path of the DB file
  59. * - trxMode : one of (deferred, immediate, exclusive)
  60. * @param array $p
  61. */
  62. public function __construct( array $p ) {
  63. if ( isset( $p['dbFilePath'] ) ) {
  64. $this->dbPath = $p['dbFilePath'];
  65. if ( !strlen( $p['dbname'] ) ) {
  66. $p['dbname'] = self::generateDatabaseName( $this->dbPath );
  67. }
  68. } elseif ( isset( $p['dbDirectory'] ) ) {
  69. $this->dbDir = $p['dbDirectory'];
  70. }
  71. parent::__construct( $p );
  72. $this->trxMode = strtoupper( $p['trxMode'] ?? '' );
  73. $lockDirectory = $this->getLockFileDirectory();
  74. if ( $lockDirectory !== null ) {
  75. $this->lockMgr = new FSLockManager( [
  76. 'domain' => $this->getDomainID(),
  77. 'lockDirectory' => $lockDirectory
  78. ] );
  79. } else {
  80. $this->lockMgr = new NullLockManager( [ 'domain' => $this->getDomainID() ] );
  81. }
  82. }
  83. protected static function getAttributes() {
  84. return [ self::ATTR_DB_LEVEL_LOCKING => true ];
  85. }
  86. /**
  87. * @param string $filename
  88. * @param array $p Options map; supports:
  89. * - flags : (same as __construct counterpart)
  90. * - trxMode : (same as __construct counterpart)
  91. * - dbDirectory : (same as __construct counterpart)
  92. * @return DatabaseSqlite
  93. * @since 1.25
  94. */
  95. public static function newStandaloneInstance( $filename, array $p = [] ) {
  96. $p['dbFilePath'] = $filename;
  97. $p['schema'] = null;
  98. $p['tablePrefix'] = '';
  99. /** @var DatabaseSqlite $db */
  100. $db = Database::factory( 'sqlite', $p );
  101. return $db;
  102. }
  103. /**
  104. * @return string
  105. */
  106. public function getType() {
  107. return 'sqlite';
  108. }
  109. protected function open( $server, $user, $pass, $dbName, $schema, $tablePrefix ) {
  110. $this->close();
  111. // Note that for SQLite, $server, $user, and $pass are ignored
  112. if ( $schema !== null ) {
  113. throw $this->newExceptionAfterConnectError( "Got schema '$schema'; not supported." );
  114. }
  115. if ( $this->dbPath !== null ) {
  116. $path = $this->dbPath;
  117. } elseif ( $this->dbDir !== null ) {
  118. $path = self::generateFileName( $this->dbDir, $dbName );
  119. } else {
  120. throw $this->newExceptionAfterConnectError( "DB path or directory required" );
  121. }
  122. // Check if the database file already exists but is non-readable
  123. if (
  124. !self::isProcessMemoryPath( $path ) &&
  125. file_exists( $path ) &&
  126. !is_readable( $path )
  127. ) {
  128. throw $this->newExceptionAfterConnectError( 'SQLite database file is not readable' );
  129. } elseif ( !in_array( $this->trxMode, self::$VALID_TRX_MODES, true ) ) {
  130. throw $this->newExceptionAfterConnectError( "Got mode '{$this->trxMode}' for BEGIN" );
  131. }
  132. $attributes = [];
  133. if ( $this->getFlag( self::DBO_PERSISTENT ) ) {
  134. // Persistent connections can avoid some schema index reading overhead.
  135. // On the other hand, they can cause horrible contention with DBO_TRX.
  136. if ( $this->getFlag( self::DBO_TRX ) || $this->getFlag( self::DBO_DEFAULT ) ) {
  137. $this->connLogger->warning(
  138. __METHOD__ . ": ignoring DBO_PERSISTENT due to DBO_TRX or DBO_DEFAULT",
  139. $this->getLogContext()
  140. );
  141. } else {
  142. $attributes[PDO::ATTR_PERSISTENT] = true;
  143. }
  144. }
  145. try {
  146. // Open the database file, creating it if it does not yet exist
  147. $this->conn = new PDO( "sqlite:$path", null, null, $attributes );
  148. } catch ( PDOException $e ) {
  149. throw $this->newExceptionAfterConnectError( $e->getMessage() );
  150. }
  151. $this->currentDomain = new DatabaseDomain( $dbName, null, $tablePrefix );
  152. try {
  153. $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_NO_RETRY;
  154. // Enforce LIKE to be case sensitive, just like MySQL
  155. $this->query( 'PRAGMA case_sensitive_like = 1', __METHOD__, $flags );
  156. // Apply optimizations or requirements regarding fsync() usage
  157. $sync = $this->connectionVariables['synchronous'] ?? null;
  158. if ( in_array( $sync, [ 'EXTRA', 'FULL', 'NORMAL', 'OFF' ], true ) ) {
  159. $this->query( "PRAGMA synchronous = $sync", __METHOD__, $flags );
  160. }
  161. $this->attachDatabasesFromTableAliases();
  162. } catch ( Exception $e ) {
  163. throw $this->newExceptionAfterConnectError( $e->getMessage() );
  164. }
  165. }
  166. /**
  167. * @return string|null SQLite DB file path
  168. * @throws DBUnexpectedError
  169. * @since 1.25
  170. */
  171. public function getDbFilePath() {
  172. return $this->dbPath ?? self::generateFileName( $this->dbDir, $this->getDBname() );
  173. }
  174. /**
  175. * @return string|null Lock file directory
  176. */
  177. public function getLockFileDirectory() {
  178. if ( $this->dbPath !== null && !self::isProcessMemoryPath( $this->dbPath ) ) {
  179. return dirname( $this->dbPath ) . '/locks';
  180. } elseif ( $this->dbDir !== null && !self::isProcessMemoryPath( $this->dbDir ) ) {
  181. return $this->dbDir . '/locks';
  182. }
  183. return null;
  184. }
  185. /**
  186. * Does not actually close the connection, just destroys the reference for GC to do its work
  187. * @return bool
  188. */
  189. protected function closeConnection() {
  190. $this->conn = null;
  191. return true;
  192. }
  193. /**
  194. * Generates a database file name. Explicitly public for installer.
  195. * @param string $dir Directory where database resides
  196. * @param string|bool $dbName Database name (or false from Database::factory, validated here)
  197. * @return string
  198. * @throws DBUnexpectedError
  199. */
  200. public static function generateFileName( $dir, $dbName ) {
  201. if ( $dir == '' ) {
  202. throw new DBUnexpectedError( null, __CLASS__ . ": no DB directory specified" );
  203. } elseif ( self::isProcessMemoryPath( $dir ) ) {
  204. throw new DBUnexpectedError(
  205. null,
  206. __CLASS__ . ": cannot use process memory directory '$dir'"
  207. );
  208. } elseif ( !strlen( $dbName ) ) {
  209. throw new DBUnexpectedError( null, __CLASS__ . ": no DB name specified" );
  210. }
  211. return "$dir/$dbName.sqlite";
  212. }
  213. /**
  214. * @param string $path
  215. * @return string
  216. */
  217. private static function generateDatabaseName( $path ) {
  218. if ( preg_match( '/^(:memory:$|file::memory:)/', $path ) ) {
  219. // E.g. "file::memory:?cache=shared" => ":memory":
  220. return ':memory:';
  221. } elseif ( preg_match( '/^file::([^?]+)\?mode=memory(&|$)/', $path, $m ) ) {
  222. // E.g. "file:memdb1?mode=memory" => ":memdb1:"
  223. return ":{$m[1]}:";
  224. } else {
  225. // E.g. "/home/.../some_db.sqlite3" => "some_db"
  226. return preg_replace( '/\.sqlite\d?$/', '', basename( $path ) );
  227. }
  228. }
  229. /**
  230. * @param string $path
  231. * @return bool
  232. */
  233. private static function isProcessMemoryPath( $path ) {
  234. return preg_match( '/^(:memory:$|file:(:memory:|[^?]+\?mode=memory(&|$)))/', $path );
  235. }
  236. /**
  237. * Returns version of currently supported SQLite fulltext search module or false if none present.
  238. * @return string
  239. */
  240. static function getFulltextSearchModule() {
  241. static $cachedResult = null;
  242. if ( $cachedResult !== null ) {
  243. return $cachedResult;
  244. }
  245. $cachedResult = false;
  246. $table = 'dummy_search_test';
  247. $db = self::newStandaloneInstance( ':memory:' );
  248. if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
  249. $cachedResult = 'FTS3';
  250. }
  251. $db->close();
  252. return $cachedResult;
  253. }
  254. /**
  255. * Attaches external database to the connection handle
  256. *
  257. * @see https://sqlite.org/lang_attach.html
  258. *
  259. * @param string $name Database name to be used in queries like
  260. * SELECT foo FROM dbname.table
  261. * @param bool|string $file Database file name. If omitted, will be generated
  262. * using $name and configured data directory
  263. * @param string $fname Calling function name
  264. * @return IResultWrapper
  265. */
  266. public function attachDatabase( $name, $file = false, $fname = __METHOD__ ) {
  267. $file = is_string( $file ) ? $file : self::generateFileName( $this->dbDir, $name );
  268. $encFile = $this->addQuotes( $file );
  269. return $this->query(
  270. "ATTACH DATABASE $encFile AS $name",
  271. $fname,
  272. self::QUERY_IGNORE_DBO_TRX
  273. );
  274. }
  275. protected function isWriteQuery( $sql ) {
  276. return parent::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
  277. }
  278. protected function isTransactableQuery( $sql ) {
  279. return parent::isTransactableQuery( $sql ) && !in_array(
  280. $this->getQueryVerb( $sql ),
  281. [ 'ATTACH', 'PRAGMA' ],
  282. true
  283. );
  284. }
  285. /**
  286. * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
  287. *
  288. * @param string $sql
  289. * @return bool|IResultWrapper
  290. */
  291. protected function doQuery( $sql ) {
  292. $res = $this->getBindingHandle()->query( $sql );
  293. if ( $res === false ) {
  294. return false;
  295. }
  296. $resource = ResultWrapper::unwrap( $res );
  297. $this->lastAffectedRowCount = $resource->rowCount();
  298. $res = new ResultWrapper( $this, $resource->fetchAll() );
  299. return $res;
  300. }
  301. /**
  302. * @param IResultWrapper|mixed $res
  303. */
  304. function freeResult( $res ) {
  305. if ( $res instanceof ResultWrapper ) {
  306. $res->free();
  307. }
  308. }
  309. /**
  310. * @param IResultWrapper|array $res
  311. * @return stdClass|bool
  312. */
  313. function fetchObject( $res ) {
  314. $resource =& ResultWrapper::unwrap( $res );
  315. $cur = current( $resource );
  316. if ( is_array( $cur ) ) {
  317. next( $resource );
  318. $obj = new stdClass;
  319. foreach ( $cur as $k => $v ) {
  320. if ( !is_numeric( $k ) ) {
  321. $obj->$k = $v;
  322. }
  323. }
  324. return $obj;
  325. }
  326. return false;
  327. }
  328. /**
  329. * @param IResultWrapper|mixed $res
  330. * @return array|bool
  331. */
  332. function fetchRow( $res ) {
  333. $resource =& ResultWrapper::unwrap( $res );
  334. $cur = current( $resource );
  335. if ( is_array( $cur ) ) {
  336. next( $resource );
  337. return $cur;
  338. }
  339. return false;
  340. }
  341. /**
  342. * The PDO::Statement class implements the array interface so count() will work
  343. *
  344. * @param IResultWrapper|array|false $res
  345. * @return int
  346. */
  347. function numRows( $res ) {
  348. // false does not implement Countable
  349. $resource = ResultWrapper::unwrap( $res );
  350. return is_array( $resource ) ? count( $resource ) : 0;
  351. }
  352. /**
  353. * @param IResultWrapper $res
  354. * @return int
  355. */
  356. function numFields( $res ) {
  357. $resource = ResultWrapper::unwrap( $res );
  358. if ( is_array( $resource ) && count( $resource ) > 0 ) {
  359. // The size of the result array is twice the number of fields. (T67578)
  360. return count( $resource[0] ) / 2;
  361. } else {
  362. // If the result is empty return 0
  363. return 0;
  364. }
  365. }
  366. /**
  367. * @param IResultWrapper $res
  368. * @param int $n
  369. * @return bool
  370. */
  371. function fieldName( $res, $n ) {
  372. $resource = ResultWrapper::unwrap( $res );
  373. if ( is_array( $resource ) ) {
  374. $keys = array_keys( $resource[0] );
  375. return $keys[$n];
  376. }
  377. return false;
  378. }
  379. protected function doSelectDomain( DatabaseDomain $domain ) {
  380. if ( $domain->getSchema() !== null ) {
  381. throw new DBExpectedError(
  382. $this,
  383. __CLASS__ . ": domain '{$domain->getId()}' has a schema component"
  384. );
  385. }
  386. $database = $domain->getDatabase();
  387. // A null database means "don't care" so leave it as is and update the table prefix
  388. if ( $database === null ) {
  389. $this->currentDomain = new DatabaseDomain(
  390. $this->currentDomain->getDatabase(),
  391. null,
  392. $domain->getTablePrefix()
  393. );
  394. return true;
  395. }
  396. if ( $database !== $this->getDBname() ) {
  397. throw new DBExpectedError(
  398. $this,
  399. __CLASS__ . ": cannot change database (got '$database')"
  400. );
  401. }
  402. return true;
  403. }
  404. /**
  405. * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
  406. *
  407. * @param string $name
  408. * @param string $format
  409. * @return string
  410. */
  411. function tableName( $name, $format = 'quoted' ) {
  412. // table names starting with sqlite_ are reserved
  413. if ( strpos( $name, 'sqlite_' ) === 0 ) {
  414. return $name;
  415. }
  416. return str_replace( '"', '', parent::tableName( $name, $format ) );
  417. }
  418. /**
  419. * This must be called after nextSequenceVal
  420. *
  421. * @return int
  422. */
  423. function insertId() {
  424. // PDO::lastInsertId yields a string :(
  425. return intval( $this->getBindingHandle()->lastInsertId() );
  426. }
  427. /**
  428. * @param IResultWrapper|array $res
  429. * @param int $row
  430. */
  431. function dataSeek( $res, $row ) {
  432. $resource =& ResultWrapper::unwrap( $res );
  433. reset( $resource );
  434. if ( $row > 0 ) {
  435. for ( $i = 0; $i < $row; $i++ ) {
  436. next( $resource );
  437. }
  438. }
  439. }
  440. /**
  441. * @return string
  442. */
  443. function lastError() {
  444. if ( !is_object( $this->conn ) ) {
  445. return "Cannot return last error, no db connection";
  446. }
  447. $e = $this->conn->errorInfo();
  448. return $e[2] ?? '';
  449. }
  450. /**
  451. * @return string
  452. */
  453. function lastErrno() {
  454. if ( !is_object( $this->conn ) ) {
  455. return "Cannot return last error, no db connection";
  456. } else {
  457. $info = $this->conn->errorInfo();
  458. return $info[1];
  459. }
  460. }
  461. /**
  462. * @return int
  463. */
  464. protected function fetchAffectedRowCount() {
  465. return $this->lastAffectedRowCount;
  466. }
  467. function tableExists( $table, $fname = __METHOD__ ) {
  468. $tableRaw = $this->tableName( $table, 'raw' );
  469. if ( isset( $this->sessionTempTables[$tableRaw] ) ) {
  470. return true; // already known to exist
  471. }
  472. $encTable = $this->addQuotes( $tableRaw );
  473. $res = $this->query(
  474. "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable",
  475. __METHOD__,
  476. self::QUERY_IGNORE_DBO_TRX
  477. );
  478. return $res->numRows() ? true : false;
  479. }
  480. /**
  481. * Returns information about an index
  482. * Returns false if the index does not exist
  483. * - if errors are explicitly ignored, returns NULL on failure
  484. *
  485. * @param string $table
  486. * @param string $index
  487. * @param string $fname
  488. * @return array|false
  489. */
  490. function indexInfo( $table, $index, $fname = __METHOD__ ) {
  491. $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
  492. $res = $this->query( $sql, $fname, self::QUERY_IGNORE_DBO_TRX );
  493. if ( !$res || $res->numRows() == 0 ) {
  494. return false;
  495. }
  496. $info = [];
  497. foreach ( $res as $row ) {
  498. $info[] = $row->name;
  499. }
  500. return $info;
  501. }
  502. /**
  503. * @param string $table
  504. * @param string $index
  505. * @param string $fname
  506. * @return bool|null
  507. */
  508. function indexUnique( $table, $index, $fname = __METHOD__ ) {
  509. $row = $this->selectRow( 'sqlite_master', '*',
  510. [
  511. 'type' => 'index',
  512. 'name' => $this->indexName( $index ),
  513. ], $fname );
  514. if ( !$row || !isset( $row->sql ) ) {
  515. return null;
  516. }
  517. // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
  518. $indexPos = strpos( $row->sql, 'INDEX' );
  519. if ( $indexPos === false ) {
  520. return null;
  521. }
  522. $firstPart = substr( $row->sql, 0, $indexPos );
  523. $options = explode( ' ', $firstPart );
  524. return in_array( 'UNIQUE', $options );
  525. }
  526. protected function makeSelectOptions( array $options ) {
  527. // Remove problematic options that the base implementation converts to SQL
  528. foreach ( $options as $k => $v ) {
  529. if ( is_numeric( $k ) && ( $v === 'FOR UPDATE' || $v === 'LOCK IN SHARE MODE' ) ) {
  530. $options[$k] = '';
  531. }
  532. }
  533. return parent::makeSelectOptions( $options );
  534. }
  535. /**
  536. * @param array $options
  537. * @return array
  538. */
  539. protected function makeUpdateOptionsArray( $options ) {
  540. $options = parent::makeUpdateOptionsArray( $options );
  541. $options = self::fixIgnore( $options );
  542. return $options;
  543. }
  544. /**
  545. * @param array $options
  546. * @return array
  547. */
  548. static function fixIgnore( $options ) {
  549. # SQLite uses OR IGNORE not just IGNORE
  550. foreach ( $options as $k => $v ) {
  551. if ( $v == 'IGNORE' ) {
  552. $options[$k] = 'OR IGNORE';
  553. }
  554. }
  555. return $options;
  556. }
  557. /**
  558. * @param array $options
  559. * @return string
  560. */
  561. function makeInsertOptions( $options ) {
  562. $options = self::fixIgnore( $options );
  563. return parent::makeInsertOptions( $options );
  564. }
  565. /**
  566. * Based on generic method (parent) with some prior SQLite-sepcific adjustments
  567. * @param string $table
  568. * @param array $a
  569. * @param string $fname
  570. * @param array $options
  571. * @return bool
  572. */
  573. function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
  574. if ( !count( $a ) ) {
  575. return true;
  576. }
  577. # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
  578. if ( isset( $a[0] ) && is_array( $a[0] ) ) {
  579. $affectedRowCount = 0;
  580. try {
  581. $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
  582. foreach ( $a as $v ) {
  583. parent::insert( $table, $v, "$fname/multi-row", $options );
  584. $affectedRowCount += $this->affectedRows();
  585. }
  586. $this->endAtomic( $fname );
  587. } catch ( Exception $e ) {
  588. $this->cancelAtomic( $fname );
  589. throw $e;
  590. }
  591. $this->affectedRowCount = $affectedRowCount;
  592. } else {
  593. parent::insert( $table, $a, "$fname/single-row", $options );
  594. }
  595. return true;
  596. }
  597. /**
  598. * @param string $table
  599. * @param array $uniqueIndexes Unused
  600. * @param string|array $rows
  601. * @param string $fname
  602. */
  603. function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
  604. if ( !count( $rows ) ) {
  605. return;
  606. }
  607. # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
  608. if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
  609. $affectedRowCount = 0;
  610. try {
  611. $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
  612. foreach ( $rows as $v ) {
  613. $this->nativeReplace( $table, $v, "$fname/multi-row" );
  614. $affectedRowCount += $this->affectedRows();
  615. }
  616. $this->endAtomic( $fname );
  617. } catch ( Exception $e ) {
  618. $this->cancelAtomic( $fname );
  619. throw $e;
  620. }
  621. $this->affectedRowCount = $affectedRowCount;
  622. } else {
  623. $this->nativeReplace( $table, $rows, "$fname/single-row" );
  624. }
  625. }
  626. /**
  627. * Returns the size of a text field, or -1 for "unlimited"
  628. * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
  629. *
  630. * @param string $table
  631. * @param string $field
  632. * @return int
  633. */
  634. function textFieldSize( $table, $field ) {
  635. return -1;
  636. }
  637. /**
  638. * @return bool
  639. */
  640. function unionSupportsOrderAndLimit() {
  641. return false;
  642. }
  643. /**
  644. * @param string[] $sqls
  645. * @param bool $all Whether to "UNION ALL" or not
  646. * @return string
  647. */
  648. function unionQueries( $sqls, $all ) {
  649. $glue = $all ? ' UNION ALL ' : ' UNION ';
  650. return implode( $glue, $sqls );
  651. }
  652. /**
  653. * @return bool
  654. */
  655. function wasDeadlock() {
  656. return $this->lastErrno() == 5; // SQLITE_BUSY
  657. }
  658. /**
  659. * @return bool
  660. */
  661. function wasReadOnlyError() {
  662. return $this->lastErrno() == 8; // SQLITE_READONLY;
  663. }
  664. public function wasConnectionError( $errno ) {
  665. return $errno == 17; // SQLITE_SCHEMA;
  666. }
  667. protected function wasKnownStatementRollbackError() {
  668. // ON CONFLICT ROLLBACK clauses make it so that SQLITE_CONSTRAINT error is
  669. // ambiguous with regard to whether it implies a ROLLBACK or an ABORT happened.
  670. // https://sqlite.org/lang_createtable.html#uniqueconst
  671. // https://sqlite.org/lang_conflict.html
  672. return false;
  673. }
  674. public function serverIsReadOnly() {
  675. $this->assertHasConnectionHandle();
  676. $path = $this->getDbFilePath();
  677. return ( !self::isProcessMemoryPath( $path ) && !is_writable( $path ) );
  678. }
  679. /**
  680. * @return string Wikitext of a link to the server software's web site
  681. */
  682. public function getSoftwareLink() {
  683. return "[{{int:version-db-sqlite-url}} SQLite]";
  684. }
  685. /**
  686. * @return string Version information from the database
  687. */
  688. function getServerVersion() {
  689. $ver = $this->getBindingHandle()->getAttribute( PDO::ATTR_SERVER_VERSION );
  690. return $ver;
  691. }
  692. /**
  693. * Get information about a given field
  694. * Returns false if the field does not exist.
  695. *
  696. * @param string $table
  697. * @param string $field
  698. * @return SQLiteField|bool False on failure
  699. */
  700. function fieldInfo( $table, $field ) {
  701. $tableName = $this->tableName( $table );
  702. $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
  703. $res = $this->query( $sql, __METHOD__, self::QUERY_IGNORE_DBO_TRX );
  704. foreach ( $res as $row ) {
  705. if ( $row->name == $field ) {
  706. return new SQLiteField( $row, $tableName );
  707. }
  708. }
  709. return false;
  710. }
  711. protected function doBegin( $fname = '' ) {
  712. if ( $this->trxMode != '' ) {
  713. $this->query( "BEGIN {$this->trxMode}", $fname );
  714. } else {
  715. $this->query( 'BEGIN', $fname );
  716. }
  717. }
  718. /**
  719. * @param string $s
  720. * @return string
  721. */
  722. function strencode( $s ) {
  723. return substr( $this->addQuotes( $s ), 1, -1 );
  724. }
  725. /**
  726. * @param string $b
  727. * @return Blob
  728. */
  729. function encodeBlob( $b ) {
  730. return new Blob( $b );
  731. }
  732. /**
  733. * @param Blob|string $b
  734. * @return string
  735. */
  736. function decodeBlob( $b ) {
  737. if ( $b instanceof Blob ) {
  738. $b = $b->fetch();
  739. }
  740. return $b;
  741. }
  742. /**
  743. * @param string|int|null|bool|Blob $s
  744. * @return string|int
  745. */
  746. function addQuotes( $s ) {
  747. if ( $s instanceof Blob ) {
  748. return "x'" . bin2hex( $s->fetch() ) . "'";
  749. } elseif ( is_bool( $s ) ) {
  750. return (int)$s;
  751. } elseif ( strpos( (string)$s, "\0" ) !== false ) {
  752. // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
  753. // This is a known limitation of SQLite's mprintf function which PDO
  754. // should work around, but doesn't. I have reported this to php.net as bug #63419:
  755. // https://bugs.php.net/bug.php?id=63419
  756. // There was already a similar report for SQLite3::escapeString, bug #62361:
  757. // https://bugs.php.net/bug.php?id=62361
  758. // There is an additional bug regarding sorting this data after insert
  759. // on older versions of sqlite shipped with ubuntu 12.04
  760. // https://phabricator.wikimedia.org/T74367
  761. $this->queryLogger->debug(
  762. __FUNCTION__ .
  763. ': Quoting value containing null byte. ' .
  764. 'For consistency all binary data should have been ' .
  765. 'first processed with self::encodeBlob()'
  766. );
  767. return "x'" . bin2hex( (string)$s ) . "'";
  768. } else {
  769. return $this->getBindingHandle()->quote( (string)$s );
  770. }
  771. }
  772. public function buildSubstring( $input, $startPosition, $length = null ) {
  773. $this->assertBuildSubstringParams( $startPosition, $length );
  774. $params = [ $input, $startPosition ];
  775. if ( $length !== null ) {
  776. $params[] = $length;
  777. }
  778. return 'SUBSTR(' . implode( ',', $params ) . ')';
  779. }
  780. /**
  781. * @param string $field Field or column to cast
  782. * @return string
  783. * @since 1.28
  784. */
  785. public function buildStringCast( $field ) {
  786. return 'CAST ( ' . $field . ' AS TEXT )';
  787. }
  788. /**
  789. * No-op version of deadlockLoop
  790. *
  791. * @return mixed
  792. */
  793. public function deadlockLoop( /*...*/ ) {
  794. $args = func_get_args();
  795. $function = array_shift( $args );
  796. return $function( ...$args );
  797. }
  798. /**
  799. * @param string $s
  800. * @return string
  801. */
  802. protected function replaceVars( $s ) {
  803. $s = parent::replaceVars( $s );
  804. if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
  805. // CREATE TABLE hacks to allow schema file sharing with MySQL
  806. // binary/varbinary column type -> blob
  807. $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
  808. // no such thing as unsigned
  809. $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
  810. // INT -> INTEGER
  811. $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
  812. // floating point types -> REAL
  813. $s = preg_replace(
  814. '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
  815. 'REAL',
  816. $s
  817. );
  818. // varchar -> TEXT
  819. $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
  820. // TEXT normalization
  821. $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
  822. // BLOB normalization
  823. $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
  824. // BOOL -> INTEGER
  825. $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
  826. // DATETIME -> TEXT
  827. $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
  828. // No ENUM type
  829. $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
  830. // binary collation type -> nothing
  831. $s = preg_replace( '/\bbinary\b/i', '', $s );
  832. // auto_increment -> autoincrement
  833. $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
  834. // No explicit options
  835. $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
  836. // AUTOINCREMENT should immedidately follow PRIMARY KEY
  837. $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
  838. } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
  839. // No truncated indexes
  840. $s = preg_replace( '/\(\d+\)/', '', $s );
  841. // No FULLTEXT
  842. $s = preg_replace( '/\bfulltext\b/i', '', $s );
  843. } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
  844. // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
  845. $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
  846. } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
  847. // INSERT IGNORE --> INSERT OR IGNORE
  848. $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
  849. }
  850. return $s;
  851. }
  852. public function lock( $lockName, $method, $timeout = 5 ) {
  853. $status = $this->lockMgr->lock( [ $lockName ], LockManager::LOCK_EX, $timeout );
  854. if (
  855. $this->lockMgr instanceof FSLockManager &&
  856. $status->hasMessage( 'lockmanager-fail-openlock' )
  857. ) {
  858. throw new DBError( $this, "Cannot create directory \"{$this->getLockFileDirectory()}\"" );
  859. }
  860. return $status->isOK();
  861. }
  862. public function unlock( $lockName, $method ) {
  863. return $this->lockMgr->unlock( [ $lockName ], LockManager::LOCK_EX )->isGood();
  864. }
  865. /**
  866. * Build a concatenation list to feed into a SQL query
  867. *
  868. * @param string[] $stringList
  869. * @return string
  870. */
  871. function buildConcat( $stringList ) {
  872. return '(' . implode( ') || (', $stringList ) . ')';
  873. }
  874. public function buildGroupConcatField(
  875. $delim, $table, $field, $conds = '', $join_conds = []
  876. ) {
  877. $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
  878. return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
  879. }
  880. /**
  881. * @param string $oldName
  882. * @param string $newName
  883. * @param bool $temporary
  884. * @param string $fname
  885. * @return bool|IResultWrapper
  886. * @throws RuntimeException
  887. */
  888. function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
  889. $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
  890. $this->addQuotes( $oldName ) . " AND type='table'", $fname );
  891. $obj = $this->fetchObject( $res );
  892. if ( !$obj ) {
  893. throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
  894. }
  895. $sql = $obj->sql;
  896. $sql = preg_replace(
  897. '/(?<=\W)"?' .
  898. preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ), '/' ) .
  899. '"?(?=\W)/',
  900. $this->addIdentifierQuotes( $newName ),
  901. $sql,
  902. 1
  903. );
  904. if ( $temporary ) {
  905. if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
  906. $this->queryLogger->debug(
  907. "Table $oldName is virtual, can't create a temporary duplicate.\n" );
  908. } else {
  909. $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
  910. }
  911. }
  912. $res = $this->query( $sql, $fname, self::QUERY_PSEUDO_PERMANENT );
  913. // Take over indexes
  914. $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
  915. foreach ( $indexList as $index ) {
  916. if ( strpos( $index->name, 'sqlite_autoindex' ) === 0 ) {
  917. continue;
  918. }
  919. if ( $index->unique ) {
  920. $sql = 'CREATE UNIQUE INDEX';
  921. } else {
  922. $sql = 'CREATE INDEX';
  923. }
  924. // Try to come up with a new index name, given indexes have database scope in SQLite
  925. $indexName = $newName . '_' . $index->name;
  926. $sql .= ' ' . $indexName . ' ON ' . $newName;
  927. $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name ) . ')' );
  928. $fields = [];
  929. foreach ( $indexInfo as $indexInfoRow ) {
  930. $fields[$indexInfoRow->seqno] = $indexInfoRow->name;
  931. }
  932. $sql .= '(' . implode( ',', $fields ) . ')';
  933. $this->query( $sql );
  934. }
  935. return $res;
  936. }
  937. /**
  938. * List all tables on the database
  939. *
  940. * @param string|null $prefix Only show tables with this prefix, e.g. mw_
  941. * @param string $fname Calling function name
  942. *
  943. * @return array
  944. */
  945. function listTables( $prefix = null, $fname = __METHOD__ ) {
  946. $result = $this->select(
  947. 'sqlite_master',
  948. 'name',
  949. "type='table'"
  950. );
  951. $endArray = [];
  952. foreach ( $result as $table ) {
  953. $vars = get_object_vars( $table );
  954. $table = array_pop( $vars );
  955. if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
  956. if ( strpos( $table, 'sqlite_' ) !== 0 ) {
  957. $endArray[] = $table;
  958. }
  959. }
  960. }
  961. return $endArray;
  962. }
  963. /**
  964. * Override due to no CASCADE support
  965. *
  966. * @param string $tableName
  967. * @param string $fName
  968. * @return bool|IResultWrapper
  969. * @throws DBReadOnlyError
  970. */
  971. public function dropTable( $tableName, $fName = __METHOD__ ) {
  972. if ( !$this->tableExists( $tableName, $fName ) ) {
  973. return false;
  974. }
  975. $sql = "DROP TABLE " . $this->tableName( $tableName );
  976. return $this->query( $sql, $fName, self::QUERY_IGNORE_DBO_TRX );
  977. }
  978. public function setTableAliases( array $aliases ) {
  979. parent::setTableAliases( $aliases );
  980. if ( $this->isOpen() ) {
  981. $this->attachDatabasesFromTableAliases();
  982. }
  983. }
  984. /**
  985. * Issue ATTATCH statements for all unattached foreign DBs in table aliases
  986. */
  987. private function attachDatabasesFromTableAliases() {
  988. foreach ( $this->tableAliases as $params ) {
  989. if (
  990. $params['dbname'] !== $this->getDBname() &&
  991. !isset( $this->sessionAttachedDbs[$params['dbname']] )
  992. ) {
  993. $this->attachDatabase( $params['dbname'] );
  994. $this->sessionAttachedDbs[$params['dbname']] = true;
  995. }
  996. }
  997. }
  998. public function resetSequenceForTable( $table, $fname = __METHOD__ ) {
  999. $encTable = $this->addIdentifierQuotes( 'sqlite_sequence' );
  1000. $encName = $this->addQuotes( $this->tableName( $table, 'raw' ) );
  1001. $this->query(
  1002. "DELETE FROM $encTable WHERE name = $encName",
  1003. $fname,
  1004. self::QUERY_IGNORE_DBO_TRX
  1005. );
  1006. }
  1007. public function databasesAreIndependent() {
  1008. return true;
  1009. }
  1010. protected function doHandleSessionLossPreconnect() {
  1011. $this->sessionAttachedDbs = [];
  1012. }
  1013. /**
  1014. * @return PDO
  1015. */
  1016. protected function getBindingHandle() {
  1017. return parent::getBindingHandle();
  1018. }
  1019. }
  1020. /**
  1021. * @deprecated since 1.29
  1022. */
  1023. class_alias( DatabaseSqlite::class, 'DatabaseSqlite' );