DBO2/Fields.pm

filter: Statementstmt 10.1% 20 / 197 Branchbran 0.0% 0 / 86 Conditioncond 0.0% 0 / 14 MC/DCmcdc 0.0% 0 / 9 Subroutinesub 8.4% 6 / 71 Podpod 89.1% 33 / 37 totaltotal 14.2% 59 / 414 CC 52 SCAR 32.3
CC
52
Cov
7%
__ANON__
125.3
_column_autodetect
56.0
__ANON__
42.0
CRAP 25.2
↑ Summary DBO2/Record.pm »
1 =head1 NAME
2  
3 DBIx::DBO2::Fields - Construct methods for database fields
4  
5  
6 =head1 SYNOPSIS
7  
8 package MyCDs::Disc;
9
10 use DBIx::DBO2::Record '-isasubclass';
11
12 use DBIx::DBO2::Fields (
13 { name => 'id', field_type => 'number', required => 1 },
14 { name => 'name', field_type => 'string', length => 64, required => 1 },
15 { name => 'year', field_type => 'number' },
16 { name => 'artist', field_type => 'number' },
17 { name => 'genre', field_type => 'number' },
18 );
19
20 1;
21  
22  
23 =head1 DESCRIPTION
24  
25 This package creates methods for DBIx::DBO2::Record objects.
26  
27 It's based on Class::MakeMethods::Template.
28  
29 =head2 Accessing Field Attributes
30  
31 Calling C<-E<gt>fields()> on a class or instance returns a hash of field-name => field-attribute-hash pairs.
32  
33 my %fields = EBiz::Customer::Account->fields();
34 foreach my $fieldname ( sort keys %fields ) {
35 my $field = $fields{ $fieldname };
36 print "$fieldname is a $field->{meta_type} field\n";
37 print " $fieldname is required\n" if ( $field->{required} );
38 print " $fieldname max length $field->{length}\n" if ( $field->{length} );
39 }
40  
41 You can also pass in a field name to retrieve its attributes.
42  
43 print EBiz::Customer::Account->fields('public_id')->{'length'};
44  
45 The results of C<-E<gt>fields()> includes field information inherited from superclasses. To access only those fields declared within a particular class, call C<-E<gt>class_fields()> instead.
46  
47 =cut
48  
49 ########################################################################
50  
51 package DBIx::DBO2::Fields;
52  
53 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
54  
55 1 ▶use Class::MakeMethods::Template;
Subroutine BEGIN: called CC=1 SCAR=0.0
56 1 ▶use base qw( Class::MakeMethods::Template );
Subroutine BEGIN: called CC=1 SCAR=0.0
57  
58 1 ▶use DBIx::SQLEngine::Criteria::Equality;
Subroutine BEGIN: called CC=1 SCAR=0.0
59 1 ▶use DBIx::SQLEngine::Criteria::And;
Subroutine BEGIN: called CC=1 SCAR=0.0
60  
61 ########################################################################
62  
63 0 ▶sub make {
Subroutine make: not called CC=2 SCAR=17.9
Pod documented
64 0 my $callee = shift;
65 0 ▶ if ( ref( $_[0] ) eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[0] eq 'HASH') { } 0 0 0
66 0 $callee->SUPER::make( map { $_->{field_type} => $_ } @_ )
67 } else {
68 0 $callee->SUPER::make( @_ )
69 }
70 }
71  
72 ########################################################################
73  
74 1 my %ClassInfo;
75  
76 0 ▶sub generic {
Subroutine generic: not called CC=1 SCAR=6.4
Pod undocumented
77 {
78 '-import' => { 'Template::Hash:generic' => '*' },
79 'behavior' => {
80 'detect_column_attributes' => q{
81 DBIx::DBO2::Fields::_column_autodetect( _SELF_, $m_info, )
82 if ( $m_info->{column_autodetect} );
83 },
84 0 ▶ -register => sub {
Subroutine __ANON__: not called CC=6 SCAR=36.5
85 0 my $m_info = shift;
86 0 ▶ $ClassInfo{$m_info->{target_class}} ||= {};
Condition0%0/2
$ClassInfo{$m_info->{"target_class"}} ||= {}
l!l
00
MC/DC0%0/1
$ClassInfo{$m_info->{"target_class"}} ||= {}
$ClassInfo{$m_info->{"target_class"}}
Truth table0%0/2
A
A= $ClassInfo{$m_info->{"target_class"}}
Aresult
11
00
87 0 my $target_info = $ClassInfo{$m_info->{target_class}};
88 0 $target_info->{ $m_info->{name} } = $m_info;
89 0 push @{ $target_info->{'-order'} }, $m_info;
90  
91 # warn "Installing field method: " .join(', ', %$m_info ) ."\n";
92
93 0 ▶ if ( my $hooks = $m_info->{'hook'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $hooks = $m_info->{"hook"}) 0 0 0
94 0 ▶ while ( my ( $method, $code ) = each %$hooks ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %$hooks) 0 0 0
95 0 ▶ if ( ref($code) eq 'CODE' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $code eq 'CODE') { } 0 0 0
elsif (not ref $code) { } 0 0 0
96 } elsif ( ! ref($code) ) {
97 0 my $mname = $code;
98 0 $mname =~ s/\*/$m_info->{name}/g;
99 0 ▶ $code = sub { (shift)->$mname() };
Subroutine __ANON__: not called CC=1 SCAR=6.9
100 } else {
101 0 die "Unsurpported Field hook $method => '$code'";
102 }
103 # warn "Installing field hook " . $m_info->{target_class} . "->" . $method . " for $m_info->{name} ($m_info->{method_type}/$m_info->{interface})";
104 0 $m_info->{target_class}->$method(
105 Class::MakeMethods::Composite::Inheritable->Hook( $code )
106 )
107 }
108 }
109
110 return (
111 0 ▶ 'class_fields' => sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
112 0 my $self = shift;
113 0 ▶ ( scalar(@_) == 0 ) ? map { $_->{name}, $_ } @{ $target_info->{'-order'} }:
Branch: 1 branch
BranchTrueFalseTotal
scalar @_ == 1 ? : 0 0 0
114 ( scalar(@_) == 1 ) ? $target_info->{$_[0]} :
115 0 ▶ @{$target_info}{ @_ };
Branch: 1 branch
BranchTrueFalseTotal
scalar @_ == 0 ? : 0 0 0
116 },
117 0 ▶ 'fields' => sub {
Subroutine __ANON__: not called CC=12 SCAR=48.3
118 0 my $self = shift;
119 0 ▶ my @sources = ref($self) || $self;
Condition0%0/3
ref $self || $self
l!l&&r!l&&!r
000
MC/DC0%0/2
ref $self || $self
ref $self $self
Truth table0%0/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
120 0 my @results;
121
122 # Extract field information for all superclasses
123 0 ▶ while ( my $class = shift @sources ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $class = shift @sources) 0 0 0
124 1 ▶ no strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
125 0 push @sources, @{"$class\::ISA"};
126 0 ▶ unshift @results, $class->class_fields()
Branch: 1 branch
BranchTrueFalseTotal
if $class->can("class_fields") 0 0 0
127 if ( $class->can('class_fields') );
128 }
129
130 # Re-definitions in later classes override earlier ones of same name
131 0 my %results = @results;
132
133 # But names are added in order defined, from earlier to later
134 0 my ( @names, %names );
135 0 ▶ while ( scalar @results ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @results) 0 0 0
136 0 my ( $name, $info ) = splice( @results, 0, 2 );
137 0 ▶ push @names, $name unless ( $names{ $name } ++ );
Branch: 1 branch
BranchTrueFalseTotal
unless $names{$name}++ 0 0 0
138 }
139
140 0 foreach my $field ( values %results ) {
141 DBIx::DBO2::Fields::_column_autodetect( $self, $field )
142 0 ▶ if ( $field->{column_autodetect} );
Branch: 1 branch
BranchTrueFalseTotal
if $field->{"column_autodetect"} 0 0 0
143 }
144
145 ( scalar(@_) == 0 ) ?
146 (wantarray ? @results{@names} : [@results{@names}] ) :
147 ( scalar(@_) == 1 ) ? $results{$_[0]} :
148 0 ▶ (wantarray ? @results{ @_ } : [@results{ @_ }] )
Branch: 4 branches
BranchTrueFalseTotal
scalar @_ == 0 ? : 0 0 0
wantarray ? : 0 0 0
scalar @_ == 1 ? : 0 0 0
wantarray ? : 0 0 0
149 },
150 0 ▶ 'field_columns' => sub {
Subroutine __ANON__: not called CC=6 SCAR=37.4
151 0 my $self = shift;
152 0 my @columns;
153 0 foreach my $info ( $self->fields ) {
154 my %colinfo = (
155 name => $info->{hash_key},
156 type => $info->{column_type},
157 ( $info->{length} ? ( length => $info->{length} ) : () ),
158 0 ▶ ( $info->{required} ? ( required => $info->{required} ) : () ),
Branch: 2 branches
BranchTrueFalseTotal
$info->{'length'} ? : 0 0 0
$info->{'required'} ? : 0 0 0
159 );
160 0 ▶ push @columns, \%colinfo if ( $colinfo{type} );
Branch: 1 branch
BranchTrueFalseTotal
if $colinfo{"type"} 0 0 0
161 }
162 0 ▶ wantarray ? @columns : \@columns;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
163 },
164 0 );
165 }
166 },
167 }
168 0 }
169  
170 0 ▶sub scalar {
Subroutine scalar: not called CC=1 SCAR=6.9
Pod undocumented
171 {
172 0 '-import' => { '::DBIx::DBO2::Fields:generic' => '*' },
173 'params' => {
174 'hash_key' => '*',
175 'column_autodetect' => [],
176 },
177 'interface' => {
178 default => { '*'=>'get_set', '*_invalid' => 'invalid' },
179 read_only => { '*'=>'get' },
180 init_and_get => { '*'=>'get_init', -params=>{init_method=>'init_*'} },
181 },
182 'code_expr' => {
183 _VALUE_ => '_SELF_->{_STATIC_ATTR_{hash_key}}',
184 '-import' => { 'Template::Generic:generic' => '*' },
185 },
186 'behavior' => {
187 'get_set' => q{
188 if ( scalar @_ ) {
189 _BEHAVIOR_{set}
190 } else {
191 _BEHAVIOR_{get}
192 }
193 },
194 'get' => q{
195 _GET_VALUE_
196 },
197 'set' => q{
198 _SET_VALUE_{ $_[0] }
199 },
200 'get_init' => q{
201 my $init_method = _ATTR_{'init_method'};
202 _SET_VALUE_{ _SELF_->$init_method( @_ ) } unless ( defined _VALUE_ );
203 _GET_VALUE_;
204 },
205 },
206 }
207 }
208  
209 0 ▶sub _look_for_column {
Subroutine _look_for_column: not called CC=4 SCAR=30.0
210 0 my ($record, $colname) = @_;
211 0 ▶ return unless ( UNIVERSAL::can($record, 'table') );
Branch: 1 branch
BranchTrueFalseTotal
unless UNIVERSAL::can($record, "table") 0 0 0
212 0 my @columns = eval { local $SIG{__DIE__}; $record->table->columns };
213 0 foreach my $column ( @columns ) {
214 0 ▶ return $column if ( $column->name eq $colname );
Branch: 1 branch
BranchTrueFalseTotal
if $column->name eq $colname 0 0 0
215 }
216 }
217  
218 0 ▶sub _column_autodetect {
Subroutine _column_autodetect: not called CC=7 SCAR=40.3
219 0 my ($record, $field) = @_;
220  
221 0 my @attribs = @{ $field->{column_autodetect} };
222 0 my $autocol;
223 0 ▶ while ( scalar @attribs ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @attribs) 0 0 0
224 0 my($name, $default) = (shift(@attribs), shift(@attribs));
225 0 ▶ if ( ! defined $field->{$name} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $field->{$name}) 0 0 0
226 0 ▶ $autocol ||= _look_for_column($record, $field->{hash_key});
Condition0%0/3
$autocol ||= _look_for_column($record, $field->{"hash_key"})
l!l&&r!l&&!r
000
MC/DC0%0/2
$autocol ||= _look_for_column($record, $field->{"hash_key"})
$autocol _look_for_column($record, $field->{"hash_key"})
Truth table0%0/3
A ||= B
A= $autocolB= _look_for_column($record, $field->{"hash_key"})
ABresult
1X1
011
000
227 0 ▶ if ( $autocol and $autocol->can($name) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($autocol and $autocol->can($name)) { } 0 0 0
Condition0%0/3
$autocol and $autocol->can($name)
!ll&&!rl&&r
000
MC/DC0%0/2
$autocol and $autocol->can($name)
$autocol $autocol->can($name)
Truth table0%0/3
A and B
A= $autocolB= $autocol->can($name)
ABresult
0X0
100
111
228 0 $field->{$name} = $autocol->$name();
229 } else {
230 0 ▶ $field->{$name} = defined($default) ? $default : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $default ? : 0 0 0
231 }
232 }
233 }
234 0 delete $field->{column_autodetect};
235 }
236  
237 ########################################################################
238  
239 =head1 STRING FIELDS
240  
241 =head2 Field Type string
242  
243 Generates methods corresponding to a SQL varchar column.
244  
245 =head3 Default Interface
246  
247 The general usage for a string field is:
248  
249 use DBIx::DBO2::Fields (
250 string => 'x',
251 );
252  
253 This declaration will generate methods to support the following interface:
254  
255 =over 4
256  
257 =item *
258  
259 I<$record>-E<gt>x() : I<value>
260  
261 Returns the value of field x for the given record.
262  
263 =item *
264  
265 I<$record>-E<gt>x( I<value> )
266  
267 Sets the value of field x for the given record.
268  
269 =item *
270  
271 I<$record>-E<gt>x_invalid() : I<fieldname> => I<error_message>, ...
272  
273 Check for any error conditions regarding the current value of field x. See Validation, below.
274  
275 =back
276  
277 =head3 Validation
278  
279 String fields provide basic error-checking for required values or text that is too long to fit into the associated database column.
280  
281 You may specify the length of the column and whether a field is required in your field declaration:
282  
283 use DBIx::DBO2::Fields (
284 string => '-required 1 -length 64 x',
285 string => '-required 0 -length 255 y',
286 );
287  
288 If you leave the required and length attributes undefined, an attempt will be made to detect them automatically, by checking the database table associated with the current object for a column whose name matches the field's.
289  
290 use DBIx::DBO2::Fields (
291 string => 'x',
292 string => 'y',
293 );
294  
295 create table xyzzy (
296 x varchar(64) not null,
297 y varchar(255)
298 );
299  
300  
301 =head3 The --init_and_get Interface
302  
303 The string field also supports the following declaration for values which only need to be calculated once:
304  
305 use DBIx::DBO2::Fields (
306 string => '--init_and_get x',
307 );
308  
309 =over 4
310  
311 =item *
312  
313 I<$record>-E<gt>x() : I<value>
314  
315 Returns the value of field x for the given record.
316  
317 If the value of field x is undefined, it first calls an initialization method and stores the result. The default it to call a method named init_x, but you can override this by providing a different value for the init_method attribute.
318  
319 use DBIx::DBO2::Fields (
320 string => '--init_and_get -init_method find_spot x',
321 );
322  
323 Or equivalently, and perhaps more readably:
324  
325 use DBIx::DBO2::Fields (
326 string => [ '--init_and_get', x, { init_method => 'find_spot' } ],
327 );
328  
329 =back
330  
331 =cut
332  
333 0 ▶sub string {
Subroutine string: not called CC=1 SCAR=6.9
Pod documented
334 {
335 0 '-import' => { '::DBIx::DBO2::Fields:scalar' => '*' },
336 'params' => {
337 'length' => undef,
338 'required' => undef,
339 'column_type' => 'text',
340 'column_autodetect' => [ 'required', 0, 'length', 0 ],
341 },
342 'behavior' => {
343 'set' => q{
344 Carp::carp "Setting " . _ATTR_{name} . " to object value"
345 if ( ref $_[0] );
346 _SET_VALUE_{ "$_[0]" };
347 },
348 'invalid' => q{
349 _BEHAVIOR_{detect_column_attributes}
350 my $value = _GET_VALUE_;
351 if ( _ATTR_{required} and ! length( $value ) ) {
352 return _ATTR_{name} => "This field can not be left empty."
353 }
354 if ( my $length = _ATTR_{length} ) {
355 return _ATTR_{name} => "This field can not hold more than " .
356 "$length characters." if ( length( $value ) > $length );
357 }
358 return;
359 },
360 },
361 }
362 }
363  
364  
365 ########################################################################
366  
367 =head2 Field Type binary
368  
369 Identical to the string type, except that it specifies a binary column_type for the underlying SQL DBMS column, allowing DBIx::SQLEngine to produce a platform-specific data type such as C<blob> or C<bytea>.
370  
371 =cut
372  
373 0 ▶sub binary {
Subroutine binary: not called CC=1 SCAR=6.9
Pod documented
374 {
375 0 '-import' => { '::DBIx::DBO2::Fields:string' => '*' },
376 'params' => {
377 'length' => 65536,
378 'column_type' => 'binary',
379 },
380 }
381 }
382  
383 ########################################################################
384  
385 =head1 STRUCTURED TEXT FIELDS
386  
387 =head2 Field Type phone_number
388  
389 Identical to the string type except for validation.
390  
391 =cut
392  
393 0 ▶sub phone_number {
Subroutine phone_number: not called CC=1 SCAR=6.9
Pod documented
394 {
395 0 '-import' => { '::DBIx::DBO2::Fields:string' => '*' },
396 'code_expr' => {
397 _QUANTITY_CLASS_ => 'EBiz::Postal::Address',
398 },
399 'behavior' => {
400 'invalid' => q{
401 _BEHAVIOR_{detect_column_attributes}
402 my $value = _GET_VALUE_;
403 if ( _ATTR_{required} and ! length( $value ) ) {
404 return _ATTR_{name} => "This field can not be left empty."
405 }
406 if ( $value ) {
407 my $error_msg = _QUANTITY_CLASS_->invalid_phone($value);
408 $value =~ s/\D+//g;
409 if ( length($value) < 7 ) {
410 return _ATTR_{name} => 'This is to short to be a phone number.'
411 } elsif ( length($value) < 10 ) {
412 return _ATTR_{name} => 'Please include your area code.';
413 }
414 }
415 if ( my $length = _ATTR_{length} ) {
416 return _ATTR_{name} => "This field can not hold more than " .
417 "$length characters." if ( length( $value ) > $length );
418 }
419 return;
420 },
421 },
422 }
423 }
424  
425 =head2 Field Type post_code
426  
427 Identical to the string type except for validation.
428  
429 =cut
430  
431 0 ▶sub post_code {
Subroutine post_code: not called CC=1 SCAR=6.9
Pod documented
432 {
433 0 '-import' => { '::DBIx::DBO2::Fields:string' => '*' },
434 'code_expr' => {
435 _QUANTITY_CLASS_ => 'EBiz::Postal::Address',
436 },
437 'behavior' => {
438 'invalid' => q{
439 _BEHAVIOR_{detect_column_attributes}
440 my $value = _GET_VALUE_;
441 if ( _ATTR_{required} and ! length( $value ) ) {
442 return _ATTR_{name} => "This field can not be left empty."
443 }
444 if ( $value ) {
445 my $error_msg = $self->invalid_postcode($value);
446 return _ATTR_{name} => $error_msg if $error_msg;
447 }
448 if ( my $length = _ATTR_{length} ) {
449 return _ATTR_{name} => "This field can not hold more than " .
450 "$length characters." if ( length( $value ) > $length );
451 }
452 return;
453 },
454 },
455 }
456 }
457  
458 =head2 Field Type state_province
459  
460 Identical to the string type except for validation.
461  
462 =cut
463  
464 0 ▶sub state_province {
Subroutine state_province: not called CC=1 SCAR=6.9
Pod documented
465 {
466 0 '-import' => { '::DBIx::DBO2::Fields:string' => '*' },
467 'code_expr' => {
468 _QUANTITY_CLASS_ => 'EBiz::Postal::Address',
469 },
470 'behavior' => {
471 'set' => q{
472 Carp::carp "Setting " . _ATTR_{name} . " to canonical value";
473 if ($self->state_object( $_[0] )) {
474 _SET_VALUE_{ $self->state_object( $_[0] )->id };
475 } else {
476 _SET_VALUE_{ $_[0] };
477 }
478 },
479 'invalid' => q{
480 _BEHAVIOR_{detect_column_attributes}
481 my $value = _GET_VALUE_;
482 if ( _ATTR_{required} and ! length( $value ) ) {
483 return _ATTR_{name} => "This field can not be left empty."
484 }
485 if ( $value ) {
486 my $error_msg = $self->invalid_state($value);
487 return _ATTR_{name} => $error_msg if $error_msg;
488 }
489 if ( my $length = _ATTR_{length} ) {
490 return _ATTR_{name} => "This field can not hold more than " .
491 "$length characters." if ( length( $value ) > $length );
492 }
493 return;
494 },
495 },
496 }
497 }
498  
499 =head2 Field Type email_addr
500  
501 Identical to the string type except for validation.
502  
503 =cut
504  
505 0 ▶sub email_addr {
Subroutine email_addr: not called CC=1 SCAR=6.9
Pod documented
506 {
507 0 '-import' => { '::DBIx::DBO2::Fields:string' => '*' },
508 'behavior' => {
509 'invalid' => q{
510 _BEHAVIOR_{detect_column_attributes}
511 my $value = _GET_VALUE_;
512  
513 if ( _ATTR_{required} and ! length( $value ) ) {
514 return _ATTR_{name} => "This field can not be left empty."
515 }
516 if ( $value ) {
517 my $error_msg = DBIx::DBO2::Fields::invalid_email_address(_GET_VALUE_);
518 return _ATTR_{name} => $error_msg if $error_msg;
519 }
520 return;
521 },
522 }
523 }
524 }
525  
526 ## Validation
527  
528 # $boolean = invalid_email_address()
529 0 ▶sub invalid_email_address {
Subroutine invalid_email_address: not called CC=4 SCAR=30.0
Pod undocumented
530 0 my $email = shift;
531 0 require Net::DNS;
532 0 ▶ return 'This does not appear to be a valid e-mail address.'
Branch: 1 branch
BranchTrueFalseTotal
unless $email =~ /^([\w\.-]+)\@([\w\.-]+)$/o 0 0 0
533 unless $email =~ /^([\w\.-]+)\@([\w\.-]+)$/o;
534 0 my($User, $Host) = ($1, $2);
535 0 ▶ return 'This does not appear to be a valid e-mail domain.'
Branch: 1 branch
BranchTrueFalseTotal
unless defined Net::DNS::mx($Host) or defined gethostbyname $Host 0 0 0
Condition0%0/3
defined Net::DNS::mx($Host) or defined gethostbyname $Host
l!l&&r!l&&!r
000
MC/DC0%0/2
defined Net::DNS::mx($Host) or defined gethostbyname $Host
defined Net::DNS::mx($Host) defined gethostbyname $Host
Truth table0%0/3
A or B
A= defined Net::DNS::mx($Host)B= defined gethostbyname $Host
ABresult
1X1
011
000
536 unless ( defined(Net::DNS::mx($Host)) or defined(gethostbyname($Host)) );
537 0 return;
538 }
539  
540 ########################################################################
541  
542 =head2 Field Type creditcardnumber
543  
544 If you declare the following:
545  
546 use DBIx::DBO2::Fields (
547 creditcardnumber => "ccnum",
548 );
549  
550 You can now use these methods:
551  
552 # Set and get raw value
553 $customer->ccnum('4242424242424242');
554 $customer->ccnum() eq '4242424242424242';
555  
556 # Analyze card number
557 $customer->ccnum_checksum() == 1;
558 $customer->ccnum_flavor() eq 'VISA card';
559  
560 # Opaque readable value for display
561 $customer->ccnum_readable() eq '************4242';
562  
563 # Setting the readable value to the prior opaque value has no effect
564 $customer->ccnum_readable('************4242');
565 $customer->ccnum() eq '4242424242424242';
566  
567 # But setting the readable value to another value overwrites the contents
568 $customer->ccnum_readable('1234-5678-9101-1213');
569 $customer->ccnum() eq '1234-5678-9101-1213';
570  
571 # Recognize bogus cards by the following characteristics...
572 $customer->ccnum_checksum() == 0;
573 $customer->ccnum_flavor() eq 'Unrecognized';
574 $customer->ccnum_readable() eq '1234-5678-9101-1213';
575  
576 B<DEPENDCIES:> Note that this type of field requires the following modules: Data::Quantity::Finance::CreditCardNumber.
577  
578 =cut
579  
580 0 ▶sub creditcardnumber {
Subroutine creditcardnumber: not called CC=1 SCAR=6.9
Pod documented
581 {
582 '-import' => { '::DBIx::DBO2::Fields:number' => '*' },
583 'interface' => {
584 default => {
585 '*'=>'get_set',
586 # 'clear_*'=>'clear',
587 '*_readable'=>'readable',
588 '*_flavor'=>'flavor',
589 '*_invalid'=>'invalid',
590 '*_checksum'=>'checksum',
591 },
592 },
593 'code_expr' => {
594 _QUANTITY_CLASS_ => 'Data::Quantity::Finance::CreditCardNumber',
595 },
596 'behavior' => {
597 0 ▶ '-init' => [ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
598 0 require Data::Quantity::Finance::CreditCardNumber;
599 0 return;
600 0 } ],
601 'get' => q{
602 my $value = _GET_VALUE_;
603 length($value) ? sprintf( '%.0f', $value ) : undef;
604 },
605 'set' => q{
606 _SET_VALUE_{ _QUANTITY_CLASS_->new( shift() )->value }
607 },
608 'readable' => q {
609 if ( scalar @_ ) {
610 # warn "in readable, got input";
611 my $value = shift;
612 if ( ! length( $value ) ) {
613 _SET_VALUE_{ undef }
614 } elsif ( $value ne _QUANTITY_CLASS_->readable_value(_GET_VALUE_) ) {
615 # warn "in readable, setting input to '$value' for " . _QUANTITY_CLASS_->readable_value(_GET_VALUE_) . ' aka ' . (_GET_VALUE_ + 0);
616 _SET_VALUE_{ _QUANTITY_CLASS_->new( $value )->value }
617 }
618 } else {
619 # warn "in readable, didn't get input";
620 _QUANTITY_CLASS_->readable_value(_GET_VALUE_)
621 }
622 },
623 'flavor' => q {
624 _QUANTITY_CLASS_->flavor_value(_GET_VALUE_)
625 },
626 'checksum' => q {
627 _QUANTITY_CLASS_->checksum_value(_GET_VALUE_)
628 },
629 'invalid' => q{
630 _BEHAVIOR_{detect_column_attributes}
631 for ( _GET_VALUE_ ) {
632 if ( _ATTR_{required} and ! length( $_ ) ) {
633 return _ATTR_{name} => "This field can not be left empty."
634 }
635 if ( my $length = _ATTR_{length} ) {
636 return _ATTR_{name} => "Number must not be longer than ".
637 "$length characters." if ( length( $_ ) > $length );
638 }
639 if ( length $_ ) {
640 return _ATTR_{name} => "This does not appear to be a valid credit card number." unless ( _QUANTITY_CLASS_->checksum_value($_) );
641 }
642 }
643 return;
644 },
645 },
646 }
647 }
648  
649 ########################################################################
650  
651 =head1 NUMERIC QUANTITY FIELDS
652  
653 =head2 Field Type number
654  
655 Generates methods corresponding to a SQL int or float column.
656  
657 The general usage for a number field is:
658  
659 use DBIx::DBO2::Fields (
660 number => 'x',
661 );
662  
663 This declaration will generate methods to support the following interface:
664  
665 =over 4
666  
667 =item *
668  
669 I<$record>-E<gt>x() : I<value>
670  
671 Returns the value of field x for the given record.
672  
673 =item *
674  
675 I<$record>-E<gt>x( I<value> )
676  
677 Sets the value of field x for the given record.
678  
679 =item *
680  
681 I<$record>-E<gt>x_readable() : I<value>
682  
683 Returns the value of field x for the given record formatted for display, including commas for thousands separators.
684  
685 =item *
686  
687 I<$record>-E<gt>x_readable( I<value> )
688  
689 Sets the value of field x for the given record from a possibly formatted value.
690  
691 =item *
692  
693 I<$record>-E<gt>x_invalid() : I<fieldname> => I<error_message>, ...
694  
695 Check for any error conditions regarding the current value of field x. See Validation, below.
696  
697 =back
698  
699 =head3 Validation
700  
701 Number fields provide error-checking for required values or values which are not numeric.
702  
703 You may specify whether a field is required or allow this to be detected based on whether the corresponding database column allows null values.
704  
705 =head3 The -init_and_get Interface
706  
707 The number field also supports the -init_and_get provided by the string field type.
708  
709 B<DEPENDCIES:> Note that this type of field requires the following modules: Data::Quantity::Number::Number.
710  
711 =cut
712  
713 0 ▶sub number {
Subroutine number: not called CC=1 SCAR=6.9
Pod documented
714 {
715 '-import' => { '::DBIx::DBO2::Fields:scalar' => '*' },
716 'params' => {
717 'required' => '0',
718 'column_type' => 'int',
719 'column_autodetect' => [ 'required', 0, ],
720 },
721 'code_expr' => {
722 _QUANTITY_CLASS_ => 'Data::Quantity::Number::Number',
723 },
724 'interface' => {
725 default => { '*'=>'get_set', '*_readable' => 'readable', '*_invalid' => 'invalid' },
726 read_only => { '*'=>'get' },
727 init_and_get => { '*'=>'get_init', -params=>{init_method=>'init_*'} },
728 },
729 'behavior' => {
730 0 ▶ '-init' => [ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
731 0 require Data::Quantity::Number::Number;
732 0 return;
733 0 } ],
734 'get' => q{
735 for ( _GET_VALUE_ ) { return ( length($_) ? $_ + 0 : $_ ) }
736 },
737 'set' => q{
738 Carp::carp "Setting " . _ATTR_{name} . " to non-numeric value"
739 if ( ref $_[0] or $_[0] =~ /[^\d\-\.]/ );
740 _SET_VALUE_{ length($_[0]) ? $_[0] + 0 : $_[0] };
741 },
742 'invalid' => q{
743 _BEHAVIOR_{detect_column_attributes}
744 for ( _GET_VALUE_ ) {
745 if ( ref $_[0] or $_[0] =~ /[^\d\-\.]/ ) {
746 return _ATTR_{name} => " can only contain numeric values."
747 }
748 if ( _ATTR_{required} and ! length( $_ ) ) {
749 return _ATTR_{name} => "This field can not be left empty."
750 }
751 }
752 return;
753 },
754 'readable' => q {
755 if ( scalar @_ ) {
756 _SET_VALUE_{ _QUANTITY_CLASS_->new( @_ )->value }
757 } else {
758 _QUANTITY_CLASS_->readable_value(_GET_VALUE_ + 0)
759 }
760 },
761 },
762 }
763 }
764  
765 ########################################################################
766  
767 0 ▶sub time_absolute {
Subroutine time_absolute: not called CC=1 SCAR=6.9
Pod undocumented
768 {
769 0 '-import' => { '::DBIx::DBO2::Fields:number' => '*' },
770 'interface' => {
771 default => {
772 '*'=>'get_set',
773 'touch_*'=>'set_current',
774 '*_obj'=>'get_obj',
775 '*_readable'=>'readable'
776 },
777 created => {
778 -base => 'default',
779 -params => {
780 hook => { post_new => 'touch_*' }
781 },
782 },
783 modified => {
784 -base => 'default',
785 -params => {
786 hook => { pre_insert => 'touch_*', pre_update => 'touch_*'}
787 },
788 },
789 },
790 'params' => {
791 'default_readable_format' => undef,
792 },
793 'code_expr' => {
794 _QUANTITY_CLASS_ => 'croak "Abstract code_expr should contain Quantity"',
795 },
796 'behavior' => {
797 'set_current' => q{
798 _SET_VALUE_{ _QUANTITY_CLASS_->current()->value };
799 # warn "Setting time for " . _ATTR_{name};
800 },
801 'set' => q{
802 _SET_VALUE_{ _QUANTITY_CLASS_->new( shift() )->value }
803 },
804 'get_obj' => q{
805 _QUANTITY_CLASS_->new( _GET_VALUE_ )
806 },
807 'readable' => q{
808 _QUANTITY_CLASS_->new(_GET_VALUE_)->readable(
809 scalar( @_ ) ? shift() : _ATTR_{default_readable_format}
810 )
811 },
812 },
813 }
814 }
815  
816 =head2 Field Type timestamp
817  
818 Generates methods corresponding to a SQL int column storing a date and time in Unix seconds-since-1970 format.
819  
820 =head3 Default Interface
821  
822 The general usage for a timestamp field is:
823  
824 use DBIx::DBO2::Fields (
825 timestamp => 'x',
826 );
827  
828 This declaration will generate methods to support the following interface:
829  
830 =over 4
831  
832 =item *
833  
834 I<$record>-E<gt>x() : I<value>
835  
836 Returns the raw numeric value of field x for the given record.
837  
838 =item *
839  
840 I<$record>-E<gt>x( I<value> )
841  
842 I<$record>-E<gt>x( I<readable_value> )
843  
844 Sets the value of field x for the given record. You may provide either a raw numeric value or a human-entered formatted value.
845  
846 =item *
847  
848 I<$record>-E<gt>touch_x()
849  
850 Sets the value of field x to the current date and time.
851  
852 =item *
853  
854 I<$record>-E<gt>x_readable() : I<readable_value>
855  
856 Returns the value of field x formatted for display.
857  
858 =item *
859  
860 I<$record>-E<gt>x_readable(I<format_string>) : I<readable_value>
861  
862 Returns the value of field x formatted in particular way. (See L<Data::Quantity::Time::Timestamp> for supported formats.)
863  
864 =item *
865  
866 I<$record>-E<gt>x_obj() : I<quantity_object>
867  
868 Gets the value of field x as a Data::Quantity::Time::Timestamp object.
869  
870 =item *
871  
872 I<$record>-E<gt>x_invalid() : I<fieldname> => I<error_message>, ...
873  
874 Inherited from the number field.
875  
876 =back
877  
878 B<DEPENDCIES:> Note that this type of field requires the following modules: Data::Quantity::Time::Timestamp.
879  
880 =cut
881  
882  
883 0 ▶sub timestamp {
Subroutine timestamp: not called CC=1 SCAR=6.9
Pod documented
884 {
885 '-import' => { '::DBIx::DBO2::Fields:time_absolute' => '*' },
886 'code_expr' => {
887 _QUANTITY_CLASS_ => 'Data::Quantity::Time::Timestamp',
888 },
889 'behavior' => {
890 0 ▶ '-init' => [ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
891 0 require Data::Quantity::Time::Timestamp;
892 0 return;
893 0 } ],
894 },
895 }
896 }
897  
898  
899 =head2 Field Type julian_day
900  
901 Generates methods corresponding to a SQL int column storing a date in the Julian days-since-the-invention-of-fire format.
902  
903 =head3 Default Interface
904  
905 The general usage for a julian_day field is:
906  
907 use DBIx::DBO2::Fields (
908 julian_day => 'x',
909 );
910  
911 This declaration will generate methods to support the following interface:
912  
913 =over 4
914  
915 =item *
916  
917 I<$record>-E<gt>x() : I<value>
918  
919 Returns the raw numeric value of field x for the given record.
920  
921 =item *
922  
923 I<$record>-E<gt>x( I<value> )
924  
925 I<$record>-E<gt>x( I<readable_value> )
926  
927 Sets the value of field x for the given record. You may provide either a raw numeric value or a human-entered formatted value.
928  
929 =item *
930  
931 I<$record>-E<gt>touch_x()
932  
933 Sets the value of field x to the current date.
934  
935 =item *
936  
937 I<$record>-E<gt>x_readable() : I<readable_value>
938  
939 Returns the value of field x formatted for display.
940  
941 =item *
942  
943 I<$record>-E<gt>x_readable(I<format_string>) : I<readable_value>
944  
945 Returns the value of field x formatted in particular way. (See L<Data::Quantity::Time::Date> for supported formats.)
946  
947 =item *
948  
949 I<$record>-E<gt>x_obj() : I<quantity_object>
950  
951 Gets the value of field x as a Data::Quantity::Time::Date object.
952  
953 =item *
954  
955 I<$record>-E<gt>x_invalid() : I<fieldname> => I<error_message>, ...
956  
957 Inherited from the number field.
958  
959 =back
960  
961 B<DEPENDCIES:> Note that this type of field requires the following modules: Data::Quantity::Time::Date.
962  
963 =cut
964  
965 0 ▶sub julian_day {
Subroutine julian_day: not called CC=1 SCAR=6.9
Pod documented
966 {
967 '-import' => { '::DBIx::DBO2::Fields:time_absolute' => '*' },
968 'params' => {
969 'default_readable_format' => 'mm/dd/yyyy',
970 },
971 'code_expr' => {
972 _QUANTITY_CLASS_ => 'Data::Quantity::Time::Date',
973 },
974 'behavior' => {
975 0 ▶ '-init' => [ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
976 0 require Data::Quantity::Time::Date;
977 0 return;
978 0 } ],
979 },
980 }
981 }
982  
983 ########################################################################
984  
985  
986 =head2 Field Type currency_uspennies
987  
988 Generates methods corresponding to a SQL int column storing a US currency value in pennies.
989  
990 =head3 Default Interface
991  
992 The general usage for a currency_uspennies field is:
993  
994 use DBIx::DBO2::Fields (
995 currency_uspennies => 'x',
996 );
997  
998 This declaration will generate methods to support the following interface:
999  
1000 =over 4
1001  
1002 =item *
1003  
1004 I<$record>-E<gt>x() : I<value>
1005  
1006 Returns the raw numeric value of field x for the given record.
1007  
1008 =item *
1009  
1010 I<$record>-E<gt>x( I<value> )
1011  
1012 Sets the raw numeric value of field x for the given record.
1013  
1014 =item *
1015  
1016 I<$record>-E<gt>x_readable() : I<readable_value>
1017  
1018 Returns the value of field x formatted for display.
1019  
1020 =item *
1021  
1022 I<$record>-E<gt>x_readable(I<readable_value>)
1023  
1024 Set the value of x based on a human-entered value
1025  
1026 =item *
1027  
1028 I<$record>-E<gt>x_invalid() : I<fieldname> => I<error_message>, ...
1029  
1030 Inherited from the number field.
1031  
1032 =back
1033  
1034 B<DEPENDCIES:> Note that this type of field requires the following modules: Data::Quantity::Finance::Currency.
1035  
1036 =cut
1037  
1038 0 ▶sub currency_uspennies {
Subroutine currency_uspennies: not called CC=1 SCAR=6.9
Pod documented
1039 {
1040 '-import' => { '::DBIx::DBO2::Fields:number' => '*' },
1041 'interface' => {
1042 default => { '*'=>'get_set', '*_readable'=>'readable' },
1043 },
1044 'code_expr' => {
1045 _QUANTITY_CLASS_ => 'Data::Quantity::Finance::Currency->type("USD")',
1046 },
1047 'behavior' => {
1048 0 ▶ '-init' => [ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1049 0 require Data::Quantity::Finance::Currency;
1050 0 return;
1051 0 } ],
1052 'set' => q{
1053 _SET_VALUE_{ _QUANTITY_CLASS_->new( shift() )->value }
1054 },
1055 'readable' => q {
1056 if ( scalar @_ ) {
1057 my $value = shift;
1058 if ( ! length( $value ) ) {
1059 _SET_VALUE_{ undef }
1060 } else {
1061 # Stick $ on front if not there already, so Q::C knows it's not raw
1062 # warn "INPUT VALUE $value";
1063 $value = '$' . $value if ( $value =~ m/\A\-?\d/ );
1064 # warn "VALUE $value CLASS VALUE " . _QUANTITY_CLASS_->new( $value )->value;
1065 _SET_VALUE_{ _QUANTITY_CLASS_->new( $value )->value }
1066 }
1067 } else {
1068 _QUANTITY_CLASS_->readable_value(_GET_VALUE_)
1069 }
1070 },
1071 },
1072 }
1073 }
1074  
1075 ########################################################################
1076  
1077 =head2 Field Type saved_total
1078  
1079 Used to store numeric values which only have to be calculated when the related records change.
1080  
1081 A declaration of
1082  
1083 use DBIx::DBO2::Fields (
1084 saved_total => 'x',
1085 reset_checker => 'status_is_cart',
1086 );
1087  
1088 Is equivalent to the following method definitions:
1089  
1090 # Recalculate if status_is_cart; else return previously stored value
1091 sub x {
1092 my $self = shift;
1093 if ( $self->status_is_cart() ) {
1094 $self->{x} = $self->init_x();
1095 } else {
1096 $self->{x};
1097 }
1098 }
1099
1100 # Recalculate and store the value.
1101 sub reset_x {
1102 my $self = shift;
1103 $self->{x} = $self->init_x();
1104 }
1105
1106 # Is our stored value out of synch with current calculations?
1107 sub x_difference {
1108 my $self = shift;
1109 $self->init_x() - $self->{x};
1110 }
1111  
1112 You are expected to provide an 'init_x' method which calculates and returns the value, but does not save it.
1113  
1114 =cut
1115  
1116 0 ▶sub saved_total {
Subroutine saved_total: not called CC=1 SCAR=6.9
Pod documented
1117 {
1118 0 '-import' => { '::DBIx::DBO2::Fields:number' => '*' },
1119 'interface' => {
1120 default => {
1121 '*' => 'get_or_init_or_set',
1122 'reset_*' => 'reset',
1123 '*_difference' => 'difference',
1124 },
1125 },
1126 'params' => {
1127 'hash_key' => '*',
1128 'reset_checker' => '',
1129 'init_method' => 'init_*',
1130 },
1131 'code_expr' => {
1132 },
1133 'behavior' => {
1134 'get_or_init' => q{
1135 my $check_method = _ATTR_{reset_checker};
1136 my $value = _GET_VALUE_;
1137 if ( ! length $value or $check_method and $self->$check_method() ) {
1138 _BEHAVIOR_{reset}
1139 } else {
1140 $value;
1141 }
1142 },
1143 'get_or_init_or_set' => q{
1144 if ( scalar @_ ) {
1145 _BEHAVIOR_{set}
1146 } else {
1147 my $check_method = _ATTR_{reset_checker};
1148 my $value = _GET_VALUE_;
1149 if ( ! length $value or $check_method and $self->$check_method() ) {
1150 _BEHAVIOR_{reset}
1151 } else {
1152 $value;
1153 }
1154 }
1155 },
1156 'reset' => q{
1157 my $init_method = _ATTR_{init_method};
1158 _SET_VALUE_{ $self->$init_method() };
1159 },
1160 'difference' => q{
1161 my $init_method = _ATTR_{init_method};
1162 $self->$init_method() - _GET_VALUE_;
1163 },
1164 },
1165 }
1166 }
1167  
1168 =head2 Field Type saved_total_uspennies
1169  
1170 Like saved_total, but also has a read-only *_readable method that provides US Currency formatting.
1171  
1172 =cut
1173  
1174 0 ▶sub saved_total_uspennies {
Subroutine saved_total_uspennies: not called CC=1 SCAR=6.9
Pod documented
1175 {
1176 0 '-import' => { '::DBIx::DBO2::Fields:saved_total' => '*' },
1177 'interface' => {
1178 default => {
1179 '*' => 'get_or_init_or_set',
1180 'set_*' => 'set',
1181 'reset_*' => 'reset',
1182 '*_difference' => 'difference',
1183 '*_readable' => 'readable',
1184 },
1185 },
1186 'params' => {
1187 'hash_key' => '*',
1188 'reset_checker' => '',
1189 'init_method' => 'init_*',
1190 },
1191 'code_expr' => {
1192 _QUANTITY_CLASS_ => 'Data::Quantity::Finance::Currency->type("USD")',
1193 },
1194 'behavior' => {
1195 'set' => q{
1196 _SET_VALUE_{ _QUANTITY_CLASS_->new( @_ )->value }
1197 },
1198 'reset' => q{
1199 my $init_method = _ATTR_{init_method};
1200 _SET_VALUE_{ int( $self->$init_method() ) };
1201 },
1202 'difference' => q{
1203 my $init_method = _ATTR_{init_method};
1204 $self->$init_method() - _GET_VALUE_;
1205 },
1206 'readable' => q{
1207 my $check_method = _ATTR_{reset_checker};
1208 my $value = _GET_VALUE_;
1209 if ( ! length $value or $check_method and $self->$check_method() ) {
1210 _BEHAVIOR_{reset}
1211 $value = _GET_VALUE_;
1212 } else {
1213 $value;
1214 }
1215 _QUANTITY_CLASS_->readable_value( $value )
1216 },
1217 },
1218 }
1219 }
1220  
1221 ########################################################################
1222  
1223 =head1 ID AND RELATIONAL FIELDS
1224  
1225 =head2 Field Type sequential
1226  
1227 Represents an auto-incrementing or database-assigned sequential value that forms the primarily for a table.
1228  
1229 It is expected that you'll only have one of these per class.
1230  
1231 =cut
1232  
1233 0 ▶sub sequential {
Subroutine sequential: not called CC=1 SCAR=6.9
Pod documented
1234 {
1235 0 '-import' => { '::DBIx::DBO2::Fields:number' => '*' },
1236 'params' => {
1237 'column_type' => 'sequential',
1238 'required' => 1,
1239 }
1240 }
1241 }
1242  
1243  
1244 =head2 Field Type unique_code
1245  
1246 Used to generate and store a unique code for this object.
1247  
1248 The identifiers generally look like 'QX3P6N' or the like -- a mix of the digits from 0 to 9 and upper case consonants (skipping the vowels to avoid confusion between 0/O and 1/I, and to avoid constructing real words). The size is controlled by the "length" meta-method attribute.
1249  
1250 Here's a sample declaration:
1251  
1252 package Acme::Order::Order;
1253 use DBIx::DBO2::Fields (
1254 "unique_code --length 6 => 'public_id',
1255 );
1256  
1257 This field is automatically assigned and confirmed to be unique when the record is inserted.
1258  
1259 Here's how you retrieve a specific row:
1260  
1261 my $pubid = 'QX3P6N';
1262 $order = Acme::Order::Order->fetch_public_id( $pubid );
1263  
1264 With 31 possible characters, a length of 2 gives almost a thousand chocies, 4 gives almost a million, 6 gives almost a billion, and 8 gives 852 billion, or almost a trillion possible choices.
1265  
1266 Note that you'll want to have many more choices than you are actually going to use, both to avoid conflicts and to prevent guessing.
1267  
1268 B<DEPENDCIES:> Note that if you use the "dated" parameter, this type of field requires the following module: Time::JulianDay.
1269  
1270 =cut
1271  
1272 0 ▶sub unique_code {
Subroutine unique_code: not called CC=1 SCAR=6.9
Pod documented
1273 {
1274 '-import' => { '::DBIx::DBO2::Fields:string' => '*' },
1275 'params' => {
1276 length => 6,
1277 # chars => [ grep { 'AEIOU' !~ /$_/ } ( 'A'..'Z') ],
1278 0 chars => [ (0 .. 9), grep { 'AEIOU' !~ /$_/ } ( 'A'..'Z') ],
1279 0 date_chars => [ grep { 'AEIOU' !~ /$_/ } ( 'A'..'Z') ],
1280 hook => { pre_insert=>'assign_*' },
1281 prohibited => '^\\d+$',
1282 },
1283 'interface' => {
1284 default => { '*'=>'get_set', 'assign_*'=>'assign',
1285 'generate_*'=>'generate', 'fetch_*'=>'fetch' },
1286 },
1287 'behavior' => {
1288 assign => q{
1289 return if ( _GET_VALUE_ );
1290 my $generator = 'generate_' . _STATIC_ATTR_{name};
1291 my $fetcher = 'fetch_' . _STATIC_ATTR_{name};
1292 do {
1293 _SET_VALUE_{ $self->$generator() };
1294 } while (
1295 $self->table->count_rows({ _STATIC_ATTR_{hash_key} => _GET_VALUE_ })
1296 );
1297 },
1298 generate => q{
1299 my $char = _STATIC_ATTR_{chars};
1300 my $date_char = _STATIC_ATTR_{date_chars};
1301 my $dated = _STATIC_ATTR_{dated} || 0;
1302 my $length = _STATIC_ATTR_{length};
1303 $length -= 4 if ( $dated );
1304 my $prohibited_rx = _STATIC_ATTR_{prohibited};
1305 if ( $length < 1 ) {
1306 Carp::confess("Unable to generate unique_code: field length is misisng or insufficient")
1307 }
1308 my $code;
1309 do {
1310 $code = '';
1311 if ( $dated ) {
1312 require Time::JulianDay;
1313 my $today = Time::JulianDay::local_julian_day(time);
1314 my $incr = $today - $dated;
1315 my $charcnt = scalar(@$date_char);
1316 while ( $incr > 0 ) {
1317 use integer;
1318 my $diff = $incr % $charcnt;
1319 $incr = int( $incr / $charcnt );
1320 $code = $date_char->[ $diff ] . $code;
1321 }
1322 if ( my $length = length($code) and length($code) < 3 ) {
1323 $code = ( $date_char->[0] x ( 3 - $length ) ) . $code;
1324 }
1325 if ( length($code) ) {
1326 $code .= '-';
1327 }
1328 }
1329 foreach (1 .. $length ) {
1330 $code .= $char->[ rand( scalar(@$char) ) ];
1331 }
1332 # Don't generate all-numeric codes
1333 } until ( $code and ! $prohibited_rx or $code !~ /$prohibited_rx/ );
1334 return $code;
1335 },
1336 fetch => q{
1337 my $value = shift()
1338 or return;
1339 $self->fetch_one(criteria => { _STATIC_ATTR_{hash_key} => $value });
1340 },
1341 },
1342 }
1343 }
1344  
1345 ########################################################################
1346  
1347 =head2 Field Type foreign_key
1348  
1349 Generates methods corresponding to a SQL int or varchar column storing a value which corresponds to the primary key of a related record from another table.
1350  
1351 =head3 Default Interface
1352  
1353 The general usage for a foreign_key field is:
1354  
1355 use DBIx::DBO2::Fields (
1356 foreign_key => 'x',
1357 );
1358  
1359 This declaration will generate methods to support the following interface:
1360  
1361 =over 4
1362  
1363 =item *
1364  
1365 I<$record>-E<gt>x_id() : I<value>
1366  
1367 Returns the raw numeric value of field x_id for the given record.
1368  
1369 =item *
1370  
1371 I<$record>-E<gt>x_id( I<value> )
1372  
1373 Sets the raw numeric value of field x_id for the given record.
1374  
1375 =item *
1376  
1377 I<$record>-E<gt>x() : I<related_object>
1378  
1379 Fetches and returns the related record.
1380  
1381 If the x_id value is empty, or if there is not a record with the corresponding value in the related table, returns undef.
1382  
1383 =item *
1384  
1385 I<$record>-E<gt>x( I<related_object> )
1386  
1387 Sets the raw numeric value of field x_id based on the corresponding field in the related object.
1388  
1389 =item *
1390  
1391 I<$record>-E<gt>x_required() : I<related_object>
1392  
1393 Fetches and returns the related record, in a case where your code depends on it existing, generally because it calls additional methods without checking the result.
1394  
1395 If the x_id value is empty, or if there is not a record with the corresponding value in the related table, croaks with a fatal exception. This makes it easier to spot the problem then Perl's generic "can't call method on undefined value" message.
1396  
1397 =item *
1398  
1399 I<$record>-E<gt>x_invalid() : I<fieldname> => I<error_message>, ...
1400  
1401 If the field is marked required (or the underlying column is defined as not null), reports an error for missing values.
1402  
1403 If a value is provided, attempts to fetch the associated record and reports an error if can not be found.
1404  
1405 =back
1406  
1407 =head3 Attributes
1408  
1409 =over 4
1410  
1411 =item *
1412  
1413 hash_key - defaults to *_id
1414  
1415 =item *
1416  
1417 related_class
1418  
1419 =item *
1420  
1421 related_id_method
1422  
1423 =back
1424  
1425 =head3 Example
1426  
1427 package EBiz::Order::Order;
1428 use DBIx::DBO2::Fields (
1429 foreign_key => { name=>'account', related_class => 'Account' },
1430 );
1431 ...
1432 $order->account_id( 27 );
1433 print $order->required_account->email();
1434  
1435 =cut
1436  
1437 0 ▶sub foreign_key {
Subroutine foreign_key: not called CC=1 SCAR=6.9
Pod documented
1438 {
1439 '-import' => { '::DBIx::DBO2::Fields:generic' => '*' },
1440 'params' => {
1441 'hash_key' => '*_id',
1442 'related_class' => undef,
1443 'related_id_method' => 'id',
1444 'column_type' => 'int',
1445 'column_autodetect' => [ 'required', 0, ],
1446 },
1447 'interface' => {
1448 default => {
1449 '*_id'=>'id',
1450 '*'=>'obj',
1451 '*_parse_text'=>'parse_text',
1452 'required_*'=>'req_obj',
1453 '*_readable' => 'readable',
1454 '*_invalid' => 'invalid'
1455 },
1456 },
1457 'code_expr' => {
1458 },
1459 'behavior' => {
1460 'id' => q{
1461 if ( scalar @_ ) {
1462 _SET_VALUE_{ shift() }
1463 } else {
1464 _GET_VALUE_
1465 }
1466 },
1467 'readable' => q{
1468 my $related = _ATTR_REQUIRED_{related_class};
1469 my $value = _GET_VALUE_ or return;
1470 my $id_method = _ATTR_REQUIRED_{related_id_method};
1471 my $foreign = $related->fetch_one(criteria => { $id_method=>$value })
1472 or croak "Couldn't find related _STATIC_ATTR_{name} record based on $id_method '$value'";
1473 if ( my $display_method = _ATTR_{related_display_method} ) {
1474 $foreign->$display_method();
1475 } else {
1476 $related =~ s{.*::}{}g;
1477 "$related ID #$value"
1478 }
1479 },
1480 'req_obj' => q{
1481 my $related = _ATTR_REQUIRED_{related_class};
1482 my $value = _GET_VALUE_
1483 or croak "No _STATIC_ATTR_{name} foreign key ID for " . ref($self) . " ID '$self->{id}'";
1484 my $id_method = _ATTR_REQUIRED_{related_id_method};
1485 $related->fetch_one(criteria => { $id_method => $value })
1486 or croak "Couldn't find related _STATIC_ATTR_{name} record based on $id_method '$value'";
1487 },
1488 'obj' => q{
1489 my $related = _ATTR_REQUIRED_{related_class};
1490
1491 if ( scalar @_ ) {
1492 my $obj = shift();
1493 UNIVERSAL::isa($obj, $related)
1494 or Carp::croak "Inappropriate object type for " . _ATTR_{name} . ": '$obj' should be a $related";
1495 my $id_method = _ATTR_REQUIRED_{related_id_method};
1496 my $id = $obj->$id_method()
1497 or Carp::croak "Can't store reference to unsaved record";
1498 _SET_VALUE_{ $id }
1499 } else {
1500 my $value = _GET_VALUE_
1501 or return undef;
1502 my $id_method = _ATTR_REQUIRED_{related_id_method};
1503 $related->fetch_one(criteria => { $id_method => $value })
1504 }
1505 },
1506 'invalid' => q{
1507 _BEHAVIOR_{detect_column_attributes}
1508 for ( _GET_VALUE_ ) {
1509 if ( _ATTR_{required} and ! length( $_ ) ) {
1510 return _ATTR_{name} => "This field can not be left empty."
1511 }
1512 if ( length( $_ ) ) {
1513 my $related = _ATTR_REQUIRED_{related_class};
1514 my $id_method = _ATTR_REQUIRED_{related_id_method};
1515 $related->fetch_one(criteria => { $id_method => $_ })
1516 or return _ATTR_{name} => "This field can not be left empty."
1517 }
1518 }
1519 return;
1520 },
1521 'parse_text' => q{
1522 my $related = _ATTR_REQUIRED_{related_class};
1523  
1524 my $text = shift;
1525
1526 my $id_method = _ATTR_REQUIRED_{related_id_method};
1527 my $display_method = _ATTR_{related_display_method};
1528  
1529 my $display_field = 'name';
1530 if ( ! $text ) {
1531 _SET_VALUE_{ undef }
1532  
1533 } elsif ( my $match = ! $display_method ? undef : $related->fetch_records( criteria => { $display_field => $text } )->record(0) ) {
1534 _SET_VALUE_{ $match->$id_method() }
1535  
1536 } elsif ( $match = $related->fetch_records( criteria => { $id_method => uc($text) } )->record(0) ) {
1537 _SET_VALUE_{ $match->$id_method() }
1538  
1539 } elsif ( $match = $related->fetch_records( criteria => [ 'synonyms like ?', "% $text %" ] )->record(0) ) {
1540 _SET_VALUE_{ $match->$id_method() }
1541  
1542 } else {
1543 _SET_VALUE_{ undef }
1544 }
1545 },
1546 0 ▶ '-subs' => sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
1547 0 my $m_info = shift();
1548 0 my $name = $m_info->{'name'};
1549
1550 0 my $forward = $m_info->{'delegate'};
1551 0 ▶ my @forward = ! defined $forward ? ()
Branch: 2 branches
BranchTrueFalseTotal
!defined($forward) ? : 0 0 0
ref $forward eq 'ARRAY' ? : 0 0 0
1552 : ref($forward) eq 'ARRAY' ? @$forward
1553 : split ' ', $forward;
1554
1555 0 my $access = $m_info->{'accessors'};
1556 0 ▶ my @access = ! defined $access ? ()
Branch: 2 branches
BranchTrueFalseTotal
!defined($access) ? : 0 0 0
ref $access eq 'ARRAY' ? : 0 0 0
1557 : ref($access) eq 'ARRAY' ? @$access
1558 : split ' ', $access;
1559
1560 map({
1561 0 my $fwd = $_;
1562 0 ▶ $fwd, sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
1563 0 ▶ my $obj = (shift)->$name()
Branch: 1 branch
BranchTrueFalseTotal
my $obj = (shift())->$name or Carp::croak("Can't forward $fwd because $name is empty") 0 0 0
1564 or Carp::croak("Can't forward $fwd because $name is empty");
1565 0 $obj->$fwd(@_)
1566 }
1567 0 } @forward ),
1568 map({
1569 0 my $acc = $_;
1570 0 ▶ "$name\_$acc", sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
1571 0 ▶ my $obj = (shift)->$name()
Branch: 1 branch
BranchTrueFalseTotal
my $obj = (shift())->$name or return 0 0 0
1572 or return;
1573 0 $obj->$acc(@_)
1574 }
1575 0 } @access ),
1576 },
1577 },
1578 }
1579 0 }
1580  
1581 ########################################################################
1582  
1583 =head2 Field Type line_items
1584  
1585 Generates methods to retrieve records from another table which have a foreign_key relationship to the current record. Depends on there being a primary key column, but does not require a separate database column of its own.
1586  
1587 =head3 Default Interface
1588  
1589 The general usage for a line_items field is:
1590  
1591 package Y;
1592 use DBIx::DBO2::Fields (
1593 line_items => { name=>'x', 'related_field'=>'y_id', related_class=>'X' },
1594 );
1595  
1596 This declaration will generate methods to support the following interface:
1597  
1598 =over 4
1599  
1600 =item *
1601  
1602 I<$record>-E<gt>x() : I<related_objects>
1603  
1604 Fetches the related records. Returns a RecordSet.
1605  
1606 =item *
1607  
1608 I<$record>-E<gt>x( I<rel_col> => I<rel_value>, ...) : I<related_objects>
1609  
1610 Fetches a subset of the related records which also meet the indicated criteria. Returns a RecordSet.
1611  
1612 =item *
1613  
1614 I<$record>-E<gt>count_x()
1615  
1616 Returns the number or related records.
1617  
1618 =item *
1619  
1620 I<$record>-E<gt>new_x() : I<related_object>
1621  
1622 Creates and returns a new related record, setting its foreign key field to refer to our record's ID.
1623  
1624 (Note that the record is created but not inserted; you need to call -E<gt>save() yourself.)
1625  
1626 =item *
1627  
1628 I<$record>-E<gt>delete_x()
1629  
1630 Deletes B<all> of the related records.
1631  
1632 =back
1633  
1634 You can also specify an array-ref value for the default_criteria attribute; if present, it is treated as a list of fieldname/value pairs to be passed to the fetch and new methods of the related class.
1635  
1636  
1637 =head3 restrict_delete Interface
1638  
1639 Identical to the default interface except as follows: an ok_delete hook is installed to check for the existance of any related records, in which case the deletion is cancelled. This prevents you from deleting the "parent" record for a number of related records.
1640  
1641 =head3 cascade_delete Interface
1642  
1643 Identical to the default interface except as follows: a post_delete hook is installed to delete all of the related records after the parent record is deleted.
1644  
1645 =head3 nullify_delete Interface
1646  
1647 Identical to the default interface except as follows: a post_delete hook is installed to change all of the related records to have a default value.
1648  
1649 =cut
1650  
1651 0 ▶sub line_items {
Subroutine line_items: not called CC=1 SCAR=6.9
Pod documented
1652 {
1653 0 '-import' => { '::DBIx::DBO2::Fields:generic' => '*' },
1654 'params' => {
1655 'id_method' => 'id',
1656 'related_class' => undef,
1657 'related_field' => undef,
1658 'default_criteria' => undef,
1659 'default_order' => 'id',
1660 },
1661 'interface' => {
1662 default => {
1663 '*'=>'fetch',
1664 'count_*'=>'count',
1665 'new_*'=>'new',
1666 'delete_*'=>'delete',
1667 },
1668 restrict_delete => {
1669 -base => 'default',
1670 'check_for_*'=>'check_count',
1671 -params => {
1672 hook => { ok_delete => 'check_for_*' }
1673 },
1674 },
1675 nullify_on_delete => {
1676 -base => 'default',
1677 'nullify_*'=>'nullify',
1678 -params => {
1679 delete_default => undef,
1680 hook => { post_delete => 'nullify_*' }
1681 },
1682 },
1683 cascade_delete => {
1684 -base => 'default',
1685 -params => {
1686 hook => { post_delete => 'delete_*' }
1687 },
1688 },
1689 },
1690 'behavior' => {
1691 'fetch' => q{
1692 my $related = _ATTR_REQUIRED_{related_class};
1693  
1694 my %params = @_;
1695
1696 my $r_field = _ATTR_REQUIRED_{related_field};
1697 my $id_method = _ATTR_REQUIRED_{id_method};
1698 my $d_crit = _ATTR_{default_criteria};
1699 $d_crit = { @$d_crit } if ( ref($d_crit) eq 'ARRAY' );
1700 my $id = $self->$id_method()
1701 or return DBIx::DBO2::RecordSet->new();
1702 my $criteria = DBIx::SQLEngine::Criteria->auto_and(
1703 DBIx::SQLEngine::Criteria::Equality->new($r_field=>$id),
1704 ( $d_crit || () ),
1705 ( $params{criteria} ? $params{criteria} : () ),
1706 );
1707 $params{criteria} = $criteria;
1708 if ( my $default_order = _ATTR_{default_order} ) {
1709 $params{order} ||= $default_order
1710 }
1711 $related->fetch_records(%params);
1712 },
1713 'count' => q{
1714 my $related = _ATTR_REQUIRED_{related_class};
1715  
1716 my %params = @_;
1717
1718 my $r_field = _ATTR_REQUIRED_{related_field};
1719 my $id_method = _ATTR_REQUIRED_{id_method};
1720 my $d_crit = _ATTR_{default_criteria};
1721 $d_crit = { @$d_crit } if ( ref($d_crit) eq 'ARRAY' );
1722 my $id = $self->$id_method()
1723 or return 0;
1724 # warn "Counting from " . $related->table->name;
1725 my $criteria = DBIx::SQLEngine::Criteria->auto_and(
1726 DBIx::SQLEngine::Criteria::Equality ->new($r_field=>$id),
1727 ( $d_crit || () ),
1728 ( $params{criteria} ? $params{criteria} : () ),
1729 );
1730 delete $params{criteria};
1731 $related->table->count_rows($criteria);
1732 },
1733 'delete' => q{
1734 my $fetch_method = _STATIC_ATTR_{name};
1735 foreach my $item ( $self->$fetch_method(@_)->records ) {
1736 $item->delete_record();
1737 }
1738 },
1739 'nullify' => q{
1740 my $fetch_method = _STATIC_ATTR_{name};
1741 my $r_field = _ATTR_REQUIRED_{related_field};
1742 my $default = _ATTR_{delete_default};
1743 foreach my $item ( $self->$fetch_method(@_)->records ) {
1744 $item->$r_field( $default );
1745 }
1746 },
1747 'check_count' => q{
1748 my $count_method = "count_" . _STATIC_ATTR_{name};
1749 my $count = $self->$count_method();
1750 # warn "Checking count $count_method: $count";
1751 return $count ? 0 : 1;
1752 },
1753 'new' => q{
1754 my $related = _ATTR_REQUIRED_{related_class};
1755
1756 my $r_field = _ATTR_REQUIRED_{related_field};
1757 my $id_method = _ATTR_REQUIRED_{id_method};
1758 my $d_crit = _ATTR_{default_criteria};
1759 $related->new( $r_field=>$self->$id_method(), ((ref($d_crit) eq 'ARRAY' ) ? @$d_crit : ()), @_ );
1760 },
1761 },
1762 }
1763 }
1764  
1765 ########################################################################
1766  
1767 =head1 FIELDS WITH AUTOMATIC BEHAVIOR
1768  
1769 =head2 Field Type subclass_name
1770  
1771 use DBIx::DBO2::Fields ( subclass_name => 'type' );
1772  
1773 This field type allows you to have different records in the same table be handled as various subclasses of some common Record type.
1774  
1775 package MyClass;
1776 use DBIx::DBO2::Fields (
1777 subclass_name => 'type',
1778 string => 'name',
1779 );
1780  
1781 package MyClass::Subber;
1782  
1783 sub foo { ... }
1784
1785 package main;
1786
1787 my $obj = MyClass->new;
1788 $obj->type('Subber'); # Rebless to subclass
1789 $obj->foo; # New methods available
1790 $obj->save_record; # Subclass name stored in text field
1791 ...
1792 my $obj = MyClass->fetch_one(...);
1793 print $obj->type; # Type is remembed after fetch,
1794 $obj->foo if $obj->can('foo') # and objects are auto-reblessed.
1795  
1796 =cut
1797  
1798 0 ▶sub subclass_name {
Subroutine subclass_name: not called CC=1 SCAR=6.9
Pod documented
1799 {
1800 0 '-import' => { '::DBIx::DBO2::Fields:string' => '*' },
1801 'interface' => {
1802 default => {
1803 '*'=>'get_set',
1804 '*_pack' => 'pack',
1805 '*_unpack' => 'unpack'
1806 },
1807 },
1808 'params' => {
1809 hook => { post_fetch=>'*_unpack', post_new=>'*_pack', pre_insert=>'*_pack', pre_update=>'*_pack' }
1810 },
1811 'behavior' => {
1812 'get' => q{
1813 my $type = ref( $self ) ? _GET_VALUE_ :
1814 Class::MakeMethods::Template::ClassName::_pack_subclass
1815 ( _ATTR_{target_class}, $self );
1816 defined( $type ) ? $type : '';
1817 },
1818 'set' => q{
1819 my $type = shift;
1820 my $subclass =
1821 Class::MakeMethods::Template::ClassName::_unpack_subclass(
1822 _ATTR_{target_class}, $type );
1823 # my $class = Class::MakeMethods::Template::ClassName::_provide_class(
1824 # _ATTR_{target_class}, $subclass );
1825 my $class = Class::MakeMethods::Template::ClassName::_require_class(
1826 $subclass );
1827
1828 if ( ref _SELF_ ) {
1829 _SET_VALUE_{ $type };
1830 bless $self, $class;
1831 }
1832 return $class;
1833 },
1834 'pack' => q{
1835 my $class = ref( $self ) or Carp::confess "Not a class method";
1836 my $type = Class::MakeMethods::Template::ClassName::_pack_subclass
1837 ( _ATTR_{target_class}, $class );
1838 _SET_VALUE_{ $type };
1839 },
1840 'unpack' => q{
1841 my $type = _GET_VALUE_;
1842 my $subclass = Class::MakeMethods::Template::ClassName::_unpack_subclass(
1843 _ATTR_{target_class}, $type );
1844 # my $class = Class::MakeMethods::Template::ClassName::_provide_class(
1845 # _ATTR_{target_class}, $subclass );
1846 my $class = Class::MakeMethods::Template::ClassName::_require_class(
1847 $subclass );
1848
1849 if ( ref _SELF_ ) {
1850 bless $self, $class;
1851 }
1852 return $class;
1853 },
1854 },
1855 }
1856 }
1857  
1858 ########################################################################
1859  
1860 =head2 Field Type stringified_hash
1861  
1862 use DBIx::DBO2::Fields ( stringified_hash => 'data' );
1863  
1864 This field type allows you to manipulate a simple hash of key-value pairs for each record, which is automatically converted to and from a stringified form in the database. Don't store nested data structures in the values.
1865  
1866 A reference to the hash structure is stored in the record using the field name as the hash key, but this is not saved in the database. The text version of the data is packed into and unpacked outof a string stored under the hash key "packed_I<name>", using the string2hash and hash2string functions from String::Escape.
1867  
1868 package MyClass;
1869 use DBIx::DBO2::Record '-isasubclass';
1870 use DBIx::DBO2::Fields (
1871 stringified_hash => 'data',
1872 ...
1873 );
1874  
1875 package main;
1876 my $obj = MyClass->new;
1877 $obj->data( 'key' => $non_ref_value );
1878 print $obj->data('key');
1879 %info = $obj->data();
1880 $obj->save_record;
1881 ...
1882
1883 my $obj = MyClass->fetch_one(...);
1884 print $obj->data('key');
1885  
1886 B<DEPENDCIES:> Note that this type of field requires the following modules: String::Escape.
1887  
1888 =cut
1889  
1890 0 ▶sub stringified_hash {
Subroutine stringified_hash: not called CC=1 SCAR=6.9
Pod documented
1891 {
1892 '-import' => { '::DBIx::DBO2::Fields:string' => '*' },
1893 'interface' => {
1894 default => {
1895 'packed_*'=>'get_set',
1896 '*_pack' => 'pack',
1897 '*_unpack' => 'unpack',
1898 '*_readable'=>'readable',
1899 },
1900 },
1901 'params' => {
1902 hash_key => 'packed_*',
1903 hook => {
1904 post_fetch => '*_unpack',
1905 pre_insert => '*_pack',
1906 pre_update => '*_pack',
1907 },
1908 },
1909 'behavior' => {
1910 0 ▶ '-init' => [ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1911 0 require String::Escape;
1912 0 return;
1913 } ],
1914 0 ▶ '-subs' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1915 0 my $m_info = shift;
1916 Class::MakeMethods::Standard::Hash->make(
1917 -TargetClass => $m_info->{target_class},
1918 0 'hash' => [ $m_info->{name} => { auto_init => 1 } ],
1919 )
1920 },
1921 0 'pack' => q{
1922 my $struct_method = _ATTR_{name};
1923 my %hash = $self->{$struct_method} ? %{$self->{$struct_method}} : ();
1924 _SET_VALUE_{ ( ! scalar keys %hash ) ? '' :
1925 ' ' . String::Escape::hash2string(
1926 map { $_ => $hash{ $_ } } sort keys %hash
1927 ) . ' '
1928 };
1929 },
1930 'unpack' => q{
1931 my $struct_method = _ATTR_{name};
1932 my $string = _GET_VALUE_;
1933 $string =~ s/\A\s+|\s+\Z//g;
1934 $self->$struct_method( length($string) ? String::Escape::string2hash( $string ) : {} );
1935 },
1936 'readable' => q{
1937 _GET_VALUE_
1938 },
1939 },
1940 }
1941 }
1942  
1943 ########################################################################
1944  
1945 =head2 Field Type storable_hash
1946  
1947 use DBIx::DBO2::Fields ( storable_hash => 'data' );
1948  
1949 This field type allows you to manipulate a hash structure for each record, which is automatically converted to and from a stringified form in the database. You can store nested data structures in the values.
1950  
1951 A reference to the hash structure is stored in the record using the field name as the hash key, but this is not saved in the database. The text version of the data is packed into and unpacked outof a string stored under the hash key "packed_I<name>", using the Storable module.
1952  
1953 package MyClass;
1954 use DBIx::DBO2::Record '-isasubclass';
1955 use DBIx::DBO2::Fields (
1956 storable_hash => 'data',
1957 ...
1958 );
1959  
1960 package main;
1961 my $obj = MyClass->new;
1962 $obj->data( 'key' => [ 1, 2, 3 ] );
1963 print $obj->data('key');
1964 %info = $obj->data();
1965 $obj->save_record;
1966 ...
1967
1968 my $obj = MyClass->fetch_one(...);
1969 print $obj->data('key');
1970  
1971 B<DEPENDCIES:> Note that this type of field requires the following modules: Storable, MIME::Base64, Data::Dumper.
1972  
1973 =cut
1974  
1975 0 ▶sub storable_hash {
Subroutine storable_hash: not called CC=1 SCAR=6.9
Pod documented
1976 {
1977 '-import' => { '::DBIx::DBO2::Fields:string' => '*' },
1978 'interface' => {
1979 default => {
1980 'packed_*'=>'get_set',
1981 '*_pack' => 'pack',
1982 '*_unpack' => 'unpack',
1983 '*_readable'=>'readable',
1984 },
1985 },
1986 'params' => {
1987 hash_key => 'packed_*',
1988 hook => {
1989 post_fetch => '*_unpack',
1990 pre_insert => '*_pack',
1991 pre_update => '*_pack',
1992 },
1993 },
1994 'behavior' => {
1995 0 ▶ '-init' => [ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1996 0 require Storable;
1997 0 require MIME::Base64;
1998 0 require Data::Dumper;
1999 0 return;
2000 } ],
2001 0 ▶ '-subs' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2002 0 my $m_info = shift;
2003 Class::MakeMethods::Standard::Hash->make(
2004 -TargetClass => $m_info->{target_class},
2005 'hash' => $m_info->{name},
2006 )
2007 0 },
2008 0 'pack' => q{
2009 my $struct_method = _ATTR_{name};
2010 my %hash = $self->{$struct_method} ? %{$self->{$struct_method}} : ();
2011 _SET_VALUE_{ ! scalar(keys %hash) ? '' :
2012 MIME::Base64::encode_base64( Storable::nfreeze \%hash ) }
2013 },
2014 'unpack' => q{
2015 my $struct_method = _ATTR_{name};
2016 my $string = _GET_VALUE_;
2017 if ( length($string) and $string !~ m{^BQ} ) {
2018 warn "Skipping mangled storable_hash $struct_method for $self $self->{id}";
2019 return;
2020 }
2021 # warn "About to unpack storable_hash $struct_method for $self $self->{id}";
2022 $self->$struct_method( length($string) ?
2023 Storable::thaw( MIME::Base64::decode_base64( $string ) ) : {}
2024 );
2025 },
2026 'readable' => q{
2027 my $struct_method = _ATTR_{name};
2028 my %hash = $self->$struct_method();
2029 my $string = Data::Dumper->Dump( [\%hash], [ $struct_method ] );
2030 $string =~ s/^\$$struct_method\s\=\s\{(.*)\}\;$/$1/s;
2031 $string;
2032 },
2033 },
2034 }
2035 }
2036  
2037 ########################################################################
2038  
2039 =head2 runnable_code
2040  
2041 A text field which is expected to contain syntactically valid Perl code.
2042  
2043 Provides an additional helper method that executes that code, by caching it as a subroutine reference.
2044  
2045 Optional parameters:
2046  
2047 =over 4
2048  
2049 =item sub_hash_key
2050  
2051 Name of hash key under which to store a cached subroutine. Defaults to '*_sub'.
2052  
2053 =item sub_template
2054  
2055 Outline for subroutine.
2056  
2057 =item pass_self_arg
2058  
2059 Boolean. Determines whether a reference to the object is to be passed as an argument to the subroutine.
2060  
2061 =back
2062  
2063 =cut
2064  
2065 0 ▶sub runnable_code {
Subroutine runnable_code: not called CC=1 SCAR=6.9
Pod documented
2066 {
2067 0 '-import' => { '::DBIx::DBO2::Fields:string' => '*' },
2068 'interface' => {
2069 default => {
2070 '*' => 'get_set',
2071 'run_*'=>'run',
2072 },
2073 },
2074 'params' => {
2075 sub_hash_key => '*_sub',
2076 sub_template => q{ sub {
2077 __CODE__
2078 } },
2079 pass_self_arg => 0,
2080 },
2081 'code_expr' => {
2082 _CACHED_SUB_ => '_SELF_->{ _ATTR_{sub_hash_key} }',
2083 },
2084 'behavior' => {
2085 'set' => q{
2086 undef _CACHED_SUB_;
2087 _SET_VALUE_{ $_[0] };
2088 },
2089 'run' => q{
2090 unless ( _CACHED_SUB_ ) {
2091 my $code = _ATTR_{sub_template};
2092 $code =~ s{\_\_CODE\_\_}{_GET_VALUE_}g;
2093 local $SIG{__DIE__};
2094 _CACHED_SUB_ = eval $code or
2095 die "Can't eval ".(_ATTR_{name})." code: ".(_GET_VALUE_)."\n$@";
2096 }
2097 unshift @_, _SELF_ if ( _ATTR_{pass_self_arg} );
2098 &{_CACHED_SUB_}( @_ );
2099 },
2100 },
2101 }
2102 }
2103  
2104 ########################################################################
2105  
2106 =head1 WRAPPER FIELDS
2107  
2108 These methods provide a field-ish interface to behavior provided by other Perl methods; they are computed on the fly, and do not correspond to SQL columns.
2109  
2110 =head2 Field Type alias
2111  
2112 use DBIx::DBO2::Fields (
2113 alias => [ 'x', { target=>'subject' } ],
2114 );
2115  
2116 This declares a method -E<gt>x() that simply calls method -E<gt>y() and passes along all of its arguments.
2117  
2118 B<Note:> This method does not store a value, and does not correspond to an SQL column.
2119  
2120 =cut
2121  
2122 0 ▶sub alias {
Subroutine alias: not called CC=1 SCAR=6.9
Pod documented
2123 {
2124 '-import' => { '::DBIx::DBO2::Fields:generic' => '*' },
2125 'interface' => {
2126 default => 'alias',
2127 'alias' => 'alias'
2128 },
2129 'params' => { 'method_name' => '*' },
2130 'behavior' => {
2131 0 ▶ 'alias' => sub { my $m_info = $_[0]; sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
Subroutine __ANON__: not called CC=1 SCAR=6.9
2132 0 my $target = $m_info->{'target'};
2133 0 (shift)->$target(@_)
2134 0 }},
2135 },
2136 }
2137 0 }
2138  
2139 ########################################################################
2140  
2141 =head2 Field Type delegate
2142  
2143 Local alias for the Universal:forward_methods method generator.
2144  
2145 Creates a method which delegates to an object provided by another method.
2146  
2147 B<Note:> This method does not store a value, and does not correspond to an SQL column.
2148  
2149 Example:
2150  
2151 use DBIx::DBO2::Fields
2152 delegate => [
2153 [ 'w' ], { target=> 'whistle' },
2154 [ 'x', 'y' ], { target=> 'xylophone' },
2155 { name=>'z', target=>'zither', target_args=>[123], method_name=>do_zed },
2156 ];
2157  
2158 Example: The above defines that method C<w> will be handled by the
2159 calling C<w> on the object returned by C<whistle>, whilst methods C<x>
2160 and C<y> will be handled by xylophone, and method C<z> will be handled
2161 by calling C<do_zed> on the object returned by calling C<zither(123)>.
2162  
2163 B<Attributes>: The following additional attributes are supported:
2164  
2165 =over 4
2166  
2167 =item target
2168  
2169 I<Required>. The name of the method that will provide the object that will handle the operation.
2170  
2171 =item target_args
2172  
2173 Optional ref to an array of arguments to be passed to the target method.
2174  
2175 =item method_name
2176  
2177 The name of the method to call on the handling object. Defaults to the name of the meta-method being created.
2178  
2179 =back
2180  
2181 =cut
2182  
2183 0 ▶sub delegate { 'Universal:forward_methods' }
Subroutine delegate: not called CC=1 SCAR=6.9
Pod documented
2184  
2185 ########################################################################
2186  
2187 =head2 Field Type calculated_string
2188  
2189 B<To Do:> Documentation for this field type has not been written yet.
2190  
2191 =cut
2192  
2193 0 ▶sub calculated_string {
Subroutine calculated_string: not called CC=1 SCAR=6.9
Pod documented
2194 {
2195 '-import' => { '::DBIx::DBO2::Fields:generic' => '*' },
2196 'interface' => {
2197 default => { },
2198 },
2199 'params' => {
2200 calc_sub => undef,
2201 },
2202 'behavior' => {
2203 0 ▶ '-subs' => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
2204 0 my $m_info = shift();
2205 0 my $name = $m_info->{'name'};
2206 0 ▶ ( $m_info->{calc_sub} ) ? ( $name => $m_info->{calc_sub} ) : ();
Branch: 1 branch
BranchTrueFalseTotal
$m_info->{'calc_sub'} ? : 0 0 0
2207 },
2208 },
2209 }
2210 0 }
2211  
2212  
2213 ########################################################################
2214  
2215 =head2 Field Type calculated_quantity
2216  
2217 B<To Do:> Documentation for this field type has not been written yet.
2218  
2219 =cut
2220  
2221 0 ▶sub calculated_quantity {
Subroutine calculated_quantity: not called CC=1 SCAR=6.9
Pod documented
2222 {
2223 '-import' => { '::DBIx::DBO2::Fields:generic' => '*' },
2224 'interface' => {
2225 default => { '*_readable'=>'readable' },
2226 },
2227 'params' => {
2228 quantity_class => undef,
2229 calc_sub => undef,
2230 },
2231 'behavior' => {
2232 0 ▶ '-init' => [ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2233 0 my $m_info = shift();
2234 0 my $qclass = $m_info->{quantity_class};
2235 0 $qclass =~ s{::}{/}g;
2236 0 require "$qclass.pm";
2237 0 return;
2238 } ],
2239 'readable' => q{
2240 my $method = _ATTR_{name};
2241 my $qclass = _ATTR_{quantity_class};
2242 $qclass->readable_value(_SELF_->$method())
2243 },
2244 0 ▶ '-subs' => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
2245 0 my $m_info = shift();
2246 0 my $name = $m_info->{'name'};
2247 0 ▶ ( $m_info->{calc_sub} ) ? ( $name => $m_info->{calc_sub} ) : ();
Branch: 1 branch
BranchTrueFalseTotal
$m_info->{'calc_sub'} ? : 0 0 0
2248 },
2249 },
2250 }
2251 0 }
2252  
2253  
2254 ########################################################################
2255  
2256 =head2 Field Type calculated_uspennies
2257  
2258 B<To Do:> Documentation for this field type has not been written yet.
2259  
2260 =cut
2261  
2262 0 ▶sub calculated_uspennies {
Subroutine calculated_uspennies: not called CC=1 SCAR=6.9
Pod documented
2263 {
2264 0 '-import' => { '::DBIx::DBO2::Fields:calculated_quantity' => '*' },
2265 'params' => {
2266 quantity_class => 'Data::Quantity::Finance::Currency::USD',
2267 },
2268 }
2269 }
2270  
2271 ########################################################################
2272  
2273 =head2 Field Type calculated_timestamp
2274  
2275 B<To Do:> Documentation for this field type has not been written yet.
2276  
2277 =cut
2278  
2279 0 ▶sub calculated_timestamp {
Subroutine calculated_timestamp: not called CC=1 SCAR=6.9
Pod documented
2280 {
2281 0 '-import' => { '::DBIx::DBO2::Fields:calculated_quantity' => '*' },
2282 'params' => {
2283 quantity_class => 'Data::Quantity::Time::Timestamp',
2284 },
2285 }
2286 }
2287  
2288 ########################################################################
2289  
2290 =head2 Field Type calculated_duration
2291  
2292 B<To Do:> Documentation for this field type has not been written yet.
2293  
2294 =cut
2295  
2296 0 ▶sub calculated_duration {
Subroutine calculated_duration: not called CC=1 SCAR=6.9
Pod documented
2297 {
2298 0 '-import' => { '::DBIx::DBO2::Fields:calculated_quantity' => '*' },
2299 'params' => {
2300 quantity_class => 'Data::Quantity::Time::DurationSeconds',
2301 },
2302 }
2303 }
2304  
2305 ########################################################################
2306  
2307 =head2 Field Type calculated_line_items
2308  
2309 B<To Do:> Documentation for this field type has not been written yet.
2310  
2311 =cut
2312  
2313 0 ▶sub calculated_line_items {
Subroutine calculated_line_items: not called CC=1 SCAR=6.9
Pod documented
2314 {
2315 '-import' => { '::DBIx::DBO2::Fields:generic' => '*' },
2316 'interface' => {
2317 default => { },
2318 },
2319 'behavior' => {
2320 0 ▶ '-subs' => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
2321 0 my $m_info = shift();
2322 0 my $name = $m_info->{'name'};
2323 0 ▶ ( $m_info->{calc_sub} ) ? ( $name => $m_info->{calc_sub} ) : ();
Branch: 1 branch
BranchTrueFalseTotal
$m_info->{'calc_sub'} ? : 0 0 0
2324 },
2325 },
2326 }
2327 0 }
2328  
2329 ########################################################################
2330  
2331 =head2 Field Type filtered_line_items
2332  
2333 B<To Do:> Documentation for this field type has not been written yet.
2334  
2335 =cut
2336  
2337 0 ▶sub filtered_line_items {
Subroutine filtered_line_items: not called CC=1 SCAR=6.9
Pod documented
2338 {
2339 0 '-import' => { '::DBIx::DBO2::Fields:generic' => '*' },
2340 'params' => {
2341 'line_items_method' => undef,
2342 'criteria' => undef,
2343 'related_class' => undef,
2344 'related_field' => undef,
2345 },
2346 'interface' => {
2347 default => {
2348 '*'=>'fetch',
2349 'count_*'=>'count',
2350 },
2351 },
2352 'behavior' => {
2353 'fetch' => q{
2354 my $base_method = _ATTR_{line_items_method};
2355 _SELF_->$base_method( criteria => _ATTR_{criteria} );
2356 },
2357 'count' => q{
2358 my $base_method = 'count_' . _ATTR_{line_items_method};
2359 _SELF_->$base_method( criteria => _ATTR_{criteria} );
2360 },
2361 },
2362 }
2363 }
2364  
2365 ########################################################################
2366  
2367 =head2 Field Type dynamic_select
2368  
2369 B<To Do:> Documentation for this field type has not been written yet.
2370  
2371 =cut
2372  
2373 0 ▶sub dynamic_select {
Subroutine dynamic_select: not called CC=1 SCAR=6.9
Pod documented
2374 {
2375 0 '-import' => { '::DBIx::DBO2::Fields:generic' => '*' },
2376 'params' => {
2377 'related_class' => undef,
2378 'default_criteria' => undef,
2379 'default_order' => undef,
2380 'clauses_sub' => undef,
2381 },
2382 'interface' => {
2383 default => {
2384 '*'=>'fetch',
2385 'count_*'=>'count',
2386 },
2387 },
2388 'behavior' => {
2389 'fetch' => q{
2390 my $clauses_sub = _ATTR_{clauses_sub};
2391 my @clauses = $clauses_sub ? &$clauses_sub( _SELF_ ) : ();
2392 my %clauses = ( $#clauses == 0 ) ? (criteria => @clauses) : @clauses;
2393 foreach ( qw( criteria order ) ) {
2394 $clauses{$_} ||= _ATTR_{"default_$_"} if ( _ATTR_{"default_$_"} );
2395 }
2396 my $related_class = _ATTR_REQUIRED_{related_class};
2397 $related_class->fetch_records( %clauses );
2398 },
2399 'count' => q{
2400 my $clauses_sub = _ATTR_{clauses_sub};
2401 my @clauses = $clauses_sub ? &$clauses_sub( _SELF_ ) : ();
2402 my %clauses = ( $#clauses == 0 ) ? (criteria => @clauses) : @clauses;
2403 foreach ( qw( criteria order ) ) {
2404 $clauses{$_} ||= _ATTR_{"default_$_"} if ( _ATTR_{"default_$_"} );
2405 }
2406 my $related_class = _ATTR_REQUIRED_{related_class};
2407 $related_class->table->count_rows( $clauses{criteria} );
2408 },
2409 },
2410 }
2411 }
2412  
2413 ########################################################################
2414  
2415 =head2 Field Type dynamic_fetch
2416  
2417 B<To Do:> Documentation for this field type has not been written yet.
2418  
2419 =cut
2420  
2421 0 ▶sub dynamic_fetch {
Subroutine dynamic_fetch: not called CC=1 SCAR=6.9
Pod documented
2422 {
2423 '-import' => { '::DBIx::DBO2::Fields:generic' => '*' },
2424 'params' => {
2425 'related_class' => undef,
2426 'default_criteria' => undef,
2427 'default_order' => undef,
2428 'default_limit' => 1,
2429 'clauses_sub' => undef,
2430 'related_id_method' => 'id',
2431 },
2432 'interface' => {
2433 default => {
2434 '*'=>'fetch',
2435 '*_readable'=>'readable',
2436 },
2437 },
2438 'behavior' => {
2439 'fetch' => q{
2440 my $clauses_sub = _ATTR_{clauses_sub};
2441 my @clauses = $clauses_sub ? &$clauses_sub( _SELF_ ) : ();
2442 my %clauses = ( $#clauses == 0 ) ? (criteria => @clauses) : @clauses;
2443 foreach ( qw( criteria order limit ) ) {
2444 $clauses{$_} ||= _ATTR_{"default_$_"} if ( _ATTR_{"default_$_"} );
2445 }
2446 my $related_class = _ATTR_REQUIRED_{related_class};
2447 $related_class->fetch_one( %clauses );
2448 },
2449 'readable' => q{
2450 my $fetch_method = _ATTR_REQUIRED_{name};
2451 my $foreign = _SELF_->$fetch_method() or return;
2452 if ( my $display_method = _ATTR_{related_display_method} ) {
2453 $foreign->$display_method();
2454 } else {
2455 my $related_class = _ATTR_REQUIRED_{related_class};
2456 $related_class =~ s{.*::}{}g;
2457 my $id_method = _ATTR_REQUIRED_{related_id_method};
2458 "$related_class ID #" . $foreign->$id_method();
2459 }
2460 },
2461 0 ▶ '-subs' => sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
2462 0 my $m_info = shift();
2463 0 my $name = $m_info->{'name'};
2464
2465 0 my $forward = $m_info->{'delegate'};
2466 0 ▶ my @forward = ! defined $forward ? ()
Branch: 2 branches
BranchTrueFalseTotal
!defined($forward) ? : 0 0 0
ref $forward eq 'ARRAY' ? : 0 0 0
2467 : ref($forward) eq 'ARRAY' ? @$forward
2468 : split ' ', $forward;
2469
2470 0 my $access = $m_info->{'accessors'};
2471 0 ▶ my @access = ! defined $access ? ()
Branch: 2 branches
BranchTrueFalseTotal
!defined($access) ? : 0 0 0
ref $access eq 'ARRAY' ? : 0 0 0
2472 : ref($access) eq 'ARRAY' ? @$access
2473 : split ' ', $access;
2474
2475 map({
2476 0 my $fwd = $_;
2477 0 ▶ $fwd, sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
2478 0 ▶ my $obj = (shift)->$name()
Branch: 1 branch
BranchTrueFalseTotal
my $obj = (shift())->$name or Carp::croak("Can't forward $fwd because $name is empty") 0 0 0
2479 or Carp::croak("Can't forward $fwd because $name is empty");
2480 0 $obj->$fwd(@_)
2481 }
2482 0 } @forward ),
2483 map({
2484 0 my $acc = $_;
2485 0 ▶ "$name\_$acc", sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
2486 0 ▶ my $obj = (shift)->$name()
Branch: 1 branch
BranchTrueFalseTotal
my $obj = (shift())->$name or return 0 0 0
2487 or return;
2488 0 $obj->$acc(@_)
2489 }
2490 0 } @access ),
2491 },
2492 },
2493 }
2494 0 }
2495  
2496 ########################################################################
2497  
2498 =head1 TO DO
2499  
2500 =over 4
2501  
2502 =item *
2503  
2504 Resolve differing approaches to setting values from human-entered formatted values. Current interface is:
2505  
2506 =over 4
2507  
2508 =item -
2509  
2510 julian_day: I<$record>-E<gt>x( I<readable_value> )
2511  
2512 =item -
2513  
2514 timestamp: I<$record>-E<gt>x( I<readable_value> )
2515  
2516 =item -
2517  
2518 currency_uspennies: I<$record>-E<gt>x_readable(I<readable_value>)
2519  
2520 =item -
2521  
2522 creditcardnumber: I<$record>-E<gt>x_readable(I<readable_value>)
2523  
2524 =back
2525  
2526 =back
2527  
2528  
2529 =head1 SEE ALSO
2530  
2531 See L<DBIx::DBO2> for an overview of this framework.
2532  
2533 =cut
2534  
2535 ########################################################################
2536  
2537 1 1;
↑ Summary DBO2/Record.pm »