| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330 |
- <?php
- namespace KarmaFW\Database\Sql;
- use \KarmaFW\Database\Sql\SqlResultSetError;
- class SqlQuery
- {
- protected $db;
- protected $duration = null;
- protected $error = null;
- protected $recordset = null;
- protected $status = 'ready';
- protected $query = null;
- protected $results_rows_count = null;
- protected $affected_rows_count = null;
- public function __construct($db, $query=null)
- {
- $this->db = $db;
- $this->query = $query;
- }
- public function __toString()
- {
- return $this->getQuery();
- }
- public function __debugInfo() {
- return [
- //'db:protected' => get_class($this->db) ." Object",
- 'db:protected' => $this->db,
- 'status:protected' => $this->status,
- 'error:protected' => $this->error,
- 'query:protected' => $this->query,
- 'duration:protected' => $this->duration,
- //'recordset:protected' => get_class($this->recordset) ." Object",
- 'recordset:protected' => $this->recordset,
- 'results_rows_count:protected' => $this->results_rows_count,
- 'affected_rows_count:protected' => $this->affected_rows_count,
- ];
- }
- /*
- public function fetchColumn($column_name)
- {
- if ($this->status == 'ready') {
- $this->execute();
- }
- return $this->recordset->fetchColumn($column_name);
- }
- public function fetchOne()
- {
- if ($this->status == 'ready') {
- $this->execute();
- }
- return $this->recordset->fetchOne();
- }
- public function fetchAll()
- {
- if ($this->status == 'ready') {
- $this->execute();
- }
- return $this->recordset->fetchAll();
- }
- */
- public function getQuery()
- {
- return $this->query;
- }
- public function getStatus()
- {
- return $this->status;
- }
- public function execute($query=null, $params=[], $nb_tries=1)
- {
- if (! $this->db->isConnected()) {
- $this->db->connect();
- }
- if (empty($query)) {
- $query = $this->query;
- }
- if (! empty($params)) {
- $parts = explode('?', $query);
- $query = array_shift($parts);
- $i = 1;
- foreach ($params as $param) {
- if (empty($parts)) {
- throw new \Exception('SqlQuery::execute() => params error (1) [QUERY: ' . preg_replace('/\s+/', ' ', $query) . ' ]');
- }
- $param = $this->db->escape($param);
- $query .= $param;
- $query .= array_shift($parts);
- $i++;
- }
- if (! empty($parts)) {
- throw new \Exception('SqlQuery::execute() => params error (2) [QUERY: ' . preg_replace('/\s+/', ' ', $query) . ' ]');
- }
- }
- $this->query = preg_replace('/\s+/', ' ', $query);
- $this->status = 'running';
- $ts_start = microtime(true);
-
- if (! empty($_GET['debug_sql'])) {
- echo $query . "<hr />";
- }
- $_query = $query;
- if (! empty($_GET['dry_sql'])) {
- $_query = "select 1 from ( select 1 ) tmp where 0";
- }
- $rs = $this->db->getDriver()->execute($_query);
- //pre($rs);
- $ts_end = microtime(true);
- $this->duration = $ts_end - $ts_start;
-
- $this->recordset = $rs;
- $this->db->setLastQuery($this);
- if ($rs instanceOf SqlResultSetError) {
- // query error
- $error_code = $rs->getErrorCode();
- $error_msg = $rs->getErrorMessage();
- $this->error = $error_msg;
- $this->status = 'error';
- if ($error_code == 2006) {
- // MySQL server has gone away
- if ($nb_tries > 1) {
- sleep(1);
- return $this->execute($query, $params, $nb_tries-1);
- }
- }
- if ($this->db->throwOnSqlError) {
- throw new \Exception('SqlQuery::execute() => DB error [' . $error_code . '] : ' . $error_msg . PHP_EOL . '[QUERY: ' . preg_replace('/\s+/', ' ', $query) . ' ]');
- }
- //return null;
-
- } else {
- $this->status = 'success';
- }
- $this->results_rows_count = $rs->getRowsCount();
- $this->affected_rows_count = $this->db->getDriver()->getAffectedRowsCount();
- //return $this;
- return $rs;
- }
-
- public function executeSelect($query, $params=[])
- {
- // Alias of executeSelectAll
- return $this->executeSelectAll($query, $params);
- }
- public function executeSelectOne($query, $params=[])
- {
- return $this->execute($query, $params)->fetchOne();
- }
- public function executeSelectValue($query, $column_name, $params=[])
- {
- return $this->execute($query, $params)->fetchColumn($column_name);
- }
- public function executeSelectAll($query, $params=[])
- {
- return $this->execute($query, $params)->fetchAll();
- }
- public function executeSelectAllWithFoundRows($query, $params=[])
- {
- if (strpos($query, 'SQL_CALC_FOUND_ROWS') === false) {
- $query = str_replace("select ", "select SQL_CALC_FOUND_ROWS ", $query);
- }
- $rs = $this->execute($query, $params);
- $data = $rs->fetchAll();
- $found_rows = $rs->getfoundRowsCount();
- return ['found_rows' => $found_rows, 'data' => $data];
- }
- public function executeSelectAllPagination($query, $nb_per_page=10, $page_idx=1, $params=[])
- {
- if (true) {
- $page_idx = max(1, intval($page_idx));
- $nb_per_page = max(1, intval($nb_per_page));
- $offset = ($page_idx - 1) * $nb_per_page;
- $limit = $offset . ', ' . $nb_per_page;
- $query .= " limit " . $limit;
- }
- $result = $this->executeSelectAllWithFoundRows($query, $params);
- $found_rows = $result['found_rows'];
- $data = $result['data'];
- $pagination = [
- 'page' => $page_idx,
- 'limit' => $nb_per_page,
- 'offset' => $offset,
- 'page_rows' => count($data),
- 'total_rows' => $found_rows,
- 'nb_pages' => empty($nb_per_page) ? null : ceil($found_rows / $nb_per_page),
- ];
- return [
- 'pagination' => $pagination,
- 'data' => $data,
- ];
- }
- public function executeInsert($query, $params=[])
- {
- $this->execute($query, $params);
- return $this->db->getInsertId();
- }
-
- public function executeInsertAll($query, $params=[])
- {
- return $this->execute($query, $params);
- }
- public function executeUpdate($query, $params=[])
- {
- $this->execute($query, $params);
- return $this->affected_rows_count;
- }
- public function executeDelete($query, $params=[])
- {
- $this->execute($query, $params);
- return $this->affected_rows_count;
- }
- /* ### */
- public function tableSelect($table_name, $where=[], $options=[])
- {
- // Alias of tableSelectAll
- return $this->tableSelectAll($table_name, $where, $options);
- }
- public function tableSelectAll($table_name, $where=[], $options=[])
- {
- $table = new SqlTable($table_name, $this->db);
- $query = $table->buildQuery($where, $options);
- return $this->executeSelectAll($query);
- }
- public function tableSelectOne($table_name, $where=[], $options=[])
- {
- if (empty($options)) {
- $options = [];
- }
- $options['limit'] = 1;
- $table = new SqlTable($table_name, $this->db);
- $query = $table->buildQuery($where, $options);
- return $this->executeSelectOne($query);
- }
- public function tableInsert($table_name, $values=[], $options=[])
- {
- $this->tableInsertAll($table_name, [$values], $options);
- return $this->db->getInsertId();
- }
- public function tableInsertAll($table_name, $inserts=[], $options=[])
- {
- $table = new SqlTable($table_name, $this->db);
- return $table->insertAll($inserts, $options);
- }
- public function tableUpdate($table_name, $updates=[], $where=[], $options=[])
- {
- $table = new SqlTable($table_name, $this->db);
- return $table->update($updates, $where, $options);
- }
- public function tableDelete($table_name, $where=[], $options=[])
- {
- $table = new SqlTable($table_name, $this->db);
- return $table->delete($where, $options);
- }
- }
|