Sql.php 12 KB

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