mssql.class.php 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  1. <?php
  2. /* Copyright (C) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2008 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2005-2007 Regis Houssin <regis.houssin@capnetworks.com>
  5. * Copyright (C) 2007 Simon Desee <simon@dedisoft.com>
  6. * Copyright (C) 2015 Cedric GROSS <c.gross@kreiz-it.fr>
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. /**
  22. * \file htdocs/core/db/mssql.class.php
  23. * \brief Fichier de la classe permettant de gerer une base MSSQL
  24. */
  25. require_once DOL_DOCUMENT_ROOT .'/core/db/DoliDB.class.php';
  26. /**
  27. * Classe de gestion de la database de dolibarr
  28. */
  29. class DoliDBMssql extends DoliDB
  30. {
  31. //! Database type
  32. public $type='mssql';
  33. //! Database label
  34. const LABEL='MSSQL';
  35. //! Charset used to force charset when creating database
  36. var $forcecharset='latin1'; // Can't be static as it may be forced with a dynamic value
  37. //! Collate used to force collate when creating database
  38. var $forcecollate='latin1_swedish_ci'; // Can't be static as it may be forced with a dynamic value
  39. //! Version min database
  40. const VERSIONMIN='2000';
  41. /** @var resource Resultset of last query */
  42. private $_results;
  43. /**
  44. * Constructor.
  45. * This create an opened connexion to a database server and eventually to a database
  46. *
  47. * @param string $type Type of database (mysql, pgsql...)
  48. * @param string $host Address of database server
  49. * @param string $user Nom de l'utilisateur autorise
  50. * @param string $pass Mot de passe
  51. * @param string $name Nom de la database
  52. * @param int $port Port of database server
  53. */
  54. function __construct($type, $host, $user, $pass, $name='', $port=0)
  55. {
  56. global $langs;
  57. $this->database_user=$user;
  58. $this->database_host=$host;
  59. $this->database_port=$port;
  60. $this->transaction_opened=0;
  61. if (! function_exists("mssql_connect"))
  62. {
  63. $this->connected = false;
  64. $this->ok = false;
  65. $this->error="Mssql PHP functions for using MSSql driver are not available in this version of PHP";
  66. dol_syslog(get_class($this)."::DoliDBMssql : MSsql PHP functions for using MSsql driver are not available in this version of PHP",LOG_ERR);
  67. return $this->ok;
  68. }
  69. if (! $host)
  70. {
  71. $this->connected = false;
  72. $this->ok = false;
  73. $this->error=$langs->trans("ErrorWrongHostParameter");
  74. dol_syslog(get_class($this)."::DoliDBMssql : Erreur Connect, wrong host parameters",LOG_ERR);
  75. return $this->ok;
  76. }
  77. // Essai connexion serveur
  78. $this->db = $this->connect($host, $user, $pass, $name, $port);
  79. if ($this->db)
  80. {
  81. // Si client connecte avec charset different de celui de la base Dolibarr
  82. // (La base Dolibarr a ete forcee en this->forcecharset a l'install)
  83. $this->connected = true;
  84. $this->ok = true;
  85. }
  86. else
  87. {
  88. // host, login ou password incorrect
  89. $this->connected = false;
  90. $this->ok = false;
  91. $this->error=mssql_get_last_message();
  92. dol_syslog(get_class($this)."::DoliDBMssql : Erreur Connect mssql_get_last_message=".$this->error,LOG_ERR);
  93. }
  94. // Si connexion serveur ok et si connexion base demandee, on essaie connexion base
  95. if ($this->connected && $name)
  96. {
  97. if ($this->select_db($name))
  98. {
  99. $this->database_selected = true;
  100. $this->database_name = $name;
  101. $this->ok = true;
  102. }
  103. else
  104. {
  105. $this->database_selected = false;
  106. $this->database_name = '';
  107. $this->ok = false;
  108. $this->error=$this->error();
  109. dol_syslog(get_class($this)."::DoliDBMssql : Erreur Select_db ".$this->error,LOG_ERR);
  110. }
  111. }
  112. else
  113. {
  114. // Pas de selection de base demandee, ok ou ko
  115. $this->database_selected = false;
  116. }
  117. return $this->ok;
  118. }
  119. /**
  120. * Convert a SQL request in Mysql syntax to native syntax
  121. *
  122. * @param string $line SQL request line to convert
  123. * @param string $type Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
  124. * @return string SQL request line converted
  125. */
  126. static function convertSQLFromMysql($line,$type='ddl')
  127. {
  128. return $line;
  129. }
  130. /**
  131. * Select a database
  132. *
  133. * @param string $database Name of database
  134. * @return boolean true if OK, false if KO
  135. */
  136. function select_db($database)
  137. {
  138. return @mssql_select_db($database, $this->db);
  139. }
  140. /**
  141. * Connexion to server
  142. *
  143. * @param string $host database server host
  144. * @param string $login login
  145. * @param string $passwd password
  146. * @param string $name name of database (not used for mysql, used for pgsql)
  147. * @param int $port Port of database server
  148. * @return false|resource|true Database access handler
  149. * @see close
  150. */
  151. function connect($host, $login, $passwd, $name, $port=0)
  152. {
  153. dol_syslog(get_class($this)."::connect host=$host, port=$port, login=$login, passwd=--hidden--, name=$name");
  154. $newhost=$host;
  155. if ($port) $newhost.=':'.$port;
  156. $this->db = @mssql_connect($newhost, $login, $passwd);
  157. //force les enregistrement en latin1 si la base est en utf8 par defaut
  158. // Supprime car plante sur mon PHP-Mysql. De plus, la base est forcement en latin1 avec
  159. // les nouvelles version de Dolibarr car force par l'install Dolibarr.
  160. //$this->query('SET NAMES '.$this->forcecharset);
  161. //print "Resultat fonction connect: ".$this->db;
  162. $set_options=array('SET ANSI_PADDING ON;',
  163. "SET ANSI_NULLS ON;",
  164. "SET ANSI_WARNINGS ON;",
  165. "SET ARITHABORT ON;",
  166. "SET CONCAT_NULL_YIELDS_NULL ON;",
  167. "SET QUOTED_IDENTIFIER ON;"
  168. );
  169. mssql_query(implode(' ',$set_options),$this->db);
  170. return $this->db;
  171. }
  172. /**
  173. * Return version of database server
  174. *
  175. * @return string Version string
  176. */
  177. function getVersion()
  178. {
  179. $resql=$this->query("SELECT @@VERSION");
  180. if ($resql)
  181. {
  182. $version=$this->fetch_array($resql);
  183. return $version['computed'];
  184. }
  185. else return '';
  186. }
  187. /**
  188. * Return version of database client driver
  189. *
  190. * @return string Version string
  191. */
  192. function getDriverInfo()
  193. {
  194. return 'php mssql driver';
  195. }
  196. /**
  197. * Close database connexion
  198. *
  199. * @return bool True if disconnect successfull, false otherwise
  200. * @see connect
  201. */
  202. function close()
  203. {
  204. if ($this->db)
  205. {
  206. if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
  207. $this->connected=false;
  208. return mssql_close($this->db);
  209. }
  210. return false;
  211. }
  212. /**
  213. * Start transaction
  214. *
  215. * @return bool true if transaction successfuly opened or already opened, false if error
  216. */
  217. function begin()
  218. {
  219. $res=mssql_query('select @@TRANCOUNT');
  220. $this->transaction_opened=mssql_result($res, 0, 0);
  221. if ($this->transaction_opened == 0)
  222. {
  223. //return 1; //There is a mess with auto_commit and 'SET IMPLICIT_TRANSACTIONS ON' generate also a mess
  224. $ret=mssql_query("SET IMPLICIT_TRANSACTIONS OFF;BEGIN TRANSACTION;",$this->db);
  225. if ($ret)
  226. {
  227. dol_syslog("BEGIN Transaction",LOG_DEBUG);
  228. }
  229. return $ret;
  230. }
  231. else
  232. {
  233. return true;
  234. }
  235. }
  236. /**
  237. * Validate a database transaction
  238. *
  239. * @param string $log Add more log to default log line
  240. * @return bool true if validation is OK or transaction level no started, false if ERROR
  241. */
  242. function commit($log='')
  243. {
  244. $res=mssql_query('select @@TRANCOUNT');
  245. $this->transaction_opened=mssql_result($res, 0, 0);
  246. if ($this->transaction_opened == 1)
  247. {
  248. //return 1; //There is a mess with auto_commit and 'SET IMPLICIT_TRANSACTION ON' generate also a mess
  249. $ret=mssql_query("COMMIT TRANSACTION",$this->db);
  250. if ($ret)
  251. {
  252. dol_syslog("COMMIT Transaction",LOG_DEBUG);
  253. return true;
  254. }
  255. else
  256. {
  257. return false;
  258. }
  259. }
  260. elseif ($this->transaction_opened > 1)
  261. {
  262. return true;
  263. }
  264. trigger_error("Commit requested but no transaction remain");
  265. return false;
  266. }
  267. /**
  268. * Annulation d'une transaction et retour aux anciennes valeurs
  269. *
  270. * @param string $log Add more log to default log line
  271. * @return bool true si annulation ok ou transaction non ouverte, false en cas d'erreur
  272. */
  273. function rollback($log='')
  274. {
  275. $res=mssql_query('select @@TRANCOUNT');
  276. $this->transaction_opened=mssql_result($res, 0, 0);
  277. if ($this->transaction_opened == 1)
  278. {
  279. $ret=mssql_query("ROLLBACK TRANSACTION",$this->db);
  280. dol_syslog("ROLLBACK Transaction".($log?' '.$log:''),LOG_DEBUG);
  281. return $ret;
  282. }
  283. elseif ($this->transaction_opened > 1)
  284. {
  285. return true;
  286. }
  287. trigger_error("Rollback requested but no transaction remain");
  288. return false;
  289. }
  290. /**
  291. * Execute a SQL request and return the resultset
  292. *
  293. * @param string $query SQL query string
  294. * @param int $usesavepoint 0=Default mode, 1=Run a savepoint before and a rollbock to savepoint if error (this allow to have some request with errors inside global transactions).
  295. * Note that with Mysql, this parameter is not used as Myssql can already commit a transaction even if one request is in error, without using savepoints.
  296. * @param string $type Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
  297. * @return false|resource|true Resultset of answer
  298. */
  299. function query($query,$usesavepoint=0,$type='auto')
  300. {
  301. $query = trim($query);
  302. if (preg_match('/^--/',$query)) return true;
  303. // Conversion syntaxe MySql vers MSDE.
  304. $query = str_ireplace("now()", "getdate()", $query);
  305. // Erreur SQL: cannot update timestamp field
  306. $query = str_ireplace(", tms = tms", "", $query);
  307. $query=preg_replace("/([. ,\t(])(percent|file|public)([. ,=\t)])/","$1[$2]$3",$query);
  308. if ($type=="auto" || $type='dml')
  309. {
  310. $query=preg_replace('/AUTO_INCREMENT/i','IDENTITY',$query);
  311. $query=preg_replace('/double/i','float',$query);
  312. $query=preg_replace('/float\((.*)\)/','numeric($1)',$query);
  313. $query=preg_replace('/([ \t])unsigned|IF NOT EXISTS[ \t]/i','$1',$query);
  314. $query=preg_replace('/([ \t])(MEDIUM|TINY|LONG){0,1}TEXT([ \t,])/i',"$1VARCHAR(MAX)$3",$query);
  315. $matches=array();
  316. $original_query='';
  317. if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+(?:(UNIQUE)|INDEX)\h+(?:INDEX)?\h*(\w+?)\h*\((.+)\)/is', $query,$matches))
  318. {
  319. $original_query=$query;
  320. $query="CREATE ".trim($matches[2])." INDEX [".trim($matches[3])."] ON [".trim($matches[1])."] (".trim($matches[4]).")";
  321. if ($matches[2]) {
  322. //check if columun is nullable cause Sql server only allow 1 null value if unique index.
  323. $fields=explode(",",trim($matches[4]));
  324. $fields_clear=array_map('trim',$fields);
  325. $infos=$this->GetFieldInformation(trim($matches[1]), $fields_clear);
  326. $query_comp=array();
  327. foreach($infos as $fld) {
  328. if ($fld->IS_NULLABLE == 'YES') {
  329. $query_comp[]=$fld->COLUMN_NAME." IS NOT NULL";
  330. }
  331. }
  332. if (! empty($query_comp))
  333. $query.=" WHERE ".implode(" AND ",$query_comp);
  334. }
  335. }
  336. else
  337. {
  338. if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+PRIMARY\h+KEY\h+(\w+?)\h*\((.+)\)/is', $query, $matches))
  339. {
  340. $original_query=$query;
  341. $query="ALTER TABLE [".$matches[1]."] ADD CONSTRAINT [".$matches[2]."] PRIMARY KEY CLUSTERED (".$matches[3].")";
  342. }
  343. }
  344. }
  345. if ($type=="auto" || $type='ddl')
  346. {
  347. $itemfound = stripos($query, " limit ");
  348. if ($itemfound !== false) {
  349. // Extraire le nombre limite
  350. $number = stristr($query, " limit ");
  351. $number = substr($number, 7);
  352. // Inserer l'instruction TOP et le nombre limite
  353. $query = str_ireplace("select ", "select top ".$number." ", $query);
  354. // Supprimer l'instruction MySql
  355. $query = str_ireplace(" limit ".$number, "", $query);
  356. }
  357. $itemfound = stripos($query, " week(");
  358. if ($itemfound !== false) {
  359. // Recreer une requete sans instruction Mysql
  360. $positionMySql = stripos($query, " week(");
  361. $newquery = substr($query, 0, $positionMySql);
  362. // Recuperer la date passee en parametre
  363. $extractvalue = stristr($query, " week(");
  364. $extractvalue = substr($extractvalue, 6);
  365. $positionMySql = stripos($extractvalue, ")");
  366. // Conserver la fin de la requete
  367. $endofquery = substr($extractvalue, $positionMySql);
  368. $extractvalue = substr($extractvalue, 0, $positionMySql);
  369. // Remplacer l'instruction MySql en Sql Server
  370. // Inserer la date en parametre et le reste de la requete
  371. $query = $newquery." DATEPART(week, ".$extractvalue.$endofquery;
  372. }
  373. if (preg_match('/^insert\h+(?:INTO)?\h*(\w+?)\h*\(.*\b(?:row)?id\b.*\)\h+VALUES/i',$query,$matches))
  374. {
  375. //var_dump($query);
  376. //var_dump($matches);
  377. //if (stripos($query,'llx_c_departements') !== false) var_dump($query);
  378. $sql='SET IDENTITY_INSERT ['.trim($matches[1]).'] ON;';
  379. @mssql_query($sql, $this->db);
  380. $post_query='SET IDENTITY_INSERT ['.trim($matches[1]).'] OFF;';
  381. }
  382. }
  383. //print "<!--".$query."-->";
  384. if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
  385. if (! $this->database_name)
  386. {
  387. // Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
  388. $ret = mssql_query($query, $this->db);
  389. }
  390. else
  391. {
  392. $ret = mssql_query($query, $this->db);
  393. }
  394. if (!empty($post_query))
  395. {
  396. @mssql_query($post_query, $this->db);
  397. }
  398. if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query))
  399. {
  400. // Si requete utilisateur, on la sauvegarde ainsi que son resultset
  401. if (! $ret)
  402. {
  403. $result = mssql_query("SELECT @@ERROR as code", $this->db);
  404. $row = mssql_fetch_array($result);
  405. $this->lastqueryerror = $query;
  406. $this->lasterror = $this->error();
  407. $this->lasterrno = $row["code"];
  408. dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR);
  409. if ($original_query) dol_syslog(get_class($this)."::query SQL Original query: ".$original_query, LOG_ERR);
  410. dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterror." (".$this->lasterrno.")", LOG_ERR);
  411. }
  412. $this->lastquery=$query;
  413. $this->_results = $ret;
  414. }
  415. return $ret;
  416. }
  417. /**
  418. * Renvoie la ligne courante (comme un objet) pour le curseur resultset
  419. *
  420. * @param resource $resultset Curseur de la requete voulue
  421. * @return object|false Object result line or false if KO or end of cursor
  422. */
  423. function fetch_object($resultset)
  424. {
  425. // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
  426. if (! is_resource($resultset)) { $resultset=$this->_results; }
  427. return mssql_fetch_object($resultset);
  428. }
  429. /**
  430. * Return datas as an array
  431. *
  432. * @param resource $resultset Resultset of request
  433. * @return array|false Array or false if KO or end of cursor
  434. */
  435. function fetch_array($resultset)
  436. {
  437. // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
  438. if (! is_resource($resultset)) { $resultset=$this->_results; }
  439. return mssql_fetch_array($resultset);
  440. }
  441. /**
  442. * Return datas as an array
  443. *
  444. * @param resource $resultset Resultset of request
  445. * @return array|false Array or false if KO or end of cursor
  446. */
  447. function fetch_row($resultset)
  448. {
  449. // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
  450. if (! is_resource($resultset)) { $resultset=$this->_results; }
  451. return @mssql_fetch_row($resultset);
  452. }
  453. /**
  454. * Return number of lines for result of a SELECT
  455. *
  456. * @param resource $resultset Resulset of requests
  457. * @return int Nb of lines
  458. * @see affected_rows
  459. */
  460. function num_rows($resultset)
  461. {
  462. // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
  463. if (! is_resource($resultset)) { $resultset=$this->_results; }
  464. return mssql_num_rows($resultset);
  465. }
  466. /**
  467. * Renvoie le nombre de lignes dans le resultat d'une requete INSERT, DELETE ou UPDATE
  468. *
  469. * @param resource $resultset Curseur de la requete voulue
  470. * @return int Nombre de lignes
  471. * @see num_rows
  472. */
  473. function affected_rows($resultset)
  474. {
  475. // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
  476. if (! is_resource($resultset)) { $resultset=$this->_results; }
  477. // mssql necessite un link de base pour cette fonction contrairement
  478. // a pqsql qui prend un resultset
  479. $rsRows = mssql_query("select @@rowcount as rows", $this->db);
  480. return mssql_result($rsRows, 0, "rows");
  481. //return mssql_affected_rows($this->db);
  482. }
  483. /**
  484. * Free last resultset used.
  485. *
  486. * @param resource $resultset Curseur de la requete voulue
  487. * @return bool
  488. */
  489. function free($resultset=null)
  490. {
  491. // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
  492. if (! is_resource($resultset)) { $resultset=$this->_results; }
  493. // Si resultset en est un, on libere la memoire
  494. if (is_resource($resultset)) mssql_free_result($resultset);
  495. }
  496. /**
  497. * Escape a string to insert data
  498. *
  499. * @param string $stringtoencode String to escape
  500. * @return string String escaped
  501. */
  502. function escape($stringtoencode)
  503. {
  504. return addslashes($stringtoencode);
  505. }
  506. /**
  507. * Convert (by PHP) a GM Timestamp date into a PHP server TZ to insert into a date field.
  508. * Function to use to build INSERT, UPDATE or WHERE predica
  509. *
  510. * @param string $param Date TMS to convert
  511. * @return string Date in a string YYYYMMDDHHMMSS
  512. */
  513. function idate($param)
  514. {
  515. return dol_print_date($param,"%Y-%m-%d %H:%M:%S");
  516. }
  517. /**
  518. * Return generic error code of last operation.
  519. *
  520. * @return string Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
  521. */
  522. function errno()
  523. {
  524. if (! $this->connected)
  525. {
  526. // Si il y a eu echec de connexion, $this->db n'est pas valide.
  527. return 'DB_ERROR_FAILED_TO_CONNECT';
  528. }
  529. else
  530. {
  531. // Constants to convert a MSSql error code to a generic Dolibarr error code
  532. $errorcode_map = array(
  533. 1004 => 'DB_ERROR_CANNOT_CREATE',
  534. 1005 => 'DB_ERROR_CANNOT_CREATE',
  535. 1006 => 'DB_ERROR_CANNOT_CREATE',
  536. 1007 => 'DB_ERROR_ALREADY_EXISTS',
  537. 1008 => 'DB_ERROR_CANNOT_DROP',
  538. 1025 => 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
  539. 1046 => 'DB_ERROR_NODBSELECTED',
  540. 1048 => 'DB_ERROR_CONSTRAINT',
  541. 2714 => 'DB_ERROR_TABLE_ALREADY_EXISTS',
  542. 1051 => 'DB_ERROR_NOSUCHTABLE',
  543. 1054 => 'DB_ERROR_NOSUCHFIELD',
  544. 1060 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
  545. 1061 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
  546. 2627 => 'DB_ERROR_RECORD_ALREADY_EXISTS',
  547. 102 => 'DB_ERROR_SYNTAX',
  548. 8120 => 'DB_ERROR_GROUP_BY_SYNTAX',
  549. 1068 => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
  550. 1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
  551. 1091 => 'DB_ERROR_NOSUCHFIELD',
  552. 1100 => 'DB_ERROR_NOT_LOCKED',
  553. 1136 => 'DB_ERROR_VALUE_COUNT_ON_ROW',
  554. 1146 => 'DB_ERROR_NOSUCHTABLE',
  555. 1216 => 'DB_ERROR_NO_PARENT',
  556. 1217 => 'DB_ERROR_CHILD_EXISTS',
  557. 1451 => 'DB_ERROR_CHILD_EXISTS',
  558. 1913 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS'
  559. );
  560. if (isset($errorcode_map[$this->lasterrno]))
  561. {
  562. return $errorcode_map[$this->lasterrno];
  563. }
  564. $errno=$this->lasterrno;
  565. return ($errno?'DB_ERROR_'.$errno:'0');
  566. }
  567. }
  568. /**
  569. * Return description of last error
  570. *
  571. * @return string Error text
  572. */
  573. function error()
  574. {
  575. if (! $this->connected) {
  576. // Si il y a eu echec de connexion, $this->db n'est pas valide pour mssql_get_last_message.
  577. return 'Not connected. Check setup parameters in conf/conf.php file and your mssql client and server versions';
  578. }
  579. else {
  580. return mssql_get_last_message();
  581. }
  582. }
  583. /**
  584. * Get last ID after an insert INSERT
  585. *
  586. * @param string $tab Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql
  587. * @param string $fieldid Field name
  588. * @return int Id of row or -1 on error
  589. */
  590. function last_insert_id($tab,$fieldid='rowid')
  591. {
  592. $res = $this->query("SELECT @@IDENTITY as id");
  593. if ($res && $data = $this->fetch_array($res))
  594. {
  595. return $data["id"];
  596. }
  597. else
  598. {
  599. return -1;
  600. }
  601. }
  602. /**
  603. * Encrypt sensitive data in database
  604. * Warning: This function includes the escape, so it must use direct value
  605. *
  606. * @param string $fieldorvalue Field name or value to encrypt
  607. * @param int $withQuotes Return string with quotes
  608. * @return string XXX(field) or XXX('value') or field or 'value'
  609. */
  610. function encrypt($fieldorvalue, $withQuotes=0)
  611. {
  612. global $conf;
  613. // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
  614. $cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
  615. //Encryption key
  616. $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
  617. $return = $fieldorvalue;
  618. return ($withQuotes?"'":"").$this->escape($return).($withQuotes?"'":"");
  619. }
  620. /**
  621. * Decrypt sensitive data in database
  622. *
  623. * @param string $value Value to decrypt
  624. * @return string Decrypted value if used
  625. */
  626. function decrypt($value)
  627. {
  628. global $conf;
  629. // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
  630. $cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
  631. //Encryption key
  632. $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
  633. $return = $value;
  634. return $return;
  635. }
  636. /**
  637. * Return connexion ID
  638. *
  639. * @return string Id connexion
  640. */
  641. function DDLGetConnectId()
  642. {
  643. $resql=$this->query('SELECT CONNECTION_ID()');
  644. if ($resql)
  645. {
  646. $row=$this->fetch_row($resql);
  647. return $row[0];
  648. }
  649. else return '?';
  650. }
  651. /**
  652. * Create a new database
  653. * Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
  654. * We force to create database with charset this->forcecharset and collate this->forcecollate
  655. *
  656. * @param string $database Database name to create
  657. * @param string $charset Charset used to store data
  658. * @param string $collation Charset used to sort data
  659. * @param string $owner Username of database owner
  660. * @return false|resource|true resource defined if OK, false if KO
  661. */
  662. function DDLCreateDb($database,$charset='',$collation='',$owner='')
  663. {
  664. /*if (empty($charset)) $charset=$this->forcecharset;
  665. if (empty($collation)) $collation=$this->forcecollate;
  666. */
  667. $sql = 'CREATE DATABASE '.$this->EscapeFieldName($database);
  668. //TODO: Check if we need to force a charset
  669. //$sql.= ' DEFAULT CHARACTER SET '.$charset.' DEFAULT COLLATE '.$collation;
  670. $ret=$this->query($sql);
  671. $this->select_db($database);
  672. $sql="CREATE USER [$owner] FOR LOGIN [$owner]";
  673. mssql_query($sql,$this->db);
  674. $sql="ALTER ROLE [db_owner] ADD MEMBER [$owner]";
  675. mssql_query($sql,$this->db);
  676. $sql="ALTER DATABASE [$database] SET ANSI_NULL_DEFAULT ON;";
  677. @mssql_query($sql,$this->db);
  678. $sql="ALTER DATABASE [$database] SET ANSI_NULL ON;";
  679. @mssql_query($sql,$this->db);
  680. return $ret;
  681. }
  682. /**
  683. * List tables into a database
  684. *
  685. * @param string $database Name of database
  686. * @param string $table Nmae of table filter ('xxx%')
  687. * @return array List of tables in an array
  688. */
  689. function DDLListTables($database,$table='')
  690. {
  691. $this->_results = mssql_list_tables($database, $this->db);
  692. return $this->_results;
  693. }
  694. /**
  695. * List information of columns into a table.
  696. *
  697. * @param string $table Name of table
  698. * @return array Tableau des informations des champs de la table
  699. */
  700. function DDLInfoTable($table)
  701. {
  702. // FIXME: Dummy method
  703. // TODO: Implement
  704. // May help: https://stackoverflow.com/questions/600446/sql-server-how-do-you-return-the-column-names-from-a-table
  705. $infotables=array();
  706. return $infotables;
  707. }
  708. /**
  709. * Create a table into database
  710. *
  711. * @param string $table Nom de la table
  712. * @param array $fields Tableau associatif [nom champ][tableau des descriptions]
  713. * @param string $primary_key Nom du champ qui sera la clef primaire
  714. * @param string $type Type de la table
  715. * @param array $unique_keys Tableau associatifs Nom de champs qui seront clef unique => valeur
  716. * @param array $fulltext_keys Tableau des Nom de champs qui seront indexes en fulltext
  717. * @param array $keys Tableau des champs cles noms => valeur
  718. * @return int <0 if KO, >=0 if OK
  719. */
  720. function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
  721. {
  722. // FIXME: $fulltext_keys parameter is unused
  723. // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
  724. // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
  725. $sql = "create table ".$table."(";
  726. $i=0;
  727. foreach($fields as $field_name => $field_desc)
  728. {
  729. $sqlfields[$i] = $field_name." ";
  730. $sqlfields[$i] .= $field_desc['type'];
  731. if( preg_match("/^[^\s]/i",$field_desc['value']))
  732. $sqlfields[$i] .= "(".$field_desc['value'].")";
  733. else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
  734. $sqlfields[$i] .= " ".$field_desc['attribute'];
  735. else if( preg_match("/^[^\s]/i",$field_desc['default']))
  736. {
  737. if(preg_match("/null/i",$field_desc['default']))
  738. $sqlfields[$i] .= " default ".$field_desc['default'];
  739. else
  740. $sqlfields[$i] .= " default '".$field_desc['default']."'";
  741. }
  742. else if( preg_match("/^[^\s]/i",$field_desc['null']))
  743. $sqlfields[$i] .= " ".$field_desc['null'];
  744. else if( preg_match("/^[^\s]/i",$field_desc['extra']))
  745. $sqlfields[$i] .= " ".$field_desc['extra'];
  746. $i++;
  747. }
  748. if($primary_key != "")
  749. $pk = "primary key(".$primary_key.")";
  750. if(is_array($unique_keys))
  751. {
  752. $i = 0;
  753. foreach($unique_keys as $key => $value)
  754. {
  755. $sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
  756. $i++;
  757. }
  758. }
  759. if(is_array($keys))
  760. {
  761. $i = 0;
  762. foreach($keys as $key => $value)
  763. {
  764. $sqlk[$i] = "KEY ".$key." (".$value.")";
  765. $i++;
  766. }
  767. }
  768. $sql .= implode(',',$sqlfields);
  769. if($primary_key != "")
  770. $sql .= ",".$pk;
  771. if(is_array($unique_keys))
  772. $sql .= ",".implode(',',$sqluq);
  773. if(is_array($keys))
  774. $sql .= ",".implode(',',$sqlk);
  775. $sql .=") type=".$type;
  776. dol_syslog($sql);
  777. if(! $this -> query($sql))
  778. return -1;
  779. else
  780. return 1;
  781. }
  782. /**
  783. * Return a pointer of line with description of a table or field
  784. *
  785. * @param string $table Name of table
  786. * @param string $field Optionnel : Name of field if we want description of field
  787. * @return false|resource|true Resource
  788. */
  789. function DDLDescTable($table,$field="")
  790. {
  791. $sql="DESC ".$table." ".$field;
  792. dol_syslog($sql);
  793. $this->_results = $this->query($sql);
  794. return $this->_results;
  795. }
  796. /**
  797. * Create a new field into table
  798. *
  799. * @param string $table Name of table
  800. * @param string $field_name Name of field to add
  801. * @param string $field_desc Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
  802. * @param string $field_position Optionnel ex.: "after champtruc"
  803. * @return int <0 if KO, >0 if OK
  804. */
  805. function DDLAddField($table,$field_name,$field_desc,$field_position="")
  806. {
  807. // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
  808. // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
  809. $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
  810. $sql .= $field_desc['type'];
  811. if( preg_match("/^[^\s]/i",$field_desc['value']))
  812. $sql .= "(".$field_desc['value'].")";
  813. if( preg_match("/^[^\s]/i",$field_desc['attribute']))
  814. $sql .= " ".$field_desc['attribute'];
  815. if( preg_match("/^[^\s]/i",$field_desc['null']))
  816. $sql .= " ".$field_desc['null'];
  817. if( preg_match("/^[^\s]/i",$field_desc['default']))
  818. if(preg_match("/null/i",$field_desc['default']))
  819. $sql .= " default ".$field_desc['default'];
  820. else
  821. $sql .= " default '".$field_desc['default']."'";
  822. if( preg_match("/^[^\s]/i",$field_desc['extra']))
  823. $sql .= " ".$field_desc['extra'];
  824. $sql .= " ".$field_position;
  825. if(! $this -> query($sql))
  826. return -1;
  827. else
  828. return 1;
  829. }
  830. /**
  831. * Update format of a field into a table
  832. *
  833. * @param string $table Name of table
  834. * @param string $field_name Name of field to modify
  835. * @param string $field_desc Array with description of field format
  836. * @return int <0 if KO, >0 if OK
  837. */
  838. function DDLUpdateField($table,$field_name,$field_desc)
  839. {
  840. $sql = "ALTER TABLE ".$table;
  841. $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
  842. if ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
  843. $sql.="(".$field_desc['value'].")";
  844. }
  845. dol_syslog($sql,LOG_DEBUG);
  846. if (! $this->query($sql))
  847. return -1;
  848. else
  849. return 1;
  850. }
  851. /**
  852. * Drop a field from table
  853. *
  854. * @param string $table Name of table
  855. * @param string $field_name Name of field to drop
  856. * @return int <0 if KO, >0 if OK
  857. */
  858. function DDLDropField($table,$field_name)
  859. {
  860. $sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
  861. dol_syslog($sql,LOG_DEBUG);
  862. if (! $this->query($sql))
  863. {
  864. $this->error=$this->lasterror();
  865. return -1;
  866. }
  867. else return 1;
  868. }
  869. /**
  870. * Create a user and privileges to connect to database (even if database does not exists yet)
  871. *
  872. * @param string $dolibarr_main_db_host Ip serveur
  873. * @param string $dolibarr_main_db_user Nom user a creer
  874. * @param string $dolibarr_main_db_pass Mot de passe user a creer
  875. * @param string $dolibarr_main_db_name Database name where user must be granted
  876. * @return int <0 if KO, >=0 if OK
  877. */
  878. function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
  879. {
  880. $sql = "CREATE LOGIN ".$this->EscapeFieldName($dolibarr_main_db_user)." WITH PASSWORD='$dolibarr_main_db_pass'";
  881. dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
  882. $resql=$this->query($sql);
  883. if (! $resql)
  884. {
  885. if ($this->lasterrno != '15025')
  886. {
  887. return -1;
  888. }
  889. else
  890. {
  891. // If user already exists, we continue to set permissions
  892. dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
  893. }
  894. }
  895. $sql="SELECT name from sys.databases where name='".$dolibarr_main_db_name."'";
  896. $ressql=$this->query($sql);
  897. if (! $ressql)
  898. {
  899. dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
  900. return -1;
  901. }
  902. else
  903. {
  904. if ($num)
  905. {
  906. $this->select_db($dolibarr_main_db_name);
  907. $sql="CREATE USER [$dolibarr_main_db_user] FOR LOGIN [$dolibarr_main_db_user]";
  908. $this->query($sql);
  909. $sql="ALTER ROLE [db_owner] ADD MEMBER [$dolibarr_main_db_user]";
  910. $this->query($sql);
  911. }
  912. }
  913. return 1;
  914. }
  915. /**
  916. * Return charset used to store data in database
  917. *
  918. * @return string Charset
  919. */
  920. function getDefaultCharacterSetDatabase()
  921. {
  922. // FIXME: Dummy method
  923. // TODO: Implement
  924. return '';
  925. }
  926. /**
  927. * Return list of available charset that can be used to store data in database
  928. *
  929. * @return array List of Charset
  930. */
  931. function getListOfCharacterSet()
  932. {
  933. // FIXME: Dummy method
  934. // TODO: Implement
  935. return '';
  936. }
  937. /**
  938. * Return collation used in database
  939. *
  940. * @return string Collation value
  941. */
  942. function getDefaultCollationDatabase()
  943. {
  944. $resql=$this->query("SELECT SERVERPROPERTY('collation')");
  945. if (!$resql)
  946. {
  947. return $this->forcecollate;
  948. }
  949. $liste=$this->fetch_array($resql);
  950. return $liste['computed'];
  951. }
  952. /**
  953. * Return list of available collation that can be used for database
  954. *
  955. * @return array Liste of Collation
  956. */
  957. function getListOfCollation()
  958. {
  959. // FIXME: Dummy method
  960. // TODO: Implement
  961. return array();
  962. }
  963. /**
  964. * Return full path of dump program
  965. *
  966. * @return string Full path of dump program
  967. */
  968. function getPathOfDump()
  969. {
  970. // FIXME: Dummy method
  971. // TODO: Implement
  972. return '';
  973. }
  974. /**
  975. * Return full path of restore program
  976. *
  977. * @return string Full path of restore program
  978. */
  979. function getPathOfRestore()
  980. {
  981. // FIXME: Dummy method
  982. // TODO: Implement
  983. return '';
  984. }
  985. /**
  986. * Return value of server parameters
  987. *
  988. * @param string $filter Filter list on a particular value
  989. * @return array Array of key-values (key=>value)
  990. */
  991. function getServerParametersValues($filter='')
  992. {
  993. // FIXME: Dummy method
  994. // TODO: Implement
  995. // May help: SELECT SERVERPROPERTY
  996. $result=array();
  997. return $result;
  998. }
  999. /**
  1000. * Return value of server status
  1001. *
  1002. * @param string $filter Filter list on a particular value
  1003. * @return array Array of key-values (key=>value)
  1004. */
  1005. function getServerStatusValues($filter='')
  1006. {
  1007. // FIXME: Dummy method
  1008. // TODO: Implement
  1009. // May help: http://www.experts-exchange.com/Database/MS-SQL-Server/Q_20971756.html
  1010. return array();
  1011. }
  1012. /**
  1013. * Escape a field name according to escape's syntax
  1014. *
  1015. * @param string $fieldname Field's name to escape
  1016. * @return string field's name escaped
  1017. */
  1018. function EscapeFieldName($fieldname) {
  1019. return "[".$fieldname."]";
  1020. }
  1021. /**
  1022. * Get information on field
  1023. *
  1024. * @param string $table Table name which contains fields
  1025. * @param mixed $fields String for one field or array of string for multiple field
  1026. * @return false|object
  1027. */
  1028. function GetFieldInformation($table,$fields) {
  1029. $sql="SELECT * from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='".$this->escape($table)."' AND COLUMN_NAME";
  1030. if (is_array($fields))
  1031. {
  1032. $where=" IN ('".implode("','",$fields)."')";
  1033. }
  1034. else
  1035. {
  1036. $where="='".$this->escape($fields)."'";
  1037. }
  1038. $result=array();
  1039. $ret=mssql_query($sql.$where,$this->db);
  1040. if ($ret)
  1041. {
  1042. while($obj=mssql_fetch_object($ret))
  1043. {
  1044. $result[]=$obj;
  1045. }
  1046. }
  1047. else
  1048. return false;
  1049. return $result;
  1050. }
  1051. }