dolibarr 21.0.0-beta
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 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 //print $line."\n";
179
180 if ($type == 'auto') {
181 if (preg_match('/ALTER TABLE/i', $line)) {
182 $type = 'dml';
183 } elseif (preg_match('/CREATE TABLE/i', $line)) {
184 $type = 'dml';
185 } elseif (preg_match('/DROP TABLE/i', $line)) {
186 $type = 'dml';
187 }
188 }
189
190 $line = preg_replace('/ as signed\‍)/i', ' as integer)', $line);
191
192 if ($type == 'dml') {
193 $reg = array();
194
195 $line = preg_replace('/\s/', ' ', $line); // Replace tabulation with space
196
197 // we are inside create table statement so let's process datatypes
198 if (preg_match('/(ISAM|innodb)/i', $line)) { // end of create table sequence
199 $line = preg_replace('/\‍)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb).*;/i', ');', $line);
200 $line = preg_replace('/\‍)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb).*;/i', ');', $line);
201 $line = preg_replace('/,$/', '', $line);
202 }
203
204 // Process case: "CREATE TABLE llx_mytable(rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY,code..."
205 if (preg_match('/[\s\t\‍(]*(\w*)[\s\t]+int.*auto_increment/i', $line, $reg)) {
206 $newline = preg_replace('/([\s\t\‍(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i', '\\1 \\2 SERIAL PRIMARY KEY', $line);
207 //$line = "-- ".$line." replaced by --\n".$newline;
208 $line = $newline;
209 }
210
211 if (preg_match('/[\s\t\‍(]*(\w*)[\s\t]+bigint.*auto_increment/i', $line, $reg)) {
212 $newline = preg_replace('/([\s\t\‍(]*)([a-zA-Z_0-9]*)[\s\t]+bigint.*auto_increment[^,]*/i', '\\1 \\2 BIGSERIAL PRIMARY KEY', $line);
213 //$line = "-- ".$line." replaced by --\n".$newline;
214 $line = $newline;
215 }
216
217 // tinyint type conversion
218 $line = preg_replace('/tinyint\‍(?[0-9]*\‍)?/', 'smallint', $line);
219 $line = preg_replace('/tinyint/i', 'smallint', $line);
220
221 // nuke unsigned
222 $line = preg_replace('/(int\w+|smallint|bigint)\s+unsigned/i', '\\1', $line);
223
224 // blob -> text
225 $line = preg_replace('/\w*blob/i', 'text', $line);
226
227 // tinytext/mediumtext -> text
228 $line = preg_replace('/tinytext/i', 'text', $line);
229 $line = preg_replace('/mediumtext/i', 'text', $line);
230 $line = preg_replace('/longtext/i', 'text', $line);
231
232 $line = preg_replace('/text\‍([0-9]+\‍)/i', 'text', $line);
233
234 // change not null datetime field to null valid ones
235 // (to support remapping of "zero time" to null
236 $line = preg_replace('/datetime not null/i', 'datetime', $line);
237 $line = preg_replace('/datetime/i', 'timestamp', $line);
238
239 // double -> numeric
240 $line = preg_replace('/^double/i', 'numeric', $line);
241 $line = preg_replace('/(\s*)double/i', '\\1numeric', $line);
242 // float -> numeric
243 $line = preg_replace('/^float/i', 'numeric', $line);
244 $line = preg_replace('/(\s*)float/i', '\\1numeric', $line);
245
246 //Check tms timestamp field case (in Mysql this field is defaulted to now and
247 // on update defaulted by now
248 $line = preg_replace('/(\s*)tms(\s*)timestamp/i', '\\1tms timestamp without time zone DEFAULT now() NOT NULL', $line);
249
250 // nuke DEFAULT CURRENT_TIMESTAMP
251 $line = preg_replace('/(\s*)DEFAULT(\s*)CURRENT_TIMESTAMP/i', '\\1', $line);
252
253 // nuke ON UPDATE CURRENT_TIMESTAMP
254 $line = preg_replace('/(\s*)ON(\s*)UPDATE(\s*)CURRENT_TIMESTAMP/i', '\\1', $line);
255
256 // unique index(field1,field2)
257 if (preg_match('/unique index\s*\‍((\w+\s*,\s*\w+)\‍)/i', $line)) {
258 $line = preg_replace('/unique index\s*\‍((\w+\s*,\s*\w+)\‍)/i', 'UNIQUE\‍(\\1\‍)', $line);
259 }
260
261 // We remove end of requests "AFTER fieldxxx"
262 $line = preg_replace('/\sAFTER [a-z0-9_]+/i', '', $line);
263
264 // We remove start of requests "ALTER TABLE tablexxx" if this is a DROP INDEX
265 $line = preg_replace('/ALTER TABLE [a-z0-9_]+\s+DROP INDEX/i', 'DROP INDEX', $line);
266
267 // Translate order to rename fields
268 if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i', $line, $reg)) {
269 $line = "-- ".$line." replaced by --\n";
270 $line .= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
271 }
272
273 // Translate order to modify field format
274 if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i', $line, $reg)) {
275 $line = "-- ".$line." replaced by --\n";
276 $newreg3 = $reg[3];
277 $newreg3 = preg_replace('/ DEFAULT NULL/i', '', $newreg3);
278 $newreg3 = preg_replace('/ NOT NULL/i', '', $newreg3);
279 $newreg3 = preg_replace('/ NULL/i', '', $newreg3);
280 $newreg3 = preg_replace('/ DEFAULT 0/i', '', $newreg3);
281 $newreg3 = preg_replace('/ DEFAULT \'?[0-9a-zA-Z_@]*\'?/i', '', $newreg3);
282 $line .= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3;
283 // TODO Add alter to set default value or null/not null if there is this in $reg[3]
284 }
285
286 // alter table add primary key (field1, field2 ...) -> We remove the primary key name not accepted by PostGreSQL
287 // ALTER TABLE llx_dolibarr_modules ADD PRIMARY KEY pk_dolibarr_modules (numero, entity)
288 if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\‍((.*)$/i', $line, $reg)) {
289 $line = "-- ".$line." replaced by --\n";
290 $line .= "ALTER TABLE ".$reg[1]." ADD PRIMARY KEY (".$reg[3];
291 }
292
293 // Translate order to drop primary keys
294 // ALTER TABLE llx_dolibarr_modules DROP PRIMARY KEY pk_xxx
295 if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+PRIMARY\s+KEY\s*([^;]+)$/i', $line, $reg)) {
296 $line = "-- ".$line." replaced by --\n";
297 $line .= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
298 }
299
300 // Translate order to drop foreign keys
301 // ALTER TABLE llx_dolibarr_modules DROP FOREIGN KEY fk_xxx
302 if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i', $line, $reg)) {
303 $line = "-- ".$line." replaced by --\n";
304 $line .= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
305 }
306
307 // Translate order to add foreign keys
308 // ALTER TABLE llx_tablechild ADD CONSTRAINT fk_tablechild_fk_fieldparent FOREIGN KEY (fk_fieldparent) REFERENCES llx_tableparent (rowid)
309 if (preg_match('/ALTER\s+TABLE\s+(.*)\s*ADD CONSTRAINT\s+(.*)\s*FOREIGN\s+KEY\s*(.*)$/i', $line, $reg)) {
310 $line = preg_replace('/;$/', '', $line);
311 $line .= " DEFERRABLE INITIALLY IMMEDIATE;";
312 }
313
314 // alter table add [unique] [index] (field1, field2 ...)
315 // ALTER TABLE llx_accountingaccount ADD INDEX idx_accountingaccount_fk_pcg_version (fk_pcg_version)
316 if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\‍(([\w,\s]+)\‍)/i', $line, $reg)) {
317 $fieldlist = $reg[4];
318 $idxname = $reg[3];
319 $tablename = $reg[1];
320 $line = "-- ".$line." replaced by --\n";
321 $line .= "CREATE ".(preg_match('/UNIQUE/', $reg[2]) ? 'UNIQUE ' : '')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")";
322 }
323 }
324
325 // To have PostgreSQL case sensitive
326 $count_like = 0;
327 $line = str_replace(' LIKE \'', ' ILIKE \'', $line, $count_like);
328 if (getDolGlobalString('PSQL_USE_UNACCENT') && $count_like > 0) {
329 // @see https://docs.PostgreSQL.fr/11/unaccent.html : 'unaccent()' function must be installed before
330 $line = preg_replace('/\s+(\‍(+\s*)([a-zA-Z0-9\-\_\.]+) ILIKE /', ' \1unaccent(\2) ILIKE ', $line);
331 }
332
333 $line = str_replace(' LIKE BINARY \'', ' LIKE \'', $line);
334
335 // Replace INSERT IGNORE into INSERT
336 $line = preg_replace('/^INSERT IGNORE/', 'INSERT', $line);
337
338 // Delete using criteria on other table must not declare twice the deleted table
339 // DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable
340 if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', $line, $reg)) {
341 if ($reg[1] == $reg[2]) { // If same table, we remove second one
342 $line = preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', 'DELETE FROM \\1 USING \\3', $line);
343 }
344 }
345
346 // Remove () in the tables in FROM if 1 table
347 $line = preg_replace('/FROM\s*\‍((([a-z_]+)\s+as\s+([a-z_]+)\s*)\‍)/i', 'FROM \\1', $line);
348 //print $line."\n";
349
350 // Remove () in the tables in FROM if 2 table
351 $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);
352 //print $line."\n";
353
354 // Remove () in the tables in FROM if 3 table
355 $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);
356 //print $line."\n";
357
358 // Remove () in the tables in FROM if 4 table
359 $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);
360 //print $line."\n";
361
362 // Remove () in the tables in FROM if 5 table
363 $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);
364 //print $line."\n";
365
366 // Replace spacing ' with ''.
367 // By default we do not (should be already done by db->escape function if required
368 // except for sql insert in data file that are mysql escaped so we removed them to
369 // be compatible with standard_conforming_strings=on that considers \ as ordinary character).
370 if ($unescapeslashquot) {
371 $line = preg_replace("/\\\'/", "''", $line);
372 }
373
374 //print "type=".$type." newline=".$line."<br>\n";
375 }
376
377 return $line;
378 }
379
380 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
389 public function select_db($database)
390 {
391 // phpcs:enable
392 if ($database == $this->database_name) {
393 return true;
394 } else {
395 return false;
396 }
397 }
398
410 public function connect($host, $login, $passwd, $name, $port = 0)
411 {
412 // use pg_pconnect() instead of pg_connect() if you want to use persistent connection costing 1ms, instead of 30ms for non persistent
413
414 $this->db = false;
415
416 // connections parameters must be protected (only \ and ' according to pg_connect() manual)
417 $host = str_replace(array("\\", "'"), array("\\\\", "\\'"), $host);
418 $login = str_replace(array("\\", "'"), array("\\\\", "\\'"), $login);
419 $passwd = str_replace(array("\\", "'"), array("\\\\", "\\'"), $passwd);
420 $name = str_replace(array("\\", "'"), array("\\\\", "\\'"), $name);
421 $port = str_replace(array("\\", "'"), array("\\\\", "\\'"), (string) $port);
422
423 if (!$name) {
424 $name = "postgres"; // When try to connect using admin user
425 }
426
427 // try first Unix domain socket (local)
428 if ((!empty($host) && $host == "socket") && !defined('NOLOCALSOCKETPGCONNECT')) {
429 $con_string = "dbname='".$name."' user='".$login."' password='".$passwd."'"; // $name may be empty
430 try {
431 $this->db = @pg_connect($con_string);
432 } catch (Exception $e) {
433 // No message
434 }
435 }
436
437 // if local connection failed or not requested, use TCP/IP
438 if (empty($this->db)) {
439 if (!$host) {
440 $host = "localhost";
441 }
442 if (!$port) {
443 $port = 5432;
444 }
445
446 $con_string = "host='".$host."' port='".$port."' dbname='".$name."' user='".$login."' password='".$passwd."'";
447 try {
448 $this->db = @pg_connect($con_string);
449 } catch (Exception $e) {
450 print $e->getMessage();
451 }
452 }
453
454 // now we test if at least one connect method was a success
455 if ($this->db) {
456 $this->database_name = $name;
457 pg_set_error_verbosity($this->db, PGSQL_ERRORS_VERBOSE); // Set verbosity to max
458 pg_query($this->db, "set datestyle = 'ISO, YMD';");
459 }
460
461 return $this->db;
462 }
463
469 public function getVersion()
470 {
471 $resql = $this->query('SHOW server_version');
472 if ($resql) {
473 $liste = $this->fetch_array($resql);
474 return $liste['server_version'];
475 }
476 return '';
477 }
478
484 public function getDriverInfo()
485 {
486 return 'pgsql php driver';
487 }
488
495 public function close()
496 {
497 if ($this->db) {
498 if ($this->transaction_opened > 0) {
499 dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened, LOG_ERR);
500 }
501 $this->connected = false;
502 return pg_close($this->db);
503 }
504 return false;
505 }
506
516 public function query($query, $usesavepoint = 0, $type = 'auto', $result_mode = 0)
517 {
518 global $dolibarr_main_db_readonly;
519
520 $query = trim($query);
521
522 // Convert MySQL syntax to PostgreSQL syntax
523 $query = $this->convertSQLFromMysql($query, $type, ($this->unescapeslashquot && $this->standard_conforming_strings));
524 //print "After convertSQLFromMysql:\n".$query."<br>\n";
525
526 if (getDolGlobalString('MAIN_DB_AUTOFIX_BAD_SQL_REQUEST')) {
527 // Fix bad formed requests. If request contains a date without quotes, we fix this but this should not occurs.
528 $loop = true;
529 while ($loop) {
530 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)) {
531 $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);
532 dol_syslog("Warning: Bad formed request converted into ".$query, LOG_WARNING);
533 } else {
534 $loop = false;
535 }
536 }
537 }
538
539 if ($usesavepoint && $this->transaction_opened) {
540 @pg_query($this->db, 'SAVEPOINT mysavepoint');
541 }
542
543 if (!in_array($query, array('BEGIN', 'COMMIT', 'ROLLBACK'))) {
544 $SYSLOG_SQL_LIMIT = 10000; // limit log to 10kb per line to limit DOS attacks
545 dol_syslog('sql='.substr($query, 0, $SYSLOG_SQL_LIMIT), LOG_DEBUG);
546 }
547 if (empty($query)) {
548 return false; // Return false = error if empty request
549 }
550
551 if (!empty($dolibarr_main_db_readonly)) {
552 if (preg_match('/^(INSERT|UPDATE|REPLACE|DELETE|CREATE|ALTER|TRUNCATE|DROP)/i', $query)) {
553 $this->lasterror = 'Application in read-only mode';
554 $this->lasterrno = 'APPREADONLY';
555 $this->lastquery = $query;
556 return false;
557 }
558 }
559
560 $ret = @pg_query($this->db, $query);
561
562 //print $query;
563 if (!preg_match("/^COMMIT/i", $query) && !preg_match("/^ROLLBACK/i", $query)) { // Si requete utilisateur, on la sauvegarde ainsi que son resultset
564 if (!$ret) {
565 if ($this->errno() != 'DB_ERROR_25P02') { // Do not overwrite errors if this is a consecutive error
566 $this->lastqueryerror = $query;
567 $this->lasterror = $this->error();
568 $this->lasterrno = $this->errno();
569
570 if (getDolGlobalInt('SYSLOG_LEVEL') < LOG_DEBUG) {
571 dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR); // Log of request was not yet done previously
572 }
573 dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterror." (".$this->lasterrno.")", LOG_ERR);
574 dol_syslog(get_class($this)."::query SQL Error usesavepoint = ".$usesavepoint, LOG_ERR);
575 }
576
577 if ($usesavepoint && $this->transaction_opened) { // Warning, after that errno will be erased
578 @pg_query($this->db, 'ROLLBACK TO SAVEPOINT mysavepoint');
579 }
580 }
581 $this->lastquery = $query;
582 $this->_results = $ret;
583 }
584
585 return $ret;
586 }
587
588 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
595 public function fetch_object($resultset)
596 {
597 // phpcs:enable
598 // If resultset not provided, we take the last used by connection
599 if (!is_resource($resultset) && !is_object($resultset)) {
600 $resultset = $this->_results;
601 }
602 return pg_fetch_object($resultset);
603 }
604
605 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
612 public function fetch_array($resultset)
613 {
614 // phpcs:enable
615 // If resultset not provided, we take the last used by connection
616 if (!is_resource($resultset) && !is_object($resultset)) {
617 $resultset = $this->_results;
618 }
619 return pg_fetch_array($resultset);
620 }
621
622 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
629 public function fetch_row($resultset)
630 {
631 // phpcs:enable
632 // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connection
633 if (!is_resource($resultset) && !is_object($resultset)) {
634 $resultset = $this->_results;
635 }
636 return pg_fetch_row($resultset); // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal
637 }
638
639 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
647 public function num_rows($resultset)
648 {
649 // phpcs:enable
650 // If resultset not provided, we take the last used by connection
651 if (!is_resource($resultset) && !is_object($resultset)) {
652 $resultset = $this->_results;
653 }
654 return pg_num_rows($resultset);
655 }
656
657 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
665 public function affected_rows($resultset)
666 {
667 // phpcs:enable
668 // If resultset not provided, we take the last used by connection
669 if (!is_resource($resultset) && !is_object($resultset)) {
670 $resultset = $this->_results;
671 }
672 // pgsql necessite un resultset pour cette fonction contrairement
673 // a mysql qui prend un link de base
674 return pg_affected_rows($resultset);
675 }
676
677
684 public function free($resultset = null)
685 {
686 // If resultset not provided, we take the last used by connection
687 if (!is_resource($resultset) && !is_object($resultset)) {
688 $resultset = $this->_results;
689 }
690 // Si resultset en est un, on libere la memoire
691 if (is_resource($resultset) || is_object($resultset)) {
692 pg_free_result($resultset);
693 }
694 }
695
696
704 public function plimit($limit = 0, $offset = 0)
705 {
706 global $conf;
707 if (empty($limit)) {
708 return "";
709 }
710 if ($limit < 0) {
711 $limit = $conf->liste_limit;
712 }
713 if ($offset > 0) {
714 return " LIMIT ".$limit." OFFSET ".$offset." ";
715 } else {
716 return " LIMIT $limit ";
717 }
718 }
719
720
727 public function escape($stringtoencode)
728 {
729 return pg_escape_string($this->db, $stringtoencode);
730 }
731
738 public function escapeforlike($stringtoencode)
739 {
740 return str_replace(array('\\', '_', '%'), array('\\\\', '\_', '\%'), (string) $stringtoencode);
741 }
742
751 public function ifsql($test, $resok, $resko)
752 {
753 return '(CASE WHEN '.$test.' THEN '.$resok.' ELSE '.$resko.' END)';
754 }
755
764 public function regexpsql($subject, $pattern, $sqlstring = 0)
765 {
766 if ($sqlstring) {
767 return "(". $subject ." ~ '" . $this->escape($pattern) . "')";
768 }
769
770 return "('". $this->escape($subject) ."' ~ '" . $this->escape($pattern) . "')";
771 }
772
773
779 public function errno()
780 {
781 if (!$this->connected) {
782 // Si il y a eu echec de connection, $this->db n'est pas valide.
783 return 'DB_ERROR_FAILED_TO_CONNECT';
784 } else {
785 // Constants to convert error code to a generic Dolibarr error code
786 $errorcode_map = array(
787 1004 => 'DB_ERROR_CANNOT_CREATE',
788 1005 => 'DB_ERROR_CANNOT_CREATE',
789 1006 => 'DB_ERROR_CANNOT_CREATE',
790 1007 => 'DB_ERROR_ALREADY_EXISTS',
791 1008 => 'DB_ERROR_CANNOT_DROP',
792 1025 => 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
793 1044 => 'DB_ERROR_ACCESSDENIED',
794 1046 => 'DB_ERROR_NODBSELECTED',
795 1048 => 'DB_ERROR_CONSTRAINT',
796 '42P07' => 'DB_ERROR_TABLE_OR_KEY_ALREADY_EXISTS',
797 '42703' => 'DB_ERROR_NOSUCHFIELD',
798 1060 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
799 42701 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
800 '42710' => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
801 '23505' => 'DB_ERROR_RECORD_ALREADY_EXISTS',
802 '42704' => 'DB_ERROR_NO_INDEX_TO_DROP', // May also be Type xxx does not exists
803 '42601' => 'DB_ERROR_SYNTAX',
804 '42P16' => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
805 1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
806 1091 => 'DB_ERROR_NOSUCHFIELD',
807 1100 => 'DB_ERROR_NOT_LOCKED',
808 1136 => 'DB_ERROR_VALUE_COUNT_ON_ROW',
809 '42P01' => 'DB_ERROR_NOSUCHTABLE',
810 '23503' => 'DB_ERROR_NO_PARENT',
811 1217 => 'DB_ERROR_CHILD_EXISTS',
812 1451 => 'DB_ERROR_CHILD_EXISTS',
813 '42P04' => 'DB_DATABASE_ALREADY_EXISTS'
814 );
815
816 $errorlabel = pg_last_error($this->db);
817 $errorcode = '';
818 $reg = array();
819 if (preg_match('/: *([0-9P]+):/', $errorlabel, $reg)) {
820 $errorcode = $reg[1];
821 if (isset($errorcode_map[$errorcode])) {
822 return $errorcode_map[$errorcode];
823 }
824 }
825 $errno = $errorcode ? $errorcode : $errorlabel;
826 return ($errno ? 'DB_ERROR_'.$errno : '0');
827 }
828 // '/(Table does not exist\.|Relation [\"\'].*[\"\'] does not exist|sequence does not exist|class ".+" not found)$/' => 'DB_ERROR_NOSUCHTABLE',
829 // '/table [\"\'].*[\"\'] does not exist/' => 'DB_ERROR_NOSUCHTABLE',
830 // '/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*/' => 'DB_ERROR_RECORD_ALREADY_EXISTS',
831 // '/divide by zero$/' => 'DB_ERROR_DIVZERO',
832 // '/pg_atoi: error in .*: can\'t parse /' => 'DB_ERROR_INVALID_NUMBER',
833 // '/ttribute [\"\'].*[\"\'] not found$|Relation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/' => 'DB_ERROR_NOSUCHFIELD',
834 // '/parser: parse error at or near \"/' => 'DB_ERROR_SYNTAX',
835 // '/referential integrity violation/' => 'DB_ERROR_CONSTRAINT'
836 }
837
843 public function error()
844 {
845 return pg_last_error($this->db);
846 }
847
848 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
856 public function last_insert_id($tab, $fieldid = 'rowid')
857 {
858 // phpcs:enable
859 //$result = pg_query($this->db,"SELECT MAX(".$fieldid.") FROM ".$tab);
860 $result = pg_query($this->db, "SELECT currval('".$tab."_".$fieldid."_seq')");
861 if (!$result) {
862 print pg_last_error($this->db);
863 exit;
864 }
865 //$nbre = pg_num_rows($result);
866 $row = pg_fetch_result($result, 0, 0);
867 return (int) $row;
868 }
869
878 public function encrypt($fieldorvalue, $withQuotes = 1)
879 {
880 //global $conf;
881
882 // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
883 //$cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
884
885 //Encryption key
886 //$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
887
888 $return = $fieldorvalue;
889 return ($withQuotes ? "'" : "").$this->escape($return).($withQuotes ? "'" : "");
890 }
891
892
899 public function decrypt($value)
900 {
901 //global $conf;
902
903 // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
904 //$cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
905
906 //Encryption key
907 //$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
908
909 $return = $value;
910 return $return;
911 }
912
913
914 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
920 public function DDLGetConnectId()
921 {
922 // phpcs:enable
923 return '?';
924 }
925
926
927
928 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
940 public function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
941 {
942 // phpcs:enable
943 if (empty($charset)) {
944 $charset = $this->forcecharset;
945 }
946 if (empty($collation)) {
947 $collation = $this->forcecollate;
948 }
949
950 // Test charset match LC_TYPE (pgsql error otherwise)
951 //print $charset.' '.setlocale(LC_CTYPE,'0'); exit;
952
953 // NOTE: Do not use ' around the database name
954 $sql = "CREATE DATABASE ".$this->escape($database)." OWNER '".$this->escape($owner)."' ENCODING '".$this->escape($charset)."'";
955
956 dol_syslog($sql, LOG_DEBUG);
957 $ret = $this->query($sql);
958
959 return $ret;
960 }
961
962 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
970 public function DDLListTables($database, $table = '')
971 {
972 // phpcs:enable
973 $listtables = array();
974
975 $escapedlike = '';
976 if ($table) {
977 $tmptable = preg_replace('/[^a-z0-9\.\-\_%]/i', '', $table);
978
979 $escapedlike = " AND table_name LIKE '".$this->escape($tmptable)."'";
980 }
981 $result = pg_query($this->db, "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'".$escapedlike." ORDER BY table_name");
982 if ($result) {
983 while ($row = $this->fetch_row($result)) { // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal
984 $listtables[] = $row[0];
985 }
986 }
987 return $listtables;
988 }
989
990 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
998 public function DDLListTablesFull($database, $table = '')
999 {
1000 // phpcs:enable
1001 $listtables = array();
1002
1003 $escapedlike = '';
1004 if ($table) {
1005 $tmptable = preg_replace('/[^a-z0-9\.\-\_%]/i', '', $table);
1006
1007 $escapedlike = " AND table_name LIKE '".$this->escape($tmptable)."'";
1008 }
1009 $result = pg_query($this->db, "SELECT table_name, table_type FROM information_schema.tables WHERE table_schema = 'public'".$escapedlike." ORDER BY table_name");
1010 if ($result) {
1011 while ($row = $this->fetch_row($result)) { // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal
1012 $listtables[] = $row;
1013 }
1014 }
1015 return $listtables;
1016 }
1017
1018 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1025 public function DDLInfoTable($table)
1026 {
1027 // phpcs:enable
1028 $infotables = array();
1029
1030 $sql = "SELECT ";
1031 $sql .= " infcol.column_name as 'Column',";
1032 $sql .= " CASE WHEN infcol.character_maximum_length IS NOT NULL THEN infcol.udt_name || '('||infcol.character_maximum_length||')'";
1033 $sql .= " ELSE infcol.udt_name";
1034 $sql .= " END as 'Type',";
1035 $sql .= " infcol.collation_name as 'Collation',";
1036 $sql .= " infcol.is_nullable as 'Null',";
1037 $sql .= " '' as 'Key',";
1038 $sql .= " infcol.column_default as 'Default',";
1039 $sql .= " '' as 'Extra',";
1040 $sql .= " '' as 'Privileges'";
1041 $sql .= " FROM information_schema.columns infcol";
1042 $sql .= " WHERE table_schema = 'public' ";
1043 $sql .= " AND table_name = '".$this->escape($table)."'";
1044 $sql .= " ORDER BY ordinal_position;";
1045
1046 $result = $this->query($sql);
1047 if ($result) {
1048 while ($row = $this->fetch_row($result)) {
1049 $infotables[] = $row;
1050 }
1051 }
1052 return $infotables;
1053 }
1054
1055
1056 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1069 public function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
1070 {
1071 // phpcs:enable
1072 // @TODO: $fulltext_keys parameter is unused
1073
1074 $sqlk = array();
1075 $sqluq = array();
1076
1077 // Keys found into the array $fields: type,value,attribute,null,default,extra
1078 // ex. : $fields['rowid'] = array(
1079 // 'type'=>'int' or 'integer',
1080 // 'value'=>'11',
1081 // 'null'=>'not null',
1082 // 'extra'=> 'auto_increment'
1083 // );
1084 $sql = "CREATE TABLE ".$this->sanitize($table)."(";
1085 $i = 0;
1086 $sqlfields = array();
1087 foreach ($fields as $field_name => $field_desc) {
1088 $sqlfields[$i] = $this->sanitize($field_name)." ";
1089 $sqlfields[$i] .= $this->sanitize($field_desc['type']);
1090 if (isset($field_desc['value']) && $field_desc['value'] !== '') {
1091 $sqlfields[$i] .= "(".$this->sanitize($field_desc['value']).")";
1092 }
1093 if (isset($field_desc['attribute']) && $field_desc['attribute'] !== '') {
1094 $sqlfields[$i] .= " ".$this->sanitize($field_desc['attribute']);
1095 }
1096 if (isset($field_desc['default']) && $field_desc['default'] !== '') {
1097 if (in_array($field_desc['type'], array('tinyint', 'smallint', 'int', 'double'))) {
1098 $sqlfields[$i] .= " DEFAULT ".((float) $field_desc['default']);
1099 } elseif ($field_desc['default'] == 'null' || $field_desc['default'] == 'CURRENT_TIMESTAMP') {
1100 $sqlfields[$i] .= " DEFAULT ".$this->sanitize($field_desc['default']);
1101 } else {
1102 $sqlfields[$i] .= " DEFAULT '".$this->escape($field_desc['default'])."'";
1103 }
1104 }
1105 if (isset($field_desc['null']) && $field_desc['null'] !== '') {
1106 $sqlfields[$i] .= " ".$this->sanitize($field_desc['null'], 0, 0, 1);
1107 }
1108 if (isset($field_desc['extra']) && $field_desc['extra'] !== '') {
1109 $sqlfields[$i] .= " ".$this->sanitize($field_desc['extra'], 0, 0, 1);
1110 }
1111 if (!empty($primary_key) && $primary_key == $field_name) {
1112 $sqlfields[$i] .= " AUTO_INCREMENT PRIMARY KEY"; // mysql instruction that will be converted by driver late
1113 }
1114 $i++;
1115 }
1116
1117 if (is_array($unique_keys)) {
1118 $i = 0;
1119 foreach ($unique_keys as $key => $value) {
1120 $sqluq[$i] = "UNIQUE KEY '".$this->sanitize($key)."' ('".$this->escape($value)."')";
1121 $i++;
1122 }
1123 }
1124 if (is_array($keys)) {
1125 $i = 0;
1126 foreach ($keys as $key => $value) {
1127 $sqlk[$i] = "KEY ".$this->sanitize($key)." (".$value.")";
1128 $i++;
1129 }
1130 }
1131 $sql .= implode(', ', $sqlfields);
1132 if ($unique_keys != "") {
1133 $sql .= ",".implode(',', $sqluq);
1134 }
1135 if (is_array($keys)) {
1136 $sql .= ",".implode(',', $sqlk);
1137 }
1138 $sql .= ")";
1139 //$sql .= " engine=".$this->sanitize($type);
1140
1141 if (!$this->query($sql, 1)) {
1142 return -1;
1143 } else {
1144 return 1;
1145 }
1146 }
1147
1148 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1155 public function DDLDropTable($table)
1156 {
1157 // phpcs:enable
1158 $tmptable = preg_replace('/[^a-z0-9\.\-\_]/i', '', $table);
1159
1160 $sql = "DROP TABLE ".$this->sanitize($tmptable);
1161
1162 if (!$this->query($sql, 1)) {
1163 return -1;
1164 } else {
1165 return 1;
1166 }
1167 }
1168
1169 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1177 public function DDLDescTable($table, $field = "")
1178 {
1179 // phpcs:enable
1180 $sql = "SELECT attname FROM pg_attribute, pg_type WHERE typname = '".$this->escape($table)."' AND attrelid = typrelid";
1181 $sql .= " AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', 'tableoid', 'xmin', 'xmax')";
1182 if ($field) {
1183 $sql .= " AND attname = '".$this->escape($field)."'";
1184 }
1185
1186 dol_syslog($sql, LOG_DEBUG);
1187 $this->_results = $this->query($sql);
1188 return $this->_results;
1189 }
1190
1191 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1201 public function DDLAddField($table, $field_name, $field_desc, $field_position = "")
1202 {
1203 // phpcs:enable
1204 // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
1205 // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
1206 $sql = "ALTER TABLE ".$this->sanitize($table)." ADD ".$this->sanitize($field_name)." ";
1207 $sql .= $this->sanitize($field_desc['type']);
1208 if (isset($field_desc['value']) && preg_match("/^[^\s]/i", $field_desc['value'])) {
1209 if (!in_array($field_desc['type'], array('tinyint', 'smallint', 'int', 'date', 'datetime')) && $field_desc['value']) {
1210 $sql .= "(".$this->sanitize($field_desc['value']).")";
1211 }
1212 }
1213 if (isset($field_desc['attribute']) && preg_match("/^[^\s]/i", $field_desc['attribute'])) {
1214 $sql .= " ".$this->sanitize($field_desc['attribute']);
1215 }
1216 if (isset($field_desc['null']) && preg_match("/^[^\s]/i", $field_desc['null'])) {
1217 $sql .= " ".$this->sanitize($field_desc['null']);
1218 }
1219 if (isset($field_desc['default']) && preg_match("/^[^\s]/i", $field_desc['default'])) {
1220 if (in_array($field_desc['type'], array('tinyint', 'smallint', 'int', 'double'))) {
1221 $sql .= " DEFAULT ".((float) $field_desc['default']);
1222 } elseif ($field_desc['default'] == 'null' || $field_desc['default'] == 'CURRENT_TIMESTAMP') {
1223 $sql .= " DEFAULT ".$this->sanitize($field_desc['default']);
1224 } else {
1225 $sql .= " DEFAULT '".$this->escape($field_desc['default'])."'";
1226 }
1227 }
1228 if (isset($field_desc['extra']) && preg_match("/^[^\s]/i", $field_desc['extra'])) {
1229 $sql .= " ".$this->sanitize($field_desc['extra'], 0, 0, 1);
1230 }
1231 $sql .= " ".$this->sanitize($field_position, 0, 0, 1);
1232
1233 dol_syslog($sql, LOG_DEBUG);
1234 if (!$this -> query($sql)) {
1235 return -1;
1236 }
1237 return 1;
1238 }
1239
1240 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1249 public function DDLUpdateField($table, $field_name, $field_desc)
1250 {
1251 // phpcs:enable
1252 $sql = "ALTER TABLE ".$this->sanitize($table);
1253 $sql .= " ALTER COLUMN ".$this->sanitize($field_name)." TYPE ".$this->sanitize($field_desc['type']);
1254 if (isset($field_desc['value']) && preg_match("/^[^\s]/i", $field_desc['value'])) {
1255 if (!in_array($field_desc['type'], array('smallint', 'int', 'date', 'datetime')) && $field_desc['value']) {
1256 $sql .= "(".$this->sanitize($field_desc['value']).")";
1257 }
1258 }
1259
1260 if (isset($field_desc['null']) && ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL')) {
1261 // 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
1262 if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text') {
1263 $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";
1264 $this->query($sqlbis);
1265 } elseif (in_array($field_desc['type'], array('tinyint', 'smallint', 'int', 'double'))) {
1266 $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";
1267 $this->query($sqlbis);
1268 }
1269 }
1270
1271 if (isset($field_desc['default']) && $field_desc['default'] != '') {
1272 if (in_array($field_desc['type'], array('tinyint', 'smallint', 'int', 'double'))) {
1273 $sql .= ", ALTER COLUMN ".$this->sanitize($field_name)." SET DEFAULT ".((float) $field_desc['default']);
1274 } elseif ($field_desc['type'] != 'text') { // Default not supported on text fields ?
1275 $sql .= ", ALTER COLUMN ".$this->sanitize($field_name)." SET DEFAULT '".$this->escape($field_desc['default'])."'";
1276 }
1277 }
1278
1279 dol_syslog($sql, LOG_DEBUG);
1280 if (!$this->query($sql)) {
1281 return -1;
1282 }
1283 return 1;
1284 }
1285
1286 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1294 public function DDLDropField($table, $field_name)
1295 {
1296 // phpcs:enable
1297 $tmp_field_name = preg_replace('/[^a-z0-9\.\-\_]/i', '', $field_name);
1298
1299 $sql = "ALTER TABLE ".$this->sanitize($table)." DROP COLUMN ".$this->sanitize($tmp_field_name);
1300 if (!$this->query($sql)) {
1301 $this->error = $this->lasterror();
1302 return -1;
1303 }
1304 return 1;
1305 }
1306
1307 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1317 public function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
1318 {
1319 // phpcs:enable
1320 // Note: using ' on user does not works with pgsql
1321 $sql = "CREATE USER ".$this->sanitize($dolibarr_main_db_user)." with password '".$this->escape($dolibarr_main_db_pass)."'";
1322
1323 dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
1324 $resql = $this->query($sql);
1325 if (!$resql) {
1326 return -1;
1327 }
1328
1329 return 1;
1330 }
1331
1338 {
1339 $resql = $this->query('SHOW SERVER_ENCODING');
1340 if ($resql) {
1341 $liste = $this->fetch_array($resql);
1342 return $liste['server_encoding'];
1343 } else {
1344 return '';
1345 }
1346 }
1347
1353 public function getListOfCharacterSet()
1354 {
1355 $resql = $this->query('SHOW SERVER_ENCODING');
1356 $liste = array();
1357 if ($resql) {
1358 $i = 0;
1359 while ($obj = $this->fetch_object($resql)) {
1360 $liste[$i]['charset'] = $obj->server_encoding;
1361 $liste[$i]['description'] = 'Default database charset';
1362 $i++;
1363 }
1364 $this->free($resql);
1365 } else {
1366 return null;
1367 }
1368 return $liste;
1369 }
1370
1377 {
1378 $resql = $this->query('SHOW LC_COLLATE');
1379 if ($resql) {
1380 $liste = $this->fetch_array($resql);
1381 return $liste['lc_collate'];
1382 } else {
1383 return '';
1384 }
1385 }
1386
1392 public function getListOfCollation()
1393 {
1394 $resql = $this->query('SHOW LC_COLLATE');
1395 $liste = array();
1396 if ($resql) {
1397 $i = 0;
1398 while ($obj = $this->fetch_object($resql)) {
1399 $liste[$i]['collation'] = $obj->lc_collate;
1400 $i++;
1401 }
1402 $this->free($resql);
1403 } else {
1404 return null;
1405 }
1406 return $liste;
1407 }
1408
1414 public function getPathOfDump()
1415 {
1416 $fullpathofdump = '/pathtopgdump/pg_dump';
1417
1418 if (file_exists('/usr/bin/pg_dump')) {
1419 $fullpathofdump = '/usr/bin/pg_dump';
1420 } else {
1421 // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1422 $resql = $this->query('SHOW data_directory');
1423 if ($resql) {
1424 $liste = $this->fetch_array($resql);
1425 $basedir = $liste['data_directory'];
1426 $fullpathofdump = preg_replace('/data$/', 'bin', $basedir).'/pg_dump';
1427 }
1428 }
1429
1430 return $fullpathofdump;
1431 }
1432
1438 public function getPathOfRestore()
1439 {
1440 //$tool='pg_restore';
1441 $tool = 'psql';
1442
1443 $fullpathofdump = '/pathtopgrestore/'.$tool;
1444
1445 if (file_exists('/usr/bin/'.$tool)) {
1446 $fullpathofdump = '/usr/bin/'.$tool;
1447 } else {
1448 // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
1449 $resql = $this->query('SHOW data_directory');
1450 if ($resql) {
1451 $liste = $this->fetch_array($resql);
1452 $basedir = $liste['data_directory'];
1453 $fullpathofdump = preg_replace('/data$/', 'bin', $basedir).'/'.$tool;
1454 }
1455 }
1456
1457 return $fullpathofdump;
1458 }
1459
1466 public function getServerParametersValues($filter = '')
1467 {
1468 $result = array();
1469
1470 $resql = 'select name,setting from pg_settings';
1471 if ($filter) {
1472 $resql .= " WHERE name = '".$this->escape($filter)."'";
1473 }
1474 $resql = $this->query($resql);
1475 if ($resql) {
1476 while ($obj = $this->fetch_object($resql)) {
1477 $result[$obj->name] = $obj->setting;
1478 }
1479 }
1480
1481 return $result;
1482 }
1483
1490 public function getServerStatusValues($filter = '')
1491 {
1492 /* This is to return current running requests.
1493 $sql='SELECT datname,procpid,current_query FROM pg_stat_activity ORDER BY procpid';
1494 if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1495 $resql=$this->query($sql);
1496 if ($resql)
1497 {
1498 $obj=$this->fetch_object($resql);
1499 $result[$obj->Variable_name]=$obj->Value;
1500 }
1501 */
1502
1503 return array();
1504 }
1505}
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.
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.
last_insert_id($tab, $fieldid='rowid')
Get last ID after an insert INSERT.
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.
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.
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.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79