Guest № 0
You can also sign in by:



Александр Черных

(Александр)

Запись в дневнике

MySQL, Docker, производительность, миграция и обновление

Т.к. на машине de004 не используются SSD, то вылезла проблема с производительностью БД под докером.
Сказывается в первую очередь на операциях обновления и записи. Причина: произвольный доступ к диску.

Подходящего "лечения" для VP VPS на Debian 9 не найдено. Изменение scheduler'а диска не подходит.

Принято решение использовать dockerhost.

Однако вылезает ошибка при импорте БД:


ERROR 1118 (42000) at line 2189: Row size too large (> 8126). Changing some columns to TEXT or BLOB or using ROW_FORMAT=DYNAMIC or ROW_FORMAT=COMPRESSED may help. In current row format, BLOB prefix of 768 bytes is stored inline.


На сервере сейчас:

Версия сервера: 10.1.41-MariaDB-0+deb9u1 - Debian 9.9
Версия протокола: 10


Для:
set global innodb_default_row_format = DYNAMIC;

innodb_default_row_format = dynamic

@see
https://dba.stackexchange.com/questions/228635/unable-to-fix-row-size-too-large-even-with-innodb-file-per-table

Необходимо мигрировать на MariaDB starting with 10.4+

https://mariadb.com/kb/en/library/installing-mariadb-deb-files/#installing-mariadb-packages-with-apt

Когда написано: [2019-09-29 20:26:25] - [2019-09-29 20:26:25] 1447



Comment
Comments: 15
 Александр Черных (Sensei) 29.9.2019 in 20:40:27
Например:
UPDATE `UsersManagement_Users` SET `LastActivity`=Now() WHERE `GUID`='9kjginjduk2egss5dtd6iuu4ms-20190827210013-153792-515587' ;
341.381 ms.
 Александр Черных (Sensei) 29.9.2019 in 20:44:34
И, вообще производительность системы (в т.ч. PHP) раза в 2 медленнее чем сейчас на бою ВТАТУ (5.6.40-0+deb8u2).
Напр, до .init.php:12 - 321.08400 ms вместо 119.49900 ms!
 Александр Черных (Sensei) 29.9.2019 in 20:45:35
PHP 7.2.23
 Александр Черных (Sensei) 29.9.2019 in 22:12:49
curl -sS https://downloads.mariadb.com/MariaDB/mariadb_repo_setup | sudo bash

sudo apt update
service mysql stop
sudo apt-get install mariadb-server galera-4 mariadb-client libmariadb3 mariadb-backup mariadb-common

/var/lib/mysql: found previous version 10.1
Failed to stop mysql.service: Unit mysql.service not loaded.
'systemctl stop mysql' returned 5
There is a MySQL server running, but we failed in our attempts to stop it.
Stop it yourself and try again!
dpkg: ошибка при обработке архива /var/cache/apt/archives/mariadb-server-10.4_1%3a10.4.8+maria~stretch_amd64.deb (--unpack):
подпроцесс новый сценарий pre-installation возвратил код ошибки 1
При обработке следующих пакетов произошли ошибки:
/var/cache/apt/archives/mariadb-server-10.4_1%3a10.4.8+maria~stretch_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)
----------
Уже установлен пакет mariadb-server самой новой версии (1:10.4.8+maria~stretch).
Возможно, для исправления этих ошибок вы захотите воспользоваться «apt-get -f install».
Пакеты, имеющие неудовлетворённые зависимости:
mariadb-server : Зависит: mariadb-server-10.4 (>= 1:10.4.8+maria~stretch) но он не будет установлен
E: Неудовлетворённые зависимости. Попытайтесь выполнить «apt --fix-broken install», не указывая имени пакета, (или найдите другое решение).
 Александр Черных (Sensei) 29.9.2019 in 22:23:7
aptitude purge mysql-server mysql-client mysql-common
----

Следующие действия разрешат зависимости:

Удалить следующие пакеты:
1) dbconfig-mysql [2.0.8 (now, oldstable)]
2) libdbd-mysql-perl [4.041-2 (now, oldstable)]
3) libmariadb3 [1:10.4.8+maria~stretch (<NULL>, now)]
4) libmariadbclient18 [1:10.4.8+maria~stretch (<NULL>, now)]
5) libmysqlclient18 [5.5.62-0+deb8u1 (now)]
6) mariadb-backup [1:10.4.8+maria~stretch (<NULL>, now)]
7) mariadb-client [1:10.4.8+maria~stretch (<NULL>, now)]
8) mariadb-client-10.4 [1:10.4.8+maria~stretch (<NULL>, now)]
9) mariadb-client-core-10.4 [1:10.4.8+maria~stretch (<NULL>, now)]
10) mariadb-common [1:10.4.8+maria~stretch (<NULL>, now)]
11) mariadb-server [1:10.4.8+maria~stretch (<NULL>, now)]
12) php5-mysql [5.6.40+dfsg-0+deb8u6 (now)]

Установить следующие пакеты:
13) dbconfig-no-thanks [2.0.8 (oldstable)]



Принять данное решение? [Y/n/q/?] y
Следующие НОВЫЕ пакеты будут установлены:
dbconfig-no-thanks{a}
Следующие пакеты будут УДАЛЕНЫ:
dbconfig-mysql{a} libaio1{u} libcgi-fast-perl{u} libcgi-pm-perl{u} libconfig-inifiles-perl{u} libdbd-mysql-perl{a} libdbi-perl{u}
libencode-locale-perl{u} libfcgi-perl{u} libhtml-parser-perl{u} libhtml-tagset-perl{u} libhtml-template-perl{u} libhttp-date-perl{u}
libhttp-message-perl{u} libio-html-perl{u} libjemalloc1{u} liblwp-mediatypes-perl{u} libmariadb3{a} libmariadbclient18{a}
libmysqlclient18{a} libreadline5{u} liburi-perl{u} mariadb-backup{a} mariadb-client{a} mariadb-client-10.4{a}
mariadb-client-core-10.4{a} mariadb-common{a} mariadb-server{a} mariadb-server-core-10.4{u} mysql-common{p} php5-mysql{a} socat{u}
Следующие частично установленные пакеты будут настроены:
galera-4 libc-bin man-db
 Александр Черных (Sensei) 29.9.2019 in 22:29:46
aptitude install mariadb-server galera-4 mariadb-client libmariadb3 mariadb-backup mariadb-common
---
Настраивается пакет libhttp-message-perl (6.11-1) …
dpkg: зависимости пакетов не позволяют настроить пакет mariadb-server:
mariadb-server зависит от mariadb-server-10.4 (>= 1:10.4.8+maria~stretch), однако:
Пакет mariadb-server-10.4 не установлен.

dpkg: ошибка при обработке пакета mariadb-server (--configure):
проблемы зависимостей — оставляем не настроенным
Настраивается пакет libreadline5:amd64 (5.2+dfsg-3+b1) …
Настраивается пакет libfcgi-perl (0.78-2) …
Настраивается пакет libdbi-perl (1.636-1+b1) …
Настраивается пакет libhtml-template-perl (2.95-2) …
Настраивается пакет mariadb-client-core-10.4 (1:10.4.8+maria~stretch) …
Настраивается пакет libcgi-fast-perl (1:2.12-1) …
Настраивается пакет mariadb-client-10.4 (1:10.4.8+maria~stretch) …
Настраивается пакет mariadb-backup (1:10.4.8+maria~stretch) …
Настраивается пакет libdbd-mysql-perl (4.041-2) …
Настраивается пакет mariadb-client (1:10.4.8+maria~stretch) …
Обрабатываются триггеры для libc-bin (2.24-11+deb9u4) …
При обработке следующих пакетов произошли ошибки:
mariadb-server

Текущее состояние: 1 сломан [+1].
 Александр Черных (Sensei) 29.9.2019 in 22:52:35
sudo apt remove --purge mysql-server mysql-client mysql-common
sudo apt autoremove


reboot
sudo apt-get -f install
sudo apt-get remove mariadb-server
apt-get --purge remove mariadb*
sudo apt remove --purge mysql-server mysql-client mysql-common

 Александр Черных (Sensei) 29.9.2019 in 23:37:32
sudo apt-get install mariadb-server galera-4 mariadb-client libmariadb3 mariadb-backup mariadb-common

и всё в порядке
 Александр Черных (Sensei) 29.9.2019 in 23:41:30
sudo apt-get install mariadb-backup
 Александр Черных (Sensei) 30.9.2019 in 0:45:28
почти та же хрень в итоге... очень медленная запись. Вероятно дело в диске
 Александр Черных (Sensei) 30.9.2019 in 0:45:54
time sysbench --test=fileio --file-total-size=100M --file-num=1000 prepare
 Александр Черных (Sensei) 30.9.2019 in 0:47:17
root@test ~ # time sysbench --test=fileio --file-total-size=100M --file-num=1000 prepare
sysbench 0.4.12: multi-threaded system evaluation benchmark

1000 files, 102Kb each, 99Mb total
Creating files for the test...

real 1m42,824s
user 0m0,004s
sys 0m0,172s
 Александр Черных (Sensei) 30.9.2019 in 0:53:18
там временем на VTATU

root@vtatu ~ # time sysbench --test=fileio --file-total-size=100M --file-num=1000 prepare
sysbench 0.4.12: multi-threaded system evaluation benchmark

1000 files, 102Kb each, 99Mb total
Creating files for the test...

real 1m33.286s
user 0m0.000s
sys 0m0.240s
--

однако

Затронуто 0 строк. (Запрос занял 0.0003 сек.)
UPDATE `UsersManagement_Users` SET `LastActivity`=Now() WHERE `GUID`='9kjginjduk2egss5dtd6iuu4ms-20190827210013-153792-515587'

vs

Затронута 1 строка. (Запрос занял 0.0840 сек.)
UPDATE `UsersManagement_Users` SET `LastActivity`=Now() WHERE `GUID`='9kjginjduk2egss5dtd6iuu4ms-20190827210013-153792-515587'
-
Затронута 1 строка. (Запрос занял 0.5692 сек.)
 Александр Черных (Sensei) 30.9.2019 in 1:19:57
причина в том , что МарияДБ использует другую директорию для конфигов и не обрабатывала тюн!

-rw-r--r-- 1 root 527 сен 9 00:02 mariadb.cnf
drwxr-xr-x 2 root 4096 сен 30 01:16 mariadb.conf.d
 Александр Черных (Sensei) 30.9.2019 in 1:20:23
главное



#
#Variables to adjust:
# query_cache_type (=1)
# tmp_table_size (> 16M)
# max_heap_table_size (> 16M)
# innodb_buffer_pool_size (>= 323M) if possible.


# mysqltuner --user root --pass password
query_cache_type = 1
tmp_table_size = 512M
max_heap_table_size = 512M
innodb_buffer_pool_size = 1024M
innodb_buffer_pool_instances = 4
Произошла ошибка! @vtatu.com __Shutdown_Decorator::renderErrorReport
Ошибка типа [1]: [
Uncaught *{DB\Exception}:
[1114][The table 'Statistics_RequestJournal_Records' is full]

BD={MySQL}
SQL=[INSERT INTO 
		`Statistics_RequestJournal_Records` 
 (
		`ID`, 
		`GUID`, 
		`POUUID`, 
		`ClassName`, 
		`ParentGUID`, 
		`OwnerGUID`, 
		`timeCreated`, 
		`timeModified`, 
		`timeAccessed`, 
		`Description`, 
		`Comments`, 
		`CodeID`, 
		`VersionString`, 
		`Name`, 
		`Hash`, 
		`Order`, 
		`Active`, 
		`timeSynchronized`, 
		`Owner_GUID`, 
		`Owner_POUUID`, 
		`Owner_ClassName`, 
		`Owner_Active`, 
		`ParentObject_GUID`, 
		`ParentObject_POUUID`, 
		`ParentObject_ClassName`, 
		`ParentObject_VersionString`, 
		`Tags`, 
		`REQUEST_METHOD`, 
		`UNIQUE_ID`, 
		`RequestTime_Start`, 
		`HTTP_SCHEME`, 
		`HTTP_HOST`, 
		`HTTP_URL`, 
		`QUERY_STRING`, 
		`HTTP_REFERER`, 
		`HTTP_REFERER_HOST`, 
		`Request_Headers_JSON`, 
		`SessionID`, 
		`Client_IP`, 
		`Client_UserAgent`, 
		`Client_IsRobot`, 
		`Client_IsSearchEngineCrawler`, 
		`Client_IsVulnerabilityScanner`, 
		`Client_Robot_Type`, 
		`Client_Robot_Fami
] в файле [/home/www-master/www/apps/HostSystem/SharedApps/moonlite13.cmf/core.moonlite13.ru/Modules/DBManagement/classes/class.DB_SQL.php] в строке [654]

Текущее(реальное) использование памяти [15'072'552] (15'728'640) из [512M] разрешённых
Участок с ошибкой:
00650:
        }
00651:
        //\System::LoadObjectsList($class_name, $Groups);
00652:
        //var_dump($query);
00653:
        
00654:        throw new \DB\Exception (
00655:
             sprintf(
00656:
                "*Ошибка при исполнении SQL запроса! <br /> MySQL error:[<b>%s</b>]\n While [<b>%s</b>] \n callstack:\n <pre>%s</pre>"
00657:
                ,$message
00658:
                ,$query
00659:
                ,$_tmp_debug_print_backtrace
00660:
            )


Файл целиком:
<?php
/**
 * Класс DB, обеспечивающий работу с SQL базами данных
 * 
 * 
 * @package     DBManagement
 * @author      Premier13 (Черных Александр) <alex@sensei.su>
 * @copyright   Sensei Media Concept(C) 2006
 *
 */
class DB_SQL
    
implements \JsonSerializable
{
    const 
DB_CATEGORY_SQL       "SQL";
    const 
DB_CATEGORY_NOSQL     "NoSQL";
    
    const 
DB_TYPE_MYSQL         "MySQL";
    const 
DB_TYPE_MSSQL         "MSSQL";
    const 
DB_TYPE_ORACLE        "Oracle";
    const 
DB_TYPE_POSTGRESQL    "PostgreSQL";
    
    
    const 
DB_ROLE_PERSISTENT    "Persistent Storage";
    const 
DB_ROLE_TEMPORARY     "Temporary Storage";
    
    
    
    
    const 
INDEX_TYPE_BTREE      "BTREE";
    const 
INDEX_TYPE_FULLTEXT   "FULLTEXT";
    const 
INDEX_TYPE_HASH       "HASH";
    const 
INDEX_TYPE_RTREE      "RTREE";
    
    
    
    
    protected 
$DB_CATEGORY  self::DB_CATEGORY_SQL;
    protected 
$DB_TYPE      self::DB_TYPE_MYSQL;
    protected 
$DB_ROLE      self::DB_ROLE_PERSISTENT;
    
    const 
PROVIDER_ID       NULL;
    
    
    
/**
     * Имя сервера
     *
     * @var string
     */
    
public $dbServer;
    
/**
     * Имя базы активной данных
     *
     * @var string
     */
    
public $dbName;
    
/**
     * Имя пользователя БД
     *
     * @var string
     */
    
public $dbUser;
    
/**
     * Пароль пользователя БД
     *
     * @var string
     */
    
public $dbPass;
    
    
    
    
/**
     * Ссылка на подключение к базе данных
     *
     * @var mixed
     */
    
var $dbConnection;
    
    
    
    
    
    
    
/**
     * Счётчик выполненных запросов к базе данных
     *
     * @var integer
     */
    
var $dbqQueryCounter;
    
/**
     * Лог запросов (текстовый)
     *
     * @var string
     */
    
var $QueryLog;
    
    
    
    var 
$QueryLog_microtime_b;
    var 
$QueryLog_microtime_e;
    var 
$QueryLog_delta;
    var 
$QueryLog_query;
    
    
    
/**
     * Суммарное время выполнения запросов
     *
     * @var float
     */
    
var $sum_delta;                 #time
    
    
    
    
    
    /**
     * Флаг разрешаюшие логирование запросов
     *
     * @var boolean
     */
    
var $enableLogging;
    
/**
     * Структура логов запросов (Порядковый номер, время, время исполнения, запрос)
     *
     * @var MemoryLog
     */
    
protected $_log;
    
    protected 
$_is_persistent_connection    =   false;
    
    protected 
$_is_persistent_connection_enabled    =   true;
    
    protected 
$_is_db_selected false;
    
    
    
//TODO: Реализовать!
    
var $_access_level;
    var 
$_access_rights;
    var 
$_alowed_operators;
    var 
$_alowed_queries;
    
    
    
    
    
    
    
/**
     * Конструктор
     *
     * @param string $server
     * @param string $name
     * @param string $user
     * @param string $pass
     */
    
public function __construct($server="localhost",$name="database",$user="root",$pass="rootpass")
    {
        
$this->dbServer         =   $server;
        
$this->dbName           =   $name;
        
$this->dbUser           =   $user;
        
$this->dbPass           =   $pass;
        
//
        
$this->sum_delta        =   0;
        
//
        
$this->enableLogging    =   true;
        
//
        
$this->_log             =   new MemoryLog();
    }
    
/**
     * Деструктор
     *
     */
    
public function __destruct()
    {
        if(!
$this->isConnectionPersistent())
        {
            if(
$this->isConnected())
            {
                
$this->disconnect();
            }
        }
    }
     
/**
     * Отключение возможности клонирования объекта.
     * Реализация шаблона Singleton
     *
     * @ignore
     */
    
private function __clone() {}
    
    
/**
     *
     * @return string
     */
    
function getProviderType()
    {
        return 
"MySQL";
    }
    
    
/**
     *
     * @return string
     */
    
function getLastErrorNo()
    {
        return 
mysql_errno($this->getDBConnection());
    }
    
/**
     *
     * @return string
     */
    
function getLastErrorMessage()
    {
        return 
mysql_error($this->getDBConnection());
    }
    
    
    
    
/**
     * Получить категорию БД
     *
     * @return string
     */
    
function getCategory()
    {
        return 
$this->DB_CATEGORY;
    }
    
    
/**
     * Получить тип базы данных
     * 
     * @return string
     */
    
function getType()
    {
        return 
$this->DB_TYPE;
    }
    
    
    function 
getRole()
    {
        return 
$this->DB_ROLE;
    }
    
    
/**
     * Получить имя сервера
     *
     * @return string
     */
    
public function getServerName ()
    {
        
$result =   $this->dbServer;
        return 
$result;
    }
    
    
/**
     * Получить имя активной базы данных в подключении
     *
     * @return string
     */
    
public function getDBName ()
    {
        
$result =   $this->dbName;
        return 
$result;
    }
    
/**
     * 
     * @param string $value
     * @return DB_SQL
     */
    
function &setDBName($value)
    {
        
$this->dbName $value;
        return 
$this;
    }
    
    
    
/**
     * 
     * @return string
     */
    
public function getUserName()
    {
        return 
$this->dbUser;
    }
    
/**
     * 
     * @return string
     */
    
public function getUserPassword()
    {
        return 
$this->dbPass;
    }
    
    
    
    
/**
     * Реализация метода интерфейса JsonSerializable (PHP 5 >= 5.4.0, PHP 7)
     *
     * Цель метода - исключение проблем с сериализацией объектов
     *  и в частности наличием в них переменных типа resource.
     *  
     * @see http://php.net/manual/ru/jsonserializable.jsonserialize.php
     *
     *
     *
     *
     * @return string
     */
    
function jsonSerialize()
    {
        
$result = array();
        
//
        
$result["Server"]   = $this->dbServer;
        
$result["Databale"] = $this->dbName;
        
$result["User"]     = $this->dbUser;
        
$result["Passowrd"] = $this->dbPass;
        
//
        
$result["IsPersistentConnection"]        = $this->_is_persistent_connection;
        
$result["IsPersistentConnectionEnabled"] = $this->_is_persistent_connection_enabled;
        
$result["IsDbSelected"]                  = $this->_is_db_selected;
        
//
        
$result["Connection"] = $this->dbConnection true false;
        
//
        
        
        
        
        
$result["enableLogging"] = $this->enableLogging;
        
//
        
$result["QueryLog"]        = $this->QueryLog;
        
        
        
$result["QueryLog_microtime_b"] = $this->QueryLog_microtime_b;
        
$result["QueryLog_microtime_e"] = $this->QueryLog_microtime_e;
        
$result["QueryLog_delta"]       = $this->QueryLog_delta;
        
$result["QueryLog_query"]       = $this->QueryLog_query;
        
        
// Суммарное время выполнения запросов
        
        
$result["TotalDBTimeUsed"]      = $this->sum_delta;
        
$result["TotalQueriesCount"]    = $this->dbqQueryCounter;
        
        
//
        
$result["sum_delta"]       = $this->sum_delta;
        
$result["dbqQueryCounter"] = $this->dbqQueryCounter;
        
        
//
        
        
        
        //
        //$this->_log             =   new MemoryLog();
        
        
        
        
        
        //return $this->toSimpleArray();
        //
        
return $result;
    }
    
    
    
/**
     * 
     * @return number
     */
    
function getTotalQueriesCount()
    {
        return 
$this->dbqQueryCounter;;
    }
    
/**
     *
     * @return number
     */
    
function getTotalDBTimeUsed()
    {
        return 
$this->sum_delta;;
    }
    
    
    function &
connect()
    {
        
//
        
$this->dbConnection     =   mysql_pconnect($this->dbServer$this->dbUser$this->dbPass);
        if(!
$this->dbConnection)
        {
            
// TODO: пересмотреть!
            
$_tmp_debug_print_backtrace =   "";
                
ob_start();
                    
debug_print_backtrace();
                    
$_tmp_debug_print_backtrace =   ob_get_contents();
                
ob_end_clean();
                
//
            
throw new DBException (
                 
sprintf(
                    
"Ошибка при подключении к серверу БД! <br /> MySQL error:[<b>%s</b>]\n While [<b>CONNECT TO BD Server</b>] \n callstack:\n <pre>%s</pre>"
                    
,mysql_error()
                    
//,$query
                    
,$_tmp_debug_print_backtrace
                 
)
                ,
503
              
);
            
//$result = false;
            
die("503");
            
//
        
}
        
$this->_is_persistent_connection    =   true;
        
//
        
        
if($this->isConnected())
        {
            
$this->onConnect();
        }
        
        return 
$this;
    }
    
    function &
disconnect()
    {
        if(
$this->isConnected())
        {
            
        }
        
        return 
$this;
    }
    
    
/**
     * Подключена ли БД
     *
     * @return boolean
     */
    
function isConnected()
    {
        return 
$this->dbConnection true false;
    }
    
    function 
isConnectionPersistent()
    {
        return  
$this->_is_persistent_connection;
    }
    
    function &
onConnect()
    {
        
$this->resetCounters();
        
//
        
$queries   = array();
        
$queries[] = "SET NAMES UTF8;";
        
$queries[] = "SET COLLATION_CONNECTION=UTF8_GENERAL_CI;";
        
        
        
// @todo только на текстовых полях и полях ввода пользователями (соц.сети)
        // Storage for variable-length columns includes length bytes, 
        // which are counted toward the row size. 
        // For example, a VARCHAR(255) CHARACTER SET utf8mb3 column 
        // takes two bytes to store the length of the value, so each value can take up to 767 bytes.
        //$queries[] = "SET COLLATION_CONNECTION=utf8mb4_unicode_ci;";
        
        // https://mathiasbynens.be/notes/mysql-utf8mb4
        //$queries[] = "SET COLLATION_CONNECTION=utf8mb4_unicode_ci;";
        
        //
        // The default SQL mode in MySQL 5.7 includes these modes: ONLY_FULL_GROUP_BY, STRICT_TRANS_TABLES, NO_ZERO_IN_DATE, NO_ZERO_DATE, ERROR_FOR_DIVISION_BY_ZERO, NO_AUTO_CREATE_USER, and NO_ENGINE_SUBSTITUTION.
        // SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '0000-00-00 00:00:00' for column
        
$queries[] = "SET SQL_MODE='ALLOW_INVALID_DATES';";
        
//
        
foreach($queries as $query)
        {
            
//$Result1    =   $this->ExecQuery($query,false);
            
            
if(!$this->execQuery($query,false))
            {
                
//
            
}
        }
        
//
        
return $this;
    }
    
    function 
selectDB($dbname)
    {
        return 
false;
    }
    
    
    
    function 
onConnectionError($errorno,$message)
    {
        
//
        
$_tmp_debug_print_backtrace =   "";
        
//
        
ob_start();
        
debug_print_backtrace();
        
$_tmp_debug_print_backtrace =   ob_get_contents();
        
ob_end_clean();
        
//
        
throw new \DB\Exception (
            
sprintf(
                
"Ошибка при подключении к серверу БД!"."<br />"
                
."Ошибка:[<b>%s</b>] (<b>%s</b>)"."<br />"
                
."Стэк вызова:"."<br />"
                
."<pre>%s</pre>"
                
,$message
                
,$errorno
                
//,$query
                
,$_tmp_debug_print_backtrace
            
)
            ,
503
            
,$this
        
);
        
$result false;
        
//
        
die("503");
        
//
        
return $result;
    }
    
    
    
    
    
    
    function 
onSwitchDbError($dbname,$errorno,$message)
    {
        
// Временное решение! TODO: довести до ума!
        
if(class_exists("__Shutdown_Processor"))
        {
            @
ini_set('display_errors'false);
        }
        
//
        //echo "<pre>";            debug_print_backtrace(); echo "</pre>";            die();
        //
        
$_tmp_debug_print_backtrace =   "";
        
ob_start();
        
debug_print_backtrace();
        
$_tmp_debug_print_backtrace =   ob_get_contents();
        
ob_end_clean();
        
//
        
throw new \DB\Exception (
            
sprintf(
                
"Ошибка при переключении на БД [<b>%s</b>]!"."\n<br />\n"
                
."Ошибка:[<b>%s</b>] (<b>%s</b>)"."<br />"
                
."\n<br />\n"
                
."\n<br />\n"
                
."Стэк вызова:"."<br />"
                
,$dbname
                
,$message
                
,$errorno
                
,$_tmp_debug_print_backtrace
            
)
            ,
503
            
,$this
            
,""
            
,debug_backtrace()
        );
        
//
        
$result false;
        die(
"503");
        
//
        
return $result;
    }
    
    
    
    
    
/**
     * 
     * @global Engine $engine
     * 
     * @param string $query
     * @param string $errorno
     * @param string $message
     * @throws DBException
     * @return boolean
     */
    
function onQueryError($query,$errorno,$message)
    {
        global 
$engine;
        
        
// Временное решение! TODO: довести до ума!
        
if(class_exists("__Shutdown_Processor"))
        {
            @
ini_set('display_errors'false);
        }
            
        if(
$engine->isDevServer())
        {
            echo 
sprintf(
                 
"[%s]< br />"
                
,$message
                
//,$query
            
);
        }
        
        
$_tmp_debug_print_backtrace =   "";
        
        
ob_start();
        
debug_print_backtrace();
        
$_tmp_debug_print_backtrace =   ob_get_contents();
        
//die($query);
        //
        
ob_end_clean();
        
//
        
        
        
if(1)
        {
            
error_log($query);
            
//error_log($_tmp_debug_print_backtrace);
            
            
$_trace_stack debug_backtrace();
            
array_shift($_trace_stack);
            
            
            
$___log "";
            
            foreach(
$_trace_stack as $key => $record)
            {
                
//
                // Борьба с наличием рекурсии
                //$backtrace = unserialize(    serialize(debug_backtrace()));
                //
                //$___args    =   NULL;
                //$___args    =   (isset($_trace_stack[$key]["args"])) ? unserialize(serialize($_trace_stack[$key]["args"])) : $___args;
                //
                
$___log .= sprintf(
                    
"#%s [%s] [%s][%s][%s] (%s); on [%s:%s] \n"
                    
,$key
                    
,(isset($record["object"])                                          ? get_class($record["object"])  : "")
                    ,(isset(
$record["class"]))                                          ? $record["class"]              : ""
                    
,(isset($record["type"]))                                           ? $record["type"]               : ""
                    
,(isset($record["function"]))                                       ? $record["function"]           : ""
                    
/*,(isset($_trace_stack[$key]["args"])
                    AND is_array($_trace_stack[$key]["args"]))
                    ?
                    //implode(",",$_trace_stack[$key]["args"])
                    //"I::".
                    \Debug::implode_func_arg($_trace_stack[$key]["args"])
                    //."<br />".print_r($_trace_stack[$key]["args"],true)
                      :
                     ((isset($_trace_stack[$key]["args"]))                                       ? \Debug::implode_func_arg($_trace_stack[$key]["args"])           : "")
                    */
                    
,"..."
                    
,(isset($record["file"]))                                       ? $record["file"]           : "?"
                    
,(isset($record["line"]))                                       ? $record["line"]           : "?"
                
);
            }
            
error_log($___log);
            
//error_log(Debug::Bugtrace("ext",true,false,$_trace));
        
}
        
//\System::LoadObjectsList($class_name, $Groups);
        //var_dump($query);
        
        
throw new \DB\Exception (
             
sprintf(
                
"*Ошибка при исполнении SQL запроса! <br /> MySQL error:[<b>%s</b>]\n While [<b>%s</b>] \n callstack:\n <pre>%s</pre>"
                
,$message
                
,$query
                
,$_tmp_debug_print_backtrace
            
)
            ,
503
            
,$this
            
,$query
            
,debug_backtrace()
        );
        
$result false;
        die(
"503");
        
        return 
$result;
    }
    
    
/**
     * 
     * @param mixed $handle
     * @return NULL
     */
    
function &instantiateQueryResult($handle=NULL)
    {
        
$result = new \DBQueryResult();
        
//
        
if($handle)
        {
            
$result->setHandle($handle);
        }
        
//
        
return $result;
    }
    
    
    
    
    
    
    
    
    function &
resetCounters()
    {
        
//
        
$this->dbqQueryCounter  =   0;
        
$this->sum_delta        =   0;
        
//
        
return $this;
    }
    
    
/**
     * 
     * @return self
     */
    
function &disableLogging()
    {
        
$this->enableLogging false;
        
//
        
return $this;
    }
    
/**
     * 
     * @return self
     */
    
function &enableLogging()
    {
        
$this->enableLogging true;
        
//
        
return $this;
    }
    
    
    
/**
     * Инициализация подключения к БД
     *
     */
    
public function dbInit()
    {
        
$this->connect();
    }
    
/**
     * Закрытие подключения к БД
     *
     * @return boolean
     */
    
public function dbClose()
    {
        
$this->disconnect();
    }
    
    
    
    
    
    
    
    
    
    
    
    
/**
     * Исполнение SQL запроса
     *
     * @global $engine
     * @param string $query SQL запрос
     * @param boolean $do_dbselect флаг разрешающий выбор SQL БД при исполнении запроса
     * @return resource результат выполения запроса (mysql_result)
     */
    
public function &ExecQuery($query,$do_dbselect=true)
    {
        
$result NULL;
        return 
$result;
    }
    
    
    
    
/**
     * Расширенная функция (метод) выполнения SQL-запроса
     *
     * @param SQLQuery $query
     * @param boolean $do_dbselect
     * @throws DBException
     * @return DBQueryResult
     */
    
public function &ExtendedExecQuery($query,$do_dbselect=true)
    {
        
$result NULL;
        return 
$result;
    }
    
/**
     * 
     * @param \SQLQuery $query
     * @param boolean $do_dbselect
     * @return \DBQueryResult
     */
    
public function &execQueryExtended($query,$do_dbselect=true)
    {
        if(
is_string($query))
        {
            return 
$this->instantiateQueryResult($this->ExecQuery($query));
        }
        
//
        
return $this->instantiateQueryResult($this->ExecQuery($query->toSQL()));
        
    }
    
    
    
        
    
    
    
    
/**
     * Получение числа записей получаемых при выполнении SQL запроса
     *
     * @param string $query SQL запрос
     * @param boolean $do_dbselect флаг разрешающий выбор SQL БД при исполнении запроса
     * @return integer $this->ExecQuery($query,$do_dbselect);
     */
    
public function getQueryRowsCount($query,$do_dbselect=false)
    {
        
$result NULL;
        
//
        
$query         =   str_replace(" * "," COUNT(*) as `num_count` ",$query);
        
//
        
$dbresult      =   $this->ExtendedExecQuery($query,$do_dbselect);
        
//
        
if($dbresult)
        {
            
$row_recordset =   $dbresult->getCurrentRowRecordset("assoc");
            
$result        =   $row_recordset['num_count'];
            
//
            
$dbresult->free();
        }
        
//
        
return $result;
    }
    
    
/**
     * 
     * 
     * @deprecated
     * 
     * @param string $query
     * @param boolean $do_dbselect
     * @return array
     */
    
function DBQueryResultAsArray($query,$do_dbselect=true)
    {
        
$result = array();
        
//
        
$dbresult      =   $this->ExtendedExecQuery($query,$do_dbselect);
        
//
        
if($dbresult)
        {
            
$result        =   $dbresult->asArray(true);
        }
        
//
        
return $result;
    }
    
    
    
    
    
    
/**
     * Получение списка имён баз данных на текущем сервере
     * (Замена mysql_list_dbs($this->dbConnection);)
     *
     * SHOW databases [ LIKE wild-card ]
     *
     * @return array
     */
    
public function getDBs ()
    {
        
$result =   array();
        
//
        
$query      =   'SHOW DATABASES';
        
$dbresult   =   $this->ExtendedExecQuery($query,false);
        
//
        
while ($rec_db  =   $dbresult->getCurrentRowRecordset(DBQueryResult::FETCH_MODE_INDEX))
        {
            
$result[]   =   $rec_db[0];
        }
        
//
        
$dbresult->free();
        
//
        
return $result;
    }
    
    
    
    
    
/**
     * Получение списка имён таблиц выбранной базы данных
     *
     * @param string $db_name имя базы данных
     * @return array
     */
    
public function getDBTables ($db_name=NULL)
    {
        
$result =   array();
        
//
        
if(!mb_strlen($db_name))
        {
            
$db_name      =   $this->getDBName();
        }
        
//
        //SHOW [FULL] TABLES [FROM db_name]  [LIKE 'pattern' | WHERE expr]
        //
        
$query      =   "SHOW TABLES FROM ".$this->quoteIdentifier($db_name).";";
        
//
        
$dbresult   =   $this->ExtendedExecQuery($query,false);
        
//
        
while ($row  =   $dbresult->getCurrentRowRecordset(DBQueryResult::FETCH_MODE_INDEX))
        {
            
$result[]   =   $row[0];
        }
        
//
        
$dbresult->free();
        return 
$result;
    }
    
    
/**
     * 
        Table
        Non_unique
        Key_name
        Seq_in_index
        Column_name
        Collation
        Cardinality
        Sub_part
        Packed
        Null
        Index_type
        Comment
        Index_comment

     * @param string $table_name
     * @param mixed $filter
     * @param array $options
     * @return mixed[]|NULL[]
     */
    
function getDBTableIndexes($table_name,$filter=NULL,$options=array())
    {
        
$result =   array();
        
//
        
        //
        /*
        $default_filter = array(
            "Index_type" => array(),
        );
        */
        //
        
$query      =   "SHOW INDEX FROM ".$this->quoteIdentifier($table_name).";";
        
//
        
if(count($filter))
        {
           if(isset(
$filter["Index_type"]) AND count($filter["Index_type"]))
           {
               
$condition = \DBPropertyCondition::instantiate("Index_type"                   ,$filter["Index_type"]    ,"IN");
               
               
               
//System::PrintArray($condition->toSQL());
               
               
               
$query      =   "SHOW INDEX \n FROM \n".$this->quoteIdentifier($table_name)."\n WHERE \n".$condition->toSQL().";";
               
           }
        }
        
//
        //System::PrintArray($query);
        //
        
$dbresult   =   $this->ExtendedExecQuery($query,false);
        
//
        
while ($row  =   $dbresult->getCurrentRowRecordset(DBQueryResult::FETCH_MODE_ASSOC))
        {
            
//$result[]   =   $row[0];
            
$result[]   =   $row;
        }
        
//
        
$dbresult->free();
        return 
$result;
    }
    
    
/**
     * 
     * @param string $table_name
     * @param string $fields
     * @param string $index_name
     * @param array $options
     * @return DBQueryResult
     */
    
function &addFullTextIndexTo($table_name,$fields,$index_name NULL,$options=array())
    {
        
//$fields_string = "";
        //
        
        //
        
$fields_quoted = array();
        
//
        
foreach ($fields as $key => $field_name)
        {
            if(
strlen($field_name))
            {
                
$fields_quoted[$key] = $this->quoteIdentifier($field_name);
            }
        }
        
//
        
$sql_query sprintf(
            
"ALTER TABLE %s ADD FULLTEXT %s (%s);"
            
,$this->quoteIdentifier($table_name)
            ,
strlen($index_name) ? $this->quoteIdentifier($index_name) : ""
            
,implode(","$fields_quoted)
        );
        
//
        
$dbresult   =   $this->ExtendedExecQuery($sql_query,false);
        
//
        
return $dbresult;
    }
    
    
/**
     * 
     * @param string $table_name
     * @param string $index_name
     * @param array $options
     * @return DBQueryResult
     */
    
function &dropIndexByName($table_name,$index_name,$options=array())
    {
        
// ALTER TABLE `VTatu_Artists` DROP INDEX `TextSearch_Index_Names_2`;
        //
        
$sql_query sprintf(
            
"ALTER TABLE %s  DROP INDEX %s;"
            
,$this->quoteIdentifier($table_name)
            ,
$this->quoteIdentifier($index_name)
        );
        
//
        
$dbresult   =   $this->ExtendedExecQuery($sql_query,false);
        
//
        
return $dbresult;
    }
    
    
    
    
    
    
    
    
    
    
/**
     * Получение информации о полях таблицы
     * 
     * SHOW COLUMNS FROM `UsersManagement_Authentication_Credentials`
     * SHOW FULL COLUMNS FROM `UsersManagement_Authentication_Credentials`
     * 
     * 
     *      [Field] => id
            [Type] => int(7)
            [Null] =>
            [Key] => PRI
            [Default] =>
            [Extra] => auto_increment
     *
     * @param string $tblName
     * @param string $dbName
     * @param string $full
     * @return array
     */
    
public function getFieldsList($tblName,$dbName=NULL,$full=true)
    {
        
//
        
$query sprintf(
            
$full "SHOW FULL COLUMNS FROM %s;" "SHOW COLUMNS FROM %s;"
            
,$this->quoteIdentifier($tblName)
        );
        
//
        
if($dbName !== NULL)
        {
            
$query sprintf(
                
$full "SHOW FULL COLUMNS FROM %s;" "SHOW COLUMNS FROM %s.%s;"
                
,$this->quoteIdentifier($dbName)
                ,
$this->quoteIdentifier($tblName)
            );
        }
        
        
$dbresult $this->ExtendedExecQuery($query);
        
        if(
$dbresult)
        {
            
$result   =   $dbresult->asArray(true);
        }
        
        
        
//$str = "";
        
        
foreach($result as $key => $value)
        {
            
//
            
if(!isset($result[$key]["TypeModificator"]))
            {
                
$result[$key]["TypeModificator"] = NULL;
            }
            
//
            
$result[$key]["FullType"] = $result[$key]["Type"];
            
//$result[$key]["Type"]     = NULL;
            //
            
$matches NULL;
            
//
            
if(preg_match("/^([^\(\)]*)\((.*)\)(.*)$/uis"$result[$key]["FullType"],$matches))
            {
                
$result[$key]["Type"]            = trim($matches[1]);
                
$result[$key]["TypeModificator"] = trim($matches[3]);
                
                
//$result[$key]["_"]["Type"]       = $value["FullType"];
                
                
                
if(!key_exists("Length"$value))
                {
                    
$result[$key]["Length"] = $matches[2];
                }
                
                
                
                
$result[$key]["."]              = $matches;
            }
            
//
        
}
        
//
        
return $result;
    }
    
    
    
    
    
    
    
    
    
    
/**
     * Проверка на наличие указаной БД на сервере
     * 
     * @param string $name
     * @param string $reset_cache
     * @return boolean
     */
    
function existsDB($name=NULL,$reset_cache=false)
    {
        static 
$dbs NULL;
        
        if(
$dbs === NULL OR $reset_cache)
        {
            
$dbs $this->getDBs();
        }
        
        if(
$name === NULL)
        {
            
$name =  $this->getDBName();
        }
        
        return 
in_array($name$dbs);
    }
    
    
/**
     * Исполнить запрос на создание базы данных
     *
     * @param string $db_name
     * @param boolean $if_not_exists
     * @return boolean
     */
    
function createDB($db_name='',$if_not_exists=true)
    {
        
$query  =   sprintf(
             
"CREATE DATABASE IF NOT EXISTS %s %s;"
            
,$this->quoteIdentifier($db_name)
            ,
'DEFAULT CHARSET=utf8 COLLATE utf8_unicode_ci'
        
);
        return 
$this->ExecQuery($query,false);
    }
    
/**
     * Получение числа записей в таблице выбранной базы данных
     *
     * @param string $db_tablename
     * @param string $db_name
     * @return integer
     */
    
public function getCountDBTableRecords ($db_tablename='',$db_name='')
    {
        
$result =   -1;
        
//
        
if(mb_strlen($db_name) < 1)
        {
            
$db_name      =   $this->getDBName();
        }
        
//
        
$query  =   sprintf(
            
"SELECT COUNT(*) as `num_count` FROM %s.%s;"
            
,$this->quoteIdentifier($db_name)
            ,
$this->quoteIdentifier($db_tablename)
        );
        
//
        //
        
$dbresult   =   $this->ExtendedExecQuery($query,false);
        
//
        
if($dbresult)
        {
            
$row_recordset  =   $dbresult->getCurrentRowRecordset(DBQueryResult::FETCH_MODE_ASSOC);
            
$result         =   $row_recordset["num_count"];
            
$dbresult->free();
        }
        
//
        
return $result;
    }
    
    
/**
     * Получение информации о таблицах базы данных
     *
     * @param string $dbname имя базы данных
     * @return array
     */
    
public function gatherTablesInfo($dbname="")
    {
        
$result =   array();
        
//
        
if(mb_strlen($dbname) < 1)
        {
            
$dbname      =   $this->getDBName();
        }
        
//
        
$query  =   sprintf("SHOW TABLE STATUS FROM %s;",$this->quoteIdentifier($dbname));
        
//
        
$dbresult   =   $this->ExtendedExecQuery($query,false);
        
//
        
if($dbresult)
        {
            while (
$row  =   $dbresult->getCurrentRowRecordset(DBQueryResult::FETCH_MODE_ASSOC))
            {
                
$result[$row['Name']] =   array();
                
$result[$row['Name']]['Name']         =   $row['Name'];
                
$result[$row['Name']]['Data_length']  =   $row['Data_length'];
                
$result[$row['Name']]['Index_length'] =   $row['Index_length'];
                
$result[$row['Name']]['Rows']         =   $row['Rows'];
            }
            
$dbresult->free();
        }
        
//
        
return $result;
    }
    
    
    
    
/**
     * Проверка наличия таблицы в активной базе данных
     *
     * @param string $table_name имя таблицы базы данных
     * @return boolean
     */
    
public function askTableExists ($table_name,$do_dbselect=true)
    {
        
$result =   NULL;
        
//
        
if(mb_strlen($table_name) < )
        {
            return 
$result;
        }
        
//
        
$query  =   sprintf("SHOW TABLES LIKE %s;",$this->quoteString($table_name));
        
//
        
$dbresult   =   $this->ExtendedExecQuery($query,$do_dbselect);
        
//
        
if($dbresult)
        {
            
$result $dbresult->getRowsCount();
            
$dbresult->free();
        }
        
//
        
return $result;
    }
    
    
/**
     * Проверка наличия базы данных на активном сервере
     *
     * @param string $dbname имя базы данных
     * @return boolean
     */
    
public function askDatabaseExists ($dbname)
    {
        
$result =   NULL;
        
//
        
if(mb_strlen($dbname) < 1)
        {
            return 
$result;
        }
        
//
        
$query  =   sprintf("SHOW DATABASES LIKE %s;",$this->quoteString($dbname));
        
//
        
$dbresult   =   $this->ExtendedExecQuery($query,false);
        
//
        
if($dbresult)
        {
            
$result $dbresult->getRowsCount();
            
$dbresult->free();
        }
        
//
        
return $result;
    }
    
    
    
    
    
    
    
    
    
    
    
/**
     * Проверка наличия таблицы в активной базе данных
     *
     * @param string $table_name имя таблицы базы данных
     * @return integer
     */
    
public function TableExists ($table_name,$do_dbselect=true)
    {
        if(!
$this->askTableExists($table_name,$do_dbselect))
        {
            
//return -1;
            
return false;
        }
        
//
        
return 1;
    }
    
    
    
/**
     * Проверка наличия базы данных на активном сервере
     *
     * @param string $dbname имя базы данных
     * @return integer
     */
    
public function DatabaseExists ($dbname)
    {
        if(
$this->askDatabaseExists($dbname))
        {
            return -
1;
        }
        
//
        
return 1;
    }
    
    
    
    
    
/**
     * Добавление нового поля в таблицу БД, если оно отсутствует
     *
     * @param string $tblName имя таблицы
     * @param string $clName имя добавляемого поля
     * @param string $clParams параметры добавляемого поля
     * @param string $PredclName имя поля передшествующего добавляемому
     * @return boolean
     */
    
public function addColumnIfItDoesNotExist($tblName,$clName,$clParams,$PredclName)
    {
        
$result NULL;
        
//
        
$query sprintf(
            
"SHOW COLUMNS FROM %s LIKE %s;"
            
,$this->quoteIdentifier($tblName)
            ,
$this->quoteString($clName)
        );
        
//
        
$dbresult   =   $this->ExtendedExecQuery($query,false);
        
//
        
if($dbresult)
        {
            
$exists $dbresult->getRowsCount();
            
$dbresult->free();
        }
        
//
        
        
if(!$exists)
        {
            
$query 
                 
"ALTER TABLE "." ".$this->quoteIdentifier($tblName)." "
                
."ADD COLUMN {$this->quoteIdentifier($clName)} {$clParams} "
                
."AFTER {$this->quoteIdentifier($PredclName)}"
                
.";"
            
;
            
$result_cmd $this->ExecQuery($query);
            if(!
$result_cmd)
            {
                
$result false;
            }
        }
        
//
        
return $result;
    }
    
    
    
    
    
/**
     * Переключиться на другую БД в текущем <b>подключении</b>
     *
     * Возвращает имя установленой БД
     *
     * @param string $db_name
     * @throws DBException
     * @return string
     */
    
function switchDB($db_name)
    {
        
$this->selectDB($db_name);
        
$this->dbName $db_name;
        
        return 
$this->dbName;
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
/**
     * Получить отчёт о текущем состоянии сервера
     *
     *
     * @param boolean $print
     * @return string
     */
    
function getServerStats($_format="struct",$print=false)
    {
        
        
$result    =  NULL;
        
//
        
$status explode('  'mysqli_stat($this->dbConnection));
        
//Returns a string with the status for uptime, threads, queries, open tables, flush tables and queries per second.
        // For a complete list of other status variables, you have to use the SHOW STATUS SQL command
        
switch(mb_strtolower($_format,"UTF-8"))
        {
            case 
"string" :
            {
                
$result    =  print_r($status,true);
                break;
            }
            case 
"array" :
            case 
"struct" :
            {
                
$result =   $status;
                break;
            }
        }
        
        return 
$result;
    }
    
    
    
    
    
    
    
    
/**
     * Получить отчёт о текущем состоянии сервера
     * 
     * @deprecated use getServerStats
     *
     * @param boolean $print
     * @return string
     */
    
function ServerStats($_format="struct",$print=false)
    {
        return 
$this->getServerStats($_format,$print);
    }
    
    
    
    
    
    
/**
     * Получить лог запросов
     *
     * @return MemoryLog
     */
    
function &getQueryLog()
    {
        return 
$this->_log;
    }
    
    
    
/**
     * Получить ссылку на логгер (SQL) запросов
     *
     * @todo: Написать логгер SQL запросов (запись в файл построчно, с сериализацией, каждого отдельного запроса. заголовок лога? (с отдалочной информацией, в т.ч. и по формату)
     *
     * @return MemoryLog
     */
    
function &getQueryLogger()
    {
    
        return 
$this->_log;
    }
    
    
    
    
/**
     * Формирование информации о выполныенных запросах в соответствии с указанным шаблоном
     * 
     * @deprecated
     *
     * @param string $_rec_tmpl шаблон строки информации о выполненносм запросе (формат sprintf, порядок: порядковый номер, время выполенения запроса, время затраченное на запрос, запрос)
     * @return string
     */
    
public function QueryLogAsText($_rec_tmpl=NULL)
    {
        
$_result =   '';
        
        if(
$_rec_tmpl === NULL)
        {
            
$_rec_tmpl "<br />[<strong>%s</strong>][%s][<strong>&Delta;=%s</strong>][%s]<br />";
        }
        
        
        
#
        #   Рендеринг данных
        #
        
$_data  =   $this->_log->GetRawData();
        
#
        #
        
foreach($_data as $record)
        {
            
$_result .= sprintf(
                
#"<br />[<strong>%s</strong>][%s][<strong>&Delta;=%s</strong>][%s]<br />"
                 
$_rec_tmpl
                
,$record['No']
                ,
$record['DateTime']
                ,
$record['delta']
                ,
$record['Query']
            );
        }
        
#
        #
        
return $_result;
    }
    
    
    
/**
     * Формирование информации о выполныенных запросах в соответствии с указанным шаблоном
     * 
     * @deprecated
     *
     * @param string $_rec_tmpl шаблон строки информации о выполненносм запросе (формат sprintf, порядок: порядковый номер, время выполенения запроса, время затраченное на запрос, запрос)
     * @return string
     */
    
public function renderQueryLog()
    {
        
$_result =   "";
        
//
        
$_data  =   $this->_log->getRawData();
        
//
        
$_result '<table class="table table-bordered table-striped table-hover">';
        
        foreach(
$_data as $record)
        {
            
$_result .= "<tr>";
            
            
$_result .= "<th>".$record['No']."</th>";
            
            
$_result .= "<td>".$record['DateTime']."</td>";
            
            
$_result .= "<td>[<strong>&Delta;=".$record['delta']."</strong>]</td>";
            
            
$_result .= "<td>".\SMC\HTML::TextAsHTML($record['Query'])."</td>";
            
            
$_result .= "</tr>";
        }
        
        
$_result "</table>";
        
//
        
return $_result;
    }
    
    
    
    
    
/**
     * Получить сводку о базе данных (хранилище/источнике)
     * 
     * 
     * @var array $exclude_tables
     * @return array
     */
    
function getSummary($exclude_tables=array())
    {
        
$result = array();
        
//
        
$result["Stats"] = array();
        
$result["Stats"]["nTables"]  = 0;
        
$result["Stats"]["nRecords"] = 0;
        
$result["Stats"]["DataSize"] = 0;
        
//
        
        
        
$DBResult $this->extendedExecQuery("SHOW TABLE STATUS;");
        
        
$tables_info $DBResult->asArray(true);
        
//
        
foreach ($tables_info as $data)
        {
            if(
in_array($data["Name"], $exclude_tables))
            {
                continue;
            }
            
            
$result["Stats"]["nTables"]++;
            
$result["Stats"]["nRecords"] += (double) $data["Rows"];
            
$result["Stats"]["DataSize"] += (double) $data["Data_length"];
        }
        
//
        
$result["Category"] = $this->getCategory();
        
$result["Type"]     = $this->getType();
        
$result["Server"]   = $this->getServerName();
        
$result["Name"]     = $this->getDBName();
        
//
        
$result["Role"]     = $this->getRole();
        
//
        
return $result;
    }
    
    
    
    
    
    
    
    
    
    
    
/**
     * PostgreSQL requires double quotes for identifier (SQL standard)
     * 
     * Both Oracle and MySQL let you use reserved words as object names by representing the name with a quoted identifier. However, MySQL allows some reserved words such as DATE and TIMESTAMP to be used as unquoted identifier for object names, although this is not allowed in Oracle.
     * SQL Developer appends an underscore (_) to the name of a MySQL object that is an Oracle reserved word.
     * 
     * //MySQL allows to use single and double quotes for data and for identifiers
     * //PostgreSQL requires single quotes for data (SQL standard)
     * 
     * @return string
     */
    
function getIdentifierQuotationCharacter()
    {
        switch (
$this->DB_TYPE)
        {
            case 
self::DB_TYPE_POSTGRESQL:
            {
                
// PostgreSQL requires double quotes for identifier (SQL standard)
                
return '"';
                break;
            }
            
            case 
self::DB_TYPE_MYSQL:
            case 
self::DB_TYPE_ORACLE:
            default:
            {
                
//Both Oracle and MySQL let you use reserved words as object names by representing the name with a quoted identifier. However, MySQL allows some reserved words such as DATE and TIMESTAMP to be used as unquoted identifier for object names, although this is not allowed in Oracle. SQL Developer appends an underscore (_) to the name of a MySQL object that is an Oracle reserved word.
                
return "`";
                break;
            }
        }
    }
    
    
    
    
    
    
    
    function 
real_escape_string($string)
    {
        return 
"'".$string."'";
    }
    
    function 
quote_string($value)
    {
        if(
$value === NULL)
        {
            
$value    =   "NULL";
        }
        else
        {
            
//$value    =   "'".$this->real_escape_string($value)."'";
            
$value    =   "".$this->real_escape_string($value)."";
        }
        
//
        
return $value;
    }
    
    
    
    
    
    
    function 
quoteIdentifier($value)
    {
        
$value    =   "`".$this->real_escape_string($value)."`";
        
        
//
        
return $value;
    }
    
    function 
quoteString($value)
    {
        if(
$value === NULL)
        {
            
$value    =   "NULL";
        }
        if(
$value === false)
        {
            
$value    =   0;
        }
        else
        {
            
$value    =   "'".$this->real_escape_string($value)."'";
        }
        
//
        
return $value;
    }
}

[Debug::Bugtrace] - не определена!

#0  __Shutdown_Decorator->renderErrorReport(Array ([type] => 1,[message] => Uncaught *{DB\Exception}:
[1114][The table 'Statistics_RequestJournal_Records' is full]

BD={MySQL}
SQL=[INSERT INTO 
		`Statistics_RequestJournal_Records` 
 (
		`ID`, 
		`GUID`, 
		`POUUID`, 
		`ClassName`, 
		`ParentGUID`, 
		`OwnerGUID`, 
		`timeCreated`, 
		`timeModified`, 
		`timeAccessed`, 
		`Description`, 
		`Comments`, 
		`CodeID`, 
		`VersionString`, 
		`Name`, 
		`Hash`, 
		`Order`, 
		`Active`, 
		`timeSynchronized`, 
		`Owner_GUID`, 
		`Owner_POUUID`, 
		`Owner_ClassName`, 
		`Owner_Active`, 
		`ParentObject_GUID`, 
		`ParentObject_POUUID`, 
		`ParentObject_ClassName`, 
		`ParentObject_VersionString`, 
		`Tags`, 
		`REQUEST_METHOD`, 
		`UNIQUE_ID`, 
		`RequestTime_Start`, 
		`HTTP_SCHEME`, 
		`HTTP_HOST`, 
		`HTTP_URL`, 
		`QUERY_STRING`, 
		`HTTP_REFERER`, 
		`HTTP_REFERER_HOST`, 
		`Request_Headers_JSON`, 
		`SessionID`, 
		`Client_IP`, 
		`Client_UserAgent`, 
		`Client_IsRobot`, 
		`Client_IsSearchEngineCrawler`, 
		`Client_IsVulnerabilityScanner`, 
		`Client_Robot_Type`, 
		`Client_Robot_Fami,[file] => /home/www-master/www/apps/HostSystem/SharedApps/moonlite13.cmf/core.moonlite13.ru/Modules/DBManagement/classes/class.DB_SQL.php,[line] => 654), html) called at [/home/www-master/www/vhosts/htdocs/preload.moonlite13.ru/.preload/classes/Processor.php:492]
#1  __Shutdown_Processor->_DislpayErrorReport(Array ([type] => 1,[message] => Uncaught *{DB\Exception}:
[1114][The table 'Statistics_RequestJournal_Records' is full]

BD={MySQL}
SQL=[INSERT INTO 
		`Statistics_RequestJournal_Records` 
 (
		`ID`, 
		`GUID`, 
		`POUUID`, 
		`ClassName`, 
		`ParentGUID`, 
		`OwnerGUID`, 
		`timeCreated`, 
		`timeModified`, 
		`timeAccessed`, 
		`Description`, 
		`Comments`, 
		`CodeID`, 
		`VersionString`, 
		`Name`, 
		`Hash`, 
		`Order`, 
		`Active`, 
		`timeSynchronized`, 
		`Owner_GUID`, 
		`Owner_POUUID`, 
		`Owner_ClassName`, 
		`Owner_Active`, 
		`ParentObject_GUID`, 
		`ParentObject_POUUID`, 
		`ParentObject_ClassName`, 
		`ParentObject_VersionString`, 
		`Tags`, 
		`REQUEST_METHOD`, 
		`UNIQUE_ID`, 
		`RequestTime_Start`, 
		`HTTP_SCHEME`, 
		`HTTP_HOST`, 
		`HTTP_URL`, 
		`QUERY_STRING`, 
		`HTTP_REFERER`, 
		`HTTP_REFERER_HOST`, 
		`Request_Headers_JSON`, 
		`SessionID`, 
		`Client_IP`, 
		`Client_UserAgent`, 
		`Client_IsRobot`, 
		`Client_IsSearchEngineCrawler`, 
		`Client_IsVulnerabilityScanner`, 
		`Client_Robot_Type`, 
		`Client_Robot_Fami,[file] => /home/www-master/www/apps/HostSystem/SharedApps/moonlite13.cmf/core.moonlite13.ru/Modules/DBManagement/classes/class.DB_SQL.php,[line] => 654), html, 1) called at [/home/www-master/www/vhosts/htdocs/preload.moonlite13.ru/.preload/classes/Processor.php:274]
#2  __Shutdown_Processor->shutdown(int)

Информация о данных текущего запроса


SERVER

Array
(
    [UNIQUE_ID] => ZvOsy4rJsaoAABaMP3MAAAAB
    [CMF_ML13_MAIN_URL] => http://www.vtatu.ru/
    [ml13_PathTo_HostSystem] => /home/www-master/www/apps/HostSystem
    [ml13_PathTo_SharedApps] => /home/www-master/www/apps/HostSystem/SharedApps/moonlite13.cmf/core.moonlite13.ru
    [ml13_SystemFilesLocationPath] => /home/www-master/www/apps/HostSystem/SharedApps/moonlite13.cmf/core.moonlite13.ru
    [CMF_ML13_SharedCoreMode] => 1
    [HTTPS] => on
    [SSL_TLS_SNI] => vtatu.com
    [SSL_SERVER_S_DN_CN] => vtatu.ru
    [SSL_SERVER_I_DN_C] => US
    [SSL_SERVER_I_DN_O] => Let's Encrypt
    [SSL_SERVER_I_DN_CN] => R10
    [SSL_VERSION_INTERFACE] => mod_ssl/2.4.10
    [SSL_VERSION_LIBRARY] => OpenSSL/1.0.1t
    [SSL_PROTOCOL] => TLSv1.2
    [SSL_SECURE_RENEG] => true
    [SSL_COMPRESS_METHOD] => NULL
    [SSL_CIPHER] => ECDHE-RSA-AES256-GCM-SHA384
    [SSL_CIPHER_EXPORT] => false
    [SSL_CIPHER_USEKEYSIZE] => 256
    [SSL_CIPHER_ALGKEYSIZE] => 256
    [SSL_CLIENT_VERIFY] => NONE
    [SSL_SERVER_M_VERSION] => 3
    [SSL_SERVER_M_SERIAL] => 0428BDF4C0AAE673CCD1852158AA70E0EDED
    [SSL_SERVER_V_START] => Jun 28 20:20:14 2024 GMT
    [SSL_SERVER_V_END] => Sep 26 20:20:13 2024 GMT
    [SSL_SERVER_S_DN] => CN=vtatu.ru
    [SSL_SERVER_I_DN] => CN=R10,O=Let's Encrypt,C=US
    [SSL_SERVER_A_KEY] => rsaEncryption
    [SSL_SERVER_A_SIG] => sha256WithRSAEncryption
    [SSL_SESSION_RESUMED] => Initial
    [HTTP_ACCEPT] => */*
    [HTTP_USER_AGENT] => Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
    [HTTP_COOKIE] => PHPSESSID=63bf0fc59fd9b717732339017799a889
    [HTTP_ACCEPT_ENCODING] => gzip, br, zstd, deflate
    [HTTP_HOST] => vtatu.com
    [PATH] => /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
    [SERVER_SIGNATURE] => 
Apache/2.4.10 (Debian) Server at vtatu.com Port 443
[SERVER_SOFTWARE] => Apache/2.4.10 (Debian) [SERVER_NAME] => vtatu.com [SERVER_ADDR] => 95.217.151.145 [SERVER_PORT] => 443 [REMOTE_ADDR] => 18.188.151.107 [DOCUMENT_ROOT] => /home/www-master/www/vhosts/htdocs/www.vtatu.ru [REQUEST_SCHEME] => https [CONTEXT_PREFIX] => [CONTEXT_DOCUMENT_ROOT] => /home/www-master/www/vhosts/htdocs/www.vtatu.ru [SERVER_ADMIN] => [no address given] [SCRIPT_FILENAME] => /home/www-master/www/vhosts/htdocs/www.vtatu.ru/diary/record/index.php [REMOTE_PORT] => 23281 [GATEWAY_INTERFACE] => CGI/1.1 [SERVER_PROTOCOL] => HTTP/1.1 [REQUEST_METHOD] => GET [QUERY_STRING] => UUID=32b73a7e-6380-de91-3b63-6a322d3466d9&back_url=%2Fstream%2F%3Fp%3D74 [REQUEST_URI] => /diary/record/?UUID=32b73a7e-6380-de91-3b63-6a322d3466d9&back_url=%2Fstream%2F%3Fp%3D74 [SCRIPT_NAME] => /diary/record/index.php [PHP_SELF] => /diary/record/index.php [REQUEST_TIME_FLOAT] => 1727245515.67 [REQUEST_TIME] => 1727245515 )

GET

Array
(
    [UUID] => 32b73a7e-6380-de91-3b63-6a322d3466d9
    [back_url] => /stream/?p=74
)

POST

Array
(
)

FILES

Array
(
)

SESSION

Array
(
)

COOKIE

Array
(
    [PHPSESSID] => 63bf0fc59fd9b717732339017799a889
)
[]