adodb-sqlite.inc.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. <?php
  2. /*
  3. @version v5.20.17 31-Mar-2020
  4. @copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
  5. @copyright (c) 2014 Damien Regad, Mark Newnham and the ADOdb community
  6. Released under both BSD license and Lesser GPL library license.
  7. Whenever there is any discrepancy between the two licenses,
  8. the BSD license will take precedence.
  9. Latest version is available at http://adodb.org/
  10. SQLite info: http://www.hwaci.com/sw/sqlite/
  11. Install Instructions:
  12. ====================
  13. 1. Place this in adodb/drivers
  14. 2. Rename the file, remove the .txt prefix.
  15. */
  16. // security - hide paths
  17. if (!defined('ADODB_DIR')) die();
  18. class ADODB_sqlite extends ADOConnection {
  19. var $databaseType = "sqlite";
  20. var $replaceQuote = "''"; // string to use to replace quotes
  21. var $concat_operator='||';
  22. var $_errorNo = 0;
  23. var $hasLimit = true;
  24. var $hasInsertID = true; /// supports autoincrement ID?
  25. var $hasAffectedRows = true; /// supports affected rows for update/delete?
  26. var $metaTablesSQL = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name";
  27. var $sysDate = "adodb_date('Y-m-d')";
  28. var $sysTimeStamp = "adodb_date('Y-m-d H:i:s')";
  29. var $fmtTimeStamp = "'Y-m-d H:i:s'";
  30. function __construct()
  31. {
  32. }
  33. function ServerInfo()
  34. {
  35. $arr['version'] = sqlite_libversion();
  36. $arr['description'] = 'SQLite ';
  37. $arr['encoding'] = sqlite_libencoding();
  38. return $arr;
  39. }
  40. function BeginTrans()
  41. {
  42. if ($this->transOff) {
  43. return true;
  44. }
  45. $ret = $this->Execute("BEGIN TRANSACTION");
  46. $this->transCnt += 1;
  47. return true;
  48. }
  49. function CommitTrans($ok=true)
  50. {
  51. if ($this->transOff) {
  52. return true;
  53. }
  54. if (!$ok) {
  55. return $this->RollbackTrans();
  56. }
  57. $ret = $this->Execute("COMMIT");
  58. if ($this->transCnt > 0) {
  59. $this->transCnt -= 1;
  60. }
  61. return !empty($ret);
  62. }
  63. function RollbackTrans()
  64. {
  65. if ($this->transOff) {
  66. return true;
  67. }
  68. $ret = $this->Execute("ROLLBACK");
  69. if ($this->transCnt > 0) {
  70. $this->transCnt -= 1;
  71. }
  72. return !empty($ret);
  73. }
  74. // mark newnham
  75. function MetaColumns($table, $normalize=true)
  76. {
  77. global $ADODB_FETCH_MODE;
  78. $false = false;
  79. $save = $ADODB_FETCH_MODE;
  80. $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
  81. if ($this->fetchMode !== false) {
  82. $savem = $this->SetFetchMode(false);
  83. }
  84. $rs = $this->Execute("PRAGMA table_info('$table')");
  85. if (isset($savem)) {
  86. $this->SetFetchMode($savem);
  87. }
  88. if (!$rs) {
  89. $ADODB_FETCH_MODE = $save;
  90. return $false;
  91. }
  92. $arr = array();
  93. while ($r = $rs->FetchRow()) {
  94. $type = explode('(',$r['type']);
  95. $size = '';
  96. if (sizeof($type)==2) {
  97. $size = trim($type[1],')');
  98. }
  99. $fn = strtoupper($r['name']);
  100. $fld = new ADOFieldObject;
  101. $fld->name = $r['name'];
  102. $fld->type = $type[0];
  103. $fld->max_length = $size;
  104. $fld->not_null = $r['notnull'];
  105. $fld->default_value = $r['dflt_value'];
  106. $fld->scale = 0;
  107. if (isset($r['pk']) && $r['pk']) {
  108. $fld->primary_key=1;
  109. }
  110. if ($save == ADODB_FETCH_NUM) {
  111. $arr[] = $fld;
  112. } else {
  113. $arr[strtoupper($fld->name)] = $fld;
  114. }
  115. }
  116. $rs->Close();
  117. $ADODB_FETCH_MODE = $save;
  118. return $arr;
  119. }
  120. function _init($parentDriver)
  121. {
  122. $parentDriver->hasTransactions = false;
  123. $parentDriver->hasInsertID = true;
  124. }
  125. function _insertid()
  126. {
  127. return sqlite_last_insert_rowid($this->_connectionID);
  128. }
  129. function _affectedrows()
  130. {
  131. return sqlite_changes($this->_connectionID);
  132. }
  133. function ErrorMsg()
  134. {
  135. if ($this->_logsql) {
  136. return $this->_errorMsg;
  137. }
  138. return ($this->_errorNo) ? sqlite_error_string($this->_errorNo) : '';
  139. }
  140. function ErrorNo()
  141. {
  142. return $this->_errorNo;
  143. }
  144. function SQLDate($fmt, $col=false)
  145. {
  146. $fmt = $this->qstr($fmt);
  147. return ($col) ? "adodb_date2($fmt,$col)" : "adodb_date($fmt)";
  148. }
  149. function _createFunctions()
  150. {
  151. @sqlite_create_function($this->_connectionID, 'adodb_date', 'adodb_date', 1);
  152. @sqlite_create_function($this->_connectionID, 'adodb_date2', 'adodb_date2', 2);
  153. }
  154. // returns true or false
  155. function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
  156. {
  157. if (!function_exists('sqlite_open')) {
  158. return null;
  159. }
  160. if (empty($argHostname) && $argDatabasename) {
  161. $argHostname = $argDatabasename;
  162. }
  163. $this->_connectionID = sqlite_open($argHostname);
  164. if ($this->_connectionID === false) {
  165. return false;
  166. }
  167. $this->_createFunctions();
  168. return true;
  169. }
  170. // returns true or false
  171. function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
  172. {
  173. if (!function_exists('sqlite_open')) {
  174. return null;
  175. }
  176. if (empty($argHostname) && $argDatabasename) {
  177. $argHostname = $argDatabasename;
  178. }
  179. $this->_connectionID = sqlite_popen($argHostname);
  180. if ($this->_connectionID === false) {
  181. return false;
  182. }
  183. $this->_createFunctions();
  184. return true;
  185. }
  186. // returns query ID if successful, otherwise false
  187. function _query($sql,$inputarr=false)
  188. {
  189. $rez = sqlite_query($sql,$this->_connectionID);
  190. if (!$rez) {
  191. $this->_errorNo = sqlite_last_error($this->_connectionID);
  192. }
  193. // If no data was returned, we don't need to create a real recordset
  194. // Note: this code is untested, as I don't have a sqlite2 setup available
  195. elseif (sqlite_num_fields($rez) == 0) {
  196. $rez = true;
  197. }
  198. return $rez;
  199. }
  200. function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
  201. {
  202. $nrows = (int) $nrows;
  203. $offset = (int) $offset;
  204. $offsetStr = ($offset >= 0) ? " OFFSET $offset" : '';
  205. $limitStr = ($nrows >= 0) ? " LIMIT $nrows" : ($offset >= 0 ? ' LIMIT 999999999' : '');
  206. if ($secs2cache) {
  207. $rs = $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);
  208. } else {
  209. $rs = $this->Execute($sql."$limitStr$offsetStr",$inputarr);
  210. }
  211. return $rs;
  212. }
  213. /*
  214. This algorithm is not very efficient, but works even if table locking
  215. is not available.
  216. Will return false if unable to generate an ID after $MAXLOOPS attempts.
  217. */
  218. var $_genSeqSQL = "create table %s (id integer)";
  219. function GenID($seq='adodbseq',$start=1)
  220. {
  221. // if you have to modify the parameter below, your database is overloaded,
  222. // or you need to implement generation of id's yourself!
  223. $MAXLOOPS = 100;
  224. //$this->debug=1;
  225. while (--$MAXLOOPS>=0) {
  226. @($num = $this->GetOne("select id from $seq"));
  227. if ($num === false) {
  228. $this->Execute(sprintf($this->_genSeqSQL ,$seq));
  229. $start -= 1;
  230. $num = '0';
  231. $ok = $this->Execute("insert into $seq values($start)");
  232. if (!$ok) {
  233. return false;
  234. }
  235. }
  236. $this->Execute("update $seq set id=id+1 where id=$num");
  237. if ($this->affected_rows() > 0) {
  238. $num += 1;
  239. $this->genID = $num;
  240. return $num;
  241. }
  242. }
  243. if ($fn = $this->raiseErrorFn) {
  244. $fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);
  245. }
  246. return false;
  247. }
  248. function CreateSequence($seqname='adodbseq',$start=1)
  249. {
  250. if (empty($this->_genSeqSQL)) {
  251. return false;
  252. }
  253. $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
  254. if (!$ok) {
  255. return false;
  256. }
  257. $start -= 1;
  258. return $this->Execute("insert into $seqname values($start)");
  259. }
  260. var $_dropSeqSQL = 'drop table %s';
  261. function DropSequence($seqname = 'adodbseq')
  262. {
  263. if (empty($this->_dropSeqSQL)) {
  264. return false;
  265. }
  266. return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
  267. }
  268. // returns true or false
  269. function _close()
  270. {
  271. return @sqlite_close($this->_connectionID);
  272. }
  273. function MetaIndexes($table, $primary = FALSE, $owner = false)
  274. {
  275. $false = false;
  276. // save old fetch mode
  277. global $ADODB_FETCH_MODE;
  278. $save = $ADODB_FETCH_MODE;
  279. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  280. if ($this->fetchMode !== FALSE) {
  281. $savem = $this->SetFetchMode(FALSE);
  282. }
  283. $SQL=sprintf("SELECT name,sql FROM sqlite_master WHERE type='index' AND tbl_name='%s'", strtolower($table));
  284. $rs = $this->Execute($SQL);
  285. if (!is_object($rs)) {
  286. if (isset($savem)) {
  287. $this->SetFetchMode($savem);
  288. }
  289. $ADODB_FETCH_MODE = $save;
  290. return $false;
  291. }
  292. $indexes = array ();
  293. while ($row = $rs->FetchRow()) {
  294. if ($primary && preg_match("/primary/i",$row[1]) == 0) {
  295. continue;
  296. }
  297. if (!isset($indexes[$row[0]])) {
  298. $indexes[$row[0]] = array(
  299. 'unique' => preg_match("/unique/i",$row[1]),
  300. 'columns' => array()
  301. );
  302. }
  303. /**
  304. * There must be a more elegant way of doing this,
  305. * the index elements appear in the SQL statement
  306. * in cols[1] between parentheses
  307. * e.g CREATE UNIQUE INDEX ware_0 ON warehouse (org,warehouse)
  308. */
  309. $cols = explode("(",$row[1]);
  310. $cols = explode(")",$cols[1]);
  311. array_pop($cols);
  312. $indexes[$row[0]]['columns'] = $cols;
  313. }
  314. if (isset($savem)) {
  315. $this->SetFetchMode($savem);
  316. $ADODB_FETCH_MODE = $save;
  317. }
  318. return $indexes;
  319. }
  320. }
  321. /*--------------------------------------------------------------------------------------
  322. Class Name: Recordset
  323. --------------------------------------------------------------------------------------*/
  324. class ADORecordset_sqlite extends ADORecordSet {
  325. var $databaseType = "sqlite";
  326. var $bind = false;
  327. function __construct($queryID,$mode=false)
  328. {
  329. if ($mode === false) {
  330. global $ADODB_FETCH_MODE;
  331. $mode = $ADODB_FETCH_MODE;
  332. }
  333. switch($mode) {
  334. case ADODB_FETCH_NUM:
  335. $this->fetchMode = SQLITE_NUM;
  336. break;
  337. case ADODB_FETCH_ASSOC:
  338. $this->fetchMode = SQLITE_ASSOC;
  339. break;
  340. default:
  341. $this->fetchMode = SQLITE_BOTH;
  342. break;
  343. }
  344. $this->adodbFetchMode = $mode;
  345. $this->_queryID = $queryID;
  346. $this->_inited = true;
  347. $this->fields = array();
  348. if ($queryID) {
  349. $this->_currentRow = 0;
  350. $this->EOF = !$this->_fetch();
  351. @$this->_initrs();
  352. } else {
  353. $this->_numOfRows = 0;
  354. $this->_numOfFields = 0;
  355. $this->EOF = true;
  356. }
  357. return $this->_queryID;
  358. }
  359. function FetchField($fieldOffset = -1)
  360. {
  361. $fld = new ADOFieldObject;
  362. $fld->name = sqlite_field_name($this->_queryID, $fieldOffset);
  363. $fld->type = 'VARCHAR';
  364. $fld->max_length = -1;
  365. return $fld;
  366. }
  367. function _initrs()
  368. {
  369. $this->_numOfRows = @sqlite_num_rows($this->_queryID);
  370. $this->_numOfFields = @sqlite_num_fields($this->_queryID);
  371. }
  372. function Fields($colname)
  373. {
  374. if ($this->fetchMode != SQLITE_NUM) {
  375. return $this->fields[$colname];
  376. }
  377. if (!$this->bind) {
  378. $this->bind = array();
  379. for ($i=0; $i < $this->_numOfFields; $i++) {
  380. $o = $this->FetchField($i);
  381. $this->bind[strtoupper($o->name)] = $i;
  382. }
  383. }
  384. return $this->fields[$this->bind[strtoupper($colname)]];
  385. }
  386. function _seek($row)
  387. {
  388. return sqlite_seek($this->_queryID, $row);
  389. }
  390. function _fetch($ignore_fields=false)
  391. {
  392. $this->fields = @sqlite_fetch_array($this->_queryID,$this->fetchMode);
  393. return !empty($this->fields);
  394. }
  395. function _close()
  396. {
  397. }
  398. }