8df9495558acc64e1c650c1f5414a5973910cf5e
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 private static $inTransaction = false
;
198 public static function startTransaction()
200 if (self
::$inTransaction) {
201 throw new XDBException('START TRANSACTION', 'Already in a transaction');
203 self
::$inTransaction = true
;
204 self
::rawExecute('SET AUTOCOMMIT = 0');
205 self
::rawExecute('START TRANSACTION');
208 public static function commit()
210 self
::rawExecute('COMMIT');
211 self
::rawExecute('SET AUTOCOMMIT = 1');
212 self
::$inTransaction = false
;
215 public static function rollback()
217 self
::rawExecute('ROLLBACK');
218 self
::rawExecute('SET AUTOCOMMIT = 1');
219 self
::$inTransaction = false
;
222 public static function runTransactionV($callback, array $args)
224 self
::startTransaction();
226 if (call_user_func_array($callback, $args)) {
233 } catch (Exception
$e) {
239 /** This function takes a callback followed by the arguments to be passed to the callback
240 * as arguments. It starts a transaction and execute the callback. If the callback fails
241 * (return false or raise an exception), the transaction is rollbacked, if the callback
242 * succeeds (return true), the transaction is committed.
244 public static function runTransaction()
246 $args = func_get_args();
247 $cb = array_shift($args);
248 self
::runTransactionV($cb, $args);
251 public static function iterator()
253 return new XDBIterator(self
::prepare(func_get_args()));
256 public static function rawIterator($query)
258 return new XDBIterator($query);
261 public static function iterRow()
263 return new XDBIterator(self
::prepare(func_get_args()), MYSQL_NUM
);
266 public static function rawIterRow($query)
268 return new XDBIterator($query, MYSQL_NUM
);
271 private static function findQuery($params, $default = array())
273 for ($i = 0 ; $i < count($default) ; ++
$i) {
275 foreach (array('insert', 'select', 'replace', 'delete', 'update') as $kwd) {
276 if (stripos($params[0], $kwd) !== false
) {
284 $default[$i] = array_shift($params);
287 return array($default, $params);
290 /** Fetch all rows returned by the given query.
291 * This functions can take 2 optional arguments (cf XDBResult::fetchAllRow()).
292 * Optional arguments are given *before* the query.
294 public static function fetchAllRow()
296 list($args, $query) = self
::findQuery(func_get_args(), array(false
, false
));
297 return self
::queryv($query)->fetchAllRow($args[0], $args[1]);
300 public static function rawFetchAllRow($query, $id = false
, $keep_array = false
)
302 return self
::rawQuery($query)->fetchAllRow($id, $keep_array);
305 /** Fetch all rows returned by the given query.
306 * This functions can take 2 optional arguments (cf XDBResult::fetchAllAssoc()).
307 * Optional arguments are given *before* the query.
309 public static function fetchAllAssoc()
311 list($args, $query) = self
::findQuery(func_get_args(), array(false
, false
));
312 return self
::queryv($query)->fetchAllAssoc($args[0], $args[1]);
315 public static function rawFetchAllAssoc($query, $id = false
, $keep_array = false
)
317 return self
::rawQuery($query)->fetchAllAssoc($id, $keep_array);
320 public static function fetchOneCell()
322 list($args, $query) = self
::findQuery(func_get_args());
323 return self
::queryv($query)->fetchOneCell();
326 public static function rawFetchOneCell($query)
328 return self
::rawQuery($query)->fetchOneCell();
331 public static function fetchOneRow()
333 list($args, $query) = self
::findQuery(func_get_args());
334 return self
::queryv($query)->fetchOneRow();
337 public static function rawFetchOneRow($query)
339 return self
::rawQuery($query)->fetchOneRow();
342 public static function fetchOneAssoc()
344 list($args, $query) = self
::findQuery(func_get_args());
345 return self
::queryv($query)->fetchOneAssoc();
348 public static function rawFetchOneAssoc($query)
350 return self
::rawQuery($query)->fetchOneAssoc();
353 /** Fetch a column from the result of the given query.
354 * This functions can take 1 optional arguments (cf XDBResult::fetchColumn()).
355 * Optional arguments are given *before* the query.
357 public static function fetchColumn()
359 list($args, $query) = self
::findQuery(func_get_args(), array(0));
360 return self
::queryv($query)->fetchColumn($args[0]);
363 public static function rawFetchColumn($query, $key = 0)
365 return self
::rawQuery($query)->fetchColumn($key);
368 public static function insertId()
370 return self
::$mysqli->insert_id
;
373 public static function errno()
375 return self
::$mysqli->errno
;
378 public static function error()
380 return self
::$mysqli->error
;
383 public static function affectedRows()
385 return self
::$mysqli->affected_rows
;
388 public static function escape($var)
390 switch (gettype($var)) {
400 return "'".addslashes($var)."'";
406 if ($var instanceof XDBFormat
) {
407 return $var->format();
409 return "'".addslashes(serialize($var))."'";
413 return '(' . implode(', ', array_map(array('XDB', 'escape'), $var)) . ')';
416 die(var_export($var, true
).' is not a valid for a database entry');
421 class XDBException
extends PlException
423 public function __construct($query, $error)
425 if (strpos($query, 'INSERT') === false
&& strpos($query, 'UPDATE') === false
426 && strpos($query, 'REPLACE') === false
&& strpos($query, 'DELETE') === false
) {
427 $text = 'Erreur lors de l\'interrogation de la base de données';
429 $text = 'Erreur lors de l\'écriture dans la base de données';
431 parent
::__construct($text, $query . "\n" . $error);
437 public function format();
440 class XDBWildcard
implements XDBFormat
445 public function __construct($value, $mode)
447 $this->value
= $value;
451 public function format()
453 if ($this->mode
== XDB
::WILDCARD_EXACT
) {
454 return XDB
::format(' = {?}', $this->value
);
456 $text = str_replace(array('%', '_'), array('\%', '\_'), $this->value
);
457 if ($this->mode
& XDB
::WILDCARD_PREFIX
) {
460 if ($this->mode
& XDB
::WILDCARD_SUFFIX
) {
463 return XDB
::format(" LIKE {?}", $text);
473 public function __construct($query)
475 $this->res
= XDB
::run($query);
478 public function free()
486 protected function fetchRow()
488 return $this->res ?
$this->res
->fetch_row() : null
;
491 protected function fetchAssoc()
493 return $this->res ?
$this->res
->fetch_assoc() : null
;
496 public function fetchAllRow($id = false
, $keep_array = false
)
502 while (($data = $this->res
->fetch_row())) {
506 if (!$keep_array && count($data) == 1) {
508 $result[$key] = current($data);
510 $result[$key] = $data;
520 public function fetchAllAssoc($id = false
, $keep_array = false
)
526 while (($data = $this->res
->fetch_assoc())) {
530 if (!$keep_array && count($data) == 1) {
532 $result[$key] = current($data);
534 $result[$key] = $data;
544 public function fetchOneAssoc()
546 $tmp = $this->fetchAssoc();
551 public function fetchOneRow()
553 $tmp = $this->fetchRow();
558 public function fetchOneCell()
560 $tmp = $this->fetchRow();
565 public function fetchColumn($key = 0)
568 if (is_numeric($key)) {
569 while($tmp = $this->fetchRow()) {
573 while($tmp = $this->fetchAssoc()) {
581 public function fetchOneField()
583 return $this->res ?
$this->res
->fetch_field() : null
;
586 public function fetchFields()
589 while ($res[] = $this->fetchOneField());
593 public function numRows()
595 return $this->res ?
$this->res
->num_rows
: 0;
598 public function fieldCount()
600 return $this->res ?
$this->res
->field_count
: 0;
605 class XDBIterator
extends XDBResult
implements PlIterator
612 private $mode = MYSQL_ASSOC
;
614 public function __construct($query, $mode = MYSQL_ASSOC
)
616 parent
::__construct($query);
618 $this->total
= $this->numRows();
620 $this->fields
= $this->fieldCount();
624 public function next()
627 if ($this->pos
> $this->total
) {
632 return $this->mode
!= MYSQL_ASSOC ?
$this->fetchRow() : $this->fetchAssoc();
635 public function first()
637 return $this->pos
== 1;
640 public function last()
642 return $this->pos
== $this->total
;
645 public function total()
650 public function nextField()
653 if ($this->fpos
> $this->fields
) {
656 return $this->fetchOneField();
659 public function firstField()
661 return $this->fpos
== 1;
664 public function lastField()
666 return $this->fpos
== $this->fields
;
669 public function totalFields()
671 return $this->fields
;
675 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: