sql.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. <?php
  2. /*
  3. Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved.
  4. This file is part of the Fat-Free Framework (http://fatfreeframework.com).
  5. This is free software: you can redistribute it and/or modify it under the
  6. terms of the GNU General Public License as published by the Free Software
  7. Foundation, either version 3 of the License, or later.
  8. Fat-Free Framework is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License along
  13. with Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. namespace DB;
  16. //! PDO wrapper
  17. class SQL {
  18. //@{ Error messages
  19. const
  20. E_PKey='Table %s does not have a primary key';
  21. //@}
  22. const
  23. PARAM_FLOAT='float';
  24. protected
  25. //! UUID
  26. $uuid,
  27. //! Raw PDO
  28. $pdo,
  29. //! Data source name
  30. $dsn,
  31. //! Database engine
  32. $engine,
  33. //! Database name
  34. $dbname,
  35. //! Transaction flag
  36. $trans=FALSE,
  37. //! Number of rows affected by query
  38. $rows=0,
  39. //! SQL log
  40. $log;
  41. /**
  42. * Begin SQL transaction
  43. * @return bool
  44. **/
  45. function begin() {
  46. $out=$this->pdo->begintransaction();
  47. $this->trans=TRUE;
  48. return $out;
  49. }
  50. /**
  51. * Rollback SQL transaction
  52. * @return bool
  53. **/
  54. function rollback() {
  55. $out=$this->pdo->rollback();
  56. $this->trans=FALSE;
  57. return $out;
  58. }
  59. /**
  60. * Commit SQL transaction
  61. * @return bool
  62. **/
  63. function commit() {
  64. $out=$this->pdo->commit();
  65. $this->trans=FALSE;
  66. return $out;
  67. }
  68. /**
  69. * Return transaction flag
  70. * @return bool
  71. **/
  72. function trans() {
  73. return $this->trans;
  74. }
  75. /**
  76. * Map data type of argument to a PDO constant
  77. * @return int
  78. * @param $val scalar
  79. **/
  80. function type($val) {
  81. switch (gettype($val)) {
  82. case 'NULL':
  83. return \PDO::PARAM_NULL;
  84. case 'boolean':
  85. return \PDO::PARAM_BOOL;
  86. case 'integer':
  87. return \PDO::PARAM_INT;
  88. case 'resource':
  89. return \PDO::PARAM_LOB;
  90. case 'float':
  91. return self::PARAM_FLOAT;
  92. default:
  93. return \PDO::PARAM_STR;
  94. }
  95. }
  96. /**
  97. * Cast value to PHP type
  98. * @return mixed
  99. * @param $type string
  100. * @param $val mixed
  101. **/
  102. function value($type,$val) {
  103. switch ($type) {
  104. case self::PARAM_FLOAT:
  105. if (!is_string($val))
  106. $val=str_replace(',','.',$val);
  107. return $val;
  108. case \PDO::PARAM_NULL:
  109. return NULL;
  110. case \PDO::PARAM_INT:
  111. return (int)$val;
  112. case \PDO::PARAM_BOOL:
  113. return (bool)$val;
  114. case \PDO::PARAM_STR:
  115. return (string)$val;
  116. case \PDO::PARAM_LOB:
  117. return (binary)$val;
  118. }
  119. }
  120. /**
  121. * Execute SQL statement(s)
  122. * @return array|int|FALSE
  123. * @param $cmds string|array
  124. * @param $args string|array
  125. * @param $ttl int|array
  126. * @param $log bool
  127. * @param $stamp bool
  128. **/
  129. function exec($cmds,$args=NULL,$ttl=0,$log=TRUE,$stamp=FALSE) {
  130. $tag='';
  131. if (is_array($ttl))
  132. list($ttl,$tag)=$ttl;
  133. $auto=FALSE;
  134. if (is_null($args))
  135. $args=[];
  136. elseif (is_scalar($args))
  137. $args=[1=>$args];
  138. if (is_array($cmds)) {
  139. if (count($args)<($count=count($cmds)))
  140. // Apply arguments to SQL commands
  141. $args=array_fill(0,$count,$args);
  142. if (!$this->trans) {
  143. $this->begin();
  144. $auto=TRUE;
  145. }
  146. }
  147. else {
  148. $count=1;
  149. $cmds=[$cmds];
  150. $args=[$args];
  151. }
  152. if ($this->log===FALSE)
  153. $log=FALSE;
  154. $fw=\Base::instance();
  155. $cache=\Cache::instance();
  156. $result=FALSE;
  157. for ($i=0;$i<$count;$i++) {
  158. $cmd=$cmds[$i];
  159. $arg=$args[$i];
  160. // ensure 1-based arguments
  161. if (array_key_exists(0,$arg)) {
  162. array_unshift($arg,'');
  163. unset($arg[0]);
  164. }
  165. if (!preg_replace('/(^\s+|[\s;]+$)/','',$cmd))
  166. continue;
  167. $now=microtime(TRUE);
  168. $keys=$vals=[];
  169. if ($fw->CACHE && $ttl && ($cached=$cache->exists(
  170. $hash=$fw->hash($this->dsn.$cmd.
  171. $fw->stringify($arg)).($tag?'.'.$tag:'').'.sql',$result)) &&
  172. $cached[0]+$ttl>microtime(TRUE)) {
  173. foreach ($arg as $key=>$val) {
  174. $vals[]=$fw->stringify(is_array($val)?$val[0]:$val);
  175. $keys[]='/'.preg_quote(is_numeric($key)?chr(0).'?':$key).
  176. '/';
  177. }
  178. if ($log)
  179. $this->log.=($stamp?(date('r').' '):'').'('.
  180. sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
  181. '[CACHED] '.
  182. preg_replace($keys,$vals,
  183. str_replace('?',chr(0).'?',$cmd),1).PHP_EOL;
  184. }
  185. elseif (is_object($query=$this->pdo->prepare($cmd))) {
  186. foreach ($arg as $key=>$val) {
  187. if (is_array($val)) {
  188. // User-specified data type
  189. $query->bindvalue($key,$val[0],
  190. $val[1]==self::PARAM_FLOAT?\PDO::PARAM_STR:$val[1]);
  191. $vals[]=$fw->stringify($this->value($val[1],$val[0]));
  192. }
  193. else {
  194. // Convert to PDO data type
  195. $query->bindvalue($key,$val,
  196. ($type=$this->type($val))==self::PARAM_FLOAT?
  197. \PDO::PARAM_STR:$type);
  198. $vals[]=$fw->stringify($this->value($type,$val));
  199. }
  200. $keys[]='/'.preg_quote(is_numeric($key)?chr(0).'?':$key).
  201. '/';
  202. }
  203. if ($log)
  204. $this->log.=($stamp?(date('r').' '):'').'(-0ms) '.
  205. preg_replace($keys,$vals,
  206. str_replace('?',chr(0).'?',$cmd),1).PHP_EOL;
  207. $query->execute();
  208. if ($log)
  209. $this->log=str_replace('(-0ms)',
  210. '('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms)',
  211. $this->log);
  212. if (($error=$query->errorinfo()) && $error[0]!=\PDO::ERR_NONE) {
  213. // Statement-level error occurred
  214. if ($this->trans)
  215. $this->rollback();
  216. user_error('PDOStatement: '.$error[2],E_USER_ERROR);
  217. }
  218. if (preg_match('/(?:^[\s\(]*'.
  219. '(?:WITH|EXPLAIN|SELECT|PRAGMA|SHOW)|RETURNING)\b/is',$cmd) ||
  220. (preg_match('/^\s*(?:CALL|EXEC)\b/is',$cmd) &&
  221. $query->columnCount())) {
  222. $result=$query->fetchall(\PDO::FETCH_ASSOC);
  223. // Work around SQLite quote bug
  224. if (preg_match('/sqlite2?/',$this->engine))
  225. foreach ($result as $pos=>$rec) {
  226. unset($result[$pos]);
  227. $result[$pos]=[];
  228. foreach ($rec as $key=>$val)
  229. $result[$pos][trim($key,'\'"[]`')]=$val;
  230. }
  231. $this->rows=count($result);
  232. if ($fw->CACHE && $ttl)
  233. // Save to cache backend
  234. $cache->set($hash,$result,$ttl);
  235. }
  236. else
  237. $this->rows=$result=$query->rowcount();
  238. $query->closecursor();
  239. unset($query);
  240. }
  241. elseif (($error=$this->errorinfo()) && $error[0]!=\PDO::ERR_NONE) {
  242. // PDO-level error occurred
  243. if ($this->trans)
  244. $this->rollback();
  245. user_error('PDO: '.$error[2],E_USER_ERROR);
  246. }
  247. }
  248. if ($this->trans && $auto)
  249. $this->commit();
  250. return $result;
  251. }
  252. /**
  253. * Return number of rows affected by last query
  254. * @return int
  255. **/
  256. function count() {
  257. return $this->rows;
  258. }
  259. /**
  260. * Return SQL profiler results (or disable logging)
  261. * @return string
  262. * @param $flag bool
  263. **/
  264. function log($flag=TRUE) {
  265. if ($flag)
  266. return $this->log;
  267. $this->log=FALSE;
  268. }
  269. /**
  270. * Return TRUE if table exists
  271. * @return bool
  272. * @param $table string
  273. **/
  274. function exists($table) {
  275. $mode=$this->pdo->getAttribute(\PDO::ATTR_ERRMODE);
  276. $this->pdo->setAttribute(\PDO::ATTR_ERRMODE,\PDO::ERRMODE_SILENT);
  277. $out=$this->pdo->
  278. query('SELECT 1 FROM '.$this->quotekey($table).' LIMIT 1');
  279. $this->pdo->setAttribute(\PDO::ATTR_ERRMODE,$mode);
  280. return is_object($out);
  281. }
  282. /**
  283. * Retrieve schema of SQL table
  284. * @return array|FALSE
  285. * @param $table string
  286. * @param $fields array|string
  287. * @param $ttl int|array
  288. **/
  289. function schema($table,$fields=NULL,$ttl=0) {
  290. $fw=\Base::instance();
  291. $cache=\Cache::instance();
  292. if ($fw->CACHE && $ttl &&
  293. ($cached=$cache->exists(
  294. $hash=$fw->hash($this->dsn.$table).'.schema',$result)) &&
  295. $cached[0]+$ttl>microtime(TRUE))
  296. return $result;
  297. if (strpos($table,'.'))
  298. list($schema,$table)=explode('.',$table);
  299. // Supported engines
  300. $cmd=[
  301. 'sqlite2?'=>[
  302. 'PRAGMA table_info(`'.$table.'`)',
  303. 'name','type','dflt_value','notnull',0,'pk',TRUE],
  304. 'mysql'=>[
  305. 'SHOW columns FROM `'.$this->dbname.'`.`'.$table.'`',
  306. 'Field','Type','Default','Null','YES','Key','PRI'],
  307. 'mssql|sqlsrv|sybase|dblib|pgsql|odbc'=>[
  308. 'SELECT '.
  309. 'C.COLUMN_NAME AS field,'.
  310. 'C.DATA_TYPE AS type,'.
  311. 'C.COLUMN_DEFAULT AS defval,'.
  312. 'C.IS_NULLABLE AS nullable,'.
  313. 'T.CONSTRAINT_TYPE AS pkey '.
  314. 'FROM INFORMATION_SCHEMA.COLUMNS AS C '.
  315. 'LEFT OUTER JOIN '.
  316. 'INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K '.
  317. 'ON '.
  318. 'C.TABLE_NAME=K.TABLE_NAME AND '.
  319. 'C.COLUMN_NAME=K.COLUMN_NAME AND '.
  320. 'C.TABLE_SCHEMA=K.TABLE_SCHEMA '.
  321. ($this->dbname?
  322. ('AND C.TABLE_CATALOG=K.TABLE_CATALOG '):'').
  323. 'LEFT OUTER JOIN '.
  324. 'INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS T ON '.
  325. 'K.TABLE_NAME=T.TABLE_NAME AND '.
  326. 'K.CONSTRAINT_NAME=T.CONSTRAINT_NAME AND '.
  327. 'K.TABLE_SCHEMA=T.TABLE_SCHEMA '.
  328. ($this->dbname?
  329. ('AND K.TABLE_CATALOG=T.TABLE_CATALOG '):'').
  330. 'WHERE '.
  331. 'C.TABLE_NAME='.$this->quote($table).
  332. ($this->dbname?
  333. (' AND C.TABLE_CATALOG='.
  334. $this->quote($this->dbname)):''),
  335. 'field','type','defval','nullable','YES','pkey','PRIMARY KEY'],
  336. 'oci'=>[
  337. 'SELECT c.column_name AS field, '.
  338. 'c.data_type AS type, '.
  339. 'c.data_default AS defval, '.
  340. 'c.nullable AS nullable, '.
  341. '(SELECT t.constraint_type '.
  342. 'FROM all_cons_columns acc '.
  343. 'LEFT OUTER JOIN all_constraints t '.
  344. 'ON acc.constraint_name=t.constraint_name '.
  345. 'WHERE acc.table_name='.$this->quote($table).' '.
  346. 'AND acc.column_name=c.column_name '.
  347. 'AND constraint_type='.$this->quote('P').') AS pkey '.
  348. 'FROM all_tab_cols c '.
  349. 'WHERE c.table_name='.$this->quote($table),
  350. 'FIELD','TYPE','DEFVAL','NULLABLE','Y','PKEY','P']
  351. ];
  352. if (is_string($fields))
  353. $fields=\Base::instance()->split($fields);
  354. $conv=[
  355. 'int\b|integer'=>\PDO::PARAM_INT,
  356. 'bool'=>\PDO::PARAM_BOOL,
  357. 'blob|bytea|image|binary'=>\PDO::PARAM_LOB,
  358. 'float|real|double|decimal|numeric'=>self::PARAM_FLOAT,
  359. '.+'=>\PDO::PARAM_STR
  360. ];
  361. foreach ($cmd as $key=>$val)
  362. if (preg_match('/'.$key.'/',$this->engine)) {
  363. $rows=[];
  364. foreach ($this->exec($val[0],NULL) as $row)
  365. if (!$fields || in_array($row[$val[1]],$fields)) {
  366. foreach ($conv as $regex=>$type)
  367. if (preg_match('/'.$regex.'/i',$row[$val[2]]))
  368. break;
  369. $rows[$row[$val[1]]]=[
  370. 'type'=>$row[$val[2]],
  371. 'pdo_type'=>$type,
  372. 'default'=>is_string($row[$val[3]])?
  373. preg_replace('/^\s*([\'"])(.*)\1\s*/','\2',
  374. $row[$val[3]]):$row[$val[3]],
  375. 'nullable'=>$row[$val[4]]==$val[5],
  376. 'pkey'=>$row[$val[6]]==$val[7]
  377. ];
  378. }
  379. if ($fw->CACHE && $ttl)
  380. // Save to cache backend
  381. $cache->set($hash,$rows,$ttl);
  382. return $rows;
  383. }
  384. user_error(sprintf(self::E_PKey,$table),E_USER_ERROR);
  385. return FALSE;
  386. }
  387. /**
  388. * Quote string
  389. * @return string
  390. * @param $val mixed
  391. * @param $type int
  392. **/
  393. function quote($val,$type=\PDO::PARAM_STR) {
  394. return $this->engine=='odbc'?
  395. (is_string($val)?
  396. \Base::instance()->stringify(str_replace('\'','\'\'',$val)):
  397. $val):
  398. $this->pdo->quote($val,$type);
  399. }
  400. /**
  401. * Return UUID
  402. * @return string
  403. **/
  404. function uuid() {
  405. return $this->uuid;
  406. }
  407. /**
  408. * Return parent object
  409. * @return \PDO
  410. **/
  411. function pdo() {
  412. return $this->pdo;
  413. }
  414. /**
  415. * Return database engine
  416. * @return string
  417. **/
  418. function driver() {
  419. return $this->engine;
  420. }
  421. /**
  422. * Return server version
  423. * @return string
  424. **/
  425. function version() {
  426. return $this->pdo->getattribute(\PDO::ATTR_SERVER_VERSION);
  427. }
  428. /**
  429. * Return database name
  430. * @return string
  431. **/
  432. function name() {
  433. return $this->dbname;
  434. }
  435. /**
  436. * Return quoted identifier name
  437. * @return string
  438. * @param $key
  439. * @param bool $split
  440. **/
  441. function quotekey($key, $split=TRUE) {
  442. $delims=[
  443. 'sqlite2?|mysql'=>'``',
  444. 'pgsql|oci'=>'""',
  445. 'mssql|sqlsrv|odbc|sybase|dblib'=>'[]'
  446. ];
  447. $use='';
  448. foreach ($delims as $engine=>$delim)
  449. if (preg_match('/'.$engine.'/',$this->engine)) {
  450. $use=$delim;
  451. break;
  452. }
  453. return $use[0].($split ? implode($use[1].'.'.$use[0],explode('.',$key))
  454. : $key).$use[1];
  455. }
  456. /**
  457. * Redirect call to PDO object
  458. * @return mixed
  459. * @param $func string
  460. * @param $args array
  461. **/
  462. function __call($func,array $args) {
  463. return call_user_func_array([$this->pdo,$func],$args);
  464. }
  465. //! Prohibit cloning
  466. private function __clone() {
  467. }
  468. /**
  469. * Instantiate class
  470. * @param $dsn string
  471. * @param $user string
  472. * @param $pw string
  473. * @param $options array
  474. **/
  475. function __construct($dsn,$user=NULL,$pw=NULL,array $options=NULL) {
  476. $fw=\Base::instance();
  477. $this->uuid=$fw->hash($this->dsn=$dsn);
  478. if (preg_match('/^.+?(?:dbname|database)=(.+?)(?=;|$)/is',$dsn,$parts))
  479. $this->dbname=$parts[1];
  480. if (!$options)
  481. $options=[];
  482. if (isset($parts[0]) && strstr($parts[0],':',TRUE)=='mysql')
  483. $options+=[\PDO::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES '.
  484. strtolower(str_replace('-','',$fw->ENCODING)).';'];
  485. $this->pdo=new \PDO($dsn,$user,$pw,$options);
  486. $this->engine=$this->pdo->getattribute(\PDO::ATTR_DRIVER_NAME);
  487. }
  488. }