dolibarr 23.0.4
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-2025 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
66 private $_results;
67
68
69
81 public function __construct($type, $host, $user, $pass, $name = '', $port = 0)
82 {
83 global $conf, $langs;
84
85 // Note that having "static" property for "$forcecharset" and "$forcecollate" will make error here in strict mode, so they are not static
86 if (!empty($conf->db->character_set)) {
87 $this->forcecharset = $conf->db->character_set;
88 }
89 if (!empty($conf->db->dolibarr_main_db_collation)) {
90 $this->forcecollate = $conf->db->dolibarr_main_db_collation;
91 }
92
93 $this->database_user = $user;
94 $this->database_host = $host;
95 $this->database_port = $port;
96
97 $this->transaction_opened = 0;
98
99 //print "Name DB: $host,$user,$pass,$name<br>";
100
101 if (!function_exists("pg_connect")) {
102 $this->connected = false;
103 $this->ok = false;
104 $this->error = "Pgsql PHP functions are not available in this version of PHP";
105 dol_syslog(get_class($this)."::DoliDBPgsql : Pgsql PHP functions are not available in this version of PHP", LOG_ERR);
106 return;
107 }
108
109 if (!$host) {
110 $this->connected = false;
111 $this->ok = false;
112 $this->error = $langs->trans("ErrorWrongHostParameter");
113 dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Connect, wrong host parameters", LOG_ERR);
114 return;
115 }
116
117 // Essai connection serveur
118 //print "$host, $user, $pass, $name, $port";
119 $this->db = $this->connect($host, $user, $pass, $name, $port);
120
121 if ($this->db) {
122 $this->connected = true;
123 $this->ok = true;
124 } else {
125 // host, login ou password incorrect
126 $this->connected = false;
127 $this->ok = false;
128 $this->error = 'Host, login or password incorrect';
129 dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Connect ".$this->error.'. Failed to connect to host='.$host.' port='.$port.' user='.$user, LOG_ERR);
130 }
131
132 // If server connection serveur ok and DB connection is requested, try to connect to DB
133 if ($this->connected && $name) {
134 if ($this->select_db($name)) {
135 $this->database_selected = true;
136 $this->database_name = $name;
137 $this->ok = true;
138 } else {
139 $this->database_selected = false;
140 $this->database_name = '';
141 $this->ok = false;
142 $this->error = $this->error();
143 dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Select_db ".$this->error, LOG_ERR);
144 }
145 } else {
146 // Pas de selection de base demandee, ok ou ko
147 $this->database_selected = false;
148 }
149 }
150
151
160 public function convertSQLFromMysql($line, $type = 'auto', $unescapeslashquot = false)
161 {
162 global $conf;
163
164 // Removed empty line if this is a comment line for SVN tagging
165 if (preg_match('/^--\s\$Id/i', $line)) {
166 return '';
167 }
168 // Return line if this is a comment
169 if (preg_match('/^#/i', $line) || preg_match('/^$/i', $line) || preg_match('/^--/i', $line)) {
170 return $line;
171 }
172 if ($line != "") {
173 // group_concat support (PgSQL >= 9.0)
174 // Replace group_concat(x) or group_concat(x SEPARATOR ',') with string_agg(x, ',')
175 $line = preg_replace('/GROUP_CONCAT/i', 'STRING_AGG', $line);
176 $line = preg_replace('/ SEPARATOR/i', ',', $line);
177 $line = preg_replace('/STRING_AGG\‍(([^,\‍)]+)\‍)/i', 'STRING_AGG(\\1, \',\')', $line);
178 $line = preg_replace('/STRING_AGG\‍(([^,]+),([^\‍)]+)\‍)/i', 'STRING_AGG(\\1::TEXT,\\2::TEXT)', $line);
179 //print $line."\n";
180
181 if ($type == 'auto') {
182 if (preg_match('/ALTER TABLE/i', $line)) {
183 $type = 'dml';
184 } elseif (preg_match('/CREATE TABLE/i', $line)) {
185 $type = 'dml';
186 } elseif (preg_match('/DROP TABLE/i', $line)) {
187 $type = 'dml';
188 }
189 }
190
191 $line = preg_replace('/ as signed\‍)/i', ' as integer)', $line);
192
193 if ($type == 'dml') {
194 $reg = array();
195
196 $line = preg_replace('/\s/', ' ', $line); // Replace tabulation with space
197
198 // we are inside create table statement so let's process datatypes
199 if (preg_match('/(ISAM|innodb)/i', $line)) { // end of create table sequence
200 $line = preg_replace('/\‍)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb).*;/i', ');', $line);
201 $line = preg_replace('/\‍)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb).*;/i', ');', $line);
202 $line = preg_replace('/,$/', '', $line);
203 }
204
205 // Process case: "CREATE TABLE llx_mytable(rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY,code..."
206 if (preg_match('/[\s\t\‍(]*(\w*)[\s\t]+int.*auto_increment/i', $line, $reg)) {
207 $newline = preg_replace('/([\s\t\‍(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i', '\\1 \\2 SERIAL PRIMARY KEY', $line);
208 //$line = "-- ".$line." replaced by --\n".$newline;
209 $line = $newline;
210 }
211
212 if (preg_match('/[\s\t\‍(]*(\w*)[\s\t]+bigint.*auto_increment/i', $line, $reg)) {
213 $newline = preg_replace('/([\s\t\‍(]*)([a-zA-Z_0-9]*)[\s\t]+bigint.*auto_increment[^,]*/i', '\\1 \\2 BIGSERIAL PRIMARY KEY', $line);
214 //$line = "-- ".$line." replaced by --\n".$newline;
215 $line = $newline;
216 }
217
218 // tinyint type conversion
219 $line = preg_replace('/tinyint\‍(?[0-9]*\‍)?/', 'smallint', $line);
220 $line = preg_replace('/tinyint/i', 'smallint', $line);
221
222 // nuke unsigned
223 $line = preg_replace('/(int\w+|smallint|bigint)\s+unsigned/i', '\\1', $line);
224
225 // blob -> text
226 $line = preg_replace('/\w*blob/i', 'text', $line);
227
228 // tinytext/mediumtext -> text
229 $line = preg_replace('/tinytext/i', 'text', $line);
230 $line = preg_replace('/mediumtext/i', 'text', $line);
231 $line = preg_replace('/longtext/i', 'text', $line);
232
233 $line = preg_replace('/text\‍([0-9]+\‍)/i', 'text', $line);
234
235 // change not null datetime field to null valid ones
236 // (to support remapping of "zero time" to null
237 $line = preg_replace('/datetime not null/i', 'datetime', $line);
238 $line = preg_replace('/datetime/i', 'timestamp', $line);
239
240 // double -> numeric
241 $line = preg_replace('/^double/i', 'numeric', $line);
242 $line = preg_replace('/(\s*)double/i', '\\1numeric', $line);
243 // float -> numeric
244 $line = preg_replace('/^float/i', 'numeric', $line);
245 $line = preg_replace('/(\s*)float/i', '\\1numeric', $line);
246
247 //Check tms timestamp field case (in Mysql this field is defaulted to now and
248 // on update defaulted by now
249 $line = preg_replace('/(\s*)tms(\s*)timestamp/i', '\\1tms timestamp without time zone DEFAULT now() NOT NULL', $line);
250
251 // nuke DEFAULT CURRENT_TIMESTAMP
252 $line = preg_replace('/(\s*)DEFAULT(\s*)CURRENT_TIMESTAMP/i', '\\1', $line);
253
254 // nuke ON UPDATE CURRENT_TIMESTAMP
255 $line = preg_replace('/(\s*)ON(\s*)UPDATE(\s*)CURRENT_TIMESTAMP/i', '\\1', $line);
256
257 // unique index(field1,field2)
258 if (preg_match('/unique index\s*\‍((\w+\s*,\s*\w+)\‍)/i', $line)) {
259 $line = preg_replace('/unique index\s*\‍((\w+\s*,\s*\w+)\‍)/i', 'UNIQUE\‍(\\1\‍)', $line);
260 }
261
262 // We remove end of requests "AFTER fieldxxx"
263 $line = preg_replace('/\sAFTER [a-z0-9_]+/i', '', $line);
264
265 // We remove start of requests "ALTER TABLE tablexxx" if this is a DROP INDEX
266 $line = preg_replace('/ALTER TABLE [a-z0-9_]+\s+DROP INDEX/i', 'DROP INDEX', $line);
267
268 // Translate order to rename fields
269 if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i', $line, $reg)) {
270 $line = "-- ".$line." replaced by --\n";
271 $line .= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
272 }
273
274 // Translate order to modify field format
275 if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i', $line, $reg)) {
276 $line = "-- ".$line." replaced by --\n";
277 $newreg3 = $reg[3];
278 $newreg3 = preg_replace('/ DEFAULT NULL/i', '', $newreg3);
279 $newreg3 = preg_replace('/ NOT NULL/i', '', $newreg3);
280 $newreg3 = preg_replace('/ NULL/i', '', $newreg3);
281 $newreg3 = preg_replace('/ DEFAULT 0/i', '', $newreg3);
282 $newreg3 = preg_replace('/ DEFAULT \'?[0-9a-zA-Z_@]*\'?/i', '', $newreg3);
283 $line .= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3;
284 // TODO Add alter to set default value or null/not null if there is this in $reg[3]
285 }
286
287 // alter table add primary key (field1, field2 ...) -> We remove the primary key name not accepted by PostGreSQL
288 // ALTER TABLE llx_dolibarr_modules ADD PRIMARY KEY pk_dolibarr_modules (numero, entity)
289 if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\‍((.*)$/i', $line, $reg)) {
290 $line = "-- ".$line." replaced by --\n";
291 $line .= "ALTER TABLE ".$reg[1]." ADD PRIMARY KEY (".$reg[3];
292 }
293
294 // Translate order to drop primary keys
295 // ALTER TABLE llx_dolibarr_modules DROP PRIMARY KEY pk_xxx
296 if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+PRIMARY\s+KEY\s*([^;]+)$/i', $line, $reg)) {
297 $line = "-- ".$line." replaced by --\n";
298 $line .= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
299 }
300
301 // Translate order to drop foreign keys
302 // ALTER TABLE llx_dolibarr_modules DROP FOREIGN KEY fk_xxx
303 if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i', $line, $reg)) {
304 $line = "-- ".$line." replaced by --\n";
305 $line .= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
306 }
307
308 // Translate order to add foreign keys
309 // ALTER TABLE llx_tablechild ADD CONSTRAINT fk_tablechild_fk_fieldparent FOREIGN KEY (fk_fieldparent) REFERENCES llx_tableparent (rowid)
310 if (preg_match('/ALTER\s+TABLE\s+(.*)\s*ADD CONSTRAINT\s+(.*)\s*FOREIGN\s+KEY\s*(.*)$/i', $line, $reg)) {
311 $line = preg_replace('/;$/', '', $line);
312 $line .= " DEFERRABLE INITIALLY IMMEDIATE;";
313 }
314
315 // alter table add [unique] [index] (field1, field2 ...)
316 // ALTER TABLE llx_accountingaccount ADD INDEX idx_accountingaccount_fk_pcg_version (fk_pcg_version)
317 if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\‍(([\w,\s]+)\‍)/i', $line, $reg)) {
318 $fieldlist = $reg[4];
319 $idxname = $reg[3];
320 $tablename = $reg[1];
321 $line = "-- ".$line." replaced by --\n";
322 $line .= "CREATE ".(preg_match('/UNIQUE/', $reg[2]) ? 'UNIQUE ' : '')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")";
323 }
324 }
325
326 // To have PostgreSQL case sensitive
327 $count_like = 0;
328 $line = str_replace(" LIKE '", " ILIKE '", $line, $count_like);
329 if (getDolGlobalString('PSQL_USE_UNACCENT') && $count_like > 0) {
330 // @see https://docs.PostgreSQL.fr/11/unaccent.html : 'unaccent()' function must be installed before
331 $line = preg_replace('/\s+(\‍(+\s*)([a-zA-Z0-9\-\_\.]+) ILIKE /', ' \1unaccent(\2) ILIKE ', $line);
332 }
333
334 $line = str_replace(" LIKE BINARY '", " LIKE '", $line);
335
336 // Replace INSERT IGNORE into INSERT
337 $line = preg_replace('/^INSERT IGNORE/', 'INSERT', $line);
338
339 // Delete using criteria on other table must not declare twice the deleted table
340 // DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable
341 if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', $line, $reg)) {
342 if ($reg[1] == $reg[2]) { // If same table, we remove second one
343 $line = preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', 'DELETE FROM \\1 USING \\3', $line);
344 }
345 }
346
347 // Remove () in the tables in FROM if 1 table
348 $line = preg_replace('/FROM\s*\‍((([a-z_]+)\s+as\s+([a-z_]+)\s*)\‍)/i', 'FROM \\1', $line);
349 //print $line."\n";
350
351 // Remove () in the tables in FROM if 2 table
352 $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);
353 //print $line."\n";
354
355 // Remove () in the tables in FROM if 3 table
356 $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);
357 //print $line."\n";
358
359 // Remove () in the tables in FROM if 4 table
360 $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);
361 //print $line."\n";
362
363 // Remove () in the tables in FROM if 5 table
364 $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);
365 //print $line."\n";
366
367 // Replace spacing ' with ''.
368 // By default we do not (should be already done by db->escape function if required
369 // except for sql insert in data file that are mysql escaped so we removed them to
370 // be compatible with standard_conforming_strings=on that considers \ as ordinary character).
371 if ($unescapeslashquot) {
372 $line = preg_replace("/\\\'/", "''", $line);
373 }
374
375 //print "type=".$type." newline=".$line."<br>\n";
376 }
377
378 return $line;
379 }
380
381 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
390 public function select_db($database)
391 {
392 // phpcs:enable
393 if ($database == $this->database_name) {
394 return true;
395 } else {
396 return false;
397 }
398 }
399
411 public function connect($host, $login, $passwd, $name, $port = 0)
412 {
413 // use pg_pconnect() instead of pg_connect() if you want to use persistent connection costing 1ms, instead of 30ms for non persistent
414
415 $this->db = false;
416
417 // connections parameters must be protected (only \ and ' according to pg_connect() manual)
418 $host = str_replace(array("\\", "'"), array("\\\\", "\\'"), $host);
419 $login = str_replace(array("\\", "'"), array("\\\\", "\\'"), $login);
420 $passwd = str_replace(array("\\", "'"), array("\\\\", "\\'"), $passwd);
421 $name = str_replace(array("\\", "'"), array("\\\\", "\\'"), $name);
422 $port = str_replace(array("\\", "'"), array("\\\\", "\\'"), (string) $port);
423
424 if (!$name) {
425 $name = "postgres"; // When try to connect using admin user
426 }
427
428 // try first Unix domain socket (local)
429 if ((!empty($host) && $host == "socket") && !defined('NOLOCALSOCKETPGCONNECT')) {
430 $con_string = "dbname='".$name."' user='".$login."' password='".$passwd."'"; // $name may be empty
431 try {
432 // PGSQL_CONNECT_FORCE_NEW is required: pg_connect() otherwise returns the connection already
433 // opened for the same connection string, so a second handle would share the main one and
434 // closing it would close the connection still in use by the caller.
435 $this->db = @pg_connect($con_string, PGSQL_CONNECT_FORCE_NEW);
436 } catch (Exception $e) {
437 // No message
438 }
439 }
440
441 // if local connection failed or not requested, use TCP/IP
442 if (empty($this->db)) {
443 if (!$host) {
444 $host = "localhost";
445 }
446 if (!$port) {
447 $port = 5432;
448 }
449
450 $con_string = "host='".$host."' port='".$port."' dbname='".$name."' user='".$login."' password='".$passwd."'";
451 try {
452 $this->db = @pg_connect($con_string, PGSQL_CONNECT_FORCE_NEW);
453 } catch (Exception $e) {
454 print $e->getMessage();
455 }
456 }
457
458 // now we test if at least one connect method was a success
459 if ($this->db) {
460 $this->database_name = $name;
461 pg_set_error_verbosity($this->db, PGSQL_ERRORS_VERBOSE); // Set verbosity to max
462 pg_query($this->db, "set datestyle = 'ISO, YMD';");
463 }
464
465 return $this->db;
466 }
467
473 public function getVersion()
474 {
475 $resql = $this->query('SHOW server_version');
476 if ($resql) {
477 $liste = $this->fetch_array($resql);
478 return $liste['server_version'];
479 }
480 return '';
481 }
482
488 public function getDriverInfo()
489 {
490 return 'pgsql php driver';
491 }
492
499 public function close()
500 {
501 if ($this->db) {
502 if ($this->transaction_opened > 0) {
503 dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened, LOG_ERR);
504 }
505 $this->connected = false;
506 return pg_close($this->db);
507 }
508 return false;
509 }
510
520 public function query($query, $usesavepoint = 0, $type = 'auto', $result_mode = 0)
521 {
522 global $dolibarr_main_db_readonly;
523
524 $query = trim($query);
525
526 // Convert MySQL syntax to PostgreSQL syntax
527 $query = $this->convertSQLFromMysql($query, $type, ($this->unescapeslashquot && $this->standard_conforming_strings));
528 //print "After convertSQLFromMysql:\n".$query."<br>\n";
529
530 if (getDolGlobalString('MAIN_DB_AUTOFIX_BAD_SQL_REQUEST')) {
531 // Fix bad formed requests. If request contains a date without quotes, we fix this but this should not occurs.
532 $loop = true;
533 while ($loop) {
534 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)) {
535 $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);
536 dol_syslog("Warning: Bad formed request converted into ".$query, LOG_WARNING);
537 } else {
538 $loop = false;
539 }
540 }
541 }
542
543 if ($usesavepoint && $this->transaction_opened) {
544 @pg_query($this->db, 'SAVEPOINT mysavepoint');
545 }
546
547 if (!in_array($query, array('BEGIN', 'COMMIT', 'ROLLBACK'))) {
548 $SYSLOG_SQL_LIMIT = 10000; // limit log to 10kb per line to limit DOS attacks
549 dol_syslog('sql='.substr($query, 0, $SYSLOG_SQL_LIMIT), LOG_DEBUG);
550 }
551 if (empty($query)) {
552 return false; // Return false = error if empty request
553 }
554
555 if (!empty($dolibarr_main_db_readonly)) {
556 if (preg_match('/^(INSERT|UPDATE|REPLACE|DELETE|CREATE|ALTER|TRUNCATE|DROP)/i', $query)) {
557 $this->lasterror = 'Application in read-only mode';
558 $this->lasterrno = 'APPREADONLY';
559 $this->lastquery = $query;
560 return false;
561 }
562 }
563
564 $ret = @pg_query($this->db, $query);
565
566 //print $query;
567 if (!preg_match("/^COMMIT/i", $query) && !preg_match("/^ROLLBACK/i", $query)) { // Si requete utilisateur, on la sauvegarde ainsi que son resultset
568 if (!$ret) {
569 if ($this->errno() != 'DB_ERROR_25P02') { // Do not overwrite errors if this is a consecutive error
570 $this->lastqueryerror = $query;
571 $this->lasterror = $this->error();
572 $this->lasterrno = $this->errno();
573
574 if (getDolGlobalInt('SYSLOG_LEVEL') < LOG_DEBUG) {
575 dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR); // Log of request was not yet done previously
576 }
577 dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterror." (".$this->lasterrno.")", LOG_ERR);
578 dol_syslog(get_class($this)."::query SQL Error usesavepoint = ".$usesavepoint, LOG_ERR);
579 }
580
581 if ($usesavepoint && $this->transaction_opened) { // Warning, after that errno will be erased
582 @pg_query($this->db, 'ROLLBACK TO SAVEPOINT mysavepoint');
583 }
584 }
585 $this->lastquery = $query;
586 $this->_results = $ret;
587 }
588
589 return $ret;
590 }
591
592 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
599 public function fetch_object($resultset)
600 {
601 // phpcs:enable
602 // If resultset not provided, we take the last used by connection
603 if (!is_resource($resultset) && !is_object($resultset)) {
604 $resultset = $this->_results;
605 }
606 return pg_fetch_object($resultset);
607 }
608
609 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
616 public function fetch_array($resultset)
617 {
618 // phpcs:enable
619 // If resultset not provided, we take the last used by connection
620 if (!is_resource($resultset) && !is_object($resultset)) {
621 $resultset = $this->_results;
622 }
623 return pg_fetch_array($resultset);
624 }
625
626 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
633 public function fetch_row($resultset)
634 {
635 // phpcs:enable
636 // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connection
637 if (!is_resource($resultset) && !is_object($resultset)) {
638 $resultset = $this->_results;
639 }
640 return pg_fetch_row($resultset); // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal
641 }
642
643 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
651 public function num_rows($resultset)
652 {
653 // phpcs:enable
654 // If resultset not provided, we take the last used by connection
655 if (!is_resource($resultset) && !is_object($resultset)) {
656 $resultset = $this->_results;
657 }
658 // avoid error if $resultset = null or false
659 if ($resultset) {
660 return pg_num_rows($resultset);
661 } else {
662 return 0;
663 } // end of avoid error
664 }
665
666 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
674 public function affected_rows($resultset)
675 {
676 // phpcs:enable
677 // If resultset not provided, we take the last used by connection
678 if (!is_resource($resultset) && !is_object($resultset)) {
679 $resultset = $this->_results;
680 }
681 // pgsql necessite un resultset pour cette fonction contrairement
682 // a mysql qui prend un link de base
683 return pg_affected_rows($resultset);
684 }
685
686
693 public function free($resultset = null)
694 {
695 // If resultset not provided, we take the last used by connection
696 if (!is_resource($resultset) && !is_object($resultset)) {
697 $resultset = $this->_results;
698 }
699 // Si resultset en est un, on libere la memoire
700 if (is_resource($resultset) || is_object($resultset)) {
701 pg_free_result($resultset);
702 }
703 }
704
705
713 public function plimit($limit = 0, $offset = 0)
714 {
715 global $conf;
716 if (empty($limit)) {
717 return "";
718 }
719 if ($limit < 0) {
720 $limit = $conf->liste_limit;
721 }
722 if ($offset > 0) {
723 return " LIMIT ".$limit." OFFSET ".$offset." ";
724 } else {
725 return " LIMIT $limit ";
726 }
727 }
728
729
736 public function escape($stringtoencode)
737 {
738 return pg_escape_string($this->db, $stringtoencode);
739 }
740
747 public function escapeforlike($stringtoencode)
748 {
749 return str_replace(array('\\', '_', '%'), array('\\\\', '\_', '\%'), (string) $stringtoencode);
750 }
751
760 public function ifsql($test, $resok, $resko)
761 {
762 return '(CASE WHEN '.$test.' THEN '.$resok.' ELSE '.$resko.' END)';
763 }
764
773 public function regexpsql($subject, $pattern, $sqlstring = 0)
774 {
775 if ($sqlstring) {
776 return "(". $subject ." ~ '" . $this->escape($pattern) . "')";
777 }
778
779 return "('". $this->escape($subject) ."' ~ '" . $this->escape($pattern) . "')";
780 }
781
782
788 public function errno()
789 {
790 if (!$this->connected) {
791 // Si il y a eu echec de connection, $this->db n'est pas valide.
792 return 'DB_ERROR_FAILED_TO_CONNECT';
793 } else {
794 // Constants to convert error code to a generic Dolibarr error code
795 $errorcode_map = array(
796 1004 => 'DB_ERROR_CANNOT_CREATE',
797 1005 => 'DB_ERROR_CANNOT_CREATE',
798 1006 => 'DB_ERROR_CANNOT_CREATE',
799 1007 => 'DB_ERROR_ALREADY_EXISTS',
800 1008 => 'DB_ERROR_CANNOT_DROP',
801 1025 => 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
802 1044 => 'DB_ERROR_ACCESSDENIED',
803 1046 => 'DB_ERROR_NODBSELECTED',
804 1048 => 'DB_ERROR_CONSTRAINT',
805 '42P07' => 'DB_ERROR_TABLE_OR_KEY_ALREADY_EXISTS',
806 '42703' => 'DB_ERROR_NOSUCHFIELD',
807 1060 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
808 42701 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
809 '42710' => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
810 '23505' => 'DB_ERROR_RECORD_ALREADY_EXISTS',
811 '42704' => 'DB_ERROR_NO_INDEX_TO_DROP', // May also be Type xxx does not exists
812 '42601' => 'DB_ERROR_SYNTAX',
813 '42P16' => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
814 1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
815 1091 => 'DB_ERROR_NOSUCHFIELD',
816 1100 => 'DB_ERROR_NOT_LOCKED',
817 1136 => 'DB_ERROR_VALUE_COUNT_ON_ROW',
818 '42P01' => 'DB_ERROR_NOSUCHTABLE',
819 '23503' => 'DB_ERROR_NO_PARENT',
820 1217 => 'DB_ERROR_CHILD_EXISTS',
821 1451 => 'DB_ERROR_CHILD_EXISTS',
822 '42P04' => 'DB_DATABASE_ALREADY_EXISTS'
823 );
824
825 $errorlabel = pg_last_error($this->db);
826 $errorcode = '';
827 $reg = array();
828 if (preg_match('/: *([0-9P]+):/', $errorlabel, $reg)) {
829 $errorcode = $reg[1];
830 if (isset($errorcode_map[$errorcode])) {
831 return $errorcode_map[$errorcode];
832 }
833 }
834 $errno = $errorcode ? $errorcode : $errorlabel;
835 return ($errno ? 'DB_ERROR_'.$errno : '0');
836 }
837 // '/(Table does not exist\.|Relation [\"\'].*[\"\'] does not exist|sequence does not exist|class ".+" not found)$/' => 'DB_ERROR_NOSUCHTABLE',
838 // '/table [\"\'].*[\"\'] does not exist/' => 'DB_ERROR_NOSUCHTABLE',
839 // '/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*/' => 'DB_ERROR_RECORD_ALREADY_EXISTS',
840 // '/divide by zero$/' => 'DB_ERROR_DIVZERO',
841 // '/pg_atoi: error in .*: can\'t parse /' => 'DB_ERROR_INVALID_NUMBER',
842 // '/ttribute [\"\'].*[\"\'] not found$|Relation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/' => 'DB_ERROR_NOSUCHFIELD',
843 // '/parser: parse error at or near \"/' => 'DB_ERROR_SYNTAX',
844 // '/referential integrity violation/' => 'DB_ERROR_CONSTRAINT'
845 }
846
852 public function error()
853 {
854 return pg_last_error($this->db);
855 }
856
857 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
865 public function last_insert_id($table, $fieldid = 'rowid')
866 {
867 // phpcs:enable
868 $sequencename = $table."_".$fieldid."_seq";
869
870 //$result = pg_query($this->db,"SELECT MAX(".$fieldid.") FROM ".$table);
871 $result = pg_query($this->db, "SELECT currval('".$sequencename."')");
872 if (!$result) {
873 print pg_last_error($this->db);
874 return -1;
875 }
876 //$nbre = pg_num_rows($result);
877 $row = pg_fetch_result($result, 0, 0);
878 return (int) $row;
879 }
880
889 public function encrypt($fieldorvalue, $withQuotes = 1)
890 {
891 //global $conf;
892
893 // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
894 //$cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
895
896 //Encryption key
897 //$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
898
899 $return = $fieldorvalue;
900 return ($withQuotes ? "'" : "").$this->escape($return).($withQuotes ? "'" : "");
901 }
902
903
910 public function decrypt($value)
911 {
912 //global $conf;
913
914 // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
915 //$cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
916
917 //Encryption key
918 //$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
919
920 $return = $value;
921 return $return;
922 }
923
924
925 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
931 public function DDLGetConnectId()
932 {
933 // phpcs:enable
934 return '?';
935 }
936
937
938
939 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
951 public function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
952 {
953 // phpcs:enable
954 if (empty($charset)) {
955 $charset = $this->forcecharset;
956 }
957 if (empty($collation)) {
958 $collation = $this->forcecollate;
959 }
960
961 // Test charset match LC_TYPE (pgsql error otherwise)
962 //print $charset.' '.setlocale(LC_CTYPE,'0'); exit;
963
964 // NOTE: Do not use ' around the database name
965 $sql = "CREATE DATABASE ".$this->escape($database)." OWNER '".$this->escape($owner)."' ENCODING '".$this->escape((string) $charset)."'";
966
967 dol_syslog($sql, LOG_DEBUG);
968 $ret = $this->query($sql);
969
970 return $ret;
971 }
972
973 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
981 public function DDLListTables($database, $table = '')
982 {
983 // phpcs:enable
984 $listtables = array();
985
986 $escapedlike = '';
987 if ($table) {
988 $tmptable = preg_replace('/[^a-z0-9\.\-\_%]/i', '', $table);
989
990 $escapedlike = " AND table_name LIKE '".$this->escape($tmptable)."'";
991 }
992 $result = pg_query($this->db, "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'".$escapedlike." ORDER BY table_name");
993 if ($result) {
994 while ($row = $this->fetch_row($result)) { // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal
995 $listtables[] = $row[0];
996 }
997 }
998 return $listtables;
999 }
1000
1001 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1009 public function DDLListTablesFull($database, $table = '')
1010 {
1011 // phpcs:enable
1012 $listtables = array();
1013
1014 $escapedlike = '';
1015 if ($table) {
1016 $tmptable = preg_replace('/[^a-z0-9\.\-\_%]/i', '', $table);
1017
1018 $escapedlike = " AND table_name LIKE '".$this->escape($tmptable)."'";
1019 }
1020 $result = pg_query($this->db, "SELECT table_name, table_type FROM information_schema.tables WHERE table_schema = 'public'".$escapedlike." ORDER BY table_name");
1021 if ($result) {
1022 while ($row = $this->fetch_row($result)) { // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal
1023 $listtables[] = $row;
1024 }
1025 }
1026 return $listtables;
1027 }
1028
1029 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1036 public function DDLInfoTable($table)
1037 {
1038 // phpcs:enable
1039 $infotables = array();
1040
1041 $sql = "SELECT ";
1042 $sql .= " infcol.column_name as \"Column\","; // pgsql need " for alias names !
1043 $sql .= " CASE WHEN infcol.character_maximum_length IS NOT NULL THEN infcol.udt_name || '('||infcol.character_maximum_length||')'";
1044 $sql .= " ELSE infcol.udt_name";
1045 $sql .= " END as \"Type\","; // pgsql need " for alias names !
1046 $sql .= " infcol.collation_name as \"Collation\","; // pgsql need " for alias names !
1047 $sql .= " infcol.is_nullable as \"Null\","; // pgsql need " for alias names !
1048 $sql .= " '' as \"Key\","; // pgsql need " for alias names !
1049 $sql .= " infcol.column_default as \"Default\","; // pgsql need " for alias names !
1050 $sql .= " '' as \"Extra\","; // pgsql need " for alias names !
1051 $sql .= " '' as \"Privileges\""; // pgsql need " for alias names !
1052 $sql .= " FROM information_schema.columns infcol";
1053 $sql .= " WHERE table_schema = 'public' ";
1054 $sql .= " AND table_name = '".$this->escape($table)."'";
1055 $sql .= " ORDER BY ordinal_position;";
1056
1057 $result = $this->query($sql);
1058 if ($result) {
1059 while ($row = $this->fetch_row($result)) {
1060 $infotables[] = $row;
1061 }
1062 }
1063 return $infotables;
1064 }
1065
1066
1067 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1080 public function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
1081 {
1082 // phpcs:enable
1083 // @TODO: $fulltext_keys parameter is unused
1084
1085 $sqlk = array();
1086 $sqluq = array();
1087
1088 // Keys found into the array $fields: type,value,attribute,null,default,extra
1089 // ex. : $fields['rowid'] = array(
1090 // 'type'=>'int' or 'integer',
1091 // 'value'=>'11',
1092 // 'null'=>'not null',
1093 // 'extra'=> 'auto_increment'
1094 // );
1095 $sql = "CREATE TABLE ".$this->sanitize($table)."(";
1096 $i = 0;
1097 $sqlfields = array();
1098 foreach ($fields as $field_name => $field_desc) {
1099 $sqlfields[$i] = $this->sanitize($field_name)." ";
1100 $sqlfields[$i] .= $this->sanitize($field_desc['type']);
1101 if (isset($field_desc['value']) && $field_desc['value'] !== '') {
1102 $sqlfields[$i] .= "(".$this->sanitize($field_desc['value']).")";
1103 }
1104 if (isset($field_desc['attribute']) && $field_desc['attribute'] !== '') {
1105 $sqlfields[$i] .= " ".$this->sanitize($field_desc['attribute']);
1106 }
1107 if (isset($field_desc['default']) && $field_desc['default'] !== '') {
1108 if (in_array($field_desc['type'], array('tinyint', 'smallint', 'int', 'double'))) {
1109 $sqlfields[$i] .= " DEFAULT ".((float) $field_desc['default']);
1110 } elseif ($field_desc['default'] == 'null' || $field_desc['default'] == 'CURRENT_TIMESTAMP') {
1111 $sqlfields[$i] .= " DEFAULT ".$this->sanitize($field_desc['default']);
1112 } else {
1113 $sqlfields[$i] .= " DEFAULT '".$this->escape($field_desc['default'])."'";
1114 }
1115 }
1116 if (isset($field_desc['null']) && $field_desc['null'] !== '') {
1117 $sqlfields[$i] .= " ".$this->sanitize($field_desc['null'], 0, 0, 1);
1118 }
1119 if (isset($field_desc['extra']) && $field_desc['extra'] !== '') {
1120 $sqlfields[$i] .= " ".$this->sanitize($field_desc['extra'], 0, 0, 1);
1121 }
1122 if (!empty($primary_key) && $primary_key == $field_name) {
1123 $sqlfields[$i] .= " AUTO_INCREMENT PRIMARY KEY"; // mysql instruction that will be converted by driver late
1124 }
1125 $i++;
1126 }
1127
1128 if (is_array($unique_keys)) {
1129 $i = 0;
1130 foreach ($unique_keys as $key => $value) {
1131 $sqluq[$i] = "UNIQUE KEY '".$this->sanitize($key)."' ('".$this->escape($value)."')";
1132 $i++;
1133 }
1134 }
1135 if (is_array($keys)) {
1136 $i = 0;
1137 foreach ($keys as $key => $value) {
1138 $sqlk[$i] = "KEY ".$this->sanitize($key)." (".$value.")";
1139 $i++;
1140 }
1141 }
1142 $sql .= implode(', ', $sqlfields);
1143 if ($unique_keys != "") {
1144 $sql .= ",".implode(',', $sqluq);
1145 }
1146 if (is_array($keys)) {
1147 $sql .= ",".implode(',', $sqlk);
1148 }
1149 $sql .= ")";
1150 //$sql .= " engine=".$this->sanitize($type);
1151
1152 if (!$this->query($sql, 1)) {
1153 return -1;
1154 } else {
1155 return 1;
1156 }
1157 }
1158
1159 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1166 public function DDLDropTable($table)
1167 {
1168 // phpcs:enable
1169 $tmptable = preg_replace('/[^a-z0-9\.\-\_]/i', '', $table);
1170
1171 $sql = "DROP TABLE ".$this->sanitize($tmptable);
1172
1173 if (!$this->query($sql, 1)) {
1174 return -1;
1175 } else {
1176 return 1;
1177 }
1178 }
1179
1180 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1188 public function DDLDescTable($table, $field = "")
1189 {
1190 // phpcs:enable
1191 $sql = "SELECT attname FROM pg_attribute, pg_type WHERE typname = '".$this->escape($table)."' AND attrelid = typrelid";
1192 $sql .= " AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', 'tableoid', 'xmin', 'xmax')";
1193 if ($field) {
1194 $sql .= " AND attname = '".$this->escape($field)."'";
1195 }
1196
1197 dol_syslog($sql, LOG_DEBUG);
1198 $this->_results = $this->query($sql);
1199 return $this->_results;
1200 }
1201
1202 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1212 public function DDLAddField($table, $field_name, $field_desc, $field_position = "")
1213 {
1214 // phpcs:enable
1215 // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
1216 // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
1217 $sql = "ALTER TABLE ".$this->sanitize($table)." ADD ".$this->sanitize($field_name)." ";
1218
1219 if ($field_desc['type'] !== 'datetimegmt') {
1220 $sql .= $this->sanitize($field_desc['type']);
1221 } else {
1222 $sql .= 'datetime';
1223 }
1224
1225 if (isset($field_desc['value']) && preg_match("/^[^\s]/i", $field_desc['value'])) {
1226 if (!in_array($field_desc['type'], array('tinyint', 'smallint', 'int', 'date', 'datetime', 'datetimegmt')) && $field_desc['value']) {
1227 $sql .= "(".$this->sanitize($field_desc['value']).")";
1228 }
1229 }
1230 if (isset($field_desc['attribute']) && preg_match("/^[^\s]/i", $field_desc['attribute'])) {
1231 $sql .= " ".$this->sanitize($field_desc['attribute']);
1232 }
1233 if (isset($field_desc['null']) && preg_match("/^[^\s]/i", $field_desc['null'])) {
1234 if ($field_desc['null'] == 'NOT NULL') {
1235 $sql .= " ".$this->sanitize($field_desc['null'], 0, 0, 1);
1236 } else {
1237 $sql .= " ".$this->sanitize($field_desc['null']);
1238 }
1239 }
1240 if (isset($field_desc['default']) && preg_match("/^[^\s]/i", $field_desc['default'])) {
1241 if (in_array($field_desc['type'], array('tinyint', 'smallint', 'int', 'double'))) {
1242 $sql .= " DEFAULT ".((float) $field_desc['default']);
1243 } elseif ($field_desc['default'] == 'null' || $field_desc['default'] == 'CURRENT_TIMESTAMP') {
1244 $sql .= " DEFAULT ".$this->sanitize($field_desc['default']);
1245 } else {
1246 $sql .= " DEFAULT '".$this->escape($field_desc['default'])."'";
1247 }
1248 }
1249 if (isset($field_desc['extra']) && preg_match("/^[^\s]/i", $field_desc['extra'])) {
1250 $sql .= " ".$this->sanitize($field_desc['extra'], 0, 0, 1);
1251 }
1252 $sql .= " ".$this->sanitize($field_position, 0, 0, 1);
1253
1254 dol_syslog($sql, LOG_DEBUG);
1255 if (!$this -> query($sql)) {
1256 return -1;
1257 }
1258 return 1;
1259 }
1260
1261 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1270 public function DDLUpdateField($table, $field_name, $field_desc)
1271 {
1272 // phpcs:enable
1273 $sql = "ALTER TABLE ".$this->sanitize($table);
1274 $sql .= " ALTER COLUMN ".$this->sanitize($field_name)." TYPE ";
1275
1276 if ($field_desc['type'] !== 'datetimegmt') {
1277 $sql .= $this->sanitize($field_desc['type']);
1278 } else {
1279 $sql .= 'datetime';
1280 }
1281
1282 if (isset($field_desc['value']) && preg_match("/^[^\s]/i", $field_desc['value'])) {
1283 if (!in_array($field_desc['type'], array('smallint', 'int', 'date', 'datetime', 'datetimegmt')) && $field_desc['value']) {
1284 $sql .= "(".$this->sanitize($field_desc['value']).")";
1285 }
1286 }
1287
1288 if (isset($field_desc['null']) && ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL')) {
1289 // 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
1290 if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text') {
1291 $sqlbis = "UPDATE ".$this->sanitize($table)." SET ".$this->escape($field_name)." = '".$this->escape(isset($field_desc['default']) ? $field_desc['default'] : '')."' WHERE ".$this->escape($field_name)." IS NULL";
1292 $this->query($sqlbis);
1293 } elseif (in_array($field_desc['type'], array('tinyint', 'smallint', 'int', 'double'))) {
1294 $sqlbis = "UPDATE ".$this->sanitize($table)." SET ".$this->escape($field_name)." = ".((float) $this->escape(isset($field_desc['default']) ? $field_desc['default'] : 0))." WHERE ".$this->escape($field_name)." IS NULL";
1295 $this->query($sqlbis);
1296 }
1297 }
1298
1299 if (isset($field_desc['default']) && $field_desc['default'] != '') {
1300 if (in_array($field_desc['type'], array('tinyint', 'smallint', 'int', 'double'))) {
1301 $sql .= ", ALTER COLUMN ".$this->sanitize($field_name)." SET DEFAULT ".((float) $field_desc['default']);
1302 } elseif ($field_desc['type'] != 'text') { // Default not supported on text fields ?
1303 $sql .= ", ALTER COLUMN ".$this->sanitize($field_name)." SET DEFAULT '".$this->escape($field_desc['default'])."'";
1304 }
1305 }
1306
1307 dol_syslog($sql, LOG_DEBUG);
1308 if (!$this->query($sql)) {
1309 return -1;
1310 }
1311 return 1;
1312 }
1313
1314 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1322 public function DDLDropField($table, $field_name)
1323 {
1324 // phpcs:enable
1325 $tmp_field_name = preg_replace('/[^a-z0-9\.\-\_]/i', '', $field_name);
1326
1327 $sql = "ALTER TABLE ".$this->sanitize($table)." DROP COLUMN ".$this->sanitize($tmp_field_name);
1328 if (!$this->query($sql)) {
1329 $this->error = $this->lasterror();
1330 return -1;
1331 }
1332 return 1;
1333 }
1334
1335 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1345 public function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
1346 {
1347 // phpcs:enable
1348 // Note: using ' on user does not works with pgsql
1349 $sql = "CREATE USER ".$this->sanitize($dolibarr_main_db_user)." with password '".$this->escape($dolibarr_main_db_pass)."'";
1350
1351 dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
1352 $resql = $this->query($sql);
1353 if (!$resql) {
1354 return -1;
1355 }
1356
1357 return 1;
1358 }
1359
1366 {
1367 $resql = $this->query('SHOW SERVER_ENCODING');
1368 if ($resql) {
1369 $liste = $this->fetch_array($resql);
1370 return $liste['server_encoding'];
1371 } else {
1372 return '';
1373 }
1374 }
1375
1381 public function getListOfCharacterSet()
1382 {
1383 $resql = $this->query('SHOW SERVER_ENCODING');
1384 $liste = array();
1385 if ($resql) {
1386 $i = 0;
1387 while ($obj = $this->fetch_object($resql)) {
1388 $liste[$i]['charset'] = $obj->server_encoding;
1389 $liste[$i]['description'] = 'Default database charset';
1390 $i++;
1391 }
1392 $this->free($resql);
1393 } else {
1394 return null;
1395 }
1396 return $liste;
1397 }
1398
1405 {
1406 $resql = $this->query('SHOW LC_COLLATE');
1407 if ($resql) {
1408 $liste = $this->fetch_array($resql);
1409 return $liste['lc_collate'];
1410 } else {
1411 return '';
1412 }
1413 }
1414
1420 public function getListOfCollation()
1421 {
1422 $resql = $this->query('SHOW LC_COLLATE');
1423 $liste = array();
1424 if ($resql) {
1425 $i = 0;
1426 while ($obj = $this->fetch_object($resql)) {
1427 $liste[$i]['collation'] = $obj->lc_collate;
1428 $i++;
1429 }
1430 $this->free($resql);
1431 } else {
1432 return null;
1433 }
1434 return $liste;
1435 }
1436
1442 public function getPathOfDump()
1443 {
1444 $fullpathofdump = '/pathtopgdump/pg_dump';
1445
1446 if (file_exists('/usr/bin/pg_dump')) {
1447 $fullpathofdump = '/usr/bin/pg_dump';
1448 } else {
1449 // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1450 $resql = $this->query('SHOW data_directory');
1451 if ($resql) {
1452 $liste = $this->fetch_array($resql);
1453 $basedir = $liste['data_directory'];
1454 $fullpathofdump = preg_replace('/data$/', 'bin', $basedir).'/pg_dump';
1455 }
1456 }
1457
1458 return $fullpathofdump;
1459 }
1460
1466 public function getPathOfRestore()
1467 {
1468 //$tool='pg_restore';
1469 $tool = 'psql';
1470
1471 $fullpathofdump = '/pathtopgrestore/'.$tool;
1472
1473 if (file_exists('/usr/bin/'.$tool)) {
1474 $fullpathofdump = '/usr/bin/'.$tool;
1475 } else {
1476 // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1477 $resql = $this->query('SHOW data_directory');
1478 if ($resql) {
1479 $liste = $this->fetch_array($resql);
1480 $basedir = $liste['data_directory'];
1481 $fullpathofdump = preg_replace('/data$/', 'bin', $basedir).'/'.$tool;
1482 }
1483 }
1484
1485 return $fullpathofdump;
1486 }
1487
1494 public function getServerParametersValues($filter = '')
1495 {
1496 $result = array();
1497
1498 $resql = 'select name,setting from pg_settings';
1499 if ($filter) {
1500 $resql .= " WHERE name = '".$this->escape($filter)."'";
1501 }
1502 $resql = $this->query($resql);
1503 if ($resql) {
1504 while ($obj = $this->fetch_object($resql)) {
1505 $result[$obj->name] = $obj->setting;
1506 }
1507 }
1508
1509 return $result;
1510 }
1511
1518 public function getServerStatusValues($filter = '')
1519 {
1520 /* This is to return current running requests.
1521 $sql='SELECT datname,procpid,current_query FROM pg_stat_activity ORDER BY procpid';
1522 if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1523 $resql=$this->query($sql);
1524 if ($resql)
1525 {
1526 $obj=$this->fetch_object($resql);
1527 $result[$obj->Variable_name]=$obj->Value;
1528 }
1529 */
1530
1531 return array();
1532 }
1533
1540 public function getNextAutoIncrementId($table)
1541 {
1542 return $this->last_insert_id($table, 'rowid') + 1;
1543 }
1544
1545
1552 public function prepare($sql)
1553 {
1554 $stmtname = uniqid('dolipgstmt_'); // Generate a unique identifier for the statement
1555
1556 $result = pg_prepare($this->db, $stmtname, $sql);
1557 if (!$result) {
1558 $this->lasterror = pg_last_error($this->db);
1559 return false;
1560 }
1561
1562 return $stmtname; // We just return the name of the prepared statement
1563 }
1564}
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 datas 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 lines 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)
Libere le dernier resultset utilise sur cette 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
Collate 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.
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.