blib/lib/DB/Object/Fields.pm untested

filter: Statementstmt 0.0% 0 / 150 Branchbran 0.0% 0 / 62 Conditioncond 0.0% 0 / 58 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 25 Podpod 0.0% 0 / 13 totaltotal 0.0% 0 / 308 CC 32 SCAR 37.2
CC
32
Cov
0%
new_field
132.0
prefixed
42.0
AUTOLOAD
42.0
CRAP 41.3
1 ##----------------------------------------------------------------------------
2 ## Database Object Interface - ~/lib/DB/Object/Fields.pm
3 ## Version v1.3.0
4 ## Copyright(c) 2024 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2020/01/01
7 ## Modified 2026/03/22
8 ## All rights reserved
9 ##
10 ##
11 ## This program is free software; you can redistribute it and/or modify it
12 ## under the same terms as Perl itself.
13 ##----------------------------------------------------------------------------
14 package DB::Object::Fields;
15 BEGIN
16 {
17 use strict;
18 use warnings;
19 use common::sense;
20 use parent qw( Module::Generic );
21 use vars qw( $VERSION $EXCEPTION_CLASS );
22 use DB::Object::Fields::Field;
23 our $EXCEPTION_CLASS = $DB::Object::EXCEPTION_CLASS;
24 our $VERSION = 'v1.3.0';
25 };
26  
27 use strict;
28 use warnings;
29  
30 sub init
31 {
32 my $self = shift( @_ );
33 $self->{prefixed} = 0;
34 # Property 'query_object' not used anymore. Instead, we use table_object->query_object
35 $self->{table_object} = '';
36 # $self->{fatal} = 1;
37 $self->{_init_strict_use_sub} = 1;
38 $self->{_init_params_order} = [qw( table_object query_object prefixed )];
39 $self->{_exception_class} = $EXCEPTION_CLASS;
40 $self->SUPER::init( @_ );
41 $self->{_fields} = [qw( prefixed )];
42 return( $self->error( "No table object was provided" ) ) if( !$self->{table_object} );
43 return( $self );
44 }
45  
46 sub database_object { return( shift->table_object->database_object ); }
47  
48 # To manually create a new table field
49 sub new_field
50 {
51 my $self = shift( @_ );
52 my $opts = $self->_get_args_as_hash( @_ );
53 if( !exists( $opts->{name} ) ||
54 $self->_is_empty( $opts->{name} ) )
55 {
56 return( $self->error( "No field name was provided." ) );
57 }
58 elsif( !exists( $opts->{type} ) ||
59 $self->_is_empty( $opts->{type} ) )
60 {
61 return( $self->error( "No field type was provided." ) );
62 }
63 $opts->{type} = lc( $opts->{type} );
64 # But actually we ignore it; users should not provide it
65 if( exists( $opts->{constant} ) &&
66 defined( $opts->{constant} ) &&
67 ref( $opts->{constant} ) eq 'HASH' )
68 {
69 $opts->{datatype} = delete( $opts->{constant} );
70 }
71 my $datatype_dict = $self->database_object->datatype_dict;
72 if( !exists( $datatype_dict->{ $opts->{type} } ) )
73 {
74 return( $self->error( "Field type provided ($opts->{type}) is not supported by driver ", $self->database_object->driver ) );
75 }
76 my $def = $datatype_dict->{ $opts->{type} };
77 $opts->{debug} = $self->debug unless( exists( $opts->{debug} ) && length( $opts->{debug} // '' ) );
78 my $fo = DB::Object::Fields::Field->new(
79 datatype => {
80 constant => $def->{constant},
81 name => $def->{name},
82 type => $def->{type},
83 },
84 debug => $opts->{debug},
85 ( !$self->_is_empty( $opts->{default} ) ? ( default => $opts->{default} ) : () ),
86 ( !$self->_is_empty( $opts->{is_array} ) ? ( is_array => $opts->{is_array} ) : () ),
87 ( !$self->_is_empty( $opts->{is_nullable} ) ? ( is_nullable => $opts->{is_nullable} ) : () ),
88 name => $opts->{name},
89 ( !$self->_is_empty( $opts->{pos} ) ? ( pos => $opts->{pos} ) : () ),
90 query_object => $self->query_object,
91 ( !$self->_is_empty( $opts->{size} ) ? ( size => $opts->{size} ) : () ),
92 table_object => $self->table_object,
93 type => $opts->{type},
94 ) || return( $self->pass_error( DB::Object::Fields::Field->error ) );
95 return( $fo );
96 }
97  
98 sub prefixed
99 {
100 my $self = shift( @_ );
101 if( @_ )
102 {
103 $self->{prefixed} = ( $_[0] =~ /^\d+$/ ? $_[0] : ( $_[0] ? 1 : 0 ) );
104 }
105 else
106 {
107 $self->{prefixed} = 1;
108 }
109 my $fields = $self->table_object->fields;
110 foreach my $f ( keys( %$fields ) )
111 {
112 next if( !CORE::length( $self->{ $f } ) );
113 next if( !$self->_is_object( $self->{ $f } ) );
114 my $o = $self->{ $f };
115 $o->prefixed( $self->{prefixed} );
116 }
117 return( $self );
118 }
119  
120 # sub query_object { return( shift->_set_get_object_without_init( 'query_object', 'DB::Object::Query', @_ ) ); }
121 sub query_object { return( shift->table_object->query_object ); }
122  
123 sub table_object { return( shift->_set_get_object_without_init( 'table_object', 'DB::Object::Tables', @_ ) ); }
124  
125 sub _initiate_field_object
126 {
127 my $self = shift( @_ );
128 my $field = shift( @_ ) || return( $self->error( "No field was provided to get its object." ) );
129 my $class = ref( $self ) || $self;
130 my $tbl = $self->table_object;
131 my $fields = $tbl->fields;
132 return( $self->error( "Table ", $tbl->name, " has no such field \"$field\"." ) ) if( !CORE::exists( $fields->{ $field } ) );
133 my $code = $self->can( $field );
134 unless( defined( $code ) )
135 {
136 $code = sub
137 {
138 my $self = shift( @_ );
139 unless( $self->{ $field } )
140 {
141 my $fo = $tbl->fields( $field );
142 $fo->debug( ( $self->debug // 0 ) );
143 $fo->prefixed( $self->{prefixed} );
144 $fo->query_object( $self->table_object->query_object );
145 $fo->table_object( $self->table_object );
146 $self->{ $field } = $fo;
147 }
148 return( $self->{ $field } );
149 };
150 no strict 'refs';
151 *{"$field"} = $code;
152 }
153 my $o = $code->( $self );
154 return( $o );
155 }
156  
157 # NOTE: AUTOLOAD
158 AUTOLOAD
159 {
160 my( $method ) = our $AUTOLOAD =~ /([^:]+)$/;
161 # my( $class, $method ) = our $AUTOLOAD =~ /^(.*?)::([^\:]+)$/;
162 no overloading;
163 my $self = shift( @_ );
164 my $fields = $self->table_object->fields;
165 if( my $code = $self->can( $method ) )
166 {
167 return( $code->( $self, @_ ) );
168 }
169 elsif( exists( $fields->{ $method } ) )
170 {
171 return( $self->_initiate_field_object( $method ) );
172 }
173 else
174 {
175 # This is an unrecoverable error. We have no choice, but to die.
176 my $error = "Table " . $self->table_object->name . " has no such field \"$method\"";
177 $self->_load_class( 'Module::Generic::Exception' ) || die( $self->error );
178 my $exception = Module::Generic::Exception->new( $error );
179 my $on_unknown_field = $self->table_object->database_object->unknown_field;
180 if( ref( $on_unknown_field ) eq 'CODE' )
181 {
182 return( $on_unknown_field->({
183 table => $self->table_object,
184 field => $method,
185 error => $exception,
186 }) );
187 }
188 elsif( defined( $on_unknown_field ) && ( $on_unknown_field eq 'die' || $on_unknown_field eq 'fatal' ) )
189 {
190 die( $exception );
191 }
192 else
193 {
194 $self->_load_class( 'DB::Object::Fields::Unknown' ) ||
195 die( "${error}, and I could not load the module DB::Object::Fields::Unknown: ", $self->error );
196 my $unknown = DB::Object::Fields::Unknown->new(
197 table => $self->table_object->name,
198 error => $exception,
199 field => $method,
200 ) || die( "${error}, and I could not instantiate a new instance of the module DB::Object::Fields::Unknown: ", DB::Object::Fields::Unknown->error );
201 warn( "Table ", $self->table_object->name, " has no such field \"$method\".\n" ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
202 # return( $self->error( "Table ", $self->table_object->name, " has no such field \"$method\"." ) );
203 #die( "Table ", $self->table_object->name, " has no such field \"$method\".\n" );
204 return( $unknown );
205 }
206 }
207 };
208  
209 sub FREEZE
210 {
211 my $self = CORE::shift( @_ );
212 my $serialiser = CORE::shift( @_ ) // '';
213 my $class = CORE::ref( $self );
214  
215 # We keep a strict allow-list to avoid accidentally freezing DBI handles or other
216 # process-local state.
217 my @props = @{$self->{_fields}};
218  
219 my $hash = {};
220 foreach my $prop ( @props )
221 {
222 if( CORE::exists( $self->{ $prop } ) &&
223 defined( $self->{ $prop } ) &&
224 CORE::ref( $self->{ $prop } ) ne 'CODE' )
225 {
226 $hash->{ $prop } = $self->{ $prop };
227 }
228 }
229  
230 # Return an array reference rather than a list so this works with Sereal and CBOR.
231 # Before Sereal version 4.023, Sereal did not support multiple values returned.
232 if( $serialiser eq 'Sereal' )
233 {
234 require Sereal::Encoder;
235 require version;
236  
237 if( version->parse( Sereal::Encoder->VERSION ) < version->parse( '4.023' ) )
238 {
239 CORE::return( [$class, $hash] );
240 }
241 }
242  
243 # But Storable wants a list with the first element being the serialised element
244 CORE::return( $class, $hash );
245 }
246  
247 sub STORABLE_freeze { return( shift->FREEZE( @_ ) ); }
248  
249 sub STORABLE_thaw { return( shift->THAW( @_ ) ); }
250  
251 sub THAW
252 {
253 # STORABLE_thaw would issue $cloning as the 2nd argument, while CBOR would issue
254 # 'CBOR' as the second value.
255 my( $self, undef, @args ) = @_;
256 my $ref = ( CORE::scalar( @args ) == 1 && CORE::ref( $args[0] ) eq 'ARRAY' ) ? CORE::shift( @args ) : \@args;
257 my $class = ( CORE::defined( $ref ) && CORE::ref( $ref ) eq 'ARRAY' && CORE::scalar( @$ref ) > 1 ) ? CORE::shift( @$ref ) : ( CORE::ref( $self ) || $self );
258 my $hash = CORE::ref( $ref ) eq 'ARRAY' ? CORE::shift( @$ref ) : {};
259 my $new;
260 # Storable pattern requires to modify the object it created rather than returning a new one
261 if( CORE::ref( $self ) )
262 {
263 foreach( CORE::keys( %$hash ) )
264 {
265 $self->{ $_ } = CORE::delete( $hash->{ $_ } );
266 }
267 $new = $self;
268 }
269 else
270 {
271 $new = CORE::bless( $hash => $class );
272 }
273 CORE::return( $new );
274 }
275  
276 1;
277 # NOTE: POD
278 __END__
279  
280 =encoding utf8
281  
282 =head1 NAME
283  
284 DB::Object::Fields - Tables Fields Object Accessor
285  
286 =head1 SYNOPSIS
287  
288 my $dbh = DB::Object->connect({
289 driver => 'Pg',
290 conf_file => $conf,
291 database => 'my_shop',
292 host => 'localhost',
293 login => 'super_admin',
294 schema => 'auth',
295 unknown_field => 'fatal',
296 # debug => 3,
297 }) || bailout( "Unable to connect to sql server on host localhost: ", DB::Object->error );
298  
299 my $tbl = $dbh->some_table || die( "No table \"some_table\" could be found: ", $dbh->error, "\n" );
300 my $fo = $tbl->fields_object || die( $tbl->error );
301 my $expr = $fo->id == 2;
302 print "Expression is: $expr\n"; # Expression is: id = 2
303  
304 my $tbl_object = $dbh->customers || die( "Unable to get the customers table object: ", $dbh->error, "\n" );
305 my $fields = $tbl_object->fields;
306 print( "Fields for table \"", $tbl_object->name, "\": ", Dumper( $fields ), "\n" );
307 my $c = $tbl_object->fo->currency;
308 print( "Got field object for currency: \"", ref( $c ), "\": '$c'\n" );
309 printf( "Name: %s\n", $c->name );
310 printf( "Type: %s\n", $c->type );
311 printf( "Default: %s\n", $c->default );
312 printf( "Position: %s\n", $c->pos );
313 printf( "Table: %s\n", $c->table );
314 printf( "Database: %s\n", $c->database );
315 printf( "Schema: %s\n", $c->schema );
316 printf( "Next field: %s (%s)\n", $c->next, ref( $c->next ) );
317 print( "Showing name fully qualified: ", $c->prefixed( 3 )->name, "\n" );
318 ## would print: my_shop.public.customers.currency
319 print( "Trying again (should keep prefix): ", $c->name, "\n" );
320 ## would print again: my_shop.public.customers.currency
321 print( "Now cancel prefixing at the table fields level.\n" );
322 $tbl_object->fo->prefixed( 0 );
323 print( "Showing name fully qualified again (should not be prefixed): ", $c->name, "\n" );
324 ## would print currency
325 print( "First element is: ", $c->first, "\n" );
326 print( "Last element is: ", $c->last, "\n" );
327 # Works also with the operators +, -, *, /, %, <, <=, >, >=, !=, <<, >>, &, |, ^, ==
328 my $table = $dbh->dummy;
329 $table->select( $c + 10 ); # SELECT currency + 10 FROM dummy;
330 $c == 'NULL' # currency IS NULL
331  
332 # if DB::Object unknown_field option is set to fatal, this will die. By default, it will simply be ignored
333 my $unknown_field = $tbl->unknown;
334  
335 =head1 VERSION
336  
337 v1.3.0
338  
339 =head1 DESCRIPTION
340  
341 The purpose of this module is to enable access to the table fields as L<DB::Object::Fields::Field> objects.
342  
343 The way this works is by having L<DB::Object::Tables/fields_object> or L<DB::Object::Tables/fo> for short, dynamically create a class based on the database name and table name. For example if the database driver were C<PostgreSQL>, the database were C<my_shop> and the table C<customers>, the dynamically created package would become C<DB::Object::Postgres::Tables::MyShop::Customers>. This class would inherit from this package L<DB::Object::Fields>.
344  
345 Field objects can than be dynamically instantiated by accessing them, such as (assuming the table object C<$tbl_object> here represent the table C<customers>) C<$tbl_object->fo->last_name>. This will return a L<DB::Object::Fields::Field> object.
346  
347 A note on the design: there had to be a separate this separate package L<DB::Object::Fields>, because access to table fields is done through the C<AUTOLOAD> and the methods within the package L<DB::Object::Tables> and its inheriting packages would clash with the tables fields. This package has very few methods, so the risk of a sql table field clashing with a method name is very limited. In any case, if you have in your table a field with the same name as one of those methods here (see below for the list), then you can instantiate a field object with:
348  
349 $tbl_object->_initiate_field_object( 'last_name' );
350  
351 If you call an unknown field, its behaviour will change depending on the option value C<unknown_field> of L<DB::Object> upon instantiation:
352  
353 =over 4
354  
355 =item * C<ignore> (default)
356  
357 The unknown field will be ignored and a warning will be emitted that this field does not exist in the given database table.
358  
359 =item * C<fatal> or C<die>
360  
361 This will trigger a L</die> using a L<Module::Generic::Exception> object. So you could catch it like this:
362  
363 use Nice::Try;
364  
365 try
366 {
367 # $opts contains the property 'unknown_field' set to 'die'
368 my $dbh = DB::Object::Postgres->connect( $opts ) || die( "Unable to connect" );
369 my $tbl = $dbh->some_table || die( "Unable to get the database table \"some_table\": ", $dbh->error );
370 $tbl->where( $dbh->AND(
371 $tbl->fo->faulty_field == '?',
372 $tbl->fo->status == 'live',
373 ) );
374 my $ref = $tbl->select->fetchrow_hashref;
375 }
376 catch( $e isa( 'Module::Generic::Exception' ) )
377 {
378 die( "Caught error preparing SQL: $e" );
379 }
380 else
381 {
382 die( "Caught some other error." );
383 }
384  
385 =item * C<code reference>
386  
387 When the option C<unknown_field> is set to a code reference, this will be executed and passed an hash reference that will contain 3 properties:
388  
389 =over 8
390  
391 =item 1. C<table>
392  
393 The L<table object|DB::Object::Tables>
394  
395 =item 2. C<field>
396  
397 A regular string containing the unknown field name
398  
399 =item 3. C<error>
400  
401 The L<error object|Module::Generic::Exception>, which includes the error string and a stack trace
402  
403 =back
404  
405 =back
406  
407 By default, the unknown field will be ignored.
408  
409 =head1 CONSTRUCTOR
410  
411 =head2 new
412  
413 Creates a new L<DB::Object::Fields> objects. It may also take an hash like arguments, that also are method of the same name.
414  
415 =over 4
416  
417 =item I<debug>
418  
419 Toggles debug mode on/off
420  
421 =back
422  
423 =head1 METHODS
424  
425 =head2 database_object
426  
427 The database object, which is a L<DB::Object> object or one of its descendant.
428  
429 =head2 new_field
430  
431 This takes an hash or hash reference of parameters and instantiate a new L<DB::Object::Fields::Field> object and return it.
432  
433 If an error occurred, it sets an L<error object|Module::Generic::Exception> and return an empty list in list context or C<undef> in scalar context.
434  
435 =head2 prefixed
436  
437 This si the prefix level, from 0 to 2.
438  
439 2 or higher including the database, higher than 1 includes the schema name and above 0 includes the table name. 0 includes nothing.
440  
441 When this value is changed, it is propagated to all the fields objects.
442  
443 =head2 query_object
444  
445 The query object, which is a L<DB::Object::Query> object or one of its descendant.
446  
447 =head2 table_object
448  
449 The query object, which is a L<DB::Object::Tables> object or one of its descendant.
450  
451 =head2 _initiate_field_object
452  
453 This method is called from C<AUTOLOAD>
454  
455 Provided with a table column name and this will create a new L<DB::Object::Fields::Field> object and add dynamically the associated method for this column in the current package so that next time, it returns the cached object without using C<AUTOLOAD>
456  
457 =head1 AUTOLOAD
458  
459 Called with a column name and this will check if the given column name actually exists in this table. If it does, it will call L</_initiate_field_object> to instantiate a new field object and returns it.
460  
461 If the column does not exist, it returns an error.
462  
463 =head1 SEE ALSO
464  
465 L<perl>
466  
467 =head1 AUTHOR
468  
469 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
470  
471 =head1 COPYRIGHT & LICENSE
472  
473 Copyright (c) 2020-2021 DEGUEST Pte. Ltd.
474  
475 You can use, copy, modify and redistribute this package and associated
476 files under the same terms as Perl itself.
477  
478 =cut