SelectTest.php 21.5 KB
Newer Older
1 2
<?php

3
namespace Drupal\KernelTests\Core\Database;
4

5
use Drupal\Core\Database\InvalidQueryException;
6
use Drupal\Core\Database\Database;
7
use Drupal\Core\Database\DatabaseExceptionWrapper;
8
use Drupal\Core\Database\Query\SelectExtender;
9 10

/**
11 12 13
 * Tests the Select query builder.
 *
 * @group Database
14 15 16 17
 */
class SelectTest extends DatabaseTestBase {

  /**
18
   * Tests rudimentary SELECT statements.
19
   */
20
  public function testSimpleSelect() {
21
    $query = $this->connection->select('test');
22 23 24
    $query->addField('test', 'name');
    $query->addField('test', 'age', 'age');
    $num_records = $query->countQuery()->execute()->fetchField();
25

26
    $this->assertEqual(4, $num_records, 'Returned the correct number of rows.');
27 28 29
  }

  /**
30
   * Tests rudimentary SELECT statement with a COMMENT.
31
   */
32
  public function testSimpleComment() {
33
    $query = $this->connection->select('test')->comment('Testing query comments');
34 35
    $query->addField('test', 'name');
    $query->addField('test', 'age', 'age');
36 37
    $result = $query->execute();

38
    $records = $result->fetchAll();
39

40
    $query = (string) $query;
41
    $expected = "/* Testing query comments */";
42

43
    $this->assertCount(4, $records, 'Returned the correct number of rows.');
44
    $this->assertStringContainsString($expected, $query, 'The flattened query contains the comment string.');
45 46 47
  }

  /**
48
   * Tests query COMMENT system against vulnerabilities.
49
   */
50
  public function testVulnerableComment() {
51
    $query = $this->connection->select('test')->comment('Testing query comments */ SELECT nid FROM {node}; --');
52 53
    $query->addField('test', 'name');
    $query->addField('test', 'age', 'age');
54 55
    $result = $query->execute();

56
    $records = $result->fetchAll();
57

58
    $query = (string) $query;
59
    $expected = "/* Testing query comments  * / SELECT nid FROM {node}. -- */";
60

61 62
    // Check the returned number of rows.
    $this->assertCount(4, $records);
63
    // Check that the flattened query contains the sanitized comment string.
64
    $this->assertStringContainsString($expected, $query);
65 66 67 68

    $connection = Database::getConnection();
    foreach ($this->makeCommentsProvider() as $test_set) {
      list($expected, $comments) = $test_set;
69
      $this->assertEquals($expected, $connection->makeComment($comments));
70 71 72 73 74 75
    }
  }

  /**
   * Provides expected and input values for testVulnerableComment().
   */
76
  public function makeCommentsProvider() {
77 78 79 80 81 82 83
    return [
      [
        '/*  */ ',
        [''],
      ],
      // Try and close the comment early.
      [
84
        '/* Exploit  * / DROP TABLE node. -- */ ',
85 86 87 88
        ['Exploit */ DROP TABLE node; --'],
      ],
      // Variations on comment closing.
      [
89
        '/* Exploit  * / * / DROP TABLE node. -- */ ',
90 91 92
        ['Exploit */*/ DROP TABLE node; --'],
      ],
      [
93
        '/* Exploit  *  * // DROP TABLE node. -- */ ',
94 95 96 97
        ['Exploit **// DROP TABLE node; --'],
      ],
      // Try closing the comment in the second string which is appended.
      [
98
        '/* Exploit  * / DROP TABLE node. --. Another try  * / DROP TABLE node. -- */ ',
99 100 101
        ['Exploit */ DROP TABLE node; --', 'Another try */ DROP TABLE node; --'],
      ],
    ];
102 103 104
  }

  /**
105
   * Tests basic conditionals on SELECT statements.
106
   */
107
  public function testSimpleSelectConditional() {
108
    $query = $this->connection->select('test');
109 110 111 112 113 114
    $name_field = $query->addField('test', 'name');
    $age_field = $query->addField('test', 'age', 'age');
    $query->condition('age', 27);
    $result = $query->execute();

    // Check that the aliases are being created the way we want.
115 116
    $this->assertEqual('name', $name_field, 'Name field alias is correct.');
    $this->assertEqual('age', $age_field, 'Age field alias is correct.');
117 118 119

    // Ensure that we got the right record.
    $record = $result->fetch();
120 121
    $this->assertEqual('George', $record->{$name_field}, 'Fetched name is correct.');
    $this->assertEqual(27, $record->{$age_field}, 'Fetched age is correct.');
122 123 124
  }

  /**
125
   * Tests SELECT statements with expressions.
126
   */
127
  public function testSimpleSelectExpression() {
128
    $query = $this->connection->select('test');
129
    $name_field = $query->addField('test', 'name');
130
    $age_field = $query->addExpression("[age]*2", 'double_age');
131 132 133 134
    $query->condition('age', 27);
    $result = $query->execute();

    // Check that the aliases are being created the way we want.
135 136
    $this->assertEqual('name', $name_field, 'Name field alias is correct.');
    $this->assertEqual('double_age', $age_field, 'Age field alias is correct.');
137 138 139

    // Ensure that we got the right record.
    $record = $result->fetch();
140 141
    $this->assertEqual('George', $record->{$name_field}, 'Fetched name is correct.');
    $this->assertEqual(27 * 2, $record->{$age_field}, 'Fetched age expression is correct.');
142 143 144
  }

  /**
145
   * Tests SELECT statements with multiple expressions.
146
   */
147
  public function testSimpleSelectExpressionMultiple() {
148
    $query = $this->connection->select('test');
149
    $name_field = $query->addField('test', 'name');
150 151
    $age_double_field = $query->addExpression("[age]*2");
    $age_triple_field = $query->addExpression("[age]*3");
152 153 154 155
    $query->condition('age', 27);
    $result = $query->execute();

    // Check that the aliases are being created the way we want.
156 157
    $this->assertEqual('expression', $age_double_field, 'Double age field alias is correct.');
    $this->assertEqual('expression_2', $age_triple_field, 'Triple age field alias is correct.');
158 159 160

    // Ensure that we got the right record.
    $record = $result->fetch();
161 162 163
    $this->assertEqual('George', $record->{$name_field}, 'Fetched name is correct.');
    $this->assertEqual(27 * 2, $record->{$age_double_field}, 'Fetched double age expression is correct.');
    $this->assertEqual(27 * 3, $record->{$age_triple_field}, 'Fetched triple age expression is correct.');
164 165 166
  }

  /**
167
   * Tests adding multiple fields to a SELECT statement at the same time.
168
   */
169
  public function testSimpleSelectMultipleFields() {
170
    $record = $this->connection->select('test')
171
      ->fields('test', ['id', 'name', 'age', 'job'])
172 173 174 175
      ->condition('age', 27)
      ->execute()->fetchObject();

    // Check that all fields we asked for are present.
176 177 178 179
    $this->assertNotNull($record->id, 'ID field is present.');
    $this->assertNotNull($record->name, 'Name field is present.');
    $this->assertNotNull($record->age, 'Age field is present.');
    $this->assertNotNull($record->job, 'Job field is present.');
180 181 182

    // Ensure that we got the right record.
    // Check that all fields we asked for are present.
183 184 185 186
    $this->assertEqual(2, $record->id, 'ID field has the correct value.');
    $this->assertEqual('George', $record->name, 'Name field has the correct value.');
    $this->assertEqual(27, $record->age, 'Age field has the correct value.');
    $this->assertEqual('Singer', $record->job, 'Job field has the correct value.');
187 188 189
  }

  /**
190
   * Tests adding all fields from a given table to a SELECT statement.
191
   */
192
  public function testSimpleSelectAllFields() {
193
    $record = $this->connection->select('test')
194 195 196 197 198
      ->fields('test')
      ->condition('age', 27)
      ->execute()->fetchObject();

    // Check that all fields we asked for are present.
199 200 201 202
    $this->assertNotNull($record->id, 'ID field is present.');
    $this->assertNotNull($record->name, 'Name field is present.');
    $this->assertNotNull($record->age, 'Age field is present.');
    $this->assertNotNull($record->job, 'Job field is present.');
203 204 205

    // Ensure that we got the right record.
    // Check that all fields we asked for are present.
206 207 208 209
    $this->assertEqual(2, $record->id, 'ID field has the correct value.');
    $this->assertEqual('George', $record->name, 'Name field has the correct value.');
    $this->assertEqual(27, $record->age, 'Age field has the correct value.');
    $this->assertEqual('Singer', $record->job, 'Job field has the correct value.');
210 211 212
  }

  /**
213
   * Tests that a comparison with NULL is always FALSE.
214
   */
215
  public function testNullCondition() {
216 217
    $this->ensureSampleDataNull();

218
    $names = $this->connection->select('test_null', 'tn')
219
      ->fields('tn', ['name'])
220 221 222
      ->condition('age', NULL)
      ->execute()->fetchCol();

223
    $this->assertCount(0, $names, 'No records found when comparing to NULL.');
224 225 226
  }

  /**
227
   * Tests that we can find a record with a NULL value.
228
   */
229
  public function testIsNullCondition() {
230 231
    $this->ensureSampleDataNull();

232
    $names = $this->connection->select('test_null', 'tn')
233
      ->fields('tn', ['name'])
234 235 236
      ->isNull('age')
      ->execute()->fetchCol();

237
    $this->assertCount(1, $names, 'Correct number of records found with NULL age.');
238
    $this->assertEqual('Fozzie', $names[0], 'Correct record returned for NULL age.');
239 240 241
  }

  /**
242
   * Tests that we can find a record without a NULL value.
243
   */
244
  public function testIsNotNullCondition() {
245 246
    $this->ensureSampleDataNull();

247
    $names = $this->connection->select('test_null', 'tn')
248
      ->fields('tn', ['name'])
249 250 251 252
      ->isNotNull('tn.age')
      ->orderBy('name')
      ->execute()->fetchCol();

253
    $this->assertCount(2, $names, 'Correct number of records found withNOT NULL age.');
254 255
    $this->assertEqual('Gonzo', $names[0], 'Correct record returned for NOT NULL age.');
    $this->assertEqual('Kermit', $names[1], 'Correct record returned for NOT NULL age.');
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
  /**
   * Tests that we can force a query to return an empty result.
   */
  public function testAlwaysFalseCondition() {
    $names = $this->connection->select('test', 'test')
      ->fields('test', ['name'])
      ->condition('age', 27)
      ->execute()->fetchCol();

    $this->assertCount(1, $names);
    $this->assertSame($names[0], 'George');

    $names = $this->connection->select('test', 'test')
      ->fields('test', ['name'])
      ->condition('age', 27)
      ->alwaysFalse()
      ->execute()->fetchCol();

    $this->assertCount(0, $names);
  }

  /**
   * Tests that we can force an extended query to return an empty result.
   */
  public function testExtenderAlwaysFalseCondition() {
    $names = $this->connection->select('test', 'test')
284
      ->extend(SelectExtender::class)
285 286 287 288 289 290 291 292
      ->fields('test', ['name'])
      ->condition('age', 27)
      ->execute()->fetchCol();

    $this->assertCount(1, $names);
    $this->assertSame($names[0], 'George');

    $names = $this->connection->select('test', 'test')
293
      ->extend(SelectExtender::class)
294 295 296 297 298 299 300 301
      ->fields('test', ['name'])
      ->condition('age', 27)
      ->alwaysFalse()
      ->execute()->fetchCol();

    $this->assertCount(0, $names);
  }

302
  /**
303 304
   * Tests that we can UNION multiple Select queries together.
   *
305
   * This is semantically equal to UNION DISTINCT, so we don't explicitly test
306
   * that.
307
   */
308
  public function testUnion() {
309
    $query_1 = $this->connection->select('test', 't')
310 311
      ->fields('t', ['name'])
      ->condition('age', [27, 28], 'IN');
312

313
    $query_2 = $this->connection->select('test', 't')
314
      ->fields('t', ['name'])
315 316 317 318 319 320 321
      ->condition('age', 28);

    $query_1->union($query_2);

    $names = $query_1->execute()->fetchCol();

    // Ensure we only get 2 records.
322
    $this->assertCount(2, $names, 'UNION correctly discarded duplicates.');
323

324
    $this->assertEqualsCanonicalizing(['George', 'Ringo'], $names);
325 326 327
  }

  /**
328
   * Tests that we can UNION ALL multiple SELECT queries together.
329
   */
330
  public function testUnionAll() {
331
    $query_1 = $this->connection->select('test', 't')
332 333
      ->fields('t', ['name'])
      ->condition('age', [27, 28], 'IN');
334

335
    $query_2 = $this->connection->select('test', 't')
336
      ->fields('t', ['name'])
337 338 339 340 341 342 343
      ->condition('age', 28);

    $query_1->union($query_2, 'ALL');

    $names = $query_1->execute()->fetchCol();

    // Ensure we get all 3 records.
344
    $this->assertCount(3, $names, 'UNION ALL correctly preserved duplicates.');
345

346 347 348
    $this->assertEqual('George', $names[0], 'First query returned correct first name.');
    $this->assertEqual('Ringo', $names[1], 'Second query returned correct second name.');
    $this->assertEqual('Ringo', $names[2], 'Third query returned correct name.');
349 350
  }

351 352 353
  /**
   * Tests that we can get a count query for a UNION Select query.
   */
354
  public function testUnionCount() {
355
    $query_1 = $this->connection->select('test', 't')
356 357
      ->fields('t', ['name', 'age'])
      ->condition('age', [27, 28], 'IN');
358

359
    $query_2 = $this->connection->select('test', 't')
360
      ->fields('t', ['name', 'age'])
361 362 363 364
      ->condition('age', 28);

    $query_1->union($query_2, 'ALL');
    $names = $query_1->execute()->fetchCol();
365
    $count = (int) $query_1->countQuery()->execute()->fetchField();
366 367

    // Ensure the counts match.
368
    $this->assertSame(count($names), $count, "The count query's result matched the number of rows in the UNION query.");
369 370
  }

371 372 373
  /**
   * Tests that we can UNION multiple Select queries together and set the ORDER.
   */
374
  public function testUnionOrder() {
375
    // This gives George and Ringo.
376
    $query_1 = $this->connection->select('test', 't')
377 378
      ->fields('t', ['name'])
      ->condition('age', [27, 28], 'IN');
379 380

    // This gives Paul.
381
    $query_2 = $this->connection->select('test', 't')
382
      ->fields('t', ['name'])
383 384 385 386 387 388 389 390
      ->condition('age', 26);

    $query_1->union($query_2);
    $query_1->orderBy('name', 'DESC');

    $names = $query_1->execute()->fetchCol();

    // Ensure we get all 3 records.
391
    $this->assertCount(3, $names, 'UNION returned rows from both queries.');
392 393 394

    // Ensure that the names are in the correct reverse alphabetical order,
    // regardless of which query they came from.
395 396 397
    $this->assertEqual('Ringo', $names[0], 'First query returned correct name.');
    $this->assertEqual('Paul', $names[1], 'Second query returned correct name.');
    $this->assertEqual('George', $names[2], 'Third query returned correct name.');
398 399 400 401 402
  }

  /**
   * Tests that we can UNION multiple Select queries together with and a LIMIT.
   */
403
  public function testUnionOrderLimit() {
404
    // This gives George and Ringo.
405
    $query_1 = $this->connection->select('test', 't')
406 407
      ->fields('t', ['name'])
      ->condition('age', [27, 28], 'IN');
408 409

    // This gives Paul.
410
    $query_2 = $this->connection->select('test', 't')
411
      ->fields('t', ['name'])
412 413 414 415 416 417 418 419 420
      ->condition('age', 26);

    $query_1->union($query_2);
    $query_1->orderBy('name', 'DESC');
    $query_1->range(0, 2);

    $names = $query_1->execute()->fetchCol();

    // Ensure we get all only 2 of the 3 records.
421
    $this->assertCount(2, $names, 'UNION with a limit returned rows from both queries.');
422 423 424

    // Ensure that the names are in the correct reverse alphabetical order,
    // regardless of which query they came from.
425 426
    $this->assertEqual('Ringo', $names[0], 'First query returned correct name.');
    $this->assertEqual('Paul', $names[1], 'Second query returned correct name.');
427 428
  }

429
  /**
430
   * Tests that random ordering of queries works.
431 432 433 434 435 436 437 438 439 440 441 442 443
   *
   * We take the approach of testing the Drupal layer only, rather than trying
   * to test that the database's random number generator actually produces
   * random queries (which is very difficult to do without an unacceptable risk
   * of the test failing by accident).
   *
   * Therefore, in this test we simply run the same query twice and assert that
   * the two results are reordered versions of each other (as well as of the
   * same query without the random ordering). It is reasonable to assume that
   * if we run the same select query twice and the results are in a different
   * order each time, the only way this could happen is if we have successfully
   * triggered the database's random ordering functionality.
   */
444
  public function testRandomOrder() {
445 446 447 448
    // Use 52 items, so the chance that this test fails by accident will be the
    // same as the chance that a deck of cards will come out in the same order
    // after shuffling it (in other words, nearly impossible).
    $number_of_items = 52;
449
    while ($this->connection->query("SELECT MAX([id]) FROM {test}")->fetchField() < $number_of_items) {
450
      $this->connection->insert('test')->fields(['name' => $this->randomMachineName()])->execute();
451 452 453 454
    }

    // First select the items in order and make sure we get an ordered list.
    $expected_ids = range(1, $number_of_items);
455
    $ordered_ids = $this->connection->select('test', 't')
456
      ->fields('t', ['id'])
457 458 459 460
      ->range(0, $number_of_items)
      ->orderBy('id')
      ->execute()
      ->fetchCol();
461
    $this->assertEqual($expected_ids, $ordered_ids, 'A query without random ordering returns IDs in the correct order.');
462 463 464 465

    // Now perform the same query, but instead choose a random ordering. We
    // expect this to contain a differently ordered version of the original
    // result.
466
    $randomized_ids = $this->connection->select('test', 't')
467
      ->fields('t', ['id'])
468 469 470 471
      ->range(0, $number_of_items)
      ->orderRandom()
      ->execute()
      ->fetchCol();
472
    $this->assertNotEquals($ordered_ids, $randomized_ids, 'A query with random ordering returns an unordered set of IDs.');
473 474
    $sorted_ids = $randomized_ids;
    sort($sorted_ids);
475
    $this->assertEqual($ordered_ids, $sorted_ids, 'After sorting the random list, the result matches the original query.');
476 477 478

    // Now perform the exact same query again, and make sure the order is
    // different.
479
    $randomized_ids_second_set = $this->connection->select('test', 't')
480
      ->fields('t', ['id'])
481 482 483 484
      ->range(0, $number_of_items)
      ->orderRandom()
      ->execute()
      ->fetchCol();
485
    $this->assertNotEquals($randomized_ids, $randomized_ids_second_set, 'Performing the query with random ordering a second time returns IDs in a different order.');
486 487
    $sorted_ids_second_set = $randomized_ids_second_set;
    sort($sorted_ids_second_set);
488
    $this->assertEqual($sorted_ids, $sorted_ids_second_set, 'After sorting the second random list, the result matches the sorted version of the first random list.');
489 490
  }

491
  /**
492 493 494 495 496 497 498 499
   * Data provider for testRegularExpressionCondition().
   *
   * @return array[]
   *   Returns data-set elements with:
   *     - the expected result of the query
   *     - the table column to do the search on.
   *     - the regular expression pattern to search for.
   *     - the regular expression operator 'REGEXP' or 'NOT REGEXP'.
500
   */
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
  public function providerRegularExpressionCondition() {
    return [
      [['John'], 'name', 'hn$', 'REGEXP'],
      [['Paul'], 'name', '^Pau', 'REGEXP'],
      [['George', 'Ringo'], 'name', 'Ringo|George', 'REGEXP'],
      [['Pete'], 'job', '#Drummer', 'REGEXP'],
      [[], 'job', '#Singer', 'REGEXP'],
      [['Paul', 'Pete'], 'age', '2[6]', 'REGEXP'],

      [['George', 'Paul', 'Pete', 'Ringo'], 'name', 'hn$', 'NOT REGEXP'],
      [['George', 'John', 'Pete', 'Ringo'], 'name', '^Pau', 'NOT REGEXP'],
      [['John', 'Paul', 'Pete'], 'name', 'Ringo|George', 'NOT REGEXP'],
      [['George', 'John', 'Paul', 'Ringo'], 'job', '#Drummer', 'NOT REGEXP'],
      [['George', 'John', 'Paul', 'Pete', 'Ringo'], 'job', '#Singer', 'NOT REGEXP'],
      [['George', 'John', 'Ringo'], 'age', '2[6]', 'NOT REGEXP'],
516
    ];
517
  }
518

519 520 521 522 523 524
  /**
   * Tests that filter by 'REGEXP' and 'NOT REGEXP' works as expected.
   *
   * @dataProvider providerRegularExpressionCondition
   */
  public function testRegularExpressionCondition($expected, $column, $pattern, $operator) {
525 526
    $database = $this->container->get('database');
    $database->insert('test')
527
      ->fields([
528 529 530
        'name' => 'Pete',
        'age' => 26,
        'job' => '#Drummer',
531
      ])
532 533
      ->execute();

534
    $query = $database->select('test', 't');
535 536 537 538 539 540
    $query->addField('t', 'name');
    $query->condition("t.$column", $pattern, $operator);
    $result = $query->execute()->fetchCol();
    sort($result);

    $this->assertEquals($expected, $result);
541 542
  }

543
  /**
544
   * Tests that aliases are renamed when they are duplicates.
545
   */
546
  public function testSelectDuplicateAlias() {
547
    $query = $this->connection->select('test', 't');
548 549
    $alias1 = $query->addField('t', 'name', 'the_alias');
    $alias2 = $query->addField('t', 'age', 'the_alias');
550
    $this->assertNotSame($alias1, $alias2, 'Duplicate aliases are renamed.');
551
  }
552

553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
  /**
   * Tests deprecation of the 'throw_exception' option.
   *
   * @group legacy
   */
  public function testLegacyThrowExceptionOption(): void {
    $this->expectDeprecation("Passing a 'throw_exception' option to %AExceptionHandler::handleExecutionException is deprecated in drupal:9.2.0 and is removed in drupal:10.0.0. Always catch exceptions. See https://www.drupal.org/node/3201187");
    // This query will fail because the table does not exist.
    $this->assertNull($this->connection->select('some_table_that_does_not_exist', 't', ['throw_exception' => FALSE])
      ->fields('t')
      ->countQuery()
      ->execute()
    );
  }

568
  /**
569
   * Tests that an invalid count query throws an exception.
570
   */
571
  public function testInvalidSelectCount() {
572 573 574 575 576 577
    $this->expectException(DatabaseExceptionWrapper::class);
    // This query will fail because the table does not exist.
    $this->connection->select('some_table_that_does_not_exist', 't')
      ->fields('t')
      ->countQuery()
      ->execute();
578 579
  }

580 581 582
  /**
   * Tests thrown exception for IN query conditions with an empty array.
   */
583
  public function testEmptyInCondition() {
584
    try {
585
      $this->connection->select('test', 't')
586
        ->fields('t')
587
        ->condition('age', [], 'IN')
588 589 590 591 592 593 594 595 596
        ->execute();

      $this->fail('Expected exception not thrown');
    }
    catch (InvalidQueryException $e) {
      $this->assertEqual("Query condition 'age IN ()' cannot be empty.", $e->getMessage());
    }

    try {
597
      $this->connection->select('test', 't')
598
        ->fields('t')
599
        ->condition('age', [], 'NOT IN')
600 601 602 603 604 605 606 607 608
        ->execute();

      $this->fail('Expected exception not thrown');
    }
    catch (InvalidQueryException $e) {
      $this->assertEqual("Query condition 'age NOT IN ()' cannot be empty.", $e->getMessage());
    }
  }

609
}