Skip to content

Commit

Permalink
Added exception for missing sub select alias
Browse files Browse the repository at this point in the history
  • Loading branch information
jrabausch committed Jul 12, 2021
1 parent 39d85da commit 33f90fd
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 5 deletions.
9 changes: 5 additions & 4 deletions src/Expression/Table.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
namespace Semperton\Query\Expression;

use Closure;
use InvalidArgumentException;
use Semperton\Query\ExpressionInterface;
use Semperton\Query\QueryFactory;
use Semperton\Query\Type\SelectQuery;
use RuntimeException;

use function is_string;
use function implode;
Expand All @@ -31,6 +31,10 @@ public function __construct(QueryFactory $factory)
*/
public function add($table, string $alias = ''): self
{
if ($table instanceof Closure && $alias === '') {
throw new InvalidArgumentException('Alias cannot be empty for sub select');
}

$this->tables[] = [$table, $alias];
return $this;
}
Expand Down Expand Up @@ -71,9 +75,6 @@ public function compile(array &$params = []): string
$sql[] = $table . ' ' . $this->factory->quoteIdentifier($alias);
}
} else {
if ($alias === '') {
throw new RuntimeException('Alias is required for sub select');
}

$subSelect = new SelectQuery($this->factory);
$table($subSelect);
Expand Down
2 changes: 1 addition & 1 deletion src/Type/SelectQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ public function compile(array &$params = []): string

if ($this->where->isValid()) {
$sql[] = 'where';
$sql[] = $this->where->compile($params);
$sql[] = $this->where->compile($params);
}

if (!!$this->groupBy) {
Expand Down
19 changes: 19 additions & 0 deletions tests/ExpressionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
use PHPUnit\Framework\TestCase;
use Semperton\Query\Expression\Field;
use Semperton\Query\Expression\Filter;
use Semperton\Query\Expression\Table;
use Semperton\Query\QueryFactory;
use Semperton\Query\Type\SelectQuery;

final class ExpressionTest extends TestCase
{
Expand Down Expand Up @@ -107,4 +109,21 @@ public function testIndentifier(): void

$this->assertEquals('"table".*', $ident->compile());
}

public function testTable(): void
{
$this->expectException(InvalidArgumentException::class);
$factory = new QueryFactory();
$table = new Table($factory);

$table->add(function (SelectQuery $query) {
$query->from('user')->where('id', '>', 3);
}, 'users');

$this->assertEquals('(select * from user where id > :p1) users', $table->compile());

$table->reset();
$table->add(function (SelectQuery $query) {
});
}
}

0 comments on commit 33f90fd

Please sign in to comment.