-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMyQueryBuilder.class.php
More file actions
584 lines (473 loc) · 12.7 KB
/
MyQueryBuilder.class.php
File metadata and controls
584 lines (473 loc) · 12.7 KB
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
<?php
/**
* Helper class for building sql statements progmatically.
*
* @category Database
* @package MyActiveRecord
* @author Ramon Antonio Parada <ramon@bigpress.net>
* @copyright 2012 Ramon Antonio Parada
* @version 0.5
* @package ActiveRecord
*/
class MyQueryBuilder {
private $connection;
private $operation = 'SELECT';
private $table;
private $select = '*';
private $joins;
private $order;
private $limit;
private $offset;
private $group;
private $having;
private $update;
// for where
private $where;
private $where_values = array();
// for insert/update
private $data;
private $sequence;
/**
* Constructor.
*
* @param Connection $connection A database connection object
* @param string $table Name of a table
* @return MyQueryBuilder
* @throws ActiveRecordException if connection was invalid
*/
public function __construct($connection, $table) {
if (!$connection)
throw new ActiveRecordException('A valid database connection is required.');
$this->connection = $connection;
$this->table = $table;
}
/**
* Returns the SQL string.
*
* @return string
*/
public function __toString() {
return $this->to_s();
}
/**
* Returns the SQL string.
*
* @see __toString
* @return string
*/
public function to_s()
{
$func = 'build_' . strtolower($this->operation);
return $this->$func();
}
/**
* Returns the bind values.
*
* @return array
*/
public function bind_values() {
$ret = array();
if ($this->data)
$ret = array_values($this->data);
if ($this->get_where_values())
$ret = array_merge($ret,$this->get_where_values());
return array_flatten($ret);
}
public function get_where_values() {
return $this->where_values;
}
public function where(/* (conditions, values) || (hash) */) {
$this->apply_where_conditions(func_get_args());
return $this;
}
public function order($order) {
$this->order = $order;
return $this;
}
public function group($group) {
$this->group = $group;
return $this;
}
public function having($having) {
$this->having = $having;
return $this;
}
public function limit($limit) {
$this->limit = intval($limit);
return $this;
}
public function offset($offset) {
$this->offset = intval($offset);
return $this;
}
public function select($select) {
$this->operation = 'SELECT';
$this->select = $select;
return $this;
}
public function joins($joins) {
$this->joins = $joins;
return $this;
}
public function insert($hash, $pk=null, $sequence_name=null) {
if (!is_hash($hash))
throw new ActiveRecordException('Inserting requires a hash.');
$this->operation = 'INSERT';
$this->data = $hash;
if ($pk && $sequence_name)
$this->sequence = array($pk,$sequence_name);
return $this;
}
public function update($mixed) {
$this->operation = 'UPDATE';
if (is_hash($mixed))
$this->data = $mixed;
elseif (is_string($mixed))
$this->update = $mixed;
else
throw new ActiveRecordException('Updating requires a hash or string.');
return $this;
}
public function delete() {
$this->operation = 'DELETE';
$this->apply_where_conditions(func_get_args());
return $this;
}
/**
* Reverses an order clause.
*/
public static function reverse_order($order) {
if (!trim($order))
return $order;
$parts = explode(',',$order);
for ($i=0,$n=count($parts); $i<$n; ++$i)
{
$v = strtolower($parts[$i]);
if (strpos($v,' asc') !== false)
$parts[$i] = preg_replace('/asc/i','DESC',$parts[$i]);
elseif (strpos($v,' desc') !== false)
$parts[$i] = preg_replace('/desc/i','ASC',$parts[$i]);
else
$parts[$i] .= ' DESC';
}
return join(',',$parts);
}
/**
* Converts a string like "id_and_name_or_z" into a conditions value like array("id=? AND name=? OR z=?", values, ...).
*
* @param Connection $connection
* @param $name Underscored string
* @param $values Array of values for the field names. This is used
* to determine what kind of bind marker to use: =?, IN(?), IS NULL
* @param $map A hash of "mapped_column_name" => "real_column_name"
* @return A conditions array in the form array(sql_string, value1, value2,...)
*/
public static function create_conditions_from_underscored_string(Connection $connection, $name, &$values=array(), &$map=null) {
if (!$name)
return null;
$parts = preg_split('/(_and_|_or_)/i',$name,-1,PREG_SPLIT_DELIM_CAPTURE);
$num_values = count($values);
$conditions = array('');
for ($i=0,$j=0,$n=count($parts); $i<$n; $i+=2,++$j)
{
if ($i >= 2)
$conditions[0] .= preg_replace(array('/_and_/i','/_or_/i'),array(' AND ',' OR '),$parts[$i-1]);
if ($j < $num_values)
{
if (!is_null($values[$j]))
{
$bind = is_array($values[$j]) ? ' IN(?)' : '=?';
$conditions[] = $values[$j];
}
else
$bind = ' IS NULL';
}
else
$bind = ' IS NULL';
// map to correct name if $map was supplied
$name = $map && isset($map[$parts[$i]]) ? $map[$parts[$i]] : $parts[$i];
$conditions[0] .= $connection->quote_name($name) . $bind;
}
return $conditions;
}
/**
* Like create_conditions_from_underscored_string but returns a hash of name => value array instead.
*
* @param string $name A string containing attribute names connected with _and_ or _or_
* @param $args Array of values for each attribute in $name
* @param $map A hash of "mapped_column_name" => "real_column_name"
* @return array A hash of array(name => value, ...)
*/
public static function create_hash_from_underscored_string($name, &$values=array(), &$map=null) {
$parts = preg_split('/(_and_|_or_)/i',$name);
$hash = array();
for ($i=0,$n=count($parts); $i<$n; ++$i)
{
// map to correct name if $map was supplied
$name = $map && isset($map[$parts[$i]]) ? $map[$parts[$i]] : $parts[$i];
$hash[$name] = $values[$i];
}
return $hash;
}
/**
* prepends table name to hash of field names to get around ambiguous fields when SQL builder
* has joins
*
* @param array $hash
* @return array $new
*/
private function prepend_table_name_to_fields($hash=array()) {
$new = array();
$table = $this->connection->quote_name($this->table);
foreach ($hash as $key => $value)
{
$k = $this->connection->quote_name($key);
$new[$table.'.'.$k] = $value;
}
return $new;
}
private function apply_where_conditions($args) {
// require_once 'Expressions.php';
$num_args = count($args);
if ($num_args == 1 && is_hash($args[0]))
{
$hash = is_null($this->joins) ? $args[0] : $this->prepend_table_name_to_fields($args[0]);
$e = new Expressions($this->connection,$hash);
$this->where = $e->to_s();
$this->where_values = array_flatten($e->values());
}
elseif ($num_args > 0)
{
// if the values has a nested array then we'll need to use Expressions to expand the bind marker for us
$values = array_slice($args,1);
foreach ($values as $name => &$value)
{
if (is_array($value))
{
$e = new Expressions($this->connection,$args[0]);
$e->bind_values($values);
$this->where = $e->to_s();
$this->where_values = array_flatten($e->values());
return;
}
}
// no nested array so nothing special to do
$this->where = $args[0];
$this->where_values = &$values;
}
}
private function build_delete() {
$sql = "DELETE FROM $this->table";
if ($this->where)
$sql .= " WHERE $this->where";
if ($this->connection->accepts_limit_and_order_for_update_and_delete())
{
if ($this->order)
$sql .= " ORDER BY $this->order";
if ($this->limit)
$sql = $this->connection->limit($sql,null,$this->limit);
}
return $sql;
}
private function build_insert()
{
require_once 'Expressions.php';
$keys = join(',',$this->quoted_key_names());
if ($this->sequence)
{
$sql =
"INSERT INTO $this->table($keys," . $this->connection->quote_name($this->sequence[0]) .
") VALUES(?," . $this->connection->next_sequence_value($this->sequence[1]) . ")";
}
else
$sql = "INSERT INTO $this->table($keys) VALUES(?)";
$e = new Expressions($this->connection,$sql,array_values($this->data));
return $e->to_s();
}
private function build_select()
{
$sql = "SELECT $this->select FROM $this->table";
if ($this->joins)
$sql .= ' ' . $this->joins;
if ($this->where)
$sql .= " WHERE $this->where";
if ($this->group)
$sql .= " GROUP BY $this->group";
if ($this->having)
$sql .= " HAVING $this->having";
if ($this->order)
$sql .= " ORDER BY $this->order";
if ($this->limit || $this->offset)
$sql = $this->connection->limit($sql,$this->offset,$this->limit);
return $sql;
}
private function build_update()
{
if (strlen($this->update) > 0)
$set = $this->update;
else
$set = join('=?, ', $this->quoted_key_names()) . '=?';
$sql = "UPDATE $this->table SET $set";
if ($this->where)
$sql .= " WHERE $this->where";
if ($this->connection->accepts_limit_and_order_for_update_and_delete())
{
if ($this->order)
$sql .= " ORDER BY $this->order";
if ($this->limit)
$sql = $this->connection->limit($sql,null,$this->limit);
}
return $sql;
}
private function quoted_key_names()
{
$keys = array();
foreach ($this->data as $key => $value)
$keys[] = $this->connection->quote_name($key);
return $keys;
}
}
/**
* Templating like class for building SQL statements.
*
* Examples:
* 'name = :name AND author = :author'
* 'id = IN(:ids)'
* 'id IN(:subselect)'
*
* @package ActiveRecord
*/
class Expressions
{
const ParameterMarker = '?';
private $expressions;
private $values = array();
private $connection;
public function __construct($connection, $expressions=null /* [, $values ... ] */)
{
$values = null;
$this->connection = $connection;
if (is_array($expressions))
{
$glue = func_num_args() > 2 ? func_get_arg(2) : ' AND ';
list($expressions,$values) = $this->build_sql_from_hash($expressions,$glue);
}
if ($expressions != '')
{
if (!$values)
$values = array_slice(func_get_args(),2);
$this->values = $values;
$this->expressions = $expressions;
}
}
/**
* Bind a value to the specific one based index. There must be a bind marker
* for each value bound or to_s() will throw an exception.
*/
public function bind($parameter_number, $value)
{
if ($parameter_number <= 0)
throw new ExpressionsException("Invalid parameter index: $parameter_number");
$this->values[$parameter_number-1] = $value;
}
public function bind_values($values)
{
$this->values = $values;
}
/**
* Returns all the values currently bound.
*/
public function values()
{
return $this->values;
}
/**
* Returns the connection object.
*/
public function get_connection()
{
return $this->connection;
}
/**
* Sets the connection object. It is highly recommended to set this so we can
* use the adapter's native escaping mechanism.
*
* @param string $connection a Connection instance
*/
public function set_connection($connection)
{
$this->connection = $connection;
}
public function to_s($substitute=false, &$options=null)
{
if (!$options) $options = array();
$values = array_key_exists('values',$options) ? $options['values'] : $this->values;
$ret = "";
$replace = array();
$num_values = count($values);
$len = strlen($this->expressions);
$quotes = 0;
for ($i=0,$n=strlen($this->expressions),$j=0; $i<$n; ++$i)
{
$ch = $this->expressions[$i];
if ($ch == self::ParameterMarker)
{
if ($quotes % 2 == 0)
{
if ($j > $num_values-1)
throw new ExpressionsException("No bound parameter for index $j");
$ch = $this->substitute($values,$substitute,$i,$j++);
}
}
elseif ($ch == '\'' && $i > 0 && $this->expressions[$i-1] != '\\')
++$quotes;
$ret .= $ch;
}
return $ret;
}
private function build_sql_from_hash(&$hash, $glue)
{
$sql = $g = "";
foreach ($hash as $name => $value)
{
if ($this->connection)
$name = $this->connection->quote_name($name);
if (is_array($value))
$sql .= "$g$name IN(?)";
else
$sql .= "$g$name=?";
$g = $glue;
}
return array($sql,array_values($hash));
}
private function substitute(&$values, $substitute, $pos, $parameter_index)
{
$value = $values[$parameter_index];
if (is_array($value))
{
if ($substitute)
{
$ret = '';
for ($i=0,$n=count($value); $i<$n; ++$i)
$ret .= ($i > 0 ? ',' : '') . $this->stringify_value($value[$i]);
return $ret;
}
return join(',',array_fill(0,count($value),self::ParameterMarker));
}
if ($substitute)
return $this->stringify_value($value);
return $this->expressions[$pos];
}
private function stringify_value($value)
{
if (is_null($value))
return "NULL";
return is_string($value) ? $this->quote_string($value) : $value;
}
private function quote_string($value)
{
if ($this->connection)
return $this->connection->escape($value);
return "'" . str_replace("'","''",$value) . "'";
}
}