mirror of
https://gitee.com/fastadminnet/framework.git
synced 2026-07-06 15:02:47 +08:00
PSR规范调整
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -10,34 +10,40 @@
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\db\driver;
|
||||
|
||||
use think\db\Driver;
|
||||
use think\Exception;
|
||||
use think\Lang as Lang;
|
||||
use think\Log as Log;
|
||||
|
||||
/**
|
||||
* Mongo数据库驱动
|
||||
*/
|
||||
class Mongo extends Driver {
|
||||
class Mongo extends Driver
|
||||
{
|
||||
|
||||
protected $_mongo = null; // MongoDb Object
|
||||
protected $_collection = null; // MongoCollection Object
|
||||
protected $_dbName = ''; // dbName
|
||||
protected $_collectionName = ''; // collectionName
|
||||
protected $_cursor = null; // MongoCursor Object
|
||||
protected $comparison = ['neq'=>'ne','ne'=>'ne','gt'=>'gt','egt'=>'gte','gte'=>'gte','lt'=>'lt','elt'=>'lte','lte'=>'lte','in'=>'in','not in'=>'nin','nin'=>'nin'];
|
||||
protected $_mongo = null; // MongoDb Object
|
||||
protected $_collection = null; // MongoCollection Object
|
||||
protected $_dbName = ''; // dbName
|
||||
protected $_collectionName = ''; // collectionName
|
||||
protected $_cursor = null; // MongoCursor Object
|
||||
protected $comparison = ['neq' => 'ne', 'ne' => 'ne', 'gt' => 'gt', 'egt' => 'gte', 'gte' => 'gte', 'lt' => 'lt', 'elt' => 'lte', 'lte' => 'lte', 'in' => 'in', 'not in' => 'nin', 'nin' => 'nin'];
|
||||
|
||||
/**
|
||||
* 架构函数 读取数据库配置信息
|
||||
* @access public
|
||||
* @param array $config 数据库配置数组
|
||||
*/
|
||||
public function __construct($config=''){
|
||||
if ( !class_exists('mongoClient') ) {
|
||||
throw new Exception(Lang::get('_NOT_SUPPERT_').':Mongo');
|
||||
public function __construct($config = '')
|
||||
{
|
||||
if (!class_exists('mongoClient')) {
|
||||
throw new Exception(Lang::get('_NOT_SUPPERT_') . ':Mongo');
|
||||
}
|
||||
if(!empty($config)) {
|
||||
$this->config = array_merge($this->config,$config);
|
||||
if(empty($this->config['params'])){
|
||||
$this->config['params'] = [];
|
||||
}
|
||||
if (!empty($config)) {
|
||||
$this->config = array_merge($this->config, $config);
|
||||
if (empty($this->config['params'])) {
|
||||
$this->config['params'] = [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,13 +51,17 @@ class Mongo extends Driver {
|
||||
* 连接数据库方法
|
||||
* @access public
|
||||
*/
|
||||
public function connect($config='',$linkNum=0) {
|
||||
if ( !isset($this->linkID[$linkNum]) ) {
|
||||
if(empty($config)) $config = $this->config['connection'];
|
||||
$host = 'mongodb://'.($config['username']?"{$config['username']}":'').($config['password']?":{$config['password']}@":'').$config['hostname'].($config['hostport']?":{$config['hostport']}":'').'/'.($config['database']?"{$config['database']}":'');
|
||||
try{
|
||||
$this->linkID[$linkNum] = new \mongoClient( $host,$this->config['params']);
|
||||
}catch (\MongoConnectionException $e){
|
||||
public function connect($config = '', $linkNum = 0)
|
||||
{
|
||||
if (!isset($this->linkID[$linkNum])) {
|
||||
if (empty($config)) {
|
||||
$config = $this->config['connection'];
|
||||
}
|
||||
|
||||
$host = 'mongodb://' . ($config['username'] ? "{$config['username']}" : '') . ($config['password'] ? ":{$config['password']}@" : '') . $config['hostname'] . ($config['hostport'] ? ":{$config['hostport']}" : '') . '/' . ($config['database'] ? "{$config['database']}" : '');
|
||||
try {
|
||||
$this->linkID[$linkNum] = new \mongoClient($host, $this->config['params']);
|
||||
} catch (\MongoConnectionException $e) {
|
||||
throw new Exception($e->getmessage());
|
||||
}
|
||||
}
|
||||
@@ -66,27 +76,32 @@ class Mongo extends Driver {
|
||||
* @param boolean $master 是否主服务器
|
||||
* @return void
|
||||
*/
|
||||
public function switchCollection($collection,$db='',$master=true){
|
||||
public function switchCollection($collection, $db = '', $master = true)
|
||||
{
|
||||
// 当前没有连接 则首先进行数据库连接
|
||||
if ( !$this->_linkID ) $this->initConnect($master);
|
||||
try{
|
||||
if(!empty($db)) { // 传人Db则切换数据库
|
||||
if (!$this->_linkID) {
|
||||
$this->initConnect($master);
|
||||
}
|
||||
|
||||
try {
|
||||
if (!empty($db)) {
|
||||
// 传人Db则切换数据库
|
||||
// 当前MongoDb对象
|
||||
$this->_dbName = $db;
|
||||
$this->_mongo = $this->_linkID->selectDb($db);
|
||||
$this->_dbName = $db;
|
||||
$this->_mongo = $this->_linkID->selectDb($db);
|
||||
}
|
||||
// 当前MongoCollection对象
|
||||
if($this->config['debug']) {
|
||||
$this->queryStr = $this->_dbName.'.getCollection('.$collection.')';
|
||||
if ($this->config['debug']) {
|
||||
$this->queryStr = $this->_dbName . '.getCollection(' . $collection . ')';
|
||||
}
|
||||
if($this->_collectionName != $collection) {
|
||||
if ($this->_collectionName != $collection) {
|
||||
$this->queryTimes++;
|
||||
$this->debug(true);
|
||||
$this->_collection = $this->_mongo->selectCollection($collection);
|
||||
$this->_collection = $this->_mongo->selectCollection($collection);
|
||||
$this->debug(false);
|
||||
$this->_collectionName = $collection; // 记录当前Collection名称
|
||||
$this->_collectionName = $collection; // 记录当前Collection名称
|
||||
}
|
||||
}catch (\MongoException $e){
|
||||
} catch (\MongoException $e) {
|
||||
throw new Exception($e->getMessage());
|
||||
}
|
||||
}
|
||||
@@ -95,7 +110,8 @@ class Mongo extends Driver {
|
||||
* 释放查询结果
|
||||
* @access public
|
||||
*/
|
||||
public function free() {
|
||||
public function free()
|
||||
{
|
||||
$this->_cursor = null;
|
||||
}
|
||||
|
||||
@@ -105,13 +121,14 @@ class Mongo extends Driver {
|
||||
* @param array $command 指令
|
||||
* @return array
|
||||
*/
|
||||
public function command($command=[]) {
|
||||
public function command($command = [])
|
||||
{
|
||||
$this->executeTimes++;
|
||||
$this->debug(true);
|
||||
$this->queryStr = 'command:'.json_encode($command);
|
||||
$result = $this->_mongo->command($command);
|
||||
$this->queryStr = 'command:' . json_encode($command);
|
||||
$result = $this->_mongo->command($command);
|
||||
$this->debug(false);
|
||||
if(!$result['ok']) {
|
||||
if (!$result['ok']) {
|
||||
throw new Exception($result['errmsg']);
|
||||
}
|
||||
return $result;
|
||||
@@ -124,15 +141,16 @@ class Mongo extends Driver {
|
||||
* @param array $args 参数
|
||||
* @return mixed
|
||||
*/
|
||||
public function execute($code,$args=[]) {
|
||||
public function execute($code, $args = [])
|
||||
{
|
||||
$this->executeTimes++;
|
||||
$this->debug(true);
|
||||
$this->queryStr = 'execute:'.$code;
|
||||
$result = $this->_mongo->execute($code,$args);
|
||||
$this->queryStr = 'execute:' . $code;
|
||||
$result = $this->_mongo->execute($code, $args);
|
||||
$this->debug(false);
|
||||
if($result['ok']) {
|
||||
if ($result['ok']) {
|
||||
return $result['retval'];
|
||||
}else{
|
||||
} else {
|
||||
throw new Exception($result['errmsg']);
|
||||
}
|
||||
}
|
||||
@@ -141,13 +159,14 @@ class Mongo extends Driver {
|
||||
* 关闭数据库
|
||||
* @access public
|
||||
*/
|
||||
public function close() {
|
||||
if($this->_linkID) {
|
||||
public function close()
|
||||
{
|
||||
if ($this->_linkID) {
|
||||
$this->_linkID->close();
|
||||
$this->_linkID = null;
|
||||
$this->_mongo = null;
|
||||
$this->_collection = null;
|
||||
$this->_cursor = null;
|
||||
$this->_linkID = null;
|
||||
$this->_mongo = null;
|
||||
$this->_collection = null;
|
||||
$this->_cursor = null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,9 +175,10 @@ class Mongo extends Driver {
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function error() {
|
||||
public function error()
|
||||
{
|
||||
$this->error = $this->_mongo->lastError();
|
||||
Log::record($this->error,'ERR');
|
||||
Log::record($this->error, 'ERR');
|
||||
return $this->error;
|
||||
}
|
||||
|
||||
@@ -170,27 +190,28 @@ class Mongo extends Driver {
|
||||
* @param boolean $replace 是否replace
|
||||
* @return false | integer
|
||||
*/
|
||||
public function insert($data,$options=[],$replace=false) {
|
||||
if(isset($options['table'])) {
|
||||
public function insert($data, $options = [], $replace = false)
|
||||
{
|
||||
if (isset($options['table'])) {
|
||||
$this->switchCollection($options['table']);
|
||||
}
|
||||
$this->model = $options['model'];
|
||||
$this->model = $options['model'];
|
||||
$this->executeTimes++;
|
||||
if($this->config['debug']) {
|
||||
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.insert(';
|
||||
$this->queryStr .= $data?json_encode($data):'{}';
|
||||
$this->queryStr .= ')';
|
||||
if ($this->config['debug']) {
|
||||
$this->queryStr = $this->_dbName . '.' . $this->_collectionName . '.insert(';
|
||||
$this->queryStr .= $data ? json_encode($data) : '{}';
|
||||
$this->queryStr .= ')';
|
||||
}
|
||||
try{
|
||||
try {
|
||||
$this->debug(true);
|
||||
$result = $replace? $this->_collection->save($data): $this->_collection->insert($data);
|
||||
$result = $replace ? $this->_collection->save($data) : $this->_collection->insert($data);
|
||||
$this->debug(false);
|
||||
if($result) {
|
||||
$_id = $data['_id'];
|
||||
if(is_object($_id)) {
|
||||
if ($result) {
|
||||
$_id = $data['_id'];
|
||||
if (is_object($_id)) {
|
||||
$_id = $_id->__toString();
|
||||
}
|
||||
$this->lastInsID = $_id;
|
||||
$this->lastInsID = $_id;
|
||||
}
|
||||
return $result;
|
||||
} catch (\MongoCursorException $e) {
|
||||
@@ -205,15 +226,16 @@ class Mongo extends Driver {
|
||||
* @param array $options 参数表达式
|
||||
* @return bool
|
||||
*/
|
||||
public function insertAll($dataList,$options=[]) {
|
||||
if(isset($options['table'])) {
|
||||
public function insertAll($dataList, $options = [])
|
||||
{
|
||||
if (isset($options['table'])) {
|
||||
$this->switchCollection($options['table']);
|
||||
}
|
||||
$this->model = $options['model'];
|
||||
$this->model = $options['model'];
|
||||
$this->executeTimes++;
|
||||
try{
|
||||
try {
|
||||
$this->debug(true);
|
||||
$result = $this->_collection->batchInsert($dataList);
|
||||
$result = $this->_collection->batchInsert($dataList);
|
||||
$this->debug(false);
|
||||
return $result;
|
||||
} catch (\MongoCursorException $e) {
|
||||
@@ -227,19 +249,20 @@ class Mongo extends Driver {
|
||||
* @param string $pk 主键名
|
||||
* @return integer
|
||||
*/
|
||||
public function getMongoNextId($pk) {
|
||||
if($this->config['debug']) {
|
||||
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.find({},{'.$pk.':1}).sort({'.$pk.':-1}).limit(1)';
|
||||
public function getMongoNextId($pk)
|
||||
{
|
||||
if ($this->config['debug']) {
|
||||
$this->queryStr = $this->_dbName . '.' . $this->_collectionName . '.find({},{' . $pk . ':1}).sort({' . $pk . ':-1}).limit(1)';
|
||||
}
|
||||
try{
|
||||
try {
|
||||
$this->debug(true);
|
||||
$result = $this->_collection->find([],[$pk=>1])->sort([$pk=>-1])->limit(1);
|
||||
$result = $this->_collection->find([], [$pk => 1])->sort([$pk => -1])->limit(1);
|
||||
$this->debug(false);
|
||||
} catch (\MongoCursorException $e) {
|
||||
throw new Exception($e->getMessage());
|
||||
}
|
||||
$data = $result->getNext();
|
||||
return isset($data[$pk])?$data[$pk]+1:1;
|
||||
return isset($data[$pk]) ? $data[$pk] + 1 : 1;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -249,27 +272,28 @@ class Mongo extends Driver {
|
||||
* @param array $options 表达式
|
||||
* @return bool
|
||||
*/
|
||||
public function update($data,$options) {
|
||||
if(isset($options['table'])) {
|
||||
public function update($data, $options)
|
||||
{
|
||||
if (isset($options['table'])) {
|
||||
$this->switchCollection($options['table']);
|
||||
}
|
||||
$this->executeTimes++;
|
||||
$this->model = $options['model'];
|
||||
$query = $this->parseWhere($options['where']);
|
||||
$set = $this->parseSet($data);
|
||||
if($this->config['debug']) {
|
||||
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.update(';
|
||||
$this->queryStr .= $query?json_encode($query):'{}';
|
||||
$this->queryStr .= ','.json_encode($set).')';
|
||||
$this->model = $options['model'];
|
||||
$query = $this->parseWhere($options['where']);
|
||||
$set = $this->parseSet($data);
|
||||
if ($this->config['debug']) {
|
||||
$this->queryStr = $this->_dbName . '.' . $this->_collectionName . '.update(';
|
||||
$this->queryStr .= $query ? json_encode($query) : '{}';
|
||||
$this->queryStr .= ',' . json_encode($set) . ')';
|
||||
}
|
||||
try{
|
||||
try {
|
||||
$this->debug(true);
|
||||
if(isset($options['limit']) && $options['limit'] == 1) {
|
||||
$multiple = ["multiple" => false];
|
||||
}else{
|
||||
$multiple = ["multiple" => true];
|
||||
if (isset($options['limit']) && 1 == $options['limit']) {
|
||||
$multiple = ["multiple" => false];
|
||||
} else {
|
||||
$multiple = ["multiple" => true];
|
||||
}
|
||||
$result = $this->_collection->update($query,$set,$multiple);
|
||||
$result = $this->_collection->update($query, $set, $multiple);
|
||||
$this->debug(false);
|
||||
return $result;
|
||||
} catch (\MongoCursorException $e) {
|
||||
@@ -283,19 +307,20 @@ class Mongo extends Driver {
|
||||
* @param array $options 表达式
|
||||
* @return false | integer
|
||||
*/
|
||||
public function delete($options=[]) {
|
||||
if(isset($options['table'])) {
|
||||
public function delete($options = [])
|
||||
{
|
||||
if (isset($options['table'])) {
|
||||
$this->switchCollection($options['table']);
|
||||
}
|
||||
$query = $this->parseWhere($options['where']);
|
||||
$this->model = $options['model'];
|
||||
$query = $this->parseWhere($options['where']);
|
||||
$this->model = $options['model'];
|
||||
$this->executeTimes++;
|
||||
if($this->config['debug']) {
|
||||
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.remove('.json_encode($query).')';
|
||||
if ($this->config['debug']) {
|
||||
$this->queryStr = $this->_dbName . '.' . $this->_collectionName . '.remove(' . json_encode($query) . ')';
|
||||
}
|
||||
try{
|
||||
try {
|
||||
$this->debug(true);
|
||||
$result = $this->_collection->remove($query);
|
||||
$result = $this->_collection->remove($query);
|
||||
$this->debug(false);
|
||||
return $result;
|
||||
} catch (\MongoCursorException $e) {
|
||||
@@ -309,18 +334,19 @@ class Mongo extends Driver {
|
||||
* @param array $options 表达式
|
||||
* @return false | integer
|
||||
*/
|
||||
public function clear($options=[]){
|
||||
if(isset($options['table'])) {
|
||||
public function clear($options = [])
|
||||
{
|
||||
if (isset($options['table'])) {
|
||||
$this->switchCollection($options['table']);
|
||||
}
|
||||
$this->model = $options['model'];
|
||||
$this->model = $options['model'];
|
||||
$this->executeTimes++;
|
||||
if($this->config['debug']) {
|
||||
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.remove({})';
|
||||
if ($this->config['debug']) {
|
||||
$this->queryStr = $this->_dbName . '.' . $this->_collectionName . '.remove({})';
|
||||
}
|
||||
try{
|
||||
try {
|
||||
$this->debug(true);
|
||||
$result = $this->_collection->drop();
|
||||
$result = $this->_collection->drop();
|
||||
$this->debug(false);
|
||||
return $result;
|
||||
} catch (\MongoCursorException $e) {
|
||||
@@ -334,67 +360,71 @@ class Mongo extends Driver {
|
||||
* @param array $options 表达式
|
||||
* @return iterator
|
||||
*/
|
||||
public function select($options=[]) {
|
||||
if(isset($options['table'])) {
|
||||
$this->switchCollection($options['table'],'',false);
|
||||
public function select($options = [])
|
||||
{
|
||||
if (isset($options['table'])) {
|
||||
$this->switchCollection($options['table'], '', false);
|
||||
}
|
||||
$cache = isset($options['cache'])?$options['cache']:false;
|
||||
if($cache) { // 查询缓存检测
|
||||
$key = is_string($cache['key'])?$cache['key']:md5(serialize($options));
|
||||
$value = S($key,'','',$cache['type']);
|
||||
if(false !== $value) {
|
||||
$cache = isset($options['cache']) ? $options['cache'] : false;
|
||||
if ($cache) {
|
||||
// 查询缓存检测
|
||||
$key = is_string($cache['key']) ? $cache['key'] : md5(serialize($options));
|
||||
$value = S($key, '', '', $cache['type']);
|
||||
if (false !== $value) {
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
$this->model = $options['model'];
|
||||
$this->model = $options['model'];
|
||||
$this->queryTimes++;
|
||||
$query = $this->parseWhere($options['where']);
|
||||
$field = $this->parseField($options['field']);
|
||||
try{
|
||||
if($this->config['debug']) {
|
||||
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.find(';
|
||||
$this->queryStr .= $query? json_encode($query):'{}';
|
||||
$this->queryStr .= $field? ','.json_encode($field):'';
|
||||
$this->queryStr .= ')';
|
||||
$query = $this->parseWhere($options['where']);
|
||||
$field = $this->parseField($options['field']);
|
||||
try {
|
||||
if ($this->config['debug']) {
|
||||
$this->queryStr = $this->_dbName . '.' . $this->_collectionName . '.find(';
|
||||
$this->queryStr .= $query ? json_encode($query) : '{}';
|
||||
$this->queryStr .= $field ? ',' . json_encode($field) : '';
|
||||
$this->queryStr .= ')';
|
||||
}
|
||||
$this->debug(true);
|
||||
$_cursor = $this->_collection->find($query,$field);
|
||||
if($options['order']) {
|
||||
$order = $this->parseOrder($options['order']);
|
||||
if($this->config['debug']) {
|
||||
$this->queryStr .= '.sort('.json_encode($order).')';
|
||||
$_cursor = $this->_collection->find($query, $field);
|
||||
if ($options['order']) {
|
||||
$order = $this->parseOrder($options['order']);
|
||||
if ($this->config['debug']) {
|
||||
$this->queryStr .= '.sort(' . json_encode($order) . ')';
|
||||
}
|
||||
$_cursor = $_cursor->sort($order);
|
||||
$_cursor = $_cursor->sort($order);
|
||||
}
|
||||
if(isset($options['page'])) { // 根据页数计算limit
|
||||
if(strpos($options['page'],',')) {
|
||||
list($page,$length) = explode(',',$options['page']);
|
||||
}else{
|
||||
$page = $options['page'];
|
||||
if (isset($options['page'])) {
|
||||
// 根据页数计算limit
|
||||
if (strpos($options['page'], ',')) {
|
||||
list($page, $length) = explode(',', $options['page']);
|
||||
} else {
|
||||
$page = $options['page'];
|
||||
}
|
||||
$page = $page?$page:1;
|
||||
$length = isset($length)?$length:(is_numeric($options['limit'])?$options['limit']:20);
|
||||
$offset = $length*((int)$page-1);
|
||||
$options['limit'] = $offset.','.$length;
|
||||
$page = $page ? $page : 1;
|
||||
$length = isset($length) ? $length : (is_numeric($options['limit']) ? $options['limit'] : 20);
|
||||
$offset = $length * ((int) $page - 1);
|
||||
$options['limit'] = $offset . ',' . $length;
|
||||
}
|
||||
if(isset($options['limit'])) {
|
||||
list($offset,$length) = $this->parseLimit($options['limit']);
|
||||
if(!empty($offset)) {
|
||||
if($this->config['debug']) {
|
||||
$this->queryStr .= '.skip('.intval($offset).')';
|
||||
if (isset($options['limit'])) {
|
||||
list($offset, $length) = $this->parseLimit($options['limit']);
|
||||
if (!empty($offset)) {
|
||||
if ($this->config['debug']) {
|
||||
$this->queryStr .= '.skip(' . intval($offset) . ')';
|
||||
}
|
||||
$_cursor = $_cursor->skip(intval($offset));
|
||||
$_cursor = $_cursor->skip(intval($offset));
|
||||
}
|
||||
if($this->config['debug']) {
|
||||
$this->queryStr .= '.limit('.intval($length).')';
|
||||
if ($this->config['debug']) {
|
||||
$this->queryStr .= '.limit(' . intval($length) . ')';
|
||||
}
|
||||
$_cursor = $_cursor->limit(intval($length));
|
||||
$_cursor = $_cursor->limit(intval($length));
|
||||
}
|
||||
$this->debug(false);
|
||||
$this->_cursor = $_cursor;
|
||||
$resultSet = iterator_to_array($_cursor);
|
||||
if($cache && $resultSet ) { // 查询缓存写入
|
||||
S($key,$resultSet,$cache['expire'],$cache['type']);
|
||||
$this->_cursor = $_cursor;
|
||||
$resultSet = iterator_to_array($_cursor);
|
||||
if ($cache && $resultSet) {
|
||||
// 查询缓存写入
|
||||
S($key, $resultSet, $cache['expire'], $cache['type']);
|
||||
}
|
||||
return $resultSet;
|
||||
} catch (\MongoCursorException $e) {
|
||||
@@ -408,34 +438,37 @@ class Mongo extends Driver {
|
||||
* @param array $options 表达式
|
||||
* @return array
|
||||
*/
|
||||
public function find($options=[]){
|
||||
if(isset($options['table'])) {
|
||||
$this->switchCollection($options['table'],'',false);
|
||||
public function find($options = [])
|
||||
{
|
||||
if (isset($options['table'])) {
|
||||
$this->switchCollection($options['table'], '', false);
|
||||
}
|
||||
$cache = isset($options['cache'])?$options['cache']:false;
|
||||
if($cache) { // 查询缓存检测
|
||||
$key = is_string($cache['key'])?$cache['key']:md5(serialize($options));
|
||||
$value = S($key,'','',$cache['type']);
|
||||
if(false !== $value) {
|
||||
$cache = isset($options['cache']) ? $options['cache'] : false;
|
||||
if ($cache) {
|
||||
// 查询缓存检测
|
||||
$key = is_string($cache['key']) ? $cache['key'] : md5(serialize($options));
|
||||
$value = S($key, '', '', $cache['type']);
|
||||
if (false !== $value) {
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
$this->model = $options['model'];
|
||||
$this->model = $options['model'];
|
||||
$this->queryTimes++;
|
||||
$query = $this->parseWhere($options['where']);
|
||||
$fields = $this->parseField($options['field']);
|
||||
if($this->config['debug']) {
|
||||
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.findOne(';
|
||||
$this->queryStr .= $query?json_encode($query):'{}';
|
||||
$this->queryStr .= $fields?','.json_encode($fields):'';
|
||||
$query = $this->parseWhere($options['where']);
|
||||
$fields = $this->parseField($options['field']);
|
||||
if ($this->config['debug']) {
|
||||
$this->queryStr = $this->_dbName . '.' . $this->_collectionName . '.findOne(';
|
||||
$this->queryStr .= $query ? json_encode($query) : '{}';
|
||||
$this->queryStr .= $fields ? ',' . json_encode($fields) : '';
|
||||
$this->queryStr .= ')';
|
||||
}
|
||||
try{
|
||||
try {
|
||||
$this->debug(true);
|
||||
$result = $this->_collection->findOne($query,$fields);
|
||||
$result = $this->_collection->findOne($query, $fields);
|
||||
$this->debug(false);
|
||||
if($cache && $result ) { // 查询缓存写入
|
||||
S($key,$result,$cache['expire'],$cache['type']);
|
||||
if ($cache && $result) {
|
||||
// 查询缓存写入
|
||||
S($key, $result, $cache['expire'], $cache['type']);
|
||||
}
|
||||
return $result;
|
||||
} catch (\MongoCursorException $e) {
|
||||
@@ -449,21 +482,22 @@ class Mongo extends Driver {
|
||||
* @param array $options 表达式
|
||||
* @return iterator
|
||||
*/
|
||||
public function count($options=[]){
|
||||
if(isset($options['table'])) {
|
||||
$this->switchCollection($options['table'],'',false);
|
||||
public function count($options = [])
|
||||
{
|
||||
if (isset($options['table'])) {
|
||||
$this->switchCollection($options['table'], '', false);
|
||||
}
|
||||
$this->model = $options['model'];
|
||||
$this->model = $options['model'];
|
||||
$this->queryTimes++;
|
||||
$query = $this->parseWhere($options['where']);
|
||||
if($this->config['debug']) {
|
||||
$this->queryStr = $this->_dbName.'.'.$this->_collectionName;
|
||||
$this->queryStr .= $query?'.find('.json_encode($query).')':'';
|
||||
$this->queryStr .= '.count()';
|
||||
$query = $this->parseWhere($options['where']);
|
||||
if ($this->config['debug']) {
|
||||
$this->queryStr = $this->_dbName . '.' . $this->_collectionName;
|
||||
$this->queryStr .= $query ? '.find(' . json_encode($query) . ')' : '';
|
||||
$this->queryStr .= '.count()';
|
||||
}
|
||||
try{
|
||||
try {
|
||||
$this->debug(true);
|
||||
$count = $this->_collection->count($query);
|
||||
$count = $this->_collection->count($query);
|
||||
$this->debug(false);
|
||||
return $count;
|
||||
} catch (\MongoCursorException $e) {
|
||||
@@ -471,8 +505,9 @@ class Mongo extends Driver {
|
||||
}
|
||||
}
|
||||
|
||||
public function group($keys,$initial,$reduce,$options=[]){
|
||||
$this->_collection->group($keys,$initial,$reduce,$options);
|
||||
public function group($keys, $initial, $reduce, $options = [])
|
||||
{
|
||||
$this->_collection->group($keys, $initial, $reduce, $options);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -480,27 +515,29 @@ class Mongo extends Driver {
|
||||
* @access public
|
||||
* @return array
|
||||
*/
|
||||
public function getFields($collection=''){
|
||||
if(!empty($collection) && $collection != $this->_collectionName) {
|
||||
$this->switchCollection($collection,'',false);
|
||||
public function getFields($collection = '')
|
||||
{
|
||||
if (!empty($collection) && $collection != $this->_collectionName) {
|
||||
$this->switchCollection($collection, '', false);
|
||||
}
|
||||
$this->queryTimes++;
|
||||
if($this->config['debug']) {
|
||||
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.findOne()';
|
||||
if ($this->config['debug']) {
|
||||
$this->queryStr = $this->_dbName . '.' . $this->_collectionName . '.findOne()';
|
||||
}
|
||||
try{
|
||||
try {
|
||||
$this->debug(true);
|
||||
$result = $this->_collection->findOne();
|
||||
$result = $this->_collection->findOne();
|
||||
$this->debug(false);
|
||||
} catch (\MongoCursorException $e) {
|
||||
throw new Exception($e->getMessage());
|
||||
}
|
||||
if($result) { // 存在数据则分析字段
|
||||
$info = [];
|
||||
foreach ($result as $key=>$val){
|
||||
$info[$key] = [
|
||||
'name' => $key,
|
||||
'type' => getType($val),
|
||||
if ($result) {
|
||||
// 存在数据则分析字段
|
||||
$info = [];
|
||||
foreach ($result as $key => $val) {
|
||||
$info[$key] = [
|
||||
'name' => $key,
|
||||
'type' => getType($val),
|
||||
];
|
||||
}
|
||||
return $info;
|
||||
@@ -513,17 +550,18 @@ class Mongo extends Driver {
|
||||
* 取得当前数据库的collection信息
|
||||
* @access public
|
||||
*/
|
||||
public function getTables(){
|
||||
if($this->config['debug']) {
|
||||
$this->queryStr = $this->_dbName.'.getCollenctionNames()';
|
||||
public function getTables()
|
||||
{
|
||||
if ($this->config['debug']) {
|
||||
$this->queryStr = $this->_dbName . '.getCollenctionNames()';
|
||||
}
|
||||
$this->queryTimes++;
|
||||
$this->debug(true);
|
||||
$list = $this->_mongo->listCollections();
|
||||
$list = $this->_mongo->listCollections();
|
||||
$this->debug(false);
|
||||
$info = [];
|
||||
foreach ($list as $collection){
|
||||
$info[] = $collection->getName();
|
||||
$info = [];
|
||||
foreach ($list as $collection) {
|
||||
$info[] = $collection->getName();
|
||||
}
|
||||
return $info;
|
||||
}
|
||||
@@ -534,13 +572,14 @@ class Mongo extends Driver {
|
||||
* @param array $data
|
||||
* @return string
|
||||
*/
|
||||
protected function parseSet($data) {
|
||||
$result = [];
|
||||
foreach ($data as $key=>$val){
|
||||
if(is_array($val)) {
|
||||
switch($val[0]) {
|
||||
protected function parseSet($data)
|
||||
{
|
||||
$result = [];
|
||||
foreach ($data as $key => $val) {
|
||||
if (is_array($val)) {
|
||||
switch ($val[0]) {
|
||||
case 'inc':
|
||||
$result['$inc'][$key] = (int)$val[1];
|
||||
$result['$inc'][$key] = (int) $val[1];
|
||||
break;
|
||||
case 'set':
|
||||
case 'unset':
|
||||
@@ -550,13 +589,13 @@ class Mongo extends Driver {
|
||||
case 'pop':
|
||||
case 'pull':
|
||||
case 'pullall':
|
||||
$result['$'.$val[0]][$key] = $val[1];
|
||||
$result['$' . $val[0]][$key] = $val[1];
|
||||
break;
|
||||
default:
|
||||
$result['$set'][$key] = $val;
|
||||
$result['$set'][$key] = $val;
|
||||
}
|
||||
}else{
|
||||
$result['$set'][$key] = $val;
|
||||
} else {
|
||||
$result['$set'][$key] = $val;
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
@@ -568,18 +607,19 @@ class Mongo extends Driver {
|
||||
* @param mixed $order
|
||||
* @return array
|
||||
*/
|
||||
protected function parseOrder($order) {
|
||||
if(is_string($order)) {
|
||||
$array = explode(',',$order);
|
||||
$order = [];
|
||||
foreach ($array as $key=>$val){
|
||||
$arr = explode(' ',trim($val));
|
||||
if(isset($arr[1])) {
|
||||
$arr[1] = $arr[1]=='asc'?1:-1;
|
||||
}else{
|
||||
$arr[1] = 1;
|
||||
protected function parseOrder($order)
|
||||
{
|
||||
if (is_string($order)) {
|
||||
$array = explode(',', $order);
|
||||
$order = [];
|
||||
foreach ($array as $key => $val) {
|
||||
$arr = explode(' ', trim($val));
|
||||
if (isset($arr[1])) {
|
||||
$arr[1] = 'asc' == $arr[1] ? 1 : -1;
|
||||
} else {
|
||||
$arr[1] = 1;
|
||||
}
|
||||
$order[$arr[0]] = $arr[1];
|
||||
$order[$arr[0]] = $arr[1];
|
||||
}
|
||||
}
|
||||
return $order;
|
||||
@@ -591,11 +631,12 @@ class Mongo extends Driver {
|
||||
* @param mixed $limit
|
||||
* @return array
|
||||
*/
|
||||
protected function parseLimit($limit) {
|
||||
if(strpos($limit,',')) {
|
||||
$array = explode(',',$limit);
|
||||
}else{
|
||||
$array = [0,$limit];
|
||||
protected function parseLimit($limit)
|
||||
{
|
||||
if (strpos($limit, ',')) {
|
||||
$array = explode(',', $limit);
|
||||
} else {
|
||||
$array = [0, $limit];
|
||||
}
|
||||
return $array;
|
||||
}
|
||||
@@ -606,12 +647,13 @@ class Mongo extends Driver {
|
||||
* @param mixed $fields
|
||||
* @return array
|
||||
*/
|
||||
public function parseField($fields){
|
||||
if(empty($fields)) {
|
||||
$fields = [];
|
||||
public function parseField($fields)
|
||||
{
|
||||
if (empty($fields)) {
|
||||
$fields = [];
|
||||
}
|
||||
if(is_string($fields)) {
|
||||
$fields = explode(',',$fields);
|
||||
if (is_string($fields)) {
|
||||
$fields = explode(',', $fields);
|
||||
}
|
||||
return $fields;
|
||||
}
|
||||
@@ -622,35 +664,36 @@ class Mongo extends Driver {
|
||||
* @param mixed $where
|
||||
* @return array
|
||||
*/
|
||||
public function parseWhere($where){
|
||||
$query = [];
|
||||
foreach ($where as $key=>$val){
|
||||
if('_id' != $key && 0===strpos($key,'_')) {
|
||||
public function parseWhere($where)
|
||||
{
|
||||
$query = [];
|
||||
foreach ($where as $key => $val) {
|
||||
if ('_id' != $key && 0 === strpos($key, '_')) {
|
||||
// 解析特殊条件表达式
|
||||
$query = $this->parseThinkWhere($key,$val);
|
||||
}else{
|
||||
$query = $this->parseThinkWhere($key, $val);
|
||||
} else {
|
||||
// 查询字段的安全过滤
|
||||
if(!preg_match('/^[A-Z_\|\&\-.a-z0-9]+$/',trim($key))){
|
||||
throw new Exception(Lang::get('_ERROR_QUERY_').':'.$key);
|
||||
if (!preg_match('/^[A-Z_\|\&\-.a-z0-9]+$/', trim($key))) {
|
||||
throw new Exception(Lang::get('_ERROR_QUERY_') . ':' . $key);
|
||||
}
|
||||
$key = trim($key);
|
||||
if(strpos($key,'|')) {
|
||||
$array = explode('|',$key);
|
||||
if (strpos($key, '|')) {
|
||||
$array = explode('|', $key);
|
||||
$str = [];
|
||||
foreach ($array as $k){
|
||||
$str[] = $this->parseWhereItem($k,$val);
|
||||
foreach ($array as $k) {
|
||||
$str[] = $this->parseWhereItem($k, $val);
|
||||
}
|
||||
$query['$or'] = $str;
|
||||
}elseif(strpos($key,'&')){
|
||||
$array = explode('&',$key);
|
||||
$query['$or'] = $str;
|
||||
} elseif (strpos($key, '&')) {
|
||||
$array = explode('&', $key);
|
||||
$str = [];
|
||||
foreach ($array as $k){
|
||||
$str[] = $this->parseWhereItem($k,$val);
|
||||
foreach ($array as $k) {
|
||||
$str[] = $this->parseWhereItem($k, $val);
|
||||
}
|
||||
$query = array_merge($query,$str);
|
||||
}else{
|
||||
$str = $this->parseWhereItem($key,$val);
|
||||
$query = array_merge($query,$str);
|
||||
$query = array_merge($query, $str);
|
||||
} else {
|
||||
$str = $this->parseWhereItem($key, $val);
|
||||
$query = array_merge($query, $str);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -664,18 +707,19 @@ class Mongo extends Driver {
|
||||
* @param mixed $val
|
||||
* @return string
|
||||
*/
|
||||
protected function parseThinkWhere($key,$val) {
|
||||
$query = [];
|
||||
switch($key) {
|
||||
protected function parseThinkWhere($key, $val)
|
||||
{
|
||||
$query = [];
|
||||
switch ($key) {
|
||||
case '_query': // 字符串模式查询条件
|
||||
parse_str($val,$query);
|
||||
if(isset($query['_logic']) && strtolower($query['_logic']) == 'or' ) {
|
||||
parse_str($val, $query);
|
||||
if (isset($query['_logic']) && strtolower($query['_logic']) == 'or') {
|
||||
unset($query['_logic']);
|
||||
$query['$or'] = $query;
|
||||
$query['$or'] = $query;
|
||||
}
|
||||
break;
|
||||
case '_string':// MongoCode查询
|
||||
$query['$where'] = new \MongoCode($val);
|
||||
case '_string': // MongoCode查询
|
||||
$query['$where'] = new \MongoCode($val);
|
||||
break;
|
||||
}
|
||||
return $query;
|
||||
@@ -688,48 +732,60 @@ class Mongo extends Driver {
|
||||
* @param mixed $val
|
||||
* @return array
|
||||
*/
|
||||
protected function parseWhereItem($key,$val) {
|
||||
$query = [];
|
||||
if(is_array($val)) {
|
||||
if(is_string($val[0])) {
|
||||
$con = strtolower($val[0]);
|
||||
if(in_array($con,['neq','ne','gt','egt','gte','lt','lte','elt'])) { // 比较运算
|
||||
$k = '$'.$this->comparison[$con];
|
||||
$query[$key] = [$k=>$val[1]];
|
||||
}elseif('like'== $con){ // 模糊查询 采用正则方式
|
||||
$query[$key] = new \MongoRegex("/".$val[1]."/");
|
||||
}elseif('mod'==$con){ // mod 查询
|
||||
$query[$key] = ['$mod'=>$val[1]];
|
||||
}elseif('regex'==$con){ // 正则查询
|
||||
$query[$key] = new \MongoRegex($val[1]);
|
||||
}elseif(in_array($con,['in','nin','not in'])){ // IN NIN 运算
|
||||
$data = is_string($val[1])? explode(',',$val[1]):$val[1];
|
||||
$k = '$'.$this->comparison[$con];
|
||||
$query[$key] = [$k=>$data];
|
||||
}elseif('all'==$con){ // 满足所有指定条件
|
||||
$data = is_string($val[1])? explode(',',$val[1]):$val[1];
|
||||
$query[$key] = ['$all'=>$data];
|
||||
}elseif('between'==$con){ // BETWEEN运算
|
||||
$data = is_string($val[1])? explode(',',$val[1]):$val[1];
|
||||
$query[$key] = ['$gte'=>$data[0],'$lte'=>$data[1]];
|
||||
}elseif('not between'==$con){
|
||||
$data = is_string($val[1])? explode(',',$val[1]):$val[1];
|
||||
$query[$key] = ['$lt'=>$data[0],'$gt'=>$data[1]];
|
||||
}elseif('exp'==$con){ // 表达式查询
|
||||
$query['$where'] = new \MongoCode($val[1]);
|
||||
}elseif('exists'==$con){ // 字段是否存在
|
||||
$query[$key] =['$exists'=>(bool)$val[1]];
|
||||
}elseif('size'==$con){ // 限制属性大小
|
||||
$query[$key] =['$size'=>intval($val[1])];
|
||||
}elseif('type'==$con){ // 限制字段类型 1 浮点型 2 字符型 3 对象或者MongoDBRef 5 MongoBinData 7 MongoId 8 布尔型 9 MongoDate 10 NULL 15 MongoCode 16 32位整型 17 MongoTimestamp 18 MongoInt64 如果是数组的话判断元素的类型
|
||||
$query[$key] =['$type'=>intval($val[1])];
|
||||
}else{
|
||||
$query[$key] = $val;
|
||||
protected function parseWhereItem($key, $val)
|
||||
{
|
||||
$query = [];
|
||||
if (is_array($val)) {
|
||||
if (is_string($val[0])) {
|
||||
$con = strtolower($val[0]);
|
||||
if (in_array($con, ['neq', 'ne', 'gt', 'egt', 'gte', 'lt', 'lte', 'elt'])) {
|
||||
// 比较运算
|
||||
$k = '$' . $this->comparison[$con];
|
||||
$query[$key] = [$k => $val[1]];
|
||||
} elseif ('like' == $con) {
|
||||
// 模糊查询 采用正则方式
|
||||
$query[$key] = new \MongoRegex("/" . $val[1] . "/");
|
||||
} elseif ('mod' == $con) {
|
||||
// mod 查询
|
||||
$query[$key] = ['$mod' => $val[1]];
|
||||
} elseif ('regex' == $con) {
|
||||
// 正则查询
|
||||
$query[$key] = new \MongoRegex($val[1]);
|
||||
} elseif (in_array($con, ['in', 'nin', 'not in'])) {
|
||||
// IN NIN 运算
|
||||
$data = is_string($val[1]) ? explode(',', $val[1]) : $val[1];
|
||||
$k = '$' . $this->comparison[$con];
|
||||
$query[$key] = [$k => $data];
|
||||
} elseif ('all' == $con) {
|
||||
// 满足所有指定条件
|
||||
$data = is_string($val[1]) ? explode(',', $val[1]) : $val[1];
|
||||
$query[$key] = ['$all' => $data];
|
||||
} elseif ('between' == $con) {
|
||||
// BETWEEN运算
|
||||
$data = is_string($val[1]) ? explode(',', $val[1]) : $val[1];
|
||||
$query[$key] = ['$gte' => $data[0], '$lte' => $data[1]];
|
||||
} elseif ('not between' == $con) {
|
||||
$data = is_string($val[1]) ? explode(',', $val[1]) : $val[1];
|
||||
$query[$key] = ['$lt' => $data[0], '$gt' => $data[1]];
|
||||
} elseif ('exp' == $con) {
|
||||
// 表达式查询
|
||||
$query['$where'] = new \MongoCode($val[1]);
|
||||
} elseif ('exists' == $con) {
|
||||
// 字段是否存在
|
||||
$query[$key] = ['$exists' => (bool) $val[1]];
|
||||
} elseif ('size' == $con) {
|
||||
// 限制属性大小
|
||||
$query[$key] = ['$size' => intval($val[1])];
|
||||
} elseif ('type' == $con) {
|
||||
// 限制字段类型 1 浮点型 2 字符型 3 对象或者MongoDBRef 5 MongoBinData 7 MongoId 8 布尔型 9 MongoDate 10 NULL 15 MongoCode 16 32位整型 17 MongoTimestamp 18 MongoInt64 如果是数组的话判断元素的类型
|
||||
$query[$key] = ['$type' => intval($val[1])];
|
||||
} else {
|
||||
$query[$key] = $val;
|
||||
}
|
||||
return $query;
|
||||
}
|
||||
}
|
||||
$query[$key] = $val;
|
||||
$query[$key] = $val;
|
||||
return $query;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,12 +10,14 @@
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\db\driver;
|
||||
|
||||
use think\db\Driver;
|
||||
|
||||
/**
|
||||
* mysql数据库驱动
|
||||
* mysql数据库驱动
|
||||
*/
|
||||
class Mysql extends Driver{
|
||||
class Mysql extends Driver
|
||||
{
|
||||
|
||||
/**
|
||||
* 解析pdo连接的dsn信息
|
||||
@@ -23,15 +25,16 @@ class Mysql extends Driver{
|
||||
* @param array $config 连接信息
|
||||
* @return string
|
||||
*/
|
||||
protected function parseDsn($config){
|
||||
$dsn = 'mysql:dbname='.$config['database'].';host='.$config['hostname'];
|
||||
if(!empty($config['hostport'])) {
|
||||
$dsn .= ';port='.$config['hostport'];
|
||||
}elseif(!empty($config['socket'])){
|
||||
$dsn .= ';unix_socket='.$config['socket'];
|
||||
protected function parseDsn($config)
|
||||
{
|
||||
$dsn = 'mysql:dbname=' . $config['database'] . ';host=' . $config['hostname'];
|
||||
if (!empty($config['hostport'])) {
|
||||
$dsn .= ';port=' . $config['hostport'];
|
||||
} elseif (!empty($config['socket'])) {
|
||||
$dsn .= ';unix_socket=' . $config['socket'];
|
||||
}
|
||||
if(!empty($config['charset'])){
|
||||
$dsn .= ';charset='.$config['charset'];
|
||||
if (!empty($config['charset'])) {
|
||||
$dsn .= ';charset=' . $config['charset'];
|
||||
}
|
||||
return $dsn;
|
||||
}
|
||||
@@ -40,18 +43,19 @@ class Mysql extends Driver{
|
||||
* 取得数据表的字段信息
|
||||
* @access public
|
||||
*/
|
||||
public function getFields($tableName) {
|
||||
public function getFields($tableName)
|
||||
{
|
||||
$this->initConnect(true);
|
||||
list($tableName) = explode(' ', $tableName);
|
||||
$sql = 'SHOW COLUMNS FROM `'.$tableName.'`';
|
||||
$result = $this->query($sql);
|
||||
$info = [];
|
||||
if($result) {
|
||||
$sql = 'SHOW COLUMNS FROM `' . $tableName . '`';
|
||||
$result = $this->query($sql);
|
||||
$info = [];
|
||||
if ($result) {
|
||||
foreach ($result as $key => $val) {
|
||||
$info[$val['field']] = [
|
||||
'name' => $val['field'],
|
||||
'type' => $val['type'],
|
||||
'notnull' => (bool) ($val['null'] === ''), // not null is empty, null is yes
|
||||
'notnull' => (bool) ('' === $val['null']), // not null is empty, null is yes
|
||||
'default' => $val['default'],
|
||||
'primary' => (strtolower($val['key']) == 'pri'),
|
||||
'autoinc' => (strtolower($val['extra']) == 'auto_increment'),
|
||||
@@ -65,10 +69,11 @@ class Mysql extends Driver{
|
||||
* 取得数据库的表信息
|
||||
* @access public
|
||||
*/
|
||||
public function getTables($dbName='') {
|
||||
$sql = !empty($dbName)?'SHOW TABLES FROM '.$dbName:'SHOW TABLES ';
|
||||
public function getTables($dbName = '')
|
||||
{
|
||||
$sql = !empty($dbName) ? 'SHOW TABLES FROM ' . $dbName : 'SHOW TABLES ';
|
||||
$result = $this->query($sql);
|
||||
$info = [];
|
||||
$info = [];
|
||||
foreach ($result as $key => $val) {
|
||||
$info[$key] = current($val);
|
||||
}
|
||||
@@ -81,12 +86,13 @@ class Mysql extends Driver{
|
||||
* @param string $key
|
||||
* @return string
|
||||
*/
|
||||
protected function parseKey(&$key) {
|
||||
$key = trim($key);
|
||||
if(!preg_match('/[,\'\"\*\(\)`.\s]/',$key)) {
|
||||
$key = '`'.$key.'`';
|
||||
protected function parseKey(&$key)
|
||||
{
|
||||
$key = trim($key);
|
||||
if (!preg_match('/[,\'\"\*\(\)`.\s]/', $key)) {
|
||||
$key = '`' . $key . '`';
|
||||
}
|
||||
return $key;
|
||||
return $key;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -10,15 +10,17 @@
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\db\driver;
|
||||
|
||||
use think\db\Driver;
|
||||
|
||||
/**
|
||||
* Oracle数据库驱动
|
||||
*/
|
||||
class Oracle extends Driver{
|
||||
class Oracle extends Driver
|
||||
{
|
||||
|
||||
private $table = '';
|
||||
protected $selectSql = 'SELECT * FROM (SELECT thinkphp.*, rownum AS numrow FROM (SELECT %DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%) thinkphp ) %LIMIT%%COMMENT%';
|
||||
private $table = '';
|
||||
protected $selectSql = 'SELECT * FROM (SELECT thinkphp.*, rownum AS numrow FROM (SELECT %DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%) thinkphp ) %LIMIT%%COMMENT%';
|
||||
|
||||
/**
|
||||
* 解析pdo连接的dsn信息
|
||||
@@ -26,10 +28,11 @@ class Oracle extends Driver{
|
||||
* @param array $config 连接信息
|
||||
* @return string
|
||||
*/
|
||||
protected function parseDsn($config){
|
||||
$dsn = 'oci:dbname='.$config['database'];
|
||||
if(!empty($config['charset'])) {
|
||||
$dsn .= ';charset='.$config['charset'];
|
||||
protected function parseDsn($config)
|
||||
{
|
||||
$dsn = 'oci:dbname=' . $config['database'];
|
||||
if (!empty($config['charset'])) {
|
||||
$dsn .= ';charset=' . $config['charset'];
|
||||
}
|
||||
return $dsn;
|
||||
}
|
||||
@@ -40,42 +43,49 @@ class Oracle extends Driver{
|
||||
* @param string $str sql指令
|
||||
* @return integer
|
||||
*/
|
||||
public function execute($str,$bind=[]) {
|
||||
public function execute($str, $bind = [])
|
||||
{
|
||||
$this->initConnect(true);
|
||||
if ( !$this->_linkID ) return false;
|
||||
if (!$this->_linkID) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->queryStr = $str;
|
||||
if(!empty($bind)){
|
||||
$this->queryStr .= '[ '.print_r($bind,true).' ]';
|
||||
}
|
||||
if (!empty($bind)) {
|
||||
$this->queryStr .= '[ ' . print_r($bind, true) . ' ]';
|
||||
}
|
||||
$flag = false;
|
||||
if(preg_match("/^\s*(INSERT\s+INTO)\s+(\w+)\s+/i", $str, $match)) {
|
||||
$this->table = C("DB_SEQUENCE_PREFIX").str_ireplace(C("DB_PREFIX"), "", $match[2]);
|
||||
$flag = (boolean)$this->query("SELECT * FROM user_sequences WHERE sequence_name='" . strtoupper($this->table) . "'");
|
||||
if (preg_match("/^\s*(INSERT\s+INTO)\s+(\w+)\s+/i", $str, $match)) {
|
||||
$this->table = C("DB_SEQUENCE_PREFIX") . str_ireplace(C("DB_PREFIX"), "", $match[2]);
|
||||
$flag = (boolean) $this->query("SELECT * FROM user_sequences WHERE sequence_name='" . strtoupper($this->table) . "'");
|
||||
}
|
||||
//释放前次的查询结果
|
||||
if ( !empty($this->PDOStatement) ) $this->free();
|
||||
if (!empty($this->PDOStatement)) {
|
||||
$this->free();
|
||||
}
|
||||
|
||||
$this->executeTimes++;
|
||||
// 记录开始执行时间
|
||||
$this->debug(true);
|
||||
$this->PDOStatement = $this->_linkID->prepare($str);
|
||||
if(false === $this->PDOStatement) {
|
||||
$this->PDOStatement = $this->_linkID->prepare($str);
|
||||
if (false === $this->PDOStatement) {
|
||||
$this->error();
|
||||
return false;
|
||||
}
|
||||
try{
|
||||
$result = $this->PDOStatement->execute($bind);
|
||||
try {
|
||||
$result = $this->PDOStatement->execute($bind);
|
||||
$this->debug(false);
|
||||
if ( false === $result) {
|
||||
if (false === $result) {
|
||||
$this->error();
|
||||
return false;
|
||||
} else {
|
||||
$this->numRows = $this->PDOStatement->rowCount();
|
||||
if($flag || preg_match("/^\s*(INSERT\s+INTO|REPLACE\s+INTO)\s+/i", $str)) {
|
||||
if ($flag || preg_match("/^\s*(INSERT\s+INTO|REPLACE\s+INTO)\s+/i", $str)) {
|
||||
$this->lastInsID = $this->_linkID->lastInsertId();
|
||||
}
|
||||
return $this->numRows;
|
||||
}
|
||||
}catch (\PDOException $e) {
|
||||
} catch (\PDOException $e) {
|
||||
$this->error();
|
||||
return false;
|
||||
}
|
||||
@@ -85,14 +95,15 @@ class Oracle extends Driver{
|
||||
* 取得数据表的字段信息
|
||||
* @access public
|
||||
*/
|
||||
public function getFields($tableName) {
|
||||
public function getFields($tableName)
|
||||
{
|
||||
list($tableName) = explode(' ', $tableName);
|
||||
$result = $this->query("select a.column_name,data_type,decode(nullable,'Y',0,1) notnull,data_default,decode(a.column_name,b.column_name,1,0) pk "
|
||||
."from user_tab_columns a,(select column_name from user_constraints c,user_cons_columns col "
|
||||
."where c.constraint_name=col.constraint_name and c.constraint_type='P'and c.table_name='".strtoupper($tableName)
|
||||
."') b where table_name='".strtoupper($tableName)."' and a.column_name=b.column_name(+)");
|
||||
$info = [];
|
||||
if($result) {
|
||||
$result = $this->query("select a.column_name,data_type,decode(nullable,'Y',0,1) notnull,data_default,decode(a.column_name,b.column_name,1,0) pk "
|
||||
. "from user_tab_columns a,(select column_name from user_constraints c,user_cons_columns col "
|
||||
. "where c.constraint_name=col.constraint_name and c.constraint_type='P'and c.table_name='" . strtoupper($tableName)
|
||||
. "') b where table_name='" . strtoupper($tableName) . "' and a.column_name=b.column_name(+)");
|
||||
$info = [];
|
||||
if ($result) {
|
||||
foreach ($result as $key => $val) {
|
||||
$info[strtolower($val['column_name'])] = [
|
||||
'name' => strtolower($val['column_name']),
|
||||
@@ -111,9 +122,10 @@ class Oracle extends Driver{
|
||||
* 取得数据库的表信息(暂时实现取得用户表信息)
|
||||
* @access public
|
||||
*/
|
||||
public function getTables($dbName='') {
|
||||
public function getTables($dbName = '')
|
||||
{
|
||||
$result = $this->query("select table_name from user_tables");
|
||||
$info = [];
|
||||
$info = [];
|
||||
foreach ($result as $key => $val) {
|
||||
$info[$key] = current($val);
|
||||
}
|
||||
@@ -126,7 +138,8 @@ class Oracle extends Driver{
|
||||
* @param string $str SQL指令
|
||||
* @return string
|
||||
*/
|
||||
public function escapeString($str) {
|
||||
public function escapeString($str)
|
||||
{
|
||||
return str_ireplace("'", "''", $str);
|
||||
}
|
||||
|
||||
@@ -135,16 +148,19 @@ class Oracle extends Driver{
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function parseLimit($limit) {
|
||||
$limitStr = '';
|
||||
if(!empty($limit)) {
|
||||
$limit = explode(',',$limit);
|
||||
if(count($limit)>1)
|
||||
$limitStr = "(numrow>" . $limit[0] . ") AND (numrow<=" . ($limit[0]+$limit[1]) . ")";
|
||||
else
|
||||
$limitStr = "(numrow>0 AND numrow<=".$limit[0].")";
|
||||
public function parseLimit($limit)
|
||||
{
|
||||
$limitStr = '';
|
||||
if (!empty($limit)) {
|
||||
$limit = explode(',', $limit);
|
||||
if (count($limit) > 1) {
|
||||
$limitStr = "(numrow>" . $limit[0] . ") AND (numrow<=" . ($limit[0] + $limit[1]) . ")";
|
||||
} else {
|
||||
$limitStr = "(numrow>0 AND numrow<=" . $limit[0] . ")";
|
||||
}
|
||||
|
||||
}
|
||||
return $limitStr?' WHERE '.$limitStr:'';
|
||||
return $limitStr ? ' WHERE ' . $limitStr : '';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -152,8 +168,12 @@ class Oracle extends Driver{
|
||||
* @access protected
|
||||
* @return string
|
||||
*/
|
||||
protected function parseLock($lock=false) {
|
||||
if(!$lock) return '';
|
||||
protected function parseLock($lock = false)
|
||||
{
|
||||
if (!$lock) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return ' FOR UPDATE NOWAIT ';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,12 +10,14 @@
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\db\driver;
|
||||
|
||||
use think\db\Driver;
|
||||
|
||||
/**
|
||||
* Pgsql数据库驱动
|
||||
*/
|
||||
class Pgsql extends Driver{
|
||||
class Pgsql extends Driver
|
||||
{
|
||||
|
||||
/**
|
||||
* 解析pdo连接的dsn信息
|
||||
@@ -23,10 +25,11 @@ class Pgsql extends Driver{
|
||||
* @param array $config 连接信息
|
||||
* @return string
|
||||
*/
|
||||
protected function parseDsn($config){
|
||||
$dsn = 'pgsql:dbname='.$config['database'].';host='.$config['hostname'];
|
||||
if(!empty($config['hostport'])) {
|
||||
$dsn .= ';port='.$config['hostport'];
|
||||
protected function parseDsn($config)
|
||||
{
|
||||
$dsn = 'pgsql:dbname=' . $config['database'] . ';host=' . $config['hostname'];
|
||||
if (!empty($config['hostport'])) {
|
||||
$dsn .= ';port=' . $config['hostport'];
|
||||
}
|
||||
return $dsn;
|
||||
}
|
||||
@@ -36,16 +39,17 @@ class Pgsql extends Driver{
|
||||
* @access public
|
||||
* @return array
|
||||
*/
|
||||
public function getFields($tableName) {
|
||||
public function getFields($tableName)
|
||||
{
|
||||
list($tableName) = explode(' ', $tableName);
|
||||
$result = $this->query('select fields_name as "field",fields_type as "type",fields_not_null as "null",fields_key_name as "key",fields_default as "default",fields_default as "extra" from table_msg('.$tableName.');');
|
||||
$info = [];
|
||||
if($result){
|
||||
$result = $this->query('select fields_name as "field",fields_type as "type",fields_not_null as "null",fields_key_name as "key",fields_default as "default",fields_default as "extra" from table_msg(' . $tableName . ');');
|
||||
$info = [];
|
||||
if ($result) {
|
||||
foreach ($result as $key => $val) {
|
||||
$info[$val['field']] = [
|
||||
'name' => $val['field'],
|
||||
'type' => $val['type'],
|
||||
'notnull' => (bool) ($val['null'] === ''), // not null is empty, null is yes
|
||||
'notnull' => (bool) ('' === $val['null']), // not null is empty, null is yes
|
||||
'default' => $val['default'],
|
||||
'primary' => (strtolower($val['key']) == 'pri'),
|
||||
'autoinc' => (strtolower($val['extra']) == 'auto_increment'),
|
||||
@@ -60,9 +64,10 @@ class Pgsql extends Driver{
|
||||
* @access public
|
||||
* @return array
|
||||
*/
|
||||
public function getTables($dbName='') {
|
||||
$result = $this->query("select tablename as Tables_in_test from pg_tables where schemaname ='public'");
|
||||
$info = [];
|
||||
public function getTables($dbName = '')
|
||||
{
|
||||
$result = $this->query("select tablename as Tables_in_test from pg_tables where schemaname ='public'");
|
||||
$info = [];
|
||||
foreach ($result as $key => $val) {
|
||||
$info[$key] = current($val);
|
||||
}
|
||||
@@ -75,14 +80,15 @@ class Pgsql extends Driver{
|
||||
* @param mixed $lmit
|
||||
* @return string
|
||||
*/
|
||||
public function parseLimit($limit) {
|
||||
$limitStr = '';
|
||||
if(!empty($limit)) {
|
||||
$limit = explode(',',$limit);
|
||||
if(count($limit)>1) {
|
||||
$limitStr .= ' LIMIT '.$limit[1].' OFFSET '.$limit[0].' ';
|
||||
}else{
|
||||
$limitStr .= ' LIMIT '.$limit[0].' ';
|
||||
public function parseLimit($limit)
|
||||
{
|
||||
$limitStr = '';
|
||||
if (!empty($limit)) {
|
||||
$limit = explode(',', $limit);
|
||||
if (count($limit) > 1) {
|
||||
$limitStr .= ' LIMIT ' . $limit[1] . ' OFFSET ' . $limit[0] . ' ';
|
||||
} else {
|
||||
$limitStr .= ' LIMIT ' . $limit[0] . ' ';
|
||||
}
|
||||
}
|
||||
return $limitStr;
|
||||
|
||||
@@ -10,12 +10,14 @@
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\db\driver;
|
||||
|
||||
use think\db\Driver;
|
||||
|
||||
/**
|
||||
* Sqlite数据库驱动
|
||||
*/
|
||||
class Sqlite extends Driver {
|
||||
class Sqlite extends Driver
|
||||
{
|
||||
|
||||
/**
|
||||
* 解析pdo连接的dsn信息
|
||||
@@ -23,8 +25,9 @@ class Sqlite extends Driver {
|
||||
* @param array $config 连接信息
|
||||
* @return string
|
||||
*/
|
||||
protected function parseDsn($config){
|
||||
$dsn = 'sqlite:'.$config['database'];
|
||||
protected function parseDsn($config)
|
||||
{
|
||||
$dsn = 'sqlite:' . $config['database'];
|
||||
return $dsn;
|
||||
}
|
||||
|
||||
@@ -33,16 +36,17 @@ class Sqlite extends Driver {
|
||||
* @access public
|
||||
* @return array
|
||||
*/
|
||||
public function getFields($tableName) {
|
||||
public function getFields($tableName)
|
||||
{
|
||||
list($tableName) = explode(' ', $tableName);
|
||||
$result = $this->query('PRAGMA table_info( '.$tableName.' )');
|
||||
$info = [];
|
||||
if($result){
|
||||
$result = $this->query('PRAGMA table_info( ' . $tableName . ' )');
|
||||
$info = [];
|
||||
if ($result) {
|
||||
foreach ($result as $key => $val) {
|
||||
$info[$val['field']] = [
|
||||
'name' => $val['field'],
|
||||
'type' => $val['type'],
|
||||
'notnull' => (bool) ($val['null'] === ''), // not null is empty, null is yes
|
||||
'notnull' => (bool) ('' === $val['null']), // not null is empty, null is yes
|
||||
'default' => $val['default'],
|
||||
'primary' => (strtolower($val['dey']) == 'pri'),
|
||||
'autoinc' => (strtolower($val['extra']) == 'auto_increment'),
|
||||
@@ -57,11 +61,12 @@ class Sqlite extends Driver {
|
||||
* @access public
|
||||
* @return array
|
||||
*/
|
||||
public function getTables($dbName='') {
|
||||
$result = $this->query("SELECT name FROM sqlite_master WHERE type='table' "
|
||||
. "UNION ALL SELECT name FROM sqlite_temp_master "
|
||||
. "WHERE type='table' ORDER BY name");
|
||||
$info = [];
|
||||
public function getTables($dbName = '')
|
||||
{
|
||||
$result = $this->query("SELECT name FROM sqlite_master WHERE type='table' "
|
||||
. "UNION ALL SELECT name FROM sqlite_temp_master "
|
||||
. "WHERE type='table' ORDER BY name");
|
||||
$info = [];
|
||||
foreach ($result as $key => $val) {
|
||||
$info[$key] = current($val);
|
||||
}
|
||||
@@ -74,7 +79,8 @@ class Sqlite extends Driver {
|
||||
* @param string $str SQL指令
|
||||
* @return string
|
||||
*/
|
||||
public function escapeString($str) {
|
||||
public function escapeString($str)
|
||||
{
|
||||
return str_ireplace("'", "''", $str);
|
||||
}
|
||||
|
||||
@@ -83,14 +89,15 @@ class Sqlite extends Driver {
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function parseLimit($limit) {
|
||||
$limitStr = '';
|
||||
if(!empty($limit)) {
|
||||
$limit = explode(',',$limit);
|
||||
if(count($limit)>1) {
|
||||
$limitStr .= ' LIMIT '.$limit[1].' OFFSET '.$limit[0].' ';
|
||||
}else{
|
||||
$limitStr .= ' LIMIT '.$limit[0].' ';
|
||||
public function parseLimit($limit)
|
||||
{
|
||||
$limitStr = '';
|
||||
if (!empty($limit)) {
|
||||
$limit = explode(',', $limit);
|
||||
if (count($limit) > 1) {
|
||||
$limitStr .= ' LIMIT ' . $limit[1] . ' OFFSET ' . $limit[0] . ' ';
|
||||
} else {
|
||||
$limitStr .= ' LIMIT ' . $limit[0] . ' ';
|
||||
}
|
||||
}
|
||||
return $limitStr;
|
||||
|
||||
@@ -10,20 +10,22 @@
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\db\driver;
|
||||
use think\db\Driver;
|
||||
|
||||
use PDO;
|
||||
use think\db\Driver;
|
||||
|
||||
/**
|
||||
* Sqlsrv数据库驱动
|
||||
*/
|
||||
class Sqlsrv extends Driver{
|
||||
protected $selectSql = 'SELECT T1.* FROM (SELECT thinkphp.*, ROW_NUMBER() OVER (%ORDER%) AS ROW_NUMBER FROM (SELECT %DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%) AS thinkphp) AS T1 %LIMIT%%COMMENT%';
|
||||
class Sqlsrv extends Driver
|
||||
{
|
||||
protected $selectSql = 'SELECT T1.* FROM (SELECT thinkphp.*, ROW_NUMBER() OVER (%ORDER%) AS ROW_NUMBER FROM (SELECT %DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%) AS thinkphp) AS T1 %LIMIT%%COMMENT%';
|
||||
// PDO连接参数
|
||||
protected $options = [
|
||||
PDO::ATTR_CASE => PDO::CASE_LOWER,
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||
PDO::ATTR_STRINGIFY_FETCHES => false,
|
||||
PDO::SQLSRV_ATTR_ENCODING => PDO::SQLSRV_ENCODING_UTF8,
|
||||
PDO::ATTR_CASE => PDO::CASE_LOWER,
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||
PDO::ATTR_STRINGIFY_FETCHES => false,
|
||||
PDO::SQLSRV_ATTR_ENCODING => PDO::SQLSRV_ENCODING_UTF8,
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -32,10 +34,11 @@ class Sqlsrv extends Driver{
|
||||
* @param array $config 连接信息
|
||||
* @return string
|
||||
*/
|
||||
protected function parseDsn($config){
|
||||
$dsn = 'sqlsrv:dbname='.$config['database'].';Server='.$config['hostname'];
|
||||
if(!empty($config['hostport'])) {
|
||||
$dsn .= ','.$config['hostport'];
|
||||
protected function parseDsn($config)
|
||||
{
|
||||
$dsn = 'sqlsrv:dbname=' . $config['database'] . ';Server=' . $config['hostname'];
|
||||
if (!empty($config['hostport'])) {
|
||||
$dsn .= ',' . $config['hostport'];
|
||||
}
|
||||
return $dsn;
|
||||
}
|
||||
@@ -45,22 +48,23 @@ class Sqlsrv extends Driver{
|
||||
* @access public
|
||||
* @return array
|
||||
*/
|
||||
public function getFields($tableName) {
|
||||
public function getFields($tableName)
|
||||
{
|
||||
list($tableName) = explode(' ', $tableName);
|
||||
$result = $this->query("SELECT column_name, data_type, column_default, is_nullable
|
||||
$result = $this->query("SELECT column_name, data_type, column_default, is_nullable
|
||||
FROM information_schema.tables AS t
|
||||
JOIN information_schema.columns AS c
|
||||
ON t.table_catalog = c.table_catalog
|
||||
AND t.table_schema = c.table_schema
|
||||
AND t.table_name = c.table_name
|
||||
WHERE t.table_name = '$tableName'");
|
||||
$info = [];
|
||||
if($result) {
|
||||
$info = [];
|
||||
if ($result) {
|
||||
foreach ($result as $key => $val) {
|
||||
$info[$val['column_name']] = [
|
||||
'name' => $val['column_name'],
|
||||
'type' => $val['data_type'],
|
||||
'notnull' => (bool) ($val['is_nullable'] === ''), // not null is empty, null is yes
|
||||
'notnull' => (bool) ('' === $val['is_nullable']), // not null is empty, null is yes
|
||||
'default' => $val['column_default'],
|
||||
'primary' => false,
|
||||
'autoinc' => false,
|
||||
@@ -75,26 +79,28 @@ class Sqlsrv extends Driver{
|
||||
* @access public
|
||||
* @return array
|
||||
*/
|
||||
public function getTables($dbName='') {
|
||||
$result = $this->query("SELECT TABLE_NAME
|
||||
public function getTables($dbName = '')
|
||||
{
|
||||
$result = $this->query("SELECT TABLE_NAME
|
||||
FROM INFORMATION_SCHEMA.TABLES
|
||||
WHERE TABLE_TYPE = 'BASE TABLE'
|
||||
");
|
||||
$info = [];
|
||||
$info = [];
|
||||
foreach ($result as $key => $val) {
|
||||
$info[$key] = current($val);
|
||||
}
|
||||
return $info;
|
||||
}
|
||||
|
||||
/**
|
||||
/**
|
||||
* order分析
|
||||
* @access protected
|
||||
* @param mixed $order
|
||||
* @return string
|
||||
*/
|
||||
protected function parseOrder($order) {
|
||||
return !empty($order)? ' ORDER BY '.$order:' ORDER BY rand()';
|
||||
protected function parseOrder($order)
|
||||
{
|
||||
return !empty($order) ? ' ORDER BY ' . $order : ' ORDER BY rand()';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -103,12 +109,13 @@ class Sqlsrv extends Driver{
|
||||
* @param string $key
|
||||
* @return string
|
||||
*/
|
||||
protected function parseKey(&$key) {
|
||||
$key = trim($key);
|
||||
if(!preg_match('/[,\'\"\*\(\)\[.\s]/',$key)) {
|
||||
$key = '['.$key.']';
|
||||
protected function parseKey(&$key)
|
||||
{
|
||||
$key = trim($key);
|
||||
if (!preg_match('/[,\'\"\*\(\)\[.\s]/', $key)) {
|
||||
$key = '[' . $key . ']';
|
||||
}
|
||||
return $key;
|
||||
return $key;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -117,14 +124,20 @@ class Sqlsrv extends Driver{
|
||||
* @param mixed $limit
|
||||
* @return string
|
||||
*/
|
||||
public function parseLimit($limit) {
|
||||
if(empty($limit)) return '';
|
||||
$limit = explode(',',$limit);
|
||||
if(count($limit)>1)
|
||||
$limitStr = '(T1.ROW_NUMBER BETWEEN '.$limit[0].' + 1 AND '.$limit[0].' + '.$limit[1].')';
|
||||
else
|
||||
$limitStr = '(T1.ROW_NUMBER BETWEEN 1 AND '.$limit[0].")";
|
||||
return 'WHERE '.$limitStr;
|
||||
public function parseLimit($limit)
|
||||
{
|
||||
if (empty($limit)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$limit = explode(',', $limit);
|
||||
if (count($limit) > 1) {
|
||||
$limitStr = '(T1.ROW_NUMBER BETWEEN ' . $limit[0] . ' + 1 AND ' . $limit[0] . ' + ' . $limit[1] . ')';
|
||||
} else {
|
||||
$limitStr = '(T1.ROW_NUMBER BETWEEN 1 AND ' . $limit[0] . ")";
|
||||
}
|
||||
|
||||
return 'WHERE ' . $limitStr;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -134,15 +147,16 @@ class Sqlsrv extends Driver{
|
||||
* @param array $options 表达式
|
||||
* @return false | integer
|
||||
*/
|
||||
public function update($data,$options) {
|
||||
$this->model = $options['model'];
|
||||
$sql = 'UPDATE '
|
||||
.$this->parseTable($options['table'])
|
||||
.$this->parseSet($data)
|
||||
.$this->parseWhere(!empty($options['where'])?$options['where']:'')
|
||||
.$this->parseLock(isset($options['lock'])?$options['lock']:false)
|
||||
.$this->parseComment(!empty($options['comment'])?$options['comment']:'');
|
||||
return $this->execute($sql,$this->parseBind(!empty($options['bind'])?$options['bind']:[]));
|
||||
public function update($data, $options)
|
||||
{
|
||||
$this->model = $options['model'];
|
||||
$sql = 'UPDATE '
|
||||
. $this->parseTable($options['table'])
|
||||
. $this->parseSet($data)
|
||||
. $this->parseWhere(!empty($options['where']) ? $options['where'] : '')
|
||||
. $this->parseLock(isset($options['lock']) ? $options['lock'] : false)
|
||||
. $this->parseComment(!empty($options['comment']) ? $options['comment'] : '');
|
||||
return $this->execute($sql, $this->parseBind(!empty($options['bind']) ? $options['bind'] : []));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -151,14 +165,15 @@ class Sqlsrv extends Driver{
|
||||
* @param array $options 表达式
|
||||
* @return false | integer
|
||||
*/
|
||||
public function delete($options=[]) {
|
||||
$this->model = $options['model'];
|
||||
$sql = 'DELETE FROM '
|
||||
.$this->parseTable($options['table'])
|
||||
.$this->parseWhere(!empty($options['where'])?$options['where']:'')
|
||||
.$this->parseLock(isset($options['lock'])?$options['lock']:false)
|
||||
.$this->parseComment(!empty($options['comment'])?$options['comment']:'');
|
||||
return $this->execute($sql,$this->parseBind(!empty($options['bind'])?$options['bind']:[]));
|
||||
public function delete($options = [])
|
||||
{
|
||||
$this->model = $options['model'];
|
||||
$sql = 'DELETE FROM '
|
||||
. $this->parseTable($options['table'])
|
||||
. $this->parseWhere(!empty($options['where']) ? $options['where'] : '')
|
||||
. $this->parseLock(isset($options['lock']) ? $options['lock'] : false)
|
||||
. $this->parseComment(!empty($options['comment']) ? $options['comment'] : '');
|
||||
return $this->execute($sql, $this->parseBind(!empty($options['bind']) ? $options['bind'] : []));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,64 +10,66 @@
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\db;
|
||||
|
||||
use PDO;
|
||||
use think\Config;
|
||||
use think\Debug;
|
||||
use think\Log;
|
||||
use think\Exception;
|
||||
use PDO;
|
||||
use think\Log;
|
||||
|
||||
class Lite {
|
||||
class Lite
|
||||
{
|
||||
// PDO操作实例
|
||||
protected $PDOStatement = null;
|
||||
// 当前操作所属的模型名
|
||||
protected $model = '_think_';
|
||||
protected $model = '_think_';
|
||||
// 当前SQL指令
|
||||
protected $queryStr = '';
|
||||
protected $modelSql = [];
|
||||
protected $queryStr = '';
|
||||
protected $modelSql = [];
|
||||
// 最后插入ID
|
||||
protected $lastInsID = null;
|
||||
protected $lastInsID = null;
|
||||
// 返回或者影响记录数
|
||||
protected $numRows = 0;
|
||||
protected $numRows = 0;
|
||||
// 事务指令数
|
||||
protected $transTimes = 0;
|
||||
// 错误信息
|
||||
protected $error = '';
|
||||
protected $error = '';
|
||||
// 数据库连接ID 支持多个连接
|
||||
protected $linkID = [];
|
||||
protected $linkID = [];
|
||||
// 当前连接ID
|
||||
protected $_linkID = null;
|
||||
protected $_linkID = null;
|
||||
// 数据库连接参数配置
|
||||
protected $config = [
|
||||
'type' => '', // 数据库类型
|
||||
'hostname' => '127.0.0.1', // 服务器地址
|
||||
'database' => '', // 数据库名
|
||||
'username' => '', // 用户名
|
||||
'password' => '', // 密码
|
||||
'hostport' => '', // 端口
|
||||
'dsn' => '', //
|
||||
'params' => [], // 数据库连接参数
|
||||
'charset' => 'utf8', // 数据库编码默认采用utf8
|
||||
'prefix' => '', // 数据库表前缀
|
||||
'debug' => false, // 数据库调试模式
|
||||
'deploy' => 0, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
|
||||
'rw_separate' => false, // 数据库读写是否分离 主从式有效
|
||||
'master_num' => 1, // 读写分离后 主服务器数量
|
||||
'slave_no' => '', // 指定从服务器序号
|
||||
protected $config = [
|
||||
'type' => '', // 数据库类型
|
||||
'hostname' => '127.0.0.1', // 服务器地址
|
||||
'database' => '', // 数据库名
|
||||
'username' => '', // 用户名
|
||||
'password' => '', // 密码
|
||||
'hostport' => '', // 端口
|
||||
'dsn' => '', //
|
||||
'params' => [], // 数据库连接参数
|
||||
'charset' => 'utf8', // 数据库编码默认采用utf8
|
||||
'prefix' => '', // 数据库表前缀
|
||||
'debug' => false, // 数据库调试模式
|
||||
'deploy' => 0, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
|
||||
'rw_separate' => false, // 数据库读写是否分离 主从式有效
|
||||
'master_num' => 1, // 读写分离后 主服务器数量
|
||||
'slave_no' => '', // 指定从服务器序号
|
||||
];
|
||||
// 数据库表达式
|
||||
protected $comparison = ['eq'=>'=','neq'=>'<>','gt'=>'>','egt'=>'>=','lt'=>'<','elt'=>'<=','notlike'=>'NOT LIKE','like'=>'LIKE','in'=>'IN','notin'=>'NOT IN'];
|
||||
protected $comparison = ['eq' => '=', 'neq' => '<>', 'gt' => '>', 'egt' => '>=', 'lt' => '<', 'elt' => '<=', 'notlike' => 'NOT LIKE', 'like' => 'LIKE', 'in' => 'IN', 'notin' => 'NOT IN'];
|
||||
// 查询表达式
|
||||
protected $selectSql = 'SELECT%DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT% %UNION%%COMMENT%';
|
||||
protected $selectSql = 'SELECT%DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT% %UNION%%COMMENT%';
|
||||
// 查询次数
|
||||
protected $queryTimes = 0;
|
||||
protected $queryTimes = 0;
|
||||
// 执行次数
|
||||
protected $executeTimes = 0;
|
||||
protected $executeTimes = 0;
|
||||
// PDO连接参数
|
||||
protected $options = [
|
||||
PDO::ATTR_CASE => PDO::CASE_LOWER,
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||
PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,
|
||||
PDO::ATTR_STRINGIFY_FETCHES => false,
|
||||
PDO::ATTR_CASE => PDO::CASE_LOWER,
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||
PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,
|
||||
PDO::ATTR_STRINGIFY_FETCHES => false,
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -75,10 +77,11 @@ class Lite {
|
||||
* @access public
|
||||
* @param array $config 数据库配置数组
|
||||
*/
|
||||
public function __construct($config=''){
|
||||
if(!empty($config)) {
|
||||
$this->config = array_merge($this->config,$config);
|
||||
$this->config['params'] = $this->options+$this->config['params'];
|
||||
public function __construct($config = '')
|
||||
{
|
||||
if (!empty($config)) {
|
||||
$this->config = array_merge($this->config, $config);
|
||||
$this->config['params'] = $this->options + $this->config['params'];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,15 +89,19 @@ class Lite {
|
||||
* 连接数据库方法
|
||||
* @access public
|
||||
*/
|
||||
public function connect($config='',$linkNum=0) {
|
||||
if ( !isset($this->linkID[$linkNum]) ) {
|
||||
if(empty($config)) $config = $this->config;
|
||||
try{
|
||||
if(empty($config['dsn'])) {
|
||||
public function connect($config = '', $linkNum = 0)
|
||||
{
|
||||
if (!isset($this->linkID[$linkNum])) {
|
||||
if (empty($config)) {
|
||||
$config = $this->config;
|
||||
}
|
||||
|
||||
try {
|
||||
if (empty($config['dsn'])) {
|
||||
throw new Exception('Think/Db/Lite 必须设置 dsn参数');
|
||||
}
|
||||
$this->linkID[$linkNum] = new PDO( $config['dsn'], $config['username'], $config['password'],$config['params']);
|
||||
}catch (\PDOException $e) {
|
||||
$this->linkID[$linkNum] = new PDO($config['dsn'], $config['username'], $config['password'], $config['params']);
|
||||
} catch (\PDOException $e) {
|
||||
throw new Exception($e->getMessage());
|
||||
}
|
||||
}
|
||||
@@ -105,7 +112,8 @@ class Lite {
|
||||
* 释放查询结果
|
||||
* @access public
|
||||
*/
|
||||
public function free() {
|
||||
public function free()
|
||||
{
|
||||
$this->PDOStatement = null;
|
||||
}
|
||||
|
||||
@@ -116,41 +124,48 @@ class Lite {
|
||||
* @param array $bind 参数绑定
|
||||
* @return mixed
|
||||
*/
|
||||
public function query($str,$bind=[]) {
|
||||
public function query($str, $bind = [])
|
||||
{
|
||||
$this->initConnect(false);
|
||||
if ( !$this->_linkID ) return false;
|
||||
$this->queryStr = $str;
|
||||
if(!empty($bind)){
|
||||
$this->queryStr .= '[ '.print_r($bind,true).' ]';
|
||||
if (!$this->_linkID) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->queryStr = $str;
|
||||
if (!empty($bind)) {
|
||||
$this->queryStr .= '[ ' . print_r($bind, true) . ' ]';
|
||||
}
|
||||
//释放前次的查询结果
|
||||
if ( !empty($this->PDOStatement) ) $this->free();
|
||||
if (!empty($this->PDOStatement)) {
|
||||
$this->free();
|
||||
}
|
||||
|
||||
$this->queryTimes++;
|
||||
// 调试开始
|
||||
$this->debug(true);
|
||||
$this->PDOStatement = $this->_linkID->prepare($str);
|
||||
if(false === $this->PDOStatement){
|
||||
if (false === $this->PDOStatement) {
|
||||
$this->error();
|
||||
return false;
|
||||
}
|
||||
foreach ($bind as $key => $val) {
|
||||
if(is_array($val)){
|
||||
if (is_array($val)) {
|
||||
$this->PDOStatement->bindValue($key, $val[0], $val[1]);
|
||||
}else{
|
||||
} else {
|
||||
$this->PDOStatement->bindValue($key, $val);
|
||||
}
|
||||
}
|
||||
try{
|
||||
$result = $this->PDOStatement->execute();
|
||||
try {
|
||||
$result = $this->PDOStatement->execute();
|
||||
// 调试结束
|
||||
$this->debug(false);
|
||||
if ( false === $result ) {
|
||||
if (false === $result) {
|
||||
$this->error();
|
||||
return false;
|
||||
} else {
|
||||
return $this->getResult();
|
||||
}
|
||||
}catch (\PDOException $e) {
|
||||
} catch (\PDOException $e) {
|
||||
$this->error();
|
||||
return false;
|
||||
}
|
||||
@@ -163,44 +178,51 @@ class Lite {
|
||||
* @param array $bind 参数绑定
|
||||
* @return integer
|
||||
*/
|
||||
public function execute($str,$bind=[]) {
|
||||
public function execute($str, $bind = [])
|
||||
{
|
||||
$this->initConnect(true);
|
||||
if ( !$this->_linkID ) return false;
|
||||
if (!$this->_linkID) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->queryStr = $str;
|
||||
if(!empty($bind)){
|
||||
$this->queryStr .= '[ '.print_r($bind,true).' ]';
|
||||
}
|
||||
if (!empty($bind)) {
|
||||
$this->queryStr .= '[ ' . print_r($bind, true) . ' ]';
|
||||
}
|
||||
//释放前次的查询结果
|
||||
if ( !empty($this->PDOStatement) ) $this->free();
|
||||
if (!empty($this->PDOStatement)) {
|
||||
$this->free();
|
||||
}
|
||||
|
||||
$this->executeTimes++;
|
||||
// 记录开始执行时间
|
||||
$this->debug(true);
|
||||
$this->PDOStatement = $this->_linkID->prepare($str);
|
||||
if(false === $this->PDOStatement){
|
||||
$this->PDOStatement = $this->_linkID->prepare($str);
|
||||
if (false === $this->PDOStatement) {
|
||||
$this->error();
|
||||
return false;
|
||||
}
|
||||
foreach ($bind as $key => $val) {
|
||||
if(is_array($val)){
|
||||
if (is_array($val)) {
|
||||
$this->PDOStatement->bindValue($key, $val[0], $val[1]);
|
||||
}else{
|
||||
} else {
|
||||
$this->PDOStatement->bindValue($key, $val);
|
||||
}
|
||||
}
|
||||
try{
|
||||
$result = $this->PDOStatement->execute();
|
||||
try {
|
||||
$result = $this->PDOStatement->execute();
|
||||
$this->debug(false);
|
||||
if ( false === $result) {
|
||||
if (false === $result) {
|
||||
$this->error();
|
||||
return false;
|
||||
} else {
|
||||
$this->numRows = $this->PDOStatement->rowCount();
|
||||
if(preg_match("/^\s*(INSERT\s+INTO|REPLACE\s+INTO)\s+/i", $str)) {
|
||||
if (preg_match("/^\s*(INSERT\s+INTO|REPLACE\s+INTO)\s+/i", $str)) {
|
||||
$this->lastInsID = $this->_linkID->lastInsertId();
|
||||
}
|
||||
return $this->numRows;
|
||||
}
|
||||
}catch (\PDOException $e) {
|
||||
} catch (\PDOException $e) {
|
||||
$this->error();
|
||||
return false;
|
||||
}
|
||||
@@ -211,15 +233,19 @@ class Lite {
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function startTrans() {
|
||||
public function startTrans()
|
||||
{
|
||||
$this->initConnect(true);
|
||||
if ( !$this->_linkID ) return false;
|
||||
if (!$this->_linkID) {
|
||||
return false;
|
||||
}
|
||||
|
||||
//数据rollback 支持
|
||||
if ($this->transTimes == 0) {
|
||||
if (0 == $this->transTimes) {
|
||||
$this->_linkID->beginTransaction();
|
||||
}
|
||||
$this->transTimes++;
|
||||
return ;
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -227,11 +253,12 @@ class Lite {
|
||||
* @access public
|
||||
* @return boolen
|
||||
*/
|
||||
public function commit() {
|
||||
public function commit()
|
||||
{
|
||||
if ($this->transTimes > 0) {
|
||||
$result = $this->_linkID->commit();
|
||||
$result = $this->_linkID->commit();
|
||||
$this->transTimes = 0;
|
||||
if(!$result){
|
||||
if (!$result) {
|
||||
$this->error();
|
||||
return false;
|
||||
}
|
||||
@@ -244,11 +271,12 @@ class Lite {
|
||||
* @access public
|
||||
* @return boolen
|
||||
*/
|
||||
public function rollback() {
|
||||
public function rollback()
|
||||
{
|
||||
if ($this->transTimes > 0) {
|
||||
$result = $this->_linkID->rollback();
|
||||
$result = $this->_linkID->rollback();
|
||||
$this->transTimes = 0;
|
||||
if(!$result){
|
||||
if (!$result) {
|
||||
$this->error();
|
||||
return false;
|
||||
}
|
||||
@@ -261,10 +289,11 @@ class Lite {
|
||||
* @access private
|
||||
* @return array
|
||||
*/
|
||||
private function getResult() {
|
||||
private function getResult()
|
||||
{
|
||||
//返回数据集
|
||||
$result = $this->PDOStatement->fetchAll(PDO::FETCH_ASSOC);
|
||||
$this->numRows = count( $result );
|
||||
$result = $this->PDOStatement->fetchAll(PDO::FETCH_ASSOC);
|
||||
$this->numRows = count($result);
|
||||
return $result;
|
||||
}
|
||||
|
||||
@@ -274,8 +303,9 @@ class Lite {
|
||||
* @param boolean $execute 是否包含所有查询
|
||||
* @return integer
|
||||
*/
|
||||
public function getQueryTimes($execute=false){
|
||||
return $execute?$this->queryTimes+$this->executeTimes:$this->queryTimes;
|
||||
public function getQueryTimes($execute = false)
|
||||
{
|
||||
return $execute ? $this->queryTimes + $this->executeTimes : $this->queryTimes;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -283,7 +313,8 @@ class Lite {
|
||||
* @access public
|
||||
* @return integer
|
||||
*/
|
||||
public function getExecuteTimes(){
|
||||
public function getExecuteTimes()
|
||||
{
|
||||
return $this->executeTimes;
|
||||
}
|
||||
|
||||
@@ -291,7 +322,8 @@ class Lite {
|
||||
* 关闭数据库
|
||||
* @access public
|
||||
*/
|
||||
public function close() {
|
||||
public function close()
|
||||
{
|
||||
$this->_linkID = null;
|
||||
}
|
||||
|
||||
@@ -301,33 +333,36 @@ class Lite {
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function error() {
|
||||
if($this->PDOStatement) {
|
||||
$error = $this->PDOStatement->errorInfo();
|
||||
$this->error = $error[1].':'.$error[2];
|
||||
}else{
|
||||
public function error()
|
||||
{
|
||||
if ($this->PDOStatement) {
|
||||
$error = $this->PDOStatement->errorInfo();
|
||||
$this->error = $error[1] . ':' . $error[2];
|
||||
} else {
|
||||
$this->error = '';
|
||||
}
|
||||
if('' != $this->queryStr){
|
||||
$this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
|
||||
if ('' != $this->queryStr) {
|
||||
$this->error .= "\n [ SQL语句 ] : " . $this->queryStr;
|
||||
}
|
||||
// 记录错误日志
|
||||
Log::record($this->error,'ERR');
|
||||
if($this->config['debug']) {// 开启数据库调试模式
|
||||
Log::record($this->error, 'ERR');
|
||||
if ($this->config['debug']) {
|
||||
// 开启数据库调试模式
|
||||
throw new Exception($this->error);
|
||||
}else{
|
||||
} else {
|
||||
return $this->error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取最近一次查询的sql语句
|
||||
* 获取最近一次查询的sql语句
|
||||
* @param string $model 模型名
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function getLastSql($model='') {
|
||||
return $model?$this->modelSql[$model]:$this->queryStr;
|
||||
public function getLastSql($model = '')
|
||||
{
|
||||
return $model ? $this->modelSql[$model] : $this->queryStr;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -335,7 +370,8 @@ class Lite {
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function getLastInsID() {
|
||||
public function getLastInsID()
|
||||
{
|
||||
return $this->lastInsID;
|
||||
}
|
||||
|
||||
@@ -344,7 +380,8 @@ class Lite {
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function getError() {
|
||||
public function getError()
|
||||
{
|
||||
return $this->error;
|
||||
}
|
||||
|
||||
@@ -354,7 +391,8 @@ class Lite {
|
||||
* @param string $str SQL字符串
|
||||
* @return string
|
||||
*/
|
||||
public function escapeString($str) {
|
||||
public function escapeString($str)
|
||||
{
|
||||
return addslashes($str);
|
||||
}
|
||||
|
||||
@@ -364,8 +402,9 @@ class Lite {
|
||||
* @param string $model 模型名
|
||||
* @return void
|
||||
*/
|
||||
public function setModel($model){
|
||||
$this->model = $model;
|
||||
public function setModel($model)
|
||||
{
|
||||
$this->model = $model;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -373,16 +412,18 @@ class Lite {
|
||||
* @access protected
|
||||
* @param boolean $start 调试开始标记 true 开始 false 结束
|
||||
*/
|
||||
protected function debug($start) {
|
||||
if($this->config['debug']) {// 开启数据库调试模式
|
||||
if($start) {
|
||||
Debug::remark('queryStartTime','time');
|
||||
}else{
|
||||
$this->modelSql[$this->model] = $this->queryStr;
|
||||
protected function debug($start)
|
||||
{
|
||||
if ($this->config['debug']) {
|
||||
// 开启数据库调试模式
|
||||
if ($start) {
|
||||
Debug::remark('queryStartTime', 'time');
|
||||
} else {
|
||||
$this->modelSql[$this->model] = $this->queryStr;
|
||||
//$this->model = '_think_';
|
||||
// 记录操作结束时间
|
||||
Debug::remark('queryEndTime','time');
|
||||
Log::record($this->queryStr.' [ RunTime:'.Debug::getUseTime('queryStartTime','queryEndTime').'s ]','SQL');
|
||||
Debug::remark('queryEndTime', 'time');
|
||||
Log::record($this->queryStr . ' [ RunTime:' . Debug::getUseTime('queryStartTime', 'queryEndTime') . 's ]', 'SQL');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -393,13 +434,18 @@ class Lite {
|
||||
* @param boolean $master 主服务器
|
||||
* @return void
|
||||
*/
|
||||
protected function initConnect($master=true) {
|
||||
if(!empty($this->config['deploy']))
|
||||
// 采用分布式数据库
|
||||
protected function initConnect($master = true)
|
||||
{
|
||||
if (!empty($this->config['deploy']))
|
||||
// 采用分布式数据库
|
||||
{
|
||||
$this->_linkID = $this->multiConnect($master);
|
||||
else
|
||||
// 默认单数据库
|
||||
if ( !$this->_linkID ) $this->_linkID = $this->connect();
|
||||
} else
|
||||
// 默认单数据库
|
||||
if (!$this->_linkID) {
|
||||
$this->_linkID = $this->connect();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -408,56 +454,60 @@ class Lite {
|
||||
* @param boolean $master 主服务器
|
||||
* @return void
|
||||
*/
|
||||
protected function multiConnect($master=false) {
|
||||
protected function multiConnect($master = false)
|
||||
{
|
||||
static $_config = [];
|
||||
if(empty($_config)) {
|
||||
if (empty($_config)) {
|
||||
// 缓存分布式数据库配置解析
|
||||
$_config['username'] = explode(',',$$this->config['username']);
|
||||
$_config['password'] = explode(',',$$this->config['password']);
|
||||
$_config['hostname'] = explode(',',$$this->config['hostname']);
|
||||
$_config['hostport'] = explode(',',$$this->config['hostport']);
|
||||
$_config['database'] = explode(',',$$this->config['database']);
|
||||
$_config['dsn'] = explode(',',$$this->config['dsn']);
|
||||
$_config['username'] = explode(',', $$this->config['username']);
|
||||
$_config['password'] = explode(',', $$this->config['password']);
|
||||
$_config['hostname'] = explode(',', $$this->config['hostname']);
|
||||
$_config['hostport'] = explode(',', $$this->config['hostport']);
|
||||
$_config['database'] = explode(',', $$this->config['database']);
|
||||
$_config['dsn'] = explode(',', $$this->config['dsn']);
|
||||
}
|
||||
// 数据库读写是否分离
|
||||
if($this->config['rw_separate']){
|
||||
if ($this->config['rw_separate']) {
|
||||
// 主从式采用读写分离
|
||||
if($master)
|
||||
// 主服务器写入
|
||||
$r = floor(mt_rand(0,$this->config['master_num']-1));
|
||||
else{
|
||||
if(is_numeric($this->config['slave_no'])) {// 指定服务器读
|
||||
if ($master)
|
||||
// 主服务器写入
|
||||
{
|
||||
$r = floor(mt_rand(0, $this->config['master_num'] - 1));
|
||||
} else {
|
||||
if (is_numeric($this->config['slave_no'])) {
|
||||
// 指定服务器读
|
||||
$r = $this->config['slave_no'];
|
||||
}else{
|
||||
} else {
|
||||
// 读操作连接从服务器
|
||||
$r = floor(mt_rand($this->config['master_num'],count($_config['hostname'])-1)); // 每次随机连接的数据库
|
||||
$r = floor(mt_rand($this->config['master_num'], count($_config['hostname']) - 1)); // 每次随机连接的数据库
|
||||
}
|
||||
}
|
||||
}else{
|
||||
} else {
|
||||
// 读写操作不区分服务器
|
||||
$r = floor(mt_rand(0,count($_config['hostname'])-1)); // 每次随机连接的数据库
|
||||
$r = floor(mt_rand(0, count($_config['hostname']) - 1)); // 每次随机连接的数据库
|
||||
}
|
||||
$db_config = [
|
||||
'username' => isset($_config['username'][$r])?$_config['username'][$r]:$_config['username'][0],
|
||||
'password' => isset($_config['password'][$r])?$_config['password'][$r]:$_config['password'][0],
|
||||
'hostname' => isset($_config['hostname'][$r])?$_config['hostname'][$r]:$_config['hostname'][0],
|
||||
'hostport' => isset($_config['hostport'][$r])?$_config['hostport'][$r]:$_config['hostport'][0],
|
||||
'database' => isset($_config['database'][$r])?$_config['database'][$r]:$_config['database'][0],
|
||||
'dsn' => isset($_config['dsn'][$r])?$_config['dsn'][$r]:$_config['dsn'][0],
|
||||
'username' => isset($_config['username'][$r]) ? $_config['username'][$r] : $_config['username'][0],
|
||||
'password' => isset($_config['password'][$r]) ? $_config['password'][$r] : $_config['password'][0],
|
||||
'hostname' => isset($_config['hostname'][$r]) ? $_config['hostname'][$r] : $_config['hostname'][0],
|
||||
'hostport' => isset($_config['hostport'][$r]) ? $_config['hostport'][$r] : $_config['hostport'][0],
|
||||
'database' => isset($_config['database'][$r]) ? $_config['database'][$r] : $_config['database'][0],
|
||||
'dsn' => isset($_config['dsn'][$r]) ? $_config['dsn'][$r] : $_config['dsn'][0],
|
||||
];
|
||||
return $this->connect($db_config,$r);
|
||||
return $this->connect($db_config, $r);
|
||||
}
|
||||
|
||||
/**
|
||||
/**
|
||||
* 析构方法
|
||||
* @access public
|
||||
*/
|
||||
public function __destruct() {
|
||||
public function __destruct()
|
||||
{
|
||||
// 释放查询
|
||||
if ($this->PDOStatement){
|
||||
if ($this->PDOStatement) {
|
||||
$this->free();
|
||||
}
|
||||
// 关闭连接
|
||||
$this->close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user