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

filter: Statementstmt 0.0% 0 / 277 Branchbran 0.0% 0 / 92 Conditioncond 0.0% 0 / 67 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 58 Podpod 0.0% 0 / 42 totaltotal 0.0% 0 / 536 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 ##
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::Field;
15 BEGIN
16 {
17 use strict;
18 use warnings;
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__
532  
533 =encoding utf8
534  
535 =head1 NAME
536  
537 DB::Object::Fields::Field - Table Field Object
538  
539 =head1 SYNOPSIS
540  
541 my $dbh = DB::Object->connect({
542 driver => 'Pg',
543 conf_file => $conf,
544 database => 'my_shop',
545 host => 'localhost',
546 login => 'super_admin',
547 schema => 'auth',
548 # debug => 3,
549 }) || bailout( "Unable to connect to sql server on host localhost: ", DB::Object->error );
550 my $tbl_object = $dbh->customers || die( "Unable to get the customers table object: ", $dbh->error, "\n" );
551 my $fields = $tbl_object->fields;
552 print( "Fields for table \"", $tbl_object->name, "\": ", Dumper( $fields ), "\n" );
553 my $c = $tbl_object->fo->currency;
554 print( "Got field object for currency: \"", ref( $c ), "\": '$c'\n" );
555 printf( "Name: %s\n", $c->name );
556 printf( "Type: %s\n", $c->type );
557 printf( "Default: %s\n", $c->default );
558 printf( "Is nullable: %s\n", $c->is_nullable );
559 printf( "Is primary key: %s\n", $c->is_primary );
560 printf( "Is an array: %s\n", $c->is_array );
561 printf( "Position: %s\n", $c->pos );
562 # For example for varchar, this could be 255 based on the table schema
563 printf( "Size: %s\n", $c->size );
564 printf( "Table: %s\n", $c->table );
565 printf( "Database: %s\n", $c->database );
566 printf( "Schema: %s\n", $c->schema );
567 printf( "Field comment: %s\n", $c->comment );
568 printf( "Constant value: %s\n", $c->datatype->constant ); # 12
569 printf( "Constant name: %s\n", $c->datatype->name ); # For example: SQL_VARCHAR
570 printf( "Constant type: %s\n", $c->datatype->type ); # varchar
571 printf( "Next field: %s (%s)\n", $c->next, ref( $c->next ) );
572 print( "Showing name fully qualified: ", $c->prefixed(3)->name, "\n" );
573 # would print: my_shop.public.customers.currency
574 print( "Trying again (should keep prefix): ", $c->name, "\n" );
575 # would print again: my_shop.public.customers.currency
576 print( "Now cancel prefixing at the table fields level.\n" );
577 $tbl_object->fo->prefixed( 0 );
578 print( "Showing name fully qualified again (should not be prefixed): ", $c->name, "\n" );
579 # would print currency
580 print( "First element is: ", $c->first, "\n" );
581 print( "Last element is: ", $c->last, "\n" );
582 # Works also with the operators +, -, *, /, %, <, <=, >, >=, !=, <<, >>, &, |, ^, ==
583 my $table = $dbh->dummy;
584 $table->select( $c + 10 ); # SELECT currency + 10 FROM dummy;
585 $c == 'NULL' # currency IS NULL
586  
587 You can also use a L<DB::Object::Statement> as a value in the operation:
588  
589 my $tbl = $dbh->services || die( "Unable to get the table object \"services\": ", $dbh->error );
590 my $userv_tbl = $dbh->user_services || die( "Unable to get the table object \"user_services\": ", $tbl->->error );
591 $tbl->where( $tbl->fo->name == '?' );
592 my $sub_sth = $tbl->select( 'id' ) || die( "Unable to prepare the sql query to get the service id: ", $tbl->error );
593 $userv_tbl->where(
594 $dbh->AND(
595 $tbl->fo->user_id == '?',
596 $tbl->fo->service_id == $sub_sth
597 )
598 );
599 my $query = $userv_tbl->delete->as_string || die( $tbl->error );
600  
601 This would yield:
602  
603 DELETE FROM user_services WHERE user_id = ? AND name = (SELECT id FROM services WHERE name = ?)
604  
605 =head1 VERSION
606  
607 v1.4.0
608  
609 =head1 DESCRIPTION
610  
611 This is a table field object as instantiated by L<DB::Object::Fields>
612  
613 =head1 CONSTRUCTOR
614  
615 =head2 new
616  
617 Takes an hash or hash reference of parameters and this will create a new L<DB::Object::Fields::Field> object.
618  
619 =over 4
620  
621 =item * C<check_name>
622  
623 Specifies the name of the check constraint associated wit this field.
624  
625 =item * C<comment>
626  
627 Specifies the field comment, if any.
628  
629 =item * C<datatype>
630  
631 Specifies an hash of key-value pairs, namely: C<name>, C<constant>, C<type> and C<re>
632  
633 =item * C<debug>
634  
635 Toggles debug mode on/off
636  
637 =item * C<default>
638  
639 Specifies the default field value.
640  
641 =item * C<foreign_name>
642  
643 Specifies the name of the foreign key constraint associated wit this field.
644  
645 =item * C<index_name>
646  
647 Specifies the index name to which this field is related.
648  
649 =item * C<is_array>
650  
651 Specifies a boolean value whether the field value represents an array or not.
652  
653 =item * C<is_check>
654  
655 Specifies a boolean value whether the field is associated with a check constraint or not.
656  
657 =item * C<is_foreign>
658  
659 Specifies a boolean value whether the field is associated with a foreign key constraint or not.
660  
661 =item * C<is_nullable>
662  
663 Specifies a boolean value whether the field value can be null or not.
664  
665 =item * C<is_primary>
666  
667 Specifies a boolean value whether the field is the primary key for its table or not.
668  
669 =item * C<is_unique>
670  
671 Specifies a boolean value whether the field is part of a unique index or not.
672  
673 =item * C<name>
674  
675 The table column name.
676  
677 An error will be returned if this value is not provided upon instantiation.
678  
679 =item * C<pos>
680  
681 The table column position in the table.
682  
683 =item * C<prefixed>
684  
685 Defaults to 0
686  
687 =item * C<query_object>
688  
689 The L<DB::Object::Query> object.
690  
691 =item * C<size>
692  
693 Set the field size, such as for varchar.
694  
695 Defaults to C<undef>
696  
697 =item * C<table_object>
698  
699 The L<DB::Object::Tables> object.
700  
701 An error will be returned if this value is not provided upon instantiation.
702  
703 =item * C<type>
704  
705 The column data type.
706  
707 =back
708  
709 =head1 METHODS
710  
711 =head2 as_string
712  
713 This returns the name of the field, possibly prefixed
714  
715 This is also called to stringify the object
716  
717 print( "Field is: $field\n" );
718  
719 =head2 attach
720  
721 This takes a table object, and attach it to our current object.
722  
723 This returns the current object upon success, or upon error, it sets an L<error object|DB::Object::Exception>, and returns C<undef> in scalar context, or an empty list in list context.
724  
725 =head2 base_class
726  
727 Returns the base class, such as C<DB::Object::Postgres> or C<DB::Object::SQLite>
728  
729 =head2 clone
730  
731 Makes a clone of the object and returns it.
732  
733 However, it does not makes a clone of the entire field object, but instead leaves out the L<query object|DB::Object::Query> and the L<table object|DB::Object::Tables>
734  
735 =head2 constant
736  
737 A data type constant set by L<DB::Object::Table/structure>. This helps determine how to deal with some fields.
738  
739 This is an hash object that contains 3 properties:
740  
741 =over 4
742  
743 =item * C<constant>
744  
745 An integer set by the database driver to represent the constant
746  
747 =item * C<name>
748  
749 The constant name, e.g. C<PG_JSONB>
750  
751 =item * C<type>
752  
753 The data type, e.g. C<jsonb>
754  
755 =back
756  
757 =head2 check_name
758  
759 Sets or gets the optional name of the check constraint associated with this field.
760  
761 =head2 comment
762  
763 Sets or gets the optional comment that may have been set for this table field.
764  
765 =head2 database
766  
767 Sets or gets the name of the database this field is attached to.
768  
769 =head2 database_object
770  
771 Returns the database object, ie the one used to make sql queries
772  
773 =head2 default
774  
775 Sets or gets the default value, if any, for that field.
776  
777 =head2 foreign_name
778  
779 Sets or gets the optional name of the foreign key constraint associated with this field.
780  
781 =head2 first
782  
783 Returns the first field in the table.
784  
785 =head2 index_name
786  
787 Sets or gets the index name to which this field is related. Defaults to C<undef>
788  
789 =head2 is_array
790  
791 Sets or gets true if the field is an array, or false otherwise.
792  
793 =head2 is_check
794  
795 Sets or gets true if the field is associated with a check constraint, or false otherwise.
796  
797 =head2 is_foreign
798  
799 Sets or gets true if the field is associated with a foreign key constraint, or false otherwise.
800  
801 =head2 is_nullable
802  
803 Sets or gets true if the field can be null, or false otherwise.
804  
805 =head2 is_primary
806  
807 Sets or gets true if the field is the primary key of the table, or false otherwise.
808  
809 =head2 is_unique
810  
811 Sets or gets true if the field is part of a unique index, or false otherwise.
812  
813 If it is, check out the value for L<index_name|/index_name>
814  
815 =head2 last
816  
817 Returns the last field in the table.
818  
819 =head2 name
820  
821 Sets or gets the field name. This is also what is returned when object is stringified. For example
822  
823 my $c = $tbl_object->fo->last_name;
824 print( "$c\n" );
825 # will produce "last_name"
826  
827 The output is altered by the use of B<prefixed>. See below.
828  
829 =head2 next
830  
831 Returns the next field object.
832  
833 =head2 pos
834  
835 Sets or gets the position of the field in the table. This is an integer starting from 1.
836  
837 =head2 prefixed
838  
839 Called without argument, this will instruct the field name to be returned prefixed by the table name.
840  
841 print( $tbl_object->fo->last_name->prefixed, "\n" );
842 # would produce my_shop.last_name
843  
844 B<prefixed> can also be called with an integer as argument. 1 will prefix it with the table name, 2 with the schema name and 3 with the database name.
845  
846 =head2 prev
847  
848 Returns the previous field object.
849  
850 =head2 query_object
851  
852 Sets or gets the query object (L<DB::Object::Query> or one of its descendant)
853  
854 =head2 schema
855  
856 Returns the table schema to which this field is attached.
857  
858 =head2 size
859  
860 Sets or gets the size of the field when appropriate, such as when the type is C<varchar> or C<char>
861  
862 =head2 table
863  
864 Returns the table name for this field.
865  
866 =head2 table_name
867  
868 Same as above. This returns the table name.
869  
870 =head2 table_object
871  
872 Sets or gets the table object which is a L<DB::Object::Tables> object.
873  
874 =head2 type
875  
876 Returns the field type such as C<jsonb>, C<json>, C<varchar>, C<integer>, etc.
877  
878 See also L</constant> for an even more accurate data type, and the driver associated constant that is used for binding values to placeholders.
879  
880 =head2 _find_siblings
881  
882 Given a field position from 1 to n, this will find and return the field object. It returns undef or empty list if none could be found.
883  
884 =head1 OVERLOADING
885  
886 The following operators are overloaded:
887  
888 +, -, *, /, %, <, <=, >, >=, !=, <<, >>, lt, gt, le, ge, ne, &, |, ^, ==, eq, ~~
889  
890 Thus a field named "dummy" could be used like:
891  
892 $f + 10
893  
894 which would become:
895  
896 dummy + 10
897  
898 And this works too:
899  
900 10 + $f # 10 + dummy
901  
902 Another example, which works in PostgreSQL:
903  
904 $ip_tbl->where( 'inet 192.16.1.20' << $ip_tbl->fo->ip_addr );
905 my $ref = $ip_tbl->select->fetchrow_hashref;
906  
907 The equal operator C<==> would become C<=>:
908  
909 $f == 'NULL' # dummy = NULL
910  
911 but, if you use perl's C<eq> instead of C<==>, you would get:
912  
913 $f eq 'NULL' # dummy IS NULL
914  
915 Note that you have to take care of quotes yourself, because there is no way to tell if the right hand side is a string or a function
916  
917 $f == q{'JPY'} # dummy IS 'JPY'
918  
919 or, to insert a placeholder
920  
921 $f == '?' # dummy = ?
922 # or;
923 $f eq '?' # dummy IS ?
924 my $sth = $table->select( $f eq '?' ); # SELECT dummy IS ? FROM some_table
925 my $row = $sth->exec( 'JPY' )->fetchrow;
926  
927 of course
928  
929 my $sth = $table->select( dummy => '?' );
930  
931 also works
932  
933 The C<=~> and C<!~> operators cannot be overloaded in perl, so for regular expressions, use the C<REGEXP> function if available, or provided the expression directly as a string:
934  
935 $table->select( "currency ~ '^[A-Z]{3}$'" );
936  
937 If you want to use placeholder in the value provided, you will have to provide a C<?> in the value next to the operator. This module will not parse the value used with the operation, so if you wanted to use a placeholder in:
938  
939 $f == "'JPY'"
940  
941 Simply provide:
942  
943 $f == '?'
944  
945 You can use the search operator C<~~> for SQL Full Text Search and it would be converted into C<@@>:
946  
947 Let's imagine a table C<articles> in a L<PostgreSQL database|https://www.postgresql.org/docs/current/textsearch.html>, such as:
948  
949 CREATE TABLE articles (
950 id SERIAL PRIMARY KEY,
951 title TEXT NOT NULL,
952 content TEXT NOT NULL,
953 ts TSVECTOR GENERATED ALWAYS AS
954 (setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
955 setweight(to_tsvector('english', coalesce(content, '')), 'B')) STORED
956 );
957  
958 them you coud do:
959  
960 $tbl->where(
961 \"websearch_to_tsquery(?)" ~~ $tbl->fo->ts,
962 );
963  
964 and this would create a C<WHERE> clause, such as:
965  
966 WHERE websearch_to_tsquery(?) @@ ts
967  
968 See L<PostgreSQL documentation|https://www.postgresql.org/docs/current/textsearch.html> for more details.
969  
970 but, under L<SQLite|https://www.sqlite.org/fts5.html>, this is not necessary, because the Full Text Search syntax is different:
971  
972 Create a FTS-enabled virtual table.
973  
974 CREATE VIRTUAL TABLE articles
975 USING FTS5(title, content);
976  
977 then query it:
978  
979 SELECT * FROM articles WHERE articles MATCH(?);
980  
981 See L<SQLite documentation|https://www.sqlite.org/fts5.html> for more details.
982  
983 and, in a L<MySQL database|https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html>, also unnecessary, because a bit different:
984  
985 CREATE TABLE articles (
986 id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
987 title TEXT NOT NULL,
988 content TEXT NOT NULL,
989 FULLTEXT (title,content)
990 ) ENGINE=InnoDB;
991  
992 then:
993  
994 SELECT * FROM articles WHERE MATCH(title,content) AGAINST(? IN NATURAL LANGUAGE MODE);
995  
996 See L<MySQL documentation|https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html> for more details.
997  
998 =head1 SEE ALSO
999  
1000 L<perl>
1001  
1002 =head1 AUTHOR
1003  
1004 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
1005  
1006 =head1 COPYRIGHT & LICENSE
1007  
1008 Copyright (c) 2020-2021 DEGUEST Pte. Ltd.
1009  
1010 You can use, copy, modify and redistribute this package and associated
1011 files under the same terms as Perl itself.
1012  
1013 =cut