TraceableDB.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. <?php
  2. require_once DOL_DOCUMENT_ROOT.'/core/db/DoliDB.class.php';
  3. /**
  4. * TraceableDB class
  5. *
  6. * Used to log queries into DebugBar
  7. */
  8. class TraceableDB extends DoliDB
  9. {
  10. /**
  11. * @var DoliDb Database handler
  12. */
  13. public $db; // cannot be protected because of parent declaration
  14. /**
  15. * @var array Queries array
  16. */
  17. public $queries;
  18. /**
  19. * @var int Request start time
  20. */
  21. protected $startTime;
  22. /**
  23. * @var int Request start memory
  24. */
  25. protected $startMemory;
  26. /**
  27. * @var string type
  28. */
  29. public $type;
  30. /**
  31. * @const Database label
  32. */
  33. const LABEL = ''; // TODO: the right value should be $this->db::LABEL (but this is a constant? o_O)
  34. /**
  35. * @const Version min database
  36. */
  37. const VERSIONMIN = ''; // TODO: the same thing here, $this->db::VERSIONMIN is the right value
  38. /**
  39. * Constructor
  40. *
  41. * @param DoliDB $db Database handler
  42. */
  43. public function __construct($db)
  44. {
  45. $this->db = $db;
  46. $this->type = $this->db->type;
  47. $this->queries = array();
  48. }
  49. /**
  50. * Format a SQL IF
  51. *
  52. * @param string $test Test string (example: 'cd.statut=0', 'field IS NULL')
  53. * @param string $resok resultat si test egal
  54. * @param string $resko resultat si test non egal
  55. * @return string SQL string
  56. */
  57. public function ifsql($test, $resok, $resko)
  58. {
  59. return $this->db->ifsql($test, $resok, $resko);
  60. }
  61. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  62. /**
  63. * Return datas as an array
  64. *
  65. * @param resource $resultset Resultset of request
  66. * @return array Array
  67. */
  68. public function fetch_row($resultset)
  69. {
  70. // phpcs:enable
  71. return $this->db->fetch_row($resultset);
  72. }
  73. /**
  74. * Convert (by PHP) a GM Timestamp date into a string date with PHP server TZ to insert into a date field.
  75. * Function to use to build INSERT, UPDATE or WHERE predica
  76. *
  77. * @param int $param Date TMS to convert
  78. * @param mixed $gm 'gmt'=Input informations are GMT values, 'tzserver'=Local to server TZ
  79. * @return string Date in a string YYYY-MM-DD HH:MM:SS
  80. */
  81. public function idate($param, $gm = 'tzserver')
  82. {
  83. return $this->db->idate($param, $gm);
  84. }
  85. /**
  86. * Return last error code
  87. *
  88. * @return string lasterrno
  89. */
  90. public function lasterrno()
  91. {
  92. return $this->db->lasterrno();
  93. }
  94. /**
  95. * Start transaction
  96. *
  97. * @return int 1 if transaction successfuly opened or already opened, 0 if error
  98. */
  99. public function begin()
  100. {
  101. return $this->db->begin();
  102. }
  103. /**
  104. * Create a new database
  105. * Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
  106. * We force to create database with charset this->forcecharset and collate this->forcecollate
  107. *
  108. * @param string $database Database name to create
  109. * @param string $charset Charset used to store data
  110. * @param string $collation Charset used to sort data
  111. * @param string $owner Username of database owner
  112. * @return resource resource defined if OK, null if KO
  113. */
  114. public function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
  115. {
  116. return $this->db->DDLCreateDb($database, $charset, $collation, $owner);
  117. }
  118. /**
  119. * Return version of database server into an array
  120. *
  121. * @return array Version array
  122. */
  123. public function getVersionArray()
  124. {
  125. return $this->db->getVersionArray();
  126. }
  127. /**
  128. * Convert a SQL request in Mysql syntax to native syntax
  129. *
  130. * @param string $line SQL request line to convert
  131. * @param string $type Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
  132. * @return string SQL request line converted
  133. */
  134. public static function convertSQLFromMysql($line, $type = 'ddl')
  135. {
  136. return self::$db->convertSQLFromMysql($line);
  137. }
  138. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  139. /**
  140. * Return the number o flines into the result of a request INSERT, DELETE or UPDATE
  141. *
  142. * @param resource $resultset Curseur de la requete voulue
  143. * @return int Number of lines
  144. * @see num_rows()
  145. */
  146. public function affected_rows($resultset)
  147. {
  148. // phpcs:enable
  149. return $this->db->affected_rows($resultset);
  150. }
  151. /**
  152. * Return description of last error
  153. *
  154. * @return string Error text
  155. */
  156. public function error()
  157. {
  158. return $this->db->error();
  159. }
  160. /**
  161. * List tables into a database
  162. *
  163. * @param string $database Name of database
  164. * @param string $table Nmae of table filter ('xxx%')
  165. * @return array List of tables in an array
  166. */
  167. public function DDLListTables($database, $table = '')
  168. {
  169. return $this->db->DDLListTables($database, $table);
  170. }
  171. /**
  172. * Return last request executed with query()
  173. *
  174. * @return string Last query
  175. */
  176. public function lastquery()
  177. {
  178. return $this->db->lastquery();
  179. }
  180. /**
  181. * Define sort criteria of request
  182. *
  183. * @param string $sortfield List of sort fields
  184. * @param string $sortorder Sort order
  185. * @return string String to provide syntax of a sort sql string
  186. */
  187. public function order($sortfield = null, $sortorder = null)
  188. {
  189. return $this->db->order($sortfield, $sortorder);
  190. }
  191. /**
  192. * Decrypt sensitive data in database
  193. *
  194. * @param string $value Value to decrypt
  195. * @return string Decrypted value if used
  196. */
  197. public function decrypt($value)
  198. {
  199. return $this->db->decrypt($value);
  200. }
  201. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  202. /**
  203. * Return datas as an array
  204. *
  205. * @param resource $resultset Resultset of request
  206. * @return array Array
  207. */
  208. public function fetch_array($resultset)
  209. {
  210. // phpcs:enable
  211. return $this->db->fetch_array($resultset);
  212. }
  213. /**
  214. * Return last error label
  215. *
  216. * @return string lasterror
  217. */
  218. public function lasterror()
  219. {
  220. return $this->db->lasterror();
  221. }
  222. /**
  223. * Escape a string to insert data
  224. *
  225. * @param string $stringtoencode String to escape
  226. * @return string String escaped
  227. */
  228. public function escape($stringtoencode)
  229. {
  230. return $this->db->escape($stringtoencode);
  231. }
  232. /**
  233. * Escape a string to insert data
  234. *
  235. * @param string $stringtoencode String to escape
  236. * @return string String escaped
  237. */
  238. public function escapeunderscore($stringtoencode)
  239. {
  240. return $this->db->escapeunderscore($stringtoencode);
  241. }
  242. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  243. /**
  244. * Get last ID after an insert INSERT
  245. *
  246. * @param string $tab Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql
  247. * @param string $fieldid Field name
  248. * @return int Id of row
  249. */
  250. public function last_insert_id($tab, $fieldid = 'rowid')
  251. {
  252. // phpcs:enable
  253. return $this->db->last_insert_id($tab, $fieldid);
  254. }
  255. /**
  256. * Return full path of restore program
  257. *
  258. * @return string Full path of restore program
  259. */
  260. public function getPathOfRestore()
  261. {
  262. return $this->db->getPathOfRestore();
  263. }
  264. /**
  265. * Cancel a transaction and go back to initial data values
  266. *
  267. * @param string $log Add more log to default log line
  268. * @return resource|int 1 if cancelation is ok or transaction not open, 0 if error
  269. */
  270. public function rollback($log = '')
  271. {
  272. return $this->db->rollback($log);
  273. }
  274. /**
  275. * Execute a SQL request and return the resultset
  276. *
  277. * @param string $query SQL query string
  278. * @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).
  279. * 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.
  280. * @param string $type Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
  281. * @param int $result_mode Result mode
  282. * @return resource Resultset of answer
  283. */
  284. public function query($query, $usesavepoint = 0, $type = 'auto', $result_mode = 0)
  285. {
  286. $this->startTracing();
  287. $resql = $this->db->query($query, $usesavepoint, $type, $result_mode);
  288. $this->endTracing($query, $resql);
  289. return $resql;
  290. }
  291. /**
  292. * Start query tracing
  293. *
  294. * @return void
  295. */
  296. protected function startTracing()
  297. {
  298. $this->startTime = microtime(true);
  299. $this->startMemory = memory_get_usage(true);
  300. }
  301. /**
  302. * End query tracing
  303. *
  304. * @param string $sql query string
  305. * @param string $resql query result
  306. * @return void
  307. */
  308. protected function endTracing($sql, $resql)
  309. {
  310. $endTime = microtime(true);
  311. $duration = $endTime - $this->startTime;
  312. $endMemory = memory_get_usage(true);
  313. $memoryDelta = $endMemory - $this->startMemory;
  314. $this->queries[] = array(
  315. 'sql' => $sql,
  316. 'duration' => $duration,
  317. 'memory_usage' => $memoryDelta,
  318. 'is_success' => $resql ? true : false,
  319. 'error_code' => $resql ? null : $this->db->lasterrno(),
  320. 'error_message' => $resql ? null : $this->db->lasterror()
  321. );
  322. }
  323. /**
  324. * Connexion to server
  325. *
  326. * @param string $host database server host
  327. * @param string $login login
  328. * @param string $passwd password
  329. * @param string $name name of database (not used for mysql, used for pgsql)
  330. * @param int $port Port of database server
  331. * @return resource Database access handler
  332. * @see close()
  333. */
  334. public function connect($host, $login, $passwd, $name, $port = 0)
  335. {
  336. return $this->db->connect($host, $login, $passwd, $name, $port);
  337. }
  338. /**
  339. * Define limits and offset of request
  340. *
  341. * @param int $limit Maximum number of lines returned (-1=conf->liste_limit, 0=no limit)
  342. * @param int $offset Numero of line from where starting fetch
  343. * @return string String with SQL syntax to add a limit and offset
  344. */
  345. public function plimit($limit = 0, $offset = 0)
  346. {
  347. return $this->db->plimit($limit, $offset);
  348. }
  349. /**
  350. * Return value of server parameters
  351. *
  352. * @param string $filter Filter list on a particular value
  353. * @return array Array of key-values (key=>value)
  354. */
  355. public function getServerParametersValues($filter = '')
  356. {
  357. return $this->db->getServerParametersValues($filter);
  358. }
  359. /**
  360. * Return value of server status
  361. *
  362. * @param string $filter Filter list on a particular value
  363. * @return array Array of key-values (key=>value)
  364. */
  365. public function getServerStatusValues($filter = '')
  366. {
  367. return $this->db->getServerStatusValues($filter);
  368. }
  369. /**
  370. * Return collation used in database
  371. *
  372. * @return string Collation value
  373. */
  374. public function getDefaultCollationDatabase()
  375. {
  376. return $this->db->getDefaultCollationDatabase();
  377. }
  378. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  379. /**
  380. * Return number of lines for result of a SELECT
  381. *
  382. * @param resource $resultset Resulset of requests
  383. * @return int Nb of lines
  384. * @see affected_rows()
  385. */
  386. public function num_rows($resultset)
  387. {
  388. // phpcs:enable
  389. return $this->db->num_rows($resultset);
  390. }
  391. /**
  392. * Return full path of dump program
  393. *
  394. * @return string Full path of dump program
  395. */
  396. public function getPathOfDump()
  397. {
  398. return $this->db->getPathOfDump();
  399. }
  400. /**
  401. * Return version of database client driver
  402. *
  403. * @return string Version string
  404. */
  405. public function getDriverInfo()
  406. {
  407. return $this->db->getDriverInfo();
  408. }
  409. /**
  410. * Return generic error code of last operation.
  411. *
  412. * @return string Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
  413. */
  414. public function errno()
  415. {
  416. return $this->db->errno();
  417. }
  418. /**
  419. * Create a table into database
  420. *
  421. * @param string $table Name of table
  422. * @param array $fields Tableau associatif [nom champ][tableau des descriptions]
  423. * @param string $primary_key Nom du champ qui sera la clef primaire
  424. * @param string $type Type de la table
  425. * @param array $unique_keys Tableau associatifs Nom de champs qui seront clef unique => valeur
  426. * @param array $fulltext_keys Tableau des Nom de champs qui seront indexes en fulltext
  427. * @param array $keys Tableau des champs cles noms => valeur
  428. * @return int <0 if KO, >=0 if OK
  429. */
  430. public function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
  431. {
  432. return $this->db->DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys, $fulltext_keys, $keys);
  433. }
  434. /**
  435. * Drop a table into database
  436. *
  437. * @param string $table Name of table
  438. * @return int <0 if KO, >=0 if OK
  439. */
  440. public function DDLDropTable($table)
  441. {
  442. return $this->db->DDLDropTable($table);
  443. }
  444. /**
  445. * Return list of available charset that can be used to store data in database
  446. *
  447. * @return array List of Charset
  448. */
  449. public function getListOfCharacterSet()
  450. {
  451. return $this->db->getListOfCharacterSet();
  452. }
  453. /**
  454. * Create a new field into table
  455. *
  456. * @param string $table Name of table
  457. * @param string $field_name Name of field to add
  458. * @param string $field_desc Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
  459. * @param string $field_position Optionnel ex.: "after champtruc"
  460. * @return int <0 if KO, >0 if OK
  461. */
  462. public function DDLAddField($table, $field_name, $field_desc, $field_position = "")
  463. {
  464. return $this->db->DDLAddField($table, $field_name, $field_desc, $field_position);
  465. }
  466. /**
  467. * Drop a field from table
  468. *
  469. * @param string $table Name of table
  470. * @param string $field_name Name of field to drop
  471. * @return int <0 if KO, >0 if OK
  472. */
  473. public function DDLDropField($table, $field_name)
  474. {
  475. return $this->db->DDLDropField($table, $field_name);
  476. }
  477. /**
  478. * Update format of a field into a table
  479. *
  480. * @param string $table Name of table
  481. * @param string $field_name Name of field to modify
  482. * @param string $field_desc Array with description of field format
  483. * @return int <0 if KO, >0 if OK
  484. */
  485. public function DDLUpdateField($table, $field_name, $field_desc)
  486. {
  487. return $this->db->DDLUpdateField($table, $field_name, $field_desc);
  488. }
  489. /**
  490. * Return list of available collation that can be used for database
  491. *
  492. * @return array List of Collation
  493. */
  494. public function getListOfCollation()
  495. {
  496. return $this->db->getListOfCollation();
  497. }
  498. /**
  499. * Return a pointer of line with description of a table or field
  500. *
  501. * @param string $table Name of table
  502. * @param string $field Optionnel : Name of field if we want description of field
  503. * @return resource Resource
  504. */
  505. public function DDLDescTable($table, $field = "")
  506. {
  507. return $this->db->DDLDescTable($table, $field);
  508. }
  509. /**
  510. * Return version of database server
  511. *
  512. * @return string Version string
  513. */
  514. public function getVersion()
  515. {
  516. return $this->db->getVersion();
  517. }
  518. /**
  519. * Return charset used to store data in database
  520. *
  521. * @return string Charset
  522. */
  523. public function getDefaultCharacterSetDatabase()
  524. {
  525. return $this->db->getDefaultCharacterSetDatabase();
  526. }
  527. /**
  528. * Create a user and privileges to connect to database (even if database does not exists yet)
  529. *
  530. * @param string $dolibarr_main_db_host Ip serveur
  531. * @param string $dolibarr_main_db_user Nom user a creer
  532. * @param string $dolibarr_main_db_pass Mot de passe user a creer
  533. * @param string $dolibarr_main_db_name Database name where user must be granted
  534. * @return int <0 if KO, >=0 if OK
  535. */
  536. public function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
  537. {
  538. return $this->db->DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name);
  539. }
  540. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  541. /**
  542. * Convert (by PHP) a PHP server TZ string date into a Timestamps date (GMT if gm=true)
  543. * 19700101020000 -> 3600 with TZ+1 and gmt=0
  544. * 19700101020000 -> 7200 whaterver is TZ if gmt=1
  545. *
  546. * @param string $string Date in a string (YYYYMMDDHHMMSS, YYYYMMDD, YYYY-MM-DD HH:MM:SS)
  547. * @param bool $gm 1=Input informations are GMT values, otherwise local to server TZ
  548. * @return int|string Date TMS or ''
  549. */
  550. public function jdate($string, $gm = false)
  551. {
  552. // phpcs:enable
  553. return $this->db->jdate($string, $gm);
  554. }
  555. /**
  556. * Encrypt sensitive data in database
  557. * Warning: This function includes the escape and add the SQL simple quotes on strings.
  558. *
  559. * @param string $fieldorvalue Field name or value to encrypt
  560. * @param int $withQuotes Return string including the SQL simple quotes. This param must always be 1 (Value 0 is bugged and deprecated).
  561. * @return string XXX(field) or XXX('value') or field or 'value'
  562. */
  563. public function encrypt($fieldorvalue, $withQuotes = 1)
  564. {
  565. return $this->db->encrypt($fieldorvalue, $withQuotes);
  566. }
  567. /**
  568. * Validate a database transaction
  569. *
  570. * @param string $log Add more log to default log line
  571. * @return int 1 if validation is OK or transaction level no started, 0 if ERROR
  572. */
  573. public function commit($log = '')
  574. {
  575. return $this->db->commit($log);
  576. }
  577. /**
  578. * List information of columns into a table.
  579. *
  580. * @param string $table Name of table
  581. * @return array Array with inforation on table
  582. */
  583. public function DDLInfoTable($table)
  584. {
  585. return $this->db->DDLInfoTable($table);
  586. }
  587. /**
  588. * Free last resultset used.
  589. *
  590. * @param resource $resultset Fre cursor
  591. * @return void
  592. */
  593. public function free($resultset = null)
  594. {
  595. return $this->db->free($resultset);
  596. }
  597. /**
  598. * Close database connexion
  599. *
  600. * @return boolean True if disconnect successfull, false otherwise
  601. * @see connect()
  602. */
  603. public function close()
  604. {
  605. return $this->db->close();
  606. }
  607. /**
  608. * Return last query in error
  609. *
  610. * @return string lastqueryerror
  611. */
  612. public function lastqueryerror()
  613. {
  614. return $this->db->lastqueryerror();
  615. }
  616. /**
  617. * Return connexion ID
  618. *
  619. * @return string Id connexion
  620. */
  621. public function DDLGetConnectId()
  622. {
  623. return $this->db->DDLGetConnectId();
  624. }
  625. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  626. /**
  627. * Returns the current line (as an object) for the resultset cursor
  628. *
  629. * @param resource|Connection $resultset Handler of the desired SQL request
  630. * @return Object Object result line or false if KO or end of cursor
  631. */
  632. public function fetch_object($resultset)
  633. {
  634. // phpcs:enable
  635. return $this->db->fetch_object($resultset);
  636. }
  637. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  638. /**
  639. * Select a database
  640. *
  641. * @param string $database Name of database
  642. * @return boolean true if OK, false if KO
  643. */
  644. public function select_db($database)
  645. {
  646. // phpcs:enable
  647. return $this->db->select_db($database);
  648. }
  649. }