PageRenderTime 27ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/libs/adodb5/drivers/adodb-sqlite3.inc.php

https://gitlab.com/mrktinh/bookonline
PHP | 438 lines | 342 code | 51 blank | 45 comment | 49 complexity | 403e157d8b0bc7ef5396d843fd87021e MD5 | raw file
  1. <?php
  2. /*
  3. @version v5.20.4 30-Mar-2016
  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.sourceforge.net
  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. $offsetStr = ($offset >= 0) ? " OFFSET $offset" : '';
  187. $limitStr = ($nrows >= 0) ? " LIMIT $nrows" : ($offset >= 0 ? ' LIMIT 999999999' : '');
  188. if ($secs2cache) {
  189. $rs = $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);
  190. } else {
  191. $rs = $this->Execute($sql."$limitStr$offsetStr",$inputarr);
  192. }
  193. return $rs;
  194. }
  195. /*
  196. This algorithm is not very efficient, but works even if table locking
  197. is not available.
  198. Will return false if unable to generate an ID after $MAXLOOPS attempts.
  199. */
  200. var $_genSeqSQL = "create table %s (id integer)";
  201. function GenID($seq='adodbseq',$start=1)
  202. {
  203. // if you have to modify the parameter below, your database is overloaded,
  204. // or you need to implement generation of id's yourself!
  205. $MAXLOOPS = 100;
  206. //$this->debug=1;
  207. while (--$MAXLOOPS>=0) {
  208. @($num = $this->GetOne("select id from $seq"));
  209. if ($num === false) {
  210. $this->Execute(sprintf($this->_genSeqSQL ,$seq));
  211. $start -= 1;
  212. $num = '0';
  213. $ok = $this->Execute("insert into $seq values($start)");
  214. if (!$ok) {
  215. return false;
  216. }
  217. }
  218. $this->Execute("update $seq set id=id+1 where id=$num");
  219. if ($this->affected_rows() > 0) {
  220. $num += 1;
  221. $this->genID = $num;
  222. return $num;
  223. }
  224. }
  225. if ($fn = $this->raiseErrorFn) {
  226. $fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);
  227. }
  228. return false;
  229. }
  230. function CreateSequence($seqname='adodbseq',$start=1)
  231. {
  232. if (empty($this->_genSeqSQL)) {
  233. return false;
  234. }
  235. $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
  236. if (!$ok) {
  237. return false;
  238. }
  239. $start -= 1;
  240. return $this->Execute("insert into $seqname values($start)");
  241. }
  242. var $_dropSeqSQL = 'drop table %s';
  243. function DropSequence($seqname = 'adodbseq')
  244. {
  245. if (empty($this->_dropSeqSQL)) {
  246. return false;
  247. }
  248. return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
  249. }
  250. // returns true or false
  251. function _close()
  252. {
  253. return $this->_connectionID->close();
  254. }
  255. function MetaIndexes($table, $primary = FALSE, $owner = false)
  256. {
  257. $false = false;
  258. // save old fetch mode
  259. global $ADODB_FETCH_MODE;
  260. $save = $ADODB_FETCH_MODE;
  261. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  262. if ($this->fetchMode !== FALSE) {
  263. $savem = $this->SetFetchMode(FALSE);
  264. }
  265. $SQL=sprintf("SELECT name,sql FROM sqlite_master WHERE type='index' AND tbl_name='%s'", strtolower($table));
  266. $rs = $this->Execute($SQL);
  267. if (!is_object($rs)) {
  268. if (isset($savem)) {
  269. $this->SetFetchMode($savem);
  270. }
  271. $ADODB_FETCH_MODE = $save;
  272. return $false;
  273. }
  274. $indexes = array ();
  275. while ($row = $rs->FetchRow()) {
  276. if ($primary && preg_match("/primary/i",$row[1]) == 0) {
  277. continue;
  278. }
  279. if (!isset($indexes[$row[0]])) {
  280. $indexes[$row[0]] = array(
  281. 'unique' => preg_match("/unique/i",$row[1]),
  282. 'columns' => array()
  283. );
  284. }
  285. /**
  286. * There must be a more elegant way of doing this,
  287. * the index elements appear in the SQL statement
  288. * in cols[1] between parentheses
  289. * e.g CREATE UNIQUE INDEX ware_0 ON warehouse (org,warehouse)
  290. */
  291. $cols = explode("(",$row[1]);
  292. $cols = explode(")",$cols[1]);
  293. array_pop($cols);
  294. $indexes[$row[0]]['columns'] = $cols;
  295. }
  296. if (isset($savem)) {
  297. $this->SetFetchMode($savem);
  298. $ADODB_FETCH_MODE = $save;
  299. }
  300. return $indexes;
  301. }
  302. }
  303. /*--------------------------------------------------------------------------------------
  304. Class Name: Recordset
  305. --------------------------------------------------------------------------------------*/
  306. class ADORecordset_sqlite3 extends ADORecordSet {
  307. var $databaseType = "sqlite3";
  308. var $bind = false;
  309. function __construct($queryID,$mode=false)
  310. {
  311. if ($mode === false) {
  312. global $ADODB_FETCH_MODE;
  313. $mode = $ADODB_FETCH_MODE;
  314. }
  315. switch($mode) {
  316. case ADODB_FETCH_NUM:
  317. $this->fetchMode = SQLITE3_NUM;
  318. break;
  319. case ADODB_FETCH_ASSOC:
  320. $this->fetchMode = SQLITE3_ASSOC;
  321. break;
  322. default:
  323. $this->fetchMode = SQLITE3_BOTH;
  324. break;
  325. }
  326. $this->adodbFetchMode = $mode;
  327. $this->_queryID = $queryID;
  328. $this->_inited = true;
  329. $this->fields = array();
  330. if ($queryID) {
  331. $this->_currentRow = 0;
  332. $this->EOF = !$this->_fetch();
  333. @$this->_initrs();
  334. } else {
  335. $this->_numOfRows = 0;
  336. $this->_numOfFields = 0;
  337. $this->EOF = true;
  338. }
  339. return $this->_queryID;
  340. }
  341. function FetchField($fieldOffset = -1)
  342. {
  343. $fld = new ADOFieldObject;
  344. $fld->name = $this->_queryID->columnName($fieldOffset);
  345. $fld->type = 'VARCHAR';
  346. $fld->max_length = -1;
  347. return $fld;
  348. }
  349. function _initrs()
  350. {
  351. $this->_numOfFields = $this->_queryID->numColumns();
  352. }
  353. function Fields($colname)
  354. {
  355. if ($this->fetchMode != SQLITE3_NUM) {
  356. return $this->fields[$colname];
  357. }
  358. if (!$this->bind) {
  359. $this->bind = array();
  360. for ($i=0; $i < $this->_numOfFields; $i++) {
  361. $o = $this->FetchField($i);
  362. $this->bind[strtoupper($o->name)] = $i;
  363. }
  364. }
  365. return $this->fields[$this->bind[strtoupper($colname)]];
  366. }
  367. function _seek($row)
  368. {
  369. // sqlite3 does not implement seek
  370. if ($this->debug) {
  371. ADOConnection::outp("SQLite3 does not implement seek");
  372. }
  373. return false;
  374. }
  375. function _fetch($ignore_fields=false)
  376. {
  377. $this->fields = $this->_queryID->fetchArray($this->fetchMode);
  378. return !empty($this->fields);
  379. }
  380. function _close()
  381. {
  382. }
  383. }