Mongo.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. <?php namespace Dever\Store;
  2. use Dever\Debug;
  3. use Dever\Output;
  4. use MongoDB\Driver\Manager;
  5. use MongoDB\Driver\Command;
  6. use MongoDB\Driver\BulkWrite;
  7. use MongoDB\Driver\Query;
  8. use MongoDB\BSON\Regex;
  9. use MongoDB\BSON\ObjectId;
  10. class Mongo extends Base
  11. {
  12. protected function connect($setting)
  13. {
  14. $this->type = $setting['type'];
  15. $this->db = $setting['name'];
  16. if (strpos($setting['host'], ':') !== false) {
  17. list($setting['host'], $setting['port']) = explode(':', $setting['host']);
  18. }
  19. try {
  20. if (empty($setting['timeout'])) {
  21. $setting['timeout'] = 1000;
  22. }
  23. $handle = new Manager('mongodb://' . $setting['host'] . ':' . $setting['port'], ['username' => $setting['user'], 'password' => $setting['pwd'], 'connectTimeoutMS' => $setting['timeout']]);
  24. Debug::add('mongodb ' . $setting['host'] . ' connected', $setting['type']);
  25. return $handle;
  26. } catch (\PDOException $e) {
  27. echo $e->getMessage();die;
  28. }
  29. }
  30. public function index($config, $state = 0)
  31. {
  32. return;
  33. $command = ['listIndexes' => $config['table']];
  34. $result = $this->read->executeCommand($this->db, new Command($command));
  35. foreach ($result as $k => $v) {
  36. if ($v->name != '_id_') {
  37. $command = ['dropIndexes' => $config['table'], 'index' => $v->name];
  38. $this->read->executeCommand($this->db, new Command($command));
  39. }
  40. }
  41. $index = [];
  42. foreach ($config['index'] as $k => $v) {
  43. $t = false;
  44. if (strpos($v, '.')) {
  45. list($v, $t) = explode('.', $v);
  46. if ($t == 'unique') {
  47. $t = true;
  48. }
  49. }
  50. $v = explode(',', $v);
  51. $key = [];
  52. foreach ($v as $v1) {
  53. $key[$v1] = 1;
  54. }
  55. $index[] = [
  56. 'name' => $k,
  57. 'key' => $key,
  58. 'background' => false,
  59. 'unique' => $t
  60. ];
  61. }
  62. $command = ['createIndexes' => $config['table'],'indexes' => $index];
  63. $this->read->executeCommand($this->db, new Command($command));
  64. }
  65. public function load($table, $param, $set, $field, $lock)
  66. {
  67. $param = $this->param($param);
  68. $options = [];
  69. if (isset($set['order'])) {
  70. if (is_string($set['order'])) {
  71. $temp = explode(',', $set['order']);
  72. $set['order'] = [];
  73. foreach ($temp as $k => $v) {
  74. $t = explode(' ', $v);
  75. if ($t[0] == 'id') {
  76. $t[0] = '_' . $t[0];
  77. }
  78. $set['order'][$t[0]] = $t[1] == 'desc' ? -1 : 1;
  79. }
  80. }
  81. $options['sort'] = $set['order'];
  82. }
  83. if (isset($set['limit'])) {
  84. if (is_array($set['limit'])) {
  85. $options['skip'] = $set['limit'][0];
  86. $options['limit'] = $set['limit'][1];
  87. } elseif (strstr($set['limit'], ',')) {
  88. $temp = explode(',', $set['limit']);
  89. $options['skip'] = $temp[0];
  90. $options['limit'] = $temp[1];
  91. } else {
  92. $options['skip'] = 0;
  93. $options['limit'] = $set['limit'];
  94. }
  95. }
  96. if (isset($set['col']) && $set['col'] && $set['col'] != '*') {
  97. $temp = explode(',', $set['col']);
  98. $total = [];
  99. foreach ($temp as $k => $v) {
  100. if (strstr($v, 'sum(')) {
  101. if (strstr($v, ' as')) {
  102. $t = explode(' as ', $v);
  103. $k = $t[1];
  104. $v = $t[0];
  105. } else {
  106. $k = $v;
  107. }
  108. $v = str_replace(array('sum(', ')'), '', $v);
  109. $total[$k] = ['$sum' => '$' . $v];
  110. } else {
  111. $options['projection'][$v] = true;
  112. }
  113. }
  114. if ($total && empty($set['group'])) {
  115. $set['group'] = [];
  116. foreach ($param as $k => $v) {
  117. $set['group'][] = $k;
  118. }
  119. }
  120. }
  121. if (isset($set['group'])) {
  122. $pipeline = [];
  123. if ($param) {
  124. $pipeline[] = ['$match' => $param];
  125. }
  126. $group = [];
  127. if ($set['group'] == 'null') {
  128. $group = null;
  129. } else {
  130. if (is_string($set['group'])) {
  131. $set['group']= explode(',', $set['group']);
  132. }
  133. foreach ($set['group'] as $k => $v) {
  134. $group[$v] = '$' . $v;
  135. }
  136. }
  137. $group = ['_id' => $group];
  138. if (isset($total) && $total) {
  139. $group = array_merge($group, $total);
  140. } else {
  141. $group['count'] = ['$sum' => 1];
  142. }
  143. if (isset($options['projection'])) {
  144. foreach ($options['projection'] as $k => $v) {
  145. $group[$k] = ['$push' => '$' . $k];
  146. }
  147. }
  148. $pipeline[] = ['$group' => $group];
  149. if (isset($options['sort'])) {
  150. $pipeline[] = ['$sort' => $options['sort']];
  151. }
  152. if (isset($options['skip'])) {
  153. $pipeline[] = ['$skip' => $options['skip']];
  154. }
  155. if (isset($options['limit'])) {
  156. $pipeline[] = ['$limit' => $options['limit']];
  157. }
  158. $options = array('aggregate' => $table,'pipeline' => $pipeline,'cursor' => new \stdClass());
  159. $command = new Command($options);
  160. $result = $this->read->executeCommand($this->db, $command)->toArray();
  161. } else {
  162. $query = new Query($param, $options);
  163. $result = $this->read->executeQuery($this->db . '.' . $table, $query);
  164. }
  165. if (Debug::$shell) {
  166. $this->log(['table' => $this->db . '.' . $table, 'param' => $param, 'option' => $options, 'result' => $result]);
  167. }
  168. return $result;
  169. }
  170. public function select($table, $param, $set, $field, $lock)
  171. {
  172. $result = [];
  173. $data = $this->load($table, $param, $set, $field, $lock);
  174. foreach ($data as $k => $v) {
  175. $result[] = $this->handle($v);
  176. }
  177. return $result;
  178. }
  179. public function find($table, $param, $set, $field, $lock)
  180. {
  181. $result = [];
  182. $data = $this->load($table, $param, $set, $field, $lock);
  183. foreach ($data as $k => $v) {
  184. $result = $this->handle($v);
  185. break;
  186. }
  187. return $result;
  188. }
  189. public function count($table, $param, $field)
  190. {
  191. $result = 0;
  192. $set['group'] = 'null';
  193. $data = $this->load($table, $param, $set, $field, false);
  194. if (isset($data[0]) && $data[0]->count) {
  195. $result = $data[0]->count;
  196. }
  197. if (Debug::$shell) {
  198. $this->log(['table' => $this->db . '.' . $table, 'param' => $param, 'result' => $result]);
  199. }
  200. return $result;
  201. }
  202. public function insert($table, $data, $field)
  203. {
  204. $insert = [];
  205. foreach ($data as $k => $v) {
  206. if ($field && empty($field[$k]) && strpos('id,cdate', $k) === false) {
  207. continue;
  208. }
  209. /*
  210. if (is_numeric($v)) {
  211. if (isset($field[$k]) && strpos($field[$k]['type'], 'char')) {
  212. } else {
  213. $v = (float) $v;
  214. }
  215. }*/
  216. $insert[$k] = $v;
  217. }
  218. if ($field) {
  219. foreach ($field as $k => $v) {
  220. if (!isset($insert[$k])) {
  221. $insert[$k] = $v['default'] ?? '';
  222. }
  223. }
  224. }
  225. //$insert['_id'] = new ObjectId();
  226. $bulk = new BulkWrite;
  227. $id = $bulk->insert($insert);
  228. $id = (array) $id;
  229. $id = $id['oid'];
  230. $result = $this->update->executeBulkWrite($this->db . '.' . $table, $bulk);
  231. if (Debug::$shell) {
  232. $this->log(['table' => $this->db . '.' . $table, 'insert' => $insert, 'result' => $id]);
  233. }
  234. if ($result->getInsertedCount() >= 1) {
  235. return $id;
  236. }
  237. return false;
  238. }
  239. public function update($table, $param, $data, $field)
  240. {
  241. $update = [];
  242. foreach ($data as $k => $v) {
  243. if ($field && empty($field[$k]) && strpos('id,cdate', $k) === false) {
  244. continue;
  245. }
  246. /*
  247. if (is_numeric($v)) {
  248. if (isset($field[$k]) && strpos($field[$k]['type'], 'char')) {
  249. } else {
  250. $v = (float) $v;
  251. }
  252. }*/
  253. $update[$k] = $v;
  254. }
  255. $update = ['$set' => $update];
  256. $param = $this->param($param);
  257. $bulk = new BulkWrite;
  258. $bulk->update($param, $update, ['multi' => true, 'upsert' => false]);
  259. $result = $this->update->executeBulkWrite($this->db . '.' . $table, $bulk);
  260. $result = $result->getModifiedCount();
  261. if (Debug::$shell) {
  262. $this->log(['table' => $this->db . '.' . $table, 'param' => $param, 'update' => $update, 'result' => $result]);
  263. }
  264. return $result;
  265. }
  266. public function delete($table, $param, $field)
  267. {
  268. $param = $this->param($param);
  269. $bulk = new BulkWrite;
  270. $bulk->delete($param);
  271. $result = $this->update->executeBulkWrite($this->db . '.' . $table, $bulk);
  272. $result = $result->getDeletedCount();
  273. if (Debug::$shell) {
  274. $this->log(['table' => $this->db . '.' . $table, 'param' => $param, 'result' => $result]);
  275. }
  276. return $result;
  277. }
  278. private function param($param)
  279. {
  280. $result = [];
  281. if ($param) {
  282. if (is_array($param)) {
  283. foreach ($param as $k => $v) {
  284. if (strpos($k, '#')) {
  285. $k = trim($k, '#');
  286. }
  287. if ($k == 'id') {
  288. $k = '_id';
  289. }
  290. if ($k == 'or' || $k == 'and') {
  291. $where = [];
  292. foreach ($v as $k1 => $v1) {
  293. if (strpos($k1, '#')) {
  294. $k1 = trim($k1, '#');
  295. }
  296. if ($k1 == 'id') {
  297. $k1 = '_id';
  298. }
  299. $where[$k1] = $this->where($k1, $v1);
  300. }
  301. $result['$' . $k][] = $where;
  302. } else {
  303. if (isset($result[$k])) {
  304. $result[$k] = array_merge($result[$k], $this->where($k, $v));
  305. } else {
  306. $result[$k] = $this->where($k, $v);
  307. }
  308. }
  309. }
  310. } elseif ($param) {
  311. $pk = '_id';
  312. $result[$pk] = $this->where($pk, $param);
  313. } else {
  314. $result = $param;
  315. }
  316. }
  317. return $result;
  318. }
  319. private function where(&$key, $value)
  320. {
  321. $method = '';
  322. if (is_array($value)) {
  323. $method = $value[0];
  324. $value = $value[1];
  325. }
  326. switch ($method) {
  327. case 'like':
  328. # 模糊查询
  329. $value = (string) $value;
  330. if (strpos($value, '%') !== false) {
  331. $value = str_replace('%', '(.*?)', $value);
  332. $value = new Regex($value, 'i');
  333. } else {
  334. $value = new Regex($value . '(.*?)', 'i');
  335. }
  336. break;
  337. case 'in':
  338. case 'nin':
  339. # in查询
  340. $value = explode(',', $value);
  341. foreach ($value as $k => $v) {
  342. $value[$k] = $this->value($key, $v);
  343. }
  344. $value = ['$' . $method => $value];
  345. break;
  346. case '>':
  347. $value = array('$gt' => $this->value($key, $value));
  348. break;
  349. case '>=':
  350. $value = array('$gte' => $this->value($key, $value));
  351. break;
  352. case '<':
  353. $value = array('$lt' => $this->value($key, $value));
  354. break;
  355. case '<=':
  356. $value = array('$lte' => $this->value($key, $value));
  357. break;
  358. case '!=':
  359. $value = array('$ne' => $this->value($key, $value));
  360. break;
  361. case '%':
  362. $value = array('$mod' => $this->value($key, $value));
  363. break;
  364. case 'between':
  365. $value = array('$gt' => $this->value($key, $value[0]), '$lt' => $this->value($key, $value[1]));
  366. break;
  367. case 'betweens':
  368. $value = array('$gte' => $this->value($key, $value[0]), '$lte' => $this->value($key, $value[1]));
  369. break;
  370. default :
  371. $value = $this->value($key, $value);
  372. break;
  373. }
  374. return $value;
  375. }
  376. private function value(&$key, $value)
  377. {
  378. if ($key == '_id') {
  379. if (is_numeric($value)) {
  380. $key = 'id';
  381. $value = (float) $value;
  382. } else {
  383. $value = new ObjectId($value);
  384. }
  385. } elseif (strlen($value) != 11 && is_numeric($value)) {
  386. $value = (float) $value;
  387. }
  388. return $value;
  389. }
  390. private function handle($v)
  391. {
  392. $v = (array)$v;
  393. # 后续删除
  394. foreach ($v as &$v1) {
  395. if (is_numeric($v1) && strstr($v1, 'E')) {
  396. $v1 = number_format($v1, 0, '', '');
  397. }
  398. }
  399. $v['_id'] = (array) $v['_id'];
  400. if (isset($v['_id']['oid'])) {
  401. $v['_id'] = $v['_id']['oid'];
  402. if (!isset($v['id'])) {
  403. $v['id'] = $v['_id'];
  404. }
  405. } else {
  406. $v = array_merge($v['_id'], $v);
  407. unset($v['_id']);
  408. }
  409. return $v;
  410. }
  411. public function struct($config, $state = 0){}
  412. public function partition($config, $partition){}
  413. public function begin(){}
  414. public function commit(){}
  415. public function rollback(){}
  416. public function transaction(){}
  417. }