-
Notifications
You must be signed in to change notification settings - Fork 197
Expand file tree
/
Copy pathSQLQueryEngine.php
More file actions
595 lines (532 loc) · 20.9 KB
/
SQLQueryEngine.php
File metadata and controls
595 lines (532 loc) · 20.9 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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
<?php declare(strict_types=1);
namespace LORIS\Data\Query;
use LORIS\StudyEntities\Candidate\CandID;
use LORIS\Data\DataInstance;
use LORIS\Data\Dictionary\DictionaryItem;
use LORIS\Data\Query\Criteria;
use LORIS\Data\Query\Criteria\Equal;
use LORIS\Data\Query\Criteria\NotEqual;
use LORIS\Data\Query\Criteria\LessThan;
use LORIS\Data\Query\Criteria\LessThanOrEqual;
use LORIS\Data\Query\Criteria\GreaterThanOrEqual;
use LORIS\Data\Query\Criteria\GreaterThan;
use LORIS\Data\Query\Criteria\In;
use LORIS\Data\Query\Criteria\NotNull;
use LORIS\Data\Query\Criteria\IsNull;
use LORIS\Data\Query\Criteria\StartsWith;
use LORIS\Data\Query\Criteria\Substring;
use LORIS\Data\Query\Criteria\EndsWith;
/**
* An SQLQueryEngine is a type of QueryEngine which queries
* against the LORIS SQL database. It implements most of the
* functionality of the QueryEngine interface, while leaving
* a few necessary methods abstract for the concretized QueryEngine
* to fill in the necessary details.
*
* The concrete implementation must provide the getDataDictionary
* and getVisitList functions from the QueryEngine interface, but
* default getCandidateMatches and getCandidateData implementations
* are provided by the SQLQueryEngine.
*
* The implementation must provide getFieldNameFromDict,
* which returns a string of the database fieldname (and calls
* $this->addTable as many times as it needs for the joins) and
* getCorrespondingKeyField to get the primary key for any Cardinality::MANY
* fields.
*/
abstract class SQLQueryEngine implements QueryEngine
{
/**
* Construct an SQLQueryEngine
*
* @param \LORIS\LorisInstance $loris The LORIS instance being queried
*/
public function __construct(protected \LORIS\LorisInstance $loris)
{
}
/**
* {@inheritDoc}
*
* @return \LORIS\Data\Dictionary\Category[]
*/
abstract public function getDataDictionary() : iterable;
/**
* {@inheritDoc}
*
* @param \LORIS\Data\Dictionary\Category $inst The item category
* @param \LORIS\Data\Dictionary\DictionaryItem $item The item itself
*
* @return string[]
*/
abstract public function getVisitList(
\LORIS\Data\Dictionary\Category $inst,
\LORIS\Data\Dictionary\DictionaryItem $item
) : iterable;
/**
* Return the field name that can be used to get the value for
* this field.
*
* The implementation should call $this->addTable() to add any
* tables necessary for the field name to be valid.
*
* @return string
*/
abstract protected function getFieldNameFromDict(
\LORIS\Data\Dictionary\DictionaryItem $item
) : string;
/**
* Return the field name that can be used to get the value for
* the primary key of any Cardinality::MANY fields.
*
* The implementation should call $this->addTable() to add any
* tables necessary for the field name to be valid.
*
* @return string
*/
abstract protected function getCorrespondingKeyField(\LORIS\Data\Dictionary\DictionaryItem $field);
abstract public function getCorrespondingKeyFieldType(\LORIS\Data\Dictionary\DictionaryItem $item) : string;
/**
* {@inheritDoc}
*
* @param \LORIS\Data\Query\QueryTerm $term The criteria term.
* @param ?string[] $visitlist The optional list of visits
* to match at.
*
* @return \Generator<CandID>
*/
public function getCandidateMatches(
\LORIS\Data\Query\QueryTerm $term,
?array $visitlist = null
) : iterable {
$this->resetEngineState();
$this->addTable('candidate c');
$this->addWhereClause("c.Active='Y'");
$prepbindings = [];
$this->buildQueryFromCriteria($term, $prepbindings, $visitlist);
$query = 'SELECT DISTINCT c.CandID FROM';
$query .= ' ' . $this->getTableJoins();
$query .= ' WHERE ';
$query .= $this->getWhereConditions();
$query .= ' ORDER BY c.CandID';
$DB = $this->loris->getDatabaseConnection();
$rows = $DB->pselectCol($query, $prepbindings);
foreach ($rows as $candID) {
yield new CandID(strval($candID));
}
}
/**
* {@inheritDoc}
*
* @param DictionaryItem[] $items Items to get data for
* @param iterable $candidates CandIDs to get data for
* @param ?string[] $visitlist Possible list of visits
*
* @return iterable<string, DataInstance>
*/
public function getCandidateData(
array $items,
iterable $candidates,
?array $visitlist
) : iterable {
if (count($candidates) == 0) {
return [];
}
$this->resetEngineState();
$this->addTable('candidate c');
// Always required for candidateCombine
$fields = ['c.CandID'];
$DB = $this->loris->getDatabaseConnection();
$this->createTemporaryCandIDTable($DB, "searchcandidates", $candidates);
$DB->setBuffering($this->useBufferedQuery);
$sessionVariables = false;
$keyFields = [];
foreach ($items as $dict) {
// Quote the question marks otherwise PDO will interpret
// these as positional placeholders
$dictName = str_replace('?', '??', $dict->getName());
$fields[] = $this->getFieldNameFromDict($dict)
. ' as '
. "`$dictName`";
if ($dict->getScope() == 'session') {
$sessionVariables = true;
}
if ($dict->getCardinality()->__toString() === "many") {
$keyFields[] = $this->getCorrespondingKeyField($dict) . " as `$dictName:key`";
}
}
if ($sessionVariables) {
if (!in_array('s.Visit_label as VisitLabel', $fields)) {
$fields[] = 's.Visit_label as VisitLabel';
}
if (!in_array('s.SessionID', $fields)) {
$fields[] = 's.ID as SessionID';
}
}
if (!empty($keyFields)) {
$fields = array_merge($fields, $keyFields);
}
$query = 'SELECT ' . join(', ', $fields) . ' FROM';
$query .= ' ' . $this->getTableJoins();
$prepbindings = [];
$query .= ' WHERE c.CandID IN (SELECT CandID from searchcandidates)';
if ($visitlist != null) {
$inset = [];
$i = count($prepbindings);
foreach ($visitlist as $vl) {
$prepname = ':val' . $i++;
$inset[] = $prepname;
$prepbindings[$prepname] = $vl;
}
$query .= 'AND s.Visit_label IN (' . join(",", $inset) . ')';
}
$whereCond = $this->getWhereConditions();
if (!empty($whereCond)) {
$query .= ' AND ' . $this->getWhereConditions();
}
$query .= ' ORDER BY c.CandID';
$rows = $DB->prepare($query);
$result = $rows->execute($prepbindings);
if ($result === false) {
throw new \Exception("Invalid query $query");
}
// Yield the generator ourself, so that when it's done we can restore the
// buffered query attribute
foreach ($this->candidateCombine($items, $rows) as $candid => $val) {
yield $candid => $val;
};
// Restore the default now that the generator has finished yielding.
$DB->setBuffering($this->useBufferedQuery, true);
}
/**
* Converts a Criteria object to the equivalent SQL operator.
*
* @return string
*/
public static function sqlOperator(Criteria $criteria) : string
{
if ($criteria instanceof LessThan) {
return '<';
}
if ($criteria instanceof LessThanOrEqual) {
return '<=';
}
if ($criteria instanceof Equal) {
return '=';
}
if ($criteria instanceof NotEqual) {
return '<>';
}
if ($criteria instanceof GreaterThanOrEqual) {
return '>=';
}
if ($criteria instanceof GreaterThan) {
return '>';
}
if ($criteria instanceof In) {
return 'IN';
}
if ($criteria instanceof IsNull) {
return "IS NULL";
}
if ($criteria instanceof NotNull) {
return "IS NOT NULL";
}
if ($criteria instanceof StartsWith) {
return "LIKE";
}
if ($criteria instanceof EndsWith) {
return "LIKE";
}
if ($criteria instanceof Substring) {
return "LIKE";
}
throw new \Exception("Unhandled operator: " . get_class($criteria));
}
/**
* Converts a Criteria object to the equivalent SQL value, putting
* any bindings required into $prepbindings
*
* @return string
*/
public static function sqlValue(DictionaryItem $dict, Criteria $criteria, array &$prepbindings) : string
{
static $i = 1;
if ($criteria instanceof In) {
$val = '(';
$critvalues = $criteria->getValue();
foreach ($critvalues as $critnum => $critval) {
$prepname = ':val' . $i++;
$prepbindings[$prepname] = $critval;
$val .= $prepname;
if ($critnum != count($critvalues)-1) {
$val .= ', ';
}
}
$val .= ')';
return $val;
}
if ($criteria instanceof IsNull) {
return "";
}
if ($criteria instanceof NotNull) {
return "";
}
$prepname = ':val' . $i++;
if ($dict->getDataType() instanceof \LORIS\Data\Types\BooleanType) {
$val = $criteria->getValue();
$prepbindings[$prepname] = !empty($val) && $val !== "false";
} else {
$prepbindings[$prepname] = $criteria->getValue();
}
if ($criteria instanceof StartsWith) {
return "CONCAT($prepname, '%')";
}
if ($criteria instanceof EndsWith) {
return "CONCAT('%', $prepname)";
}
if ($criteria instanceof Substring) {
return "CONCAT('%', $prepname, '%')";
}
return $prepname;
}
private $tables;
/**
* Adds a to be joined to the internal state of this QueryEngine
* $tablename should be the full "LEFT JOIN tablename x" string
* required to be added to the query. If an identical join is
* already present, it will not be duplicated.
*
* @param string $tablename The join string
*
* @return void
*/
protected function addTable(string $tablename)
{
if (isset($this->tables[$tablename])) {
// Already added
return;
}
$this->tables[$tablename] = $tablename;
}
/**
* Get the full SQL join statement for this query.
*/
protected function getTableJoins() : string
{
return join(' ', $this->tables);
}
private $where;
/**
* Adds a where clause to the query based on converting Criteria
* to SQL.
*/
protected function addWhereCriteria(DictionaryItem $dict, Criteria $criteria, array &$prepbindings)
{
$fieldname = $this->getFieldNameFromDict($dict);
$this->where[] = $fieldname . ' '
. $this->sqlOperator($criteria) . ' '
. $this->sqlValue($dict, $criteria, $prepbindings);
}
/**
* Add a static where clause directly to the query.
*/
protected function addWhereClause(string $s)
{
$this->where[] = $s;
}
/**
* Get a list of WHERE conditions.
*/
protected function getWhereConditions() : string
{
return join(' AND ', $this->where);
}
/**
* Reset the internal engine state (tables and where clause)
*/
protected function resetEngineState()
{
$this->where = [];
$this->tables = [];
}
/**
* Combines the rows from $rows into a CandID =>DataInstance for
* getCandidateData.
*
* The DataInstance returned is an array where the i'th index is
* the Candidate's value of item i from $items.
*
* @param DictionaryItem[] $items Items to get data for
* @param iterable $candidates CandIDs to get data for
*
* @return <string,DataInstance>
*/
protected function candidateCombine(iterable $dict, iterable &$rows)
{
$lastcandid = null;
$candval = [];
foreach ($rows as $row) {
if ($lastcandid !== null && $row['CandID'] !== $lastcandid) {
yield $lastcandid => $candval;
$candval = [];
}
$lastcandid = $row['CandID'];
foreach ($dict as $field) {
$fname = $field->getName();
if ($field->getScope() == 'session') {
// Session variables exist many times per CandID, so put
// the values in an array.
if (!isset($candval[$fname])) {
$candval[$fname] = [];
}
// Each session must have a VisitLabel and SessionID key.
if ($row['VisitLabel'] === null || $row['SessionID'] === null) {
// If they don't exist and there's a value, there was a bug
// somewhere. If they don't exist and the value is also null,
// the query might have just done a LEFT JOIN on session.
assert($row[$fname] === null);
} else {
$SID = $row['SessionID'];
if (isset($candval[$fname][$SID])) {
// There is already a value stored for this session ID.
// Assert that the VisitLabel and SessionID are the same.
assert($candval[$fname][$SID]['VisitLabel'] == $row['VisitLabel']);
assert($candval[$fname][$SID]['SessionID'] == $row['SessionID']);
if ($field->getCardinality()->__toString() !== "many") {
// It's not cardinality many, so ensure it's the same value. The
// Query may have returned multiple rows with the same value as
// the result of a JOIN, so it's not a problem to see it many
// times.
assert($candval[$fname][$SID]['value'] == $row[$fname]);
} else {
// It is cardinality many, so append the value.
// A null val in a cardinality many column means the row came from a left join
// and shouldn't be included (as opposed to a cardinality:optional where it
// means that the value was the value null)
$key = $row[$field->getName() . ':key'];
$val = $this->displayValue($field, $row[$fname]);
if ($key !== null && $val !== null) {
if (isset($candval[$fname][$SID]['values']['key'])) {
assert($candval[$fname][$SID]['values']['key'] == $val);
} else {
$candval[$fname][$SID]['values'][$key] = $val;
}
}
}
} else {
// This is the first time we've session this sessionID
if ($field->getCardinality()->__toString() !== "many") {
// It's not many, so just store the value directly.
$candval[$fname][$SID] = [
'VisitLabel' => $row['VisitLabel'],
'SessionID' => $row['SessionID'],
'value' => $this->displayValue($field, $row[$fname]),
];
} else {
// It is many, so use an array
$key = $row[$field->getName() . ':key'];
$val = $this->displayValue($field, $row[$fname]);
// A null val in a cardinality many column means the row came from a left join
// and shouldn't be included (as opposed to a cardinality:optional where it
// means that the value was the value null)
if ($key !== null && $val !== null) {
$candval[$fname]['keytype'] = $this->getCorrespondingKeyFieldtype($field);
// This is just to get around PHPCS complaining about line
// length.
$sarray = [
'VisitLabel' => $row['VisitLabel'],
'SessionID' => $row['SessionID'],
'values' => [$key => $val],
];
$candval[$fname][$SID] = $sarray;
}
}
}
}
} elseif ($field->getCardinality()->__toString() === 'many') {
// FIXME: Implement this.
throw new \Exception("Cardinality many for candidate variables not handled");
} else {
// It was a candidate variable that isn't cardinality::many.
// Just store the value directly.
$candval[$fname] = $row[$fname];
}
}
}
if (!empty($candval)) {
yield $lastcandid => $candval;
}
}
private function displayValue(DictionaryItem $field, mixed $value) : mixed
{
// MySQL queries turn boolean columns into 0/1, so if it's a boolean dictionary
// item we need to convert it back to true/false
if ($field->getDataType() instanceof \LORIS\Data\Types\BooleanType) {
return !empty($value);
}
return $value;
}
/**
* Create a temporary table containing the candIDs from $candidates using the
* LORIS database connection $DB.
*/
protected function createTemporaryCandIDTable(\Database $DB, string $tablename, array &$candidates)
{
// Put candidates into a temporary table so that it can be used in a join
// clause. Directly using "c.CandID IN (candid1, candid2, candid3, etc)" is
// too slow.
$DB->run("DROP TEMPORARY TABLE IF EXISTS $tablename");
$DB->run(
"CREATE TEMPORARY TABLE $tablename (
CandID int(10) unsigned
);"
);
$insertstmt = "INSERT INTO $tablename VALUES"
. " (" . join('),(', $candidates) . ')';
$q = $DB->prepare($insertstmt);
$q->execute([]);
}
protected $useBufferedQuery = true;
/**
* Enable or disable MySQL query buffering by PHP. Disabling query
* buffering is more memory efficient, but bypasses LORIS and does
* not share the internal state of the LORIS database such as temporary tables.
*/
public function useQueryBuffering(bool $buffered)
{
$this->useBufferedQuery = $buffered;
}
/**
* Adds the necessary fields and tables to run the query $term
*
* @param \LORIS\Data\Query\QueryTerm $term The term being added to the
* query.
* @param array $prepbindings Any prepared statement
* bindings required.
* @param ?array $visitlist The list of visits.
*
* @return void
*/
protected function buildQueryFromCriteria(
\LORIS\Data\Query\QueryTerm $term,
array &$prepbindings,
?array $visitlist = null
) {
$dict = $term->dictionary;
$this->addWhereCriteria(
$dict,
$term->criteria,
$prepbindings
);
if ($visitlist != null) {
$inset = [];
$i = count($prepbindings);
foreach ($visitlist as $vl) {
$prepname = ':val' . ++$i;
$inset[] = $prepname;
$prepbindings[$prepname] = $vl;
}
$this->addWhereClause('s.Visit_label IN (' . join(",", $inset) . ')');
}
}
}