dolibarr/htdocs/debugbar/class/TraceableDB.php

783 lines
23 KiB
PHP
Raw Normal View History

2019-03-16 15:27:14 +00:00
<?php
2023-01-14 14:57:12 +00:00
/* Copyright (C) 2023 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
* Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
2023-01-14 14:57:12 +00:00
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/debugbar/class/DataCollector/TraceableDB.php
* \brief Class for debugbar DB
* \ingroup debugbar
*/
2019-03-16 15:27:14 +00:00
require_once DOL_DOCUMENT_ROOT.'/core/db/DoliDB.class.php';
2019-03-16 15:27:14 +00:00
/**
* TraceableDB class
*
* Used to log queries into DebugBar
*/
class TraceableDB extends DoliDB
{
/**
* @var DoliDB Database handler
2019-03-16 15:27:14 +00:00
*/
public $db; // cannot be protected because of parent declaration
/**
* @var array<array<string,null|true|string>> Queries array
2019-03-16 15:27:14 +00:00
*/
public $queries;
/**
2024-04-05 08:26:43 +00:00
* @var float Request start time in second + microseconds as decimal part (Example: 1712305485.1104)
2019-03-16 15:27:14 +00:00
*/
protected $startTime;
/**
2024-04-05 08:26:43 +00:00
* @var int Request start memory
2019-03-16 15:27:14 +00:00
*/
protected $startMemory;
/**
2020-05-27 21:37:22 +00:00
* @var string type
2019-03-16 15:27:14 +00:00
*/
public $type;
/**
* @const Database label
*/
const LABEL = ''; // TODO: the right value should be $this->db::LABEL (but this is a constant? o_O)
/**
* @const Version min database
*/
const VERSIONMIN = ''; // TODO: the same thing here, $this->db::VERSIONMIN is the right value
/**
* Constructor
*
* @param DoliDB $db Database handler
*/
public function __construct($db)
{
$this->db = $db;
2020-09-20 00:30:53 +00:00
$this->type = $this->db->type;
2019-03-16 15:27:14 +00:00
$this->queries = array();
}
/**
* Format a SQL IF
*
* @param string $test Test string (example: 'cd.statut=0', 'field IS NULL')
* @param string $resok result if test equal
* @param string $resko result if test non equal
2019-03-16 15:27:14 +00:00
* @return string SQL string
*/
public function ifsql($test, $resok, $resko)
{
return $this->db->ifsql($test, $resok, $resko);
}
/**
* format a sql regexp
*
* @param string $subject field name to test
* @param string $pattern sql pattern to match
* @param int $sqlstring 0=the string being tested is a hard coded string, 1=the string is a field
* @return string sql string
*/
public function regexpsql($subject, $pattern, $sqlstring = 0): string
{
return $this->db->regexpsql($subject, $pattern, $sqlstring = 0);
}
2019-03-16 22:31:48 +00:00
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2019-03-16 15:27:14 +00:00
/**
* Return datas as an array
*
* @param resource $resultset Resultset of request
* @return array<int,mixed>|null|int<0,0> Array
2019-03-16 15:27:14 +00:00
*/
public function fetch_row($resultset)
{
// phpcs:enable
2019-03-16 15:27:14 +00:00
return $this->db->fetch_row($resultset);
}
/**
* Convert (by PHP) a GM Timestamp date into a string date with PHP server TZ to insert into a date field.
* Function to use to build INSERT, UPDATE or WHERE predica
*
Qual: Fix phan notices (#37837) * Qual: Ignore PhanUndeclaredProperty for specific lines * Fix: Update payment mode reference in PDF generation # Fix: Update payment mode reference in PDF generation The payment mode reference in the PDF generation was incorrectly using `type_payment_code`, an unknown property in Salary. It has been updated to use `type_code` as used elsewhere for the same purpose. * Qual: Typing of several DDLUpdateField field_desc items made optional # Qual: Typing of several DDLUpdateField field_desc items made optional Not all fields are required for updateing the DB typing, and ExtraFields was not providing all of them. * Qual: Update typing for phan notices # Qual: Update typing for phan notices Fix typing mismatches * Qual: Fix extrafields typing in objectline_create.tpl.php # Qual: Fix extrafields typing in objectline_create.tpl.php - Update typing for phan * Qual: Fix typing for Phan & re-use encrypted password when requested # Qual: Fix typing for Phan & re-use encrypted password when requested - Added a cast to string for the crypted password to hint phan that it returns the string version (not the array) - Added a check to ensure the password is not already crypted before generating a new password. - Updated the type hints for parameters `$changelater`, `$notrigger`, `$nosyncmember`, and `$passwordalreadycrypted` to include the range of possible values. - Updated the return type hint for the `setPassword` method to include the range of possible error values. * Qual: Fix file argument to showPreview() calls # Qual: Fix file argument to showPreview() calls Fix argument type mismatches by adjusting '$file' arguments in showPreview calls. * Qual: Update login_c type to string # Qual: Update login_c type to string login_c is username from db. * Qual: Update type hints in treeview.lib.php # Qual: Update type hints in treeview.lib.php Update type hints for static analysis. * Qual: Add null check for objecttmp in selectForFormsList # Qual: Add null check for objecttmp in selectForFormsList Add null check for objecttmp before calling selectForFormsList to ensure static analysis * Qual: Fix phan through null check on object argument # Qual: Fix phan through null check on object argument - Do null check to avoid null parameter (fix phan); - Set more specific type for argument. * Qual: Change type hint of $remise_percent parameter to float # Qual: Change type hint of $remise_percent parameter to float DB type is float, so correct arg type to fix phan notice. * Qual: Ignore some phan notices The descriptions for the linkedObjectsFullLoaded and oldcopy properties have been updated to avoid modification by code formatting tools * Qual: Update phan baseline * Qual: Cast remise_percent to float to match typing requirements * Qual: Cast label to string to help static analysis * Qual: Update date_cancel property type and assignment To fix phan notices: - The date_cancel property type was changed from 'int|string' to 'int|""' to match return type from jdate(). - Additionally, the assignment of date_cancel was updated to use dol_now() instead of $this->db->idate(dol_now()). * Qual: Provide the expected user_id instead of the User object Changed the user fetch logic from using `user_author` to `user_creation_id` * Qual: Correct bool argument from 0 to false ($fill) * Qual/Fix: Correct date converted to dol_print_date * Qual: Fix argument type for addline() * Qual: Update Phan baseline.txt
2026-04-13 10:50:23 +00:00
* @param int|'' $param Date TMS to convert
* @param 'gmt'|'tzserver' $gm 'gmt'=Input information are GMT values, 'tzserver'=Local to server TZ
* @return string Date in a string YYYY-MM-DD HH:MM:SS
2019-03-16 15:27:14 +00:00
*/
public function idate($param, $gm = 'tzserver')
2019-03-16 15:27:14 +00:00
{
return $this->db->idate($param, $gm);
2019-03-16 15:27:14 +00:00
}
/**
* Return last error code
*
* @return string lasterrno
*/
public function lasterrno()
{
return $this->db->lasterrno();
}
/**
* Start transaction
*
2022-10-06 15:09:10 +00:00
* @param string $textinlog Add a small text into log. '' by default.
* @return int 1 if transaction successfully opened or already opened, 0 if error
2019-03-16 15:27:14 +00:00
*/
2022-10-06 15:09:10 +00:00
public function begin($textinlog = '')
2019-03-16 15:27:14 +00:00
{
2022-10-06 15:09:10 +00:00
return $this->db->begin($textinlog);
2019-03-16 15:27:14 +00:00
}
/**
* Create a new database
* Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
* We force to create database with charset this->forcecharset and collate this->forcecollate
*
* @param string $database Database name to create
* @param string $charset Charset used to store data
* @param string $collation Charset used to sort data
* @param string $owner Username of database owner
* @return resource resource defined if OK, null if KO
*/
public function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
{
return $this->db->DDLCreateDb($database, $charset, $collation, $owner);
}
/**
* Return version of database server into an array
*
* @return string[] Version array
2019-03-16 15:27:14 +00:00
*/
public function getVersionArray()
{
return $this->db->getVersionArray();
}
/**
* Convert a SQL request in Mysql syntax to native syntax
*
2019-03-16 19:10:22 +00:00
* @param string $line SQL request line to convert
* @param string $type Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
* @return string SQL request line converted
2019-03-16 15:27:14 +00:00
*/
public function convertSQLFromMysql($line, $type = 'ddl')
2019-03-16 15:27:14 +00:00
{
return $this->db->convertSQLFromMysql($line);
2019-03-16 15:27:14 +00:00
}
2019-03-16 22:17:23 +00:00
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2019-03-16 15:27:14 +00:00
/**
* Return the number of lines into the result of a request INSERT, DELETE or UPDATE
2019-03-16 15:27:14 +00:00
*
2019-03-16 19:10:22 +00:00
* @param resource $resultset Curseur de la requete voulue
2019-06-29 14:29:32 +00:00
* @return int Number of lines
2019-03-16 19:10:22 +00:00
* @see num_rows()
2019-03-16 15:27:14 +00:00
*/
public function affected_rows($resultset)
{
// phpcs:enable
2019-03-16 15:27:14 +00:00
return $this->db->affected_rows($resultset);
}
/**
* Return description of last error
*
* @return string Error text
*/
public function error()
{
return $this->db->error();
}
/**
* List tables into a database
*
* @param string $database Name of database
* @param string $table Name of table filter ('xxx%')
* @return string[] List of tables in an array
2019-03-16 15:27:14 +00:00
*/
public function DDLListTables($database, $table = '')
{
return $this->db->DDLListTables($database, $table);
}
2023-04-14 08:15:23 +00:00
/**
* List tables into a database with table info
*
* @param string $database Name of database
* @param string $table Name of table filter ('xxx%')
* @return array<array{0:string,1:string}> List of tables in an array
2023-04-14 08:15:23 +00:00
*/
public function DDLListTablesFull($database, $table = '')
{
return $this->db->DDLListTablesFull($database, $table);
}
2019-03-16 15:27:14 +00:00
/**
* Return last request executed with query()
*
* @return string Last query
*/
public function lastquery()
{
return $this->db->lastquery();
}
/**
* Define sort criteria of request
*
* @param string $sortfield List of sort fields
* @param string $sortorder Sort order
* @return string String to provide syntax of a sort sql string
*/
public function order($sortfield = null, $sortorder = null)
{
return $this->db->order($sortfield, $sortorder);
}
/**
* Decrypt sensitive data in database
*
* @param string $value Value to decrypt
* @return string Decrypted value if used
*/
public function decrypt($value)
{
return $this->db->decrypt($value);
}
2019-03-16 19:10:22 +00:00
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2019-03-16 15:27:14 +00:00
/**
2019-03-16 19:10:22 +00:00
* Return datas as an array
2019-03-16 15:27:14 +00:00
*
2019-03-16 19:10:22 +00:00
* @param resource $resultset Resultset of request
* @return array<int|string,mixed>|null|false Result with row
2019-03-16 15:27:14 +00:00
*/
public function fetch_array($resultset)
{
// phpcs:enable
2019-03-16 15:27:14 +00:00
return $this->db->fetch_array($resultset);
}
/**
* Return last error label
*
* @return string lasterror
*/
public function lasterror()
{
return $this->db->lasterror();
}
/**
* Escape a string to insert data
*
* @param string $stringtoencode String to escape
* @return string String escaped
*/
public function escape($stringtoencode)
{
return $this->db->escape($stringtoencode);
}
/**
* Escape a string to insert data into a like
*
* @param string $stringtoencode String to escape
* @return string String escaped
*/
public function escapeforlike($stringtoencode)
{
return $this->db->escapeforlike($stringtoencode);
}
2019-03-16 19:10:22 +00:00
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2019-03-16 15:27:14 +00:00
/**
* Get last ID after an insert INSERT
*
* @param string $tab Table name concerned by insert. Needed for Postgresql compatibility (not useful for MySql)
2019-03-16 15:27:14 +00:00
* @param string $fieldid Field name
* @return int Id of row
*/
public function last_insert_id($tab, $fieldid = 'rowid')
{
// phpcs:enable
return $this->db->last_insert_id($tab, $fieldid);
2019-03-16 15:27:14 +00:00
}
/**
2019-03-16 19:10:22 +00:00
* Return full path of restore program
2019-03-16 15:27:14 +00:00
*
* @return string Full path of restore program
*/
public function getPathOfRestore()
{
return $this->db->getPathOfRestore();
}
/**
2019-06-22 17:15:15 +00:00
* Cancel a transaction and go back to initial data values
2019-03-16 15:27:14 +00:00
*
2019-06-22 17:15:15 +00:00
* @param string $log Add more log to default log line
* @return resource|int 1 if cancellation is ok or transaction not open, 0 if error
2019-03-16 15:27:14 +00:00
*/
public function rollback($log = '')
{
return $this->db->rollback($log);
}
/**
* Execute a SQL request and return the resultset
*
* @param string $query SQL query string
* @param int $usesavepoint 0=Default mode, 1=Run a savepoint before and a rollback to savepoint if error (this allow to have some request with errors inside global transactions).
* Note that with Mysql, this parameter is not used as Myssql can already commit a transaction even if one request is in error, without using savepoints.
* @param string $type Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
* @param int $result_mode Result mode
* @return resource Resultset of answer
2019-03-16 15:27:14 +00:00
*/
public function query($query, $usesavepoint = 0, $type = 'auto', $result_mode = 0)
2019-03-16 15:27:14 +00:00
{
$this->startTracing();
$resql = $this->db->query($query, $usesavepoint, $type, $result_mode);
2019-03-16 15:27:14 +00:00
$this->endTracing($query, $resql);
return $resql;
}
/**
* Start query tracing
2019-03-16 22:17:23 +00:00
*
* @return void
2019-03-16 15:27:14 +00:00
*/
protected function startTracing()
{
$this->startTime = microtime(true);
$this->startMemory = memory_get_usage(true);
}
NEW debugbar: Add backtrace capture for database query failures (#36612) * debugbar: Add backtrace capture for database query failures Implements backtrace forwarding to capture and display backtraces when database queries fail, making it easier for developers to identify the source of database errors. Backtrace are captured in TraceableDB::endTracing() when queries fail using debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) and stored to be fowarded to the DolQueryCollector that will expose it to the debugbar integration. Because of that, the backtrace is now captured at the correct location, ie. when the query fails, rather than when the error is retrieved, ensuring it shows the actual application code that triggered the problematic query. This is particularly useful for debugging MySQL to PostgreSQL compatibility issues, module development and maintenance, and quickly identifying query origins during development. In particular, paired with the list and time profiling of each request, it will allow finding the location where queries are not properly optimized. Before this patch, it was possible to try and find snippets from the queries but because queries are generated at runtime, it was tedious and could lead to the wrong location. Related to #34050 * debugbar: Add SQL query backtrace Extends the debugbar SQL widget with backtrace display capabilities. To keep vendor files pristine, a custom widget (TracingSQLQueriesWidget) extends the vendor SQLQueriesWidget using DOM manipulation to inject Dolibarr-specific features after parent render completes. The widget intercepts the parent's data binding callback via wrapDataBinding() to enhance rendered queries with backtrace buttons. This patch pattern depends on php-debugbar internals but might break if the vendor API changes, without breaking the rendering done by php-debugbar. A tracing toggle icon in the status bar allows switching between tracing failed queries only (default, minimal overhead) and tracing all queries. The setting persists via cookie (debugbar_full_tracing) which the PHP backend reads to decide whether to capture backtraces. Custom styles in widgets.css is for the tracing state (eye/eye-slash icons) and so as to format the backtrace display within a frame and using monospace font. Closes #34050
2026-05-03 14:26:33 +00:00
/**
* Check if full query tracing is enabled
*
* Full tracing captures backtrace for ALL queries, not just failed ones.
* This is useful for debugging but has performance impact.
*
* @return bool True if full tracing is enabled
*/
protected function isFullTracingEnabled()
{
if (isset($_COOKIE['debugbar_full_tracing'])) {
return $_COOKIE['debugbar_full_tracing'] === '1';
}
return false;
}
2019-03-16 15:27:14 +00:00
/**
* End query tracing
*
2019-03-16 22:17:23 +00:00
* @param string $sql query string
* @param mysqli_result|bool|resource $resql query result
2019-03-16 22:17:23 +00:00
* @return void
2019-03-16 15:27:14 +00:00
*/
protected function endTracing($sql, $resql)
{
$endTime = microtime(true);
$duration = $endTime - $this->startTime;
$endMemory = memory_get_usage(true);
$memoryDelta = $endMemory - $this->startMemory;
NEW debugbar: Add backtrace capture for database query failures (#36612) * debugbar: Add backtrace capture for database query failures Implements backtrace forwarding to capture and display backtraces when database queries fail, making it easier for developers to identify the source of database errors. Backtrace are captured in TraceableDB::endTracing() when queries fail using debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) and stored to be fowarded to the DolQueryCollector that will expose it to the debugbar integration. Because of that, the backtrace is now captured at the correct location, ie. when the query fails, rather than when the error is retrieved, ensuring it shows the actual application code that triggered the problematic query. This is particularly useful for debugging MySQL to PostgreSQL compatibility issues, module development and maintenance, and quickly identifying query origins during development. In particular, paired with the list and time profiling of each request, it will allow finding the location where queries are not properly optimized. Before this patch, it was possible to try and find snippets from the queries but because queries are generated at runtime, it was tedious and could lead to the wrong location. Related to #34050 * debugbar: Add SQL query backtrace Extends the debugbar SQL widget with backtrace display capabilities. To keep vendor files pristine, a custom widget (TracingSQLQueriesWidget) extends the vendor SQLQueriesWidget using DOM manipulation to inject Dolibarr-specific features after parent render completes. The widget intercepts the parent's data binding callback via wrapDataBinding() to enhance rendered queries with backtrace buttons. This patch pattern depends on php-debugbar internals but might break if the vendor API changes, without breaking the rendering done by php-debugbar. A tracing toggle icon in the status bar allows switching between tracing failed queries only (default, minimal overhead) and tracing all queries. The setting persists via cookie (debugbar_full_tracing) which the PHP backend reads to decide whether to capture backtraces. Custom styles in widgets.css is for the tracing state (eye/eye-slash icons) and so as to format the backtrace display within a frame and using monospace font. Closes #34050
2026-05-03 14:26:33 +00:00
// Capture backtrace for failed queries, or if full tracing is enabled
$backtrace = null;
if (!$resql || $this->isFullTracingEnabled()) {
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
}
2019-03-16 15:27:14 +00:00
$this->queries[] = array(
'sql' => $sql,
'duration' => $duration,
'memory_usage' => $memoryDelta,
2019-10-11 12:53:30 +00:00
'is_success' => $resql ? true : false,
'error_code' => $resql ? null : $this->db->lasterrno(),
NEW debugbar: Add backtrace capture for database query failures (#36612) * debugbar: Add backtrace capture for database query failures Implements backtrace forwarding to capture and display backtraces when database queries fail, making it easier for developers to identify the source of database errors. Backtrace are captured in TraceableDB::endTracing() when queries fail using debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) and stored to be fowarded to the DolQueryCollector that will expose it to the debugbar integration. Because of that, the backtrace is now captured at the correct location, ie. when the query fails, rather than when the error is retrieved, ensuring it shows the actual application code that triggered the problematic query. This is particularly useful for debugging MySQL to PostgreSQL compatibility issues, module development and maintenance, and quickly identifying query origins during development. In particular, paired with the list and time profiling of each request, it will allow finding the location where queries are not properly optimized. Before this patch, it was possible to try and find snippets from the queries but because queries are generated at runtime, it was tedious and could lead to the wrong location. Related to #34050 * debugbar: Add SQL query backtrace Extends the debugbar SQL widget with backtrace display capabilities. To keep vendor files pristine, a custom widget (TracingSQLQueriesWidget) extends the vendor SQLQueriesWidget using DOM manipulation to inject Dolibarr-specific features after parent render completes. The widget intercepts the parent's data binding callback via wrapDataBinding() to enhance rendered queries with backtrace buttons. This patch pattern depends on php-debugbar internals but might break if the vendor API changes, without breaking the rendering done by php-debugbar. A tracing toggle icon in the status bar allows switching between tracing failed queries only (default, minimal overhead) and tracing all queries. The setting persists via cookie (debugbar_full_tracing) which the PHP backend reads to decide whether to capture backtraces. Custom styles in widgets.css is for the tracing state (eye/eye-slash icons) and so as to format the backtrace display within a frame and using monospace font. Closes #34050
2026-05-03 14:26:33 +00:00
'error_message' => $resql ? null : $this->db->lasterror(),
'backtrace' => $backtrace
2019-03-16 15:27:14 +00:00
);
}
/**
* Connection to server
2019-03-16 15:27:14 +00:00
*
* @param string $host database server host
* @param string $login login
* @param string $passwd password
* @param string $name name of database (not used for mysql, used for pgsql)
* @param int $port Port of database server
* @return resource Database access handler
2019-03-16 19:10:22 +00:00
* @see close()
2019-03-16 15:27:14 +00:00
*/
public function connect($host, $login, $passwd, $name, $port = 0)
{
return $this->db->connect($host, $login, $passwd, $name, $port);
}
/**
* Define limits and offset of request
*
* @param int $limit Maximum number of lines returned (-1=conf->liste_limit, 0=no limit)
* @param int $offset Numero of line from where starting fetch
* @return string String with SQL syntax to add a limit and offset
*/
public function plimit($limit = 0, $offset = 0)
{
return $this->db->plimit($limit, $offset);
}
/**
* Return value of server parameters
*
* @param string $filter Filter list on a particular value
* @return array<string,string> Array of key-values (key=>value)
2019-03-16 15:27:14 +00:00
*/
public function getServerParametersValues($filter = '')
{
return $this->db->getServerParametersValues($filter);
}
/**
* Return value of server status
*
* @param string $filter Filter list on a particular value
* @return array<string,string> Array of key-values (key=>value)
2019-03-16 15:27:14 +00:00
*/
public function getServerStatusValues($filter = '')
{
return $this->db->getServerStatusValues($filter);
}
/**
* Return collation used in database
*
* @return string Collation value
*/
public function getDefaultCollationDatabase()
{
return $this->db->getDefaultCollationDatabase();
}
2019-03-16 22:17:23 +00:00
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2019-03-16 15:27:14 +00:00
/**
* Return number of lines for result of a SELECT
*
2019-03-16 22:17:23 +00:00
* @param resource $resultset Resulset of requests
* @return int Nb of lines
2019-03-16 19:10:22 +00:00
* @see affected_rows()
2019-03-16 15:27:14 +00:00
*/
public function num_rows($resultset)
{
// phpcs:enable
2019-03-16 15:27:14 +00:00
return $this->db->num_rows($resultset);
}
/**
* Return full path of dump program
*
* @return string Full path of dump program
*/
public function getPathOfDump()
{
return $this->db->getPathOfDump();
}
/**
* Return version of database client driver
*
* @return string Version string
*/
public function getDriverInfo()
{
return $this->db->getDriverInfo();
}
/**
* Return generic error code of last operation.
*
* @return string Error code (Examples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
2019-03-16 15:27:14 +00:00
*/
public function errno()
{
return $this->db->errno();
}
/**
* Create a table into database
*
* @param string $table Name of table
2025-02-26 22:14:28 +00:00
* @param array<string,array{type:string,label?:string,enabled?:int<0,2>|string,position?:int,notnull?:int,visible?:int<-2,5>|string,alwayseditable?:int<0,1>,noteditable?:int<0,1>,default?:string,index?:int,foreignkey?:string,searchall?:int<0,1>,isameasure?:int<0,1>,css?:string,csslist?:string,help?:string,showoncombobox?:int<0,2>,disabled?:int<0,1>,arrayofkeyval?:array<int,string>,autofocusoncreate?:int<0,1>,comment?:string,copytoclipboard?:int<1,2>,validate?:int<0,1>}> $fields Associative table [field name][table of descriptions]
2019-03-16 15:27:14 +00:00
* @param string $primary_key Nom du champ qui sera la clef primaire
* @param string $type Type de la table
* @param ?array<string,mixed> $unique_keys Tableau associatifs Nom de champs qui seront clef unique => valeur
* @param string[] $fulltext_keys Tableau des Nom de champs qui seront indexes en fulltext
* @param string[] $keys Tableau des champs cles noms => valeur
2023-12-06 14:46:39 +00:00
* @return int Return integer <0 if KO, >=0 if OK
2019-03-16 15:27:14 +00:00
*/
public function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
{
return $this->db->DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys, $fulltext_keys, $keys);
}
/**
* Drop a table into database
*
* @param string $table Name of table
2023-12-06 14:46:39 +00:00
* @return int Return integer <0 if KO, >=0 if OK
2019-03-16 15:27:14 +00:00
*/
public function DDLDropTable($table)
{
return $this->db->DDLDropTable($table);
}
/**
* Return list of available charset that can be used to store data in database
*
* @return ?array<int,array{charset:string,description:string}> List of Charset
2019-03-16 15:27:14 +00:00
*/
public function getListOfCharacterSet()
{
return $this->db->getListOfCharacterSet();
}
/**
* Create a new field into table
*
* @param string $table Name of table
* @param string $field_name Name of field to add
2025-02-03 13:28:54 +00:00
* @param array{type:string,label?:string,enabled?:int<0,2>|string,position?:int,notnull?:int,visible?:int,noteditable?:int,default?:string,extra?:string,null?:string,index?:int,foreignkey?:string,searchall?:int,isameasure?:int,css?:string,csslist?:string,help?:string,showoncombobox?:int,disabled?:int,arrayofkeyval?:array<int,string>,comment?:string} $field_desc Associative array of description of the field to insert [parameter name][parameter value]
2019-03-16 15:27:14 +00:00
* @param string $field_position Optionnel ex.: "after champtruc"
2023-12-01 18:51:32 +00:00
* @return int Return integer <0 if KO, >0 if OK
2019-03-16 15:27:14 +00:00
*/
public function DDLAddField($table, $field_name, $field_desc, $field_position = "")
{
return $this->db->DDLAddField($table, $field_name, $field_desc, $field_position);
}
/**
* Drop a field from table
*
* @param string $table Name of table
* @param string $field_name Name of field to drop
2023-12-01 18:51:32 +00:00
* @return int Return integer <0 if KO, >0 if OK
2019-03-16 15:27:14 +00:00
*/
public function DDLDropField($table, $field_name)
{
return $this->db->DDLDropField($table, $field_name);
}
/**
* Update format of a field into a table
*
* @param string $table Name of table
* @param string $field_name Name of field to modify
Qual: Fix phan notices (#37837) * Qual: Ignore PhanUndeclaredProperty for specific lines * Fix: Update payment mode reference in PDF generation # Fix: Update payment mode reference in PDF generation The payment mode reference in the PDF generation was incorrectly using `type_payment_code`, an unknown property in Salary. It has been updated to use `type_code` as used elsewhere for the same purpose. * Qual: Typing of several DDLUpdateField field_desc items made optional # Qual: Typing of several DDLUpdateField field_desc items made optional Not all fields are required for updateing the DB typing, and ExtraFields was not providing all of them. * Qual: Update typing for phan notices # Qual: Update typing for phan notices Fix typing mismatches * Qual: Fix extrafields typing in objectline_create.tpl.php # Qual: Fix extrafields typing in objectline_create.tpl.php - Update typing for phan * Qual: Fix typing for Phan & re-use encrypted password when requested # Qual: Fix typing for Phan & re-use encrypted password when requested - Added a cast to string for the crypted password to hint phan that it returns the string version (not the array) - Added a check to ensure the password is not already crypted before generating a new password. - Updated the type hints for parameters `$changelater`, `$notrigger`, `$nosyncmember`, and `$passwordalreadycrypted` to include the range of possible values. - Updated the return type hint for the `setPassword` method to include the range of possible error values. * Qual: Fix file argument to showPreview() calls # Qual: Fix file argument to showPreview() calls Fix argument type mismatches by adjusting '$file' arguments in showPreview calls. * Qual: Update login_c type to string # Qual: Update login_c type to string login_c is username from db. * Qual: Update type hints in treeview.lib.php # Qual: Update type hints in treeview.lib.php Update type hints for static analysis. * Qual: Add null check for objecttmp in selectForFormsList # Qual: Add null check for objecttmp in selectForFormsList Add null check for objecttmp before calling selectForFormsList to ensure static analysis * Qual: Fix phan through null check on object argument # Qual: Fix phan through null check on object argument - Do null check to avoid null parameter (fix phan); - Set more specific type for argument. * Qual: Change type hint of $remise_percent parameter to float # Qual: Change type hint of $remise_percent parameter to float DB type is float, so correct arg type to fix phan notice. * Qual: Ignore some phan notices The descriptions for the linkedObjectsFullLoaded and oldcopy properties have been updated to avoid modification by code formatting tools * Qual: Update phan baseline * Qual: Cast remise_percent to float to match typing requirements * Qual: Cast label to string to help static analysis * Qual: Update date_cancel property type and assignment To fix phan notices: - The date_cancel property type was changed from 'int|string' to 'int|""' to match return type from jdate(). - Additionally, the assignment of date_cancel was updated to use dol_now() instead of $this->db->idate(dol_now()). * Qual: Provide the expected user_id instead of the User object Changed the user fetch logic from using `user_author` to `user_creation_id` * Qual: Correct bool argument from 0 to false ($fill) * Qual/Fix: Correct date converted to dol_print_date * Qual: Fix argument type for addline() * Qual: Update Phan baseline.txt
2026-04-13 10:50:23 +00:00
* @param array{type:string,label?:string,enabled?:int<0,2>|string,position?:int,notnull?:int,visible?:int,noteditable?:int,default?:string,index?:int,foreignkey?:string,searchall?:int,isameasure?:int,css?:string,csslist?:string,help?:string,showoncombobox?:int,disabled?:int,arrayofkeyval?:array<int,string>,comment?:string,value?:string,null?:string} $field_desc Array with description of field format
2023-12-01 18:51:32 +00:00
* @return int Return integer <0 if KO, >0 if OK
2019-03-16 15:27:14 +00:00
*/
public function DDLUpdateField($table, $field_name, $field_desc)
{
return $this->db->DDLUpdateField($table, $field_name, $field_desc);
}
/**
* Return list of available collation that can be used for database
*
* @return ?array<int,array{collation:string}> List of Collation
2019-03-16 15:27:14 +00:00
*/
public function getListOfCollation()
{
return $this->db->getListOfCollation();
}
/**
* Return a pointer of line with description of a table or field
*
* @param string $table Name of table
* @param string $field Optionnel : Name of field if we want description of field
* @return resource Resource
*/
public function DDLDescTable($table, $field = "")
{
return $this->db->DDLDescTable($table, $field);
}
/**
* Return version of database server
*
* @return string Version string
*/
public function getVersion()
{
return $this->db->getVersion();
}
/**
* Return charset used to store data in database
*
* @return string Charset
*/
public function getDefaultCharacterSetDatabase()
{
return $this->db->getDefaultCharacterSetDatabase();
}
/**
* Create a user and privileges to connect to database (even if database does not exists yet)
*
* @param string $dolibarr_main_db_host Ip serveur
* @param string $dolibarr_main_db_user Name of user to create
* @param string $dolibarr_main_db_pass Password of user to create
2019-03-16 15:27:14 +00:00
* @param string $dolibarr_main_db_name Database name where user must be granted
2023-12-06 14:46:39 +00:00
* @return int Return integer <0 if KO, >=0 if OK
2019-03-16 15:27:14 +00:00
*/
public function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
{
return $this->db->DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name);
}
2019-03-16 22:17:23 +00:00
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2019-03-16 15:27:14 +00:00
/**
* Convert (by PHP) a PHP server TZ string date into a Timestamps date (GMT if gm=true)
* 19700101020000 -> 3600 with TZ+1 and gmt=0
* 19700101020000 -> 7200 whatever is TZ if gmt=1
2019-03-16 15:27:14 +00:00
*
2026-02-08 13:51:11 +00:00
* @param ?string $string Date in a string (YYYYMMDDHHMMSS, YYYYMMDD, YYYY-MM-DD HH:MM:SS)
* @param bool|int|string $gm 1=Input information are GMT values, otherwise local to server TZ
* @return int|'' Date TMS or ''
2019-03-16 15:27:14 +00:00
*/
2019-03-16 22:17:23 +00:00
public function jdate($string, $gm = false)
2019-03-16 15:27:14 +00:00
{
// phpcs:enable
2019-03-16 15:27:14 +00:00
return $this->db->jdate($string, $gm);
}
/**
* Encrypt sensitive data in database
2021-09-02 11:25:00 +00:00
* Warning: This function includes the escape and add the SQL simple quotes on strings.
2019-03-16 15:27:14 +00:00
*
2021-09-02 11:25:00 +00:00
* @param string $fieldorvalue Field name or value to encrypt
* @param int $withQuotes Return string including the SQL simple quotes. This param must always be 1 (Value 0 is bugged and deprecated).
* @return string XXX(field) or XXX('value') or field or 'value'
2019-03-16 15:27:14 +00:00
*/
2021-09-02 11:25:00 +00:00
public function encrypt($fieldorvalue, $withQuotes = 1)
2019-03-16 15:27:14 +00:00
{
return $this->db->encrypt($fieldorvalue, $withQuotes);
}
/**
* Validate a database transaction
*
* @param string $log Add more log to default log line
* @return int 1 if validation is OK or transaction level no started, 0 if ERROR
*/
public function commit($log = '')
{
return $this->db->commit($log);
}
/**
* List information of columns into a table.
*
* @param string $table Name of table
* @return array<array<string,mixed>> Array with information on table
2019-03-16 15:27:14 +00:00
*/
public function DDLInfoTable($table)
{
return $this->db->DDLInfoTable($table);
}
/**
* Free last resultset used.
*
* @param resource $resultset Fre cursor
* @return void
*/
public function free($resultset = null)
{
2022-12-31 13:37:33 +00:00
$this->db->free($resultset);
2019-03-16 15:27:14 +00:00
}
/**
* Close database connection
2019-03-16 15:27:14 +00:00
*
* @return boolean True if disconnect successful, false otherwise
2019-03-16 19:10:22 +00:00
* @see connect()
2019-03-16 15:27:14 +00:00
*/
public function close()
{
return $this->db->close();
}
/**
* Return last query in error
*
* @return string lastqueryerror
*/
public function lastqueryerror()
{
return $this->db->lastqueryerror();
}
/**
* Return connection ID
2019-03-16 15:27:14 +00:00
*
* @return string Id connection
2019-03-16 15:27:14 +00:00
*/
public function DDLGetConnectId()
{
return $this->db->DDLGetConnectId();
}
2019-03-16 19:10:22 +00:00
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2019-03-16 15:27:14 +00:00
/**
2022-05-08 16:25:22 +00:00
* Returns the current line (as an object) for the resultset cursor
2019-03-16 15:27:14 +00:00
*
2023-11-27 11:13:50 +00:00
* @param resource|PgSql\Connection $resultset Handler of the desired SQL request
* @return Object Object result line or false if KO or end of cursor
2019-03-16 15:27:14 +00:00
*/
public function fetch_object($resultset)
{
// phpcs:enable
2019-03-16 15:27:14 +00:00
return $this->db->fetch_object($resultset);
}
2019-03-16 19:10:22 +00:00
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2019-03-16 15:27:14 +00:00
/**
* Select a database
*
2019-03-16 19:10:22 +00:00
* @param string $database Name of database
* @return boolean true if OK, false if KO
2019-03-16 15:27:14 +00:00
*/
public function select_db($database)
{
// phpcs:enable
2019-03-16 15:27:14 +00:00
return $this->db->select_db($database);
}
2019-03-16 19:10:22 +00:00
}