Sql.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. <?php namespace Dever;
  2. use Dever;
  3. class Sql
  4. {
  5. public function desc($table)
  6. {
  7. return 'DESC ' . $table;
  8. }
  9. public function truncate($table)
  10. {
  11. return 'TRUNCATE TABLE `' . $table . '`';
  12. }
  13. public function optimize($table)
  14. {
  15. return 'OPTIMIZE TABLE `' . $table . '`';
  16. }
  17. public function analyze($table)
  18. {
  19. return 'ANALYZE TABLE `' . $table . '`';
  20. }
  21. public function explain($sql)
  22. {
  23. return 'EXPLAIN ' . $sql;
  24. }
  25. public function showIndex($table)
  26. {
  27. return 'SHOW INDEX FROM ' . $table;
  28. }
  29. public function create($config)
  30. {
  31. if (isset(Dever::config('setting')['database']['create']) && !Dever::config('setting')['database']['create']) {
  32. return;
  33. }
  34. $sql = 'DROP TABLE IF EXISTS `' . $config['table'] . '`;CREATE TABLE IF NOT EXISTS `' . $config['table'] . '`(';
  35. $struct = array('id' => array('name' => 'ID', 'type' => 'int(11)'),'cdate' => array('name' => 'cdate', 'type' => 'int(11)'));
  36. $struct = array_merge($struct, $config['struct']);
  37. foreach ($struct as $k => $v) {
  38. $sql .= $this->createField($k, $v) . ',';
  39. }
  40. $sql = rtrim($sql, ',') . ')';
  41. if (isset($config['auto'])) {
  42. $sql .= ' AUTO_INCREMENT = ' . $config['auto'];
  43. }
  44. if (isset($config['type'])) {
  45. $sql .= ' ENGINE = ' . $config['type'] . ' ';
  46. }
  47. return $sql . ' COMMENT="'.$config['name'].'"';
  48. }
  49. public function createField($name, $set)
  50. {
  51. $field = '`' . $name . '` ' . strtoupper($set['type']);
  52. if ($name == 'id') {
  53. $field .= ' UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL';
  54. } elseif (strpos($set['type'], 'text') !== false) {
  55. $field .= ' NULL';
  56. } elseif (isset($set['default'])) {
  57. $field .= ' NOT NULL DEFAULT "' . $set['default'] . '"';
  58. } elseif (strpos($set['type'], 'int') !== false || strpos($set['type'], 'float') !== false || strpos($set['type'], 'decimal') !== false || strpos($set['type'], 'double') !== false) {
  59. $field .= ' NOT NULL DEFAULT 0';
  60. } else {
  61. $field .= ' NOT NULL DEFAULT ""';
  62. }
  63. if (isset($set['name'])) {
  64. $field .= ' COMMENT \'' . $set['name'] . '\'';
  65. }
  66. return $field;
  67. }
  68. public function alter($table, $struct, $data)
  69. {
  70. $sql = [];
  71. $alter = 'ALTER TABLE `' . $table . '` ';
  72. foreach ($data as $v) {
  73. $field = $v['Field'];
  74. if ($field != 'id' && $field != 'cdate') {
  75. $set = $struct[$field] ?? false;
  76. if ($set) {
  77. if ($set['type'] != $v['Type'] || (isset($set['default']) && $set['default'] != $v['Default'])) {
  78. $sql[] = $alter . ' CHANGE `' . $field . '` ' . $this->createField($field, $set);
  79. } else {
  80. unset($struct[$field]);
  81. }
  82. } else {
  83. $sql[] = $alter . ' DROP `' . $field . '`';
  84. }
  85. }
  86. }
  87. if ($struct) {
  88. foreach ($struct as $k => $v) {
  89. $sql[] = $alter . ' ADD ' . $this->createField($k, $v);
  90. }
  91. }
  92. return implode(';', $sql);
  93. }
  94. public function index($table, $index, $del = [])
  95. {
  96. $sql = [];
  97. $alter = 'ALTER TABLE `' . $table . '` ';
  98. foreach ($del as $v) {
  99. if ($v['Key_name'] != 'PRIMARY') {
  100. $sql[] = $alter . ' DROP INDEX ' . $v['Key_name'];
  101. }
  102. }
  103. if ($index) {
  104. foreach ($index as $k => $v) {
  105. $t = 'INDEX';
  106. if (strpos($v, '.')) {
  107. list($v, $t) = explode('.', $v);
  108. }
  109. $sql[] = $alter . ' ADD ' . strtoupper($t) . ' ' . $k . ' (' . $v . ')';
  110. }
  111. }
  112. return implode(';', $sql);
  113. }
  114. public function partition($table, $partition, $index)
  115. {
  116. $state = true;
  117. foreach ($index as $k => $v) {
  118. if ($v['Key_name'] == 'PRIMARY' && $v['Column_name'] == $partition['field']) {
  119. $state = false;
  120. }
  121. }
  122. $alter = '';
  123. if ($state) {
  124. $type = $partition['type'];
  125. if ($partition['type'] == 'time') {
  126. $type = 'range';
  127. }
  128. $alter = 'ALTER TABLE `' . $table . '` DROP PRIMARY KEY, ADD PRIMARY KEY (`id`, `'.$partition['field'].'`) USING BTREE;ALTER TABLE `' . $table . '` PARTITION BY '.strtoupper($type).' ('.$partition['field'].') ';
  129. } else {
  130. $alter = 'ALTER TABLE `' . $table . '` ADD PARTITION ';
  131. }
  132. if ($partition['type'] == 'range' || $partition['type'] == 'time') {
  133. $name = $partition['value'];
  134. if ($partition['type'] == 'time') {
  135. $name = date('Ymd', $name - 86400);
  136. }
  137. $sql = 'PARTITION p'.$name.' VALUES LESS THAN ('.$partition['value'].')';
  138. return $alter . '('.$sql.')';
  139. } elseif ($partition['type'] == 'list') {
  140. $sql = [];
  141. foreach ($partition['value'] as $k => $v) {
  142. $k = str_replace('-', '_', $v);
  143. $sql[] = 'PARTITION p'.$k.' VALUES IN ('.$v.')';
  144. }
  145. $sql = implode(',', $sql);
  146. return $alter . '('.$sql.')';
  147. } elseif ($partition['type'] == 'hash' || $partition['type'] == 'key') {
  148. if ($state) {
  149. return $alter . 'PARTITIONS ' . $partition['value'];
  150. }
  151. return $this->desc($table);
  152. }
  153. }
  154. public function select($table, $param, &$bind, $set = [], $field = [], $version = false, $type = '')
  155. {
  156. $col = '*';
  157. $rule = '';
  158. if (isset($set['col'])) {
  159. $col = $set['col'];
  160. }
  161. if (isset($set['join'])) {
  162. $table .= ' AS main';
  163. foreach ($set['join'] as $k => $v) {
  164. $table .= ' ' . $v['type'] . ' ' . DEVER_PROJECT . '_' . $v['table'] . ' AS t' . $k . ' ON ' . $v['on'];
  165. }
  166. }
  167. if (isset($set['group'])) {
  168. $rule .= ' GROUP BY ' . $set['group'];
  169. }
  170. if (isset($set['order'])) {
  171. if ($type == 'Influxdb') {
  172. $set['order'] = ' time desc';
  173. }
  174. $rule .= ' ORDER BY ' . $set['order'];
  175. }
  176. if (isset($set['limit'])) {
  177. if (is_array($set['limit']) && !$type) {
  178. $table .= ' inner join (select id from ' . $table . $this->where($param, $bind, $field) . $rule . ' limit ' . $set['limit'][0].','.$set['limit'][1].') as t on '.$table.'.id=t.id';
  179. $rule = '';
  180. $param = false;
  181. } else {
  182. if ($type == 'Influxdb' && strpos($set['limit'], ',')) {
  183. $temp = explode(',', $set['limit']);
  184. $rule .= ' LIMIT ' . $temp[1] . ' OFFSET ' . $temp[0];
  185. } else {
  186. $rule .= ' LIMIT ' . $set['limit'];
  187. }
  188. }
  189. }
  190. if ($version) {
  191. $rule .= ' FOR UPDATE';
  192. }
  193. return 'SELECT ' . $col . ' FROM ' . $table . $this->where($param, $bind, $field, $type) . $rule;
  194. }
  195. public function where($param, &$bind, $field = [], $type = '')
  196. {
  197. if ($param || is_numeric($param)) {
  198. $first = $second = '';
  199. if (is_array($param)) {
  200. $i = 0;
  201. foreach ($param as $k => $v) {
  202. if (strpos($k, '#')) {
  203. $k = trim($k, '#');
  204. }
  205. if ($k == 'or' || $k == 'and') {
  206. $first_link = $second_link = '';
  207. foreach ($v as $k1 => $v1) {
  208. if (is_array($v1)) {
  209. $this->field($second_link, $bind, $i, $k1, $v1[0], $v1[1], $field, $type);
  210. } else {
  211. $this->field($first_link, $bind, $i, $k1, '=', $v1, $field, $type);
  212. }
  213. }
  214. $second .= ' ' . $k . ' (' . $this->replace($first_link) . $second_link . ')';
  215. } else {
  216. if (is_array($v)) {
  217. $this->field($second, $bind, $i, $k, $v[0], $v[1], $field, $type);
  218. } else {
  219. $this->field($first, $bind, $i, $k, '=', $v, $field, $type);
  220. }
  221. }
  222. }
  223. return ' WHERE ' . $this->replace($first . $second);
  224. } elseif (is_numeric($param)) {
  225. if ($type == 'Influxdb') {
  226. return ' WHERE "id" = \'' . $param . '\'';
  227. } else {
  228. return ' WHERE id = ' . intval($param);
  229. }
  230. } else {
  231. return ' WHERE ' . $param;
  232. }
  233. } else {
  234. return '';
  235. }
  236. }
  237. private function field(&$sql, &$bind, &$num, $key, $symbol, $value, $field, $type)
  238. {
  239. $prefix = '';
  240. if (strstr($key, '.')) {
  241. $temp = explode('.', $key);
  242. $key = $temp[1];
  243. $prefix = $temp[0] . '.';
  244. } elseif ($field && empty($field[$key]) && strpos('id,cdate', $key) === false) {
  245. return;
  246. }
  247. $sql .= ' and ';
  248. $state = false;
  249. $index = '';
  250. $link = '`';
  251. if ($type == 'Influxdb') {
  252. if ($key == 'cdate') {
  253. $key = 'time';
  254. $value = date('Y-m-d H:i:s', $value-28800);
  255. }
  256. $link = '"';
  257. if (strpos($symbol, 'in') !== false) {
  258. $symbol = '=';
  259. }
  260. } elseif (is_string($value) && stristr($value, 'select ')) {
  261. $index = $value;
  262. } elseif (is_array($bind)) {
  263. $state = true;
  264. $index = ':'.$key.$num;
  265. }
  266. if ($state == false && $index == '') {
  267. $index = "'".$value."'";
  268. }
  269. $key = $prefix.$link.$key.$link;
  270. if (strpos($symbol, 'in') !== false) {
  271. if ($state) {
  272. if (!is_array($value)) {
  273. $value = explode(',', $value);
  274. }
  275. $in = '';
  276. foreach ($value as $k => $v) {
  277. if ($k > 0) {
  278. $k = $index.'_'.$k;
  279. $in .= ','.$k;
  280. $state && $bind[$k] = $v;
  281. } else {
  282. $value = $v;
  283. $in .= $index;
  284. }
  285. }
  286. } else {
  287. $in = $index;
  288. }
  289. $sql .= $key.' ' .$symbol.' ('.$in.')';
  290. } elseif ($symbol == 'like') {
  291. $sql .= 'instr('.$key.','.$index.')'.' > 0';
  292. } elseif ($symbol == 'group') {
  293. $value = ','.$value.',';
  294. $sql .= 'instr(concat(",",'.$key.',","),'.$index.')' . ' = 1';
  295. //$sql .= 'FIND_IN_SET("'.$index.'", '.$key.') = 1';
  296. } elseif ($symbol == 'JSON_CONTAINS') {
  297. $sql .= 'JSON_CONTAINS('.$key.', "'.$index.'", "$")';
  298. } elseif ($symbol == 'between') {
  299. $state && $bind[$index.'_e'] = $value[1];
  300. $value = $value[0];
  301. $sql .= $key.' between '.$index.' and '.$index.'_e';
  302. } else {
  303. $sql .= $key.$symbol.$index;
  304. }
  305. $state && $bind[$index] = $value;
  306. $num++;
  307. }
  308. public function insert($table, $data, &$bind, $field)
  309. {
  310. $sql = 'INSERT INTO `' . $table . '` SET ';#IGNORE
  311. foreach ($data as $k => $v) {
  312. if (!$v && $v !== 0) {
  313. continue;
  314. }
  315. if ($field && empty($field[$k]) && strpos('id,cdate', $k) === false) {
  316. continue;
  317. }
  318. $sql .= '`' . $k . '`=:' . $k . ',';
  319. $bind[':'.$k] = $v;
  320. }
  321. return rtrim($sql, ',');
  322. }
  323. public function update($table, $param, $data, &$bind, $field)
  324. {
  325. $i = 0;
  326. $sql = 'UPDATE `' . $table . '` SET ';
  327. foreach ($data as $k => $v) {
  328. if ($field && empty($field[$k]) && strpos('id,cdate', $k) === false) {
  329. continue;
  330. }
  331. $a = '';
  332. if (is_array($v)) {
  333. if (isset($v[2])) {
  334. $a = '`' . $v[0] . '`' . $v[1] . '`' . $v[2] . '`';
  335. $sql .= '`' . $k . '`=' . $a . ',';
  336. continue;
  337. } elseif (isset($v[1])) {
  338. $a = '`' . $k . '`' . $v[0];
  339. $v = $v[1];
  340. } else {
  341. $v = json_encode($v, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  342. }
  343. }
  344. $sql .= '`' . $k . '`=' . $a . ':' . $k . ',';
  345. $bind[':'.$k] = $v;
  346. }
  347. return rtrim($sql, ',') . $this->where($param, $bind, $field);
  348. }
  349. public function delete($table, $param, &$bind, $field)
  350. {
  351. return 'DELETE FROM `' . $table . '`' . $this->where($param, $bind, $field);
  352. }
  353. public function inserts($table, $param)
  354. {
  355. $num = $param['num'] ?? 1;
  356. $sql = 'INSERT INTO `' . $table . '` (' . $param['field'] . ') VALUES ';
  357. foreach ($param['value'] as $k => $v) {
  358. for ($i = 1; $i <= $num; $i++) {
  359. $insert[] = '(' . $v . ')';
  360. }
  361. }
  362. $sql .= implode(',', $insert) . ',';
  363. return rtrim($sql, ',');
  364. }
  365. public function distance($lng, $lat)
  366. {
  367. return 'round((st_distance(point(lng, lat), point('.$lng.', '.$lat.'))*111195)/1000, 2) as distance';
  368. }
  369. private function replace($string)
  370. {
  371. if (strpos($string, ' and ') === 0) {
  372. $string = substr($string, 5);
  373. }
  374. return $string;
  375. }
  376. }