blib/lib/DBIx/QuickORM/Manual/RowClasses.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::RowClasses;
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::RowClasses - Your own row classes: for one table, every table, or one query, and plain hashrefs, by example.
14  
15 =head1 DESCRIPTION
16  
17 A row object wraps one row's data (a hashref) with the ORM and the table it
18 came from. L<DBIx::QuickORM::Row> is the default class. Replace it where you
19 want methods of your own, or ask for the hashrefs themselves.
20  
21 L<DBIx::QuickORM::Manual::Classes> shows the same as C<row> blocks.
22  
23 =head1 SCHEMA
24  
25 The examples use PostgreSQL and this schema:
26  
27 =for highlighter language=sql
28  
29 CREATE TABLE users (
30 id SERIAL PRIMARY KEY,
31 name TEXT NOT NULL,
32 email TEXT UNIQUE,
33 prefs JSON,
34 referred_by INTEGER REFERENCES users (id),
35 created TIMESTAMP NOT NULL DEFAULT now()
36 );
37  
38 CREATE TABLE posts (
39 id SERIAL PRIMARY KEY,
40 user_id INTEGER NOT NULL REFERENCES users (id),
41 title TEXT NOT NULL,
42 views INTEGER NOT NULL DEFAULT 0
43 );
44  
45 =head1 ONE TABLE
46  
47 =for highlighter language=perl
48  
49 package My::User;
50 use parent 'DBIx::QuickORM::Row';
51  
52 sub posts { $_[0]->follow_fk('posts') } # a handle on this user's posts
53  
54 sub theme { ($_[0]->field('prefs') // {})->{theme} } # from the inflated JSON
55  
56 sub change_email {
57 my ($self, $email) = @_;
58 # rows have no setters: writes go through update
59 return $self->update({email => $email});
60 }
61  
62 package main;
63  
64 my $orm = DBIx::QuickORM->new(
65 credentials => {
66 dsn => $dsn,
67 user => $user,
68 pass => $pass,
69 },
70 row_classes => {users => 'My::User'},
71 );
72  
73 my $ann = $orm->insert(users => {
74 name => 'Ann',
75 prefs => {theme => 'dark'},
76 });
77  
78 my $theme = $ann->theme; # 'dark'
79  
80 # a DBIx::QuickORM::Row: posts has no row class here
81 my $post = $orm->insert(posts => {
82 user_id => $ann->field('id'),
83 title => 'Hi',
84 });
85  
86 my $count = $ann->posts->count; # 1
87 $ann->change_email('ann@example.com');
88  
89 Every C<users> row is a C<My::User>, however it was read: C<insert>, C<find>,
90 a handle, C<follow_fk> (L<DBIx::QuickORM::Manual::ForeignKeys>), or a
91 join's C<< ->row('users') >> (L<DBIx::QuickORM::Manual::Joins>). A handle's
92 C<row_class> can still choose another class for one query (L</THE ROLE>).
93 The class is loaded for you.
94  
95 =head1 EVERY TABLE
96  
97 package My::Row;
98 use parent 'DBIx::QuickORM::Row';
99  
100 sub id { $_[0]->field('id') } # every table here has one
101  
102 package main;
103  
104 my $app = DBIx::QuickORM->new(
105 credentials => {
106 dsn => $dsn,
107 user => $user,
108 pass => $pass,
109 },
110 row_class => 'My::Row', # the default for every table
111 row_classes => {users => 'My::User'}, # but users
112 );
113  
114 my $hi = $app->handle('posts')->where({title => 'Hi'})->only;
115 my $id = $hi->id;
116  
117 C<My::User> does not extend C<My::Row>, so here a users row has no C<id>
118 method. A table's class usually extends the shared one (C<use parent
119 'My::Row'>) to get both.
120  
121 =head1 A CLASS PER TABLE, BY NAME
122  
123 package My::Rows::Users;
124 use parent 'DBIx::QuickORM::Row';
125  
126 sub name { $_[0]->field('name') }
127  
128 package main;
129  
130 my $named = DBIx::QuickORM->new(
131 credentials => {
132 dsn => $dsn,
133 user => $user,
134 pass => $pass,
135 },
136 row_namespace => 'My::Rows',
137 );
138  
139 my $ned = $named->insert(users => {name => 'Ned'}); # a My::Rows::Users
140 my $who = $ned->name;
141 my $note = $named->insert(posts => {
142 user_id => $ned->field('id'),
143 title => 'Note',
144 }); # no My::Rows::Posts: a DBIx::QuickORM::Row
145  
146 C<row_namespace> names each table's class from the table: C<user_posts> gets
147 C<My::Rows::UserPosts>. The class is loaded for you. A table whose class has
148 no module keeps the default row class. C<row_classes> still wins.
149  
150 A class found there must be a row class (do L<DBIx::QuickORM::Role::Row>,
151 as a subclass of L<DBIx::QuickORM::Row> does). Any other module croaks.
152  
153 package My::Rows::Person;
154 use parent 'DBIx::QuickORM::Row';
155  
156 package main;
157  
158 my $people = DBIx::QuickORM->new(
159 credentials => {
160 dsn => $dsn,
161 user => $user,
162 pass => $pass,
163 },
164 row_namespace => 'My::Rows',
165 row_class_name => sub {
166 my ($table) = @_;
167 return 'Person' if $table eq 'users';
168 return undef; # the default row class
169 },
170 );
171  
172 my $pat = $people->insert(users => {name => 'Pat'}); # a My::Rows::Person
173  
174 C<row_class_name> names the class instead: it gets the table and returns the
175 part after the namespace. Undef keeps the default row class.
176  
177 A name part that is not valid (it holds C<::>, or starts with a digit) warns
178 and keeps the default row class, whether it came from the table or from
179 C<row_class_name>.
180  
181 =head1 HASHREFS
182  
183 my @data = $app->handle('users')->data_only->all; # the row data itself
184 my $name = $data[0]->{name};
185  
186 # as the database returned it: JSON text
187 my $json = $data[0]->{prefs};
188  
189 my $plain = DBIx::QuickORM->new(
190 credentials => {
191 dsn => $dsn,
192 user => $user,
193 pass => $pass,
194 },
195 row_class => undef, # hashrefs for every table
196 );
197  
198 # a hashref: {id => ..., name => 'Bob', email => undef, ...}
199 my $bob = $plain->insert(users => {name => 'Bob'});
200 my $same = $plain->find(users => $bob->{id});
201  
202 # new row data ($bob is unchanged)
203 my $new = $plain->update_row(users => $bob, {name => 'Robert'});
204 my $gone = $plain->delete_row(users => $new); # 1
205  
206 A hashref is the row data the ORM works on everywhere. Treat it as
207 read-only: a missing key is a field not fetched, undef is NULL, nothing
208 inflates it, and nothing fetches for it. Write with C<update_row> and keep
209 what it returns. The hashref you passed is stale after that
210 (L<DBIx::QuickORM::Manual::Caching>). The ORM's CRUD operations take a hashref
211 wherever a row is expected. If a rollback undoes the insert, find the row
212 again before relying on a hashref returned by C<cas_update>
213 (L<DBIx::QuickORM/"CRUD operations">).
214  
215 C<data_only> is short for C<row_class(undef)>. Table rows still go through the
216 row cache. C<bare> is C<data_only> plus C<no_cache>: hashrefs the row cache
217 never sees. It reads a table with a primary key faster than C<data_only>.
218 C<< row_classes => {posts => undef} >> gives one table hashrefs.
219  
220 =head1 ROWS NOT IN THE DATABASE
221  
222 my $draft = $orm->vivify(users => {name => 'Draft'}); # nothing written yet
223 $draft->modify({email => 'draft@example.com'});
224 my $stored = $draft->is_in_db; # false
225  
226 $draft->insert; # now it is
227 $draft->update({name => 'Final'});
228  
229 $draft->delete;
230 my $deleted = $draft->was_deleted; # true
231 $draft->insert; # back in, with the same key
232  
233 C<vivify> builds a row the database does not have yet. C<modify> changes it
234 and C<insert> writes it. C<update>, C<cas_update>, C<delete>, and C<refresh>
235 croak on a row not in the database. C<insert> and C<modify> croak on one that
236 is.
237  
238 C<is_in_db> is what this ORM last saw, not a check of the database. A row's
239 own C<delete>, a C<delete_row>, or a C<refresh> or C<find> that finds nothing
240 marks it deleted. A handle's bulk C<delete> marks nothing unless given
241 C<< mark_deleted => 1 >>. A transaction rollback undoes the deletes and
242 inserts made inside it
243 (L<DBIx::QuickORM::Manual::Transactions/"THE ROWS YOU HOLD">).
244  
245 =head1 THE ROLE
246  
247 package My::RawRow;
248 use Object::HashBase qw{<orm <table row_data};
249 use Role::Tiny::With qw/with/;
250 with 'DBIx::QuickORM::Role::Row';
251  
252 # raw by default, but inflated_field still inflates
253 sub field { my $self = shift; $self->raw_field(@_) }
254 sub fields { my $self = shift; $self->raw_fields(@_) }
255  
256 package main;
257  
258 # one query's rows
259 my $raw = $app->handle('users')
260 ->where({id => $ann->field('id')})
261 ->row_class('My::RawRow')
262 ->only;
263  
264 my $text = $raw->field('prefs'); # '{"theme":"dark"}'
265 my $prefs = $raw->inflated_field('prefs'); # {theme => 'dark'}
266  
267 L<DBIx::QuickORM::Role::Row> holds everything a row does (reading, inflation,
268 C<update>, C<delete>, C<follow_fk>). Consume it when your class cannot extend
269 L<DBIx::QuickORM::Row>. A subclass can override C<field> and C<fields> the
270 same way.
271  
272 The ORM itself needs only a constructor and four methods (the role needs the
273 same):
274  
275 package My::Bare;
276 # new, orm, table, row_data, set_row_data: all the ORM needs
277 use Object::HashBase qw{<orm <table row_data};
278  
279 package main;
280  
281 my $bare = $app->handle('users')->row_class('My::Bare')->first;
282  
283 # field(), update(), and the rest are yours to add
284 my $data = $bare->row_data;
285  
286 It builds a row with C<< $class->new(row_data => \%data, orm => $orm, table
287 => $table) >>, where C<$table> is the table's name (undef for a query's
288 rows). A class whose C<fast_bless> is true, as L<DBIx::QuickORM::Row> and its
289 plain subclasses are, is blessed from those directly. When C<update_row> or
290 C<refresh_row> is given the row, it hands the row the new data through
291 C<set_row_data>. L<Object::HashBase> is one way to get those. Any class that
292 has them works.
293  
294 =head1 WHICH CLASS
295  
296 The most specific wins, and undef at any level means hashrefs:
297  
298 =over 4
299  
300 =item *
301  
302 The C<row_class> option of a CRUD operation, for that call
303 (L<DBIx::QuickORM/"CRUD operations">).
304  
305 =item *
306  
307 The handle's C<row_class> (or C<data_only>), when it was called.
308  
309 =item *
310  
311 The table's: C<row_classes>, or a table class (L<DBIx::QuickORM::Manual::Classes>).
312  
313 =item *
314  
315 The table's class under C<row_namespace>, when it exists.
316  
317 =item *
318  
319 The ORM's C<row_class>, L<DBIx::QuickORM::Row> unless given.
320  
321 =back
322  
323 Join rows are L<DBIx::QuickORM::JoinRow> objects
324 (L<DBIx::QuickORM::Manual::Joins>). The join handle's
325 C<row_class(undef)> gives flat hashrefs keyed C<component.field> instead. Any
326 other class there croaks when the query runs. The component rows
327 (C<< ->row('users') >>) use their tables' classes.
328  
329 Computed rows (C<fields> with an aggregate, see
330 L<DBIx::QuickORM::Manual::Aggregates>) are L<DBIx::QuickORM::AggregateRow>
331 objects, or hashrefs when the class resolved for the table (over a join, the
332 ORM's C<row_class>) is undef. The handle's C<row_class> replaces either.
333  
334 =cut
335  
336 1;
337  
338 __END__