SqlTable.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. <?php
  2. namespace KarmaFW\Database\Sql;
  3. use \KarmaFW\App;
  4. class SqlTable
  5. {
  6. protected $db;
  7. protected $table_name;
  8. protected $columns = null;
  9. public function __construct($table_name, $db=null)
  10. {
  11. if (is_null($db)) {
  12. $db = App::getDb();
  13. }
  14. $this->table_name = $table_name;
  15. $this->db = $db;
  16. }
  17. public function getTableName()
  18. {
  19. return $this->table_name;
  20. }
  21. public function __toString()
  22. {
  23. return $this->getTableName();
  24. }
  25. public function exists($force_refresh=false)
  26. {
  27. static $tables = [];
  28. if (empty($tables[$this->table_name]) || $force_refresh) {
  29. $schema = new SqlSchema($this->db);
  30. $tables[$this->table_name] = $schema->tableExists($this->table_name);
  31. }
  32. return $tables[$this->table_name];
  33. }
  34. public function listColumns($force_refresh=false)
  35. {
  36. static $tables = [];
  37. if (empty($tables[$this->table_name]) || $force_refresh) {
  38. $schema = new SqlSchema($this->db);
  39. $tables[$this->table_name] = $schema->listTableColumns($this->table_name, $column=null);
  40. }
  41. $this->columns = $tables[$this->table_name];
  42. return $tables[$this->table_name];
  43. }
  44. public function getEmpty()
  45. {
  46. $columns = $this->listColumns();
  47. return array_map(function ($v) {return '';}, $columns);
  48. }
  49. public function insert($values=[], $options=[]) /* : int */
  50. {
  51. $this->insertAll([$values], $options);
  52. return $this->db->getInsertId();
  53. }
  54. public function insertAll($rows=[], $options=[])
  55. {
  56. /*
  57. $rows = [
  58. ['id' => 1, 'name' => 'foo'],
  59. ['id' => 2, 'name' => 'bar'],
  60. ];
  61. */
  62. $values_array = [];
  63. $fields_sql = '';
  64. foreach ($rows as $values) {
  65. $insert = $this->db->buildSqlInsertValues($values);
  66. $values_array[] = "(" . $insert['values'] . ")";
  67. if (empty($fields_sql)) {
  68. $fields_sql = $insert['fields'];
  69. }
  70. }
  71. if (empty($values_array)) {
  72. return null;
  73. }
  74. if (! empty($options['on duplicate key updates'])) {
  75. $options['on_duplicate_key_updates'] = $options['on duplicate key updates'];
  76. }
  77. if (! empty($options['on_duplicate_key_update'])) {
  78. $options['on_duplicate_key_updates'] = $options['on_duplicate_key_update'];
  79. }
  80. if (! empty($options['on duplicate key update'])) {
  81. $options['on_duplicate_key_updates'] = $options['on duplicate key update'];
  82. }
  83. if (! empty($options['on duplicate key'])) {
  84. $options['on_duplicate_key_updates'] = $options['on duplicate key'];
  85. }
  86. if (! empty($options['on_duplicate_key'])) {
  87. $options['on_duplicate_key_updates'] = $options['on_duplicate_key'];
  88. }
  89. if (! empty($options['on_duplicate'])) {
  90. $options['on_duplicate_key_updates'] = $options['on_duplicate'];
  91. }
  92. if (! empty($options['on duplicate'])) {
  93. $options['on_duplicate_key_updates'] = $options['on duplicate'];
  94. }
  95. $ignore_sql = empty($options['ignore']) ? '' : 'ignore';
  96. $on_duplicate_key_updates_sql = empty($options['on_duplicate_key_updates']) ? "" : ("on duplicate key update " . $options['on_duplicate_key_updates']);
  97. $chunks = [];
  98. if (empty($options['chunk'])) {
  99. $chunks = [$values_array];
  100. } else {
  101. $chunks = array_chunk($values_array, $options['chunk']);
  102. }
  103. $ok = false;
  104. foreach ($chunks as $chunk) {
  105. $inserts_sql = implode(', ', $chunk);
  106. // TODO: gerer on_duplicate_key_updates comme le where, dans un tableau et non dans un string
  107. $query = "insert " . $ignore_sql . " into " . $this->table_name . " (" . $fields_sql . ") values " . $inserts_sql . " " . $on_duplicate_key_updates_sql;
  108. if (! empty($options['debug'])) {
  109. echo "<pre>" .preg_replace('/\s+/', ' ', $query) . "</pre>";
  110. }
  111. if (isset($options['dry'])) {
  112. $ok = $options['dry'];
  113. } else {
  114. $ok = $this->db->createQuery()->executeInsertAll($query);
  115. }
  116. }
  117. return $ok;
  118. }
  119. public function insertSelect($insert_table, $insert_keys=null, $where=null, $options=[])
  120. {
  121. $options_select = array_slice($options, 0);
  122. unset($options_select['debug']);
  123. $ignore_sql = empty($options['ignore']) ? '' : 'ignore';
  124. $on_duplicate_key_updates_sql = empty($options['on_duplicate_key_updates']) ? "" : ("on duplicate key update " . $options['on_duplicate_key_updates']);
  125. $sql_keys = $insert_keys ? ("(" . $insert_keys . ")") : "";
  126. $insert = "insert " . $ignore_sql . " into " . $insert_table . " " . $sql_keys . PHP_EOL;
  127. $query = $this->buildQuery($where, $options_select);
  128. $query = $insert . " " . $query . " " . $on_duplicate_key_updates_sql;
  129. if (! empty($options['debug'])) {
  130. echo "<pre>" .preg_replace('/\s+/', ' ', $query) . "</pre>";
  131. }
  132. if (! empty($options['dry'])) {
  133. return true;
  134. }
  135. return $this->db->createQuery()->execute($query);
  136. }
  137. public function update(array $updates=[], array $where=[], $options=[]) /* : int */
  138. {
  139. $limit_sql = (isset($options['limit']) && ! is_null($options['limit'])) ? ("limit " . $options['limit']) : "";
  140. $join_sql = isset($options['join']) ? implode(" ", $options['join']) : "";
  141. /*
  142. if (isset($options['group by']) && empty($options['group_by'])) {
  143. $options['group_by'] = $options['group by'];
  144. }
  145. $group_by_sql = isset($options['group_by']) ? ("group by " . $options['group_by']) : "";
  146. */
  147. $query = "update " . $this->table_name . "
  148. " . $join_sql . "
  149. set " . $this->db->buildSqlUpdateValues($updates) . "
  150. where " . $this->db->buildSqlWhere($where) . "
  151. " . $limit_sql;
  152. if (! empty($options['debug'])) {
  153. echo "<pre>" .preg_replace('/\s+/', ' ', $query) . "</pre>";
  154. }
  155. if (! empty($options['dry'])) {
  156. return true;
  157. }
  158. return $this->db->createQuery()->executeUpdate($query);
  159. }
  160. public function delete(array $where=[], $options=[]) /* : int */
  161. {
  162. $limit_sql = isset($options['limit']) ? ("limit " . $options['limit']) : "";
  163. $query = "delete from " . $this->table_name . "
  164. where " . $this->db->buildSqlWhere($where) . "
  165. " . $limit_sql;
  166. if (! empty($options['debug'])) {
  167. echo "<pre>" .preg_replace('/\s+/', ' ', $query) . "</pre>";
  168. }
  169. if (! empty($options['dry'])) {
  170. return true;
  171. }
  172. return $this->db->createQuery()->executeDelete($query);
  173. }
  174. public function all($where=null, $options=[])
  175. {
  176. // Alias of getAll
  177. return $this->getAll($where, $options);
  178. }
  179. public function select($where=null, $options=[])
  180. {
  181. // Alias of getAll
  182. return $this->getAll($where, $options);
  183. }
  184. public function selectAll($where=null, $options=[])
  185. {
  186. // Alias of getAll
  187. return $this->getAll($where, $options);
  188. }
  189. public function getAll($where=null, $options=[]) /* : array */
  190. {
  191. $query = $this->buildQuery($where, $options);
  192. if (! empty($options['dry'])) {
  193. return [];
  194. }
  195. return $this->db->createQuery()->executeSelectAll($query);
  196. }
  197. public function getAllWithFoundRows($where=null, $options=[]) /* : array */
  198. {
  199. $options['CALC_FOUND_ROWS'] = true;
  200. $query = $this->buildQuery($where, $options);
  201. if (! empty($options['dry'])) {
  202. $data = [];
  203. $found_rows = 0;
  204. } else {
  205. $rs = $this->db->createQuery()->execute($query);
  206. $data = $rs->fetchAll();
  207. $found_rows = $rs->getfoundRowsCount();
  208. }
  209. return ['found_rows' => $found_rows, 'data' => $data];
  210. }
  211. public function getAllPagination($where=null, $nb_per_page=10, $page_idx=1, $options=[])
  212. {
  213. if (! is_array($options)) {
  214. $options = [];
  215. }
  216. if (! empty($options['output'])) {
  217. $page_idx = 1;
  218. $nb_per_page = null;
  219. $offset = 0;
  220. unset($options['limit']);
  221. } else {
  222. $page_idx = max(1, intval($page_idx));
  223. $nb_per_page = max(1, intval($nb_per_page));
  224. $offset = ($page_idx - 1) * $nb_per_page;
  225. $options['limit'] = $offset . ', ' . $nb_per_page;
  226. }
  227. $result = $this->getAllWithFoundRows($where, $options);
  228. $found_rows = $result['found_rows'];
  229. $data = $result['data'];
  230. $pagination = [
  231. 'page' => $page_idx,
  232. 'limit' => $nb_per_page,
  233. 'offset' => $offset,
  234. 'page_rows' => count($data),
  235. 'total_rows' => $found_rows,
  236. 'nb_pages' => empty($nb_per_page) ? 1 : ceil($found_rows / $nb_per_page),
  237. ];
  238. return [
  239. 'pagination' => $pagination,
  240. 'data' => $data,
  241. ];
  242. }
  243. public function selectCount($where=null, $options=[])
  244. {
  245. $options['select'] = 'count(*) as nb';
  246. $row = $this->getOne($where, $options);
  247. return empty($row['nb']) ? 0 : $row['nb'];
  248. }
  249. public function one($where=null, $options=[])
  250. {
  251. // Alias of getOne
  252. return $this->getOne($where, $options);
  253. }
  254. public function selectOne($where=null, $options=[])
  255. {
  256. // Alias of getOne
  257. return $this->getOne($where, $options);
  258. }
  259. public function getOne($where=null, $options=[]) /* : array */
  260. {
  261. $options['limit'] = 1;
  262. //return $this->getAll($where, $options)->fetchOne();
  263. $query = $this->buildQuery($where, $options);
  264. if (! empty($options['dry'])) {
  265. return [];
  266. }
  267. return $this->db->createQuery()->executeSelectOne($query);
  268. }
  269. public function buildQuery($where=null, $options=[]) /* : string */
  270. {
  271. if (empty($options['order_by']) && ! empty($options['order by'])) {
  272. // alias "order by" to "order_by"
  273. $options['order_by'] = $options['order by'];
  274. }
  275. if (empty($options['group_by']) && ! empty($options['group by'])) {
  276. // alias "group by" to "group_by"
  277. $options['group_by'] = $options['group by'];
  278. }
  279. $limit_sql = isset($options['limit']) ? ("limit " . $options['limit']) : "";
  280. $group_by_sql = isset($options['group_by']) ? ("group by " . $options['group_by']) : "";
  281. $order_by_sql = isset($options['order_by']) ? ("order by " . $options['order_by']) : "";
  282. $having_sql = isset($options['having']) ? ("having " . $options['having']) : "";
  283. $table_name = isset($options['from']) ? $options['from'] : $this->table_name;
  284. $select_sql = '*';
  285. if (! empty($options['select'])) {
  286. $options['select'] = is_array($options['select']) ? $options['select'] : [$options['select']];
  287. $select_sql = implode(', ', $options['select']);
  288. }
  289. if (! empty($options['CALC_FOUND_ROWS']) && stripos($select_sql, 'SQL_CALC_FOUND_ROWS') === false) {
  290. $select_sql = 'SQL_CALC_FOUND_ROWS ' . $select_sql;
  291. }
  292. if (! empty($options['where'])) {
  293. if (empty($where)) {
  294. $where = $options['where'];
  295. } else {
  296. $where = array_merge($where, $options['where']);
  297. }
  298. }
  299. $table_alias = empty($options['alias']) ? "" : $options['alias'];
  300. $joins_sql = '';
  301. if (! empty($options['join'])) {
  302. $options['join'] = is_array($options['join']) ? $options['join'] : [$options['join']];
  303. $joins_sql = implode(' ', $options['join']);
  304. }
  305. $query = "select " . $select_sql . "
  306. from " . $this->table_name . " " . $table_alias . "
  307. " . $joins_sql . "
  308. where " . $this->db->buildSqlWhere($where) . "
  309. " . $group_by_sql . "
  310. " . $having_sql . "
  311. " . $order_by_sql . "
  312. " . $limit_sql;
  313. if (! empty($options['debug'])) {
  314. echo "<pre>" .preg_replace('/\s+/', ' ', $query) . "</pre>";
  315. }
  316. return $query;
  317. }
  318. }