blib/lib/DBIx/QuickORM/Manual/Aggregates.pm untested

filter: Statementstmt 0.0% 0 / 8 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 2 Podpod n/a totaltotal 0.0% 0 / 10 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 package DBIx::QuickORM::Manual::Aggregates;
2 use strict;
3 use warnings;
4  
5 our $VERSION = '0.000033';
6  
7 =pod
8  
9 =encoding UTF-8
10  
11 =head1 NAME
12  
13 DBIx::QuickORM::Manual::Aggregates - Group, count, and compute columns, by example.
14  
15 =head1 DESCRIPTION
16  
17 C<group_by>, C<having>, or a hashref given to C<fields> makes a handle query
18 computed columns. Its rows are L<DBIx::QuickORM::AggregateRow> objects by
19 default: they inflate values and follow foreign keys
20 (L<DBIx::QuickORM::Manual::ForeignKeys>), but cannot be written.
21  
22 =head1 SCHEMA
23  
24 The examples use PostgreSQL and this schema:
25  
26 =for highlighter language=sql
27  
28 CREATE TABLE users (
29 id SERIAL PRIMARY KEY,
30 name TEXT NOT NULL,
31 email TEXT UNIQUE,
32 prefs JSON,
33 referred_by INTEGER REFERENCES users (id),
34 created TIMESTAMP NOT NULL DEFAULT now()
35 );
36  
37 CREATE TABLE posts (
38 id SERIAL PRIMARY KEY,
39 user_id INTEGER NOT NULL REFERENCES users (id),
40 title TEXT NOT NULL,
41 views INTEGER NOT NULL DEFAULT 0
42 );
43  
44 =head1 COUNTING
45  
46 =for highlighter language=perl
47  
48 my $total = $orm->handle('posts')->count; # SELECT COUNT(*)
49 my $alice = $orm->handle('posts')->where({user_id => $alice_id})->count; # with its WHERE
50  
51 =head1 GROUPING
52  
53 use DBIx::QuickORM::Value qw/sql/;
54  
55 my @per_user = $orm->handle('posts')
56 ->group_by('user_id')
57 ->fields({
58 user_id => 'user_id',
59 posts => [count => '*'],
60 views => [sum => 'views'],
61 })
62 ->order_by('user_id')
63 ->all;
64  
65 for my $stat (@per_user) {
66 my $posts = $stat->field('posts');
67 my ($user_id, $views) = $stat->fields(qw/user_id views/);
68 my $user = $stat->follow_fk('users')->only; # user_id keeps its foreign key
69 }
70  
71 # Without group_by the whole table is one group.
72 my $all = $orm->handle('posts')->fields({
73 posts => [count => '*'],
74 top => [max => 'views'],
75 })->only;
76  
77 my ($count, $top) = $all->fields(qw/posts top/);
78  
79 # group_by alone selects the grouped fields.
80 my @groups = $orm->handle('posts')
81 ->group_by('user_id')
82 ->order_by('user_id')
83 ->all;
84  
85 # Several fields: pass them all. One row per user and title.
86 my @per_title = $orm->handle('posts')
87 ->group_by('user_id', 'title')
88 ->fields({
89 user_id => 'user_id',
90 title => 'title',
91 posts => [count => '*'],
92 })
93 ->order_by(['user_id', 'title'])
94 ->all;
95  
96 Each row is an L<DBIx::QuickORM::AggregateRow>. C<field>, C<fields>, and
97 C<raw_field> read its columns. C<follow_fk> follows a column that kept a
98 foreign key (L</COLUMN SPECS>).
99  
100 C<count> croaks on a grouped handle. Use C<< posts => [count => '*'] >>, as
101 above, to count the rows in each group.
102  
103 =head1 HAVING
104  
105 C<having> filters groups, as C<where> filters rows. Use it with C<group_by>
106 or computed fields. Without either, it croaks.
107  
108 Name a computed column to filter on it:
109  
110 my @busy = $orm->handle('posts')
111 ->where({views => {'>' => 0}}) # filters rows, before grouping
112 ->group_by('user_id')
113 ->fields({
114 user_id => 'user_id',
115 posts => [count => '*'],
116 })
117 ->having({posts => {'>' => 1}}) # filters groups
118 ->all;
119  
120 This works on every database. On MySQL and MariaDB the ORM sends the name as
121 written, and the server computes the count once. Elsewhere it writes the
122 column's SQL there instead, C<COUNT(*) E<gt> ?>: PostgreSQL rejects the
123 name in C<HAVING>, and SQLite would let a table column of the same name win.
124  
125 Every database can name a grouped field:
126  
127 my @later = $orm->handle('posts')
128 ->group_by('user_id')
129 ->having({user_id => {'>' => 1}})
130 ->all;
131  
132 C<sql()> writes the condition yourself. Extra arguments to C<sql()> are
133 binds:
134  
135 my @two = $orm->handle('posts')
136 ->group_by('user_id')
137 ->having(sql('COUNT(*) > ?', 1))
138 ->all;
139  
140 SQLite sends a bind as text, which never compares with a count, whether the
141 having names the column or writes C<sql()>. Write the number into the SQL
142 there, C<< {posts => {'>' => \'1'}} >>, or cast the bind:
143 C<< sql('COUNT(*) > CAST(? AS INTEGER)', $minimum) >>
144 (L<DBIx::QuickORM::Manual::Dialects/"SQL YOU WRITE">). C<sql()> is in
145 L<DBIx::QuickORM::Manual::Values>.
146  
147 =head1 COLUMN SPECS
148  
149 my $stat = $orm->handle('posts')
150 ->group_by('user_id')
151 ->fields({
152 # the field itself: its type and single-column foreign keys come along
153 user_id => 'user_id',
154 posts => [count => '*'], # COUNT(*): '*' stands for the whole row
155 titles => sql('COUNT(DISTINCT title)'), # any SQL: no type, no foreign key
156 chars => \'SUM(LENGTH(title))', # short for sql('SUM(LENGTH(title))')
157  
158 # MAX(views): min and max keep the field's type and single-column keys
159 top => [max => 'views'],
160 views => [sum => 'views'], # SUM(views): other functions keep neither
161  
162 # MAX(id), declared a foreign key to posts
163 latest => {
164 agg => [max => 'id'],
165 fk => 'posts',
166 },
167 })
168 ->order_by('user_id')
169 ->first;
170  
171 my $author = $stat->follow_fk('users')->only; # user_id kept its key
172 my $latest = $stat->follow_fk('posts')->only; # latest was given one
173  
174 In C<fields>, a reference to a string, C<\'SQL'>, is short for C<sql('SQL')>.
175 C<having> and C<order_by> already take L<SQL::Abstract>'s C<\'SQL'> literals.
176 C<group_by> takes field names only.
177  
178 Insert and update values do not take the shorthand, since a scalar reference
179 there can be a JSON boolean (C<\1>, C<\0>). Use C<sql()>.
180  
181 =head1 TYPES
182  
183 my $signups = $orm->handle('users')->fields({
184 newest => [max => 'created'],
185 total => [count => '*'],
186 })->only;
187  
188 my $year = $signups->field('newest')->datetime_ref->year; # MAX kept created's type: a DateTime
189 my $text = $signups->raw_field('newest'); # the value as fetched
190  
191 my $span = $orm->handle('users')->fields({
192 # an sql() column inflates only when told: like takes created's type and keys
193 first => {
194 sql => sql("date_trunc('day', MIN(created))"),
195 like => 'created',
196 },
197 # or name the type by hand
198 last => {
199 sql => sql("date_trunc('day', MAX(created))"),
200 type => 'DateTime',
201 db_type => 'timestamp',
202 },
203 })->only;
204  
205 my ($first, $last) = map { $_->datetime_ref->ymd } $span->fields(qw/first last/);
206  
207 C<date_trunc> is PostgreSQL's. Other databases have their own functions.
208  
209 =head1 LIKE_AGGREGATES
210  
211 my $orm = DBIx::QuickORM->new(
212 credentials => {
213 dsn => $dsn,
214 user => $user,
215 pass => $pass,
216 },
217 like_aggregates => ['any_value'],
218 );
219  
220 # ANY_VALUE (PostgreSQL 16 and later) gives one of the group's values, so the
221 # column keeps the field's type and keys.
222 my @groups = $orm->handle('users')
223 ->group_by('referred_by')
224 ->fields({
225 referred_by => 'referred_by',
226 joined => [any_value => 'created'],
227 })
228 ->order_by('referred_by')
229 ->all;
230  
231 my $year = $groups[0]->field('joined')->datetime_ref->year; # a DateTime, like created
232  
233 Plain fields, C<min>, and C<max> keep the field's type and single-column
234 foreign keys, because their result is one of the field's values.
235 C<like_aggregates> adds functions to that list.
236  
237 =head1 OVER A JOIN
238  
239 my @by_name = $orm->handle('posts')
240 ->join('users')
241 ->group_by('users.id', 'users.name') # several fields: a list
242 ->fields({
243 name => 'users.name',
244 posts => [count => '*'],
245 newest => [max => 'users.created'],
246 })
247 ->order_by('name')
248 ->all;
249  
250 my ($name, $posts) = $by_name[0]->fields(qw/name posts/);
251  
252 With C<group_by> or computed fields, C<all> returns
253 L<DBIx::QuickORM::AggregateRow> objects, joined or not, never join rows. When
254 the row class is undef it returns hashrefs instead: C<data_only>, the table's
255 row class, or over a join the ORM's C<row_class>. A handle C<row_class>
256 replaces C<AggregateRow> (L<DBIx::QuickORM::Manual::RowClasses>).
257  
258 Fields are named C<table.field> (or C<alias.field>), as on any join handle
259 (L<DBIx::QuickORM::Manual::Joins>).
260 C<order_by> may also name a selected column, as C<name> is here.
261  
262 =head1 AGGREGATE ROWS
263  
264 my $stat = $per_user[0]; # from GROUPING
265  
266 my $posts = $stat->field('posts');
267 my ($id, $n) = $stat->fields(qw/user_id posts/);
268 my $pk = $stat->pk; # undef: no primary key
269  
270 # Plain hashrefs instead.
271 my @data = $orm->handle('posts')
272 ->group_by('user_id')
273 ->data_only
274 ->all;
275  
276 Aggregate rows are L<DBIx::QuickORM::AggregateRow> objects. They have no
277 primary key, so C<update>, C<delete>, and C<refresh> croak.
278  
279 =cut
280  
281 1;
282  
283 __END__