pgsql.class.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447
  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. * Renvoie le code erreur generique de l'operation precedente.
  659. *
  660. * @return string Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
  661. */
  662. public function errno()
  663. {
  664. if (!$this->connected) {
  665. // Si il y a eu echec de connexion, $this->db n'est pas valide.
  666. return 'DB_ERROR_FAILED_TO_CONNECT';
  667. } else {
  668. // Constants to convert error code to a generic Dolibarr error code
  669. $errorcode_map = array(
  670. 1004 => 'DB_ERROR_CANNOT_CREATE',
  671. 1005 => 'DB_ERROR_CANNOT_CREATE',
  672. 1006 => 'DB_ERROR_CANNOT_CREATE',
  673. 1007 => 'DB_ERROR_ALREADY_EXISTS',
  674. 1008 => 'DB_ERROR_CANNOT_DROP',
  675. 1025 => 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
  676. 1044 => 'DB_ERROR_ACCESSDENIED',
  677. 1046 => 'DB_ERROR_NODBSELECTED',
  678. 1048 => 'DB_ERROR_CONSTRAINT',
  679. '42P07' => 'DB_ERROR_TABLE_OR_KEY_ALREADY_EXISTS',
  680. '42703' => 'DB_ERROR_NOSUCHFIELD',
  681. 1060 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
  682. 42701=> 'DB_ERROR_COLUMN_ALREADY_EXISTS',
  683. '42710' => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
  684. '23505' => 'DB_ERROR_RECORD_ALREADY_EXISTS',
  685. '42704' => 'DB_ERROR_NO_INDEX_TO_DROP', // May also be Type xxx does not exists
  686. '42601' => 'DB_ERROR_SYNTAX',
  687. '42P16' => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
  688. 1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
  689. 1091 => 'DB_ERROR_NOSUCHFIELD',
  690. 1100 => 'DB_ERROR_NOT_LOCKED',
  691. 1136 => 'DB_ERROR_VALUE_COUNT_ON_ROW',
  692. '42P01' => 'DB_ERROR_NOSUCHTABLE',
  693. '23503' => 'DB_ERROR_NO_PARENT',
  694. 1217 => 'DB_ERROR_CHILD_EXISTS',
  695. 1451 => 'DB_ERROR_CHILD_EXISTS',
  696. '42P04' => 'DB_DATABASE_ALREADY_EXISTS'
  697. );
  698. $errorlabel = pg_last_error($this->db);
  699. $errorcode = '';
  700. $reg = array();
  701. if (preg_match('/: *([0-9P]+):/', $errorlabel, $reg)) {
  702. $errorcode = $reg[1];
  703. if (isset($errorcode_map[$errorcode])) {
  704. return $errorcode_map[$errorcode];
  705. }
  706. }
  707. $errno = $errorcode ? $errorcode : $errorlabel;
  708. return ($errno ? 'DB_ERROR_'.$errno : '0');
  709. }
  710. // '/(Table does not exist\.|Relation [\"\'].*[\"\'] does not exist|sequence does not exist|class ".+" not found)$/' => 'DB_ERROR_NOSUCHTABLE',
  711. // '/table [\"\'].*[\"\'] does not exist/' => 'DB_ERROR_NOSUCHTABLE',
  712. // '/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*/' => 'DB_ERROR_RECORD_ALREADY_EXISTS',
  713. // '/divide by zero$/' => 'DB_ERROR_DIVZERO',
  714. // '/pg_atoi: error in .*: can\'t parse /' => 'DB_ERROR_INVALID_NUMBER',
  715. // '/ttribute [\"\'].*[\"\'] not found$|Relation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/' => 'DB_ERROR_NOSUCHFIELD',
  716. // '/parser: parse error at or near \"/' => 'DB_ERROR_SYNTAX',
  717. // '/referential integrity violation/' => 'DB_ERROR_CONSTRAINT'
  718. }
  719. /**
  720. * Renvoie le texte de l'erreur pgsql de l'operation precedente
  721. *
  722. * @return string Error text
  723. */
  724. public function error()
  725. {
  726. return pg_last_error($this->db);
  727. }
  728. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  729. /**
  730. * Get last ID after an insert INSERT
  731. *
  732. * @param string $tab Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql
  733. * @param string $fieldid Field name
  734. * @return string Id of row
  735. */
  736. public function last_insert_id($tab, $fieldid = 'rowid')
  737. {
  738. // phpcs:enable
  739. //$result = pg_query($this->db,"SELECT MAX(".$fieldid.") FROM ".$tab);
  740. $result = pg_query($this->db, "SELECT currval('".$tab."_".$fieldid."_seq')");
  741. if (!$result) {
  742. print pg_last_error($this->db);
  743. exit;
  744. }
  745. //$nbre = pg_num_rows($result);
  746. $row = pg_fetch_result($result, 0, 0);
  747. return $row;
  748. }
  749. /**
  750. * Encrypt sensitive data in database
  751. * Warning: This function includes the escape and add the SQL simple quotes on strings.
  752. *
  753. * @param string $fieldorvalue Field name or value to encrypt
  754. * @param int $withQuotes Return string including the SQL simple quotes. This param must always be 1 (Value 0 is bugged and deprecated).
  755. * @return string XXX(field) or XXX('value') or field or 'value'
  756. */
  757. public function encrypt($fieldorvalue, $withQuotes = 1)
  758. {
  759. global $conf;
  760. // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
  761. //$cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
  762. //Encryption key
  763. //$cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
  764. $return = $fieldorvalue;
  765. return ($withQuotes ? "'" : "").$this->escape($return).($withQuotes ? "'" : "");
  766. }
  767. /**
  768. * Decrypt sensitive data in database
  769. *
  770. * @param int $value Value to decrypt
  771. * @return string Decrypted value if used
  772. */
  773. public function decrypt($value)
  774. {
  775. global $conf;
  776. // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
  777. $cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
  778. //Encryption key
  779. $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
  780. $return = $value;
  781. return $return;
  782. }
  783. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  784. /**
  785. * Return connexion ID
  786. *
  787. * @return string Id connexion
  788. */
  789. public function DDLGetConnectId()
  790. {
  791. // phpcs:enable
  792. return '?';
  793. }
  794. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  795. /**
  796. * Create a new database
  797. * Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
  798. * We force to create database with charset this->forcecharset and collate this->forcecollate
  799. *
  800. * @param string $database Database name to create
  801. * @param string $charset Charset used to store data
  802. * @param string $collation Charset used to sort data
  803. * @param string $owner Username of database owner
  804. * @return false|resource resource defined if OK, null if KO
  805. */
  806. public function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
  807. {
  808. // phpcs:enable
  809. if (empty($charset)) {
  810. $charset = $this->forcecharset;
  811. }
  812. if (empty($collation)) {
  813. $collation = $this->forcecollate;
  814. }
  815. // Test charset match LC_TYPE (pgsql error otherwise)
  816. //print $charset.' '.setlocale(LC_CTYPE,'0'); exit;
  817. // NOTE: Do not use ' around the database name
  818. $sql = "CREATE DATABASE ".$this->escape($database)." OWNER '".$this->escape($owner)."' ENCODING '".$this->escape($charset)."'";
  819. dol_syslog($sql, LOG_DEBUG);
  820. $ret = $this->query($sql);
  821. return $ret;
  822. }
  823. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  824. /**
  825. * List tables into a database
  826. *
  827. * @param string $database Name of database
  828. * @param string $table Name of table filter ('xxx%')
  829. * @return array List of tables in an array
  830. */
  831. public function DDLListTables($database, $table = '')
  832. {
  833. // phpcs:enable
  834. $listtables = array();
  835. $escapedlike = '';
  836. if ($table) {
  837. $tmptable = preg_replace('/[^a-z0-9\.\-\_%]/i', '', $table);
  838. $escapedlike = " AND table_name LIKE '".$this->escape($tmptable)."'";
  839. }
  840. $result = pg_query($this->db, "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'".$escapedlike." ORDER BY table_name");
  841. if ($result) {
  842. while ($row = $this->fetch_row($result)) {
  843. $listtables[] = $row[0];
  844. }
  845. }
  846. return $listtables;
  847. }
  848. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  849. /**
  850. * List information of columns into a table.
  851. *
  852. * @param string $table Name of table
  853. * @return array Tableau des informations des champs de la table
  854. *
  855. */
  856. public function DDLInfoTable($table)
  857. {
  858. // phpcs:enable
  859. $infotables = array();
  860. $sql = "SELECT ";
  861. $sql .= " infcol.column_name as \"Column\",";
  862. $sql .= " CASE WHEN infcol.character_maximum_length IS NOT NULL THEN infcol.udt_name || '('||infcol.character_maximum_length||')'";
  863. $sql .= " ELSE infcol.udt_name";
  864. $sql .= " END as \"Type\",";
  865. $sql .= " infcol.collation_name as \"Collation\",";
  866. $sql .= " infcol.is_nullable as \"Null\",";
  867. $sql .= " '' as \"Key\",";
  868. $sql .= " infcol.column_default as \"Default\",";
  869. $sql .= " '' as \"Extra\",";
  870. $sql .= " '' as \"Privileges\"";
  871. $sql .= " FROM information_schema.columns infcol";
  872. $sql .= " WHERE table_schema = 'public' ";
  873. $sql .= " AND table_name = '".$this->escape($table)."'";
  874. $sql .= " ORDER BY ordinal_position;";
  875. dol_syslog($sql, LOG_DEBUG);
  876. $result = $this->query($sql);
  877. if ($result) {
  878. while ($row = $this->fetch_row($result)) {
  879. $infotables[] = $row;
  880. }
  881. }
  882. return $infotables;
  883. }
  884. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  885. /**
  886. * Create a table into database
  887. *
  888. * @param string $table Nom de la table
  889. * @param array $fields Tableau associatif [nom champ][tableau des descriptions]
  890. * @param string $primary_key Nom du champ qui sera la clef primaire
  891. * @param string $type Type de la table
  892. * @param array $unique_keys Tableau associatifs Nom de champs qui seront clef unique => valeur
  893. * @param array $fulltext_keys Tableau des Nom de champs qui seront indexes en fulltext
  894. * @param array $keys Tableau des champs cles noms => valeur
  895. * @return int <0 if KO, >=0 if OK
  896. */
  897. public function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
  898. {
  899. // phpcs:enable
  900. // FIXME: $fulltext_keys parameter is unused
  901. // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
  902. // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
  903. $sql = "create table ".$table."(";
  904. $i = 0;
  905. foreach ($fields as $field_name => $field_desc) {
  906. $sqlfields[$i] = $field_name." ";
  907. $sqlfields[$i] .= $field_desc['type'];
  908. if (preg_match("/^[^\s]/i", $field_desc['value'])) {
  909. $sqlfields[$i] .= "(".$field_desc['value'].")";
  910. } elseif (preg_match("/^[^\s]/i", $field_desc['attribute'])) {
  911. $sqlfields[$i] .= " ".$field_desc['attribute'];
  912. } elseif (preg_match("/^[^\s]/i", $field_desc['default'])) {
  913. if (preg_match("/null/i", $field_desc['default'])) {
  914. $sqlfields[$i] .= " default ".$field_desc['default'];
  915. } else {
  916. $sqlfields[$i] .= " default '".$this->escape($field_desc['default'])."'";
  917. }
  918. } elseif (preg_match("/^[^\s]/i", $field_desc['null'])) {
  919. $sqlfields[$i] .= " ".$field_desc['null'];
  920. } elseif (preg_match("/^[^\s]/i", $field_desc['extra'])) {
  921. $sqlfields[$i] .= " ".$field_desc['extra'];
  922. }
  923. $i++;
  924. }
  925. if ($primary_key != "") {
  926. $pk = "primary key(".$primary_key.")";
  927. }
  928. if (is_array($unique_keys)) {
  929. $i = 0;
  930. foreach ($unique_keys as $key => $value) {
  931. $sqluq[$i] = "UNIQUE KEY '".$key."' ('".$this->escape($value)."')";
  932. $i++;
  933. }
  934. }
  935. if (is_array($keys)) {
  936. $i = 0;
  937. foreach ($keys as $key => $value) {
  938. $sqlk[$i] = "KEY ".$key." (".$value.")";
  939. $i++;
  940. }
  941. }
  942. $sql .= implode(',', $sqlfields);
  943. if ($primary_key != "") {
  944. $sql .= ",".$pk;
  945. }
  946. if (is_array($unique_keys)) {
  947. $sql .= ",".implode(',', $sqluq);
  948. }
  949. if (is_array($keys)) {
  950. $sql .= ",".implode(',', $sqlk);
  951. }
  952. $sql .= ") type=".$type;
  953. dol_syslog($sql, LOG_DEBUG);
  954. if (!$this->query($sql)) {
  955. return -1;
  956. } else {
  957. return 1;
  958. }
  959. }
  960. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  961. /**
  962. * Drop a table into database
  963. *
  964. * @param string $table Name of table
  965. * @return int <0 if KO, >=0 if OK
  966. */
  967. public function DDLDropTable($table)
  968. {
  969. // phpcs:enable
  970. $tmptable = preg_replace('/[^a-z0-9\.\-\_]/i', '', $table);
  971. $sql = "DROP TABLE ".$tmptable;
  972. if (!$this->query($sql)) {
  973. return -1;
  974. } else {
  975. return 1;
  976. }
  977. }
  978. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  979. /**
  980. * Create a user to connect to database
  981. *
  982. * @param string $dolibarr_main_db_host Ip server
  983. * @param string $dolibarr_main_db_user Name of user to create
  984. * @param string $dolibarr_main_db_pass Password of user to create
  985. * @param string $dolibarr_main_db_name Database name where user must be granted
  986. * @return int <0 if KO, >=0 if OK
  987. */
  988. public function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
  989. {
  990. // phpcs:enable
  991. // Note: using ' on user does not works with pgsql
  992. $sql = "CREATE USER ".$this->escape($dolibarr_main_db_user)." with password '".$this->escape($dolibarr_main_db_pass)."'";
  993. dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
  994. $resql = $this->query($sql);
  995. if (!$resql) {
  996. return -1;
  997. }
  998. return 1;
  999. }
  1000. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1001. /**
  1002. * Return a pointer of line with description of a table or field
  1003. *
  1004. * @param string $table Name of table
  1005. * @param string $field Optionnel : Name of field if we want description of field
  1006. * @return false|resource Resultset x (x->attname)
  1007. */
  1008. public function DDLDescTable($table, $field = "")
  1009. {
  1010. // phpcs:enable
  1011. $sql = "SELECT attname FROM pg_attribute, pg_type WHERE typname = '".$this->escape($table)."' AND attrelid = typrelid";
  1012. $sql .= " AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', 'tableoid', 'xmin', 'xmax')";
  1013. if ($field) {
  1014. $sql .= " AND attname = '".$this->escape($field)."'";
  1015. }
  1016. dol_syslog($sql, LOG_DEBUG);
  1017. $this->_results = $this->query($sql);
  1018. return $this->_results;
  1019. }
  1020. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1021. /**
  1022. * Create a new field into table
  1023. *
  1024. * @param string $table Name of table
  1025. * @param string $field_name Name of field to add
  1026. * @param string $field_desc Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
  1027. * @param string $field_position Optionnel ex.: "after champtruc"
  1028. * @return int <0 if KO, >0 if OK
  1029. */
  1030. public function DDLAddField($table, $field_name, $field_desc, $field_position = "")
  1031. {
  1032. // phpcs:enable
  1033. // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
  1034. // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
  1035. $sql = "ALTER TABLE ".$table." ADD ".$field_name." ";
  1036. $sql .= $field_desc['type'];
  1037. if (preg_match("/^[^\s]/i", $field_desc['value'])) {
  1038. if (!in_array($field_desc['type'], array('int', 'date', 'datetime')) && $field_desc['value']) {
  1039. $sql .= "(".$field_desc['value'].")";
  1040. }
  1041. }
  1042. if (preg_match("/^[^\s]/i", $field_desc['attribute'])) {
  1043. $sql .= " ".$field_desc['attribute'];
  1044. }
  1045. if (preg_match("/^[^\s]/i", $field_desc['null'])) {
  1046. $sql .= " ".$field_desc['null'];
  1047. }
  1048. if (preg_match("/^[^\s]/i", $field_desc['default'])) {
  1049. if (preg_match("/null/i", $field_desc['default'])) {
  1050. $sql .= " default ".$field_desc['default'];
  1051. } else {
  1052. $sql .= " default '".$this->escape($field_desc['default'])."'";
  1053. }
  1054. }
  1055. if (preg_match("/^[^\s]/i", $field_desc['extra'])) {
  1056. $sql .= " ".$field_desc['extra'];
  1057. }
  1058. $sql .= " ".$field_position;
  1059. dol_syslog($sql, LOG_DEBUG);
  1060. if (!$this -> query($sql)) {
  1061. return -1;
  1062. }
  1063. return 1;
  1064. }
  1065. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1066. /**
  1067. * Update format of a field into a table
  1068. *
  1069. * @param string $table Name of table
  1070. * @param string $field_name Name of field to modify
  1071. * @param string $field_desc Array with description of field format
  1072. * @return int <0 if KO, >0 if OK
  1073. */
  1074. public function DDLUpdateField($table, $field_name, $field_desc)
  1075. {
  1076. // phpcs:enable
  1077. $sql = "ALTER TABLE ".$table;
  1078. $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
  1079. if (in_array($field_desc['type'], array('double', 'varchar')) && $field_desc['value']) {
  1080. $sql .= "(".$field_desc['value'].")";
  1081. }
  1082. if ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL') {
  1083. // 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
  1084. if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text') {
  1085. $sqlbis = "UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
  1086. $this->query($sqlbis);
  1087. } elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') {
  1088. $sqlbis = "UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
  1089. $this->query($sqlbis);
  1090. }
  1091. }
  1092. if ($field_desc['default'] != '') {
  1093. if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') {
  1094. $sql .= " DEFAULT ".$this->escape($field_desc['default']);
  1095. } elseif ($field_desc['type'] != 'text') {
  1096. $sql .= " DEFAULT '".$this->escape($field_desc['default'])."'"; // Default not supported on text fields
  1097. }
  1098. }
  1099. dol_syslog($sql, LOG_DEBUG);
  1100. if (!$this->query($sql)) {
  1101. return -1;
  1102. }
  1103. return 1;
  1104. }
  1105. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1106. /**
  1107. * Drop a field from table
  1108. *
  1109. * @param string $table Name of table
  1110. * @param string $field_name Name of field to drop
  1111. * @return int <0 if KO, >0 if OK
  1112. */
  1113. public function DDLDropField($table, $field_name)
  1114. {
  1115. // phpcs:enable
  1116. $tmp_field_name = preg_replace('/[^a-z0-9\.\-\_]/i', '', $field_name);
  1117. $sql = "ALTER TABLE ".$table." DROP COLUMN ".$tmp_field_name;
  1118. if (!$this->query($sql)) {
  1119. $this->error = $this->lasterror();
  1120. return -1;
  1121. }
  1122. return 1;
  1123. }
  1124. /**
  1125. * Return charset used to store data in database
  1126. *
  1127. * @return string Charset
  1128. */
  1129. public function getDefaultCharacterSetDatabase()
  1130. {
  1131. $resql = $this->query('SHOW SERVER_ENCODING');
  1132. if ($resql) {
  1133. $liste = $this->fetch_array($resql);
  1134. return $liste['server_encoding'];
  1135. } else {
  1136. return '';
  1137. }
  1138. }
  1139. /**
  1140. * Return list of available charset that can be used to store data in database
  1141. *
  1142. * @return array List of Charset
  1143. */
  1144. public function getListOfCharacterSet()
  1145. {
  1146. $resql = $this->query('SHOW SERVER_ENCODING');
  1147. $liste = array();
  1148. if ($resql) {
  1149. $i = 0;
  1150. while ($obj = $this->fetch_object($resql)) {
  1151. $liste[$i]['charset'] = $obj->server_encoding;
  1152. $liste[$i]['description'] = 'Default database charset';
  1153. $i++;
  1154. }
  1155. $this->free($resql);
  1156. } else {
  1157. return null;
  1158. }
  1159. return $liste;
  1160. }
  1161. /**
  1162. * Return collation used in database
  1163. *
  1164. * @return string Collation value
  1165. */
  1166. public function getDefaultCollationDatabase()
  1167. {
  1168. $resql = $this->query('SHOW LC_COLLATE');
  1169. if ($resql) {
  1170. $liste = $this->fetch_array($resql);
  1171. return $liste['lc_collate'];
  1172. } else {
  1173. return '';
  1174. }
  1175. }
  1176. /**
  1177. * Return list of available collation that can be used for database
  1178. *
  1179. * @return array Liste of Collation
  1180. */
  1181. public function getListOfCollation()
  1182. {
  1183. $resql = $this->query('SHOW LC_COLLATE');
  1184. $liste = array();
  1185. if ($resql) {
  1186. $i = 0;
  1187. while ($obj = $this->fetch_object($resql)) {
  1188. $liste[$i]['collation'] = $obj->lc_collate;
  1189. $i++;
  1190. }
  1191. $this->free($resql);
  1192. } else {
  1193. return null;
  1194. }
  1195. return $liste;
  1196. }
  1197. /**
  1198. * Return full path of dump program
  1199. *
  1200. * @return string Full path of dump program
  1201. */
  1202. public function getPathOfDump()
  1203. {
  1204. $fullpathofdump = '/pathtopgdump/pg_dump';
  1205. if (file_exists('/usr/bin/pg_dump')) {
  1206. $fullpathofdump = '/usr/bin/pg_dump';
  1207. } else {
  1208. // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
  1209. $resql = $this->query('SHOW data_directory');
  1210. if ($resql) {
  1211. $liste = $this->fetch_array($resql);
  1212. $basedir = $liste['data_directory'];
  1213. $fullpathofdump = preg_replace('/data$/', 'bin', $basedir).'/pg_dump';
  1214. }
  1215. }
  1216. return $fullpathofdump;
  1217. }
  1218. /**
  1219. * Return full path of restore program
  1220. *
  1221. * @return string Full path of restore program
  1222. */
  1223. public function getPathOfRestore()
  1224. {
  1225. //$tool='pg_restore';
  1226. $tool = 'psql';
  1227. $fullpathofdump = '/pathtopgrestore/'.$tool;
  1228. if (file_exists('/usr/bin/'.$tool)) {
  1229. $fullpathofdump = '/usr/bin/'.$tool;
  1230. } else {
  1231. // TODO L'utilisateur de la base doit etre un superadmin pour lancer cette commande
  1232. $resql = $this->query('SHOW data_directory');
  1233. if ($resql) {
  1234. $liste = $this->fetch_array($resql);
  1235. $basedir = $liste['data_directory'];
  1236. $fullpathofdump = preg_replace('/data$/', 'bin', $basedir).'/'.$tool;
  1237. }
  1238. }
  1239. return $fullpathofdump;
  1240. }
  1241. /**
  1242. * Return value of server parameters
  1243. *
  1244. * @param string $filter Filter list on a particular value
  1245. * @return array Array of key-values (key=>value)
  1246. */
  1247. public function getServerParametersValues($filter = '')
  1248. {
  1249. $result = array();
  1250. $resql = 'select name,setting from pg_settings';
  1251. if ($filter) {
  1252. $resql .= " WHERE name = '".$this->escape($filter)."'";
  1253. }
  1254. $resql = $this->query($resql);
  1255. if ($resql) {
  1256. while ($obj = $this->fetch_object($resql)) {
  1257. $result[$obj->name] = $obj->setting;
  1258. }
  1259. }
  1260. return $result;
  1261. }
  1262. /**
  1263. * Return value of server status
  1264. *
  1265. * @param string $filter Filter list on a particular value
  1266. * @return array Array of key-values (key=>value)
  1267. */
  1268. public function getServerStatusValues($filter = '')
  1269. {
  1270. /* This is to return current running requests.
  1271. $sql='SELECT datname,procpid,current_query FROM pg_stat_activity ORDER BY procpid';
  1272. if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
  1273. $resql=$this->query($sql);
  1274. if ($resql)
  1275. {
  1276. $obj=$this->fetch_object($resql);
  1277. $result[$obj->Variable_name]=$obj->Value;
  1278. }
  1279. */
  1280. return array();
  1281. }
  1282. }