2 /***************************************************************************
3 * Copyright (C) 2003-2010 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)
45 $query = array_map(Array('XDB', 'escape'), $args);
46 $query[0] = preg_replace('/#([a-z0-9]+)#/', $globals->dbprefix
. '$1', $args[0]);
47 $query[0] = str_replace('%', '%%', $query[0]);
48 $query[0] = str_replace('{?}', '%s', $query[0]);
49 return call_user_func_array('sprintf', $query);
52 public static function reformatQuery($query)
54 $query = preg_split("/\n\\s*/", trim($query));
56 foreach ($query as $key=>$line) {
58 if (preg_match('/^([A-Z]+(?:\s+(?:JOIN|BY|FROM|INTO))?)\s+(.*)/u', $line, $matches)
59 && $matches[1] != 'AND' && $matches[1] != 'OR')
61 $local = strlen($matches[1]);
62 $line = $matches[1] . ' ' . $matches[2];
63 $length = max($length, $local);
65 $query[$key] = array($line, $local);
68 foreach ($query as $array) {
69 list($line, $local) = $array;
70 $local = max(0, $length - $local);
71 $res .= str_repeat(' ', $local) . $line . "\n";
72 $length +
= 2 * (substr_count($line, '(') - substr_count($line, ')'));
77 public static function run($query)
81 if (!self
::$mysqli && !self
::connect()) {
82 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
83 Platal
::page()->kill('Impossible de se connecter à la base de données.');
87 if ($globals->debug
& DEBUG_BT
) {
89 if (strpos($query, 'FOUND_ROWS()') === false
&& strpos($query, 'AUTOCOMMIT') === false
) {
90 $res = self
::$mysqli->query("EXPLAIN $query");
92 while ($row = $res->fetch_assoc()) {
98 PlBacktrace
::$bt['MySQL']->start(XDB
::reformatQuery($query));
101 $res = XDB
::$mysqli->query($query);
103 if ($globals->debug
& DEBUG_BT
) {
104 PlBacktrace
::$bt['MySQL']->stop(@$res->num_rows ?
$res->num_rows
: self
::$mysqli->affected_rows
,
105 self
::$mysqli->error
,
109 if ($res === false
) {
110 throw new XDBException(XDB
::reformatQuery($query), XDB
::$mysqli->error
);
115 private static function queryv($query)
117 return new XDBResult(self
::prepare($query));
120 public static function query()
122 return self
::queryv(func_get_args());
125 public static function rawQuery($query)
127 return new XDBResult($query);
130 public static function format()
132 return self
::prepare(func_get_args());
135 // Produce the SQL statement for setting/unsetting a flag
136 public static function changeFlag($fieldname, $flagname, $state)
139 return XDB
::format($fieldname . ' = CONCAT({?}, \',\', ' . $fieldname . ')', $flagname);
141 return XDB
::format($fieldname . ' = REPLACE(' . $fieldname . ', {?}, \'\')', $flagname);
145 // Produce the SQL statement representing an array
146 public static function formatArray(array $array)
148 return self
::escape($array);
151 const WILDCARD_EXACT
= 0x00;
152 const WILDCARD_PREFIX
= 0x01;
153 const WILDCARD_SUFFIX
= 0x02;
154 const WILDCARD_CONTAINS
= 0x03; // WILDCARD_PREFIX | WILDCARD_SUFFIX
156 // Produce a valid XDB argument that get formatted as a wildcard
157 // according to the given mode.
160 // XDB::query("SELECT * FROM table WHERE field {?}", XDB::wildcard($text, WILDCARD_EXACT));
161 public static function wildcard($mode, $value)
163 return new XDBWildcard($value, $mode);
166 // Returns the SQL statement for a wildcard search.
167 public static function formatWildcards($mode, $text)
169 return XDB
::wildcard($mode, $text)->format();
172 // Returns a FIELD(blah, 3, 1, 2) for use in an order with custom orders
173 public static function formatCustomOrder($field, $values)
175 return 'FIELD( ' . $field . ', ' . implode(', ', array_map(array('XDB', 'escape'), $values)) . ')';
178 public static function execute()
181 $args = func_get_args();
182 if ($globals->mode
!= 'rw' && !strpos($args[0], 'logger')) {
185 return self
::run(XDB
::prepare($args));
188 public static function rawExecute($query)
191 if ($globals->mode
!= 'rw') {
194 return self
::run($query);
197 public static function startTransaction()
199 self
::rawExecute('SET AUTOCOMMIT = 0');
200 self
::rawExecute('START TRANSACTION');
203 public static function commit()
205 self
::rawExecute('COMMIT');
206 self
::rawExecute('SET AUTOCOMMIT = 1');
209 public static function rollback()
211 self
::rawExecute('ROLLBACK');
212 self
::rawExecute('SET AUTOCOMMIT = 1');
215 public static function runTransactionV($callback, array $args)
217 self
::startTransaction();
219 if (call_user_func_array($callback, $args)) {
226 } catch (Exception
$e) {
232 /** This function takes a callback followed by the arguments to be passed to the callback
233 * as arguments. It starts a transaction and execute the callback. If the callback fails
234 * (return false or raise an exception), the transaction is rollbacked, if the callback
235 * succeeds (return true), the transaction is committed.
237 public static function runTransaction()
239 $args = func_get_args();
240 $cb = array_shift($args);
241 self
::runTransactionV($cb, $args);
244 public static function iterator()
246 return new XDBIterator(self
::prepare(func_get_args()));
249 public static function rawIterator($query)
251 return new XDBIterator($query);
254 public static function iterRow()
256 return new XDBIterator(self
::prepare(func_get_args()), MYSQL_NUM
);
259 public static function rawIterRow($query)
261 return new XDBIterator($query, MYSQL_NUM
);
264 private static function findQuery($params, $default = array())
266 for ($i = 0 ; $i < count($default) ; ++
$i) {
268 foreach (array('insert', 'select', 'replace', 'delete', 'update') as $kwd) {
269 if (stripos($params[0], $kwd) !== false
) {
277 $default[$i] = array_shift($params);
280 return array($default, $params);
283 /** Fetch all rows returned by the given query.
284 * This functions can take 2 optional arguments (cf XDBResult::fetchAllRow()).
285 * Optional arguments are given *before* the query.
287 public static function fetchAllRow()
289 list($args, $query) = self
::findQuery(func_get_args(), array(false
, false
));
290 return self
::queryv($query)->fetchAllRow($args[0], $args[1]);
293 public static function rawFetchAllRow($query, $id = false
, $keep_array = false
)
295 return self
::rawQuery($query)->fetchAllRow($id, $keep_array);
298 /** Fetch all rows returned by the given query.
299 * This functions can take 2 optional arguments (cf XDBResult::fetchAllAssoc()).
300 * Optional arguments are given *before* the query.
302 public static function fetchAllAssoc()
304 list($args, $query) = self
::findQuery(func_get_args(), array(false
, false
));
305 return self
::queryv($query)->fetchAllAssoc($args[0], $args[1]);
308 public static function rawFetchAllAssoc($query, $id = false
, $keep_array = false
)
310 return self
::rawQuery($query)->fetchAllAssoc($id, $keep_array);
313 public static function fetchOneCell()
315 list($args, $query) = self
::findQuery(func_get_args());
316 return self
::queryv($query)->fetchOneCell();
319 public static function rawFetchOneCell($query)
321 return self
::rawQuery($query)->fetchOneCell();
324 public static function fetchOneRow()
326 list($args, $query) = self
::findQuery(func_get_args());
327 return self
::queryv($query)->fetchOneRow();
330 public static function rawFetchOneRow($query)
332 return self
::rawQuery($query)->fetchOneRow();
335 public static function fetchOneAssoc()
337 list($args, $query) = self
::findQuery(func_get_args());
338 return self
::queryv($query)->fetchOneAssoc();
341 public static function rawFetchOneAssoc($query)
343 return self
::rawQuery($query)->fetchOneAssoc();
346 /** Fetch a column from the result of the given query.
347 * This functions can take 1 optional arguments (cf XDBResult::fetchColumn()).
348 * Optional arguments are given *before* the query.
350 public static function fetchColumn()
352 list($args, $query) = self
::findQuery(func_get_args(), array(0));
353 return self
::queryv($query)->fetchColumn($args[0]);
356 public static function rawFetchColumn($query, $key = 0)
358 return self
::rawQuery($query)->fetchColumn($key);
361 public static function insertId()
363 return self
::$mysqli->insert_id
;
366 public static function errno()
368 return self
::$mysqli->errno
;
371 public static function error()
373 return self
::$mysqli->error
;
376 public static function affectedRows()
378 return self
::$mysqli->affected_rows
;
381 public static function escape($var)
383 switch (gettype($var)) {
393 return "'".addslashes($var)."'";
399 if ($var instanceof XDBFormat
) {
400 return $var->format();
402 return "'".addslashes(serialize($var))."'";
406 return '(' . implode(', ', array_map(array('XDB', 'escape'), $var)) . ')';
409 die(var_export($var, true
).' is not a valid for a database entry');
414 class XDBException
extends PlException
416 public function __construct($query, $error)
418 if (strpos($query, 'INSERT') === false
&& strpos($query, 'UPDATE') === false
419 && strpos($query, 'REPLACE') === false
&& strpos($query, 'DELETE') === false
) {
420 $text = 'Erreur lors de l\'interrogation de la base de données';
422 $text = 'Erreur lors de l\'écriture dans la base de données';
424 parent
::__construct($text, $query . "\n" . $error);
430 public function format();
433 class XDBWildcard
implements XDBFormat
438 public function __construct($value, $mode)
440 $this->value
= $value;
444 public function format()
446 if ($this->mode
== XDB
::WILDCARD_EXACT
) {
447 return XDB
::format(' = {?}', $this->value
);
449 $text = str_replace(array('%', '_'), array('\%', '\_'), $this->value
);
450 if ($this->mode
& XDB
::WILDCARD_PREFIX
) {
453 if ($this->mode
& XDB
::WILDCARD_SUFFIX
) {
456 return XDB
::format(" LIKE {?}", $text);
466 public function __construct($query)
468 $this->res
= XDB
::run($query);
471 public function free()
479 protected function fetchRow()
481 return $this->res ?
$this->res
->fetch_row() : null
;
484 protected function fetchAssoc()
486 return $this->res ?
$this->res
->fetch_assoc() : null
;
489 public function fetchAllRow($id = false
, $keep_array = false
)
495 while (($data = $this->res
->fetch_row())) {
499 if (!$keep_array && count($data) == 1) {
501 $result[$key] = current($data);
503 $result[$key] = $data;
513 public function fetchAllAssoc($id = false
, $keep_array = false
)
519 while (($data = $this->res
->fetch_assoc())) {
523 if (!$keep_array && count($data) == 1) {
525 $result[$key] = current($data);
527 $result[$key] = $data;
537 public function fetchOneAssoc()
539 $tmp = $this->fetchAssoc();
544 public function fetchOneRow()
546 $tmp = $this->fetchRow();
551 public function fetchOneCell()
553 $tmp = $this->fetchRow();
558 public function fetchColumn($key = 0)
561 if (is_numeric($key)) {
562 while($tmp = $this->fetchRow()) {
566 while($tmp = $this->fetchAssoc()) {
574 public function fetchOneField()
576 return $this->res ?
$this->res
->fetch_field() : null
;
579 public function fetchFields()
582 while ($res[] = $this->fetchOneField());
586 public function numRows()
588 return $this->res ?
$this->res
->num_rows
: 0;
591 public function fieldCount()
593 return $this->res ?
$this->res
->field_count
: 0;
598 class XDBIterator
extends XDBResult
implements PlIterator
605 private $mode = MYSQL_ASSOC
;
607 public function __construct($query, $mode = MYSQL_ASSOC
)
609 parent
::__construct($query);
611 $this->total
= $this->numRows();
613 $this->fields
= $this->fieldCount();
617 public function next()
620 if ($this->pos
> $this->total
) {
625 return $this->mode
!= MYSQL_ASSOC ?
$this->fetchRow() : $this->fetchAssoc();
628 public function first()
630 return $this->pos
== 1;
633 public function last()
635 return $this->pos
== $this->total
;
638 public function total()
643 public function nextField()
646 if ($this->fpos
> $this->fields
) {
649 return $this->fetchOneField();
652 public function firstField()
654 return $this->fpos
== 1;
657 public function lastField()
659 return $this->fpos
== $this->fields
;
662 public function totalFields()
664 return $this->fields
;
668 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: