summaryrefslogtreecommitdiff
path: root/lib/Boha/Karma.rakumod
diff options
context:
space:
mode:
Diffstat (limited to 'lib/Boha/Karma.rakumod')
-rw-r--r--lib/Boha/Karma.rakumod79
1 files changed, 79 insertions, 0 deletions
diff --git a/lib/Boha/Karma.rakumod b/lib/Boha/Karma.rakumod
new file mode 100644
index 0000000..2240743
--- /dev/null
+++ b/lib/Boha/Karma.rakumod
@@ -0,0 +1,79 @@
+use v6.d;
+use IRC::Client;
+use Red:api<2>;
+use Red::AST::Function;
+
+model Boha::KarmaEvent is table<karma_event> {
+ 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<SUM>, :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<SUM>, :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;
+ }
+}