dolibarr 24.0.1
pgsql.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2001 Fabien Seisen <seisen@linuxfr.org>
3 * Copyright (C) 2002-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
4 * Copyright (C) 2004-2014 Laurent Destailleur <eldy@users.sourceforge.net>
5 * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
6 * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
7 * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
8 * Copyright (C) 2012 Yann Droneaud <yann@droneaud.fr>
9 * Copyright (C) 2012 Florian Henry <florian.henry@open-concept.pro>
10 * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
11 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
12 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
13 *
14 * This program is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 3 of the License, or
17 * (at your option) any later version.
18 *
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
23 *
24 * You should have received a copy of the GNU General Public License
25 * along with this program. If not, see <https://www.gnu.org/licenses/>.
26 */
27
33require_once DOL_DOCUMENT_ROOT.'/core/db/DoliDB.class.php';
34
38class DoliDBPgsql extends DoliDB
39{
41 public $type = 'pgsql'; // Name of manager
42
44 const LABEL = 'PostgreSQL'; // Label of manager
45
47 public $forcecharset = 'UTF8'; // Can't be static as it may be forced with a dynamic value
48
50 public $forcecollate = ''; // Can't be static as it may be forced with a dynamic value
51
53 const VERSIONMIN = '9.0.0'; // Version min database
54
58 public $unescapeslashquot = false;
62 public $standard_conforming_strings = false;
63
64
68 private $_results;
69
70
71
83 public function __construct($type, $host, $user, $pass, $name = '', $port = 0) // @phpstan-ignore constructor.unusedParameter
84 {
85 global $conf, $langs;
86
87 // Note that having "static" property for "$forcecharset" and "$forcecollate" will make error here in strict mode, so they are not static
88 if (!empty($conf->db->character_set)) {
89 $this->forcecharset = $conf->db->character_set;
90 }
91 if (!empty($conf->db->dolibarr_main_db_collation)) {
92 $this->forcecollate = $conf->db->dolibarr_main_db_collation;
93 }
94
95 $this->database_user = $user;
96 $this->database_host = $host;
97 $this->database_port = $port;
98
99 $this->transaction_opened = 0;
100
101 //print "Name DB: $host,$user,$pass,$name<br>";
102
103 if (!function_exists("pg_connect")) {
104 $this->connected = false;
105 $this->ok = false;
106 $this->error = "Pgsql PHP functions are not available in this version of PHP";
107 dol_syslog(get_class($this)."::DoliDBPgsql : Pgsql PHP functions are not available in this version of PHP", LOG_ERR);
108 return;
109 }
110
111 if (!$host) {
112 $this->connected = false;
113 $this->ok = false;
114 $this->error = $langs->trans("ErrorWrongHostParameter");
115 dol_syslog(get_class($this)."::DoliDBPgsql : Connection Error, wrong host parameters", LOG_ERR);
116 return;
117 }
118
119 // Try server connection
120 //print "$host, $user, $pass, $name, $port";
121 $this->db = $this->connect($host, $user, $pass, $name, $port);
122
123 if ($this->db) {
124 $this->connected = true;
125 $this->ok = true;
126 } else {
127 // host, login ou password incorrect
128 $this->connected = false;
129 $this->ok = false;
130 $this->error = 'Host, login or password incorrect';
131 dol_syslog(get_class($this)."::DoliDBPgsql : Connection Error ".$this->error.'. Failed to connect to host='.$host.' port='.$port.' user='.$user, LOG_ERR);
132 }
133
134 // If server connection ok and DB connection is requested, try to connect to DB
135 if ($this->connected && $name) {
136 if ($this->select_db($name)) {
137 $this->database_selected = true;
138 $this->database_name = $name;
139 $this->ok = true;
140 } else {
141 $this->database_selected = false;
142 $this->database_name = '';
143 $this->ok = false;
144 $this->error = $this->error();
145 dol_syslog(get_class($this)."::DoliDBPgsql : Select_db Error ".$this->error, LOG_ERR);
146 }
147 } else {
148 // No database selection requested, ok or ko
149 $this->database_selected = false;
150 }
151 }
152
153
162 public function convertSQLFromMysql($line, $type = 'auto', $unescapeslashquot = false)
163 {
164 global $conf;
165
166 // Removed empty line if this is a comment line for SVN tagging
167 if (preg_match('/^--\s\$Id/i', $line)) {
168 return '';
169 }
170 // Return line if this is a comment
171 if (preg_match('/^#/i', $line) || preg_match('/^$/i', $line) || preg_match('/^--/i', $line)) {
172 return $line;
173 }
174 if ($line != "") {
175 // group_concat support (PgSQL >= 9.0)
176 // Replace group_concat(x) or group_concat(x SEPARATOR ',') with string_agg(x, ',')
177 $line = preg_replace('/GROUP_CONCAT/i', 'STRING_AGG', $line);
178 $line = preg_replace('/ SEPARATOR/i', ',', $line);
179 $line = preg_replace('/STRING_AGG\‍(([^,\‍)]+)\‍)/i', 'STRING_AGG(\\1, \',\')', $line);
180 $line = preg_replace('/STRING_AGG\‍(([^,]+),([^\‍)]+)\‍)/i', 'STRING_AGG(\\1::TEXT,\\2::TEXT)', $line);
181 //print $line."\n";
182
183 if ($type == 'auto') {
184 if (preg_match('/ALTER TABLE/i', $line)) {
185 $type = 'dml';
186 } elseif (preg_match('/CREATE TABLE/i', $line)) {
187 $type = 'dml';
188 } elseif (preg_match('/DROP TABLE/i', $line)) {
189 $type = 'dml';
190 }
191 }
192
193 $line = preg_replace('/ as signed\‍)/i', ' as integer)', $line);
194
195 if ($type == 'dml') {
196 $reg = array();
197
198 $line = preg_replace('/\s/', ' ', $line); // Replace tabulation with space
199
200 // we are inside create table statement so let's process datatypes
201 if (preg_match('/(ISAM|innodb)/i', $line)) { // end of create table sequence
202 $line = preg_replace('/\‍)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb).*;/i', ');', $line);
203 $line = preg_replace('/\‍)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb).*;/i', ');', $line);
204 $line = preg_replace('/,$/', '', $line);
205 }
206
207 // Process case: "CREATE TABLE llx_mytable(rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY,code..."
208 if (preg_match('/[\s\t\‍(]*(\w*)[\s\t]+int.*auto_increment/i', $line, $reg)) {
209 $newline = preg_replace('/([\s\t\‍(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i', '\\1 \\2 SERIAL PRIMARY KEY', $line);
210 //$line = "-- ".$line." replaced by --\n".$newline;
211 $line = $newline;
212 }
213
214 if (preg_match('/[\s\t\‍(]*(\w*)[\s\t]+bigint.*auto_increment/i', $line, $reg)) {
215 $newline = preg_replace('/([\s\t\‍(]*)([a-zA-Z_0-9]*)[\s\t]+bigint.*auto_increment[^,]*/i', '\\1 \\2 BIGSERIAL PRIMARY KEY', $line);
216 //$line = "-- ".$line." replaced by --\n".$newline;
217 $line = $newline;
218 }
219
220 // tinyint type conversion
221 $line = preg_replace('/tinyint\‍(?[0-9]*\‍)?/', 'smallint', $line);
222 $line = preg_replace('/tinyint/i', 'smallint', $line);
223
224 // nuke unsigned
225 $line = preg_replace('/(int\w+|smallint|bigint)\s+unsigned/i', '\\1', $line);
226
227 // blob -> text
228 $line = preg_replace('/\w*blob/i', 'text', $line);
229
230 // tinytext/mediumtext -> text
231 $line = preg_replace('/tinytext/i', 'text', $line);
232 $line = preg_replace('/mediumtext/i', 'text', $line);
233 $line = preg_replace('/longtext/i', 'text', $line);
234
235 $line = preg_replace('/text\‍([0-9]+\‍)/i', 'text', $line);
236
237 // change not null datetime field to null valid ones
238 // (to support remapping of "zero time" to null
239 $line = preg_replace('/datetime not null/i', 'datetime', $line);
240 $line = preg_replace('/datetime/i', 'timestamp', $line);
241
242 // double -> numeric
243 $line = preg_replace('/^double/i', 'numeric', $line);
244 $line = preg_replace('/(\s*)double/i', '\\1numeric', $line);
245 // float -> numeric
246 $line = preg_replace('/^float/i', 'numeric', $line);
247 $line = preg_replace('/(\s*)float/i', '\\1numeric', $line);
248
249 //Check tms timestamp field case (in Mysql this field is defaulted to now and
250 // on update defaulted by now
251 $line = preg_replace('/(\s*)tms(\s*)timestamp/i', '\\1tms timestamp without time zone DEFAULT now() NOT NULL', $line);
252
253 // nuke DEFAULT CURRENT_TIMESTAMP
254 $line = preg_replace('/(\s*)DEFAULT(\s*)CURRENT_TIMESTAMP/i', '\\1', $line);
255
256 // nuke ON UPDATE CURRENT_TIMESTAMP
257 $line = preg_replace('/(\s*)ON(\s*)UPDATE(\s*)CURRENT_TIMESTAMP/i', '\\1', $line);
258
259 // unique index(field1,field2)
260 if (preg_match('/unique index\s*\‍((\w+\s*,\s*\w+)\‍)/i', $line)) {
261 $line = preg_replace('/unique index\s*\‍((\w+\s*,\s*\w+)\‍)/i', 'UNIQUE\‍(\\1\‍)', $line);
262 }
263
264 // We remove end of requests "AFTER fieldxxx"
265 $line = preg_replace('/\sAFTER [a-z0-9_]+/i', '', $line);
266
267 // We remove start of requests "ALTER TABLE tablexxx" if this is a DROP INDEX
268 $line = preg_replace('/ALTER TABLE [a-z0-9_]+\s+DROP INDEX/i', 'DROP INDEX', $line);
269
270 // Translate order to rename fields
271 if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i', $line, $reg)) {
272 $line = "-- ".$line." replaced by --\n";
273 $line .= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
274 }
275
276 // Translate order to modify field format
277 if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i', $line, $reg)) {
278 $line = "-- ".$line." replaced by --\n";
279 $newreg3 = $reg[3];
280 $newreg3 = preg_replace('/ DEFAULT NULL/i', '', $newreg3);
281 $newreg3 = preg_replace('/ NOT NULL/i', '', $newreg3);
282 $newreg3 = preg_replace('/ NULL/i', '', $newreg3);
283 $newreg3 = preg_replace('/ DEFAULT 0/i', '', $newreg3);
284 $newreg3 = preg_replace('/ DEFAULT \'?[0-9a-zA-Z_@]*\'?/i', '', $newreg3);
285 $line .= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3;
286 // TODO Add alter to set default value or null/not null if there is this in $reg[3]
287 }
288
289 // alter table add primary key (field1, field2 ...) -> We remove the primary key name not accepted by PostGreSQL
290 // ALTER TABLE llx_dolibarr_modules ADD PRIMARY KEY pk_dolibarr_modules (numero, entity)
291 if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\‍((.*)$/i', $line, $reg)) {
292 $line = "-- ".$line." replaced by --\n";
293 $line .= "ALTER TABLE ".$reg[1]." ADD PRIMARY KEY (".$reg[3];
294 }
295
296 // Translate order to drop primary keys
297 // ALTER TABLE llx_dolibarr_modules DROP PRIMARY KEY pk_xxx
298 if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+PRIMARY\s+KEY\s*([^;]+)$/i', $line, $reg)) {
299 $line = "-- ".$line." replaced by --\n";
300 $line .= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
301 }
302
303 // Translate order to drop foreign keys
304 // ALTER TABLE llx_dolibarr_modules DROP FOREIGN KEY fk_xxx
305 if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i', $line, $reg)) {
306 $line = "-- ".$line." replaced by --\n";
307 $line .= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
308 }
309
310 // Translate order to add foreign keys
311 // ALTER TABLE llx_tablechild ADD CONSTRAINT fk_tablechild_fk_fieldparent FOREIGN KEY (fk_fieldparent) REFERENCES llx_tableparent (rowid)
312 if (preg_match('/ALTER\s+TABLE\s+(.*)\s*ADD CONSTRAINT\s+(.*)\s*FOREIGN\s+KEY\s*(.*)$/i', $line, $reg)) {
313 $line = preg_replace('/;$/', '', $line);
314 $line .= " DEFERRABLE INITIALLY IMMEDIATE;";
315 }
316
317 // alter table add [unique] [index] (field1, field2 ...)
318 // ALTER TABLE llx_accountingaccount ADD INDEX idx_accountingaccount_fk_pcg_version (fk_pcg_version)
319 if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\‍(([\w,\s]+)\‍)/i', $line, $reg)) {
320 $fieldlist = $reg[4];
321 $idxname = $reg[3];
322 $tablename = $reg[1];
323 $line = "-- ".$line." replaced by --\n";
324 $line .= "CREATE ".(preg_match('/UNIQUE/', $reg[2]) ? 'UNIQUE ' : '')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")";
325 }
326 }
327
328 // To have PostgreSQL case sensitive
329 $count_like = 0;
330 $line = str_replace(" LIKE '", " ILIKE '", $line, $count_like);
331 if (getDolGlobalString('PSQL_USE_UNACCENT') && $count_like > 0) {
332 // @see https://docs.PostgreSQL.fr/11/unaccent.html : 'unaccent()' function must be installed before
333 $line = preg_replace('/\s+(\‍(+\s*)([a-zA-Z0-9\-\_\.]+) ILIKE /', ' \1unaccent(\2) ILIKE ', $line);
334 }
335
336 $line = str_replace(" LIKE BINARY '", " LIKE '", $line);
337
338 // Replace INSERT IGNORE into INSERT
339 $line = preg_replace('/^INSERT IGNORE/', 'INSERT', $line);
340
341 // Delete using criteria on other table must not declare twice the deleted table
342 // DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable
343 if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', $line, $reg)) {
344 if ($reg[1] == $reg[2]) { // If same table, we remove second one
345 $line = preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', 'DELETE FROM \\1 USING \\3', $line);
346 }
347 }
348
349 // Remove () in the tables in FROM if 1 table
350 $line = preg_replace('/FROM\s*\‍((([a-z_]+)\s+as\s+([a-z_]+)\s*)\‍)/i', 'FROM \\1', $line);
351 //print $line."\n";
352
353 // Remove () in the tables in FROM if 2 table
354 $line = preg_replace('/FROM\s*\‍(([a-z_]+\s+as\s+[a-z_]+)\s*,\s*([a-z_]+\s+as\s+[a-z_]+\s*)\‍)/i', 'FROM \\1, \\2', $line);
355 //print $line."\n";
356
357 // Remove () in the tables in FROM if 3 table
358 $line = preg_replace('/FROM\s*\‍(([a-z_]+\s+as\s+[a-z_]+)\s*,\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*)\‍)/i', 'FROM \\1, \\2, \\3', $line);
359 //print $line."\n";
360
361 // Remove () in the tables in FROM if 4 table
362 $line = preg_replace('/FROM\s*\‍(([a-z_]+\s+as\s+[a-z_]+)\s*,\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*)\‍)/i', 'FROM \\1, \\2, \\3, \\4', $line);
363 //print $line."\n";
364
365 // Remove () in the tables in FROM if 5 table
366 $line = preg_replace('/FROM\s*\‍(([a-z_]+\s+as\s+[a-z_]+)\s*,\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*)\‍)/i', 'FROM \\1, \\2, \\3, \\4, \\5', $line);
367 //print $line."\n";
368
369 // Replace spacing ' with ''.
370 // By default we do not (should be already done by db->escape function if required
371 // except for sql insert in data file that are mysql escaped so we removed them to
372 // be compatible with standard_conforming_strings=on that considers \ as ordinary character).
373 if ($unescapeslashquot) {
374 $line = preg_replace("/\\\'/", "''", $line);
375 }
376
377 //print "type=".$type." newline=".$line."<br>\n";
378 }
379
380 return $line;
381 }
382
383 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
392 public function select_db($database)
393 {
394 // phpcs:enable
395 if ($database == $this->database_name) {
396 return true;
397 } else {
398 return false;
399 }
400 }
401
413 public function connect($host, $login, $passwd, $name, $port = 0)
414 {
415 // use pg_pconnect() instead of pg_connect() if you want to use persistent connection costing 1ms, instead of 30ms for non persistent
416
417 $this->db = false;
418
419 // connections parameters must be protected (only \ and ' according to pg_connect() manual)
420 $host = str_replace(array("\\", "'"), array("\\\\", "\\'"), $host);
421 $login = str_replace(array("\\", "'"), array("\\\\", "\\'"), $login);
422 $passwd = str_replace(array("\\", "'"), array("\\\\", "\\'"), $passwd);
423 $name = str_replace(array("\\", "'"), array("\\\\", "\\'"), $name);
424 $port = str_replace(array("\\", "'"), array("\\\\", "\\'"), (string) $port);
425
426 if (!$name) {
427 $name = "postgres"; // When try to connect using admin user
428 }
429
430 // try first Unix domain socket (local)
431 if ((!empty($host) && $host == "socket") && !defined('NOLOCALSOCKETPGCONNECT')) {
432 $con_string = "dbname='".$name."' user='".$login."' password='".$passwd."'"; // $name may be empty
433 try {
434 // PGSQL_CONNECT_FORCE_NEW is required: pg_connect() otherwise returns the connection already
435 // opened for the same connection string, so a second handle would share the main one and
436 // closing it would close the connection still in use by the caller.
437 $this->db = @pg_connect($con_string, PGSQL_CONNECT_FORCE_NEW);
438 } catch (Exception $e) {
439 // No message
440 }
441 }
442
443 // if local connection failed or not requested, use TCP/IP
444 if (empty($this->db)) {
445 if (!$host) {
446 $host = "localhost";
447 }
448 if (!$port) {
449 $port = 5432;
450 }
451
452 $con_string = "host='".$host."' port='".$port."' dbname='".$name."' user='".$login."' password='".$passwd."'";
453 try {
454 $this->db = @pg_connect($con_string, PGSQL_CONNECT_FORCE_NEW);
455 } catch (Exception $e) {
456 print $e->getMessage();
457 }
458 }
459
460 // now we test if at least one connect method was a success
461 if ($this->db) {
462 $this->database_name = $name;
463 pg_set_error_verbosity($this->db, PGSQL_ERRORS_VERBOSE); // Set verbosity to max
464 pg_query($this->db, "set datestyle = 'ISO, YMD';");
465 }
466
467 return $this->db;
468 }
469
475 public function getVersion()
476 {
477 $resql = $this->query('SHOW server_version');
478 if ($resql) {
479 $liste = $this->fetch_array($resql);
480 return $liste['server_version'];
481 }
482 return '';
483 }
484
490 public function getDriverInfo()
491 {
492 return 'pgsql php driver';
493 }
494
501 public function close()
502 {
503 if ($this->db) {
504 if ($this->transaction_opened > 0) {
505 dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened, LOG_ERR);
506 }
507 $this->connected = false;
508 return pg_close($this->db);
509 }
510 return false;
511 }
512
522 public function query($query, $usesavepoint = 0, $type = 'auto', $result_mode = 0)
523 {
524 global $dolibarr_main_db_readonly;
525
526 $query = trim($query);
527
528 // Convert MySQL syntax to PostgreSQL syntax
529 $query = $this->convertSQLFromMysql($query, $type, ($this->unescapeslashquot && $this->standard_conforming_strings));
530 //print "After convertSQLFromMysql:\n".$query."<br>\n";
531
532 if (getDolGlobalString('MAIN_DB_AUTOFIX_BAD_SQL_REQUEST')) {
533 // Fix bad formed requests. If request contains a date without quotes, we fix this but this should not occurs.
534 $loop = true;
535 while ($loop) {
536 if (preg_match('/([^\'])([0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9])/', $query)) {
537 $query = preg_replace('/([^\'])([0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9])/', '\\1\'\\2\'', $query);
538 dol_syslog("Warning: Bad formed request converted into ".$query, LOG_WARNING);
539 } else {
540 $loop = false;
541 }
542 }
543 }
544
545 if ($usesavepoint && $this->transaction_opened) {
546 @pg_query($this->db, 'SAVEPOINT mysavepoint');
547 }
548
549 if (!in_array($query, array('BEGIN', 'COMMIT', 'ROLLBACK'))) {
550 $SYSLOG_SQL_LIMIT = 10000; // limit log to 10kb per line to limit DOS attacks
551 dol_syslog('sql='.substr($query, 0, $SYSLOG_SQL_LIMIT), LOG_DEBUG);
552 }
553 if (empty($query)) {
554 return false; // Return false = error if empty request
555 }
556
557 if (!empty($dolibarr_main_db_readonly)) {
558 if (preg_match('/^(INSERT|UPDATE|REPLACE|DELETE|CREATE|ALTER|TRUNCATE|DROP)/i', $query)) {
559 $this->lasterror = 'Application in read-only mode';
560 $this->lasterrno = 'APPREADONLY';
561 $this->lastquery = $query;
562 return false;
563 }
564 }
565
566 $ret = @pg_query($this->db, $query);
567
568 //print $query;
569 if (!preg_match("/^COMMIT/i", $query) && !preg_match("/^ROLLBACK/i", $query)) { // Si requete utilisateur, on la sauvegarde ainsi que son resultset
570 if (!$ret) {
571 if ($this->errno() != 'DB_ERROR_25P02') { // Do not overwrite errors if this is a consecutive error
572 $this->lastqueryerror = $query;
573 $this->lasterror = $this->error();
574 $this->lasterrno = $this->errno();
575
576 if (getDolGlobalInt('SYSLOG_LEVEL') < LOG_DEBUG) {
577 dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR); // Log of request was not yet done previously
578 }
579 dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterror." (".$this->lasterrno.")", LOG_ERR);
580 dol_syslog(get_class($this)."::query SQL Error usesavepoint = ".$usesavepoint, LOG_ERR);
581 }
582
583 if ($usesavepoint && $this->transaction_opened) { // Warning, after that errno will be erased
584 @pg_query($this->db, 'ROLLBACK TO SAVEPOINT mysavepoint');
585 }
586 }
587 $this->lastquery = $query;
588 $this->_results = $ret;
589 }
590
591 return $ret;
592 }
593
594 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
601 public function fetch_object($resultset)
602 {
603 // phpcs:enable
604 // If resultset not provided, we take the last used by connection
605 if (!is_resource($resultset) && !is_object($resultset)) {
606 $resultset = $this->_results;
607 }
608 return pg_fetch_object($resultset);
609 }
610
611 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
618 public function fetch_array($resultset)
619 {
620 // phpcs:enable
621 // If resultset not provided, we take the last used by connection
622 if (!is_resource($resultset) && !is_object($resultset)) {
623 $resultset = $this->_results;
624 }
625 return pg_fetch_array($resultset);
626 }
627
628 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
636 public function fetch_row($resultset)
637 {
638 // phpcs:enable
639 // If resultset not provided, we take the last used by connection
640 if (!is_resource($resultset) && !is_object($resultset)) {
641 $resultset = $this->_results;
642 }
643 if (is_bool($resultset)) {
644 return 0;
645 }
646 return pg_fetch_row($resultset); // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal
647 }
648
649 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
657 public function num_rows($resultset)
658 {
659 // phpcs:enable
660 // If resultset not provided, we take the last used by connection
661 if (!is_resource($resultset) && !is_object($resultset)) {
662 $resultset = $this->_results;
663 }
664 // avoid error if $resultset = null or false
665 if ($resultset) {
666 return pg_num_rows($resultset);
667 } else {
668 return 0;
669 } // end of avoid error
670 }
671
672 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
680 public function affected_rows($resultset)
681 {
682 // phpcs:enable
683 // If resultset not provided, we take the last used by connection
684 if (!is_resource($resultset) && !is_object($resultset)) {
685 $resultset = $this->_results;
686 }
687 // pgsql requires a resultset for this function contrary to
688 // mysql that requires a database link
689 return pg_affected_rows($resultset);
690 }
691
692
699 public function free($resultset = null)
700 {
701 // If resultset not provided, we take the last used by connection
702 if (!is_resource($resultset) && !is_object($resultset)) {
703 $resultset = $this->_results;
704 }
705 // If it is a resource, we free the memory
706 if (is_resource($resultset) || is_object($resultset)) {
707 pg_free_result($resultset);
708 }
709 }
710
711
719 public function plimit($limit = 0, $offset = 0)
720 {
721 global $conf;
722 if (empty($limit)) {
723 return "";
724 }
725 if ($limit < 0) {
726 $limit = $conf->liste_limit;
727 }
728 if ($offset > 0) {
729 return " LIMIT ".$limit." OFFSET ".$offset." ";
730 } else {
731 return " LIMIT $limit ";
732 }
733 }
734
735
742 public function escape($stringtoencode)
743 {
744 return pg_escape_string($this->db, $stringtoencode);
745 }
746
753 public function escapeforlike($stringtoencode)
754 {
755 return str_replace(array('\\', '_', '%'), array('\\\\', '\_', '\%'), (string) $stringtoencode);
756 }
757
766 public function ifsql($test, $resok, $resko)
767 {
768 return '(CASE WHEN '.$test.' THEN '.$resok.' ELSE '.$resko.' END)';
769 }
770
779 public function regexpsql($subject, $pattern, $sqlstring = 0)
780 {
781 if ($sqlstring) {
782 return "(". $subject ." ~ '" . $this->escape($pattern) . "')";
783 }
784
785 return "('". $this->escape($subject) ."' ~ '" . $this->escape($pattern) . "')";
786 }
787
788
794 public function errno()
795 {
796 if (!$this->connected) {
797 // Si il y a eu echec de connection, $this->db n'est pas valide.
798 return 'DB_ERROR_FAILED_TO_CONNECT';
799 } else {
800 // Constants to convert error code to a generic Dolibarr error code
801 $errorcode_map = array(
802 1004 => 'DB_ERROR_CANNOT_CREATE',
803 1005 => 'DB_ERROR_CANNOT_CREATE',
804 1006 => 'DB_ERROR_CANNOT_CREATE',
805 1007 => 'DB_ERROR_ALREADY_EXISTS',
806 1008 => 'DB_ERROR_CANNOT_DROP',
807 1025 => 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
808 1044 => 'DB_ERROR_ACCESSDENIED',
809 1046 => 'DB_ERROR_NODBSELECTED',
810 1048 => 'DB_ERROR_CONSTRAINT',
811 '42P07' => 'DB_ERROR_TABLE_OR_KEY_ALREADY_EXISTS',
812 '42703' => 'DB_ERROR_NOSUCHFIELD',
813 1060 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
814 42701 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
815 '42710' => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
816 '23505' => 'DB_ERROR_RECORD_ALREADY_EXISTS',
817 '42704' => 'DB_ERROR_NO_INDEX_TO_DROP', // May also be Type xxx does not exists
818 '42601' => 'DB_ERROR_SYNTAX',
819 '42P16' => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
820 1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
821 1091 => 'DB_ERROR_NOSUCHFIELD',
822 1100 => 'DB_ERROR_NOT_LOCKED',
823 1136 => 'DB_ERROR_VALUE_COUNT_ON_ROW',
824 '42P01' => 'DB_ERROR_NOSUCHTABLE',
825 '23503' => 'DB_ERROR_NO_PARENT',
826 1217 => 'DB_ERROR_CHILD_EXISTS',
827 1451 => 'DB_ERROR_CHILD_EXISTS',
828 '42P04' => 'DB_DATABASE_ALREADY_EXISTS'
829 );
830
831 $errorlabel = pg_last_error($this->db);
832 $errorcode = '';
833 $reg = array();
834 if (preg_match('/: *([0-9P]+):/', $errorlabel, $reg)) {
835 $errorcode = $reg[1];
836 if (isset($errorcode_map[$errorcode])) {
837 return $errorcode_map[$errorcode];
838 }
839 }
840 $errno = $errorcode ? $errorcode : $errorlabel;
841 return ($errno ? 'DB_ERROR_'.$errno : '0');
842 }
843 // '/(Table does not exist\.|Relation [\"\'].*[\"\'] does not exist|sequence does not exist|class ".+" not found)$/' => 'DB_ERROR_NOSUCHTABLE',
844 // '/table [\"\'].*[\"\'] does not exist/' => 'DB_ERROR_NOSUCHTABLE',
845 // '/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*/' => 'DB_ERROR_RECORD_ALREADY_EXISTS',
846 // '/divide by zero$/' => 'DB_ERROR_DIVZERO',
847 // '/pg_atoi: error in .*: can\'t parse /' => 'DB_ERROR_INVALID_NUMBER',
848 // '/ttribute [\"\'].*[\"\'] not found$|Relation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/' => 'DB_ERROR_NOSUCHFIELD',
849 // '/parser: parse error at or near \"/' => 'DB_ERROR_SYNTAX',
850 // '/referential integrity violation/' => 'DB_ERROR_CONSTRAINT'
851 }
852
858 public function error()
859 {
860 return pg_last_error($this->db);
861 }
862
863 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
871 public function last_insert_id($table, $fieldid = 'rowid')
872 {
873 // phpcs:enable
874 $sequencename = $table."_".$fieldid."_seq";
875
876 //$result = pg_query($this->db,"SELECT MAX(".$fieldid.") FROM ".$table);
877 $result = pg_query($this->db, "SELECT currval('".$sequencename."')");
878 if (!$result) {
879 print pg_last_error($this->db);
880 return -1;
881 }
882 //$nbre = pg_num_rows($result);
883 $row = pg_fetch_result($result, 0, 0);
884 return (int) $row;
885 }
886
895 public function encrypt($fieldorvalue, $withQuotes = 1)
896 {
897 //global $conf;
898
899 // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
900 //$cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
901
902 //Encryption key
903 //$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
904
905 $return = $fieldorvalue;
906 return ($withQuotes ? "'" : "").$this->escape($return).($withQuotes ? "'" : "");
907 }
908
909
916 public function decrypt($value)
917 {
918 //global $conf;
919
920 // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
921 //$cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
922
923 //Encryption key
924 //$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
925
926 $return = $value;
927 return $return;
928 }
929
930
931 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
937 public function DDLGetConnectId()
938 {
939 // phpcs:enable
940 return '?';
941 }
942
943
944
945 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
957 public function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
958 {
959 // phpcs:enable
960 if (empty($charset)) {
961 $charset = $this->forcecharset;
962 }
963 if (empty($collation)) {
964 $collation = $this->forcecollate;
965 }
966
967 // Test charset match LC_TYPE (pgsql error otherwise)
968 //print $charset.' '.setlocale(LC_CTYPE,'0'); exit;
969
970 // NOTE: Do not use ' around the database name
971 $sql = "CREATE DATABASE ".$this->sanitize($database)." OWNER '".$this->escape($owner)."' ENCODING '".$this->escape((string) $charset)."'";
972
973 dol_syslog($sql, LOG_DEBUG);
974 $ret = $this->query($sql);
975
976 return $ret;
977 }
978
979 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
987 public function DDLListTables($database, $table = '')
988 {
989 // phpcs:enable
990 $listtables = array();
991
992 $escapedlike = '';
993 if ($table) {
994 $tmptable = preg_replace('/[^a-z0-9\.\-\_%]/i', '', $table);
995
996 $escapedlike = " AND table_name LIKE '".$this->escape($tmptable)."'";
997 }
998 $result = pg_query($this->db, "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'".$escapedlike." ORDER BY table_name");
999 if ($result) {
1000 while ($row = $this->fetch_row($result)) { // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal
1001 $listtables[] = $row[0];
1002 }
1003 }
1004 return $listtables;
1005 }
1006
1007 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1015 public function DDLListTablesFull($database, $table = '')
1016 {
1017 // phpcs:enable
1018 $listtables = array();
1019
1020 $escapedlike = '';
1021 if ($table) {
1022 $tmptable = preg_replace('/[^a-z0-9\.\-\_%]/i', '', $table);
1023
1024 $escapedlike = " AND table_name LIKE '".$this->escape($tmptable)."'";
1025 }
1026 $result = pg_query($this->db, "SELECT table_name, table_type FROM information_schema.tables WHERE table_schema = 'public'".$escapedlike." ORDER BY table_name");
1027 if ($result) {
1028 while ($row = $this->fetch_row($result)) { // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal
1029 $listtables[] = $row;
1030 }
1031 }
1032 return $listtables;
1033 }
1034
1035 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1042 public function DDLInfoTable($table)
1043 {
1044 // phpcs:enable
1045 $infotables = array();
1046
1047 $sql = "SELECT ";
1048 $sql .= " infcol.column_name as \"Column\","; // pgsql need " for alias names !
1049 $sql .= " CASE WHEN infcol.character_maximum_length IS NOT NULL THEN infcol.udt_name || '('||infcol.character_maximum_length||')'";
1050 $sql .= " ELSE infcol.udt_name";
1051 $sql .= " END as \"Type\","; // pgsql need " for alias names !
1052 $sql .= " infcol.collation_name as \"Collation\","; // pgsql need " for alias names !
1053 $sql .= " infcol.is_nullable as \"Null\","; // pgsql need " for alias names !
1054 $sql .= " '' as \"Key\","; // pgsql need " for alias names !
1055 $sql .= " infcol.column_default as \"Default\","; // pgsql need " for alias names !
1056 $sql .= " '' as \"Extra\","; // pgsql need " for alias names !
1057 $sql .= " '' as \"Privileges\""; // pgsql need " for alias names !
1058 $sql .= " FROM information_schema.columns infcol";
1059 $sql .= " WHERE table_schema = 'public' ";
1060 $sql .= " AND table_name = '".$this->escape($table)."'";
1061 $sql .= " ORDER BY ordinal_position;";
1062
1063 $result = $this->query($sql);
1064 if ($result) {
1065 while ($row = $this->fetch_row($result)) {
1066 $infotables[] = $row;
1067 }
1068 }
1069 return $infotables;
1070 }
1071
1072
1073 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1086 public function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
1087 {
1088 // phpcs:enable
1089 // @TODO: $fulltext_keys parameter is unused
1090
1091 $sqlk = array();
1092 $sqluq = array();
1093
1094 // Keys found into the array $fields: type,value,attribute,null,default,extra
1095 // ex. : $fields['rowid'] = array(
1096 // 'type'=>'int' or 'integer',
1097 // 'value'=>'11',
1098 // 'null'=>'not null',
1099 // 'extra'=> 'auto_increment'
1100 // );
1101 $sql = "CREATE TABLE ".$this->sanitize($table)."(";
1102 $i = 0;
1103 $sqlfields = array();
1104 foreach ($fields as $field_name => $field_desc) {
1105 $sqlfields[$i] = $this->sanitize($field_name)." ";
1106 $sqlfields[$i] .= $this->sanitize($field_desc['type']);
1107 if (isset($field_desc['value']) && $field_desc['value'] !== '') {
1108 $sqlfields[$i] .= "(".$this->sanitize($field_desc['value']).")";
1109 }
1110 if (isset($field_desc['attribute']) && $field_desc['attribute'] !== '') {
1111 $sqlfields[$i] .= " ".$this->sanitize($field_desc['attribute'], 0, 0, 1); // Allow space to accept attributes like "ON UPDATE CURRENT_TIMESTAMP"
1112 }
1113 if (isset($field_desc['default']) && $field_desc['default'] !== '') {
1114 if (in_array($field_desc['type'], array('tinyint', 'smallint', 'int', 'double'))) {
1115 $sqlfields[$i] .= " DEFAULT ".((float) $field_desc['default']);
1116 } elseif ($field_desc['default'] == 'null' || $field_desc['default'] == 'CURRENT_TIMESTAMP') {
1117 $sqlfields[$i] .= " DEFAULT ".$this->sanitize($field_desc['default']);
1118 } else {
1119 $sqlfields[$i] .= " DEFAULT '".$this->escape($field_desc['default'])."'";
1120 }
1121 }
1122 if (isset($field_desc['null']) && $field_desc['null'] !== '') {
1123 $sqlfields[$i] .= " ".$this->sanitize($field_desc['null'], 0, 0, 1);
1124 }
1125 if (isset($field_desc['extra']) && $field_desc['extra'] !== '') {
1126 $sqlfields[$i] .= " ".$this->sanitize($field_desc['extra'], 0, 0, 1);
1127 }
1128 if (!empty($primary_key) && $primary_key == $field_name) {
1129 $sqlfields[$i] .= " AUTO_INCREMENT PRIMARY KEY"; // mysql instruction that will be converted by driver late
1130 }
1131 $i++;
1132 }
1133
1134 if (is_array($unique_keys)) {
1135 $i = 0;
1136 foreach ($unique_keys as $key => $value) {
1137 $sqluq[$i] = "UNIQUE KEY '".$this->sanitize($key)."' ('".$this->escape($value)."')";
1138 $i++;
1139 }
1140 }
1141 if (is_array($keys)) {
1142 $i = 0;
1143 foreach ($keys as $key => $value) {
1144 $sqlk[$i] = "KEY ".$this->sanitize($key)." (".$value.")";
1145 $i++;
1146 }
1147 }
1148 $sql .= implode(', ', $sqlfields);
1149 if (!is_array($unique_keys) && $unique_keys != "") {
1150 $sql .= ",".implode(',', $sqluq);
1151 }
1152 if (is_array($keys)) {
1153 $sql .= ",".implode(',', $sqlk);
1154 }
1155 $sql .= ")";
1156 //$sql .= " engine=".$this->sanitize($type);
1157
1158 if (!$this->query($sql, 1)) {
1159 return -1;
1160 } else {
1161 return 1;
1162 }
1163 }
1164
1165 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1172 public function DDLDropTable($table)
1173 {
1174 // phpcs:enable
1175 $tmptable = preg_replace('/[^a-z0-9\.\-\_]/i', '', $table);
1176
1177 $sql = "DROP TABLE ".$this->sanitize($tmptable);
1178
1179 if (!$this->query($sql, 1)) {
1180 return -1;
1181 } else {
1182 return 1;
1183 }
1184 }
1185
1186 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1194 public function DDLDescTable($table, $field = "")
1195 {
1196 // phpcs:enable
1197 $sql = "SELECT attname FROM pg_attribute, pg_type WHERE typname = '".$this->escape($table)."' AND attrelid = typrelid";
1198 $sql .= " AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', 'tableoid', 'xmin', 'xmax')";
1199 if ($field) {
1200 $sql .= " AND attname = '".$this->escape($field)."'";
1201 }
1202
1203 dol_syslog($sql, LOG_DEBUG);
1204 $this->_results = $this->query($sql);
1205 return $this->_results;
1206 }
1207
1208 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1218 public function DDLAddField($table, $field_name, $field_desc, $field_position = "")
1219 {
1220 // phpcs:enable
1221 // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
1222 // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
1223 $sql = "ALTER TABLE ".$this->sanitize($table)." ADD ".$this->sanitize($field_name)." ";
1224
1225 if ($field_desc['type'] !== 'datetimegmt') {
1226 $sql .= $this->sanitize($field_desc['type']);
1227 } else {
1228 $sql .= 'datetime';
1229 }
1230
1231 if (in_array($field_desc['type'], array('varchar')) && array_key_exists('value', $field_desc) && !empty($field_desc['value'])) {
1232 $sql .= "(".$this->sanitize($field_desc['value']).")";
1233 }
1234 if (isset($field_desc['attribute']) && preg_match("/^[^\s]/i", $field_desc['attribute'])) {
1235 $sql .= " ".$this->sanitize($field_desc['attribute']);
1236 }
1237 if (isset($field_desc['null']) && preg_match("/^[^\s]/i", $field_desc['null'])) {
1238 if ($field_desc['null'] == 'NOT NULL') {
1239 $sql .= " ".$this->sanitize($field_desc['null'], 0, 0, 1);
1240 } else {
1241 $sql .= " ".$this->sanitize($field_desc['null']);
1242 }
1243 }
1244 if (isset($field_desc['default']) && preg_match("/^[^\s]/i", $field_desc['default'])) {
1245 if (in_array($field_desc['type'], array('tinyint', 'smallint', 'int', 'double'))) {
1246 $sql .= " DEFAULT ".((float) $field_desc['default']);
1247 } elseif ($field_desc['default'] == 'null' || $field_desc['default'] == 'CURRENT_TIMESTAMP') {
1248 $sql .= " DEFAULT ".$this->sanitize($field_desc['default']);
1249 } else {
1250 $sql .= " DEFAULT '".$this->escape($field_desc['default'])."'";
1251 }
1252 }
1253 if (isset($field_desc['extra']) && preg_match("/^[^\s]/i", $field_desc['extra'])) {
1254 $sql .= " ".$this->sanitize($field_desc['extra'], 0, 0, 1);
1255 }
1256 $sql .= " ".$this->sanitize($field_position, 0, 0, 1);
1257
1258 dol_syslog(get_class($this)."::DDLAddField ".$sql, LOG_DEBUG);
1259 if ($this->query($sql)) {
1260 return 1;
1261 }
1262 return -1;
1263 }
1264
1265 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1274 public function DDLUpdateField($table, $field_name, $field_desc)
1275 {
1276 // phpcs:enable
1277 $sql = "ALTER TABLE ".$this->sanitize($table);
1278 $sql .= " ALTER COLUMN ".$this->sanitize($field_name)." TYPE ";
1279
1280 if ($field_desc['type'] !== 'datetimegmt') {
1281 $sql .= $this->sanitize($field_desc['type']);
1282 } else {
1283 $sql .= 'datetime';
1284 }
1285
1286 if (in_array($field_desc['type'], array('varchar')) && array_key_exists('value', $field_desc) && !empty($field_desc['value'])) {
1287 $sql .= "(".$this->sanitize($field_desc['value']).")";
1288 }
1289
1290 if (isset($field_desc['null']) && ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL')) {
1291 // We will try to change format of column to NOT NULL. To be sure the ALTER works, we try to update fields that are NULL
1292 if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text') {
1293 $sqlbis = "UPDATE ".$this->sanitize($table)." SET ".$this->sanitize($field_name)." = '".$this->escape(isset($field_desc['default']) ? $field_desc['default'] : '')."' WHERE ".$this->sanitize($field_name)." IS NULL";
1294 $this->query($sqlbis);
1295 } elseif (in_array($field_desc['type'], array('tinyint', 'smallint', 'int', 'double'))) {
1296 $sqlbis = "UPDATE ".$this->sanitize($table)." SET ".$this->sanitize($field_name)." = ".((float) $this->escape(isset($field_desc['default']) ? $field_desc['default'] : 0))." WHERE ".$this->sanitize($field_name)." IS NULL";
1297 $this->query($sqlbis);
1298 }
1299 }
1300
1301 if (isset($field_desc['default']) && $field_desc['default'] != '') {
1302 if (in_array($field_desc['type'], array('tinyint', 'smallint', 'int', 'double'))) {
1303 $sql .= ", ALTER COLUMN ".$this->sanitize($field_name)." SET DEFAULT ".((float) $field_desc['default']);
1304 } elseif ($field_desc['type'] != 'text') { // Default not supported on text fields ?
1305 $sql .= ", ALTER COLUMN ".$this->sanitize($field_name)." SET DEFAULT '".$this->escape($field_desc['default'])."'";
1306 }
1307 }
1308
1309 dol_syslog($sql, LOG_DEBUG);
1310 if (!$this->query($sql)) {
1311 return -1;
1312 }
1313 return 1;
1314 }
1315
1316 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1324 public function DDLDropField($table, $field_name)
1325 {
1326 // phpcs:enable
1327 $tmp_field_name = preg_replace('/[^a-z0-9\.\-\_]/i', '', $field_name);
1328
1329 $sql = "ALTER TABLE ".$this->sanitize($table)." DROP COLUMN ".$this->sanitize($tmp_field_name);
1330 if (!$this->query($sql)) {
1331 $this->error = $this->lasterror();
1332 return -1;
1333 }
1334 return 1;
1335 }
1336
1337 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1347 public function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
1348 {
1349 // phpcs:enable
1350 // Note: using ' on user does not works with pgsql
1351 $sql = "CREATE USER ".$this->sanitize($dolibarr_main_db_user)." with password '".$this->escape($dolibarr_main_db_pass)."'";
1352
1353 dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
1354 $resql = $this->query($sql);
1355 if (!$resql) {
1356 return -1;
1357 }
1358
1359 return 1;
1360 }
1361
1368 {
1369 $resql = $this->query('SHOW SERVER_ENCODING');
1370 if ($resql) {
1371 $liste = $this->fetch_array($resql);
1372 return $liste['server_encoding'];
1373 } else {
1374 return '';
1375 }
1376 }
1377
1383 public function getListOfCharacterSet()
1384 {
1385 $resql = $this->query('SHOW SERVER_ENCODING');
1386 $liste = array();
1387 if ($resql) {
1388 $i = 0;
1389 while ($obj = $this->fetch_object($resql)) {
1390 $liste[$i]['charset'] = $obj->server_encoding;
1391 $liste[$i]['description'] = 'Default database charset';
1392 $i++;
1393 }
1394 $this->free($resql);
1395 } else {
1396 return null;
1397 }
1398 return $liste;
1399 }
1400
1407 {
1408 $resql = $this->query('SHOW LC_COLLATE');
1409 if ($resql) {
1410 $liste = $this->fetch_array($resql);
1411 return $liste['lc_collate'];
1412 } else {
1413 return '';
1414 }
1415 }
1416
1422 public function getListOfCollation()
1423 {
1424 $resql = $this->query('SHOW LC_COLLATE');
1425 $liste = array();
1426 if ($resql) {
1427 $i = 0;
1428 while ($obj = $this->fetch_object($resql)) {
1429 $liste[$i]['collation'] = $obj->lc_collate;
1430 $i++;
1431 }
1432 $this->free($resql);
1433 } else {
1434 return null;
1435 }
1436 return $liste;
1437 }
1438
1444 public function getPathOfDump()
1445 {
1446 $fullpathofdump = '/pathtopgdump/pg_dump';
1447
1448 if (file_exists('/usr/bin/pg_dump')) {
1449 $fullpathofdump = '/usr/bin/pg_dump';
1450 } else {
1451 // TODO The database user must be a superadmin to run this command
1452 $resql = $this->query('SHOW data_directory');
1453 if ($resql) {
1454 $liste = $this->fetch_array($resql);
1455 $basedir = $liste['data_directory'];
1456 $fullpathofdump = preg_replace('/data$/', 'bin', $basedir).'/pg_dump';
1457 }
1458 }
1459
1460 return $fullpathofdump;
1461 }
1462
1468 public function getPathOfRestore()
1469 {
1470 //$tool='pg_restore';
1471 $tool = 'psql';
1472
1473 $fullpathofdump = '/pathtopgrestore/'.$tool;
1474
1475 if (file_exists('/usr/bin/'.$tool)) {
1476 $fullpathofdump = '/usr/bin/'.$tool;
1477 } else {
1478 // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1479 $resql = $this->query('SHOW data_directory');
1480 if ($resql) {
1481 $liste = $this->fetch_array($resql);
1482 $basedir = $liste['data_directory'];
1483 $fullpathofdump = preg_replace('/data$/', 'bin', $basedir).'/'.$tool;
1484 }
1485 }
1486
1487 return $fullpathofdump;
1488 }
1489
1496 public function getServerParametersValues($filter = '')
1497 {
1498 $result = array();
1499
1500 $resql = 'select name,setting from pg_settings';
1501 if ($filter) {
1502 $resql .= " WHERE name = '".$this->escape($filter)."'";
1503 }
1504 $resql = $this->query($resql);
1505 if ($resql) {
1506 while ($obj = $this->fetch_object($resql)) {
1507 $result[$obj->name] = $obj->setting;
1508 }
1509 }
1510
1511 return $result;
1512 }
1513
1520 public function getServerStatusValues($filter = '')
1521 {
1522 /* This is to return current running requests.
1523 $sql='SELECT datname,procpid,current_query FROM pg_stat_activity ORDER BY procpid';
1524 if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1525 $resql=$this->query($sql);
1526 if ($resql)
1527 {
1528 $obj=$this->fetch_object($resql);
1529 $result[$obj->Variable_name]=$obj->Value;
1530 }
1531 */
1532
1533 return array();
1534 }
1535
1542 public function getNextAutoIncrementId($table)
1543 {
1544 return $this->last_insert_id($table, 'rowid') + 1;
1545 }
1546
1547
1554 public function prepare($sql)
1555 {
1556 $stmtname = 'dolipgstmt_' . bin2hex(random_bytes(8)); // Generate a unique identifier for the statement
1557
1558 $result = pg_prepare($this->db, $stmtname, $sql);
1559 if (!$result) {
1560 $this->lasterror = pg_last_error($this->db);
1561 return false;
1562 }
1563
1564 return $stmtname; // We just return the name of the prepared statement
1565 }
1566}
Class to manage Dolibarr database access.
lastqueryerror()
Return last query in error.
lasterror()
Return last error label.
lasterrno()
Return last error code.
lastquery()
Return last request executed with query()
sanitize($stringtosanitize, $allowsimplequote=0, $allowsequals=0, $allowsspace=0, $allowschars=1)
Sanitize a string for SQL forging.
Class to drive a PostgreSQL database for Dolibarr.
errno()
Renvoie le code erreur generique de l'operation precedente.
DDLListTablesFull($database, $table='')
List tables into a database.
DDLGetConnectId()
Return connection ID.
num_rows($resultset)
Return number of lines for result of a SELECT.
const VERSIONMIN
Version min database.
__construct($type, $host, $user, $pass, $name='', $port=0)
Constructor.
DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
Create a user to connect to database.
DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys=null, $fulltext_keys=null, $keys=null)
Create a table into database.
getNextAutoIncrementId($table)
Get the last ID of an auto-increment field of a table.
DDLDropTable($table)
Drop a table into database.
DDLUpdateField($table, $field_name, $field_desc)
Update format of a field into a table.
getPathOfDump()
Return full path of dump program.
select_db($database)
Select a database PostgreSQL does not have an equivalent for mysql_select_db Only compare if the chos...
getServerStatusValues($filter='')
Return value of server status.
plimit($limit=0, $offset=0)
Define limits and offset of request.
decrypt($value)
Decrypt sensitive data in database.
error()
Renvoie le texte de l'erreur pgsql de l'operation precedente.
escape($stringtoencode)
Escape a string to insert data.
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Convert request to PostgreSQL syntax, execute it and return the resultset.
fetch_object($resultset)
Returns the current line (as an object) for the resultset cursor.
close()
Close database connection.
encrypt($fieldorvalue, $withQuotes=1)
Encrypt sensitive data in database Warning: This function includes the escape and add the SQL simple ...
getListOfCharacterSet()
Return list of available charset that can be used to store data in database.
fetch_array($resultset)
Return data as an array.
getPathOfRestore()
Return full path of restore program.
DDLAddField($table, $field_name, $field_desc, $field_position="")
Create a new field into table.
$type
Database type.
DDLInfoTable($table)
List information of columns in a table.
connect($host, $login, $passwd, $name, $port=0)
Connection to server.
getVersion()
Return version of database server.
$forcecharset
Charset.
escapeforlike($stringtoencode)
Escape a string to insert data into a like.
last_insert_id($table, $fieldid='rowid')
Get last ID after an insert INSERT.
affected_rows($resultset)
Return the number of rows in the result of a request INSERT, DELETE or UPDATE.
DDLDropField($table, $field_name)
Drop a field from table.
regexpsql($subject, $pattern, $sqlstring=0)
Format a SQL REGEXP.
DDLCreateDb($database, $charset='', $collation='', $owner='')
Create a new database Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated We fo...
const LABEL
Database label.
getListOfCollation()
Return list of available collation that can be used for database.
getDriverInfo()
Return version of database client driver.
free($resultset=null)
Free the last pointer resultset used by this connection.
DDLDescTable($table, $field="")
Return a pointer of line with description of a table or field.
ifsql($test, $resok, $resko)
Format a SQL IF.
getDefaultCollationDatabase()
Return collation used in database.
convertSQLFromMysql($line, $type='auto', $unescapeslashquot=false)
Convert a SQL request in Mysql syntax to native syntax.
getDefaultCharacterSetDatabase()
Return charset used to store data in database.
$forcecollate
Collation used to force collate when creating database.
fetch_row($resultset)
Return datas as an array.
getServerParametersValues($filter='')
Return value of server parameters.
prepare($sql)
Prepare a SQL statement for execution (PostgreSQL prepared statement)
DDLListTables($database, $table='')
List tables into a database.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.