blib/lib/DB/Object.pm untested

filter: Statementstmt 0.0% 0 / 1755 Branchbran 0.0% 0 / 872 Conditioncond 0.0% 0 / 889 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 218 Podpod 0.0% 0 / 161 totaltotal 0.0% 0 / 3895 CC 436 SCAR 62.3
CC
436
Cov
0%
_cache_this
2256.0
_connection_params2hash
1806.0
cache_query_get
1260.0
CRAP 505.3
1 # -*- perl -*-
2 ##----------------------------------------------------------------------------
3 ## Database Object Interface - ~/lib/DB/Object.pm
4 ## Version v1.10.0
5 ## Copyright(c) 2026 DEGUEST Pte. Ltd.
6 ## Author: Jacques Deguest <jack@deguest.jp>
7 ## Created 2017/07/19
8 ## Modified 2026/03/27
9 ## All rights reserved
10 ##
11 ##
12 ## This program is free software; you can redistribute it and/or modify it
13 ## under the same terms as Perl itself.
14 ##----------------------------------------------------------------------------
15 ## This is the subclassable module for driver specific ones.
16 package DB::Object;
17 BEGIN
18 {
19 require 5.16.0;
20 use strict;
21 use warnings;
22 use warnings::register;
23 use parent qw( Module::Generic DBI );
24 use vars qw(
25 $VERSION $AUTOLOAD $CACHE_DIR $CACHE_SIZE $DRIVER2PACK
26 $ERROR $DEBUG $MOD_PERL $USE_BIND $USE_CACHE $PLACEHOLDER_REGEXP $SERIALISER
27 $SERIALISATION_VERSION $EXCEPTION_CLASS
28 );
29 use Regexp::Common;
30 use Scalar::Util qw( blessed weaken );
31 use DB::Object::Cache::Tables;
32 use DBI;
33 use JSON;
34 use Module::Generic::File qw( sys_tmpdir );
35 use Module::Generic::Global qw( :const );
36 use POSIX ();
37 use Wanted;
38 our $PLACEHOLDER_REGEXP = qr/(?<![?\w])\?(?![?\w])/;
39 our $EXCEPTION_CLASS = 'DB::Object::Exception';
40 our $VERSION = 'v1.10.0';
41 };
42  
43 use strict;
44 use warnings;
45  
46 our $DEBUG = 0;
47 # A global setting variable. This is not changed dynamically, and can be set by the user
48 our $CACHE_SIZE = 10;
49 our $USE_BIND = 0;
50 our $USE_CACHE = 0;
51 our $MOD_PERL = 0;
52 # A global variable that can be set by the user to serve as a default value
53 our $CACHE_DIR = '';
54 if( $INC{ 'Apache/DBI.pm' } &&
55 substr( $ENV{GATEWAY_INTERFACE} || '', 0, 8 ) eq 'CGI-Perl' )
56 {
57 $MOD_PERL++;
58 }
59 # Global constant
60 our $DRIVER2PACK =
61 {
62 mysql => 'DB::Object::Mysql',
63 Pg => 'DB::Object::Postgres',
64 SQLite => 'DB::Object::SQLite',
65 };
66 # Default value
67 our $SERIALISER = 'Storable';
68 our $SERIALISATION_VERSION = 1;
69  
70 sub new
71 {
72 my $that = shift( @_ );
73 my $class = ref( $that ) || $that;
74 my $self = {};
75 bless( $self, $class );
76 return( $self->init( @_ ) );
77 }
78  
79 sub init
80 {
81 my $self = shift( @_ );
82 $self->{cache_connections} = 1;
83 $self->{cache_dir} = sys_tmpdir();
84 # Cache query on file ? Only works if 'cache_dir' is set too.
85 $self->{cache_query} = 0;
86 $self->{cache_size} = $CACHE_SIZE;
87 $self->{cache_table} = 0;
88 $self->{driver} = '';
89 # Auto-decode json data into perl hash
90 $self->{auto_decode_json} = 1;
91 $self->{auto_convert_datetime_to_object} = 0;
92 $self->{allow_bulk_delete} = 0;
93 $self->{allow_bulk_update} = 0;
94 $self->{serialiser} = undef;
95 $self->{unknown_field} = 'ignore';
96 $self->{_init_strict_use_sub} = 1;
97 $self->{_exception_class} = $EXCEPTION_CLASS;
98 $self->Module::Generic::init( @_ ) || return( $self->pass_error );
99 return( $self );
100 }
101  
102 sub allow_bulk_delete { return( shift->_set_get_scalar( 'allow_bulk_delete', @_ ) ); }
103  
104 sub allow_bulk_update { return( shift->_set_get_scalar( 'allow_bulk_update', @_ ) ); }
105  
106 sub ALL { return( shift->_operator_object_create( 'DB::Object::ALL', @_ ) ); }
107  
108 sub AND { return( shift->_operator_object_create( 'DB::Object::AND', @_ ) ); }
109  
110 sub ANY { return( shift->_operator_object_create( 'DB::Object::ANY', @_ ) ); }
111  
112 sub auto_convert_datetime_to_object { return( shift->_set_get_scalar( 'auto_convert_datetime_to_object', @_ ) ); }
113  
114 sub auto_decode_json { return( shift->_set_get_scalar( 'auto_decode_json', @_ ) ); }
115  
116 sub attribute($;$@)
117 {
118 my $self = shift( @_ );
119 # $h->{AttributeName} = ...; # set/write
120 # ... = $h->{AttributeName}; # get/read
121 # 1 means that the attribute may be modified
122 # 0 mneas that the attribute may only be read
123 my $name = shift( @_ ) if( @_ == 1 );
124 my %arg = ( @_ );
125 my %attr =
126 (
127 Active => 0,
128 ActiveKids => 0,
129 AutoCommit => 1,
130 AutoInactiveDestroy => 1,
131 CachedKids => 0,
132 Callbacks => 1,
133 ChildHandles => 0,
134 ChopBlanks => 1,
135 CompatMode => 1,
136 CursorName => 0,
137 ErrCount => 0,
138 Executed => 0,
139 FetchHashKeyName => 0,
140 HandleError => 1,
141 HandleSetErr => 1,
142 InactiveDestroy => 1,
143 Kids => 0,
144 LongReadLen => 1,
145 LongTruncOk => 1,
146 NAME => 0,
147 NULLABLE => 0,
148 NUM_OF_FIELDS => 0,
149 NUM_OF_PARAMS => 0,
150 Name => 0,
151 PRECISION => 0,
152 PrintError => 1,
153 PrintWarn => 1,
154 Profile => 0,
155 RaiseError => 1,
156 ReadOnly => 1,
157 RowCacheSize => 0,
158 RowsInCache => 0,
159 SCALE => 0,
160 ShowErrorStatement => 1,
161 Statement => 0,
162 TYPE => 0,
163 Taint => 1,
164 TaintIn => 1,
165 TaintOut => 1,
166 TraceLevel => 1,
167 Type => 0,
168 Warn => 1,
169 );
170 # Only those attribute exist
171 # Using an a non existing attribute produce an exception, so we better avoid
172 if( $name )
173 {
174 return( $self->{dbh}->{ $name } ) if( exists( $attr{ $name } ) );
175 }
176 else
177 {
178 my $value;
179 while( ( $name, $value ) = each( %arg ) )
180 {
181 # We intend to modifiy the value of an attribute
182 # we are allowed to modify this value if it is true
183 if( exists( $attr{ $name } ) &&
184 defined( $value ) &&
185 $attr{ $name } )
186 {
187 $self->{dbh}->{ $name } = $value;
188 }
189 }
190 }
191 }
192  
193 sub available_drivers(@)
194 {
195 my $self = shift( @_ );
196 my $class = ref( $self ) || $self;
197 # @ary = DBI->available_drivers( $quiet );
198 return( $class->SUPER::available_drivers( 1 ) );
199 }
200  
201 sub base_class
202 {
203 my $self = shift( @_ );
204 my $this = @_ ? shift( @_ ) : $self;
205 my @supported_classes = $self->supported_class;
206 push( @supported_classes, 'DB::Object' );
207 my $ok_classes = CORE::join( '|', CORE::map{ CORE::quotemeta( $_ ) } @supported_classes );
208 my $class = ref( $this ) ? ref( $this ) : $this;
209 my $base_class = ( $class =~ /^($ok_classes)/ )[0];
210 return( $base_class );
211 }
212  
213 # This method is common to DB::Object and DB::Object::Statement
214 sub bind
215 {
216 my $self = shift( @_ );
217 # Usage:
218 # This activate the binding stuff
219 # $dbh->bind() or $dbh->bind->where( "something" ) or $dbh->bind->select->fetchrow_hashref();
220 # Later, $dbh->bind( 'thingy' )->select->fetchrow_hashref()
221 # When used like $table->bind; this means the user is setting the use bind option as a setting for all transactions, but
222 # when used like $table->bind->select then the use bind option is only used for this transaction only and is reset after
223 $self->{bind} = want('VOID')
224 ? 2
225 # Otherwise is it already set maybe?
226 : $self->{bind}
227 # Then use it
228 ? $self->{bind}
229 : 1;
230 if( @_ )
231 {
232 # If we are using the cache system, we search the object of this query
233 my $obj = $self;
234 $obj->{binded} = [ @_ ];
235 # Since new binded parameters have been passed, since mean a new request to the
236 # same statement is pending, so we need to re-execute the statement
237 # and since most of the fetch method rely on AUTOLOAD that call
238 # execute() automatically *IF* the statement was not already executed....
239 # we need to delete 'executed' value or set it to false, so the statement gets re-executed
240 $obj->{executed} = 0;
241 return( $obj );
242 }
243 return( $self );
244 }
245  
246 sub cache
247 {
248 my $self = shift( @_ );
249 # activate cache
250 # So we may be called as: $tbl->cache->select->fetchrow_hashref();
251 $self->{cache}++;
252 return( $self );
253 }
254  
255 sub cache_connections { return( shift->_set_get_boolean( 'cache_connections', @_ ) ); }
256  
257 sub cache_dir { return( shift->_set_get_scalar( 'cache_dir', @_ ) ); }
258  
259 sub cache_query { return( shift->_set_get_scalar( 'cache_query', @_ ) ); }
260  
261 sub cache_query_get
262 {
263 my $self = shift( @_ );
264 my $name = shift( @_ ) || return( $self->error( "No name for this query cache was provided." ) );
265 my $opts = $self->_get_args_as_hash( @_ );
266 my $base_class = $self->base_class;
267  
268 # Because we need the database object to revive the statement handler after having thawed it.
269 if( ref( $self ) ne $base_class )
270 {
271 return( $self->error( "This method must be called by the database object itself." ) );
272 }
273  
274 # Cannot be called without using a DB::Object
275 my $dbo = $self;
276 my $dbh = $self->{dbh};
277 my $cache_size = $dbo->cache_size // 0;
278 my $cache = $dbo->{cache};
279 # We want to know what kind of cache we are expected to use
280 my $cache_query = $opts->{cache_query} // $dbo->cache_query // 1;
281 my $cache_dir = $opts->{cache_dir} // $dbo->cache_dir // $self->sys_tmpdir;
282 my $ext = $opts->{extension} // 'bin';
283  
284 my $use_file_cache = ( defined( $cache_query ) && $cache_query eq 'file' ) ? 1 : 0;
285  
286 # Not a hard error
287 if( $cache_query !~ /^1|0|file$/ )
288 {
289 warn( "Unknown value for cache_query '$cache_query'" ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
290 }
291  
292 my $serialiser = $opts->{serialiser} || $self->serialiser || $DB::Object::SERIALISER || 'Storable';
293 # If the serialiser selected is the default one, and we have Sereal installed, we use it instead.
294 if( $serialiser eq 'Storable' && $self->_load_class( 'Sereal' ) )
295 {
296 $serialiser = 'Sereal';
297 }
298 $name = lc( $serialiser ) . "-${name}";
299  
300 # We make sure the extension passed to '_get_cache_filepath' is coherent with ours
301 my $cache_file = $self->_get_cache_filepath( %$opts, name => $name, extension => $ext, prefix => 'query' ) ||
302 return( $self->pass_error );
303 my $cache_key = $cache_file->basename( ".${ext}" );
304  
305 # Need to ensure DB::Object::Statement is loaded, so the deserialisation of the statement object has a proper inheritance.
306 $self->_load_class( $base_class, { force => 1 } ) || return( $self->pass_error );
307 $self->_load_class( 'DB::Object::Query::Clause', { force => 1 } ) || return( $self->pass_error );
308 $self->_load_class( 'DB::Object::Query::Elements', { force => 1 } ) || return( $self->pass_error );
309 $self->_load_class( 'DB::Object::Query::Element', { force => 1 } ) || return( $self->pass_error );
310 $self->_load_class( 'DB::Object::Constraint::Check', { force => 1 } ) || return( $self->pass_error );
311 $self->_load_class( 'DB::Object::Constraint::Foreign', { force => 1 } ) || return( $self->pass_error );
312 $self->_load_class( 'DB::Object::Constraint::Index', { force => 1 } ) || return( $self->pass_error );
313 $self->_load_class( 'DB::Object::Statement', { force => 1 } ) || return( $self->pass_error );
314 $self->_load_class( "${base_class}::Query", { force => 1 } ) || return( $self->pass_error );
315 $self->_load_class( "${base_class}::Statement", { force => 1 } ) || return( $self->pass_error );
316 $self->_load_class( "${base_class}::Tables", { force => 1 } ) || return( $self->pass_error );
317 ( my $mod_path = "${base_class}::Statement" ) =~ s,::,/,g;
318 $mod_path .= '.pm';
319 my $lock;
320 my $repo = Module::Generic::Global->new( queries_cache => $base_class,
321 max_size => $cache_size,
322 serialiser => $serialiser,
323 key => $cache_key,
324 ) || return( $self->pass_error( Module::Generic::Global->error ) );
325 # The lock gets removed automatically when it gets out of scope, so we store it in $lock
326 $lock = $repo->lock;
327 local $@;
328 my $sth = eval{ $repo->get };
329 # The deserialisation of the in-memory object died, most likely in the THAW, and maybe due to a serialisation version mismatch
330 if( !$sth && $@ )
331 {
332 if( $@ =~ /Serialisation[[:blank:]]+version[[:blank:]]+mismatch/i )
333 {
334 # We just warn, and since no object has been deserialise, we will return nothing, thus leading the caller to create a fresh object.
335 warn( $@ );
336 }
337 elsif( $self->_is_object( $@ ) )
338 {
339 return( $self->pass_error( $@ ) );
340 }
341 else
342 {
343 return( $self->error( "Unable to deserialise in-memory statement object: $@" ) );
344 }
345 }
346  
347  
348 if( !$sth && $cache_query eq 'file' )
349 {
350 if( !$cache_file->exists ||
351 !$cache_file->is_file ||
352 $cache_file->is_empty )
353 {
354 return( '' );
355 }
356 $sth = eval{
357 $self->Module::Generic::deserialise(
358 file => $cache_file,
359 lock => 1,
360 serialiser => $serialiser,
361 );
362 };
363 if( !$sth )
364 {
365 # A fatal exception occurred in the THAW hook maybe?
366 if( $@ )
367 {
368 if( $@ =~ /Serialisation[[:blank:]]+version[[:blank:]]+mismatch/i )
369 {
370 # We just warn, and since no object has been deserialise, we will return nothing, thus leading the caller to create a fresh object.
371 warn( $@ );
372 }
373 elsif( $self->_is_object( $@ ) )
374 {
375 return( $self->pass_error( $@ ) );
376 }
377 else
378 {
379 return( $self->error( "Unable to deserialise in-memory statement object: $@" ) );
380 }
381 }
382 else
383 {
384 return( $self->pass_error );
385 }
386 }
387 $repo->set( $sth ) || return( $self->pass_error( $repo->error ) );
388 }
389  
390 # No statement object found, so we return empty, but not undefined, which is reserved for errors.
391 if( !$sth )
392 {
393 return( '' );
394 }
395  
396 unless( $self->_is_a( $sth => "${base_class}::Statement" ) )
397 {
398 $repo->unlock if( $repo );
399 die( "Statement object found (", $self->_str_val( $sth ), ") in this statement object is actually not a statement object (${base_class}::Statement) !" );
400 }
401  
402 # my $sth_class = ref( $sth );
403 # if( !$self->_load_class( $sth_class ) )
404 # {
405 # $repo->unlock if( $repo );
406 # return( $self->pass_error );
407 # }
408 # my $sth_base_class = $dbo->base_class( $sth_class );
409 # if( !$self->_load_class( "${sth_base_class}::Query" ) )
410 # {
411 # $repo->unlock if( $repo );
412 # return( $self->pass_error );
413 # }
414 # if( !$self->_load_class( "${sth_base_class}::Tables" ) )
415 # {
416 # $repo->unlock if( $repo );
417 # return( $self->pass_error );
418 # }
419 # bless( $sth => $sth_class );
420 # Detect "zombie" DBI handles (blessed but no magic) without leaking warnings
421 my $dbh_ok = 0;
422 if( $dbh && ref( $dbh ) =~ /^DBI::db\b/ )
423 {
424 local $SIG{__WARN__} = sub
425 {
426 die( $_[0] );
427 };
428 local $@;
429 $dbh_ok = eval
430 {
431 $dbh->ping ? 1 : 0;
432 };
433 $dbh_ok = 0 if( !$dbh_ok || $@ );
434 }
435  
436 if( !$dbh_ok )
437 {
438 $dbh = $self->_dbi_connect;
439 if( !$dbh )
440 {
441 $repo->unlock if( $repo );
442 return( $self->pass_error );
443 }
444 $dbo->{dbh} = $dbh;
445 }
446  
447 $sth->debug( $self->debug );
448 # We reattach the database object to that statement
449 if( !$sth->attach( $dbo ) )
450 {
451 $repo->unlock if( $repo );
452 return( $self->pass_error( $sth->error ) );
453 }
454 my $query = $sth->as_string;
455 if( !defined( $query ) || !CORE::length( $query ) )
456 {
457 $repo->unlock if( $repo );
458 return( $self->error( "No SQL query string could be found." ) );
459 }
460 my $prepare_options = {};
461 if( my $q = $sth->query_object )
462 {
463 $prepare_options = $q->prepare_options->as_hash;
464 }
465  
466 local $@;
467 my $sth_dbi = eval
468 {
469 $dbh->prepare( $query, ( scalar( keys( %$prepare_options ) ) ? $prepare_options : () ) );
470 };
471  
472 if( $@ )
473 {
474 $repo->unlock if( $repo );
475 return( $self->error( "Error preparing cached SQL query: $@\nQuery was:\n$query" ) );
476 }
477 elsif( !$sth_dbi )
478 {
479 $repo->unlock if( $repo );
480 my $err = ( $self->{dbh}->errstr() || 'unknown DBI error' );
481 return( $self->error( "Error while trying to prepare query: ${err}\nQuery was:\n$query" ) );
482 }
483  
484 $sth->{sth} = $sth_dbi;
485  
486 $repo->unlock if( $repo );
487 return( $sth );
488 }
489  
490 sub cache_query_set
491 {
492 my $self = shift( @_ );
493 my $name = shift( @_ ) || return( $self->error( "No name for this query cache was provided." ) );
494 my $sth = shift( @_ ) || return( $self->error( "No statement handler was provided." ) );
495 my $opts = $self->_get_args_as_hash( @_ );
496 my $base_class = $self->base_class;
497  
498 # Because we need the database object to revive the statement handler after having thawed it.
499 if( ref( $self ) ne $base_class )
500 {
501 return( $self->error( "This method must be called by the database object itself." ) );
502 }
503  
504 # Cannot be called without using a DB::Object
505 my $dbo = $self;
506 my $cache_size = $dbo->cache_size // 0;
507 my $cache = $dbo->{cache};
508 # We want to know what kind of cache we are expected to use
509 my $cache_query = $opts->{cache_query} // $dbo->cache_query // 1;
510 my $cache_dir = $opts->{cache_dir} // $dbo->cache_dir // $self->sys_tmpdir;
511 my $ext = $opts->{extension} // 'bin';
512  
513 my $use_file_cache = ( defined( $cache_query ) && $cache_query eq 'file' ) ? 1 : 0;
514  
515 # Not a hard error
516 if( $cache_query !~ /^1|0|file$/ )
517 {
518 warn( "Unknown value for cache_query '$cache_query'" ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
519 }
520  
521 my $serialiser = $opts->{serialiser} || $self->serialiser || $DB::Object::SERIALISER || 'Storable';
522 # If the serialiser selected is the default one, and we have Sereal installed, we use it instead.
523 if( $serialiser eq 'Storable' && $self->_load_class( 'Sereal' ) )
524 {
525 $serialiser = 'Sereal';
526 }
527 $name = lc( $serialiser ) . "-${name}";
528  
529 # We make sure the extension passed to '_get_cache_filepath' is coherent with ours
530 my $cache_file = $self->_get_cache_filepath( %$opts, name => $name, extension => $ext, prefix => 'query' ) ||
531 return( $self->pass_error );
532 my $cache_key = $cache_file->basename( ".${ext}" );
533  
534 my $lock;
535 my $repo = Module::Generic::Global->new( queries_cache => $base_class,
536 max_size => $cache_size,
537 serialiser => $serialiser,
538 key => $cache_key,
539 ) || return( $self->pass_error( Module::Generic::Global->error ) );
540 # The lock gets removed automatically when it gets out of scope, so we store it in $lock
541 $lock = $repo->lock;
542  
543 if( $cache_query eq 'file' )
544 {
545 # If it is already there, we return immediately. There is nothing more to do.
546 if( $cache_file->exists &&
547 !$cache_file->is_file )
548 {
549 return( $self->error( "There already existing a cache file $cache_file, but it is not a file!" ) );
550 }
551 if( $cache_file->exists &&
552 $cache_file->is_file &&
553 !$cache_file->is_empty )
554 {
555 return( $sth );
556 }
557 $self->Module::Generic::serialise( $sth,
558 file => $cache_file,
559 lock => 1,
560 serialiser => $serialiser,
561 ( $serialiser eq 'Sereal' ? ( freeze_callbacks => 1 ) : () ),
562 ) || return( $self->pass_error );
563 }
564 elsif( $cache_query )
565 {
566 $repo->set( $sth );
567 $repo->unlock;
568 }
569 return( $sth );
570 }
571  
572 sub cache_size { return( shift->_set_get_scalar( 'cache_size', @_ ) ); }
573  
574 sub cache_table { return( shift->_set_get_scalar( 'cache_table', @_ ) ); }
575  
576 sub cache_tables { return( shift->_set_get_object( 'cache_tables', 'DB::Object::Cache::Tables', @_ ) ); }
577  
578 sub check_driver()
579 {
580 my $self = shift( @_ );
581 my $driver = shift( @_ ) || return( $self->error( "No SQL driver provided to check" ) );
582 my $ok = undef();
583 local $_;
584 my @drivers = $self->available_drivers();
585 foreach( @drivers )
586 {
587 if( m/$driver/s )
588 {
589 $ok++;
590 last;
591 }
592 }
593 return( $ok );
594 }
595  
596 sub connect
597 {
598 my $this = shift( @_ );
599 my $class = ref( $this ) || $this;
600 my $base_class = $this->base_class;
601 my $opts = $this->_get_args_as_hash( @_ );
602 # We pass the arguments so that debug and other init parameters can be set early
603 my $that = ref( $this ) ? $this : $this->Module::Generic::new( debug => $opts->{debug} );
604 my $param = $that->_connection_params2hash( $opts ) || return( $this->error( "No valid connection parameters found" ) );
605 $param = $that->_connection_params2hash_driver( $param );
606 my $driver2pack =
607 {
608 mysql => 'DB::Object::Mysql',
609 Pg => 'DB::Object::Postgres',
610 SQLite => 'DB::Object::SQLite',
611 };
612 my $pack2driver = +{ map{ $driver2pack->{ $_ } => $_ } keys( %$driver2pack ) };
613 my $driver_class;
614 if( exists( $param->{driver} ) )
615 {
616 if( !exists( $driver2pack->{ $param->{driver} } ) )
617 {
618 return( $this->error( "Driver $param->{driver} is not supported." ) );
619 }
620 # For example, will make this object a DB::ObjectD::Postgres object
621 $driver_class = $driver2pack->{ $param->{driver} };
622 my $driver_module = $driver_class;
623 $driver_module =~ s|::|/|g;
624 $driver_module .= '.pm';
625 eval
626 {
627 local $DEBUG;
628 require $driver_module;
629 };
630 return( $this->error( "Unable to load module $driver_class ($driver_module): $@" ) ) if( $@ );
631 }
632 elsif( exists( $pack2driver->{ $base_class } ) )
633 {
634 $driver_class = $base_class;
635 $param->{driver} = $pack2driver->{ $base_class };
636 }
637 else
638 {
639 return( $this->error( "No driver was provided." ) );
640 }
641 my $self = $driver_class->new || return( $this->error( "Cannot get object from package $driver_class" ) );
642 $self->debug(
643 CORE::exists( $param->{debug} )
644 ? CORE::delete( $param->{debug} )
645 : CORE::exists( $param->{Debug} )
646 ? CORE::delete( $param->{Debug} )
647 : $DEBUG
648 );
649 # Needed to be specified if the user does not want to cache connections
650 # Will be used in _dbi_connect()
651 $self->cache_connections( CORE::delete( $param->{cache_connections} ) ) if( CORE::exists( $param->{cache_connections} ) );
652 $self->connect_via( CORE::delete( $param->{connect_via} ) ) if( CORE::exists( $param->{connect_via} ) );
653 $self->cache_dir(
654 CORE::exists( $param->{cache_dir} )
655 ? CORE::delete( $param->{cache_dir} )
656 : CORE::exists( $that->{cache_dir} )
657 ? $that->{cache_dir}
658 : $CACHE_DIR
659 );
660  
661 if( CORE::exists( $param->{cache_table} ) && defined( $param->{cache_table} ) )
662 {
663 $self->cache_table( CORE::delete( $param->{cache_table} ) );
664 }
665 elsif( CORE::exists( $that->{cache_table} ) && defined( $that->{cache_table} ) )
666 {
667 $self->cache_table( $that->{cache_table} );
668 }
669  
670 if( CORE::exists( $param->{cache_query} ) && defined( $param->{cache_query} ) )
671 {
672 $self->cache_query( CORE::delete( $param->{cache_query} ) );
673 }
674 elsif( CORE::exists( $that->{cache_query} ) && defined( $that->{cache_query} ) )
675 {
676 $self->cache_query( $that->{cache_query} );
677 }
678  
679 if( CORE::exists( $param->{cache_size} ) && defined( $param->{cache_size} ) )
680 {
681 $self->cache_size( $param->{cache_size} );
682 }
683 elsif( CORE::exists( $that->{cache_size} ) && defined( $that->{cache_size} ) )
684 {
685 $self->cache_size( $that->{cache_size} );
686 }
687  
688 if( CORE::exists( $param->{use_cache} ) )
689 {
690 $self->{cache} = CORE::delete( $param->{use_cache} );
691 }
692 elsif( CORE::exists( $param->{cache} ) )
693 {
694 $self->{cache} = CORE::delete( $param->{cache} );
695 }
696 else
697 {
698 $self->{cache} = $USE_CACHE;
699 }
700  
701 if( CORE::exists( $param->{serialiser} ) )
702 {
703 $self->{serialiser} = CORE::delete( $param->{serialiser} );
704 }
705 elsif( CORE::exists( $param->{serializer} ) )
706 {
707 $self->{serialiser} = CORE::delete( $param->{serializer} );
708 }
709 else
710 {
711 $self->{serialiser} = $SERIALISER;
712 }
713  
714 $self->{unknown_field} = CORE::delete( $param->{unknown_field} ) if( CORE::exists( $param->{unknown_field} ) );
715  
716 $param = $self->_check_connect_param( $param ) || return( $this->pass_error( $self->error ) );
717 my $opt = {};
718 if( exists( $param->{opt} ) )
719 {
720 $opt = CORE::delete( $param->{opt} );
721 $opt = $self->_check_default_option( $opt );
722 }
723 # print( STDERR ref( $self ), "::connect(): \$param is: ", $self->dumper( $param ), "\n" );
724 $self->{database} = CORE::exists( $param->{database} )
725 ? CORE::delete( $param->{database} )
726 : CORE::exists( $param->{db} )
727 ? CORE::delete( $param->{db} )
728 : undef();
729 $self->{host} = CORE::exists( $param->{host} )
730 ? CORE::delete( $param->{host} )
731 : CORE::exists( $param->{server} )
732 ? CORE::delete( $param->{server} )
733 : undef();
734 $self->{port} = CORE::delete( $param->{port} );
735 # $self->{database} = CORE::delete( $param->{ 'db' } );
736 $self->{login} = CORE::delete( $param->{login} );
737 $self->{passwd} = CORE::delete( $param->{passwd} );
738 $self->{driver} = CORE::delete( $param->{driver} );
739 $self->{bind} = CORE::exists( $param->{use_bind} )
740 ? CORE::delete( $param->{use_bind} )
741 : $USE_BIND;
742  
743 # If parameters starting with an upper case are provided, they are DBI database parameters
744 #my @dbi_opts = grep( /^[A-Z][a-zA-Z]+/, keys( %$param ) );
745 #@$opt{ @dbi_opts } = @$param{ @dbi_opts };
746  
747 if( my $driver = $self->driver )
748 {
749 my $drh = $self->SUPER::install_driver( $driver ) ||
750 return( $this->pass_error( $self->error ) );
751 $self->{drh} = $drh;
752 }
753 $opt->{RaiseError} = 0 if( !CORE::exists( $opt->{RaiseError} ) );
754 $opt->{AutoCommit} = 1 if( !CORE::exists( $opt->{AutoCommit} ) );
755 $opt->{PrintError} = 0 if( !CORE::exists( $opt->{PrintError} ) );
756 $self->{opt} = $opt;
757 my $dbh = $self->_dbi_connect || return( $this->pass_error( $self->error ) );
758 # This is possibly a Apache::DBI::db object
759 $self->{dbh} = $dbh;
760 #$self->param(
761 # ## Do not allow SELECT that will take too long or too much resource, i.e. over 2Gb of data
762 # ## This is idiot proof mode
763 # 'SQL_BIG_SELECTS' => 0,
764 # ## SQL will abort if a DELETE or UPDATE is being executed w/o LIMIT nor WHERE clause
765 # 'SQL_SAFE_MODE' => 1,
766 #);
767 local $/ = "\n";
768 my $tables = [];
769 # 1 day
770 # my $tbl_cache_timeout = 86400;
771 my $host = $self->host || 'localhost';
772 my $port = $self->port || 0;
773 my $driver = $self->driver;
774 my $database = $self->database;
775 my $cache_params = {};
776 if( my $cache_dir = $self->cache_dir )
777 {
778 $cache_params->{cache_dir} = $cache_dir;
779 }
780 $cache_params->{debug} = $self->debug;
781 my $cache_tables = DB::Object::Cache::Tables->new( $cache_params );
782 $self->cache_tables( $cache_tables );
783 $tables = $self->tables_info;
784 my $cache =
785 {
786 host => $host,
787 driver => $driver,
788 port => $port,
789 database => $database,
790 tables => $tables,
791 };
792 if( !defined( $cache_tables->set( $cache ) ) )
793 {
794 warn( "Unable to write to tables cache: ", $cache_tables->error, "\n" );
795 }
796 return( $self );
797 }
798  
799 sub connect_via { return( shift->_set_get_scalar( 'connect_via', @_ ) ); }
800  
801 sub constant_queries_cache_get
802 {
803 my( $self, $def ) = @_;
804 my $base_class = $self->base_class;
805  
806 # Because we need the database object to revive the statement handler after having thawed it.
807 if( ref( $self ) ne $base_class )
808 {
809 return( $self->error( "This method must be called by the database object itself." ) );
810 }
811  
812 my $dbo = $self;
813 my $cache_size = $dbo->cache_size // 0;
814  
815 if( !defined( $def ) || ref( $def // '' ) ne 'HASH' )
816 {
817 return( $self->error( "Parameter provided must be a hash, but I got '", $self->_str_val( $def // 'undef' ), "'." ) );
818 }
819  
820 foreach my $k ( qw( pack file line ) )
821 {
822 return( $self->error( "Parameter \"$k\" is missing from the hash." ) )
823 if( !defined( $def->{ $k } ) || !CORE::length( $def->{ $k } // '' ) );
824 }
825  
826 my $cache_key = CORE::join( '|', @$def{qw( pack file line )} );
827 my $serialiser = CORE::delete( $def->{serialiser} ) || $DB::Object::SERIALISER || 'Storable';
828  
829 my $lock;
830 my $repo = Module::Generic::Global->new( queries_cache => $base_class,
831 max_size => $cache_size,
832 serialiser => $serialiser,
833 key => $cache_key,
834 ) || return( $self->pass_error( Module::Generic::Global->error ) );
835 $repo->lock;
836  
837 my $store = $repo->get;
838 return( '' ) if( !$store );
839  
840 # $ts is thee timestamp of the file recorded at the time
841 my $ts = $store->{ts} || return( $self->error( "No timestamp set in this constant statement object." ) );
842 my $sth = $repo->{sth} || return( '' );
843 # A DB::Object::Statement object
844 my $qo = $sth->query_object;
845 return( '' ) if( !CORE::length( $def->{file} ) );
846 return( '' ) if( !-e( $def->{file} ) );
847 return( '' ) if( ( CORE::stat( $def->{file} ) )[9] != $ts );
848 return( $self->error( "Query object retrieved from constant query cache is void!" ) ) if( !$qo );
849 return( $self->error( "Query object retrieved from constant query cache is not a DB::Object::Query object or one of its sub classes." ) ) if( !$self->_is_object( $qo ) || !$qo->isa( 'DB::Object::Query' ) );
850 return if( $self->database ne $qo->database_object->database );
851  
852 return( $sth );
853 }
854  
855 sub constant_queries_cache_set
856 {
857 my( $self, $def ) = @_;
858 my $base_class = $self->base_class;
859  
860 # Because we need the database object to revive the statement handler after having thawed it.
861 if( ref( $self ) ne $base_class )
862 {
863 return( $self->error( "This method must be called by the database object itself." ) );
864 }
865  
866  
867 if( !defined( $def ) || ref( $def // '' ) ne 'HASH' )
868 {
869 return( $self->error( "Parameter provided must be a hash, but I got '", $self->_str_val( $def // 'undef' ), "'." ) );
870 }
871  
872 foreach my $k ( qw( pack file line ) )
873 {
874 if( !defined( $def->{ $k } ) || !CORE::length( $def->{ $k } // '' ) )
875 {
876 return( $self->error( "Parameter \"$k\" is missing from the hash." ) );
877 }
878 }
879  
880 my $dbo = $self;
881 my $cache_size = $dbo->cache_size // 0;
882  
883 return( $self->error( "Parameter \"query_object\" is missing from the hash." ) )
884 if( !defined( $def->{query_object} ) );
885  
886 if( !$self->_is_object( $def->{query_object} ) ||
887 !$def->{query_object}->isa( 'DB::Object::Query' ) )
888 {
889 return( $self->error( "Provided query object is not a DB::Object::Query." ) );
890 }
891  
892 $def->{ts} = [CORE::stat( $def->{file} )]->[9];
893  
894 my $cache_key = CORE::join( '|', @$def{qw( pack file line )} );
895 my $serialiser = CORE::delete( $def->{serialiser} ) || $DB::Object::SERIALISER || 'Storable';
896  
897 my $repo = Module::Generic::Global->new( queries_cache => $base_class,
898 max_size => $cache_size,
899 serialiser => $serialiser,
900 key => $cache_key,
901 ) || return( $self->pass_error( Module::Generic::Global->error ) );
902 $repo->lock;
903 $repo->set( $def ) || return( $self->pass_error( $repo->error ) );
904  
905 return( $def );
906 }
907  
908 sub constant_queries_cache_del
909 {
910 my( $self, $def ) = @_;
911 my $base_class = $self->base_class;
912  
913 # Because we need the database object to revive the statement handler after having thawed it.
914 if( ref( $self ) ne $base_class )
915 {
916 return( $self->error( "This method must be called by the database object itself." ) );
917 }
918  
919 if( !defined( $def ) || ref( $def // '' ) ne 'HASH' )
920 {
921 return( $self->error( "Parameter provided must be a hash, but I got '", $self->_str_val( $def // 'undef' ), "'." ) );
922 }
923  
924 foreach my $k ( qw( pack file line ) )
925 {
926 return( $self->error( "Parameter \"$k\" is missing from the hash." ) )
927 if( !defined( $def->{ $k } ) || !CORE::length( $def->{ $k } // '' ) );
928 }
929  
930 my $dbo = $self;
931 my $cache_size = $dbo->cache_size // 0;
932 my $cache_key = CORE::join( '|', @$def{qw( pack file line )} );
933 my $serialiser = CORE::delete( $def->{serialiser} ) || $DB::Object::SERIALISER || 'Storable';
934  
935 my $repo = Module::Generic::Global->new( queries_cache => $base_class,
936 max_size => $cache_size,
937 serialiser => $serialiser,
938 key => $cache_key,
939 ) || return( $self->pass_error( Module::Generic::Global->error ) );
940 $repo->lock;
941 $repo->remove;
942 $repo->unlock;
943 return(1);
944 }
945  
946 # See also datatype_to_constant()
947 sub constant_to_datatype
948 {
949 my $self = shift( @_ );
950 return unless( scalar( @_ ) && defined( $_[0] ) );
951 my $this = shift( @_ );
952 my $ref = $self->datatypes;
953 foreach my $t ( keys( %$ref ) )
954 {
955 return( $t ) if( $ref->{ $t } eq $this );
956 }
957 return;
958 }
959  
960 sub copy
961 {
962 my $self = shift( @_ );
963 my $opts = $self->_get_args_as_hash( @_ );
964 my $ref = $self->select->fetchrow_hashref();
965 my $keys = keys( %$opts );
966 @$ref{ @$keys } = @$opts{ @$keys };
967 return(0) if( !scalar( keys( %$ref ) ) );
968 $self->insert( $ref );
969 return(1);
970 }
971  
972 sub create_db { return( shift->error( "The driver has not implemented the create database method create_db." ) ); }
973  
974 sub create_table { return( shift->error( "The driver has not implemented the create table method create_table." ) ); }
975  
976 sub data_sources($;\%)
977 {
978 my $self = shift( @_ );
979 my $class = ref( $self ) || $self;
980 my $opt;
981 $opt = shift( @_ ) if( @_ );
982 my $driver = $self->{driver} || return( $self->error( "No driver to to use to check for data sources." ) );
983 return( $class->SUPER::data_sources( $driver, $opt ) );
984 }
985  
986 sub data_type
987 {
988 my $self = shift( @_ );
989 my $type = @_ == 1 ? shift( @_ ) : [ @_ ] if( @_ );
990 my $ref = eval
991 {
992 local $SIG{__DIE__} = sub{ };
993 local $SIG{__WARN__} = sub{ };
994 $self->{dbh}->type_info_all();
995 };
996 return( $self->error( "type_info_all() is unsupported by vendor '$self->{ 'driver' }'." ) ) if( $@ );
997 # First item is a reference to hash containing the order of the header
998 my $header = shift( @$ref );
999 my $hash = {};
1000 my $name_idx = $header->{TYPE_NAME};
1001 my @found = ();
1002 if( $type )
1003 {
1004 my @types = ref( $type ) ? @$type : ( $type );
1005 foreach my $requested ( @types )
1006 {
1007 push( @found, grep{ uc( $requested ) eq $_->[ $name_idx ] } @$ref );
1008 }
1009 }
1010 else
1011 {
1012 @found = @$ref;
1013 }
1014 # Stop. No need to go further
1015 return( wantarray() ? () : undef() ) if( !@found );
1016 my @names = map{ lc( $_ ) } keys( %$header );
1017 my $len = scalar( keys( %$header ) );
1018 my @order = values( %$header );
1019 map
1020 {
1021 next if( @$_ != $len );
1022 my %data;
1023 @data{ @names } = @{ $_ }[ @order ];
1024 $hash->{ lc( $_->[ $name_idx ] ) } = \%data;
1025 } @found;
1026 return( wantarray() ? () : undef() ) if( !%$hash );
1027 return( wantarray() ? %$hash : $hash );
1028 }
1029  
1030 sub database
1031 {
1032 # Read only
1033 return( shift->{database} );
1034 }
1035  
1036 sub databases { return( shift->error( "Method databases() is not implemented by driver." ) ); }
1037  
1038 sub datatype_dict
1039 {
1040 my $self = shift( @_ );
1041 my $class = ( ref( $self ) || $self );
1042 no strict 'refs';
1043 my $sym = $self->_get_symbol( $class => '$DATATYPES_DICT' );
1044 if( !defined( $sym ) )
1045 {
1046 return( $self->pass_error ) if( $self->error );
1047 return( $self->error( "No global variable \$DATATYPES_DICT defined in class $class" ) );
1048 }
1049 my $dict = $$sym;
1050 return( $self->error( "Symbol found for \$DATATYPES_DICT in class $class did not resolve into an expecxted hash reference." ) ) if( ref( $dict ) ne 'HASH' );
1051 if( @_ )
1052 {
1053 return( $dict->{ lc( shift( @_ ) ) } );
1054 }
1055 return( $dict );
1056 }
1057  
1058 # See also constant_to_datatype()
1059 sub datatype_to_constant
1060 {
1061 my $self = shift( @_ );
1062 my $ref = $self->datatypes || return( $self->pass_error );
1063 return unless( scalar( @_ ) && defined( $_[0] ) );
1064 return( $ref->{ lc( shift( @_ ) ) } );
1065 }
1066  
1067 # Returns an hash of SQL constant name to its value
1068 sub datatypes
1069 {
1070 my $self = shift( @_ );
1071 my $dict = $self->datatype_dict || return( $self->pass_error );
1072 my $ref = +{ map{ $_ => $dict->{ $_ }->{constant} } keys( %$dict ) };
1073 return( $ref );
1074 }
1075  
1076 sub disconnect($)
1077 {
1078 my $self = shift( @_ );
1079 # my( $pack, $file, $line ) = caller();
1080 # print( STDERR "disconnect() called from package '$pack' in file '$file' at line '$line'.\n" );
1081 my $rc = $self->{dbh}->disconnect( @_ );
1082 return( $rc );
1083 }
1084  
1085 sub do($;$@)
1086 {
1087 my $self = shift( @_ );
1088 # $rc = $dbh->do( $statement ) || die( $dbh->errstr );
1089 # $rc = $dbh->do( $statement, \%attr ) || die( $dbh->errstr );
1090 # $rv = $dbh->do( $statement, \%attr, @bind_values ) || ...
1091 # my( $rows_deleted ) = $dbh->do(
1092 # q{
1093 # DELETE FROM table WHERE status = ?
1094 # }, undef(), 'DONE' ) || die( $dbh->errstr );
1095 my $query = shift( @_ );
1096 my $opt_ref = shift( @_ ) || undef();
1097 my $param_ref = shift( @_ ) || [];
1098 my $dbh = $self->can( 'database_object' ) ? $self->database_object : $self;
1099 $dbh or return( $self->error( "Could not find database handler." ) );
1100 my $sth = $dbh->prepare( $query, $opt_ref ) ||
1101 return( $self->error( "Error while preparing do query:\n$query", $dbh->errstr() ) );
1102 $sth->execute( @$param_ref ) ||
1103 return( $self->error( "Error while executing do query:\n$query", $sth->errstr() ) );
1104 # my $rows = $sth->rows();
1105 # return( ( $rows == 0 ) ? "0E0" : $rows );
1106 return( $sth );
1107 }
1108  
1109 sub driver { return( shift->_set_get( 'driver' ) ); }
1110  
1111 sub enhance
1112 {
1113 my $self = shift( @_ );
1114 my $prev = $self->{enhance};
1115 $self->{enhance} = shift( @_ ) if( @_ );
1116 return( $prev );
1117 }
1118  
1119 sub err(@)
1120 {
1121 my $self = shift( @_ );
1122 # $rv = $h->err;
1123 if( defined( $self->{sth} ) )
1124 {
1125 return( $self->{sth}->err() );
1126 }
1127 elsif( $self->{dbh} )
1128 {
1129 return( $self->{dbh}->err() );
1130 }
1131 #else
1132 #{
1133 # return( $self->{ 'drh' }->err() );
1134 # return( DBI::err();
1135 #}
1136 }
1137  
1138 sub errno
1139 {
1140 goto( &err );
1141 }
1142  
1143 sub errmesg
1144 {
1145 goto( &errstr );
1146 }
1147  
1148 sub errstr(@)
1149 {
1150 my $self = shift( @_ );
1151 if( !ref( $self ) )
1152 {
1153 return( $DBI::errstr );
1154 }
1155 elsif( defined( $self->{sth} ) && $self->{sth}->errstr() )
1156 {
1157 return( $self->{sth}->errstr() );
1158 }
1159 elsif( defined( $self->{dbh} ) && $self->{dbh}->errstr() )
1160 {
1161 return( $self->{dbh}->errstr() );
1162 }
1163 else
1164 {
1165 return( $self->{errstr} );
1166 }
1167 }
1168  
1169 sub FALSE { return( 'FALSE' ); }
1170  
1171 sub fatal
1172 {
1173 my $self = shift( @_ );
1174 if( @_ )
1175 {
1176 $self->{fatal} = int( shift( @_ ) );
1177 }
1178 return( $self->{fatal} );
1179 }
1180  
1181 sub get_sql_type { return( shift->error( "The driver has not provided support for this method get_sql_type()" ) ); }
1182  
1183 sub host { return( shift->_set_get_scalar( 'host', @_ ) ); }
1184  
1185 sub IN { return( shift->_operator_object_create( 'DB::Object::IN', @_ ) ); }
1186  
1187 # $rv = $dbh->last_insert_id($catalog, $schema, $table, $field, \%attr);
1188 sub last_insert_id
1189 {
1190 my $self = shift( @_ );
1191 return( $self->error( "Method \"last_insert_id\" has not been implemented by driver $self->{driver} (object = $self)." ) );
1192 }
1193  
1194 sub LIKE { return( shift->_operator_object_create( 'DB::Object::LIKE', @_ ) ); }
1195  
1196 sub lock
1197 {
1198 my $self = shift( @_ );
1199 return( $self->error( "Method \"lock\" has not been implemented by driver $self->{driver} (object = $self)." ) );
1200 }
1201  
1202 sub login { return( shift->_set_get_scalar( 'login', @_ ) ); }
1203  
1204 # This value will be passed on to newly instantiated DB::Object::Tables objects
1205 sub no_bind { return( shift->_set_get_boolean( 'no_bind', @_ ) ); }
1206  
1207 sub no_cache
1208 {
1209 my $self = shift( @_ );
1210 $self->{cache} = 0;
1211 return( $self );
1212 }
1213  
1214 sub NOT { return( shift->_operator_object_create( 'DB::Object::NOT', @_ ) ); }
1215  
1216 sub NULL { return( 'NULL' ); }
1217  
1218 sub OR { return( shift->_operator_object_create( 'DB::Object::OR', @_ ) ); }
1219  
1220 sub P { return( shift->placeholder( @_ ) ); }
1221  
1222 sub param
1223 {
1224 my $self = shift( @_ );
1225 return if( !@_ );
1226 my @supported =
1227 qw(
1228 SQL_AUTO_IS_NULL AUTOCOMMIT SQL_BIG_TABLES SQL_BIG_SELECTS
1229 SQL_BUFFER_RESULT SQL_LOW_PRIORITY_UPDATES SQL_MAX_JOIN_SIZE
1230 SQL_SAFE_MODE SQL_SELECT_LIMIT SQL_LOG_OFF SQL_LOG_UPDATE
1231 TIMESTAMP INSERT_ID LAST_INSERT_ID
1232 );
1233 my $params = $self->{params} ||= {};
1234 if( @_ == 1 )
1235 {
1236 my $type = shift( @_ );
1237 $type = uc( $type ) if( scalar( grep{ /^$_[ 0 ]$/i } @supported ) );
1238 return( $params->{ $type } );
1239 }
1240 else
1241 {
1242 my %arg = ( @_ );
1243 my( $type, $value );
1244 my @query = ();
1245 while( ( $type, $value ) = each( %arg ) )
1246 {
1247 my @found = grep{ /^(SQL_)?$type$/i } @supported;
1248 # SQL parameter
1249 if( scalar( @found ) )
1250 {
1251 $type = uc( $type );
1252 $value = 0 if( !defined( $value ) || $value eq '' );
1253 $params->{ $type } = $value;
1254 if( $type eq 'AUTOCOMMIT' && $self->{dbh} && $value =~ /^(?:1|0)$/ )
1255 {
1256 $self->{dbh}->{AutoCommit} = $value;
1257 }
1258 push( @query, "$type = $value" );
1259 }
1260 # Private parameter - May be anything
1261 else
1262 {
1263 $params->{ $type } = $value;
1264 }
1265 }
1266 return( $self ) if( !scalar( @query ) );
1267 my $dbh = $self->{dbh} || return( $self->error( "Could not find database handler." ) );
1268 my $query = 'SET ' . CORE::join( ', ', @query );
1269 my $sth = $dbh->prepare( $query ) ||
1270 return( $self->error( "Unable to set options '", CORE::join( ', ', @query ), "'" ) );
1271 $sth->execute();
1272 $sth->finish();
1273 return( $self );
1274 }
1275 }
1276  
1277 sub passwd { return( shift->_set_get_scalar( 'passwd', @_ ) ); }
1278  
1279 sub ping(@)
1280 {
1281 #return( shift->{ 'dbh' }->ping );
1282 my $self = shift( @_ );
1283 return( $self->{dbh}->ping );
1284 }
1285  
1286 sub ping_select(@)
1287 {
1288 my $self = shift( @_ );
1289 # $rc = $dbh->ping;
1290 # Some new ping method replacement.... See Apache::DBI
1291 # my( $dbh ) = @_;
1292 my $ret = 0;
1293 eval
1294 {
1295 local( $SIG{__DIE__} ) = sub{ return( 0 ); };
1296 local( $SIG{__WARN__} ) = sub{ return( 0 ); };
1297 # adapt the select statement to your database:
1298 my $sth = $self->prepare( "SELECT 1" );
1299 $ret = $sth && ( $sth->execute() );
1300 $sth->finish();
1301 };
1302 return( ($@) ? 0 : $ret );
1303 }
1304  
1305 sub placeholder
1306 {
1307 my $self = shift( @_ );
1308 $self->_load_class( 'DB::Object::Placeholder' ) || return( $self->pass_error );
1309 my $opts = $self->_get_args_as_hash( @_ );
1310 $opts->{debug} = $self->debug if( !exists( $opts->{debug} ) );
1311 my $obj = DB::Object::Placeholder->new( %$opts ) ||
1312 return( $self->pass_error( DB::Object::Placeholder->error ) );
1313 return( $obj );
1314 }
1315  
1316 sub port { return( shift->_set_get_number( 'port', @_ ) ); }
1317  
1318 # Gateway to DB::Object::Statement
1319 sub prepare($;$)
1320 {
1321 my $self = shift( @_ );
1322 my $class = ref( $self ) || $self;
1323 my $query = shift( @_ );
1324 my $opt_ref = shift( @_ ) || undef();
1325 my $base_class = $self->base_class;
1326 my $q;
1327 if( $self->_is_a( $query => "${base_class}::Query" ) )
1328 {
1329 $q = $query;
1330 $query = $q->as_string;
1331 }
1332 elsif( $self->_is_a( $self => "${base_class}::Tables" ) )
1333 {
1334 $q = $self->query_object;
1335 }
1336 $self->_clean_statement( \$query );
1337 # Wether we are called from DB::Object or DB::Object::Tables object
1338 my $dbo = $self->{dbo} || $self->{database_object} || $self;
1339 if( !$dbo->ping )
1340 {
1341 my $dbh = $dbo->_dbi_connect || return( $self->pass_error );
1342 $dbo->{dbh} = $dbh;
1343 }
1344 local $@;
1345 my $sth = eval
1346 {
1347 local( $SIG{__DIE__} ) = sub{ };
1348 local( $SIG{__WARN__} ) = sub{ };
1349 $dbo->{dbh}->prepare( $query, $opt_ref );
1350 };
1351 if( $sth )
1352 {
1353 # my $data = { 'sth' => $sth, 'query' => $query };
1354 my( $query_values, $sel_fields );
1355 if( $q )
1356 {
1357 $query_values = $q->query_values;
1358 $sel_fields = $q->selected_fields;
1359 }
1360 my $data =
1361 {
1362 sth => $sth,
1363 query => $query,
1364 # query_values => $q->query_values,
1365 # selected_fields => $q->selected_fields,
1366 ( defined( $query_values ) ? ( query_values => $query_values ) : () ),
1367 ( defined( $sel_fields ) ? ( selected_fields => $sel_fields ) : () ),
1368 ( $q ? ( query_object => $q ) : () ),
1369 };
1370 return( $self->_make_sth( "${base_class}::Statement", $data ) );
1371 }
1372 else
1373 {
1374 my $err = $@ || $self->{dbh}->errstr() || 'Unknown error while cache preparing query.';
1375 $self->{query} = $query;
1376 return( $self->error( $err ) );
1377 }
1378 }
1379  
1380 sub prepare_cached
1381 {
1382 my $self = shift( @_ );
1383 my $class = ref( $self ) || $self;
1384 my $query = shift( @_ );
1385 my $opt_ref = shift( @_ ) || undef();
1386 my $base_class = $self->base_class;
1387 my $q;
1388 if( $self->_is_a( $q => "${base_class}::Query" ) )
1389 {
1390 $q = $query;
1391 $query = $q->as_string;
1392 }
1393 $self->_clean_statement( \$query );
1394 # Wether we are called from DB::Object or DB::Object::Tables object
1395 my $dbo = $self->{dbo} || $self->{database_object} || $self;
1396 if( !$dbo->ping )
1397 {
1398 my $dbh = $dbo->_dbi_connect || return( $self->pass_error );
1399 $dbo->{dbh} = $dbh;
1400 }
1401 my $sth = eval
1402 {
1403 local( $SIG{__DIE__} ) = sub{ };
1404 local( $SIG{__WARN__} ) = sub{ };
1405 $dbo->{dbh}->prepare_cached( $query, $opt_ref );
1406 };
1407 if( $sth )
1408 {
1409 # my $data = { %$self, 'sth' => $sth, 'query' => $query };
1410 # my $data = { 'sth' => $sth, 'query' => $query };
1411 my $data =
1412 {
1413 sth => $sth,
1414 query => $query,
1415 query_values => $self->{query_values},
1416 selected_fields => $self->{selected_fields},
1417 ( $q ? ( query_object => $q ) : () ),
1418 };
1419 # CORE::delete( $data->{ 'executed' } );
1420 # This is an inner package
1421 # bless( $data, "DB::Object::Statement" );
1422 # return( $data );
1423 return( $self->_make_sth( "${base_class}::Statement", $data ) );
1424 }
1425 else
1426 {
1427 my $err = $@ || $self->{dbh}->errstr() || 'Unknown error while cache preparing query.';
1428 $self->{query} = $query;
1429 return( $self->error( $err ) );
1430 }
1431 }
1432  
1433 sub query($$)
1434 {
1435 my $self = shift( @_ );
1436 my $sth = $self->prepare( @_ );
1437 my $result;
1438 if( $sth && !( $result = $sth->execute() ) )
1439 {
1440 return;
1441 }
1442 else
1443 {
1444 # bless( $sth, ref( $self ) );
1445 return( $sth );
1446 }
1447 }
1448  
1449 sub query_object { return( shift->_set_get_object_without_init( 'query_object', 'DB::Object::Query', @_ ) ); }
1450  
1451 sub quote
1452 {
1453 my $self = shift( @_ );
1454 # my $dbh = $self->{dbh} || return( $self->error( "No database handler was set." ) );
1455 my $dbh;
1456 unless( $dbh = $self->{dbh} )
1457 {
1458 # This is a fallback in case we need to use quote, but do not have a database connection yet.
1459 my $str = shift( @_ );
1460 # print( STDERR ref( $self ), "::quote -> \$str is '$str' (without surrounding quote\n" );
1461 return( $self->NULL ) if( !defined( $str ) || uc( $str ) eq 'NULL' );
1462 if( $str =~ /^$RE{num}{real}$/ )
1463 {
1464 return( $str );
1465 }
1466 else
1467 {
1468 $str =~ s/'/''/g; # iso SQL 2
1469 return( "'$str'" );
1470 }
1471 }
1472 return( $dbh->quote( @_ ) );
1473 }
1474  
1475 sub serialiser { return( shift->_set_get_scalar( 'serialiser', @_ ) ); }
1476  
1477 sub serializer { return( shift->serialiser( @_ ) ); }
1478  
1479 sub set
1480 {
1481 my $self = shift( @_ );
1482 my $vars = '';
1483 $vars = shift( @_ );
1484 $vars ||= $self->local();
1485 # Are there any variable declaration?
1486 if( $vars )
1487 {
1488 my $query = "SET $vars";
1489 eval
1490 {
1491 local( $SIG{__DIE__} ) = sub{ };
1492 local( $SIG{__WARN__} ) = sub{ };
1493 local( $SIG{ALRM} ) = sub{ die( "Timeout while processing query to set variables:\n$query\n" ) };
1494 $self->do( $query );
1495 };
1496 if( $@ )
1497 {
1498 my $err = '*** ' . join( "\n*** ", split( /\n/, $@ ) );
1499 if( $self->fatal() )
1500 {
1501 die( "Error occured while setting SQL variables before executing query:\n$self->{sth}->{Statement}\n$err\n" );
1502 }
1503 else
1504 {
1505 return( $self->error( $@ ) );
1506 }
1507 }
1508 }
1509 return(1);
1510 }
1511  
1512 # To also consider:
1513 # $sth = $dbh->statistics_info( undef, $schema, $table, $unique_only, $quick );
1514 sub stat
1515 {
1516 my $self = shift( @_ );
1517 my $type = lc( shift( @_ ) );
1518 my $sth = $self->prepare( "SHOW STATUS" );
1519 $sth->execute();
1520 my @data = ();
1521 my $ref = {};
1522 while( @data = $sth->fetchrow() )
1523 {
1524 $ref->{ lc( $data[ 0 ] ) } = $data[ 1 ];
1525 }
1526 $sth->finish();
1527 if( $type )
1528 {
1529 return( exists( $ref->{ $type } ) ? $ref->{ $type } : undef() );
1530 }
1531 else
1532 {
1533 return( wantarray() ? () : undef() ) if( !%$ref );
1534 return( wantarray() ? %$ref : $ref );
1535 }
1536 }
1537  
1538 sub state(@)
1539 {
1540 my $self = shift( @_ );
1541 # $str = $h->state;
1542 if( !ref( $self ) )
1543 {
1544 return( $DBI::state );
1545 }
1546 else
1547 {
1548 return( $self->SUPER::state() );
1549 }
1550 }
1551  
1552 sub supported_class
1553 {
1554 my $self = shift( @_ );
1555 my @classes = values( %$DRIVER2PACK );
1556 return( @classes );
1557 }
1558  
1559 sub supported_drivers
1560 {
1561 my $self = shift( @_ );
1562 my @drivers = keys( %$DRIVER2PACK );
1563 return( @drivers );
1564 }
1565  
1566 sub table
1567 {
1568 my $self = shift( @_ );
1569 my $base_class = $self->base_class;
1570 return( $self->error( "You must use the database object to access this method." ) ) if( ref( $self ) ne $base_class );
1571 my $table = shift( @_ ) ||
1572 return( $self->error( "You must provide a table name to access the table methods." ) );
1573 my $table_class = "${base_class}::Tables";
1574 $self->_load_class( $table_class ) || return( $self->pass_error );
1575 my $host = $self->{server} // '';
1576 my $db = $self->{database} // '';
1577 my $tbl;
1578 if( my $medium = $self->cache_table )
1579 {
1580 $tbl = $self->_cache_table(
1581 host => $self->host,
1582 database => $self->database,
1583 table => $table,
1584 ( $medium eq 'file' ? ( medium => $medium ) : () )
1585 );
1586 return( $self->pass_error ) if( !defined( $tbl ) );
1587 $tbl->reset if( $tbl );
1588 }
1589 else
1590 {
1591 # cache_table is not enabled.
1592 }
1593  
1594 if( !$tbl )
1595 {
1596 $tbl = $table_class->new( $table,
1597 # Not necessary
1598 # dbh => $self->{dbh},
1599 dbo => $self,
1600 debug => $self->debug,
1601 ) || return( $self->pass_error( $table_class->error ) );
1602 $tbl->reset;
1603 if( $self->cache_table )
1604 {
1605 $self->_cache_table(
1606 host => $self->host,
1607 database => $self->database,
1608 table => $tbl,
1609 ) || return( $self->pass_error );
1610 }
1611 }
1612 $tbl->no_bind( $self->no_bind );
1613 # We set debug and again here in case it changed since the table object was instantiated
1614 $tbl->debug( $self->debug );
1615 return( $tbl );
1616 }
1617  
1618 sub table_exists
1619 {
1620 my $self = shift( @_ );
1621 my $table = shift( @_ ) ||
1622 return( $self->error( "You must provide a table name to access the table methods." ) );
1623 my $cache_tables = $self->cache_tables;
1624 my $tables_in_cache = [];
1625 if( defined( $cache_tables ) )
1626 {
1627 $tables_in_cache = $cache_tables->get({
1628 host => $self->host,
1629 driver => $self->driver,
1630 port => $self->port,
1631 database => $self->database,
1632 });
1633 }
1634 foreach my $ref ( @$tables_in_cache )
1635 {
1636 return( 1 ) if( $ref->{name} eq $table );
1637 }
1638 # We did not find it, so let's try by checking directly the database
1639 my $def = $self->table_info( $table );
1640 return( $self->pass_error ) if( !defined( $def ) );
1641 return(0) if( $self->_is_empty( $def ) );
1642 return(1);
1643 }
1644  
1645 sub table_info
1646 {
1647 my $self = shift( @_ );
1648 return( $self->error( "table_info() has not been implemented by driver \"$self->{driver}\" (object = $self)." ) );
1649 }
1650  
1651 sub table_push
1652 {
1653 my $self = shift( @_ );
1654 my $table = shift( @_ ) || return( $self->error( "No table provided to add to our cache." ) );
1655 my $def = $self->tables_info || return;
1656 my $hash =
1657 {
1658 host => $self->host,
1659 driver => $self->driver,
1660 port => $self->port,
1661 database => $self->database,
1662 tables => $def,
1663 };
1664 my $cache_tables = $self->cache_tables;
1665 if( !defined( $cache_tables->set( $hash ) ) )
1666 {
1667 return( $self->pass_error( $cache_tables->error ) );
1668 }
1669 return( $table );
1670 }
1671  
1672 sub tables
1673 {
1674 my $self = shift( @_ );
1675 my $db = shift( @_ ) || $self->database;
1676 my $opts = $self->_get_args_as_hash( @_ );
1677 $db = $opts->{database} if( $opts->{database} );
1678 my $all = [];
1679 if( !$opts->{no_cache} && !$opts->{live} )
1680 {
1681 if( my $cache_tables = $self->cache_tables )
1682 {
1683 $all = $cache_tables->get({
1684 host => $self->host,
1685 driver => $self->driver,
1686 port => $self->port,
1687 database => $db,
1688 }) || do
1689 {
1690 $self->error( "Warning only: an error occured while trying to fetch the tables cache for host '", $self->host, "', driver '", $self->driver, "', port '", $self->port, "' and database '", $self->database, "': ", $cache_tables->error, "\n" );
1691 };
1692 }
1693 else
1694 {
1695 $self->error( "Warning only: no cache tables object found in our self ($self)! Current keys are: '", join( "', '", sort( keys( %$self ) ) ), "'." );
1696 }
1697 }
1698 if( $opts->{no_cache} || $opts->{live} || !scalar( @$all ) )
1699 {
1700 $all = $self->tables_info || return;
1701 }
1702 my @tables = ();
1703 @tables = map( $_->{name}, @$all ) if( scalar( @$all ) );
1704 return( \@tables );
1705 }
1706  
1707 sub tables_cache
1708 {
1709 my $self = shift( @_ );
1710 my $opts = $self->_get_args_as_hash( @_ );
1711 my $cache_tables = $self->cache_tables;
1712 my $cache = $cache_tables->get({
1713 host => $self->host,
1714 driver => $self->driver,
1715 port => $self->port,
1716 database => $self->database,
1717 });
1718 return( $cache );
1719 }
1720  
1721 sub tables_info { return( shift->error( "tables_info() has not been implemented by driver." ) ); }
1722  
1723 sub tables_refresh
1724 {
1725 my $self = shift( @_ );
1726 my $db = shift( @_ ) || $self->database;
1727 my $tables = $self->tables_info || return;
1728 my $hash =
1729 {
1730 host => $self->host,
1731 driver => $self->driver,
1732 port => $self->port,
1733 database => $self->database,
1734 tables => $tables,
1735 };
1736 my $cache_tables = $self->cache_tables;
1737 if( !defined( $cache_tables->set( $hash ) ) )
1738 {
1739 return( $self->pass_error( $cache_tables->error ) );
1740 }
1741 return( wantarray() ? @$tables : $tables );
1742 }
1743  
1744 # Used to flag this as a transaction when begin_work is triggered
1745 sub transaction { return( shift->_set_get_boolean( 'transaction', @_ ) ); }
1746  
1747 sub TRUE { return( 'TRUE' ); }
1748  
1749 sub unknown_field { return( shift->_set_get_scalar( 'unknown_field', @_ ) ); }
1750  
1751 sub unlock
1752 {
1753 my $self = shift( @_ );
1754 return( $self->error( "Method \"unlock\" has not been implemented by driver $self->{driver} (object $self)." ) );
1755 }
1756  
1757 sub use
1758 {
1759 my $self = shift( @_ );
1760 my $base_class = $self->base_class;
1761 return( $self->error( "You must use the the database object to switch database." ) ) if( ref( $self ) ne $base_class );
1762 my $db = shift( @_ );
1763 # No need to go further
1764 return( $self ) if( $db eq $self->{database} );
1765 my $repo = Module::Generic::Global->new( 'available_databases' => CORE::ref( $self ), key => CORE::ref( $self ) ) ||
1766 return( $self->pass_error( Module::Generic::Global->error ) );
1767 my $all_dbs = $repo->get;
1768 if( !defined( $all_dbs ) || !$self->_is_array( $all_dbs ) )
1769 {
1770 $all_dbs = [];
1771 @$all_dbs = $self->databases();
1772 $repo->set( $all_dbs );
1773 }
1774 if( !scalar( grep{ /^$db$/ } @$all_dbs ) )
1775 {
1776 return( $self->error( "The database '$db' does not exist." ) );
1777 }
1778 my $dbh = $base_class->connect( $db ) ||
1779 return( $self->error( "Unable to connect to database '$db'." ) );
1780 $self->param( 'multi_db' => 1 );
1781 $dbh->param( 'multi_db' => 1 );
1782 return( $dbh );
1783 }
1784  
1785 sub use_cache { return( shift->_set_get_boolean( 'cache', @_ ) ) }
1786  
1787 sub use_bind { return( shift->_set_get_boolean( 'bind', @_ ) ) }
1788  
1789 sub variables
1790 {
1791 my $self = shift( @_ );
1792 my $type = shift( @_ );
1793 $self->error( "Variable '$type' is a read-only value." ) if( @_ );
1794 my $vars = $self->{variables} ||= {};
1795 if( !%$vars )
1796 {
1797 my $sth = $self->prepare( "SHOW VARIABLES" ) ||
1798 return( $self->error( "SHOW VARIABLES is not supported." ) );
1799 $sth->execute();
1800 my $ref = $self->fetchall_arrayref();
1801 my %vars = map{ lc( $_->[ 0 ] ) => $_->[ 1 ] } @$ref;
1802 $vars = \%vars if( %vars );
1803 $sth->finish();
1804 }
1805 my @found = grep{ /$type/i } keys( %$vars );
1806 return( '' ) if( !scalar( @found ) );
1807 return( $vars->{ $found[ 0 ] } );
1808 }
1809  
1810 sub version
1811 {
1812 return( shift->error( "This driver has not set the version() method." ) );
1813 }
1814  
1815 # When the table schema caching is enabled, we store the table field objects in an hash reference
1816 # database->table => table_object
1817 sub _cache_table
1818 {
1819 my $self = shift( @_ );
1820 my $opts = $self->_get_args_as_hash( @_ );
1821 my $class = ( ref( $self ) || $self );
1822 my $base_class = $self->base_class;
1823 my $medium = $opts->{medium} // $self->cache_table;
1824 if( defined( $medium ) && "$medium" !~ /^0|1|file$/ )
1825 {
1826 return( $self->error( "medium argument or 'cache_table' method value has unsupported value. It can only be 0, 1 or 'file'." ) );
1827 }
1828 # Short-circuit if the preferred cache medium is file
1829 if( $medium eq 'file' )
1830 {
1831 return( $self->_cache_table_on_file( %$opts ) );
1832 }
1833 my $repo = Module::Generic::Global->new( table_cache => 'system',
1834 on_get => sub
1835 {
1836 my $cache = shift( @_ );
1837 # my $repo = $_;
1838 # Structure of the cache is host->database->table_name
1839 if( ref( $cache ) eq 'HASH' )
1840 {
1841 foreach my $host ( keys( %$cache ) )
1842 {
1843 next unless( ref( $cache->{ $host } ) eq 'HASH' );
1844 foreach my $db ( keys( %{$cache->{ $host }} ) )
1845 {
1846 next unless( ref( $cache->{ $host }->{ $db } ) eq 'HASH' );
1847 foreach my $tbl_name ( keys( %{$cache->{ $host }->{ $db }} ) )
1848 {
1849 my $table = $cache->{ $host }->{ $db }->{ $tbl_name };
1850 next unless( $self->_is_a( $table => "${base_class}::Tables" ) );
1851 $table->database_object( $self );
1852 if( my $qo = $table->query_object )
1853 {
1854 $qo->database_object( $self );
1855 }
1856 }
1857 }
1858 }
1859 }
1860 return( $cache );
1861 }
1862 ) || return( $self->pass_error( Module::Generic::Global->error ) );
1863 $repo->lock;
1864 my $cache = $repo->get // {};
1865 unless( CORE::exists( $opts->{host} ) && CORE::exists( $opts->{database} ) )
1866 {
1867 return( $cache );
1868 }
1869 my( $host, $database, $table ) = @$opts{qw( host database table )};
1870 return( $self->error( "A host name was provided, but is undefined or empty." ) ) if( !defined( $host ) || !CORE::length( $host // '' ) );
1871 return( $self->error( "A database name was provided, but is undefined or empty." ) ) if( !defined( $database ) || !CORE::length( $database // '' ) );
1872 my $updated = 0;
1873 if( !defined( $cache->{ $host } ) )
1874 {
1875 if( !CORE::exists( $cache->{ $host } ) ||
1876 ref( $cache->{ $host } ) ne 'HASH' )
1877 {
1878 $cache->{ $host } = {};
1879 $updated++;
1880 }
1881 }
1882 if( !defined( $cache->{ $host }->{ $database } ) )
1883 {
1884 if( !CORE::exists( $cache->{ $host }->{ $database } ) ||
1885 ref( $cache->{ $host }->{ $database } ) ne 'HASH' )
1886 {
1887 $cache->{ $host }->{ $database } = {};
1888 $updated++;
1889 }
1890 }
1891 # The caller has not provided any table value, hinting it wants the entire hash repository for this database.
1892 if( !defined( $table ) )
1893 {
1894 $repo->set( $cache ) if( $updated );
1895 return( $cache->{ $host }->{ $database } );
1896 }
1897 # We are given a table object, we store it in the repository. This is mutator mode
1898 if( $self->_is_a( $table => "${base_class}::Tables" ) )
1899 {
1900 my $name = $table->name ||
1901 return( $self->error( "No table name associated with this table object." ) );
1902 my $dbo = $table->database_object;
1903 $table->database_object( undef );
1904 my $clone = $table->clone;
1905 $table->database_object( $dbo );
1906 $cache->{ $host }->{ $database }->{ "$name" } = $clone;
1907 $repo->set( $cache );
1908 }
1909 # The user has provided a table name, and thus expects the related cloned table object from the cache table repository.
1910 # This is accessor mode.
1911 elsif( !ref( $table ) || ( ref( $table ) && $self->_can_overload( $table => '""' ) ) )
1912 {
1913 if( !CORE::exists( $cache->{ $host }->{ $database }->{ "$table" } ) ||
1914 !defined( $cache->{ $host }->{ $database }->{ "$table" } ) )
1915 {
1916 return( '' );
1917 }
1918 my $tbl = $cache->{ $host }->{ $database }->{ "$table" };
1919 unless( $self->_is_a( $tbl => "${base_class}::Tables" ) )
1920 {
1921 die( "Table object found (", $self->_str_val( $tbl ), ") in this statement object is actually not a table object (${base_class}::Tables) !" );
1922 }
1923 my $table_class = ref( $tbl );
1924 $self->_load_class( $table_class ) || return( $self->pass_error );
1925 my $clone = $tbl->clone;
1926 # $clone->database_object( $self );
1927 $clone->attach( $self );
1928 return( $clone );
1929 }
1930 else
1931 {
1932 return( $self->error( "I do not understand the value provided for the 'table' option -> ", $self->_str_val( $table ) ) );
1933 }
1934 }
1935  
1936 # Set or get the table object serialised on file.
1937 sub _cache_table_on_file
1938 {
1939 my $self = shift( @_ );
1940 my $base_class = $self->base_class;
1941 my $dbo;
1942 if( $self->isa( $base_class ) )
1943 {
1944 $dbo = $self;
1945 }
1946 elsif( $self->can( 'database_object' ) )
1947 {
1948 $dbo = $self->database_object ||
1949 return( $self->error( "There is no database object associated." ) );
1950 }
1951 else
1952 {
1953 return( $self->error( "This object is neither a $base_class object, nor an object that supports the 'database_object' method." ) );
1954 }
1955 # new_file() is inherited from Module::Generic
1956 my $cache_dir = $self->cache_dir;
1957 if( $self->_is_empty( $cache_dir ) )
1958 {
1959 return( $self->error( "No cache directory is set." ) );
1960 }
1961 $cache_dir = $self->new_file( $cache_dir );
1962 # Ensure cache directory exists
1963 if( !$cache_dir->exists )
1964 {
1965 $cache_dir->mkpath || return( $self->pass_error( $cache_dir->error ) );
1966 }
1967 elsif( !$cache_dir->is_dir )
1968 {
1969 return( $self->error( "Cache directory path '$cache_dir' exists but is not a directory." ) );
1970 }
1971  
1972 my $opts = $self->_get_args_as_hash( @_ );
1973 my $serialiser = $self->serialiser || $DB::Object::SERIALISER || 'Storable';
1974 my( $host, $database, $table ) = @$opts{qw( host database table )};
1975 if( !defined( $host ) || !CORE::length( $host // '' ) )
1976 {
1977 return( $self->error( "A host name was provided, but is undefined or empty." ) );
1978 }
1979 elsif( !defined( $database ) || !CORE::length( $database // '' ) )
1980 {
1981 return( $self->error( "A database name was provided, but is undefined or empty." ) );
1982 }
1983 elsif( $database !~ /^\w+$/ )
1984 {
1985 return( $self->error( "The database name '$database' contains illegal characters." ) );
1986 }
1987  
1988 if( !$self->ping )
1989 {
1990 my $dbh = $self->_dbi_connect || return( $self->pass_error );
1991 $self->{dbh} = $dbh;
1992 }
1993  
1994 # Normalise host for filename usage: keep only [A-Za-z0-9_.-], percent-encode everything else.
1995 # This avoids collisions that would happen with s/\W//g and supports IPv6, ports, etc.
1996 my $host_key = "$host";
1997 $host_key =~ s/([^A-Za-z0-9_.-])/sprintf( '%%%02X', ord( $1 ) )/ge;
1998 my $prefix = "table-${host_key}-${database}-\L${serialiser}";
1999  
2000 my $deserialise_from_file = sub
2001 {
2002 my $f = shift( @_ );
2003 my $name = $f->basename( '.bin' );
2004 if( index( $name, $prefix ) != 0 )
2005 {
2006 # Unexpected file name format; ignore it
2007 warn( "Ignoring cache file with unexpected name format: '$f'" ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
2008 return;
2009 }
2010  
2011 $self->_load_class( $base_class, { force => 1 } ) || return( $self->pass_error );
2012 $self->_load_class( 'DB::Object::Tables', { force => 1 } ) || return( $self->pass_error );
2013 $self->_load_class( 'DB::Object::Constraint::Foreign', { force => 1 } ) || return( $self->pass_error );
2014 $self->_load_class( "${base_class}::Tables", { force => 1 } ) || return( $self->pass_error );
2015 my $tbl = $self->Module::Generic::deserialise(
2016 file => $f,
2017 lock => 1,
2018 serialiser => $serialiser,
2019 ) || return;
2020 unless( $self->_is_a( $tbl => "${base_class}::Tables" ) )
2021 {
2022 warn( "Deserialised object from file '$f' is not a ${base_class}::Tables object, but a '", ref( $tbl ), " object." ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
2023 return;
2024 }
2025  
2026 # bless( $tbl => $table_class );
2027 $tbl->attach( $dbo ) || return( $self->pass_error( $tbl->error ) );
2028 return( $tbl );
2029 };
2030  
2031 # The caller wants the whole shebang
2032 if( !defined( $table ) )
2033 {
2034 # The caller wants all the table objects for that host and database
2035 my @files = $cache_dir->glob( "${prefix}-[a-zA-Z0-9_][a-zA-Z0-9_\\-\\.]*.bin" );
2036 my $cache = {};
2037 foreach my $f ( @files )
2038 {
2039 my $table = $deserialise_from_file->( $f ) || next;
2040 my $name = $f->basename( '.bin' );
2041 if( index( $name, $prefix ) != 0 )
2042 {
2043 # Unexpected file name format; ignore it
2044 warn( "Ignoring cache file with unexpected name format: '$f'" ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
2045 next;
2046 }
2047 $name = [split( /-/, $name )]->[-1];
2048 $cache->{ $name } = $table;
2049 }
2050 return( $cache );
2051 }
2052 # We are given a table object, we store it in the repository. This is mutator mode
2053 elsif( $self->_is_a( $table => "${base_class}::Tables" ) )
2054 {
2055 my $name = $table->name ||
2056 return( $self->error( "No table name associated with this table object." ) );
2057 if( $name !~ /^\w+[\w\-\.]*$/ )
2058 {
2059 return( $self->error( "The table name '$name' contains illegal characters." ) );
2060 }
2061 my $file = $cache_dir->child( "${prefix}-${name}.bin" );
2062 my $tbl = $self->Module::Generic::serialise( $table,
2063 file => $file,
2064 lock => 1,
2065 serialiser => $serialiser,
2066 ( $serialiser eq 'Sereal' ? ( freeze_callbacks => 1 ) : () ),
2067 ) || return( $self->pass_error );
2068 return(1);
2069 }
2070 # The user has provided a table name, and thus expects the related cloned table object from the cache table repository.
2071 # This is accessor mode.
2072 elsif( !ref( $table ) || ( ref( $table ) && $self->_can_overload( $table => '""' ) ) )
2073 {
2074 $table = "$table";
2075 if( $table !~ /^\w+[\w\-\.]*$/ )
2076 {
2077 return( $self->error( "The table name '$table' contains illegal characters." ) );
2078 }
2079 my $cache_file = $cache_dir->child( "${prefix}-${table}.bin" );
2080 if( !$cache_file->exists || $cache_file->is_empty || !$cache_file->is_file )
2081 {
2082 return( '' );
2083 }
2084 my $tbl = $deserialise_from_file->( $cache_file ) || return( '' );
2085 return( $tbl );
2086 }
2087 else
2088 {
2089 return( $self->error( "I do not understand the value provided for the 'table' option -> ", $self->_str_val( $table ) ) );
2090 }
2091 }
2092  
2093 sub _cache_this
2094 {
2095 my $self = shift( @_ );
2096 # When this method is accessed by method from package DB::Object::Statement, they CAN NOT
2097 # implicitly pass the statement string or they would risk to modify the previous stored
2098 # query object they represent.
2099 # For instance:
2100 # $obj->select->join( 'some_table', { 'parameter', 'list' } )->fetchrow_hashref()
2101 # here the first query is prepared and cached and its resulting object is passed on to join
2102 # here join will rebuild the query, but will search first if there was one already cached
2103 # if join passes implictly the statement string, this means it will modify the cached query select()
2104 # has just previously stored... This is why method such as join must pass explicitly the query string
2105 my $q = shift( @_ );
2106 my $query = ( ref( $q ) && $q->isa( 'DB::Object::Query' ) ) ? $q->as_string : $q;
2107 my $dbo = $self->{dbo} || $self->{database_object} || $self;
2108 my $base_class = $self->base_class;
2109 my $cache = $dbo->{cache};
2110 my $bind = $dbo->{bind};
2111 my $cache_dir = $dbo->cache_dir // $self->new_tempdir;
2112 my $cache_query = $dbo->cache_query;
2113 my $cache_size = $dbo->cache_size // 0;
2114 my $serialiser = $dbo->serialiser || $DB::Object::SERIALISER || 'Storable';
2115  
2116 my $use_file_cache = ( defined( $cache_query ) && $cache_query eq 'file' ) ? 1 : 0;
2117  
2118 my( $repo, $sth, $cache_file, $checksum, $cache_key );
2119 my $cached_sth = '';
2120 my $host = $dbo->host;
2121 my $database = $dbo->database;
2122 my $table = ( ref( $q ) && $dbo->_is_a( $q => "${base_class}::Query" ) && $q->table_object ) ? $q->table_object->name : '';
2123  
2124 # Compute cache_file (and cache key) early when caching is enabled and cache_dir exists.
2125 # Even if cache_query is "file", we also want a small hot cache in memory.
2126 if( $cache )
2127 {
2128 local $@;
2129 if( $dbo->_load_class( 'Crypt::Digest::MD5' ) )
2130 {
2131 $checksum = eval
2132 {
2133 return( Crypt::Digest::MD5::md5_hex( $query ) );
2134 };
2135 }
2136  
2137 if( !defined( $checksum ) && $dbo->_load_class( 'Digest::MD5' ) )
2138 {
2139 $checksum = eval
2140 {
2141 return( Digest::MD5::md5_hex( $query ) );
2142 };
2143 }
2144  
2145 if( !defined( $checksum ) )
2146 {
2147 return( $self->error( "Caching query object is requested, but I could not find either Crypt::Digest::MD5 or Digest::MD5" ) );
2148 }
2149  
2150 my $file = $self->_get_cache_filepath(
2151 cache_dir => $cache_dir,
2152 extension => 'bin',
2153 name => $checksum,
2154 host => $host,
2155 database => $database,
2156 ( $table ? ( table => $table ) : () ),
2157 prefix => 'query',
2158 ) || return( $self->pass_error );
2159 if( $cache_dir )
2160 {
2161 $cache_file = $file;
2162 }
2163 # User requested identifier: basename of cache_file
2164 $cache_key = $cache_file->basename( '.bin' );
2165 }
2166  
2167 # Instead of storing statement object in an hash which would mean they would ALL be serialised and deserialised EVRY TIME, we store them by their unique index key, and access them DIRECTLY
2168 my $lock;
2169 if( $cache_key )
2170 {
2171 $repo = Module::Generic::Global->new( queries_cache => $base_class,
2172 key => $cache_key,
2173 max_size => $cache_size,
2174 ) || return( $dbo->pass_error( Module::Generic::Global->error ) );
2175 $lock = $repo->lock;
2176 $cached_sth = $repo->get;
2177 # Nothing, so we remove that repo. We do not leave it. This saves memory, although not much.
2178 $repo->remove if( !defined( $cached_sth ) );
2179 # The lock gets removed automatically when it gets out of scope, so we store it in $lock
2180 $repo->unlock;
2181 }
2182  
2183 # If found in-memory cache, we revive it
2184 if( $cached_sth )
2185 {
2186 # Thanks to Module::Generic::Global, this is an thawed statement object.
2187 # We just need to attach it to our current database object
2188 $sth = $cached_sth;
2189 if( !$sth->attach( $dbo ) )
2190 {
2191 $repo->unlock if( $repo );
2192 return( $self->pass_error( $sth->error ) );
2193 }
2194  
2195 my $prepare_options = {};
2196 if( $q && $self->_is_a( $q, "${base_class}::Query" ) )
2197 {
2198 $prepare_options = $q->prepare_options->as_hash;
2199 }
2200  
2201  
2202 local $@;
2203 my $sth_dbi = eval
2204 {
2205 local( $SIG{__DIE__} ) = sub{ };
2206 local( $SIG{__WARN__} ) = sub{ };
2207 $dbo->{dbh}->prepare_cached( $query, ( scalar( keys( %$prepare_options ) ) ? $prepare_options : () ) );
2208 };
2209  
2210 if( $@ )
2211 {
2212 $repo->unlock if( $repo );
2213 return( $self->error( "Error preparing cached SQL query: $@\nQuery was:\n$query" ) );
2214 }
2215  
2216 $sth->{sth} = $sth_dbi;
2217  
2218 $repo->unlock if( $repo );
2219 }
2220  
2221 # If no in-memory was found yet, we try the file cache (explicit mode only)
2222 if( !defined( $sth ) &&
2223 $cache &&
2224 $use_file_cache &&
2225 $cache_file &&
2226 $cache_file->exists &&
2227 !$cache_file->is_empty &&
2228 $cache_file->is_file )
2229 {
2230 $sth = $self->Module::Generic::deserialise(
2231 file => $cache_file,
2232 lock => 1,
2233 serialiser => $serialiser,
2234 );
2235 if( !$sth )
2236 {
2237 $repo->unlock if( $repo );
2238 return( $self->pass_error );
2239 }
2240  
2241 if( !$sth->attach( $dbo ) )
2242 {
2243 $repo->unlock if( $repo );
2244 return( $self->pass_error( $sth->error ) );
2245 }
2246  
2247 my $prepare_options = {};
2248 if( $q && $dbo->_is_a( $q, "${base_class}::Query" ) )
2249 {
2250 $prepare_options = $q->prepare_options->as_hash;
2251 }
2252  
2253  
2254 local $@;
2255 my $sth_dbi = eval
2256 {
2257 local( $SIG{__DIE__} ) = sub{ };
2258 local( $SIG{__WARN__} ) = sub{ };
2259 $dbo->{dbh}->prepare_cached( $query, ( scalar( keys( %$prepare_options ) ) ? $prepare_options : () ) );
2260 };
2261  
2262 if( $@ )
2263 {
2264 $repo->unlock if( $repo );
2265 return( $self->error( "Error preparing cached SQL query: $@\nQuery was:\n$query" ) );
2266 }
2267  
2268 $sth->{sth} = $sth_dbi;
2269 $repo->unlock if( $repo );
2270 }
2271  
2272 # The statement is not cached anywhere, so we prepare it now
2273 if( !defined( $sth ) )
2274 {
2275 my $prepare_options = {};
2276 if( $q && $self->_is_a( $q, "${base_class}::Query" ) )
2277 {
2278 $prepare_options = $q->prepare_options->as_hash;
2279 }
2280  
2281 if( !( $sth = $dbo->prepare( $query, ( scalar( keys( %$prepare_options ) ) ? $prepare_options : () ) ) ) )
2282 {
2283 $repo->unlock if( $repo );
2284 return( $self->pass_error( $dbo->error ) );
2285 }
2286  
2287 # File cache (explicit mode only)
2288 if( $cache && $use_file_cache && $cache_file )
2289 {
2290 if( !$dbo->Module::Generic::serialise( $sth,
2291 file => $cache_file,
2292 lock => 1,
2293 serialiser => $serialiser,
2294 ) )
2295 {
2296 $repo->unlock if( $repo );
2297 return( $self->pass_error( $dbo->error ) );
2298 }
2299 }
2300 # If caching is off, but the query is a binded parameters' one,
2301 # make the current object hold the statement object
2302 elsif( $bind )
2303 {
2304 $self->{sth} = $sth;
2305 }
2306 $repo->unlock if( $repo );
2307 }
2308 else
2309 {
2310 $repo->unlock if( $repo );
2311 }
2312  
2313 # Ensure we unlock even if sth came from mem cache path where we unlocked earlier
2314 $repo->unlock if( $repo );
2315  
2316 # Attach query object to statement (this can be dangerous if the statement is long-lived;
2317 # keep your query object small / reset/dirty it aggressively)
2318 $sth->query_object( $q ) if( $dbo->_is_a( $q, "${base_class}::Query" ) );
2319 $sth->table_object( $self ) if( $self->isa( "${base_class}::Tables" ) );
2320  
2321 # Caching the query as a constant
2322 if( $q && $dbo->_is_object( $q ) && $q->isa( "${base_class}::Query" ) )
2323 {
2324 my $constant = $q->constant;
2325 if( $constant && scalar( keys( %$constant ) ) )
2326 {
2327 foreach my $k (qw( pack file line ))
2328 {
2329 return( $self->error( "Could not find the parameter \"$k\" in the constant query hash reference." ) ) if( !$constant->{ $k } );
2330 }
2331  
2332 # We temporarily not store the query object, and see if this affects positively the memory consumption.
2333 # $constant->{query_object} = $q;
2334 # $dbo->constant_queries_cache_set( $constant );
2335 }
2336 }
2337  
2338 return( $sth );
2339 }
2340  
2341 sub _check_connect_param
2342 {
2343 my $self = shift( @_ );
2344 my $param = shift( @_ );
2345 my $valid = $self->_connection_parameters( $param );
2346 my $opts = $self->_connection_options( $param );
2347 foreach my $k ( keys( %$param ) )
2348 {
2349 # If it is not in the list and it does not start with an upper case; those are like RaiseError, AutoCommit, etc
2350 if( CORE::length( $param->{ $k } ) && !grep( /^$k$/, @$valid ) && !CORE::exists( $opts->{ $k } ) )
2351 {
2352 return( $self->error( "Invalid parameter '$k'." ) );
2353 }
2354 }
2355 my @opts_to_remove = keys( %$opts );
2356 CORE::delete( @$param{ @opts_to_remove } ) if( scalar( @opts_to_remove ) );
2357 $param->{opt} = $opts;
2358 $param->{database} = CORE::delete( $param->{db} ) if( !length( $param->{database} ) && $param->{db} );
2359 return( $param );
2360 }
2361  
2362 sub _check_default_option
2363 {
2364 my $self = shift( @_ );
2365 my $opts = $self->_get_args_as_hash( @_ );
2366 # return( $self->error( "Provided option is not a hash reference." ) ) if( !$self->_is_hash( $opts ) );
2367 # This method should be superseded by an inherited class
2368 return( $opts );
2369 }
2370  
2371 # Simplistic clone by design. We do not want a recursive clone like Clone::clone()
2372 sub _clone
2373 {
2374 my( $self, $this ) = @_;
2375 if( $self->_is_array( $this ) )
2376 {
2377 my @clone = @$this;
2378 return( \@clone );
2379 }
2380 elsif( ref( $this ) eq 'HASH' )
2381 {
2382 my @keys = keys( %$this );
2383 my $clone = {};
2384 @$clone{ @keys } = @$this{ @keys };
2385 return( $clone );
2386 }
2387 else
2388 {
2389 return( $self->error( "Unsupported data type to clone. This method only support hash or array reference." ) );
2390 }
2391 }
2392  
2393 sub _connection_options
2394 {
2395 my $self = shift( @_ );
2396 my $param = shift( @_ );
2397 my @dbi_opts = grep( /^[A-Z][a-zA-Z]+/, keys( %$param ) );
2398 my $opt = {};
2399 $opt = CORE::delete( $param->{opt} ) if( $param->{opt} && $self->_is_hash( $param->{opt} => 'strict' ) );
2400 @$opt{ @dbi_opts } = @$param{ @dbi_opts };
2401 return( $opt );
2402 }
2403  
2404 sub _connection_parameters
2405 {
2406 my $self = shift( @_ );
2407 my $param = shift( @_ );
2408 return( [qw(
2409 db login passwd host port driver database server opt uri debug cache_connections
2410 cache_dir cache_table connect_via serialiser unknown_field
2411 )] );
2412 }
2413  
2414 sub _connection_params2hash
2415 {
2416 my $self = shift( @_ );
2417 my $argv = [@_];
2418 my $param = {};
2419 if( !( @_ % 2 ) )
2420 {
2421 $param = { @_ };
2422 }
2423 elsif( @_ == 1 && ( ref( $_[0] ) // '' ) eq 'HASH' )
2424 {
2425 $param = shift( @_ );
2426 }
2427 else
2428 {
2429 my @keys = qw( database login passwd host driver schema );
2430 # Only add in the $param hash the keys value we were given, so we don't create keys entry when not needed
2431 for( my $i = 0; $i < scalar( @_ ); $i++ )
2432 {
2433 $param->{ $keys[ $i ] } = $_[ $i ];
2434 }
2435 }
2436  
2437 my $equi =
2438 {
2439 database => 'DB_NAME',
2440 login => 'DB_LOGIN',
2441 passwd => 'DB_PASSWD',
2442 host => 'DB_HOST',
2443 port => 'DB_PORT',
2444 driver => 'DB_DRIVER',
2445 schema => 'DB_SCHEMA',
2446 };
2447 foreach my $prop ( keys( %$equi ) )
2448 {
2449 $param->{ $prop } = $ENV{ $equi->{ $prop } } if( $ENV{ $equi->{ $prop } } && !length( $param->{ $prop } ) );
2450 }
2451  
2452 # A simple json file
2453 # An URI could be http://localhost:5432?database=somedb etc...
2454 # or it could also be file:/foo/bar?opt={"RaiseError":true}
2455 if( $param->{uri} || $ENV{DB_CON_URI} )
2456 {
2457 my $uri;
2458 eval
2459 {
2460 require URI;
2461 $uri = URI->new( $param->{uri} || $ENV{DB_CON_URI} );
2462 };
2463 if( !$@ && $uri )
2464 {
2465 # Make sure our parameter is a valid URI object
2466 $param->{uri} = $uri;
2467 if( $uri->can( 'port' ) )
2468 {
2469 $param->{host} = $uri->host;
2470 $param->{port} = $uri->port if( $uri->port );
2471 }
2472 # file:/
2473 elsif( length( $uri->path ) )
2474 {
2475 $param->{database} = ( $uri->path_segments )[-1];
2476 }
2477 my( %q ) = $uri->query_form;
2478 $param->{host} = $q{host} if( $q{host} );
2479 $param->{port} = $q{port} if( $q{port} );
2480 $param->{database} = $q{database} if( $q{database} );
2481 $param->{schema} = $q{schema} if( $q{schema} );
2482 $param->{user} = $q{user} if( $q{user} );
2483 $param->{login} = $q{login} if( $q{login} );
2484 $param->{password} = $q{password} if( $q{password} );
2485 $param->{opt} = $q{opt} if( $q{opt} );
2486 $param->{login} = CORE::delete( $param->{user} ) if( !$param->{login} && $param->{user} );
2487 if( $q{opt} )
2488 {
2489 my $jdata = {};
2490 eval
2491 {
2492 require JSON;
2493 if( defined( *{ "JSON::" } ) )
2494 {
2495 my $j = JSON->new->allow_nonref;
2496 $jdata = $j->decode( $q{opt} );
2497 }
2498 };
2499 if( $@ )
2500 {
2501 warn( "Found the database connection opt parameter provided in the connection uri \"$uri\", but could not decode its json value: $@\n" );
2502 }
2503 $param->{opt} = $jdata if( scalar( keys( %$jdata ) ) );
2504 }
2505 }
2506 }
2507  
2508 if( $param->{conf_file} || $param->{config_file} || $ENV{DB_CON_FILE} )
2509 {
2510 my $db_con_file = $self->new_file( CORE::delete( $param->{conf_file} ) || CORE::delete( $param->{config_file} ) || $ENV{DB_CON_FILE} );
2511 my $db_con_file_ok = 0;
2512 if( !$db_con_file->exists )
2513 {
2514 warn( "Database connection parameter file \"$db_con_file\" was provided but does not exist.\n" );
2515 }
2516 elsif( $db_con_file->is_empty )
2517 {
2518 warn( "Database connection parameter file \"$db_con_file\" was provided but the file is empty.\n" );
2519 }
2520 elsif( !$db_con_file->can_read )
2521 {
2522 warn( "Database connection parameter file \"$db_con_file\" was provided but the file lacks privileges to be read.\n" );
2523 }
2524 else
2525 {
2526 $db_con_file_ok++;
2527 }
2528  
2529 my $json = $db_con_file->load_json;
2530 # If the configuration file has some issue, we warn about it, but we move on.
2531 if( !$json )
2532 {
2533 warn( "Database connection parameter file \"$db_con_file\" was provided, but I encountered the following error while trying to read its json data: ", $db_con_file->error );
2534 }
2535 $json = {} if( !$self->_is_hash( $json => 'strict' ) );
2536 my $ref = {};
2537 if( exists( $json->{databases} ) )
2538 {
2539 return( $self->error( "Found a property 'databases' in the connections configuration file \"$db_con_file\". I was expecting this property to be an array reference and instead I found this: '$json->{databases}'" ) ) if( !$self->_is_array( $json->{databases} ) );
2540 # When called from sub classes, this is set
2541 my $driver = $self->driver;
2542 # We take the first one matching our driver if any, or else we just take the first one
2543 foreach my $this ( @{$json->{databases}} )
2544 {
2545 if( !$param->{database} && ( !$driver || $this->{driver} eq $driver ) )
2546 {
2547 $ref = $this;
2548 last;
2549 }
2550 elsif( $param->{database} && $this->{database} && $this->{database} eq $param->{database} &&
2551 ( !$param->{host} || ( $this->{host} && $param->{host} eq $this->{host} ) ) &&
2552 ( !$param->{port} || ( $this->{port} && $param->{port} eq $this->{port} ) ) &&
2553 ( !$param->{login} || ( $this->{login} && $param->{login} eq $this->{login} ) ) )
2554 {
2555 $ref = $this;
2556 last;
2557 }
2558 }
2559 }
2560 else
2561 {
2562 $ref = $json;
2563 }
2564  
2565 if( scalar( keys( %$ref ) ) )
2566 {
2567 foreach my $k ( qw( database login passwd host port driver schema opt ) )
2568 {
2569 $param->{ $k } = $ref->{ $k } if( !length( $param->{ $k } ) && length( $ref->{ $k } ) );
2570 }
2571 }
2572  
2573 # Grab any cache_* configuration property in the file
2574 foreach my $prop ( grep{ /^(cache_|cache\z|use_cache\z)/ } keys( %$json ) )
2575 {
2576 $param->{ $prop } = $json->{ $prop } if( CORE::exists( $json->{ $prop } ) );
2577 }
2578 if( CORE::exists( $json->{serialiser} ) )
2579 {
2580 $param->{serialiser} = $json->{serialiser};
2581 }
2582 elsif( CORE::exists( $json->{serializer} ) )
2583 {
2584 $param->{serialiser} = $json->{serializer};
2585 }
2586 }
2587  
2588 if( CORE::exists( $param->{host} ) && index( $param->{host}, ':' ) != -1 )
2589 {
2590 @$param{ qw( host port ) } = split( /:/, $param->{host}, 2 );
2591 }
2592  
2593 if( !$param->{opt} && $ENV{DB_OPT} )
2594 {
2595 my $jdata = {};
2596 eval
2597 {
2598 require JSON;
2599 if( defined( *{ "JSON::" } ) )
2600 {
2601 my $j = JSON->new->allow_nonref;
2602 $jdata = $j->decode( $ENV{DB_OPT} );
2603 }
2604 };
2605 if( $@ )
2606 {
2607 warn( "Found the database connection opt parameter provided in the envionment variable DB_OPT, but could not decode its json value: $@\n" );
2608 }
2609 $param->{opt} = $jdata if( scalar( keys( %$jdata ) ) );
2610 }
2611 return( $param );
2612 }
2613  
2614 sub _connection_params2hash_driver
2615 {
2616 my $self = shift( @_ );
2617 my $opts = $self->_get_args_as_hash( @_ );
2618 return( $opts );
2619 }
2620  
2621 sub _clean_statement
2622 {
2623 my $self = shift( @_ );
2624 my $data = shift( @_ );
2625 my $query = ref( $data ) ? $data : \$data;
2626 $$query = CORE::join( "\n", map{ s/^\s+|\s+$//gs; $_ } split( /\n/, $$query ) );
2627 return( $$query ) if( !ref( $data ) );
2628 }
2629  
2630 sub _dbi_connect
2631 {
2632 my $self = shift( @_ );
2633 my $dbh;
2634 my $dsn = $self->_dsn;
2635 # print( STDERR ref( $self ) . "::_dbi_connect() Options are: ", $self->dumper( $self->{opt} ), "\n" );
2636 my $connect_via = $self->connect_via;
2637 # See: <https://metacpan.org/pod/DBI#Timeout>
2638 # signals to mask in the handler
2639 my $mask = POSIX::SigSet->new( POSIX::SIGALRM );
2640 my $action = POSIX::SigAction->new(
2641 # the handler code ref
2642 sub{ die( "connect timeout\n" ) },
2643 $mask,
2644 # not using (perl 5.8.2 and later) 'safe' switch or sa_flags
2645 );
2646 my $oldaction = POSIX::SigAction->new();
2647 POSIX::sigaction( POSIX::SIGALRM, $action, $oldaction );
2648 my $failed;
2649 local $@;
2650 eval
2651 {
2652 eval
2653 {
2654 # seconds before time out
2655 alarm(5);
2656 if( $self->{cache_connections} )
2657 {
2658 $dbh = DBI->connect_cached(
2659 $dsn,
2660 $self->{login},
2661 $self->{passwd},
2662 $self->{opt},
2663 undef(),
2664 ( $connect_via ? $connect_via : () ),
2665 );
2666 }
2667 else
2668 {
2669 $dbh = DBI->connect(
2670 $dsn,
2671 $self->{login},
2672 $self->{passwd},
2673 $self->{opt},
2674 undef(),
2675 ( $connect_via ? $connect_via : () ),
2676 );
2677 }
2678 1;
2679 } or $failed = 1;
2680 # cancel alarm (if connect worked fast)
2681 alarm(0);
2682 # connect died
2683 die( "$@\n" ) if( $failed );
2684 1;
2685 } or $failed = 1;
2686 # restore original signal handler
2687 POSIX::sigaction( POSIX::SIGALRM, $oldaction );
2688 if( defined( $failed ) && $failed )
2689 {
2690 if( defined( $@ ) && $@ =~ /^connect timeout/ )
2691 {
2692 return( $self->error( "Connection timed out for dsn '", ( $dsn // 'undef' ), " and login '", ( $self->{login} // 'undef' ), "'" ) );
2693 }
2694 else
2695 {
2696 return( $self->error( "Error connecting with dsn '", ( $dsn // 'undef' ), " and login '", ( $self->{login} // 'undef' ), "': $@" ) );
2697 }
2698 }
2699  
2700 return( $self->error( $DBI::errstr ) ) if( !$dbh );
2701 return( $dbh );
2702 }
2703  
2704 sub _decode_json
2705 {
2706 my $self = shift( @_ );
2707 my $json = shift( @_ );
2708 return if( !CORE::length( $json ) );
2709 my $j = JSON->new->allow_nonref;
2710 my $hash = eval
2711 {
2712 $j->decode( $json );
2713 };
2714 return if( $@ );
2715 return( $hash );
2716 }
2717  
2718 sub _dsn
2719 {
2720 my $self = shift( @_ );
2721 my $class = ref( $self ) || $self;
2722 die( "Method _dsn is not implemented in class $class\n" );
2723 }
2724  
2725 sub _encode_json
2726 {
2727 my $self = shift( @_ );
2728 return if( !scalar( @_ ) || ( scalar( @_ ) == 1 && !defined( $_[0] ) ) );
2729 my $this = shift( @_ );
2730 return( $self->error( "Value provided is not a hash reference. I was expecting a hash reference to encode data into json." ) ) if( !$self->_is_hash( $this => 'strict' ) );
2731 my $j = JSON->new;
2732 my $json = eval
2733 {
2734 $j->encode( $this );
2735 };
2736 return( $self->error( "An error occurred while trying to encode hash reference provided: $@" ) ) if( $@ );
2737 return( $json );
2738 }
2739  
2740 sub _get_cache_filepath
2741 {
2742 my $self = shift( @_ );
2743 my $opts = $self->_get_args_as_hash( @_ );
2744 my $name = $opts->{name};
2745 my $ext = $opts->{extension} // 'bin';
2746 if( $name !~ /^[\w\-]+$/ )
2747 {
2748 return( $self->error( "The name for this cache file contains illegal characters '$name'. Only alphabetical, numeric characters, underscore, and dash are allowed" ) );
2749 }
2750 my $host = $opts->{host} || $self->host;
2751 my $database = $opts->{database} || $self->database;
2752 # May not be specified, and thus empty.
2753 my $table = $opts->{table};
2754 if( defined( $host ) && !CORE::length( $host // '' ) )
2755 {
2756 return( $self->error( "A host name was provided, but is undefined or empty." ) );
2757 }
2758 elsif( !defined( $database ) || !CORE::length( $database // '' ) )
2759 {
2760 return( $self->error( "The database name is undefined or empty." ) );
2761 }
2762 elsif( $database !~ /^\w+$/ )
2763 {
2764 return( $self->error( "The database name '$database' contains illegal characters." ) );
2765 }
2766 elsif( $table && $table !~ /^\w+[\w\-\.]*$/ )
2767 {
2768 return( $self->error( "The table name '$table' contains illegal characters." ) );
2769 }
2770  
2771 $host //= '_unknown_';
2772 # Normalise host for filename usage: keep only [A-Za-z0-9_.-], percent-encode everything else.
2773 # This avoids collisions that would happen with s/\W//g and supports IPv6, ports, etc.
2774 my $host_key = "$host";
2775 $host_key =~ s/([^A-Za-z0-9_.-])/sprintf( '%%%02X', ord( $1 ) )/ge;
2776  
2777 my $cache_dir = $opts->{cache_dir} || $self->cache_dir ||
2778 return( $self->error( "No cache directory was provided." ) );
2779 $cache_dir = $self->new_file( $cache_dir ) ||
2780 return( $self->pass_error );
2781 # Ensure cache directory exists
2782 if( !$cache_dir->exists )
2783 {
2784 $cache_dir->mkpath || return( $self->pass_error( $cache_dir->error ) );
2785 }
2786 elsif( !$cache_dir->is_dir )
2787 {
2788 return( $self->error( "Cache directory path '$cache_dir' exists but is not a directory." ) );
2789 }
2790 my @parts = ( ( $opts->{prefix} ? $opts->{prefix} : () ), $host_key, $database );
2791 push( @parts, $table ) if( $table );
2792 push( @parts, "${name}.${ext}" );
2793 my $cache_file = $cache_dir->child( join( '-', @parts ) ) ||
2794 return( $self->pass_error( $cache_dir->error ) );
2795 return( $cache_file );
2796 }
2797  
2798 sub _make_sth
2799 {
2800 my $self = shift( @_ );
2801 my $pkg = shift( @_ );
2802 my $data = shift( @_ ) || {};
2803 my $base_class = $self->base_class;
2804 $self->_load_class( $pkg ) || return( $self->pass_error );
2805 # map{ $data->{ $_ } = $self->{ $_ } }
2806 # qw(
2807 # dbh drh server login passwd database driver
2808 # table debug bind cache params selected_fields
2809 # local where limit group_by order_by reverse from_table left_join
2810 # tie tie_order
2811 # );
2812 foreach my $prop ( qw( table debug bind cache params from_table left_join ) )
2813 {
2814 $data->{ $prop } = $self->{ $prop };
2815 }
2816 $data->{dbh} = $self->{dbh};
2817 $data->{dbo} = $self->{dbo} ? $self->{dbo} : ref( $self ) eq $self->base_class ? $self : '';
2818 # $data->{ 'binded' } = $self->{ 'binded' } if( $self->{ 'binded' } && ref( $self ) ne $base_class );
2819 # In any case suppress the binded parameter from our parent object to avoid polluting the next queries
2820 # If needed, the binded parameter will be rebuilt using the data stored in 'where', 'group', 'order' and 'limit'
2821 # CORE::delete( $self->{ 'binded' } );
2822 # Binded parameters are now either in the DB::Object::Query package or one of its descendant OR passed as arguments to execute
2823 $data->{errstr} = '';
2824 CORE::delete( $data->{executed} );
2825 $data->{query_time} = time();
2826 $data->{selected_fields} = '' if( !exists( $data->{selected_fields} ) );
2827 $data->{table_object} = $self if( $self->_is_a( $self => "${base_class}::Tables" ) );
2828 my $this = bless( $data, $pkg );
2829 $this->debug( $self->debug );
2830 return( $this );
2831 }
2832  
2833 sub _operator_object_create
2834 {
2835 my $self = shift( @_ );
2836 my $class = shift( @_ ) || return( $self->error( "No operator class was provided." ) );
2837 my $q = $self->_reset_query;
2838 my $args = ( scalar( @_ ) == 1 && ref( $_[0] ) eq 'ARRAY' ) ? [ @{$_[0]} ] : [ @_ ];
2839 return( $class->new(
2840 debug => $self->debug,
2841 query_object => $q,
2842 value => $args,
2843 ) );
2844 }
2845  
2846 sub _param2hash
2847 {
2848 my $self = shift( @_ );
2849 my $opts = {};
2850 if( scalar( @_ ) )
2851 {
2852 if( $self->_is_hash( $_[0] => 'strict' ) )
2853 {
2854 $opts = shift( @_ );
2855 }
2856 elsif( !( scalar( @_ ) % 2 ) )
2857 {
2858 $opts = { @_ };
2859 }
2860 else
2861 {
2862 return( $self->error( "Uneven number of parameters. I was expecting a hash or a hash reference." ) );
2863 }
2864 }
2865 return( $opts );
2866 }
2867  
2868 sub _placeholder_regexp { return( $PLACEHOLDER_REGEXP ) }
2869  
2870 # NOTE: _query_object_add needs to reside in DB::Object (called indirectly by no_bind)
2871 sub _query_object_add
2872 {
2873 my $self = shift( @_ );
2874 my $obj = shift( @_ ) || return( $self->error( "No query object was provided" ) );
2875 my $base = $self->base_class;
2876 return( $self->error( "Object provided is not a query object class" ) ) if( ref( $obj ) !~ /^${base}\::Query$/ );
2877 $self->query_object( $obj );
2878 return( $obj );
2879 }
2880  
2881 # NOTE: _query_object_create needs to reside in DB::Object (called indirectly by no_bind)
2882 sub _query_object_create
2883 {
2884 my $self = shift( @_ );
2885 my $base = $self->base_class;
2886 my $query_class = "${base}::Query";
2887 $self->_load_class( $query_class ) ||
2888 return( $self->error( "Unable to load Query builder module $query_class: ", $self->error->message ) );
2889 my $o = $query_class->new;
2890 $o->debug( $self->debug );
2891 $o->enhance( $self->{enhance} ) if( CORE::length( $self->{enhance} ) );
2892 if( $self->isa( 'DB::Object::Tables' ) )
2893 {
2894 $o->table_object( $self ) || return( $self->pass_error( $o->error ) );
2895 # Weaken the back-reference from the Query object to its owning Table to break
2896 # the circular reference cycle (Table -> query_object -> Query -> table_object -> Table)
2897 # that prevents Perl's garbage collector from reclaiming old Query objects.
2898 weaken( $o->{table_object} );
2899 $o->database_object( $self->database_object ) || return( $self->pass_error( $o->error ) );
2900 # Also weaken the database_object reference - the dbo is a long-lived singleton
2901 # and does not own Query objects, so a weak reference is safe here.
2902 weaken( $o->{database_object} );
2903 # Set the table alias if any has been set
2904 if( my $table_alias = $self->as )
2905 {
2906 $o->table_alias( $table_alias ) if( defined( $table_alias ) );
2907 }
2908 }
2909 elsif( $self->isa( 'DB::Object' ) )
2910 {
2911 $o->database_object( $self ) || return( $self->pass_error( $o->error ) );
2912 }
2913 return( $o );
2914 }
2915  
2916 # NOTE: _query_object_current needs to reside in DB::Object (called indirectly by no_bind)
2917 sub _query_object_current { return( shift->{query_object} ); }
2918  
2919 # NOTE: _query_object_get_or_create needs to reside in DB::Object (called indirectly by no_bind)
2920 # If the stack is empty, we create an object, add it and resend it
2921 sub _query_object_get_or_create
2922 {
2923 my $self = shift( @_ );
2924 my $obj = $self->query_object;
2925 if( $obj && $obj->dirty )
2926 {
2927 $self->_query_object_remove( $obj );
2928 undef( $obj );
2929 }
2930 if( !$obj )
2931 {
2932 $obj = $self->_query_object_create || return( $self->pass_error );
2933 $self->query_object( $obj );
2934 }
2935 return( $obj );
2936 }
2937  
2938 # NOTE: _query_object_remove needs to reside in DB::Object (called indirectly by no_bind)
2939 sub _query_object_remove
2940 {
2941 my $self = shift( @_ );
2942 my $obj = shift( @_ ) || return( $self->error( "No query object was provided" ) );
2943 my $base = $self->base_class;
2944 # return( $self->error( "Object provided is not a query object class" ) ) if( ref( $obj ) !~ /^${base}\::Query$/ );
2945 return( $self->error( "Object provided is not a query object class" ) ) if( !$obj->isa( "DB::Object::Query" ) );
2946 $self->query_object( undef );
2947 return( $obj );
2948 }
2949  
2950 # NOTE: A query object can be owned by a table object, but also by a database object, such as when instantiating operators like ALL, AND, OR
2951 sub _reset_query
2952 {
2953 my $self = shift( @_ );
2954  
2955 if( !$self->{query_reset} )
2956 {
2957 $self->{query_reset} = 1;
2958 $self->{enhance} = 1;
2959  
2960 my $obj = $self->query_object;
2961  
2962 # If current query object is dirty, detach it right away.
2963 if( $obj && $obj->dirty )
2964 {
2965 $self->_query_object_remove( $obj );
2966 undef( $obj );
2967 }
2968  
2969  
2970 # Capture join tables BEFORE we detach the query object
2971 my $join_tables;
2972 if( $obj )
2973 {
2974 $join_tables = $obj->join_tables;
2975 }
2976  
2977 $self->_query_object_remove( $obj ) if( $obj );
2978  
2979 if( $join_tables && $join_tables->length > 0 )
2980 {
2981 $join_tables->foreach(sub{
2982 my $tbl = shift( @_ );
2983  
2984 return if( $tbl->name eq $self->name );
2985  
2986 my $this_query_object = $tbl->query_object;
2987 $tbl->_query_object_remove( $this_query_object ) if( $this_query_object );
2988  
2989 $tbl->use_bind(0) unless( $tbl->use_bind > 1 );
2990 $tbl->use_cache(0) unless( $tbl->use_cache > 1 );
2991  
2992 # Important: do NOT force query_reset to 1 here.
2993 # We want the next use to rebuild a fresh query object lazily.
2994 CORE::delete( $tbl->{query_reset} );
2995  
2996 return;
2997 });
2998 }
2999  
3000 $self->{bind} = 0 unless( defined( $self->{bind} ) && $self->{bind} > 1 );
3001 $self->{cache} = 0 unless( defined( $self->{cache} ) && $self->{cache} > 1 );
3002  
3003 return( $self->_query_object_get_or_create );
3004 }
3005  
3006 return( $self->_query_object_current );
3007 }
3008  
3009 # NOTE: AUTOLOAD
3010 AUTOLOAD
3011 {
3012 my $self;
3013 $self = shift( @_ ) if( blessed( $_[ 0 ] ) || index( $_[0], '::' ) != -1 );
3014 my( $class, $meth );
3015 if( $self )
3016 {
3017 $class = ref( $self ) || $self;
3018 }
3019 $meth = $AUTOLOAD;
3020 if( CORE::index( $meth, '::' ) != -1 )
3021 {
3022 my $idx = rindex( $meth, '::' );
3023 $class = substr( $meth, 0, $idx );
3024 $meth = substr( $meth, $idx + 2 );
3025 }
3026 my @supported_class = DB::Object->supported_class;
3027 push( @supported_class, 'DB::Object' );
3028 my $ok_classes = join( '|', @supported_class );
3029 my $base_class = ( $class =~ /^($ok_classes)/ )[0];
3030  
3031 # Is it a table object that is being requested?
3032 # if( $self && scalar( grep{ /^$meth$/ } @$tables ) )
3033 # Getting table object take NO argument.
3034 # If the user wants to access a method, and somehow the table name is identical to one of our methods,
3035 # it is likely it will take an argument
3036 if( $class eq $base_class && !scalar( @_ ) && $self->table_exists( $meth ) )
3037 {
3038 return( $self->table( $meth ) );
3039 }
3040 elsif( $self && $self->can( $meth ) && defined( &{ "$class\::$meth" } ) )
3041 {
3042 return( $self->$meth( @_ ) );
3043 }
3044 # For imported subs
3045 elsif( defined( &$meth ) )
3046 {
3047 no strict 'refs';
3048 *{"${class}\::${meth}"} = \&$meth;
3049 unshift( @_, $self ) if( $self );
3050 return( &$meth( @_ ) );
3051 }
3052 # Taken from AutoLoader.pm
3053 elsif( $class =~ /^(?:$ok_classes)$/ )
3054 {
3055 my $filename;
3056 my $pkg = $class;
3057 $pkg =~ s/::/\//g;
3058 if( defined( $filename = $INC{ "$pkg.pm" } ) )
3059 {
3060 $filename =~ s%^(.*)$pkg\.pm\z%$1auto/${pkg}/${meth}.al%s;
3061 if( -r( $filename ) )
3062 {
3063 unless( $filename =~ m|^/|s )
3064 {
3065 $filename = "./$filename";
3066 }
3067 }
3068 else
3069 {
3070 $filename = undef();
3071 }
3072 }
3073 if( !defined( $filename ) )
3074 {
3075 $filename = "auto/${meth}.al";
3076 $filename =~ s/::/\//g;
3077 }
3078 my $save = $@;
3079 eval
3080 {
3081 local $SIG{__DIE__} = sub{ };
3082 local $SIG{__WARN__} = sub{ };
3083 require $filename;
3084 };
3085 if( $@ )
3086 {
3087 if( substr( $AUTOLOAD, -9 ) eq '::DESTROY' )
3088 {
3089 no strict 'refs';
3090 *$meth = sub {};
3091 }
3092 else
3093 {
3094 # The load might just have failed because the filename was too
3095 # long for some old SVR3 systems which treat long names as errors.
3096 # If we can succesfully truncate a long name then it's worth a go.
3097 # There is a slight risk that we could pick up the wrong file here
3098 # but autosplit should have warned about that when splitting.
3099 if( $filename =~ s/(\w{12,})\.al$/substr( $1, 0, 11 ) . ".al"/e )
3100 {
3101 eval
3102 {
3103 local $SIG{__DIE__} = sub{ };
3104 local $SIG{__WARN__} = sub{ };
3105 require $filename
3106 };
3107 }
3108 }
3109 }
3110 unless( $@ )
3111 {
3112 $@ = $save;
3113 unshift( @_, $self ) if( $self );
3114 goto &$meth;
3115 }
3116 $@ = $save;
3117 }
3118  
3119 if( $self && exists( $self->{sth} ) )
3120 {
3121 # e.g. $sth->pg_server_prepare => $self->{sth}->{pg_server_prepare}
3122 if( CORE::exists( $self->{sth}->{ $meth } ) )
3123 {
3124 $self->{sth}->{ $meth } = shift( @_ ) if( scalar( @_ ) );
3125 return( $self->{sth}->{ $meth } );
3126 }
3127 if( !$self->executed() )
3128 {
3129 $self->execute() || return( $self->error( $self->{sth}->errstr() ) );
3130 }
3131 # $self->_cleanup();
3132 # print( STDERR "Calling DBI method $meth with sth '$self->{sth}' arguments: '", join( "', '", @_ ), "'\n" ) if( $DEBUG );
3133 # *{ "${class}\::$meth" } = sub{ return( shift->{ 'sth' }->$meth( @_ ) ); };
3134 return( $self->{sth}->$meth( @_ ) );
3135 }
3136 # e.g. $dbh->pg_notifies
3137 elsif( $self && ( ( $self->{dbh} && $self->{dbh}->can( $meth ) ) || defined( &{ "DBI::db::" . $meth } ) ) )
3138 {
3139 return( $self->{dbh}->$meth( @_ ) );
3140 }
3141 # e.g. $dbh->pg_enable_utf8 becomes $self->{dbh}->{pg_enable_utf8]
3142 elsif( $self && $self->{dbh} && CORE::exists( $self->{dbh}->{ $meth } ) )
3143 {
3144 $self->{dbh}->{ $meth } = shift( @_ ) if( scalar( @_ ) );
3145 return( $self->{dbh}->{ $meth } );
3146 }
3147 elsif( defined( &{ "DBI::" . $meth } ) )
3148 {
3149 my $h = &{ "DBI::" . $meth }( @_ );
3150 if( defined( $h ) )
3151 {
3152 bless( $h, $class );
3153 return( $h );
3154 }
3155 else
3156 {
3157 return;
3158 }
3159 }
3160 my $what = $self ? $self : $class;
3161 return( $what->error( "${class}::AUTOLOAD: Not defined in $class and not autoloadable (last try $meth)" ) );
3162 }
3163  
3164 # NOTE: DESTROY
3165 sub DESTROY
3166 {
3167 # <https://perldoc.perl.org/perlobj#Destructors>
3168 CORE::local( $., $@, $!, $^E, $? );
3169 CORE::return if( ${^GLOBAL_PHASE} eq 'DESTRUCT' );
3170 my $self = CORE::shift( @_ );
3171 CORE::return if( !CORE::defined( $self ) );
3172 my $class = ref( $self ) || $self;
3173 if( $self->{sth} )
3174 {
3175 print( STDERR "DESTROY(): Terminating sth '$self' for query:\n$self->{query}\n" ) if( $DEBUG || $self->{debug} );
3176 $self->{sth}->finish();
3177 }
3178 elsif( $self->{dbh} && $class =~ /^AI\:\:DB(?:\:\:(?:Postgres|Mysql|SQLite))?$/ )
3179 {
3180 local( $SIG{__WARN__} ) = sub { };
3181 # $self->{ 'dbh' }->disconnect();
3182 if( $DEBUG || $self->{debug} )
3183 {
3184 my( $pack, $file, $line, $sub ) = ( caller(0) )[0, 1, 2, 3];
3185 my( $pack2, $file2, $line2, $sub2 ) = ( caller(1) ) [0, 1, 2, 3];
3186 print( STDERR "DESTROY database handle ($self) [$self->{ 'query' }]\ncalled within sub '$sub' ($sub2) from package '$pack' ($pack2) in file '$file' ($file2) at line '$line' ($line2).\n" );
3187 }
3188 $self->disconnect();
3189 }
3190 my $locks = $self->{_locks};
3191 if( $locks && $self->_is_array( $locks ) )
3192 {
3193 foreach my $name ( @$locks )
3194 {
3195 $self->unlock( $name );
3196 }
3197 }
3198  
3199 my $repo = Module::Generic::Global->new( 'available_databases' => $class, key => $class );
3200 $repo->cleanup;
3201 my $table_repo = Module::Generic::Global->new( table_cache => 'system' );
3202 $table_repo->cleanup;
3203 # NOTE: We cannot cleanup here the 'queries_cache, because we need the $cache_key used to build the key, and we do not have it at this very moment.
3204 }
3205  
3206 # NOTE: package DB::Object::Operator
3207 package DB::Object::Operator;
3208 BEGIN
3209 {
3210 use strict;
3211 use parent qw( Module::Generic );
3212 };
3213  
3214 sub init
3215 {
3216 my $self = shift( @_ );
3217 $self->{operator} = undef;
3218 $self->{query_object} = undef;
3219 $self->{value} = [];
3220 $self->{_init_strict_use_sub} = 1;
3221 $self->SUPER::init( @_ ) || return( $self->pass_error );
3222 return( $self );
3223 }
3224  
3225 sub operator { return( '' ); }
3226  
3227 sub query_object { return( shift->_set_get_object_without_init( 'query_object', 'DB::Object::Query', @_ ) ); }
3228  
3229 # sub value { return( wantarray() ? @{$_[0]->{value}} : $_[0]->{value} ); }
3230 # wantlist option instructs this method to return a list in list context instead of the default array object
3231 sub value { return( shift->_set_get_array_as_object( { field => 'value', wantlist => 1 }, @_ ) ); }
3232  
3233 # For arguments that have a query object like statements, we coy their binded_types and binded_values to our current query object.
3234 # This is used by ALL, ANY and IN
3235 sub _copy_binded_elements
3236 {
3237 my $self = shift( @_ );
3238 my $base_class = $self->base_class;
3239 if( my $qo = $self->query_object )
3240 {
3241 $self->value->foreach(sub
3242 {
3243 my $this = shift( @_ );
3244 my $q;
3245 if( $self->_is_a( $this => "${base_class}::Statement" ) &&
3246 ( $q = $this->query_object ) )
3247 {
3248 $qo->binded_types->push( $q->binded_types->list );
3249 $qo->binded_values->push( $q->binded_values->list );
3250 }
3251 });
3252 }
3253 return( $self );
3254 }
3255  
3256 # Ref:
3257 # <https://www.postgresql.org/docs/12/arrays.html#ARRAYS-SEARCHING>
3258 # NOTE: package DB::Object::ALL
3259 package DB::Object::ALL;
3260 BEGIN
3261 {
3262 use strict;
3263 use warnings;
3264 use parent -norequire, qw( DB::Object::Operator );
3265 use Scalar::Util ();
3266 use overload (
3267 '""' => 'as_string',
3268 'bool' => sub{1},
3269 '==' => sub{ &_opt_overload( @_, '==' ) },
3270 '!=' => sub{ &_opt_overload( @_, '!=' ) },
3271 fallback => 1,
3272 );
3273 };
3274  
3275 sub init
3276 {
3277 my $self = shift( @_ );
3278 $self->SUPER::init( @_ ) || return( $self->pass_error );
3279 # $self->_copy_binded_elements || return( $self->pass_error );
3280 return( $self );
3281 }
3282  
3283 sub as_string
3284 {
3285 my $self = shift( @_ );
3286 my $vals = $self->value;
3287 my @list = ();
3288 foreach my $elem ( @$vals )
3289 {
3290 next unless( defined( $elem ) );
3291 if( Scalar::Util::blessed( $elem ) &&
3292 $elem->isa( 'DB::Object::Statement' ) )
3293 {
3294 push( @list, $elem->as_string );
3295 }
3296 else
3297 {
3298 push( @list, $elem );
3299 }
3300 }
3301 local $" = ',';
3302 my $sql = "ALL (@list)";
3303 return( $sql );
3304 }
3305  
3306 sub operator { return( 'ALL' ); }
3307  
3308 sub _opt_overload
3309 {
3310 my( $self, $val, $swap, $op ) = @_;
3311 my $map =
3312 {
3313 '!=' => '!= ',
3314 '<>' => '!= ',
3315 '==' => '= ',
3316 };
3317 my $not = $map->{ $op };
3318 if( !defined( $not ) )
3319 {
3320 warn( "Unknown operator '${op}'. Falling back to '='." );
3321 $not = $map->{ '==' };
3322 }
3323 my $in = $self->as_string;
3324 my $placeholder_re = $self->query_object->database_object->_placeholder_regexp;
3325 my $lval = ( Scalar::Util::blessed( $val ) && $val->isa( 'DB::Object::Fields::Field' ) )
3326 ? $val->name
3327 : ( $val =~ $placeholder_re || $self->_is_number( $val ) )
3328 ? $val
3329 : qq{'${val}'};
3330 return( DB::Object::Expression->new( "${lval} ${not}${in}" ) );
3331 }
3332  
3333 # NOTE: package DB::Object::AND
3334 package DB::Object::AND;
3335 BEGIN
3336 {
3337 use strict;
3338 use parent -norequire, qw( DB::Object::Operator );
3339 };
3340  
3341 sub operator { return( 'AND' ); }
3342  
3343 # Ref:
3344 # <https://www.postgresql.org/docs/12/arrays.html#ARRAYS-SEARCHING>
3345 # NOTE: package DB::Object::ANY
3346 package DB::Object::ANY;
3347 BEGIN
3348 {
3349 use strict;
3350 use warnings;
3351 use parent -norequire, qw( DB::Object::Operator );
3352 use Scalar::Util ();
3353 use overload (
3354 '""' => 'as_string',
3355 'bool' => sub{1},
3356 '==' => sub{ &_opt_overload( @_, '==' ) },
3357 '!=' => sub{ &_opt_overload( @_, '!=' ) },
3358 fallback => 1,
3359 );
3360 };
3361  
3362 sub init
3363 {
3364 my $self = shift( @_ );
3365 $self->SUPER::init( @_ ) || return( $self->pass_error );
3366 # $self->_copy_binded_elements || return( $self->pass_error );
3367 return( $self );
3368 }
3369  
3370 sub as_string
3371 {
3372 my $self = shift( @_ );
3373 my $vals = $self->value;
3374 my @list = ();
3375 foreach my $elem ( @$vals )
3376 {
3377 next unless( defined( $elem ) );
3378 if( Scalar::Util::blessed( $elem ) &&
3379 $elem->isa( 'DB::Object::Statement' ) )
3380 {
3381 push( @list, $elem->as_string );
3382 }
3383 else
3384 {
3385 push( @list, $elem );
3386 }
3387 }
3388 local $" = ',';
3389 my $sql = "ANY (@list)";
3390 return( $sql );
3391 }
3392  
3393 sub operator { return( 'ANY' ); }
3394  
3395 sub _opt_overload
3396 {
3397 my( $self, $val, $swap, $op ) = @_;
3398 my $map =
3399 {
3400 '!=' => '!= ',
3401 '==' => '= ',
3402 };
3403 my $not = $map->{ $op };
3404 if( !defined( $not ) )
3405 {
3406 warn( "Unknown operator '${op}'. Falling back to '='." );
3407 $not = $map->{ '==' };
3408 }
3409 my $in = $self->as_string;
3410 my $placeholder_re = $self->query_object->database_object->_placeholder_regexp;
3411 my $lval = ( Scalar::Util::blessed( $val ) && $val->isa( 'DB::Object::Fields::Field' ) )
3412 ? $val->name
3413 : ( $val =~ $placeholder_re || $self->_is_number( $val ) )
3414 ? $val
3415 : qq{'${val}'};
3416 return( DB::Object::Expression->new( "${lval} ${not}${in}" ) );
3417 }
3418  
3419 # NOTE: package DB::Object::Expression
3420 package DB::Object::Expression;
3421 BEGIN
3422 {
3423 use strict;
3424 use warnings;
3425 use overload (
3426 '""' => 'as_string',
3427 'bool' => sub{1},
3428 fallback => 1,
3429 );
3430 };
3431  
3432 sub new
3433 {
3434 my $that = shift( @_ );
3435 my $val = ( scalar( @_ ) == 1 && ref( $_[0] ) eq 'ARRAY' ) ? [ @{$_[0]} ] : [ @_ ];
3436 return( bless( { value => $val } => ( ref( $that ) || $that ) ) );
3437 }
3438  
3439 sub as_string
3440 {
3441 my $self = shift( @_ );
3442 my $vals = $self->components;
3443 return( join( ' ', @$vals ) );
3444 }
3445  
3446 sub components { return( wantarray() ? @{$_[0]->{value}} : $_[0]->{value} ); }
3447  
3448  
3449 # Ref:
3450 # <https://www.postgresql.org/docs/12/functions-subquery.html#FUNCTIONS-SUBQUERY-IN>
3451 # <https://www.postgresql.org/docs/12/functions-comparisons.html#FUNCTIONS-COMPARISONS-IN-SCALAR>
3452 # <https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#operator_in>
3453 # <https://www.sqlite.org/lang_expr.html#the_in_and_not_in_operators>
3454 # NOTE: package DB::Object::IN
3455 package DB::Object::IN;
3456 BEGIN
3457 {
3458 use strict;
3459 use warnings;
3460 use parent -norequire, qw( DB::Object::Operator );
3461 use Scalar::Util ();
3462 use overload (
3463 '""' => 'as_string',
3464 'bool' => sub{1},
3465 '==' => sub{ &_opt_overload( @_, '==' ) },
3466 '!=' => sub{ &_opt_overload( @_, '!=' ) },
3467 fallback => 1,
3468 );
3469 };
3470  
3471 sub init
3472 {
3473 my $self = shift( @_ );
3474 $self->SUPER::init( @_ ) || return( $self->pass_error );
3475 # $self->_copy_binded_elements || return( $self->pass_error );
3476 return( $self );
3477 }
3478  
3479 sub as_string
3480 {
3481 my $self = shift( @_ );
3482 my $vals = $self->value;
3483 my @list = ();
3484 foreach my $elem ( @$vals )
3485 {
3486 next unless( defined( $elem ) );
3487 if( Scalar::Util::blessed( $elem ) &&
3488 $elem->isa( 'DB::Object::Statement' ) )
3489 {
3490 push( @list, $elem->as_string );
3491 }
3492 else
3493 {
3494 push( @list, $elem );
3495 }
3496 }
3497 local $" = ',';
3498 my $sql = "IN (@list)";
3499 return( $sql );
3500 }
3501  
3502 sub operator { return( 'IN' ); }
3503  
3504 sub _opt_overload
3505 {
3506 my( $self, $val, $swap, $op ) = @_;
3507 my $map =
3508 {
3509 '!=' => 'NOT ',
3510 '<>' => 'NOT ',
3511 '==' => '',
3512 };
3513 my $not = $map->{ $op } // '';
3514 my $in = $self->as_string;
3515 my $placeholder_re = $self->query_object->database_object->_placeholder_regexp;
3516 my $lval = ( Scalar::Util::blessed( $val ) && $val->isa( 'DB::Object::Fields::Field' ) )
3517 ? $val->name
3518 : ( $val =~ $placeholder_re || $self->_is_number( $val ) )
3519 ? $val
3520 : qq{'${val}'};
3521 return( DB::Object::Expression->new( "${lval} ${not}${in}" ) );
3522 }
3523  
3524 # Ref:
3525 # <https://www.postgresql.org/docs/current/functions-matching.html>
3526 # <https://dev.mysql.com/doc/refman/8.4/en/pattern-matching.html>
3527 # <https://www.sqlite.org/lang_corefunc.html#like>
3528 # <https://www.sqlite.org/lang_expr.html#the_like_glob_regexp_match_and_extract_operators>
3529 # NOTE: package DB::Object::LIKE
3530 # TODO: Finish the class DB::Object::LIKE
3531 package DB::Object::LIKE;
3532 BEGIN
3533 {
3534 use strict;
3535 use warnings;
3536 use parent -norequire, qw( DB::Object::Operator );
3537 use Scalar::Util ();
3538 use overload (
3539 '""' => 'as_string',
3540 'bool' => sub{1},
3541 '==' => sub{ &_opt_overload( @_, '==' ) },
3542 '!=' => sub{ &_opt_overload( @_, '!=' ) },
3543 fallback => 1,
3544 );
3545 };
3546  
3547 sub init
3548 {
3549 my $self = shift( @_ );
3550 $self->SUPER::init( @_ ) || return( $self->pass_error );
3551 # $self->_copy_binded_elements || return( $self->pass_error );
3552 return( $self );
3553 }
3554  
3555 sub as_string
3556 {
3557 my $self = shift( @_ );
3558 my $vals = $self->value;
3559 # Parameters can be given as an array for convenience, and they will concatenated
3560 my $sql = "LIKE '" . join( '', @$vals ) . "'";
3561 return( $sql );
3562 }
3563  
3564 sub _opt_overload
3565 {
3566 my( $self, $val, $swap, $op ) = @_;
3567 my $map =
3568 {
3569 '!=' => 'NOT ',
3570 '<>' => 'NOT ',
3571 '==' => '',
3572 };
3573 my $not = $map->{ $op } // '';
3574 my $like = $self->as_string;
3575 my $placeholder_re = $self->query_object->database_object->_placeholder_regexp;
3576 my $lval = ( Scalar::Util::blessed( $val ) && $val->isa( 'DB::Object::Fields::Field' ) )
3577 ? $val->name
3578 : ( $val =~ $placeholder_re || $self->_is_number( $val ) )
3579 ? $val
3580 : qq{'${val}'};
3581 return( DB::Object::Expression->new( "${lval} ${not}${like}" ) );
3582 }
3583  
3584  
3585 # NOTE: package DB::Object::NOT
3586 package DB::Object::NOT;
3587 BEGIN
3588 {
3589 use strict;
3590 use parent -norequire, qw( DB::Object::Operator );
3591 };
3592  
3593 sub operator { return( 'NOT' ); }
3594  
3595 # NOTE: package DB::Object::OR
3596 package DB::Object::OR;
3597 BEGIN
3598 {
3599 use strict;
3600 use parent -norequire, qw( DB::Object::Operator );
3601 };
3602  
3603 sub operator { return( 'OR' ); }
3604  
3605 1;
3606 # NOTE: POD
3607 __END__
3608  
3609 =encoding utf8
3610  
3611 =head1 NAME
3612  
3613 DB::Object - SQL API
3614  
3615 =head1 SYNOPSIS
3616  
3617 use DB::Object;
3618  
3619 my $dbh = DB::Object->connect({
3620 driver => 'Pg',
3621 conf_file => 'db-settings.json',
3622 database => 'webstore',
3623 host => 'localhost',
3624 login => 'store-admin',
3625 schema => 'auth',
3626 debug => 3,
3627 }) || bailout( "Unable to connect to sql server on host localhost: ", DB::Object->error );
3628  
3629 # Legacy regular query
3630 my $sth = $dbh->prepare( "SELECT login,name FROM login WHERE login='jack'" ) ||
3631 die( $dbh->errstr() );
3632 $sth->execute() || die( $sth->errstr() );
3633 my $ref = $sth->fetchrow_hashref();
3634 $sth->finish();
3635  
3636 # Get a list of databases;
3637 my @databases = $dbh->databases;
3638 # Doesn't exist? Create it:
3639 my $dbh2 = $dbh->create_db( 'webstore' );
3640 # Load some sql into it
3641 my $rv = $dbh2->do( $sql ) || die( $dbh->error );
3642  
3643 # Check a table exists
3644 $dbh->table_exists( 'customers' ) || die( "Cannot find the customers table!\n" );
3645  
3646 # Get list of tables, as array reference:
3647 my $tables = $dbh->tables;
3648  
3649 my $cust = $dbh->customers || die( "Cannot get customers object." );
3650 $cust->where( email => 'john@example.org' );
3651 my $str = $cust->delete->as_string;
3652 # Becomes: DELETE FROM customers WHERE email='john\@example.org'
3653  
3654 # Do some insert with transaction
3655 $dbh->begin_work;
3656 # Making some other inserts and updates here...
3657 my $cust_sth_ins = $cust->insert(
3658 first_name => 'Paul',
3659 last_name => 'Goldman',
3660 email => 'paul@example.org',
3661 active => 0,
3662 ) || do
3663 {
3664 # Rollback everything since the begin_work
3665 $dbh->rollback;
3666 die( "Error while create query to add data to table customers: " . $cust->error );
3667 };
3668 $result = $cust_sth_ins->as_string;
3669 # INSERT INTO customers (first_name, last_name, email, active) VALUES('Paul', 'Goldman', 'paul\@example.org', '0')
3670 $dbh->commit;
3671 # Get the last used insert id
3672 my $id = $dbh->last_insert_id();
3673  
3674 $cust->where( email => 'john@example.org' );
3675 $cust->order( 'last_name' );
3676 $cust->having( email => qr/\@example/ );
3677 $cust->limit( 10 );
3678 my $cust_sth_sel = $cust->select || die( "An error occurred while creating a query to select data frm table customers: " . $cust->error );
3679 # Becomes:
3680 # SELECT id, first_name, last_name, email, created, modified, active, created::ABSTIME::INTEGER AS created_unixtime, modified::ABSTIME::INTEGER AS modified_unixtime, CONCAT(first_name, ' ', last_name) AS name FROM customers WHERE email='john\@example.org' HAVING email ~ '\@example' ORDER BY last_name LIMIT 10
3681  
3682 $cust->reset;
3683 $cust->where( email => 'john@example.org' );
3684 my $cust_sth_upd = $cust->update( active => 0 )
3685 # Would become:
3686 # UPDATE ONLY customers SET active='0' WHERE email='john\@example.org'
3687  
3688 # Lets' dump the result of our query
3689 # First to STDERR
3690 $login->where( "login='jack'" );
3691 $login->select->dump();
3692 # Now dump the result to a file
3693 $login->select->dump( "my_file.txt" );
3694  
3695 Using L<fields objects|DB::Object::Fields::Field>
3696  
3697 $cust->where( $dbh->OR( $cust->fo->email == 'john@example.org', $cust->fo->id == 2 ) );
3698 my $ref = $cust->select->fetchrow_hashref;
3699  
3700 Doing some left join
3701  
3702 my $geo_tbl = $dbh->geoip || return( $self->error( "Unable to get the database object \"geoip\"." ) );
3703 my $name_tbl = $dbh->geoname || return( $self->error( "Unable to get the database object \"geoname\"." ) );
3704 $geo_tbl->as( 'i' );
3705 $name_tbl->as( 'l' );
3706 $geo_tbl->where( "INET '?'" << $geo_tbl->fo->network );
3707 $geo_tbl->alias( id => 'ip_id' );
3708 $name_tbl->alias( country_iso_code => 'code' );
3709 my $sth = $geo_tbl->select->join( $name_tbl, $geo_tbl->fo->geoname_id == $name_tbl->fo->geoname_id );
3710 # SELECT
3711 # -- tables fields
3712 # FROM
3713 # geoip AS i
3714 # LEFT JOIN geoname AS l ON i.geoname_id = l.geoname_id
3715 # WHERE
3716 # INET '?' << i.network
3717  
3718 Using a promise (L<Promise::Me>) to execute an asynchronous query:
3719  
3720 my $sth = $dbh->prepare( "SELECT some_slow_function(?)" ) || die( $dbh->error );
3721 my $p = $sth->promise(10)->then(sub
3722 {
3723 my $st = shift( @_ );
3724 my $ref = $st->fetchrow_hashref;
3725 my $obj = My::Module->new( %$ref );
3726 })->catch(sub
3727 {
3728 $log->warn( "Failed to execute query: ", @_ );
3729 });
3730 # Do other regular processing here
3731 # Get the My::Module object
3732 my( $obj ) = await( $p );
3733  
3734 Sometimes, having placeholders in expression makes it difficult to work, so you can use placeholder objects to make it work:
3735  
3736 my $P = $dbh->placeholder( type => 'inet' );
3737 $orders_tbl->where( $dbh->OR( $orders_tbl->fo->ip_addr == "inet $P", "inet $P" << $orders_tbl->fo->ip_addr ) );
3738 my $order_ip_sth = $orders_tbl->select( 'id' ) || fail( "An error has occurred while trying to create a select by ip query for table orders: " . $orders_tbl->error );
3739 # SELECT id FROM orders WHERE ip_addr = inet ? OR inet ? << ip_addr
3740  
3741 Be careful though, when using L<fields objects|DB::Object::Fields::Field>, not to do this:
3742  
3743 my $tbl = $dbh->some_table;
3744 $tbl->where( $tbl->fo->some_field => '?', $tbl->fo->other_field => '?' );
3745 my $sth = $tbl->select || die( $tbl->error );
3746  
3747 Because the L<fields objects|DB::Object::Fields::Field> are overloaded, instead do this:
3748  
3749 my $tbl = $dbh->some_table;
3750 $tbl->where( $tbl->fo->some_field == '?', $tbl->fo->other_field == '?' );
3751 my $sth = $tbl->select || die( $tbl->error );
3752  
3753 Accessing a property in a C<JSON> or C<JSONB> field:
3754  
3755 my $tbl = $dbh->some_table;
3756 $tbl->where( metadata => { is_system => 'true' } );
3757 my $sth = $tbl->select;
3758 say $sth->as_string;
3759 # SELECT * FROM some_table WHERE metadata->>is_system = 'true';
3760  
3761 In future release, other operators than C<=> will be implemented for C<JSON> and C<JSONB> fields.
3762  
3763 =head1 VERSION
3764  
3765 v1.10.0
3766  
3767 =head1 DESCRIPTION
3768  
3769 L<DB::Object> is a SQL API much alike C<DBI>, but with the added benefits that it formats queries in a simple object oriented, chaining way.
3770  
3771 So why use a private module instead of using that great C<DBI> package?
3772  
3773 At first, I started to inherit from C<DBI> to conform to C<perlmod> perl manual page and to general perl coding guidlines. It became very quickly a real hassle. Barely impossible to inherit, difficulty to handle error, too much dependent from an API that changes its behaviour with new versions.
3774 In short, I wanted a better, more accurate control over the SQL connection and an easy way to format sql statement using an object oriented approach.
3775  
3776 So, L<DB::Object> acts as a convenient, modifiable wrapper that provides the programmer with an intuitive, user-friendly, object oriented and hassle free interface.
3777  
3778 However, if you use the power of this interface to prepare queries conveniently, you should cache the resulting statement handler object, because there is an obvious real cost penalty in preparing queries and they absolutely do not need to be prepared each time. So you can do something like:
3779  
3780 my $sth;
3781 unless( $sth = $dbh->cache_query_get( 'some_arbitrary_identifier' ) )
3782 {
3783 # prepare the query
3784 my $tbl = $dbh->some_table || die( $dbh->error );
3785 $tbl->where( id => '?' );
3786 $sth = $tbl->select || die( $tbl->error );
3787 $dbh->cache_query_set( some_arbitrary_identifier => $sth );
3788 }
3789 $sth->exec(12) || die( $sth->error );
3790 my $ref = $sth->fetchrow_hashref;
3791  
3792 This will provide you with the convenience and power of L<DB::Object> while keeping execution fast.
3793  
3794 =head1 CONSTRUCTOR
3795  
3796 =head2 new
3797  
3798 Create a new instance of L<DB::Object>. Nothing much to say.
3799  
3800 =head2 connect
3801  
3802 Provided with a C<database>, C<login>, C<password>, C<server>:[C<port>], C<driver>, C<schema>, and optional hash or hash reference of parameters and this will issue a, possibly cached, database connection and return the resulting database handler.
3803  
3804 Create a new instance of L<DB::Object>, but also attempts a connection to SQL server.
3805  
3806 It can take either an array of value in the order database name, login, password, host, driver and optionally schema, or it can take a has or hash reference. The hash or hash reference attributes are as follow.
3807  
3808 Note that if you provide connection options that are not among the followings, this will return an error.
3809  
3810 =over 4
3811  
3812 =item * C<cache_connections>
3813  
3814 Defaults to true.
3815  
3816 If true, this will instruct L<DBI> to use L<DBI/connect_cached> instead of just L<DBI/connect>
3817  
3818 Beware that using cached connections can have some drawbacks, such as if you open a cached connection, enters into a transaction using L<DB::Object/begin_work>, then somewhere else in your code a call to a cached connection using the same parameters, which L<DBI> will provide, but will reset the database handler parameters, including the C<AutoCommit> that will have been temporarily set to false when you called L</begin_work>, and then you close your transaction by calling L</rollback> or L</commit>, but it will trigger an error, because C<AutoCommit> will have been reset on this cached connection to a true value. L</rollback> and L</commit> require that C<AutoCommit> be disabled, which L</begin_work> normally do.
3819  
3820 Thus, if you want to avoid using a cached connection, set this to false.
3821  
3822 More on this issue at L<DBI documentation|https://metacpan.org/pod/DBI#connect_cached>
3823  
3824 =item * C<database> or I<DB_NAME>
3825  
3826 The database name you wish to connect to
3827  
3828 =item * C<login> or I<DB_LOGIN>
3829  
3830 The login used to access that database
3831  
3832 =item * C<passwd> or I<DB_PASSWD>
3833  
3834 The password that goes along
3835  
3836 =item * C<host> or I<DB_HOST>
3837  
3838 The server, that is hostname of the machine serving a SQL server.
3839  
3840 =item * C<port> or I<DB_PORT>
3841  
3842 The port to connect to
3843  
3844 =item * C<driver> or I<DB_DRIVER>
3845  
3846 The driver you want to use. It needs to be of the same type than the server you want to connect to. If you are connecting to a MySQL server, you would use C<mysql>, if you would connecto to an Oracle server, you would use C<oracle>.
3847  
3848 You need to make sure that those driver are properly installed in the system before attempting to connect.
3849  
3850 To install the required driver, you could start with the command line:
3851  
3852 perl -MCPAN -e shell
3853  
3854 which will provide you a special shell to install modules in a convenient way.
3855  
3856 =item * C<schema> or I<DB_SCHEMA>
3857  
3858 The schema to use to access the tables. Currently only used by PostgreSQL
3859  
3860 =item * C<opt>
3861  
3862 This takes a hash reference and contains the standard C<DBI> options such as I<PrintError>, I<RaiseError>, I<AutoCommit>, etc
3863  
3864 =item * C<conf_file> or C<DB_CON_FILE>
3865  
3866 This is used to specify a json connection configuration file. It can also provided via the environment variable I<DB_CON_FILE>. It has the following structure:
3867  
3868 {
3869 "database": "some_database",
3870 "host": "db.example.com",
3871 "login": "sql_joe",
3872 "passwd": "some password",
3873 "driver": "Pg",
3874 "schema": "warehouse",
3875 "opt":
3876 {
3877 "RaiseError": false,
3878 "PrintError": true,
3879 "AutoCommit": true
3880 }
3881 }
3882  
3883 Alternatively, it can contain connections parameters for multiple databases and drivers, such as:
3884  
3885 {
3886 "databases": [
3887 {
3888 "database": "some_database",
3889 "host": "db.example.com",
3890 "port": 5432,
3891 "login": "sql_joe",
3892 "passwd": "some password",
3893 "driver": "Pg",
3894 "schema": "warehouse",
3895 "opt":
3896 {
3897 "RaiseError": false,
3898 "PrintError": true,
3899 "AutoCommit": true
3900 }
3901 },
3902 {
3903 "database": "other_database",
3904 "host": "db.example2.com",
3905 "login": "sql_bob",
3906 "passwd": "other password",
3907 "driver": "mysql",
3908 },
3909 {
3910 "database": "/path/to/my/database.sqlite",
3911 "driver": "SQLite",
3912 }
3913 ]
3914 }
3915  
3916 =item * C<uri> or I<DB_CON_URI>
3917  
3918 This is used to specify an uri to contain all the connection parameters for one database connection. It can also provided via the environment variable I<DB_CON_URI>. For example:
3919  
3920 http://db.example.com:5432?database=some_database&login=sql_joe&passwd=some%020password&driver=Pg&schema=warehouse&&opt=%7B%22RaiseError%22%3A+false%2C+%22PrintError%22%3Atrue%2C+%22AutoCommit%22%3Atrue%7D
3921  
3922 Here the I<opt> parameter is passed as a json string, for example:
3923  
3924 {"RaiseError": false, "PrintError":true, "AutoCommit":true}
3925  
3926 =back
3927  
3928 =head1 METHODS
3929  
3930 =head2 alias
3931  
3932 See L<DB::Object::Tables/alias>
3933  
3934 =head2 allow_bulk_delete
3935  
3936 Sets/gets the boolean value for whether to allow unsafe bulk delete. This means query without any C<where> clause.
3937  
3938 Default is false.
3939  
3940 =head2 allow_bulk_update
3941  
3942 Sets/gets the boolean value for whether to allow unsafe bulk update. This means query without any C<where> clause.
3943  
3944 Default is false.
3945  
3946 =head2 AND
3947  
3948 Takes any arguments and wrap them into a C<AND> clause.
3949  
3950 $tbl->where( $dbh->AND( $tbl->fo->id == ?, $tbl->fo->frequency >= .30 ) );
3951  
3952 =head2 as_string
3953  
3954 See L<DB::Object::Statement/as_string>
3955  
3956 =head2 auto_convert_datetime_to_object
3957  
3958 Sets or gets the boolean value. If true, then this api will automatically transcode datetime value into their equivalent L<DateTime> object.
3959  
3960 Default is false.
3961  
3962 =head2 auto_decode_json
3963  
3964 Sets or gets the boolean value. If true, then this api will automatically transcode json data into perl hash reference.
3965  
3966 Default is true.
3967  
3968 =head2 avoid
3969  
3970 See L<DB::Object::Tables/avoid>
3971  
3972 =head2 attribute
3973  
3974 Sets or get the value of database connection parameters.
3975  
3976 If only one argument is provided, returns its value.
3977 If multiple arguments in a form of pair => value are provided, it sets the corresponding database parameters.
3978  
3979 The authorised parameters are:
3980  
3981 =over 4
3982  
3983 =item I<Active>
3984  
3985 Is read-only.
3986  
3987 =item I<ActiveKids>
3988  
3989 Is read-only.
3990  
3991 =item I<AutoCommit>
3992  
3993 Can be changed.
3994  
3995 =item I<AutoInactiveDestroy>
3996  
3997 Can be changed.
3998  
3999 =item I<CachedKids>
4000  
4001 Is read-only.
4002  
4003 =item I<Callbacks>
4004  
4005 Can be changed.
4006  
4007 =item I<ChildHandles>
4008  
4009 Is read-only.
4010  
4011 =item I<ChopBlanks>
4012  
4013 Can be changed.
4014  
4015 =item I<CompatMode>
4016  
4017 Can be changed.
4018  
4019 =item I<CursorName>
4020  
4021 Is read-only.
4022  
4023 =item I<ErrCount>
4024  
4025 Is read-only.
4026  
4027 =item I<Executed>
4028  
4029 Is read-only.
4030  
4031 =item I<FetchHashKeyName>
4032  
4033 Is read-only.
4034  
4035 =item I<HandleError>
4036  
4037 Can be changed.
4038  
4039 =item I<HandleSetErr>
4040  
4041 Can be changed.
4042  
4043 =item I<InactiveDestroy>
4044  
4045 Can be changed.
4046  
4047 =item I<Kids>
4048  
4049 Is read-only.
4050  
4051 =item I<LongReadLen>
4052  
4053 Can be changed.
4054  
4055 =item I<LongTruncOk>
4056  
4057 Can be changed.
4058  
4059 =item I<NAME>
4060  
4061 Is read-only.
4062  
4063 =item I<NULLABLE>
4064  
4065 Is read-only.
4066  
4067 =item I<NUM_OF_FIELDS>
4068  
4069 Is read-only.
4070  
4071 =item I<NUM_OF_PARAMS>
4072  
4073 Is read-only.
4074  
4075 =item I<Name>
4076  
4077 Is read-only.
4078  
4079 =item I<PRECISION>
4080  
4081 Is read-only.
4082  
4083 =item I<PrintError>
4084  
4085 Can be changed.
4086  
4087 =item I<PrintWarn>
4088  
4089 Can be changed.
4090  
4091 =item I<Profile>
4092  
4093 Is read-only.
4094  
4095 =item I<RaiseError>
4096  
4097 Can be changed.
4098  
4099 =item I<ReadOnly>
4100  
4101 Can be changed.
4102  
4103 =item I<RowCacheSize>
4104  
4105 Is read-only.
4106  
4107 =item I<RowsInCache>
4108  
4109 Is read-only.
4110  
4111 =item I<SCALE>
4112  
4113 Is read-only.
4114  
4115 =item I<ShowErrorStatement>
4116  
4117 Can be changed.
4118  
4119 =item I<Statement>
4120  
4121 Is read-only.
4122  
4123 =item I<TYPE>
4124  
4125 Is read-only.
4126  
4127 =item I<Taint>
4128  
4129 Can be changed.
4130  
4131 =item I<TaintIn>
4132  
4133 Can be changed.
4134  
4135 =item I<TaintOut>
4136  
4137 Can be changed.
4138  
4139 =item I<TraceLevel>
4140  
4141 Can be changed.
4142  
4143 =item I<Type>
4144  
4145 Is read-only.
4146  
4147 =item I<Warn>
4148  
4149 Can be changed.
4150  
4151 =back
4152  
4153 =head2 available_drivers
4154  
4155 Return the list of available drivers.
4156  
4157 =head2 base_class
4158  
4159 Returns the base class.
4160  
4161 =head2 bind
4162  
4163 If no values to bind to the underlying query is provided, L</bind> simply activate the bind value feature.
4164  
4165 If values are provided, they are allocated to the statement object and will be applied when the query will be executed.
4166  
4167 Example:
4168  
4169 $dbh->bind()
4170 # or
4171 $dbh->bind->where( "something" )
4172 # or
4173 $dbh->bind->select->fetchrow_hashref()
4174 # and then later
4175 $dbh->bind( 'thingy' )->select->fetchrow_hashref()
4176  
4177 =head2 cache
4178  
4179 Activate caching.
4180  
4181 $tbl->cache->select->fetchrow_hashref();
4182  
4183 =head2 cache_connections
4184  
4185 Sets/get the cached database connection.
4186  
4187 =head2 cache_dir
4188  
4189 Sets or gets the directory on the file system used for caching data.
4190  
4191 =head2 cache_query
4192  
4193 Boolean. When set to a true value, this will enable the caching of the query objects.
4194  
4195 You can specify a particular serialiser with the method L</serialiser>. By default, the serialiser used is L<Storable::Improved>
4196  
4197 =head2 cache_query_get
4198  
4199 my $sth;
4200 unless( $sth = $dbh->cache_query_get( 'some_arbitrary_identifier' ) )
4201 {
4202 # prepare the query
4203 my $tbl = $dbh->some_table || die( $dbh->error );
4204 $tbl->where( id => '?' );
4205 $sth = $tbl->select || die( $tbl->error );
4206 $dbh->cache_query_set( some_arbitrary_identifier => $sth );
4207 }
4208 $sth->exec(12) || die( $sth->error );
4209 my $ref = $sth->fetchrow_hashref;
4210  
4211 Provided with a unique name, and this will return a cached statement object if it exists already, otherwise it will return undef
4212  
4213 =head2 cache_query_set
4214  
4215 my $sth;
4216 unless( $sth = $dbh->cache_query_get( 'some_arbitrary_identifier' ) )
4217 {
4218 # prepare the query
4219 my $tbl = $dbh->some_table || die( $dbh->error );
4220 $tbl->where( id => '?' );
4221 $sth = $tbl->select || die( $tbl->error );
4222 $dbh->cache_query_set( some_arbitrary_identifier => $sth );
4223 }
4224 $sth->exec(12) || die( $sth->error );
4225 my $ref = $sth->fetchrow_hashref;
4226  
4227 Provided with a unique name and a statement object (L<DB::Object::Statement>), and this will cache it.
4228  
4229 What this does simply is store the statement object in a global repository C<queries_cache> of identifier-statement object pairs. This is managed using L<Module::Generic::Global>
4230  
4231 It returns the statement object cached.
4232  
4233 =head2 cache_size
4234  
4235 The maximum number of serialised objects in the cache.
4236  
4237 This defaults to the class global variable C<$CACHE_SIZE>, which is C<10>
4238  
4239 =head2 cache_table
4240  
4241 Sets or gets a boolean value whether to cache the table fields object.
4242  
4243 When this is enabled, the second time a database table is accessed, it will retrieve its field objects from the cache rather than recreating them after reading the structure from the database. This is much faster.
4244  
4245 By default, this is set to false.
4246  
4247 This can be specified in the configuration file passed when instantiating a new C<DB::Object> object with the property C<cache_table>
4248  
4249 =head2 cache_table_fields
4250  
4251 my $all_dbs = $dbh->cache_table_fields;
4252 my $all_tables = $dbh->cache_table_fields( database => $some_database );
4253 my $all_fields = $dbh->cache_table_fields(
4254 database => $some_database,
4255 table => $some_table,
4256 );
4257 $dbh->cache_table_fields(
4258 database => $some_database,
4259 table => $some_table,
4260 fields => $some_hash_reference,
4261 );
4262  
4263 Sets or gets the hash reference of database table field name to their L<corresponding object|DB::Object::Fields::Field>.
4264  
4265 If no parameter is provided, it will return the entire cache for all databases for a given driver.
4266  
4267 If only a database name is provided, it will return the cache hash reference for all the tables in the given database.
4268  
4269 If a database and a table name is provided, this will return an hash reference of field name to their L<corresponding object|DB::Object::Fields::Field>.
4270  
4271 If a database and a table name and an hash reference of field names to their L<corresponding objects|DB::Object::Fields::Field> is provided, it will set this hash as the cache for the given database and table.
4272  
4273 =head2 cache_tables
4274  
4275 Sets or gets the L<DB::Object::Cache::Tables> object.
4276  
4277 =head2 check_driver
4278  
4279 Check that the driver set in I<$SQL_DRIVER> in ~/etc/common.cfg is indeed available.
4280  
4281 It does this by calling L</available_drivers>.
4282  
4283 =head2 connect
4284  
4285 This will attempt a database server connection.
4286  
4287 It called L</_connection_params2hash> to get the necessary connection parameters, which is superseded in each driver package.
4288  
4289 Then, it will call L</_check_connect_param> to get the right parameters for connection.
4290  
4291 It will also call L</_check_default_option> to get some driver specific default options unless the previous call to _check_connect_param returned an has with a property I<opt>.
4292  
4293 It will then set the following current object properties: L</database>, L</host>, L</port>, L</login>, L</passwd>, L</driver>, L</cache>, L</bind>, L</opt>
4294  
4295 Unless specified in the connection options retrieved with L</_check_default_option>, it sets some basic default value:
4296  
4297 =over 4
4298  
4299 =item I<AutoCommit> 1
4300  
4301 =item I<PrintError> 0
4302  
4303 =item I<RaiseError> 0
4304  
4305 =back
4306  
4307 Finally it tries to connect by calling the, possibly superseded, method L</_dbi_connect>
4308  
4309 It instantiate a L<DB::Object::Cache::Tables> object to cache database tables and return the current object.
4310  
4311 =head2 connect_via
4312  
4313 Sets or gets the perl module used to connect to DBI. Typically, this would be L<Apache::DBI>. By default, this is empty.
4314  
4315 =head2 constant_queries_cache
4316  
4317 Returns the global repository of constant queries. This uses L<Module::Generic::Global>, and is thread-safe.
4318  
4319 This is used by L</constant_queries_cache_get> and L</constant_queries_cache_set>
4320  
4321 =head2 constant_queries_cache_get
4322  
4323 Provided with some hash reference with properties C<pack>, C<file> and C<line> that are together used as a key in the cache and this will use an existing entry in the cache if available.
4324  
4325 =head2 constant_queries_cache_del
4326  
4327 Removes a constant query cache.
4328  
4329 =head2 constant_queries_cache_set
4330  
4331 Provided with some hash reference with properties C<pack>, C<file> and C<line> that are together used as a key in the cache and C<query_object> and this will set an entry in the cache. it returns the hash reference initially provided.
4332  
4333 =head2 constant_to_datatype
4334  
4335 Provided with a data type constant value and this returns its equivalent data type as a string in upper case.
4336  
4337 This constant is set by the driver, or by default by L<DBI>. For example C<SQL_VARCHAR> is C<12> and its data type is C<VARCHAR>
4338  
4339 See also L</datatype_to_constant>
4340  
4341 =head2 copy
4342  
4343 Provided with either a reference to an hash or an hash of key => value pairs, L</copy> will first execute a select statement on the table object, then fetch the row of data, then replace the key-value pair in the result by the ones provided, and finally will perform an insert.
4344  
4345 Return false if no data to copy were provided, otherwise it always returns true.
4346  
4347 =head2 create_db
4348  
4349 This is a method that must be implemented by the driver package.
4350  
4351 =head2 create_table
4352  
4353 This is a method that must be implemented by the driver package.
4354  
4355 =head2 data_sources
4356  
4357 Given an optional list of options as hash, this return the data source of the database handler.
4358  
4359 =head2 data_type
4360  
4361 Given a reference to an array or an array of data type, L</data_type> will check their availability in the database driver.
4362  
4363 If nothing found, it return an empty list in list context, or undef in scalar context.
4364  
4365 If something was found, it returns a hash in list context or a reference to a hash in list context.
4366  
4367 =head2 database
4368  
4369 Return the name of the current database.
4370  
4371 =head2 databases
4372  
4373 This returns the list of available databases.
4374  
4375 This is a method that must be implemented by the driver package.
4376  
4377 =head2 datatype_dict
4378  
4379 Returns an hash reference of each data type with their equivalent C<constant>, regular expression (C<re>), constant C<name> and C<type> name.
4380  
4381 Each data type is an hash with the following properties for each type: C<constant>, C<name>, C<re>, C<type>
4382  
4383 The data returned is dependent on each driver.
4384  
4385 =head2 datatype_to_constant
4386  
4387 my $type = $dbh->datatype_to_constant( 'varchar' ); # 12
4388  
4389 # Below achieves the same result
4390 use DBI ':sql_types';
4391 say SQL_VARCHAR; # 12
4392  
4393 Provided with a data type as a string and this returns its equivalent driver value if any, or by default the one of set by L<DBI>.
4394  
4395 The data type provided is case insensitive.
4396  
4397 If no matching data type exists, it returns C<undef> in scalar context, or an empty list in list context.
4398  
4399 As pointed out by L<DBI documentation|DBI/"DBI Constants">: "just because the DBI defines a named constant for a given data type doesn't mean that drivers will support that data type."
4400  
4401 See also L</constant_to_datatype>
4402  
4403 =head2 datatypes
4404  
4405 my $types = $dbh->datatypes;
4406  
4407 Returns an hash reference of data types to their respective values.
4408  
4409 If the driver has its own, it will return the driver's constants, otherwise, this will return an hash reference of L<DBI data type constants|DBI/"DBI Constants">.
4410  
4411 As pointed out by L<DBI documentation|DBI/"DBI Constants">: "just because the DBI defines a named constant for a given data type doesn't mean that drivers will support that data type."
4412  
4413 =head2 delete
4414  
4415 See L<DB::Object::Tables/delete>
4416  
4417 =head2 disconnect
4418  
4419 Disconnect from database. Returns the return code.
4420  
4421 my $rc = $dbh->disconnect;
4422  
4423 =head2 do
4424  
4425 Provided with a string representing a sql query, some hash reference of attributes and some optional values to bind and this will execute the query and return the statement handler.
4426  
4427 The attributes list will be used to B<prepare> the query and the bind values will be used when executing the query.
4428  
4429 Example:
4430  
4431 $rc = $dbh->do( $statement ) || die( $dbh->errstr );
4432 $rc = $dbh->do( $statement, \%attr ) || die( $dbh->errstr );
4433 $rv = $dbh->do( $statement, \%attr, @bind_values ) || die( $dbh->errstr );
4434 my $rows_deleted = $dbh->do(
4435 q{
4436 DELETE FROM table WHERE status = ?
4437 }, undef(), 'DONE' ) || die( $dbh->errstr );
4438  
4439 =head2 driver
4440  
4441 Return the name of the driver for the current object.
4442  
4443 =head2 enhance
4444  
4445 Toggle the enhance mode on/off.
4446  
4447 When on, the functions L</from_unixtime> and L</unix_timestamp> will be used on date/time field to translate from and to unix time seamlessly.
4448  
4449 =head2 err
4450  
4451 Get the currently set error.
4452  
4453 =head2 errno
4454  
4455 Is just an alias for L</err>.
4456  
4457 =head2 errmesg
4458  
4459 Is just an alias for L</errstr>.
4460  
4461 =head2 errstr
4462  
4463 Get the currently set error string.
4464  
4465 =head2 FALSE
4466  
4467 This return the keyword C<FALSE> to be used in queries.
4468  
4469 =head2 fatal
4470  
4471 Provided a boolean value and this toggles fatal mode on/off.
4472  
4473 =head2 format_statement
4474  
4475 See L<DB::Object::Tables/format_statement>
4476  
4477 =head2 format_update
4478  
4479 See L<DB::Object::Tables/format_update>
4480  
4481 =head2 from_unixtime
4482  
4483 See L<DB::Object::Tables/from_unixtime>
4484  
4485 =head2 get_sql_type
4486  
4487 Provided with a sql type, irrespective of the character case, and this will return the driver equivalent constant value.
4488  
4489 =head2 group
4490  
4491 See L<DB::Object::Tables/group>
4492  
4493 =head2 host
4494  
4495 Sets or gets the C<host> property for this database object.
4496  
4497 =head2 insert
4498  
4499 See L<DB::Object::Tables/insert>
4500  
4501 =head2 last_insert_id
4502  
4503 Get the id of the primary key from the last insert.
4504  
4505 =head2 LIKE
4506  
4507 Returns a new L<DB::Object::LIKE> object, passing it whatever arguments were provided.
4508  
4509 =head2 limit
4510  
4511 See L<DB::Object::Tables/limit>
4512  
4513 =head2 local
4514  
4515 See L<DB::Object::Tables/local>
4516  
4517 =head2 lock
4518  
4519 This method must be implemented by the driver package.
4520  
4521 =head2 login
4522  
4523 Sets or gets the C<login> property for this database object.
4524  
4525 =head2 no_bind
4526  
4527 When invoked, L</no_bind> will change any preparation made so far for caching the query with bind parameters, and instead substitute the value in lieu of the question mark placeholder.
4528  
4529 =head2 no_cache
4530  
4531 Disable caching of queries.
4532  
4533 =head2 NOT
4534  
4535 Returns a new L<DB::Object::NOT> object, passing it whatever arguments were provided.
4536  
4537 =head2 NULL
4538  
4539 Returns a C<NULL> string to be used in queries.
4540  
4541 =head2 on_conflict
4542  
4543 See L<DB::Object::Tables/on_conflict>
4544  
4545 =head2 OR
4546  
4547 Returns a new L<DB::Object::OR> object, passing it whatever arguments were provided.
4548  
4549 =head2 order
4550  
4551 See L<DB::Object::Tables/order>
4552  
4553 =head2 P
4554  
4555 Returns a L<DB::Object::Placeholder> object, passing it whatever arguments was provided.
4556  
4557 =head2 param
4558  
4559 If only a single parameter is provided, its value is return. If a list of parameters is provided they are set accordingly using the C<SET> sql command.
4560  
4561 Supported parameters are:
4562  
4563 =over 4
4564  
4565 =item AUTOCOMMIT
4566  
4567 =item INSERT_ID
4568  
4569 =item LAST_INSERT_ID
4570  
4571 =item SQL_AUTO_IS_NULL
4572  
4573 =item SQL_BIG_SELECTS
4574  
4575 =item SQL_BIG_TABLES
4576  
4577 =item SQL_BUFFER_RESULT
4578  
4579 =item SQL_LOG_OFF
4580  
4581 =item SQL_LOW_PRIORITY_UPDATES
4582  
4583 =item SQL_MAX_JOIN_SIZE
4584  
4585 =item SQL_SAFE_MODE
4586  
4587 =item SQL_SELECT_LIMIT
4588  
4589 =item SQL_LOG_UPDATE
4590  
4591 =item TIMESTAMP
4592  
4593 =back
4594  
4595 If unsupported parameters are provided, they are considered to be private and not passed to the database handler.
4596  
4597 It then execute the query and return L<perlfunc/undef> in case of error.
4598  
4599 Otherwise, it returns the current object used to call the method.
4600  
4601 =head2 passwd
4602  
4603 Sets or gets the C<passwd> property for this database object.
4604  
4605 =head2 ping
4606  
4607 Evals a SELECT 1 statement and returns 0 if errors occurred or the return value.
4608  
4609 =head2 ping_select
4610  
4611 Will prepare and execute a simple C<SELECT 1> and return 0 upon failure or return the value returned from calling L<DBI/execute>.
4612  
4613 =head2 placeholder
4614  
4615 Same as L</P>. Returns a L<DB::Object::Placeholder> object, passing it whatever arguments was provided.
4616  
4617 =head2 port
4618  
4619 Sets or gets the C<port> property for this database object.
4620  
4621 =head2 prepare
4622  
4623 Provided with a sql query and some hash reference of options and this will prepare the query using the options provided. The options are the same as the one in L<DBI/prepare> method.
4624  
4625 It returns a L<DB::Object::Statement> object upon success or undef if an error occurred. The error can then be retrieved using L</errstr> or L</error>.
4626  
4627 =head2 prepare_cached
4628  
4629 Same as L</prepare> except the query is cached.
4630  
4631 =head2 query
4632  
4633 It prepares and executes the given SQL query with the options provided and return L<perlfunc/undef> upon error or the statement handler upon success.
4634  
4635 =head2 query_object
4636  
4637 Sets or gets the L<query object|DB::Object::Query>.
4638  
4639 =head2 quote
4640  
4641 This is used to properly format data by surrounding them with quotes or not.
4642  
4643 Calls L<DBI/quote> and pass it whatever argument was provided.
4644  
4645 =head2 replace
4646  
4647 See L<DB::Object::Tables/replace>
4648  
4649 =head2 reset
4650  
4651 See L<DB::Object::Tables/reset>
4652  
4653 =head2 returning
4654  
4655 See L<DB::Object::Tables/returning>
4656  
4657 =head2 reverse
4658  
4659 See L<DB::Object::Tables/reverse>
4660  
4661 =head2 select
4662  
4663 See L<DB::Object::Tables/select>
4664  
4665 =head2 set
4666  
4667 Provided with variable and this will issue a query to C<SET> the given SQL variable.
4668  
4669 If any error occurred, undef will be returned and an error set, otherwise it returns true.
4670  
4671 =head2 sort
4672  
4673 See L<DB::Object::Tables/sort>
4674  
4675 =head2 stat
4676  
4677 Issue a C<SHOW STATUS> query and if a particular C<$type> is provided, it will return its value if it exists, otherwise it will return L<perlfunc/undef>.
4678  
4679 In absence of particular $type provided, it returns the hash list of values returns or a reference to the hash list in scalar context.
4680  
4681 =head2 state
4682  
4683 Queries the DBI state and return its value.
4684  
4685 =head2 supported_class
4686  
4687 Returns the list of driver packages such as L<DB::Object::Postgres>
4688  
4689 =head2 supported_drivers
4690  
4691 Returns the list of driver name such as L<Pg>
4692  
4693 =head2 table
4694  
4695 Given a table name, L</table> will return a L<DB::Object::Tables> object. The object is cached for re-use.
4696  
4697 When a cached table object is found, it is cloned and reset (using L</reset>), before it is returned to avoid undesirable effets in following query that would have some table properties set such as table alias.
4698  
4699 =head2 table_exists
4700  
4701 Provided with a table name and this returns true if the table exist or false otherwise.
4702  
4703 =head2 table_info
4704  
4705 This is a method that must be implemented by the driver package.
4706  
4707 It returns an array reference of hash reference containing information about each table column.
4708  
4709 =head2 table_push
4710  
4711 Add the given table name to the stack of cached table names.
4712  
4713 =head2 tables
4714  
4715 Connects to the database and finds out the list of all available tables. If cache is available, it will use it instead of querying the database server.
4716  
4717 Returns undef or empty list in scalar or list context respectively if no table found.
4718  
4719 Otherwise, it returns the list of table in list context or a reference of it in scalar context.
4720  
4721 =head2 tables_cache
4722  
4723 Returns the table cache object
4724  
4725 =head2 tables_info
4726  
4727 This is a method that must be implemented by the driver package.
4728  
4729 =head2 tables_refresh
4730  
4731 Rebuild the list of available database table.
4732  
4733 Returns the list of table in list context or a reference of it in scalar context.
4734  
4735 =head2 tie
4736  
4737 See L<DB::Object::Tables/tie>
4738  
4739 =head2 transaction
4740  
4741 True when a transaction has been started with L</begin_work>, false otherwise.
4742  
4743 =head2 TRUE
4744  
4745 Returns C<TRUE> to be used in queries.
4746  
4747 =head2 unix_timestamp
4748  
4749 See L<DB::Object::Tables/unix_timestamp>
4750  
4751 =head2 for POD::Coverage unknown_field
4752  
4753 =head2 unlock
4754  
4755 This is a convenient wrapper around L<DB::Object::Query/unlock>
4756  
4757 =head2 update
4758  
4759 See L<DB::Object::Tables/update>
4760  
4761 =head2 use
4762  
4763 Given a database, it switch to it, but before it checks that the database exists.
4764 If the database is different than the current one, it sets the I<multi_db> parameter, which will have the fields in the queries be prefixed by their respective database name.
4765  
4766 It returns the database handler.
4767  
4768 =head2 use_cache
4769  
4770 Provided with a boolean value and this sets or get the I<use_cache> parameter.
4771  
4772 =head2 use_bind
4773  
4774 Provided with a boolean value and this sets or get the I<use_cache> parameter.
4775  
4776 =head2 variables
4777  
4778 Query the SQL variable $type
4779  
4780 It returns a blank string if nothing was found, or the value found.
4781  
4782 =head2 version
4783  
4784 This is a method that must be implemented by the driver package.
4785  
4786 =head2 where
4787  
4788 See L<DB::Object::Tables/where>
4789  
4790 =head2 _cache_this
4791  
4792 Provided with a query, this will cache it for future re-use.
4793  
4794 It does some check and maintenance job to ensure the cache does not get too big whenever it exceed the value of $CACHE_SIZE set in the main config file.
4795  
4796 It returns the cached statement as an L<DB::Object::Statement> object.
4797  
4798 =head2 _check_connect_param
4799  
4800 Provided with an hash reference of connection parameters, this will get the valid parameters by calling L</_connection_parameters> and the connection default options by calling L</_connection_options>
4801  
4802 It returns the connection parameters hash reference.
4803  
4804 =head2 _check_default_option
4805  
4806 Provided with an hash reference of options, and it actually returns it, so this does not do much, because this method is supposed to be supereded by the driver package.
4807  
4808 =head2 _connection_options
4809  
4810 Provided with an hash reference of connection parameters and this will returns an hash reference of options whose keys match the regular expression C</^[A-Z][a-zA-Z]+/>
4811  
4812 So this does not do much, because this method is supposed to be superseded by the driver package.
4813  
4814 =head2 _connection_parameters
4815  
4816 Returns an array reference containing the following keys: db login passwd host port driver database server opt uri debug
4817  
4818 =head2 _connection_params2hash
4819  
4820 Provided with an hash reference of connection parameters and this will check if the following environment variables exists and if so use them: C<DB_NAME>, C<DB_LOGIN>, C<DB_PASSWD>, C<DB_HOST>, C<DB_PORT>, C<DB_DRIVER>, C<DB_SCHEMA>
4821  
4822 If the parameter property I<uri> was provided of if the environment variable C<DB_CON_URI> is set, it will use this connection uri to get the necessary connection parameters values.
4823  
4824 An L<URI> could be C<http://localhost:5432?database=somedb> or C<file:/foo/bar?opt={"RaiseError":true}>
4825  
4826 Alternatively, if the connection parameter I<conf_file> is provided then its json content will be read and decoded into an hash reference.
4827  
4828 The following keys can be used in the json data in the I<conf_file>: C<database>, C<login>, C<passwd>, C<host>, C<port>, C<driver>, C<schema>, C<opt>
4829  
4830 The port can be specified in the I<host> parameter by separating it with a semicolon such as C<localhost:5432>
4831  
4832 The I<opt> parameter can Alternatively be provided through the environment variable C<DB_OPT>
4833  
4834 It returns the hash reference of connection parameters.
4835  
4836 =head2 _clean_statement
4837  
4838 Given a query string or a reference to it, it cleans the statement by removing leading and trailing space before and after line breaks.
4839  
4840 It returns the cleaned up query as a string if the original query was provided as a scalar reference.
4841  
4842 =head2 _convert_datetime2object
4843  
4844 Provided with an hash or hash reference of options and this will simply return the I<data> property.
4845  
4846 This does not do anything meaningful, because it is supposed to be superseded by the diver package.
4847  
4848 =head2 _convert_json2hash
4849  
4850 Provided with an hash or hash reference of options and this will simply return the I<data> property.
4851  
4852 This does not do anything meaningful, because it is supposed to be superseded by the diver package.
4853  
4854 =head2 _dbi_connect
4855  
4856 This will call L</_dsn> which must exist in the driver package, and based on the C<dsn> received, this will initiate a L<DBI/connect_cache> if the object property L</cache_connections> has a true value, or simply a L<DBI/connect> otherwise.
4857  
4858 It returns the database handler.
4859  
4860 =head2 _decode_json
4861  
4862 Provided with some json data and this will decode it using L<JSON> and return the associated hash reference or L<perlfunc/undef> if an error occurred.
4863  
4864 =head2 _dsn
4865  
4866 This will die complaining the driver has not implemented this method, unless the driver did implement it.
4867  
4868 =head2 _encode_json
4869  
4870 Provided with an hash reference and this will encode it into a json string and return it.
4871  
4872 =head2 _make_sth
4873  
4874 Given a package name and a hash reference, this builds a statement object with all the necessary parameters.
4875  
4876 It also sets the query time to the current time with the parameter I<query_time>
4877  
4878 It returns an object of the given $package.
4879  
4880 =head2 _param2hash
4881  
4882 Provided with some hash reference parameters and this will simply return it, so it does not do anything meaningful.
4883  
4884 This is supposed to be superseded by the driver package.
4885  
4886 =head2 _process_limit
4887  
4888 A convenient wrapper around the L<DB::Object::Query/_process_limit>
4889  
4890 =head2 _query_object_add
4891  
4892 Provided with a L<DB::Object::Query> and this will add it to the current object property I<query_object> and return it.
4893  
4894 =head2 _query_object_create
4895  
4896 This is supposed to be called from a L<DB::Object::Tables>
4897  
4898 Create a new L<DB::Object::Query> object, sets the I<debug> and I<verbose> values and sets its property L<DB::Object::Query/table_object> to the value of the current object.
4899  
4900 =head2 _query_object_current
4901  
4902 Returns the current I<query_object>
4903  
4904 =head2 _query_object_get_or_create
4905  
4906 Check to see if the L</query_object> is already set and then return its value, otherwise create a new object by calling L</_query_object_create> and return it.
4907  
4908 =head2 _query_object_remove
4909  
4910 Provided with a L<DB::Object::Query> and this will remove it from the current object property I<query_object>.
4911  
4912 It returns the object removed.
4913  
4914 =head2 _reset_query
4915  
4916 If this has not already been reset, this will mark the current query object as reset and calls L</_query_object_remove> and return the value for L</_query_object_get_or_create>
4917  
4918 If it has been already reset, this will return the value for L</_query_object_current>
4919  
4920 =head1 OPERATORS
4921  
4922 =head2 ALL( VALUES )
4923  
4924 This operator is used to query an array where all elements must match.
4925  
4926 my $tbl = $dbh->hosts || die( "Uable to get table object 'hosts'." );
4927 $tbl->where( $dbh->OR(
4928 $tbl->fo->name == 'example.com',
4929 'example.com' == $dbh->ALL( $tbl->fo->alias )
4930 ));
4931 my $sth = $tbl->select || die( "Failed to prepare query to get host information: ", $tbl->error );
4932 my $ref = $sth->fetchrow_hashref;
4933  
4934 See L<PostgreSQL documentation|https://www.postgresql.org/docs/current/arrays.html>
4935  
4936 =head2 AND( VALUES )
4937  
4938 Given a value, this returns a L<DB::Object::AND> object. You can retrieve the value with L<DB::Object::AND/value>
4939  
4940 This is used by L</where>
4941  
4942 my $op = $dbh->AND( login => 'joe', status => 'active' );
4943 # will produce:
4944 WHERE login = 'joe' AND status = 'active'
4945  
4946 =head2 ANY( VALUES )
4947  
4948 This operator is used to query an array where all elements must match.
4949  
4950 my $tbl = $dbh->hosts || die( "Uable to get table object 'hosts'." );
4951 $tbl->where( $dbh->OR(
4952 $tbl->fo->name == 'example.com',
4953 'example.com' == $dbh->ANY( $tbl->fo->alias )
4954 ));
4955 my $sth = $tbl->select || die( "Failed to prepare query to get host information: ", $tbl->error );
4956 my $ref = $sth->fetchrow_hashref;
4957  
4958 See L<PostgreSQL documentation|https://www.postgresql.org/docs/current/arrays.html>
4959  
4960 =head2 IN
4961  
4962 For example:
4963  
4964 SELECT
4965 c.code, c.name, c.name_l10n, c.locale
4966 FROM country_locale AS c
4967 WHERE
4968 c.locale = 'fr_FR' OR
4969 ('fr_FR' NOT IN (SELECT DISTINCT l.locale FROM country_locale AS l ORDER BY l.locale) AND
4970 c.locale = 'en_GB')
4971 ORDER BY c.code
4972  
4973 my $tbl = $dbh->country_locale || die( $dbh->error );
4974 my $tbl2 = $dbh->country_locale || die( $dbh->error );
4975 $tbl2->as( 'l' );
4976 $tbl2->order( 'locale' );
4977 my $sth2 = $tbl2->select( 'DISTINCT locale' ) || die( $tbl2->error );
4978  
4979 $tbl->as( 'c' );
4980 $tbl->where( $dbh->OR(
4981 $tbl->fo->locale == 'fr_FR',
4982 $dbh->AND(
4983 'fr_FR' != $dbh->IN( $sth2 ),
4984 $tbl->fo->locale == 'en_GB'
4985 )
4986 ) );
4987  
4988 $tbl->order( $tbl->fo->code );
4989 my $sth = $tbl->select( qw( code name name_l10n locale ) ) || die( $tbl->error );
4990 say $sth->as_string;
4991  
4992 =head2 NOT( VALUES )
4993  
4994 Given a value, this returns a L<DB::Object::NOT> object. You can retrieve the value with L<DB::Object::NOT/value>
4995  
4996 This is used by L</where>
4997  
4998 my $op = $dbh->AND( login => 'joe', status => $dbh->NOT( 'active' ) );
4999 # will produce:
5000 WHERE login = 'joe' AND status != 'active'
5001  
5002 =head2 OR( VALUES )
5003  
5004 Given a value, this returns a L<DB::Object::OR> object. You can retrieve the value with L<DB::Object::OR/value>
5005  
5006 This is used by L</where>
5007  
5008 my $op = $dbh->OR( login => 'joe', login => 'john' );
5009 # will produce:
5010 WHERE login = 'joe' OR login = 'john'
5011  
5012 =head1 SEE ALSO
5013  
5014 L<DBI>, L<Apache::DBI>
5015  
5016 =head1 AUTHOR
5017  
5018 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
5019  
5020 =head1 COPYRIGHT & LICENSE
5021  
5022 Copyright (c) 2019-2025 DEGUEST Pte. Ltd.
5023  
5024 You can use, copy, modify and redistribute this package and associated files under the same terms as Perl itself.
5025  
5026 =cut