query.class.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. <?php
  2. /**
  3. * [WeEngine System] Copyright (c) 2014 WE7.CC
  4. * WeEngine is NOT a free software, it under the license terms, visited http://www.we7.cc/ for more details.
  5. */
  6. defined('IN_IA') or exit('Access Denied');
  7. class Query {
  8. private $clauses;
  9. private $statements = array();
  10. private $parameters = array();
  11. private $mainTable = '';
  12. private $currentTableAlias = '';
  13. private $error = array();
  14. private $lastsql = '';
  15. private $lastparams = '';
  16. private $values;
  17. public function __construct() {
  18. $this->initClauses();
  19. }
  20. private function initClauses() {
  21. $this->clauses = array(
  22. 'SELECT' => array(),
  23. 'DELETE' => '',
  24. 'UPDATE' => '',
  25. 'INSERT INTO' => '',
  26. 'FROM' => '',
  27. 'LEFTJOIN' => array(),
  28. 'INNERJOIN' => array(),
  29. 'ON' => array(),
  30. 'SET' => '',
  31. 'WHERE' => array(),
  32. 'WHEREOR' => array(),
  33. 'GROUPBY' => array(),
  34. 'HAVING' => array(),
  35. 'ORDERBY' => array(),
  36. 'LIMIT' => '',
  37. 'PAGE' => '',
  38. );
  39. foreach ($this->clauses as $clause => $value) {
  40. $this->statements[$clause] = $value;
  41. }
  42. $this->parameters = array();
  43. }
  44. private function resetClause($clause = '') {
  45. if (empty($clause)) {
  46. $this->initClauses();
  47. return $this;
  48. }
  49. $this->statements[$clause] = null;
  50. $this->parameters = array();
  51. $this->values = array();
  52. if (isset($this->clauses[$clause]) && is_array($this->clauses[$clause])) {
  53. $this->statements[$clause] = array();
  54. }
  55. return $this;
  56. }
  57. private function addStatement($clause, $statement, $parameters = array()) {
  58. if ($statement === null) {
  59. return $this->resetClause($clause);
  60. }
  61. if (isset($this->statements[$clause]) && is_array($this->statements[$clause])) {
  62. if (is_array($statement)) {
  63. $this->statements[$clause] = array_merge($this->statements[$clause], $statement);
  64. } else {
  65. if (empty($parameters) && is_array($parameters)) {
  66. $this->statements[$clause][] = $statement;
  67. } else {
  68. $this->statements[$clause][$statement] = empty($parameters) && is_array($parameters) ? '' : $parameters;
  69. }
  70. }
  71. } else {
  72. $this->statements[$clause] = $statement;
  73. }
  74. return $this;
  75. }
  76. public function __call($clause, $statement = array()) {
  77. $origin_clause = $clause;
  78. $clause = strtoupper($clause);
  79. if ($clause == 'HAVING') {
  80. array_unshift($statement, $clause);
  81. return call_user_func_array(array($this, 'condition'), $statement);
  82. }
  83. if ($clause == 'LEFTJOIN' || $clause == 'INNERJOIN') {
  84. array_unshift($statement, $clause);
  85. return call_user_func_array(array($this, 'join'), $statement);
  86. }
  87. return $this->addStatement($clause, $statement);
  88. }
  89. public function where($condition, $parameters = array(), $operator = 'AND') {
  90. if (!is_array($condition) && !($condition instanceof Closure)) {
  91. $condition = array($condition => $parameters);
  92. }
  93. $this->addStatement('WHERE', array(array($operator, $condition)));
  94. return $this;
  95. }
  96. public function whereor($condition, $parameters = array()) {
  97. return $this->where($condition, $parameters, 'OR');
  98. }
  99. public function from($tablename, $alias = '') {
  100. if (empty($tablename)) {
  101. return $this;
  102. }
  103. $this->mainTable = $tablename;
  104. $this->currentTableAlias = $alias;
  105. $this->statements['FROM'] = $this->mainTable;
  106. return $this;
  107. }
  108. public function join($clause, $tablename, $alias = '') {
  109. if (empty($tablename)) {
  110. return $this;
  111. }
  112. $this->joinTable = $tablename;
  113. return $this->addStatement($clause, $tablename . ' ' .$alias);
  114. }
  115. public function on($condition, $parameters = array()) {
  116. if ($condition === null) {
  117. return $this->resetClause('ON');
  118. }
  119. if (empty($condition)) {
  120. return $this;
  121. }
  122. if (is_array($condition)) {
  123. foreach ($condition as $key => $val) {
  124. $this->on($key, $val);
  125. }
  126. return $this;
  127. }
  128. if (empty($this->statements['ON'][$this->joinTable])) {
  129. $this->statements['ON'][$this->joinTable] = array();
  130. }
  131. $this->statements['ON'][$this->joinTable][$condition] = $parameters;
  132. return $this;
  133. }
  134. public function select($field) {
  135. if (is_string($field)) {
  136. $field = func_get_args();
  137. }
  138. if (empty($field)) {
  139. return $this;
  140. }
  141. if (count($this->statements['SELECT']) == 1) {
  142. $this->resetClause('SELECT');
  143. }
  144. return $this->addStatement('SELECT', $field);
  145. }
  146. private function condition($operator, $condition, $parameters = array()) {
  147. if ($condition === null) {
  148. return $this->resetClause('WHERE');
  149. }
  150. if (empty($condition)) {
  151. return $this;
  152. }
  153. if (is_array($condition)) {
  154. foreach ($condition as $key => $val) {
  155. $this->condition($operator, $key, $val);
  156. }
  157. return $this;
  158. }
  159. return $this->addStatement($operator, $condition, $parameters);
  160. }
  161. public function orderby($field, $direction = 'ASC') {
  162. if (is_array($field)) {
  163. foreach ($field as $column => $order) {
  164. $this->orderby($column, $order);
  165. }
  166. return $this;
  167. }
  168. $direction = strtoupper($direction);
  169. $direction = in_array($direction, array('ASC', 'DESC')) ? $direction : 'ASC';
  170. return $this->addStatement('ORDERBY', $field . ' ' . $direction);
  171. }
  172. public function fill($field, $value = '') {
  173. if (is_array($field)) {
  174. foreach ($field as $column => $val) {
  175. $this->fill($column, $val);
  176. }
  177. return $this;
  178. }
  179. $this->values[$field] = $value;
  180. return $this;
  181. }
  182. public function hasWhere() {
  183. return count($this->statements['WHERE']) > 0;
  184. }
  185. public function get() {
  186. if (empty($this->statements['SELECT'])) {
  187. $this->addStatement('SELECT', '*');
  188. }
  189. $this->lastsql = $this->buildQuery();
  190. $this->lastparams = $this->parameters;
  191. $result = pdo_fetch($this->lastsql, $this->parameters);
  192. $this->resetClause();
  193. return $result;
  194. }
  195. public function getcolumn($field = '') {
  196. if (!empty($field)) {
  197. $this->select($field);
  198. }
  199. if (empty($this->statements['SELECT'])) {
  200. $this->addStatement('SELECT', '*');
  201. }
  202. $this->lastsql = $this->buildQuery();
  203. $this->lastparams = $this->parameters;
  204. $result = pdo_fetchcolumn($this->lastsql, $this->parameters);
  205. $this->resetClause();
  206. return $result;
  207. }
  208. public function getall($keyfield = '') {
  209. if (empty($this->statements['SELECT'])) {
  210. $this->addStatement('SELECT', '*');
  211. }
  212. $this->lastsql = $this->buildQuery();
  213. $this->lastparams = $this->parameters;
  214. $result = pdo_fetchall($this->lastsql, $this->parameters, $keyfield);
  215. $this->resetClause();
  216. return $result;
  217. }
  218. public function getLastQueryTotal() {
  219. $lastquery = $this->getLastQuery();
  220. $countsql = str_replace(substr($lastquery[0], 0, strpos($lastquery[0], 'FROM')), 'SELECT COUNT(*) ', $lastquery[0]);
  221. if (strpos($countsql, 'LIMIT') !== false) {
  222. $countsql = substr($countsql, 0, strpos($countsql, 'LIMIT'));
  223. }
  224. if (strexists(strtoupper($countsql), 'GROUP BY')) {
  225. $result = pdo_fetchall($countsql, $this->lastparams, $keyfield);
  226. $result = count($result);
  227. } else {
  228. $result = pdo_fetchcolumn($countsql, $this->lastparams, $keyfield);
  229. }
  230. return $result;
  231. }
  232. public function count() {
  233. $where = array();
  234. if (!empty($this->statements['WHERE'])) {
  235. foreach ($this->statements['WHERE'] as $row) {
  236. $where = array_merge($where, $row[1]);
  237. }
  238. }
  239. return pdo_count($this->statements['FROM'], $where);
  240. }
  241. public function exists() {
  242. $where = array();
  243. if (!empty($this->statements['WHERE'])) {
  244. foreach ($this->statements['WHERE'] as $row) {
  245. $where = array_merge($where, $row[1]);
  246. }
  247. }
  248. return pdo_exists($this->statements['FROM'], $where);
  249. }
  250. public function delete() {
  251. $where = $this->buildWhereArray();
  252. $result = pdo_delete($this->statements['FROM'], $where);
  253. $this->resetClause();
  254. return $result;
  255. }
  256. public function insert() {
  257. $result = pdo_insert($this->statements['FROM'], $this->values);
  258. $this->resetClause();
  259. return $result;
  260. }
  261. public function update() {
  262. $where = $this->buildWhereArray();
  263. if (empty($where)) {
  264. return error(-1, '未指定更新条件');
  265. }
  266. $result = pdo_update($this->statements['FROM'], $this->values, $where);
  267. $this->resetClause();
  268. return $result;
  269. }
  270. private function buildQuery() {
  271. $query = '';
  272. foreach ($this->clauses as $clause => $separator) {
  273. if (!empty($this->statements[$clause])) {
  274. if (method_exists($this, 'buildQuery' . $clause)) {
  275. $query .= call_user_func(array($this, 'buildQuery' . $clause), $this->statements[$clause]);
  276. } elseif (is_string($separator)) {
  277. $query .= " $clause " . implode($separator, $this->statements[$clause]);
  278. } elseif ($separator === null) {
  279. $query .= " $clause " . $this->statements[$clause];
  280. }
  281. }
  282. }
  283. return trim($query);
  284. }
  285. private function buildQueryWhere() {
  286. $closure = array();
  287. $sql = '';
  288. foreach ($this->statements['WHERE'] as $i => $wheregroup) {
  289. $where = array();
  290. if (!empty($wheregroup[1]) && $wheregroup[1] instanceof Closure) {
  291. $closure[] = $wheregroup;
  292. } else {
  293. $where = \SqlPaser::parseParameter($wheregroup[1], 'AND', $this->currentTableAlias);
  294. $this->parameters = array_merge($this->parameters, $where['params']);
  295. $sql .= ' ' . $wheregroup[0] . ' ' . $where['fields'];
  296. }
  297. unset($this->statements['WHERE'][$i]);
  298. }
  299. foreach ($closure as $callback) {
  300. $callback[1]($this);
  301. $subsql = '';
  302. $where = array();
  303. foreach ($this->statements['WHERE'] as $i => $wheregroup) {
  304. $where = \SqlPaser::parseParameter($wheregroup[1], 'AND', $this->currentTableAlias);
  305. $this->parameters = array_merge($this->parameters, $where['params']);
  306. $subsql .= ' ' . $wheregroup[0] . ' ' . $where['fields'];
  307. unset($this->statements['WHERE'][$i]);
  308. }
  309. $subsql = ltrim(ltrim($subsql, ' AND '), ' OR ');
  310. $sql .= " {$callback[0]} ( $subsql )";
  311. }
  312. return empty($where['fields']) ? '' : " WHERE " . ltrim(ltrim($sql, ' AND '), ' OR ');
  313. }
  314. private function buildQueryWhereor() {
  315. $where = \SqlPaser::parseParameter($this->statements['WHEREOR'], 'OR', $this->currentTableAlias);
  316. $this->parameters = array_merge($this->parameters, $where['params']);
  317. if (empty($where['fields'])) {
  318. return '';
  319. }
  320. if (empty($this->statements['WHERE'])) {
  321. return " WHERE {$where['fields']} ";
  322. } else {
  323. return " OR {$where['fields']} ";
  324. }
  325. }
  326. private function buildQueryHaving() {
  327. $where = \SqlPaser::parseParameter($this->statements['HAVING'], 'AND', $this->currentTableAlias);
  328. $this->parameters = array_merge($this->parameters, $where['params']);
  329. return empty($where['fields']) ? '' : " HAVING {$where['fields']} ";
  330. }
  331. private function buildQueryFrom() {
  332. return " FROM " . tablename($this->statements['FROM']) . ' ' . $this->currentTableAlias;
  333. }
  334. private function buildQueryLeftjoin() {
  335. return $this->buildQueryJoin('LEFTJOIN');
  336. }
  337. private function buildQueryInnerjoin() {
  338. return $this->buildQueryJoin('INNERJOIN');
  339. }
  340. private function buildQueryJoin($clause) {
  341. if (empty($this->statements[$clause])) {
  342. return '';
  343. }
  344. $clause_operator = array(
  345. 'LEFTJOIN' => ' LEFT JOIN ',
  346. 'INNERJOIN' => ' INNER JOIN ',
  347. );
  348. $sql = '';
  349. foreach ($this->statements[$clause] as $tablename) {
  350. list($tablename, $alias) = explode(' ', $tablename);
  351. $sql .= $clause_operator[$clause] . tablename($tablename) . ' ' . $alias;
  352. if (!empty($this->statements['ON'][$tablename])) {
  353. $sql .= " ON ";
  354. $split = "";
  355. foreach ($this->statements['ON'][$tablename] as $field => $condition) {
  356. $operator = '';
  357. if (strexists($field, ' ')) {
  358. list($field, $operator) = explode(' ', $field);
  359. }
  360. $operator = $operator ? $operator : '=';
  361. $field = '`' . str_replace('.', '`.`', $field) . '`';
  362. if (strexists($condition, '.')) {
  363. $condition = '`' . str_replace('.', '`.`', $condition) . '`';
  364. }
  365. $sql .= " $split $field $operator $condition ";
  366. $split = " AND ";
  367. }
  368. }
  369. }
  370. return $sql;
  371. }
  372. private function buildQuerySelect() {
  373. return \SqlPaser::parseSelect($this->statements['SELECT'], $this->currentTableAlias);
  374. }
  375. private function buildQueryLimit() {
  376. return \SqlPaser::parseLimit($this->statements['LIMIT'], false);
  377. }
  378. private function buildQueryPage() {
  379. return \SqlPaser::parseLimit($this->statements['PAGE'], true);
  380. }
  381. private function buildQueryOrderby() {
  382. return \SqlPaser::parseOrderby($this->statements['ORDERBY'], $this->currentTableAlias);
  383. }
  384. private function buildQueryGroupby() {
  385. return \SqlPaser::parseGroupby($this->statements['GROUPBY'], $this->currentTableAlias);
  386. }
  387. private function buildWhereArray() {
  388. $where = array();
  389. if (!empty($this->statements['WHERE'])) {
  390. foreach ($this->statements['WHERE'] as $row) {
  391. $where = array_merge($where, $row[1]);
  392. }
  393. }
  394. return $where;
  395. }
  396. public function getLastQuery() {
  397. return array($this->lastsql, $this->lastparams);
  398. }
  399. }