You are here

public function AlterTest::testSimpleAlterSubquery in Drupal 8

Same name and namespace in other branches
  1. 9 core/tests/Drupal/KernelTests/Core/Database/AlterTest.php \Drupal\KernelTests\Core\Database\AlterTest::testSimpleAlterSubquery()

Tests that we can do basic alters on subqueries.

File

core/tests/Drupal/KernelTests/Core/Database/AlterTest.php, line 129

Class

AlterTest
Tests the hook_query_alter capabilities of the Select builder.

Namespace

Drupal\KernelTests\Core\Database

Code

public function testSimpleAlterSubquery() {

  // Create a sub-query with an alter tag.
  $subquery = $this->connection
    ->select('test', 'p');
  $subquery
    ->addField('p', 'name');
  $subquery
    ->addField('p', 'id');

  // Pick out George.
  $subquery
    ->condition('age', 27);
  $subquery
    ->addExpression("age*2", 'double_age');

  // This query alter should change it to age * 3.
  $subquery
    ->addTag('database_test_alter_change_expressions');

  // Create a main query and join to sub-query.
  $query = $this->connection
    ->select('test_task', 'tt');
  $query
    ->join($subquery, 'pq', 'pq.id = tt.pid');
  $age_field = $query
    ->addField('pq', 'double_age');
  $name_field = $query
    ->addField('pq', 'name');
  $record = $query
    ->execute()
    ->fetch();
  $this
    ->assertEqual($record->{$name_field}, 'George', 'Fetched name is correct.');
  $this
    ->assertEqual($record->{$age_field}, 27 * 3, 'Fetched age expression is correct.');
}