blib/lib/DB/Object.pm untested

filter: Statementstmt 0.0% 0 / 1869 Branchbran 0.0% 0 / 932 Conditioncond 0.0% 0 / 952 MC/DCmcdc 0.0% 0 / 530 Subroutinesub 0.0% 0 / 226 Podpod 0.0% 0 / 168 totaltotal 0.0% 0 / 4677 CC 466 SCAR 62.9
CC
466
Cov
0%
_cache_this
2256.0
_connection_params2hash
1806.0
connect
1560.0
CRAP 539.4
1 # -*- perl -*-
2 ##----------------------------------------------------------------------------
3 ## Database Object Interface - ~/lib/m
4 ## Version v1.11.0
5 ## Copyright(c) 2026 DEGUEST Pte. Ltd.
6 ## Author: Jacques Deguest <jack@deguest.jp>
7 ## Created 2017/07/19
8 ## Modified 2026/09/23
9 ## All rights reserved
10 ##
11 ## This program is free software; you can redistribute it and/or modify it
12 ## under the same terms as Perl itself.
13 ##----------------------------------------------------------------------------
14 ## This is the subclassable module for driver specific ones.
15 package DB::Object;
16 BEGIN
17 {
18 require 5.16.0;
19 use strict;
20 use warnings;
21 use warnings::register;
22 use parent qw( Module::Generic DBI );
23 use vars qw(
24 $VERSION $AUTOLOAD $CACHE_DIR $CACHE_SIZE $DRIVER2PACK
25 $ERROR $DEBUG $MOD_PERL $USE_BIND $USE_CACHE $PLACEHOLDER_REGEXP $SERIALISER
26 $SERIALISATION_VERSION $EXCEPTION_CLASS
27 );
28 use Regexp::Common;
29 use Scalar::Util qw( blessed weaken );
30 use DB::Object::Cache::Tables;
31 use DBI;
32 use JSON;
33 use Module::Generic::File qw( sys_tmpdir );
34 use Module::Generic::Global qw( :const );
35 use POSIX ();
36 use Wanted;
37 our $PLACEHOLDER_REGEXP = qr/(?<![?\w])\?(?![?\w])/;
38 our $EXCEPTION_CLASS = 'DB::Object::Exception';
39 our $VERSION = 'v1.11.0';
40 };
41  
42 use strict;
43 use warnings;
44  
45 our $DEBUG = 0;
46 # A global setting variable. This is not changed dynamically, and can be set by the user
47 our $CACHE_SIZE = 10;
48 our $USE_BIND = 0;
49 our $USE_CACHE = 0;
50 our $MOD_PERL = 0;
51 # A global variable that can be set by the user to serve as a default value
52 our $CACHE_DIR = '';
53 if( $INC{ 'Apache/DBI.pm' } &&
54 substr( $ENV{GATEWAY_INTERFACE} || '', 0, 8 ) eq 'CGI-Perl' )
55 {
56 $MOD_PERL++;
57 }
58 # Global constant
59 our $DRIVER2PACK =
60 {
61 mysql => 'DB::Object::Mysql',
62 Pg => 'DB::Object::Postgres',
63 SQLite => 'DB::Object::SQLite',
64 };
65 # Default value
66 our $SERIALISER = 'Storable';
67 our $SERIALISATION_VERSION = 1;
68 my $CONNECTION_ID_SEQUENCE = 0;
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 $self->{enhance} = 0;
90 $self->{id} = undef;
91 # Auto-decode json data into perl hash
92 $self->{auto_decode_json} = 1;
93 $self->{auto_convert_datetime_to_object} = 0;
94 $self->{allow_bulk_delete} = 0;
95 $self->{allow_bulk_update} = 0;
96 $self->{serialiser} = undef;
97 $self->{unknown_field} = 'ignore';
98 $self->{_init_strict_use_sub} = 1;
99 $self->{_core_fields} = [grep( !/^_/, keys( %$self ) )];
100 $self->{_exception_class} = $EXCEPTION_CLASS;
101 $self->Module::Generic::init( @_ ) || return( $self->pass_error );
102 return( $self );
103 }
104  
105 sub active_transactions
106 {
107 my $self = shift( @_ );
108 my $found = [];
109 my $error;
110 DBI->visit_handles(sub
111 {
112 my( $handle, $transactions ) = @_;
113 my $type = $handle->{Type} // '';
114  
115 # Driver handle: descend towards its database handles.
116 return( $transactions ) if( $type eq 'dr' );
117  
118 # Database handle: inspect it, but do not descend towards statements.
119 return if( $type ne 'db' );
120  
121 my $meta = $handle->{private_db_object};
122 if( ref( $meta ) eq 'HASH' && $meta->{transaction} )
123 {
124 if( $handle->{AutoCommit} )
125 {
126 $error = "DB::Object transaction metadata for connection ID '" . ( defined( $meta->{id} ) ? $meta->{id} : 'unknown' ) . "' indicates an active transaction, but DBI AutoCommit is enabled on handle '$handle'.";
127 return;
128 }
129  
130 push( @$transactions,
131 {
132 id => $meta->{id},
133 handle => $handle,
134 });
135 }
136 elsif( !$handle->{AutoCommit} )
137 {
138 $error = "DBI handle '$handle' has AutoCommit disabled, but is not marked as an active DB::Object transaction.";
139 }
140  
141 return;
142 }, $found );
143  
144 return( $self->error( $error ) ) if( defined( $error ) );
145 return( $found );
146 }
147  
148 sub allow_bulk_delete { return( shift->_set_get_scalar( 'allow_bulk_delete', @_ ) ); }
149  
150 sub allow_bulk_update { return( shift->_set_get_scalar( 'allow_bulk_update', @_ ) ); }
151  
152 sub ALL { return( shift->_operator_object_create( 'DB::Object::ALL', @_ ) ); }
153  
154 sub AND { return( shift->_operator_object_create( 'DB::Object::AND', @_ ) ); }
155  
156 sub ANY { return( shift->_operator_object_create( 'DB::Object::ANY', @_ ) ); }
157  
158 sub auto_convert_datetime_to_object { return( shift->_set_get_scalar( 'auto_convert_datetime_to_object', @_ ) ); }
159  
160 sub auto_decode_json { return( shift->_set_get_scalar( 'auto_decode_json', @_ ) ); }
161  
162 sub attribute($;$@)
163 {
164 my $self = shift( @_ );
165 # $h->{AttributeName} = ...; # set/write
166 # ... = $h->{AttributeName}; # get/read
167 # 1 means that the attribute may be modified
168 # 0 mneas that the attribute may only be read
169 my $name = shift( @_ ) if( @_ == 1 );
170 my %arg = ( @_ );
171 my %attr =
172 (
173 Active => 0,
174 ActiveKids => 0,
175 AutoCommit => 1,
176 AutoInactiveDestroy => 1,
177 CachedKids => 0,
178 Callbacks => 1,
179 ChildHandles => 0,
180 ChopBlanks => 1,
181 CompatMode => 1,
182 CursorName => 0,
183 ErrCount => 0,
184 Executed => 0,
185 FetchHashKeyName => 0,
186 HandleError => 1,
187 HandleSetErr => 1,
188 InactiveDestroy => 1,
189 Kids => 0,
190 LongReadLen => 1,
191 LongTruncOk => 1,
192 NAME => 0,
193 NULLABLE => 0,
194 NUM_OF_FIELDS => 0,
195 NUM_OF_PARAMS => 0,
196 Name => 0,
197 PRECISION => 0,
198 PrintError => 1,
199 PrintWarn => 1,
200 Profile => 0,
201 RaiseError => 1,
202 ReadOnly => 1,
203 RowCacheSize => 0,
204 RowsInCache => 0,
205 SCALE => 0,
206 ShowErrorStatement => 1,
207 Statement => 0,
208 TYPE => 0,
209 Taint => 1,
210 TaintIn => 1,
211 TaintOut => 1,
212 TraceLevel => 1,
213 Type => 0,
214 Warn => 1,
215 );
216 # Only those attribute exist
217 # Using an a non existing attribute produce an exception, so we better avoid
218 if( $name )
219 {
220 return( $self->{dbh}->{ $name } ) if( exists( $attr{ $name } ) );
221 }
222 else
223 {
224 my $value;
225 while( ( $name, $value ) = each( %arg ) )
226 {
227 # We intend to modifiy the value of an attribute
228 # we are allowed to modify this value if it is true
229 if( exists( $attr{ $name } ) &&
230 defined( $value ) &&
231 $attr{ $name } )
232 {
233 $self->{dbh}->{ $name } = $value;
234 }
235 }
236 }
237 }
238  
239 sub available_drivers(@)
240 {
241 # @ary = DBI->available_drivers( $quiet );
242 return( DBI->available_drivers(1) );
243 }
244  
245 sub base_class
246 {
247 my $self = shift( @_ );
248 my $this = @_ ? shift( @_ ) : $self;
249 my @supported_classes = $self->supported_class;
250 push( @supported_classes, 'DB::Object' );
251 my $ok_classes = CORE::join( '|', CORE::map{ CORE::quotemeta( $_ ) } @supported_classes );
252 my $class = ref( $this ) ? ref( $this ) : $this;
253 my $base_class = ( $class =~ /^($ok_classes)/ )[0];
254 return( $base_class );
255 }
256  
257 # This method is common to DB::Object and DB::Object::Statement
258 sub bind
259 {
260 my $self = shift( @_ );
261 # Usage:
262 # This activate the binding stuff
263 # $dbh->bind() or $dbh->bind->where( "something" ) or $dbh->bind->select->fetchrow_hashref();
264 # Later, $dbh->bind( 'thingy' )->select->fetchrow_hashref()
265 # When used like $table->bind; this means the user is setting the use bind option as a setting for all transactions, but
266 # when used like $table->bind->select then the use bind option is only used for this transaction only and is reset after
267 $self->{bind} = want('VOID')
268 ? 2
269 # Otherwise is it already set maybe?
270 : $self->{bind}
271 # Then use it
272 ? $self->{bind}
273 : 1;
274 if( @_ )
275 {
276 # If we are using the cache system, we search the object of this query
277 my $obj = $self;
278 $obj->{binded} = [ @_ ];
279 # Since new binded parameters have been passed, since mean a new request to the
280 # same statement is pending, so we need to re-execute the statement
281 # and since most of the fetch method rely on AUTOLOAD that call
282 # execute() automatically *IF* the statement was not already executed....
283 # we need to delete 'executed' value or set it to false, so the statement gets re-executed
284 $obj->{executed} = 0;
285 return( $obj );
286 }
287 return( $self );
288 }
289  
290 sub cache
291 {
292 my $self = shift( @_ );
293 # activate cache
294 # So we may be called as: $tbl->cache->select->fetchrow_hashref();
295 $self->{cache}++;
296 return( $self );
297 }
298  
299 sub cache_connections { return( shift->_set_get_boolean( 'cache_connections', @_ ) ); }
300  
301 sub cache_dir { return( shift->_set_get_scalar( 'cache_dir', @_ ) ); }
302  
303 sub cache_query { return( shift->_set_get_scalar( 'cache_query', @_ ) ); }
304  
305 sub cache_query_get
306 {
307 my $self = shift( @_ );
308 my $name = shift( @_ ) || return( $self->error( "No name for this query cache was provided." ) );
309 my $opts = $self->_get_args_as_hash( @_ );
310 my $base_class = $self->base_class;
311  
312 # Because we need the database object to revive the statement handler after having thawed it.
313 if( ref( $self ) ne $base_class )
314 {
315 return( $self->error( "This method must be called by the database object itself." ) );
316 }
317  
318 # Cannot be called without using a DB::Object
319 my $dbo = $self;
320 my $dbh = $self->{dbh};
321 my $cache_size = $dbo->cache_size // 0;
322 my $cache = $dbo->{cache};
323 # We want to know what kind of cache we are expected to use
324 my $cache_query = $opts->{cache_query} // $dbo->cache_query // 1;
325 my $cache_dir = $opts->{cache_dir} // $dbo->cache_dir // $self->sys_tmpdir;
326 my $ext = $opts->{extension} // 'bin';
327  
328 my $use_file_cache = ( defined( $cache_query ) && $cache_query eq 'file' ) ? 1 : 0;
329  
330 # Not a hard error
331 if( $cache_query !~ /^1|0|file$/ )
332 {
333 warn( "Unknown value for cache_query '$cache_query'" ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
334 }
335  
336 my $serialiser = $opts->{serialiser} || $self->serialiser || $DB::Object::SERIALISER || 'Storable';
337 # If the serialiser selected is the default one, and we have Sereal installed, we use it instead.
338 if( $serialiser eq 'Storable' && $self->_load_class( 'Sereal' ) )
339 {
340 $serialiser = 'Sereal';
341 }
342 $name = lc( $serialiser ) . "-${name}";
343  
344 # We make sure the extension passed to '_get_cache_filepath' is coherent with ours
345 my $cache_file = $self->_get_cache_filepath( %$opts, name => $name, extension => $ext, prefix => 'query' ) ||
346 return( $self->pass_error );
347 my $cache_key = $cache_file->basename( ".${ext}" );
348  
349 # NOTE: Ensure all classes are loaded before deserialising, so the deserialiser can call their THAW methods.
350 # This is especially important for Sereal, which needs classes to be defined when unmarshalling blessed objects.
351 $self->_load_class( 'Module::Generic', { force => 1 } ) || return( $self->pass_error );
352 $self->_load_class( 'Module::Generic::Array', { force => 1 } ) || return( $self->pass_error );
353 $self->_load_class( 'Module::Generic::Hash', { force => 1 } ) || return( $self->pass_error );
354 $self->_load_class( 'Module::Generic::Number', { force => 1 } ) || return( $self->pass_error );
355 $self->_load_class( 'Module::Generic::Scalar', { force => 1 } ) || return( $self->pass_error );
356  
357 # Need to ensure DB::Object::Statement is loaded, so the deserialisation of the statement object has a proper inheritance.
358 $self->_load_class( $base_class, { force => 1 } ) || return( $self->pass_error );
359 $self->_load_class( 'DB::Object::Query::Clause', { force => 1 } ) || return( $self->pass_error );
360 $self->_load_class( 'DB::Object::Query::Elements', { force => 1 } ) || return( $self->pass_error );
361 $self->_load_class( 'DB::Object::Query::Element', { force => 1 } ) || return( $self->pass_error );
362 $self->_load_class( 'DB::Object::Constraint::Check', { force => 1 } ) || return( $self->pass_error );
363 $self->_load_class( 'DB::Object::Constraint::Foreign', { force => 1 } ) || return( $self->pass_error );
364 $self->_load_class( 'DB::Object::Constraint::Index', { force => 1 } ) || return( $self->pass_error );
365 $self->_load_class( 'DB::Object::Statement', { force => 1 } ) || return( $self->pass_error );
366 $self->_load_class( "${base_class}::Query", { force => 1 } ) || return( $self->pass_error );
367 $self->_load_class( "${base_class}::Statement", { force => 1 } ) || return( $self->pass_error );
368 $self->_load_class( "${base_class}::Tables", { force => 1 } ) || return( $self->pass_error );
369 ( my $mod_path = "${base_class}::Statement" ) =~ s,::,/,g;
370 $mod_path .= '.pm';
371 my $lock;
372 my $repo = Module::Generic::Global->new( queries_cache => $base_class,
373 max_size => $cache_size,
374 serialiser => $serialiser,
375 key => $cache_key,
376 ) || return( $self->pass_error( Module::Generic::Global->error ) );
377 # The lock gets removed automatically when it gets out of scope, so we store it in $lock
378 $lock = $repo->lock;
379 local $@;
380 my $sth = eval{ $repo->get };
381 # The deserialisation of the in-memory object died, most likely in the THAW, and maybe due to a serialisation version mismatch
382 if( !$sth && $@ )
383 {
384 if( $@ =~ /Serialisation[[:blank:]]+version[[:blank:]]+mismatch/i )
385 {
386 # We just warn, and since no object has been deserialise, we will return nothing, thus leading the caller to create a fresh object.
387 warn( $@ );
388 }
389 elsif( $self->_is_object( $@ ) )
390 {
391 return( $self->pass_error( $@ ) );
392 }
393 else
394 {
395 return( $self->error( "Unable to deserialise in-memory statement object: $@" ) );
396 }
397 }
398  
399  
400 if( !$sth && $cache_query eq 'file' )
401 {
402 if( !$cache_file->exists ||
403 !$cache_file->is_file ||
404 $cache_file->is_empty )
405 {
406 return( '' );
407 }
408 $sth = eval{
409 $self->Module::Generic::deserialise(
410 file => $cache_file,
411 lock => 1,
412 serialiser => $serialiser,
413 );
414 };
415 if( !$sth )
416 {
417 # A fatal exception occurred in the THAW hook maybe?
418 if( $@ )
419 {
420 if( $@ =~ /Serialisation[[:blank:]]+version[[:blank:]]+mismatch/i )
421 {
422 # We just warn, and since no object has been deserialise, we will return nothing, thus leading the caller to create a fresh object.
423 warn( $@ );
424 }
425 elsif( $self->_is_object( $@ ) )
426 {
427 return( $self->pass_error( $@ ) );
428 }
429 else
430 {
431 return( $self->error( "Unable to deserialise in-memory statement object: $@" ) );
432 }
433 }
434 else
435 {
436 return( $self->pass_error );
437 }
438 }
439 $repo->set( $sth ) || return( $self->pass_error( $repo->error ) );
440 }
441  
442 # No statement object found, so we return empty, but not undefined, which is reserved for errors.
443 if( !$sth )
444 {
445 return( '' );
446 }
447  
448 unless( $self->_is_a( $sth => "${base_class}::Statement" ) )
449 {
450 $repo->unlock if( $repo );
451 die( "Statement object found (", $self->_str_val( $sth ), ") in this statement object is actually not a statement object (${base_class}::Statement) !" );
452 }
453  
454 # my $sth_class = ref( $sth );
455 # if( !$self->_load_class( $sth_class ) )
456 # {
457 # $repo->unlock if( $repo );
458 # return( $self->pass_error );
459 # }
460 # my $sth_base_class = $dbo->base_class( $sth_class );
461 # if( !$self->_load_class( "${sth_base_class}::Query" ) )
462 # {
463 # $repo->unlock if( $repo );
464 # return( $self->pass_error );
465 # }
466 # if( !$self->_load_class( "${sth_base_class}::Tables" ) )
467 # {
468 # $repo->unlock if( $repo );
469 # return( $self->pass_error );
470 # }
471 # bless( $sth => $sth_class );
472 # Detect "zombie" DBI handles (blessed but no magic) without leaking warnings
473 my $dbh_ok = 0;
474 if( $dbh && ref( $dbh ) =~ /^DBI::db\b/ )
475 {
476 local $SIG{__WARN__} = sub
477 {
478 die( $_[0] );
479 };
480 local $@;
481 $dbh_ok = eval
482 {
483 $dbh->ping ? 1 : 0;
484 };
485 $dbh_ok = 0 if( !$dbh_ok || $@ );
486 }
487  
488 if( !$dbh_ok )
489 {
490 $dbh = $self->_dbi_connect;
491 if( !$dbh )
492 {
493 $repo->unlock if( $repo );
494 return( $self->pass_error );
495 }
496 $dbo->{dbh} = $dbh;
497 }
498  
499 $sth->debug( $self->debug );
500 # We reattach the database object to that statement
501 if( !$sth->attach( $dbo ) )
502 {
503 $repo->unlock if( $repo );
504 return( $self->pass_error( $sth->error ) );
505 }
506 my $query = $sth->as_string;
507 if( !defined( $query ) || !CORE::length( $query ) )
508 {
509 $repo->unlock if( $repo );
510 return( $self->error( "No SQL query string could be found." ) );
511 }
512 my $prepare_options = {};
513 if( my $q = $sth->query_object )
514 {
515 $prepare_options = $q->prepare_options->as_hash;
516 }
517  
518 local $@;
519 my $sth_dbi = eval
520 {
521 $dbh->prepare( $query, ( scalar( keys( %$prepare_options ) ) ? $prepare_options : () ) );
522 };
523  
524 if( $@ )
525 {
526 $repo->unlock if( $repo );
527 return( $self->error( "Error preparing cached SQL query: $@\nQuery was:\n$query" ) );
528 }
529 elsif( !$sth_dbi )
530 {
531 $repo->unlock if( $repo );
532 my $err = ( $self->{dbh}->errstr() || 'unknown DBI error' );
533 return( $self->error( "Error while trying to prepare query: ${err}\nQuery was:\n$query" ) );
534 }
535  
536 $sth->{sth} = $sth_dbi;
537  
538 $repo->unlock if( $repo );
539 return( $sth );
540 }
541  
542 sub cache_query_set
543 {
544 my $self = shift( @_ );
545 my $name = shift( @_ ) || return( $self->error( "No name for this query cache was provided." ) );
546 my $sth = shift( @_ ) || return( $self->error( "No statement handler was provided." ) );
547 my $opts = $self->_get_args_as_hash( @_ );
548 my $base_class = $self->base_class;
549  
550 # Because we need the database object to revive the statement handler after having thawed it.
551 if( ref( $self ) ne $base_class )
552 {
553 return( $self->error( "This method must be called by the database object itself." ) );
554 }
555  
556 # Cannot be called without using a DB::Object
557 my $dbo = $self;
558 my $cache_size = $dbo->cache_size // 0;
559 my $cache = $dbo->{cache};
560 # We want to know what kind of cache we are expected to use
561 my $cache_query = $opts->{cache_query} // $dbo->cache_query // 1;
562 my $cache_dir = $opts->{cache_dir} // $dbo->cache_dir // $self->sys_tmpdir;
563 my $ext = $opts->{extension} // 'bin';
564  
565 my $use_file_cache = ( defined( $cache_query ) && $cache_query eq 'file' ) ? 1 : 0;
566  
567 # Not a hard error
568 if( $cache_query !~ /^1|0|file$/ )
569 {
570 warn( "Unknown value for cache_query '$cache_query'" ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
571 }
572  
573 my $serialiser = $opts->{serialiser} || $self->serialiser || $DB::Object::SERIALISER || 'Storable';
574 # If the serialiser selected is the default one, and we have Sereal installed, we use it instead.
575 if( $serialiser eq 'Storable' && $self->_load_class( 'Sereal' ) )
576 {
577 $serialiser = 'Sereal';
578 }
579 $name = lc( $serialiser ) . "-${name}";
580  
581 # We make sure the extension passed to '_get_cache_filepath' is coherent with ours
582 my $cache_file = $self->_get_cache_filepath( %$opts, name => $name, extension => $ext, prefix => 'query' ) ||
583 return( $self->pass_error );
584 my $cache_key = $cache_file->basename( ".${ext}" );
585  
586 my $lock;
587 my $repo = Module::Generic::Global->new( queries_cache => $base_class,
588 max_size => $cache_size,
589 serialiser => $serialiser,
590 key => $cache_key,
591 ) || return( $self->pass_error( Module::Generic::Global->error ) );
592 # The lock gets removed automatically when it gets out of scope, so we store it in $lock
593 $lock = $repo->lock;
594  
595 if( $cache_query eq 'file' )
596 {
597 # If it is already there, we return immediately. There is nothing more to do.
598 if( $cache_file->exists &&
599 !$cache_file->is_file )
600 {
601 return( $self->error( "There already existing a cache file $cache_file, but it is not a file!" ) );
602 }
603 if( $cache_file->exists &&
604 $cache_file->is_file &&
605 !$cache_file->is_empty )
606 {
607 return( $sth );
608 }
609 $self->Module::Generic::serialise( $sth,
610 file => $cache_file,
611 lock => 1,
612 serialiser => $serialiser,
613 ( $serialiser eq 'Sereal' ? ( freeze_callbacks => 1 ) : () ),
614 ) || return( $self->pass_error );
615 }
616 elsif( $cache_query )
617 {
618 $repo->set( $sth );
619 $repo->unlock;
620 }
621 return( $sth );
622 }
623  
624 sub cache_size { return( shift->_set_get_scalar( 'cache_size', @_ ) ); }
625  
626 sub cache_table { return( shift->_set_get_scalar( 'cache_table', @_ ) ); }
627  
628 sub cache_tables { return( shift->_set_get_object( 'cache_tables', 'DB::Object::Cache::Tables', @_ ) ); }
629  
630 sub check_driver()
631 {
632 my $self = shift( @_ );
633 my $driver = shift( @_ ) || return( $self->error( "No SQL driver provided to check" ) );
634 my $ok = undef();
635 local $_;
636 my @drivers = $self->available_drivers();
637 foreach( @drivers )
638 {
639 if( m/$driver/s )
640 {
641 $ok++;
642 last;
643 }
644 }
645 return( $ok );
646 }
647  
648 sub connect
649 {
650 my $this = shift( @_ );
651 my $class = ref( $this ) || $this;
652 my $base_class = $this->base_class;
653 my $opts = $this->_get_args_as_hash( @_ );
654 # We pass the arguments so that debug and other init parameters can be set early
655 my $that = ref( $this ) ? $this : $this->Module::Generic::new( debug => $opts->{debug} );
656 my $param = $that->_connection_params2hash( $opts ) || return( $this->error( "No valid connection parameters found" ) );
657 $param = $that->_connection_params2hash_driver( $param );
658 my $driver2pack =
659 {
660 mysql => 'DB::Object::Mysql',
661 Pg => 'DB::Object::Postgres',
662 SQLite => 'DB::Object::SQLite',
663 };
664 my $pack2driver = +{ map{ $driver2pack->{ $_ } => $_ } keys( %$driver2pack ) };
665 my $driver_class;
666 if( exists( $param->{driver} ) )
667 {
668 if( !exists( $driver2pack->{ $param->{driver} } ) )
669 {
670 return( $this->error( "Driver $param->{driver} is not supported." ) );
671 }
672 # For example, will make this object a DB::ObjectD::Postgres object
673 $driver_class = $driver2pack->{ $param->{driver} };
674 my $driver_module = $driver_class;
675 $driver_module =~ s|::|/|g;
676 $driver_module .= '.pm';
677 eval
678 {
679 local $DEBUG;
680 require $driver_module;
681 };
682 return( $this->error( "Unable to load module $driver_class ($driver_module): $@" ) ) if( $@ );
683 }
684 elsif( exists( $pack2driver->{ $base_class } ) )
685 {
686 $driver_class = $base_class;
687 $param->{driver} = $pack2driver->{ $base_class };
688 }
689 else
690 {
691 return( $this->error( "No driver was provided." ) );
692 }
693 my $self = $driver_class->new || return( $this->error( "Cannot get object from package $driver_class" ) );
694 $self->debug(
695 CORE::exists( $param->{debug} )
696 ? CORE::delete( $param->{debug} )
697 : CORE::exists( $param->{Debug} )
698 ? CORE::delete( $param->{Debug} )
699 : $DEBUG
700 );
701 # Needed to be specified if the user does not want to cache connections
702 # Will be used in _dbi_connect()
703 $self->cache_connections( CORE::delete( $param->{cache_connections} ) ) if( CORE::exists( $param->{cache_connections} ) );
704 $self->connect_via( CORE::delete( $param->{connect_via} ) ) if( CORE::exists( $param->{connect_via} ) );
705 $self->cache_dir(
706 CORE::exists( $param->{cache_dir} )
707 ? CORE::delete( $param->{cache_dir} )
708 : CORE::exists( $that->{cache_dir} )
709 ? $that->{cache_dir}
710 : $CACHE_DIR
711 );
712  
713 if( CORE::exists( $param->{cache_table} ) && defined( $param->{cache_table} ) )
714 {
715 $self->cache_table( CORE::delete( $param->{cache_table} ) );
716 }
717 elsif( CORE::exists( $that->{cache_table} ) && defined( $that->{cache_table} ) )
718 {
719 $self->cache_table( $that->{cache_table} );
720 }
721  
722 if( CORE::exists( $param->{cache_query} ) && defined( $param->{cache_query} ) )
723 {
724 $self->cache_query( CORE::delete( $param->{cache_query} ) );
725 }
726 elsif( CORE::exists( $that->{cache_query} ) && defined( $that->{cache_query} ) )
727 {
728 $self->cache_query( $that->{cache_query} );
729 }
730  
731 if( CORE::exists( $param->{cache_size} ) && defined( $param->{cache_size} ) )
732 {
733 $self->cache_size( $param->{cache_size} );
734 }
735 elsif( CORE::exists( $that->{cache_size} ) && defined( $that->{cache_size} ) )
736 {
737 $self->cache_size( $that->{cache_size} );
738 }
739  
740 if( CORE::exists( $param->{use_cache} ) )
741 {
742 $self->{cache} = CORE::delete( $param->{use_cache} );
743 }
744 elsif( CORE::exists( $param->{cache} ) )
745 {
746 $self->{cache} = CORE::delete( $param->{cache} );
747 }
748 else
749 {
750 $self->{cache} = $USE_CACHE;
751 }
752  
753 if( CORE::exists( $param->{serialiser} ) )
754 {
755 $self->{serialiser} = CORE::delete( $param->{serialiser} );
756 }
757 elsif( CORE::exists( $param->{serializer} ) )
758 {
759 $self->{serialiser} = CORE::delete( $param->{serializer} );
760 }
761 else
762 {
763 $self->{serialiser} = $SERIALISER;
764 }
765  
766 my $id = CORE::exists( $param->{id} ) ? CORE::delete( $param->{id} ) : undef;
767 if( defined( $id ) && CORE::length( $id ) )
768 {
769 $self->id( $id );
770 }
771 else
772 {
773 $self->id( $self->_new_connection_id );
774 }
775  
776 $self->{unknown_field} = CORE::delete( $param->{unknown_field} ) if( CORE::exists( $param->{unknown_field} ) );
777  
778 # Other remaining params, we check if they are supported with a corresponding method
779 # We do all this jazz so we can handle other parameters a bit more dynamically.
780 foreach my $key ( keys( %$param ) )
781 {
782 # Those are special, and are dealt with a bit later
783 if( $key eq 'opt' ||
784 $key eq 'database' ||
785 $key eq 'db' ||
786 $key eq 'host' ||
787 $key eq 'server' ||
788 $key eq 'login' ||
789 $key eq 'passwd' ||
790 $key eq 'driver' ||
791 $key eq 'use_bind' )
792 {
793 next;
794 }
795 if( my $coderef = $self->can( $key ) )
796 {
797 $coderef->( $self, CORE::delete( $param->{ $key } ) );
798 }
799 }
800  
801 $param = $self->_check_connect_param( $param ) || return( $this->pass_error( $self->error ) );
802 my $opt = {};
803 if( exists( $param->{opt} ) )
804 {
805 $opt = CORE::delete( $param->{opt} );
806 $opt = $self->_check_default_option( $opt );
807 }
808 # print( STDERR ref( $self ), "::connect(): \$param is: ", $self->dumper( $param ), "\n" );
809 $self->{database} = CORE::exists( $param->{database} )
810 ? CORE::delete( $param->{database} )
811 : CORE::exists( $param->{db} )
812 ? CORE::delete( $param->{db} )
813 : undef();
814 $self->{host} = CORE::exists( $param->{host} )
815 ? CORE::delete( $param->{host} )
816 : CORE::exists( $param->{server} )
817 ? CORE::delete( $param->{server} )
818 : undef();
819 $self->{port} = CORE::delete( $param->{port} );
820 # $self->{database} = CORE::delete( $param->{ 'db' } );
821 $self->{login} = CORE::delete( $param->{login} );
822 $self->{passwd} = CORE::delete( $param->{passwd} );
823 $self->{driver} = CORE::delete( $param->{driver} );
824 $self->{bind} = CORE::exists( $param->{use_bind} )
825 ? CORE::delete( $param->{use_bind} )
826 : $USE_BIND;
827  
828 # If parameters starting with an upper case are provided, they are DBI database parameters
829 #my @dbi_opts = grep( /^[A-Z][a-zA-Z]+/, keys( %$param ) );
830 #@$opt{ @dbi_opts } = @$param{ @dbi_opts };
831  
832  
833 if( my $driver = $self->driver )
834 {
835 local $@;
836 my $drh = eval {
837 DBI->install_driver( $driver )
838 } || return( $this->error( $@ || $DBI::errstr ) );
839 $self->{drh} = $drh;
840 }
841 $opt->{RaiseError} = 0 if( !CORE::exists( $opt->{RaiseError} ) );
842 $opt->{AutoCommit} = 1 if( !CORE::exists( $opt->{AutoCommit} ) );
843 $opt->{PrintError} = 0 if( !CORE::exists( $opt->{PrintError} ) );
844 $self->{opt} = $opt;
845 my $dbh = $self->_dbi_connect || return( $this->pass_error( $self->error ) );
846 # This is possibly a Apache::DBI::db object
847 $self->{dbh} = $dbh;
848 #$self->param(
849 # ## Do not allow SELECT that will take too long or too much resource, i.e. over 2Gb of data
850 # ## This is idiot proof mode
851 # 'SQL_BIG_SELECTS' => 0,
852 # ## SQL will abort if a DELETE or UPDATE is being executed w/o LIMIT nor WHERE clause
853 # 'SQL_SAFE_MODE' => 1,
854 #);
855 local $/ = "\n";
856 my $tables = [];
857 # 1 day
858 # my $tbl_cache_timeout = 86400;
859 my $host = $self->host || 'localhost';
860 my $port = $self->port || 0;
861 my $driver = $self->driver;
862 my $database = $self->database;
863 my $cache_params = {};
864 if( my $cache_dir = $self->cache_dir )
865 {
866 $cache_params->{cache_dir} = $cache_dir;
867 }
868 $cache_params->{debug} = $self->debug;
869 my $cache_tables = DB::Object::Cache::Tables->new( $cache_params );
870 $self->cache_tables( $cache_tables );
871 $tables = $self->tables_info;
872 my $cache =
873 {
874 host => $host,
875 driver => $driver,
876 port => $port,
877 database => $database,
878 tables => $tables,
879 };
880 if( !defined( $cache_tables->set( $cache ) ) )
881 {
882 warn( "Unable to write to tables cache: ", $cache_tables->error, "\n" );
883 }
884 return( $self );
885 }
886  
887 sub connect_via { return( shift->_set_get_scalar( 'connect_via', @_ ) ); }
888  
889 sub constant_queries_cache_get
890 {
891 my( $self, $def ) = @_;
892 my $base_class = $self->base_class;
893  
894 # Because we need the database object to revive the statement handler after having thawed it.
895 if( ref( $self ) ne $base_class )
896 {
897 return( $self->error( "This method must be called by the database object itself." ) );
898 }
899  
900 my $dbo = $self;
901 my $cache_size = $dbo->cache_size // 0;
902  
903 if( !defined( $def ) || ref( $def // '' ) ne 'HASH' )
904 {
905 return( $self->error( "Parameter provided must be a hash, but I got '", $self->_str_val( $def // 'undef' ), "'." ) );
906 }
907  
908 foreach my $k ( qw( pack file line ) )
909 {
910 return( $self->error( "Parameter \"$k\" is missing from the hash." ) )
911 if( !defined( $def->{ $k } ) || !CORE::length( $def->{ $k } // '' ) );
912 }
913  
914 my $cache_key = CORE::join( '|', @$def{qw( pack file line )} );
915 my $serialiser = CORE::delete( $def->{serialiser} ) || $DB::Object::SERIALISER || 'Storable';
916  
917 my $lock;
918 my $repo = Module::Generic::Global->new( queries_cache => $base_class,
919 max_size => $cache_size,
920 serialiser => $serialiser,
921 key => $cache_key,
922 ) || return( $self->pass_error( Module::Generic::Global->error ) );
923 $repo->lock;
924  
925 my $store = $repo->get;
926 return( '' ) if( !$store );
927  
928 # $ts is thee timestamp of the file recorded at the time
929 my $ts = $store->{ts} || return( $self->error( "No timestamp set in this constant statement object." ) );
930 my $sth = $repo->{sth} || return( '' );
931 # A DB::Object::Statement object
932 my $qo = $sth->query_object;
933 return( '' ) if( !CORE::length( $def->{file} ) );
934 return( '' ) if( !-e( $def->{file} ) );
935 return( '' ) if( ( CORE::stat( $def->{file} ) )[9] != $ts );
936 return( $self->error( "Query object retrieved from constant query cache is void!" ) ) if( !$qo );
937 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' ) );
938 return if( $self->database ne $qo->database_object->database );
939  
940 return( $sth );
941 }
942  
943 sub constant_queries_cache_set
944 {
945 my( $self, $def ) = @_;
946 my $base_class = $self->base_class;
947  
948 # Because we need the database object to revive the statement handler after having thawed it.
949 if( ref( $self ) ne $base_class )
950 {
951 return( $self->error( "This method must be called by the database object itself." ) );
952 }
953  
954  
955 if( !defined( $def ) || ref( $def // '' ) ne 'HASH' )
956 {
957 return( $self->error( "Parameter provided must be a hash, but I got '", $self->_str_val( $def // 'undef' ), "'." ) );
958 }
959  
960 foreach my $k ( qw( pack file line ) )
961 {
962 if( !defined( $def->{ $k } ) || !CORE::length( $def->{ $k } // '' ) )
963 {
964 return( $self->error( "Parameter \"$k\" is missing from the hash." ) );
965 }
966 }
967  
968 my $dbo = $self;
969 my $cache_size = $dbo->cache_size // 0;
970  
971 return( $self->error( "Parameter \"query_object\" is missing from the hash." ) )
972 if( !defined( $def->{query_object} ) );
973  
974 if( !$self->_is_object( $def->{query_object} ) ||
975 !$def->{query_object}->isa( 'DB::Object::Query' ) )
976 {
977 return( $self->error( "Provided query object is not a DB::Object::Query." ) );
978 }
979  
980 $def->{ts} = [CORE::stat( $def->{file} )]->[9];
981  
982 my $cache_key = CORE::join( '|', @$def{qw( pack file line )} );
983 my $serialiser = CORE::delete( $def->{serialiser} ) || $DB::Object::SERIALISER || 'Storable';
984  
985 my $repo = Module::Generic::Global->new( queries_cache => $base_class,
986 max_size => $cache_size,
987 serialiser => $serialiser,
988 key => $cache_key,
989 ) || return( $self->pass_error( Module::Generic::Global->error ) );
990 $repo->lock;
991 $repo->set( $def ) || return( $self->pass_error( $repo->error ) );
992  
993 return( $def );
994 }
995  
996 sub constant_queries_cache_del
997 {
998 my( $self, $def ) = @_;
999 my $base_class = $self->base_class;
1000  
1001 # Because we need the database object to revive the statement handler after having thawed it.
1002 if( ref( $self ) ne $base_class )
1003 {
1004 return( $self->error( "This method must be called by the database object itself." ) );
1005 }
1006  
1007 if( !defined( $def ) || ref( $def // '' ) ne 'HASH' )
1008 {
1009 return( $self->error( "Parameter provided must be a hash, but I got '", $self->_str_val( $def // 'undef' ), "'." ) );
1010 }
1011  
1012 foreach my $k ( qw( pack file line ) )
1013 {
1014 return( $self->error( "Parameter \"$k\" is missing from the hash." ) )
1015 if( !defined( $def->{ $k } ) || !CORE::length( $def->{ $k } // '' ) );
1016 }
1017  
1018 my $dbo = $self;
1019 my $cache_size = $dbo->cache_size // 0;
1020 my $cache_key = CORE::join( '|', @$def{qw( pack file line )} );
1021 my $serialiser = CORE::delete( $def->{serialiser} ) || $DB::Object::SERIALISER || 'Storable';
1022  
1023 my $repo = Module::Generic::Global->new( queries_cache => $base_class,
1024 max_size => $cache_size,
1025 serialiser => $serialiser,
1026 key => $cache_key,
1027 ) || return( $self->pass_error( Module::Generic::Global->error ) );
1028 $repo->lock;
1029 $repo->remove;
1030 $repo->unlock;
1031 return(1);
1032 }
1033  
1034 # See also datatype_to_constant()
1035 sub constant_to_datatype
1036 {
1037 my $self = shift( @_ );
1038 return unless( scalar( @_ ) && defined( $_[0] ) );
1039 my $this = shift( @_ );
1040 my $ref = $self->datatypes;
1041 foreach my $t ( keys( %$ref ) )
1042 {
1043 return( $t ) if( $ref->{ $t } eq $this );
1044 }
1045 return;
1046 }
1047  
1048 sub copy
1049 {
1050 my $self = shift( @_ );
1051 my $opts = $self->_get_args_as_hash( @_ );
1052 my $ref = $self->select->fetchrow_hashref();
1053 my $keys = keys( %$opts );
1054 @$ref{ @$keys } = @$opts{ @$keys };
1055 return(0) if( !scalar( keys( %$ref ) ) );
1056 $self->insert( $ref );
1057 return(1);
1058 }
1059  
1060 sub create_db { return( shift->error( "The driver has not implemented the create database method create_db." ) ); }
1061  
1062 sub create_table { return( shift->error( "The driver has not implemented the create table method create_table." ) ); }
1063  
1064 sub data_sources($;\%)
1065 {
1066 my $self = shift( @_ );
1067 my $opts = $self->_get_args_as_hash( @_ );
1068 my $driver = $self->{driver} || return( $self->error( "No driver to to use to check for data sources." ) );
1069 return( DBI->data_sources( $driver, ( scalar( keys( %$opts ) ) ? $opts : () ) ) );
1070 }
1071  
1072 sub data_type
1073 {
1074 my $self = shift( @_ );
1075 my $type = @_ == 1 ? shift( @_ ) : [ @_ ] if( @_ );
1076 my $ref = eval
1077 {
1078 local $SIG{__DIE__} = sub{ };
1079 local $SIG{__WARN__} = sub{ };
1080 $self->{dbh}->type_info_all();
1081 };
1082 return( $self->error( "type_info_all() is unsupported by vendor '$self->{ 'driver' }'." ) ) if( $@ );
1083 # First item is a reference to hash containing the order of the header
1084 my $header = shift( @$ref );
1085 my $hash = {};
1086 my $name_idx = $header->{TYPE_NAME};
1087 my @found = ();
1088 if( $type )
1089 {
1090 my @types = ref( $type ) ? @$type : ( $type );
1091 foreach my $requested ( @types )
1092 {
1093 push( @found, grep{ uc( $requested ) eq $_->[ $name_idx ] } @$ref );
1094 }
1095 }
1096 else
1097 {
1098 @found = @$ref;
1099 }
1100 # Stop. No need to go further
1101 return( wantarray() ? () : undef() ) if( !@found );
1102 my @names = map{ lc( $_ ) } keys( %$header );
1103 my $len = scalar( keys( %$header ) );
1104 my @order = values( %$header );
1105 map
1106 {
1107 next if( @$_ != $len );
1108 my %data;
1109 @data{ @names } = @{ $_ }[ @order ];
1110 $hash->{ lc( $_->[ $name_idx ] ) } = \%data;
1111 } @found;
1112 return( wantarray() ? () : undef() ) if( !%$hash );
1113 return( wantarray() ? %$hash : $hash );
1114 }
1115  
1116 sub database
1117 {
1118 # Read only
1119 return( shift->{database} );
1120 }
1121  
1122 sub databases { return( shift->error( "Method databases() is not implemented by driver." ) ); }
1123  
1124 sub datatype_dict
1125 {
1126 my $self = shift( @_ );
1127 my $class = ( ref( $self ) || $self );
1128 no strict 'refs';
1129 my $sym = $self->_get_symbol( $class => '$DATATYPES_DICT' );
1130 if( !defined( $sym ) )
1131 {
1132 return( $self->pass_error ) if( $self->error );
1133 return( $self->error( "No global variable \$DATATYPES_DICT defined in class $class" ) );
1134 }
1135 my $dict = $$sym;
1136 return( $self->error( "Symbol found for \$DATATYPES_DICT in class $class did not resolve into an expecxted hash reference." ) ) if( ref( $dict ) ne 'HASH' );
1137 if( @_ )
1138 {
1139 return( $dict->{ lc( shift( @_ ) ) } );
1140 }
1141 return( $dict );
1142 }
1143  
1144 # See also constant_to_datatype()
1145 sub datatype_to_constant
1146 {
1147 my $self = shift( @_ );
1148 my $ref = $self->datatypes || return( $self->pass_error );
1149 return unless( scalar( @_ ) && defined( $_[0] ) );
1150 return( $ref->{ lc( shift( @_ ) ) } );
1151 }
1152  
1153 # Returns an hash of SQL constant name to its value
1154 sub datatypes
1155 {
1156 my $self = shift( @_ );
1157 my $dict = $self->datatype_dict || return( $self->pass_error );
1158 my $ref = +{ map{ $_ => $dict->{ $_ }->{constant} } keys( %$dict ) };
1159 return( $ref );
1160 }
1161  
1162 sub disconnect($)
1163 {
1164 my $self = shift( @_ );
1165 # my( $pack, $file, $line ) = caller();
1166 # print( STDERR "disconnect() called from package '$pack' in file '$file' at line '$line'.\n" );
1167 my $rc = $self->{dbh}->disconnect( @_ );
1168 return( $rc );
1169 }
1170  
1171 sub do($;$@)
1172 {
1173 my $self = shift( @_ );
1174 # $rc = $dbh->do( $statement ) || die( $dbh->errstr );
1175 # $rc = $dbh->do( $statement, \%attr ) || die( $dbh->errstr );
1176 # $rv = $dbh->do( $statement, \%attr, @bind_values ) || ...
1177 # my( $rows_deleted ) = $dbh->do(
1178 # q{
1179 # DELETE FROM table WHERE status = ?
1180 # }, undef(), 'DONE' ) || die( $dbh->errstr );
1181 my $query = shift( @_ );
1182 my $opt_ref = shift( @_ ) || undef();
1183 my $param_ref = shift( @_ ) || [];
1184 my $dbh = $self->can( 'database_object' ) ? $self->database_object : $self;
1185 $dbh or return( $self->error( "Could not find database handler." ) );
1186 my $sth = $dbh->prepare( $query, $opt_ref ) ||
1187 return( $self->error( "Error while preparing do query:\n$query", $dbh->errstr() ) );
1188 $sth->execute( @$param_ref ) ||
1189 return( $self->error( "Error while executing do query:\n$query", $sth->errstr() ) );
1190 # my $rows = $sth->rows();
1191 # return( ( $rows == 0 ) ? "0E0" : $rows );
1192 return( $sth );
1193 }
1194  
1195 sub driver { return( shift->_set_get( 'driver' ) ); }
1196  
1197 sub enhance
1198 {
1199 my $self = shift( @_ );
1200 my $prev = $self->{enhance};
1201 $self->{enhance} = shift( @_ ) if( @_ );
1202 return( $prev );
1203 }
1204  
1205 sub err(@)
1206 {
1207 my $self = shift( @_ );
1208 # $rv = $h->err;
1209 if( defined( $self->{sth} ) )
1210 {
1211 return( $self->{sth}->err() );
1212 }
1213 elsif( $self->{dbh} )
1214 {
1215 return( $self->{dbh}->err() );
1216 }
1217 #else
1218 #{
1219 # return( $self->{ 'drh' }->err() );
1220 # return( DBI::err();
1221 #}
1222 }
1223  
1224 sub errno
1225 {
1226 goto( &err );
1227 }
1228  
1229 sub errmesg
1230 {
1231 goto( &errstr );
1232 }
1233  
1234 sub errstr(@)
1235 {
1236 my $self = shift( @_ );
1237 if( !ref( $self ) )
1238 {
1239 return( $DBI::errstr );
1240 }
1241 elsif( defined( $self->{sth} ) && $self->{sth}->errstr() )
1242 {
1243 return( $self->{sth}->errstr() );
1244 }
1245 elsif( defined( $self->{dbh} ) && $self->{dbh}->errstr() )
1246 {
1247 return( $self->{dbh}->errstr() );
1248 }
1249 else
1250 {
1251 return( $self->{errstr} );
1252 }
1253 }
1254  
1255 sub FALSE { return( 'FALSE' ); }
1256  
1257 sub fatal
1258 {
1259 my $self = shift( @_ );
1260 if( @_ )
1261 {
1262 $self->{fatal} = int( shift( @_ ) );
1263 }
1264 return( $self->{fatal} );
1265 }
1266  
1267 sub get_sql_type { return( shift->error( "The driver has not provided support for this method get_sql_type()" ) ); }
1268  
1269 sub host { return( shift->_set_get_scalar( 'host', @_ ) ); }
1270  
1271 sub id { return( shift->_set_get_scalar( 'id', @_ ) ); }
1272  
1273 sub IN { return( shift->_operator_object_create( 'DB::Object::IN', @_ ) ); }
1274  
1275 # $rv = $dbh->last_insert_id($catalog, $schema, $table, $field, \%attr);
1276 sub last_insert_id
1277 {
1278 my $self = shift( @_ );
1279 return( $self->error( "Method \"last_insert_id\" has not been implemented by driver $self->{driver} (object = $self)." ) );
1280 }
1281  
1282 sub LIKE { return( shift->_operator_object_create( 'DB::Object::LIKE', @_ ) ); }
1283  
1284 sub lock
1285 {
1286 my $self = shift( @_ );
1287 return( $self->error( "Method \"lock\" has not been implemented by driver $self->{driver} (object = $self)." ) );
1288 }
1289  
1290 sub login { return( shift->_set_get_scalar( 'login', @_ ) ); }
1291  
1292 # This value will be passed on to newly instantiated DB::Object::Tables objects
1293 sub no_bind { return( shift->_set_get_boolean( 'no_bind', @_ ) ); }
1294  
1295 sub no_cache
1296 {
1297 my $self = shift( @_ );
1298 $self->{cache} = 0;
1299 return( $self );
1300 }
1301  
1302 sub NOT { return( shift->_operator_object_create( 'DB::Object::NOT', @_ ) ); }
1303  
1304 sub NULL { return( 'NULL' ); }
1305  
1306 sub OR { return( shift->_operator_object_create( 'DB::Object::OR', @_ ) ); }
1307  
1308 sub P { return( shift->placeholder( @_ ) ); }
1309  
1310 sub param
1311 {
1312 my $self = shift( @_ );
1313 return if( !@_ );
1314 my @supported =
1315 qw(
1316 SQL_AUTO_IS_NULL AUTOCOMMIT SQL_BIG_TABLES SQL_BIG_SELECTS
1317 SQL_BUFFER_RESULT SQL_LOW_PRIORITY_UPDATES SQL_MAX_JOIN_SIZE
1318 SQL_SAFE_MODE SQL_SELECT_LIMIT SQL_LOG_OFF SQL_LOG_UPDATE
1319 TIMESTAMP INSERT_ID LAST_INSERT_ID
1320 );
1321 my $params = $self->{params} ||= {};
1322 if( @_ == 1 )
1323 {
1324 my $type = shift( @_ );
1325 $type = uc( $type ) if( scalar( grep{ /^$type$/i } @supported ) );
1326 return( $params->{ $type } );
1327 }
1328 else
1329 {
1330 my %arg = ( @_ );
1331 my( $type, $value );
1332 my @query = ();
1333 while( ( $type, $value ) = each( %arg ) )
1334 {
1335 my @found = grep{ /^(SQL_)?$type$/i } @supported;
1336 # SQL parameter
1337 if( scalar( @found ) )
1338 {
1339 $type = uc( $type );
1340 $value = 0 if( !defined( $value ) || $value eq '' );
1341 $params->{ $type } = $value;
1342 if( $type eq 'AUTOCOMMIT' && $self->{dbh} && $value =~ /^(?:1|0)$/ )
1343 {
1344 $self->{dbh}->{AutoCommit} = $value;
1345 }
1346 push( @query, "$type = $value" );
1347 }
1348 # Private parameter - May be anything
1349 else
1350 {
1351 $params->{ $type } = $value;
1352 }
1353 }
1354 return( $self ) if( !scalar( @query ) );
1355 my $dbh = $self->{dbh} || return( $self->error( "Could not find database handler." ) );
1356 my $query = 'SET ' . CORE::join( ', ', @query );
1357 my $sth = $dbh->prepare( $query ) ||
1358 return( $self->error( "Unable to set options '", CORE::join( ', ', @query ), "'" ) );
1359 $sth->execute();
1360 $sth->finish();
1361 return( $self );
1362 }
1363 }
1364  
1365 sub passwd { return( shift->_set_get_scalar( 'passwd', @_ ) ); }
1366  
1367 sub ping(@)
1368 {
1369 my $self = shift( @_ );
1370 my $dbh = $self->{dbh};
1371 return(0) if( !$dbh );
1372  
1373 my $ok = 0;
1374 my $errstr;
1375 local $@;
1376 {
1377 $ok = eval
1378 {
1379 my $errstr;
1380 local $SIG{__WARN__} = sub
1381 {
1382 # die( $_[0] );
1383 $errstr = join( '', @_ );
1384 };
1385 $dbh->ping ? 1 : 0;
1386 };
1387 }
1388  
1389 return(0) if( !$ok || $@ );
1390 return(1);
1391 }
1392  
1393 sub ping_select(@)
1394 {
1395 my $self = shift( @_ );
1396 # $rc = $dbh->ping;
1397 # Some new ping method replacement.... See Apache::DBI
1398 # my( $dbh ) = @_;
1399 my $ret = 0;
1400 local $@;
1401 eval
1402 {
1403 local( $SIG{__DIE__} ) = sub{ return( 0 ); };
1404 local( $SIG{__WARN__} ) = sub{ return( 0 ); };
1405 # adapt the select statement to your database:
1406 my $sth = $self->prepare( "SELECT 1" );
1407 $ret = $sth && ( $sth->execute() );
1408 $sth->finish();
1409 };
1410 return( ($@) ? 0 : $ret );
1411 }
1412  
1413 sub placeholder
1414 {
1415 my $self = shift( @_ );
1416 $self->_load_class( 'DB::Object::Placeholder' ) || return( $self->pass_error );
1417 my $opts = $self->_get_args_as_hash( @_ );
1418 $opts->{debug} = $self->debug if( !exists( $opts->{debug} ) );
1419 my $obj = DB::Object::Placeholder->new( %$opts ) ||
1420 return( $self->pass_error( DB::Object::Placeholder->error ) );
1421 return( $obj );
1422 }
1423  
1424 sub port { return( shift->_set_get_number( 'port', @_ ) ); }
1425  
1426 # Gateway to DB::Object::Statement
1427 sub prepare($;$)
1428 {
1429 my $self = shift( @_ );
1430 my $class = ref( $self ) || $self;
1431 my $query = shift( @_ );
1432 my $opt_ref = shift( @_ ) || undef();
1433 my $base_class = $self->base_class;
1434 my $q;
1435 if( $self->_is_a( $query => "${base_class}::Query" ) )
1436 {
1437 $q = $query;
1438 $query = $q->as_string;
1439 }
1440 elsif( $self->_is_a( $self => "${base_class}::Tables" ) )
1441 {
1442 $q = $self->query_object;
1443 }
1444 $self->_clean_statement( \$query );
1445 # Wether we are called from DB::Object or DB::Object::Tables object
1446 my $dbo = $self->{dbo} || $self->{database_object} || $self;
1447 if( !$dbo->ping )
1448 {
1449 my $dbh = $dbo->_dbi_connect || return( $self->pass_error );
1450 $dbo->{dbh} = $dbh;
1451 }
1452 local $@;
1453 my $sth = eval
1454 {
1455 local( $SIG{__DIE__} ) = sub{ };
1456 local( $SIG{__WARN__} ) = sub{ };
1457 $dbo->{dbh}->prepare( $query, $opt_ref );
1458 };
1459 if( $sth )
1460 {
1461 # my $data = { 'sth' => $sth, 'query' => $query };
1462 my( $query_values, $sel_fields );
1463 if( $q )
1464 {
1465 $query_values = $q->query_values;
1466 $sel_fields = $q->selected_fields;
1467 }
1468 my $data =
1469 {
1470 sth => $sth,
1471 query => $query,
1472 # query_values => $q->query_values,
1473 # selected_fields => $q->selected_fields,
1474 ( defined( $query_values ) ? ( query_values => $query_values ) : () ),
1475 ( defined( $sel_fields ) ? ( selected_fields => $sel_fields ) : () ),
1476 ( $q ? ( query_object => $q ) : () ),
1477 };
1478 return( $self->_make_sth( "${base_class}::Statement", $data ) );
1479 }
1480 else
1481 {
1482 my $err = $@ || $self->{dbh}->errstr() || 'Unknown error while cache preparing query.';
1483 $self->{query} = $query;
1484 return( $self->error( $err ) );
1485 }
1486 }
1487  
1488 sub prepare_cached
1489 {
1490 my $self = shift( @_ );
1491 my $class = ref( $self ) || $self;
1492 my $query = shift( @_ );
1493 my $opt_ref = shift( @_ ) || undef();
1494 my $base_class = $self->base_class;
1495 my $q;
1496 if( $self->_is_a( $q => "${base_class}::Query" ) )
1497 {
1498 $q = $query;
1499 $query = $q->as_string;
1500 }
1501 $self->_clean_statement( \$query );
1502 # Wether we are called from DB::Object or DB::Object::Tables object
1503 my $dbo = $self->{dbo} || $self->{database_object} || $self;
1504 if( !$dbo->ping )
1505 {
1506 my $dbh = $dbo->_dbi_connect || return( $self->pass_error );
1507 $dbo->{dbh} = $dbh;
1508 }
1509 my $sth = eval
1510 {
1511 local( $SIG{__DIE__} ) = sub{ };
1512 local( $SIG{__WARN__} ) = sub{ };
1513 $dbo->{dbh}->prepare_cached( $query, $opt_ref );
1514 };
1515 if( $sth )
1516 {
1517 # my $data = { %$self, 'sth' => $sth, 'query' => $query };
1518 # my $data = { 'sth' => $sth, 'query' => $query };
1519 my $data =
1520 {
1521 sth => $sth,
1522 query => $query,
1523 query_values => $self->{query_values},
1524 selected_fields => $self->{selected_fields},
1525 ( $q ? ( query_object => $q ) : () ),
1526 };
1527 # CORE::delete( $data->{ 'executed' } );
1528 # This is an inner package
1529 # bless( $data, "DB::Object::Statement" );
1530 # return( $data );
1531 return( $self->_make_sth( "${base_class}::Statement", $data ) );
1532 }
1533 else
1534 {
1535 my $err = $@ || $self->{dbh}->errstr() || 'Unknown error while cache preparing query.';
1536 $self->{query} = $query;
1537 return( $self->error( $err ) );
1538 }
1539 }
1540  
1541 sub query($$)
1542 {
1543 my $self = shift( @_ );
1544 my $sth = $self->prepare( @_ );
1545 my $result;
1546 if( $sth && !( $result = $sth->execute() ) )
1547 {
1548 return;
1549 }
1550 else
1551 {
1552 # bless( $sth, ref( $self ) );
1553 return( $sth );
1554 }
1555 }
1556  
1557 sub query_object { return( shift->_set_get_object_without_init( 'query_object', 'DB::Object::Query', @_ ) ); }
1558  
1559 sub quote
1560 {
1561 my $self = shift( @_ );
1562 # my $dbh = $self->{dbh} || return( $self->error( "No database handler was set." ) );
1563 my $dbh;
1564 unless( $dbh = $self->{dbh} )
1565 {
1566 # This is a fallback in case we need to use quote, but do not have a database connection yet.
1567 my $str = shift( @_ );
1568 # print( STDERR ref( $self ), "::quote -> \$str is '$str' (without surrounding quote\n" );
1569 return( $self->NULL ) if( !defined( $str ) || uc( $str ) eq 'NULL' );
1570 if( $str =~ /^$RE{num}{real}$/ )
1571 {
1572 return( $str );
1573 }
1574 else
1575 {
1576 $str =~ s/'/''/g; # iso SQL 2
1577 return( "'$str'" );
1578 }
1579 }
1580 return( $dbh->quote( @_ ) );
1581 }
1582  
1583 sub serialiser { return( shift->_set_get_scalar( 'serialiser', @_ ) ); }
1584  
1585 sub serializer { return( shift->serialiser( @_ ) ); }
1586  
1587 sub set
1588 {
1589 my $self = shift( @_ );
1590 my $vars = '';
1591 $vars = shift( @_ );
1592 $vars ||= $self->local();
1593 # Are there any variable declaration?
1594 if( $vars )
1595 {
1596 my $query = "SET $vars";
1597 eval
1598 {
1599 local( $SIG{__DIE__} ) = sub{ };
1600 local( $SIG{__WARN__} ) = sub{ };
1601 local( $SIG{ALRM} ) = sub{ die( "Timeout while processing query to set variables:\n$query\n" ) };
1602 $self->do( $query );
1603 };
1604 if( $@ )
1605 {
1606 my $err = '*** ' . join( "\n*** ", split( /\n/, $@ ) );
1607 if( $self->fatal() )
1608 {
1609 die( "Error occured while setting SQL variables before executing query:\n$self->{sth}->{Statement}\n$err\n" );
1610 }
1611 else
1612 {
1613 return( $self->error( $@ ) );
1614 }
1615 }
1616 }
1617 return(1);
1618 }
1619  
1620 # To also consider:
1621 # $sth = $dbh->statistics_info( undef, $schema, $table, $unique_only, $quick );
1622 sub stat
1623 {
1624 my $self = shift( @_ );
1625 my $type = lc( shift( @_ ) );
1626 my $sth = $self->prepare( "SHOW STATUS" );
1627 $sth->execute();
1628 my @data = ();
1629 my $ref = {};
1630 while( @data = $sth->fetchrow() )
1631 {
1632 $ref->{ lc( $data[ 0 ] ) } = $data[ 1 ];
1633 }
1634 $sth->finish();
1635 if( $type )
1636 {
1637 return( exists( $ref->{ $type } ) ? $ref->{ $type } : undef() );
1638 }
1639 else
1640 {
1641 return( wantarray() ? () : undef() ) if( !%$ref );
1642 return( wantarray() ? %$ref : $ref );
1643 }
1644 }
1645  
1646 sub state(@)
1647 {
1648 my $self = shift( @_ );
1649 # $str = $h->state;
1650 if( !ref( $self ) )
1651 {
1652 return( $DBI::state );
1653 }
1654 else
1655 {
1656 my $dbh = $self->{dbh} || return( $self->error( "No database handle is available. You need to connect to a database before using state() or call it as a class function." ) );
1657 local $@;
1658 my $rv = eval
1659 {
1660 $dbh->state();
1661 };
1662 if( $@ )
1663 {
1664 return( $self->error( $@ ) );
1665 }
1666 return( $rv );
1667 }
1668 }
1669  
1670 sub supported_class
1671 {
1672 my $self = shift( @_ );
1673 my @classes = values( %$DRIVER2PACK );
1674 return( @classes );
1675 }
1676  
1677 sub supported_drivers
1678 {
1679 my $self = shift( @_ );
1680 my @drivers = keys( %$DRIVER2PACK );
1681 return( @drivers );
1682 }
1683  
1684 sub table
1685 {
1686 my $self = shift( @_ );
1687 my $base_class = $self->base_class;
1688 return( $self->error( "You must use the database object to access this method." ) ) if( ref( $self ) ne $base_class );
1689 my $table = shift( @_ ) ||
1690 return( $self->error( "You must provide a table name to access the table methods." ) );
1691 my $table_class = "${base_class}::Tables";
1692 $self->_load_class( $table_class ) || return( $self->pass_error );
1693 my $host = $self->{server} // '';
1694 my $db = $self->{database} // '';
1695 my $tbl;
1696 if( my $medium = $self->cache_table )
1697 {
1698 $tbl = $self->_cache_table(
1699 host => $self->host,
1700 database => $self->database,
1701 table => $table,
1702 ( $medium eq 'file' ? ( medium => $medium ) : () )
1703 );
1704 return( $self->pass_error ) if( !defined( $tbl ) );
1705 $tbl->reset if( $tbl );
1706 }
1707 else
1708 {
1709 # cache_table is not enabled.
1710 }
1711  
1712 if( !$tbl )
1713 {
1714 $tbl = $table_class->new( $table,
1715 # Not necessary
1716 # dbh => $self->{dbh},
1717 dbo => $self,
1718 debug => $self->debug,
1719 ) || return( $self->pass_error( $table_class->error ) );
1720 $tbl->reset;
1721 if( $self->cache_table )
1722 {
1723 $self->_cache_table(
1724 host => $self->host,
1725 database => $self->database,
1726 table => $tbl,
1727 ) || return( $self->pass_error );
1728 }
1729 }
1730 $tbl->no_bind( $self->no_bind );
1731 # We set debug and again here in case it changed since the table object was instantiated
1732 $tbl->debug( $self->debug );
1733 return( $tbl );
1734 }
1735  
1736 sub table_exists
1737 {
1738 my $self = shift( @_ );
1739 my $table = shift( @_ ) ||
1740 return( $self->error( "You must provide a table name to access the table methods." ) );
1741 my $cache_tables = $self->cache_tables;
1742 my $tables_in_cache = [];
1743 if( defined( $cache_tables ) )
1744 {
1745 $tables_in_cache = $cache_tables->get({
1746 host => $self->host,
1747 driver => $self->driver,
1748 port => $self->port,
1749 database => $self->database,
1750 });
1751 }
1752 foreach my $ref ( @$tables_in_cache )
1753 {
1754 return( 1 ) if( $ref->{name} eq $table );
1755 }
1756 # We did not find it, so let's try by checking directly the database
1757 my $def = $self->table_info( $table );
1758 return( $self->pass_error ) if( !defined( $def ) );
1759 return(0) if( $self->_is_empty( $def ) );
1760 return(1);
1761 }
1762  
1763 sub table_info
1764 {
1765 my $self = shift( @_ );
1766 return( $self->error( "table_info() has not been implemented by driver \"$self->{driver}\" (object = $self)." ) );
1767 }
1768  
1769 sub table_push
1770 {
1771 my $self = shift( @_ );
1772 my $table = shift( @_ ) || return( $self->error( "No table provided to add to our cache." ) );
1773 my $def = $self->tables_info || return;
1774 my $hash =
1775 {
1776 host => $self->host,
1777 driver => $self->driver,
1778 port => $self->port,
1779 database => $self->database,
1780 tables => $def,
1781 };
1782 my $cache_tables = $self->cache_tables;
1783 if( !defined( $cache_tables->set( $hash ) ) )
1784 {
1785 return( $self->pass_error( $cache_tables->error ) );
1786 }
1787 return( $table );
1788 }
1789  
1790 sub tables
1791 {
1792 my $self = shift( @_ );
1793 my $db = shift( @_ ) || $self->database;
1794 my $opts = $self->_get_args_as_hash( @_ );
1795 $db = $opts->{database} if( $opts->{database} );
1796 my $all = [];
1797 if( !$opts->{no_cache} && !$opts->{live} )
1798 {
1799 if( my $cache_tables = $self->cache_tables )
1800 {
1801 $all = $cache_tables->get({
1802 host => $self->host,
1803 driver => $self->driver,
1804 port => $self->port,
1805 database => $db,
1806 }) || do
1807 {
1808 $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" );
1809 };
1810 }
1811 else
1812 {
1813 $self->error( "Warning only: no cache tables object found in our self ($self)! Current keys are: '", join( "', '", sort( keys( %$self ) ) ), "'." );
1814 }
1815 }
1816 if( $opts->{no_cache} || $opts->{live} || !scalar( @$all ) )
1817 {
1818 $all = $self->tables_info || return;
1819 }
1820 my @tables = ();
1821 @tables = map( $_->{name}, @$all ) if( scalar( @$all ) );
1822 return( \@tables );
1823 }
1824  
1825 sub tables_cache
1826 {
1827 my $self = shift( @_ );
1828 my $opts = $self->_get_args_as_hash( @_ );
1829 my $cache_tables = $self->cache_tables;
1830 my $cache = $cache_tables->get({
1831 host => $self->host,
1832 driver => $self->driver,
1833 port => $self->port,
1834 database => $self->database,
1835 });
1836 return( $cache );
1837 }
1838  
1839 sub tables_info { return( shift->error( "tables_info() has not been implemented by driver." ) ); }
1840  
1841 sub tables_refresh
1842 {
1843 my $self = shift( @_ );
1844 my $db = shift( @_ ) || $self->database;
1845 my $tables = $self->tables_info || return;
1846 my $hash =
1847 {
1848 host => $self->host,
1849 driver => $self->driver,
1850 port => $self->port,
1851 database => $self->database,
1852 tables => $tables,
1853 };
1854 my $cache_tables = $self->cache_tables;
1855 if( !defined( $cache_tables->set( $hash ) ) )
1856 {
1857 return( $self->pass_error( $cache_tables->error ) );
1858 }
1859 return( wantarray() ? @$tables : $tables );
1860 }
1861  
1862 # Used to flag this as a transaction when begin_work is triggered
1863 sub transaction { return( shift->_set_get_boolean( 'transaction', @_ ) ); }
1864  
1865 sub transaction_state
1866 {
1867 my $self = shift( @_ );
1868 my $candidate = shift( @_ );
1869  
1870 if( defined( $candidate ) &&
1871 !( blessed( $candidate ) && $candidate->isa( 'DB::Object' ) ) )
1872 {
1873 return( $self->error( "Candidate provided is not a DB::Object object." ) );
1874 }
1875  
1876 my $transactions = $self->active_transactions;
1877 return( $self->pass_error ) if( !defined( $transactions ) );
1878  
1879 my $count = scalar( @$transactions );
1880 my $state =
1881 {
1882 active => $count ? 1 : 0,
1883 count => $count,
1884 ids => [map( $_->{id}, @$transactions )],
1885 };
1886  
1887 if( $count == 1 )
1888 {
1889 $state->{id} = $transactions->[0]->{id};
1890 $state->{same} = $candidate->uses_handle( $transactions->[0]->{handle} ) ? 1 : 0 if( defined( $candidate ) );
1891 }
1892 return( $state );
1893 }
1894  
1895 sub TRUE { return( 'TRUE' ); }
1896  
1897 sub unknown_field { return( shift->_set_get_scalar( 'unknown_field', @_ ) ); }
1898  
1899 sub unlock
1900 {
1901 my $self = shift( @_ );
1902 return( $self->error( "Method \"unlock\" has not been implemented by driver $self->{driver} (object $self)." ) );
1903 }
1904  
1905 sub use
1906 {
1907 my $self = shift( @_ );
1908 my $base_class = $self->base_class;
1909 return( $self->error( "You must use the the database object to switch database." ) ) if( ref( $self ) ne $base_class );
1910 my $db = shift( @_ );
1911 # No need to go further
1912 return( $self ) if( $db eq $self->{database} );
1913 my $repo = Module::Generic::Global->new( 'available_databases' => CORE::ref( $self ), key => CORE::ref( $self ) ) ||
1914 return( $self->pass_error( Module::Generic::Global->error ) );
1915 my $all_dbs = $repo->get;
1916 if( !defined( $all_dbs ) || !$self->_is_array( $all_dbs ) )
1917 {
1918 $all_dbs = [];
1919 @$all_dbs = $self->databases();
1920 $repo->set( $all_dbs );
1921 }
1922 if( !scalar( grep{ /^$db$/ } @$all_dbs ) )
1923 {
1924 return( $self->error( "The database '$db' does not exist." ) );
1925 }
1926 my $dbh = $base_class->connect( $db ) ||
1927 return( $self->error( "Unable to connect to database '$db'." ) );
1928 $self->param( 'multi_db' => 1 );
1929 $dbh->param( 'multi_db' => 1 );
1930 return( $dbh );
1931 }
1932  
1933 sub use_cache { return( shift->_set_get_boolean( 'cache', @_ ) ) }
1934  
1935 sub use_bind { return( shift->_set_get_boolean( 'bind', @_ ) ) }
1936  
1937 sub uses_handle
1938 {
1939 my $self = shift( @_ );
1940 my $dbh = shift( @_ ) || return;
1941  
1942 return if( !$self->{dbh} );
1943  
1944 require Scalar::Util;
1945 return( $self->_refaddr( $self->{dbh} ) == $self->_refaddr( $dbh ) );
1946 }
1947  
1948 sub variables
1949 {
1950 my $self = shift( @_ );
1951 my $type = shift( @_ );
1952 $self->error( "Variable '$type' is a read-only value." ) if( @_ );
1953 my $vars = $self->{variables} ||= {};
1954 if( !%$vars )
1955 {
1956 my $sth = $self->prepare( "SHOW VARIABLES" ) ||
1957 return( $self->error( "SHOW VARIABLES is not supported." ) );
1958 $sth->execute();
1959 my $ref = $self->fetchall_arrayref();
1960 my %vars = map{ lc( $_->[ 0 ] ) => $_->[ 1 ] } @$ref;
1961 $vars = \%vars if( %vars );
1962 $sth->finish();
1963 }
1964 my @found = grep{ /$type/i } keys( %$vars );
1965 return( '' ) if( !scalar( @found ) );
1966 return( $vars->{ $found[ 0 ] } );
1967 }
1968  
1969 sub version
1970 {
1971 return( shift->error( "This driver has not set the version() method." ) );
1972 }
1973  
1974 # When the table schema caching is enabled, we store the table field objects in an hash reference
1975 # database->table => table_object
1976 sub _cache_table
1977 {
1978 my $self = shift( @_ );
1979 my $opts = $self->_get_args_as_hash( @_ );
1980 my $class = ( ref( $self ) || $self );
1981 my $base_class = $self->base_class;
1982 my $medium = $opts->{medium} // $self->cache_table;
1983 if( defined( $medium ) && "$medium" !~ /^0|1|file$/ )
1984 {
1985 return( $self->error( "medium argument or 'cache_table' method value has unsupported value. It can only be 0, 1 or 'file'." ) );
1986 }
1987 # Short-circuit if the preferred cache medium is file
1988 if( $medium eq 'file' )
1989 {
1990 return( $self->_cache_table_on_file( %$opts ) );
1991 }
1992 my $repo = Module::Generic::Global->new( table_cache => 'system',
1993 on_get => sub
1994 {
1995 my $cache = shift( @_ );
1996 # my $repo = $_;
1997 # Structure of the cache is host->database->table_name
1998 if( ref( $cache ) eq 'HASH' )
1999 {
2000 foreach my $host ( keys( %$cache ) )
2001 {
2002 next unless( ref( $cache->{ $host } ) eq 'HASH' );
2003 foreach my $db ( keys( %{$cache->{ $host }} ) )
2004 {
2005 next unless( ref( $cache->{ $host }->{ $db } ) eq 'HASH' );
2006 foreach my $tbl_name ( keys( %{$cache->{ $host }->{ $db }} ) )
2007 {
2008 my $table = $cache->{ $host }->{ $db }->{ $tbl_name };
2009 next unless( $self->_is_a( $table => "${base_class}::Tables" ) );
2010 $table->database_object( $self );
2011 if( my $qo = $table->query_object )
2012 {
2013 $qo->database_object( $self );
2014 }
2015 }
2016 }
2017 }
2018 }
2019 return( $cache );
2020 }
2021 ) || return( $self->pass_error( Module::Generic::Global->error ) );
2022 $repo->lock;
2023 my $cache = $repo->get // {};
2024 unless( CORE::exists( $opts->{host} ) && CORE::exists( $opts->{database} ) )
2025 {
2026 return( $cache );
2027 }
2028 my( $host, $database, $table ) = @$opts{qw( host database table )};
2029 return( $self->error( "A host name was provided, but is undefined or empty." ) ) if( !defined( $host ) || !CORE::length( $host // '' ) );
2030 return( $self->error( "A database name was provided, but is undefined or empty." ) ) if( !defined( $database ) || !CORE::length( $database // '' ) );
2031 my $updated = 0;
2032 if( !defined( $cache->{ $host } ) )
2033 {
2034 if( !CORE::exists( $cache->{ $host } ) ||
2035 ref( $cache->{ $host } ) ne 'HASH' )
2036 {
2037 $cache->{ $host } = {};
2038 $updated++;
2039 }
2040 }
2041 if( !defined( $cache->{ $host }->{ $database } ) )
2042 {
2043 if( !CORE::exists( $cache->{ $host }->{ $database } ) ||
2044 ref( $cache->{ $host }->{ $database } ) ne 'HASH' )
2045 {
2046 $cache->{ $host }->{ $database } = {};
2047 $updated++;
2048 }
2049 }
2050 # The caller has not provided any table value, hinting it wants the entire hash repository for this database.
2051 if( !defined( $table ) )
2052 {
2053 $repo->set( $cache ) if( $updated );
2054 return( $cache->{ $host }->{ $database } );
2055 }
2056 # We are given a table object, we store it in the repository. This is mutator mode
2057 if( $self->_is_a( $table => "${base_class}::Tables" ) )
2058 {
2059 my $name = $table->name ||
2060 return( $self->error( "No table name associated with this table object." ) );
2061 my $dbo = $table->database_object;
2062 $table->database_object( undef );
2063 my $clone = $table->clone;
2064 $table->database_object( $dbo );
2065 $cache->{ $host }->{ $database }->{ "$name" } = $clone;
2066 $repo->set( $cache );
2067 }
2068 # The user has provided a table name, and thus expects the related cloned table object from the cache table repository.
2069 # This is accessor mode.
2070 elsif( !ref( $table ) || ( ref( $table ) && $self->_can_overload( $table => '""' ) ) )
2071 {
2072 if( !CORE::exists( $cache->{ $host }->{ $database }->{ "$table" } ) ||
2073 !defined( $cache->{ $host }->{ $database }->{ "$table" } ) )
2074 {
2075 return( '' );
2076 }
2077 my $tbl = $cache->{ $host }->{ $database }->{ "$table" };
2078 unless( $self->_is_a( $tbl => "${base_class}::Tables" ) )
2079 {
2080 die( "Table object found (", $self->_str_val( $tbl ), ") in this statement object is actually not a table object (${base_class}::Tables) !" );
2081 }
2082 my $table_class = ref( $tbl );
2083 $self->_load_class( $table_class ) || return( $self->pass_error );
2084 my $clone = $tbl->clone;
2085 # $clone->database_object( $self );
2086 $clone->attach( $self );
2087 return( $clone );
2088 }
2089 else
2090 {
2091 return( $self->error( "I do not understand the value provided for the 'table' option -> ", $self->_str_val( $table ) ) );
2092 }
2093 }
2094  
2095 # Set or get the table object serialised on file.
2096 sub _cache_table_on_file
2097 {
2098 my $self = shift( @_ );
2099 my $base_class = $self->base_class;
2100 my $dbo;
2101 if( $self->isa( $base_class ) )
2102 {
2103 $dbo = $self;
2104 }
2105 elsif( $self->can( 'database_object' ) )
2106 {
2107 $dbo = $self->database_object ||
2108 return( $self->error( "There is no database object associated." ) );
2109 }
2110 else
2111 {
2112 return( $self->error( "This object is neither a $base_class object, nor an object that supports the 'database_object' method." ) );
2113 }
2114 # new_file() is inherited from Module::Generic
2115 my $cache_dir = $self->cache_dir;
2116 if( $self->_is_empty( $cache_dir ) )
2117 {
2118 return( $self->error( "No cache directory is set." ) );
2119 }
2120 $cache_dir = $self->new_file( $cache_dir );
2121 # Ensure cache directory exists
2122 if( !$cache_dir->exists )
2123 {
2124 $cache_dir->mkpath || return( $self->pass_error( $cache_dir->error ) );
2125 }
2126 elsif( !$cache_dir->is_dir )
2127 {
2128 return( $self->error( "Cache directory path '$cache_dir' exists but is not a directory." ) );
2129 }
2130  
2131 my $opts = $self->_get_args_as_hash( @_ );
2132 my $serialiser = $self->serialiser || $DB::Object::SERIALISER || 'Storable';
2133 my( $host, $database, $table ) = @$opts{qw( host database table )};
2134 if( !defined( $host ) || !CORE::length( $host // '' ) )
2135 {
2136 return( $self->error( "A host name was provided, but is undefined or empty." ) );
2137 }
2138 elsif( !defined( $database ) || !CORE::length( $database // '' ) )
2139 {
2140 return( $self->error( "A database name was provided, but is undefined or empty." ) );
2141 }
2142 elsif( $database !~ /^\w+$/ )
2143 {
2144 return( $self->error( "The database name '$database' contains illegal characters." ) );
2145 }
2146  
2147 if( !$self->ping )
2148 {
2149 my $dbh = $self->_dbi_connect || return( $self->pass_error );
2150 $self->{dbh} = $dbh;
2151 }
2152  
2153 # Normalise host for filename usage: keep only [A-Za-z0-9_.-], percent-encode everything else.
2154 # This avoids collisions that would happen with s/\W//g and supports IPv6, ports, etc.
2155 my $host_key = "$host";
2156 $host_key =~ s/([^A-Za-z0-9_.-])/sprintf( '%%%02X', ord( $1 ) )/ge;
2157 my $prefix = "table-${host_key}-${database}-\L${serialiser}";
2158  
2159 my $deserialise_from_file = sub
2160 {
2161 my $f = shift( @_ );
2162 my $name = $f->basename( '.bin' );
2163 if( index( $name, $prefix ) != 0 )
2164 {
2165 # Unexpected file name format; ignore it
2166 warn( "Ignoring cache file with unexpected name format: '$f'" ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
2167 return;
2168 }
2169  
2170 $self->_load_class( $base_class, { force => 1 } ) || return( $self->pass_error );
2171 $self->_load_class( 'DB::Object::Tables', { force => 1 } ) || return( $self->pass_error );
2172 $self->_load_class( 'DB::Object::Constraint::Foreign', { force => 1 } ) || return( $self->pass_error );
2173 $self->_load_class( "${base_class}::Tables", { force => 1 } ) || return( $self->pass_error );
2174 my $tbl = $self->Module::Generic::deserialise(
2175 file => $f,
2176 lock => 1,
2177 serialiser => $serialiser,
2178 ) || return;
2179 unless( $self->_is_a( $tbl => "${base_class}::Tables" ) )
2180 {
2181 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' ) );
2182 return;
2183 }
2184  
2185 # bless( $tbl => $table_class );
2186 $tbl->attach( $dbo ) || return( $self->pass_error( $tbl->error ) );
2187 return( $tbl );
2188 };
2189  
2190 # The caller wants the whole shebang
2191 if( !defined( $table ) )
2192 {
2193 # The caller wants all the table objects for that host and database
2194 my @files = $cache_dir->glob( "${prefix}-[a-zA-Z0-9_][a-zA-Z0-9_\\-\\.]*.bin" );
2195 my $cache = {};
2196 foreach my $f ( @files )
2197 {
2198 my $table = $deserialise_from_file->( $f ) || next;
2199 my $name = $f->basename( '.bin' );
2200 if( index( $name, $prefix ) != 0 )
2201 {
2202 # Unexpected file name format; ignore it
2203 warn( "Ignoring cache file with unexpected name format: '$f'" ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
2204 next;
2205 }
2206 $name = [split( /-/, $name )]->[-1];
2207 $cache->{ $name } = $table;
2208 }
2209 return( $cache );
2210 }
2211 # We are given a table object, we store it in the repository. This is mutator mode
2212 elsif( $self->_is_a( $table => "${base_class}::Tables" ) )
2213 {
2214 my $name = $table->name ||
2215 return( $self->error( "No table name associated with this table object." ) );
2216 if( $name !~ /^\w+[\w\-\.]*$/ )
2217 {
2218 return( $self->error( "The table name '$name' contains illegal characters." ) );
2219 }
2220 my $file = $cache_dir->child( "${prefix}-${name}.bin" );
2221 my $tbl = $self->Module::Generic::serialise( $table,
2222 file => $file,
2223 lock => 1,
2224 serialiser => $serialiser,
2225 ( $serialiser eq 'Sereal' ? ( freeze_callbacks => 1 ) : () ),
2226 ) || return( $self->pass_error );
2227 return(1);
2228 }
2229 # The user has provided a table name, and thus expects the related cloned table object from the cache table repository.
2230 # This is accessor mode.
2231 elsif( !ref( $table ) || ( ref( $table ) && $self->_can_overload( $table => '""' ) ) )
2232 {
2233 $table = "$table";
2234 if( $table !~ /^\w+[\w\-\.]*$/ )
2235 {
2236 return( $self->error( "The table name '$table' contains illegal characters." ) );
2237 }
2238 my $cache_file = $cache_dir->child( "${prefix}-${table}.bin" );
2239 if( !$cache_file->exists || $cache_file->is_empty || !$cache_file->is_file )
2240 {
2241 return( '' );
2242 }
2243 my $tbl = $deserialise_from_file->( $cache_file ) || return( '' );
2244 return( $tbl );
2245 }
2246 else
2247 {
2248 return( $self->error( "I do not understand the value provided for the 'table' option -> ", $self->_str_val( $table ) ) );
2249 }
2250 }
2251  
2252 sub _cache_this
2253 {
2254 my $self = shift( @_ );
2255 # When this method is accessed by method from package DB::Object::Statement, they CAN NOT
2256 # implicitly pass the statement string or they would risk to modify the previous stored
2257 # query object they represent.
2258 # For instance:
2259 # $obj->select->join( 'some_table', { 'parameter', 'list' } )->fetchrow_hashref()
2260 # here the first query is prepared and cached and its resulting object is passed on to join
2261 # here join will rebuild the query, but will search first if there was one already cached
2262 # if join passes implictly the statement string, this means it will modify the cached query select()
2263 # has just previously stored... This is why method such as join must pass explicitly the query string
2264 my $q = shift( @_ );
2265 my $query = ( ref( $q ) && $q->isa( 'DB::Object::Query' ) ) ? $q->as_string : $q;
2266 my $dbo = $self->{dbo} || $self->{database_object} || $self;
2267 my $base_class = $self->base_class;
2268 my $cache = $dbo->{cache};
2269 my $bind = $dbo->{bind};
2270 my $cache_dir = $dbo->cache_dir // $self->new_tempdir;
2271 my $cache_query = $dbo->cache_query;
2272 my $cache_size = $dbo->cache_size // 0;
2273 my $serialiser = $dbo->serialiser || $DB::Object::SERIALISER || 'Storable';
2274  
2275 my $use_file_cache = ( defined( $cache_query ) && $cache_query eq 'file' ) ? 1 : 0;
2276  
2277 my( $repo, $sth, $cache_file, $checksum, $cache_key );
2278 my $cached_sth = '';
2279 my $host = $dbo->host;
2280 my $database = $dbo->database;
2281 my $table = ( ref( $q ) && $dbo->_is_a( $q => "${base_class}::Query" ) && $q->table_object ) ? $q->table_object->name : '';
2282  
2283 # Compute cache_file (and cache key) early when caching is enabled and cache_dir exists.
2284 # Even if cache_query is "file", we also want a small hot cache in memory.
2285 if( $cache )
2286 {
2287 local $@;
2288 if( $dbo->_load_class( 'Crypt::Digest::MD5' ) )
2289 {
2290 $checksum = eval
2291 {
2292 return( Crypt::Digest::MD5::md5_hex( $query ) );
2293 };
2294 }
2295  
2296 if( !defined( $checksum ) && $dbo->_load_class( 'Digest::MD5' ) )
2297 {
2298 $checksum = eval
2299 {
2300 return( Digest::MD5::md5_hex( $query ) );
2301 };
2302 }
2303  
2304 if( !defined( $checksum ) )
2305 {
2306 return( $self->error( "Caching query object is requested, but I could not find either Crypt::Digest::MD5 or Digest::MD5" ) );
2307 }
2308  
2309 my $file = $self->_get_cache_filepath(
2310 cache_dir => $cache_dir,
2311 extension => 'bin',
2312 name => $checksum,
2313 host => $host,
2314 database => $database,
2315 ( $table ? ( table => $table ) : () ),
2316 prefix => 'query',
2317 ) || return( $self->pass_error );
2318 if( $cache_dir )
2319 {
2320 $cache_file = $file;
2321 }
2322 # User requested identifier: basename of cache_file
2323 $cache_key = $cache_file->basename( '.bin' );
2324 }
2325  
2326 # 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
2327 my $lock;
2328 if( $cache_key )
2329 {
2330 $repo = Module::Generic::Global->new( queries_cache => $base_class,
2331 key => $cache_key,
2332 max_size => $cache_size,
2333 ) || return( $dbo->pass_error( Module::Generic::Global->error ) );
2334 $lock = $repo->lock;
2335 $cached_sth = $repo->get;
2336 # Nothing, so we remove that repo. We do not leave it. This saves memory, although not much.
2337 $repo->remove if( !defined( $cached_sth ) );
2338 # The lock gets removed automatically when it gets out of scope, so we store it in $lock
2339 $repo->unlock;
2340 }
2341  
2342 # If found in-memory cache, we revive it
2343 if( $cached_sth )
2344 {
2345 # Thanks to Module::Generic::Global, this is an thawed statement object.
2346 # We just need to attach it to our current database object
2347 $sth = $cached_sth;
2348 if( !$sth->attach( $dbo ) )
2349 {
2350 $repo->unlock if( $repo );
2351 return( $self->pass_error( $sth->error ) );
2352 }
2353  
2354 my $prepare_options = {};
2355 if( $q && $self->_is_a( $q, "${base_class}::Query" ) )
2356 {
2357 $prepare_options = $q->prepare_options->as_hash;
2358 }
2359  
2360  
2361 local $@;
2362 my $sth_dbi = eval
2363 {
2364 local( $SIG{__DIE__} ) = sub{ };
2365 local( $SIG{__WARN__} ) = sub{ };
2366 $dbo->{dbh}->prepare_cached( $query, ( scalar( keys( %$prepare_options ) ) ? $prepare_options : () ) );
2367 };
2368  
2369 if( $@ )
2370 {
2371 $repo->unlock if( $repo );
2372 return( $self->error( "Error preparing cached SQL query: $@\nQuery was:\n$query" ) );
2373 }
2374  
2375 $sth->{sth} = $sth_dbi;
2376  
2377 $repo->unlock if( $repo );
2378 }
2379  
2380 # If no in-memory was found yet, we try the file cache (explicit mode only)
2381 if( !defined( $sth ) &&
2382 $cache &&
2383 $use_file_cache &&
2384 $cache_file &&
2385 $cache_file->exists &&
2386 !$cache_file->is_empty &&
2387 $cache_file->is_file )
2388 {
2389 $sth = $self->Module::Generic::deserialise(
2390 file => $cache_file,
2391 lock => 1,
2392 serialiser => $serialiser,
2393 );
2394 if( !$sth )
2395 {
2396 $repo->unlock if( $repo );
2397 return( $self->pass_error );
2398 }
2399  
2400 if( !$sth->attach( $dbo ) )
2401 {
2402 $repo->unlock if( $repo );
2403 return( $self->pass_error( $sth->error ) );
2404 }
2405  
2406 my $prepare_options = {};
2407 if( $q && $dbo->_is_a( $q, "${base_class}::Query" ) )
2408 {
2409 $prepare_options = $q->prepare_options->as_hash;
2410 }
2411  
2412  
2413 local $@;
2414 my $sth_dbi = eval
2415 {
2416 local( $SIG{__DIE__} ) = sub{ };
2417 local( $SIG{__WARN__} ) = sub{ };
2418 $dbo->{dbh}->prepare_cached( $query, ( scalar( keys( %$prepare_options ) ) ? $prepare_options : () ) );
2419 };
2420  
2421 if( $@ )
2422 {
2423 $repo->unlock if( $repo );
2424 return( $self->error( "Error preparing cached SQL query: $@\nQuery was:\n$query" ) );
2425 }
2426  
2427 $sth->{sth} = $sth_dbi;
2428 $repo->unlock if( $repo );
2429 }
2430  
2431 # The statement is not cached anywhere, so we prepare it now
2432 if( !defined( $sth ) )
2433 {
2434 my $prepare_options = {};
2435 if( $q && $self->_is_a( $q, "${base_class}::Query" ) )
2436 {
2437 $prepare_options = $q->prepare_options->as_hash;
2438 }
2439  
2440 if( !( $sth = $dbo->prepare( $query, ( scalar( keys( %$prepare_options ) ) ? $prepare_options : () ) ) ) )
2441 {
2442 $repo->unlock if( $repo );
2443 return( $self->pass_error( $dbo->error ) );
2444 }
2445  
2446 # File cache (explicit mode only)
2447 if( $cache && $use_file_cache && $cache_file )
2448 {
2449 if( !$dbo->Module::Generic::serialise( $sth,
2450 file => $cache_file,
2451 lock => 1,
2452 serialiser => $serialiser,
2453 ) )
2454 {
2455 $repo->unlock if( $repo );
2456 return( $self->pass_error( $dbo->error ) );
2457 }
2458 }
2459 # If caching is off, but the query is a binded parameters' one,
2460 # make the current object hold the statement object
2461 elsif( $bind )
2462 {
2463 $self->{sth} = $sth;
2464 }
2465 $repo->unlock if( $repo );
2466 }
2467 else
2468 {
2469 $repo->unlock if( $repo );
2470 }
2471  
2472 # Ensure we unlock even if sth came from mem cache path where we unlocked earlier
2473 $repo->unlock if( $repo );
2474  
2475 # Attach query object to statement (this can be dangerous if the statement is long-lived;
2476 # keep your query object small / reset/dirty it aggressively)
2477 $sth->query_object( $q ) if( $dbo->_is_a( $q, "${base_class}::Query" ) );
2478 $sth->table_object( $self ) if( $self->isa( "${base_class}::Tables" ) );
2479  
2480 # Caching the query as a constant
2481 if( $q && $dbo->_is_object( $q ) && $q->isa( "${base_class}::Query" ) )
2482 {
2483 my $constant = $q->constant;
2484 if( $constant && scalar( keys( %$constant ) ) )
2485 {
2486 foreach my $k (qw( pack file line ))
2487 {
2488 return( $self->error( "Could not find the parameter \"$k\" in the constant query hash reference." ) ) if( !$constant->{ $k } );
2489 }
2490  
2491 # We temporarily not store the query object, and see if this affects positively the memory consumption.
2492 # $constant->{query_object} = $q;
2493 # $dbo->constant_queries_cache_set( $constant );
2494 }
2495 }
2496  
2497 return( $sth );
2498 }
2499  
2500 sub _check_connect_param
2501 {
2502 my $self = shift( @_ );
2503 my $param = shift( @_ );
2504 my $valid = $self->_connection_parameters( $param );
2505 my $opts = $self->_connection_options( $param );
2506 foreach my $k ( keys( %$param ) )
2507 {
2508 # If it is not in the list and it does not start with an upper case; those are like RaiseError, AutoCommit, etc
2509 if( CORE::length( $param->{ $k } ) && !grep( /^$k$/, @$valid ) && !CORE::exists( $opts->{ $k } ) )
2510 {
2511 return( $self->error( "Invalid parameter '$k'." ) );
2512 }
2513 }
2514 my @opts_to_remove = keys( %$opts );
2515 CORE::delete( @$param{ @opts_to_remove } ) if( scalar( @opts_to_remove ) );
2516 $param->{opt} = $opts;
2517 $param->{database} = CORE::delete( $param->{db} ) if( !length( $param->{database} ) && $param->{db} );
2518 return( $param );
2519 }
2520  
2521 sub _check_default_option
2522 {
2523 my $self = shift( @_ );
2524 my $opts = $self->_get_args_as_hash( @_ );
2525 # return( $self->error( "Provided option is not a hash reference." ) ) if( !$self->_is_hash( $opts ) );
2526 # This method should be superseded by an inherited class
2527 return( $opts );
2528 }
2529  
2530 # Simplistic clone by design. We do not want a recursive clone like Clone::clone()
2531 sub _clone
2532 {
2533 my( $self, $this ) = @_;
2534 if( $self->_is_array( $this ) )
2535 {
2536 my @clone = @$this;
2537 return( \@clone );
2538 }
2539 elsif( ref( $this ) eq 'HASH' )
2540 {
2541 my @keys = keys( %$this );
2542 my $clone = {};
2543 @$clone{ @keys } = @$this{ @keys };
2544 return( $clone );
2545 }
2546 else
2547 {
2548 return( $self->error( "Unsupported data type to clone. This method only support hash or array reference." ) );
2549 }
2550 }
2551  
2552 sub _connection_options
2553 {
2554 my $self = shift( @_ );
2555 my $param = shift( @_ );
2556 my @dbi_opts = grep( /^[A-Z][a-zA-Z]+/, keys( %$param ) );
2557 my $opt = {};
2558 $opt = CORE::delete( $param->{opt} ) if( $param->{opt} && $self->_is_hash( $param->{opt} => 'strict' ) );
2559 @$opt{ @dbi_opts } = @$param{ @dbi_opts };
2560 return( $opt );
2561 }
2562  
2563 sub _connection_parameters
2564 {
2565 my $self = shift( @_ );
2566 my $param = shift( @_ );
2567 my $params = $self->new_array( [qw(
2568 db login passwd host port driver database server opt uri debug cache_connections
2569 cache_dir cache_table connect_via serialiser unknown_field id
2570 )] );
2571 my $core = $self->{_core_fields} || [];
2572 $params->push( @$core );
2573 return( $params->unique(1) );
2574 }
2575  
2576 sub _connection_params2hash
2577 {
2578 my $self = shift( @_ );
2579 my $argv = [@_];
2580 my $param = {};
2581 if( !( @_ % 2 ) )
2582 {
2583 $param = { @_ };
2584 }
2585 elsif( @_ == 1 && ( ref( $_[0] ) // '' ) eq 'HASH' )
2586 {
2587 $param = shift( @_ );
2588 }
2589 else
2590 {
2591 my @keys = qw( database login passwd host driver schema );
2592 # Only add in the $param hash the keys value we were given, so we don't create keys entry when not needed
2593 for( my $i = 0; $i < scalar( @_ ); $i++ )
2594 {
2595 $param->{ $keys[ $i ] } = $_[ $i ];
2596 }
2597 }
2598  
2599 my $equi =
2600 {
2601 database => 'DB_NAME',
2602 login => 'DB_LOGIN',
2603 passwd => 'DB_PASSWD',
2604 host => 'DB_HOST',
2605 port => 'DB_PORT',
2606 driver => 'DB_DRIVER',
2607 schema => 'DB_SCHEMA',
2608 };
2609 foreach my $prop ( keys( %$equi ) )
2610 {
2611 $param->{ $prop } = $ENV{ $equi->{ $prop } } if( $ENV{ $equi->{ $prop } } && !length( $param->{ $prop } ) );
2612 }
2613  
2614 # A simple json file
2615 # An URI could be http://localhost:5432?database=somedb etc...
2616 # or it could also be file:/foo/bar?opt={"RaiseError":true}
2617 if( $param->{uri} || $ENV{DB_CON_URI} )
2618 {
2619 my $uri;
2620 eval
2621 {
2622 require URI;
2623 $uri = URI->new( $param->{uri} || $ENV{DB_CON_URI} );
2624 };
2625 if( !$@ && $uri )
2626 {
2627 # Make sure our parameter is a valid URI object
2628 $param->{uri} = $uri;
2629 if( $uri->can( 'port' ) )
2630 {
2631 $param->{host} = $uri->host;
2632 $param->{port} = $uri->port if( $uri->port );
2633 }
2634 # file:/
2635 elsif( length( $uri->path ) )
2636 {
2637 $param->{database} = ( $uri->path_segments )[-1];
2638 }
2639 my( %q ) = $uri->query_form;
2640 $param->{host} = $q{host} if( $q{host} );
2641 $param->{port} = $q{port} if( $q{port} );
2642 $param->{database} = $q{database} if( $q{database} );
2643 $param->{schema} = $q{schema} if( $q{schema} );
2644 $param->{user} = $q{user} if( $q{user} );
2645 $param->{login} = $q{login} if( $q{login} );
2646 $param->{password} = $q{password} if( $q{password} );
2647 $param->{opt} = $q{opt} if( $q{opt} );
2648 $param->{login} = CORE::delete( $param->{user} ) if( !$param->{login} && $param->{user} );
2649 if( $q{opt} )
2650 {
2651 my $jdata = {};
2652 eval
2653 {
2654 require JSON;
2655 if( defined( *{ "JSON::" } ) )
2656 {
2657 my $j = JSON->new->allow_nonref;
2658 $jdata = $j->decode( $q{opt} );
2659 }
2660 };
2661 if( $@ )
2662 {
2663 warn( "Found the database connection opt parameter provided in the connection uri \"$uri\", but could not decode its json value: $@\n" );
2664 }
2665 $param->{opt} = $jdata if( scalar( keys( %$jdata ) ) );
2666 }
2667 }
2668 }
2669  
2670 if( $param->{conf_file} || $param->{config_file} || $ENV{DB_CON_FILE} )
2671 {
2672 my $db_con_file = $self->new_file( CORE::delete( $param->{conf_file} ) || CORE::delete( $param->{config_file} ) || $ENV{DB_CON_FILE} );
2673 my $db_con_file_ok = 0;
2674 if( !$db_con_file->exists )
2675 {
2676 warn( "Database connection parameter file \"$db_con_file\" was provided but does not exist.\n" );
2677 }
2678 elsif( $db_con_file->is_empty )
2679 {
2680 warn( "Database connection parameter file \"$db_con_file\" was provided but the file is empty.\n" );
2681 }
2682 elsif( !$db_con_file->can_read )
2683 {
2684 warn( "Database connection parameter file \"$db_con_file\" was provided but the file lacks privileges to be read.\n" );
2685 }
2686 else
2687 {
2688 $db_con_file_ok++;
2689 }
2690  
2691 my $json = $db_con_file->load_json;
2692 # If the configuration file has some issue, we warn about it, but we move on.
2693 if( !$json )
2694 {
2695 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 );
2696 }
2697 $json = {} if( !$self->_is_hash( $json => 'strict' ) );
2698 my $ref = {};
2699 if( exists( $json->{databases} ) )
2700 {
2701 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} ) );
2702 # When called from sub classes, this is set
2703 my $driver = $self->driver;
2704 # We take the first one matching our driver if any, or else we just take the first one
2705 foreach my $this ( @{$json->{databases}} )
2706 {
2707 if( !$param->{database} && ( !$driver || $this->{driver} eq $driver ) )
2708 {
2709 $ref = $this;
2710 last;
2711 }
2712 elsif( $param->{database} && $this->{database} && $this->{database} eq $param->{database} &&
2713 ( !$param->{host} || ( $this->{host} && $param->{host} eq $this->{host} ) ) &&
2714 ( !$param->{port} || ( $this->{port} && $param->{port} eq $this->{port} ) ) &&
2715 ( !$param->{login} || ( $this->{login} && $param->{login} eq $this->{login} ) ) )
2716 {
2717 $ref = $this;
2718 last;
2719 }
2720 }
2721 }
2722 else
2723 {
2724 $ref = $json;
2725 }
2726  
2727 if( scalar( keys( %$ref ) ) )
2728 {
2729 foreach my $k ( qw( database login passwd host port driver schema opt ) )
2730 {
2731 $param->{ $k } = $ref->{ $k } if( !length( $param->{ $k } ) && length( $ref->{ $k } ) );
2732 }
2733 }
2734  
2735 # Grab any cache_* configuration property in the file
2736 foreach my $prop ( grep{ /^(cache_|cache\z|use_cache\z)/ } keys( %$json ) )
2737 {
2738 $param->{ $prop } = $json->{ $prop } if( CORE::exists( $json->{ $prop } ) );
2739 }
2740 if( CORE::exists( $json->{serialiser} ) )
2741 {
2742 $param->{serialiser} = $json->{serialiser};
2743 }
2744 elsif( CORE::exists( $json->{serializer} ) )
2745 {
2746 $param->{serialiser} = $json->{serializer};
2747 }
2748 }
2749  
2750 if( CORE::exists( $param->{host} ) && index( $param->{host}, ':' ) != -1 )
2751 {
2752 @$param{ qw( host port ) } = split( /:/, $param->{host}, 2 );
2753 }
2754  
2755 if( !$param->{opt} && $ENV{DB_OPT} )
2756 {
2757 my $jdata = {};
2758 eval
2759 {
2760 require JSON;
2761 if( defined( *{ "JSON::" } ) )
2762 {
2763 my $j = JSON->new->allow_nonref;
2764 $jdata = $j->decode( $ENV{DB_OPT} );
2765 }
2766 };
2767 if( $@ )
2768 {
2769 warn( "Found the database connection opt parameter provided in the envionment variable DB_OPT, but could not decode its json value: $@\n" );
2770 }
2771 $param->{opt} = $jdata if( scalar( keys( %$jdata ) ) );
2772 }
2773 return( $param );
2774 }
2775  
2776 sub _connection_params2hash_driver
2777 {
2778 my $self = shift( @_ );
2779 my $opts = $self->_get_args_as_hash( @_ );
2780 return( $opts );
2781 }
2782  
2783 sub _clean_statement
2784 {
2785 my $self = shift( @_ );
2786 my $data = shift( @_ );
2787 my $query = ref( $data ) ? $data : \$data;
2788 $$query = CORE::join( "\n", map{ s/^\s+|\s+$//gs; $_ } split( /\n/, $$query ) );
2789 return( $$query ) if( !ref( $data ) );
2790 }
2791  
2792 sub _dbi_connect
2793 {
2794 my $self = shift( @_ );
2795 my $dbh;
2796 my $dsn = $self->_dsn;
2797 # print( STDERR ref( $self ) . "::_dbi_connect() Options are: ", $self->dumper( $self->{opt} ), "\n" );
2798 my $connect_via = $self->connect_via;
2799 # See: <https://metacpan.org/pod/DBI#Timeout>
2800 # signals to mask in the handler
2801 my $mask = POSIX::SigSet->new( POSIX::SIGALRM );
2802 my $action = POSIX::SigAction->new(
2803 # the handler code ref
2804 sub{ die( "connect timeout\n" ) },
2805 $mask,
2806 # not using (perl 5.8.2 and later) 'safe' switch or sa_flags
2807 );
2808 my $oldaction = POSIX::SigAction->new();
2809 POSIX::sigaction( POSIX::SIGALRM, $action, $oldaction );
2810 my $failed;
2811 local $@;
2812 eval
2813 {
2814 eval
2815 {
2816 # seconds before time out
2817 alarm(5);
2818 if( $self->{cache_connections} )
2819 {
2820 $dbh = DBI->connect_cached(
2821 $dsn,
2822 $self->{login},
2823 $self->{passwd},
2824 $self->{opt},
2825 undef(),
2826 ( $connect_via ? $connect_via : () ),
2827 );
2828 }
2829 else
2830 {
2831 $dbh = DBI->connect(
2832 $dsn,
2833 $self->{login},
2834 $self->{passwd},
2835 $self->{opt},
2836 undef(),
2837 ( $connect_via ? $connect_via : () ),
2838 );
2839 }
2840 1;
2841 } or $failed = 1;
2842 # cancel alarm (if connect worked fast)
2843 alarm(0);
2844 # connect died
2845 die( "$@\n" ) if( $failed );
2846 1;
2847 } or $failed = 1;
2848 # restore original signal handler
2849 POSIX::sigaction( POSIX::SIGALRM, $oldaction );
2850 if( defined( $failed ) && $failed )
2851 {
2852 if( defined( $@ ) && $@ =~ /^connect timeout/ )
2853 {
2854 return( $self->error( "Connection timed out for dsn '", ( $dsn // 'undef' ), " and login '", ( $self->{login} // 'undef' ), "'" ) );
2855 }
2856 else
2857 {
2858 return( $self->error( "Error connecting with dsn '", ( $dsn // 'undef' ), " and login '", ( $self->{login} // 'undef' ), "': $@" ) );
2859 }
2860 }
2861  
2862 return( $self->error( $DBI::errstr ) ) if( !$dbh );
2863 return( $dbh );
2864 }
2865  
2866 sub _decode_json
2867 {
2868 my $self = shift( @_ );
2869 my $json = shift( @_ );
2870 return if( !CORE::length( $json ) );
2871 my $j = JSON->new->allow_nonref;
2872 my $hash = eval
2873 {
2874 $j->decode( $json );
2875 };
2876 return if( $@ );
2877 return( $hash );
2878 }
2879  
2880 sub _dsn
2881 {
2882 my $self = shift( @_ );
2883 my $class = ref( $self ) || $self;
2884 die( "Method _dsn is not implemented in class $class\n" );
2885 }
2886  
2887 sub _encode_json
2888 {
2889 my $self = shift( @_ );
2890 return if( !scalar( @_ ) || ( scalar( @_ ) == 1 && !defined( $_[0] ) ) );
2891 my $this = shift( @_ );
2892 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' ) );
2893 my $j = JSON->new;
2894 my $json = eval
2895 {
2896 $j->encode( $this );
2897 };
2898 return( $self->error( "An error occurred while trying to encode hash reference provided: $@" ) ) if( $@ );
2899 return( $json );
2900 }
2901  
2902 sub _get_cache_filepath
2903 {
2904 my $self = shift( @_ );
2905 my $opts = $self->_get_args_as_hash( @_ );
2906 my $name = $opts->{name};
2907 my $ext = $opts->{extension} // 'bin';
2908 if( $name !~ /^[\w\-]+$/ )
2909 {
2910 return( $self->error( "The name for this cache file contains illegal characters '$name'. Only alphabetical, numeric characters, underscore, and dash are allowed" ) );
2911 }
2912 my $host = $opts->{host} || $self->host;
2913 my $database = $opts->{database} || $self->database;
2914 # May not be specified, and thus empty.
2915 my $table = $opts->{table};
2916 if( defined( $host ) && !CORE::length( $host // '' ) )
2917 {
2918 return( $self->error( "A host name was provided, but is undefined or empty." ) );
2919 }
2920 elsif( !defined( $database ) || !CORE::length( $database // '' ) )
2921 {
2922 return( $self->error( "The database name is undefined or empty." ) );
2923 }
2924 elsif( $database !~ /^\w+$/ )
2925 {
2926 return( $self->error( "The database name '$database' contains illegal characters." ) );
2927 }
2928 elsif( $table && $table !~ /^\w+[\w\-\.]*$/ )
2929 {
2930 return( $self->error( "The table name '$table' contains illegal characters." ) );
2931 }
2932  
2933 $host //= '_unknown_';
2934 # Normalise host for filename usage: keep only [A-Za-z0-9_.-], percent-encode everything else.
2935 # This avoids collisions that would happen with s/\W//g and supports IPv6, ports, etc.
2936 my $host_key = "$host";
2937 $host_key =~ s/([^A-Za-z0-9_.-])/sprintf( '%%%02X', ord( $1 ) )/ge;
2938  
2939 my $cache_dir = $opts->{cache_dir} || $self->cache_dir ||
2940 return( $self->error( "No cache directory was provided." ) );
2941 $cache_dir = $self->new_file( $cache_dir ) ||
2942 return( $self->pass_error );
2943 # Ensure cache directory exists
2944 if( !$cache_dir->exists )
2945 {
2946 $cache_dir->mkpath || return( $self->pass_error( $cache_dir->error ) );
2947 }
2948 elsif( !$cache_dir->is_dir )
2949 {
2950 return( $self->error( "Cache directory path '$cache_dir' exists but is not a directory." ) );
2951 }
2952 my @parts = ( ( $opts->{prefix} ? $opts->{prefix} : () ), $host_key, $database );
2953 push( @parts, $table ) if( $table );
2954 push( @parts, "${name}.${ext}" );
2955 my $cache_file = $cache_dir->child( join( '-', @parts ) ) ||
2956 return( $self->pass_error( $cache_dir->error ) );
2957 return( $cache_file );
2958 }
2959  
2960 sub _make_sth
2961 {
2962 my $self = shift( @_ );
2963 my $pkg = shift( @_ );
2964 my $data = shift( @_ ) || {};
2965 my $base_class = $self->base_class;
2966 $self->_load_class( $pkg ) || return( $self->pass_error );
2967 foreach my $prop ( qw( table debug bind cache params from_table left_join ) )
2968 {
2969 $data->{ $prop } = $self->{ $prop };
2970 }
2971 $data->{dbh} = $self->{dbh};
2972 $data->{dbo} = $self->{dbo} ? $self->{dbo} : ref( $self ) eq $self->base_class ? $self : '';
2973 # $data->{ 'binded' } = $self->{ 'binded' } if( $self->{ 'binded' } && ref( $self ) ne $base_class );
2974 # In any case suppress the binded parameter from our parent object to avoid polluting the next queries
2975 # If needed, the binded parameter will be rebuilt using the data stored in 'where', 'group', 'order' and 'limit'
2976 # CORE::delete( $self->{ 'binded' } );
2977 # Binded parameters are now either in the DB::Object::Query package or one of its descendant OR passed as arguments to execute
2978 $data->{errstr} = '';
2979 CORE::delete( $data->{executed} );
2980 $data->{query_time} = time();
2981 $data->{selected_fields} = '' if( !exists( $data->{selected_fields} ) );
2982 $data->{table_object} = $self if( $self->_is_a( $self => "${base_class}::Tables" ) );
2983 my $this = bless( $data, $pkg );
2984 $this->debug( $self->debug );
2985 return( $this );
2986 }
2987  
2988 sub _new_connection_id
2989 {
2990 my $self = shift( @_ );
2991 $self->_load_class( 'Time::HiRes' ) || return( $self->pass_error );
2992 return( sprintf( '%x-%x-%x', $$, int( Time::HiRes::time() * 1_000_000 ), ++$CONNECTION_ID_SEQUENCE ) );
2993 }
2994  
2995 sub _operator_object_create
2996 {
2997 my $self = shift( @_ );
2998 my $class = shift( @_ ) || return( $self->error( "No operator class was provided." ) );
2999 my $q = $self->_reset_query;
3000 my $args = ( scalar( @_ ) == 1 && ref( $_[0] ) eq 'ARRAY' ) ? [ @{$_[0]} ] : [ @_ ];
3001 return( $class->new(
3002 debug => $self->debug,
3003 query_object => $q,
3004 value => $args,
3005 ) );
3006 }
3007  
3008 sub _param2hash
3009 {
3010 my $self = shift( @_ );
3011 my $opts = {};
3012 if( scalar( @_ ) )
3013 {
3014 if( $self->_is_hash( $_[0] => 'strict' ) )
3015 {
3016 $opts = shift( @_ );
3017 }
3018 elsif( !( scalar( @_ ) % 2 ) )
3019 {
3020 $opts = { @_ };
3021 }
3022 else
3023 {
3024 return( $self->error( "Uneven number of parameters. I was expecting a hash or a hash reference." ) );
3025 }
3026 }
3027 return( $opts );
3028 }
3029  
3030 sub _placeholder_regexp { return( $PLACEHOLDER_REGEXP ) }
3031  
3032 # NOTE: _query_object_add needs to reside in DB::Object (called indirectly by no_bind)
3033 sub _query_object_add
3034 {
3035 my $self = shift( @_ );
3036 my $obj = shift( @_ ) || return( $self->error( "No query object was provided" ) );
3037 my $base = $self->base_class;
3038 return( $self->error( "Object provided is not a query object class" ) ) if( ref( $obj ) !~ /^${base}\::Query$/ );
3039 $self->query_object( $obj );
3040 return( $obj );
3041 }
3042  
3043 # NOTE: _query_object_create needs to reside in DB::Object (called indirectly by no_bind)
3044 sub _query_object_create
3045 {
3046 my $self = shift( @_ );
3047 my $base = $self->base_class;
3048 my $query_class = "${base}::Query";
3049 $self->_load_class( $query_class ) ||
3050 return( $self->error( "Unable to load Query builder module $query_class: ", $self->error->message ) );
3051 my $o = $query_class->new;
3052 $o->debug( $self->debug );
3053 if( $self->isa( "${base}::Tables" ) )
3054 {
3055 $o->table_object( $self ) || return( $self->pass_error( $o->error ) );
3056 # Weaken the back-reference from the Query object to its owning Table to break
3057 # the circular reference cycle (Table -> query_object -> Query -> table_object -> Table)
3058 # that prevents Perl's garbage collector from reclaiming old Query objects.
3059 weaken( $o->{table_object} );
3060 $o->enhance( $self->database_object->enhance );
3061 $o->database_object( $self->database_object ) || return( $self->pass_error( $o->error ) );
3062 # Also weaken the database_object reference - the dbo is a long-lived singleton
3063 # and does not own Query objects, so a weak reference is safe here.
3064 weaken( $o->{database_object} );
3065 # Set the table alias if any has been set
3066 if( my $table_alias = $self->as )
3067 {
3068 $o->table_alias( $table_alias ) if( defined( $table_alias ) );
3069 }
3070 }
3071 elsif( $self->isa( $base ) )
3072 {
3073 $o->enhance( $self->enhance );
3074 $o->database_object( $self ) || return( $self->pass_error( $o->error ) );
3075 }
3076 return( $o );
3077 }
3078  
3079 # NOTE: _query_object_current needs to reside in DB::Object (called indirectly by no_bind)
3080 sub _query_object_current { return( shift->{query_object} ); }
3081  
3082 # NOTE: _query_object_get_or_create needs to reside in DB::Object (called indirectly by no_bind)
3083 # If the stack is empty, we create an object, add it and resend it
3084 sub _query_object_get_or_create
3085 {
3086 my $self = shift( @_ );
3087 my $obj = $self->query_object;
3088 if( $obj && $obj->dirty )
3089 {
3090 $self->_query_object_remove( $obj );
3091 undef( $obj );
3092 }
3093 if( !$obj )
3094 {
3095 $obj = $self->_query_object_create || return( $self->pass_error );
3096 $self->query_object( $obj );
3097 }
3098 return( $obj );
3099 }
3100  
3101 # NOTE: _query_object_remove needs to reside in DB::Object (called indirectly by no_bind)
3102 sub _query_object_remove
3103 {
3104 my $self = shift( @_ );
3105 my $obj = shift( @_ ) || return( $self->error( "No query object was provided" ) );
3106 my $base = $self->base_class;
3107 # return( $self->error( "Object provided is not a query object class" ) ) if( ref( $obj ) !~ /^${base}\::Query$/ );
3108 return( $self->error( "Object provided is not a query object class" ) ) if( !$obj->isa( "DB::Object::Query" ) );
3109 $self->query_object( undef );
3110 return( $obj );
3111 }
3112  
3113 # 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
3114 sub _reset_query
3115 {
3116 my $self = shift( @_ );
3117 if( !$self->{query_reset} )
3118 {
3119 $self->{query_reset} = 1;
3120 # $self->{enhance} = 1;
3121 my $obj = $self->query_object;
3122 # If current query object is dirty, detach it right away.
3123 if( $obj && $obj->dirty )
3124 {
3125 $self->_query_object_remove( $obj );
3126 undef( $obj );
3127 }
3128  
3129 # Capture join tables BEFORE we detach the query object
3130 my $join_tables;
3131 if( $obj )
3132 {
3133 $join_tables = $obj->join_tables;
3134 }
3135  
3136 $self->_query_object_remove( $obj ) if( $obj );
3137 if( $join_tables && $join_tables->length > 0 )
3138 {
3139 $join_tables->foreach(sub{
3140 my $tbl = shift( @_ );
3141  
3142 return if( $tbl->name eq $self->name );
3143  
3144 my $this_query_object = $tbl->query_object;
3145 $tbl->_query_object_remove( $this_query_object ) if( $this_query_object );
3146  
3147 $tbl->use_bind(0) unless( $tbl->use_bind > 1 );
3148 $tbl->use_cache(0) unless( $tbl->use_cache > 1 );
3149  
3150 # Important: do NOT force query_reset to 1 here.
3151 # We want the next use to rebuild a fresh query object lazily.
3152 CORE::delete( $tbl->{query_reset} );
3153 return;
3154 });
3155 }
3156  
3157 $self->{bind} = 0 unless( defined( $self->{bind} ) && $self->{bind} > 1 );
3158 $self->{cache} = 0 unless( defined( $self->{cache} ) && $self->{cache} > 1 );
3159 return( $self->_query_object_get_or_create );
3160 }
3161 return( $self->_query_object_current );
3162 }
3163  
3164 sub _transaction_finished
3165 {
3166 my $self = shift( @_ );
3167 $self->{transaction} = 0;
3168 if( $self->{dbh} )
3169 {
3170 $self->{dbh}->{private_db_object} //= {};
3171 $self->{dbh}->{private_db_object}->{id} = $self->id;
3172 $self->{dbh}->{private_db_object}->{transaction} = 0;
3173 }
3174 return( $self );
3175 }
3176  
3177 sub _transaction_started
3178 {
3179 my $self = shift( @_ );
3180 $self->{transaction} = 1;
3181 if( $self->{dbh} )
3182 {
3183 $self->{dbh}->{private_db_object} //= {};
3184 $self->{dbh}->{private_db_object}->{id} = $self->id;
3185 $self->{dbh}->{private_db_object}->{transaction} = 1;
3186 }
3187 return( $self );
3188 }
3189  
3190 # NOTE: AUTOLOAD
3191 AUTOLOAD
3192 {
3193 my $self;
3194 $self = shift( @_ ) if( blessed( $_[ 0 ] ) || index( $_[0], '::' ) != -1 );
3195 my( $class, $meth );
3196 if( $self )
3197 {
3198 $class = ref( $self ) || $self;
3199 }
3200 $meth = $AUTOLOAD;
3201 if( CORE::index( $meth, '::' ) != -1 )
3202 {
3203 my $idx = rindex( $meth, '::' );
3204 $class = substr( $meth, 0, $idx );
3205 $meth = substr( $meth, $idx + 2 );
3206 }
3207 my @supported_class = DB::Object->supported_class;
3208 push( @supported_class, 'DB::Object' );
3209 my $ok_classes = join( '|', @supported_class );
3210 my $base_class = ( $class =~ /^($ok_classes)/ )[0];
3211  
3212 # Is it a table object that is being requested?
3213 # if( $self && scalar( grep{ /^$meth$/ } @$tables ) )
3214 # Getting table object take NO argument.
3215 # If the user wants to access a method, and somehow the table name is identical to one of our methods,
3216 # it is likely it will take an argument
3217 if( $class eq $base_class && !scalar( @_ ) && $self->table_exists( $meth ) )
3218 {
3219 return( $self->table( $meth ) );
3220 }
3221 elsif( $self && $self->can( $meth ) && defined( &{ "$class\::$meth" } ) )
3222 {
3223 return( $self->$meth( @_ ) );
3224 }
3225 # For imported subs
3226 elsif( defined( &$meth ) )
3227 {
3228 no strict 'refs';
3229 *{"${class}\::${meth}"} = \&$meth;
3230 unshift( @_, $self ) if( $self );
3231 return( &$meth( @_ ) );
3232 }
3233 # Taken from AutoLoader.pm
3234 elsif( $class =~ /^(?:$ok_classes)$/ )
3235 {
3236 my $filename;
3237 my $pkg = $class;
3238 $pkg =~ s/::/\//g;
3239 if( defined( $filename = $INC{ "$pkg.pm" } ) )
3240 {
3241 $filename =~ s%^(.*)$pkg\.pm\z%$1auto/${pkg}/${meth}.al%s;
3242 if( -r( $filename ) )
3243 {
3244 unless( $filename =~ m|^/|s )
3245 {
3246 $filename = "./$filename";
3247 }
3248 }
3249 else
3250 {
3251 $filename = undef();
3252 }
3253 }
3254 if( !defined( $filename ) )
3255 {
3256 $filename = "auto/${meth}.al";
3257 $filename =~ s/::/\//g;
3258 }
3259 my $save = $@;
3260 eval
3261 {
3262 local $SIG{__DIE__} = sub{ };
3263 local $SIG{__WARN__} = sub{ };
3264 require $filename;
3265 };
3266 if( $@ )
3267 {
3268 if( substr( $AUTOLOAD, -9 ) eq '::DESTROY' )
3269 {
3270 no strict 'refs';
3271 *$meth = sub {};
3272 }
3273 else
3274 {
3275 # The load might just have failed because the filename was too
3276 # long for some old SVR3 systems which treat long names as errors.
3277 # If we can succesfully truncate a long name then it's worth a go.
3278 # There is a slight risk that we could pick up the wrong file here
3279 # but autosplit should have warned about that when splitting.
3280 if( $filename =~ s/(\w{12,})\.al$/substr( $1, 0, 11 ) . ".al"/e )
3281 {
3282 eval
3283 {
3284 local $SIG{__DIE__} = sub{ };
3285 local $SIG{__WARN__} = sub{ };
3286 require $filename
3287 };
3288 }
3289 }
3290 }
3291 unless( $@ )
3292 {
3293 $@ = $save;
3294 unshift( @_, $self ) if( $self );
3295 goto &$meth;
3296 }
3297 $@ = $save;
3298 }
3299  
3300 if( $self && exists( $self->{sth} ) )
3301 {
3302 # e.g. $sth->pg_server_prepare => $self->{sth}->{pg_server_prepare}
3303 if( CORE::exists( $self->{sth}->{ $meth } ) )
3304 {
3305 $self->{sth}->{ $meth } = shift( @_ ) if( scalar( @_ ) );
3306 return( $self->{sth}->{ $meth } );
3307 }
3308 if( !$self->executed() )
3309 {
3310 $self->execute() || return( $self->error( $self->{sth}->errstr() ) );
3311 }
3312 # $self->_cleanup();
3313 # print( STDERR "Calling DBI method $meth with sth '$self->{sth}' arguments: '", join( "', '", @_ ), "'\n" ) if( $DEBUG );
3314 # *{ "${class}\::$meth" } = sub{ return( shift->{ 'sth' }->$meth( @_ ) ); };
3315 # return( $self->{sth}->$meth( @_ ) );
3316 my $ctx = Wanted::context();
3317 if( $ctx eq 'LIST' )
3318 {
3319 local $@;
3320 my @rv = eval{ $self->{sth}->$meth( @_ ); };
3321 if( $@ )
3322 {
3323 # We set the error
3324 $self->error( "Error calling $meth: $@" );
3325 }
3326 # From DBI documentation:
3327 # "If there are no more rows or if an error occurs, then fetchrow_array returns an empty list. You should check $sth->err afterwards (or use the RaiseError attribute) to discover if the empty list returned was due to an error."
3328 # Also: <https://metacpan.org/pod/DBI#errstr>
3329 elsif( !scalar( @rv ) && $self->{sth}->err )
3330 {
3331 $self->error({ code => $self->{sth}->err, message => $self->{sth}->errstr });
3332 }
3333 # We still return whatever was retrieved
3334 return( @rv );
3335 }
3336 else
3337 {
3338 local $@;
3339 my $rv = eval{ $self->{sth}->$meth( @_ ); };
3340 if( $@ )
3341 {
3342 # We set the error
3343 $self->error( "Error calling $meth: $@" );
3344 }
3345 # From DBI documentation:
3346 # "If there are no more rows or if an error occurs, then fetchrow_array returns an empty list. You should check $sth->err afterwards (or use the RaiseError attribute) to discover if the empty list returned was due to an error."
3347 # Also: <https://metacpan.org/pod/DBI#errstr>
3348 elsif( !defined( $rv ) && $self->{sth}->err )
3349 {
3350 $self->error({ code => $self->{sth}->err, message => $self->{sth}->errstr });
3351 }
3352  
3353 # We check if the user is asking for chaining, but the returned value is undef.
3354 # We want to avoid the famous Perl error: "Can't call method "%s" on an undefined value"
3355 # See perldiag man page.
3356 if( !defined( $rv ) )
3357 {
3358 # $ctx returns also CODE, HASH, ARRAY, GLOB, SCALAR or OBJECT
3359 if( $ctx eq 'HASH' )
3360 {
3361 return( {} );
3362 }
3363 elsif( $ctx eq 'ARRAY' )
3364 {
3365 return( [] );
3366 }
3367 }
3368 return( $rv );
3369 }
3370 }
3371 # e.g. $dbh->pg_notifies
3372 elsif( $self && ( ( $self->{dbh} && $self->{dbh}->can( $meth ) ) || defined( &{ "DBI::db::" . $meth } ) ) )
3373 {
3374 return( $self->{dbh}->$meth( @_ ) );
3375 }
3376 # e.g. $dbh->pg_enable_utf8 becomes $self->{dbh}->{pg_enable_utf8]
3377 elsif( $self && $self->{dbh} && CORE::exists( $self->{dbh}->{ $meth } ) )
3378 {
3379 $self->{dbh}->{ $meth } = shift( @_ ) if( scalar( @_ ) );
3380 return( $self->{dbh}->{ $meth } );
3381 }
3382 elsif( defined( &{ "DBI::" . $meth } ) )
3383 {
3384 my $h = &{ "DBI::" . $meth }( @_ );
3385 if( defined( $h ) )
3386 {
3387 bless( $h, $class );
3388 return( $h );
3389 }
3390 else
3391 {
3392 return;
3393 }
3394 }
3395 my $what = $self ? $self : $class;
3396 return( $what->error( "${class}::AUTOLOAD: Not defined in $class and not autoloadable (last try $meth)" ) );
3397 }
3398  
3399 # NOTE: DESTROY
3400 sub DESTROY
3401 {
3402 # <https://perldoc.perl.org/perlobj#Destructors>
3403 CORE::local( $., $@, $!, $^E, $? );
3404 CORE::return if( ${^GLOBAL_PHASE} eq 'DESTRUCT' );
3405 my $self = CORE::shift( @_ );
3406 CORE::return if( !CORE::defined( $self ) );
3407 my $class = ref( $self ) || $self;
3408 if( $self->{sth} )
3409 {
3410 print( STDERR "DESTROY(): Terminating sth '$self' for query:\n$self->{query}\n" ) if( $DEBUG || $self->{debug} );
3411 $self->{sth}->finish();
3412 }
3413 elsif( $self->{dbh} && $class =~ /^DB\:\:Object(?:\:\:(?:Postgres|Mysql|SQLite))?$/ )
3414 {
3415 local( $SIG{__WARN__} ) = sub{};
3416 # $self->{ 'dbh' }->disconnect();
3417 $self->disconnect();
3418 }
3419 my $locks = $self->{_locks};
3420 if( $locks && $self->_is_array( $locks ) )
3421 {
3422 foreach my $name ( @$locks )
3423 {
3424 $self->unlock( $name );
3425 }
3426 }
3427  
3428 my $repo = Module::Generic::Global->new( 'available_databases' => $class, key => $class );
3429 $repo->cleanup;
3430 my $table_repo = Module::Generic::Global->new( table_cache => 'system' );
3431 $table_repo->cleanup;
3432 # 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.
3433 }
3434  
3435 # NOTE: package DB::Object::Operator
3436 package DB::Object::Operator;
3437 BEGIN
3438 {
3439 use strict;
3440 use parent qw( Module::Generic );
3441 };
3442  
3443 sub init
3444 {
3445 my $self = shift( @_ );
3446 $self->{operator} = undef;
3447 $self->{query_object} = undef;
3448 $self->{value} = [];
3449 $self->{_init_strict_use_sub} = 1;
3450 $self->SUPER::init( @_ ) || return( $self->pass_error );
3451 return( $self );
3452 }
3453  
3454 sub operator { return( '' ); }
3455  
3456 sub query_object { return( shift->_set_get_object_without_init( 'query_object', 'DB::Object::Query', @_ ) ); }
3457  
3458 # sub value { return( wantarray() ? @{$_[0]->{value}} : $_[0]->{value} ); }
3459 # wantlist option instructs this method to return a list in list context instead of the default array object
3460 sub value { return( shift->_set_get_array_as_object( { field => 'value', wantlist => 1 }, @_ ) ); }
3461  
3462 # For arguments that have a query object like statements, we coy their binded_types and binded_values to our current query object.
3463 # This is used by ALL, ANY and IN
3464 sub _copy_binded_elements
3465 {
3466 my $self = shift( @_ );
3467 my $base_class = $self->base_class;
3468 if( my $qo = $self->query_object )
3469 {
3470 $self->value->foreach(sub
3471 {
3472 my $this = shift( @_ );
3473 my $q;
3474 if( $self->_is_a( $this => "${base_class}::Statement" ) &&
3475 ( $q = $this->query_object ) )
3476 {
3477 $qo->binded_types->push( $q->binded_types->list );
3478 $qo->binded_values->push( $q->binded_values->list );
3479 }
3480 });
3481 }
3482 return( $self );
3483 }
3484  
3485 # Ref:
3486 # <https://www.postgresql.org/docs/12/arrays.html#ARRAYS-SEARCHING>
3487 # NOTE: package DB::Object::ALL
3488 package DB::Object::ALL;
3489 BEGIN
3490 {
3491 use strict;
3492 use warnings;
3493 use parent -norequire, qw( DB::Object::Operator );
3494 use Scalar::Util ();
3495 use overload (
3496 '""' => 'as_string',
3497 'bool' => sub{1},
3498 '==' => sub{ &_opt_overload( @_, '==' ) },
3499 '!=' => sub{ &_opt_overload( @_, '!=' ) },
3500 fallback => 1,
3501 );
3502 };
3503  
3504 sub init
3505 {
3506 my $self = shift( @_ );
3507 $self->SUPER::init( @_ ) || return( $self->pass_error );
3508 # $self->_copy_binded_elements || return( $self->pass_error );
3509 return( $self );
3510 }
3511  
3512 sub as_string
3513 {
3514 my $self = shift( @_ );
3515 my $vals = $self->value;
3516 my @list = ();
3517 foreach my $elem ( @$vals )
3518 {
3519 next unless( defined( $elem ) );
3520 if( Scalar::Util::blessed( $elem ) &&
3521 $elem->isa( 'DB::Object::Statement' ) )
3522 {
3523 push( @list, $elem->as_string );
3524 }
3525 else
3526 {
3527 push( @list, $elem );
3528 }
3529 }
3530 local $" = ',';
3531 my $sql = "ALL (@list)";
3532 return( $sql );
3533 }
3534  
3535 sub operator { return( 'ALL' ); }
3536  
3537 sub _opt_overload
3538 {
3539 my( $self, $val, $swap, $op ) = @_;
3540 my $map =
3541 {
3542 '!=' => '!= ',
3543 '<>' => '!= ',
3544 '==' => '= ',
3545 };
3546 my $not = $map->{ $op };
3547 if( !defined( $not ) )
3548 {
3549 warn( "Unknown operator '${op}'. Falling back to '='." );
3550 $not = $map->{ '==' };
3551 }
3552 my $in = $self->as_string;
3553 my $placeholder_re = $self->query_object->database_object->_placeholder_regexp;
3554 my $lval = ( Scalar::Util::blessed( $val ) && $val->isa( 'DB::Object::Fields::Field' ) )
3555 ? $val->name
3556 : ( $val =~ $placeholder_re || $self->_is_number( $val ) )
3557 ? $val
3558 : qq{'${val}'};
3559 return( DB::Object::Expression->new( "${lval} ${not}${in}" ) );
3560 }
3561  
3562 # NOTE: package DB::Object::AND
3563 package DB::Object::AND;
3564 BEGIN
3565 {
3566 use strict;
3567 use parent -norequire, qw( DB::Object::Operator );
3568 };
3569  
3570 sub operator { return( 'AND' ); }
3571  
3572 # Ref:
3573 # <https://www.postgresql.org/docs/12/arrays.html#ARRAYS-SEARCHING>
3574 # NOTE: package DB::Object::ANY
3575 package DB::Object::ANY;
3576 BEGIN
3577 {
3578 use strict;
3579 use warnings;
3580 use parent -norequire, qw( DB::Object::Operator );
3581 use Scalar::Util ();
3582 use overload (
3583 '""' => 'as_string',
3584 'bool' => sub{1},
3585 '==' => sub{ &_opt_overload( @_, '==' ) },
3586 '!=' => sub{ &_opt_overload( @_, '!=' ) },
3587 fallback => 1,
3588 );
3589 };
3590  
3591 sub init
3592 {
3593 my $self = shift( @_ );
3594 $self->SUPER::init( @_ ) || return( $self->pass_error );
3595 # $self->_copy_binded_elements || return( $self->pass_error );
3596 return( $self );
3597 }
3598  
3599 sub as_string
3600 {
3601 my $self = shift( @_ );
3602 my $vals = $self->value;
3603 my @list = ();
3604 foreach my $elem ( @$vals )
3605 {
3606 next unless( defined( $elem ) );
3607 if( Scalar::Util::blessed( $elem ) &&
3608 $elem->isa( 'DB::Object::Statement' ) )
3609 {
3610 push( @list, $elem->as_string );
3611 }
3612 else
3613 {
3614 push( @list, $elem );
3615 }
3616 }
3617 local $" = ',';
3618 my $sql = "ANY (@list)";
3619 return( $sql );
3620 }
3621  
3622 sub operator { return( 'ANY' ); }
3623  
3624 sub _opt_overload
3625 {
3626 my( $self, $val, $swap, $op ) = @_;
3627 my $map =
3628 {
3629 '!=' => '!= ',
3630 '==' => '= ',
3631 };
3632 my $not = $map->{ $op };
3633 if( !defined( $not ) )
3634 {
3635 warn( "Unknown operator '${op}'. Falling back to '='." );
3636 $not = $map->{ '==' };
3637 }
3638 my $in = $self->as_string;
3639 my $placeholder_re = $self->query_object->database_object->_placeholder_regexp;
3640 my $lval = ( Scalar::Util::blessed( $val ) && $val->isa( 'DB::Object::Fields::Field' ) )
3641 ? $val->name
3642 : ( $val =~ $placeholder_re || $self->_is_number( $val ) )
3643 ? $val
3644 : qq{'${val}'};
3645 return( DB::Object::Expression->new( "${lval} ${not}${in}" ) );
3646 }
3647  
3648 # NOTE: package DB::Object::Expression
3649 package DB::Object::Expression;
3650 BEGIN
3651 {
3652 use strict;
3653 use warnings;
3654 use overload (
3655 '""' => 'as_string',
3656 'bool' => sub{1},
3657 fallback => 1,
3658 );
3659 };
3660  
3661 sub new
3662 {
3663 my $that = shift( @_ );
3664 my $val = ( scalar( @_ ) == 1 && ref( $_[0] ) eq 'ARRAY' ) ? [ @{$_[0]} ] : [ @_ ];
3665 return( bless( { value => $val } => ( ref( $that ) || $that ) ) );
3666 }
3667  
3668 sub as_string
3669 {
3670 my $self = shift( @_ );
3671 my $vals = $self->components;
3672 return( join( ' ', @$vals ) );
3673 }
3674  
3675 sub components { return( wantarray() ? @{$_[0]->{value}} : $_[0]->{value} ); }
3676  
3677  
3678 # Ref:
3679 # <https://www.postgresql.org/docs/12/functions-subquery.html#FUNCTIONS-SUBQUERY-IN>
3680 # <https://www.postgresql.org/docs/12/functions-comparisons.html#FUNCTIONS-COMPARISONS-IN-SCALAR>
3681 # <https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#operator_in>
3682 # <https://www.sqlite.org/lang_expr.html#the_in_and_not_in_operators>
3683 # NOTE: package DB::Object::IN
3684 package DB::Object::IN;
3685 BEGIN
3686 {
3687 use strict;
3688 use warnings;
3689 use parent -norequire, qw( DB::Object::Operator );
3690 use Scalar::Util ();
3691 use overload (
3692 '""' => 'as_string',
3693 'bool' => sub{1},
3694 '==' => sub{ &_opt_overload( @_, '==' ) },
3695 '!=' => sub{ &_opt_overload( @_, '!=' ) },
3696 fallback => 1,
3697 );
3698 };
3699  
3700 sub init
3701 {
3702 my $self = shift( @_ );
3703 $self->SUPER::init( @_ ) || return( $self->pass_error );
3704 # $self->_copy_binded_elements || return( $self->pass_error );
3705 return( $self );
3706 }
3707  
3708 sub as_string
3709 {
3710 my $self = shift( @_ );
3711 my $vals = $self->value;
3712 my @list = ();
3713 foreach my $elem ( @$vals )
3714 {
3715 next unless( defined( $elem ) );
3716 if( Scalar::Util::blessed( $elem ) &&
3717 $elem->isa( 'DB::Object::Statement' ) )
3718 {
3719 push( @list, $elem->as_string );
3720 }
3721 else
3722 {
3723 push( @list, $elem );
3724 }
3725 }
3726 local $" = ',';
3727 my $sql = "IN (@list)";
3728 return( $sql );
3729 }
3730  
3731 sub operator { return( 'IN' ); }
3732  
3733 sub _opt_overload
3734 {
3735 my( $self, $val, $swap, $op ) = @_;
3736 my $map =
3737 {
3738 '!=' => 'NOT ',
3739 '<>' => 'NOT ',
3740 '==' => '',
3741 };
3742 my $not = $map->{ $op } // '';
3743 my $in = $self->as_string;
3744 my $placeholder_re = $self->query_object->database_object->_placeholder_regexp;
3745 my $lval = ( Scalar::Util::blessed( $val ) && $val->isa( 'DB::Object::Fields::Field' ) )
3746 ? $val->name
3747 : ( $val =~ $placeholder_re || $self->_is_number( $val ) )
3748 ? $val
3749 : qq{'${val}'};
3750 return( DB::Object::Expression->new( "${lval} ${not}${in}" ) );
3751 }
3752  
3753 # Ref:
3754 # <https://www.postgresql.org/docs/current/functions-matching.html>
3755 # <https://dev.mysql.com/doc/refman/8.4/en/pattern-matching.html>
3756 # <https://www.sqlite.org/lang_corefunc.html#like>
3757 # <https://www.sqlite.org/lang_expr.html#the_like_glob_regexp_match_and_extract_operators>
3758 # NOTE: package DB::Object::LIKE
3759 # TODO: Finish the class DB::Object::LIKE
3760 package DB::Object::LIKE;
3761 BEGIN
3762 {
3763 use strict;
3764 use warnings;
3765 use parent -norequire, qw( DB::Object::Operator );
3766 use Scalar::Util ();
3767 use overload (
3768 '""' => 'as_string',
3769 'bool' => sub{1},
3770 '==' => sub{ &_opt_overload( @_, '==' ) },
3771 '!=' => sub{ &_opt_overload( @_, '!=' ) },
3772 fallback => 1,
3773 );
3774 };
3775  
3776 sub init
3777 {
3778 my $self = shift( @_ );
3779 $self->SUPER::init( @_ ) || return( $self->pass_error );
3780 # $self->_copy_binded_elements || return( $self->pass_error );
3781 return( $self );
3782 }
3783  
3784 sub as_string
3785 {
3786 my $self = shift( @_ );
3787 my $vals = $self->value;
3788 # Parameters can be given as an array for convenience, and they will concatenated
3789 my $sql = "LIKE '" . join( '', @$vals ) . "'";
3790 return( $sql );
3791 }
3792  
3793 sub _opt_overload
3794 {
3795 my( $self, $val, $swap, $op ) = @_;
3796 my $map =
3797 {
3798 '!=' => 'NOT ',
3799 '<>' => 'NOT ',
3800 '==' => '',
3801 };
3802 my $not = $map->{ $op } // '';
3803 my $like = $self->as_string;
3804 my $placeholder_re = $self->query_object->database_object->_placeholder_regexp;
3805 my $lval = ( Scalar::Util::blessed( $val ) && $val->isa( 'DB::Object::Fields::Field' ) )
3806 ? $val->name
3807 : ( $val =~ $placeholder_re || $self->_is_number( $val ) )
3808 ? $val
3809 : qq{'${val}'};
3810 return( DB::Object::Expression->new( "${lval} ${not}${like}" ) );
3811 }
3812  
3813  
3814 # NOTE: package DB::Object::NOT
3815 package DB::Object::NOT;
3816 BEGIN
3817 {
3818 use strict;
3819 use parent -norequire, qw( DB::Object::Operator );
3820 };
3821  
3822 sub operator { return( 'NOT' ); }
3823  
3824 # NOTE: package DB::Object::OR
3825 package DB::Object::OR;
3826 BEGIN
3827 {
3828 use strict;
3829 use parent -norequire, qw( DB::Object::Operator );
3830 };
3831  
3832 sub operator { return( 'OR' ); }
3833  
3834 1;
3835 # NOTE: POD
3836 __END__