C3P0异常:java.lang.Exception: DEBUG -- CLOSE BY CLIENT STACK TRACE 解决

本文探讨了在Spring项目中遇到的c3p0报错问题:DEBUG--CLOSEBYCLIENTSTACKTRACE。通过深入研究源码及配置,揭示了这一异常并非真正的错误,而是连接池在测试连接时产生的正常日志信息。

问题说明

接手一个新项目的时候意外发现项目一直有一个c3p0的报错,完整信息是这样的:

java.lang.Exception: DEBUG -- CLOSE BY CLIENT STACK TRACE
    at com.mchange.v2.c3p0.impl.NewPooledConnection.close(NewPooledConnection.java:566)
    at com.mchange.v2.c3p0.impl.NewPooledConnection.close(NewPooledConnection.java:234)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.destroyResource(C3P0PooledConnectionPool.java:470)
    at com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask.run(BasicResourcePool.java:964)
    at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547)

之前也没有用过c3p0,遇见报错第一时间就求助搜索引擎了,没有找到太多有用的信息,于是跟进源码看了一下。
相关的报错信息在NewPooledConnection.java这个类里,抛出这个异常的代码段如下所示:

//  methods below must be called from sync'ed methods

    /*
     *  If a throwable cause is provided, the PooledConnection is known to be broken (cause is an invalidating exception)
     *  and this method will not throw any exceptions, even if some resource closes fail.
     *
     *  If cause is null, then we think the PooledConnection is healthy, and we will report (throw) an exception
     *  if resources unexpectedlay fail to close.
     */
    private void close( Throwable cause ) throws SQLException
    {
        if ( this.invalidatingException == null )
        {
            List closeExceptions = new LinkedList();

            // cleanup ResultSets
            cleanupResultSets( closeExceptions );

            // cleanup uncached Statements
            cleanupUncachedStatements( closeExceptions );

            // cleanup cached Statements
            try
            { closeAllCachedStatements(); }
            catch ( SQLException e )
            { closeExceptions.add(e); }

            // cleanup physicalConnection
            try
            { physicalConnection.close(); }
            catch ( SQLException e )
            {
                if (logger.isLoggable( MLevel.FINER ))
                    logger.log( MLevel.FINER, "Failed to close physical Connection: " + physicalConnection, e );

                closeExceptions.add(e); 
            }

            // update our state to bad status and closed, and log any exceptions
            if ( connection_status == ConnectionTester.CONNECTION_IS_OKAY )
                connection_status = ConnectionTester.CONNECTION_IS_INVALID;
            if ( cause == null )
            {
                this.invalidatingException = NORMAL_CLOSE_PLACEHOLDER;

                if ( logger.isLoggable( MLevel.FINEST ) )
                    logger.log( MLevel.FINEST, this + " closed by a client.", new Exception("DEBUG -- CLOSE BY CLIENT STACK TRACE") );

                logCloseExceptions( null, closeExceptions );

                if (closeExceptions.size() > 0)
                    throw new SQLException("Some resources failed to close properly while closing " + this);
            }
            else
            {
                this.invalidatingException = cause;
                if (Debug.TRACE >= Debug.TRACE_MED)
                    logCloseExceptions( cause, closeExceptions );
                else
                    logCloseExceptions( cause, null );
            }
        }
    }

在stackoverflow上搜索到的相关问题这么说:

This is the code that triggers this log statement in C3P0:

if ( logger.isLoggable( MLevel.FINEST ) ) logger.log( MLevel.FINEST,
this + ” closed by a client.”,
new Exception(“DEBUG – CLOSE BY CLIENT STACK
TRACE”) );

Note that:

This is not an exception, the new Exception is used merely to show
execution path for debug purposes. And yes, this is only a debug
message (actually, FINEST is the lowest possible level in
java.util.logging). To wrap this up: ignore and tune your logging
levels to skip these.

意思就是说我们不用在意这个报错,这并不是提示我们项目有错误信息,只是一个提示。提高日志级别就看不到了。
这个看上去能解决问题,但肯定不是我想要的答案,于是继续搜索。

解决方案

网上讲说,只要修改配置文件就可以解决这个问题:
找到配置文件,去掉

<!--c3p0将建一张名为c3p0_test的空表,并使用其自带的查询语句进行测试。如果定义了这个参数那么
属性preferredTestQuery将被忽略。你不能在这张c3p0_test表上进行任何操作,它将只供c3p0测试
使用。Default: null-->
<property name="automaticTestTable"><value>c3p0_test</value></property>

增加:

<!--定义所有连接测试都执行的测试语句。在使用连接测试的情况下这个一显著提高测试速度。注意:
测试的表必须在初始数据源的时候就存在。Default: null--> 
<property name="preferredTestQuery"><value>SELECT 1 FORM TABLE</value></property>

但是我检查了一下自己的项目,发现项目中根本没有这两个配置项,那这两个配置肯定没能解决根本问题。不过这个信息还是有价值的,对照查询c3p0配置文件说明,发现这两个配置文件都是testConnectionOnCheckin这个配置项使用的,也就是用来检查数据库连接是否正常的。有第一个配置文件的同学可以尝试一下,未必没用。

真实原因解析

自己最后在网上找到了一篇解答,解释了为什么会抛出异常。
spring在配置数据源时,一般是这么写的:

    <bean id="ds1" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
</bean>

中间配置数据源的相关内容,重点就在class和destory-method两个属性上,一个是实现类,一个是析构方法。spring读取配置文件后,需要根据这些信息来实例化向关内,再根据配置信息构造数据源。但是由于spring本身没办法确认类是不是真实有效,打开和关闭连接的方法可用,那么为了确保这些事情,spring会去实际构造一个链接,打开、查询、关闭,完成这么一套流程,也就能够保证这个配置是真实有效的。
我们知道任何一个数据库连接的实现类都是在实java.sql.Connection这个接口。java是这么规定的,接口的实现类必须实现接口的所有方法,反过来说,数据库的实现类就有可能包含java.sql.Connection中没有的方法。所以spring就需要destory-method这个属性来确认到底使用什么方法来close(关闭连接释放资源)。

回到我们最初的问题,既然已经清楚了这个过程,那么我们就可以确认,这个异常,其实不是一个错误,而是一个提示信息,产生于程序尝试建立数据库连接的过程,信息的抛出是为了告诉我们连接建立成功并且测试链接已经成功关闭。

这是api/api.php文件代码 <?php // api/api.php // === 配置区 === define('MUIP_API', 'http://127.0.0.1:62221/api'); define('REGION', 'dev_gio'); define('TIME_TOLERANT', 5); define('PRIVATE_KEY_SIZE', 4096); define('PRIVATE_KEY', '$$$PRIVATE_KEY$$$'); // 签名函数(根据实际算法调整) function calcSign($params, $secretKey) { ksort($params); $str = ''; foreach ($params as $k => $v) { $str .= $k . '=' . $v . '&'; } $str = rtrim($str, '&'); return md5($str . $secretKey); } // 返回 JSON 并结束 function returnJSON($data, $code = 200) { http_response_code($code); header('Content-Type: application/json'); echo json_encode($data, JSON_UNESCAPED_UNICODE); exit; } // === 认证校验 === if ($_GET["adminpass"] !== "syxywlQQ28009618hello") { returnJSON(['success' => false, 'message' => 'gm码错误'], 403); } if ($_GET["sha"] !== md5("getflag")) { returnJSON(['success' => false, 'message' => 'gm码错误'], 403); } $uid = intval($_GET["uid"]); $item = $_GET["item"] ?? ''; $number = max(1, intval($_GET["number"] ?? 1)); if ($uid <= 0) { returnJSON(['success' => false, 'message' => '无效UID'], 400); } // === 命令类型映射表 === $commandMap = [ 'item' => "item add $item $number", 'mcoin' => "mcoin $number", 'level' => "player level $item", 'exp' => "player exp $item", 'money' => "player money $item", 'vip' => "player vip $item", 'teleport' => "player teleport " . (floatval($item) ?: '0') . " 0", 'custom_cmd' => $item, ]; // 获取命令类型 $cmdType = $_GET['cmd_type'] ?? 'item'; // 特殊兼容:item=203 → mcoin if ($item == 203) { $cmdType = 'mcoin'; } if (!isset($commandMap[$cmdType])) { returnJSON(['success' => false, 'message' => "不支持的命令类型: $cmdType"], 400); } $command = $commandMap[$cmdType]; // === 构造并发送 GM 请求 === $query = [ 'cmd' => 1116, 'uid' => $uid, 'msg' => $command, 'region' => REGION ]; $query['sign'] = calcSign($query, "27bwq^d4zzXpdUxf"); $ch = curl_init(MUIP_API . '?' . http_build_query($query)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); $rsp = curl_exec($ch); if (curl_error($ch)) { returnJSON(['success' => false, 'message' => '请求失败: ' . curl_error($ch)], 500); } curl_close($ch); $rspData = @json_decode($rsp, true); returnJSON([ 'success' => isset($rspData['retcode']) && $rspData['retcode'] === 0, 'message' => $rspData['msg'] ?? '操作完成', 'data' => $rspData['data'] ?? null, 'debug' => [ // 调试用,上线前可删除 'command_sent' => $command, 'cmd_type' => $cmdType, 'uid' => $uid ] ]); ?> 这是index.php文件代码 <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8" /> <title>CDK兑换中心</title> <style> body { font-family: Arial, sans-serif; background: #f4f4f4; padding: 20px; } .container { max-width: 600px; margin: auto; background: white; padding: 20px; border-radius: 10px; box-shadow: 0 0 10px rgba(0,0,0,0.1); } input[type="text"] { width: 100%; padding: 10px; margin: 10px 0; border: 1px solid #ccc; border-radius: 5px; font-size: 16px; } button { background: #007BFF; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; } button:hover { background: #0056b3; } .message { padding: 10px; margin: 10px 0; border-radius: 5px; } .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; } .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; } </style> </head> <body> <div class="container"> <h2 style="text-align:center;">🎮 CDK兑换系统</h2> <form method="post"> UID: <input type="text" name="uid" placeholder="输入你的游戏UID" required /><br/> CDK: <input type="text" name="cdk" placeholder="输入兑换码" required /><br/> <button type="submit">立即兑换</button> </form> <?php // 引入 Medoo(请确保路径正确) require_once './medoo.php'; // 根据实际路径调整,如:vendor/medoo/medoo.min.php use Medoo\Medoo; // 初始化数据库连接 $database = new Medoo([ 'database_type' => 'mysql', 'database_name' => 'db_hk4e_gm', 'server' => '127.0.0.1', 'username' => 'db_hk4e_gm', 'password' => 'syxywl.cn', 'charset' => 'utf8', 'port' => 3306, ]); if ($_POST) { $Uid = trim($_POST['uid']); $cdk_input = trim($_POST['cdk']); if (!is_numeric($Uid) || intval($Uid) <= 0) { echo "<div class='message error'>❌ 请输入有效的数字UID!</div>"; return; } $Uid = intval($Uid); try { // === 查询 CDK 是否存在且启用 === $cdkData = $database->get("cdk", [ "id", "item", "number", "command_type" ], [ "AND" => [ "cdk" => $cdk_input, "start" => 1 ] ]); if (!$cdkData) { echo "<div class='message error'>❌ CDK不存在或已停用!<br>卡密: $cdk_input</div>"; return; } // === 检查是否已兑换过该 CDK === $used = $database->get("used_cdk", ["id"], [ "AND" => [ "uid" => $Uid, "cdk" => $cdk_input ] ]); if ($used) { echo "<div class='message error'>❌ 此CDK已被您兑换过!<br>卡密: $cdk_input</div>"; return; } // === 准备调用 API 发放奖励 === $cmd_type = $cdkData["command_type"] ?? "item"; $item_value = $cdkData["item"]; $number_value = intval($cdkData["number"]); // 特殊兼容:item=203 → mcoin if ($item_value == 203) { $cmd_type = "mcoin"; } $api_url = "http://202.189.14.206:344/api/api.php?" . http_build_query([ 'sha' => md5("getflag"), 'adminpass' => 'syxywlQQ28009618hello', 'uid' => $Uid, 'item' => urlencode($item_value), 'number' => $number_value, 'cmd_type' => urlencode($cmd_type) ]); $result = @file_get_contents($api_url); $run = json_decode($result, true); if ($run && !empty($run['success']) && $run['success'] === true) { // 记录已使用 $database->insert("used_cdk", [ "uid" => $Uid, "cdk" => $cdk_input, "used_time" => date("Y-m-d H:i:s") ]); echo "<div class='message success'>✅ 兑换成功!<br>奖励已发放:<strong>$cdk_input</strong></div>"; } else { $msg = $run['message'] ?? '接口无响应或失败'; echo "<div class='message error'>❌ 发放失败!<br>错误信息: $msg</div>"; } } catch (Exception $e) { echo "<div class='message error'>❌ 系统异常:<br>" . $e->getMessage() . "</div>"; } } ?> </div> </body> </html> 这是medoo.php文件代码 <?php /*! * Medoo database framework * https://medoo.in * Version 1.7.10 * * Copyright 2020, Angel Lai * Released under the MIT license */ namespace Medoo; use PDO; use Exception; use PDOException; use InvalidArgumentException; class Raw { public $map; public $value; } class Medoo { public $pdo; protected $type; protected $prefix; protected $statement; protected $dsn; protected $logs = []; protected $logging = false; protected $debug_mode = false; protected $guid = 0; protected $errorInfo = null; public function __construct(array $options) { if (isset($options[ 'database_type' ])) { $this->type = strtolower($options[ 'database_type' ]); if ($this->type === 'mariadb') { $this->type = 'mysql'; } } if (isset($options[ 'prefix' ])) { $this->prefix = $options[ 'prefix' ]; } if (isset($options[ 'logging' ]) && is_bool($options[ 'logging' ])) { $this->logging = $options[ 'logging' ]; } $option = isset($options[ 'option' ]) ? $options[ 'option' ] : []; $commands = (isset($options[ 'command' ]) && is_array($options[ 'command' ])) ? $options[ 'command' ] : []; switch ($this->type) { case 'mysql': // Make MySQL using standard quoted identifier $commands[] = 'SET SQL_MODE=ANSI_QUOTES'; break; case 'mssql': // Keep MSSQL QUOTED_IDENTIFIER is ON for standard quoting $commands[] = 'SET QUOTED_IDENTIFIER ON'; // Make ANSI_NULLS is ON for NULL value $commands[] = 'SET ANSI_NULLS ON'; break; } if (isset($options[ 'pdo' ])) { if (!$options[ 'pdo' ] instanceof PDO) { throw new InvalidArgumentException('Invalid PDO object supplied'); } $this->pdo = $options[ 'pdo' ]; foreach ($commands as $value) { $this->pdo->exec($value); } return; } if (isset($options[ 'dsn' ])) { if (is_array($options[ 'dsn' ]) && isset($options[ 'dsn' ][ 'driver' ])) { $attr = $options[ 'dsn' ]; } else { throw new InvalidArgumentException('Invalid DSN option supplied'); } } else { if ( isset($options[ 'port' ]) && is_int($options[ 'port' ] * 1) ) { $port = $options[ 'port' ]; } $is_port = isset($port); switch ($this->type) { case 'mysql': $attr = [ 'driver' => 'mysql', 'dbname' => $options[ 'database_name' ] ]; if (isset($options[ 'socket' ])) { $attr[ 'unix_socket' ] = $options[ 'socket' ]; } else { $attr[ 'host' ] = $options[ 'server' ]; if ($is_port) { $attr[ 'port' ] = $port; } } break; case 'pgsql': $attr = [ 'driver' => 'pgsql', 'host' => $options[ 'server' ], 'dbname' => $options[ 'database_name' ] ]; if ($is_port) { $attr[ 'port' ] = $port; } break; case 'sybase': $attr = [ 'driver' => 'dblib', 'host' => $options[ 'server' ], 'dbname' => $options[ 'database_name' ] ]; if ($is_port) { $attr[ 'port' ] = $port; } break; case 'oracle': $attr = [ 'driver' => 'oci', 'dbname' => $options[ 'server' ] ? '//' . $options[ 'server' ] . ($is_port ? ':' . $port : ':1521') . '/' . $options[ 'database_name' ] : $options[ 'database_name' ] ]; if (isset($options[ 'charset' ])) { $attr[ 'charset' ] = $options[ 'charset' ]; } break; case 'mssql': if (isset($options[ 'driver' ]) && $options[ 'driver' ] === 'dblib') { $attr = [ 'driver' => 'dblib', 'host' => $options[ 'server' ] . ($is_port ? ':' . $port : ''), 'dbname' => $options[ 'database_name' ] ]; if (isset($options[ 'appname' ])) { $attr[ 'appname' ] = $options[ 'appname' ]; } if (isset($options[ 'charset' ])) { $attr[ 'charset' ] = $options[ 'charset' ]; } } else { $attr = [ 'driver' => 'sqlsrv', 'Server' => $options[ 'server' ] . ($is_port ? ',' . $port : ''), 'Database' => $options[ 'database_name' ] ]; if (isset($options[ 'appname' ])) { $attr[ 'APP' ] = $options[ 'appname' ]; } $config = [ 'ApplicationIntent', 'AttachDBFileName', 'Authentication', 'ColumnEncryption', 'ConnectionPooling', 'Encrypt', 'Failover_Partner', 'KeyStoreAuthentication', 'KeyStorePrincipalId', 'KeyStoreSecret', 'LoginTimeout', 'MultipleActiveResultSets', 'MultiSubnetFailover', 'Scrollable', 'TraceFile', 'TraceOn', 'TransactionIsolation', 'TransparentNetworkIPResolution', 'TrustServerCertificate', 'WSID', ]; foreach ($config as $value) { $keyname = strtolower(preg_replace(['/([a-z\d])([A-Z])/', '/([^_])([A-Z][a-z])/'], '$1_$2', $value)); if (isset($options[ $keyname ])) { $attr[ $value ] = $options[ $keyname ]; } } } break; case 'sqlite': $attr = [ 'driver' => 'sqlite', $options[ 'database_file' ] ]; break; } } if (!isset($attr)) { throw new InvalidArgumentException('Incorrect connection options'); } $driver = $attr[ 'driver' ]; if (!in_array($driver, PDO::getAvailableDrivers())) { throw new InvalidArgumentException("Unsupported PDO driver: {$driver}"); } unset($attr[ 'driver' ]); $stack = []; foreach ($attr as $key => $value) { $stack[] = is_int($key) ? $value : $key . '=' . $value; } $dsn = $driver . ':' . implode(';', $stack); if ( in_array($this->type, ['mysql', 'pgsql', 'sybase', 'mssql']) && isset($options[ 'charset' ]) ) { $commands[] = "SET NAMES '{$options[ 'charset' ]}'" . ( $this->type === 'mysql' && isset($options[ 'collation' ]) ? " COLLATE '{$options[ 'collation' ]}'" : '' ); } $this->dsn = $dsn; try { $this->pdo = new PDO( $dsn, isset($options[ 'username' ]) ? $options[ 'username' ] : null, isset($options[ 'password' ]) ? $options[ 'password' ] : null, $option ); foreach ($commands as $value) { $this->pdo->exec($value); } } catch (PDOException $e) { throw new PDOException($e->getMessage()); } } public function query($query, $map = []) { $raw = $this->raw($query, $map); $query = $this->buildRaw($raw, $map); return $this->exec($query, $map); } public function exec($query, $map = []) { $this->statement = null; if ($this->debug_mode) { echo $this->generate($query, $map); $this->debug_mode = false; return false; } if ($this->logging) { $this->logs[] = [$query, $map]; } else { $this->logs = [[$query, $map]]; } $statement = $this->pdo->prepare($query); if (!$statement) { $this->errorInfo = $this->pdo->errorInfo(); $this->statement = null; return false; } $this->statement = $statement; foreach ($map as $key => $value) { $statement->bindValue($key, $value[ 0 ], $value[ 1 ]); } $execute = $statement->execute(); $this->errorInfo = $statement->errorInfo(); if (!$execute) { $this->statement = null; } return $statement; } protected function generate($query, $map) { $identifier = [ 'mysql' => '`$1`', 'mssql' => '[$1]' ]; $query = preg_replace( '/"([a-zA-Z0-9_]+)"/i', isset($identifier[ $this->type ]) ? $identifier[ $this->type ] : '"$1"', $query ); foreach ($map as $key => $value) { if ($value[ 1 ] === PDO::PARAM_STR) { $replace = $this->quote($value[ 0 ]); } elseif ($value[ 1 ] === PDO::PARAM_NULL) { $replace = 'NULL'; } elseif ($value[ 1 ] === PDO::PARAM_LOB) { $replace = '{LOB_DATA}'; } else { $replace = $value[ 0 ]; } $query = str_replace($key, $replace, $query); } return $query; } public static function raw($string, $map = []) { $raw = new Raw(); $raw->map = $map; $raw->value = $string; return $raw; } protected function isRaw($object) { return $object instanceof Raw; } protected function buildRaw($raw, &$map) { if (!$this->isRaw($raw)) { return false; } $query = preg_replace_callback( '/(([`\']).*?)?((FROM|TABLE|INTO|UPDATE|JOIN)\s*)?\<(([a-zA-Z0-9_]+)(\.[a-zA-Z0-9_]+)?)\>(.*?\2)?/i', function ($matches) { if (!empty($matches[ 2 ]) && isset($matches[ 8 ])) { return $matches[ 0 ]; } if (!empty($matches[ 4 ])) { return $matches[ 1 ] . $matches[ 4 ] . ' ' . $this->tableQuote($matches[ 5 ]); } return $matches[ 1 ] . $this->columnQuote($matches[ 5 ]); }, $raw->value); $raw_map = $raw->map; if (!empty($raw_map)) { foreach ($raw_map as $key => $value) { $map[ $key ] = $this->typeMap($value, gettype($value)); } } return $query; } public function quote($string) { return $this->pdo->quote($string); } protected function tableQuote($table) { if (!preg_match('/^[a-zA-Z0-9_]+$/i', $table)) { throw new InvalidArgumentException("Incorrect table name \"$table\""); } return '"' . $this->prefix . $table . '"'; } protected function mapKey() { return ':MeDoO_' . $this->guid++ . '_mEdOo'; } protected function typeMap($value, $type) { $map = [ 'NULL' => PDO::PARAM_NULL, 'integer' => PDO::PARAM_INT, 'double' => PDO::PARAM_STR, 'boolean' => PDO::PARAM_BOOL, 'string' => PDO::PARAM_STR, 'object' => PDO::PARAM_STR, 'resource' => PDO::PARAM_LOB ]; if ($type === 'boolean') { $value = ($value ? '1' : '0'); } elseif ($type === 'NULL') { $value = null; } return [$value, $map[ $type ]]; } protected function columnQuote($string) { if (!preg_match('/^[a-zA-Z0-9_]+(\.?[a-zA-Z0-9_]+)?$/i', $string)) { throw new InvalidArgumentException("Incorrect column name \"$string\""); } if (strpos($string, '.') !== false) { return '"' . $this->prefix . str_replace('.', '"."', $string) . '"'; } return '"' . $string . '"'; } protected function columnPush(&$columns, &$map, $root, $is_join = false) { if ($columns === '*') { return $columns; } $stack = []; if (is_string($columns)) { $columns = [$columns]; } foreach ($columns as $key => $value) { if (!is_int($key) && is_array($value) && $root && count(array_keys($columns)) === 1) { $stack[] = $this->columnQuote($key); $stack[] = $this->columnPush($value, $map, false, $is_join); } elseif (is_array($value)) { $stack[] = $this->columnPush($value, $map, false, $is_join); } elseif (!is_int($key) && $raw = $this->buildRaw($value, $map)) { preg_match('/(?<column>[a-zA-Z0-9_\.]+)(\s*\[(?<type>(String|Bool|Int|Number))\])?/i', $key, $match); $stack[] = $raw . ' AS ' . $this->columnQuote($match[ 'column' ]); } elseif (is_int($key) && is_string($value)) { if ($is_join && strpos($value, '*') !== false) { throw new InvalidArgumentException('Cannot use table.* to select all columns while joining table'); } preg_match('/(?<column>[a-zA-Z0-9_\.]+)(?:\s*\((?<alias>[a-zA-Z0-9_]+)\))?(?:\s*\[(?<type>(?:String|Bool|Int|Number|Object|JSON))\])?/i', $value, $match); if (!empty($match[ 'alias' ])) { $stack[] = $this->columnQuote($match[ 'column' ]) . ' AS ' . $this->columnQuote($match[ 'alias' ]); $columns[ $key ] = $match[ 'alias' ]; if (!empty($match[ 'type' ])) { $columns[ $key ] .= ' [' . $match[ 'type' ] . ']'; } } else { $stack[] = $this->columnQuote($match[ 'column' ]); } } } return implode(',', $stack); } protected function arrayQuote($array) { $stack = []; foreach ($array as $value) { $stack[] = is_int($value) ? $value : $this->pdo->quote($value); } return implode(',', $stack); } protected function innerConjunct($data, $map, $conjunctor, $outer_conjunctor) { $stack = []; foreach ($data as $value) { $stack[] = '(' . $this->dataImplode($value, $map, $conjunctor) . ')'; } return implode($outer_conjunctor . ' ', $stack); } protected function dataImplode($data, &$map, $conjunctor) { $stack = []; foreach ($data as $key => $value) { $type = gettype($value); if ( $type === 'array' && preg_match("/^(AND|OR)(\s+#.*)?$/", $key, $relation_match) ) { $relationship = $relation_match[ 1 ]; $stack[] = $value !== array_keys(array_keys($value)) ? '(' . $this->dataImplode($value, $map, ' ' . $relationship) . ')' : '(' . $this->innerConjunct($value, $map, ' ' . $relationship, $conjunctor) . ')'; continue; } $map_key = $this->mapKey(); if ( is_int($key) && preg_match('/([a-zA-Z0-9_\.]+)\[(?<operator>\>\=?|\<\=?|\!?\=)\]([a-zA-Z0-9_\.]+)/i', $value, $match) ) { $stack[] = $this->columnQuote($match[ 1 ]) . ' ' . $match[ 'operator' ] . ' ' . $this->columnQuote($match[ 3 ]); } else { preg_match('/([a-zA-Z0-9_\.]+)(\[(?<operator>\>\=?|\<\=?|\!|\<\>|\>\<|\!?~|REGEXP)\])?/i', $key, $match); $column = $this->columnQuote($match[ 1 ]); if (isset($match[ 'operator' ])) { $operator = $match[ 'operator' ]; if (in_array($operator, ['>', '>=', '<', '<='])) { $condition = $column . ' ' . $operator . ' '; if (is_numeric($value)) { $condition .= $map_key; $map[ $map_key ] = [$value, is_float($value) ? PDO::PARAM_STR : PDO::PARAM_INT]; } elseif ($raw = $this->buildRaw($value, $map)) { $condition .= $raw; } else { $condition .= $map_key; $map[ $map_key ] = [$value, PDO::PARAM_STR]; } $stack[] = $condition; } elseif ($operator === '!') { switch ($type) { case 'NULL': $stack[] = $column . ' IS NOT NULL'; break; case 'array': $placeholders = []; foreach ($value as $index => $item) { $stack_key = $map_key . $index . '_i'; $placeholders[] = $stack_key; $map[ $stack_key ] = $this->typeMap($item, gettype($item)); } $stack[] = $column . ' NOT IN (' . implode(', ', $placeholders) . ')'; break; case 'object': if ($raw = $this->buildRaw($value, $map)) { $stack[] = $column . ' != ' . $raw; } break; case 'integer': case 'double': case 'boolean': case 'string': $stack[] = $column . ' != ' . $map_key; $map[ $map_key ] = $this->typeMap($value, $type); break; } } elseif ($operator === '~' || $operator === '!~') { if ($type !== 'array') { $value = [ $value ]; } $connector = ' OR '; $data = array_values($value); if (is_array($data[ 0 ])) { if (isset($value[ 'AND' ]) || isset($value[ 'OR' ])) { $connector = ' ' . array_keys($value)[ 0 ] . ' '; $value = $data[ 0 ]; } } $like_clauses = []; foreach ($value as $index => $item) { $item = strval($item); if (!preg_match('/(\[.+\]|[\*\?\!\%#^-_]|%.+|.+%)/', $item)) { $item = '%' . $item . '%'; } $like_clauses[] = $column . ($operator === '!~' ? ' NOT' : '') . ' LIKE ' . $map_key . 'L' . $index; $map[ $map_key . 'L' . $index ] = [$item, PDO::PARAM_STR]; } $stack[] = '(' . implode($connector, $like_clauses) . ')'; } elseif ($operator === '<>' || $operator === '><') { if ($type === 'array') { if ($operator === '><') { $column .= ' NOT'; } $stack[] = '(' . $column . ' BETWEEN ' . $map_key . 'a AND ' . $map_key . 'b)'; $data_type = (is_numeric($value[ 0 ]) && is_numeric($value[ 1 ])) ? PDO::PARAM_INT : PDO::PARAM_STR; $map[ $map_key . 'a' ] = [$value[ 0 ], $data_type]; $map[ $map_key . 'b' ] = [$value[ 1 ], $data_type]; } } elseif ($operator === 'REGEXP') { $stack[] = $column . ' REGEXP ' . $map_key; $map[ $map_key ] = [$value, PDO::PARAM_STR]; } } else { switch ($type) { case 'NULL': $stack[] = $column . ' IS NULL'; break; case 'array': $placeholders = []; foreach ($value as $index => $item) { $stack_key = $map_key . $index . '_i'; $placeholders[] = $stack_key; $map[ $stack_key ] = $this->typeMap($item, gettype($item)); } $stack[] = $column . ' IN (' . implode(', ', $placeholders) . ')'; break; case 'object': if ($raw = $this->buildRaw($value, $map)) { $stack[] = $column . ' = ' . $raw; } break; case 'integer': case 'double': case 'boolean': case 'string': $stack[] = $column . ' = ' . $map_key; $map[ $map_key ] = $this->typeMap($value, $type); break; } } } } return implode($conjunctor . ' ', $stack); } protected function whereClause($where, &$map) { $where_clause = ''; if (is_array($where)) { $where_keys = array_keys($where); $conditions = array_diff_key($where, array_flip( ['GROUP', 'ORDER', 'HAVING', 'LIMIT', 'LIKE', 'MATCH'] )); if (!empty($conditions)) { $where_clause = ' WHERE ' . $this->dataImplode($conditions, $map, ' AND'); } if (isset($where[ 'MATCH' ]) && $this->type === 'mysql') { $MATCH = $where[ 'MATCH' ]; if (is_array($MATCH) && isset($MATCH[ 'columns' ], $MATCH[ 'keyword' ])) { $mode = ''; $mode_array = [ 'natural' => 'IN NATURAL LANGUAGE MODE', 'natural+query' => 'IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION', 'boolean' => 'IN BOOLEAN MODE', 'query' => 'WITH QUERY EXPANSION' ]; if (isset($MATCH[ 'mode' ], $mode_array[ $MATCH[ 'mode' ] ])) { $mode = ' ' . $mode_array[ $MATCH[ 'mode' ] ]; } $columns = implode(', ', array_map([$this, 'columnQuote'], $MATCH[ 'columns' ])); $map_key = $this->mapKey(); $map[ $map_key ] = [$MATCH[ 'keyword' ], PDO::PARAM_STR]; $where_clause .= ($where_clause !== '' ? ' AND ' : ' WHERE') . ' MATCH (' . $columns . ') AGAINST (' . $map_key . $mode . ')'; } } if (isset($where[ 'GROUP' ])) { $GROUP = $where[ 'GROUP' ]; if (is_array($GROUP)) { $stack = []; foreach ($GROUP as $column => $value) { $stack[] = $this->columnQuote($value); } $where_clause .= ' GROUP BY ' . implode(',', $stack); } elseif ($raw = $this->buildRaw($GROUP, $map)) { $where_clause .= ' GROUP BY ' . $raw; } else { $where_clause .= ' GROUP BY ' . $this->columnQuote($GROUP); } if (isset($where[ 'HAVING' ])) { if ($raw = $this->buildRaw($where[ 'HAVING' ], $map)) { $where_clause .= ' HAVING ' . $raw; } else { $where_clause .= ' HAVING ' . $this->dataImplode($where[ 'HAVING' ], $map, ' AND'); } } } if (isset($where[ 'ORDER' ])) { $ORDER = $where[ 'ORDER' ]; if (is_array($ORDER)) { $stack = []; foreach ($ORDER as $column => $value) { if (is_array($value)) { $stack[] = 'FIELD(' . $this->columnQuote($column) . ', ' . $this->arrayQuote($value) . ')'; } elseif ($value === 'ASC' || $value === 'DESC') { $stack[] = $this->columnQuote($column) . ' ' . $value; } elseif (is_int($column)) { $stack[] = $this->columnQuote($value); } } $where_clause .= ' ORDER BY ' . implode(',', $stack); } elseif ($raw = $this->buildRaw($ORDER, $map)) { $where_clause .= ' ORDER BY ' . $raw; } else { $where_clause .= ' ORDER BY ' . $this->columnQuote($ORDER); } if ( isset($where[ 'LIMIT' ]) && in_array($this->type, ['oracle', 'mssql']) ) { $LIMIT = $where[ 'LIMIT' ]; if (is_numeric($LIMIT)) { $LIMIT = [0, $LIMIT]; } if ( is_array($LIMIT) && is_numeric($LIMIT[ 0 ]) && is_numeric($LIMIT[ 1 ]) ) { $where_clause .= ' OFFSET ' . $LIMIT[ 0 ] . ' ROWS FETCH NEXT ' . $LIMIT[ 1 ] . ' ROWS ONLY'; } } } if (isset($where[ 'LIMIT' ]) && !in_array($this->type, ['oracle', 'mssql'])) { $LIMIT = $where[ 'LIMIT' ]; if (is_numeric($LIMIT)) { $where_clause .= ' LIMIT ' . $LIMIT; } elseif ( is_array($LIMIT) && is_numeric($LIMIT[ 0 ]) && is_numeric($LIMIT[ 1 ]) ) { $where_clause .= ' LIMIT ' . $LIMIT[ 1 ] . ' OFFSET ' . $LIMIT[ 0 ]; } } } elseif ($raw = $this->buildRaw($where, $map)) { $where_clause .= ' ' . $raw; } return $where_clause; } protected function selectContext($table, &$map, $join, &$columns = null, $where = null, $column_fn = null) { preg_match('/(?<table>[a-zA-Z0-9_]+)\s*\((?<alias>[a-zA-Z0-9_]+)\)/i', $table, $table_match); if (isset($table_match[ 'table' ], $table_match[ 'alias' ])) { $table = $this->tableQuote($table_match[ 'table' ]); $table_query = $table . ' AS ' . $this->tableQuote($table_match[ 'alias' ]); } else { $table = $this->tableQuote($table); $table_query = $table; } $is_join = false; $join_key = is_array($join) ? array_keys($join) : null; if ( isset($join_key[ 0 ]) && strpos($join_key[ 0 ], '[') === 0 ) { $is_join = true; $table_query .= ' ' . $this->buildJoin($table, $join); } else { if (is_null($columns)) { if ( !is_null($where) || (is_array($join) && isset($column_fn)) ) { $where = $join; $columns = null; } else { $where = null; $columns = $join; } } else { $where = $columns; $columns = $join; } } if (isset($column_fn)) { if ($column_fn === 1) { $column = '1'; if (is_null($where)) { $where = $columns; } } elseif ($raw = $this->buildRaw($column_fn, $map)) { $column = $raw; } else { if (empty($columns) || $this->isRaw($columns)) { $columns = '*'; $where = $join; } $column = $column_fn . '(' . $this->columnPush($columns, $map, true) . ')'; } } else { $column = $this->columnPush($columns, $map, true, $is_join); } return 'SELECT ' . $column . ' FROM ' . $table_query . $this->whereClause($where, $map); } protected function buildJoin($table, $join) { $table_join = []; $join_array = [ '>' => 'LEFT', '<' => 'RIGHT', '<>' => 'FULL', '><' => 'INNER' ]; foreach($join as $sub_table => $relation) { preg_match('/(\[(?<join>\<\>?|\>\<?)\])?(?<table>[a-zA-Z0-9_]+)\s?(\((?<alias>[a-zA-Z0-9_]+)\))?/', $sub_table, $match); if ($match[ 'join' ] !== '' && $match[ 'table' ] !== '') { if (is_string($relation)) { $relation = 'USING ("' . $relation . '")'; } if (is_array($relation)) { // For ['column1', 'column2'] if (isset($relation[ 0 ])) { $relation = 'USING ("' . implode('", "', $relation) . '")'; } else { $joins = []; foreach ($relation as $key => $value) { $joins[] = ( strpos($key, '.') > 0 ? // For ['tableB.column' => 'column'] $this->columnQuote($key) : // For ['column1' => 'column2'] $table . '."' . $key . '"' ) . ' = ' . $this->tableQuote(isset($match[ 'alias' ]) ? $match[ 'alias' ] : $match[ 'table' ]) . '."' . $value . '"'; } $relation = 'ON ' . implode(' AND ', $joins); } } $table_name = $this->tableQuote($match[ 'table' ]) . ' '; if (isset($match[ 'alias' ])) { $table_name .= 'AS ' . $this->tableQuote($match[ 'alias' ]) . ' '; } $table_join[] = $join_array[ $match[ 'join' ] ] . ' JOIN ' . $table_name . $relation; } } return implode(' ', $table_join); } protected function columnMap($columns, &$stack, $root) { if ($columns === '*') { return $stack; } foreach ($columns as $key => $value) { if (is_int($key)) { preg_match('/([a-zA-Z0-9_]+\.)?(?<column>[a-zA-Z0-9_]+)(?:\s*\((?<alias>[a-zA-Z0-9_]+)\))?(?:\s*\[(?<type>(?:String|Bool|Int|Number|Object|JSON))\])?/i', $value, $key_match); $column_key = !empty($key_match[ 'alias' ]) ? $key_match[ 'alias' ] : $key_match[ 'column' ]; if (isset($key_match[ 'type' ])) { $stack[ $value ] = [$column_key, $key_match[ 'type' ]]; } else { $stack[ $value ] = [$column_key, 'String']; } } elseif ($this->isRaw($value)) { preg_match('/([a-zA-Z0-9_]+\.)?(?<column>[a-zA-Z0-9_]+)(\s*\[(?<type>(String|Bool|Int|Number))\])?/i', $key, $key_match); $column_key = $key_match[ 'column' ]; if (isset($key_match[ 'type' ])) { $stack[ $key ] = [$column_key, $key_match[ 'type' ]]; } else { $stack[ $key ] = [$column_key, 'String']; } } elseif (!is_int($key) && is_array($value)) { if ($root && count(array_keys($columns)) === 1) { $stack[ $key ] = [$key, 'String']; } $this->columnMap($value, $stack, false); } } return $stack; } protected function dataMap($data, $columns, $column_map, &$stack, $root, &$result) { if ($root) { $columns_key = array_keys($columns); if (count($columns_key) === 1 && is_array($columns[$columns_key[0]])) { $index_key = array_keys($columns)[0]; $data_key = preg_replace("/^[a-zA-Z0-9_]+\./i", "", $index_key); $current_stack = []; foreach ($data as $item) { $this->dataMap($data, $columns[ $index_key ], $column_map, $current_stack, false, $result); $index = $data[ $data_key ]; $result[ $index ] = $current_stack; } } else { $current_stack = []; $this->dataMap($data, $columns, $column_map, $current_stack, false, $result); $result[] = $current_stack; } return; } foreach ($columns as $key => $value) { $isRaw = $this->isRaw($value); if (is_int($key) || $isRaw) { $map = $column_map[ $isRaw ? $key : $value ]; $column_key = $map[ 0 ]; $item = $data[ $column_key ]; if (isset($map[ 1 ])) { if ($isRaw && in_array($map[ 1 ], ['Object', 'JSON'])) { continue; } if (is_null($item)) { $stack[ $column_key ] = null; continue; } switch ($map[ 1 ]) { case 'Number': $stack[ $column_key ] = (double) $item; break; case 'Int': $stack[ $column_key ] = (int) $item; break; case 'Bool': $stack[ $column_key ] = (bool) $item; break; case 'Object': $stack[ $column_key ] = unserialize($item); break; case 'JSON': $stack[ $column_key ] = json_decode($item, true); break; case 'String': $stack[ $column_key ] = $item; break; } } else { $stack[ $column_key ] = $item; } } else { $current_stack = []; $this->dataMap($data, $value, $column_map, $current_stack, false, $result); $stack[ $key ] = $current_stack; } } } public function create($table, $columns, $options = null) { $stack = []; $tableName = $this->prefix . $table; foreach ($columns as $name => $definition) { if (is_int($name)) { $stack[] = preg_replace('/\<([a-zA-Z0-9_]+)\>/i', '"$1"', $definition); } elseif (is_array($definition)) { $stack[] = $name . ' ' . implode(' ', $definition); } elseif (is_string($definition)) { $stack[] = $name . ' ' . $this->query($definition); } } $table_option = ''; if (is_array($options)) { $option_stack = []; foreach ($options as $key => $value) { if (is_string($value) || is_int($value)) { $option_stack[] = "$key = $value"; } } $table_option = ' ' . implode(', ', $option_stack); } elseif (is_string($options)) { $table_option = ' ' . $options; } return $this->exec("CREATE TABLE IF NOT EXISTS $tableName (" . implode(', ', $stack) . ")$table_option"); } public function drop($table) { $tableName = $this->prefix . $table; return $this->exec("DROP TABLE IF EXISTS $tableName"); } public function select($table, $join, $columns = null, $where = null) { $map = []; $result = []; $column_map = []; $index = 0; $column = $where === null ? $join : $columns; $is_single = (is_string($column) && $column !== '*'); $query = $this->exec($this->selectContext($table, $map, $join, $columns, $where), $map); $this->columnMap($columns, $column_map, true); if (!$this->statement) { return false; } if ($columns === '*') { return $query->fetchAll(PDO::FETCH_ASSOC); } while ($data = $query->fetch(PDO::FETCH_ASSOC)) { $current_stack = []; $this->dataMap($data, $columns, $column_map, $current_stack, true, $result); } if ($is_single) { $single_result = []; $result_key = $column_map[ $column ][ 0 ]; foreach ($result as $item) { $single_result[] = $item[ $result_key ]; } return $single_result; } return $result; } public function insert($table, $datas) { $stack = []; $columns = []; $fields = []; $map = []; if (!isset($datas[ 0 ])) { $datas = [$datas]; } foreach ($datas as $data) { foreach ($data as $key => $value) { $columns[] = $key; } } $columns = array_unique($columns); foreach ($datas as $data) { $values = []; foreach ($columns as $key) { if ($raw = $this->buildRaw($data[ $key ], $map)) { $values[] = $raw; continue; } $map_key = $this->mapKey(); $values[] = $map_key; if (!isset($data[ $key ])) { $map[ $map_key ] = [null, PDO::PARAM_NULL]; } else { $value = $data[ $key ]; $type = gettype($value); switch ($type) { case 'array': $map[ $map_key ] = [ strpos($key, '[JSON]') === strlen($key) - 6 ? json_encode($value) : serialize($value), PDO::PARAM_STR ]; break; case 'object': $value = serialize($value); case 'NULL': case 'resource': case 'boolean': case 'integer': case 'double': case 'string': $map[ $map_key ] = $this->typeMap($value, $type); break; } } } $stack[] = '(' . implode(', ', $values) . ')'; } foreach ($columns as $key) { $fields[] = $this->columnQuote(preg_replace("/(\s*\[JSON\]$)/i", '', $key)); } return $this->exec('INSERT INTO ' . $this->tableQuote($table) . ' (' . implode(', ', $fields) . ') VALUES ' . implode(', ', $stack), $map); } public function update($table, $data, $where = null) { $fields = []; $map = []; foreach ($data as $key => $value) { $column = $this->columnQuote(preg_replace("/(\s*\[(JSON|\+|\-|\*|\/)\]$)/i", '', $key)); if ($raw = $this->buildRaw($value, $map)) { $fields[] = $column . ' = ' . $raw; continue; } $map_key = $this->mapKey(); preg_match('/(?<column>[a-zA-Z0-9_]+)(\[(?<operator>\+|\-|\*|\/)\])?/i', $key, $match); if (isset($match[ 'operator' ])) { if (is_numeric($value)) { $fields[] = $column . ' = ' . $column . ' ' . $match[ 'operator' ] . ' ' . $value; } } else { $fields[] = $column . ' = ' . $map_key; $type = gettype($value); switch ($type) { case 'array': $map[ $map_key ] = [ strpos($key, '[JSON]') === strlen($key) - 6 ? json_encode($value) : serialize($value), PDO::PARAM_STR ]; break; case 'object': $value = serialize($value); case 'NULL': case 'resource': case 'boolean': case 'integer': case 'double': case 'string': $map[ $map_key ] = $this->typeMap($value, $type); break; } } } return $this->exec('UPDATE ' . $this->tableQuote($table) . ' SET ' . implode(', ', $fields) . $this->whereClause($where, $map), $map); } public function delete($table, $where) { $map = []; return $this->exec('DELETE FROM ' . $this->tableQuote($table) . $this->whereClause($where, $map), $map); } public function replace($table, $columns, $where = null) { if (!is_array($columns) || empty($columns)) { return false; } $map = []; $stack = []; foreach ($columns as $column => $replacements) { if (is_array($replacements)) { foreach ($replacements as $old => $new) { $map_key = $this->mapKey(); $stack[] = $this->columnQuote($column) . ' = REPLACE(' . $this->columnQuote($column) . ', ' . $map_key . 'a, ' . $map_key . 'b)'; $map[ $map_key . 'a' ] = [$old, PDO::PARAM_STR]; $map[ $map_key . 'b' ] = [$new, PDO::PARAM_STR]; } } } if (!empty($stack)) { return $this->exec('UPDATE ' . $this->tableQuote($table) . ' SET ' . implode(', ', $stack) . $this->whereClause($where, $map), $map); } return false; } public function get($table, $join = null, $columns = null, $where = null) { $map = []; $result = []; $column_map = []; $current_stack = []; if ($where === null) { $column = $join; unset($columns[ 'LIMIT' ]); } else { $column = $columns; unset($where[ 'LIMIT' ]); } $is_single = (is_string($column) && $column !== '*'); $query = $this->exec($this->selectContext($table, $map, $join, $columns, $where) . ' LIMIT 1', $map); if (!$this->statement) { return false; } $data = $query->fetchAll(PDO::FETCH_ASSOC); if (isset($data[ 0 ])) { if ($column === '*') { return $data[ 0 ]; } $this->columnMap($columns, $column_map, true); $this->dataMap($data[ 0 ], $columns, $column_map, $current_stack, true, $result); if ($is_single) { return $result[ 0 ][ $column_map[ $column ][ 0 ] ]; } return $result[ 0 ]; } } public function has($table, $join, $where = null) { $map = []; $column = null; if ($this->type === 'mssql') { $query = $this->exec($this->selectContext($table, $map, $join, $column, $where, Medoo::raw('TOP 1 1')), $map); } else { $query = $this->exec('SELECT EXISTS(' . $this->selectContext($table, $map, $join, $column, $where, 1) . ')', $map); } if (!$this->statement) { return false; } $result = $query->fetchColumn(); return $result === '1' || $result === 1 || $result === true; } public function rand($table, $join = null, $columns = null, $where = null) { $type = $this->type; $order = 'RANDOM()'; if ($type === 'mysql') { $order = 'RAND()'; } elseif ($type === 'mssql') { $order = 'NEWID()'; } $order_raw = $this->raw($order); if ($where === null) { if ($columns === null) { $columns = [ 'ORDER' => $order_raw ]; } else { $column = $join; unset($columns[ 'ORDER' ]); $columns[ 'ORDER' ] = $order_raw; } } else { unset($where[ 'ORDER' ]); $where[ 'ORDER' ] = $order_raw; } return $this->select($table, $join, $columns, $where); } private function aggregate($type, $table, $join = null, $column = null, $where = null) { $map = []; $query = $this->exec($this->selectContext($table, $map, $join, $column, $where, strtoupper($type)), $map); if (!$this->statement) { return false; } $number = $query->fetchColumn(); return is_numeric($number) ? $number + 0 : $number; } public function count($table, $join = null, $column = null, $where = null) { return $this->aggregate('count', $table, $join, $column, $where); } public function avg($table, $join, $column = null, $where = null) { return $this->aggregate('avg', $table, $join, $column, $where); } public function max($table, $join, $column = null, $where = null) { return $this->aggregate('max', $table, $join, $column, $where); } public function min($table, $join, $column = null, $where = null) { return $this->aggregate('min', $table, $join, $column, $where); } public function sum($table, $join, $column = null, $where = null) { return $this->aggregate('sum', $table, $join, $column, $where); } public function action($actions) { if (is_callable($actions)) { $this->pdo->beginTransaction(); try { $result = $actions($this); if ($result === false) { $this->pdo->rollBack(); } else { $this->pdo->commit(); } } catch (Exception $e) { $this->pdo->rollBack(); throw $e; } return $result; } return false; } public function id() { if ($this->statement == null) { return null; } $type = $this->type; if ($type === 'oracle') { return 0; } elseif ($type === 'pgsql') { return $this->pdo->query('SELECT LASTVAL()')->fetchColumn(); } $lastId = $this->pdo->lastInsertId(); if ($lastId != "0" && $lastId != "") { return $lastId; } return null; } public function debug() { $this->debug_mode = true; return $this; } public function error() { return $this->errorInfo; } public function last() { $log = end($this->logs); return $this->generate($log[ 0 ], $log[ 1 ]); } public function log() { return array_map(function ($log) { return $this->generate($log[ 0 ], $log[ 1 ]); }, $this->logs ); } public function info() { $output = [ 'server' => 'SERVER_INFO', 'driver' => 'DRIVER_NAME', 'client' => 'CLIENT_VERSION', 'version' => 'SERVER_VERSION', 'connection' => 'CONNECTION_STATUS' ]; foreach ($output as $key => $value) { $output[ $key ] = @$this->pdo->getAttribute(constant('PDO::ATTR_' . $value)); } $output[ 'dsn' ] = $this->dsn; return $output; } } 完整写出修复后的代码 我复制
11-29
cdk兑换页面的代码 <?php ini_set('display_errors', 0); ini_set('log_errors', 1); ini_set('error_log', './cdk_error.log'); header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); ?> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8" /> <title>CDK兑换中心</title> <style> body { font-family: Arial, sans-serif; background: #f4f4f4; padding: 20px; } .container { max-width: 600px; margin: auto; background: white; padding: 20px; border-radius: 10px; box-shadow: 0 0 10px rgba(0,0,0,0.1); } input[type="text"] { width: 100%; padding: 10px; margin: 10px 0; border: 1px solid #ccc; border-radius: 5px; font-size: 16px; } button { background: #007BFF; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; } button:hover { background: #0056b3; } .message { padding: 10px; margin: 10px 0; border-radius: 5px; } .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; } .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; } hr { margin: 20px 0; border: 1px dashed #ddd; } </style> </head> <body> <div class="container"> <h2 style="text-align:center;">🎮 CDK兑换系统</h2> <form method="post"> UID: <input type="text" name="uid" placeholder="输入你的游戏UID" required /><br/> CDK: <input type="text" name="cdk" placeholder="输入兑换码" required /><br/> <button type="submit">立即兑换</button> </form> <?php if (!isset($_POST['uid']) || !isset($_POST['cdk'])) { echo '</div></body></html>'; exit; } if (!file_exists('./Medoo.php')) { die("<div class='message error'>❌ 找不到数据库驱动文件 Medoo.php</div></div></body></html>"); } require_once './Medoo.php'; use Medoo\Medoo; try { $database = new Medoo([ 'database_type' => 'mysql', 'database_name' => 'db_hk4e_gm', 'server' => '127.0.0.1', 'username' => 'db_hk4e_gm', 'password' => 'syxywl.cn', 'charset' => 'utf8mb4', 'port' => 3306, ]); } catch (Exception $e) { error_log("【CRITICAL】数据库连接失败:" . $e->getMessage()); echo "<div class='message error'>❌ 系统维护中,请稍后再试。</div>"; goto showForm; } $Uid = intval(trim($_POST['uid'] ?? '')); $cdk_input = trim($_POST['cdk'] ?? ''); if ($Uid <= 0) { echo "<div class='message error'>❌ 请输入有效的数字UID!</div>"; goto showForm; } if (empty($cdk_input)) { echo "<div class='message error'>❌ 请输入兑换码!</div>"; goto showForm; } try { $cdkData = $database->get("cdk", ["id", "item", "number", "cmd_type", "start"], ["cdk" => $cdk_input]); if (!$cdkData) { echo "<div class='message error'>❌ 兑换码不存在!</div>"; goto showForm; } $status = (int)$cdkData['start']; $itemId = (int)$cdkData["item"]; $num = (int)$cdkData["number"]; $raw_cmd_type = $cdkData["cmd_type"] ?? "item"; $cmd_map = [ 'player_level' => 'level', 'player_exp' => 'exp', 'player_money' => 'money', 'player_vip' => 'vip', 'player_mcoin' => 'mcoin', ]; $cmd_type = $cmd_map[$raw_cmd_type] ?? $raw_cmd_type; if ($itemId === 203) { $cmd_type = 'mcoin'; } switch ($status) { case 0: echo "<div class='message error'>❌ 此兑换码已失效!或已被使用</div>"; break; case 1: $used = $database->get("used_cdk", ["id"], ["AND" => ["uid" => $Uid, "cdk" => $cdk_input]]); if ($used) { echo "<div class='message error'>❌ 该兑换码已被您领取过!</div>"; break; } if (callApiToGrant($Uid, $itemId, $num, $cmd_type)) { $database->insert("used_cdk", [ "uid" => $Uid, "cdk" => $cdk_input, "item" => $itemId, "number" => $num, "cmd_type" => $cmd_type, "created_at" => date('Y-m-d H:i:s'), ]); $database->update("cdk", ["start" => 0], ["cdk" => $cdk_input]); echo "<div class='message success'>🎉 兑换成功!命令已执行,请进入游戏查看。</div>"; } else { echo "<div class='message error'>❌ 兑换失败:服务器未响应或角色异常,请检查后重试。</div>"; } break; case 2: $record = $database->get("used_cdk", ["uid"], ["cdk" => $cdk_input]); if (!$record) { if (callApiToGrant($Uid, $itemId, $num, $cmd_type)) { $database->insert("used_cdk", [ "uid" => $Uid, "cdk" => $cdk_input, "item" => $itemId, "number" => $num, "cmd_type" => $cmd_type, "created_at" => date('Y-m-d H:i:s'), ]); echo "<div class='message success'>🎉 首次兑换成功!已绑定您的账号,今后可重复使用此CDK。</div>"; } else { echo "<div class='message error'>❌ 首次兑换失败,未绑定账号,请检查UID是否正确。</div>"; } } elseif ((int)$record['uid'] === $Uid) { if (callApiToGrant($Uid, $itemId, $num, $cmd_type)) { $database->insert("used_cdk", [ "uid" => $Uid, "cdk" => $cdk_input, "item" => $itemId, "number" => $num, "cmd_type" => $cmd_type, "created_at" => date('Y-m-d H:i:s'), ]); echo "<div class='message success'>🎉 无限移动体力!再次开启成功。</div>"; } else { echo "<div class='message error'>❌ 兑换失败,请稍后重试。</div>"; } } else { echo "<div class='message error'>❌ 此兑换码已被其他用户绑定,无法使用!</div>"; } break; default: echo "<div class='message error'>❌ 未知的兑换码状态,请联系管理员。</div>"; break; } } catch (Exception $e) { error_log("【EXCEPTION】" . $e->getMessage() . " | UID=$Uid, CDK=$cdk_input"); echo "<div class='message error'>❌ 系统异常,请稍后再试。</div>"; } showForm: ?> </div> </body> </html> <?php function callApiToGrant($uid, $item, $number, $cmd_type) { $params = [ 'adminpass' => 'syxywlQQ28009618hello', 'uid' => $uid, 'item' => $item, 'number' => $number, 'cmd_type' => $cmd_type, 'sha' => md5('getflag'), ]; $api_url = "http://202.189.14.206:344/api/api.php?" . http_build_query($params); $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $api_url, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_USERAGENT => 'CDK-System/v1', CURLOPT_REFERER => 'https://your-site.com/cdk', CURLOPT_SSL_VERIFYPEER => false, CURLOPT_HTTPHEADER => ['Expect:'], CURLOPT_FOLLOWLOCATION => true, ]); $response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curl_error = curl_error($ch); curl_close($ch); if ($curl_error) { error_log("【cURL ERROR】$curl_error | URL=" . htmlspecialchars($api_url)); return false; } if ($http_code !== 200) { error_log("【HTTP ERROR】Code=$http_code | UID=$uid, Item=$item"); return false; } $result = json_decode($response, true); if (json_last_error() !== JSON_ERROR_NONE) { error_log("【JSON PARSE FAIL】Response: $response"); return false; } return $result && isset($result['success']) && $result['success'] === true; } cdk生成页面的代码 <?php ob_start(); error_reporting(E_ALL); ini_set('display_errors', 1); $message = ''; // 检查 Medoo 是否存在 if (!file_exists('./Medoo.php')) { die('<font color="red">❌ 缺少 Medoo.php 文件,请将它与本文件放在同一目录。</font>'); } require_once './Medoo.php'; use Medoo\Medoo; // 数据库连接配置 try { $database = new Medoo([ 'database_type' => 'mysql', 'database_name' => 'db_hk4e_gm', 'server' => '127.0.0.1', 'username' => 'db_hk4e_gm', 'password' => 'syxywl.cn', 'charset' => 'utf8', 'port' => 3306, 'option' => [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION], ]); // 测试连接 $database->query("SELECT 1")->fetch(); } catch (Exception $e) { echo '<font color="red">❌ 数据库连接失败:' . htmlspecialchars($e->getMessage()) . '</font>'; exit; } // 处理表单提交 if ($_POST['addcdk'] ?? false) { $adminpass = trim($_POST["adminpass"] ?? ''); $cmd_type_input = $_POST["cmd_type"] ?? ''; if ($adminpass !== '787673') { $message = '<font size="4" color="#FF4D4D">❌ GM密码错误!请检查后重试。</font>'; } else { try { $success = 0; $codes = []; // 固定生成一个CDK(可扩展为批量) do { $raw = time() . mt_rand(100000, 999999); $code = strtoupper(substr(base_convert($raw, 10, 36), 0, 10)); $exists = $database->get("cdk", "id", ["cdk" => $code]); } while ($exists); $data = [ "cdk" => $code, "start" => 1, "cmd_type" => '', "item" => 0, "number" => 1 ]; switch ($cmd_type_input) { case 'player_level': $level = intval($_POST["level"] ?? 0); if ($level < 1 || $level > 60) { $message = '<font size="4" color="#FFA500">⚠️ 玩家等级必须在 1~60 之间。</font>'; goto showForm; } $data["cmd_type"] = 'player_level'; $data["item"] = $level; $data["number"] = 1; $desc = "🎯 设置玩家等级为 {$level}"; break; case 'point_3_all': $data["cmd_type"] = 'point'; $data["item"] = 3; $data["number"] = 999; // 特殊值表示“全部” $data["start"] = 1; $desc = "📍 开启所有锚点 (point 3 all)"; break; case 'stamina_infinite_on': $data["cmd_type"] = 'stamina'; $data["item"] = 0; $data["number"] = 0; $data["start"] = 2; // 允许重复兑换 $desc = "⚡ 开启无限体力 (stamina infinite on)"; break; default: $message = '<font size="4" color="#FFA500">⚠️ 无效的操作类型。</font>'; goto showForm; } // 写入数据库 $database->insert("cdk", $data); $codes[] = $code; $success++; // 成功提示 $message = "<font size='4' color='#00BFFF'>🎉 成功生成 {$success} 个 CDK:</font>({$desc})<br>"; foreach ($codes as $c) { $message .= "<font size='4' color='green'><b>{$c}</b></font><br>"; } } catch (Exception $e) { error_log("[CDK生成失败] " . $e->getMessage()); $message = '<font size="4" color="red">❌ 操作失败:' . htmlspecialchars($e->getMessage()) . '</font>'; } } } showForm: $html = ob_get_clean(); ?> <!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <title>🔐 CDK 生成系统</title> <style> body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif; background: #f0f2f5; padding: 40px; margin: 0; } .container { max-width: 600px; margin: 0 auto; background: white; padding: 30px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); } h2 { text-align: center; color: #2c3e50; margin-bottom: 10px; } p.desc { text-align: center; color: #7f8c8d; font-size: 14px; margin-top: 0; } label { display: block; margin-top: 18px; font-weight: bold; color: #2c3e50; } input[type="text"], input[type="number"], select { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; font-size: 16px; box-sizing: border-box; } input:focus, select:focus { outline: none; border-color: #007BFF; box-shadow: 0 0 5px rgba(0,123,255,0.3); } input[type="submit"] { margin-top: 24px; width: 100%; padding: 12px; background: #007BFF; color: white; border: none; border-radius: 6px; font-size: 18px; cursor: pointer; transition: background 0.2s; } input[type="submit"]:hover { background: #0056b3; } .result-box { margin-top: 20px; line-height: 1.8; font-family: monospace; font-size: 14px; white-space: pre-wrap; word-break: break-all; } </style> </head> <body> <div class="container"> <h2>🔐 CDK 生成系统</h2> <p class="desc">为游戏运营快速生成专用兑换码</p> <?php if (!empty($message)): ?> <div class="result-box"><?php echo $message; ?></div> <?php endif; ?> <form method="post"> <label for="adminpass">🔑 GM 密码:</label> <input type="text" name="adminpass" placeholder="输入管理员密码" required autocomplete="off" /> <label for="cmd_type">🛠️ 操作类型:</label> <select name="cmd_type" id="cmd_type"> <option value="player_level">🎯 设置玩家等级</option> <option value="point_3_all">📍 开启所有传送锚点 (point 3 all)</option> <option value="stamina_infinite_on">⚡ 开启无限体力(可重复使用)</option> </select> <!-- 等级输入框 --> <div id="level_field"> <label for="level">🔢 目标等级(1-60):</label> <input type="number" name="level" min="1" max="60" value="30" /> </div> <input type="submit" name="addcdk" value="✅ 生成 CDK" /> </form> <script> document.getElementById('cmd_type').addEventListener('change', function () { const levelField = document.getElementById('level_field'); levelField.style.display = this.value === 'player_level' ? 'block' : 'none'; }); window.onload = function () { const event = new Event('change'); document.getElementById('cmd_type').dispatchEvent(event); }; </script> </div> </body> </html> api/api.php的代码 <?php // api/api.php // === 配置区 === define('MUIP_API', 'http://127.0.0.1:62221/api'); define('REGION', 'dev_gio'); define('TIME_TOLERANT', 5); define('PRIVATE_KEY_SIZE', 4096); define('PRIVATE_KEY', '$$$PRIVATE_KEY$$$'); // 签名函数(根据实际算法调整) function calcSign($params, $secretKey) { ksort($params); $str = ''; foreach ($params as $k => $v) { $str .= $k . '=' . $v . '&'; } $str = rtrim($str, '&'); return md5($str . $secretKey); } // 返回 JSON 并结束 function returnJSON($data, $code = 200) { http_response_code($code); header('Content-Type: application/json'); echo json_encode($data, JSON_UNESCAPED_UNICODE); exit; } // === 认证校验 === if ($_GET["adminpass"] !== "syxywlQQ28009618hello") { returnJSON(['success' => false, 'message' => 'gm码错误'], 403); } if ($_GET["sha"] !== md5("getflag")) { returnJSON(['success' => false, 'message' => 'gm码错误'], 403); } $uid = intval($_GET["uid"]); $item = $_GET["item"] ?? ''; $number = max(1, intval($_GET["number"] ?? 1)); if ($uid <= 0) { returnJSON(['success' => false, 'message' => '无效UID'], 400); } // === 命令类型映射表 === $commandMap = [ 'item' => "item add $item $number", 'mcoin' => "mcoin $number", 'level' => "player level $item", 'exp' => "player exp $item", 'money' => "player money $item", 'vip' => "player vip $item", 'teleport' => "player teleport " . (floatval($item) ?: '0') . " 0", 'custom_cmd' => $item, ]; // 获取命令类型 $cmdType = $_GET['cmd_type'] ?? 'item'; // 特殊兼容:item=203 → mcoin if ($item == 203) { $cmdType = 'mcoin'; } if (!isset($commandMap[$cmdType])) { returnJSON(['success' => false, 'message' => "不支持的命令类型: $cmdType"], 400); } $command = $commandMap[$cmdType]; // === 构造并发送 GM 请求 === $query = [ 'cmd' => 1116, 'uid' => $uid, 'msg' => $command, 'region' => REGION ]; $query['sign'] = calcSign($query, "27bwq^d4zzXpdUxf"); $ch = curl_init(MUIP_API . '?' . http_build_query($query)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); $rsp = curl_exec($ch); if (curl_error($ch)) { returnJSON(['success' => false, 'message' => '请求失败: ' . curl_error($ch)], 500); } curl_close($ch); $rspData = @json_decode($rsp, true); returnJSON([ 'success' => isset($rspData['retcode']) && $rspData['retcode'] === 0, 'message' => $rspData['msg'] ?? '操作完成', 'data' => $rspData['data'] ?? null, 'debug' => [ // 调试用,上线前可删除 'command_sent' => $command, 'cmd_type' => $cmdType, 'uid' => $uid ] ]); ?> Medoo.php内的代码 <?php /*! * Medoo database framework * https://medoo.in * Version 1.7.10 * * Copyright 2020, Angel Lai * Released under the MIT license */ namespace Medoo; use PDO; use Exception; use PDOException; use InvalidArgumentException; class Raw { public $map; public $value; } class Medoo { public $pdo; protected $type; protected $prefix; protected $statement; protected $dsn; protected $logs = []; protected $logging = false; protected $debug_mode = false; protected $guid = 0; protected $errorInfo = null; public function __construct(array $options) { if (isset($options[ 'database_type' ])) { $this->type = strtolower($options[ 'database_type' ]); if ($this->type === 'mariadb') { $this->type = 'mysql'; } } if (isset($options[ 'prefix' ])) { $this->prefix = $options[ 'prefix' ]; } if (isset($options[ 'logging' ]) && is_bool($options[ 'logging' ])) { $this->logging = $options[ 'logging' ]; } $option = isset($options[ 'option' ]) ? $options[ 'option' ] : []; $commands = (isset($options[ 'command' ]) && is_array($options[ 'command' ])) ? $options[ 'command' ] : []; switch ($this->type) { case 'mysql': // Make MySQL using standard quoted identifier $commands[] = 'SET SQL_MODE=ANSI_QUOTES'; break; case 'mssql': // Keep MSSQL QUOTED_IDENTIFIER is ON for standard quoting $commands[] = 'SET QUOTED_IDENTIFIER ON'; // Make ANSI_NULLS is ON for NULL value $commands[] = 'SET ANSI_NULLS ON'; break; } if (isset($options[ 'pdo' ])) { if (!$options[ 'pdo' ] instanceof PDO) { throw new InvalidArgumentException('Invalid PDO object supplied'); } $this->pdo = $options[ 'pdo' ]; foreach ($commands as $value) { $this->pdo->exec($value); } return; } if (isset($options[ 'dsn' ])) { if (is_array($options[ 'dsn' ]) && isset($options[ 'dsn' ][ 'driver' ])) { $attr = $options[ 'dsn' ]; } else { throw new InvalidArgumentException('Invalid DSN option supplied'); } } else { if ( isset($options[ 'port' ]) && is_int($options[ 'port' ] * 1) ) { $port = $options[ 'port' ]; } $is_port = isset($port); switch ($this->type) { case 'mysql': $attr = [ 'driver' => 'mysql', 'dbname' => $options[ 'database_name' ] ]; if (isset($options[ 'socket' ])) { $attr[ 'unix_socket' ] = $options[ 'socket' ]; } else { $attr[ 'host' ] = $options[ 'server' ]; if ($is_port) { $attr[ 'port' ] = $port; } } break; case 'pgsql': $attr = [ 'driver' => 'pgsql', 'host' => $options[ 'server' ], 'dbname' => $options[ 'database_name' ] ]; if ($is_port) { $attr[ 'port' ] = $port; } break; case 'sybase': $attr = [ 'driver' => 'dblib', 'host' => $options[ 'server' ], 'dbname' => $options[ 'database_name' ] ]; if ($is_port) { $attr[ 'port' ] = $port; } break; case 'oracle': $attr = [ 'driver' => 'oci', 'dbname' => $options[ 'server' ] ? '//' . $options[ 'server' ] . ($is_port ? ':' . $port : ':1521') . '/' . $options[ 'database_name' ] : $options[ 'database_name' ] ]; if (isset($options[ 'charset' ])) { $attr[ 'charset' ] = $options[ 'charset' ]; } break; case 'mssql': if (isset($options[ 'driver' ]) && $options[ 'driver' ] === 'dblib') { $attr = [ 'driver' => 'dblib', 'host' => $options[ 'server' ] . ($is_port ? ':' . $port : ''), 'dbname' => $options[ 'database_name' ] ]; if (isset($options[ 'appname' ])) { $attr[ 'appname' ] = $options[ 'appname' ]; } if (isset($options[ 'charset' ])) { $attr[ 'charset' ] = $options[ 'charset' ]; } } else { $attr = [ 'driver' => 'sqlsrv', 'Server' => $options[ 'server' ] . ($is_port ? ',' . $port : ''), 'Database' => $options[ 'database_name' ] ]; if (isset($options[ 'appname' ])) { $attr[ 'APP' ] = $options[ 'appname' ]; } $config = [ 'ApplicationIntent', 'AttachDBFileName', 'Authentication', 'ColumnEncryption', 'ConnectionPooling', 'Encrypt', 'Failover_Partner', 'KeyStoreAuthentication', 'KeyStorePrincipalId', 'KeyStoreSecret', 'LoginTimeout', 'MultipleActiveResultSets', 'MultiSubnetFailover', 'Scrollable', 'TraceFile', 'TraceOn', 'TransactionIsolation', 'TransparentNetworkIPResolution', 'TrustServerCertificate', 'WSID', ]; foreach ($config as $value) { $keyname = strtolower(preg_replace(['/([a-z\d])([A-Z])/', '/([^_])([A-Z][a-z])/'], '$1_$2', $value)); if (isset($options[ $keyname ])) { $attr[ $value ] = $options[ $keyname ]; } } } break; case 'sqlite': $attr = [ 'driver' => 'sqlite', $options[ 'database_file' ] ]; break; } } if (!isset($attr)) { throw new InvalidArgumentException('Incorrect connection options'); } $driver = $attr[ 'driver' ]; if (!in_array($driver, PDO::getAvailableDrivers())) { throw new InvalidArgumentException("Unsupported PDO driver: {$driver}"); } unset($attr[ 'driver' ]); $stack = []; foreach ($attr as $key => $value) { $stack[] = is_int($key) ? $value : $key . '=' . $value; } $dsn = $driver . ':' . implode(';', $stack); if ( in_array($this->type, ['mysql', 'pgsql', 'sybase', 'mssql']) && isset($options[ 'charset' ]) ) { $commands[] = "SET NAMES '{$options[ 'charset' ]}'" . ( $this->type === 'mysql' && isset($options[ 'collation' ]) ? " COLLATE '{$options[ 'collation' ]}'" : '' ); } $this->dsn = $dsn; try { $this->pdo = new PDO( $dsn, isset($options[ 'username' ]) ? $options[ 'username' ] : null, isset($options[ 'password' ]) ? $options[ 'password' ] : null, $option ); foreach ($commands as $value) { $this->pdo->exec($value); } } catch (PDOException $e) { throw new PDOException($e->getMessage()); } } public function query($query, $map = []) { $raw = $this->raw($query, $map); $query = $this->buildRaw($raw, $map); return $this->exec($query, $map); } public function exec($query, $map = []) { $this->statement = null; if ($this->debug_mode) { echo $this->generate($query, $map); $this->debug_mode = false; return false; } if ($this->logging) { $this->logs[] = [$query, $map]; } else { $this->logs = [[$query, $map]]; } $statement = $this->pdo->prepare($query); if (!$statement) { $this->errorInfo = $this->pdo->errorInfo(); $this->statement = null; return false; } $this->statement = $statement; foreach ($map as $key => $value) { $statement->bindValue($key, $value[ 0 ], $value[ 1 ]); } $execute = $statement->execute(); $this->errorInfo = $statement->errorInfo(); if (!$execute) { $this->statement = null; } return $statement; } protected function generate($query, $map) { $identifier = [ 'mysql' => '`$1`', 'mssql' => '[$1]' ]; $query = preg_replace( '/"([a-zA-Z0-9_]+)"/i', isset($identifier[ $this->type ]) ? $identifier[ $this->type ] : '"$1"', $query ); foreach ($map as $key => $value) { if ($value[ 1 ] === PDO::PARAM_STR) { $replace = $this->quote($value[ 0 ]); } elseif ($value[ 1 ] === PDO::PARAM_NULL) { $replace = 'NULL'; } elseif ($value[ 1 ] === PDO::PARAM_LOB) { $replace = '{LOB_DATA}'; } else { $replace = $value[ 0 ]; } $query = str_replace($key, $replace, $query); } return $query; } public static function raw($string, $map = []) { $raw = new Raw(); $raw->map = $map; $raw->value = $string; return $raw; } protected function isRaw($object) { return $object instanceof Raw; } protected function buildRaw($raw, &$map) { if (!$this->isRaw($raw)) { return false; } $query = preg_replace_callback( '/(([`\']).*?)?((FROM|TABLE|INTO|UPDATE|JOIN)\s*)?\<(([a-zA-Z0-9_]+)(\.[a-zA-Z0-9_]+)?)\>(.*?\2)?/i', function ($matches) { if (!empty($matches[ 2 ]) && isset($matches[ 8 ])) { return $matches[ 0 ]; } if (!empty($matches[ 4 ])) { return $matches[ 1 ] . $matches[ 4 ] . ' ' . $this->tableQuote($matches[ 5 ]); } return $matches[ 1 ] . $this->columnQuote($matches[ 5 ]); }, $raw->value); $raw_map = $raw->map; if (!empty($raw_map)) { foreach ($raw_map as $key => $value) { $map[ $key ] = $this->typeMap($value, gettype($value)); } } return $query; } public function quote($string) { return $this->pdo->quote($string); } protected function tableQuote($table) { if (!preg_match('/^[a-zA-Z0-9_]+$/i', $table)) { throw new InvalidArgumentException("Incorrect table name \"$table\""); } return '"' . $this->prefix . $table . '"'; } protected function mapKey() { return ':MeDoO_' . $this->guid++ . '_mEdOo'; } protected function typeMap($value, $type) { $map = [ 'NULL' => PDO::PARAM_NULL, 'integer' => PDO::PARAM_INT, 'double' => PDO::PARAM_STR, 'boolean' => PDO::PARAM_BOOL, 'string' => PDO::PARAM_STR, 'object' => PDO::PARAM_STR, 'resource' => PDO::PARAM_LOB ]; if ($type === 'boolean') { $value = ($value ? '1' : '0'); } elseif ($type === 'NULL') { $value = null; } return [$value, $map[ $type ]]; } protected function columnQuote($string) { if (!preg_match('/^[a-zA-Z0-9_]+(\.?[a-zA-Z0-9_]+)?$/i', $string)) { throw new InvalidArgumentException("Incorrect column name \"$string\""); } if (strpos($string, '.') !== false) { return '"' . $this->prefix . str_replace('.', '"."', $string) . '"'; } return '"' . $string . '"'; } protected function columnPush(&$columns, &$map, $root, $is_join = false) { if ($columns === '*') { return $columns; } $stack = []; if (is_string($columns)) { $columns = [$columns]; } foreach ($columns as $key => $value) { if (!is_int($key) && is_array($value) && $root && count(array_keys($columns)) === 1) { $stack[] = $this->columnQuote($key); $stack[] = $this->columnPush($value, $map, false, $is_join); } elseif (is_array($value)) { $stack[] = $this->columnPush($value, $map, false, $is_join); } elseif (!is_int($key) && $raw = $this->buildRaw($value, $map)) { preg_match('/(?<column>[a-zA-Z0-9_\.]+)(\s*\[(?<type>(String|Bool|Int|Number))\])?/i', $key, $match); $stack[] = $raw . ' AS ' . $this->columnQuote($match[ 'column' ]); } elseif (is_int($key) && is_string($value)) { if ($is_join && strpos($value, '*') !== false) { throw new InvalidArgumentException('Cannot use table.* to select all columns while joining table'); } preg_match('/(?<column>[a-zA-Z0-9_\.]+)(?:\s*\((?<alias>[a-zA-Z0-9_]+)\))?(?:\s*\[(?<type>(?:String|Bool|Int|Number|Object|JSON))\])?/i', $value, $match); if (!empty($match[ 'alias' ])) { $stack[] = $this->columnQuote($match[ 'column' ]) . ' AS ' . $this->columnQuote($match[ 'alias' ]); $columns[ $key ] = $match[ 'alias' ]; if (!empty($match[ 'type' ])) { $columns[ $key ] .= ' [' . $match[ 'type' ] . ']'; } } else { $stack[] = $this->columnQuote($match[ 'column' ]); } } } return implode(',', $stack); } protected function arrayQuote($array) { $stack = []; foreach ($array as $value) { $stack[] = is_int($value) ? $value : $this->pdo->quote($value); } return implode(',', $stack); } protected function innerConjunct($data, $map, $conjunctor, $outer_conjunctor) { $stack = []; foreach ($data as $value) { $stack[] = '(' . $this->dataImplode($value, $map, $conjunctor) . ')'; } return implode($outer_conjunctor . ' ', $stack); } protected function dataImplode($data, &$map, $conjunctor) { $stack = []; foreach ($data as $key => $value) { $type = gettype($value); if ( $type === 'array' && preg_match("/^(AND|OR)(\s+#.*)?$/", $key, $relation_match) ) { $relationship = $relation_match[ 1 ]; $stack[] = $value !== array_keys(array_keys($value)) ? '(' . $this->dataImplode($value, $map, ' ' . $relationship) . ')' : '(' . $this->innerConjunct($value, $map, ' ' . $relationship, $conjunctor) . ')'; continue; } $map_key = $this->mapKey(); if ( is_int($key) && preg_match('/([a-zA-Z0-9_\.]+)\[(?<operator>\>\=?|\<\=?|\!?\=)\]([a-zA-Z0-9_\.]+)/i', $value, $match) ) { $stack[] = $this->columnQuote($match[ 1 ]) . ' ' . $match[ 'operator' ] . ' ' . $this->columnQuote($match[ 3 ]); } else { preg_match('/([a-zA-Z0-9_\.]+)(\[(?<operator>\>\=?|\<\=?|\!|\<\>|\>\<|\!?~|REGEXP)\])?/i', $key, $match); $column = $this->columnQuote($match[ 1 ]); if (isset($match[ 'operator' ])) { $operator = $match[ 'operator' ]; if (in_array($operator, ['>', '>=', '<', '<='])) { $condition = $column . ' ' . $operator . ' '; if (is_numeric($value)) { $condition .= $map_key; $map[ $map_key ] = [$value, is_float($value) ? PDO::PARAM_STR : PDO::PARAM_INT]; } elseif ($raw = $this->buildRaw($value, $map)) { $condition .= $raw; } else { $condition .= $map_key; $map[ $map_key ] = [$value, PDO::PARAM_STR]; } $stack[] = $condition; } elseif ($operator === '!') { switch ($type) { case 'NULL': $stack[] = $column . ' IS NOT NULL'; break; case 'array': $placeholders = []; foreach ($value as $index => $item) { $stack_key = $map_key . $index . '_i'; $placeholders[] = $stack_key; $map[ $stack_key ] = $this->typeMap($item, gettype($item)); } $stack[] = $column . ' NOT IN (' . implode(', ', $placeholders) . ')'; break; case 'object': if ($raw = $this->buildRaw($value, $map)) { $stack[] = $column . ' != ' . $raw; } break; case 'integer': case 'double': case 'boolean': case 'string': $stack[] = $column . ' != ' . $map_key; $map[ $map_key ] = $this->typeMap($value, $type); break; } } elseif ($operator === '~' || $operator === '!~') { if ($type !== 'array') { $value = [ $value ]; } $connector = ' OR '; $data = array_values($value); if (is_array($data[ 0 ])) { if (isset($value[ 'AND' ]) || isset($value[ 'OR' ])) { $connector = ' ' . array_keys($value)[ 0 ] . ' '; $value = $data[ 0 ]; } } $like_clauses = []; foreach ($value as $index => $item) { $item = strval($item); if (!preg_match('/(\[.+\]|[\*\?\!\%#^-_]|%.+|.+%)/', $item)) { $item = '%' . $item . '%'; } $like_clauses[] = $column . ($operator === '!~' ? ' NOT' : '') . ' LIKE ' . $map_key . 'L' . $index; $map[ $map_key . 'L' . $index ] = [$item, PDO::PARAM_STR]; } $stack[] = '(' . implode($connector, $like_clauses) . ')'; } elseif ($operator === '<>' || $operator === '><') { if ($type === 'array') { if ($operator === '><') { $column .= ' NOT'; } $stack[] = '(' . $column . ' BETWEEN ' . $map_key . 'a AND ' . $map_key . 'b)'; $data_type = (is_numeric($value[ 0 ]) && is_numeric($value[ 1 ])) ? PDO::PARAM_INT : PDO::PARAM_STR; $map[ $map_key . 'a' ] = [$value[ 0 ], $data_type]; $map[ $map_key . 'b' ] = [$value[ 1 ], $data_type]; } } elseif ($operator === 'REGEXP') { $stack[] = $column . ' REGEXP ' . $map_key; $map[ $map_key ] = [$value, PDO::PARAM_STR]; } } else { switch ($type) { case 'NULL': $stack[] = $column . ' IS NULL'; break; case 'array': $placeholders = []; foreach ($value as $index => $item) { $stack_key = $map_key . $index . '_i'; $placeholders[] = $stack_key; $map[ $stack_key ] = $this->typeMap($item, gettype($item)); } $stack[] = $column . ' IN (' . implode(', ', $placeholders) . ')'; break; case 'object': if ($raw = $this->buildRaw($value, $map)) { $stack[] = $column . ' = ' . $raw; } break; case 'integer': case 'double': case 'boolean': case 'string': $stack[] = $column . ' = ' . $map_key; $map[ $map_key ] = $this->typeMap($value, $type); break; } } } } return implode($conjunctor . ' ', $stack); } protected function whereClause($where, &$map) { $where_clause = ''; if (is_array($where)) { $where_keys = array_keys($where); $conditions = array_diff_key($where, array_flip( ['GROUP', 'ORDER', 'HAVING', 'LIMIT', 'LIKE', 'MATCH'] )); if (!empty($conditions)) { $where_clause = ' WHERE ' . $this->dataImplode($conditions, $map, ' AND'); } if (isset($where[ 'MATCH' ]) && $this->type === 'mysql') { $MATCH = $where[ 'MATCH' ]; if (is_array($MATCH) && isset($MATCH[ 'columns' ], $MATCH[ 'keyword' ])) { $mode = ''; $mode_array = [ 'natural' => 'IN NATURAL LANGUAGE MODE', 'natural+query' => 'IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION', 'boolean' => 'IN BOOLEAN MODE', 'query' => 'WITH QUERY EXPANSION' ]; if (isset($MATCH[ 'mode' ], $mode_array[ $MATCH[ 'mode' ] ])) { $mode = ' ' . $mode_array[ $MATCH[ 'mode' ] ]; } $columns = implode(', ', array_map([$this, 'columnQuote'], $MATCH[ 'columns' ])); $map_key = $this->mapKey(); $map[ $map_key ] = [$MATCH[ 'keyword' ], PDO::PARAM_STR]; $where_clause .= ($where_clause !== '' ? ' AND ' : ' WHERE') . ' MATCH (' . $columns . ') AGAINST (' . $map_key . $mode . ')'; } } if (isset($where[ 'GROUP' ])) { $GROUP = $where[ 'GROUP' ]; if (is_array($GROUP)) { $stack = []; foreach ($GROUP as $column => $value) { $stack[] = $this->columnQuote($value); } $where_clause .= ' GROUP BY ' . implode(',', $stack); } elseif ($raw = $this->buildRaw($GROUP, $map)) { $where_clause .= ' GROUP BY ' . $raw; } else { $where_clause .= ' GROUP BY ' . $this->columnQuote($GROUP); } if (isset($where[ 'HAVING' ])) { if ($raw = $this->buildRaw($where[ 'HAVING' ], $map)) { $where_clause .= ' HAVING ' . $raw; } else { $where_clause .= ' HAVING ' . $this->dataImplode($where[ 'HAVING' ], $map, ' AND'); } } } if (isset($where[ 'ORDER' ])) { $ORDER = $where[ 'ORDER' ]; if (is_array($ORDER)) { $stack = []; foreach ($ORDER as $column => $value) { if (is_array($value)) { $stack[] = 'FIELD(' . $this->columnQuote($column) . ', ' . $this->arrayQuote($value) . ')'; } elseif ($value === 'ASC' || $value === 'DESC') { $stack[] = $this->columnQuote($column) . ' ' . $value; } elseif (is_int($column)) { $stack[] = $this->columnQuote($value); } } $where_clause .= ' ORDER BY ' . implode(',', $stack); } elseif ($raw = $this->buildRaw($ORDER, $map)) { $where_clause .= ' ORDER BY ' . $raw; } else { $where_clause .= ' ORDER BY ' . $this->columnQuote($ORDER); } if ( isset($where[ 'LIMIT' ]) && in_array($this->type, ['oracle', 'mssql']) ) { $LIMIT = $where[ 'LIMIT' ]; if (is_numeric($LIMIT)) { $LIMIT = [0, $LIMIT]; } if ( is_array($LIMIT) && is_numeric($LIMIT[ 0 ]) && is_numeric($LIMIT[ 1 ]) ) { $where_clause .= ' OFFSET ' . $LIMIT[ 0 ] . ' ROWS FETCH NEXT ' . $LIMIT[ 1 ] . ' ROWS ONLY'; } } } if (isset($where[ 'LIMIT' ]) && !in_array($this->type, ['oracle', 'mssql'])) { $LIMIT = $where[ 'LIMIT' ]; if (is_numeric($LIMIT)) { $where_clause .= ' LIMIT ' . $LIMIT; } elseif ( is_array($LIMIT) && is_numeric($LIMIT[ 0 ]) && is_numeric($LIMIT[ 1 ]) ) { $where_clause .= ' LIMIT ' . $LIMIT[ 1 ] . ' OFFSET ' . $LIMIT[ 0 ]; } } } elseif ($raw = $this->buildRaw($where, $map)) { $where_clause .= ' ' . $raw; } return $where_clause; } protected function selectContext($table, &$map, $join, &$columns = null, $where = null, $column_fn = null) { preg_match('/(?<table>[a-zA-Z0-9_]+)\s*\((?<alias>[a-zA-Z0-9_]+)\)/i', $table, $table_match); if (isset($table_match[ 'table' ], $table_match[ 'alias' ])) { $table = $this->tableQuote($table_match[ 'table' ]); $table_query = $table . ' AS ' . $this->tableQuote($table_match[ 'alias' ]); } else { $table = $this->tableQuote($table); $table_query = $table; } $is_join = false; $join_key = is_array($join) ? array_keys($join) : null; if ( isset($join_key[ 0 ]) && strpos($join_key[ 0 ], '[') === 0 ) { $is_join = true; $table_query .= ' ' . $this->buildJoin($table, $join); } else { if (is_null($columns)) { if ( !is_null($where) || (is_array($join) && isset($column_fn)) ) { $where = $join; $columns = null; } else { $where = null; $columns = $join; } } else { $where = $columns; $columns = $join; } } if (isset($column_fn)) { if ($column_fn === 1) { $column = '1'; if (is_null($where)) { $where = $columns; } } elseif ($raw = $this->buildRaw($column_fn, $map)) { $column = $raw; } else { if (empty($columns) || $this->isRaw($columns)) { $columns = '*'; $where = $join; } $column = $column_fn . '(' . $this->columnPush($columns, $map, true) . ')'; } } else { $column = $this->columnPush($columns, $map, true, $is_join); } return 'SELECT ' . $column . ' FROM ' . $table_query . $this->whereClause($where, $map); } protected function buildJoin($table, $join) { $table_join = []; $join_array = [ '>' => 'LEFT', '<' => 'RIGHT', '<>' => 'FULL', '><' => 'INNER' ]; foreach($join as $sub_table => $relation) { preg_match('/(\[(?<join>\<\>?|\>\<?)\])?(?<table>[a-zA-Z0-9_]+)\s?(\((?<alias>[a-zA-Z0-9_]+)\))?/', $sub_table, $match); if ($match[ 'join' ] !== '' && $match[ 'table' ] !== '') { if (is_string($relation)) { $relation = 'USING ("' . $relation . '")'; } if (is_array($relation)) { // For ['column1', 'column2'] if (isset($relation[ 0 ])) { $relation = 'USING ("' . implode('", "', $relation) . '")'; } else { $joins = []; foreach ($relation as $key => $value) { $joins[] = ( strpos($key, '.') > 0 ? // For ['tableB.column' => 'column'] $this->columnQuote($key) : // For ['column1' => 'column2'] $table . '."' . $key . '"' ) . ' = ' . $this->tableQuote(isset($match[ 'alias' ]) ? $match[ 'alias' ] : $match[ 'table' ]) . '."' . $value . '"'; } $relation = 'ON ' . implode(' AND ', $joins); } } $table_name = $this->tableQuote($match[ 'table' ]) . ' '; if (isset($match[ 'alias' ])) { $table_name .= 'AS ' . $this->tableQuote($match[ 'alias' ]) . ' '; } $table_join[] = $join_array[ $match[ 'join' ] ] . ' JOIN ' . $table_name . $relation; } } return implode(' ', $table_join); } protected function columnMap($columns, &$stack, $root) { if ($columns === '*') { return $stack; } foreach ($columns as $key => $value) { if (is_int($key)) { preg_match('/([a-zA-Z0-9_]+\.)?(?<column>[a-zA-Z0-9_]+)(?:\s*\((?<alias>[a-zA-Z0-9_]+)\))?(?:\s*\[(?<type>(?:String|Bool|Int|Number|Object|JSON))\])?/i', $value, $key_match); $column_key = !empty($key_match[ 'alias' ]) ? $key_match[ 'alias' ] : $key_match[ 'column' ]; if (isset($key_match[ 'type' ])) { $stack[ $value ] = [$column_key, $key_match[ 'type' ]]; } else { $stack[ $value ] = [$column_key, 'String']; } } elseif ($this->isRaw($value)) { preg_match('/([a-zA-Z0-9_]+\.)?(?<column>[a-zA-Z0-9_]+)(\s*\[(?<type>(String|Bool|Int|Number))\])?/i', $key, $key_match); $column_key = $key_match[ 'column' ]; if (isset($key_match[ 'type' ])) { $stack[ $key ] = [$column_key, $key_match[ 'type' ]]; } else { $stack[ $key ] = [$column_key, 'String']; } } elseif (!is_int($key) && is_array($value)) { if ($root && count(array_keys($columns)) === 1) { $stack[ $key ] = [$key, 'String']; } $this->columnMap($value, $stack, false); } } return $stack; } protected function dataMap($data, $columns, $column_map, &$stack, $root, &$result) { if ($root) { $columns_key = array_keys($columns); if (count($columns_key) === 1 && is_array($columns[$columns_key[0]])) { $index_key = array_keys($columns)[0]; $data_key = preg_replace("/^[a-zA-Z0-9_]+\./i", "", $index_key); $current_stack = []; foreach ($data as $item) { $this->dataMap($data, $columns[ $index_key ], $column_map, $current_stack, false, $result); $index = $data[ $data_key ]; $result[ $index ] = $current_stack; } } else { $current_stack = []; $this->dataMap($data, $columns, $column_map, $current_stack, false, $result); $result[] = $current_stack; } return; } foreach ($columns as $key => $value) { $isRaw = $this->isRaw($value); if (is_int($key) || $isRaw) { $map = $column_map[ $isRaw ? $key : $value ]; $column_key = $map[ 0 ]; $item = $data[ $column_key ]; if (isset($map[ 1 ])) { if ($isRaw && in_array($map[ 1 ], ['Object', 'JSON'])) { continue; } if (is_null($item)) { $stack[ $column_key ] = null; continue; } switch ($map[ 1 ]) { case 'Number': $stack[ $column_key ] = (double) $item; break; case 'Int': $stack[ $column_key ] = (int) $item; break; case 'Bool': $stack[ $column_key ] = (bool) $item; break; case 'Object': $stack[ $column_key ] = unserialize($item); break; case 'JSON': $stack[ $column_key ] = json_decode($item, true); break; case 'String': $stack[ $column_key ] = $item; break; } } else { $stack[ $column_key ] = $item; } } else { $current_stack = []; $this->dataMap($data, $value, $column_map, $current_stack, false, $result); $stack[ $key ] = $current_stack; } } } public function create($table, $columns, $options = null) { $stack = []; $tableName = $this->prefix . $table; foreach ($columns as $name => $definition) { if (is_int($name)) { $stack[] = preg_replace('/\<([a-zA-Z0-9_]+)\>/i', '"$1"', $definition); } elseif (is_array($definition)) { $stack[] = $name . ' ' . implode(' ', $definition); } elseif (is_string($definition)) { $stack[] = $name . ' ' . $this->query($definition); } } $table_option = ''; if (is_array($options)) { $option_stack = []; foreach ($options as $key => $value) { if (is_string($value) || is_int($value)) { $option_stack[] = "$key = $value"; } } $table_option = ' ' . implode(', ', $option_stack); } elseif (is_string($options)) { $table_option = ' ' . $options; } return $this->exec("CREATE TABLE IF NOT EXISTS $tableName (" . implode(', ', $stack) . ")$table_option"); } public function drop($table) { $tableName = $this->prefix . $table; return $this->exec("DROP TABLE IF EXISTS $tableName"); } public function select($table, $join, $columns = null, $where = null) { $map = []; $result = []; $column_map = []; $index = 0; $column = $where === null ? $join : $columns; $is_single = (is_string($column) && $column !== '*'); $query = $this->exec($this->selectContext($table, $map, $join, $columns, $where), $map); $this->columnMap($columns, $column_map, true); if (!$this->statement) { return false; } if ($columns === '*') { return $query->fetchAll(PDO::FETCH_ASSOC); } while ($data = $query->fetch(PDO::FETCH_ASSOC)) { $current_stack = []; $this->dataMap($data, $columns, $column_map, $current_stack, true, $result); } if ($is_single) { $single_result = []; $result_key = $column_map[ $column ][ 0 ]; foreach ($result as $item) { $single_result[] = $item[ $result_key ]; } return $single_result; } return $result; } public function insert($table, $datas) { $stack = []; $columns = []; $fields = []; $map = []; if (!isset($datas[ 0 ])) { $datas = [$datas]; } foreach ($datas as $data) { foreach ($data as $key => $value) { $columns[] = $key; } } $columns = array_unique($columns); foreach ($datas as $data) { $values = []; foreach ($columns as $key) { if ($raw = $this->buildRaw($data[ $key ], $map)) { $values[] = $raw; continue; } $map_key = $this->mapKey(); $values[] = $map_key; if (!isset($data[ $key ])) { $map[ $map_key ] = [null, PDO::PARAM_NULL]; } else { $value = $data[ $key ]; $type = gettype($value); switch ($type) { case 'array': $map[ $map_key ] = [ strpos($key, '[JSON]') === strlen($key) - 6 ? json_encode($value) : serialize($value), PDO::PARAM_STR ]; break; case 'object': $value = serialize($value); case 'NULL': case 'resource': case 'boolean': case 'integer': case 'double': case 'string': $map[ $map_key ] = $this->typeMap($value, $type); break; } } } $stack[] = '(' . implode(', ', $values) . ')'; } foreach ($columns as $key) { $fields[] = $this->columnQuote(preg_replace("/(\s*\[JSON\]$)/i", '', $key)); } return $this->exec('INSERT INTO ' . $this->tableQuote($table) . ' (' . implode(', ', $fields) . ') VALUES ' . implode(', ', $stack), $map); } public function update($table, $data, $where = null) { $fields = []; $map = []; foreach ($data as $key => $value) { $column = $this->columnQuote(preg_replace("/(\s*\[(JSON|\+|\-|\*|\/)\]$)/i", '', $key)); if ($raw = $this->buildRaw($value, $map)) { $fields[] = $column . ' = ' . $raw; continue; } $map_key = $this->mapKey(); preg_match('/(?<column>[a-zA-Z0-9_]+)(\[(?<operator>\+|\-|\*|\/)\])?/i', $key, $match); if (isset($match[ 'operator' ])) { if (is_numeric($value)) { $fields[] = $column . ' = ' . $column . ' ' . $match[ 'operator' ] . ' ' . $value; } } else { $fields[] = $column . ' = ' . $map_key; $type = gettype($value); switch ($type) { case 'array': $map[ $map_key ] = [ strpos($key, '[JSON]') === strlen($key) - 6 ? json_encode($value) : serialize($value), PDO::PARAM_STR ]; break; case 'object': $value = serialize($value); case 'NULL': case 'resource': case 'boolean': case 'integer': case 'double': case 'string': $map[ $map_key ] = $this->typeMap($value, $type); break; } } } return $this->exec('UPDATE ' . $this->tableQuote($table) . ' SET ' . implode(', ', $fields) . $this->whereClause($where, $map), $map); } public function delete($table, $where) { $map = []; return $this->exec('DELETE FROM ' . $this->tableQuote($table) . $this->whereClause($where, $map), $map); } public function replace($table, $columns, $where = null) { if (!is_array($columns) || empty($columns)) { return false; } $map = []; $stack = []; foreach ($columns as $column => $replacements) { if (is_array($replacements)) { foreach ($replacements as $old => $new) { $map_key = $this->mapKey(); $stack[] = $this->columnQuote($column) . ' = REPLACE(' . $this->columnQuote($column) . ', ' . $map_key . 'a, ' . $map_key . 'b)'; $map[ $map_key . 'a' ] = [$old, PDO::PARAM_STR]; $map[ $map_key . 'b' ] = [$new, PDO::PARAM_STR]; } } } if (!empty($stack)) { return $this->exec('UPDATE ' . $this->tableQuote($table) . ' SET ' . implode(', ', $stack) . $this->whereClause($where, $map), $map); } return false; } public function get($table, $join = null, $columns = null, $where = null) { $map = []; $result = []; $column_map = []; $current_stack = []; if ($where === null) { $column = $join; unset($columns[ 'LIMIT' ]); } else { $column = $columns; unset($where[ 'LIMIT' ]); } $is_single = (is_string($column) && $column !== '*'); $query = $this->exec($this->selectContext($table, $map, $join, $columns, $where) . ' LIMIT 1', $map); if (!$this->statement) { return false; } $data = $query->fetchAll(PDO::FETCH_ASSOC); if (isset($data[ 0 ])) { if ($column === '*') { return $data[ 0 ]; } $this->columnMap($columns, $column_map, true); $this->dataMap($data[ 0 ], $columns, $column_map, $current_stack, true, $result); if ($is_single) { return $result[ 0 ][ $column_map[ $column ][ 0 ] ]; } return $result[ 0 ]; } } public function has($table, $join, $where = null) { $map = []; $column = null; if ($this->type === 'mssql') { $query = $this->exec($this->selectContext($table, $map, $join, $column, $where, Medoo::raw('TOP 1 1')), $map); } else { $query = $this->exec('SELECT EXISTS(' . $this->selectContext($table, $map, $join, $column, $where, 1) . ')', $map); } if (!$this->statement) { return false; } $result = $query->fetchColumn(); return $result === '1' || $result === 1 || $result === true; } public function rand($table, $join = null, $columns = null, $where = null) { $type = $this->type; $order = 'RANDOM()'; if ($type === 'mysql') { $order = 'RAND()'; } elseif ($type === 'mssql') { $order = 'NEWID()'; } $order_raw = $this->raw($order); if ($where === null) { if ($columns === null) { $columns = [ 'ORDER' => $order_raw ]; } else { $column = $join; unset($columns[ 'ORDER' ]); $columns[ 'ORDER' ] = $order_raw; } } else { unset($where[ 'ORDER' ]); $where[ 'ORDER' ] = $order_raw; } return $this->select($table, $join, $columns, $where); } private function aggregate($type, $table, $join = null, $column = null, $where = null) { $map = []; $query = $this->exec($this->selectContext($table, $map, $join, $column, $where, strtoupper($type)), $map); if (!$this->statement) { return false; } $number = $query->fetchColumn(); return is_numeric($number) ? $number + 0 : $number; } public function count($table, $join = null, $column = null, $where = null) { return $this->aggregate('count', $table, $join, $column, $where); } public function avg($table, $join, $column = null, $where = null) { return $this->aggregate('avg', $table, $join, $column, $where); } public function max($table, $join, $column = null, $where = null) { return $this->aggregate('max', $table, $join, $column, $where); } public function min($table, $join, $column = null, $where = null) { return $this->aggregate('min', $table, $join, $column, $where); } public function sum($table, $join, $column = null, $where = null) { return $this->aggregate('sum', $table, $join, $column, $where); } public function action($actions) { if (is_callable($actions)) { $this->pdo->beginTransaction(); try { $result = $actions($this); if ($result === false) { $this->pdo->rollBack(); } else { $this->pdo->commit(); } } catch (Exception $e) { $this->pdo->rollBack(); throw $e; } return $result; } return false; } public function id() { if ($this->statement == null) { return null; } $type = $this->type; if ($type === 'oracle') { return 0; } elseif ($type === 'pgsql') { return $this->pdo->query('SELECT LASTVAL()')->fetchColumn(); } $lastId = $this->pdo->lastInsertId(); if ($lastId != "0" && $lastId != "") { return $lastId; } return null; } public function debug() { $this->debug_mode = true; return $this; } public function error() { return $this->errorInfo; } public function last() { $log = end($this->logs); return $this->generate($log[ 0 ], $log[ 1 ]); } public function log() { return array_map(function ($log) { return $this->generate($log[ 0 ], $log[ 1 ]); }, $this->logs ); } public function info() { $output = [ 'server' => 'SERVER_INFO', 'driver' => 'DRIVER_NAME', 'client' => 'CLIENT_VERSION', 'version' => 'SERVER_VERSION', 'connection' => 'CONNECTION_STATUS' ]; foreach ($output as $key => $value) { $output[ $key ] = @$this->pdo->getAttribute(constant('PDO::ATTR_' . $value)); } $output[ 'dsn' ] = $this->dsn; return $output; } 现在问题是生成cdk执行兑换player_level+自定义等级成功 开启所有锚点生成后 point 3 all 不能兑换成功 开启无限体力 生成后stamina infinite on 不能兑换成功 可重写数据库 cdk逻辑和used_cdk表记录逻辑
最新发布
11-30
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值