-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.php
405 lines (347 loc) · 9.21 KB
/
db.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
<?php
namespace jmvc;
class Db {
protected $write_db;
protected $read_db;
protected static $instance;
public static $stats;
public static $queries;
/**
* Singleton classe
*/
private function __construct()
{
$config = $GLOBALS['_CONFIG']['db'];
$this->write_db = new \mysqli($config['write']['host'], $config['write']['user'], $config['write']['pass'], $config['write']['name']);
if (isset($config['read'])) {
$read_config = $config['read'][rand(0, count($config['read'])-1)];
$this->read_db = new \mysqli($read_config['host'], $read_config['user'], $read_config['pass'], $read_config['name']);
} else {
$this->read_db = $this->write_db;
}
self::$stats = array('select'=>0, 'insert'=>0, 'update'=>0, 'delete'=>0);
}
public function __destruct()
{
if ($this->read_db) {
$this->read_db->close();
}
if ($this->write_db && $this->write_db != $this->read_db) {
$this->write_db->close();
}
}
/**
* Retrieve the DB instance
* @return \jmvc\Db
*/
public static function instance()
{
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
/**
* MySQL quote a value. Performs some type detection to try to match MySQL type. Protects against SQL injection.
* @param string $value
* @return string
*/
public function quote($value)
{
if ($value === NULL) {
return 'NULL';
} else if (is_numeric($value)) {
return $value;
} else {
return "'" . $this->read_db->real_escape_string($value) . "'";
}
}
/**
* MySQL quote a date. Accepts either datetime strings or Unix timestamps
* @param mixed $value
* @return string
*/
public function quote_date($value)
{
if (!empty($value) && is_numeric($value)) {
$value = date('Y-m-d H:i:s', $value);
}
return $this->quote($value);
}
/**
* Quote a string without any type detection
* @param string $value
* @return string
*/
public function escape_string($value)
{
return $this->read_db->real_escape_string($value);
}
/**
* Generate a MySQL key=value argument pair
* @param string $key Table column
* @param string $value Argument value. Will be quoted.
* @param string $prefix Prefix to put on column names in SQL. Typically \jmvc\Model::$_find_prefix.
* @return string
*/
public function make_parameter($key, $value, $prefix=null)
{
if ($key == 'raw_sql') {
// Raw (non-quoted) SQL
return (is_array($value)) ? implode(' AND ', $value) : $value;
}
if (strpos($key, '.')) {
list($prefix, $key) = explode('.', $key);
$prefix .= '.';
}
if (is_array($value)) {
if (empty($value)) { // NULL
return $prefix.$key.' IS NULL';
} else { // IN criteria
$str = $prefix.$key.' IN(';
foreach ($value as $val) {
$str .= self::quote($val).', ';
}
return substr($str, 0, -2).')';
}
} else if ($value === NULL) { // NULL
return $prefix.$key.' IS NULL';
} else if (substr($key, -7) == '_before') { // DateTime range
return $prefix.substr($key, 0, -7).' <= '.self::quote_date($value);
} else if (substr($key, -6) == '_after') { // DateTime range
return $prefix.substr($key, 0, -6).' >= '.self::quote_date($value);
} else { // equals
return $prefix.$key.'='.$this->quote($value);
}
}
/**
* Generate SQL to insert associative array into MySQL table
* @param string $table
* @param array $row Array keys match column names
* @param array $field_types Array of field information. Keys match column names. Allowed values are 'datetime'.
* @return string
*/
public function make_insert($table, $row, $field_types=array())
{
$fields = '';
$values = '';
foreach($row as $key => $value) {
$fields .= "`$key`, ";
if (is_array($value)) {
$values .= $value['raw'].', ';
} else if ($value === NULL) {
$values .= 'NULL, ';
} else {
if (isset($field_types[$key])) {
switch ($field_types[$key]) {
case 'date':
case 'datetime':
$values .= $this->quote_date($value).', ';
break;
default:
$values .= $this->quote($value).', ';
break;
}
} else {
$values .= $this->quote($value).', ';
}
}
}
$fields = substr($fields, 0, -2);
$values = substr($values, 0, -2);
return "INSERT IGNORE INTO $table($fields) VALUES($values)";
}
/**
* Insert an array into MySQL. Wraps make_insert().
* @param string $table
* @param array $row
* @return int MySQL INSERT_ID
*/
public function insert_row($table, $row)
{
$query = $this->make_insert($table, $row);
return $this->insert($query);
}
/**
* Generate SQL to update an existing row. Similar to make_insert().
* @param string $table
* @param array $data
* @param array $where Array of key=value pairs that will be used as WHERE criteria.
* @param array $field_types
* @return string
*/
public function make_update($table, $data, $where, $field_types=array())
{
$fields = '';
foreach($data as $key => $value) {
if (is_array($value)) {
$fields .= "`$key` = ". $value['raw'].", ";
} else if ($value === NULL) {
$fields .= "`$key` = NULL, ";
} else {
if (isset($field_types[$key])) {
switch ($field_types[$key]) {
case 'date':
case 'datetime':
$fields .= "`$key` = ". $this->quote_date($value) .", ";
break;
default:
$fields .= "`$key` = ". $this->quote($value) .", ";
break;
}
} else {
$fields .= "`$key` = ". $this->quote($value) .", ";
}
}
}
$fields = substr($fields, 0, -2);
$where_sql = Array();
foreach ($where as $key=>$value) {
$where_sql[] = $key.'='.$this->quote($value);
}
$where = implode($where_sql, ' AND ');
return "UPDATE $table SET $fields WHERE $where";
}
/**
* Execute a single SQL command.
* @param string $query
* @param bool $write In a multi-db environment, force query to go to the write db. All subsequent queries will be sent to write db.
* @return mysqli_result
*/
public function do_query($query, $write=false)
{
static $done_write = false;
if ($write) {
$done_write = true;
}
if ($done_write) {
$db = $this->write_db;
} else {
$db = $this->read_db;
}
$start = microtime(true);
$result = $db->query($query);
$time = microtime(true) - $start;
if (!$result) {
$message = $db->error;
throw new \ErrorException($message, 0, 1, $query, 0);
}
if (defined('DB_QUERY_STATS')) {
self::$queries[] = array('query'=>$query, 'time'=>$time);
}
return $result;
}
/**
* Execute multiple SQL commands separated by ;
* @param string $query
* @return mysqli_result
*/
public function do_multi_query($query)
{
$result = $this->write_db->multi_query($query);
if (!$result) {
$message = $this->write_db->error;
throw new \ErrorException($message, 0, 1, $query, 0);
}
// need to clear out db results before issuing new queries
while ($this->write_db->more_results()) {
$this->write_db->next_result();
}
return $result;
}
/**
* Perform a select query and retreive a single row from the database. Will return null if the query
* returns more than one row.
* @param string $query
* @return mixed If return is a single column, data value will be returned (string/int). Otherwise,
* and associative array of the row data will be returned.
*/
public function get_row($query)
{
$result = $this->select($query);
if (!$result || $result->num_rows != 1) {
return null;
}
if ($result->field_count == 1) {
$row = $result->fetch_row();
return $row[0];
} else {
return $result->fetch_assoc();
}
}
/**
* Retrieve multiple rows from the database.
* @param string $query
* @param bool $key If true, array keys match the ID column
* @param function $callback Function to filter returned data
* @return mixed Null if query returned no rows; array of associative arrays otherwise
*/
public function get_rows($query, $key=false, $callback=false)
{
$result = $this->select($query);
if (!$result || $result->num_rows == 0) {
return null;
}
$outp = array();
if ($result->field_count == 1) {
while ($row = $result->fetch_row()) {
$outp[] = $row[0];
}
} else {
if ($key) {
while ($row = $result->fetch_assoc()) {
if (!$callback || $callback($row)) $outp[$row[$key]] = $row;
}
} else {
while ($row = $result->fetch_assoc()) {
if (!$callback || $callback($row)) $outp[] = $row;
}
}
}
return $outp;
}
/**
* Perform a SELECT query
* @param string $query
* @return mysqli_result
*/
public function select($query)
{
self::$stats['select']++;
return $this->do_query($query);
}
/**
* Perform a DELETE query
* @param string $query
* @return int Number of deleted rows
*/
public function delete($query)
{
self::$stats['delete']++;
$this->do_query($query, true);
return $this->write_db->affected_rows;
}
/**
* Perform an INSERT query
* @param string $query
* @return int INSERT_ID of row added
*/
public function insert($query)
{
self::$stats['insert']++;
$this->do_query($query, true);
return $this->write_db->insert_id;
}
/**
* Perform an UPDATE query
* @param string $query
* @return int Number of affected rows
*/
public function update($query)
{
self::$stats['update']++;
$this->do_query($query, true);
return $this->write_db->affected_rows;
}
}