This commit is contained in:
wangjinlei
2020-11-12 17:15:37 +08:00
parent 824380664c
commit 1abf99316f
893 changed files with 278997 additions and 0 deletions

View File

@@ -0,0 +1 @@
.idea

201
vendor/topthink/think-mongo/LICENSE vendored Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

26
vendor/topthink/think-mongo/README.md vendored Normal file
View File

@@ -0,0 +1,26 @@
ThinkPHP 5.0 MongoDb驱动
===============
首先安装官方的mongodb扩展
http://pecl.php.net/package/mongodb
然后,配置应用的数据库配置文件`database.php``type`参数为:
~~~
'type' => '\think\mongo\Connection',
~~~
即可正常使用MongoDb例如
~~~
Db::name('demo')
->find();
Db::name('demo')
->field('id,name')
->limit(10)
->order('id','desc')
->select();
~~~
1.*版本支持ThinkPHP 5.0
2.*版本支持ThinkPHP 5.1

View File

@@ -0,0 +1,19 @@
{
"name": "topthink/think-mongo",
"description": "mongodb driver for thinkphp5",
"license": "Apache-2.0",
"authors": [
{
"name": "liu21st",
"email": "liu21st@gmail.com"
}
],
"require": {},
"autoload": {
"psr-4": {
"think\\mongo\\": "src"
},
"files": [
]
}
}

View File

@@ -0,0 +1,575 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think\mongo;
use MongoDB\BSON\Javascript;
use MongoDB\BSON\ObjectID;
use MongoDB\BSON\Regex;
use MongoDB\Driver\BulkWrite;
use MongoDB\Driver\Command;
use MongoDB\Driver\Exception\InvalidArgumentException;
use MongoDB\Driver\Query as MongoQuery;
use think\Exception;
class Builder
{
// connection对象实例
protected $connection;
// 查询对象实例
protected $query;
// 查询参数
protected $options = [];
// 最后插入ID
protected $insertId = [];
// 查询表达式
protected $exp = ['<>' => 'ne', 'neq' => 'ne', '=' => 'eq', '>' => 'gt', '>=' => 'gte', '<' => 'lt', '<=' => 'lte', 'in' => 'in', 'not in' => 'nin', 'nin' => 'nin', 'mod' => 'mod', 'exists' => 'exists', 'null' => 'null', 'notnull' => 'not null', 'not null' => 'not null', 'regex' => 'regex', 'type' => 'type', 'all' => 'all', '> time' => '> time', '< time' => '< time', 'between' => 'between', 'not between' => 'not between', 'between time' => 'between time', 'not between time' => 'not between time', 'notbetween time' => 'not between time', 'like' => 'like', 'near' => 'near', 'size' => 'size'];
/**
* 架构函数
* @access public
* @param Connection $connection 数据库连接对象实例
* @param Query $query 数据库查询对象实例
*/
public function __construct(Connection $connection, Query $query)
{
$this->connection = $connection;
$this->query = $query;
}
/**
* key分析
* @access protected
* @param string $key
* @return string
*/
protected function parseKey($key)
{
if (0 === strpos($key, '__TABLE__.')) {
list($collection, $key) = explode('.', $key, 2);
}
if ('id' == $key && $this->connection->getConfig('pk_convert_id')) {
$key = '_id';
}
return trim($key);
}
/**
* value分析
* @access protected
* @param mixed $value
* @param string $field
* @return string
*/
protected function parseValue($value, $field = '')
{
if ('_id' == $field && 'ObjectID' == $this->connection->getConfig('pk_type') && is_string($value)) {
try {
return new ObjectID($value);
} catch (InvalidArgumentException $e) {
return new ObjectID();
}
}
return $value;
}
/**
* insert数据分析
* @access protected
* @param array $data 数据
* @param array $options 查询参数
* @return array
*/
protected function parseData($data, $options)
{
if (empty($data)) {
return [];
}
$result = [];
foreach ($data as $key => $val) {
$item = $this->parseKey($key);
if (is_object($val)) {
$result[$item] = $val;
} elseif (isset($val[0]) && 'exp' == $val[0]) {
$result[$item] = $val[1];
} elseif (is_null($val)) {
$result[$item] = 'NULL';
} else {
$result[$item] = $this->parseValue($val, $key);
}
}
return $result;
}
/**
* Set数据分析
* @access protected
* @param array $data 数据
* @param array $options 查询参数
* @return array
*/
protected function parseSet($data, $options)
{
if (empty($data)) {
return [];
}
$result = [];
foreach ($data as $key => $val) {
$item = $this->parseKey($key);
if (is_array($val) && isset($val[0]) && is_string($val[0]) && 0 === strpos($val[0], '$')) {
$result[$val[0]][$item] = $this->parseValue($val[1], $key);
} else {
$result['$set'][$item] = $this->parseValue($val, $key);
}
}
return $result;
}
/**
* 生成查询过滤条件
* @access public
* @param mixed $where
* @return array
*/
public function parseWhere($where, $options = [])
{
if (empty($where)) {
$where = [];
}
$filter = [];
foreach ($where as $logic => $val) {
foreach ($val as $field => $value) {
if ($value instanceof \Closure) {
// 使用闭包查询
$query = new Query($this->connection);
call_user_func_array($value, [ & $query]);
$filter[$logic][] = $this->parseWhere($query->getOptions('where'), $options);
} else {
if (strpos($field, '|')) {
// 不同字段使用相同查询条件OR
$array = explode('|', $field);
foreach ($array as $k) {
$filter['$or'][] = $this->parseWhereItem($k, $value);
}
} elseif (strpos($field, '&')) {
// 不同字段使用相同查询条件AND
$array = explode('&', $field);
foreach ($array as $k) {
$filter['$and'][] = $this->parseWhereItem($k, $value);
}
} else {
// 对字段使用表达式查询
$field = is_string($field) ? $field : '';
$filter[$logic][] = $this->parseWhereItem($field, $value);
}
}
}
}
if (!empty($options['soft_delete'])) {
// 附加软删除条件
list($field, $condition) = $options['soft_delete'];
$filter['$and'][] = $this->parseWhereItem($field, $condition);
}
return $filter;
}
// where子单元分析
protected function parseWhereItem($field, $val)
{
$key = $field ? $this->parseKey($field) : '';
// 查询规则和条件
if (!is_array($val)) {
$val = ['=', $val];
}
list($exp, $value) = $val;
// 对一个字段使用多个查询条件
if (is_array($exp)) {
$data = [];
foreach ($val as $value) {
$exp = $value[0];
$value = $value[1];
if (!in_array($exp, $this->exp)) {
$exp = strtolower($exp);
if (isset($this->exp[$exp])) {
$exp = $this->exp[$exp];
}
}
$k = '$' . $exp;
$data[$k] = $value;
}
$query[$key] = $data;
return $query;
} elseif (!in_array($exp, $this->exp)) {
$exp = strtolower($exp);
if (isset($this->exp[$exp])) {
$exp = $this->exp[$exp];
} else {
throw new Exception('where express error:' . $exp);
}
}
$query = [];
if ('=' == $exp) {
// 普通查询
$query[$key] = $this->parseValue($value, $key);
} elseif (in_array($exp, ['neq', 'ne', 'gt', 'egt', 'gte', 'lt', 'lte', 'elt', 'mod'])) {
// 比较运算
$k = '$' . $exp;
$query[$key] = [$k => $this->parseValue($value, $key)];
} elseif ('null' == $exp) {
// NULL 查询
$query[$key] = null;
} elseif ('not null' == $exp) {
$query[$key] = ['$ne' => null];
} elseif ('all' == $exp) {
// 满足所有指定条件
$query[$key] = ['$all', $this->parseValue($value, $key)];
} elseif ('between' == $exp) {
// 区间查询
$value = is_array($value) ? $value : explode(',', $value);
$query[$key] = ['$gte' => $this->parseValue($value[0], $key), '$lte' => $this->parseValue($value[1], $key)];
} elseif ('not between' == $exp) {
// 范围查询
$value = is_array($value) ? $value : explode(',', $value);
$query[$key] = ['$lt' => $this->parseValue($value[0], $key), '$gt' => $this->parseValue($value[1], $key)];
} elseif ('exists' == $exp) {
// 字段是否存在
$query[$key] = ['$exists' => (bool) $value];
} elseif ('type' == $exp) {
// 类型查询
$query[$key] = ['$type' => intval($value)];
} elseif ('exp' == $exp) {
// 表达式查询
$query['$where'] = $value instanceof Javascript ? $value : new Javascript($value);
} elseif ('like' == $exp) {
// 模糊查询 采用正则方式
$query[$key] = $value instanceof Regex ? $value : new Regex($value, 'i');
} elseif (in_array($exp, ['nin', 'in'])) {
// IN 查询
$value = is_array($value) ? $value : explode(',', $value);
foreach ($value as $k => $val) {
$value[$k] = $this->parseValue($val, $key);
}
$query[$key] = ['$' . $exp => $value];
} elseif ('regex' == $exp) {
$query[$key] = $value instanceof Regex ? $value : new Regex($value, 'i');
} elseif ('< time' == $exp) {
$query[$key] = ['$lt' => $this->parseDateTime($value, $field)];
} elseif ('> time' == $exp) {
$query[$key] = ['$gt' => $this->parseDateTime($value, $field)];
} elseif ('between time' == $exp) {
// 区间查询
$value = is_array($value) ? $value : explode(',', $value);
$query[$key] = ['$gte' => $this->parseDateTime($value[0], $field), '$lte' => $this->parseDateTime($value[1], $field)];
} elseif ('not between time' == $exp) {
// 范围查询
$value = is_array($value) ? $value : explode(',', $value);
$query[$key] = ['$lt' => $this->parseDateTime($value[0], $field), '$gt' => $this->parseDateTime($value[1], $field)];
} elseif ('near' == $exp) {
// 经纬度查询
$query[$key] = ['$near' => $this->parseValue($value, $key)];
} elseif ('size' == $exp) {
// 元素长度查询
$query[$key] = ['$size' => intval($value)];
} else {
// 普通查询
$query[$key] = $this->parseValue($value, $key);
}
return $query;
}
/**
* 日期时间条件解析
* @access protected
* @param string $value
* @param string $key
* @return string
*/
protected function parseDateTime($value, $key)
{
// 获取时间字段类型
$type = $this->query->getTableInfo('', 'type');
if (isset($type[$key])) {
$value = strtotime($value) ?: $value;
if (preg_match('/(datetime|timestamp)/is', $type[$key])) {
// 日期及时间戳类型
$value = date('Y-m-d H:i:s', $value);
} elseif (preg_match('/(date)/is', $type[$key])) {
// 日期及时间戳类型
$value = date('Y-m-d', $value);
}
}
return $value;
}
/**
* 获取最后写入的ID 如果是insertAll方法的话 返回所有写入的ID
* @access public
* @return mixed
*/
public function getLastInsID()
{
return $this->insertId;
}
/**
* 生成insert BulkWrite对象
* @access public
* @param array $data 数据
* @param array $options 表达式
* @return BulkWrite
*/
public function insert(array $data, $options = [])
{
// 分析并处理数据
$data = $this->parseData($data, $options);
$bulk = new BulkWrite;
if ($insertId = $bulk->insert($data)) {
$this->insertId = $insertId;
}
$this->log('insert', $data, $options);
return $bulk;
}
/**
* 生成insertall BulkWrite对象
* @access public
* @param array $dataSet 数据集
* @param array $options 参数
* @return BulkWrite
*/
public function insertAll($dataSet, $options = [])
{
$bulk = new BulkWrite;
$this->insertId = [];
foreach ($dataSet as $data) {
// 分析并处理数据
$data = $this->parseData($data, $options);
if ($insertId = $bulk->insert($data)) {
$this->insertId[] = $insertId;
}
}
$this->log('insert', $dataSet, $options);
return $bulk;
}
/**
* 生成update BulkWrite对象
* @access public
* @param array $data 数据
* @param array $options 参数
* @return BulkWrite
*/
public function update($data, $options = [])
{
$data = $this->parseSet($data, $options);
$where = $this->parseWhere($options['where'], $options);
if (1 == $options['limit']) {
$updateOptions = ['multi' => false];
} else {
$updateOptions = ['multi' => true];
}
$bulk = new BulkWrite;
$bulk->update($where, $data, $updateOptions);
$this->log('update', $data, $where);
return $bulk;
}
/**
* 生成delete BulkWrite对象
* @access public
* @param array $options 参数
* @return BulkWrite
*/
public function delete($options)
{
$where = $this->parseWhere($options['where'], $options);
$bulk = new BulkWrite;
if (1 == $options['limit']) {
$deleteOptions = ['limit' => 1];
} else {
$deleteOptions = ['limit' => 0];
}
$bulk->delete($where, $deleteOptions);
$this->log('remove', $where, $deleteOptions);
return $bulk;
}
/**
* 生成Mongo查询对象
* @access public
* @param array $options 参数
* @return MongoQuery
*/
public function select($options)
{
$where = $this->parseWhere($options['where'], $options);
$query = new MongoQuery($where, $options);
$this->log('find', $where, $options);
return $query;
}
/**
* 生成Count命令
* @access public
* @param array $options 参数
* @return Command
*/
public function count($options)
{
$cmd['count'] = $options['table'];
$cmd['query'] = $this->parseWhere($options['where'], $options);
foreach (['hint', 'limit', 'maxTimeMS', 'skip'] as $option) {
if (isset($options[$option])) {
$cmd[$option] = $options[$option];
}
}
$command = new Command($cmd);
$this->log('cmd', 'count', $cmd);
return $command;
}
/**
* 聚合查询命令
* @access public
* @param array $options 参数
* @param array $extra 指令和字段
* @return Command
*/
public function aggregate($options, $extra)
{
list($fun, $field) = $extra;
$pipeline = [
['$match' => (object) $this->parseWhere($options['where'], $options)],
['$group' => ['_id' => null, 'aggregate' => ['$' . $fun => '$' . $field]]],
];
$cmd = [
'aggregate' => $options['table'],
'allowDiskUse' => true,
'pipeline' => $pipeline,
'cursor' => new \stdClass,
];
foreach (['explain', 'collation', 'bypassDocumentValidation', 'readConcern'] as $option) {
if (isset($options[$option])) {
$cmd[$option] = $options[$option];
}
}
$command = new Command($cmd);
$this->log('aggregate', $cmd);
return $command;
}
/**
* 多聚合查询命令, 可以对多个字段进行 group by 操作
*
* @param array $options 参数
* @param array $extra 指令和字段
* @return Command
*/
public function multiAggregate($options, $extra)
{
list($aggregate, $groupBy) = $extra;
$groups = ['_id' => []];
foreach ($groupBy as $field) {
$groups['_id'][$field] = '$' . $field;
}
foreach ($aggregate as $fun => $field) {
$groups[$field . '_' . $fun] = ['$' . $fun => '$' . $field];
}
$pipeline = [
['$match' => (object) $this->parseWhere($options['where'], $options)],
['$group' => $groups],
];
$cmd = [
'aggregate' => $options['table'],
'allowDiskUse' => true,
'pipeline' => $pipeline,
'cursor' => new \stdClass,
];
foreach (['explain', 'collation', 'bypassDocumentValidation', 'readConcern'] as $option) {
if (isset($options[$option])) {
$cmd[$option] = $options[$option];
}
}
$command = new Command($cmd);
$this->log('group', $cmd);
return $command;
}
/**
* 生成distinct命令
* @access public
* @param array $options 参数
* @param string $field 字段名
* @return Command
*/
public function distinct($options, $field)
{
$cmd = [
'distinct' => $options['table'],
'key' => $field,
];
if (!empty($options['where'])) {
$cmd['query'] = $this->parseWhere($options['where'], $options);
}
if (isset($options['maxTimeMS'])) {
$cmd['maxTimeMS'] = $options['maxTimeMS'];
}
$command = new Command($cmd);
$this->log('cmd', 'distinct', $cmd);
return $command;
}
/**
* 查询所有的collection
* @access public
* @return Command
*/
public function listcollections()
{
$cmd = ['listCollections' => 1];
$command = new Command($cmd);
$this->log('cmd', 'listCollections', $cmd);
return $command;
}
/**
* 查询数据表的状态信息
* @access public
* @return Command
*/
public function collStats($options)
{
$cmd = ['collStats' => $options['table']];
$command = new Command($cmd);
$this->log('cmd', 'collStats', $cmd);
return $command;
}
protected function log($type, $data, $options = [])
{
if ($this->connection->getConfig('debug')) {
$this->connection->log($type, $data, $options);
}
}
}

View File

@@ -0,0 +1,680 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think\mongo;
use MongoDB\BSON\ObjectID;
use MongoDB\Driver\BulkWrite;
use MongoDB\Driver\Command;
use MongoDB\Driver\Exception\AuthenticationException;
use MongoDB\Driver\Exception\BulkWriteException;
use MongoDB\Driver\Exception\ConnectionException;
use MongoDB\Driver\Exception\InvalidArgumentException;
use MongoDB\Driver\Exception\RuntimeException;
use MongoDB\Driver\Manager;
use MongoDB\Driver\Query as MongoQuery;
use MongoDB\Driver\ReadPreference;
use MongoDB\Driver\WriteConcern;
use think\Db;
use think\Debug;
use think\Exception;
use think\Log;
/**
* Mongo数据库驱动
*/
class Connection
{
protected $dbName = ''; // dbName
/** @var string 当前SQL指令 */
protected $queryStr = '';
// 查询数据类型
protected $typeMap = 'array';
protected $mongo; // MongoDb Object
protected $cursor; // MongoCursor Object
// 监听回调
protected static $event = [];
/** @var PDO[] 数据库连接ID 支持多个连接 */
protected $links = [];
/** @var PDO 当前连接ID */
protected $linkID;
protected $linkRead;
protected $linkWrite;
// 返回或者影响记录数
protected $numRows = 0;
// 错误信息
protected $error = '';
// 查询对象
protected $query = [];
// 查询参数
protected $options = [];
// 数据库连接参数配置
protected $config = [
// 数据库类型
'type' => '',
// 服务器地址
'hostname' => '',
// 数据库名
'database' => '',
// 是否是复制集
'is_replica_set' => false,
// 用户名
'username' => '',
// 密码
'password' => '',
// 端口
'hostport' => '',
// 连接dsn
'dsn' => '',
// 数据库连接参数
'params' => [],
// 数据库编码默认采用utf8
'charset' => 'utf8',
// 主键名
'pk' => '_id',
// 主键类型
'pk_type' => 'ObjectID',
// 数据库表前缀
'prefix' => '',
// 数据库调试模式
'debug' => false,
// 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'deploy' => 0,
// 数据库读写是否分离 主从式有效
'rw_separate' => false,
// 读写分离后 主服务器数量
'master_num' => 1,
// 指定从服务器序号
'slave_no' => '',
// 是否严格检查字段是否存在
'fields_strict' => true,
// 数据集返回类型
'resultset_type' => 'array',
// 自动写入时间戳字段
'auto_timestamp' => false,
// 时间字段取出后的默认时间格式
'datetime_format' => 'Y-m-d H:i:s',
// 是否需要进行SQL性能分析
'sql_explain' => false,
// 是否_id转换为id
'pk_convert_id' => false,
// typeMap
'type_map' => ['root' => 'array', 'document' => 'array'],
// Query对象
'query' => '\\think\\mongo\\Query',
];
/**
* 架构函数 读取数据库配置信息
* @access public
* @param array $config 数据库配置数组
*/
public function __construct(array $config = [])
{
if (!class_exists('\MongoDB\Driver\Manager')) {
throw new Exception('require mongodb > 1.0');
}
if (!empty($config)) {
$this->config = array_merge($this->config, $config);
}
}
/**
* 连接数据库方法
* @access public
* @param array $config 连接参数
* @param integer $linkNum 连接序号
* @throws InvalidArgumentException
* @throws RuntimeException
*/
public function connect(array $config = [], $linkNum = 0)
{
if (!isset($this->links[$linkNum])) {
if (empty($config)) {
$config = $this->config;
} else {
$config = array_merge($this->config, $config);
}
$this->dbName = $config['database'];
$this->typeMap = $config['type_map'];
if ($config['pk_convert_id'] && '_id' == $config['pk']) {
$this->config['pk'] = 'id';
}
$host = 'mongodb://' . ($config['username'] ? "{$config['username']}" : '') . ($config['password'] ? ":{$config['password']}@" : '') . $config['hostname'] . ($config['hostport'] ? ":{$config['hostport']}" : '');
if ($config['debug']) {
$startTime = microtime(true);
}
$this->links[$linkNum] = new Manager($host, $this->config['params']);
if ($config['debug']) {
// 记录数据库连接信息
Log::record('[ DB ] CONNECT:[ UseTime:' . number_format(microtime(true) - $startTime, 6) . 's ] ' . $config['dsn'], 'sql');
}
}
return $this->links[$linkNum];
}
/**
* 指定当前使用的查询对象
* @access public
* @param Query $query 查询对象
* @return $this
*/
public function setQuery($query, $model = 'db')
{
$this->query[$model] = $query;
return $this;
}
/**
* 创建指定模型的查询对象
* @access public
* @param string $model 模型类名称
* @param string $queryClass 查询对象类名
* @return Query
*/
public function getQuery($model = 'db', $queryClass = '')
{
if (!isset($this->query[$model])) {
$class = $queryClass ?: $this->config['query'];
$this->query[$model] = new $class($this, 'db' == $model ? '' : $model);
}
return $this->query[$model];
}
/**
* 调用Query类的查询方法
* @access public
* @param string $method 方法名称
* @param array $args 调用参数
* @return mixed
*/
public function __call($method, $args)
{
return call_user_func_array([$this->getQuery(), $method], $args);
}
/**
* 获取数据库的配置参数
* @access public
* @param string $config 配置名称
* @return mixed
*/
public function getConfig($config = '')
{
return $config ? $this->config[$config] : $this->config;
}
/**
* 设置数据库的配置参数
* @access public
* @param string $config 配置名称
* @param mixed $value 配置值
* @return void
*/
public function setConfig($config, $value)
{
$this->config[$config] = $value;
}
/**
* 获取Mongo Manager对象
* @access public
* @return Manager|null
*/
public function getMongo()
{
if (!$this->mongo) {
return;
} else {
return $this->mongo;
}
}
/**
* 设置/获取当前操作的database
* @access public
* @param string $db db
* @throws Exception
*/
public function db($db = null)
{
if (is_null($db)) {
return $this->dbName;
} else {
$this->dbName = $db;
}
}
/**
* 执行查询
* @access public
* @param string $namespace 当前查询的collection
* @param MongoQuery $query 查询对象
* @param ReadPreference $readPreference readPreference
* @param string|bool $class 返回的数据集类型
* @param string|array $typeMap 指定返回的typeMap
* @return mixed
* @throws AuthenticationException
* @throws InvalidArgumentException
* @throws ConnectionException
* @throws RuntimeException
*/
public function query($namespace, MongoQuery $query, ReadPreference $readPreference = null, $class = false, $typeMap = null)
{
$this->initConnect(false);
Db::$queryTimes++;
if (false === strpos($namespace, '.')) {
$namespace = $this->dbName . '.' . $namespace;
}
if ($this->config['debug'] && !empty($this->queryStr)) {
// 记录执行指令
$this->queryStr = 'db' . strstr($namespace, '.') . '.' . $this->queryStr;
}
$this->debug(true);
$this->cursor = $this->mongo->executeQuery($namespace, $query, $readPreference);
$this->debug(false);
return $this->getResult($class, $typeMap);
}
/**
* 执行指令
* @access public
* @param Command $command 指令
* @param string $dbName 当前数据库名
* @param ReadPreference $readPreference readPreference
* @param string|bool $class 返回的数据集类型
* @param string|array $typeMap 指定返回的typeMap
* @return mixed
* @throws AuthenticationException
* @throws InvalidArgumentException
* @throws ConnectionException
* @throws RuntimeException
*/
public function command(Command $command, $dbName = '', ReadPreference $readPreference = null, $class = false, $typeMap = null)
{
$this->initConnect(false);
Db::$queryTimes++;
$this->debug(true);
$dbName = $dbName ?: $this->dbName;
if ($this->config['debug'] && !empty($this->queryStr)) {
$this->queryStr = 'db.' . $this->queryStr;
}
$this->cursor = $this->mongo->executeCommand($dbName, $command, $readPreference);
$this->debug(false);
return $this->getResult($class, $typeMap);
}
/**
* 获得数据集
* @access protected
* @param bool|string $class true 返回Mongo cursor对象 字符串用于指定返回的类名
* @param string|array $typeMap 指定返回的typeMap
* @return mixed
*/
protected function getResult($class = '', $typeMap = null)
{
if (true === $class) {
return $this->cursor;
}
// 设置结果数据类型
if (is_null($typeMap)) {
$typeMap = $this->typeMap;
}
$typeMap = is_string($typeMap) ? ['root' => $typeMap] : $typeMap;
$this->cursor->setTypeMap($typeMap);
// 获取数据集
$result = $this->cursor->toArray();
if ($this->getConfig('pk_convert_id')) {
// 转换ObjectID 字段
foreach ($result as &$data) {
$this->convertObjectID($data);
}
}
$this->numRows = count($result);
return $result;
}
/**
* ObjectID处理
* @access public
* @param array $data
* @return void
*/
private function convertObjectID(&$data)
{
if (isset($data['_id'])) {
$data['id'] = $data['_id']->__toString();
unset($data['_id']);
}
}
/**
* 执行写操作
* @access public
* @param string $namespace
* @param BulkWrite $bulk
* @param WriteConcern $writeConcern
*
* @return WriteResult
* @throws AuthenticationException
* @throws InvalidArgumentException
* @throws ConnectionException
* @throws RuntimeException
* @throws BulkWriteException
*/
public function execute($namespace, BulkWrite $bulk, WriteConcern $writeConcern = null)
{
$this->initConnect(true);
Db::$executeTimes++;
if (false === strpos($namespace, '.')) {
$namespace = $this->dbName . '.' . $namespace;
}
if ($this->config['debug'] && !empty($this->queryStr)) {
// 记录执行指令
$this->queryStr = 'db' . strstr($namespace, '.') . '.' . $this->queryStr;
}
$this->debug(true);
$writeResult = $this->mongo->executeBulkWrite($namespace, $bulk, $writeConcern);
$this->debug(false);
$this->numRows = $writeResult->getMatchedCount();
return $writeResult;
}
/**
* 数据库日志记录(仅供参考)
* @access public
* @param string $type 类型
* @param mixed $data 数据
* @param array $options 参数
* @return void
*/
public function log($type, $data, $options = [])
{
if (!$this->config['debug']) {
return;
}
if (is_array($data)) {
array_walk_recursive($data, function (&$value) {
if ($value instanceof ObjectID) {
$value = $value->__toString();
}
});
}
switch (strtolower($type)) {
case 'aggregate':
$this->queryStr = 'runCommand(' . ($data ? json_encode($data) : '') . ');';
break;
case 'find':
$this->queryStr = $type . '(' . ($data ? json_encode($data) : '') . ')';
if (isset($options['sort'])) {
$this->queryStr .= '.sort(' . json_encode($options['sort']) . ')';
}
if (isset($options['limit'])) {
$this->queryStr .= '.limit(' . $options['limit'] . ')';
}
$this->queryStr .= ';';
break;
case 'insert':
case 'remove':
$this->queryStr = $type . '(' . ($data ? json_encode($data) : '') . ');';
break;
case 'update':
$this->queryStr = $type . '(' . json_encode($options) . ',' . json_encode($data) . ');';
break;
case 'cmd':
$this->queryStr = $data . '(' . json_encode($options) . ');';
break;
}
$this->options = $options;
}
/**
* 获取执行的指令
* @access public
* @return string
*/
public function getQueryStr()
{
return $this->queryStr;
}
/**
* 监听SQL执行
* @access public
* @param callable $callback 回调方法
* @return void
*/
public function listen($callback)
{
self::$event[] = $callback;
}
/**
* 触发SQL事件
* @access protected
* @param string $sql 语句
* @param float $runtime 运行时间
* @param array $options 参数
* @return bool
*/
protected function trigger($sql, $runtime, $options = [])
{
if (!empty(self::$event)) {
foreach (self::$event as $callback) {
if (is_callable($callback)) {
call_user_func_array($callback, [$sql, $runtime, $options]);
}
}
} else {
// 未注册监听则记录到日志中
Log::record('[ Mongo ] ' . $sql . ' [ RunTime:' . $runtime . 's ]', 'sql');
}
}
/**
* 数据库调试 记录当前SQL及分析性能
* @access protected
* @param boolean $start 调试开始标记 true 开始 false 结束
* @param string $sql 执行的SQL语句 留空自动获取
* @return void
*/
protected function debug($start, $sql = '')
{
if (!empty($this->config['debug'])) {
// 开启数据库调试模式
if ($start) {
Debug::remark('queryStartTime', 'time');
} else {
// 记录操作结束时间
Debug::remark('queryEndTime', 'time');
$runtime = Debug::getRangeTime('queryStartTime', 'queryEndTime');
$sql = $sql ?: $this->queryStr;
// SQL监听
$this->trigger($sql, $runtime, $this->options);
}
}
}
/**
* 释放查询结果
* @access public
*/
public function free()
{
$this->cursor = null;
}
/**
* 关闭数据库
* @access public
*/
public function close()
{
$this->mongo = null;
$this->cursor = null;
$this->linkRead = null;
$this->linkWrite = null;
$this->links = [];
}
/**
* 初始化数据库连接
* @access protected
* @param boolean $master 是否主服务器
* @return void
*/
protected function initConnect($master = true)
{
if (!empty($this->config['deploy'])) {
// 采用分布式数据库
if ($master) {
if (!$this->linkWrite) {
$this->linkWrite = $this->multiConnect(true);
}
$this->mongo = $this->linkWrite;
} else {
if (!$this->linkRead) {
$this->linkRead = $this->multiConnect(false);
}
$this->mongo = $this->linkRead;
}
} elseif (!$this->mongo) {
// 默认单数据库
$this->mongo = $this->connect();
}
}
/**
* 连接分布式服务器
* @access protected
* @param boolean $master 主服务器
* @return PDO
*/
protected function multiConnect($master = false)
{
$_config = [];
// 分布式数据库配置解析
foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn', 'charset'] as $name) {
$_config[$name] = explode(',', $this->config[$name]);
}
// 主服务器序号
$m = floor(mt_rand(0, $this->config['master_num'] - 1));
if ($this->config['rw_separate']) {
// 主从式采用读写分离
if ($master) // 主服务器写入
{
if ($this->config['is_replica_set']) {
return $this->replicaSetConnect();
} else {
$r = $m;
}
} elseif (is_numeric($this->config['slave_no'])) {
// 指定服务器读
$r = $this->config['slave_no'];
} else {
// 读操作连接从服务器 每次随机连接的数据库
$r = floor(mt_rand($this->config['master_num'], count($_config['hostname']) - 1));
}
} else {
// 读写操作不区分服务器 每次随机连接的数据库
$r = floor(mt_rand(0, count($_config['hostname']) - 1));
}
$dbConfig = [];
foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn', 'charset'] as $name) {
$dbConfig[$name] = isset($_config[$name][$r]) ? $_config[$name][$r] : $_config[$name][0];
}
return $this->connect($dbConfig, $r);
}
/**
* 创建基于复制集的连接
* @return Manager
*/
public function replicaSetConnect()
{
$this->dbName = $this->config['database'];
$this->typeMap = $this->config['type_map'];
if ($this->config['debug']) {
$startTime = microtime(true);
}
$this->config['params']['replicaSet'] = $this->config['database'];
$manager = new Manager($this->buildUrl(), $this->config['params']);
if ($this->config['debug']) {
// 记录数据库连接信息
Log::record('[ DB ] CONNECT:[ UseTime:' . number_format(microtime(true) - $startTime, 6) . 's ] ' . $this->config['dsn'], 'sql');
}
return $manager;
}
/**
* 根据配置信息 生成适用于链接复制集的 URL
* @return string
*/
private function buildUrl()
{
$url = 'mongodb://' . ($this->config['username'] ? "{$this->config['username']}" : '') . ($this->config['password'] ? ":{$this->config['password']}@" : '');
$hostList = explode(',', $this->config['hostname']);
$portList = explode(',', $this->config['hostport']);
for ($i = 0; $i < count($hostList); $i++) {
$url = $url . $hostList[$i] . ':' . $portList[0] . ',';
}
return rtrim($url, ",") . '/';
}
/**
* 启动事务
* @access public
* @return void
* @throws \PDOException
* @throws \Exception
*/
public function startTrans()
{}
/**
* 用于非自动提交状态下面的查询提交
* @access public
* @return void
* @throws PDOException
*/
public function commit()
{}
/**
* 事务回滚
* @access public
* @return void
* @throws PDOException
*/
public function rollback()
{}
/**
* 析构方法
* @access public
*/
public function __destruct()
{
// 释放查询
$this->free();
// 关闭连接
$this->close();
}
}

2157
vendor/topthink/think-mongo/src/Query.php vendored Normal file

File diff suppressed because it is too large Load Diff