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

filter: Statementstmt 0.0% 0 / 278 Branchbran 0.0% 0 / 92 Conditioncond 0.0% 0 / 67 MC/DCmcdc 0.0% 0 / 37 Subroutinesub 0.0% 0 / 58 Podpod 0.0% 0 / 42 totaltotal 0.0% 0 / 574 CC 47 SCAR 45.3
CC
47
Cov
0%
_op_overload
420.0
name
56.0
THAW
42.0
CRAP 92.8
1 ##----------------------------------------------------------------------------
2 ## Database Object Interface - ~/lib/DB/Object/Fields/Field.pm
3 ## Version v1.4.0
4 ## Copyright(c) 2026 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2020/01/01
7 ## Modified 2026/03/27
8 ## All rights reserved
9 ##
10 ## This program is free software; you can redistribute it and/or modify it
11 ## under the same terms as Perl itself.
12 ##----------------------------------------------------------------------------
13 package DB::Object::Fields::Field;
14 BEGIN
15 {
16 use strict;
17 use warnings;
18 warnings::register_categories( 'DB::Object' );
19 use common::sense;
20 use parent qw( Module::Generic );
21 use vars qw( $VERSION $FIELD_NAMES $EXCEPTION_CLASS );
22 use DB::Object::Fields::Overloaded;
23 use Scalar::Util qw( weaken );
24 use Module::Generic::Array;
25 use overload (
26 '""' => 'as_string',
27 'bool' => sub{1},
28 '+' => sub{ &_op_overload( @_, '+' ) },
29 '-' => sub{ &_op_overload( @_, '-' ) },
30 '*' => sub{ &_op_overload( @_, '*' ) },
31 '/' => sub{ &_op_overload( @_, '/' ) },
32 '%' => sub{ &_op_overload( @_, '%' ) },
33 '<' => sub{ &_op_overload( @_, '<' ) },
34 '>' => sub{ &_op_overload( @_, '>' ) },
35 '<=' => sub{ &_op_overload( @_, '<=' ) },
36 '>=' => sub{ &_op_overload( @_, '>=' ) },
37 # In most SQL driver, '<>' is more portable tan '!='
38 '!=' => sub{ &_op_overload( @_, '<>' ) },
39 '<<' => sub{ &_op_overload( @_, '<<' ) },
40 '>>' => sub{ &_op_overload( @_, '>>' ) },
41 'lt' => sub{ &_op_overload( @_, '<' ) },
42 'gt' => sub{ &_op_overload( @_, '>' ) },
43 'le' => sub{ &_op_overload( @_, '<=' ) },
44 'ge' => sub{ &_op_overload( @_, '>=' ) },
45 'ne' => sub{ &_op_overload( @_, '<>' ) },
46 '&' => sub{ &_op_overload( @_, '&' ) },
47 '^' => sub{ &_op_overload( @_, '^' ) },
48 '|' => sub{ &_op_overload( @_, '|' ) },
49 '==' => sub{ &_op_overload( @_, '=' ) },
50 'eq' => sub{ &_op_overload( @_, 'IS' ) },
51 # Full Text Search operator
52 '~~' => sub{ &_op_overload( @_, '@@' ) },
53 fallback => 1,
54 );
55 use Wanted;
56 our $VERSION = 'v1.4.0';
57 our $FIELD_NAMES = [qw(
58 check_name comment datatype default foreign_name index_name is_array is_check
59 is_foreign is_nullable is_primary is_unique name pos prefixed size type
60 )];
61 our $EXCEPTION_CLASS = $DB::Object::EXCEPTION_CLASS;
62 };
63  
64 use strict;
65 use warnings;
66  
67 sub init
68 {
69 my $self = shift( @_ );
70 $self->{check_name} = undef;
71 $self->{comment} = undef;
72 $self->{datatype} = undef;
73 $self->{default} = undef;
74 $self->{foreign_name} = undef;
75 $self->{index_name} = undef;
76 $self->{is_array} = undef;
77 $self->{is_check} = undef;
78 $self->{is_foreign} = undef;
79 $self->{is_nullable} = undef;
80 $self->{is_primary} = undef;
81 $self->{is_unique} = undef;
82 $self->{name} = undef;
83 $self->{pos} = undef;
84 $self->{prefixed} = 0;
85 $self->{query_object} = undef;
86 $self->{size} = undef;
87 $self->{table_object} = undef;
88 $self->{type} = undef;
89 $self->{_init_params_order} = [qw( table_object query_object default pos type prefixed name )];
90 $self->{_init_strict_use_sub} = 1;
91 $self->{_exception_class} = $EXCEPTION_CLASS;
92 $self->SUPER::init( @_ ) || return( $self->pass_error );
93 $self->{_fields} = $FIELD_NAMES;
94 # return( $self->error( "No table object was provided." ) ) if( !$self->{table_object} );
95 # return( $self->error( "Table object provided is not an object." ) ) if( !$self->_is_object( $self->{table_object} ) );
96 # return( $self->error( "Table object provided is not a DB::Object::Tables object." ) ) if( !$self->{table_object}->isa( 'DB::Object::Tables' ) );
97 # return( $self->error( "No name was provided for this field." ) ) if( !$self->{name} );
98 return( $self );
99 }
100  
101 sub as_string { return( shift->name ); }
102  
103 # We attach this field to its table object
104 sub attach
105 {
106 my $self = shift( @_ );
107 my $tbl = shift( @_ ) ||
108 return( $self->error( "No DB::Object::Tables object was provided." ) );
109 my $base_class = $self->base_class( $tbl );
110 unless( $self->_is_a( $tbl => "${base_class}::Tables" ) )
111 {
112 return( $self->error( "Value provided is not a ${base_class}::Tables object." ) );
113 }
114 $self->table_object( $tbl ) || return( $self->pass_error );
115 $self->debug( $tbl->debug );
116 return( $self );
117 }
118  
119 sub base_class
120 {
121 my $self = shift( @_ );
122 my $this = @_ ? shift( @_ ) : $self;
123 my $class = ref( $this ) ? ref( $this ) : $this;
124 no warnings 'once';
125 my @supported_classes = CORE::values( %$DB::Object::DRIVER2PACK );
126 push( @supported_classes, 'DB::Object' );
127 my $ok_classes = CORE::join( '|', CORE::map{ CORE::quotemeta( $_ ) } @supported_classes );
128 my $base_class = ( $class =~ /^($ok_classes)/ )[0];
129 return( $base_class );
130 }
131  
132 sub clone
133 {
134 my $self = shift( @_ );
135 # Fields to clone: we explicitly want to avoid cloning query_object, because it is not necessary and because it contains an object to the database connection that we do not want to clone.
136 # Likewise, the query object, we do not want to clone either.
137 # my $keys = [qw( default is_nullable name pos prefixed size type )];
138 my $keys = $self->_fields;
139 $keys = $self->new_array( $FIELD_NAMES ) if( !scalar( @$keys ) );
140 my $hash = {};
141 @$hash{ @$keys } = @$self{ @$keys };
142 # $hash->{datatype} = {};
143 # for( qw( alias constant name re type ) )
144 # {
145 # $hash->{datatype}->{ $_ } = $self->datatype->$_;
146 # }
147 my $dt = $self->datatype;
148 $hash->{datatype} =
149 {
150 alias => $dt->alias->clone,
151 constant => $dt->{constant},
152 name => $dt->{name},
153 re => $dt->{re},
154 type => $dt->{type},
155 };
156 $self->_load_class( 'Clone' ) || return( $self->pass_error );
157 my $copy = Clone::clone( $hash );
158 $copy->{query_object} = $self->query_object;
159 $copy->{table_object} = $self->table_object;
160 $copy->{debug} = $self->debug;
161 my $new = $self->new( %$copy ) || return( $self->pass_error );
162 return( $new );
163 }
164  
165 sub check_name { return( shift->_set_get_scalar( 'check_name', @_ ) ); }
166  
167 sub comment { return( shift->_set_get_scalar( 'comment', @_ ) ); }
168  
169 # A data type constant
170 # sub constant { return( shift->_set_get_hash_as_object( 'constant', @_ ) ); }
171 sub constant { return( shift->datatype->constant( @_ ) ); }
172  
173 sub database { return( shift->database_object->database ); }
174  
175 sub database_object { return( shift->table_object->database_object ); }
176  
177 sub datatype { return( shift->_set_get_class( 'datatype', {
178 alias => { type => 'array_as_object' },
179 constant => { type => 'scalar' },
180 name => { type => 'scalar_as_object' },
181 re => { type => 'object', package => 'Regexp' },
182 type => { type => 'scalar_as_object' },
183 }, @_ ) ); }
184  
185 sub default { return( shift->_set_get_scalar( 'default', @_ ) ); }
186  
187 sub foreign_name { return( shift->_set_get_scalar( 'foreign_name', @_ ) ); }
188  
189 sub first { return( shift->_find_siblings(1) ); }
190  
191 sub index_name { return( shift->_set_get_scalar( 'index_name', @_ ) ); }
192  
193 sub is_array { return( shift->_set_get_boolean( 'is_array', @_ ) ); }
194  
195 sub is_check { return( shift->_set_get_boolean( 'is_check', @_ ) ); }
196  
197 sub is_foreign { return( shift->_set_get_boolean( 'is_foreign', @_ ) ); }
198  
199 sub is_nullable { return( shift->_set_get_boolean( 'is_nullable', @_ ) ); }
200  
201 sub is_primary { return( shift->_set_get_boolean( 'is_primary', @_ ) ); }
202  
203 sub is_unique { return( shift->_set_get_boolean( 'is_unique', @_ ) ); }
204  
205 sub last
206 {
207 my $self = shift( @_ );
208 my $fields = $self->table_object->fields;
209 my $pos = scalar( keys( %$fields ) );
210 return( $self->_find_siblings( $pos ) );
211 }
212  
213 sub name
214 {
215 my $self = shift( @_ );
216 no overloading;
217 if( @_ )
218 {
219 my $name = shift( @_ );
220 if( !defined( $name ) || !CORE::length( $name // '' ) )
221 {
222 return( $self->error( "You can not set the table column name to be undefined or an empty string." ) );
223 }
224 $self->{name} = $name;
225 }
226 my $name = $self->{name};
227 my $alias = $self->query_object->table_alias;
228 if( $self->{prefixed} )
229 {
230 my @prefix = ();
231 if( length( $alias ) )
232 {
233 CORE::push( @prefix, $alias );
234 }
235 else
236 {
237 # if the value is higher than 1, we also add the database name as a prefix
238 # For example $tbl->fields->some_field->prefixed(2)->name
239 push( @prefix, $self->database ) if( $self->{prefixed} > 2 );
240 push( @prefix, $self->table_object->schema ) if( $self->{prefixed} > 1 && CORE::length( $self->table_object->schema ) );
241 push( @prefix, $self->table );
242 }
243 push( @prefix, $name );
244 return( join( '.', @prefix ) );
245 }
246 else
247 {
248 return( $name );
249 }
250 }
251  
252 sub next
253 {
254 my $self = shift( @_ );
255 return( $self->_find_siblings( $self->pos + 1 ) );
256 }
257  
258 sub pos { return( shift->_set_get_scalar( 'pos', @_ ) ); }
259  
260 sub prefixed
261 {
262 my $self = shift( @_ );
263 if( @_ )
264 {
265 $self->{prefixed} = ( $_[0] =~ /^\d+$/ ? $_[0] : ( $_[0] ? 1 : 0 ) );
266 }
267 else
268 {
269 $self->{prefixed} = 1;
270 }
271 return( want( 'OBJECT' ) ? $self : $self->{prefixed} );
272 }
273  
274 sub prev
275 {
276 my $self = shift( @_ );
277 return( $self->_find_siblings( $self->pos - 1 ) );
278 }
279  
280 # sub query_object { return( shift->_set_get_object_without_init( 'query_object', 'DB::Object::Query', @_ ) ); }
281 sub query_object { return( shift->table_object->query_object ); }
282  
283 sub schema { return( shift->table_object->schema ); }
284  
285 sub size { return( shift->_set_get_number( 'size', @_ ) ); }
286  
287 sub table { return( shift->table_object->name ); }
288  
289 sub table_name { return( shift->table_object->name ); }
290  
291 sub table_object { return( shift->_set_get_object_without_init( 'table_object', 'DB::Object::Tables', @_ ) ); }
292  
293 sub type { return( shift->_set_get_scalar( 'type', @_ ) ); }
294  
295 sub _fields { return( shift->_set_get_array_as_object( '_fields', @_ ) ); }
296  
297 sub _find_siblings
298 {
299 my $self = shift( @_ );
300 my $pos = shift( @_ );
301 return( $self->error( "No field position provided." ) ) if( !CORE::length( $pos ) );
302 return if( $pos < 0 );
303 my $fields = $self->table_object->fields;
304 my $next_field;
305 foreach my $f ( sort{ $fields->{ $a } <=> $fields->{ $b } } keys( %$fields ) )
306 {
307 if( $fields->{ $f } == $pos )
308 {
309 $next_field = $f;
310 CORE::last;
311 }
312 }
313 return if( !defined( $next_field ) );
314 my $o = $self->table_object->fields_object->_initiate_field_object( $next_field ) ||
315 return( $self->pass_error( $self->table_object->fields_object->error ) );
316 return( $o );
317 }
318  
319 # Ref:
320 # <https://www.postgresql.org/docs/10/functions-comparison.html>
321 # <https://www.postgresql.org/docs/10/functions-math.html>
322 # <https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html>
323 # <https://sqlite.org/lang_expr.html>
324 sub _op_overload
325 {
326 my( $self, $val, $swap, $op ) = @_;
327 if( $self->_is_a( $val => [qw( DB::Object::IN DB::Object::LIKE )] ) )
328 {
329 return( $val->_opt_overload( $self, 1, $op ) );
330 }
331  
332 my $field = $self->name;
333 my $map =
334 {
335 '!=' => '<>',
336 'lt' => '<',
337 'gt' => '>',
338 'le' => '<=',
339 'ge' => '>=',
340 # '=' works for all types, but IS does not work with everything.
341 # For example:
342 # select * from ip_table where ip_addr IS inet '192.168.2.12' OR inet '192.168.2.12' << ip_addr
343 # does not work, but
344 # select * from ip_table where ip_addr = inet '192.168.2.12' OR inet '192.168.2.12' << ip_addr
345 # works better
346 '==' => '=',
347 };
348 $op = $map->{ $op } if( exists( $map->{ $op } ) );
349 my $dbo = $self->database_object;
350 my $qo = $self->query_object;
351 my $placeholder_re = $dbo->_placeholder_regexp;
352 my $const = $self->datatype->constant;
353 # When the RHS is NULL, SQL requires IS NULL / IS NOT NULL - never = NULL or <> NULL,
354 # as those predicates always evaluate to NULL (never TRUE) per the SQL standard.
355 if( !ref( $val ) && uc( $val ) eq 'NULL' )
356 {
357 my $null_expr = $op eq '<>' ? "${field} IS NOT NULL" : "${field} IS NULL";
358 my $null_overloaded = DB::Object::Fields::Overloaded->new(
359 expression => $null_expr,
360 field => $self,
361 query_object => $qo,
362 debug => $self->debug,
363 );
364 weaken( $null_overloaded->{query_object} ) if( $null_overloaded && $null_overloaded->{query_object} );
365 return( $null_overloaded );
366 }
367 # If the value specified in the operation is a placeholder, or a field object or a statement object, we do not want to quote process it
368 unless( $val =~ /$placeholder_re/ ||
369 ( $self->_is_object( $val ) &&
370 (
371 $val->isa( 'DB::Object::Fields::Field' ) ||
372 $val->isa( 'DB::Object::Statement' )
373 )
374 ) ||
375 $dbo->placeholder->has( \$val ) ||
376 $self->_is_scalar( $val ) ||
377 uc( $val ) eq 'NULL' )
378 {
379 $val = $dbo->quote( $val, $const ) if( $dbo );
380 }
381  
382 my $types;
383 # If the value is a statement object, stringify it, surround it with parenthesis and use it
384 if( $self->_is_a( $val, 'DB::Object::Statement' ) )
385 {
386 $qo->elements->merge( $val->query_object->elements );
387 $val = '(' . $val->as_string . ')';
388 }
389 elsif( $dbo->placeholder->has( $self->_is_scalar( $val ) ? $val : \$val ) )
390 {
391 $types = $dbo->placeholder->replace( $self->_is_scalar( $val ) ? $val : \$val );
392 }
393 # A placeholder (pure: ?) or embedded (e.g. UPPER(?), COALESCE(?,?)):
394 # count the number of placeholders in $val and register one empty type per bind slot.
395 elsif( $val =~ /$placeholder_re/ )
396 {
397 my @matches = ( $val =~ /$placeholder_re/g );
398 $types = Module::Generic::Array->new( [ ( '' ) x scalar( @matches ) ] );
399 }
400 elsif( $self->_is_scalar( $val ) )
401 {
402 $val = $$val;
403 }
404 # return( DB::Object::Fields::Overloaded->new(
405 # expression =>
406 # (
407 # $swap
408 # ? "${val} ${op} ${field}"
409 # : "${field} ${op} ${val}"
410 # ),
411 # field => $self,
412 # # binded => ( $val =~ /^$placeholder_re$/ || $types ) ? 1 : 0,
413 # ( $val =~ /^$placeholder_re$/ ? ( placeholder => $val ) : () ),
414 # type => $self->type,
415 # # query_object => $self->query_object,
416 # debug => $self->debug,
417 # ( $val !~ /^$placeholder_re$/ ? ( value => $val ) : () ),
418 # # binded_offset => ( $val =~ /^$placeholder_re$/ && defined( $+{offset} ) ) ? ( $+{offset} - 1 ) : undef,
419 # # types => $types,
420 # ) );
421 # Capture the placeholder before calling new() - $1 can be clobbered by any
422 # subsequent regex match inside the argument list evaluation or inside new() itself.
423 my $captured_placeholder = ( $val =~ /($placeholder_re)/ ) ? $1 : undef;
424 my $over = DB::Object::Fields::Overloaded->new(
425 expression =>
426 (
427 $swap
428 ? "${val} ${op} ${field}"
429 : "${field} ${op} ${val}"
430 ),
431 field => $self,
432 # query_object must be initialised before placeholder, because the placeholder
433 # setter calls $self->query_object->database_object->_placeholder_regexp
434 query_object => $qo,
435 debug => $self->debug,
436 ( defined( $captured_placeholder ) ? ( placeholder => $captured_placeholder ) : () ),
437 # Actually type() will return us the actual data type, not the driver constant
438 # type => $self->type,
439 ( defined( $const ) ? ( type => $const ) : () ),
440 ( !defined( $captured_placeholder ) ? ( value => $val ) : () ),
441 # binded_offset => ( defined( $captured_placeholder ) && defined( $+{index} ) ) ? ( $+{index} - 1 ) : undef,
442 # types => $types,
443 );
444 weaken( $over->{query_object} ) if( $over && $over->{query_object} );
445 return( $over );
446 }
447  
448 sub FREEZE
449 {
450 my $self = CORE::shift( @_ );
451 my $serialiser = CORE::shift( @_ ) // '';
452 my $class = CORE::ref( $self );
453  
454 # We keep a strict allow-list to avoid accidentally freezing DBI handles or other
455 # process-local state.
456 my @props = grep( $_ ne 'datatype', @{$self->{_fields}} );
457  
458 my $hash = {};
459 foreach my $prop ( @props )
460 {
461 if( CORE::exists( $self->{ $prop } ) &&
462 defined( $self->{ $prop } ) &&
463 CORE::ref( $self->{ $prop } ) ne 'CODE' )
464 {
465 $hash->{ $prop } = $self->{ $prop };
466 }
467 }
468  
469 my $datatype = $self->datatype;
470 my $dtype_ref = {};
471 if( $datatype )
472 {
473 $dtype_ref->{alias} = $datatype->alias;
474 $dtype_ref->{constant} = $datatype->constant;
475 $dtype_ref->{name} = $datatype->name;
476 $dtype_ref->{re} = $datatype->re;
477 $dtype_ref->{type} = $datatype->type;
478 }
479 $hash->{datatype} = $dtype_ref;
480  
481 # Return an array reference rather than a list so this works with Sereal and CBOR.
482 # Before Sereal version 4.023, Sereal did not support multiple values returned.
483 if( $serialiser eq 'Sereal' )
484 {
485 require Sereal::Encoder;
486 require version;
487  
488 if( version->parse( Sereal::Encoder->VERSION ) < version->parse( '4.023' ) )
489 {
490 CORE::return( [$class, $hash] );
491 }
492 }
493  
494 # But Storable wants a list with the first element being the serialised element
495 CORE::return( $class, $hash );
496 }
497  
498 sub STORABLE_freeze { return( shift->FREEZE( @_ ) ); }
499  
500 sub STORABLE_thaw { return( shift->THAW( @_ ) ); }
501  
502 sub THAW
503 {
504 # STORABLE_thaw would issue $cloning as the 2nd argument, while CBOR would issue
505 # 'CBOR' as the second value.
506 my( $self, undef, @args ) = @_;
507 my $ref = ( CORE::scalar( @args ) == 1 && CORE::ref( $args[0] ) eq 'ARRAY' ) ? CORE::shift( @args ) : \@args;
508 my $class = ( CORE::defined( $ref ) && CORE::ref( $ref ) eq 'ARRAY' && CORE::scalar( @$ref ) > 1 ) ? CORE::shift( @$ref ) : ( CORE::ref( $self ) || $self );
509 my $hash = CORE::ref( $ref ) eq 'ARRAY' ? CORE::shift( @$ref ) : {};
510 my $dtype = CORE::delete( $hash->{datatype} );
511 my $new;
512 # Storable pattern requires to modify the object it created rather than returning a new one
513 if( CORE::ref( $self ) )
514 {
515 foreach( CORE::keys( %$hash ) )
516 {
517 $self->{ $_ } = CORE::delete( $hash->{ $_ } );
518 }
519 $new = $self;
520 }
521 else
522 {
523 $new = CORE::bless( $hash => $class );
524 }
525 $new->datatype( %$dtype ) if( $dtype );
526 CORE::return( $new );
527 }
528  
529 1;
530 # NOTE: POD
531 __END__