I want to generate SQL like this:
SELECT coalesce(max(a.a_index) + 1, 0) as a_index FROM table1 a
I can get everything but the “+ 1”. Is there a way to add this to the query?
use strict;
use Fey::Schema;
use Fey::Loader;
use DBI;
my $dbh = DBI->connect("DBI:mysql:....", "...", "...");
my $loader = Fey::Loader->new( dbh => $dbh );
my $s = $loader->make_schema();
my $q = Fey::SQL->new_select();
my $a_table = $s->table('table1')->alias('a');
my $a_index_col = $a_table->column('a_index');
my $max_a_index_func = Fey::Literal::Function->new('max', $a_index_col);
$max_a_index_func->set_alias_name('max_a_index');
my $c_a_index_func = Fey::Literal::Function->new('coalesce', $max_a_index_func, "0");
$c_a_index_func->set_alias_name('a_index');
$q->select($c_a_index_func);
$q->from($a_table);
print $q->sql($dbh);
print "\n";
Output
SELECT coalesce(max(`a`.`a_index`), 0) AS `a_index` FROM `table1` AS `a`
I don’t think you can since Column, Literal and Function objects don’t have operations to link them together (nor do I see any classes besides Function that can do that).
The only work-around I can see with code generation is to create a stored function:
Then use this function instead of the coalesce: