-
Notifications
You must be signed in to change notification settings - Fork 1
/
sql-helper.php
382 lines (377 loc) · 15.5 KB
/
sql-helper.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
<?php
/**
* This file is part of the db-utils package.
*
* (c) a4smanjorg5
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class SQL_WHERE_CLAUSE {
const LOGICAL_OR = "|";
const LOGICAL_AND = "&";
const OPERATOR_EQUALWITH = "=";
const OPERATOR_GREATERTHAN = ">";
const OPERATOR_GREATEROREQUAL = ">=";
const OPERATOR_LESSTHAN = "<";
const OPERATOR_LESSOREQUAL = "<=";
const OPERATOR_NOTEQUAL = "!=";
const OPERATOR_WILDCARD = "%";
const OPERATOR_LIKEWITH = "%=";
const OPERATOR_NOTLIKE = "!%";
const OPERATOR_INWITH = "@";
const OPERATOR_NOTIN = "!@";
const OPERATOR_BETWEENWITH = "~";
const OPERATOR_NOTBETWEEN = "!~";
const OPERATOR_ISNULL = "#";
const OPERATOR_NOTNULL = "!#";
private $clauses = array();
private $op_logical = self::LOGICAL_AND;
private $last_logical = null;
private $rev = -1;
function next() {
if(func_num_args() < 1) {
if($this -> rev < 0) return false;
$clauses = $this -> clauses;
if(count($clauses) > 1 && is_null($this -> last_logical) &&
$this -> rev <= 0) {
$this -> default_logical = $clauses[1];
$this -> last_logical = $clauses[1];
return $clauses[1];
}
if(is_array($clauses[$this -> rev])) {
$clause = $clauses[$this -> rev];
$result = array($clause['op'], $clause['col']);
foreach($clause as $p => $v) if($p !== "op" &&
$p !== "col") $result[] = $v;
} else {
if($this -> op_logical != $clauses[$this -> rev])
$this -> default_logical = $clauses[$this -> rev];
if($this -> last_logical != $clauses[$this -> rev]) {
$result = $clauses[$this -> rev];
$this -> last_logical = $clauses[$this -> rev];
}
}
$this -> rev++;
if(count($this -> clauses) <= $this -> rev) {
$this -> last_logical = null;
$this -> rev = -1;
}
return (isset($result) ? $result : $this -> next());
} elseif(func_num_args() <= 1)
throw new InvalidArgumentException("Missing argument 1.");
if($this -> rev >= 0) return false;
$clause = array("col" => func_get_arg(0), "op" => func_get_arg(1));
switch($clause['op']) {
case self::OPERATOR_EQUALWITH:
case self::OPERATOR_GREATERTHAN:
case self::OPERATOR_GREATEROREQUAL:
case self::OPERATOR_LESSTHAN:
case self::OPERATOR_LESSOREQUAL:
case self::OPERATOR_NOTEQUAL:
case self::OPERATOR_LIKEWITH:
case self::OPERATOR_NOTLIKE:
if(func_num_args() > 2)
$clause[] = func_get_arg(2);
else $clause[] = null;
break;
case self::OPERATOR_INWITH:
case self::OPERATOR_NOTIN:
if(func_num_args() > 2)
$clause[] = func_get_arg(2);
else $clause[] = null;
for($i = 3; $i < func_num_args(); $i++)
$clause[] = func_get_arg($i);
break;
case self::OPERATOR_BETWEENWITH:
case self::OPERATOR_NOTBETWEEN:
if(func_num_args() > 2)
$clause[] = func_get_arg(2);
else $clause[] = null;
if(func_num_args() > 3)
$clause[] = func_get_arg(3);
else $clause[] = null;
break;
case self::OPERATOR_ISNULL:
case self::OPERATOR_NOTNULL:
break;
default:
return false;
}
if(count($this -> clauses) > 0)
$this -> clauses[] = $this -> op_logical;
$this -> clauses[] = $clause;
return true;
}
function __get($prop) {
if($prop == "default_logical")
return $this -> op_logical;
}
function __set($prop, $val) {
if($prop == "default_logical") {
if($val !== self::LOGICAL_AND &&
$val !== self::LOGICAL_OR)
throw new Exception("invalid value");
$this -> op_logical = $val;
}
}
function reverse($reset = true) {
if(($this -> rev === 0 && !$reset) ||
count($this -> clauses) > 0)
$this -> last_logical = null;
if($this -> rev >= 0 && !$reset)
$this -> rev = -1;
elseif(count($this -> clauses) > 0)
$this -> rev = 0;
}
function to_clause($where_clause = true, $upper_clause = true) {
$result = "";
foreach($this -> clauses as $clause) {
if(is_array($clause)) {
$result .= SQL::fieldname_quote($clause['col']) . " ";
$vals = array();
foreach($clause as $p => $v)
if($p !== "col" && $p !== "op")
$vals[] = $v;
switch($clause['op']) {
case self::OPERATOR_EQUALWITH:
case self::OPERATOR_GREATERTHAN:
case self::OPERATOR_GREATEROREQUAL:
case self::OPERATOR_LESSTHAN:
case self::OPERATOR_LESSOREQUAL:
case self::OPERATOR_NOTEQUAL:
$result .= "$clause[op] " .
SQL::escape_valstr($vals[0], $upper_clause);
break;
case self::OPERATOR_LIKEWITH:
$result .= ($upper_clause ? "LIKE" : "like") .
" " . SQL::value_query_quote($vals[0]);
break;
case self::OPERATOR_NOTLIKE:
$result .= ($upper_clause ? "NOT LIKE" : "not like") .
" " . SQL::value_query_quote($vals[0]);
break;
case self::OPERATOR_INWITH:
$result .= ($upper_clause ? "IN" : "in") .
"(" . implode(",", array_map(function($val) use ($upper_clause) {
return SQL::escape_valstr($val, $upper_clause);
}, $vals)) . ")";
break;
case self::OPERATOR_NOTIN:
$result .= ($upper_clause ? "NOT IN" : "not in") .
"(" . implode(",", array_map(function($val) use ($upper_clause) {
return SQL::escape_valstr($val, $upper_clause);
}, $vals)) . ")";
break;
case self::OPERATOR_BETWEENWITH:
$result .= ($upper_clause ? "BETWEEN" : "between") .
" " . SQL::escape_valstr($vals[0], $upper_clause) . " " .
($upper_clause ? "AND" : "and") . " " .
SQL::escape_valstr($vals[1], $upper_clause);
break;
case self::OPERATOR_NOTBETWEEN:
$result .= ($upper_clause ? "NOT BETWEEN" : "not between") .
" " . SQL::escape_valstr($vals[0], $upper_clause) . " " .
($upper_clause ? "AND" : "and") . " " .
SQL::escape_valstr($vals[1], $upper_clause);
break;
case self::OPERATOR_ISNULL:
$result .= $upper_clause ? "IS NULL" : "is null";
break;
case self::OPERATOR_NOTNULL:
$result .= $upper_clause ? "IS NOT NULL" : "is not null";
break;
}
} else switch($clause) {
case self::LOGICAL_AND:
$result .= $upper_clause ? " AND " : " and ";
break;
case self::LOGICAL_OR:
$result .= $upper_clause ? " OR " : " or ";
break;
}
}
return ($where_clause ? ($upper_clause ? "WHERE" : "where") . " " .
(empty($result) ? 1 : "") : "") . $result;
}
function __toString() {
return $this -> to_clause();
}
private static function is_operator($value) {
switch($value) {
case self::OPERATOR_EQUALWITH:
case self::OPERATOR_GREATERTHAN:
case self::OPERATOR_GREATEROREQUAL:
case self::OPERATOR_LESSTHAN:
case self::OPERATOR_LESSOREQUAL:
case self::OPERATOR_NOTEQUAL:
case self::OPERATOR_WILDCARD:
case self::OPERATOR_LIKEWITH:
case self::OPERATOR_NOTLIKE:
case self::OPERATOR_INWITH:
case self::OPERATOR_NOTIN:
case self::OPERATOR_BETWEENWITH:
case self::OPERATOR_NOTBETWEEN:
case self::OPERATOR_ISNULL:
case self::OPERATOR_NOTNULL:
return true;
}
return false;
}
static function create($init) {
if(!is_array($init)) return false;
$result = new SQL_WHERE_CLAUSE();
$co_op = false;
foreach($init as $clause) {
if(is_array($clause)) {
if(count($clause) < 2) $clause[] = null;
if(self::is_operator($clause[0]) &&
!self::is_operator($clause[1])) {
$op = $clause[0];
$clause[0] = $clause[1];
$clause[1] = $op;
}
if($co_op && is_null($result -> op_logical))
return false;
if(!call_user_func_array(array($result, "next"), $clause))
return false;
$co_op = true;
} else try { $result -> default_logical = $clause; } catch(Exception $_) {}
}
return $result;
}
}
class SQL {
private function __construct() {}
static $upper_clause = true;
static function delete_clause($tbl_name, $where) {
$tbl = SQL::fieldname_quote($tbl_name);
$w = is_a($where, "SQL_WHERE_CLAUSE") ? " " . $where -> to_clause(true, self::$upper_clause) : "";
$sql = self::$upper_clause ? 'DELETE FROM' : 'delete from';
return "$sql $tbl$w";
}
static function escape_valstr($val, $upper_clause = true) {
if (is_null($val))
return ($upper_clause ? "NULL" : "null");
if (is_bool($val))
return self::escape_valstr((int)$val);
if ((is_numeric($val) && !is_string($val)))
return (string)$val;
if (is_array($val))
return call_user_func_array(array(get_class(),
"value_func_quote"),
array_merge(array($upper_clause), $val));
return self::value_query_quote($val, true);
}
static function fieldname_quote($qn, $quotes = true) {
if($quotes) return "`" . SQL::fieldname_quote($qn, false) . "`";
return str_replace('`', '``', $qn);
}
static function insert_clause($tbl_name, $values) {
$tbl = SQL::fieldname_quote($tbl_name);
$cols = ""; $vals = "";
foreach($values as $col => $val) {
$cols = "$cols" . (is_numeric($col) ? $col :
SQL::fieldname_quote($col)) . ', ';
$vals = "$vals" . SQL::escape_valstr($val, self::$upper_clause) . ", ";
}
$cols = substr($cols, 0, strlen($cols) - 2);
$vals = substr($vals, 0, strlen($vals) - 2);
if (self::$upper_clause) {
$ic = 'INSERT INTO';
$vc = 'VALUES';
} else {
$ic = 'insert into';
$vc = 'values';
}
return "$ic $tbl ($cols) $vc ($vals)";
}
static function select_clause($tbl_name, $fields/*, $where|$orderBy|$descOrder|$limit|$offset, ...*/) {
$tbl = SQL::fieldname_quote($tbl_name);
if($fields == "*") $cols = $fields;
else {
$cols = "";
foreach($fields as $fk => $fv) {
$cols .= self::escape_fieldstr($fv);
if (!is_numeric($fk))
$cols .= ' ' . (self::$upper_clause ? 'AS' : 'as') .
' ' . SQL::fieldname_quote($fk);
$cols .= ', ';
}
$cols = substr($cols, 0, strlen($cols) - 2);
}
$where = ""; $limit = ""; $offset = "";
$orderBy = ""; $descOrder = false;
for ($i=2; $i < func_num_args(); $i++) {
$arg = func_get_arg($i);
if(is_a($arg, "SQL_WHERE_CLAUSE")) {
if(is_a($where, "SQL_WHERE_CLAUSE")) {
$arg -> reverse();
while ($expr = $arg -> next()) {
if (is_array($expr)) {
array_splice($expr, 1, 0, array_shift($expr));
call_user_func_array(array($where, 'next'), $expr);
} else $where -> default_logical = $expr;
}
} else $where = $arg;
} elseif(is_numeric($arg)) {
if($limit == "")
$limit = ' ' . (self::$upper_clause ? 'LIMIT' : 'limit') . " $arg";
elseif($offset == "")
$offset = ' ' . (self::$upper_clause ? 'OFFSET' : 'offset') . " $arg";
} elseif(is_bool($arg))
$descOrder = $arg;
else $orderBy = SQL::fieldname_quote($arg);
}
if (self::$upper_clause) {
$sc = 'SELECT';
$fc = 'FROM';
$descOrder = $descOrder ? 'DESC' : "ASC";
} else {
$sc = 'select';
$fc = 'from';
$descOrder = $descOrder ? 'desc' : "asc";
}
if ($orderBy != "")
$orderBy = ' ' . (self::$upper_clause ? 'ORDER BY' : 'order by') .
" $orderBy $descOrder";
if($where !== "") $where = ' ' . $where -> to_clause(true, self::$upper_clause);
return "$sc $cols $fc $tbl$where$orderBy$limit$offset";
}
static function truncate_clause($tbl_name) {
$tbl = SQL::fieldname_quote($tbl_name);
$sql = self::$upper_clause ? 'TRUNCATE TABLE' : 'truncate table';
return "$sql $tbl";
}
static function update_clause($tbl_name, $col_vals, $where = "") {
$tbl = SQL::fieldname_quote($tbl_name);
$vals = "";
foreach($col_vals as $col => $val)
$vals = "$vals" . SQL::fieldname_quote($col) .
" = " . SQL::escape_valstr($val, self::$upper_clause) . ", ";
$vals = substr($vals, 0, strlen($vals) - 2);
$w = is_a($where, "SQL_WHERE_CLAUSE") ? " " . $where -> to_clause(true, self::$upper_clause) : "";
if (self::$upper_clause) {
$uc = 'UPDATE';
$sc = 'SET';
} else {
$uc = 'update';
$sc = 'set';
}
return "$uc $tbl $sc $vals$w";
}
static function value_func_quote($upper_clause, $func_name) {
if (func_num_args() > 3)
$args = implode(',', array_map(function($val) use ($upper_clause) {
return self::escape_valstr($val, $upper_clause);
}, array_slice(func_get_args(), 3)));
else $args = "";
return ($upper_clause ? strtoupper($func_name) :
strtolower($func_name)) . "($args)";
}
static function value_query_quote($val, $quotes = true) {
if($quotes) return "'" . SQL::value_query_quote($val, false) . "'";
return str_replace("'", "''", str_replace('\\', '\\\\', $val));
}
}
?>