summaryrefslogtreecommitdiff
path: root/lib/Boha/Karma.rakumod
blob: 22407436838885ce85b7cf05bcfd3e3709d47317 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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 $nickInt $delta{
        self.^create(:$nick,:$delta);
        return;
    }
}