-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuerySet.php
More file actions
372 lines (324 loc) · 11.3 KB
/
QuerySet.php
File metadata and controls
372 lines (324 loc) · 11.3 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
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
<?php
/**
* PerfORM - Object-relational mapping based on David Grudl's dibi
*
* @copyright Copyright (c) 2010 Eduard 'edke' Kracmar
* @license no license set at this point
* @link http://perform.local :-)
* @category QuerySet
* @package PerfORM
*/
/**
* QuerySets
*
* Querying class responsible for getting data from database with help of models definition
*
* @final
* @copyright Copyright (c) 2010 Eduard 'edke' Kracmar
* @package PerfORM
*/
final class QuerySet {
/**
* Instance of datasource created
* @var DibiDataSource
*/
protected $dataSource;
/**
* Array of fields created for datasource
* @var array
*/
protected $fields = array();
/**
* Array of joins created for datasource
* @var array
*/
protected $joins = array();
/**
* Instance of model
* @var PerfORM
*/
protected $model;
protected $resultClass;
/**
* Constructor
* @param PerfORM $model
*/
public function __construct($model) {
$this->model = $model;
}
/**
* Adds fields recursively from model's definition
* @param PerfORM $model
*/
protected function addFields($model) {
if ($model->isExtended()) {
$this->addFields($model->getExtend());
}
/* $extended= $model->getExtend();
foreach( $extended->getFields() as $field )
{
if ( !$field->isPrimaryKey())
{
$this->fields[]= sprintf("\t%s.%s as %s__%s", $extended->getAlias(), $field->getRealName(), $field->getModel()->getAlias(), $field->getRealName() );
if ( $field->getIdent() == PerfORM::ForeignKeyField &&
!$field->isEnabledLazyLoading()
)
{
$this->addFields($field->getReference());
}
}
}
} */
foreach ($model->getFields() as $field) {
$this->fields[] = sprintf("\t\"%s\".\"%s\" as \"%s__%s\"", $model->getAlias(), $field->getRealName(), $model->getAlias(), $field->getRealName());
if ($field->getIdent() == PerfORM::ForeignKeyField &&
!$field->isEnabledLazyLoading()
) {
$this->addFields($field->getReference());
}
}
}
/**
* Adds joins recursively from model's definition if relation to other models exists
* @param PerfORM $model
*/
protected function addJoins($model, $inner = true) {
if ($model->isExtended()) {
$this->joins[] = sprintf("\tINNER JOIN \"%s\" AS \"%s\" ON \"%s\".\"%s\" = \"%s\".\"%s\"",
$model->getExtend()->getTableName(),
$model->getExtend()->getAlias(),
$model->getExtend()->getAlias(),
$model->getExtend()->getPrimaryKey(),
$model->getAlias(),
$model->getField($model->getPrimaryKey())->getRealName()
);
}
foreach ($model->getFields() as $field) {
if ($field->getIdent() == PerfORM::ForeignKeyField &&
!$field->isEnabledLazyLoading()
) {
$join_type = !$field->isNullable() && $inner ? 'INNER' : 'LEFT';
$this->joins[] = sprintf("\t%s JOIN \"%s\" AS \"%s\" ON \"%s\".\"%s\" = \"%s\".\"%s\"",
$join_type,
$field->getReference()->getTableName(),
$field->getReference()->getAlias(),
$field->getReference()->getAlias(),
$field->getReference()->getPrimaryKey(),
$model->getAlias(),
$field->getRealName()
);
$this->addJoins($field->getReference(), $join_type == 'INNER');
}
}
}
/**
* Method to get all results from model
* @return array|false
*/
public function all() {
return $this->prepareResult();
}
/**
* Clears all model data
*/
public function clear() {
PerfORMController::getConnection()->query("DELETE FROM %n", $this->model->getTableName());
PerfORMController::addSql(dibi::$sql);
}
/**
* Deletes current datasource, including inheritated models
*/
public function delete() {
$pk = $this->model->getPrimaryKey();
$result = $this->select($pk, 'id')
->getDataSource();
$tablenames = $this->model->getAllTableNames();
foreach ($result as $row) {
foreach ($tablenames as $tablename) {
PerfORMController::getConnection()->query("DELETE FROM %n", $tablename, 'where %n = %i', $pk, $row->{$pk});
PerfORMController::addSql(dibi::$sql);
}
}
}
/**
* Limits number of rows.
* @param int limit
* @param int offset
* @return DibiDataSource provides a fluent interface
*/
public function applyLimit($limit, $offset = null) {
$this->getDataSource()->applyLimit($limit, $offset);
return $this;
}
/**
* Selects columns to order by.
* @param string|array column name or array of column names
* @param string sorting direction
* @return DibiDataSource provides a fluent interface
*
*/
public function orderBy($sourceField, $sorting = 'ASC') {
$field = $this->fieldLookup($sourceField);
$row = $field->getModel()->getAlias() . '__' . $field->getRealName();
$this->getDataSource()->orderBy($row, $sorting);
return $this;
}
/**
* Selects columns to query.
* @param string|array column name or array of column names
* @param string column alias
* @return DibiDataSource provides a fluent interface
*/
public function select($sourceField, $as = NULL) {
$field = $this->fieldLookup($sourceField);
$row = $field->getModel()->getAlias() . '__' . $field->getRealName();
$this->getDataSource()->select($row, $as);
return $this;
}
public function setResultClass($className) {
$this->resultClass = $className;
return $this;
}
/**
* Returns data source wrapped in DibiFluent
* @return DibiFluent
*/
public function toFluent() {
return $this->getDataSource()->toFluent();
}
/**
* Finds field object from relation notation
* @param string $sourceField
* @return Field
*/
protected function fieldLookup($sourceField) {
if (preg_match("#^(id|pk)$#i", $sourceField, $_match)) {
if ($this->model->getPrimaryKey() or $this->model->hasField('id')) {
return $_match[1] == 'pk' ? $this->model->getField($this->getModel()->getPrimaryKey()) : $this->model->getField($_match[1]);
}
else {
throw new Exception('Model does not have primary key nor id field');
}
}
elseif (preg_match("#^[a-z0-9]+(__([a-z0-9_]+))+$#i", $sourceField, $_match)) {
return $this->getModel()->pathLookup($sourceField);
}
elseif (!preg_match("#__#", $sourceField) && $this->getModel()->hasField($sourceField)) {
return $this->getModel()->getField($sourceField, true);
}
else {
throw new Exception("Unable to translate field '$sourceField'.");
}
}
public function where() {
$args = func_get_args();
$cond = PerfORMController::getConnection()->sql($args);
$sql_operators =
'<|>|<=|>=|=|<>|!=|' .
'\|\||' .
'~|~~|~\*|!~|!~\*';
$search = array();
$replace = array();
$fields = array();
if (preg_match_all('#[\"]?([a-z0-9_]+)[\"]?\s*(' . $sql_operators . ')#i', $cond, $matches)) {
foreach ($matches[1] as $key => $originalFieldName) {
$search[] = $matches[0][$key];
$field = $this->fieldLookup($originalFieldName);
$replace[] = '%n ' . $matches[2][$key];
$fields[] = $field->getModel()->getAlias() . '__' . $field->getRealName();
}
}
else {
throw new Exception('Unable to match operator.');
}
#Debug::barDump($search,'search');
#Debug::barDump($replace,'replace');
#Debug::barDump($fields, 'fields');
$finalCond = str_replace($search, $replace, $cond);
#Debug::barDump($finalCond, 'final condition');
#Debug::barDump($fields);
$args = array_merge(array($finalCond), $fields);
$this->getDataSource()->where($args);
return $this;
}
/**
* Get method to retreive single result and fill model
* @param mixed
* @return DibiResult
*/
public function load() {
if ($args = func_get_args())
$this->where($args);
$result = $this->getDataSource()->fetch();
if (Environment::getConfig('perform')->profiler)
PerfORMController::addSql(dibi::$sql);
$this->getModel()->fill($result);
return $result ? $this->getModel() : false;
}
public function get() {
if ($args = func_get_args())
$this->where($args);
return is_null($this->resultClass) ?
new QuerySetResult($this->getDataSource()->getResult(), $this->getModelName()) :
new QuerySetResultRedux($this->getDataSource()->getResult(), $this->getModelName(), $this->resultClass);
}
/**
* Returns array of simplified models of current result
* @return array
*/
public function getSimplified() {
$result = $this->get();
$simplifiedModels = array();
foreach ($result as $model) {
$simplifiedModels[] = $model->simplify();
}
return $simplifiedModels;
}
protected function getModelName() {
return get_class($this->model);
}
/**
* Getter for QuerySet's model
* @return PerfORM
*/
protected function getModel() {
return $this->model;
}
/**
* Getter for datasource
* @return DibiDataSource
*/
public function getDataSource() {
if (!$this->dataSource) {
# build query
$query = array();
$query[] = "\nSELECT";
$this->addFields($this->model);
$query[] = implode(",\n", $this->fields);
$query[] = sprintf("FROM \"%s\"", $this->model->getTableName());
$this->addJoins($this->model);
$query[] = implode("\n", $this->joins);
$this->dataSource = new DibiDataSource(implode("\n", $query), PerfORMController::getConnection());
}
return $this->dataSource;
}
/**
* Fetch current DataSource, fill array of models with values
* @return array|false
*/
protected function prepareResult() {
$result = array();
$modelName = get_class($this->model);
foreach ($this->getDataSource() as $values) {
$model = new $modelName;
$model->fill($values);
$result[] = $model;
}
if (sizeof($result) > 0) {
return $result;
}
else {
return false;
}
}
}