SqlQuery.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. <?php
  2. namespace KarmaFW\Database\Sql;
  3. use \KarmaFW\Database\Sql\SqlResultSetError;
  4. class SqlQuery
  5. {
  6. protected $db;
  7. protected $duration = null;
  8. protected $error = null;
  9. protected $recordset = null;
  10. protected $status = 'ready';
  11. protected $query = null;
  12. protected $results_rows_count = null;
  13. protected $affected_rows_count = null;
  14. public function __construct($db, $query=null)
  15. {
  16. $this->db = $db;
  17. $this->query = $query;
  18. }
  19. public function __toString()
  20. {
  21. return $this->getQuery();
  22. }
  23. public function __debugInfo() {
  24. return [
  25. //'db:protected' => get_class($this->db) ." Object",
  26. 'db:protected' => $this->db,
  27. 'status:protected' => $this->status,
  28. 'error:protected' => $this->error,
  29. 'query:protected' => $this->query,
  30. 'duration:protected' => $this->duration,
  31. //'recordset:protected' => get_class($this->recordset) ." Object",
  32. 'recordset:protected' => $this->recordset,
  33. 'results_rows_count:protected' => $this->results_rows_count,
  34. 'affected_rows_count:protected' => $this->affected_rows_count,
  35. ];
  36. }
  37. /*
  38. public function fetchColumn($column_name)
  39. {
  40. if ($this->status == 'ready') {
  41. $this->execute();
  42. }
  43. return $this->recordset->fetchColumn($column_name);
  44. }
  45. public function fetchOne()
  46. {
  47. if ($this->status == 'ready') {
  48. $this->execute();
  49. }
  50. return $this->recordset->fetchOne();
  51. }
  52. public function fetchAll()
  53. {
  54. if ($this->status == 'ready') {
  55. $this->execute();
  56. }
  57. return $this->recordset->fetchAll();
  58. }
  59. */
  60. public function getQuery()
  61. {
  62. return $this->query;
  63. }
  64. public function getStatus()
  65. {
  66. return $this->status;
  67. }
  68. public function execute($query=null, $params=[], $nb_tries=1)
  69. {
  70. if (! $this->db->isConnected()) {
  71. $this->db->connect();
  72. }
  73. if (empty($query)) {
  74. $query = $this->query;
  75. }
  76. if (! empty($params)) {
  77. $parts = explode('?', $query);
  78. $query = array_shift($parts);
  79. $i = 1;
  80. foreach ($params as $param) {
  81. if (empty($parts)) {
  82. throw new \Exception('SqlQuery::execute() => params error (1) [QUERY: ' . preg_replace('/\s+/', ' ', $query) . ' ]');
  83. }
  84. $param = $this->db->escape($param);
  85. $query .= $param;
  86. $query .= array_shift($parts);
  87. $i++;
  88. }
  89. if (! empty($parts)) {
  90. throw new \Exception('SqlQuery::execute() => params error (2) [QUERY: ' . preg_replace('/\s+/', ' ', $query) . ' ]');
  91. }
  92. }
  93. $this->query = preg_replace('/\s+/', ' ', $query);
  94. $this->status = 'running';
  95. $ts_start = microtime(true);
  96. if (! empty($_GET['debug_sql'])) {
  97. echo $query . "<hr />";
  98. }
  99. $_query = $query;
  100. if (! empty($_GET['dry_sql'])) {
  101. $_query = "select 1 from ( select 1 ) tmp where 0";
  102. }
  103. $rs = $this->db->getDriver()->execute($_query);
  104. //pre($rs);
  105. $ts_end = microtime(true);
  106. $this->duration = $ts_end - $ts_start;
  107. $this->recordset = $rs;
  108. $this->db->setLastQuery($this);
  109. if ($rs instanceOf SqlResultSetError) {
  110. // query error
  111. $error_code = $rs->getErrorCode();
  112. $error_msg = $rs->getErrorMessage();
  113. $this->error = $error_msg;
  114. $this->status = 'error';
  115. if ($error_code == 2006) {
  116. // MySQL server has gone away
  117. if ($nb_tries > 1) {
  118. sleep(1);
  119. return $this->execute($query, $params, $nb_tries-1);
  120. }
  121. }
  122. if ($this->db->throwOnSqlError) {
  123. throw new \Exception('SqlQuery::execute() => DB error [' . $error_code . '] : ' . $error_msg . PHP_EOL . '[QUERY: ' . preg_replace('/\s+/', ' ', $query) . ' ]');
  124. }
  125. //return null;
  126. } else {
  127. $this->status = 'success';
  128. }
  129. $this->results_rows_count = $rs->getRowsCount();
  130. $this->affected_rows_count = $this->db->getDriver()->getAffectedRowsCount();
  131. //return $this;
  132. return $rs;
  133. }
  134. public function executeSelect($query, $params=[])
  135. {
  136. // Alias of executeSelectAll
  137. return $this->executeSelectAll($query, $params);
  138. }
  139. public function executeSelectOne($query, $params=[])
  140. {
  141. return $this->execute($query, $params)->fetchOne();
  142. }
  143. public function executeSelectValue($query, $column_name, $params=[])
  144. {
  145. return $this->execute($query, $params)->fetchColumn($column_name);
  146. }
  147. public function executeSelectAll($query, $params=[])
  148. {
  149. return $this->execute($query, $params)->fetchAll();
  150. }
  151. public function executeSelectAllWithFoundRows($query, $params=[])
  152. {
  153. if (strpos($query, 'SQL_CALC_FOUND_ROWS') === false) {
  154. $query = str_replace("select ", "select SQL_CALC_FOUND_ROWS ", $query);
  155. }
  156. $rs = $this->execute($query, $params);
  157. $data = $rs->fetchAll();
  158. $found_rows = $rs->getfoundRowsCount();
  159. return ['found_rows' => $found_rows, 'data' => $data];
  160. }
  161. public function executeSelectAllPagination($query, $nb_per_page=10, $page_idx=1, $params=[])
  162. {
  163. if (true) {
  164. $page_idx = max(1, intval($page_idx));
  165. $nb_per_page = max(1, intval($nb_per_page));
  166. $offset = ($page_idx - 1) * $nb_per_page;
  167. $limit = $offset . ', ' . $nb_per_page;
  168. $query .= " limit " . $limit;
  169. }
  170. $result = $this->executeSelectAllWithFoundRows($query, $params);
  171. $found_rows = $result['found_rows'];
  172. $data = $result['data'];
  173. $pagination = [
  174. 'page' => $page_idx,
  175. 'limit' => $nb_per_page,
  176. 'offset' => $offset,
  177. 'page_rows' => count($data),
  178. 'total_rows' => $found_rows,
  179. 'nb_pages' => empty($nb_per_page) ? null : ceil($found_rows / $nb_per_page),
  180. ];
  181. return [
  182. 'pagination' => $pagination,
  183. 'data' => $data,
  184. ];
  185. }
  186. public function executeInsert($query, $params=[])
  187. {
  188. $this->execute($query, $params);
  189. return $this->db->getInsertId();
  190. }
  191. public function executeInsertAll($query, $params=[])
  192. {
  193. return $this->execute($query, $params);
  194. }
  195. public function executeUpdate($query, $params=[])
  196. {
  197. $this->execute($query, $params);
  198. return $this->affected_rows_count;
  199. }
  200. public function executeDelete($query, $params=[])
  201. {
  202. $this->execute($query, $params);
  203. return $this->affected_rows_count;
  204. }
  205. /* ### */
  206. public function tableSelect($table_name, $where=[], $options=[])
  207. {
  208. // Alias of tableSelectAll
  209. return $this->tableSelectAll($table_name, $where, $options);
  210. }
  211. public function tableSelectAll($table_name, $where=[], $options=[])
  212. {
  213. $table = new SqlTable($table_name, $this->db);
  214. $query = $table->buildQuery($where, $options);
  215. return $this->executeSelectAll($query);
  216. }
  217. public function tableSelectOne($table_name, $where=[], $options=[])
  218. {
  219. if (empty($options)) {
  220. $options = [];
  221. }
  222. $options['limit'] = 1;
  223. $table = new SqlTable($table_name, $this->db);
  224. $query = $table->buildQuery($where, $options);
  225. return $this->executeSelectOne($query);
  226. }
  227. public function tableInsert($table_name, $values=[], $options=[])
  228. {
  229. $this->tableInsertAll($table_name, [$values], $options);
  230. return $this->db->getInsertId();
  231. }
  232. public function tableInsertAll($table_name, $inserts=[], $options=[])
  233. {
  234. $table = new SqlTable($table_name, $this->db);
  235. return $table->insertAll($inserts, $options);
  236. }
  237. public function tableUpdate($table_name, $updates=[], $where=[], $options=[])
  238. {
  239. $table = new SqlTable($table_name, $this->db);
  240. return $table->update($updates, $where, $options);
  241. }
  242. public function tableDelete($table_name, $where=[], $options=[])
  243. {
  244. $table = new SqlTable($table_name, $this->db);
  245. return $table->delete($where, $options);
  246. }
  247. }