Medoo.php 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  1. <?php
  2. /*!
  3. * Medoo database framework
  4. * https://medoo.in
  5. * Version 1.4.5
  6. *
  7. * Copyright 2017, Angel Lai
  8. * Released under the MIT license
  9. */
  10. namespace Medoo;
  11. use PDO;
  12. use Exception;
  13. use PDOException;
  14. class Medoo
  15. {
  16. protected $database_type;
  17. protected $prefix;
  18. protected $statement;
  19. protected $option = [];
  20. protected $logs = [];
  21. protected $logging = false;
  22. protected $debug_mode = false;
  23. protected $guid = 0;
  24. public function __construct($options = null)
  25. {
  26. try {
  27. if (is_array($options)) {
  28. if (isset($options['database_type'])) {
  29. $this->database_type = strtolower($options['database_type']);
  30. }
  31. } else {
  32. return false;
  33. }
  34. if (isset($options['prefix'])) {
  35. $this->prefix = $options['prefix'];
  36. }
  37. if (isset($options['option'])) {
  38. $this->option = $options['option'];
  39. }
  40. if (isset($options['logging']) && is_bool($options['logging'])) {
  41. $this->logging = $options['logging'];
  42. }
  43. if (isset($options['command']) && is_array($options['command'])) {
  44. $commands = $options['command'];
  45. } else {
  46. $commands = [];
  47. }
  48. if (isset($options['dsn'])) {
  49. if (isset($options['dsn']['driver'])) {
  50. $attr = $options['dsn'];
  51. } else {
  52. return false;
  53. }
  54. } else {
  55. if (
  56. isset($options['port']) &&
  57. is_int($options['port'] * 1)
  58. ) {
  59. $port = $options['port'];
  60. }
  61. $is_port = isset($port);
  62. switch ($this->database_type) {
  63. case 'mariadb':
  64. case 'mysql':
  65. $attr = [
  66. 'driver' => 'mysql',
  67. 'dbname' => $options['database_name']
  68. ];
  69. if (isset($options['socket'])) {
  70. $attr['unix_socket'] = $options['socket'];
  71. } else {
  72. $attr['host'] = $options['server'];
  73. if ($is_port) {
  74. $attr['port'] = $port;
  75. }
  76. }
  77. // Make MySQL using standard quoted identifier
  78. $commands[] = 'SET SQL_MODE=ANSI_QUOTES';
  79. break;
  80. case 'pgsql':
  81. $attr = [
  82. 'driver' => 'pgsql',
  83. 'host' => $options['server'],
  84. 'dbname' => $options['database_name']
  85. ];
  86. if ($is_port) {
  87. $attr['port'] = $port;
  88. }
  89. break;
  90. case 'sybase':
  91. $attr = [
  92. 'driver' => 'dblib',
  93. 'host' => $options['server'],
  94. 'dbname' => $options['database_name']
  95. ];
  96. if ($is_port) {
  97. $attr['port'] = $port;
  98. }
  99. break;
  100. case 'oracle':
  101. $attr = [
  102. 'driver' => 'oci',
  103. 'dbname' => $options['server'] ?
  104. '//' . $options['server'] . ($is_port ? ':' . $port : ':1521') . '/' . $options['database_name'] :
  105. $options['database_name']
  106. ];
  107. if (isset($options['charset'])) {
  108. $attr['charset'] = $options['charset'];
  109. }
  110. break;
  111. case 'mssql':
  112. if (strstr(PHP_OS, 'WIN')) {
  113. $attr = [
  114. 'driver' => 'sqlsrv',
  115. 'Server' => $options['server'] . ($is_port ? ',' . $port : ''),
  116. 'Database' => $options['database_name']
  117. ];
  118. } else {
  119. $attr = [
  120. 'driver' => 'dblib',
  121. 'host' => $options['server'] . ($is_port ? ':' . $port : ''),
  122. 'dbname' => $options['database_name']
  123. ];
  124. }
  125. // Keep MSSQL QUOTED_IDENTIFIER is ON for standard quoting
  126. $commands[] = 'SET QUOTED_IDENTIFIER ON';
  127. // Make ANSI_NULLS is ON for NULL value
  128. $commands[] = 'SET ANSI_NULLS ON';
  129. break;
  130. case 'sqlite':
  131. $this->pdo = new PDO('sqlite:' . $options['database_file'], null, null, $this->option);
  132. return;
  133. }
  134. }
  135. $driver = $attr['driver'];
  136. unset($attr['driver']);
  137. $stack = [];
  138. foreach ($attr as $key => $value) {
  139. if (is_int($key)) {
  140. $stack[] = $value;
  141. } else {
  142. $stack[] = $key . '=' . $value;
  143. }
  144. }
  145. $dsn = $driver . ':' . implode($stack, ';');
  146. if (
  147. in_array($this->database_type, ['mariadb', 'mysql', 'pgsql', 'sybase', 'mssql']) &&
  148. isset($options['charset'])
  149. ) {
  150. $commands[] = "SET NAMES '" . $options['charset'] . "'";
  151. }
  152. $this->pdo = new PDO(
  153. $dsn,
  154. $options['username'],
  155. $options['password'],
  156. $this->option
  157. );
  158. foreach ($commands as $value) {
  159. $this->pdo->exec($value);
  160. }
  161. } catch (PDOException $e) {
  162. throw new PDOException($e->getMessage());
  163. }
  164. }
  165. public function query($query, $map = [])
  166. {
  167. if (!empty($map)) {
  168. foreach ($map as $key => $value) {
  169. switch (gettype($value)) {
  170. case 'NULL':
  171. $map[$key] = [null, PDO::PARAM_NULL];
  172. break;
  173. case 'resource':
  174. $map[$key] = [$value, PDO::PARAM_LOB];
  175. break;
  176. case 'boolean':
  177. $map[$key] = [($value ? '1' : '0'), PDO::PARAM_BOOL];
  178. break;
  179. case 'integer':
  180. case 'double':
  181. $map[$key] = [$value, PDO::PARAM_INT];
  182. break;
  183. case 'string':
  184. $map[$key] = [$value, PDO::PARAM_STR];
  185. break;
  186. }
  187. }
  188. }
  189. return $this->exec($query, $map);
  190. }
  191. public function exec($query, $map = [])
  192. {
  193. if ($this->debug_mode) {
  194. echo $this->generate($query, $map);
  195. $this->debug_mode = false;
  196. return false;
  197. }
  198. if ($this->logging) {
  199. $this->logs[] = [$query, $map];
  200. } else {
  201. $this->logs = [[$query, $map]];
  202. }
  203. $statement = $this->pdo->prepare($query);
  204. if ($statement) {
  205. foreach ($map as $key => $value) {
  206. $statement->bindValue($key, $value[0], $value[1]);
  207. }
  208. $statement->execute();
  209. $this->statement = $statement;
  210. return $statement;
  211. } else {
  212. return false;
  213. }
  214. }
  215. protected function generate($query, $map)
  216. {
  217. foreach ($map as $key => $value) {
  218. if ($value[1] === PDO::PARAM_STR) {
  219. $query = str_replace($key, $this->quote($value[0]), $query);
  220. } elseif ($value[1] === PDO::PARAM_NULL) {
  221. $query = str_replace($key, 'NULL', $query);
  222. } else {
  223. $query = str_replace($key, $value[0], $query);
  224. }
  225. }
  226. return $query;
  227. }
  228. public function quote($string)
  229. {
  230. return $this->pdo->quote($string);
  231. }
  232. protected function tableQuote($table)
  233. {
  234. return '"' . $this->prefix . $table . '"';
  235. }
  236. protected function mapKey()
  237. {
  238. return ':MeDoO_' . $this->guid++ . '_mEdOo';
  239. }
  240. protected function columnQuote($string)
  241. {
  242. preg_match('/(^#)?([a-zA-Z0-9_]*)\.([a-zA-Z0-9_]*)(\s*\[JSON\]$)?/', $string, $column_match);
  243. if (isset($column_match[2], $column_match[3])) {
  244. return '"' . $this->prefix . $column_match[2] . '"."' . $column_match[3] . '"';
  245. }
  246. return '"' . $string . '"';
  247. }
  248. protected function columnPush(&$columns)
  249. {
  250. if ($columns === '*') {
  251. return $columns;
  252. }
  253. $stack = [];
  254. if (is_string($columns)) {
  255. $columns = [$columns];
  256. }
  257. foreach ($columns as $key => $value) {
  258. if (is_array($value)) {
  259. $stack[] = $this->columnPush($value);
  260. } else {
  261. preg_match('/(?<column>[a-zA-Z0-9_\.]+)(?:\s*\((?<alias>[a-zA-Z0-9_]+)\)|\s*\[(?<type>(String|Bool|Int|Number|Object|JSON))\])?/i', $value, $match);
  262. if (!empty($match['alias'])) {
  263. $stack[] = $this->columnQuote($match['column']) . ' AS ' . $this->columnQuote($match['alias']);
  264. $columns[$key] = $match['alias'];
  265. } else {
  266. $stack[] = $this->columnQuote($match['column']);
  267. }
  268. }
  269. }
  270. return implode($stack, ',');
  271. }
  272. protected function arrayQuote($array)
  273. {
  274. $stack = [];
  275. foreach ($array as $value) {
  276. $stack[] = is_int($value) ? $value : $this->pdo->quote($value);
  277. }
  278. return implode($stack, ',');
  279. }
  280. protected function innerConjunct($data, $map, $conjunctor, $outer_conjunctor)
  281. {
  282. $stack = [];
  283. foreach ($data as $value) {
  284. $stack[] = '(' . $this->dataImplode($value, $map, $conjunctor) . ')';
  285. }
  286. return implode($outer_conjunctor . ' ', $stack);
  287. }
  288. protected function fnQuote($column, $string)
  289. {
  290. return (strpos($column, '#') === 0 && preg_match('/^[A-Z0-9\_]*\([^)]*\)$/', $string)) ?
  291. $string :
  292. $this->quote($string);
  293. }
  294. protected function dataImplode($data, &$map, $conjunctor)
  295. {
  296. $wheres = [];
  297. foreach ($data as $key => $value) {
  298. $map_key = $this->mapKey();
  299. $type = gettype($value);
  300. if (
  301. preg_match("/^(AND|OR)(\s+#.*)?$/i", $key, $relation_match) &&
  302. $type === 'array'
  303. ) {
  304. $wheres[] = 0 !== count(array_diff_key($value, array_keys(array_keys($value)))) ?
  305. '(' . $this->dataImplode($value, $map, ' ' . $relation_match[1]) . ')' :
  306. '(' . $this->innerConjunct($value, $map, ' ' . $relation_match[1], $conjunctor) . ')';
  307. } else {
  308. if (
  309. is_int($key) &&
  310. preg_match('/([a-zA-Z0-9_\.]+)\[(?<operator>\>|\>\=|\<|\<\=|\!|\=)\]([a-zA-Z0-9_\.]+)/i', $value, $match)
  311. ) {
  312. $wheres[] = $this->columnQuote($match[1]) . ' ' . $match['operator'] . ' ' . $this->columnQuote($match[3]);
  313. } else {
  314. preg_match('/(#?)([a-zA-Z0-9_\.]+)(\[(?<operator>\>|\>\=|\<|\<\=|\!|\<\>|\>\<|\!?~)\])?/i', $key, $match);
  315. $column = $this->columnQuote($match[2]);
  316. if (!empty($match[1])) {
  317. $wheres[] = $column .
  318. (isset($match['operator']) ? ' ' . $match['operator'] . ' ' : ' = ') .
  319. $this->fnQuote($key, $value);
  320. continue;
  321. }
  322. if (isset($match['operator'])) {
  323. $operator = $match['operator'];
  324. if ($operator === '!') {
  325. switch ($type) {
  326. case 'NULL':
  327. $wheres[] = $column . ' IS NOT NULL';
  328. break;
  329. case 'array':
  330. $wheres[] = $column . ' NOT IN (' . $this->arrayQuote($value) . ')';
  331. break;
  332. case 'integer':
  333. case 'double':
  334. $wheres[] = $column . ' != ' . $map_key;
  335. $map[$map_key] = [$value, PDO::PARAM_INT];
  336. break;
  337. case 'boolean':
  338. $wheres[] = $column . ' != ' . $map_key;
  339. $map[$map_key] = [($value ? '1' : '0'), PDO::PARAM_BOOL];
  340. break;
  341. case 'string':
  342. $wheres[] = $column . ' != ' . $map_key;
  343. $map[$map_key] = [$value, PDO::PARAM_STR];
  344. break;
  345. }
  346. }
  347. if ($operator === '<>' || $operator === '><') {
  348. if ($type === 'array') {
  349. if ($operator === '><') {
  350. $column .= ' NOT';
  351. }
  352. $wheres[] = '(' . $column . ' BETWEEN ' . $map_key . 'a AND ' . $map_key . 'b)';
  353. $data_type = (is_numeric($value[0]) && is_numeric($value[1])) ? PDO::PARAM_INT : PDO::PARAM_STR;
  354. $map[$map_key . 'a'] = [$value[0], $data_type];
  355. $map[$map_key . 'b'] = [$value[1], $data_type];
  356. }
  357. }
  358. if ($operator === '~' || $operator === '!~') {
  359. if ($type !== 'array') {
  360. $value = [$value];
  361. }
  362. $connector = ' OR ';
  363. $stack = array_values($value);
  364. if (is_array($stack[0])) {
  365. if (isset($value['AND']) || isset($value['OR'])) {
  366. $connector = ' ' . array_keys($value)[0] . ' ';
  367. $value = $stack[0];
  368. }
  369. }
  370. $like_clauses = [];
  371. foreach ($value as $index => $item) {
  372. $item = strval($item);
  373. if (!preg_match('/(\[.+\]|_|%.+|.+%)/', $item)) {
  374. $item = '%' . $item . '%';
  375. }
  376. $like_clauses[] = $column . ($operator === '!~' ? ' NOT' : '') . ' LIKE ' . $map_key . 'L' . $index;
  377. $map[$map_key . 'L' . $index] = [$item, PDO::PARAM_STR];
  378. }
  379. $wheres[] = '(' . implode($connector, $like_clauses) . ')';
  380. }
  381. if (in_array($operator, ['>', '>=', '<', '<='])) {
  382. $condition = $column . ' ' . $operator . ' ';
  383. if (is_numeric($value)) {
  384. $condition .= $map_key;
  385. $map[$map_key] = [$value, PDO::PARAM_INT];
  386. } else {
  387. $condition .= $map_key;
  388. $map[$map_key] = [$value, PDO::PARAM_STR];
  389. }
  390. $wheres[] = $condition;
  391. }
  392. } else {
  393. switch ($type) {
  394. case 'NULL':
  395. $wheres[] = $column . ' IS NULL';
  396. break;
  397. case 'array':
  398. $wheres[] = $column . ' IN (' . $this->arrayQuote($value) . ')';
  399. break;
  400. case 'integer':
  401. case 'double':
  402. $wheres[] = $column . ' = ' . $map_key;
  403. $map[$map_key] = [$value, PDO::PARAM_INT];
  404. break;
  405. case 'boolean':
  406. $wheres[] = $column . ' = ' . $map_key;
  407. $map[$map_key] = [($value ? '1' : '0'), PDO::PARAM_BOOL];
  408. break;
  409. case 'string':
  410. $wheres[] = $column . ' = ' . $map_key;
  411. $map[$map_key] = [$value, PDO::PARAM_STR];
  412. break;
  413. }
  414. }
  415. }
  416. }
  417. }
  418. return implode($conjunctor . ' ', $wheres);
  419. }
  420. protected function whereClause($where, &$map)
  421. {
  422. $where_clause = '';
  423. if (is_array($where)) {
  424. $where_keys = array_keys($where);
  425. $where_AND = preg_grep("/^AND\s*#?$/i", $where_keys);
  426. $where_OR = preg_grep("/^OR\s*#?$/i", $where_keys);
  427. $single_condition = array_diff_key($where, array_flip(
  428. ['AND', 'OR', 'GROUP', 'ORDER', 'HAVING', 'LIMIT', 'LIKE', 'MATCH']
  429. ));
  430. if (!empty($single_condition)) {
  431. $condition = $this->dataImplode($single_condition, $map, ' AND');
  432. if ($condition !== '') {
  433. $where_clause = ' WHERE ' . $condition;
  434. }
  435. }
  436. if (!empty($where_AND)) {
  437. $value = array_values($where_AND);
  438. $where_clause = ' WHERE ' . $this->dataImplode($where[$value[0]], $map, ' AND');
  439. }
  440. if (!empty($where_OR)) {
  441. $value = array_values($where_OR);
  442. $where_clause = ' WHERE ' . $this->dataImplode($where[$value[0]], $map, ' OR');
  443. }
  444. if (isset($where['MATCH'])) {
  445. $MATCH = $where['MATCH'];
  446. if (is_array($MATCH) && isset($MATCH['columns'], $MATCH['keyword'])) {
  447. $mode = '';
  448. $mode_array = [
  449. 'natural' => 'IN NATURAL LANGUAGE MODE',
  450. 'natural+query' => 'IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION',
  451. 'boolean' => 'IN BOOLEAN MODE',
  452. 'query' => 'WITH QUERY EXPANSION'
  453. ];
  454. if (isset($MATCH['mode'], $mode_array[$MATCH['mode']])) {
  455. $mode = ' ' . $mode_array[$MATCH['mode']];
  456. }
  457. $columns = implode(array_map([$this, 'columnQuote'], $MATCH['columns']), ', ');
  458. $map_key = $this->mapKey();
  459. $map[$map_key] = [$MATCH['keyword'], PDO::PARAM_STR];
  460. $where_clause .= ($where_clause !== '' ? ' AND ' : ' WHERE') . ' MATCH (' . $columns . ') AGAINST (' . $map_key . $mode . ')';
  461. }
  462. }
  463. if (isset($where['GROUP'])) {
  464. $GROUP = $where['GROUP'];
  465. if (is_array($GROUP)) {
  466. $stack = [];
  467. foreach ($GROUP as $column => $value) {
  468. $stack[] = $this->columnQuote($value);
  469. }
  470. $where_clause .= ' GROUP BY ' . implode($stack, ',');
  471. } else {
  472. $where_clause .= ' GROUP BY ' . $this->columnQuote($where['GROUP']);
  473. }
  474. if (isset($where['HAVING'])) {
  475. $where_clause .= ' HAVING ' . $this->dataImplode($where['HAVING'], $map, ' AND');
  476. }
  477. }
  478. if (isset($where['ORDER'])) {
  479. $ORDER = $where['ORDER'];
  480. if (is_array($ORDER)) {
  481. $stack = [];
  482. foreach ($ORDER as $column => $value) {
  483. if (is_array($value)) {
  484. $stack[] = 'FIELD(' . $this->columnQuote($column) . ', ' . $this->arrayQuote($value) . ')';
  485. } else if ($value === 'ASC' || $value === 'DESC') {
  486. $stack[] = $this->columnQuote($column) . ' ' . $value;
  487. } else if (is_int($column)) {
  488. $stack[] = $this->columnQuote($value);
  489. }
  490. }
  491. $where_clause .= ' ORDER BY ' . implode($stack, ',');
  492. } else {
  493. $where_clause .= ' ORDER BY ' . $this->columnQuote($ORDER);
  494. }
  495. if (
  496. isset($where['LIMIT']) &&
  497. in_array($this->database_type, ['oracle', 'mssql'])
  498. ) {
  499. $LIMIT = $where['LIMIT'];
  500. if (is_numeric($LIMIT)) {
  501. $where_clause .= ' FETCH FIRST ' . $LIMIT . ' ROWS ONLY';
  502. }
  503. if (
  504. is_array($LIMIT) &&
  505. is_numeric($LIMIT[0]) &&
  506. is_numeric($LIMIT[1])
  507. ) {
  508. $where_clause .= ' OFFSET ' . $LIMIT[0] . ' ROWS FETCH NEXT ' . $LIMIT[1] . ' ROWS ONLY';
  509. }
  510. }
  511. }
  512. if (isset($where['LIMIT']) && !in_array($this->database_type, ['oracle', 'mssql'])) {
  513. $LIMIT = $where['LIMIT'];
  514. if (is_numeric($LIMIT)) {
  515. $where_clause .= ' LIMIT ' . $LIMIT;
  516. }
  517. if (
  518. is_array($LIMIT) &&
  519. is_numeric($LIMIT[0]) &&
  520. is_numeric($LIMIT[1])
  521. ) {
  522. $where_clause .= ' LIMIT ' . $LIMIT[1] . ' OFFSET ' . $LIMIT[0];
  523. }
  524. }
  525. } else {
  526. if ($where !== null) {
  527. $where_clause .= ' ' . $where;
  528. }
  529. }
  530. return $where_clause;
  531. }
  532. protected function selectContext($table, &$map, $join, &$columns = null, $where = null, $column_fn = null)
  533. {
  534. preg_match('/(?<table>[a-zA-Z0-9_]+)\s*\((?<alias>[a-zA-Z0-9_]+)\)/i', $table, $table_match);
  535. if (isset($table_match['table'], $table_match['alias'])) {
  536. $table = $this->tableQuote($table_match['table']);
  537. $table_query = $table . ' AS ' . $this->tableQuote($table_match['alias']);
  538. } else {
  539. $table = $this->tableQuote($table);
  540. $table_query = $table;
  541. }
  542. $join_key = is_array($join) ? array_keys($join) : null;
  543. if (
  544. isset($join_key[0]) &&
  545. strpos($join_key[0], '[') === 0
  546. ) {
  547. $table_join = [];
  548. $join_array = [
  549. '>' => 'LEFT',
  550. '<' => 'RIGHT',
  551. '<>' => 'FULL',
  552. '><' => 'INNER'
  553. ];
  554. foreach ($join as $sub_table => $relation) {
  555. preg_match('/(\[(?<join>\<|\>|\>\<|\<\>)\])?(?<table>[a-zA-Z0-9_]+)\s?(\((?<alias>[a-zA-Z0-9_]+)\))?/', $sub_table, $match);
  556. if ($match['join'] !== '' && $match['table'] !== '') {
  557. if (is_string($relation)) {
  558. $relation = 'USING ("' . $relation . '")';
  559. }
  560. if (is_array($relation)) {
  561. // For ['column1', 'column2']
  562. if (isset($relation[0])) {
  563. $relation = 'USING ("' . implode($relation, '", "') . '")';
  564. } else {
  565. $joins = [];
  566. foreach ($relation as $key => $value) {
  567. $joins[] = (
  568. strpos($key, '.') > 0 ?
  569. // For ['tableB.column' => 'column']
  570. $this->columnQuote($key) :
  571. // For ['column1' => 'column2']
  572. $table . '."' . $key . '"'
  573. ) .
  574. ' = ' .
  575. $this->tableQuote(isset($match['alias']) ? $match['alias'] : $match['table']) . '."' . $value . '"';
  576. }
  577. $relation = 'ON ' . implode($joins, ' AND ');
  578. }
  579. }
  580. $table_name = $this->tableQuote($match['table']) . ' ';
  581. if (isset($match['alias'])) {
  582. $table_name .= 'AS ' . $this->tableQuote($match['alias']) . ' ';
  583. }
  584. $table_join[] = $join_array[$match['join']] . ' JOIN ' . $table_name . $relation;
  585. }
  586. }
  587. $table_query .= ' ' . implode($table_join, ' ');
  588. } else {
  589. if (is_null($columns)) {
  590. if (is_null($where)) {
  591. if (
  592. is_array($join) &&
  593. isset($column_fn)
  594. ) {
  595. $where = $join;
  596. $columns = null;
  597. } else {
  598. $where = null;
  599. $columns = $join;
  600. }
  601. } else {
  602. $where = $join;
  603. $columns = null;
  604. }
  605. } else {
  606. $where = $columns;
  607. $columns = $join;
  608. }
  609. }
  610. if (isset($column_fn)) {
  611. if ($column_fn === 1) {
  612. $column = '1';
  613. if (is_null($where)) {
  614. $where = $columns;
  615. }
  616. } else {
  617. if (empty($columns)) {
  618. $columns = '*';
  619. $where = $join;
  620. }
  621. $column = $column_fn . '(' . $this->columnPush($columns) . ')';
  622. }
  623. } else {
  624. $column = $this->columnPush($columns);
  625. }
  626. return 'SELECT ' . $column . ' FROM ' . $table_query . $this->whereClause($where, $map);
  627. }
  628. protected function columnMap($columns, &$stack)
  629. {
  630. if ($columns === '*') {
  631. return $stack;
  632. }
  633. foreach ($columns as $key => $value) {
  634. if (is_int($key)) {
  635. preg_match('/(?<column>[a-zA-Z0-9_\.]*)(?:\s*\((?<alias>[a-zA-Z0-9_]+)\)|\s*\[(?<type>(String|Bool|Int|Number|Object|JSON))\])?/i', $value, $key_match);
  636. $column_key = !empty($key_match['alias']) ?
  637. $key_match['alias'] :
  638. preg_replace('/^[\w]*\./i', '', $key_match['column']);
  639. if (isset($key_match['type'])) {
  640. $stack[$value] = [$column_key, $key_match['type']];
  641. } else {
  642. $stack[$value] = [$column_key, 'String'];
  643. }
  644. } else {
  645. $this->columnMap($value, $stack);
  646. }
  647. }
  648. return $stack;
  649. }
  650. protected function dataMap($data, $columns, $column_map, &$stack)
  651. {
  652. foreach ($columns as $key => $value) {
  653. if (is_int($key)) {
  654. $map = $column_map[$value];
  655. $column_key = $map[0];
  656. if (isset($map[1])) {
  657. switch ($map[1]) {
  658. case 'Number':
  659. case 'Int':
  660. $stack[$column_key] = (int)$data[$column_key];
  661. break;
  662. case 'Bool':
  663. $stack[$column_key] = (bool)$data[$column_key];
  664. break;
  665. case 'Object':
  666. $stack[$column_key] = unserialize($data[$column_key]);
  667. break;
  668. case 'JSON':
  669. $stack[$column_key] = json_decode($data[$column_key], true);
  670. break;
  671. case 'String':
  672. $stack[$column_key] = $data[$column_key];
  673. break;
  674. }
  675. } else {
  676. $stack[$column_key] = $data[$column_key];
  677. }
  678. } else {
  679. $current_stack = [];
  680. $this->dataMap($data, $value, $column_map, $current_stack);
  681. $stack[$key] = $current_stack;
  682. }
  683. }
  684. }
  685. public function select($table, $join, $columns = null, $where = null)
  686. {
  687. $map = [];
  688. $stack = [];
  689. $column_map = [];
  690. $index = 0;
  691. $column = $where === null ? $join : $columns;
  692. $is_single_column = (is_string($column) && $column !== '*');
  693. $query = $this->exec($this->selectContext($table, $map, $join, $columns, $where), $map);
  694. $this->columnMap($columns, $column_map);
  695. if (!$query) {
  696. return false;
  697. }
  698. if ($columns === '*') {
  699. return $query->fetchAll(PDO::FETCH_ASSOC);
  700. }
  701. if ($is_single_column) {
  702. return $query->fetchAll(PDO::FETCH_COLUMN);
  703. }
  704. while ($data = $query->fetch(PDO::FETCH_ASSOC)) {
  705. $current_stack = [];
  706. $this->dataMap($data, $columns, $column_map, $current_stack);
  707. $stack[$index] = $current_stack;
  708. $index++;
  709. }
  710. return $stack;
  711. }
  712. public function insert($table, $datas)
  713. {
  714. $stack = [];
  715. $columns = [];
  716. $fields = [];
  717. $map = [];
  718. if (!isset($datas[0])) {
  719. $datas = [$datas];
  720. }
  721. foreach ($datas as $data) {
  722. foreach ($data as $key => $value) {
  723. $columns[] = $key;
  724. }
  725. }
  726. $columns = array_unique($columns);
  727. foreach ($datas as $data) {
  728. $values = [];
  729. foreach ($columns as $key) {
  730. if (strpos($key, '#') === 0) {
  731. $values[] = $this->fnQuote($key, $data[$key]);
  732. continue;
  733. }
  734. $map_key = $this->mapKey();
  735. $values[] = $map_key;
  736. if (!isset($data[$key])) {
  737. $map[$map_key] = [null, PDO::PARAM_NULL];
  738. } else {
  739. $value = $data[$key];
  740. switch (gettype($value)) {
  741. case 'NULL':
  742. $map[$map_key] = [null, PDO::PARAM_NULL];
  743. break;
  744. case 'array':
  745. $map[$map_key] = [
  746. strpos($key, '[JSON]') === strlen($key) - 6 ?
  747. json_encode($value) :
  748. serialize($value),
  749. PDO::PARAM_STR
  750. ];
  751. break;
  752. case 'object':
  753. $map[$map_key] = [serialize($value), PDO::PARAM_STR];
  754. break;
  755. case 'resource':
  756. $map[$map_key] = [$value, PDO::PARAM_LOB];
  757. break;
  758. case 'boolean':
  759. $map[$map_key] = [($value ? '1' : '0'), PDO::PARAM_BOOL];
  760. break;
  761. case 'integer':
  762. case 'double':
  763. $map[$map_key] = [$value, PDO::PARAM_INT];
  764. break;
  765. case 'string':
  766. $map[$map_key] = [$value, PDO::PARAM_STR];
  767. break;
  768. }
  769. }
  770. }
  771. $stack[] = '(' . implode($values, ', ') . ')';
  772. }
  773. foreach ($columns as $key) {
  774. $fields[] = $this->columnQuote(preg_replace("/(^#|\s*\[JSON\]$)/i", '', $key));
  775. }
  776. return $this->exec('INSERT INTO ' . $this->tableQuote($table) . ' (' . implode(', ', $fields) . ') VALUES ' . implode(', ', $stack), $map);
  777. }
  778. public function update($table, $data, $where = null)
  779. {
  780. $fields = [];
  781. $map = [];
  782. foreach ($data as $key => $value) {
  783. $column = $this->columnQuote(preg_replace("/(^#|\s*\[(JSON|\+|\-|\*|\/)\]$)/i", '', $key));
  784. if (strpos($key, '#') === 0) {
  785. $fields[] = $column . ' = ' . $value;
  786. continue;
  787. }
  788. $map_key = $this->mapKey();
  789. preg_match('/(?<column>[a-zA-Z0-9_]+)(\[(?<operator>\+|\-|\*|\/)\])?/i', $key, $match);
  790. if (isset($match['operator'])) {
  791. if (is_numeric($value)) {
  792. $fields[] = $column . ' = ' . $column . ' ' . $match['operator'] . ' ' . $value;
  793. }
  794. } else {
  795. $fields[] = $column . ' = ' . $map_key;
  796. switch (gettype($value)) {
  797. case 'NULL':
  798. $map[$map_key] = [null, PDO::PARAM_NULL];
  799. break;
  800. case 'array':
  801. $map[$map_key] = [
  802. strpos($key, '[JSON]') === strlen($key) - 6 ?
  803. json_encode($value) :
  804. serialize($value),
  805. PDO::PARAM_STR
  806. ];
  807. break;
  808. case 'object':
  809. $map[$map_key] = [serialize($value), PDO::PARAM_STR];
  810. break;
  811. case 'resource':
  812. $map[$map_key] = [$value, PDO::PARAM_LOB];
  813. break;
  814. case 'boolean':
  815. $map[$map_key] = [($value ? '1' : '0'), PDO::PARAM_BOOL];
  816. break;
  817. case 'integer':
  818. case 'double':
  819. $map[$map_key] = [$value, PDO::PARAM_INT];
  820. break;
  821. case 'string':
  822. $map[$map_key] = [$value, PDO::PARAM_STR];
  823. break;
  824. }
  825. }
  826. }
  827. return $this->exec('UPDATE ' . $this->tableQuote($table) . ' SET ' . implode(', ', $fields) . $this->whereClause($where, $map), $map);
  828. }
  829. public function delete($table, $where)
  830. {
  831. $map = [];
  832. return $this->exec('DELETE FROM ' . $this->tableQuote($table) . $this->whereClause($where, $map), $map);
  833. }
  834. public function replace($table, $columns, $where = null)
  835. {
  836. $map = [];
  837. if (is_array($columns)) {
  838. $replace_query = [];
  839. foreach ($columns as $column => $replacements) {
  840. if (is_array($replacements[0])) {
  841. foreach ($replacements as $replacement) {
  842. $map_key = $this->mapKey();
  843. $replace_query[] = $this->columnQuote($column) . ' = REPLACE(' . $this->columnQuote($column) . ', ' . $map_key . 'a, ' . $map_key . 'b)';
  844. $map[$map_key . 'a'] = [$replacement[0], PDO::PARAM_STR];
  845. $map[$map_key . 'b'] = [$replacement[1], PDO::PARAM_STR];
  846. }
  847. } else {
  848. $map_key = $this->mapKey();
  849. $replace_query[] = $this->columnQuote($column) . ' = REPLACE(' . $this->columnQuote($column) . ', ' . $map_key . 'a, ' . $map_key . 'b)';
  850. $map[$map_key . 'a'] = [$replacements[0], PDO::PARAM_STR];
  851. $map[$map_key . 'b'] = [$replacements[1], PDO::PARAM_STR];
  852. }
  853. }
  854. $replace_query = implode(', ', $replace_query);
  855. }
  856. return $this->exec('UPDATE ' . $this->tableQuote($table) . ' SET ' . $replace_query . $this->whereClause($where, $map), $map);
  857. }
  858. public function get($table, $join = null, $columns = null, $where = null)
  859. {
  860. $map = [];
  861. $stack = [];
  862. $column_map = [];
  863. $column = $where === null ? $join : $columns;
  864. $is_single_column = (is_string($column) && $column !== '*');
  865. $query = $this->exec($this->selectContext($table, $map, $join, $columns, $where) . ' LIMIT 1', $map);
  866. if ($query) {
  867. $data = $query->fetchAll(PDO::FETCH_ASSOC);
  868. if (isset($data[0])) {
  869. if ($column === '*') {
  870. return $data[0];
  871. }
  872. $this->columnMap($columns, $column_map);
  873. $this->dataMap($data[0], $columns, $column_map, $stack);
  874. if ($is_single_column) {
  875. return $stack[$column_map[$column][0]];
  876. }
  877. return $stack;
  878. } else {
  879. return false;
  880. }
  881. } else {
  882. return false;
  883. }
  884. }
  885. public function has($table, $join, $where = null)
  886. {
  887. $map = [];
  888. $column = null;
  889. $query = $this->exec('SELECT EXISTS(' . $this->selectContext($table, $map, $join, $column, $where, 1) . ')', $map);
  890. if ($query) {
  891. return $query->fetchColumn() === '1';
  892. } else {
  893. return false;
  894. }
  895. }
  896. public function count($table, $join = null, $column = null, $where = null)
  897. {
  898. $map = [];
  899. $query = $this->exec($this->selectContext($table, $map, $join, $column, $where, 'COUNT'), $map);
  900. return $query ? 0 + $query->fetchColumn() : false;
  901. }
  902. public function max($table, $join, $column = null, $where = null)
  903. {
  904. $map = [];
  905. $query = $this->exec($this->selectContext($table, $map, $join, $column, $where, 'MAX'), $map);
  906. if ($query) {
  907. $max = $query->fetchColumn();
  908. return is_numeric($max) ? $max + 0 : $max;
  909. } else {
  910. return false;
  911. }
  912. }
  913. public function min($table, $join, $column = null, $where = null)
  914. {
  915. $map = [];
  916. $query = $this->exec($this->selectContext($table, $map, $join, $column, $where, 'MIN'), $map);
  917. if ($query) {
  918. $min = $query->fetchColumn();
  919. return is_numeric($min) ? $min + 0 : $min;
  920. } else {
  921. return false;
  922. }
  923. }
  924. public function avg($table, $join, $column = null, $where = null)
  925. {
  926. $map = [];
  927. $query = $this->exec($this->selectContext($table, $map, $join, $column, $where, 'AVG'), $map);
  928. return $query ? 0 + $query->fetchColumn() : false;
  929. }
  930. public function sum($table, $join, $column = null, $where = null)
  931. {
  932. $map = [];
  933. $query = $this->exec($this->selectContext($table, $map, $join, $column, $where, 'SUM'), $map);
  934. return $query ? 0 + $query->fetchColumn() : false;
  935. }
  936. public function action($actions)
  937. {
  938. if (is_callable($actions)) {
  939. $this->pdo->beginTransaction();
  940. $result = $actions($this);
  941. if ($result === false) {
  942. $this->pdo->rollBack();
  943. } else {
  944. $this->pdo->commit();
  945. }
  946. } else {
  947. return false;
  948. }
  949. }
  950. public function id()
  951. {
  952. $type = $this->database_type;
  953. if ($type === 'oracle') {
  954. return 0;
  955. } elseif ($type === 'mssql') {
  956. return $this->pdo->query('SELECT SCOPE_IDENTITY()')->fetchColumn();
  957. } elseif ($type === 'pgsql') {
  958. return $this->pdo->query('SELECT LASTVAL()')->fetchColumn();
  959. }
  960. return $this->pdo->lastInsertId();
  961. }
  962. public function debug()
  963. {
  964. $this->debug_mode = true;
  965. return $this;
  966. }
  967. public function error()
  968. {
  969. return $this->statement ? $this->statement->errorInfo() : null;
  970. }
  971. public function last()
  972. {
  973. $log = end($this->logs);
  974. return $this->generate($log[0], $log[1]);
  975. }
  976. public function log()
  977. {
  978. return array_map(function ($log) {
  979. return $this->generate($log[0], $log[1]);
  980. },
  981. $this->logs
  982. );
  983. }
  984. public function info()
  985. {
  986. $output = [
  987. 'server' => 'SERVER_INFO',
  988. 'driver' => 'DRIVER_NAME',
  989. 'client' => 'CLIENT_VERSION',
  990. 'version' => 'SERVER_VERSION',
  991. 'connection' => 'CONNECTION_STATUS'
  992. ];
  993. foreach ($output as $key => $value) {
  994. $output[$key] = @$this->pdo->getAttribute(constant('PDO::ATTR_' . $value));
  995. }
  996. return $output;
  997. }
  998. }
  999. ?>