<?php<liu21st@gmail.com>declare (strict_types = 1);
namespace think\db;
use Psr\SimpleCache\CacheInterface;
use think\DbManager;
abstract class Connection implements ConnectionInterface
{
protected $queryStr = '';
protected $numRows = 0;
protected $transTimes = 0;
protected $error = '';
protected $links = [];
protected $linkID;
protected $linkRead;
protected $linkWrite;
protected $info = [];
protected $queryStartTime;
protected $builder;
protected $db;
protected $readMaster = false;
protected $config = [];
protected $cache;
public function __construct(array $config = [])
{
if (!empty($config)) {
$this->config = array_merge($this->config, $config);
}
$class = $this->getBuilderClass();
$this->builder = new $class($this);
}
public function getBuilder()
{
return $this->builder;
}
public function newQuery()
{
$class = $this->getQueryClass();
$query = new $class($this);
$timeRule = $this->db->getConfig('time_query_rule');
if (!empty($timeRule)) {
$query->timeRule($timeRule);
}
return $query;
}
public function table($table)
{
return $this->newQuery()->table($table);
}
public function name($name)
{
return $this->newQuery()->name($name);
}
public function setDb(DbManager $db)
{
$this->db = $db;
}
public function setCache(CacheInterface $cache)
{
$this->cache = $cache;
}
public function getCache()
{
return $this->cache;
}
public function getConfig(string $config = '')
{
if ('' === $config) {
return $this->config;
}
return $this->config[$config] ?? null;
}
protected function trigger(string $sql = '', bool $master = false): void
{
$listen = $this->db->getListen();
if (!empty($listen)) {
$runtime = number_format((microtime(true) - $this->queryStartTime), 6);
$sql = $sql ?: $this->getLastsql();
if (empty($this->config['deploy'])) {
$master = null;
}
foreach ($listen as $callback) {
if (is_callable($callback)) {
$callback($sql, $runtime, $master);
}
}
}
}
protected function cacheData(CacheItem $cacheItem)
{
if ($cacheItem->getTag() && method_exists($this->cache, 'tag')) {
$this->cache->tag($cacheItem->getTag())->set($cacheItem->getKey(), $cacheItem->get(), $cacheItem->getExpire());
} else {
$this->cache->set($cacheItem->getKey(), $cacheItem->get(), $cacheItem->getExpire());
}
}
protected function getCacheKey(BaseQuery $query, string $method = ''): string
{
if (!empty($query->getOptions('key')) && empty($method)) {
$key = 'think:' . $this->getConfig('database') . '.' . $query->getTable() . '|' . $query->getOptions('key');
} else {
$key = $query->getQueryGuid();
}
return $key;
}
protected function parseCache(BaseQuery $query, array $cache, string $method = ''): CacheItem
{
[$key, $expire, $tag] = $cache;
if ($key instanceof CacheItem) {
$cacheItem = $key;
} else {
if (true === $key) {
$key = $this->getCacheKey($query, $method);
}
$cacheItem = new CacheItem($key);
$cacheItem->expire($expire);
$cacheItem->tag($tag);
}
return $cacheItem;
}
public function getNumRows(): int
{
return $this->numRows;
}
public function __destruct()
{
$this->close();
}
}