Files
nexusphp/nexus/Database/NexusDB.php

352 lines
9.3 KiB
PHP
Raw Normal View History

<?php
2021-01-27 16:26:37 +08:00
namespace Nexus\Database;
2021-05-29 21:48:50 +08:00
use Illuminate\Database\Capsule\Manager as Capsule;
2022-01-19 23:54:55 +08:00
use Illuminate\Database\Query\Expression;
use Illuminate\Support\Facades\Cache;
2022-01-19 23:54:55 +08:00
use Illuminate\Support\Facades\DB;
2022-03-30 15:37:11 +08:00
use Illuminate\Support\Facades\Redis;
2021-05-29 21:48:50 +08:00
2021-06-08 10:42:39 +08:00
class NexusDB
{
2021-01-04 20:47:22 +08:00
private $driver;
private static $instance;
2021-06-21 02:01:26 +08:00
/**
* @var \Illuminate\Database\Connection
*/
private static $eloquentConnection;
private $isConnected = false;
private function __construct()
{
}
private function __clone()
{
}
2021-04-26 20:37:17 +08:00
const ELOQUENT_CONNECTION_NAME = 'default';
public function setDriver(DBInterface $driver)
{
$this->driver = $driver;
return $this;
}
2021-01-28 18:00:54 +08:00
public function getDriver()
{
return $this->driver;
}
public static function getInstance()
{
if (self::$instance) {
return self::$instance;
}
$instance = new self;
$driver = new DBMysqli();
$instance->setDriver($driver);
return self::$instance = $instance;
}
public function connect($host, $username, $password, $database, $port)
{
2021-01-28 18:00:54 +08:00
$result = $this->driver->connect($host, $username, $password, $database, $port);
if (!$result) {
throw new DatabaseException(sprintf('[%s]: %s', $this->errno(), $this->error()));
}
2021-01-27 17:50:24 +08:00
$this->isConnected = true;
return true;
}
2021-01-27 16:26:37 +08:00
public function autoConnect()
{
if ($this->isConnected()) {
2021-01-28 18:00:54 +08:00
return null;
2021-01-27 16:26:37 +08:00
}
2021-04-02 19:48:41 +08:00
$config = nexus_config('nexus.mysql');
2021-01-28 18:00:54 +08:00
return $this->connect($config['host'], $config['username'], $config['password'], $config['database'], $config['port']);
2021-01-27 16:26:37 +08:00
}
public function query(string $sql)
{
2020-12-28 02:14:41 +08:00
try {
2021-01-27 16:26:37 +08:00
$this->autoConnect();
2020-12-28 02:14:41 +08:00
return $this->driver->query($sql);
} catch (\Exception $e) {
do_log(sprintf("%s [%s] %s", $e->getMessage(), $sql, $e->getTraceAsString()));
2021-01-27 16:26:37 +08:00
throw new DatabaseException($e->getMessage(), $sql);
2020-12-28 02:14:41 +08:00
}
}
public function error()
{
return $this->driver->error();
}
public function errno()
{
return $this->driver->errno();
}
public function numRows($result)
{
return $this->driver->numRows($result);
}
public function select_db($database)
{
return $this->driver->selectDb($database);
}
public function fetchAssoc($result)
{
return $this->driver->fetchAssoc($result);
}
public function fetchRow($result)
{
return $this->driver->fetchRow($result);
}
2020-12-28 02:14:41 +08:00
public function fetchArray($result, $type = null)
{
return $this->driver->fetchArray($result, $type);
}
public function affectedRows()
{
return $this->driver->affectedRows();
}
public function escapeString(string $string)
{
2021-01-27 16:26:37 +08:00
$this->autoConnect();
return $this->driver->escapeString($string);
}
2020-12-28 20:52:54 +08:00
public function lastInsertId()
{
return $this->driver->lastInsertId();
}
2021-01-07 17:35:00 +08:00
public function freeResult($result)
{
return $this->driver->freeResult($result);
}
public function isConnected()
{
return $this->isConnected;
}
2021-01-25 01:23:28 +08:00
public static function insert($table, $data)
{
if (empty($table) || empty($data) || !is_array($data)) {
throw new DatabaseException("require table and data(array).");
}
$fields = array_map(function ($value) {return "`$value`";}, array_keys($data));
$values = array_map(function ($value) {return sqlesc($value);}, array_values($data));
$sql = sprintf("insert into `%s` (%s) values (%s)", $table, implode(', ', $fields), implode(', ', $values));
sql_query($sql);
return mysql_insert_id();
}
2021-03-02 21:03:02 +08:00
public static function update($table, $data, $whereStr)
{
$updateArr = [];
foreach ($data as $field => $value) {
$updateArr[] = "`$field` = " . sqlesc($value);
}
$sql = sprintf("update `%s` set %s where %s", $table, implode(', ', $updateArr), $whereStr);
sql_query($sql);
return mysql_affected_rows();
}
2021-03-03 19:29:29 +08:00
public static function delete($table, $whereStr, $limit = null)
{
$sql = "delete from $table where $whereStr";
if (!is_null($limit)) {
$sql .= " limit $limit";
}
sql_query($sql);
return mysql_affected_rows();
}
2021-03-03 01:56:07 +08:00
public static function getOne($table, $whereStr, $fields = '*')
{
if ($fields != '*') {
if (is_array($fields)) {
$fields = implode(', ', $fields);
}
}
if (empty($fields)) {
do_log("args: " . json_encode(func_get_args()));
throw new DatabaseException("empty fields.");
}
$sql = "select $fields from $table where $whereStr limit 1";
$res = sql_query($sql);
return mysql_fetch_assoc($res);
}
2021-03-16 21:12:27 +08:00
public static function getAll($table, $whereStr, $fields = '*')
{
if ($fields != '*') {
if (is_array($fields)) {
$fields = implode(', ', $fields);
}
}
if (empty($fields)) {
do_log("args: " . json_encode(func_get_args()));
throw new DatabaseException("empty fields.");
}
$sql = "select $fields from $table where $whereStr";
$res = sql_query($sql);
$result = [];
while ($row = mysql_fetch_assoc($res)) {
$result[] = $row;
}
return $result;
}
2021-05-29 21:48:50 +08:00
public static function bootEloquent(array $config)
{
$capsule = new Capsule;
$connectionName = self::ELOQUENT_CONNECTION_NAME;
$capsule->addConnection($config, $connectionName);
$capsule->setAsGlobal();
$capsule->bootEloquent();
2021-06-21 02:01:26 +08:00
$connection = self::$eloquentConnection = $capsule->getConnection($connectionName);
2021-06-04 10:26:34 +08:00
$connection->enableQueryLog();
$connection->getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
2021-05-29 21:48:50 +08:00
}
public static function schema(): \Illuminate\Database\Schema\Builder
{
2022-01-19 23:54:55 +08:00
if (IN_NEXUS) {
return Capsule::schema(self::ELOQUENT_CONNECTION_NAME);
}
throw new \RuntimeException('can not call this when not in nexus.');
2021-05-29 21:48:50 +08:00
}
2021-06-05 22:41:27 +08:00
public static function table($table): \Illuminate\Database\Query\Builder
{
2022-01-19 23:54:55 +08:00
if (IN_NEXUS) {
return Capsule::table($table);
}
return DB::table($table);
}
public static function raw($value): \Illuminate\Database\Query\Expression
{
if (IN_NEXUS) {
return new Expression($value);
}
return DB::raw($value);
2021-06-05 22:41:27 +08:00
}
2022-03-08 15:08:56 +08:00
public static function statement($value)
{
if (IN_NEXUS) {
return sql_query($value);
}
return DB::statement($value);
}
public static function transaction(\Closure $callback, $attempts = 1)
{
2022-01-19 23:54:55 +08:00
if (IN_NEXUS) {
return Capsule::connection(self::ELOQUENT_CONNECTION_NAME)->transaction($callback, $attempts);
}
return DB::transaction($callback, $attempts);
}
public static function remember($key, $ttl, \Closure $callback)
{
if (IN_NEXUS) {
global $Cache;
$result = $Cache->get_value($key);
if ($result === false) {
2022-04-01 23:13:42 +08:00
do_log("cache miss [$key], get from database.");
$result = $callback();
$Cache->cache_value($key, $result, $ttl);
} else {
2022-04-01 23:13:42 +08:00
do_log("cache hit [$key].");
}
return $result;
} else {
return Cache::remember($key, $ttl, $callback);
}
}
2022-03-30 15:37:11 +08:00
public static function cache_put($key, $value, $ttl = 3600)
{
if (IN_NEXUS) {
global $Cache;
return $Cache->cache_value($key, $value, $ttl);
} else {
return Cache::put($key, $value, $ttl);
}
}
public static function cache_get($key)
{
if (IN_NEXUS) {
global $Cache;
return $Cache->get_value($key);
} else {
return Cache::get($key);
}
}
public static function cache_del($key)
{
if (IN_NEXUS) {
global $Cache;
$Cache->delete_value($key, true);
} else {
Cache::forget($key);
$langList = get_langfolder_list();
foreach ($langList as $lf) {
Cache::forget($lf . '_' . $key);
}
}
}
public static function redis()
{
if (IN_NEXUS) {
global $Cache;
$Cache->getRedis();
} else {
Redis::connection()->client();
}
}
2021-06-06 13:41:05 +08:00
public static function getMysqlColumnInfo($table, $column)
{
static $driver;
$config = nexus_config('nexus.mysql');
if (is_null($driver)) {
$driver = new DBMysqli();
$driver->connect($config['host'], $config['username'], $config['password'], 'information_schema', $config['port']);
}
$sql = sprintf(
"select * from COLUMNS where TABLE_SCHEMA = '%s' and TABLE_NAME = '%s' and COLUMN_NAME = '%s'",
$config['database'], $table, $column
);
$res = $driver->query($sql);
return $driver->fetchAssoc($res);
}
2021-06-05 22:41:27 +08:00
2021-04-02 19:48:41 +08:00
}