public
Description: The ultra-lightweight ultra-flexible blogging engine with a fetish for birds and misspellings.
Homepage: http://chyrp.net/
Clone URL: git://github.com/vito/chyrp.git
Click here to lend your support to: chyrp and make a donation at www.pledgie.com !
chyrp / includes / class / QueryBuilder.php
100644 328 lines (278 sloc) 9.57 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
<?php
/**
* Class: QueryBuilder
* A generic SQL query builder. All methods are static so there's no point in instantiating.
*/
class QueryBuilder {
/**
* Function: build_insert
* Creates a full insert query.
*/
public static function build_insert($table, $data, &$params = array()) {
$conditions = self::build_conditions($data, $params);
$data = array();
 
foreach ($conditions as $cond) {
$split = explode(" = ", $cond);
$data[$split[0]] = $split[1];
}
 
return "INSERT INTO __$table\n".
                   self::build_insert_header($data)."\n".
                   "VALUES\n".
                   self::build_insert_values($data);
}
 
/**
* Function: build_replace
* Creates a full replace query.
*/
public static function build_replace($table, $data, &$params = array()) {
$conditions = self::build_conditions($data, $params);
$data = array();
 
foreach ($conditions as $cond) {
$split = explode(" = ", $cond);
$data[$split[0]] = $split[1];
}
 
return "REPLACE INTO __$table\n".
                   self::build_insert_header($data)."\n".
                   "VALUES\n".
                   self::build_insert_values($data);
}
 
/**
* Function: build_update
* Creates a full update query.
*/
public static function build_update($table, $conds, $data, &$params = array()) {
return "UPDATE __$table\n".
                   "SET ".self::build_update_values($data, $params)."\n".
                   ($conds ? "WHERE ".self::build_where($conds, $table, $params) : "");
}
 
/**
* Function: build_delete
* Creates a full delete query.
*/
public static function build_delete($table, $conds, &$params = array()) {
return "DELETE FROM __$table\n".
                   ($conds ? "WHERE ".self::build_where($conds, $table, $params) : "");
}
 
/**
* Function: build_update_values
* Creates an update data part.
*/
public static function build_update_values($data, &$params = array()) {
$set = self::build_conditions($data, $params);
return implode(", ", $set);
}
 
/**
* Function: build_insert_header
* Creates an insert header part.
*/
public static function build_insert_header($data) {
$set = array();
 
foreach (array_keys($data) as $field)
array_push($set, $field);
 
return "(".implode(", ", $set).")";
}
 
/**
* Function: build_insert_values
* Creates an insert data part.
*/
public static function build_insert_values($data) {
return "(".implode(', ', array_values($data)).")";
}
 
/**
* Function: build_limits
* Creates a LIMIT part for a query.
*/
public static function build_limits($offset, $limit) {
if ($limit === null)
return "";
 
if ($offset !== null)
return "LIMIT ".$offset.", ".$limit;
 
return "LIMIT ".$limit;
}
 
/**
* Function: build_from
* Creates a FROM header for select queries.
*/
public static function build_from($tables) {
if (!is_array($tables))
$tables = array($tables);
 
foreach ($tables as &$table)
if (substr($table, 0, 2) != "__")
$table = "__".$table;
 
return implode(", ", $tables);
}
 
/**
* Function: build_count
* Creates a SELECT COUNT(1) query.
*/
public static function build_count($tables, $conds, &$params = array()) {
return "SELECT COUNT(1) AS count\n".
"FROM ".self::build_from($tables)."\n".
($conds ? "WHERE ".self::build_where($conds, $tables, $params) : "");
}
 
/**
* Function: build_select_header
* Creates a SELECT fields header.
*/
public static function build_select_header($fields, $tables = null) {
if (!is_array($fields))
$fields = array($fields);
 
$tables = (array) $tables;
 
foreach ($fields as &$field)
self::tablefy($field, $tables);
 
return implode(', ', $fields);
}
 
/**
* Function: build_where
* Creates a WHERE query.
*/
public static function build_where($conds, $tables = null, &$params = array()) {
$conds = (array) $conds;
$tables = (array) $tables;
 
$conditions = self::build_conditions($conds, $params, $tables);
 
return (empty($conditions)) ? "" : "(".implode(") AND (", array_filter($conditions)).")";
}
 
/**
* Function: build_group
* Creates a GROUP BY argument.
*/
public static function build_group($by, $tables = null) {
$by = (array) $by;
$tables = (array) $tables;
 
foreach ($by as &$column)
self::tablefy($column, $tables);
 
return implode(", ", array_unique(array_filter($by)));
}
 
/**
* Function: build_order
* Creates a ORDER BY argument.
*/
public static function build_order($order, $tables = null) {
$tables = (array) $tables;
 
if (!is_array($order))
$order = explode(", ", $order);
 
foreach ($order as &$by)
self::tablefy($by, $tables);
 
return implode(", ", $order);
}
 
/**
* Function: build_conditions
* Builds an associative array of SQL values into PDO-esque paramized query strings.
*
* Parameters:
* $conds - Conditions.
* $params - Parameters array to fill.
* $tables - If specified, conditions will be tablefied with these tables.
*/
public static function build_conditions($conds, &$params, $tables = null) {
foreach ($conds as $key => $val) {
if (is_int($key)) # Full expression
$cond = $val;
else { # Key => Val expression
if (is_string($val) and strlen($val) and $val[0] == ":")
$cond = $key." = ".$val;
else {
if (substr($key, -4) == " not") { # Negation
$key = substr($key, 0, -4);
$param = str_replace(array("(", ")"), "_", $key);
if (is_array($val))
$cond = $key." NOT IN ".self::build_in($val);
elseif ($val === null)
$cond = $key." IS NOT NULL";
else {
$cond = $key." != :".$param;
$params[":".$param] = $val;
}
} elseif (substr($key, -5) == " like") { # LIKE
$key = substr($key, 0, -5);
$param = str_replace(array("(", ")"), "_", $key);
$cond = $key." LIKE :".$param;
$params[":".$param] = $val;
} elseif (substr($key, -9) == " not like") { # NOT LIKE
$key = substr($key, 0, -9);
$param = str_replace(array("(", ")"), "_", $key);
$cond = $key." NOT LIKE :".$param;
$params[":".$param] = $val;
} elseif (substr_count($key, " ")) { # Custom operation, e.g. array("foo >" => $bar)
list($param,) = explode(" ", $key);
$param = str_replace(array("(", ")"), "_", $param);
$cond = $key." :".$param;
$params[":".$param] = $val;
} else { # Equation
if (is_array($val))
$cond = $key." IN ".self::build_in($val);
elseif ($val === null)
$cond = $key." IS NULL";
else {
$param = str_replace(array("(", ")"), "_", $key);
$cond = $key." = :".$param;
$params[":".$param] = $val;
}
}
}
}
 
if ($tables)
self::tablefy($cond, $tables);
 
$conditions[] = $cond;
}
 
return $conditions;
}
 
public static function build_in($vals) {
$return = array();
 
foreach ($vals as $val)
$return[] = SQL::current()->escape($val);
 
return "(".join(",", $return).")";
}
 
/**
* Function: build_select
* Creates a full SELECT query.
*/
public static function build_select($tables, $fields, $conds, $order = null, $limit = null, $offset = null, $group = null, $left_join = array(), &$params = array()) {
$query = "SELECT ".self::build_select_header($fields, $tables)."\n".
"FROM ".self::build_from($tables)."\n";
 
foreach ($left_join as $join)
$query.= "LEFT JOIN __".$join["table"]." ON ".self::build_where($join["where"], $join["table"], $params)."\n";
 
$query.= ($conds ? "WHERE ".self::build_where($conds, $tables, $params) : "")."\n".
($group ? "GROUP BY ".self::build_group($group, $tables) : "")."\n".
($order ? "ORDER BY ".self::build_order($order, $tables) : "")."\n".
self::build_limits($offset, $limit);
 
return $query;
}
 
/**
* Function: tablefy
* Automatically prepends tables and table prefixes to a field if it doesn't already have them.
*
* Parameters:
* $field - The field to "tablefy".
* $tables - An array of tables. The first one will be used for prepending.
*/
public static function tablefy(&$field, $tables) {
if (!preg_match_all("/(\(|[\s]+|^)(?!__)([a-z0-9_\.\*]+)(\)|[\s]+|$)/", $field, $matches))
return;
 
foreach ($matches[0] as $index => $full) {
$before = $matches[1][$index];
$name = $matches[2][$index];
$after = $matches[3][$index];
 
if (is_numeric($name))
continue;
 
# Does it not already have a table specified?
if (!substr_count($full, ".")) {
# Don't replace things that are already either prefixed or paramized.
$field = preg_replace("/([^\.:'\"_]|^)".preg_quote($full, "/")."/",
"\\1".$before."__".$tables[0].".".$name.$after,
$field,
1);
} else {
# Okay, it does, but is the table prefixed?
if (substr($full, 0, 2) != "__") {
# Don't replace things that are already either prefixed or paramized.
$field = preg_replace("/([^\.:'\"_]|^)".preg_quote($full, "/")."/",
"\\1".$before."__".$name.$after,
$field,
1);
}
}
}
 
$field = preg_replace("/AS ([^ ]+)\./i", "AS ", $field);
}
}