Sql.php 13 KB

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