Skip to content

Commit

Permalink
qb fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
jamesread committed Sep 5, 2023
1 parent 4ce6c53 commit fc2535a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 6 deletions.
23 changes: 18 additions & 5 deletions src/main/php/libAllure/QueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,19 +78,27 @@ public function fields(string|array ...$fields)
return $this;
}

protected function addFieldPrefix($field)
protected function addFieldPrefix($field, $alias = null)
{
/*
if (strpos($field, '!') !== false) {
return str_replace('!', '', $field);
}
*/

if (strpos($field, '.') === false) {
$alias = $this->lastAliasUsed . '.';
if ($alias == null) {
if (strpos($field, '.') !== false) {
$prefix = ''; // field already has a dot
} else {
$prefix = $this->lastAliasUsed . '.';
}
} else {
$alias = '';
if (strpos($field, '.') === false) {
$prefix = $alias . '.'; // add the dot
}
}

return $alias . $field;
return $prefix . $field;

Check failure on line 101 in src/main/php/libAllure/QueryBuilder.php

View workflow job for this annotation

GitHub Actions / build

Variable $prefix might not be defined.
}

public function where($field, $operator, $value)
Expand Down Expand Up @@ -231,6 +239,11 @@ public function onEq($field, $value)
return $this->on($field, '=', $value);
}

public function onFromFieldsEq($fromField, $joinedField)
{
return $this->onEq($this->addFieldPrefix($fromField, $this->from['alias']), $this->addFieldPrefix($joinedField));
}

public function onGt($field, $value)
{
return $this->on($field, '>', $value);
Expand Down
12 changes: 11 additions & 1 deletion src/test/php/QueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ public function testSubquery() {
public function testGroup() {
$qb = new QueryBuilder();
$qb->fields('p.id', 'p.forename')->from('people');
$qb->groupBy('p.forename');
$qb->groupBy('forename');

$this->assertEquals('SELECT p.id, p.forename FROM people p GROUP BY p.forename ORDER BY p.id', $qb->build());
}
Expand All @@ -123,6 +123,16 @@ public function testAutoAlias() {
$sql = 'SELECT f.username, o.password FROM foo f LEFT JOIN fffoobar o ON f.username = o.id ORDER BY f.username';
$this->assertEquals($sql, $qb->build());
}

public function testJoinOnWhenDontKnowTableAliases() {
$qb = new QueryBuilder();
$qb->from('foo')->fields('username');
$qb->join('fffoobar')->onFromFieldsEq('username', 'id')->fields('password');

$sql = 'SELECT f.username, o.password FROM foo f LEFT JOIN fffoobar o ON f.username = o.id ORDER BY f.username';
$this->assertEquals($sql, $qb->build());

}
}


Expand Down

0 comments on commit fc2535a

Please sign in to comment.