Connect to DB on demand
[platal.git] / classes / xdb.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2007 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
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. *
10 * *
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. *
15 * *
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 *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 **************************************************************************/
21
22 class XDB
23 {
24 private static $mysqli = null;
25
26 public static function connect()
27 {
28 global $globals;
29 XDB::$mysqli = new mysqli($globals->dbhost, $globals->dbuser, $globals->dbpwd, $globals->dbdb);
30 if (mysqli_connect_errno() && $globals->debug & 1) {
31 $GLOBALS['XDB::trace_data'][] = array('query' => 'MySQLI connection', 'explain' => array(),
32 'error' => mysqli_connect_error(), 'exectime' => 0, 'rows' => 0);
33 $GLOBALS['XDB::error'] = true;
34 return false;
35 }
36 XDB::$mysqli->autocommit(true);
37 XDB::$mysqli->set_charset($globals->dbcharset);
38 return true;
39 }
40
41 public static function _prepare($args)
42 {
43 $query = array_map(Array('XDB', '_db_escape'), $args);
44 $query[0] = str_replace('{?}', '%s', str_replace('%', '%%', $args[0]));
45 return call_user_func_array('sprintf', $query);
46 }
47
48 public static function _reformatQuery($query)
49 {
50 $query = preg_split("/\n\\s*/", trim($query));
51 $length = 0;
52 foreach ($query as $key=>$line) {
53 $local = -2;
54 if (preg_match('/^([A-Z]+(?:\s+(?:JOIN|BY|FROM|INTO))?)\s+(.*)/u', $line, $matches)
55 && $matches[1] != 'AND' && $matches[1] != 'OR')
56 {
57 $local = strlen($matches[1]);
58 $line = $matches[1] . ' ' . $matches[2];
59 $length = max($length, $local);
60 }
61 $query[$key] = array($line, $local);
62 }
63 $res = '';
64 foreach ($query as $array) {
65 list($line, $local) = $array;
66 $local = max(0, $length - $local);
67 $res .= str_repeat(' ', $local) . $line . "\n";
68 $length += 2 * (substr_count($line, '(') - substr_count($line, ')'));
69 }
70 return $res;
71 }
72
73 public static function _query($query)
74 {
75 global $globals;
76
77 if (!XDB::$mysqli && !XDB::connect()) {
78 return false;
79 }
80
81 if ($globals->debug & 1) {
82 $explain = array();
83 if (strpos($query, 'FOUND_ROWS()') === false) {
84 $res = XDB::$mysqli->query("EXPLAIN $query");
85 if ($res) {
86 while ($row = $res->fetch_assoc()) {
87 $explain[] = $row;
88 }
89 $res->free();
90 }
91 }
92 $trace_data = array('query' => XDB::_reformatQuery($query), 'explain' => $explain);
93 $time_start = microtime();
94 }
95
96 $res = XDB::$mysqli->query($query);
97
98 if ($globals->debug & 1) {
99 list($ue, $se) = explode(" ", microtime());
100 list($us, $ss) = explode(" ", $time_start);
101 $time = intval((($ue - $us) + ($se - $ss)) * 1000);
102 $trace_data['error'] = XDB::$mysqli->error;
103 $trace_data['exectime'] = $time;
104 $trace_data['rows'] = @$res->num_rows ? $res->num_rows : XDB::$mysqli->affected_rows;
105 $GLOBALS['XDB::trace_data'][] = $trace_data;
106 if (XDB::$mysqli->errno) {
107 $GLOBALS['XDB::error'] = true;
108 }
109 }
110 return $res;
111 }
112
113 public static function query()
114 {
115 return new XOrgDBResult(XDB::_prepare(func_get_args()));
116 }
117
118 public static function execute()
119 {
120 return XDB::_query(XDB::_prepare(func_get_args()));
121 }
122
123 public static function iterator()
124 {
125 return new XOrgDBIterator(XDB::_prepare(func_get_args()));
126 }
127
128 public static function iterRow()
129 {
130 return new XOrgDBIterator(XDB::_prepare(func_get_args()), MYSQL_NUM);
131 }
132
133 public static function insertId()
134 {
135 return XDB::$mysqli->insert_id;
136 }
137
138 public static function _db_escape($var)
139 {
140 switch (gettype($var)) {
141 case 'boolean':
142 return $var ? 1 : 0;
143
144 case 'integer':
145 case 'double':
146 case 'float':
147 return $var;
148
149 case 'string':
150 return "'".addslashes($var)."'";
151
152 case 'NULL':
153 return 'NULL';
154
155 case 'object':
156 case 'array':
157 return "'".addslashes(serialize($var))."'";
158
159 default:
160 die(var_export($var, true).' is not a valid for a database entry');
161 }
162 }
163
164 public static function trace_format(&$page, $template = 'skin/common.database-debug.tpl') {
165 $page->assign('trace_data', @$GLOBALS['XDB::trace_data']);
166 $page->assign('db_error', @$GLOBALS['XDB::error']);
167 return $page->fetch($template);
168 }
169 }
170
171 class XOrgDBResult
172 {
173
174 private $_res;
175
176 function XOrgDBResult($query)
177 {
178 $this->_res = XDB::_query($query);
179 }
180
181 function free()
182 {
183 $this->_res->free();
184 unset($this);
185 }
186
187 function _fetchRow()
188 {
189 return $this->_res->fetch_row();
190 }
191
192 function _fetchAssoc()
193 {
194 return $this->_res->fetch_assoc();
195 }
196
197 function fetchAllRow()
198 {
199 $result = Array();
200 while ($result[] = $this->_res->fetch_row());
201 array_pop($result);
202 $this->free();
203 return $result;
204 }
205
206 function fetchAllAssoc()
207 {
208 $result = Array();
209 while ($result[] = $this->_res->fetch_assoc());
210 array_pop($result);
211 $this->free();
212 return $result;
213 }
214
215 function fetchOneAssoc()
216 {
217 $tmp = $this->_fetchAssoc();
218 $this->free();
219 return $tmp;
220 }
221
222 function fetchOneRow()
223 {
224 $tmp = $this->_fetchRow();
225 $this->free();
226 return $tmp;
227 }
228
229 function fetchOneCell()
230 {
231 $tmp = $this->_fetchRow();
232 $this->free();
233 return $tmp[0];
234 }
235
236 function fetchColumn($key = 0)
237 {
238 $res = Array();
239 if (is_numeric($key)) {
240 while($tmp = $this->_fetchRow()) {
241 $res[] = $tmp[$key];
242 }
243 } else {
244 while($tmp = $this->_fetchAssoc()) {
245 $res[] = $tmp[$key];
246 }
247 }
248 $this->free();
249 return $res;
250 }
251
252 function numRows()
253 {
254 return $this->_res->num_rows;
255 }
256 }
257
258 class XOrgDBIterator
259 {
260 private $_result;
261 private $_pos;
262 private $_total;
263 private $_mode = MYSQL_ASSOC;
264
265 function __construct($query, $mode = MYSQL_ASSOC)
266 {
267 $this->_result = new XOrgDBResult($query);
268 $this->_pos = 0;
269 $this->_total = $this->_result->numRows();
270 $this->_mode = $mode;
271 }
272
273 function next()
274 {
275 $this->_pos ++;
276 if ($this->_pos > $this->_total) {
277 $this->_result->free();
278 unset($this);
279 return null;
280 }
281 return $this->_mode != MYSQL_ASSOC ? $this->_result->_fetchRow() : $this->_result->_fetchAssoc();
282 }
283
284 function first()
285 {
286 return $this->_pos == 1;
287 }
288
289 function last()
290 {
291 return $this->_last == $this->_total;
292 }
293
294 function total()
295 {
296 return $this->_total;
297 }
298 }
299
300 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
301 ?>