use v6.d; use IRC::Client; use Red:api<2>; use Red::AST::Function; model Boha::KarmaEvent is table { has Int $.id is serial; has DateTime $.created is column .= now; has Str $.nick is column; has Int $.delta is column; method current-karma-for(::?CLASS:U: Str $nick) { #`{ this runs: SELECT SUM("karma_event".delta) as "data_1" FROM "karma_event" WHERE "karma_event".nick = ? } self.^all.grep({ .nick eq $nick }).map( {Red::AST::Function.new(:func, :args(.delta), :returns(Int)) } ); } method current-karma(::?CLASS:U: Int :$top) { #`{ this runs: SELECT "karma_event".nick as "data_1", SUM("karma_event".delta) as "data_2" FROM "karma_event" GROUP BY "karma_event".nick ORDER BY data_2 DESC } my $rs = self.^all .map( { .nick, Red::AST::Function.new(:func, :args(.delta), :returns(Int)) } ) #`{ two notes: * $_ is a class generated my the `map`, we want its second column, so that's what we say (it's usually called `data_2`, but we won't depend on that) * the `sort` works by accident! only because `translate(Red::AST::Mul $_ where .left.?value == -1, "order")` does not prepend `.model.^as` } .sort({ -1 * .^columns[1].column}) ; #`{ * there's no direct way to do a "group by" * also, this will generate invalid SQL unless we swap the `order by` and `group by` blocks in Red::Driver::CommonSQL } $rs.group = self.nick; return $top ?? $rs.head($top) !! $rs; } method new-karma(::?CLASS:U: Str $nick, Int $delta) { self.^create(:$nick,:$delta); return; } }