2 /***************************************************************************
3 * Copyright (C) 2003-2009 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 **************************************************************************/
24 private static $mysqli = null
;
26 public static function connect()
29 self
::$mysqli = new mysqli($globals->dbhost
, $globals->dbuser
, $globals->dbpwd
, $globals->dbdb
);
30 if ($globals->debug
& DEBUG_BT
) {
31 $bt = new PlBacktrace('MySQL');
32 if (mysqli_connect_errno()) {
33 $bt->newEvent("MySQLI connection", 0, mysqli_connect_error());
37 self
::$mysqli->autocommit(true
);
38 self
::$mysqli->set_charset($globals->dbcharset
);
42 public static function _prepare($args)
44 $query = array_map(Array('XDB', 'escape'), $args);
45 $query[0] = str_replace('{?}', '%s', str_replace('%', '%%', $args[0]));
46 return call_user_func_array('sprintf', $query);
49 public static function _reformatQuery($query)
51 $query = preg_split("/\n\\s*/", trim($query));
53 foreach ($query as $key=>$line) {
55 if (preg_match('/^([A-Z]+(?:\s+(?:JOIN|BY|FROM|INTO))?)\s+(.*)/u', $line, $matches)
56 && $matches[1] != 'AND' && $matches[1] != 'OR')
58 $local = strlen($matches[1]);
59 $line = $matches[1] . ' ' . $matches[2];
60 $length = max($length, $local);
62 $query[$key] = array($line, $local);
65 foreach ($query as $array) {
66 list($line, $local) = $array;
67 $local = max(0, $length - $local);
68 $res .= str_repeat(' ', $local) . $line . "\n";
69 $length +
= 2 * (substr_count($line, '(') - substr_count($line, ')'));
74 public static function _query($query)
78 if (!self
::$mysqli && !self
::connect()) {
79 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
80 Platal
::page()->kill('Impossible de se connecter à la base de données.');
84 if ($globals->debug
& DEBUG_BT
) {
86 if (strpos($query, 'FOUND_ROWS()') === false
) {
87 $res = self
::$mysqli->query("EXPLAIN $query");
89 while ($row = $res->fetch_assoc()) {
95 PlBacktrace
::$bt['MySQL']->start(XDB
::_reformatQuery($query));
98 $res = XDB
::$mysqli->query($query);
100 if ($globals->debug
& DEBUG_BT
) {
101 PlBacktrace
::$bt['MySQL']->stop(@$res->num_rows ?
$res->num_rows
: self
::$mysqli->affected_rows
,
102 self
::$mysqli->error
,
106 if ($res === false
) {
107 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
108 if (strpos($query, 'INSERT') === false
&& strpos($query, 'UPDATE') === false
109 && strpos($query, 'REPLACE') === false
&& strpos($query, 'DELETE') === false
) {
110 $text = 'Erreur lors de l\'interrogation de la base de données';
112 $text = 'Erreur lors de l\'écriture dans la base de données';
114 if ($globals->debug
) {
115 $text .= '<pre>' . pl_entities(XDB
::_reformatQuery($query)) . '</pre>';
117 $file = fopen($globals->spoolroot
. '/spool/tmp/query_errors', 'a');
118 fwrite($file, '<pre>' . pl_entities(XDB
::_reformatQuery($query)) . '</pre>'
119 . '<pre>' . XDB
::$mysqli->error
. '</pre>' . "\n");
122 Platal
::page()->kill($text);
128 private static function queryv($query)
130 return new XOrgDBResult(self
::_prepare($query));
133 public static function query()
135 return self
::queryv(func_get_args());
138 public static function format()
140 return self
::_prepare(func_get_args());
143 // Produce the SQL statement for setting/unsetting a flag
144 public static function changeFlag($fieldname, $flagname, $state)
147 return XDB
::format($fieldname . ' = CONCAT({?}, \',\', ' . $fieldname . ')', $flagname);
149 return XDB
::format($fieldname . ' = REPLACE(' . $fieldname . ', {?}, \'\')', $flagname);
153 // Produce the SQL statement representing an array
154 public static function formatArray(array $array)
156 return '(' . implode(', ', array_map(array('XDB', 'escape'), $array)) . ')';
159 public static function execute()
162 $args = func_get_args();
163 if ($globals->mode
!= 'rw' && !strpos($args[0], 'logger')) {
166 return self
::_query(XDB
::_prepare($args));
169 public static function iterator()
171 return new XOrgDBIterator(self
::_prepare(func_get_args()));
174 public static function iterRow()
176 return new XOrgDBIterator(self
::_prepare(func_get_args()), MYSQL_NUM
);
179 private static function findQuery($params, $default = array())
181 for ($i = 0 ; $i < count($default) ; ++
$i) {
183 foreach (array('insert', 'select', 'replace', 'delete', 'update') as $kwd) {
184 if (stripos($params[0], $kwd) !== false
) {
192 $default[$i] = array_shift($params);
195 return array($default, $params);
198 /** Fetch all rows returned by the given query.
199 * This functions can take 2 optional arguments (cf XOrgDBResult::fetchAllRow()).
200 * Optional arguments are given *before* the query.
202 public static function fetchAllRow()
204 list($args, $query) = self
::findQuery(func_get_args(), array(false
, false
));
205 return self
::queryv($query)->fetchAllRow($args[0], $args[1]);
208 /** Fetch all rows returned by the given query.
209 * This functions can take 2 optional arguments (cf XOrgDBResult::fetchAllAssoc()).
210 * Optional arguments are given *before* the query.
212 public static function fetchAllAssoc()
214 list($args, $query) = self
::findQuery(func_get_args(), array(false
, false
));
215 return self
::queryv($query)->fetchAllAssoc($args[0], $args[1]);
218 public static function fetchOneCell()
220 list($args, $query) = self
::findQuery(func_get_args());
221 return self
::queryv($query)->fetchOneCell();
224 public static function fetchOneRow()
226 list($args, $query) = self
::findQuery(func_get_args());
227 return self
::queryv($query)->fetchOneRow();
230 public static function fetchOneAssoc()
232 list($args, $query) = self
::findQuery(func_get_args());
233 return self
::queryv($query)->fetchOneAssoc();
236 /** Fetch a column from the result of the given query.
237 * This functions can take 1 optional arguments (cf XOrgDBResult::fetchColumn()).
238 * Optional arguments are given *before* the query.
240 public static function fetchColumn()
242 list($args, $query) = self
::findQuery(func_get_args(), array(0));
243 return self
::queryv($query)->fetchColumn();
246 public static function insertId()
248 return self
::$mysqli->insert_id
;
251 public static function errno()
253 return self
::$mysqli->errno
;
256 public static function error()
258 return self
::$mysqli->error
;
261 public static function affectedRows()
263 return self
::$mysqli->affected_rows
;
266 public static function escape($var)
268 switch (gettype($var)) {
278 return "'".addslashes($var)."'";
284 if ($var instanceof PlFlagSet
) {
285 return "'" . addslashes($var->flags()) . "'";
288 return "'".addslashes(serialize($var))."'";
291 die(var_export($var, true
).' is not a valid for a database entry');
301 public function __construct($query)
303 $this->_res
= XDB
::_query($query);
306 public function free()
314 protected function _fetchRow()
316 return $this->_res ?
$this->_res
->fetch_row() : null
;
319 protected function _fetchAssoc()
321 return $this->_res ?
$this->_res
->fetch_assoc() : null
;
324 public function fetchAllRow($id = false
, $keep_array = false
)
330 while (($data = $this->_res
->fetch_row())) {
334 if (!$keep_array && count($data) == 1) {
336 $result[$key] = current($data);
338 $result[$key] = $data;
348 public function fetchAllAssoc($id = false
, $keep_array = false
)
354 while (($data = $this->_res
->fetch_assoc())) {
358 if (!$keep_array && count($data) == 1) {
360 $result[$key] = current($data);
362 $result[$key] = $data;
372 public function fetchOneAssoc()
374 $tmp = $this->_fetchAssoc();
379 public function fetchOneRow()
381 $tmp = $this->_fetchRow();
386 public function fetchOneCell()
388 $tmp = $this->_fetchRow();
393 public function fetchColumn($key = 0)
396 if (is_numeric($key)) {
397 while($tmp = $this->_fetchRow()) {
401 while($tmp = $this->_fetchAssoc()) {
409 public function fetchOneField()
411 return $this->_res ?
$this->_res
->fetch_field() : null
;
414 public function fetchFields()
417 while ($res[] = $this->fetchOneField());
421 public function numRows()
423 return $this->_res ?
$this->_res
->num_rows
: 0;
426 public function fieldCount()
428 return $this->_res ?
$this->_res
->field_count
: 0;
432 require_once dirname(__FILE__
) . '/pliterator.php';
434 class XOrgDBIterator
extends XOrgDBResult
implements PlIterator
441 private $_mode = MYSQL_ASSOC
;
443 public function __construct($query, $mode = MYSQL_ASSOC
)
445 parent
::__construct($query);
447 $this->_total
= $this->numRows();
449 $this->_fields
= $this->fieldCount();
450 $this->_mode
= $mode;
453 public function next()
456 if ($this->_pos
> $this->_total
) {
461 return $this->_mode
!= MYSQL_ASSOC ?
$this->_fetchRow() : $this->_fetchAssoc();
464 public function first()
466 return $this->_pos
== 1;
469 public function last()
471 return $this->_pos
== $this->_total
;
474 public function total()
476 return $this->_total
;
479 public function nextField()
482 if ($this->_fpos
> $this->_fields
) {
485 return $this->fetchOneField();
488 public function firstField()
490 return $this->_fpos
== 1;
493 public function lastField()
495 return $this->_fpos
== $this->_fields
;
498 public function totalFields()
500 return $this->_fields
;
504 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: