|
1
|
|
|
<?php |
|
2
|
|
|
namespace samson\activerecord; |
|
3
|
|
|
|
|
4
|
|
|
//TODO: Написать метод ALL() |
|
5
|
|
|
//TODO: Поддержка нескольких подключений |
|
6
|
|
|
/** |
|
7
|
|
|
* Запрос для БД |
|
8
|
|
|
* Класс собирает в себя все необходимые параметры для |
|
9
|
|
|
* формирования "правильного" запроса на самом низком уровне |
|
10
|
|
|
* работы с БД |
|
11
|
|
|
* @author Vitaly Iegorov <[email protected]> |
|
12
|
|
|
* |
|
13
|
|
|
*/ |
|
14
|
|
|
class dbQuery extends \samsonframework\orm\Query |
|
|
|
|
|
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* Указатель на текущую группу условий с которой работает запрос |
|
18
|
|
|
* |
|
19
|
|
|
* @var Condition |
|
20
|
|
|
*/ |
|
21
|
|
|
public $cConditionGroup; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* Указатель на соединение с БД |
|
25
|
|
|
* @var resource |
|
26
|
|
|
*/ |
|
27
|
|
|
public $link; |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* Указатель на группу условий для текущего объекта с которой работает запрос |
|
31
|
|
|
* |
|
32
|
|
|
* @var Condition |
|
33
|
|
|
*/ |
|
34
|
|
|
public $own_condition; |
|
35
|
|
|
|
|
36
|
|
|
/** Limiting filter for base table */ |
|
37
|
|
|
public $own_limit; |
|
38
|
|
|
|
|
39
|
|
|
/** Grouping filter for base table */ |
|
40
|
|
|
public $own_group; |
|
41
|
|
|
|
|
42
|
|
|
/** Sorting filter for base table */ |
|
43
|
|
|
public $own_order; |
|
44
|
|
|
|
|
45
|
|
|
/** Virtual field for base table */ |
|
46
|
|
|
public $own_virtual_fields = array(); |
|
47
|
|
|
|
|
48
|
|
|
/** Virtual fields */ |
|
49
|
|
|
public $virtual_fields = array(); |
|
50
|
|
|
|
|
51
|
|
|
public $empty = false; |
|
52
|
|
|
|
|
53
|
|
|
/** @var bool True to show requests */ |
|
54
|
|
|
protected $debug = false; |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* Коллекция условных групп для запроса |
|
58
|
|
|
* @var dbConditionGroup |
|
59
|
|
|
*/ |
|
60
|
|
|
public $condition; |
|
61
|
|
|
|
|
62
|
|
|
/** |
|
63
|
|
|
* Параметры ограничения результатов запроса к БД |
|
64
|
|
|
* @var array |
|
65
|
|
|
*/ |
|
66
|
|
|
public $limit = array(); |
|
67
|
|
|
|
|
68
|
|
|
/** |
|
69
|
|
|
* Параметры сортировки результатов запроса к БД |
|
70
|
|
|
* @var array |
|
71
|
|
|
*/ |
|
72
|
|
|
public $order = array(); |
|
73
|
|
|
|
|
74
|
|
|
/** |
|
75
|
|
|
* Параметры группировки результатов запроса к БД |
|
76
|
|
|
* @var array |
|
77
|
|
|
*/ |
|
78
|
|
|
public $group = array(); |
|
79
|
|
|
|
|
80
|
|
|
/** |
|
81
|
|
|
* Коллекция параметров для запроса к связанным объектам |
|
82
|
|
|
* @var array |
|
83
|
|
|
*/ |
|
84
|
|
|
public $join = array(); |
|
85
|
|
|
|
|
86
|
|
|
|
|
87
|
|
|
/** */ |
|
88
|
|
|
public function own_limit($st, $en = NULL) |
|
|
|
|
|
|
89
|
|
|
{ |
|
90
|
|
|
$this->own_limit = array($st, $en); |
|
91
|
|
|
return $this; |
|
92
|
|
|
} |
|
93
|
|
|
|
|
94
|
|
|
/** */ |
|
95
|
|
|
public function own_group_by($params) |
|
|
|
|
|
|
96
|
|
|
{ |
|
97
|
|
|
$this->own_group[] = $params; |
|
98
|
|
|
return $this; |
|
99
|
|
|
} |
|
100
|
|
|
|
|
101
|
|
|
/** */ |
|
102
|
|
|
public function own_order_by($field, $direction = 'ASC') |
|
|
|
|
|
|
103
|
|
|
{ |
|
104
|
|
|
$this->own_order = array($field,$direction); |
|
105
|
|
|
return $this; |
|
106
|
|
|
} |
|
107
|
|
|
|
|
108
|
|
|
/** @see idbQuery::flush() */ |
|
109
|
|
|
public function flush() |
|
110
|
|
|
{ |
|
111
|
|
|
// Очистим параметры запроса |
|
112
|
|
|
$this->condition = new Condition(); |
|
|
|
|
|
|
113
|
|
|
$this->limit = array(); |
|
114
|
|
|
$this->order = array(); |
|
115
|
|
|
$this->group = array(); |
|
116
|
|
|
$this->join = array(); |
|
117
|
|
|
|
|
118
|
|
|
$this->own_condition = new Condition(); |
|
|
|
|
|
|
119
|
|
|
$this->own_group = array(); |
|
120
|
|
|
$this->own_virtual_fields = array(); |
|
121
|
|
|
$this->own_limit = array(); |
|
122
|
|
|
$this->own_order = array(); |
|
123
|
|
|
|
|
124
|
|
|
$this->cConditionGroup = &$this->condition; |
|
125
|
|
|
} |
|
126
|
|
|
|
|
127
|
|
|
/** @see idbQuery::random() */ |
|
128
|
|
|
public function random(& $return_value = null) |
|
129
|
|
|
{ |
|
130
|
|
|
// Add random ordering |
|
131
|
|
|
$this->order_by('', 'RAND()'); |
|
132
|
|
|
|
|
133
|
|
|
// Correctly perform db request for multiple data |
|
134
|
|
|
return func_num_args() ? $this->exec($return_value) : $this->exec(); |
|
135
|
|
|
} |
|
136
|
|
|
|
|
137
|
|
|
|
|
138
|
|
|
/** |
|
139
|
|
|
* @see idbQuery::or_() |
|
140
|
|
|
* @deprecated |
|
141
|
|
|
*/ |
|
142
|
|
|
public function or_($relation = 'OR') |
|
|
|
|
|
|
143
|
|
|
{ |
|
144
|
|
|
// Получим либо переданную группу условий, либо создадим новую, потом добавим её в массив групп условий запроса |
|
145
|
|
|
$cond_group = new Condition($relation); |
|
|
|
|
|
|
146
|
|
|
|
|
147
|
|
|
// Установим текущую группу условий с которой работает запрос |
|
148
|
|
|
$this->cConditionGroup = &$cond_group; |
|
149
|
|
|
|
|
150
|
|
|
// Добавим нову группу условий в коллекцию групп |
|
151
|
|
|
$this->condition->arguments[] = $cond_group; |
|
152
|
|
|
|
|
153
|
|
|
// Вернем себя для цепирования |
|
154
|
|
|
return $this; |
|
155
|
|
|
} |
|
156
|
|
|
|
|
157
|
|
|
/** |
|
158
|
|
|
* Set debug query mode |
|
159
|
|
|
* @param bool $value Debug status, true - active |
|
160
|
|
|
* |
|
161
|
|
|
* @return $this Chaining |
|
162
|
|
|
*/ |
|
163
|
|
|
public function debug($value = true) |
|
164
|
|
|
{ |
|
165
|
|
|
db()->debug($this->debug = $value); |
|
166
|
|
|
|
|
167
|
|
|
return $this; |
|
168
|
|
|
} |
|
169
|
|
|
|
|
170
|
|
|
public function isnull($attribute) |
|
171
|
|
|
{ |
|
172
|
|
|
return $this->cond($attribute, '', dbRelation::ISNULL); |
|
|
|
|
|
|
173
|
|
|
} |
|
174
|
|
|
public function notnull($attribute) |
|
175
|
|
|
{ |
|
176
|
|
|
return $this->cond($attribute, '', dbRelation::NOTNULL); |
|
|
|
|
|
|
177
|
|
|
} |
|
178
|
|
|
public function notempty($attribute) |
|
179
|
|
|
{ |
|
180
|
|
|
return $this->cond($attribute, '', dbRelation::NOT_EQUAL); |
|
|
|
|
|
|
181
|
|
|
} |
|
182
|
|
|
public function like($attribute, $value = '') |
|
183
|
|
|
{ |
|
184
|
|
|
return $this->cond($attribute, $value, dbRelation::LIKE); |
|
|
|
|
|
|
185
|
|
|
} |
|
186
|
|
|
|
|
187
|
|
|
|
|
188
|
|
|
|
|
189
|
|
|
/** @deprecated Use self::fields() */ |
|
190
|
|
|
public function fieldsNew($fieldName, & $return = null) |
|
|
|
|
|
|
191
|
|
|
{ |
|
192
|
|
|
return call_user_func_array(array($this, 'fields'), func_get_args()); |
|
193
|
|
|
} |
|
194
|
|
|
|
|
195
|
|
|
/** @see idbQuery::join() */ |
|
196
|
|
|
public function join($tableName, $className = null, $ignore = false) |
|
197
|
|
|
{ |
|
198
|
|
|
// Добавим имя класса в коллекцию присоединения |
|
199
|
|
|
$this->join[] = new RelationData($this->class_name, $tableName, $className, $ignore); |
|
200
|
|
|
|
|
201
|
|
|
// Вернем себя для цепирования |
|
202
|
|
|
return $this; |
|
203
|
|
|
} |
|
204
|
|
|
|
|
205
|
|
|
/** @see idbQuery::group_by() */ |
|
206
|
|
|
public function group_by($field) |
|
|
|
|
|
|
207
|
|
|
{ |
|
208
|
|
|
// Default grouping array |
|
209
|
|
|
$destination = &$this->group; |
|
210
|
|
|
|
|
211
|
|
|
// If this field belongs to query main class |
|
212
|
|
|
//if (property_exists( $this->class_name, $field )) $destination = & $this->own_group; |
|
213
|
|
|
|
|
214
|
|
|
$destination[] = $field; |
|
215
|
|
|
|
|
216
|
|
|
// Вернем себя для цепирования |
|
217
|
|
|
return $this; |
|
218
|
|
|
} |
|
219
|
|
|
|
|
220
|
|
|
/** @see idbQuery::limit() */ |
|
221
|
|
|
public function limit($st, $en = NULL, $own = false) |
|
|
|
|
|
|
222
|
|
|
{ |
|
223
|
|
|
// Select base table or whole query destination |
|
224
|
|
|
if ($own) { |
|
225
|
|
|
$this->own_limit = array($st, $en); |
|
226
|
|
|
} else { |
|
227
|
|
|
$this->limit = array($st, $en); |
|
228
|
|
|
} |
|
229
|
|
|
|
|
230
|
|
|
// Вернем себя для цепирования |
|
231
|
|
|
return $this; |
|
232
|
|
|
} |
|
233
|
|
|
|
|
234
|
|
|
/** @see idbQuery::order_by() */ |
|
235
|
|
|
public function order_by($field, $direction = 'ASC') |
|
|
|
|
|
|
236
|
|
|
{ |
|
237
|
|
|
$this->order[] = array($field, $direction); |
|
238
|
|
|
|
|
239
|
|
|
// Вернем себя для цепирования |
|
240
|
|
|
return $this; |
|
241
|
|
|
} |
|
242
|
|
|
|
|
243
|
|
|
/** @see idbQuery::add_field() */ |
|
244
|
|
|
public function add_field($field, $alias = null, $own = true) |
|
|
|
|
|
|
245
|
|
|
{ |
|
246
|
|
|
// Если передан псевдоним для поля, то подставим его |
|
247
|
|
|
if (isset($alias)) { |
|
248
|
|
|
$field = $field . ' as ' . $alias; |
|
249
|
|
|
} else { |
|
250
|
|
|
$alias = $field; |
|
251
|
|
|
} |
|
252
|
|
|
|
|
253
|
|
|
// Добавим виртуальное поле |
|
254
|
|
|
if ($own) { |
|
255
|
|
|
$this->own_virtual_fields[$alias] = $field; |
|
256
|
|
|
} else { |
|
257
|
|
|
$this->virtual_fields[$alias] = $field; |
|
258
|
|
|
} |
|
259
|
|
|
|
|
260
|
|
|
// Вернем себя для цепирования |
|
261
|
|
|
return $this; |
|
262
|
|
|
} |
|
263
|
|
|
|
|
264
|
|
|
/** @see idbQuery::innerCount() */ |
|
265
|
|
|
public function innerCount($field = '*') |
|
|
|
|
|
|
266
|
|
|
{ |
|
267
|
|
|
return db()->innerCount($this->class_name, $this); |
|
268
|
|
|
} |
|
269
|
|
|
|
|
270
|
|
|
/** @see idbQuery::parse() */ |
|
|
|
|
|
|
271
|
|
|
public function parse($queryText, array $args = null) |
|
272
|
|
|
{ |
|
273
|
|
|
// Преобразуем текст в нижний регистр |
|
274
|
|
|
//$query_text = mb_strtolower( $query_text, 'UTF-8' ); |
|
275
|
|
|
|
|
276
|
|
|
// Паттерн для определения метода динамического запроса |
|
277
|
|
|
$sortingPattern = ' |
|
278
|
|
|
/(?:^(?<method>find_by|find_all_by|all|first|last)_) |
|
279
|
|
|
|_order_by_ (?P<order>[a-zа-я0-9]+) _ (?P<order_dir>(?:asc|desc)) |
|
280
|
|
|
|_limit_ (?P<limit_start>\d+) (?:_(?P<limit_end>\d+))? |
|
281
|
|
|
|_group_by_(?P<group>.+) |
|
282
|
|
|
|_join_ (?<join>.+) |
|
283
|
|
|
/iux'; |
|
284
|
|
|
|
|
285
|
|
|
// Это внутренний счетчик для аргументов запроса для того чтобы не сбиться при их подставлении |
|
286
|
|
|
// в условие запроса к БД |
|
287
|
|
|
$argsCnt = 0; |
|
288
|
|
|
|
|
289
|
|
|
// Выполним первоначальный парсинг проверяющий правильность указанного метода |
|
290
|
|
|
// выборки данных и поиск возможных модификаторов запроса |
|
291
|
|
|
if (preg_match_all($sortingPattern, $queryText, $globalMatches)) { |
|
292
|
|
|
// Удалим все пустые группы полученные послке разпознования |
|
293
|
|
|
$globalMatches = array_filter_recursive($globalMatches); |
|
294
|
|
|
|
|
295
|
|
|
// Получим текст условий самого запроса, убрав из него все возможные модификаторы и параметры |
|
296
|
|
|
// и переберем только полученные группы условий запроса |
|
297
|
|
|
foreach (explode('_or_', str_ireplace($globalMatches[0], '', $queryText)) as $groupText) { |
|
298
|
|
|
// Добавим группу условий к запросу |
|
299
|
|
|
$this->or_('AND'); |
|
|
|
|
|
|
300
|
|
|
|
|
301
|
|
|
// Переберем поля которые формируют условия запроса - создание объекты-условия запроса |
|
302
|
|
|
foreach (explode('_and_', $groupText) as $conditionText) { |
|
303
|
|
|
$this->cond($conditionText, $args[$argsCnt++]); |
|
|
|
|
|
|
304
|
|
|
} |
|
305
|
|
|
} |
|
306
|
|
|
|
|
307
|
|
|
// Получим сортировку запроса |
|
308
|
|
|
if (isset($globalMatches['order'])) { |
|
309
|
|
|
$this->order = array($globalMatches['order'][0], $globalMatches['order_dir'][0]); |
|
310
|
|
|
} |
|
311
|
|
|
// Получим ограничения запроса |
|
312
|
|
|
if (isset($globalMatches['limit_start'])) { |
|
313
|
|
|
$this->limit = array($globalMatches['limit_start'][0], $globalMatches['limit_end'][0]); |
|
314
|
|
|
} |
|
315
|
|
|
// Получим групировку запроса |
|
316
|
|
View Code Duplication |
if (isset($globalMatches['group'])) { |
|
|
|
|
|
|
317
|
|
|
$this->group = explode('_and_', $globalMatches['group'][0]); |
|
318
|
|
|
} |
|
319
|
|
|
// Получим имена таблиц для "объединения" в запросе |
|
320
|
|
View Code Duplication |
if (isset($globalMatches['join'])) { |
|
|
|
|
|
|
321
|
|
|
foreach (explode('_and_', $globalMatches['join'][0]) as $join) { |
|
322
|
|
|
$this->join($join); |
|
323
|
|
|
} |
|
324
|
|
|
} |
|
325
|
|
|
} |
|
326
|
|
|
|
|
327
|
|
|
// Вернем полученный объект-запрос |
|
328
|
|
|
return $this; |
|
329
|
|
|
} |
|
330
|
|
|
|
|
331
|
|
|
/** |
|
332
|
|
|
* Function to reconfigure dbQuery to work with multiple Entities |
|
333
|
|
|
* |
|
334
|
|
|
* @param string $className Entity name |
|
335
|
|
|
* @deprecated @see \samsonframework\orm\QueryInterface::entity(), full class name with namespace |
|
336
|
|
|
* should be passed. |
|
337
|
|
|
* @return self|string Chaining or current class name if nothing is passed |
|
338
|
|
|
*/ |
|
339
|
|
|
public function className($className = null) |
|
340
|
|
|
{ |
|
341
|
|
|
// Old support for not full class names |
|
342
|
|
|
if (strpos($className, '\\') === false) { |
|
343
|
|
|
// Add generic namespace |
|
344
|
|
|
$className = '\samson\activerecord\\'.$className; |
|
345
|
|
|
} |
|
346
|
|
|
|
|
347
|
|
|
return func_num_args() > 0 ? $this->entity($className) : $this->class_name; |
|
348
|
|
|
} |
|
349
|
|
|
|
|
350
|
|
|
/** |
|
351
|
|
|
* Add condition by primary field |
|
352
|
|
|
* |
|
353
|
|
|
* @param string $value Primary field value |
|
354
|
|
|
* @return self Chaining |
|
355
|
|
|
* @deprecated Use direct query with where('PRIMARY_FIELD',...) |
|
356
|
|
|
*/ |
|
357
|
|
|
public function id($value) |
|
358
|
|
|
{ |
|
359
|
|
|
// PHP 5.2 get primary field |
|
360
|
|
|
$_primary = null; |
|
361
|
|
|
eval('$_primary = ' . $this->class_name . '::$_primary;'); |
|
362
|
|
|
|
|
363
|
|
|
// Set primary field value |
|
364
|
|
|
return $this->where($_primary, $value); |
|
365
|
|
|
} |
|
366
|
|
|
|
|
367
|
|
|
/** |
|
368
|
|
|
* Add condition to current query. |
|
369
|
|
|
* This method supports receives three possible types for $fieldName, |
|
370
|
|
|
* this is deprecated logic and this should be changed to use separate methods |
|
371
|
|
|
* for each argument type. |
|
372
|
|
|
* |
|
373
|
|
|
* @param string|ConditionInterface|ArgumentInterface $fieldName Entity field name |
|
374
|
|
|
* @param string $fieldValue Value |
|
375
|
|
|
* @param string $relation Relation between field name and its value |
|
376
|
|
|
* @deprecated @see self::where() |
|
377
|
|
|
* @return self Chaining |
|
378
|
|
|
*/ |
|
379
|
|
|
public function cond($fieldName, $fieldValue = null, $relation = '=') |
|
380
|
|
|
{ |
|
381
|
|
|
// If empty array is passed |
|
382
|
|
|
if (is_string($fieldName)) { |
|
383
|
|
|
return $this->where($fieldName, $fieldValue, $relation); |
|
384
|
|
|
} elseif (is_array($fieldValue) && !sizeof($fieldValue)) { |
|
385
|
|
|
$this->empty = true; |
|
386
|
|
|
return $this; |
|
387
|
|
|
} elseif (is_a($fieldName, '\samsonframework\orm\ConditionInterface')) { |
|
388
|
|
|
$this->whereCondition($fieldName); |
|
389
|
|
|
} elseif (is_a($fieldName, '\samsonframework\orm\ArgumentInterface')) { |
|
390
|
|
|
$this->getConditionGroup($fieldName->field)->addArgument($fieldName); |
|
|
|
|
|
|
391
|
|
|
} |
|
392
|
|
|
|
|
393
|
|
|
return $this; |
|
394
|
|
|
} |
|
395
|
|
|
|
|
396
|
|
|
/** |
|
397
|
|
|
* Query constructor. |
|
398
|
|
|
* @param string|null $entity Entity identifier |
|
399
|
|
|
* @throws EntityNotFound |
|
400
|
|
|
*/ |
|
401
|
|
|
public function __construct($entity = 'material') |
|
402
|
|
|
{ |
|
403
|
|
|
// Old support for not full class names |
|
404
|
|
|
if (strpos($entity, '\\') === false) { |
|
405
|
|
|
// Add generic namespace |
|
406
|
|
|
$entity = '\samson\activerecord\\'.$entity; |
|
407
|
|
|
} |
|
408
|
|
|
|
|
409
|
|
|
// Call parent constructor |
|
410
|
|
|
parent::__construct(db()); |
|
|
|
|
|
|
411
|
|
|
$this->entity($entity); |
|
412
|
|
|
} |
|
413
|
|
|
|
|
414
|
|
|
/** |
|
415
|
|
|
* Magic method for setting beautiful conditions. |
|
416
|
|
|
* |
|
417
|
|
|
* @deprecated Use ->where(..)-> |
|
418
|
|
|
* @param $methodName |
|
419
|
|
|
* @param array $arguments |
|
420
|
|
|
* @return $this|array|bool|dbQuery |
|
421
|
|
|
*/ |
|
422
|
|
|
public function __call($methodName, array $arguments) |
|
423
|
|
|
{ |
|
424
|
|
|
/** @var array $matches Prepared statement matches */ |
|
425
|
|
|
$matches = array(); |
|
426
|
|
|
// Если этот метод поддерживается - выполним запрос к БД |
|
427
|
|
|
if (preg_match('/^(find_by|find_all_by|all)/iu', $methodName, $matches)) { |
|
428
|
|
|
return db()->find($this->class_name, $this->parse($methodName, $arguments)); |
|
429
|
|
|
} elseif (property_exists($this->class_name, $methodName)) { // Проверим существует ли у класса заданное поле |
|
430
|
|
|
// Если передан аргумент - расцениваем его как аргумент запроса |
|
431
|
|
|
if (sizeof($arguments) > 1) { |
|
432
|
|
|
return $this->cond($methodName, $arguments[0], $arguments[1]); |
|
|
|
|
|
|
433
|
|
|
} elseif (isset($arguments[0])) { |
|
434
|
|
|
return $this->cond($methodName, $arguments[0]); |
|
|
|
|
|
|
435
|
|
|
} else { // Просто игнорируем условие |
|
436
|
|
|
return $this; |
|
437
|
|
|
} |
|
438
|
|
|
} else { // Сообщим об ошибке разпознования метода |
|
439
|
|
|
return e( |
|
440
|
|
|
'Не возможно определить метод(##) для создания запроса к БД', |
|
441
|
|
|
E_SAMSON_ACTIVERECORD_ERROR, |
|
442
|
|
|
$methodName |
|
443
|
|
|
); |
|
444
|
|
|
} |
|
445
|
|
|
} |
|
446
|
|
|
} |
|
447
|
|
|
|
Classes in PHP are usually named in CamelCase.
In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. The whole name starts with a capital letter as well.
Thus the name database provider becomes
DatabaseProvider.