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
) {
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 format()
127 return self
::prepare(func_get_args());
130 // Produce the SQL statement for setting/unsetting a flag
131 public static function changeFlag($fieldname, $flagname, $state)
134 return XDB
::format($fieldname . ' = CONCAT({?}, \',\', ' . $fieldname . ')', $flagname);
136 return XDB
::format($fieldname . ' = REPLACE(' . $fieldname . ', {?}, \'\')', $flagname);
140 // Produce the SQL statement representing an array
141 public static function formatArray(array $array)
143 return self
::escape($array);
146 const WILDCARD_EXACT
= 0x00;
147 const WILDCARD_PREFIX
= 0x01;
148 const WILDCARD_SUFFIX
= 0x02;
149 const WILDCARD_CONTAINS
= 0x03; // WILDCARD_PREFIX | WILDCARD_SUFFIX
151 // Produce a valid XDB argument that get formatted as a wildcard
152 // according to the given mode.
155 // XDB::query("SELECT * FROM table WHERE field {?}", XDB::wildcard($text, WILDCARD_EXACT));
156 public static function wildcard($mode, $value)
158 return new XDBWildcard($value, $mode);
161 // Returns the SQL statement for a wildcard search.
162 public static function formatWildcards($mode, $text)
164 return XDB
::wildcard($mode, $text)->format();
167 // Returns a FIELD(blah, 3, 1, 2) for use in an order with custom orders
168 public static function formatCustomOrder($field, $values)
170 return 'FIELD( ' . $field . ', ' . implode(', ', array_map(array('XDB', 'escape'), $values)) . ')';
173 public static function execute()
176 $args = func_get_args();
177 if ($globals->mode
!= 'rw' && !strpos($args[0], 'logger')) {
180 return self
::run(XDB
::prepare($args));
183 public static function iterator()
185 return new XDBIterator(self
::prepare(func_get_args()));
188 public static function iterRow()
190 return new XDBIterator(self
::prepare(func_get_args()), MYSQL_NUM
);
193 private static function findQuery($params, $default = array())
195 for ($i = 0 ; $i < count($default) ; ++
$i) {
197 foreach (array('insert', 'select', 'replace', 'delete', 'update') as $kwd) {
198 if (stripos($params[0], $kwd) !== false
) {
206 $default[$i] = array_shift($params);
209 return array($default, $params);
212 /** Fetch all rows returned by the given query.
213 * This functions can take 2 optional arguments (cf XDBResult::fetchAllRow()).
214 * Optional arguments are given *before* the query.
216 public static function fetchAllRow()
218 list($args, $query) = self
::findQuery(func_get_args(), array(false
, false
));
219 return self
::queryv($query)->fetchAllRow($args[0], $args[1]);
222 /** Fetch all rows returned by the given query.
223 * This functions can take 2 optional arguments (cf XDBResult::fetchAllAssoc()).
224 * Optional arguments are given *before* the query.
226 public static function fetchAllAssoc()
228 list($args, $query) = self
::findQuery(func_get_args(), array(false
, false
));
229 return self
::queryv($query)->fetchAllAssoc($args[0], $args[1]);
232 public static function fetchOneCell()
234 list($args, $query) = self
::findQuery(func_get_args());
235 return self
::queryv($query)->fetchOneCell();
238 public static function fetchOneRow()
240 list($args, $query) = self
::findQuery(func_get_args());
241 return self
::queryv($query)->fetchOneRow();
244 public static function fetchOneAssoc()
246 list($args, $query) = self
::findQuery(func_get_args());
247 return self
::queryv($query)->fetchOneAssoc();
250 /** Fetch a column from the result of the given query.
251 * This functions can take 1 optional arguments (cf XDBResult::fetchColumn()).
252 * Optional arguments are given *before* the query.
254 public static function fetchColumn()
256 list($args, $query) = self
::findQuery(func_get_args(), array(0));
257 return self
::queryv($query)->fetchColumn();
260 public static function insertId()
262 return self
::$mysqli->insert_id
;
265 public static function errno()
267 return self
::$mysqli->errno
;
270 public static function error()
272 return self
::$mysqli->error
;
275 public static function affectedRows()
277 return self
::$mysqli->affected_rows
;
280 public static function escape($var)
282 switch (gettype($var)) {
292 return "'".addslashes($var)."'";
298 if ($var instanceof XDBFormat
) {
299 return $var->format();
301 return "'".addslashes(serialize($var))."'";
305 return '(' . implode(', ', array_map(array('XDB', 'escape'), $var)) . ')';
308 die(var_export($var, true
).' is not a valid for a database entry');
313 class XDBException
extends PlException
315 public function __construct($query, $error)
317 if (strpos($query, 'INSERT') === false
&& strpos($query, 'UPDATE') === false
318 && strpos($query, 'REPLACE') === false
&& strpos($query, 'DELETE') === false
) {
319 $text = 'Erreur lors de l\'interrogation de la base de données';
321 $text = 'Erreur lors de l\'écriture dans la base de données';
323 parent
::__construct($text, $query . "\n" . $error);
329 public function format();
332 class XDBWildcard
implements XDBFormat
337 public function __construct($value, $mode)
339 $this->value
= $value;
343 public function format()
345 if ($this->mode
== XDB
::WILDCARD_EXACT
) {
346 return XDB
::format(' = {?}', $this->value
);
348 $text = str_replace(array('%', '_'), array('\%', '\_'), $this->value
);
349 if ($this->mode
& XDB
::WILDCARD_PREFIX
) {
352 if ($this->mode
& XDB
::WILDCARD_SUFFIX
) {
355 return XDB
::format(" LIKE {?}", $text);
365 public function __construct($query)
367 $this->res
= XDB
::run($query);
370 public function free()
378 protected function fetchRow()
380 return $this->res ?
$this->res
->fetch_row() : null
;
383 protected function fetchAssoc()
385 return $this->res ?
$this->res
->fetch_assoc() : null
;
388 public function fetchAllRow($id = false
, $keep_array = false
)
394 while (($data = $this->res
->fetch_row())) {
398 if (!$keep_array && count($data) == 1) {
400 $result[$key] = current($data);
402 $result[$key] = $data;
412 public function fetchAllAssoc($id = false
, $keep_array = false
)
418 while (($data = $this->res
->fetch_assoc())) {
422 if (!$keep_array && count($data) == 1) {
424 $result[$key] = current($data);
426 $result[$key] = $data;
436 public function fetchOneAssoc()
438 $tmp = $this->fetchAssoc();
443 public function fetchOneRow()
445 $tmp = $this->fetchRow();
450 public function fetchOneCell()
452 $tmp = $this->fetchRow();
457 public function fetchColumn($key = 0)
460 if (is_numeric($key)) {
461 while($tmp = $this->fetchRow()) {
465 while($tmp = $this->fetchAssoc()) {
473 public function fetchOneField()
475 return $this->res ?
$this->res
->fetch_field() : null
;
478 public function fetchFields()
481 while ($res[] = $this->fetchOneField());
485 public function numRows()
487 return $this->res ?
$this->res
->num_rows
: 0;
490 public function fieldCount()
492 return $this->res ?
$this->res
->field_count
: 0;
497 class XDBIterator
extends XDBResult
implements PlIterator
504 private $mode = MYSQL_ASSOC
;
506 public function __construct($query, $mode = MYSQL_ASSOC
)
508 parent
::__construct($query);
510 $this->total
= $this->numRows();
512 $this->fields
= $this->fieldCount();
516 public function next()
519 if ($this->pos
> $this->total
) {
524 return $this->mode
!= MYSQL_ASSOC ?
$this->fetchRow() : $this->fetchAssoc();
527 public function first()
529 return $this->pos
== 1;
532 public function last()
534 return $this->pos
== $this->total
;
537 public function total()
542 public function nextField()
545 if ($this->fpos
> $this->fields
) {
548 return $this->fetchOneField();
551 public function firstField()
553 return $this->fpos
== 1;
556 public function lastField()
558 return $this->fpos
== $this->fields
;
561 public function totalFields()
563 return $this->fields
;
567 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: