31require_once DOL_DOCUMENT_ROOT.
'/core/db/DoliDB.class.php';
56 public $unescapeslashquot =
false;
60 public $standard_conforming_strings =
false;
84 if (!empty($conf->db->character_set)) {
85 $this->forcecharset = $conf->db->character_set;
87 if (!empty($conf->db->dolibarr_main_db_collation)) {
88 $this->forcecollate = $conf->db->dolibarr_main_db_collation;
91 $this->database_user = $user;
92 $this->database_host = $host;
93 $this->database_port = $port;
95 $this->transaction_opened = 0;
99 if (!function_exists(
"pg_connect")) {
100 $this->connected =
false;
102 $this->
error =
"Pgsql PHP functions are not available in this version of PHP";
103 dol_syslog(get_class($this).
"::DoliDBPgsql : Pgsql PHP functions are not available in this version of PHP", LOG_ERR);
108 $this->connected =
false;
110 $this->
error = $langs->trans(
"ErrorWrongHostParameter");
111 dol_syslog(get_class($this).
"::DoliDBPgsql : Erreur Connect, wrong host parameters", LOG_ERR);
117 $this->db = $this->
connect($host, $user, $pass, $name, $port);
120 $this->connected =
true;
124 $this->connected =
false;
126 $this->
error =
'Host, login or password incorrect';
127 dol_syslog(get_class($this).
"::DoliDBPgsql : Erreur Connect ".$this->
error.
'. Failed to connect to host='.$host.
' port='.$port.
' user='.$user, LOG_ERR);
131 if ($this->connected && $name) {
133 $this->database_selected =
true;
134 $this->database_name = $name;
137 $this->database_selected =
false;
138 $this->database_name =
'';
141 dol_syslog(get_class($this).
"::DoliDBPgsql : Erreur Select_db ".$this->
error, LOG_ERR);
145 $this->database_selected =
false;
163 if (preg_match(
'/^--\s\$Id/i', $line)) {
167 if (preg_match(
'/^#/i', $line) || preg_match(
'/^$/i', $line) || preg_match(
'/^--/i', $line)) {
173 $line = preg_replace(
'/GROUP_CONCAT/i',
'STRING_AGG', $line);
174 $line = preg_replace(
'/ SEPARATOR/i',
',', $line);
175 $line = preg_replace(
'/STRING_AGG\(([^,\)]+)\)/i',
'STRING_AGG(\\1, \',\')', $line);
178 if (
$type ==
'auto') {
179 if (preg_match(
'/ALTER TABLE/i', $line)) {
181 } elseif (preg_match(
'/CREATE TABLE/i', $line)) {
183 } elseif (preg_match(
'/DROP TABLE/i', $line)) {
188 $line = preg_replace(
'/ as signed\)/i',
' as integer)', $line);
190 if (
$type ==
'dml') {
193 $line = preg_replace(
'/\s/',
' ', $line);
196 if (preg_match(
'/(ISAM|innodb)/i', $line)) {
197 $line = preg_replace(
'/\)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb).*;/i',
');', $line);
198 $line = preg_replace(
'/\)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb).*;/i',
');', $line);
199 $line = preg_replace(
'/,$/',
'', $line);
203 if (preg_match(
'/[\s\t\(]*(\w*)[\s\t]+int.*auto_increment/i', $line, $reg)) {
204 $newline = preg_replace(
'/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i',
'\\1 \\2 SERIAL PRIMARY KEY', $line);
209 if (preg_match(
'/[\s\t\(]*(\w*)[\s\t]+bigint.*auto_increment/i', $line, $reg)) {
210 $newline = preg_replace(
'/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+bigint.*auto_increment[^,]*/i',
'\\1 \\2 BIGSERIAL PRIMARY KEY', $line);
216 $line = preg_replace(
'/tinyint\(?[0-9]*\)?/',
'smallint', $line);
217 $line = preg_replace(
'/tinyint/i',
'smallint', $line);
220 $line = preg_replace(
'/(int\w+|smallint|bigint)\s+unsigned/i',
'\\1', $line);
223 $line = preg_replace(
'/\w*blob/i',
'text', $line);
226 $line = preg_replace(
'/tinytext/i',
'text', $line);
227 $line = preg_replace(
'/mediumtext/i',
'text', $line);
228 $line = preg_replace(
'/longtext/i',
'text', $line);
230 $line = preg_replace(
'/text\([0-9]+\)/i',
'text', $line);
234 $line = preg_replace(
'/datetime not null/i',
'datetime', $line);
235 $line = preg_replace(
'/datetime/i',
'timestamp', $line);
238 $line = preg_replace(
'/^double/i',
'numeric', $line);
239 $line = preg_replace(
'/(\s*)double/i',
'\\1numeric', $line);
241 $line = preg_replace(
'/^float/i',
'numeric', $line);
242 $line = preg_replace(
'/(\s*)float/i',
'\\1numeric', $line);
246 $line = preg_replace(
'/(\s*)tms(\s*)timestamp/i',
'\\1tms timestamp without time zone DEFAULT now() NOT NULL', $line);
249 $line = preg_replace(
'/(\s*)DEFAULT(\s*)CURRENT_TIMESTAMP/i',
'\\1', $line);
252 $line = preg_replace(
'/(\s*)ON(\s*)UPDATE(\s*)CURRENT_TIMESTAMP/i',
'\\1', $line);
255 if (preg_match(
'/unique index\s*\((\w+\s*,\s*\w+)\)/i', $line)) {
256 $line = preg_replace(
'/unique index\s*\((\w+\s*,\s*\w+)\)/i',
'UNIQUE\(\\1\)', $line);
260 $line = preg_replace(
'/\sAFTER [a-z0-9_]+/i',
'', $line);
263 $line = preg_replace(
'/ALTER TABLE [a-z0-9_]+\s+DROP INDEX/i',
'DROP INDEX', $line);
266 if (preg_match(
'/ALTER TABLE ([a-z0-9_]+)\s+CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i', $line, $reg)) {
267 $line =
"-- ".$line.
" replaced by --\n";
268 $line .=
"ALTER TABLE ".$reg[1].
" RENAME COLUMN ".$reg[2].
" TO ".$reg[3];
272 if (preg_match(
'/ALTER TABLE ([a-z0-9_]+)\s+MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i', $line, $reg)) {
273 $line =
"-- ".$line.
" replaced by --\n";
275 $newreg3 = preg_replace(
'/ DEFAULT NULL/i',
'', $newreg3);
276 $newreg3 = preg_replace(
'/ NOT NULL/i',
'', $newreg3);
277 $newreg3 = preg_replace(
'/ NULL/i',
'', $newreg3);
278 $newreg3 = preg_replace(
'/ DEFAULT 0/i',
'', $newreg3);
279 $newreg3 = preg_replace(
'/ DEFAULT \'?[0-9a-zA-Z_@]*\'?/i',
'', $newreg3);
280 $line .=
"ALTER TABLE ".$reg[1].
" ALTER COLUMN ".$reg[2].
" TYPE ".$newreg3;
286 if (preg_match(
'/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\((.*)$/i', $line, $reg)) {
287 $line =
"-- ".$line.
" replaced by --\n";
288 $line .=
"ALTER TABLE ".$reg[1].
" ADD PRIMARY KEY (".$reg[3];
293 if (preg_match(
'/ALTER\s+TABLE\s*(.*)\s*DROP\s+PRIMARY\s+KEY\s*([^;]+)$/i', $line, $reg)) {
294 $line =
"-- ".$line.
" replaced by --\n";
295 $line .=
"ALTER TABLE ".$reg[1].
" DROP CONSTRAINT ".$reg[2];
300 if (preg_match(
'/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i', $line, $reg)) {
301 $line =
"-- ".$line.
" replaced by --\n";
302 $line .=
"ALTER TABLE ".$reg[1].
" DROP CONSTRAINT ".$reg[2];
307 if (preg_match(
'/ALTER\s+TABLE\s+(.*)\s*ADD CONSTRAINT\s+(.*)\s*FOREIGN\s+KEY\s*(.*)$/i', $line, $reg)) {
308 $line = preg_replace(
'/;$/',
'', $line);
309 $line .=
" DEFERRABLE INITIALLY IMMEDIATE;";
314 if (preg_match(
'/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\(([\w,\s]+)\)/i', $line, $reg)) {
315 $fieldlist = $reg[4];
317 $tablename = $reg[1];
318 $line =
"-- ".$line.
" replaced by --\n";
319 $line .=
"CREATE ".(preg_match(
'/UNIQUE/', $reg[2]) ?
'UNIQUE ' :
'').
"INDEX ".$idxname.
" ON ".$tablename.
" (".$fieldlist.
")";
325 $line = str_replace(
' LIKE \'',
' ILIKE \'', $line, $count_like);
328 $line = preg_replace(
'/\s+(\(+\s*)([a-zA-Z0-9\-\_\.]+) ILIKE /',
' \1unaccent(\2) ILIKE ', $line);
331 $line = str_replace(
' LIKE BINARY \'',
' LIKE \'', $line);
334 $line = preg_replace(
'/^INSERT IGNORE/',
'INSERT', $line);
338 if (preg_match(
'/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', $line, $reg)) {
339 if ($reg[1] == $reg[2]) {
340 $line = preg_replace(
'/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i',
'DELETE FROM \\1 USING \\3', $line);
345 $line = preg_replace(
'/FROM\s*\((([a-z_]+)\s+as\s+([a-z_]+)\s*)\)/i',
'FROM \\1', $line);
349 $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 $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 $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 $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);
368 if ($unescapeslashquot) {
369 $line = preg_replace(
"/\\\'/",
"''", $line);
390 if ($database == $this->database_name) {
408 public function connect($host, $login, $passwd, $name, $port = 0)
415 $host = str_replace(array(
"\\",
"'"), array(
"\\\\",
"\\'"), $host);
416 $login = str_replace(array(
"\\",
"'"), array(
"\\\\",
"\\'"), $login);
417 $passwd = str_replace(array(
"\\",
"'"), array(
"\\\\",
"\\'"), $passwd);
418 $name = str_replace(array(
"\\",
"'"), array(
"\\\\",
"\\'"), $name);
419 $port = str_replace(array(
"\\",
"'"), array(
"\\\\",
"\\'"), $port);
426 if ((!empty($host) && $host ==
"socket") && !defined(
'NOLOCALSOCKETPGCONNECT')) {
427 $con_string =
"dbname='".$name.
"' user='".$login.
"' password='".$passwd.
"'";
429 $this->db = @pg_connect($con_string);
436 if (empty($this->db)) {
444 $con_string =
"host='".$host.
"' port='".$port.
"' dbname='".$name.
"' user='".$login.
"' password='".$passwd.
"'";
446 $this->db = @pg_connect($con_string);
448 print $e->getMessage();
454 $this->database_name = $name;
455 pg_set_error_verbosity($this->db, PGSQL_ERRORS_VERBOSE);
456 pg_query($this->db,
"set datestyle = 'ISO, YMD';");
469 $resql = $this->
query(
'SHOW server_version');
472 return $liste[
'server_version'];
484 return 'pgsql php driver';
496 if ($this->transaction_opened > 0) {
497 dol_syslog(get_class($this).
"::close Closing a connection with an opened transaction depth=".$this->transaction_opened, LOG_ERR);
499 $this->connected =
false;
500 return pg_close($this->db);
514 public function query($query, $usesavepoint = 0,
$type =
'auto', $result_mode = 0)
516 global $conf, $dolibarr_main_db_readonly;
518 $query = trim($query);
521 $query = $this->
convertSQLFromMysql($query,
$type, ($this->unescapeslashquot && $this->standard_conforming_strings));
528 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)) {
529 $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);
530 dol_syslog(
"Warning: Bad formed request converted into ".$query, LOG_WARNING);
537 if ($usesavepoint && $this->transaction_opened) {
538 @pg_query($this->db,
'SAVEPOINT mysavepoint');
541 if (!in_array($query, array(
'BEGIN',
'COMMIT',
'ROLLBACK'))) {
542 $SYSLOG_SQL_LIMIT = 10000;
543 dol_syslog(
'sql='.substr($query, 0, $SYSLOG_SQL_LIMIT), LOG_DEBUG);
549 if (!empty($dolibarr_main_db_readonly)) {
550 if (preg_match(
'/^(INSERT|UPDATE|REPLACE|DELETE|CREATE|ALTER|TRUNCATE|DROP)/i', $query)) {
551 $this->
lasterror =
'Application in read-only mode';
558 $ret = @pg_query($this->db, $query);
561 if (!preg_match(
"/^COMMIT/i", $query) && !preg_match(
"/^ROLLBACK/i", $query)) {
563 if ($this->
errno() !=
'DB_ERROR_25P02') {
569 dol_syslog(get_class($this).
"::query SQL Error query: ".$query, LOG_ERR);
571 dol_syslog(get_class($this).
"::query SQL Error message: ".$this->
lasterror.
" (".$this->lasterrno.
")", LOG_ERR);
572 dol_syslog(get_class($this).
"::query SQL Error usesavepoint = ".$usesavepoint, LOG_ERR);
575 if ($usesavepoint && $this->transaction_opened) {
576 @pg_query($this->db,
'ROLLBACK TO SAVEPOINT mysavepoint');
580 $this->_results = $ret;
597 if (!is_resource($resultset) && !is_object($resultset)) {
598 $resultset = $this->_results;
600 return pg_fetch_object($resultset);
614 if (!is_resource($resultset) && !is_object($resultset)) {
615 $resultset = $this->_results;
617 return pg_fetch_array($resultset);
631 if (!is_resource($resultset) && !is_object($resultset)) {
632 $resultset = $this->_results;
634 return pg_fetch_row($resultset);
649 if (!is_resource($resultset) && !is_object($resultset)) {
650 $resultset = $this->_results;
652 return pg_num_rows($resultset);
667 if (!is_resource($resultset) && !is_object($resultset)) {
668 $resultset = $this->_results;
672 return pg_affected_rows($resultset);
682 public function free($resultset =
null)
685 if (!is_resource($resultset) && !is_object($resultset)) {
686 $resultset = $this->_results;
689 if (is_resource($resultset) || is_object($resultset)) {
690 pg_free_result($resultset);
702 public function plimit($limit = 0, $offset = 0)
709 $limit = $conf->liste_limit;
712 return " LIMIT ".$limit.
" OFFSET ".$offset.
" ";
714 return " LIMIT $limit ";
727 return pg_escape_string($stringtoencode);
738 return str_replace(array(
'\\',
'_',
'%'), array(
'\\\\',
'\_',
'\%'), (
string) $stringtoencode);
749 public function ifsql($test, $resok, $resko)
751 return '(CASE WHEN '.$test.
' THEN '.$resok.
' ELSE '.$resko.
' END)';
762 public function regexpsql($subject, $pattern, $sqlstring = 0)
765 return "(". $subject .
" ~ '" . $pattern .
"')";
768 return "('". $subject .
"' ~ '" . $pattern .
"')";
779 if (!$this->connected) {
781 return 'DB_ERROR_FAILED_TO_CONNECT';
784 $errorcode_map = array(
785 1004 =>
'DB_ERROR_CANNOT_CREATE',
786 1005 =>
'DB_ERROR_CANNOT_CREATE',
787 1006 =>
'DB_ERROR_CANNOT_CREATE',
788 1007 =>
'DB_ERROR_ALREADY_EXISTS',
789 1008 =>
'DB_ERROR_CANNOT_DROP',
790 1025 =>
'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
791 1044 =>
'DB_ERROR_ACCESSDENIED',
792 1046 =>
'DB_ERROR_NODBSELECTED',
793 1048 =>
'DB_ERROR_CONSTRAINT',
794 '42P07' =>
'DB_ERROR_TABLE_OR_KEY_ALREADY_EXISTS',
795 '42703' =>
'DB_ERROR_NOSUCHFIELD',
796 1060 =>
'DB_ERROR_COLUMN_ALREADY_EXISTS',
797 42701=>
'DB_ERROR_COLUMN_ALREADY_EXISTS',
798 '42710' =>
'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
799 '23505' =>
'DB_ERROR_RECORD_ALREADY_EXISTS',
800 '42704' =>
'DB_ERROR_NO_INDEX_TO_DROP',
801 '42601' =>
'DB_ERROR_SYNTAX',
802 '42P16' =>
'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
803 1075 =>
'DB_ERROR_CANT_DROP_PRIMARY_KEY',
804 1091 =>
'DB_ERROR_NOSUCHFIELD',
805 1100 =>
'DB_ERROR_NOT_LOCKED',
806 1136 =>
'DB_ERROR_VALUE_COUNT_ON_ROW',
807 '42P01' =>
'DB_ERROR_NOSUCHTABLE',
808 '23503' =>
'DB_ERROR_NO_PARENT',
809 1217 =>
'DB_ERROR_CHILD_EXISTS',
810 1451 =>
'DB_ERROR_CHILD_EXISTS',
811 '42P04' =>
'DB_DATABASE_ALREADY_EXISTS'
814 $errorlabel = pg_last_error($this->db);
817 if (preg_match(
'/: *([0-9P]+):/', $errorlabel, $reg)) {
818 $errorcode = $reg[1];
819 if (isset($errorcode_map[$errorcode])) {
820 return $errorcode_map[$errorcode];
823 $errno = $errorcode ? $errorcode : $errorlabel;
824 return ($errno ?
'DB_ERROR_'.$errno :
'0');
843 return pg_last_error($this->db);
858 $result = pg_query($this->db,
"SELECT currval('".$tab.
"_".$fieldid.
"_seq')");
860 print pg_last_error($this->db);
864 $row = pg_fetch_result($result, 0, 0);
876 public function encrypt($fieldorvalue, $withQuotes = 1)
886 $return = $fieldorvalue;
887 return ($withQuotes ?
"'" :
"").$this->
escape($return).($withQuotes ?
"'" :
"");
938 public function DDLCreateDb($database, $charset =
'', $collation =
'', $owner =
'')
941 if (empty($charset)) {
944 if (empty($collation)) {
952 $sql =
"CREATE DATABASE ".$this->escape($database).
" OWNER '".$this->
escape($owner).
"' ENCODING '".$this->
escape($charset).
"'";
954 $ret = $this->
query($sql);
969 $listtables = array();
973 $tmptable = preg_replace(
'/[^a-z0-9\.\-\_%]/i',
'', $table);
975 $escapedlike =
" AND table_name LIKE '".$this->escape($tmptable).
"'";
977 $result = pg_query($this->db,
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'".$escapedlike.
" ORDER BY table_name");
979 while ($row = $this->
fetch_row($result)) {
980 $listtables[] = $row[0];
997 $listtables = array();
1001 $tmptable = preg_replace(
'/[^a-z0-9\.\-\_%]/i',
'', $table);
1003 $escapedlike =
" AND table_name LIKE '".$this->escape($tmptable).
"'";
1005 $result = pg_query($this->db,
"SELECT table_name, table_type FROM information_schema.tables WHERE table_schema = 'public'".$escapedlike.
" ORDER BY table_name");
1007 while ($row = $this->
fetch_row($result)) {
1008 $listtables[] = $row;
1025 $infotables = array();
1028 $sql .=
" infcol.column_name as \"Column\",";
1029 $sql .=
" CASE WHEN infcol.character_maximum_length IS NOT NULL THEN infcol.udt_name || '('||infcol.character_maximum_length||')'";
1030 $sql .=
" ELSE infcol.udt_name";
1031 $sql .=
" END as \"Type\",";
1032 $sql .=
" infcol.collation_name as \"Collation\",";
1033 $sql .=
" infcol.is_nullable as \"Null\",";
1034 $sql .=
" '' as \"Key\",";
1035 $sql .=
" infcol.column_default as \"Default\",";
1036 $sql .=
" '' as \"Extra\",";
1037 $sql .=
" '' as \"Privileges\"";
1038 $sql .=
" FROM information_schema.columns infcol";
1039 $sql .=
" WHERE table_schema = 'public' ";
1040 $sql .=
" AND table_name = '".$this->escape($table).
"'";
1041 $sql .=
" ORDER BY ordinal_position;";
1044 $result = $this->
query($sql);
1046 while ($row = $this->
fetch_row($result)) {
1047 $infotables[] = $row;
1067 public function DDLCreateTable($table, $fields, $primary_key,
$type, $unique_keys =
null, $fulltext_keys =
null, $keys =
null)
1074 $sql =
"create table ".$table.
"(";
1076 foreach ($fields as $field_name => $field_desc) {
1077 $sqlfields[$i] = $field_name.
" ";
1078 $sqlfields[$i] .= $field_desc[
'type'];
1079 if (preg_match(
"/^[^\s]/i", $field_desc[
'value'])) {
1080 $sqlfields[$i] .=
"(".$field_desc[
'value'].
")";
1081 } elseif (preg_match(
"/^[^\s]/i", $field_desc[
'attribute'])) {
1082 $sqlfields[$i] .=
" ".$field_desc[
'attribute'];
1083 } elseif (preg_match(
"/^[^\s]/i", $field_desc[
'default'])) {
1084 if (preg_match(
"/null/i", $field_desc[
'default'])) {
1085 $sqlfields[$i] .=
" default ".$field_desc[
'default'];
1087 $sqlfields[$i] .=
" default '".$this->escape($field_desc[
'default']).
"'";
1089 } elseif (preg_match(
"/^[^\s]/i", $field_desc[
'null'])) {
1090 $sqlfields[$i] .=
" ".$field_desc[
'null'];
1091 } elseif (preg_match(
"/^[^\s]/i", $field_desc[
'extra'])) {
1092 $sqlfields[$i] .=
" ".$field_desc[
'extra'];
1096 if ($primary_key !=
"") {
1097 $pk =
"primary key(".$primary_key.
")";
1100 if (is_array($unique_keys)) {
1102 foreach ($unique_keys as $key => $value) {
1103 $sqluq[$i] =
"UNIQUE KEY '".$key.
"' ('".$this->
escape($value).
"')";
1107 if (is_array($keys)) {
1109 foreach ($keys as $key => $value) {
1110 $sqlk[$i] =
"KEY ".$key.
" (".$value.
")";
1114 $sql .= implode(
',', $sqlfields);
1115 if ($primary_key !=
"") {
1118 if (is_array($unique_keys)) {
1119 $sql .=
",".implode(
',', $sqluq);
1121 if (is_array($keys)) {
1122 $sql .=
",".implode(
',', $sqlk);
1124 $sql .=
") type=".$type;
1127 if (!$this->
query($sql)) {
1144 $tmptable = preg_replace(
'/[^a-z0-9\.\-\_]/i',
'', $table);
1146 $sql =
"DROP TABLE ".$tmptable;
1148 if (!$this->
query($sql)) {
1165 public function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
1169 $sql =
"CREATE USER ".$this->escape($dolibarr_main_db_user).
" with password '".$this->
escape($dolibarr_main_db_pass).
"'";
1171 dol_syslog(get_class($this).
"::DDLCreateUser", LOG_DEBUG);
1172 $resql = $this->
query($sql);
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')";
1194 $sql .=
" AND attname = '".$this->escape($field).
"'";
1198 $this->_results = $this->
query($sql);
1199 return $this->_results;
1212 public function DDLAddField($table, $field_name, $field_desc, $field_position =
"")
1217 $sql =
"ALTER TABLE ".$table.
" ADD ".$field_name.
" ";
1218 $sql .= $field_desc[
'type'];
1219 if (preg_match(
"/^[^\s]/i", $field_desc[
'value'])) {
1220 if (!in_array($field_desc[
'type'], array(
'smallint',
'int',
'date',
'datetime')) && $field_desc[
'value']) {
1221 $sql .=
"(".$field_desc[
'value'].
")";
1224 if (preg_match(
"/^[^\s]/i", $field_desc[
'attribute'])) {
1225 $sql .=
" ".$field_desc[
'attribute'];
1227 if (preg_match(
"/^[^\s]/i", $field_desc[
'null'])) {
1228 $sql .=
" ".$field_desc[
'null'];
1230 if (preg_match(
"/^[^\s]/i", $field_desc[
'default'])) {
1231 if (preg_match(
"/null/i", $field_desc[
'default'])) {
1232 $sql .=
" default ".$field_desc[
'default'];
1234 $sql .=
" default '".$this->escape($field_desc[
'default']).
"'";
1237 if (preg_match(
"/^[^\s]/i", $field_desc[
'extra'])) {
1238 $sql .=
" ".$field_desc[
'extra'];
1240 $sql .=
" ".$field_position;
1243 if (!$this ->
query($sql)) {
1261 $sql =
"ALTER TABLE ".$table;
1262 $sql .=
" ALTER COLUMN ".$this->escape($field_name).
" TYPE ".$field_desc[
'type'];
1263 if (preg_match(
"/^[^\s]/i", $field_desc[
'value'])) {
1264 if (!in_array($field_desc[
'type'], array(
'smallint',
'int',
'date',
'datetime')) && $field_desc[
'value']) {
1265 $sql .=
"(".$field_desc[
'value'].
")";
1269 if ($field_desc[
'null'] ==
'not null' || $field_desc[
'null'] ==
'NOT NULL') {
1271 if ($field_desc[
'type'] ==
'varchar' || $field_desc[
'type'] ==
'text') {
1272 $sqlbis =
"UPDATE ".$table.
" SET ".$this->
escape($field_name).
" = '".$this->
escape(isset($field_desc[
'default']) ? $field_desc[
'default'] :
'').
"' WHERE ".$this->
escape($field_name).
" IS NULL";
1273 $this->
query($sqlbis);
1274 } elseif ($field_desc[
'type'] ==
'tinyint' || $field_desc[
'type'] ==
'int') {
1275 $sqlbis =
"UPDATE ".$table.
" SET ".$this->
escape($field_name).
" = ".((int) $this->
escape(isset($field_desc[
'default']) ? $field_desc[
'default'] : 0)).
" WHERE ".$this->
escape($field_name).
" IS NULL";
1276 $this->
query($sqlbis);
1280 if (isset($field_desc[
'default']) && $field_desc[
'default'] !=
'') {
1281 if ($field_desc[
'type'] ==
'double' || $field_desc[
'type'] ==
'tinyint' || $field_desc[
'type'] ==
'int') {
1282 $sql .=
", ALTER COLUMN ".$this->escape($field_name).
" SET DEFAULT ".((float) $field_desc[
'default']);
1283 } elseif ($field_desc[
'type'] !=
'text') {
1284 $sql .=
", ALTER COLUMN ".$this->escape($field_name).
" SET DEFAULT '".$this->
escape($field_desc[
'default']).
"'";
1289 if (!$this->
query($sql)) {
1306 $tmp_field_name = preg_replace(
'/[^a-z0-9\.\-\_]/i',
'', $field_name);
1308 $sql =
"ALTER TABLE ".$table.
" DROP COLUMN ".$tmp_field_name;
1309 if (!$this->
query($sql)) {
1323 $resql = $this->
query(
'SHOW SERVER_ENCODING');
1326 return $liste[
'server_encoding'];
1339 $resql = $this->
query(
'SHOW SERVER_ENCODING');
1344 $liste[$i][
'charset'] = $obj->server_encoding;
1345 $liste[$i][
'description'] =
'Default database charset';
1348 $this->
free($resql);
1362 $resql = $this->
query(
'SHOW LC_COLLATE');
1365 return $liste[
'lc_collate'];
1378 $resql = $this->
query(
'SHOW LC_COLLATE');
1383 $liste[$i][
'collation'] = $obj->lc_collate;
1386 $this->
free($resql);
1400 $fullpathofdump =
'/pathtopgdump/pg_dump';
1402 if (file_exists(
'/usr/bin/pg_dump')) {
1403 $fullpathofdump =
'/usr/bin/pg_dump';
1406 $resql = $this->
query(
'SHOW data_directory');
1409 $basedir = $liste[
'data_directory'];
1410 $fullpathofdump = preg_replace(
'/data$/',
'bin', $basedir).
'/pg_dump';
1414 return $fullpathofdump;
1427 $fullpathofdump =
'/pathtopgrestore/'.$tool;
1429 if (file_exists(
'/usr/bin/'.$tool)) {
1430 $fullpathofdump =
'/usr/bin/'.$tool;
1433 $resql = $this->
query(
'SHOW data_directory');
1436 $basedir = $liste[
'data_directory'];
1437 $fullpathofdump = preg_replace(
'/data$/',
'bin', $basedir).
'/'.$tool;
1441 return $fullpathofdump;
1454 $resql =
'select name,setting from pg_settings';
1456 $resql .=
" WHERE name = '".$this->escape($filter).
"'";
1458 $resql = $this->
query($resql);
1461 $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()
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 connexion 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 Ici postgresql n'a aucune fonction equivalente de mysql_select_db On compare juste ...
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 connexion.
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 into a table.
connect($host, $login, $passwd, $name, $port=0)
Connexion 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 connexion.
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 dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.