use SQL::Abstract::Test import => [ qw(is_same_sql_bind is_same_sql) ];
use SQL::Abstract::ExtraClauses;
-my $sqlac = SQL::Abstract::ExtraClauses->new;
+my $sqlac = SQL::Abstract::ExtraClauses->new(unknown_unop_always_func => 1);
my ($sql, @bind) = $sqlac->select({
- select => [ qw(artist.id artist.name), { -func => [ json_agg => 'cd' ] } ],
+ select => [ qw(artist.id artist.name), { -json_agg => 'cd' } ],
from => [
{ artists => { -as => 'artist' } },
-join => [ cds => as => 'cd' => on => { 'cd.artist_id' => 'artist.id' } ],
where => { 'artist.genres', => { '@>', { -value => [ 'Rock' ] } } },
order_by => 'artist.name',
group_by => 'artist.id',
- having => { '>' => [ { -func => [ count => 'cd.id' ] }, 3 ] }
+ having => { '>' => [ { -count => 'cd.id' }, 3 ] }
});
is_same_sql_bind(
SELECT artist.id, artist.name, JSON_AGG(cd)
FROM artists AS artist JOIN cds AS cd ON cd.artist_id = artist.id
WHERE artist.genres @> ?
- ORDER BY artist.name
GROUP BY artist.id
HAVING COUNT(cd.id) > ?
+ ORDER BY artist.name
},
[ [ 'Rock' ], 3 ]
);
[ 1..6 ],
);
+is_same_sql(
+ $sqlac->select({
+ select => '*',
+ from => 'foo',
+ where => { -not_exists => {
+ -select => {
+ select => \1,
+ from => 'bar',
+ where => { 'foo.id' => { -ident => 'bar.foo_id' } }
+ },
+ } },
+ }),
+ q{SELECT * FROM foo
+ WHERE NOT EXISTS (SELECT 1 FROM bar WHERE foo.id = bar.foo_id)},
+);
+
+is_same_sql(
+ $sqlac->select({
+ select => '*',
+ from => 'foo',
+ where => { id => {
+ '=' => { -select => { select => { -max => 'id' }, from => 'foo' } }
+ } },
+ }),
+ q{SELECT * FROM foo WHERE id = (SELECT MAX(id) FROM foo)},
+);
+
+{
+ my $sqlac = $sqlac->clone
+ ->clauses_of(
+ select => (
+ $sqlac->clauses_of('select'),
+ qw(limit offset),
+ )
+ );
+
+ ($sql, @bind) = $sqlac->select({
+ select => '*',
+ from => 'foo',
+ limit => 10,
+ offset => 20,
+ });
+
+ is_same_sql_bind(
+ $sql, \@bind,
+ q{SELECT * FROM foo LIMIT ? OFFSET ?}, [ 10, 20 ]
+ );
+}
+
+$sql = $sqlac->select({
+ select => { -as => [ \1, 'x' ] },
+ union => { -select => { select => { -as => [ \2, 'x' ] } } },
+ order_by => { -desc => 'x' },
+});
+
+is_same_sql(
+ $sql,
+ q{(SELECT 1 AS x) UNION (SELECT 2 AS x) ORDER BY x DESC},
+);
+
+$sql = $sqlac->select({
+ select => '*',
+ from => 'foo',
+ except => { -select => { select => '*', from => 'foo_exclusions' } }
+});
+
+is_same_sql(
+ $sql,
+ q{(SELECT * FROM foo) EXCEPT (SELECT * FROM foo_exclusions)},
+);
+
done_testing;