-
Notifications
You must be signed in to change notification settings - Fork 440
/
Copy pathSQLBuilder.php
422 lines (350 loc) · 9.06 KB
/
SQLBuilder.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
<?php
/**
* @package ActiveRecord
*/
namespace ActiveRecord;
/**
* Helper class for building sql statements progmatically.
*
* @package ActiveRecord
*/
class SQLBuilder
{
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 SQLBuilder
* @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 = is_null($values) ? 0 : 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;
}
}