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
|
<?php
/**
* Class SQLQuery
* This class is to MANAGE a query that is maybe more complex than a standard sql-query.
* You can easily add filters, joins and additional select-parts.
*
* $query = SQLQuery::table("auth_user_md5")
* ->join("seminar_user", "seminar_user.user_id = auth_user_md5.user_id")
* ->join("seminar_inst", "seminar_inst.seminar_id = seminar_user.Seminar_id")
* ->where("seminar_inst.institut_id = :institut_id",array('institut_id' => $inst->getId()));
* if (Request::get("status") {
* $query->where("auth_user_md5.status = :status", array('status' => Request::get("status"));
* }
* if ($query->count() <= 500) {
* $user_data = $query->fetchAll();
* } else {
* PageLayout::postInfo(_("Geben Sie mehr Filter ein."));
* }
*
*
*/
class SQLQuery
{
public $settings = [
'table' => '',
'select' => [],
'joins' => [],
'where' => [],
'parameter' => [],
'having' => [],
'order' => '',
'limit' => []
];
public $name = '';
public static function table(string $table, string $query_name = '')
{
$query = new self($table, $query_name);
return $query;
}
/**
* Constructor of the query. A main table is needed.
* @param string $table : a database table
* @param string name :
*/
public function __construct(string $table, string $query_name = '')
{
$this->settings['table'] = $table;
$this->name = $query_name;
}
public function select($select, $statement = null)
{
if (!is_array($select)) {
$select = $statement ? [$select => $statement] : [$select => ''];
}
foreach ($select as $alias => $statement) {
$this->settings['select'][$alias] = $select;
}
}
/**
* Joins a table to the query. You can omit $table and just call join($tablename,
* $on, $join) if you don't need an alias.
* @param $alias : table-name or an alias.
* @param null $table : optional table name. Use this if you want to use an alias.
* @param string $on : any condition like "t1.user_id = t2.id"
* @param string $join : type of joining "INNER JOIN" or "LEFT JOIN"
* @return $this
*/
public function join($alias, $table = null, $on = '', $join = 'INNER JOIN')
{
if (preg_match('/[\s=]/', $table)) {
// user left away the $table var and shifted the other variables:
$join = $on;
$on = $table;
$table = null;
}
$this->settings['joins'][$alias] = [];
if ($table) {
$this->settings['joins'][$alias]['table'] = $table;
}
if ($on) {
$this->settings['joins'][$alias]['on'] = $on;
}
if ($join) {
$this->settings['joins'][$alias]['join'] = $join;
}
return $this;
}
/**
* Adds a condition to the query. Any conditions will get concatenated by AND.
* @param $name : the name of the condition. Use any name. It will be treated as an identifier.
* @param null $condition
* @param array $parameter
* @return $this
*/
public function where($name, $condition = null, $parameter = [])
{
if ($condition === null && isset($this->settings['where'][$name])) {
unset($this->settings['where'][$name]);
} elseif ($parameter === null && $condition !== null) {
$this->settings['where'][$name] = $name;
$this->settings['parameter'] = array_merge($this->settings['parameter'], $condition);
} elseif ($condition === null) {
$this->settings['where'][md5($name)] = $name;
} else {
$this->settings['where'][$name] = $condition;
$this->settings['parameter'] = array_merge($this->settings['parameter'], $parameter);
}
return $this;
}
public function having($name, $condition = null, $parameter = [])
{
if ($condition === null && isset($this->settings['having'][$name])) {
unset($this->settings['having'][$name]);
} elseif ($parameter === null && $condition !== null) {
$this->settings['having'][$name] = $name;
$this->settings['parameter'] = array_merge($this->settings['parameter'], $condition);
} elseif ($condition === null) {
$this->settings['having'][md5($name)] = $name;
} else {
$this->settings['having'][$name] = $condition;
$this->settings['parameter'] = array_merge($this->settings['parameter'], $parameter);
}
return $this;
}
/**
* Sets one or more parameter for this query.
* @param array|string $param : associative array or string
* @param null|string $value : value of parameter when $param is a string
*/
public function parameter($param, $value = null)
{
if (is_array($param)) {
$this->settings['parameter'] = array_merge($this->settings['parameter'], $param);
} else {
$this->settings['parameter'][$param] = $value;
}
}
/**
* Removes a formerly defined where condition identified by its name.
* @param $name : the name of the where-condition that was defined in where-method..
* @return $this
*/
public function removeWhereCondition($name)
{
unset($this->settings['where'][$name]);
return $this;
}
/**
* Sets the grouping of the resultset.
* @param string $clause : the clause to sort after like "auth_user_md5.user_id"
* @return $this
*/
public function groupBy($clause)
{
$this->settings['groupby'] = $clause;
return $this;
}
/**
* Sets the order of the resultset.
* @param string $clause : the clause to sort after like "Vorname ASC, position DESC"
* @return $this
*/
public function orderBy($clause)
{
$this->settings['order'] = $clause;
return $this;
}
/**
* Limits the resultset of the query.
* @param integer $start
* @param null|integer $end
* @return $this
*/
public function limit($start, $end = null)
{
if ($end === null) {
$end = $start;
$start = 0;
}
$this->settings['limit'] = [$start, $end];
return $this;
}
/**
* Fetches the number of entries of the resultset.
* @return integer.
*/
public function count()
{
NotificationCenter::postNotification('SQLQueryWillExecute', $this);
$sql = "SELECT COUNT(*) FROM (
SELECT `{$this->settings['table']}`.*
{$this->getQuery()}
) AS counter_table";
$statement = DBManager::get()->prepare($sql);
$statement->execute($this->settings['parameter']);
NotificationCenter::postNotification('SQLQueryDidExecute', $this);
return (int) $statement->fetchColumn();
}
/**
* Fetches the whole resultset as an array of associative arrays. If you define
* a sorm_class the result will be an array of the sorm-objects.
*
* @template T of SimpleORMap
* @param class-string<T>|string|null $sorm_class_or_column : column name, a class of SimpleORMap or null for associative array.
* @param int|null $max_results Maximum number of results to return
* @return array[]|T[]|mixed[] arrays or array of objects or array of values.
*
* @throws OverflowException if number of found rows is greater than $max_results
*/
public function fetchAll($sorm_class_or_column = null, ?int $max_results = null)
{
NotificationCenter::postNotification('SQLQueryWillExecute', $this);
if (
is_string($sorm_class_or_column)
&& !is_subclass_of($sorm_class_or_column, SimpleORMap::class)
) {
$sql = "SELECT `{$this->settings['table']}`.`{$sorm_class_or_column}` ";
} else {
$sql = "SELECT `{$this->settings['table']}`.* ";
}
foreach ($this->settings['select'] as $alias => $statement) {
$sql .= $statement ? "{$statement} AS {$alias} " : $alias;
}
$sql .= $this->getQuery();
$statement = DBManager::get()->prepare($sql);
$statement->execute((array) $this->settings['parameter']);
NotificationCenter::postNotification('SQLQueryDidExecute', $this);
if (
is_string($sorm_class_or_column)
&& !is_subclass_of($sorm_class_or_column, SimpleORMap::class)
) {
return $statement->fetchAll(PDO::FETCH_COLUMN);
}
$statement->setFetchMode(PDO::FETCH_ASSOC);
$result = [];
$count = 0;
foreach ($statement as $row) {
$result[$count++] = $sorm_class_or_column ? $sorm_class_or_column::buildExisting($row) : $row;
if ($max_results && $count > $max_results) {
// Count remaining rows
$statement->setFetchMode(PDO::FETCH_COLUMN, 0);
while ($statement->fetch()) {
$count += 1;
}
throw new OverflowException($count);
}
}
return $result;
}
/**
* Shows the query that would be executed in the method fetchAll
* @return string : sql query
*/
public function show()
{
$sql = "SELECT `{$this->settings['table']}`.* ";
foreach ((array) $this->settings['select'] as $alias => $statement) {
$sql .= $statement ? "{$statement} AS {$alias} " : $alias;
}
$sql .= $this->getQuery();
return $sql;
}
/*******************************************************************************
* protected and private *
*******************************************************************************/
/**
* Constructs a query string for a prepared statement without the SELECT part.
* @return string
*/
protected function getQuery()
{
$sql = "FROM `{$this->settings['table']}` ";
foreach ($this->settings['joins'] as $alias => $joindata) {
$table = isset($joindata['table']) ? "{$joindata['table']} AS {$alias}" : $alias;
$on = isset($joindata['on']) ? " ON ({$joindata['on']})" : '';
$sql .= " " . (isset($joindata['join']) ? $joindata['join'] : 'INNER JOIN') . " {$table}{$on} ";
}
if (!empty($this->settings['where'])) {
$sql .= "WHERE (" . implode(") AND (", $this->settings['where']) . ") ";
}
if (!empty($this->settings['groupby'])) {
$sql .= "GROUP BY {$this->settings['groupby']} ";
}
if (!empty($this->settings['having'])) {
$sql .= "HAVING (" . implode(") AND (", $this->settings['having']) . ") ";
}
if (!empty($this->settings['order'])) {
$sql .= "ORDER BY {$this->settings['order']} ";
}
if (!empty($this->settings['limit'])) {
$sql .= "LIMIT ". (int) $this->settings['limit'][0] . ", " . (int) $this->settings['limit'][1] . " ";
}
return $sql;
}
/**
* Fetches the primary key of the table and returns it as an array.
* @return array : primary key as array("column1", "column2")
*/
protected function getPrimaryKey()
{
$query = "SHOW COLUMNS FROM `{$this->settings['table']}`
WHERE `Key` = 'PRI'";
$statement = DBManager::get()->exec($query);
$pk = [];
while ($rs = $statement->fetch(PDO::FETCH_ASSOC)) {
$pk[] = "`{$this->settings['table']}`.`{$rs['Field']}`";
}
return $pk;
}
}
|