pgsql.class.php 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465
  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. *
  12. * This program is free software; you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License as published by
  14. * the Free Software Foundation; either version 3 of the License, or
  15. * (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU General Public License
  23. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  24. */
  25. /**
  26. * \file htdocs/core/db/pgsql.class.php
  27. * \brief Fichier de la classe permettant de gerer une base pgsql
  28. */
  29. require_once DOL_DOCUMENT_ROOT.'/core/db/DoliDB.class.php';
  30. /**
  31. * Class to drive a Postgresql database for Dolibarr
  32. */
  33. class DoliDBPgsql extends DoliDB
  34. {
  35. //! Database type
  36. public $type = 'pgsql'; // Name of manager
  37. //! Database label
  38. const LABEL = 'PostgreSQL'; // Label of manager
  39. //! Charset
  40. public $forcecharset = 'UTF8'; // Can't be static as it may be forced with a dynamic value
  41. //! Collate used to force collate when creating database
  42. public $forcecollate = ''; // Can't be static as it may be forced with a dynamic value
  43. //! Version min database
  44. const VERSIONMIN = '9.0.0'; // Version min database
  45. /** @var resource|boolean Resultset of last query */
  46. private $_results;
  47. public $unescapeslashquot;
  48. public $standard_conforming_strings;
  49. /**
  50. * Constructor.
  51. * This create an opened connexion to a database server and eventually to a database
  52. *
  53. * @param string $type Type of database (mysql, pgsql...)
  54. * @param string $host Address of database server
  55. * @param string $user Nom de l'utilisateur autorise
  56. * @param string $pass Mot de passe
  57. * @param string $name Nom de la database
  58. * @param int $port Port of database server
  59. */
  60. public function __construct($type, $host, $user, $pass, $name = '', $port = 0)
  61. {
  62. global $conf, $langs;
  63. // Note that having "static" property for "$forcecharset" and "$forcecollate" will make error here in strict mode, so they are not static
  64. if (!empty($conf->db->character_set)) {
  65. $this->forcecharset = $conf->db->character_set;
  66. }
  67. if (!empty($conf->db->dolibarr_main_db_collation)) {
  68. $this->forcecollate = $conf->db->dolibarr_main_db_collation;
  69. }
  70. $this->database_user = $user;
  71. $this->database_host = $host;
  72. $this->database_port = $port;
  73. $this->transaction_opened = 0;
  74. //print "Name DB: $host,$user,$pass,$name<br>";
  75. if (!function_exists("pg_connect")) {
  76. $this->connected = false;
  77. $this->ok = false;
  78. $this->error = "Pgsql PHP functions are not available in this version of PHP";
  79. dol_syslog(get_class($this)."::DoliDBPgsql : Pgsql PHP functions are not available in this version of PHP", LOG_ERR);
  80. return $this->ok;
  81. }
  82. if (!$host) {
  83. $this->connected = false;
  84. $this->ok = false;
  85. $this->error = $langs->trans("ErrorWrongHostParameter");
  86. dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Connect, wrong host parameters", LOG_ERR);
  87. return $this->ok;
  88. }
  89. // Essai connexion serveur
  90. //print "$host, $user, $pass, $name, $port";
  91. $this->db = $this->connect($host, $user, $pass, $name, $port);
  92. if ($this->db) {
  93. $this->connected = true;
  94. $this->ok = true;
  95. } else {
  96. // host, login ou password incorrect
  97. $this->connected = false;
  98. $this->ok = false;
  99. $this->error = 'Host, login or password incorrect';
  100. dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Connect ".$this->error.'. Failed to connect to host='.$host.' port='.$port.' user='.$user, LOG_ERR);
  101. }
  102. // Si connexion serveur ok et si connexion base demandee, on essaie connexion base
  103. if ($this->connected && $name) {
  104. if ($this->select_db($name)) {
  105. $this->database_selected = true;
  106. $this->database_name = $name;
  107. $this->ok = true;
  108. } else {
  109. $this->database_selected = false;
  110. $this->database_name = '';
  111. $this->ok = false;
  112. $this->error = $this->error();
  113. dol_syslog(get_class($this)."::DoliDBPgsql : Erreur Select_db ".$this->error, LOG_ERR);
  114. }
  115. } else {
  116. // Pas de selection de base demandee, ok ou ko
  117. $this->database_selected = false;
  118. }
  119. return $this->ok;
  120. }
  121. /**
  122. * Convert a SQL request in Mysql syntax to native syntax
  123. *
  124. * @param string $line SQL request line to convert
  125. * @param string $type Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
  126. * @param bool $unescapeslashquot Unescape slash quote with quote quote
  127. * @return string SQL request line converted
  128. */
  129. public static function convertSQLFromMysql($line, $type = 'auto', $unescapeslashquot = false)
  130. {
  131. global $conf;
  132. // Removed empty line if this is a comment line for SVN tagging
  133. if (preg_match('/^--\s\$Id/i', $line)) {
  134. return '';
  135. }
  136. // Return line if this is a comment
  137. if (preg_match('/^#/i', $line) || preg_match('/^$/i', $line) || preg_match('/^--/i', $line)) {
  138. return $line;
  139. }
  140. if ($line != "") {
  141. // group_concat support (PgSQL >= 9.0)
  142. // Replace group_concat(x) or group_concat(x SEPARATOR ',') with string_agg(x, ',')
  143. $line = preg_replace('/GROUP_CONCAT/i', 'STRING_AGG', $line);
  144. $line = preg_replace('/ SEPARATOR/i', ',', $line);
  145. $line = preg_replace('/STRING_AGG\(([^,\)]+)\)/i', 'STRING_AGG(\\1, \',\')', $line);
  146. //print $line."\n";
  147. if ($type == 'auto') {
  148. if (preg_match('/ALTER TABLE/i', $line)) {
  149. $type = 'dml';
  150. } elseif (preg_match('/CREATE TABLE/i', $line)) {
  151. $type = 'dml';
  152. } elseif (preg_match('/DROP TABLE/i', $line)) {
  153. $type = 'dml';
  154. }
  155. }
  156. $line = preg_replace('/ as signed\)/i', ' as integer)', $line);
  157. if ($type == 'dml') {
  158. $reg = array();
  159. $line = preg_replace('/\s/', ' ', $line); // Replace tabulation with space
  160. // we are inside create table statement so lets process datatypes
  161. if (preg_match('/(ISAM|innodb)/i', $line)) { // end of create table sequence
  162. $line = preg_replace('/\)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb).*;/i', ');', $line);
  163. $line = preg_replace('/\)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb).*;/i', ');', $line);
  164. $line = preg_replace('/,$/', '', $line);
  165. }
  166. // Process case: "CREATE TABLE llx_mytable(rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY,code..."
  167. if (preg_match('/[\s\t\(]*(\w*)[\s\t]+int.*auto_increment/i', $line, $reg)) {
  168. $newline = preg_replace('/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i', '\\1 \\2 SERIAL PRIMARY KEY', $line);
  169. //$line = "-- ".$line." replaced by --\n".$newline;
  170. $line = $newline;
  171. }
  172. if (preg_match('/[\s\t\(]*(\w*)[\s\t]+bigint.*auto_increment/i', $line, $reg)) {
  173. $newline = preg_replace('/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+bigint.*auto_increment[^,]*/i', '\\1 \\2 BIGSERIAL PRIMARY KEY', $line);
  174. //$line = "-- ".$line." replaced by --\n".$newline;
  175. $line = $newline;
  176. }
  177. // tinyint type conversion
  178. $line = preg_replace('/tinyint\(?[0-9]*\)?/', 'smallint', $line);
  179. $line = preg_replace('/tinyint/i', 'smallint', $line);
  180. // nuke unsigned
  181. $line = preg_replace('/(int\w+|smallint|bigint)\s+unsigned/i', '\\1', $line);
  182. // blob -> text
  183. $line = preg_replace('/\w*blob/i', 'text', $line);
  184. // tinytext/mediumtext -> text
  185. $line = preg_replace('/tinytext/i', 'text', $line);
  186. $line = preg_replace('/mediumtext/i', 'text', $line);
  187. $line = preg_replace('/longtext/i', 'text', $line);
  188. $line = preg_replace('/text\([0-9]+\)/i', 'text', $line);
  189. // change not null datetime field to null valid ones
  190. // (to support remapping of "zero time" to null
  191. $line = preg_replace('/datetime not null/i', 'datetime', $line);
  192. $line = preg_replace('/datetime/i', 'timestamp', $line);
  193. // double -> numeric
  194. $line = preg_replace('/^double/i', 'numeric', $line);
  195. $line = preg_replace('/(\s*)double/i', '\\1numeric', $line);
  196. // float -> numeric
  197. $line = preg_replace('/^float/i', 'numeric', $line);
  198. $line = preg_replace('/(\s*)float/i', '\\1numeric', $line);
  199. //Check tms timestamp field case (in Mysql this field is defautled to now and
  200. // on update defaulted by now
  201. $line = preg_replace('/(\s*)tms(\s*)timestamp/i', '\\1tms timestamp without time zone DEFAULT now() NOT NULL', $line);
  202. // nuke DEFAULT CURRENT_TIMESTAMP
  203. $line = preg_replace('/(\s*)DEFAULT(\s*)CURRENT_TIMESTAMP/i', '\\1', $line);
  204. // nuke ON UPDATE CURRENT_TIMESTAMP
  205. $line = preg_replace('/(\s*)ON(\s*)UPDATE(\s*)CURRENT_TIMESTAMP/i', '\\1', $line);
  206. // unique index(field1,field2)
  207. if (preg_match('/unique index\s*\((\w+\s*,\s*\w+)\)/i', $line)) {
  208. $line = preg_replace('/unique index\s*\((\w+\s*,\s*\w+)\)/i', 'UNIQUE\(\\1\)', $line);
  209. }
  210. // We remove end of requests "AFTER fieldxxx"
  211. $line = preg_replace('/\sAFTER [a-z0-9_]+/i', '', $line);
  212. // We remove start of requests "ALTER TABLE tablexxx" if this is a DROP INDEX
  213. $line = preg_replace('/ALTER TABLE [a-z0-9_]+\s+DROP INDEX/i', 'DROP INDEX', $line);
  214. // Translate order to rename fields
  215. if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i', $line, $reg)) {
  216. $line = "-- ".$line." replaced by --\n";
  217. $line .= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
  218. }
  219. // Translate order to modify field format
  220. if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i', $line, $reg)) {
  221. $line = "-- ".$line." replaced by --\n";
  222. $newreg3 = $reg[3];
  223. $newreg3 = preg_replace('/ DEFAULT NULL/i', '', $newreg3);
  224. $newreg3 = preg_replace('/ NOT NULL/i', '', $newreg3);
  225. $newreg3 = preg_replace('/ NULL/i', '', $newreg3);
  226. $newreg3 = preg_replace('/ DEFAULT 0/i', '', $newreg3);
  227. $newreg3 = preg_replace('/ DEFAULT \'?[0-9a-zA-Z_@]*\'?/i', '', $newreg3);
  228. $line .= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3;
  229. // TODO Add alter to set default value or null/not null if there is this in $reg[3]
  230. }
  231. // alter table add primary key (field1, field2 ...) -> We remove the primary key name not accepted by PostGreSQL
  232. // ALTER TABLE llx_dolibarr_modules ADD PRIMARY KEY pk_dolibarr_modules (numero, entity)
  233. if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\((.*)$/i', $line, $reg)) {
  234. $line = "-- ".$line." replaced by --\n";
  235. $line .= "ALTER TABLE ".$reg[1]." ADD PRIMARY KEY (".$reg[3];
  236. }
  237. // Translate order to drop primary keys
  238. // ALTER TABLE llx_dolibarr_modules DROP PRIMARY KEY pk_xxx
  239. if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+PRIMARY\s+KEY\s*([^;]+)$/i', $line, $reg)) {
  240. $line = "-- ".$line." replaced by --\n";
  241. $line .= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
  242. }
  243. // Translate order to drop foreign keys
  244. // ALTER TABLE llx_dolibarr_modules DROP FOREIGN KEY fk_xxx
  245. if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i', $line, $reg)) {
  246. $line = "-- ".$line." replaced by --\n";
  247. $line .= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
  248. }
  249. // Translate order to add foreign keys
  250. // ALTER TABLE llx_tablechild ADD CONSTRAINT fk_tablechild_fk_fieldparent FOREIGN KEY (fk_fieldparent) REFERENCES llx_tableparent (rowid)
  251. if (preg_match('/ALTER\s+TABLE\s+(.*)\s*ADD CONSTRAINT\s+(.*)\s*FOREIGN\s+KEY\s*(.*)$/i', $line, $reg)) {
  252. $line = preg_replace('/;$/', '', $line);
  253. $line .= " DEFERRABLE INITIALLY IMMEDIATE;";
  254. }
  255. // alter table add [unique] [index] (field1, field2 ...)
  256. // ALTER TABLE llx_accountingaccount ADD INDEX idx_accountingaccount_fk_pcg_version (fk_pcg_version)
  257. if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\(([\w,\s]+)\)/i', $line, $reg)) {
  258. $fieldlist = $reg[4];
  259. $idxname = $reg[3];
  260. $tablename = $reg[1];
  261. $line = "-- ".$line." replaced by --\n";
  262. $line .= "CREATE ".(preg_match('/UNIQUE/', $reg[2]) ? 'UNIQUE ' : '')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")";
  263. }
  264. }
  265. // To have postgresql case sensitive
  266. $count_like = 0;
  267. $line = str_replace(' LIKE \'', ' ILIKE \'', $line, $count_like);
  268. if (!empty($conf->global->PSQL_USE_UNACCENT) && $count_like > 0) {
  269. // @see https://docs.postgresql.fr/11/unaccent.html : 'unaccent()' function must be installed before
  270. $line = preg_replace('/\s+(\(+\s*)([a-zA-Z0-9\-\_\.]+) ILIKE /', ' \1unaccent(\2) ILIKE ', $line);
  271. }
  272. $line = str_replace(' LIKE BINARY \'', ' LIKE \'', $line);
  273. // Replace INSERT IGNORE into INSERT
  274. $line = preg_replace('/^INSERT IGNORE/', 'INSERT', $line);
  275. // Delete using criteria on other table must not declare twice the deleted table
  276. // DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable
  277. if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', $line, $reg)) {
  278. if ($reg[1] == $reg[2]) { // If same table, we remove second one
  279. $line = preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', 'DELETE FROM \\1 USING \\3', $line);
  280. }
  281. }
  282. // Remove () in the tables in FROM if 1 table
  283. $line = preg_replace('/FROM\s*\((([a-z_]+)\s+as\s+([a-z_]+)\s*)\)/i', 'FROM \\1', $line);
  284. //print $line."\n";
  285. // Remove () in the tables in FROM if 2 table
  286. $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);
  287. //print $line."\n";
  288. // Remove () in the tables in FROM if 3 table
  289. $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);
  290. //print $line."\n";
  291. // Remove () in the tables in FROM if 4 table
  292. $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);
  293. //print $line."\n";
  294. // Remove () in the tables in FROM if 5 table
  295. $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);
  296. //print $line."\n";
  297. // Replace espacing \' by ''.
  298. // By default we do not (should be already done by db->escape function if required
  299. // except for sql insert in data file that are mysql escaped so we removed them to
  300. // be compatible with standard_conforming_strings=on that considers \ as ordinary character).
  301. if ($unescapeslashquot) {
  302. $line = preg_replace("/\\\'/", "''", $line);
  303. }
  304. //print "type=".$type." newline=".$line."<br>\n";
  305. }
  306. return $line;
  307. }
  308. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  309. /**
  310. * Select a database
  311. * Ici postgresql n'a aucune fonction equivalente de mysql_select_db
  312. * On compare juste manuellement si la database choisie est bien celle activee par la connexion
  313. *
  314. * @param string $database Name of database
  315. * @return bool true if OK, false if KO
  316. */
  317. public function select_db($database)
  318. {
  319. // phpcs:enable
  320. if ($database == $this->database_name) {
  321. return true;
  322. } else {
  323. return false;
  324. }
  325. }
  326. /**
  327. * Connexion to server
  328. *
  329. * @param string $host Database server host
  330. * @param string $login Login
  331. * @param string $passwd Password
  332. * @param string $name Name of database (not used for mysql, used for pgsql)
  333. * @param integer $port Port of database server
  334. * @return bool|resource Database access handler
  335. * @see close()
  336. */
  337. public function connect($host, $login, $passwd, $name, $port = 0)
  338. {
  339. // use pg_pconnect() instead of pg_connect() if you want to use persistent connection costing 1ms, instead of 30ms for non persistent
  340. $this->db = false;
  341. // connections parameters must be protected (only \ and ' according to pg_connect() manual)
  342. $host = str_replace(array("\\", "'"), array("\\\\", "\\'"), $host);
  343. $login = str_replace(array("\\", "'"), array("\\\\", "\\'"), $login);
  344. $passwd = str_replace(array("\\", "'"), array("\\\\", "\\'"), $passwd);
  345. $name = str_replace(array("\\", "'"), array("\\\\", "\\'"), $name);
  346. $port = str_replace(array("\\", "'"), array("\\\\", "\\'"), $port);
  347. if (!$name) {
  348. $name = "postgres"; // When try to connect using admin user
  349. }
  350. // try first Unix domain socket (local)
  351. if ((!empty($host) && $host == "socket") && !defined('NOLOCALSOCKETPGCONNECT')) {
  352. $con_string = "dbname='".$name."' user='".$login."' password='".$passwd."'"; // $name may be empty
  353. try {
  354. $this->db = @pg_connect($con_string);
  355. } catch (Exception $e) {
  356. // No message
  357. }
  358. }
  359. // if local connection failed or not requested, use TCP/IP
  360. if (empty($this->db)) {
  361. if (!$host) {
  362. $host = "localhost";
  363. }
  364. if (!$port) {
  365. $port = 5432;
  366. }
  367. $con_string = "host='".$host."' port='".$port."' dbname='".$name."' user='".$login."' password='".$passwd."'";
  368. try {
  369. $this->db = @pg_connect($con_string);
  370. } catch (Exception $e) {
  371. print $e->getMessage();
  372. }
  373. }
  374. // now we test if at least one connect method was a success
  375. if ($this->db) {
  376. $this->database_name = $name;
  377. pg_set_error_verbosity($this->db, PGSQL_ERRORS_VERBOSE); // Set verbosity to max
  378. pg_query($this->db, "set datestyle = 'ISO, YMD';");
  379. }
  380. return $this->db;
  381. }
  382. /**
  383. * Return version of database server
  384. *
  385. * @return string Version string
  386. */
  387. public function getVersion()
  388. {
  389. $resql = $this->query('SHOW server_version');
  390. if ($resql) {
  391. $liste = $this->fetch_array($resql);
  392. return $liste['server_version'];
  393. }
  394. return '';
  395. }
  396. /**
  397. * Return version of database client driver
  398. *
  399. * @return string Version string
  400. */
  401. public function getDriverInfo()
  402. {
  403. return 'pgsql php driver';
  404. }
  405. /**
  406. * Close database connexion
  407. *
  408. * @return boolean True if disconnect successfull, false otherwise
  409. * @see connect()
  410. */
  411. public function close()
  412. {
  413. if ($this->db) {
  414. if ($this->transaction_opened > 0) {
  415. dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened, LOG_ERR);
  416. }
  417. $this->connected = false;
  418. return pg_close($this->db);
  419. }
  420. return false;
  421. }
  422. /**
  423. * Convert request to PostgreSQL syntax, execute it and return the resultset
  424. *
  425. * @param string $query SQL query string
  426. * @param int $usesavepoint 0=Default mode, 1=Run a savepoint before and a rollback to savepoint if error (this allow to have some request with errors inside global transactions).
  427. * @param string $type Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
  428. * @param int $result_mode Result mode (not used with pgsql)
  429. * @return bool|resource Resultset of answer
  430. */
  431. public function query($query, $usesavepoint = 0, $type = 'auto', $result_mode = 0)
  432. {
  433. global $conf, $dolibarr_main_db_readonly;
  434. $query = trim($query);
  435. // Convert MySQL syntax to PostgresSQL syntax
  436. $query = $this->convertSQLFromMysql($query, $type, ($this->unescapeslashquot && $this->standard_conforming_strings));
  437. //print "After convertSQLFromMysql:\n".$query."<br>\n";
  438. if (!empty($conf->global->MAIN_DB_AUTOFIX_BAD_SQL_REQUEST)) {
  439. // Fix bad formed requests. If request contains a date without quotes, we fix this but this should not occurs.
  440. $loop = true;
  441. while ($loop) {
  442. 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)) {
  443. $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);
  444. dol_syslog("Warning: Bad formed request converted into ".$query, LOG_WARNING);
  445. } else {
  446. $loop = false;
  447. }
  448. }
  449. }
  450. if ($usesavepoint && $this->transaction_opened) {
  451. @pg_query($this->db, 'SAVEPOINT mysavepoint');
  452. }
  453. if (!in_array($query, array('BEGIN', 'COMMIT', 'ROLLBACK'))) {
  454. $SYSLOG_SQL_LIMIT = 10000; // limit log to 10kb per line to limit DOS attacks
  455. dol_syslog('sql='.substr($query, 0, $SYSLOG_SQL_LIMIT), LOG_DEBUG);
  456. }
  457. if (empty($query)) {
  458. return false; // Return false = error if empty request
  459. }
  460. if (!empty($dolibarr_main_db_readonly)) {
  461. if (preg_match('/^(INSERT|UPDATE|REPLACE|DELETE|CREATE|ALTER|TRUNCATE|DROP)/i', $query)) {
  462. $this->lasterror = 'Application in read-only mode';
  463. $this->lasterrno = 'APPREADONLY';
  464. $this->lastquery = $query;
  465. return false;
  466. }
  467. }
  468. $ret = @pg_query($this->db, $query);
  469. //print $query;
  470. if (!preg_match("/^COMMIT/i", $query) && !preg_match("/^ROLLBACK/i", $query)) { // Si requete utilisateur, on la sauvegarde ainsi que son resultset
  471. if (!$ret) {
  472. if ($this->errno() != 'DB_ERROR_25P02') { // Do not overwrite errors if this is a consecutive error
  473. $this->lastqueryerror = $query;
  474. $this->lasterror = $this->error();
  475. $this->lasterrno = $this->errno();
  476. if ($conf->global->SYSLOG_LEVEL < LOG_DEBUG) {
  477. dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR); // Log of request was not yet done previously
  478. }
  479. dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterror." (".$this->lasterrno.")", LOG_ERR);
  480. dol_syslog(get_class($this)."::query SQL Error usesavepoint = ".$usesavepoint, LOG_ERR);
  481. }
  482. if ($usesavepoint && $this->transaction_opened) { // Warning, after that errno will be erased
  483. @pg_query($this->db, 'ROLLBACK TO SAVEPOINT mysavepoint');
  484. }
  485. }
  486. $this->lastquery = $query;
  487. $this->_results = $ret;
  488. }
  489. return $ret;
  490. }
  491. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  492. /**
  493. * Returns the current line (as an object) for the resultset cursor
  494. *
  495. * @param resource $resultset Curseur de la requete voulue
  496. * @return false|object Object result line or false if KO or end of cursor
  497. */
  498. public function fetch_object($resultset)
  499. {
  500. // phpcs:enable
  501. // If resultset not provided, we take the last used by connexion
  502. if (!is_resource($resultset) && !is_object($resultset)) {
  503. $resultset = $this->_results;
  504. }
  505. return pg_fetch_object($resultset);
  506. }
  507. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  508. /**
  509. * Return datas as an array
  510. *
  511. * @param resource $resultset Resultset of request
  512. * @return false|array Array
  513. */
  514. public function fetch_array($resultset)
  515. {
  516. // phpcs:enable
  517. // If resultset not provided, we take the last used by connexion
  518. if (!is_resource($resultset) && !is_object($resultset)) {
  519. $resultset = $this->_results;
  520. }
  521. return pg_fetch_array($resultset);
  522. }
  523. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  524. /**
  525. * Return datas as an array
  526. *
  527. * @param resource $resultset Resultset of request
  528. * @return false|array Array
  529. */
  530. public function fetch_row($resultset)
  531. {
  532. // phpcs:enable
  533. // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
  534. if (!is_resource($resultset) && !is_object($resultset)) {
  535. $resultset = $this->_results;
  536. }
  537. return pg_fetch_row($resultset);
  538. }
  539. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  540. /**
  541. * Return number of lines for result of a SELECT
  542. *
  543. * @param resource $resultset Resulset of requests
  544. * @return int Nb of lines, -1 on error
  545. * @see affected_rows()
  546. */
  547. public function num_rows($resultset)
  548. {
  549. // phpcs:enable
  550. // If resultset not provided, we take the last used by connexion
  551. if (!is_resource($resultset) && !is_object($resultset)) {
  552. $resultset = $this->_results;
  553. }
  554. return pg_num_rows($resultset);
  555. }
  556. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  557. /**
  558. * Return the number of lines in the result of a request INSERT, DELETE or UPDATE
  559. *
  560. * @param resource $resultset Result set of request
  561. * @return int Nb of lines
  562. * @see num_rows()
  563. */
  564. public function affected_rows($resultset)
  565. {
  566. // phpcs:enable
  567. // If resultset not provided, we take the last used by connexion
  568. if (!is_resource($resultset) && !is_object($resultset)) {
  569. $resultset = $this->_results;
  570. }
  571. // pgsql necessite un resultset pour cette fonction contrairement
  572. // a mysql qui prend un link de base
  573. return pg_affected_rows($resultset);
  574. }
  575. /**
  576. * Libere le dernier resultset utilise sur cette connexion
  577. *
  578. * @param resource $resultset Result set of request
  579. * @return void
  580. */
  581. public function free($resultset = null)
  582. {
  583. // If resultset not provided, we take the last used by connexion
  584. if (!is_resource($resultset) && !is_object($resultset)) {
  585. $resultset = $this->_results;
  586. }
  587. // Si resultset en est un, on libere la memoire
  588. if (is_resource($resultset) || is_object($resultset)) {
  589. pg_free_result($resultset);
  590. }
  591. }
  592. /**
  593. * Define limits and offset of request
  594. *
  595. * @param int $limit Maximum number of lines returned (-1=conf->liste_limit, 0=no limit)
  596. * @param int $offset Numero of line from where starting fetch
  597. * @return string String with SQL syntax to add a limit and offset
  598. */
  599. public function plimit($limit = 0, $offset = 0)
  600. {
  601. global $conf;
  602. if (empty($limit)) {
  603. return "";
  604. }
  605. if ($limit < 0) {
  606. $limit = $conf->liste_limit;
  607. }
  608. if ($offset > 0) {
  609. return " LIMIT ".$limit." OFFSET ".$offset." ";
  610. } else {
  611. return " LIMIT $limit ";
  612. }
  613. }
  614. /**
  615. * Escape a string to insert data
  616. *
  617. * @param string $stringtoencode String to escape
  618. * @return string String escaped
  619. */
  620. public function escape($stringtoencode)
  621. {
  622. return pg_escape_string($stringtoencode);
  623. }
  624. /**
  625. * Escape a string to insert data
  626. *
  627. * @param string $stringtoencode String to escape
  628. * @return string String escaped
  629. * @deprecated
  630. */
  631. public function escapeunderscore($stringtoencode)
  632. {
  633. return str_replace('_', '\_', (string) $stringtoencode);
  634. }
  635. /**
  636. * Escape a string to insert data into a like
  637. *
  638. * @param string $stringtoencode String to escape
  639. * @return string String escaped
  640. */
  641. public function escapeforlike($stringtoencode)
  642. {
  643. return str_replace(array('_', '\\', '%'), array('\_', '\\\\', '\%'), (string) $stringtoencode);
  644. }
  645. /**
  646. * Format a SQL IF
  647. *
  648. * @param string $test Test string (example: 'cd.statut=0', 'field IS NULL')
  649. * @param string $resok resultat si test egal
  650. * @param string $resko resultat si test non egal
  651. * @return string chaine formate SQL
  652. */
  653. public function ifsql($test, $resok, $resko)
  654. {
  655. return '(CASE WHEN '.$test.' THEN '.$resok.' ELSE '.$resko.' END)';
  656. }
  657. /**
  658. * Format a SQL REGEXP
  659. *
  660. * @param string $subject string tested
  661. * @param string $pattern SQL pattern to match
  662. * @param string $sqlstring whether or not the string being tested is an SQL expression
  663. * @return string SQL string
  664. */
  665. public function regexpsql($subject, $pattern, $sqlstring = false)
  666. {
  667. if ($sqlstring) {
  668. return "(". $subject ." ~ '" . $pattern . "')";
  669. }
  670. return "('". $subject ."' ~ '" . $pattern . "')";
  671. }
  672. /**
  673. * Renvoie le code erreur generique de l'operation precedente.
  674. *
  675. * @return string Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
  676. */
  677. public function errno()
  678. {
  679. if (!$this->connected) {
  680. // Si il y a eu echec de connexion, $this->db n'est pas valide.
  681. return 'DB_ERROR_FAILED_TO_CONNECT';
  682. } else {
  683. // Constants to convert error code to a generic Dolibarr error code
  684. $errorcode_map = array(
  685. 1004 => 'DB_ERROR_CANNOT_CREATE',
  686. 1005 => 'DB_ERROR_CANNOT_CREATE',
  687. 1006 => 'DB_ERROR_CANNOT_CREATE',
  688. 1007 => 'DB_ERROR_ALREADY_EXISTS',
  689. 1008 => 'DB_ERROR_CANNOT_DROP',
  690. 1025 => 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
  691. 1044 => 'DB_ERROR_ACCESSDENIED',
  692. 1046 => 'DB_ERROR_NODBSELECTED',
  693. 1048 => 'DB_ERROR_CONSTRAINT',
  694. '42P07' => 'DB_ERROR_TABLE_OR_KEY_ALREADY_EXISTS',
  695. '42703' => 'DB_ERROR_NOSUCHFIELD',
  696. 1060 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
  697. 42701=> 'DB_ERROR_COLUMN_ALREADY_EXISTS',
  698. '42710' => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
  699. '23505' => 'DB_ERROR_RECORD_ALREADY_EXISTS',
  700. '42704' => 'DB_ERROR_NO_INDEX_TO_DROP', // May also be Type xxx does not exists
  701. '42601' => 'DB_ERROR_SYNTAX',
  702. '42P16' => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
  703. 1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
  704. 1091 => 'DB_ERROR_NOSUCHFIELD',
  705. 1100 => 'DB_ERROR_NOT_LOCKED',
  706. 1136 => 'DB_ERROR_VALUE_COUNT_ON_ROW',
  707. '42P01' => 'DB_ERROR_NOSUCHTABLE',
  708. '23503' => 'DB_ERROR_NO_PARENT',
  709. 1217 => 'DB_ERROR_CHILD_EXISTS',
  710. 1451 => 'DB_ERROR_CHILD_EXISTS',
  711. '42P04' => 'DB_DATABASE_ALREADY_EXISTS'
  712. );
  713. $errorlabel = pg_last_error($this->db);
  714. $errorcode = '';
  715. $reg = array();
  716. if (preg_match('/: *([0-9P]+):/', $errorlabel, $reg)) {
  717. $errorcode = $reg[1];
  718. if (isset($errorcode_map[$errorcode])) {
  719. return $errorcode_map[$errorcode];
  720. }
  721. }
  722. $errno = $errorcode ? $errorcode : $errorlabel;
  723. return ($errno ? 'DB_ERROR_'.$errno : '0');
  724. }
  725. // '/(Table does not exist\.|Relation [\"\'].*[\"\'] does not exist|sequence does not exist|class ".+" not found)$/' => 'DB_ERROR_NOSUCHTABLE',
  726. // '/table [\"\'].*[\"\'] does not exist/' => 'DB_ERROR_NOSUCHTABLE',
  727. // '/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*/' => 'DB_ERROR_RECORD_ALREADY_EXISTS',
  728. // '/divide by zero$/' => 'DB_ERROR_DIVZERO',
  729. // '/pg_atoi: error in .*: can\'t parse /' => 'DB_ERROR_INVALID_NUMBER',
  730. // '/ttribute [\"\'].*[\"\'] not found$|Relation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/' => 'DB_ERROR_NOSUCHFIELD',
  731. // '/parser: parse error at or near \"/' => 'DB_ERROR_SYNTAX',
  732. // '/referential integrity violation/' => 'DB_ERROR_CONSTRAINT'
  733. }
  734. /**
  735. * Renvoie le texte de l'erreur pgsql de l'operation precedente
  736. *
  737. * @return string Error text
  738. */
  739. public function error()
  740. {
  741. return pg_last_error($this->db);
  742. }
  743. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  744. /**
  745. * Get last ID after an insert INSERT
  746. *
  747. * @param string $tab Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql
  748. * @param string $fieldid Field name
  749. * @return string Id of row
  750. */
  751. public function last_insert_id($tab, $fieldid = 'rowid')
  752. {
  753. // phpcs:enable
  754. //$result = pg_query($this->db,"SELECT MAX(".$fieldid.") FROM ".$tab);
  755. $result = pg_query($this->db, "SELECT currval('".$tab."_".$fieldid."_seq')");
  756. if (!$result) {
  757. print pg_last_error($this->db);
  758. exit;
  759. }
  760. //$nbre = pg_num_rows($result);
  761. $row = pg_fetch_result($result, 0, 0);
  762. return $row;
  763. }
  764. /**
  765. * Encrypt sensitive data in database
  766. * Warning: This function includes the escape and add the SQL simple quotes on strings.
  767. *
  768. * @param string $fieldorvalue Field name or value to encrypt
  769. * @param int $withQuotes Return string including the SQL simple quotes. This param must always be 1 (Value 0 is bugged and deprecated).
  770. * @return string XXX(field) or XXX('value') or field or 'value'
  771. */
  772. public function encrypt($fieldorvalue, $withQuotes = 1)
  773. {
  774. global $conf;
  775. // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
  776. //$cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
  777. //Encryption key
  778. //$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
  779. $return = $fieldorvalue;
  780. return ($withQuotes ? "'" : "").$this->escape($return).($withQuotes ? "'" : "");
  781. }
  782. /**
  783. * Decrypt sensitive data in database
  784. *
  785. * @param int $value Value to decrypt
  786. * @return string Decrypted value if used
  787. */
  788. public function decrypt($value)
  789. {
  790. global $conf;
  791. // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
  792. //$cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
  793. //Encryption key
  794. //$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
  795. $return = $value;
  796. return $return;
  797. }
  798. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  799. /**
  800. * Return connexion ID
  801. *
  802. * @return string Id connexion
  803. */
  804. public function DDLGetConnectId()
  805. {
  806. // phpcs:enable
  807. return '?';
  808. }
  809. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  810. /**
  811. * Create a new database
  812. * Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
  813. * We force to create database with charset this->forcecharset and collate this->forcecollate
  814. *
  815. * @param string $database Database name to create
  816. * @param string $charset Charset used to store data
  817. * @param string $collation Charset used to sort data
  818. * @param string $owner Username of database owner
  819. * @return false|resource resource defined if OK, null if KO
  820. */
  821. public function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
  822. {
  823. // phpcs:enable
  824. if (empty($charset)) {
  825. $charset = $this->forcecharset;
  826. }
  827. if (empty($collation)) {
  828. $collation = $this->forcecollate;
  829. }
  830. // Test charset match LC_TYPE (pgsql error otherwise)
  831. //print $charset.' '.setlocale(LC_CTYPE,'0'); exit;
  832. // NOTE: Do not use ' around the database name
  833. $sql = "CREATE DATABASE ".$this->escape($database)." OWNER '".$this->escape($owner)."' ENCODING '".$this->escape($charset)."'";
  834. dol_syslog($sql, LOG_DEBUG);
  835. $ret = $this->query($sql);
  836. return $ret;
  837. }
  838. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  839. /**
  840. * List tables into a database
  841. *
  842. * @param string $database Name of database
  843. * @param string $table Name of table filter ('xxx%')
  844. * @return array List of tables in an array
  845. */
  846. public function DDLListTables($database, $table = '')
  847. {
  848. // phpcs:enable
  849. $listtables = array();
  850. $escapedlike = '';
  851. if ($table) {
  852. $tmptable = preg_replace('/[^a-z0-9\.\-\_%]/i', '', $table);
  853. $escapedlike = " AND table_name LIKE '".$this->escape($tmptable)."'";
  854. }
  855. $result = pg_query($this->db, "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'".$escapedlike." ORDER BY table_name");
  856. if ($result) {
  857. while ($row = $this->fetch_row($result)) {
  858. $listtables[] = $row[0];
  859. }
  860. }
  861. return $listtables;
  862. }
  863. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  864. /**
  865. * List information of columns into a table.
  866. *
  867. * @param string $table Name of table
  868. * @return array Tableau des informations des champs de la table
  869. *
  870. */
  871. public function DDLInfoTable($table)
  872. {
  873. // phpcs:enable
  874. $infotables = array();
  875. $sql = "SELECT ";
  876. $sql .= " infcol.column_name as \"Column\",";
  877. $sql .= " CASE WHEN infcol.character_maximum_length IS NOT NULL THEN infcol.udt_name || '('||infcol.character_maximum_length||')'";
  878. $sql .= " ELSE infcol.udt_name";
  879. $sql .= " END as \"Type\",";
  880. $sql .= " infcol.collation_name as \"Collation\",";
  881. $sql .= " infcol.is_nullable as \"Null\",";
  882. $sql .= " '' as \"Key\",";
  883. $sql .= " infcol.column_default as \"Default\",";
  884. $sql .= " '' as \"Extra\",";
  885. $sql .= " '' as \"Privileges\"";
  886. $sql .= " FROM information_schema.columns infcol";
  887. $sql .= " WHERE table_schema = 'public' ";
  888. $sql .= " AND table_name = '".$this->escape($table)."'";
  889. $sql .= " ORDER BY ordinal_position;";
  890. dol_syslog($sql, LOG_DEBUG);
  891. $result = $this->query($sql);
  892. if ($result) {
  893. while ($row = $this->fetch_row($result)) {
  894. $infotables[] = $row;
  895. }
  896. }
  897. return $infotables;
  898. }
  899. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  900. /**
  901. * Create a table into database
  902. *
  903. * @param string $table Nom de la table
  904. * @param array $fields Tableau associatif [nom champ][tableau des descriptions]
  905. * @param string $primary_key Nom du champ qui sera la clef primaire
  906. * @param string $type Type de la table
  907. * @param array $unique_keys Tableau associatifs Nom de champs qui seront clef unique => valeur
  908. * @param array $fulltext_keys Tableau des Nom de champs qui seront indexes en fulltext
  909. * @param array $keys Tableau des champs cles noms => valeur
  910. * @return int <0 if KO, >=0 if OK
  911. */
  912. public function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
  913. {
  914. // phpcs:enable
  915. // FIXME: $fulltext_keys parameter is unused
  916. // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
  917. // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
  918. $sql = "create table ".$table."(";
  919. $i = 0;
  920. foreach ($fields as $field_name => $field_desc) {
  921. $sqlfields[$i] = $field_name." ";
  922. $sqlfields[$i] .= $field_desc['type'];
  923. if (preg_match("/^[^\s]/i", $field_desc['value'])) {
  924. $sqlfields[$i] .= "(".$field_desc['value'].")";
  925. } elseif (preg_match("/^[^\s]/i", $field_desc['attribute'])) {
  926. $sqlfields[$i] .= " ".$field_desc['attribute'];
  927. } elseif (preg_match("/^[^\s]/i", $field_desc['default'])) {
  928. if (preg_match("/null/i", $field_desc['default'])) {
  929. $sqlfields[$i] .= " default ".$field_desc['default'];
  930. } else {
  931. $sqlfields[$i] .= " default '".$this->escape($field_desc['default'])."'";
  932. }
  933. } elseif (preg_match("/^[^\s]/i", $field_desc['null'])) {
  934. $sqlfields[$i] .= " ".$field_desc['null'];
  935. } elseif (preg_match("/^[^\s]/i", $field_desc['extra'])) {
  936. $sqlfields[$i] .= " ".$field_desc['extra'];
  937. }
  938. $i++;
  939. }
  940. if ($primary_key != "") {
  941. $pk = "primary key(".$primary_key.")";
  942. }
  943. if (is_array($unique_keys)) {
  944. $i = 0;
  945. foreach ($unique_keys as $key => $value) {
  946. $sqluq[$i] = "UNIQUE KEY '".$key."' ('".$this->escape($value)."')";
  947. $i++;
  948. }
  949. }
  950. if (is_array($keys)) {
  951. $i = 0;
  952. foreach ($keys as $key => $value) {
  953. $sqlk[$i] = "KEY ".$key." (".$value.")";
  954. $i++;
  955. }
  956. }
  957. $sql .= implode(',', $sqlfields);
  958. if ($primary_key != "") {
  959. $sql .= ",".$pk;
  960. }
  961. if (is_array($unique_keys)) {
  962. $sql .= ",".implode(',', $sqluq);
  963. }
  964. if (is_array($keys)) {
  965. $sql .= ",".implode(',', $sqlk);
  966. }
  967. $sql .= ") type=".$type;
  968. dol_syslog($sql, LOG_DEBUG);
  969. if (!$this->query($sql)) {
  970. return -1;
  971. } else {
  972. return 1;
  973. }
  974. }
  975. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  976. /**
  977. * Drop a table into database
  978. *
  979. * @param string $table Name of table
  980. * @return int <0 if KO, >=0 if OK
  981. */
  982. public function DDLDropTable($table)
  983. {
  984. // phpcs:enable
  985. $tmptable = preg_replace('/[^a-z0-9\.\-\_]/i', '', $table);
  986. $sql = "DROP TABLE ".$tmptable;
  987. if (!$this->query($sql)) {
  988. return -1;
  989. } else {
  990. return 1;
  991. }
  992. }
  993. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  994. /**
  995. * Create a user to connect to database
  996. *
  997. * @param string $dolibarr_main_db_host Ip server
  998. * @param string $dolibarr_main_db_user Name of user to create
  999. * @param string $dolibarr_main_db_pass Password of user to create
  1000. * @param string $dolibarr_main_db_name Database name where user must be granted
  1001. * @return int <0 if KO, >=0 if OK
  1002. */
  1003. public function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
  1004. {
  1005. // phpcs:enable
  1006. // Note: using ' on user does not works with pgsql
  1007. $sql = "CREATE USER ".$this->escape($dolibarr_main_db_user)." with password '".$this->escape($dolibarr_main_db_pass)."'";
  1008. dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
  1009. $resql = $this->query($sql);
  1010. if (!$resql) {
  1011. return -1;
  1012. }
  1013. return 1;
  1014. }
  1015. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1016. /**
  1017. * Return a pointer of line with description of a table or field
  1018. *
  1019. * @param string $table Name of table
  1020. * @param string $field Optionnel : Name of field if we want description of field
  1021. * @return false|resource Resultset x (x->attname)
  1022. */
  1023. public function DDLDescTable($table, $field = "")
  1024. {
  1025. // phpcs:enable
  1026. $sql = "SELECT attname FROM pg_attribute, pg_type WHERE typname = '".$this->escape($table)."' AND attrelid = typrelid";
  1027. $sql .= " AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', 'tableoid', 'xmin', 'xmax')";
  1028. if ($field) {
  1029. $sql .= " AND attname = '".$this->escape($field)."'";
  1030. }
  1031. dol_syslog($sql, LOG_DEBUG);
  1032. $this->_results = $this->query($sql);
  1033. return $this->_results;
  1034. }
  1035. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1036. /**
  1037. * Create a new field into table
  1038. *
  1039. * @param string $table Name of table
  1040. * @param string $field_name Name of field to add
  1041. * @param string $field_desc Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
  1042. * @param string $field_position Optionnel ex.: "after champtruc"
  1043. * @return int <0 if KO, >0 if OK
  1044. */
  1045. public function DDLAddField($table, $field_name, $field_desc, $field_position = "")
  1046. {
  1047. // phpcs:enable
  1048. // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
  1049. // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
  1050. $sql = "ALTER TABLE ".$table." ADD ".$field_name." ";
  1051. $sql .= $field_desc['type'];
  1052. if (preg_match("/^[^\s]/i", $field_desc['value'])) {
  1053. if (!in_array($field_desc['type'], array('int', 'date', 'datetime')) && $field_desc['value']) {
  1054. $sql .= "(".$field_desc['value'].")";
  1055. }
  1056. }
  1057. if (preg_match("/^[^\s]/i", $field_desc['attribute'])) {
  1058. $sql .= " ".$field_desc['attribute'];
  1059. }
  1060. if (preg_match("/^[^\s]/i", $field_desc['null'])) {
  1061. $sql .= " ".$field_desc['null'];
  1062. }
  1063. if (preg_match("/^[^\s]/i", $field_desc['default'])) {
  1064. if (preg_match("/null/i", $field_desc['default'])) {
  1065. $sql .= " default ".$field_desc['default'];
  1066. } else {
  1067. $sql .= " default '".$this->escape($field_desc['default'])."'";
  1068. }
  1069. }
  1070. if (preg_match("/^[^\s]/i", $field_desc['extra'])) {
  1071. $sql .= " ".$field_desc['extra'];
  1072. }
  1073. $sql .= " ".$field_position;
  1074. dol_syslog($sql, LOG_DEBUG);
  1075. if (!$this -> query($sql)) {
  1076. return -1;
  1077. }
  1078. return 1;
  1079. }
  1080. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1081. /**
  1082. * Update format of a field into a table
  1083. *
  1084. * @param string $table Name of table
  1085. * @param string $field_name Name of field to modify
  1086. * @param string $field_desc Array with description of field format
  1087. * @return int <0 if KO, >0 if OK
  1088. */
  1089. public function DDLUpdateField($table, $field_name, $field_desc)
  1090. {
  1091. // phpcs:enable
  1092. $sql = "ALTER TABLE ".$table;
  1093. $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
  1094. if (in_array($field_desc['type'], array('double', 'varchar')) && $field_desc['value']) {
  1095. $sql .= "(".$field_desc['value'].")";
  1096. }
  1097. if ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL') {
  1098. // 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
  1099. if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text') {
  1100. $sqlbis = "UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
  1101. $this->query($sqlbis);
  1102. } elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') {
  1103. $sqlbis = "UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
  1104. $this->query($sqlbis);
  1105. }
  1106. }
  1107. if ($field_desc['default'] != '') {
  1108. if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') {
  1109. $sql .= " DEFAULT ".$this->escape($field_desc['default']);
  1110. } elseif ($field_desc['type'] != 'text') {
  1111. $sql .= " DEFAULT '".$this->escape($field_desc['default'])."'"; // Default not supported on text fields
  1112. }
  1113. }
  1114. dol_syslog($sql, LOG_DEBUG);
  1115. if (!$this->query($sql)) {
  1116. return -1;
  1117. }
  1118. return 1;
  1119. }
  1120. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1121. /**
  1122. * Drop a field from table
  1123. *
  1124. * @param string $table Name of table
  1125. * @param string $field_name Name of field to drop
  1126. * @return int <0 if KO, >0 if OK
  1127. */
  1128. public function DDLDropField($table, $field_name)
  1129. {
  1130. // phpcs:enable
  1131. $tmp_field_name = preg_replace('/[^a-z0-9\.\-\_]/i', '', $field_name);
  1132. $sql = "ALTER TABLE ".$table." DROP COLUMN ".$tmp_field_name;
  1133. if (!$this->query($sql)) {
  1134. $this->error = $this->lasterror();
  1135. return -1;
  1136. }
  1137. return 1;
  1138. }
  1139. /**
  1140. * Return charset used to store data in database
  1141. *
  1142. * @return string Charset
  1143. */
  1144. public function getDefaultCharacterSetDatabase()
  1145. {
  1146. $resql = $this->query('SHOW SERVER_ENCODING');
  1147. if ($resql) {
  1148. $liste = $this->fetch_array($resql);
  1149. return $liste['server_encoding'];
  1150. } else {
  1151. return '';
  1152. }
  1153. }
  1154. /**
  1155. * Return list of available charset that can be used to store data in database
  1156. *
  1157. * @return array List of Charset
  1158. */
  1159. public function getListOfCharacterSet()
  1160. {
  1161. $resql = $this->query('SHOW SERVER_ENCODING');
  1162. $liste = array();
  1163. if ($resql) {
  1164. $i = 0;
  1165. while ($obj = $this->fetch_object($resql)) {
  1166. $liste[$i]['charset'] = $obj->server_encoding;
  1167. $liste[$i]['description'] = 'Default database charset';
  1168. $i++;
  1169. }
  1170. $this->free($resql);
  1171. } else {
  1172. return null;
  1173. }
  1174. return $liste;
  1175. }
  1176. /**
  1177. * Return collation used in database
  1178. *
  1179. * @return string Collation value
  1180. */
  1181. public function getDefaultCollationDatabase()
  1182. {
  1183. $resql = $this->query('SHOW LC_COLLATE');
  1184. if ($resql) {
  1185. $liste = $this->fetch_array($resql);
  1186. return $liste['lc_collate'];
  1187. } else {
  1188. return '';
  1189. }
  1190. }
  1191. /**
  1192. * Return list of available collation that can be used for database
  1193. *
  1194. * @return array Liste of Collation
  1195. */
  1196. public function getListOfCollation()
  1197. {
  1198. $resql = $this->query('SHOW LC_COLLATE');
  1199. $liste = array();
  1200. if ($resql) {
  1201. $i = 0;
  1202. while ($obj = $this->fetch_object($resql)) {
  1203. $liste[$i]['collation'] = $obj->lc_collate;
  1204. $i++;
  1205. }
  1206. $this->free($resql);
  1207. } else {
  1208. return null;
  1209. }
  1210. return $liste;
  1211. }
  1212. /**
  1213. * Return full path of dump program
  1214. *
  1215. * @return string Full path of dump program
  1216. */
  1217. public function getPathOfDump()
  1218. {
  1219. $fullpathofdump = '/pathtopgdump/pg_dump';
  1220. if (file_exists('/usr/bin/pg_dump')) {
  1221. $fullpathofdump = '/usr/bin/pg_dump';
  1222. } else {
  1223. // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
  1224. $resql = $this->query('SHOW data_directory');
  1225. if ($resql) {
  1226. $liste = $this->fetch_array($resql);
  1227. $basedir = $liste['data_directory'];
  1228. $fullpathofdump = preg_replace('/data$/', 'bin', $basedir).'/pg_dump';
  1229. }
  1230. }
  1231. return $fullpathofdump;
  1232. }
  1233. /**
  1234. * Return full path of restore program
  1235. *
  1236. * @return string Full path of restore program
  1237. */
  1238. public function getPathOfRestore()
  1239. {
  1240. //$tool='pg_restore';
  1241. $tool = 'psql';
  1242. $fullpathofdump = '/pathtopgrestore/'.$tool;
  1243. if (file_exists('/usr/bin/'.$tool)) {
  1244. $fullpathofdump = '/usr/bin/'.$tool;
  1245. } else {
  1246. // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
  1247. $resql = $this->query('SHOW data_directory');
  1248. if ($resql) {
  1249. $liste = $this->fetch_array($resql);
  1250. $basedir = $liste['data_directory'];
  1251. $fullpathofdump = preg_replace('/data$/', 'bin', $basedir).'/'.$tool;
  1252. }
  1253. }
  1254. return $fullpathofdump;
  1255. }
  1256. /**
  1257. * Return value of server parameters
  1258. *
  1259. * @param string $filter Filter list on a particular value
  1260. * @return array Array of key-values (key=>value)
  1261. */
  1262. public function getServerParametersValues($filter = '')
  1263. {
  1264. $result = array();
  1265. $resql = 'select name,setting from pg_settings';
  1266. if ($filter) {
  1267. $resql .= " WHERE name = '".$this->escape($filter)."'";
  1268. }
  1269. $resql = $this->query($resql);
  1270. if ($resql) {
  1271. while ($obj = $this->fetch_object($resql)) {
  1272. $result[$obj->name] = $obj->setting;
  1273. }
  1274. }
  1275. return $result;
  1276. }
  1277. /**
  1278. * Return value of server status
  1279. *
  1280. * @param string $filter Filter list on a particular value
  1281. * @return array Array of key-values (key=>value)
  1282. */
  1283. public function getServerStatusValues($filter = '')
  1284. {
  1285. /* This is to return current running requests.
  1286. $sql='SELECT datname,procpid,current_query FROM pg_stat_activity ORDER BY procpid';
  1287. if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
  1288. $resql=$this->query($sql);
  1289. if ($resql)
  1290. {
  1291. $obj=$this->fetch_object($resql);
  1292. $result[$obj->Variable_name]=$obj->Value;
  1293. }
  1294. */
  1295. return array();
  1296. }
  1297. }