pgsql.class.php 48 KB

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