DatabaseSqlite.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. <?php
  2. /**
  3. * This script is the SQLite database abstraction layer
  4. *
  5. * See maintenance/sqlite/README for development notes and other specific information
  6. * @ingroup Database
  7. * @file
  8. */
  9. /**
  10. * @ingroup Database
  11. */
  12. class DatabaseSqlite extends Database {
  13. var $mAffectedRows;
  14. var $mLastResult;
  15. var $mDatabaseFile;
  16. var $mName;
  17. /**
  18. * Constructor
  19. */
  20. function __construct($server = false, $user = false, $password = false, $dbName = false, $failFunction = false, $flags = 0) {
  21. global $wgOut,$wgSQLiteDataDir, $wgSQLiteDataDirMode;
  22. if ("$wgSQLiteDataDir" == '') $wgSQLiteDataDir = dirname($_SERVER['DOCUMENT_ROOT']).'/data';
  23. if (!is_dir($wgSQLiteDataDir)) wfMkdirParents( $wgSQLiteDataDir, $wgSQLiteDataDirMode );
  24. $this->mFailFunction = $failFunction;
  25. $this->mFlags = $flags;
  26. $this->mDatabaseFile = "$wgSQLiteDataDir/$dbName.sqlite";
  27. $this->mName = $dbName;
  28. $this->open($server, $user, $password, $dbName);
  29. }
  30. /**
  31. * todo: check if these should be true like parent class
  32. */
  33. function implicitGroupby() { return false; }
  34. function implicitOrderby() { return false; }
  35. static function newFromParams($server, $user, $password, $dbName, $failFunction = false, $flags = 0) {
  36. return new DatabaseSqlite($server, $user, $password, $dbName, $failFunction, $flags);
  37. }
  38. /** Open an SQLite database and return a resource handle to it
  39. * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
  40. */
  41. function open($server,$user,$pass,$dbName) {
  42. $this->mConn = false;
  43. if ($dbName) {
  44. $file = $this->mDatabaseFile;
  45. try {
  46. if ( $this->mFlags & DBO_PERSISTENT ) {
  47. $this->mConn = new PDO( "sqlite:$file", $user, $pass,
  48. array( PDO::ATTR_PERSISTENT => true ) );
  49. } else {
  50. $this->mConn = new PDO( "sqlite:$file", $user, $pass );
  51. }
  52. } catch ( PDOException $e ) {
  53. $err = $e->getMessage();
  54. }
  55. if ( $this->mConn === false ) {
  56. wfDebug( "DB connection error: $err\n" );
  57. if ( !$this->mFailFunction ) {
  58. throw new DBConnectionError( $this, $err );
  59. } else {
  60. return false;
  61. }
  62. }
  63. $this->mOpened = $this->mConn;
  64. # set error codes only, don't raise exceptions
  65. $this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
  66. }
  67. return $this->mConn;
  68. }
  69. /**
  70. * Close an SQLite database
  71. */
  72. function close() {
  73. $this->mOpened = false;
  74. if (is_object($this->mConn)) {
  75. if ($this->trxLevel()) $this->immediateCommit();
  76. $this->mConn = null;
  77. }
  78. return true;
  79. }
  80. /**
  81. * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
  82. */
  83. function doQuery($sql) {
  84. $res = $this->mConn->query($sql);
  85. if ($res === false) {
  86. return false;
  87. } else {
  88. $r = $res instanceof ResultWrapper ? $res->result : $res;
  89. $this->mAffectedRows = $r->rowCount();
  90. $res = new ResultWrapper($this,$r->fetchAll());
  91. }
  92. return $res;
  93. }
  94. function freeResult($res) {
  95. if ($res instanceof ResultWrapper) $res->result = NULL; else $res = NULL;
  96. }
  97. function fetchObject($res) {
  98. if ($res instanceof ResultWrapper) $r =& $res->result; else $r =& $res;
  99. $cur = current($r);
  100. if (is_array($cur)) {
  101. next($r);
  102. $obj = new stdClass;
  103. foreach ($cur as $k => $v) if (!is_numeric($k)) $obj->$k = $v;
  104. return $obj;
  105. }
  106. return false;
  107. }
  108. function fetchRow($res) {
  109. if ($res instanceof ResultWrapper) $r =& $res->result; else $r =& $res;
  110. $cur = current($r);
  111. if (is_array($cur)) {
  112. next($r);
  113. return $cur;
  114. }
  115. return false;
  116. }
  117. /**
  118. * The PDO::Statement class implements the array interface so count() will work
  119. */
  120. function numRows($res) {
  121. $r = $res instanceof ResultWrapper ? $res->result : $res;
  122. return count($r);
  123. }
  124. function numFields($res) {
  125. $r = $res instanceof ResultWrapper ? $res->result : $res;
  126. return is_array($r) ? count($r[0]) : 0;
  127. }
  128. function fieldName($res,$n) {
  129. $r = $res instanceof ResultWrapper ? $res->result : $res;
  130. if (is_array($r)) {
  131. $keys = array_keys($r[0]);
  132. return $keys[$n];
  133. }
  134. return false;
  135. }
  136. /**
  137. * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
  138. */
  139. function tableName($name) {
  140. return str_replace('`','',parent::tableName($name));
  141. }
  142. /**
  143. * Index names have DB scope
  144. */
  145. function indexName( $index ) {
  146. return $index;
  147. }
  148. /**
  149. * This must be called after nextSequenceVal
  150. */
  151. function insertId() {
  152. return $this->mConn->lastInsertId();
  153. }
  154. function dataSeek($res,$row) {
  155. if ($res instanceof ResultWrapper) $r =& $res->result; else $r =& $res;
  156. reset($r);
  157. if ($row > 0) for ($i = 0; $i < $row; $i++) next($r);
  158. }
  159. function lastError() {
  160. if (!is_object($this->mConn)) return "Cannot return last error, no db connection";
  161. $e = $this->mConn->errorInfo();
  162. return isset($e[2]) ? $e[2] : '';
  163. }
  164. function lastErrno() {
  165. if (!is_object($this->mConn)) {
  166. return "Cannot return last error, no db connection";
  167. } else {
  168. $info = $this->mConn->errorInfo();
  169. return $info[1];
  170. }
  171. }
  172. function affectedRows() {
  173. return $this->mAffectedRows;
  174. }
  175. /**
  176. * Returns information about an index
  177. * Returns false if the index does not exist
  178. * - if errors are explicitly ignored, returns NULL on failure
  179. */
  180. function indexInfo($table, $index, $fname = 'Database::indexExists') {
  181. $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
  182. $res = $this->query( $sql, $fname );
  183. if ( !$res ) {
  184. return null;
  185. }
  186. if ( $res->numRows() == 0 ) {
  187. return false;
  188. }
  189. $info = array();
  190. foreach ( $res as $row ) {
  191. $info[] = $row->name;
  192. }
  193. return $info;
  194. }
  195. function indexUnique($table, $index, $fname = 'Database::indexUnique') {
  196. $row = $this->selectRow( 'sqlite_master', '*',
  197. array(
  198. 'type' => 'index',
  199. 'name' => $this->indexName( $index ),
  200. ), $fname );
  201. if ( !$row || !isset( $row->sql ) ) {
  202. return null;
  203. }
  204. // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
  205. $indexPos = strpos( $row->sql, 'INDEX' );
  206. if ( $indexPos === false ) {
  207. return null;
  208. }
  209. $firstPart = substr( $row->sql, 0, $indexPos );
  210. $options = explode( ' ', $firstPart );
  211. return in_array( 'UNIQUE', $options );
  212. }
  213. /**
  214. * Filter the options used in SELECT statements
  215. */
  216. function makeSelectOptions($options) {
  217. foreach ($options as $k => $v) if (is_numeric($k) && $v == 'FOR UPDATE') $options[$k] = '';
  218. return parent::makeSelectOptions($options);
  219. }
  220. /**
  221. * Based on MySQL method (parent) with some prior SQLite-sepcific adjustments
  222. */
  223. function insert($table, $a, $fname = 'DatabaseSqlite::insert', $options = array()) {
  224. if (!count($a)) return true;
  225. if (!is_array($options)) $options = array($options);
  226. # SQLite uses OR IGNORE not just IGNORE
  227. foreach ($options as $k => $v) if ($v == 'IGNORE') $options[$k] = 'OR IGNORE';
  228. # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
  229. if (isset($a[0]) && is_array($a[0])) {
  230. $ret = true;
  231. foreach ($a as $k => $v) if (!parent::insert($table,$v,"$fname/multi-row",$options)) $ret = false;
  232. }
  233. else $ret = parent::insert($table,$a,"$fname/single-row",$options);
  234. return $ret;
  235. }
  236. /**
  237. * SQLite does not have a "USE INDEX" clause, so return an empty string
  238. */
  239. function useIndexClause($index) {
  240. return '';
  241. }
  242. /**
  243. * Returns the size of a text field, or -1 for "unlimited"
  244. * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
  245. */
  246. function textFieldSize($table, $field) {
  247. return -1;
  248. }
  249. /**
  250. * No low priority option in SQLite
  251. */
  252. function lowPriorityOption() {
  253. return '';
  254. }
  255. /**
  256. * Returns an SQL expression for a simple conditional.
  257. * - uses CASE on SQLite
  258. */
  259. function conditional($cond, $trueVal, $falseVal) {
  260. return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
  261. }
  262. function wasDeadlock() {
  263. return $this->lastErrno() == SQLITE_BUSY;
  264. }
  265. function wasErrorReissuable() {
  266. return $this->lastErrno() == SQLITE_SCHEMA;
  267. }
  268. /**
  269. * @return string wikitext of a link to the server software's web site
  270. */
  271. function getSoftwareLink() {
  272. return "[http://sqlite.org/ SQLite]";
  273. }
  274. /**
  275. * @return string Version information from the database
  276. */
  277. function getServerVersion() {
  278. global $wgContLang;
  279. $ver = $this->mConn->getAttribute(PDO::ATTR_SERVER_VERSION);
  280. return $ver;
  281. }
  282. /**
  283. * Query whether a given column exists in the mediawiki schema
  284. */
  285. function fieldExists($table, $field, $fname = '') {
  286. $info = $this->fieldInfo( $table, $field );
  287. return (bool)$info;
  288. }
  289. /**
  290. * Get information about a given field
  291. * Returns false if the field does not exist.
  292. */
  293. function fieldInfo($table, $field) {
  294. $tableName = $this->tableName( $table );
  295. $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
  296. $res = $this->query( $sql, __METHOD__ );
  297. foreach ( $res as $row ) {
  298. if ( $row->name == $field ) {
  299. return new SQLiteField( $row, $tableName );
  300. }
  301. }
  302. return false;
  303. }
  304. function begin( $fname = '' ) {
  305. if ($this->mTrxLevel == 1) $this->commit();
  306. $this->mConn->beginTransaction();
  307. $this->mTrxLevel = 1;
  308. }
  309. function commit( $fname = '' ) {
  310. if ($this->mTrxLevel == 0) return;
  311. $this->mConn->commit();
  312. $this->mTrxLevel = 0;
  313. }
  314. function rollback( $fname = '' ) {
  315. if ($this->mTrxLevel == 0) return;
  316. $this->mConn->rollBack();
  317. $this->mTrxLevel = 0;
  318. }
  319. function limitResultForUpdate($sql, $num) {
  320. return $this->limitResult( $sql, $num );
  321. }
  322. function strencode($s) {
  323. return substr($this->addQuotes($s),1,-1);
  324. }
  325. function encodeBlob($b) {
  326. return new Blob( $b );
  327. }
  328. function decodeBlob($b) {
  329. if ($b instanceof Blob) {
  330. $b = $b->fetch();
  331. }
  332. return $b;
  333. }
  334. function addQuotes($s) {
  335. if ( $s instanceof Blob ) {
  336. return "x'" . bin2hex( $s->fetch() ) . "'";
  337. } else {
  338. return $this->mConn->quote($s);
  339. }
  340. }
  341. function quote_ident($s) { return $s; }
  342. /**
  343. * Not possible in SQLite
  344. * We have ATTACH_DATABASE but that requires database selectors before the
  345. * table names and in any case is really a different concept to MySQL's USE
  346. */
  347. function selectDB($db) {
  348. if ( $db != $this->mName ) {
  349. throw new MWException( 'selectDB is not implemented in SQLite' );
  350. }
  351. }
  352. /**
  353. * not done
  354. */
  355. public function setTimeout($timeout) { return; }
  356. /**
  357. * No-op for a non-networked database
  358. */
  359. function ping() {
  360. return true;
  361. }
  362. /**
  363. * How lagged is this slave?
  364. */
  365. public function getLag() {
  366. return 0;
  367. }
  368. /**
  369. * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
  370. * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
  371. */
  372. public function setup_database() {
  373. global $IP,$wgSQLiteDataDir,$wgDBTableOptions;
  374. $wgDBTableOptions = '';
  375. # Process common MySQL/SQLite table definitions
  376. $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
  377. if ($err !== true) {
  378. $this->reportQueryError($err,0,$sql,__FUNCTION__);
  379. exit( 1 );
  380. }
  381. # Use DatabasePostgres's code to populate interwiki from MySQL template
  382. $f = fopen("$IP/maintenance/interwiki.sql",'r');
  383. if ($f == false) dieout("<li>Could not find the interwiki.sql file");
  384. $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
  385. while (!feof($f)) {
  386. $line = fgets($f,1024);
  387. $matches = array();
  388. if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) continue;
  389. $this->query("$sql $matches[1],$matches[2])");
  390. }
  391. }
  392. /**
  393. * No-op lock functions
  394. */
  395. public function lock( $lockName, $method ) {
  396. return true;
  397. }
  398. public function unlock( $lockName, $method ) {
  399. return true;
  400. }
  401. public function getSearchEngine() {
  402. return "SearchEngineDummy";
  403. }
  404. /**
  405. * No-op version of deadlockLoop
  406. */
  407. public function deadlockLoop( /*...*/ ) {
  408. $args = func_get_args();
  409. $function = array_shift( $args );
  410. return call_user_func_array( $function, $args );
  411. }
  412. protected function replaceVars( $s ) {
  413. $s = parent::replaceVars( $s );
  414. if ( preg_match( '/^\s*CREATE TABLE/i', $s ) ) {
  415. // CREATE TABLE hacks to allow schema file sharing with MySQL
  416. // binary/varbinary column type -> blob
  417. $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'blob\1', $s );
  418. // no such thing as unsigned
  419. $s = preg_replace( '/\bunsigned\b/i', '', $s );
  420. // INT -> INTEGER for primary keys
  421. $s = preg_replacE( '/\bint\b/i', 'integer', $s );
  422. // No ENUM type
  423. $s = preg_replace( '/enum\([^)]*\)/i', 'blob', $s );
  424. // binary collation type -> nothing
  425. $s = preg_replace( '/\bbinary\b/i', '', $s );
  426. // auto_increment -> autoincrement
  427. $s = preg_replace( '/\bauto_increment\b/i', 'autoincrement', $s );
  428. // No explicit options
  429. $s = preg_replace( '/\)[^)]*$/', ')', $s );
  430. } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
  431. // No truncated indexes
  432. $s = preg_replace( '/\(\d+\)/', '', $s );
  433. // No FULLTEXT
  434. $s = preg_replace( '/\bfulltext\b/i', '', $s );
  435. }
  436. return $s;
  437. }
  438. } // end DatabaseSqlite class
  439. /**
  440. * @ingroup Database
  441. */
  442. class SQLiteField {
  443. private $info, $tableName;
  444. function __construct( $info, $tableName ) {
  445. $this->info = $info;
  446. $this->tableName = $tableName;
  447. }
  448. function name() {
  449. return $this->info->name;
  450. }
  451. function tableName() {
  452. return $this->tableName;
  453. }
  454. function defaultValue() {
  455. if ( is_string( $this->info->dflt_value ) ) {
  456. // Typically quoted
  457. if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
  458. return str_replace( "''", "'", $this->info->dflt_value );
  459. }
  460. }
  461. return $this->info->dflt_value;
  462. }
  463. function maxLength() {
  464. return -1;
  465. }
  466. function nullable() {
  467. // SQLite dynamic types are always nullable
  468. return true;
  469. }
  470. # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
  471. # Suggest removal from base class [TS]
  472. function type() {
  473. return $this->info->type;
  474. }
  475. } // end SQLiteField