33require_once DOL_DOCUMENT_ROOT.
'/core/db/DoliDB.class.php';
58 public $unescapeslashquot =
false;
62 public $standard_conforming_strings =
false;
86 if (!empty(
$conf->db->character_set)) {
87 $this->forcecharset =
$conf->db->character_set;
89 if (!empty(
$conf->db->dolibarr_main_db_collation)) {
90 $this->forcecollate =
$conf->db->dolibarr_main_db_collation;
93 $this->database_user = $user;
94 $this->database_host = $host;
95 $this->database_port = $port;
97 $this->transaction_opened = 0;
101 if (!function_exists(
"pg_connect")) {
102 $this->connected =
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);
110 $this->connected =
false;
112 $this->
error = $langs->trans(
"ErrorWrongHostParameter");
113 dol_syslog(get_class($this).
"::DoliDBPgsql : Erreur Connect, wrong host parameters", LOG_ERR);
119 $this->db = $this->
connect($host, $user, $pass, $name, $port);
122 $this->connected =
true;
126 $this->connected =
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);
133 if ($this->connected && $name) {
135 $this->database_selected =
true;
136 $this->database_name = $name;
139 $this->database_selected =
false;
140 $this->database_name =
'';
143 dol_syslog(get_class($this).
"::DoliDBPgsql : Erreur Select_db ".$this->
error, LOG_ERR);
147 $this->database_selected =
false;
165 if (preg_match(
'/^--\s\$Id/i', $line)) {
169 if (preg_match(
'/^#/i', $line) || preg_match(
'/^$/i', $line) || preg_match(
'/^--/i', $line)) {
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);
181 if (
$type ==
'auto') {
182 if (preg_match(
'/ALTER TABLE/i', $line)) {
184 } elseif (preg_match(
'/CREATE TABLE/i', $line)) {
186 } elseif (preg_match(
'/DROP TABLE/i', $line)) {
191 $line = preg_replace(
'/ as signed\)/i',
' as integer)', $line);
193 if (
$type ==
'dml') {
196 $line = preg_replace(
'/\s/',
' ', $line);
199 if (preg_match(
'/(ISAM|innodb)/i', $line)) {
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);
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);
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);
219 $line = preg_replace(
'/tinyint\(?[0-9]*\)?/',
'smallint', $line);
220 $line = preg_replace(
'/tinyint/i',
'smallint', $line);
223 $line = preg_replace(
'/(int\w+|smallint|bigint)\s+unsigned/i',
'\\1', $line);
226 $line = preg_replace(
'/\w*blob/i',
'text', $line);
229 $line = preg_replace(
'/tinytext/i',
'text', $line);
230 $line = preg_replace(
'/mediumtext/i',
'text', $line);
231 $line = preg_replace(
'/longtext/i',
'text', $line);
233 $line = preg_replace(
'/text\([0-9]+\)/i',
'text', $line);
237 $line = preg_replace(
'/datetime not null/i',
'datetime', $line);
238 $line = preg_replace(
'/datetime/i',
'timestamp', $line);
241 $line = preg_replace(
'/^double/i',
'numeric', $line);
242 $line = preg_replace(
'/(\s*)double/i',
'\\1numeric', $line);
244 $line = preg_replace(
'/^float/i',
'numeric', $line);
245 $line = preg_replace(
'/(\s*)float/i',
'\\1numeric', $line);
249 $line = preg_replace(
'/(\s*)tms(\s*)timestamp/i',
'\\1tms timestamp without time zone DEFAULT now() NOT NULL', $line);
252 $line = preg_replace(
'/(\s*)DEFAULT(\s*)CURRENT_TIMESTAMP/i',
'\\1', $line);
255 $line = preg_replace(
'/(\s*)ON(\s*)UPDATE(\s*)CURRENT_TIMESTAMP/i',
'\\1', $line);
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);
263 $line = preg_replace(
'/\sAFTER [a-z0-9_]+/i',
'', $line);
266 $line = preg_replace(
'/ALTER TABLE [a-z0-9_]+\s+DROP INDEX/i',
'DROP INDEX', $line);
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];
275 if (preg_match(
'/ALTER TABLE ([a-z0-9_]+)\s+MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i', $line, $reg)) {
276 $line =
"-- ".$line.
" replaced by --\n";
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;
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];
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];
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];
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;";
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];
320 $tablename = $reg[1];
321 $line =
"-- ".$line.
" replaced by --\n";
322 $line .=
"CREATE ".(preg_match(
'/UNIQUE/', $reg[2]) ?
'UNIQUE ' :
'').
"INDEX ".$idxname.
" ON ".$tablename.
" (".$fieldlist.
")";
328 $line = str_replace(
" LIKE '",
" ILIKE '", $line, $count_like);
331 $line = preg_replace(
'/\s+(\(+\s*)([a-zA-Z0-9\-\_\.]+) ILIKE /',
' \1unaccent(\2) ILIKE ', $line);
334 $line = str_replace(
" LIKE BINARY '",
" LIKE '", $line);
337 $line = preg_replace(
'/^INSERT IGNORE/',
'INSERT', $line);
341 if (preg_match(
'/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', $line, $reg)) {
342 if ($reg[1] == $reg[2]) {
343 $line = preg_replace(
'/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i',
'DELETE FROM \\1 USING \\3', $line);
348 $line = preg_replace(
'/FROM\s*\((([a-z_]+)\s+as\s+([a-z_]+)\s*)\)/i',
'FROM \\1', $line);
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);
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);
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);
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);
371 if ($unescapeslashquot) {
372 $line = preg_replace(
"/\\\'/",
"''", $line);
393 if ($database == $this->database_name) {
411 public function connect($host, $login, $passwd, $name, $port = 0)
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);
429 if ((!empty($host) && $host ==
"socket") && !defined(
'NOLOCALSOCKETPGCONNECT')) {
430 $con_string =
"dbname='".$name.
"' user='".$login.
"' password='".$passwd.
"'";
432 $this->db = @pg_connect($con_string);
439 if (empty($this->db)) {
447 $con_string =
"host='".$host.
"' port='".$port.
"' dbname='".$name.
"' user='".$login.
"' password='".$passwd.
"'";
449 $this->db = @pg_connect($con_string);
451 print $e->getMessage();
457 $this->database_name = $name;
458 pg_set_error_verbosity($this->db, PGSQL_ERRORS_VERBOSE);
459 pg_query($this->db,
"set datestyle = 'ISO, YMD';");
472 $resql = $this->
query(
'SHOW server_version');
475 return $liste[
'server_version'];
487 return 'pgsql php driver';
499 if ($this->transaction_opened > 0) {
500 dol_syslog(get_class($this).
"::close Closing a connection with an opened transaction depth=".$this->transaction_opened, LOG_ERR);
502 $this->connected =
false;
503 return pg_close($this->db);
517 public function query($query, $usesavepoint = 0,
$type =
'auto', $result_mode = 0)
519 global $dolibarr_main_db_readonly;
521 $query = trim($query);
524 $query = $this->
convertSQLFromMysql($query,
$type, ($this->unescapeslashquot && $this->standard_conforming_strings));
531 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)) {
532 $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);
533 dol_syslog(
"Warning: Bad formed request converted into ".$query, LOG_WARNING);
540 if ($usesavepoint && $this->transaction_opened) {
541 @pg_query($this->db,
'SAVEPOINT mysavepoint');
544 if (!in_array($query, array(
'BEGIN',
'COMMIT',
'ROLLBACK'))) {
545 $SYSLOG_SQL_LIMIT = 10000;
546 dol_syslog(
'sql='.substr($query, 0, $SYSLOG_SQL_LIMIT), LOG_DEBUG);
552 if (!empty($dolibarr_main_db_readonly)) {
553 if (preg_match(
'/^(INSERT|UPDATE|REPLACE|DELETE|CREATE|ALTER|TRUNCATE|DROP)/i', $query)) {
554 $this->
lasterror =
'Application in read-only mode';
561 $ret = @pg_query($this->db, $query);
564 if (!preg_match(
"/^COMMIT/i", $query) && !preg_match(
"/^ROLLBACK/i", $query)) {
566 if ($this->
errno() !=
'DB_ERROR_25P02') {
572 dol_syslog(get_class($this).
"::query SQL Error query: ".$query, LOG_ERR);
574 dol_syslog(get_class($this).
"::query SQL Error message: ".$this->
lasterror.
" (".$this->lasterrno.
")", LOG_ERR);
575 dol_syslog(get_class($this).
"::query SQL Error usesavepoint = ".$usesavepoint, LOG_ERR);
578 if ($usesavepoint && $this->transaction_opened) {
579 @pg_query($this->db,
'ROLLBACK TO SAVEPOINT mysavepoint');
583 $this->_results = $ret;
600 if (!is_resource($resultset) && !is_object($resultset)) {
601 $resultset = $this->_results;
603 return pg_fetch_object($resultset);
617 if (!is_resource($resultset) && !is_object($resultset)) {
618 $resultset = $this->_results;
620 return pg_fetch_array($resultset);
634 if (!is_resource($resultset) && !is_object($resultset)) {
635 $resultset = $this->_results;
637 return pg_fetch_row($resultset);
652 if (!is_resource($resultset) && !is_object($resultset)) {
653 $resultset = $this->_results;
657 return pg_num_rows($resultset);
675 if (!is_resource($resultset) && !is_object($resultset)) {
676 $resultset = $this->_results;
680 return pg_affected_rows($resultset);
690 public function free($resultset =
null)
693 if (!is_resource($resultset) && !is_object($resultset)) {
694 $resultset = $this->_results;
697 if (is_resource($resultset) || is_object($resultset)) {
698 pg_free_result($resultset);
710 public function plimit($limit = 0, $offset = 0)
717 $limit =
$conf->liste_limit;
720 return " LIMIT ".$limit.
" OFFSET ".$offset.
" ";
722 return " LIMIT $limit ";
735 return pg_escape_string($this->db, $stringtoencode);
746 return str_replace(array(
'\\',
'_',
'%'), array(
'\\\\',
'\_',
'\%'), (
string) $stringtoencode);
757 public function ifsql($test, $resok, $resko)
759 return '(CASE WHEN '.$test.
' THEN '.$resok.
' ELSE '.$resko.
' END)';
770 public function regexpsql($subject, $pattern, $sqlstring = 0)
773 return "(". $subject .
" ~ '" . $this->
escape($pattern) .
"')";
776 return "('". $this->
escape($subject) .
"' ~ '" . $this->
escape($pattern) .
"')";
787 if (!$this->connected) {
789 return 'DB_ERROR_FAILED_TO_CONNECT';
792 $errorcode_map = array(
793 1004 =>
'DB_ERROR_CANNOT_CREATE',
794 1005 =>
'DB_ERROR_CANNOT_CREATE',
795 1006 =>
'DB_ERROR_CANNOT_CREATE',
796 1007 =>
'DB_ERROR_ALREADY_EXISTS',
797 1008 =>
'DB_ERROR_CANNOT_DROP',
798 1025 =>
'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
799 1044 =>
'DB_ERROR_ACCESSDENIED',
800 1046 =>
'DB_ERROR_NODBSELECTED',
801 1048 =>
'DB_ERROR_CONSTRAINT',
802 '42P07' =>
'DB_ERROR_TABLE_OR_KEY_ALREADY_EXISTS',
803 '42703' =>
'DB_ERROR_NOSUCHFIELD',
804 1060 =>
'DB_ERROR_COLUMN_ALREADY_EXISTS',
805 42701 =>
'DB_ERROR_COLUMN_ALREADY_EXISTS',
806 '42710' =>
'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
807 '23505' =>
'DB_ERROR_RECORD_ALREADY_EXISTS',
808 '42704' =>
'DB_ERROR_NO_INDEX_TO_DROP',
809 '42601' =>
'DB_ERROR_SYNTAX',
810 '42P16' =>
'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
811 1075 =>
'DB_ERROR_CANT_DROP_PRIMARY_KEY',
812 1091 =>
'DB_ERROR_NOSUCHFIELD',
813 1100 =>
'DB_ERROR_NOT_LOCKED',
814 1136 =>
'DB_ERROR_VALUE_COUNT_ON_ROW',
815 '42P01' =>
'DB_ERROR_NOSUCHTABLE',
816 '23503' =>
'DB_ERROR_NO_PARENT',
817 1217 =>
'DB_ERROR_CHILD_EXISTS',
818 1451 =>
'DB_ERROR_CHILD_EXISTS',
819 '42P04' =>
'DB_DATABASE_ALREADY_EXISTS'
822 $errorlabel = pg_last_error($this->db);
825 if (preg_match(
'/: *([0-9P]+):/', $errorlabel, $reg)) {
826 $errorcode = $reg[1];
827 if (isset($errorcode_map[$errorcode])) {
828 return $errorcode_map[$errorcode];
831 $errno = $errorcode ? $errorcode : $errorlabel;
832 return ($errno ?
'DB_ERROR_'.$errno :
'0');
851 return pg_last_error($this->db);
866 $result = pg_query($this->db,
"SELECT currval('".$tab.
"_".$fieldid.
"_seq')");
868 print pg_last_error($this->db);
872 $row = pg_fetch_result($result, 0, 0);
884 public function encrypt($fieldorvalue, $withQuotes = 1)
894 $return = $fieldorvalue;
895 return ($withQuotes ?
"'" :
"").$this->
escape($return).($withQuotes ?
"'" :
"");
946 public function DDLCreateDb($database, $charset =
'', $collation =
'', $owner =
'')
949 if (empty($charset)) {
952 if (empty($collation)) {
960 $sql =
"CREATE DATABASE ".$this->escape($database).
" OWNER '".$this->
escape($owner).
"' ENCODING '".$this->
escape((
string) $charset).
"'";
963 $ret = $this->
query($sql);
979 $listtables = array();
983 $tmptable = preg_replace(
'/[^a-z0-9\.\-\_%]/i',
'', $table);
985 $escapedlike =
" AND table_name LIKE '".$this->escape($tmptable).
"'";
987 $result = pg_query($this->db,
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'".$escapedlike.
" ORDER BY table_name");
989 while ($row = $this->
fetch_row($result)) {
990 $listtables[] = $row[0];
1007 $listtables = array();
1011 $tmptable = preg_replace(
'/[^a-z0-9\.\-\_%]/i',
'', $table);
1013 $escapedlike =
" AND table_name LIKE '".$this->escape($tmptable).
"'";
1015 $result = pg_query($this->db,
"SELECT table_name, table_type FROM information_schema.tables WHERE table_schema = 'public'".$escapedlike.
" ORDER BY table_name");
1017 while ($row = $this->
fetch_row($result)) {
1018 $listtables[] = $row;
1034 $infotables = array();
1037 $sql .=
" infcol.column_name as \"Column\",";
1038 $sql .=
" CASE WHEN infcol.character_maximum_length IS NOT NULL THEN infcol.udt_name || '('||infcol.character_maximum_length||')'";
1039 $sql .=
" ELSE infcol.udt_name";
1040 $sql .=
" END as \"Type\",";
1041 $sql .=
" infcol.collation_name as \"Collation\",";
1042 $sql .=
" infcol.is_nullable as \"Null\",";
1043 $sql .=
" '' as \"Key\",";
1044 $sql .=
" infcol.column_default as \"Default\",";
1045 $sql .=
" '' as \"Extra\",";
1046 $sql .=
" '' as \"Privileges\"";
1047 $sql .=
" FROM information_schema.columns infcol";
1048 $sql .=
" WHERE table_schema = 'public' ";
1049 $sql .=
" AND table_name = '".$this->escape($table).
"'";
1050 $sql .=
" ORDER BY ordinal_position;";
1052 $result = $this->
query($sql);
1054 while ($row = $this->
fetch_row($result)) {
1055 $infotables[] = $row;
1075 public function DDLCreateTable($table, $fields, $primary_key,
$type, $unique_keys =
null, $fulltext_keys =
null, $keys =
null)
1090 $sql =
"CREATE TABLE ".$this->sanitize($table).
"(";
1092 $sqlfields = array();
1093 foreach ($fields as $field_name => $field_desc) {
1094 $sqlfields[$i] = $this->
sanitize($field_name).
" ";
1095 $sqlfields[$i] .= $this->
sanitize($field_desc[
'type']);
1096 if (isset($field_desc[
'value']) && $field_desc[
'value'] !==
'') {
1097 $sqlfields[$i] .=
"(".$this->sanitize($field_desc[
'value']).
")";
1099 if (isset($field_desc[
'attribute']) && $field_desc[
'attribute'] !==
'') {
1100 $sqlfields[$i] .=
" ".$this->sanitize($field_desc[
'attribute']);
1102 if (isset($field_desc[
'default']) && $field_desc[
'default'] !==
'') {
1103 if (in_array($field_desc[
'type'], array(
'tinyint',
'smallint',
'int',
'double'))) {
1104 $sqlfields[$i] .=
" DEFAULT ".((float) $field_desc[
'default']);
1105 } elseif ($field_desc[
'default'] ==
'null' || $field_desc[
'default'] ==
'CURRENT_TIMESTAMP') {
1106 $sqlfields[$i] .=
" DEFAULT ".$this->sanitize($field_desc[
'default']);
1108 $sqlfields[$i] .=
" DEFAULT '".$this->escape($field_desc[
'default']).
"'";
1111 if (isset($field_desc[
'null']) && $field_desc[
'null'] !==
'') {
1112 $sqlfields[$i] .=
" ".$this->sanitize($field_desc[
'null'], 0, 0, 1);
1114 if (isset($field_desc[
'extra']) && $field_desc[
'extra'] !==
'') {
1115 $sqlfields[$i] .=
" ".$this->sanitize($field_desc[
'extra'], 0, 0, 1);
1117 if (!empty($primary_key) && $primary_key == $field_name) {
1118 $sqlfields[$i] .=
" AUTO_INCREMENT PRIMARY KEY";
1123 if (is_array($unique_keys)) {
1125 foreach ($unique_keys as $key => $value) {
1126 $sqluq[$i] =
"UNIQUE KEY '".$this->sanitize($key).
"' ('".$this->
escape($value).
"')";
1130 if (is_array($keys)) {
1132 foreach ($keys as $key => $value) {
1133 $sqlk[$i] =
"KEY ".$this->sanitize($key).
" (".$value.
")";
1137 $sql .= implode(
', ', $sqlfields);
1138 if ($unique_keys !=
"") {
1139 $sql .=
",".implode(
',', $sqluq);
1141 if (is_array($keys)) {
1142 $sql .=
",".implode(
',', $sqlk);
1147 if (!$this->
query($sql, 1)) {
1164 $tmptable = preg_replace(
'/[^a-z0-9\.\-\_]/i',
'', $table);
1166 $sql =
"DROP TABLE ".$this->sanitize($tmptable);
1168 if (!$this->
query($sql, 1)) {
1186 $sql =
"SELECT attname FROM pg_attribute, pg_type WHERE typname = '".$this->escape($table).
"' AND attrelid = typrelid";
1187 $sql .=
" AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', 'tableoid', 'xmin', 'xmax')";
1189 $sql .=
" AND attname = '".$this->escape($field).
"'";
1193 $this->_results = $this->
query($sql);
1194 return $this->_results;
1207 public function DDLAddField($table, $field_name, $field_desc, $field_position =
"")
1212 $sql =
"ALTER TABLE ".$this->sanitize($table).
" ADD ".$this->
sanitize($field_name).
" ";
1213 $sql .= $this->
sanitize($field_desc[
'type']);
1214 if (isset($field_desc[
'value']) && preg_match(
"/^[^\s]/i", $field_desc[
'value'])) {
1215 if (!in_array($field_desc[
'type'], array(
'tinyint',
'smallint',
'int',
'date',
'datetime')) && $field_desc[
'value']) {
1216 $sql .=
"(".$this->sanitize($field_desc[
'value']).
")";
1219 if (isset($field_desc[
'attribute']) && preg_match(
"/^[^\s]/i", $field_desc[
'attribute'])) {
1220 $sql .=
" ".$this->sanitize($field_desc[
'attribute']);
1222 if (isset($field_desc[
'null']) && preg_match(
"/^[^\s]/i", $field_desc[
'null'])) {
1223 if ($field_desc[
'null'] ==
'NOT NULL') {
1224 $sql .=
" ".$this->sanitize($field_desc[
'null'], 0, 0, 1);
1226 $sql .=
" ".$this->sanitize($field_desc[
'null']);
1229 if (isset($field_desc[
'default']) && preg_match(
"/^[^\s]/i", $field_desc[
'default'])) {
1230 if (in_array($field_desc[
'type'], array(
'tinyint',
'smallint',
'int',
'double'))) {
1231 $sql .=
" DEFAULT ".((float) $field_desc[
'default']);
1232 } elseif ($field_desc[
'default'] ==
'null' || $field_desc[
'default'] ==
'CURRENT_TIMESTAMP') {
1233 $sql .=
" DEFAULT ".$this->sanitize($field_desc[
'default']);
1235 $sql .=
" DEFAULT '".$this->escape($field_desc[
'default']).
"'";
1238 if (isset($field_desc[
'extra']) && preg_match(
"/^[^\s]/i", $field_desc[
'extra'])) {
1239 $sql .=
" ".$this->sanitize($field_desc[
'extra'], 0, 0, 1);
1241 $sql .=
" ".$this->sanitize($field_position, 0, 0, 1);
1244 if (!$this ->
query($sql)) {
1262 $sql =
"ALTER TABLE ".$this->sanitize($table);
1263 $sql .=
" ALTER COLUMN ".$this->sanitize($field_name).
" TYPE ".$this->
sanitize($field_desc[
'type']);
1264 if (isset($field_desc[
'value']) && preg_match(
"/^[^\s]/i", $field_desc[
'value'])) {
1265 if (!in_array($field_desc[
'type'], array(
'smallint',
'int',
'date',
'datetime')) && $field_desc[
'value']) {
1266 $sql .=
"(".$this->sanitize($field_desc[
'value']).
")";
1270 if (isset($field_desc[
'null']) && ($field_desc[
'null'] ==
'not null' || $field_desc[
'null'] ==
'NOT NULL')) {
1272 if ($field_desc[
'type'] ==
'varchar' || $field_desc[
'type'] ==
'text') {
1273 $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";
1274 $this->
query($sqlbis);
1275 } elseif (in_array($field_desc[
'type'], array(
'tinyint',
'smallint',
'int',
'double'))) {
1276 $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";
1277 $this->
query($sqlbis);
1281 if (isset($field_desc[
'default']) && $field_desc[
'default'] !=
'') {
1282 if (in_array($field_desc[
'type'], array(
'tinyint',
'smallint',
'int',
'double'))) {
1283 $sql .=
", ALTER COLUMN ".$this->sanitize($field_name).
" SET DEFAULT ".((float) $field_desc[
'default']);
1284 } elseif ($field_desc[
'type'] !=
'text') {
1285 $sql .=
", ALTER COLUMN ".$this->sanitize($field_name).
" SET DEFAULT '".$this->
escape($field_desc[
'default']).
"'";
1290 if (!$this->
query($sql)) {
1307 $tmp_field_name = preg_replace(
'/[^a-z0-9\.\-\_]/i',
'', $field_name);
1309 $sql =
"ALTER TABLE ".$this->sanitize($table).
" DROP COLUMN ".$this->
sanitize($tmp_field_name);
1310 if (!$this->
query($sql)) {
1327 public function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
1331 $sql =
"CREATE USER ".$this->sanitize($dolibarr_main_db_user).
" with password '".$this->
escape($dolibarr_main_db_pass).
"'";
1333 dol_syslog(get_class($this).
"::DDLCreateUser", LOG_DEBUG);
1334 $resql = $this->
query($sql);
1349 $resql = $this->
query(
'SHOW SERVER_ENCODING');
1352 return $liste[
'server_encoding'];
1365 $resql = $this->
query(
'SHOW SERVER_ENCODING');
1370 $liste[$i][
'charset'] = $obj->server_encoding;
1371 $liste[$i][
'description'] =
'Default database charset';
1374 $this->
free($resql);
1388 $resql = $this->
query(
'SHOW LC_COLLATE');
1391 return $liste[
'lc_collate'];
1404 $resql = $this->
query(
'SHOW LC_COLLATE');
1409 $liste[$i][
'collation'] = $obj->lc_collate;
1412 $this->
free($resql);
1426 $fullpathofdump =
'/pathtopgdump/pg_dump';
1428 if (file_exists(
'/usr/bin/pg_dump')) {
1429 $fullpathofdump =
'/usr/bin/pg_dump';
1432 $resql = $this->
query(
'SHOW data_directory');
1435 $basedir = $liste[
'data_directory'];
1436 $fullpathofdump = preg_replace(
'/data$/',
'bin', $basedir).
'/pg_dump';
1440 return $fullpathofdump;
1453 $fullpathofdump =
'/pathtopgrestore/'.$tool;
1455 if (file_exists(
'/usr/bin/'.$tool)) {
1456 $fullpathofdump =
'/usr/bin/'.$tool;
1459 $resql = $this->
query(
'SHOW data_directory');
1462 $basedir = $liste[
'data_directory'];
1463 $fullpathofdump = preg_replace(
'/data$/',
'bin', $basedir).
'/'.$tool;
1467 return $fullpathofdump;
1480 $resql =
'select name,setting from pg_settings';
1482 $resql .=
" WHERE name = '".$this->escape($filter).
"'";
1484 $resql = $this->
query($resql);
1487 $result[$obj->name] = $obj->setting;
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.
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.
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...