Mongo.php 14 KB

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