pgsql.class.php 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  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.0)
  150. // Replace group_concat(x) or group_concat(x SEPARATOR ',') with string_agg(x, ',')
  151. $line = preg_replace('/GROUP_CONCAT/i', 'STRING_AGG', $line);
  152. $line = preg_replace('/ SEPARATOR/i', ',', $line);
  153. $line = preg_replace('/STRING_AGG\(([^,\)]+)\)/i', 'STRING_AGG(\\1, \',\')', $line);
  154. //print $line."\n";
  155. if ($type == 'auto')
  156. {
  157. if (preg_match('/ALTER TABLE/i',$line)) $type='dml';
  158. else if (preg_match('/CREATE TABLE/i',$line)) $type='dml';
  159. else if (preg_match('/DROP TABLE/i',$line)) $type='dml';
  160. }
  161. $line=preg_replace('/ as signed\)/i',' as integer)',$line);
  162. if ($type == 'dml')
  163. {
  164. $line=preg_replace('/\s/',' ',$line); // Replace tabulation with space
  165. // we are inside create table statement so lets process datatypes
  166. if (preg_match('/(ISAM|innodb)/i',$line)) { // end of create table sequence
  167. $line=preg_replace('/\)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb);/i',');',$line);
  168. $line=preg_replace('/\)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb);/i',');',$line);
  169. $line=preg_replace('/,$/','',$line);
  170. }
  171. // Process case: "CREATE TABLE llx_mytable(rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY,code..."
  172. if (preg_match('/[\s\t\(]*(\w*)[\s\t]+int.*auto_increment/i',$line,$reg)) {
  173. $newline=preg_replace('/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i','\\1 \\2 SERIAL PRIMARY KEY',$line);
  174. //$line = "-- ".$line." replaced by --\n".$newline;
  175. $line=$newline;
  176. }
  177. // tinyint type conversion
  178. $line=preg_replace('/tinyint\(?[0-9]*\)?/','smallint',$line);
  179. $line=preg_replace('/tinyint/i','smallint',$line);
  180. // nuke unsigned
  181. $line=preg_replace('/(int\w+|smallint)\s+unsigned/i','\\1',$line);
  182. // blob -> text
  183. $line=preg_replace('/\w*blob/i','text',$line);
  184. // tinytext/mediumtext -> text
  185. $line=preg_replace('/tinytext/i','text',$line);
  186. $line=preg_replace('/mediumtext/i','text',$line);
  187. $line=preg_replace('/text\([0-9]+\)/i','text',$line);
  188. // change not null datetime field to null valid ones
  189. // (to support remapping of "zero time" to null
  190. $line=preg_replace('/datetime not null/i','datetime',$line);
  191. $line=preg_replace('/datetime/i','timestamp',$line);
  192. // double -> numeric
  193. $line=preg_replace('/^double/i','numeric',$line);
  194. $line=preg_replace('/(\s*)double/i','\\1numeric',$line);
  195. // float -> numeric
  196. $line=preg_replace('/^float/i','numeric',$line);
  197. $line=preg_replace('/(\s*)float/i','\\1numeric',$line);
  198. //Check tms timestamp field case (in Mysql this field is defautled to now and
  199. // on update defaulted by now
  200. $line=preg_replace('/(\s*)tms(\s*)timestamp/i','\\1tms timestamp without time zone DEFAULT now() NOT NULL',$line);
  201. // nuke ON UPDATE CURRENT_TIMESTAMP
  202. $line=preg_replace('/(\s*)on(\s*)update(\s*)CURRENT_TIMESTAMP/i','\\1',$line);
  203. // unique index(field1,field2)
  204. if (preg_match('/unique index\s*\((\w+\s*,\s*\w+)\)/i',$line))
  205. {
  206. $line=preg_replace('/unique index\s*\((\w+\s*,\s*\w+)\)/i','UNIQUE\(\\1\)',$line);
  207. }
  208. // We remove end of requests "AFTER fieldxxx"
  209. $line=preg_replace('/\sAFTER [a-z0-9_]+/i','',$line);
  210. // We remove start of requests "ALTER TABLE tablexxx" if this is a DROP INDEX
  211. $line=preg_replace('/ALTER TABLE [a-z0-9_]+\s+DROP INDEX/i','DROP INDEX',$line);
  212. // Translate order to rename fields
  213. if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i',$line,$reg))
  214. {
  215. $line = "-- ".$line." replaced by --\n";
  216. $line.= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
  217. }
  218. // Translate order to modify field format
  219. if (preg_match('/ALTER TABLE ([a-z0-9_]+)\s+MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i',$line,$reg))
  220. {
  221. $line = "-- ".$line." replaced by --\n";
  222. $newreg3=$reg[3];
  223. $newreg3=preg_replace('/ DEFAULT NULL/i','',$newreg3);
  224. $newreg3=preg_replace('/ NOT NULL/i','',$newreg3);
  225. $newreg3=preg_replace('/ NULL/i','',$newreg3);
  226. $newreg3=preg_replace('/ DEFAULT 0/i','',$newreg3);
  227. $newreg3=preg_replace('/ DEFAULT \'?[0-9a-zA-Z_@]*\'?/i','',$newreg3);
  228. $line.= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3;
  229. // TODO Add alter to set default value or null/not null if there is this in $reg[3]
  230. }
  231. // alter table add primary key (field1, field2 ...) -> We remove the primary key name not accepted by PostGreSQL
  232. // ALTER TABLE llx_dolibarr_modules ADD PRIMARY KEY pk_dolibarr_modules (numero, entity)
  233. if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\((.*)$/i',$line,$reg))
  234. {
  235. $line = "-- ".$line." replaced by --\n";
  236. $line.= "ALTER TABLE ".$reg[1]." ADD PRIMARY KEY (".$reg[3];
  237. }
  238. // Translate order to drop foreign keys
  239. // ALTER TABLE llx_dolibarr_modules DROP FOREIGN KEY fk_xxx
  240. if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i',$line,$reg))
  241. {
  242. $line = "-- ".$line." replaced by --\n";
  243. $line.= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
  244. }
  245. // Translate order to add foreign keys
  246. // ALTER TABLE llx_tablechild ADD CONSTRAINT fk_tablechild_fk_fieldparent FOREIGN KEY (fk_fieldparent) REFERENCES llx_tableparent (rowid)
  247. if (preg_match('/ALTER\s+TABLE\s+(.*)\s*ADD CONSTRAINT\s+(.*)\s*FOREIGN\s+KEY\s*(.*)$/i',$line,$reg))
  248. {
  249. $line=preg_replace('/;$/','',$line);
  250. $line.=" DEFERRABLE INITIALLY IMMEDIATE;";
  251. }
  252. // alter table add [unique] [index] (field1, field2 ...)
  253. // ALTER TABLE llx_accountingaccount ADD INDEX idx_accountingaccount_fk_pcg_version (fk_pcg_version)
  254. if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\(([\w,\s]+)\)/i',$line,$reg))
  255. {
  256. $fieldlist=$reg[4];
  257. $idxname=$reg[3];
  258. $tablename=$reg[1];
  259. $line = "-- ".$line." replaced by --\n";
  260. $line.= "CREATE ".(preg_match('/UNIQUE/',$reg[2])?'UNIQUE ':'')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")";
  261. }
  262. }
  263. // To have postgresql case sensitive
  264. $line=str_replace(' LIKE \'',' ILIKE \'',$line);
  265. $line=str_replace(' LIKE BINARY \'',' LIKE \'',$line);
  266. // Replace INSERT IGNORE into INSERT
  267. $line=preg_replace('/^INSERT IGNORE/','INSERT',$line);
  268. // Delete using criteria on other table must not declare twice the deleted table
  269. // DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable
  270. if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i',$line,$reg))
  271. {
  272. if ($reg[1] == $reg[2]) // If same table, we remove second one
  273. {
  274. $line=preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i','DELETE FROM \\1 USING \\3', $line);
  275. }
  276. }
  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. }