pgsql.class.php 43 KB

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