开启sql日志

@return DebugStack
174557
public function enabledSqlLog()
    {
        if (!$this->sqlLogger) {
            $this->sqlLogger = new DebugStack();
            $this->dbConnection->getConfiguration()->setSQLLogger($this->sqlLogger);
        }
    }
914525
protected function triggerSql($sql, $runtime, $options = [])
    {
        if (!empty(self::$event)) {
            foreach (self::$event as $callback) {
                if (is_callable($callback)) {
                    call_user_func_array($callback, [$sql, $runtime, $options]);
                }
            }
        } else {
            // 未注册监听则记录到日志中
            $this->logger('[ SQL ] ' . $sql . ' [ RunTime:' . $runtime . 's ]');
        }
    }
549893
protected function debug($start, $sql = '', $master = false)
    {
        if (!empty($this->config['debug'])) {
            // 开启数据库调试模式
            if ($start) {
                $this->queryStartTime = microtime(true);
            } else {
                $runtime = number_format((microtime(true) - $this->queryStartTime), 6);
                $sql     = $sql ?: $this->getLastsql();
                $result  = [];

                // SQL性能分析
                if ($this->config['sql_explain'] && 0 === stripos(trim($sql), 'select')) {
                    $result = $this->getExplain($sql);
                }

                // SQL监听
                $this->triggerSql($sql, $runtime, $result, $master);
            }
        }
    }
1348557
protected function before()
    {
        $args = func_get_args();
        $op = array_shift($args);

        $property = 'hooksBefore' . $op;

        // 如果存在前置钩子
        foreach ($this->$property as $func) {
            // 执行前置 检查,
            $ret = call_user_func_array($func, $args);

            //检查失败则不再继续
            if ($ret === Table::INTERRUPT) {
                return $ret;
            }
            $args = $ret;
        }

        // 所有检查通过
        return $args;
    }
378883
private function logSql($sql, array $bind = []) {
        if (!Config::get('app', 'debug')) {
            return;
        }
        if ($bind) {
            foreach ($bind as $key => $val) {
                $value = is_array($val) ? $val[ 0 ] : $val;
                $type = is_array($val) ? $val[ 1 ] : PDO::PARAM_STR;
                if (PDO::PARAM_STR == $type) {
                    $value = $this->pdo->quote($value);
                } elseif (PDO::PARAM_INT == $type && '' === $value) {
                    $value = 0;
                }
                // 判断占位符
                $sql = is_numeric($key) ? substr_replace($sql, $value, strpos($sql, '?'), 1) : str_replace([':' . $key . ')',
                                                                                                            ':' . $key . ',',
                                                                                                            ':' . $key . ' '], [$value . ')',
                                                                                                                                $value . ',',
                                                                                                                                $value . ' '], $sql . ' ');
            }
        }
        $this->queryStr = rtrim($sql);
        Log::debug($this->queryStr, 'sql');
        return;
    }
936960
private function select() {
        $this->performed  = true;
        $this->resultSet  = [];
        $this->resultSets = [];
        $this->resultIdx  = 0;
        $this->maxIdx     = 0;
        $this->size       = 0;
        try {
            $this->checkDialect();
        } catch (DialectException $e) {
            $this->error = $e->getMessage();

            return;
        }
        //生成SQL
        if (!$this->sql) {
            $this->sql = $this->getSQL();
            if (!$this->sql) {
                $this->error       = 'can not generate the SQL';
                $this->errorSQL    = '';
                $this->errorValues = $this->values->__toString();

                return;
            }
            //重新生成SQL.
            $this->statement = null;
        }
        //生成prepare statement
        if (!$this->statement) {
            $this->prepareStatement();
        }
        //执行
        if ($this->statement) {
            try {
                if ($this->values) {
                    foreach ($this->values as $value) {
                        list ($name, $val, $type, $field, $rkey) = $value;
                        if ($this->whereData) {
                            $val = isset($this->whereData[ $rkey ]) ? $this->whereData[ $rkey ] : (isset($this->whereData[ $name ]) ? $this->whereData[ $name ] : $val);
                        }
                        if (!$this->statement->bindValue($name, $val, $type)) {
                            $this->errorSQL    = $this->sql;
                            $this->errorValues = $this->values->__toString();
                            $this->error       = 'can not bind the value ' . $val . '[' . $type . '] to the argument:' . $name . '(' . $field . ')';

                            return;
                        }
                    }
                }
                $rst = $this->statement->execute();
                QueryBuilder::addSqlCount();
                if ($rst) {
                    $this->resultSets = $this->statement->fetchAll(\PDO::FETCH_ASSOC);
                    $this->size       = count($this->resultSets);
                    if ($this->size > 0) {
                        $this->maxIdx    = $this->size - 1;
                        $this->resultSet = $this->resultSets[0];
                    }
                } else {
                    $this->dumpSQL($this->statement);
                }
            } catch (\PDOException $e) {
                $this->exception   = $e;
                $this->error       = $e->getMessage();
                $this->errorSQL    = $this->sql;
                $this->errorValues = $this->values->__toString();
            }
        }
    }
1030536
public function realQuery($sql) {
		BLog::addToLog($this->logsuffix . ' Query: ' . $sql);
		$this->queries_count++;
		$r = $this->mysqli->real_query($sql);
		if ((DEBUG_MODE) && (empty($r))) {
			BLog::addToLog($this->logsuffix . ' query failed!', LL_ERROR);
			BLog::addToLog($this->logsuffix . ' query="' . $sql . '";', LL_ERROR);
			BLog::addToLog($this->logsuffix . ' query error=' . $this->lastError(), LL_ERROR);
		}
		return $r;
	}
308192
public function trace()
    {
        //====================================================================//
        // Safety Check
        if (!isset($this->debug) || !$this->debug) {
            return;
        }
        //====================================================================//
        // Build Error Trace
        $trace = (new Exception())->getTrace()[1];
        //====================================================================//
        //  Load Translation File
        Splash::translator()->load('main');
        //====================================================================//
        // Push Trace to Log
        return  self::deb("DebTraceMsg", $trace["class"], $trace["function"]);
    }
107533
public function nextQuery()
    {
        $sql = null;

        while (($line = $this->sqlReader->readLine()) !== null) {
            $delimiter = $this->parent->getDelimiter();
            $project = $this->parent->getOwningTarget()->getProject();
            $line = $project->replaceProperties(trim($line));

            if (($line != $delimiter) && (StringHelper::startsWith("//", $line)
                    || StringHelper::startsWith("--", $line)
                    || StringHelper::startsWith("#", $line))
            ) {
                continue;
            }

            $sql .= " " . $line . "\n";

            /**
             * fix issue with PDO and wrong formated multistatements
             *
             * @issue 1108
             */
            if (StringHelper::endsWith($delimiter, $line)) {
                break;
            }
        }

        return $sql;
    }
947109
public function log()
    {
        $this->debug->groupCollapsed(__METHOD__);
        $this->columns = array(
            array('key' => 'Date', 'value' => \date('F j, Y')),
            array('key' => 'Time', 'value' => \date('g:ia')),
            array('key' => 'IP Address', 'value' => $_SERVER['REMOTE_ADDR']),
        );
        $typesSkip = array('button','image','reset','submit');
        $pages = $this->logGetAllPages();
        foreach (\array_keys($pages) as $i) {
            $this->setCurrentFields($i);
            foreach ($this->form->currentFields as $field) {
                $props = $field->props;
                $type = $props['attribs']['type'];
                $name = $props['attribs']['name'];
                if (\in_array($type, $typesSkip)) {
                    continue;           // not interested in these types o fields
                }
                $label = (\is_int($name) && !empty($props['label']))
                    ? $props['label']
                    : \ucwords(\strtr($name, '_', ' '));
                $value = $field->val();
                // do not use $field['return_array']... we're wanting a column for every possible value
                if (\in_array($type, array('checkbox','select','radio'))) {
                    if (\is_string($value)) {
                        $value = array($value);
                    }
                    foreach ($props['options'] as $opt) {
                        $this->logAddColumn($opt['value'], \in_array($opt['value'], $value) ? 1 : '');
                    }
                } else {
                    $value = \strtr($value, array("\n"=>' ',"\r"=>''));
                    $this->logAddColumn($label, $value);
                }
            }
        }
        $return = $this->logWriteFile();
        return $return;
    }
73584
public static function start() {
        if (!self::$app) {
            new App ();
        }
        if (!defined('DEBUG')) {
            $debug = App::icfg('debug', DEBUG_ERROR);
            if ($debug > 1000 || $debug < 0) {
                $debug = DEBUG_OFF;
            }
            define('DEBUG', $debug);
            if (DEBUG == DEBUG_OFF) {
                define('KS_ERROR_REPORT_LEVEL', E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_WARNING);
                @ini_set('display_errors', 0);
            } else if (DEBUG == DEBUG_DEBUG) {
                define('KS_ERROR_REPORT_LEVEL', E_ALL & ~E_NOTICE);
                @ini_set('display_errors', 1);
            } else {
                define('KS_ERROR_REPORT_LEVEL', E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT);
                @ini_set('display_errors', 1);
            }
            error_reporting(KS_ERROR_REPORT_LEVEL);
        }
        $timezone = App::cfg('timezone', 'Asia/Shanghai');
        // 时区设置
        define('TIMEZONE', $timezone);
        date_default_timezone_set(TIMEZONE);
        foreach (self::$extensions as $extension) {
            $extension->autoBind();
        }
        foreach (self::$modules as $id => $module) {
            if (self::$app->moduleLoader->isEnabled($module)) {
                self::$enabledModules[ $id ] = $module;
                if (method_exists($module->clzName, 'urlGroup')) {
                    $prefix = ObjectCaller::callClzMethod($module->clzName, 'urlGroup');
                    if ($prefix && $prefix[0]) {
                        self::registerUrlGroup($prefix, $module->getNamespace());
                    }
                }
                $module->autoBind();
            }
        }
        fire('app\started');
        //检测语言
        if (!defined('LANGUAGE')) {
            $lang        = isset($_COOKIE['language']) ? $_COOKIE['language'] : null;
            $defaultLang = self::$app->configs ['default']->get('language');
            if (preg_match('/^[a-z]{2,3}(-[A-Z]{2,8})?$/i', $lang)) {
                //用户通过cookie设置
                define('LANGUAGE', $lang);
            } else if ($defaultLang && preg_match('/^[a-z]{2,3}(-[a-z]{2,8})?$/i', $defaultLang)) {
                //系统默认
                define('LANGUAGE', $defaultLang);
            } else if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && $_SERVER['HTTP_ACCEPT_LANGUAGE']) {
                //浏览器默认
                define('LANGUAGE', explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE'])[0]);
            } else {
                //框架默认
                define('LANGUAGE', 'en');
            }
        }
        //加载语言
        I18n::addLang(WULA_ROOT . 'lang');
        foreach (self::$enabledModules as $module) {
            $lang = $module->getPath('lang');
            if (is_dir($lang)) {//加载语言
                I18n::addLang($lang);
            }
        }
        foreach (self::$extensions as $extension) {
            $lang = $extension->getPath('lang');
            if (is_dir($lang)) {//加载语言
                I18n::addLang($lang);
            }
        }

        return self::$app;
    }
1214629
protected function debug_query($sql, $params = null) {
        echo '<hr /> (', $this->get_dbtype(), '): ',  htmlentities($sql, ENT_QUOTES, 'UTF-8');
        if($params) {
            echo ' (parameters ';
            print_r($params);
            echo ')';
        }
        echo '<hr />';
    }
1238774
final public static function nowSql()
    {
        try {
            $date = new \DateTimeImmutable(null, self::tzUtc());
            return $date->format('Y-m-d H:i:s');
        } catch (\Exception $e) {
            return null;
        }


    }
384421
public function getLastRawSql()
    {
        if (!$this->logger) {

        }
        if(!isset($this->logger->queries[$this->logger->currentQuery])){
            $rawSql['msg']           = 'queries 没有数据';
            return $rawSql;
        }
        $rawSql = $this->logger->queries[$this->logger->currentQuery];
        $tmp['currentQuery'] = $rawSql;
        $query      = $tmp['currentQuery'];
        $tmp_sql    = $query['sql'];
        $tmp_params = $query['params'];
        count($tmp_params) < 1 ? $tmp_params = [] : null;
        foreach ($tmp_params as $key => $value) {
            if ($value === null) {
                $tmp_sql = preg_replace('/\?/', "NULL", $tmp_sql, 1);
            } else {
                $tmp_sql = preg_replace('/\?/', "'{$value}'", $tmp_sql, 1);
            }

        }
        $tmp['rawSql'] = $tmp_sql;
        return $tmp;
    }
1173370
public function getError()
    {
        if ($this->PDOStatement) {
            $error = $this->PDOStatement->errorInfo();
            $error = $error[1] . ':' . $error[2];
        } else {
            $error = '';
        }

        if ('' != $this->queryStr) {
            $error .= "\n [ SQL语句 ] : " . $this->getLastsql();
        }

        return $error;
    }
1170719
private function query2()
    {
        $this->returnFromCache = false;

        // 语句真正被创建
        try {
            $this->statement->create();
        } catch (MysqlException $e) {
            trigger_error('MYSQL查询错误:' . $e->getMessage(), E_USER_ERROR);
            return [];
        }

        // 取出语句的SQL,用于日志
        $sql = $this->statement->getSql();

        // 检查配置开关
        if (!$this->enabled()) {
            return self::queryStatementAndClear();
        }

        // 重构表名列表
        $tables = $this->statement->getTable();

        // 如果无法解析表名,不缓存,直接返回查询结果
        if (!$tables or !count($tables)) {
            debug(' Unknown table name');
            return self::queryStatementAndClear();
        }

        // 这句是用来载入类文件的
        $cache = CacheFactory::createByType($this->cacheType);

        // 从缓存中取
        $data = $cache->get($sql);

        // 找到(无法缓存false,null)
        if ($data and  $data !== CacheFactory::NOT_FOUND) {
            $this->returnFromCache = true;
            return $data;
        }

        // 从数据库中取
        $data = self::queryStatementAndClear();

        // 设置到缓存中,并与每一个表关联
        foreach ($tables as $name) {
            $cache->set($name, $sql, $data);
        }
        return $data;
    }
324546
public function debug()
    {
        $query = $this->pdo->prepare(<<<SQL
SELECT *
FROM robotstxt__cache1
WHERE base = :base;
SQL
        );
        $query->bindValue('base', $this->base, \PDO::PARAM_STR);
        $query->execute();
        return $query->rowCount() > 0 ? $query->fetch(\PDO::FETCH_ASSOC) : [];
    }