blib/lib/DBIx/QuickORM/Role/Type.pm

filter: Statementstmt 97.1% 34 / 35 Branchbran 100% 6 / 6 Conditioncond 100% 3 / 3 MC/DCmcdc 100% 2 / 2 Subroutinesub 90.9% 10 / 11 Podpod 100% 5 / 5 totaltotal 96.7% 60 / 62 CC 5 SCAR 6.2
CC
5
Cov
98%
clone_inflated
3.0
_for_field
3.0
inflate_on_each_read
2.0
CRAP 1.9
« blib/lib/DBIx/QuickORM/Type/JSON.pm ↑ Summary blib/lib/DBIx/QuickORM/WhereBuilder/SQLAbstract.pm »
1 package DBIx::QuickORM::Role::Type;
2 78 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 78 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 78 our $VERSION = '0.000032';
6  
7 78 ▶use Carp qw/croak/;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 78 ▶use Storable();
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 78 ▶use Role::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 =pod
13  
14 =encoding UTF-8
15  
16 =head1 NAME
17  
18 DBIx::QuickORM::Role::Type - The interface for field types.
19  
20 =head1 DESCRIPTION
21  
22 A type converts between the raw value a database stores and the inflated
23 value Perl code works with. A type is a class used through class methods. The
24 map names it by class (a field's C<orm_type>) and never holds objects. A type
25 needs C<inflate> and C<deflate>. This role supplies defaults for its other
26 methods.
27  
28 The CRUD operations deflate the values they send (see
29 L<DBIx::QuickORM/"CRUD operations">), and row objects inflate field values
30 when they are read (see L<DBIx::QuickORM::Role::Row>). NULL is never passed to
31 C<inflate> or C<deflate>.
32  
33 C<inflate> and C<deflate> get the map's record for the field and the
34 L<DBIx::QuickORM::Connection>, which gives the dialect
35 (C<< $conn->dialect >>) and the time zone (C<< $conn->time_zone >>).
36  
37 A field record has C<table> and C<name> (the field's own), C<affinity>,
38 C<db_type>, C<type>, C<size>, C<orm_type> (this type's class), the hints
39 C<format> and C<generate>, and the scan facts C<db_fills> and
40 C<db_refuses_value>.
41 Any key may be missing. A hand-written record may have only some of them.
42 C<_for_field> turns C<table> and C<name> into text for croaks.
43  
44 For C<autotype>, a type claims fields with C<base_types>, the base C<type>
45 names it takes, or C<matches($field_name, \%field, $dialect)>, for fields
46 known by name. It needs at least one of the two. A type used only through
47 C<types> needs neither. This role provides neither.
48  
49 =head2 Cached inflated values
50  
51 A row hands every reader a value of its own, so code changing a value it read
52 cannot change what the next reader gets. The type says how with
53 C<inflated_is_immutable_for_cache>, C<inflate_on_each_read>, and
54 C<clone_inflated>.
55  
56 A custom type takes one of three paths:
57  
58 =over 4
59  
60 =item *
61  
62 It inflates to values nobody can change (plain strings, or objects that
63 hand out copies to change, as L<DBIx::QuickORM::Type::DateTime::Lazy>
64 does) and declares C<inflated_is_immutable_for_cache> true.
65  
66 =item *
67  
68 It declares C<inflate_on_each_read> true when inflating the raw value again
69 is cheaper than copying an inflated one. Rows then inflate on every read and
70 cache nothing for the field. L<DBIx::QuickORM::Type::JSON> does this: decoding
71 JSON text was faster than deep-copying the decoded data at every size
72 measured, from 23 bytes to 6 KB.
73  
74 =item *
75  
76 It leaves both false (the default). Rows cache the inflated value and hand out
77 C<clone_inflated> copies. It provides C<clone_inflated> when C<dclone>
78 (L<Storable>) cannot copy its values.
79  
80 =back
81  
82 C<inflated_is_immutable_for_cache> wins over C<inflate_on_each_read>. To pick
83 between copying and inflating again, time both on realistic values. Code
84 reading large values often may prefer C<raw_field>, or a type with immutable
85 values.
86  
87 A type class that does not consume this role must provide
88 C<inflated_is_immutable_for_cache>, and C<clone_inflated> unless it is true or
89 the class provides a true C<inflate_on_each_read>.
90  
91 =head2 Primary key fields
92  
93 A type on a primary key field needs C<canonical_key_value> (see the
94 SYNOPSIS), which this role does not provide. Building the map croaks for a
95 key field whose type lacks it.
96  
97 It returns the string the row cache files the key value under. It gets every
98 form a value can arrive in: database text, an inflated value, or what
99 C<deflate> returned. Every form of one value must give the same string. Keep
100 it fast: it runs for every row read from a table whose key it covers.
101  
102 A field with no type is keyed by its value as it is.
103  
104 =head2 Generated key values
105  
106 A type may provide C<generate_key_value($field, $conn)>, which this role does
107 not. It returns a new inflated value for a primary key field an insert left
108 out. The insert deflates it like any given value. The field's C<generate>
109 hint decides when it is called.
110  
111 L<DBIx::QuickORM::Type::UUID> provides one.
112  
113 =head2 Field hints
114  
115 A field may carry a C<format> code reference beside its type. After the type
116 deflates a value to plain text, the ORM sends what C<format> returns for it.
117 Binary fields are never formatted. Reads and the row cache are unchanged.
118  
119 # CREATE TABLE tokens (token CHAR(36) PRIMARY KEY, note TEXT)
120 # -- a legacy table: UUIDs in upper case
121 my $orm = DBIx::QuickORM->new(
122 credentials => \%credentials,
123 types => {
124 tokens => {
125 token => {
126 class => 'UUID',
127 format => sub { uc $_[0] },
128 },
129 },
130 },
131 );
132  
133 my $id = '0190a6e8-1d2c-7c3b-9f00-123456789abc';
134  
135 # stores 0190A6E8-...
136 my $token = $orm->insert(
137 tokens => {
138 token => $id,
139 note => 'legacy',
140 },
141 );
142  
143 # looks up 0190A6E8-...
144 my $same = $orm->find(
145 tokens => $id,
146 cache => 0,
147 );
148  
149 That gives one field a format. C<type_options> gives one to every field of a
150 type, and a field's own wins:
151  
152 type_options => {UUID => {format => sub { uc $_[0] }}},
153  
154 C<format> must be a code reference, on a field that has a type. C<lc> and
155 C<uc> are built-in functions, so C<\&lc> does not work: write
156 C<sub { lc $_[0] }>, or C<\&CORE::lc> on Perl 5.16 and later.
157  
158 C<generate> says when a primary key field an insert leaves out gets a value
159 from its type's C<generate_key_value> (see L</Generated key values>):
160  
161 =over 4
162  
163 =item C<prefer_db> (the default)
164  
165 When the database does not fill the column itself, or fills it on a backend
166 without C<RETURNING> on insert (MySQL), which could not return the value.
167 Auto-increment integer keys are unaffected: the last insert id reads them.
168  
169 =item C<prefer_orm>
170  
171 Always, even over a database default. Use it when the database's own values
172 are not the ones you want, such as UUIDs of another version.
173  
174 =item C<none>
175  
176 Never. On a backend without C<RETURNING>, a key that is not auto-increment
177 is then unknown after the insert, so call C<insert> in void context or pass
178 the key.
179  
180 =back
181  
182 It is given like C<format>: per field in C<types>, or per type in
183 C<type_options>, such as C<< {UUID => {generate => 'prefer_orm'}} >>.
184  
185 C<prefer_orm> on a column that refuses values (PostgreSQL C<GENERATED ALWAYS
186 AS IDENTITY>) croaks when the map is built. A type without
187 C<generate_key_value> ignores the hint.
188  
189 Whether the database fills a column comes from the scan. A map passed as
190 C<db_map> without those facts reads as "it does not", so C<prefer_db>
191 generates, and the C<prefer_orm> croak cannot fire.
192  
193 =head1 SYNOPSIS
194  
195 package My::Type::Email;
196 use Role::Tiny::With qw/with/;
197 with 'DBIx::QuickORM::Role::Type';
198  
199 # claims fields named email
200 sub matches { my ($class, $name, $field, $dialect) = @_; $name eq 'email' }
201  
202 sub inflate { my ($class, $raw, $field, $conn) = @_; $raw }
203 sub deflate { my ($class, $value, $field, $conn) = @_; lc $value }
204  
205 # needed on a primary key field
206 sub canonical_key_value { my ($class, $value, $field, $conn) = @_; lc $value }
207  
208 sub is_inflated { 1 } # deflate every plain value sent
209 sub inflated_is_immutable_for_cache { 1 } # plain strings: nothing to copy
210  
211 package main;
212  
213 my $orm = DBIx::QuickORM->new(
214 credentials => \%credentials,
215 append_autotype => ['+My::Type::Email'],
216 );
217  
218 my $ann = $orm->insert(
219 users => {
220 name => 'Ann',
221 email => 'Ann@Example.COM',
222 },
223 );
224  
225 my $email = $ann->field('email'); # ann@example.com
226  
227 =head1 REQUIRED METHODS
228  
229 =over 4
230  
231 =item $value = $type->inflate($raw, \%field, $conn)
232  
233 The inflated value for a raw value the database returned.
234  
235 =item $raw = $type->deflate($value, \%field, $conn)
236  
237 The raw value to send to the database for an inflated value.
238  
239 =back
240  
241 =cut
242  
243 78 requires qw/inflate deflate/;
244  
245 =head1 PUBLIC METHODS
246  
247 =over 4
248  
249 =item $bool = $type->is_inflated($value)
250  
251 Whether a plain (non-reference) value is in inflated form and must be
252 deflated before it is sent. Undef by default.
253  
254 True, false, or undef when the type cannot tell. The ORM deflates a plain
255 value only when this is true. A reference is always deflated.
256  
257 =back
258  
259 =cut
260  
261 1 ▶sub is_inflated { undef }
Subroutine is_inflated: called CC=1 SCAR=0.0
Pod documented
262  
263 =pod
264  
265 =over 4
266  
267 =item $bool = $type->inflated_is_immutable_for_cache
268  
269 True when nothing can change an inflated value, so a row may hand every reader
270 the one value it cached. False by default.
271  
272 False means a row must hand out a value of its own: inflated again when
273 C<inflate_on_each_read> is true, otherwise a copy made by C<clone_inflated>.
274  
275 =back
276  
277 =cut
278  
279 38 ▶sub inflated_is_immutable_for_cache { 0 }
Subroutine inflated_is_immutable_for_cache: called CC=1 SCAR=0.0
Pod documented
280  
281 =pod
282  
283 =over 4
284  
285 =item $bool = $type->inflate_on_each_read
286  
287 True when inflating the raw value again is cheaper than copying an inflated
288 one, so a row inflates on every read and caches nothing for the field. False
289 by default.
290  
291 Rows ask it only when C<inflated_is_immutable_for_cache> is false.
292  
293 =back
294  
295 =cut
296  
297 0 ▶sub inflate_on_each_read { 0 }
Subroutine inflate_on_each_read: not called CC=1 SCAR=6.9
Pod documented
298  
299 =pod
300  
301 =over 4
302  
303 =item $bool = $type->inflate_is_identity(\%field)
304  
305 True when C<inflate> returns its input unchanged for the field. False by
306 default.
307  
308 A subclass that overrides C<inflate> must override C<inflate_is_identity> too.
309  
310 The ORM asks once per field when it builds the map and marks such fields
311 C<passthrough> (see L<DBIx::QuickORM::Map>). Reading one then returns the raw
312 value with no C<inflate> call and nothing cached.
313  
314 =back
315  
316 =cut
317  
318 296 ▶sub inflate_is_identity { 0 }
Subroutine inflate_is_identity: called CC=1 SCAR=0.0
Pod documented
319  
320 =pod
321  
322 =over 4
323  
324 =item $copy = $type->clone_inflated($value)
325  
326 A copy of an inflated value that shares nothing changeable with it.
327  
328 Called on the type class with the value, which need not be an object. By
329 default a plain value is returned as it is and a reference is copied with
330 C<dclone> (L<Storable>), croaking when that cannot copy it (code references, for
331 instance).
332  
333 =back
334  
335 =cut
336  
337 8 ▶sub clone_inflated {
Subroutine clone_inflated: called CC=3 SCAR=11.0
Pod documented
338 8 my $class = shift;
339 8 my ($value) = @_;
340 8 ▶ return $value unless ref $value;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value 2 6 8
341  
342 6 my $copy;
343 6 ▶ eval { $copy = Storable::dclone($value); 1 } or croak "$class cannot copy an inflated value with Storable::dclone, so it needs its own clone_inflated() or a true inflated_is_immutable_for_cache(): $@";
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $copy = &Storable::dclone($value); 1 } } or croak("$class cannot copy an inflated value with Storable::dclone, so it needs its own clone_inflated() or a true inflated_is_immutable_for_cache(): $@") 5 1 6
344 5 return $copy;
345 }
346  
347 =head1 PRIVATE METHODS
348  
349 =over 4
350  
351 =item $text = $type->_for_field(\%field)
352  
353 The C<" for table.field"> suffix for a croak about a field: C<" for name">
354 when the record has a C<name> but no C<table>, and empty without a C<name>.
355 Use it as C<< croak "Bad value" . $class->_for_field($field) >>.
356  
357 =back
358  
359 =cut
360  
361 14 ▶sub _for_field {
Subroutine _for_field: called CC=3 SCAR=11.0
362 14 my $class = shift;
363 14 my ($field) = @_;
364 14 ▶ return '' unless $field && defined $field->{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $field and defined $field->{"name"} 8 6 14
Condition100%3/3
$field and defined $field->{"name"}
!ll&&!rl&&r
176
MC/DC100%2/2
$field and defined $field->{"name"}
$field defined $field->{"name"}
Truth table100%3/3
A and B
A= $fieldB= defined $field->{"name"}
ABresult
0X0
100
111
365 6 return ' for ' . join('.' => grep { defined } $field->{table}, $field->{name});
366 }
367  
368 78 1;
369  
370 __END__
« blib/lib/DBIx/QuickORM/Type/JSON.pm ↑ Summary blib/lib/DBIx/QuickORM/WhereBuilder/SQLAbstract.pm »