adodb-sqlite3.inc.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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_sqlite3 extends ADOConnection {
  19. var $databaseType = "sqlite3";
  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. $version = SQLite3::version();
  36. $arr['version'] = $version['versionString'];
  37. $arr['description'] = 'SQLite 3';
  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 $this->_connectionID->lastInsertRowID();
  128. }
  129. function _affectedrows()
  130. {
  131. return $this->_connectionID->changes();
  132. }
  133. function ErrorMsg()
  134. {
  135. if ($this->_logsql) {
  136. return $this->_errorMsg;
  137. }
  138. return ($this->_errorNo) ? $this->ErrorNo() : ''; //**tochange?
  139. }
  140. function ErrorNo()
  141. {
  142. return $this->_connectionID->lastErrorCode(); //**tochange??
  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. $this->_connectionID->createFunction('adodb_date', 'adodb_date', 1);
  152. $this->_connectionID->createFunction('adodb_date2', 'adodb_date2', 2);
  153. }
  154. // returns true or false
  155. function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
  156. {
  157. if (empty($argHostname) && $argDatabasename) {
  158. $argHostname = $argDatabasename;
  159. }
  160. $this->_connectionID = new SQLite3($argHostname);
  161. $this->_createFunctions();
  162. return true;
  163. }
  164. // returns true or false
  165. function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
  166. {
  167. // There's no permanent connect in SQLite3
  168. return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
  169. }
  170. // returns query ID if successful, otherwise false
  171. function _query($sql,$inputarr=false)
  172. {
  173. $rez = $this->_connectionID->query($sql);
  174. if ($rez === false) {
  175. $this->_errorNo = $this->_connectionID->lastErrorCode();
  176. }
  177. // If no data was returned, we don't need to create a real recordset
  178. elseif ($rez->numColumns() == 0) {
  179. $rez->finalize();
  180. $rez = true;
  181. }
  182. return $rez;
  183. }
  184. function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
  185. {
  186. $nrows = (int) $nrows;
  187. $offset = (int) $offset;
  188. $offsetStr = ($offset >= 0) ? " OFFSET $offset" : '';
  189. $limitStr = ($nrows >= 0) ? " LIMIT $nrows" : ($offset >= 0 ? ' LIMIT 999999999' : '');
  190. if ($secs2cache) {
  191. $rs = $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);
  192. } else {
  193. $rs = $this->Execute($sql."$limitStr$offsetStr",$inputarr);
  194. }
  195. return $rs;
  196. }
  197. /*
  198. This algorithm is not very efficient, but works even if table locking
  199. is not available.
  200. Will return false if unable to generate an ID after $MAXLOOPS attempts.
  201. */
  202. var $_genSeqSQL = "create table %s (id integer)";
  203. function GenID($seq='adodbseq',$start=1)
  204. {
  205. // if you have to modify the parameter below, your database is overloaded,
  206. // or you need to implement generation of id's yourself!
  207. $MAXLOOPS = 100;
  208. //$this->debug=1;
  209. while (--$MAXLOOPS>=0) {
  210. @($num = $this->GetOne("select id from $seq"));
  211. if ($num === false) {
  212. $this->Execute(sprintf($this->_genSeqSQL ,$seq));
  213. $start -= 1;
  214. $num = '0';
  215. $ok = $this->Execute("insert into $seq values($start)");
  216. if (!$ok) {
  217. return false;
  218. }
  219. }
  220. $this->Execute("update $seq set id=id+1 where id=$num");
  221. if ($this->affected_rows() > 0) {
  222. $num += 1;
  223. $this->genID = $num;
  224. return $num;
  225. }
  226. }
  227. if ($fn = $this->raiseErrorFn) {
  228. $fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);
  229. }
  230. return false;
  231. }
  232. function CreateSequence($seqname='adodbseq',$start=1)
  233. {
  234. if (empty($this->_genSeqSQL)) {
  235. return false;
  236. }
  237. $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
  238. if (!$ok) {
  239. return false;
  240. }
  241. $start -= 1;
  242. return $this->Execute("insert into $seqname values($start)");
  243. }
  244. var $_dropSeqSQL = 'drop table %s';
  245. function DropSequence($seqname = 'adodbseq')
  246. {
  247. if (empty($this->_dropSeqSQL)) {
  248. return false;
  249. }
  250. return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
  251. }
  252. // returns true or false
  253. function _close()
  254. {
  255. return $this->_connectionID->close();
  256. }
  257. function MetaIndexes($table, $primary = FALSE, $owner = false)
  258. {
  259. $false = false;
  260. // save old fetch mode
  261. global $ADODB_FETCH_MODE;
  262. $save = $ADODB_FETCH_MODE;
  263. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  264. if ($this->fetchMode !== FALSE) {
  265. $savem = $this->SetFetchMode(FALSE);
  266. }
  267. $SQL=sprintf("SELECT name,sql FROM sqlite_master WHERE type='index' AND tbl_name='%s'", strtolower($table));
  268. $rs = $this->Execute($SQL);
  269. if (!is_object($rs)) {
  270. if (isset($savem)) {
  271. $this->SetFetchMode($savem);
  272. }
  273. $ADODB_FETCH_MODE = $save;
  274. return $false;
  275. }
  276. $indexes = array ();
  277. while ($row = $rs->FetchRow()) {
  278. if ($primary && preg_match("/primary/i",$row[1]) == 0) {
  279. continue;
  280. }
  281. if (!isset($indexes[$row[0]])) {
  282. $indexes[$row[0]] = array(
  283. 'unique' => preg_match("/unique/i",$row[1]),
  284. 'columns' => array()
  285. );
  286. }
  287. /**
  288. * There must be a more elegant way of doing this,
  289. * the index elements appear in the SQL statement
  290. * in cols[1] between parentheses
  291. * e.g CREATE UNIQUE INDEX ware_0 ON warehouse (org,warehouse)
  292. */
  293. $cols = explode("(",$row[1]);
  294. $cols = explode(")",$cols[1]);
  295. array_pop($cols);
  296. $indexes[$row[0]]['columns'] = $cols;
  297. }
  298. if (isset($savem)) {
  299. $this->SetFetchMode($savem);
  300. $ADODB_FETCH_MODE = $save;
  301. }
  302. return $indexes;
  303. }
  304. }
  305. /*--------------------------------------------------------------------------------------
  306. Class Name: Recordset
  307. --------------------------------------------------------------------------------------*/
  308. class ADORecordset_sqlite3 extends ADORecordSet {
  309. var $databaseType = "sqlite3";
  310. var $bind = false;
  311. function __construct($queryID,$mode=false)
  312. {
  313. if ($mode === false) {
  314. global $ADODB_FETCH_MODE;
  315. $mode = $ADODB_FETCH_MODE;
  316. }
  317. switch($mode) {
  318. case ADODB_FETCH_NUM:
  319. $this->fetchMode = SQLITE3_NUM;
  320. break;
  321. case ADODB_FETCH_ASSOC:
  322. $this->fetchMode = SQLITE3_ASSOC;
  323. break;
  324. default:
  325. $this->fetchMode = SQLITE3_BOTH;
  326. break;
  327. }
  328. $this->adodbFetchMode = $mode;
  329. $this->_queryID = $queryID;
  330. $this->_inited = true;
  331. $this->fields = array();
  332. if ($queryID) {
  333. $this->_currentRow = 0;
  334. $this->EOF = !$this->_fetch();
  335. @$this->_initrs();
  336. } else {
  337. $this->_numOfRows = 0;
  338. $this->_numOfFields = 0;
  339. $this->EOF = true;
  340. }
  341. return $this->_queryID;
  342. }
  343. function FetchField($fieldOffset = -1)
  344. {
  345. $fld = new ADOFieldObject;
  346. $fld->name = $this->_queryID->columnName($fieldOffset);
  347. $fld->type = 'VARCHAR';
  348. $fld->max_length = -1;
  349. return $fld;
  350. }
  351. function _initrs()
  352. {
  353. $this->_numOfFields = $this->_queryID->numColumns();
  354. }
  355. function Fields($colname)
  356. {
  357. if ($this->fetchMode != SQLITE3_NUM) {
  358. return $this->fields[$colname];
  359. }
  360. if (!$this->bind) {
  361. $this->bind = array();
  362. for ($i=0; $i < $this->_numOfFields; $i++) {
  363. $o = $this->FetchField($i);
  364. $this->bind[strtoupper($o->name)] = $i;
  365. }
  366. }
  367. return $this->fields[$this->bind[strtoupper($colname)]];
  368. }
  369. function _seek($row)
  370. {
  371. // sqlite3 does not implement seek
  372. if ($this->debug) {
  373. ADOConnection::outp("SQLite3 does not implement seek");
  374. }
  375. return false;
  376. }
  377. function _fetch($ignore_fields=false)
  378. {
  379. $this->fields = $this->_queryID->fetchArray($this->fetchMode);
  380. return !empty($this->fields);
  381. }
  382. function _close()
  383. {
  384. }
  385. }