You are here

function InsertTest::testInsertSelectFields in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/system/src/Tests/Database/InsertTest.php \Drupal\system\Tests\Database\InsertTest::testInsertSelectFields()

Tests that the INSERT INTO ... SELECT (fields) ... syntax works.

File

core/modules/system/src/Tests/Database/InsertTest.php, line 141
Contains \Drupal\system\Tests\Database\InsertTest.

Class

InsertTest
Tests the insert builder.

Namespace

Drupal\system\Tests\Database

Code

function testInsertSelectFields() {
  $query = db_select('test_people', 'tp');

  // The query builder will always append expressions after fields.
  // Add the expression first to test that the insert fields are correctly
  // re-ordered.
  $query
    ->addExpression('tp.age', 'age');
  $query
    ->fields('tp', array(
    'name',
    'job',
  ))
    ->condition('tp.name', 'Meredith');

  // The resulting query should be equivalent to:
  // INSERT INTO test (age, name, job)
  // SELECT tp.age AS age, tp.name AS name, tp.job AS job
  // FROM test_people tp
  // WHERE tp.name = 'Meredith'
  db_insert('test')
    ->from($query)
    ->execute();
  $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(
    ':name' => 'Meredith',
  ))
    ->fetchField();
  $this
    ->assertIdentical($saved_age, '30', 'Can retrieve after inserting.');
}