function ConditionCastTest::testConditionOperatorCastOnIntegerField

Same name and namespace in other branches
  1. 11.x core/modules/pgsql/tests/src/Kernel/pgsql/ConditionCastTest.php \Drupal\Tests\pgsql\Kernel\pgsql\ConditionCastTest::testConditionOperatorCastOnIntegerField()

Tests condition operators on an integer column.

PostgreSQL has no LIKE or regex operators for integers, so these queries only work when the field is cast to text. For query builder conditions the cast is added when the condition is compiled.

See also

\Drupal\pgsql\Driver\Database\pgsql\Connection::$postgresqlConditionOperatorMap

File

core/modules/pgsql/tests/src/Kernel/pgsql/ConditionCastTest.php, line 30

Class

ConditionCastTest
Tests casting of non-text fields for LIKE and regex operators.

Namespace

Drupal\Tests\pgsql\Kernel\pgsql

Code

public function testConditionOperatorCastOnIntegerField() : void {
  // The ages in the sample data are 25, 27, 28 and 26.
  $cases = [
    [
      'LIKE',
      '2%',
      4,
    ],
    [
      'LIKE',
      '%5',
      1,
    ],
    [
      'NOT LIKE',
      '%5',
      3,
    ],
    [
      'LIKE BINARY',
      '%7',
      1,
    ],
    [
      'ILIKE',
      '%6',
      1,
    ],
    [
      'NOT ILIKE',
      '%6',
      3,
    ],
    [
      'REGEXP',
      '^2[57]$',
      2,
    ],
    [
      'NOT REGEXP',
      '^2[57]$',
      2,
    ],
    [
      '~*',
      '8$',
      1,
    ],
    [
      '!~*',
      '8$',
      3,
    ],
  ];
  foreach ($cases as [$operator, $value, $expected_count]) {
    $query = $this->connection
      ->select('test');
    $query->addField('test', 'name');
    $query->condition('age', $value, $operator);
    $this->assertStringContainsString('::text', (string) $query, "The compiled condition for operator '{$operator}' contains a type-cast.");
    $this->assertCount($expected_count, $query->execute()
      ->fetchAll(), "Operator '{$operator}' with value '{$value}' returns {$expected_count} rows.");
  }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.