| 1 | # -*- perl -*- | ||
| 2 | ##---------------------------------------------------------------------------- | ||
| 3 | ## Database Object Interface - ~/lib/DB/Object/Statement.pm | ||
| 4 | ## Version v0.9.0 | ||
| 5 | ## Copyright(c) 2026 DEGUEST Pte. Ltd. | ||
| 6 | ## Author: Jacques Deguest <jack@deguest.jp> | ||
| 7 | ## Created 2017/07/19 | ||
| 8 | ## Modified 2026/03/27 | ||
| 9 | ## All rights reserved | ||
| 10 | ## | ||
| 11 | ## | ||
| 12 | ## This program is free software; you can redistribute it and/or modify it | ||
| 13 | ## under the same terms as Perl itself. | ||
| 14 | ##---------------------------------------------------------------------------- | ||
| 15 | ## This package's purpose is to automatically terminate the statement object and | ||
| 16 | ## separate them from the connection object (DB::Object). | ||
| 17 | ## Connection object last longer than statement objects | ||
| 18 | ##---------------------------------------------------------------------------- | ||
| 19 | package DB::Object::Statement; | ||
| 20 | BEGIN | ||
| 21 | { | ||
| 22 | use strict; | ||
| 23 | use warnings; | ||
| 24 | use parent qw( DB::Object ); | ||
| 25 | use vars qw( $VERSION $DEBUG $EXCEPTION_CLASS ); | ||
| 26 | use Scalar::Util (); | ||
| 27 | use Class::Struct qw( struct ); | ||
| 28 | use Wanted; | ||
| 29 | our $DEBUG = 0; | ||
| 30 | our $EXCEPTION_CLASS = $DB::Object::EXCEPTION_CLASS; | ||
| 31 | our $VERSION = 'v0.9.0'; | ||
| 32 | }; | ||
| 33 | |||
| 34 | use strict; | ||
| 35 | use warnings; | ||
| 36 | |||
| 37 | sub init | ||
| 38 | { | ||
| 39 | my $self = shift( @_ ); | ||
| 40 | $self->{_exception_class} = $EXCEPTION_CLASS; | ||
| 41 | $self->Module::Generic::init( @_ ) || return( $self->pass_error ); | ||
| 42 | return( $self ); | ||
| 43 | } | ||
| 44 | |||
| 45 | sub as_string | ||
| 46 | { | ||
| 47 | my $self = shift( @_ ); | ||
| 48 | # my $q = $self->_query_object_current; | ||
| 49 | # used by select, insert, update, delete to flag that we need to reformat the query | ||
| 50 | $self->{as_string}++; | ||
| 51 | if( my $qo = $self->query_object ) | ||
| 52 | { | ||
| 53 | $qo->final(1); | ||
| 54 | } | ||
| 55 | # return( $self->{sth}->{Statement} ); | ||
| 56 | # Same: | ||
| 57 | # return( $q->as_string ); | ||
| 58 | return( $self->{query} ); | ||
| 59 | } | ||
| 60 | |||
| 61 | sub attach | ||
| 62 | { | ||
| 63 | my $self = shift( @_ ); | ||
| 64 | my $dbo = shift( @_ ) || | ||
| 65 | return( $self->error( "No DB::Object object was provided." ) ); | ||
| 66 | my $base_class = $self->base_class; | ||
| 67 | unless( $self->_is_a( $dbo => $base_class ) ) | ||
| 68 | { | ||
| 69 | return( $self->error( "Value provided is not a ${base_class} object." ) ); | ||
| 70 | } | ||
| 71 | $self->database_object( $dbo ) || return( $self->pass_error ); | ||
| 72 | if( my $tbl = $self->table_object ) | ||
| 73 | { | ||
| 74 | if( $self->_is_a( $tbl => "${base_class}::Tables" ) ) | ||
| 75 | { | ||
| 76 | $self->_load_class( "${base_class}::Tables" ) || return( $self->pass_error ); | ||
| 77 | $tbl->attach( $dbo ); | ||
| 78 | } | ||
| 79 | else | ||
| 80 | { | ||
| 81 | warn( "Table object found (", $self->_str_val( $tbl ), ") in this statement object is actually not a table object (${base_class}::Tables) !" ); | ||
| 82 | $self->table_object( undef ); | ||
| 83 | } | ||
| 84 | } | ||
| 85 | if( my $qo = $self->query_object ) | ||
| 86 | { | ||
| 87 | unless( $self->_is_a( $qo => "${base_class}::Query" ) ) | ||
| 88 | { | ||
| 89 | die( "Query object found (", $self->_str_val( $qo ), ") in this statement object is actually not a query object (${base_class}::Query) !" ); | ||
| 90 | } | ||
| 91 | $self->_load_class( "${base_class}::Query" ) || return( $self->pass_error ); | ||
| 92 | $qo->attach( $dbo ); | ||
| 93 | } | ||
| 94 | return( $self ); | ||
| 95 | } | ||
| 96 | |||
| 97 | sub bind_param | ||
| 98 | { | ||
| 99 | my $self = shift( @_ ); | ||
| 100 | my( $pack, $file, $line ) = caller(); | ||
| 101 | my $sub = ( caller(1) )[3]; | ||
| 102 | $self->{pack} = $pack; | ||
| 103 | $self->{file} = $file; | ||
| 104 | $self->{line} = $line; | ||
| 105 | $self->{sub} = $sub; | ||
| 106 | my $rc = eval | ||
| 107 | { | ||
| 108 | $self->{sth}->bind_param( @_ ); | ||
| 109 | }; | ||
| 110 | if( $@ ) | ||
| 111 | { | ||
| 112 | my $err = $self->errstr(); | ||
| 113 | $err =~ s/ at line \d+.*$//; | ||
| 114 | # printf( STDERR "%s in %s at line %d within sub '%s'.\n", $err, $self->{file}, $self->{line}, $self->{sub} ); | ||
| 115 | # exit(1); | ||
| 116 | return( $self->error( $err ) ); | ||
| 117 | } | ||
| 118 | elsif( $rc ) | ||
| 119 | { | ||
| 120 | return( $rc ); | ||
| 121 | } | ||
| 122 | else | ||
| 123 | { | ||
| 124 | my $err = $@ = $self->{sth}->errstr() || "Unknown error while binding parameters to query."; | ||
| 125 | return( $self->error( $err ) ); | ||
| 126 | } | ||
| 127 | } | ||
| 128 | |||
| 129 | sub commit | ||
| 130 | { | ||
| 131 | my $self = shift( @_ ); | ||
| 132 | if( $self->{sth} && $self->param( 'autocommit' ) ) | ||
| 133 | { | ||
| 134 | my $sth = $self->prepare( 'COMMIT' ) || return( $self->pass_error ); | ||
| 135 | $sth->execute() || return( $self->error( "An error occurred while executing query: ", $sth->error ) ); | ||
| 136 | $sth->finish(); | ||
| 137 | } | ||
| 138 | return( $self ); | ||
| 139 | } | ||
| 140 | |||
| 141 | sub database_object { return( shift->_set_get_object_without_init( 'dbo', 'DB::Object', @_ ) ); } | ||
| 142 | |||
| 143 | sub distinct | ||
| 144 | { | ||
| 145 | my $self = shift( @_ ); | ||
| 146 | my $query = $self->{query} || | ||
| 147 | return( $self->error( "No query to set as to be ignored." ) ); | ||
| 148 | |||
| 149 | my $type = uc( ( $query =~ /^\s*(\S+)\s+/ )[0] ); | ||
| 150 | # ALTER for table alteration statements (DB::Object::Tables | ||
| 151 | my @allowed = qw( SELECT ); | ||
| 152 | my $allowed = CORE::join( '|', @allowed ); | ||
| 153 | if( !scalar( grep{ /^$type$/i } @allowed ) ) | ||
| 154 | { | ||
| 155 | return( $self->error( "You may not flag statement of type \U$type\E to be distinct:\n$query" ) ); | ||
| 156 | } | ||
| 157 | # Incompatible. Do not bother going further | ||
| 158 | return( $self ) if( $query =~ /^\s*(?:$allowed)\s+(?:DISTINCT|DISTINCTROW|ALL)\s+/i ); | ||
| 159 | |||
| 160 | $query =~ s/^(\s*)($allowed)(\s+)/$1$2 DISTINCT /; | ||
| 161 | # my $sth = $self->prepare( $query ) || | ||
| 162 | # $self->{ 'query' } = $query; | ||
| 163 | # saving parameters to bind later on must have been done previously | ||
| 164 | my $sth = $self->_cache_this( $query ) || | ||
| 165 | return( $self->error( "Error while preparing new ignored query:\n$query" ) ); | ||
| 166 | if( !defined( wantarray() ) ) | ||
| 167 | { | ||
| 168 | $sth->execute() || | ||
| 169 | return( $self->error( "Error while executing new ignored query:\n$query" ) ); | ||
| 170 | } | ||
| 171 | return( $sth ); | ||
| 172 | } | ||
| 173 | |||
| 174 | sub dump | ||
| 175 | { | ||
| 176 | my $self = shift( @_ ); | ||
| 177 | my $file = shift( @_ ); | ||
| 178 | if( $file ) | ||
| 179 | { | ||
| 180 | # Used to be handled by SQL server | ||
| 181 | # my $query = $self->as_string(); | ||
| 182 | # $query =~ s/(\s+FROM\s+)/ INTO OUTFILE '$file'$1/; | ||
| 183 | # my $sth = $self->prepare( $query ) || | ||
| 184 | # return( $self->error( "Error while preparing query to dump result on select:\n$query" ) ); | ||
| 185 | # $sth->execute() || | ||
| 186 | # return( $self->error( "Error while executing query to dump result on select:\n$query" ) ); | ||
| 187 | $self->_load_class( 'DateTime' ) || return( $self->pass_error ); | ||
| 188 | my $fields = $self->{_fields}; | ||
| 189 | my @header = sort{ $fields->{ $a } <=> $fields->{ $b } } keys( %$fields ); | ||
| 190 | # new_file is inherited from Module::Generic | ||
| 191 | $file = $self->new_file( $file ); | ||
| 192 | my $io = $file->open( '>', { binmode => 'utf8' }) || | ||
| 193 | return( $self->error( "Unable to open file '$file' in write mode: ", $file->error ) ); | ||
| 194 | my $date = DateTime->now; | ||
| 195 | my $table = $self->{table}; | ||
| 196 | $io->printf( "## Generated on %s for table $table\n", $date->strftime( '%c' ) ); | ||
| 197 | $io->print( "## ", CORE::join( "\t", @header ), "\n" ); | ||
| 198 | my @data = (); | ||
| 199 | while( @data = $self->fetchrow() ) | ||
| 200 | { | ||
| 201 | print( $io CORE::join( "\t", @data ), "\n" ); | ||
| 202 | } | ||
| 203 | $io->close; | ||
| 204 | $self->finish; | ||
| 205 | return( $self ); | ||
| 206 | } | ||
| 207 | elsif( exists( $self->{sth} ) ) | ||
| 208 | { | ||
| 209 | # my $fields = $self->{ '_fields' }; | ||
| 210 | my @fields = @{ $self->{sth}->FETCH( 'NAME' ) }; | ||
| 211 | my $max = 0; | ||
| 212 | # foreach my $field ( keys( %$fields ) ) | ||
| 213 | foreach my $field ( @fields ) | ||
| 214 | { | ||
| 215 | $max = length( $field ) if( length( $field ) > $max ); | ||
| 216 | } | ||
| 217 | my $template = ''; | ||
| 218 | ## foreach my $field ( sort{ $fields->{ $a } <=> $fields->{ $b } } keys( %$fields ) ) | ||
| 219 | foreach my $field ( @fields ) | ||
| 220 | { | ||
| 221 | $template .= "$field" . ( '.' x ( $max - length( $field ) ) ) . ": %s\n"; | ||
| 222 | } | ||
| 223 | $template .= "\n"; | ||
| 224 | my @data = (); | ||
| 225 | while( @data = $self->fetchrow() ) | ||
| 226 | { | ||
| 227 | printf( STDERR $template, @data ); | ||
| 228 | } | ||
| 229 | $self->finish; | ||
| 230 | return( $self ); | ||
| 231 | } | ||
| 232 | else | ||
| 233 | { | ||
| 234 | return( $self->error( "No query to dump." ) ); | ||
| 235 | } | ||
| 236 | } | ||
| 237 | |||
| 238 | sub exec { return( shift->execute( @_ ) ); } | ||
| 239 | |||
| 240 | sub execute | ||
| 241 | { | ||
| 242 | my $self = shift( @_ ); | ||
| 243 | my @args = @_; | ||
| 244 | # Resolve caller context only when needed for error reporting or debug. | ||
| 245 | # Calling caller() unconditionally on every execute() is expensive. | ||
| 246 | if( $self->debug || !$self->{pack} ) | ||
| 247 | { | ||
| 248 | my( $pack, $file, $line ) = caller(); | ||
| 249 | my $sub = ( caller(1) )[3]; | ||
| 250 | # What we want is to get the point from where we were originatly called | ||
| 251 | my $class = 'DB::Object'; | ||
| 252 | if( substr( $pack, 0, length( $class ) ) eq $class ) | ||
| 253 | { | ||
| 254 | for( my $i = 1; $i < 5; $i++ ) | ||
| 255 | { | ||
| 256 | ( $pack, $file, $line ) = caller( $i ); | ||
| 257 | $sub = ( caller( $i + 1 ) )[3]; | ||
| 258 | last if( substr( $pack, 0, length( $class ) ) ne $class ); | ||
| 259 | } | ||
| 260 | } | ||
| 261 | $self->{pack} = $pack; | ||
| 262 | $self->{file} = $file; | ||
| 263 | $self->{line} = $line; | ||
| 264 | $self->{sub} = $sub; | ||
| 265 | } | ||
| 266 | $self->{executed}++; | ||
| 267 | my $q = $self->query_object; | ||
| 268 | $q->final(1) if( $q ); | ||
| 269 | my @binded = (); | ||
| 270 | my @binded_types = (); | ||
| 271 | # Boolean used so we do not automatically change a string litteral into an array if | ||
| 272 | # the number of types and values are not the same, as it would lead to undesirable results. | ||
| 273 | my $bind_mismatch = 0; | ||
| 274 | my $el; | ||
| 275 | # As a rule, if the first placeholder is a numbered one, then all are, because we cannot mix numbered placeholder and non-numbered ones. | ||
| 276 | my $use_numbered_placeholders = ( ( $q && $q->elements->first->is_numbered ) ? 1 : 0 ); | ||
| 277 | if( $q && | ||
| 278 | ( $el = $q->elements ) && | ||
| 279 | $el->types->length ) | ||
| 280 | { | ||
| 281 | my $types = $q->binded_types_as_param; | ||
| 282 | @binded_types = @$types; | ||
| 283 | } | ||
| 284 | |||
| 285 | if( defined( $el ) ) | ||
| 286 | { | ||
| 287 | } | ||
| 288 | |||
| 289 | # Get the values to bind | ||
| 290 | if( $q && $self->{bind} ) | ||
| 291 | { | ||
| 292 | if( @_ && | ||
| 293 | ( | ||
| 294 | # hash reference | ||
| 295 | ( @_ == 1 && $self->_is_hash( $_[0] => 'strict' ) ) || | ||
| 296 | # key => value pairs | ||
| 297 | ( !( @_ % 2 ) && ref( $_[0] ) ne 'HASH' ) | ||
| 298 | ) | ||
| 299 | ) | ||
| 300 | { | ||
| 301 | my $vals = {}; | ||
| 302 | if( $self->_is_hash( $_[0] => 'strict' ) ) | ||
| 303 | { | ||
| 304 | $vals = shift( @_ ); | ||
| 305 | } | ||
| 306 | else | ||
| 307 | { | ||
| 308 | $vals = { @_ }; | ||
| 309 | } | ||
| 310 | # This is the list of fields as they appear in the order in insert or update query | ||
| 311 | # Knowing their order of appearance is key so we can bind follow-on values to them | ||
| 312 | my $sorted = $q->sorted; | ||
| 313 | foreach my $f ( @$sorted ) | ||
| 314 | { | ||
| 315 | if( !CORE::exists( $vals->{ $f } ) ) | ||
| 316 | { | ||
| 317 | push( @binded, undef() ); | ||
| 318 | } | ||
| 319 | # The value may be defined or not, or may be zero length long | ||
| 320 | else | ||
| 321 | { | ||
| 322 | push( @binded, $vals->{ $f } ); | ||
| 323 | } | ||
| 324 | } | ||
| 325 | } | ||
| 326 | elsif( @_ ) | ||
| 327 | { | ||
| 328 | push( @binded, @_ ); | ||
| 329 | } | ||
| 330 | else | ||
| 331 | { | ||
| 332 | # my $binded_values = $q->binded; | ||
| 333 | my $binded_values = $q->elements->values; | ||
| 334 | push( @binded, @$binded_values ) if( scalar( @$binded_values ) ); | ||
| 335 | } | ||
| 336 | } | ||
| 337 | |||
| 338 | @binded = @_ if( !@binded && @_ ); | ||
| 339 | @binded = () if( !@binded ); | ||
| 340 | if( $q && $q->is_upsert ) | ||
| 341 | { | ||
| 342 | if( !$use_numbered_placeholders && | ||
| 343 | scalar( @binded_types ) > scalar( @binded ) ) | ||
| 344 | { | ||
| 345 | CORE::push( @binded, @binded ); | ||
| 346 | } | ||
| 347 | } | ||
| 348 | |||
| 349 | if( scalar( @_ ) ) | ||
| 350 | { | ||
| 351 | my $temp = {}; | ||
| 352 | my $el; | ||
| 353 | $el = $q->elements->elements if( $q && $q->elements ); | ||
| 354 | local $" = ', '; | ||
| 355 | for( my $i = 0; $i < scalar( @args ); $i++ ) | ||
| 356 | { | ||
| 357 | # { $some_value => 'varchar' } | ||
| 358 | if( ref( $_[$i] ) eq 'HASH' && | ||
| 359 | scalar( keys( %{$_[$i]} ) ) == 1 && | ||
| 360 | # e.g. DBI::SQL_VARCHAR or DBI::SQL_INTEGER | ||
| 361 | DBI->can( "SQL_" . uc( [values( %{$_[$i]} )]->[0] ) ) ) | ||
| 362 | { | ||
| 363 | my $constant = DBI->can( "SQL_" . uc( [values( %{$_[$i]} )]->[0] ) ); | ||
| 364 | $temp->{$i} = { type => $constant->(), value => [keys( %{$_[$i]} )]->[0] }; | ||
| 365 | } | ||
| 366 | } | ||
| 367 | |||
| 368 | # The user has chosen to override any datatype computed and be explicit. | ||
| 369 | if( scalar( keys( %$temp ) ) == scalar( @_ ) ) | ||
| 370 | { | ||
| 371 | # @binded = @_; | ||
| 372 | @binded_types = (); | ||
| 373 | @binded = (); | ||
| 374 | foreach my $i ( sort( keys( %$temp ) ) ) | ||
| 375 | { | ||
| 376 | push( @binded_types, $temp->{ $i }->{type} ); | ||
| 377 | push( @binded, $temp->{ $i }->{value} ); | ||
| 378 | } | ||
| 379 | } | ||
| 380 | elsif( scalar( keys( %$temp ) ) ) | ||
| 381 | { | ||
| 382 | foreach my $i ( sort( keys( %$temp ) ) ) | ||
| 383 | { | ||
| 384 | CORE::splice( @binded_types, $i, 1, $temp->{ $i }->{type} ); | ||
| 385 | $binded[$i] = $temp->{ $i }->{value}; | ||
| 386 | } | ||
| 387 | } | ||
| 388 | } | ||
| 389 | |||
| 390 | if( $q && scalar( @binded ) != scalar( @binded_types ) ) | ||
| 391 | { | ||
| 392 | # Flag we use a bit below | ||
| 393 | $bind_mismatch++; | ||
| 394 | warn( sprintf( "Warning: total %d bound values does not match the total %d bound types ('%s')! Check the code for query $self->{sth}->{Statement}\n", scalar( @binded ), scalar( @binded_types ), CORE::join( "','", map{ ref( $_ ) eq 'HASH' ? $self->Module::Generic::dump( $_ ) : $_ } @binded_types ) ) ); | ||
| 395 | # Cancel it, because it will create problems | ||
| 396 | @binded_types = (); | ||
| 397 | } | ||
| 398 | |||
| 399 | # If there are any array object of some sort provided, make sure they are transformed into a regular array so DBD::Ph can then transform it into a Postgres array. | ||
| 400 | for( my $i = 0; $i < scalar( @binded ); $i++ ) | ||
| 401 | { | ||
| 402 | next if( !defined( $binded[$i] ) ); | ||
| 403 | my $elem; | ||
| 404 | if( defined( $el ) && | ||
| 405 | !$bind_mismatch && | ||
| 406 | ( $elem = $el->elements->[$i] ) && | ||
| 407 | defined( $elem ) && | ||
| 408 | $self->_is_a( $elem->fo => 'DB::Object::Fields::Field' ) ) | ||
| 409 | { | ||
| 410 | } | ||
| 411 | |||
| 412 | if( defined( $el ) && | ||
| 413 | !$bind_mismatch && | ||
| 414 | ( $elem = $el->elements->[$i] ) && | ||
| 415 | defined( $elem ) && | ||
| 416 | $self->_is_a( $elem->fo => 'DB::Object::Fields::Field' ) && | ||
| 417 | $elem->fo->is_array && | ||
| 418 | !$self->_is_array( $binded[$i] ) && | ||
| 419 | defined( $binded[$i] ) ) | ||
| 420 | { | ||
| 421 | $binded[$i] = $self->_is_number( $binded[$i] ) ? [$binded[$i]] : [$self->database_object->quote( $binded[$i] )]; | ||
| 422 | } | ||
| 423 | elsif( defined( $el ) && | ||
| 424 | !$bind_mismatch && | ||
| 425 | ( $elem = $el->elements->[$i] ) && | ||
| 426 | defined( $elem ) && | ||
| 427 | $self->_is_a( $elem->fo => 'DB::Object::Fields::Field' ) && | ||
| 428 | ( $elem->fo->type eq 'jsonb' || $elem->fo->type eq 'json' ) && | ||
| 429 | $self->_is_hash( $binded[$i] => 'strict' ) ) | ||
| 430 | { | ||
| 431 | # try-catch | ||
| 432 | local $@; | ||
| 433 | my $json = eval | ||
| 434 | { | ||
| 435 | $self->new_json->encode( $binded[$i] ); | ||
| 436 | }; | ||
| 437 | if( $@ ) | ||
| 438 | { | ||
| 439 | warn( "Error trying to encode hash value ", $binded[$i], ": $@" ) if( $self->_is_warnings_enabled( 'DB::Object' ) ); | ||
| 440 | } | ||
| 441 | else | ||
| 442 | { | ||
| 443 | $binded[$i] = $json; | ||
| 444 | } | ||
| 445 | } | ||
| 446 | # If the value provided is a DateTime object without a formatter, we transform the given value into a ISO8601 datetime string | ||
| 447 | elsif( defined( $el ) && | ||
| 448 | !$bind_mismatch && | ||
| 449 | ( $elem = $el->elements->[$i] ) && | ||
| 450 | defined( $elem ) && | ||
| 451 | $self->_is_a( $elem->fo => 'DB::Object::Fields::Field' ) && | ||
| 452 | ( $elem->fo->type =~ /^(date|timestamp)/i || $elem->fo->datatype->alias->grep( qr/^(date|timestamp)/i )->length ) && | ||
| 453 | defined( $binded[$i] ) && | ||
| 454 | $self->_is_a( $binded[$i] => 'DateTime' ) && | ||
| 455 | # There is no formatter | ||
| 456 | !$binded[$i]->formatter ) | ||
| 457 | { | ||
| 458 | $binded[$i] = $binded[$i]->iso8601; | ||
| 459 | } | ||
| 460 | |||
| 461 | # The value is an array object, but not a simple array, so we need to convert it | ||
| 462 | # or else the driver will not understand nor accept it. | ||
| 463 | if( $self->_is_array( $binded[$i] ) && | ||
| 464 | ref( $binded[$i] ) ne 'ARRAY' ) | ||
| 465 | { | ||
| 466 | $binded[$i] = [@{$binded[$i]}]; | ||
| 467 | } | ||
| 468 | elsif( $self->_is_object( $binded[$i] ) && | ||
| 469 | overload::Overloaded( $binded[$i] ) && | ||
| 470 | overload::Method( $binded[$i], '""' ) ) | ||
| 471 | { | ||
| 472 | no warnings 'uninitialized'; | ||
| 473 | my $v = "$binded[$i]"; | ||
| 474 | $binded[$i] = defined( $v ) ? $v : undef; | ||
| 475 | } | ||
| 476 | # Will work well with Module::Generic::Hash | ||
| 477 | elsif( $self->_is_hash( $binded[$i] ) && | ||
| 478 | $self->_can( $binded[$i], 'as_json' ) ) | ||
| 479 | { | ||
| 480 | $binded[$i] = $binded[$i]->as_json; | ||
| 481 | } | ||
| 482 | } | ||
| 483 | |||
| 484 | local $_; | ||
| 485 | my $rv = eval | ||
| 486 | { | ||
| 487 | local( $SIG{ALRM} ) = sub{ die( "Timeout while processing query $self->{sth}->{Statement}\n" ) }; | ||
| 488 | for( my $i = 0; $i < scalar( @binded ); $i++ ) | ||
| 489 | { | ||
| 490 | # Stringify the binded value if it is a stringifyable object. | ||
| 491 | if( ref( $binded[$i] ) && | ||
| 492 | $self->_is_object( $binded[$i] ) && | ||
| 493 | overload::Overloaded( $binded[$i] ) && | ||
| 494 | overload::Method( $binded[$i], '""' ) ) | ||
| 495 | { | ||
| 496 | $binded[$i] .= ''; | ||
| 497 | } | ||
| 498 | |||
| 499 | my $data_type = $binded_types[ $i ]; | ||
| 500 | if( CORE::length( $data_type ) && $self->_is_hash( $data_type ) ) | ||
| 501 | { | ||
| 502 | $self->{sth}->bind_param( $i + 1, $binded[ $i ], $data_type ); | ||
| 503 | } | ||
| 504 | else | ||
| 505 | { | ||
| 506 | $self->{sth}->bind_param( $i + 1, $binded[ $i ] ); | ||
| 507 | } | ||
| 508 | } | ||
| 509 | $self->{sth}->execute(); | ||
| 510 | }; | ||
| 511 | my $error = $@; | ||
| 512 | $error ||= $self->{sth}->errstr if( !$rv ); | ||
| 513 | if( $q ) | ||
| 514 | { | ||
| 515 | # Only reset the table's query object if this is NOT a cached/reused joined statement. | ||
| 516 | # For joined statements, the query object ($q_source) is permanently attached to the | ||
| 517 | # statement handle and resetting the table creates a new ~500KB query object on every | ||
| 518 | # execute() that is never freed (the old one is orphaned). The reset serves to prepare | ||
| 519 | # the table for a fresh query after a one-shot select(), which is not the case here. | ||
| 520 | # A joined statement is identified by having join_tables populated. | ||
| 521 | # For a joined statement that is reused in a loop (exec() called multiple times), | ||
| 522 | # calling reset() on any of the tables is wasteful: it creates a new ~500KB query | ||
| 523 | # object for every single exec() call, and those objects are never freed because the | ||
| 524 | # allocator retains the arena pages. The reset was designed for one-shot select() | ||
| 525 | # usage, not for reused prepared statements. Skip it entirely for joined statements. | ||
| 526 | if( $q->join_tables->length == 0 ) | ||
| 527 | { | ||
| 528 | $q->table_object->reset; | ||
| 529 | } | ||
| 530 | } | ||
| 531 | my $tie = $self->{tie} || {}; | ||
| 532 | # Maybe it is time to bind SQL result to possible provided perl variables? | ||
| 533 | if( !$error && %$tie ) | ||
| 534 | { | ||
| 535 | my $order = $self->{tie_order}; | ||
| 536 | my $sth = $self->{sth}; | ||
| 537 | for( my $i = 0; $i < @$order; $i++ ) | ||
| 538 | { | ||
| 539 | my $pos = $i + 1; | ||
| 540 | my $val = $order->[ $i ]; | ||
| 541 | if( exists( $tie->{ $val } ) && ref( $tie->{ $val } ) eq 'SCALAR' ) | ||
| 542 | { | ||
| 543 | $sth->bind_col( $pos, $tie->{ $val } ); | ||
| 544 | } | ||
| 545 | } | ||
| 546 | } | ||
| 547 | if( $error ) | ||
| 548 | { | ||
| 549 | $error =~ s/ at (\S+\s)?line \d+.*$//s; | ||
| 550 | # $err .= ":\n\"$self->{ 'query' }\""; | ||
| 551 | $error .= ":\n\"$self->{sth}->{Statement}\""; | ||
| 552 | $error = "Error while trying to execute query $self->{sth}->{Statement}: $error"; | ||
| 553 | if( $self->fatal() ) | ||
| 554 | { | ||
| 555 | die( "$error in $self->{file} at line $self->{line} within sub $self->{sub}\n" ); | ||
| 556 | } | ||
| 557 | else | ||
| 558 | { | ||
| 559 | # return( $self->error( "$err in $self->{ 'file' } at line $self->{ 'line' } within sub $self->{ 'sub' }" ) ); | ||
| 560 | return( $self->error( $error ) ); | ||
| 561 | } | ||
| 562 | } | ||
| 563 | elsif( $self->{sth}->errstr() ) | ||
| 564 | { | ||
| 565 | return( $self->error( "Error while trying to execute query $self->{sth}->{Statement}: ", $self->{sth}->errstr ) ); | ||
| 566 | } | ||
| 567 | # Clear any error, since this query statement may be re-used | ||
| 568 | $self->clear_error; | ||
| 569 | |||
| 570 | # User wants an object for chaining like: | ||
| 571 | # $sth->exec( 'some value' )->fetchrow; | ||
| 572 | if( want( 'OBJECT' ) ) | ||
| 573 | { | ||
| 574 | return( $self ); | ||
| 575 | } | ||
| 576 | elsif( $rv ) | ||
| 577 | { | ||
| 578 | return( $rv ); | ||
| 579 | } | ||
| 580 | # For void context too | ||
| 581 | else | ||
| 582 | { | ||
| 583 | return(1); | ||
| 584 | } | ||
| 585 | } | ||
| 586 | |||
| 587 | sub executed | ||
| 588 | { | ||
| 589 | my $self = shift( @_ ); | ||
| 590 | # For hand made query to avoid clash when executing generic routine such as fetchall_arrayref... | ||
| 591 | return( 1 ) if( !exists( $self->{query} ) ); | ||
| 592 | return( exists( $self->{executed} ) && $self->{executed} ); | ||
| 593 | } | ||
| 594 | |||
| 595 | sub fetchall_arrayref($@) | ||
| 596 | { | ||
| 597 | my $self = shift( @_ ); | ||
| 598 | my $slice = shift( @_ ) || []; | ||
| 599 | my $dbo = $self->database_object; | ||
| 600 | my $sth = $self->{sth}; | ||
| 601 | if( !$self->executed() ) | ||
| 602 | { | ||
| 603 | $self->execute() || return; | ||
| 604 | } | ||
| 605 | # Ensure we set the cache of field names and types. We will need them to post process the query results with _convert_datetime2object() | ||
| 606 | # This is necessary for MySQL whose object lose that information, while the PostgreSQL or SQLite driver keep the information. | ||
| 607 | my $need_post_processing = ( ( $dbo->auto_decode_json || $dbo->auto_convert_datetime_to_object ) ? 1 : 0 ); | ||
| 608 | if( $need_post_processing ) | ||
| 609 | { | ||
| 610 | $self->_cache_field_names; | ||
| 611 | $self->_cache_field_types; | ||
| 612 | } | ||
| 613 | # $self->_cleanup(); | ||
| 614 | my $mode = ref( $slice ); | ||
| 615 | my @rows; | ||
| 616 | my $row; | ||
| 617 | if( $mode eq 'ARRAY' ) | ||
| 618 | { | ||
| 619 | if( @$slice ) | ||
| 620 | { | ||
| 621 | push( @rows, [ @{ $row }[ @{ $slice } ] ] ) while( $row = $sth->fetch() ); | ||
| 622 | } | ||
| 623 | else | ||
| 624 | { | ||
| 625 | push( @rows, [ @{ $row } ] ) while( $row = $sth->fetch ); | ||
| 626 | } | ||
| 627 | } | ||
| 628 | elsif( $mode eq 'HASH' ) | ||
| 629 | { | ||
| 630 | my @o_keys = keys( %$slice ); | ||
| 631 | if( @o_keys ) | ||
| 632 | { | ||
| 633 | # my %i_names = map{ ( lc( $_ ) => $_ ) } @{ $sth->FETCH( 'NAME' ) }; | ||
| 634 | # my @i_keys = map{ $i_names{ lc( $_ ) } } @o_keys; | ||
| 635 | my $i_keys = $self->field_names_lc; | ||
| 636 | while( $row = $sth->fetchrow_hashref() ) | ||
| 637 | { | ||
| 638 | my %hash; | ||
| 639 | @hash{ @o_keys } = @{ $row }{ @$i_keys }; | ||
| 640 | push( @rows, \%hash ); | ||
| 641 | } | ||
| 642 | } | ||
| 643 | else | ||
| 644 | { | ||
| 645 | push( @rows, $row ) while( $row = $sth->fetchrow_hashref() ); | ||
| 646 | } | ||
| 647 | } | ||
| 648 | else | ||
| 649 | { | ||
| 650 | warn( "fetchall_arrayref($mode) invalid" ); | ||
| 651 | } | ||
| 652 | # return( \@rows ); | ||
| 653 | return( \@rows ) if( !$need_post_processing ); | ||
| 654 | my $data = \@rows; | ||
| 655 | $data = $self->_convert_json2hash({ statement => $sth, data => $data }) if( $dbo->auto_decode_json ); | ||
| 656 | $data = $self->_convert_datetime2object({ statement => $sth, data => $data }) if( $dbo->auto_convert_datetime_to_object ); | ||
| 657 | return( $data ); | ||
| 658 | } | ||
| 659 | |||
| 660 | sub fetchcol($;$) | ||
| 661 | { | ||
| 662 | my $self = shift( @_ ); | ||
| 663 | # @arr = $sth->fetchcol( $col_number ); | ||
| 664 | my $col_num = shift( @_ ); | ||
| 665 | if( !$self->executed() ) | ||
| 666 | { | ||
| 667 | $self->execute() || return( $self->pass_error ); | ||
| 668 | } | ||
| 669 | # $self->_cleanup(); | ||
| 670 | # return( $h->fetchcol( $COL_NUM ) ); | ||
| 671 | my @col; | ||
| 672 | # $self->dataseek( 0 ); | ||
| 673 | my $ref; | ||
| 674 | while( $ref = $self->{sth}->fetchrow_arrayref() ) | ||
| 675 | { | ||
| 676 | push( @col, $ref->[ $col_num ] ); | ||
| 677 | } | ||
| 678 | return( @col ); | ||
| 679 | } | ||
| 680 | |||
| 681 | sub fetchhash(@) | ||
| 682 | { | ||
| 683 | my $self = shift( @_ ); | ||
| 684 | my $dbo = $self->database_object; | ||
| 685 | if( !$self->executed() ) | ||
| 686 | { | ||
| 687 | $self->execute() || return( $self->pass_error ); | ||
| 688 | } | ||
| 689 | # Ensure we set the cache of field names and types. We will need them to post process the query results with _convert_datetime2object() | ||
| 690 | # This is necessary for MySQL whose object lose that information, while the PostgreSQL or SQLite driver keep the information. | ||
| 691 | if( $dbo->auto_decode_json || $dbo->auto_convert_datetime_to_object ) | ||
| 692 | { | ||
| 693 | $self->_cache_field_names; | ||
| 694 | $self->_cache_field_types; | ||
| 695 | } | ||
| 696 | # $self->_cleanup(); | ||
| 697 | # %hash = $sth->fetchhash; | ||
| 698 | # return( $h->fetchhash ); | ||
| 699 | my $sth = $self->{sth} || die( "Unable to get the underlying statement handler!" ); | ||
| 700 | my $ref = $sth->fetchrow_hashref(); | ||
| 701 | if( $ref ) | ||
| 702 | { | ||
| 703 | if( $dbo->auto_decode_json || $dbo->auto_convert_datetime_to_object ) | ||
| 704 | { | ||
| 705 | $ref = $self->_convert_json2hash({ statement => $sth, data => $ref }) if( $dbo->auto_decode_json ); | ||
| 706 | $ref = $self->_convert_datetime2object({ statement => $sth, data => $ref }) if( $dbo->auto_convert_datetime_to_object ); | ||
| 707 | } | ||
| 708 | return( %$ref ); | ||
| 709 | } | ||
| 710 | else | ||
| 711 | { | ||
| 712 | return( () ); | ||
| 713 | } | ||
| 714 | } | ||
| 715 | |||
| 716 | sub fetchrow(@) | ||
| 717 | { | ||
| 718 | my $self = shift( @_ ); | ||
| 719 | if( !$self->executed() ) | ||
| 720 | { | ||
| 721 | $self->execute() || return( $self->pass_error ); | ||
| 722 | } | ||
| 723 | # $self->_cleanup(); | ||
| 724 | # @arr = $sth->fetchrow; # Array context | ||
| 725 | # $firstcol = $sth->fetchrow; # Scalar context | ||
| 726 | # return( $h->fetchrow ); | ||
| 727 | # my $ref = $self->fetchrow_arrayref(); | ||
| 728 | my $ref = $self->{sth}->fetchrow_arrayref(); | ||
| 729 | # my $ref = $self->{sth}->fetch(); | ||
| 730 | if( $ref ) | ||
| 731 | { | ||
| 732 | return( wantarray ? @$ref : $ref->[0] ); | ||
| 733 | } | ||
| 734 | else | ||
| 735 | { | ||
| 736 | return( () ); | ||
| 737 | } | ||
| 738 | } | ||
| 739 | |||
| 740 | # sub fetchrow_hashref(@) is inherited from DBI | ||
| 741 | sub fetchrow_hashref | ||
| 742 | { | ||
| 743 | my $self = shift( @_ ); | ||
| 744 | my $dbo = $self->database_object; | ||
| 745 | my $deb = {}; | ||
| 746 | %$deb = %$self; | ||
| 747 | my $sth = $self->{sth}; | ||
| 748 | if( !$self->executed() ) | ||
| 749 | { | ||
| 750 | $self->execute() || return( $self->pass_error ); | ||
| 751 | } | ||
| 752 | # Ensure we set the cache of field names and types. We will need them to post process the query results with _convert_datetime2object() | ||
| 753 | # This is necessary for MySQL whose object lose that information, while the PostgreSQL or SQLite driver keep the information. | ||
| 754 | if( $dbo->auto_decode_json || $dbo->auto_convert_datetime_to_object ) | ||
| 755 | { | ||
| 756 | $self->_cache_field_names; | ||
| 757 | $self->_cache_field_types; | ||
| 758 | } | ||
| 759 | my $ref = $sth->fetchrow_hashref; | ||
| 760 | $ref = $self->_convert_json2hash({ statement => $sth, data => $ref }) if( $dbo->auto_decode_json ); | ||
| 761 | $ref = $self->_convert_datetime2object({ statement => $sth, data => $ref }) if( $dbo->auto_convert_datetime_to_object ); | ||
| 762 | return( $ref ); | ||
| 763 | } | ||
| 764 | |||
| 765 | sub fetchrow_object | ||
| 766 | { | ||
| 767 | my $self = shift( @_ ); | ||
| 768 | # This should give us something like Postgres or Mysql or SQLite | ||
| 769 | my $basePack = ( ref( $self ) =~ /^DB::Object::([^\:]+)/ )[0]; | ||
| 770 | if( !$self->executed() ) | ||
| 771 | { | ||
| 772 | $self->execute() || return( $self->pass_error ); | ||
| 773 | } | ||
| 774 | # $self->_cleanup(); | ||
| 775 | my $rows = $self->{sth}->rows; | ||
| 776 | my $ref = $self->{sth}->fetchrow_hashref(); | ||
| 777 | if( $ref && scalar( keys( %$ref ) ) ) | ||
| 778 | { | ||
| 779 | my $struct = { map{ $_ => '$' } keys( %$ref ) }; | ||
| 780 | my $table = $self->table; | ||
| 781 | my $class = "DB::Object::${basePack}::Result::${table}"; | ||
| 782 | if( !defined( &{ $class . '::new' } ) ) | ||
| 783 | { | ||
| 784 | struct $class => $struct; | ||
| 785 | } | ||
| 786 | my $obj = $class->new( %$ref ); | ||
| 787 | return( $obj ); | ||
| 788 | } | ||
| 789 | else | ||
| 790 | { | ||
| 791 | return( () ); | ||
| 792 | } | ||
| 793 | } | ||
| 794 | |||
| 795 | # NOTE: field_names -> NAME | ||
| 796 | # <https://metacpan.org/pod/DBI#NAME> | ||
| 797 | sub field_names { return( shift->_get_statement_attribute( 'NAME' ) ); } | ||
| 798 | |||
| 799 | # NOTE: field_names_lc -> NAME_lc | ||
| 800 | # <https://metacpan.org/pod/DBI#NAME_lc> | ||
| 801 | sub field_names_lc { return( shift->_get_statement_attribute( 'NAME_lc' ) ); } | ||
| 802 | |||
| 803 | # NOTE: field_names_uc -> NAME_uc | ||
| 804 | # <https://metacpan.org/pod/DBI#NAME_uc> | ||
| 805 | sub field_names_uc { return( shift->_get_statement_attribute( 'NAME_uc' ) ); } | ||
| 806 | |||
| 807 | # NOTE: field_nullables -> NULLABLE | ||
| 808 | # <https://metacpan.org/pod/DBI#NULLABLE> | ||
| 809 | sub field_nullables { return( shift->_get_statement_attribute( 'NULLABLE' ) ); } | ||
| 810 | |||
| 811 | # NOTE: field_precisions -> PRECISION | ||
| 812 | # <https://metacpan.org/pod/DBI#PRECISION> | ||
| 813 | sub field_precisions { return( shift->_get_statement_attribute( 'PRECISION' ) ); } | ||
| 814 | |||
| 815 | # NOTE: field_scales -> SCALE | ||
| 816 | # <https://metacpan.org/pod/DBI#SCALE> | ||
| 817 | sub field_scales { return( shift->_get_statement_attribute( 'SCALE' ) ); } | ||
| 818 | |||
| 819 | # NOTE: field_types -> TYPE | ||
| 820 | # <https://metacpan.org/pod/DBI#TYPE> | ||
| 821 | sub field_types { return( shift->_get_statement_attribute( 'TYPE' ) ); } | ||
| 822 | |||
| 823 | sub finish | ||
| 824 | { | ||
| 825 | my $self = shift( @_ ); | ||
| 826 | my $rc = $self->{sth}->finish(); | ||
| 827 | if( !$rc ) | ||
| 828 | { | ||
| 829 | return( $self->error( $self->{sth}->errstr() ) ); | ||
| 830 | } | ||
| 831 | else | ||
| 832 | { | ||
| 833 | return( $rc ); | ||
| 834 | } | ||
| 835 | } | ||
| 836 | |||
| 837 | sub ignore | ||
| 838 | { | ||
| 839 | my $self = shift( @_ ); | ||
| 840 | my $query = $self->{query} || | ||
| 841 | return( $self->error( "No query to set as to be ignored." ) ); | ||
| 842 | |||
| 843 | my $type = uc( ( $query =~ /^\s*(\S+)\s+/ )[0] ); | ||
| 844 | # ALTER for table alteration statements (DB::Object::Tables | ||
| 845 | my @allowed = qw( INSERT UPDATE ALTER ); | ||
| 846 | my $allowed = CORE::join( '|', @allowed ); | ||
| 847 | if( !scalar( grep{ /^$type$/i } @allowed ) ) | ||
| 848 | { | ||
| 849 | return( $self->error( "You may not flag statement of type \U$type\E to be ignored:\n$query" ) ); | ||
| 850 | } | ||
| 851 | # Incompatible. Do not bother going further | ||
| 852 | return( $self ) if( $query =~ /^\s*(?:$allowed)\s+(?:DELAYED|LOW_PRIORITY|HIGH_PRIORITY)\s+/i ); | ||
| 853 | return( $self ) if( $type eq 'ALTER' && $query !~ /^\s*$type\s+TABLE\s+/i ); | ||
| 854 | |||
| 855 | $query =~ s/^(\s*)($allowed)(\s+)/$1$2 IGNORE /; | ||
| 856 | # my $sth = $self->prepare( $query ) || | ||
| 857 | # $self->{ 'query' } = $query; | ||
| 858 | # saving parameters to bind later on must have been done previously | ||
| 859 | my $sth = $self->_cache_this( $query ) || | ||
| 860 | return( $self->error( "Error while preparing new ignored query:\n$query" ) ); | ||
| 861 | if( !defined( wantarray() ) ) | ||
| 862 | { | ||
| 863 | $sth->execute() || | ||
| 864 | return( $self->error( "Error while executing new ignored query:\n$query" ) ); | ||
| 865 | } | ||
| 866 | return( $sth ); | ||
| 867 | } | ||
| 868 | |||
| 869 | sub join | ||
| 870 | { | ||
| 871 | my $self = shift( @_ ); | ||
| 872 | my $data = shift( @_ ); | ||
| 873 | my $on; | ||
| 874 | if( @_ ) | ||
| 875 | { | ||
| 876 | $on = ( scalar( @_ ) == 1 && ref( $_[0] ) ) ? shift( @_ ) : [ @_ ]; | ||
| 877 | } | ||
| 878 | my $q = $self->query_object || return( $self->error( "No query formatter object was set" ) ); | ||
| 879 | my $tbl_o = $q->table_object || return( $self->error( "No table object is set in query object." ) ); | ||
| 880 | my $query = $q->query || | ||
| 881 | return( $self->error( "No query prepared for join with another table." ) ); | ||
| 882 | if( $query !~ /^[[:blank:]]*SELECT[[:blank:]]+/i ) | ||
| 883 | { | ||
| 884 | return( $self->error( "You may not perform a join on a query other than select." ) ); | ||
| 885 | } | ||
| 886 | my $constant = $q->constant; | ||
| 887 | # Constant is set and query object marked as final, which means this statement has already been processed as a join and so we skip all further processing. | ||
| 888 | if( scalar( keys( %$constant ) ) && $q->final ) | ||
| 889 | { | ||
| 890 | return( $self ); | ||
| 891 | } | ||
| 892 | my $table = $tbl_o->table; | ||
| 893 | my $db = $tbl_o->database; | ||
| 894 | my $multi_db = $tbl_o->prefix_database; | ||
| 895 | my $alias = $tbl_o->as; | ||
| 896 | my $new_fields = ''; | ||
| 897 | my $new_table = ''; | ||
| 898 | my $new_db = ''; | ||
| 899 | my $class = ref( $self ); | ||
| 900 | my $q_source = $q->clone; | ||
| 901 | # clone() does a shallow copy - $q_source->{elements} would share the same object | ||
| 902 | # as $q->{elements}. Any subsequent _save_bind() on $q would then corrupt the | ||
| 903 | # element list of the cached statement. We reset elements here so $q_source gets | ||
| 904 | # its own fresh object, populated by _query_components below. | ||
| 905 | $q_source->{elements} = $q_source->new_elements; | ||
| 906 | # clone() copies the hash shallowly, which means {table_object} is a strong reference | ||
| 907 | # in the clone even though _query_object_create() weakens it for freshly created query | ||
| 908 | # objects. If left strong, $q_source permanently retains the table object, which in turn | ||
| 909 | # retains every new query object created by _reset_query() on each execute() cycle, | ||
| 910 | # causing an ~8 MB per-iteration memory leak. Weaken it here to restore correct ownership. | ||
| 911 | Scalar::Util::weaken( $q_source->{table_object} ) if( $q_source->{table_object} && !Scalar::Util::isweak( $q_source->{table_object} ) ); | ||
| 912 | Scalar::Util::weaken( $q_source->{database_object} ) if( $q_source->{database_object} && !Scalar::Util::isweak( $q_source->{database_object} ) ); | ||
| 913 | |||
| 914 | my $q_target; | ||
| 915 | # On the duplicated table object, add the current table in the join | ||
| 916 | $q_source->join_tables( $tbl_o ) if( !$q_source->join_tables->length ); | ||
| 917 | # $data is a DB::Object::Postgres::Statement object - we get all its parameter and merge them with ours | ||
| 918 | # if( ref( $data ) && ref( $data ) eq $class ) | ||
| 919 | if( ref( $data ) && $self->_is_a( $data, $class ) ) | ||
| 920 | { | ||
| 921 | $q_target = $data->query_object; | ||
| 922 | } | ||
| 923 | # $data is the table name | ||
| 924 | else | ||
| 925 | { | ||
| 926 | my $join_tbl; | ||
| 927 | if( $self->_is_object( $data ) && $data->isa( 'DB::Object::Tables' ) ) | ||
| 928 | { | ||
| 929 | $join_tbl = $data; | ||
| 930 | } | ||
| 931 | elsif( $self->_is_object( $data ) ) | ||
| 932 | { | ||
| 933 | return( $self->error( "I was expecting either a table name as a scalar or a table object, but instead got \"$data\" (", ref( $data ), ")." ) ); | ||
| 934 | } | ||
| 935 | else | ||
| 936 | { | ||
| 937 | return( $self->error( "No such table \"$data\" exists in database \"$db\"." ) ) if( !$self->database_object->table_exists( $data ) ); | ||
| 938 | $join_tbl = $self->database_object->table( $data ); | ||
| 939 | return( $self->error( "Could not get a table object from \"$data\"." ) ) if( !$join_tbl ); | ||
| 940 | } | ||
| 941 | $join_tbl->prefixed( $db ne $join_tbl->database_object->database ? 3 : 1 ); | ||
| 942 | my $sth_tmp = $join_tbl->select || return( $self->pass_error( $join_tbl->error ) ); | ||
| 943 | $q_target = $sth_tmp->query_object || | ||
| 944 | return( $self->error( "Could not get a query object out of the dummy select query I made from table \"$data\"." ) ); | ||
| 945 | $new_fields = $q_target->selected_fields; | ||
| 946 | # NOTE: 2021-08-22: If we reset it here, we lose the table aliasing | ||
| 947 | # $join_tbl->reset; | ||
| 948 | |||
| 949 | # $join_tbl->prefixed( $db ne $join_tbl->database_object->database ? 3 : 1 ) unless( $join_tbl->prefixed ); | ||
| 950 | $new_table = $join_tbl->prefix; | ||
| 951 | $join_tbl->reset; | ||
| 952 | # We assume this table is part of our same database | ||
| 953 | $new_db = $db; | ||
| 954 | # my $db_data = $self->getdefault( $new_table ); | ||
| 955 | # $new_fields = $db_data->format_statement(); | ||
| 956 | $new_fields = ''; | ||
| 957 | } | ||
| 958 | # TODO: check this or remove it | ||
| 959 | # $q_target->table_object->prefixed( $db ne $q_target->database_object->database ? 3 : 1 ); | ||
| 960 | $new_fields = $q_target->selected_fields; | ||
| 961 | $new_table = $q_target->table_object->name; | ||
| 962 | # $new_table = $q_target->table_object->prefix; | ||
| 963 | $new_db = $q_target->database_object->database; | ||
| 964 | $q_source->join_tables->push( $q_target->table_object ); | ||
| 965 | if( $q->where && $q_target->where ) | ||
| 966 | { | ||
| 967 | # We must NOT call $q_source->where( AND(...) ) here because _where_having would | ||
| 968 | # reconstruct the WHERE via process_where_condition, losing the bind elements that | ||
| 969 | # were built up in $q->where. Instead we build a merged Clause directly, copying | ||
| 970 | # the existing elements from $q->where so they are available to _save_bind below. | ||
| 971 | my $merged = $q_source->new_clause; | ||
| 972 | $merged->merge( $self->AND( $q->where, $q_target->new_clause({ value => '( ' . ( $q_target->where ) . ' )' }) ) ); | ||
| 973 | $q_source->{where} = $merged; | ||
| 974 | } | ||
| 975 | elsif( $q_target->where ) | ||
| 976 | { | ||
| 977 | $q_source->where( $q_target->where ); | ||
| 978 | } | ||
| 979 | if( my $group_target = $q_target->group ) | ||
| 980 | { | ||
| 981 | $q_source->group( $group_target ) if( $group_target->value->length ); | ||
| 982 | } | ||
| 983 | if( my $order_target = $q_target->order ) | ||
| 984 | { | ||
| 985 | $q_source->order( $order_target ) if( $order_target->value->length ); | ||
| 986 | } | ||
| 987 | |||
| 988 | if( ( !$q_source->limit || ( $q_source->limit && !$q_source->limit->length ) ) && | ||
| 989 | $q_source->limit && $q_source->limit->length ) | ||
| 990 | { | ||
| 991 | $q_source->limit( $q_target->limit ); | ||
| 992 | } | ||
| 993 | |||
| 994 | my $prev_fields = length( $q->join_fields ) ? $q->join_fields : $q->selected_fields; | ||
| 995 | # Regular express to prepend previous fields by their table name if that's not the case already | ||
| 996 | $tbl_o->prefixed( $db ne $new_db ? 3 : 1 ); | ||
| 997 | # Prefix for previous fields list | ||
| 998 | my $prev_prefix = $tbl_o->prefix; | ||
| 999 | my $prev_fields_hash = $q->table_object->fields; | ||
| 1000 | my $prev_fields_list = CORE::join( '|', sort( keys( %$prev_fields_hash ) ) ); | ||
| 1001 | my $re = qr/(?<![\.\"])\b($prev_fields_list)\b/; | ||
| 1002 | $prev_fields =~ s/(?<![\.\"])\b($prev_fields_list)\b/${prev_prefix}.$1/gs; | ||
| 1003 | my $fields = $new_fields ? CORE::join( ', ', $prev_fields, $new_fields ) : $prev_fields; | ||
| 1004 | $q_source->join_fields( $fields ); | ||
| 1005 | $q_source->from_table->push( | ||
| 1006 | $q_source->table_alias | ||
| 1007 | ? sprintf( '%s AS %s', $q_source->table_object->name, $q_source->table_alias ) | ||
| 1008 | : ( $q_source->table_object->prefixed ? $q_source->table_object->prefix : $q_source->table_object->name ) | ||
| 1009 | ) if( !$q_source->from_table->length ); | ||
| 1010 | my $left_join = ''; | ||
| 1011 | my $condition = ''; | ||
| 1012 | my $format_condition; | ||
| 1013 | $format_condition = sub | ||
| 1014 | { | ||
| 1015 | my @vals = (); | ||
| 1016 | my $vals = shift( @_ ); | ||
| 1017 | my $op = shift( @_ ); | ||
| 1018 | my @res = (); | ||
| 1019 | my $fields_tables = {}; | ||
| 1020 | while( scalar( @$vals ) ) | ||
| 1021 | { | ||
| 1022 | if( $self->_is_object( $vals->[0] ) && $vals->[0]->isa( 'DB::Object::Operator' ) ) | ||
| 1023 | { | ||
| 1024 | my $sub_obj = shift( @$vals ); | ||
| 1025 | my $sub_op = $sub_obj->operator; | ||
| 1026 | my( @sub_vals ) = $sub_obj->value; | ||
| 1027 | my $this_ref = $format_condition->( \@sub_vals, $sub_op ); | ||
| 1028 | CORE::push( @res, $this_ref->{clause} ) if( length( $this_ref->{clause} ) ); | ||
| 1029 | my $tmp = $this_ref->{fields_tables}; | ||
| 1030 | my @those_table_names = keys( %$tmp ); | ||
| 1031 | @$fields_tables{ @those_table_names } = @$tmp{ @those_table_names }; | ||
| 1032 | } | ||
| 1033 | else | ||
| 1034 | { | ||
| 1035 | if( $self->_is_object( $vals->[0] ) && $vals->[0]->isa( 'DB::Object::Fields::Overloaded' ) ) | ||
| 1036 | { | ||
| 1037 | my $f1 = shift( @$vals ); | ||
| 1038 | $f1->field->prefixed( $multi_db ? 3 : 1 ); | ||
| 1039 | CORE::push( @res, "$f1" ); | ||
| 1040 | $fields_tables->{ $f1->field->table }++ if( !$fields_tables->{ $f1->field->table } ); | ||
| 1041 | next; | ||
| 1042 | } | ||
| 1043 | |||
| 1044 | my( $f1, $f2 ) = ( shift( @$vals ), shift( @$vals ) ); | ||
| 1045 | my $i_am_negative = 0; | ||
| 1046 | if( $self->_is_object( $f2 ) && $f2->isa( 'DB::Object::NOT' ) ) | ||
| 1047 | { | ||
| 1048 | ( $f2 ) = $f2->value; | ||
| 1049 | $i_am_negative++; | ||
| 1050 | } | ||
| 1051 | |||
| 1052 | my( $field1, $field2 ); | ||
| 1053 | if( $self->_is_object( $f1 ) && $f1->isa( 'DB::Object::Fields::Field' ) ) | ||
| 1054 | { | ||
| 1055 | $f1->prefixed( $multi_db ? 3 : 1 ); | ||
| 1056 | $field1 = $f1->name; | ||
| 1057 | $fields_tables->{ $f1->table }++ if( !$fields_tables->{ $f1->table } ); | ||
| 1058 | } | ||
| 1059 | else | ||
| 1060 | { | ||
| 1061 | $field1 = $multi_db ? "$new_db.$new_table.$f1" : "$new_table.$f1"; | ||
| 1062 | } | ||
| 1063 | if( $self->_is_object( $f2 ) && $f2->isa( 'DB::Object::Fields::Field' ) ) | ||
| 1064 | { | ||
| 1065 | $f2->prefixed( $multi_db ? 3 : 1 ); | ||
| 1066 | $field2 = $f2->name; | ||
| 1067 | $fields_tables->{ $f2->table }++ if( !$fields_tables->{ $f2->table } ); | ||
| 1068 | } | ||
| 1069 | else | ||
| 1070 | { | ||
| 1071 | $field2 = $multi_db ? "$new_db.$new_table.$f2" : "$new_table.$f2"; | ||
| 1072 | } | ||
| 1073 | CORE::push( @res, $i_am_negative ? "$field1 != $field2" : "$field1 = $field2" ); | ||
| 1074 | } | ||
| 1075 | } | ||
| 1076 | return({ | ||
| 1077 | clause => CORE::join( $op, @res ), | ||
| 1078 | fields_tables => $fields_tables, | ||
| 1079 | }); | ||
| 1080 | }; | ||
| 1081 | |||
| 1082 | # $on is either a $dbh->AND, or $dbh->OR | ||
| 1083 | if( defined( $on ) ) | ||
| 1084 | { | ||
| 1085 | if( $self->_is_object( $on ) && $on->isa( 'DB::Object::Operator' ) ) | ||
| 1086 | { | ||
| 1087 | my $op = $on->operator; | ||
| 1088 | my( @vals ) = $on->value; | ||
| 1089 | my $ret = $format_condition->( \@vals, $op ); | ||
| 1090 | my $as = $q_target->table_alias ? sprintf( ' AS %s', $q_target->table_alias ) : ''; | ||
| 1091 | $left_join = "LEFT JOIN ${new_table}${as} ON $ret->{clause}"; | ||
| 1092 | } | ||
| 1093 | elsif( $self->_is_object( $on ) && $on->isa( 'DB::Object::Fields::Overloaded' ) ) | ||
| 1094 | { | ||
| 1095 | my $as = $q_target->table_alias ? sprintf( ' AS %s', $q_target->table_alias ) : ''; | ||
| 1096 | $left_join = "LEFT JOIN ${new_table}${as} ON ${on}"; | ||
| 1097 | } | ||
| 1098 | elsif( $self->_is_array( $on ) ) | ||
| 1099 | { | ||
| 1100 | my $ret = $format_condition->( $on, 'AND' ); | ||
| 1101 | my $as = $q_target->table_alias ? sprintf( ' AS %s', $q_target->table_alias ) : ''; | ||
| 1102 | $left_join = "LEFT JOIN ${new_table}${as} ON $ret->{clause}"; | ||
| 1103 | } | ||
| 1104 | # There is a second parameter - if so this is the condition of the 'LEFT JOIN' | ||
| 1105 | elsif( $self->_is_hash( $on => 'strict' ) ) | ||
| 1106 | { | ||
| 1107 | # Previous join | ||
| 1108 | my $join_ref = $q_source->left_join; | ||
| 1109 | my $def = { on => $on, table_object => $q_target->table_object, query_object => $q_target }; | ||
| 1110 | ## Add the current one | ||
| 1111 | if( $multi_db ) | ||
| 1112 | { | ||
| 1113 | $join_ref->{ "$new_db.$new_table" } = $def; | ||
| 1114 | } | ||
| 1115 | else | ||
| 1116 | { | ||
| 1117 | $join_ref->{ $new_table } = $def; | ||
| 1118 | } | ||
| 1119 | # (Re)build the LEFT JOIN ... ON ... definition | ||
| 1120 | my @join_data = (); | ||
| 1121 | foreach my $joined ( keys( %$join_ref ) ) | ||
| 1122 | { | ||
| 1123 | my $condition = $join_ref->{ $joined }->{on}; | ||
| 1124 | my $to = $join_ref->{ $joined }->{table_object}; | ||
| 1125 | my $qo = $join_ref->{ $joined }->{query_object}; | ||
| 1126 | my $join_table_name = $to->prefix; | ||
| 1127 | my $join_table_alias = ''; | ||
| 1128 | if( length( $join_table_alias = $qo->table_alias ) ) | ||
| 1129 | { | ||
| 1130 | $join_table_alias = " AS $join_table_alias"; | ||
| 1131 | } | ||
| 1132 | push( @join_data, "LEFT JOIN ${join_table_name}${join_table_alias} ON " . CORE::join( ' AND ', map{ "$_=$condition->{ $_ }" } keys( %$condition ) ) ); | ||
| 1133 | } | ||
| 1134 | $left_join = CORE::join( ' ', @join_data ); | ||
| 1135 | } | ||
| 1136 | else | ||
| 1137 | { | ||
| 1138 | warn( "Warning: I have no clue what to do with '$on' (", overload::StrVal( $on ), ") in this join for table \"", $q->table_object->name, "\"\n" ); | ||
| 1139 | } | ||
| 1140 | } | ||
| 1141 | # Otherwise, this is a straight JOIN | ||
| 1142 | else | ||
| 1143 | { | ||
| 1144 | # $q_source->from_table->push( $multi_db ? "$new_db.$new_table" : $new_table ); | ||
| 1145 | $q_source->from_table->push( | ||
| 1146 | $q_target->table_alias | ||
| 1147 | ? sprintf( '%s AS %s', $q_target->table_object->name, $q_target->table_alias ) | ||
| 1148 | : ( $q_target->table_object->prefixed ? $q_target->table_object->prefix : $q_target->table_object->name ) | ||
| 1149 | ); | ||
| 1150 | } | ||
| 1151 | my $from = $q_source->from_table->join( ', ' ); | ||
| 1152 | my $clause = $q_source->_query_components( 'select', { no_bind_copy => 1 } ); | ||
| 1153 | # Copy WHERE (and other clause) elements directly into $q_source->elements so that | ||
| 1154 | # Statement::execute() can find the bind types regardless of the use_bind setting. | ||
| 1155 | # We do this explicitly rather than via _save_bind() because _save_bind() is gated | ||
| 1156 | # on use_bind, which may be 0 even when placeholders are present. | ||
| 1157 | # NOTE: $where->elements returns a Module::Generic::Array of Element objects directly | ||
| 1158 | # (NOT an Elements wrapper). Pass ->list to Elements::push(), not the array object itself. | ||
| 1159 | { | ||
| 1160 | my $elems = $q_source->new_elements; | ||
| 1161 | my $where = $q_source->where; | ||
| 1162 | my $limit = $q_source->limit; | ||
| 1163 | if( $where ) | ||
| 1164 | { | ||
| 1165 | my $where_arr = $where->elements; | ||
| 1166 | $elems->push( $where_arr->list ) if( $where_arr && $where_arr->length ); | ||
| 1167 | } | ||
| 1168 | if( $limit ) | ||
| 1169 | { | ||
| 1170 | my $limit_arr = $limit->elements; | ||
| 1171 | $elems->push( $limit_arr->list ) if( $limit_arr && $limit_arr->length ); | ||
| 1172 | } | ||
| 1173 | $q_source->elements( $elems ); | ||
| 1174 | |||
| 1175 | } | ||
| 1176 | my @query = ( "SELECT ${fields} FROM ${from} ${left_join}" ); | ||
| 1177 | push( @query, @$clause ) if( @$clause ); | ||
| 1178 | my $statement = CORE::join( ' ', @query ); | ||
| 1179 | $q_source->query( $statement ); | ||
| 1180 | my $sth = $tbl_o->_cache_this( $q_source ) || | ||
| 1181 | return( $self->error( "Error while preparing query to select:\n", $q_source->as_string(), $tbl_o->error ) ); | ||
| 1182 | # Routines such as as_string() expect an array on pupose so we do not have to commit the action | ||
| 1183 | # but rather get the statement string. At the end, we write: | ||
| 1184 | # $obj->select() to really select | ||
| 1185 | # $obj->select->as_string() to ONLY get the formatted statement | ||
| 1186 | # wantarray() returns the undefined value in void context, which is typical use of a real select command | ||
| 1187 | # i.e. $obj->select(); | ||
| 1188 | if( !defined( wantarray() ) ) | ||
| 1189 | { | ||
| 1190 | $sth->execute() || | ||
| 1191 | return( $self->error( "Error while executing query to select:\n", $q_source->as_string(), "\nError: ", $sth->error() ) ); | ||
| 1192 | } | ||
| 1193 | return( $sth ); | ||
| 1194 | } | ||
| 1195 | |||
| 1196 | # NOTE: number_of_fields -> NUM_OF_FIELDS | ||
| 1197 | # <https://metacpan.org/pod/DBI#NUM_OF_FIELDS> | ||
| 1198 | sub number_of_fields { return( shift->_get_statement_attribute( 'NUM_OF_FIELDS' ) ); } | ||
| 1199 | |||
| 1200 | # NOTE: number_of_params -> NUM_OF_PARAMS | ||
| 1201 | # <https://metacpan.org/pod/DBI#NUM_OF_PARAMS> | ||
| 1202 | sub number_of_params { return( shift->_get_statement_attribute( 'NUM_OF_PARAMS' ) ); } | ||
| 1203 | |||
| 1204 | sub object | ||
| 1205 | { | ||
| 1206 | my $self = shift( @_ ); | ||
| 1207 | # This is intended for statement to fetched their object: | ||
| 1208 | # my $obj = $table->select( '*' )->object(); | ||
| 1209 | # my $obj = $table->select( '*' ) | ||
| 1210 | # would merly execute the statement before returning its object, but there are conditions | ||
| 1211 | # such like using a SELECT to create a table where we do not want the statement to be executed already | ||
| 1212 | return( $self->{sth} ) if( $self->{sth} ); | ||
| 1213 | # More sensible approach will return a special Module::Generic::Null object to avoid perl complaining of 'called on undef value' if this is used in chaining | ||
| 1214 | return( Module::Generic::Null->new ) if( want( 'OBJECT' ) ); | ||
| 1215 | return; | ||
| 1216 | } | ||
| 1217 | |||
| 1218 | sub priority | ||
| 1219 | { | ||
| 1220 | my $self = shift( @_ ); | ||
| 1221 | my $prio = shift( @_ ); | ||
| 1222 | my $map = | ||
| 1223 | { | ||
| 1224 | 0 => 'LOW_PRIORITY', | ||
| 1225 | 1 => 'HIGH_PRIORITY', | ||
| 1226 | }; | ||
| 1227 | ## Bad argument. Do not bother | ||
| 1228 | return( $self ) if( !exists( $map->{ $prio } ) ); | ||
| 1229 | |||
| 1230 | my $query = $self->{query} || | ||
| 1231 | return( $self->error( "No query to set priority for was provided." ) ); | ||
| 1232 | my $type = uc( ( $query =~ /^\s*(\S+)\s+/ )[ 0 ] ); | ||
| 1233 | my @allowed = qw( DELETE INSERT REPLACE SELECT UPDATE ); | ||
| 1234 | my $allowed = CORE::join( '|', @allowed ); | ||
| 1235 | # Ignore if not allowed | ||
| 1236 | if( !scalar( grep{ /^$type$/i } @allowed ) ) | ||
| 1237 | { | ||
| 1238 | $self->error( "You may not set priority on statement of type \U$type\E:\n$query" ); | ||
| 1239 | return( $self ); | ||
| 1240 | } | ||
| 1241 | # Incompatible. Do not bother going further | ||
| 1242 | return( $self ) if( $query =~ /^\s*(?:$allowed)\s+(?:DELAYED|LOW_PRIORITY|HIGH_PRIORITY)\s+/i ); | ||
| 1243 | # SELECT with something else than HIGH_PRIORITY is incompatible, so do not bother to go further | ||
| 1244 | return( $self ) if( $prio != 1 && $type =~ /^(?:SELECT)$/i ); | ||
| 1245 | return( $self ) if( $prio != 0 && $type =~ /^(?:DELETE|INSERT|REPLACE|UPDATE)$/i ); | ||
| 1246 | |||
| 1247 | $query =~ s/^(\s*)($allowed)(\s+)/$1$2 $map->{ $prio } /i; | ||
| 1248 | # $self->{ 'query' } = $query; | ||
| 1249 | # my $sth = $self->prepare( $query ) || | ||
| 1250 | my $sth = $self->_cache_this( $query ) || | ||
| 1251 | return( $self->error( "Error while preparing new low priority query:\n$query" ) ); | ||
| 1252 | if( !defined( wantarray() ) ) | ||
| 1253 | { | ||
| 1254 | $sth->execute() || | ||
| 1255 | return( $self->error( "Error while executing new low priority query:\n$query" ) ); | ||
| 1256 | } | ||
| 1257 | return( $sth ); | ||
| 1258 | } | ||
| 1259 | |||
| 1260 | sub promise | ||
| 1261 | { | ||
| 1262 | my $self = shift( @_ ); | ||
| 1263 | $self->_load_class( 'Promise::Me' ) || return( $self->pass_error ); | ||
| 1264 | return( Promise::Me->new(sub | ||
| 1265 | { | ||
| 1266 | return( $self->execute( @_ ) ); | ||
| 1267 | }) ); | ||
| 1268 | } | ||
| 1269 | |||
| 1270 | sub query { return( shift->_set_get_scalar( 'query', @_ ) ); } | ||
| 1271 | |||
| 1272 | sub query_object { return( shift->_set_get_object_without_init( 'query_object', 'DB::Object::Query', @_ ) ); } | ||
| 1273 | |||
| 1274 | sub query_time { return( shift->_set_get_datetime( 'query_time', @_ ) ); } | ||
| 1275 | |||
| 1276 | sub rollback | ||
| 1277 | { | ||
| 1278 | my $self = shift( @_ ); | ||
| 1279 | if( $self->{sth} && $self->param( 'autocommit' ) ) | ||
| 1280 | { | ||
| 1281 | my $sth = $self->prepare( "ROLLBACK" ) || return( $self->error( "An error occurred while preparing query to rollback: ", $self->error ) ); | ||
| 1282 | $sth->execute() || return( $self->error( "Error occurred while executing query to rollback: ", $sth->error ) ); | ||
| 1283 | $sth->finish(); | ||
| 1284 | } | ||
| 1285 | return( $self ); | ||
| 1286 | } | ||
| 1287 | |||
| 1288 | sub rows(@) | ||
| 1289 | { | ||
| 1290 | my $self = shift( @_ ); | ||
| 1291 | if( !$self->executed() ) | ||
| 1292 | { | ||
| 1293 | $self->execute() || return( $self->pass_error ); | ||
| 1294 | } | ||
| 1295 | # $self->_cleanup(); | ||
| 1296 | # $rv = $sth->rows; | ||
| 1297 | if( !ref( $self ) ) | ||
| 1298 | { | ||
| 1299 | return( $DBI::rows ); | ||
| 1300 | } | ||
| 1301 | else | ||
| 1302 | { | ||
| 1303 | return( $self->{sth}->rows() ); | ||
| 1304 | } | ||
| 1305 | } | ||
| 1306 | |||
| 1307 | # NOTE: statement -> Statement | ||
| 1308 | # <https://metacpan.org/pod/DBI#Statement> | ||
| 1309 | sub statement { return( shift->_get_statement_attribute( 'Statement' ) ); } | ||
| 1310 | |||
| 1311 | # A DBI::sth object. This should rather be a _set_get_object helper method, but I am not 100% sure if this is really a DBI::sth | ||
| 1312 | sub sth { return( shift->_set_get_scalar( 'sth', @_ ) ); } | ||
| 1313 | |||
| 1314 | sub table { return( shift->{table} ); } | ||
| 1315 | |||
| 1316 | sub table_object { return( shift->_set_get_object_without_init( 'table_object', 'DB::Object::Tables', @_ ) ); } | ||
| 1317 | |||
| 1318 | sub undo | ||
| 1319 | { | ||
| 1320 | goto( &rollback ); | ||
| 1321 | } | ||
| 1322 | |||
| 1323 | sub wait { return( shift->error( "Method wait() is not implemented by this driver." ) ); } | ||
| 1324 | |||
| 1325 | # Used to get the cached field names by _convert_datetime2object | ||
| 1326 | sub _cache_field_names | ||
| 1327 | { | ||
| 1328 | my $self = shift( @_ ); | ||
| 1329 | my $names; | ||
| 1330 | if( !( $names = $self->{_cache_field_names} ) ) | ||
| 1331 | { | ||
| 1332 | $names = $self->{_cache_field_names} = $self->field_names; | ||
| 1333 | } | ||
| 1334 | return( $names ); | ||
| 1335 | } | ||
| 1336 | |||
| 1337 | # Used to get the cached field names by _convert_datetime2object | ||
| 1338 | sub _cache_field_types | ||
| 1339 | { | ||
| 1340 | my $self = shift( @_ ); | ||
| 1341 | my $types; | ||
| 1342 | if( !( $types = $self->{_cache_field_types} ) ) | ||
| 1343 | { | ||
| 1344 | $types = $self->{_cache_field_types} = $self->field_types; | ||
| 1345 | } | ||
| 1346 | return( $types ); | ||
| 1347 | } | ||
| 1348 | |||
| 1349 | # sub _convert_datetime2object { return( shift->database_object->_convert_datetime2object( @_ ) ); } | ||
| 1350 | # sub _convert_datetime2object | ||
| 1351 | # { | ||
| 1352 | # my $self = shift( @_ ); | ||
| 1353 | # my $opts = $self->_get_args_as_hash( @_ ); | ||
| 1354 | # return( $opts->{data} ); | ||
| 1355 | # } | ||
| 1356 | sub _convert_datetime2object | ||
| 1357 | { | ||
| 1358 | my $self = shift( @_ ); | ||
| 1359 | my $opts = $self->_get_args_as_hash( @_ ); | ||
| 1360 | my $sth = $opts->{statement} || return( $self->error( "No statement handler was provided to convert data from json to perl." ) ); | ||
| 1361 | # my $data = $opts->{data} || return( $self->error( "No data was provided to convert from json to perl." ) ); | ||
| 1362 | return( $opts->{data} ) if( !CORE::length( $opts->{data} ) ); | ||
| 1363 | my $data = $opts->{data}; | ||
| 1364 | # my $names = $sth->FETCH('NAME'); | ||
| 1365 | # my $types = $sth->FETCH('pg_type'); | ||
| 1366 | # Get the cached field names and types that we stored after executing the query, but before we finished reading the statement | ||
| 1367 | my $names = $self->_cache_field_names; | ||
| 1368 | my $types = $self->_cache_field_types; | ||
| 1369 | my $mode = ref( $data ); | ||
| 1370 | |||
| 1371 | for( my $i = 0; $i < scalar( @$names ); $i++ ) | ||
| 1372 | { | ||
| 1373 | if( $types->[$i] eq DBI::SQL_DATE || | ||
| 1374 | $types->[$i] eq DBI::SQL_TIMESTAMP || | ||
| 1375 | $types->[$i] eq 'date' || | ||
| 1376 | $types->[$i] eq 'timestamp' ) | ||
| 1377 | { | ||
| 1378 | if( $mode eq 'ARRAY' ) | ||
| 1379 | { | ||
| 1380 | for( my $j = 0; $j < scalar( @$data ); $j++ ) | ||
| 1381 | { | ||
| 1382 | next if( !$data->[ $j ]->{ $names->[ $i ] } ); | ||
| 1383 | my $dt = $self->_convert_string2datetime( $data->[ $j ]->{ $names->[ $i ] } ); | ||
| 1384 | if( !defined( $dt ) ) | ||
| 1385 | { | ||
| 1386 | warn( $self->error ); | ||
| 1387 | } | ||
| 1388 | $data->[ $j ]->{ $names->[ $i ] } = $dt; | ||
| 1389 | } | ||
| 1390 | } | ||
| 1391 | elsif( $mode eq 'HASH' ) | ||
| 1392 | { | ||
| 1393 | next if( !$data->{ $names->[ $i ] } ); | ||
| 1394 | my $dt = $self->_convert_string2datetime( $data->{ $names->[ $i ] } ); | ||
| 1395 | if( !defined( $dt ) ) | ||
| 1396 | { | ||
| 1397 | warn( $self->error ); | ||
| 1398 | } | ||
| 1399 | $data->{ $names->[ $i ] } = $dt; | ||
| 1400 | } | ||
| 1401 | } | ||
| 1402 | } | ||
| 1403 | return( $data ); | ||
| 1404 | } | ||
| 1405 | |||
| 1406 | # sub _convert_json2hash { return( shift->database_object->_convert_json2hash( @_ ) ); } | ||
| 1407 | # Does nothing by default | ||
| 1408 | # Must be superseded by the subclasses because we use the data types like PG_JSON, PG_JSONB | ||
| 1409 | # and we don't have them at this top level | ||
| 1410 | sub _convert_json2hash | ||
| 1411 | { | ||
| 1412 | my $self = shift( @_ ); | ||
| 1413 | my $opts = $self->_get_args_as_hash( @_ ); | ||
| 1414 | return( $opts->{data} ); | ||
| 1415 | } | ||
| 1416 | |||
| 1417 | sub _convert_string2datetime | ||
| 1418 | { | ||
| 1419 | my $self = shift( @_ ); | ||
| 1420 | my $str = shift( @_ ) || return; | ||
| 1421 | my $dt = $self->_parse_timestamp( $str ); | ||
| 1422 | if( !defined( $dt ) ) | ||
| 1423 | { | ||
| 1424 | return( $self->pass_error ); | ||
| 1425 | } | ||
| 1426 | # An empty string means it did not fail, but probably did not recognise the format | ||
| 1427 | elsif( !$dt ) | ||
| 1428 | { | ||
| 1429 | return( $str ); | ||
| 1430 | } | ||
| 1431 | return( $dt ); | ||
| 1432 | } | ||
| 1433 | |||
| 1434 | sub _get_statement_attribute | ||
| 1435 | { | ||
| 1436 | my $self = shift( @_ ); | ||
| 1437 | my $attr = shift( @_ ); | ||
| 1438 | if( !length( $attr // '' ) ) | ||
| 1439 | { | ||
| 1440 | return( $self->error( "No statement attribute was provided to retrieve its value." ) ); | ||
| 1441 | } | ||
| 1442 | my $sth = $self->{sth} || die( "Unable to get the underlying statement handler!" ); | ||
| 1443 | my $val; | ||
| 1444 | # try-catch | ||
| 1445 | local $@; | ||
| 1446 | eval | ||
| 1447 | { | ||
| 1448 | # Ensure we stringify | ||
| 1449 | $val = $sth->{ "$attr" }; | ||
| 1450 | }; | ||
| 1451 | if( $@ ) | ||
| 1452 | { | ||
| 1453 | return( $self->error( "Error retrieving value for '${attr}': $@" ) ); | ||
| 1454 | } | ||
| 1455 | return( $val ); | ||
| 1456 | } | ||
| 1457 | |||
| 1458 | # NOTE: DESTROY | ||
| 1459 | DESTROY | ||
| 1460 | { | ||
| 1461 | # Do nothing but existing so it is handled by this package | ||
| 1462 | # print( STDERR "DESTROY'ing statement $self ($self->{ 'query' })\n" ); | ||
| 1463 | }; | ||
| 1464 | |||
| 1465 | # NOTE: Storable hooks | ||
| 1466 | # We intentionally do NOT freeze DBI handles (dbh/sth) or back-references (dbo/table_object) | ||
| 1467 | # because they are process-local and cannot be safely restored. | ||
| 1468 | # NOTE: For CBOR and Sereal | ||
| 1469 | sub FREEZE | ||
| 1470 | { | ||
| 1471 | my $self = CORE::shift( @_ ); | ||
| 1472 | my $serialiser = CORE::shift( @_ ) // ''; | ||
| 1473 | my $class = CORE::ref( $self ); | ||
| 1474 | |||
| 1475 | # We keep a strict allow-list to avoid accidentally freezing DBI handles or other | ||
| 1476 | # process-local state. | ||
| 1477 | # 2026-01-29: I removed 'query_object' in an effort to reduce memory consumption. Let's see... | ||
| 1478 | my @props = qw( | ||
| 1479 | as_string bind cache params query query_object selected_fields | ||
| 1480 | table tie tie_order _fields _cache_field_names _cache_field_types | ||
| 1481 | ); | ||
| 1482 | |||
| 1483 | my $hash = {}; | ||
| 1484 | foreach my $prop ( @props ) | ||
| 1485 | { | ||
| 1486 | if( CORE::exists( $self->{ $prop } ) && | ||
| 1487 | defined( $self->{ $prop } ) && | ||
| 1488 | CORE::ref( $self->{ $prop } ) ne 'CODE' ) | ||
| 1489 | { | ||
| 1490 | $hash->{ $prop } = $self->{ $prop }; | ||
| 1491 | } | ||
| 1492 | } | ||
| 1493 | $hash->{_serial_version} = $DB::Object::SERIALISATION_VERSION; | ||
| 1494 | |||
| 1495 | # Return an array reference rather than a list so this works with Sereal and CBOR. | ||
| 1496 | # Before Sereal version 4.023, Sereal did not support multiple values returned. | ||
| 1497 | if( $serialiser eq 'Sereal' ) | ||
| 1498 | { | ||
| 1499 | require Sereal::Encoder; | ||
| 1500 | require version; | ||
| 1501 | |||
| 1502 | if( version->parse( Sereal::Encoder->VERSION ) < version->parse( '4.023' ) ) | ||
| 1503 | { | ||
| 1504 | CORE::return( [$class, $hash] ); | ||
| 1505 | } | ||
| 1506 | } | ||
| 1507 | |||
| 1508 | # But Storable wants a list with the first element being the serialised element | ||
| 1509 | CORE::return( $class, $hash ); | ||
| 1510 | } | ||
| 1511 | |||
| 1512 | sub STORABLE_freeze { return( shift->FREEZE( @_ ) ); } | ||
| 1513 | |||
| 1514 | sub STORABLE_thaw { return( shift->THAW( @_ ) ); } | ||
| 1515 | |||
| 1516 | sub STORABLE_thaw_post_processing | ||
| 1517 | { | ||
| 1518 | my $obj = shift( @_ ); | ||
| 1519 | my @keys = %$obj; | ||
| 1520 | my $class = ref( $obj ); | ||
| 1521 | my $hash = {}; | ||
| 1522 | @$hash{ @keys } = @$obj{ @keys }; | ||
| 1523 | my $self = bless( $hash => $class ); | ||
| 1524 | return( $self ); | ||
| 1525 | } | ||
| 1526 | |||
| 1527 | sub THAW | ||
| 1528 | { | ||
| 1529 | # STORABLE_thaw would issue $cloning as the 2nd argument, while CBOR would issue | ||
| 1530 | # 'CBOR' as the second value. | ||
| 1531 | my( $self, undef, @args ) = @_; | ||
| 1532 | my $ref = ( CORE::scalar( @args ) == 1 && CORE::ref( $args[0] ) eq 'ARRAY' ) ? CORE::shift( @args ) : \@args; | ||
| 1533 | my $class = ( CORE::defined( $ref ) && CORE::ref( $ref ) eq 'ARRAY' && CORE::scalar( @$ref ) > 1 ) ? CORE::shift( @$ref ) : ( CORE::ref( $self ) || $self ); | ||
| 1534 | my $hash = CORE::ref( $ref ) eq 'ARRAY' ? CORE::shift( @$ref ) : {}; | ||
| 1535 | |||
| 1536 | my $sv = CORE::delete( $hash->{_serial_version} ) // 0; | ||
| 1537 | if( $sv != $DB::Object::SERIALISATION_VERSION ) | ||
| 1538 | { | ||
| 1539 | require( $EXCEPTION_CLASS ); | ||
| 1540 | die( $EXCEPTION_CLASS->new({ | ||
| 1541 | code => 409, # Conflict | ||
| 1542 | message => sprintf( | ||
| 1543 | "Serialisation version mismatch in %s: expected %d, got %d. Please purge the cache.", | ||
| 1544 | $class, | ||
| 1545 | $DB::Object::SERIALISATION_VERSION, | ||
| 1546 | $sv, | ||
| 1547 | ) | ||
| 1548 | }) ); | ||
| 1549 | } | ||
| 1550 | |||
| 1551 | # Since this class is inherited, we also need to load from which we depend, if necessary. | ||
| 1552 | if( $class ne 'DB::Object::Statement' ) | ||
| 1553 | { | ||
| 1554 | require DB::Object; | ||
| 1555 | require DB::Object::Statement; | ||
| 1556 | my @supported_classes = CORE::values( %$DB::Object::DRIVER2PACK ); | ||
| 1557 | push( @supported_classes, 'DB::Object' ); | ||
| 1558 | my $ok_classes = CORE::join( '|', CORE::map{ CORE::quotemeta( $_ ) } @supported_classes ); | ||
| 1559 | my $base_class = ( $class =~ /^($ok_classes)/ )[0]; | ||
| 1560 | eval( "require $base_class;" ); | ||
| 1561 | if( $@ ) | ||
| 1562 | { | ||
| 1563 | require( $EXCEPTION_CLASS ); | ||
| 1564 | die( $EXCEPTION_CLASS->new( "Failure to load $base_class: $@" ) ); | ||
| 1565 | } | ||
| 1566 | |||
| 1567 | # If inheritance is still missing (or incomplete) for any reason, repair it explicitly. | ||
| 1568 | no strict 'refs'; | ||
| 1569 | |||
| 1570 | my $stash = \%{"${class}\::"}; | ||
| 1571 | my $isa_ref; | ||
| 1572 | # We check if the 'ISA' symbol exists in the stash and its ARRAY slot is defined | ||
| 1573 | if( exists( $stash->{ISA} ) && | ||
| 1574 | defined( *{"${class}\::ISA"}{ARRAY} ) ) | ||
| 1575 | { | ||
| 1576 | $isa_ref = *{"${class}\::ISA"}{ARRAY}; | ||
| 1577 | } | ||
| 1578 | else | ||
| 1579 | { | ||
| 1580 | # # Force creation of @ISA array slot | ||
| 1581 | # @{"${class}::ISA"} = (); | ||
| 1582 | # $isa_ref = *{"${class}::ISA"}{ARRAY}; | ||
| 1583 | # But I want it to die, so this can be dealt with, and not swept under the rug. | ||
| 1584 | die( "Unable to find the \@ISA value in $class. The package contains the following stashes:\n", $self->Module::Generic::dump( $stash ) ); | ||
| 1585 | } | ||
| 1586 | |||
| 1587 | my $has_stmt = 0; | ||
| 1588 | my $has_base = 0; | ||
| 1589 | |||
| 1590 | foreach my $p ( @$isa_ref ) | ||
| 1591 | { | ||
| 1592 | # Same as what we can find in modules DB::Object::(Postgres|SQLite|Mysql)::Statement | ||
| 1593 | $has_stmt = 1 if( CORE::defined( $p ) && $p eq 'DB::Object::Statement' ); | ||
| 1594 | $has_base = 1 if( CORE::defined( $p ) && $p eq $base_class ); | ||
| 1595 | } | ||
| 1596 | |||
| 1597 | if( !$has_stmt || !$has_base ) | ||
| 1598 | { | ||
| 1599 | @$isa_ref = ( 'DB::Object::Statement', $base_class ); | ||
| 1600 | } | ||
| 1601 | } | ||
| 1602 | my $new; | ||
| 1603 | # Storable pattern requires to modify the object it created rather than returning a new one | ||
| 1604 | if( CORE::ref( $self ) ) | ||
| 1605 | { | ||
| 1606 | foreach( CORE::keys( %$hash ) ) | ||
| 1607 | { | ||
| 1608 | $self->{ $_ } = CORE::delete( $hash->{ $_ } ); | ||
| 1609 | } | ||
| 1610 | $new = $self; | ||
| 1611 | } | ||
| 1612 | else | ||
| 1613 | { | ||
| 1614 | $new = CORE::bless( $hash => $class ); | ||
| 1615 | } | ||
| 1616 | CORE::return( $new ); | ||
| 1617 | } | ||
| 1618 | |||
| 1619 | 1; | ||
| 1620 | # NOTE: POD | ||
| 1621 | __END__ | ||
| 1622 | |||
| 1623 | =encoding utf-8 | ||
| 1624 | |||
| 1625 | =head1 NAME | ||
| 1626 | |||
| 1627 | DB::Object::Statement - Statement Object | ||
| 1628 | |||
| 1629 | =head1 SYNOPSIS | ||
| 1630 | |||
| 1631 | say $sth->as_string; | ||
| 1632 | $sth->bind_param( 2, $binded_value ); | ||
| 1633 | $sth->bind_param( 2, $binded_value, $binded_type ); | ||
| 1634 | $sth->commit; | ||
| 1635 | my $dbh = $sth->database_object; | ||
| 1636 | $sth->distinct; | ||
| 1637 | say $sth->dump; | ||
| 1638 | say $sth->execute; | ||
| 1639 | $sth->execute( $val1, $val2 ) || die( $sth->error ); | ||
| 1640 | # explicitly specify types | ||
| 1641 | # Here in this mixed example, $val1 and $val3 have known types | ||
| 1642 | $tbl->where( $dbh->AND( | ||
| 1643 | $tbl->fo->name == '?', | ||
| 1644 | $tbl->fo->city == '?', | ||
| 1645 | '?' == $dbh->ANY( $tbl->fo->alias ) | ||
| 1646 | ) ); | ||
| 1647 | my $sth = $tbl->select || die( $tbl->error ); | ||
| 1648 | $sth->execute( $val1, $val2, { $val3 => 'varchar' } ) || die( $sth->error ); | ||
| 1649 | my $ref = $sth->fetchall_arrayref; | ||
| 1650 | my $val = $sth->fetchcol; | ||
| 1651 | my %hash = $sth->fetchhash; | ||
| 1652 | my @values = $sth->fetchrow; | ||
| 1653 | my $ref = $sth->fetchrow_hashref; | ||
| 1654 | my $obj = $sth->fetchrow_object; | ||
| 1655 | $sth->finish; | ||
| 1656 | $sth->ignore; | ||
| 1657 | $sth->join( $join_condition ); | ||
| 1658 | my $qo = $sth->query_object; | ||
| 1659 | $sth->rollback; | ||
| 1660 | my $rows = $sth->rows; | ||
| 1661 | my $dbi_sth = $sth->sth; | ||
| 1662 | my $tbl = $sth->table_object; | ||
| 1663 | |||
| 1664 | =head1 VERSION | ||
| 1665 | |||
| 1666 | v0.9.0 | ||
| 1667 | |||
| 1668 | =head1 DESCRIPTION | ||
| 1669 | |||
| 1670 | This is the statement object package from which other driver specific packages inherit from. | ||
| 1671 | |||
| 1672 | =head1 METHODS | ||
| 1673 | |||
| 1674 | =head2 as_string | ||
| 1675 | |||
| 1676 | Returns the current statement object as a string. | ||
| 1677 | |||
| 1678 | =head2 attach | ||
| 1679 | |||
| 1680 | $tbl->attach( $db_object ); | ||
| 1681 | |||
| 1682 | Provided with a L<DB::Object>, or one of its inheriting classes, and this will attach that database object to this statement object. | ||
| 1683 | |||
| 1684 | It returns the current statement object upon success, or upon error, it set an error an returns an empty list in list context, or C<undef> in scalar context. | ||
| 1685 | |||
| 1686 | =head2 bind_param | ||
| 1687 | |||
| 1688 | Provided with a list of arguments and they will be passed to L<DBI/bind_param> | ||
| 1689 | |||
| 1690 | If an error occurred, an error is returned, otherwise the return value of calling C<bind_param> is returned. | ||
| 1691 | |||
| 1692 | =head2 commit | ||
| 1693 | |||
| 1694 | If the statement parameter I<autocommit> is true, a C<COMMIT> statement will be prepared and executed. | ||
| 1695 | |||
| 1696 | The current object is returned. | ||
| 1697 | |||
| 1698 | =head2 database_object | ||
| 1699 | |||
| 1700 | Sets or gets the current database object. | ||
| 1701 | |||
| 1702 | =head2 distinct | ||
| 1703 | |||
| 1704 | Assuming a I<query> object property has already been set previously, this will add the C<DISTINCT> keyword to it if not already set. | ||
| 1705 | |||
| 1706 | If L</distinct> is called in void context, the query is executed immediately. | ||
| 1707 | |||
| 1708 | The query statement is returned. | ||
| 1709 | |||
| 1710 | =head2 dump | ||
| 1711 | |||
| 1712 | Provided with a file and this will print on STDOUT the columns used, separated by a tab and then will process each rows fetched with L<DBI::fetchrow> and will join the column valus with a tab before printing it out to STDOUT. | ||
| 1713 | |||
| 1714 | It returns the current object for chaining. | ||
| 1715 | |||
| 1716 | =head2 exec | ||
| 1717 | |||
| 1718 | This is an alias for L</execute> | ||
| 1719 | |||
| 1720 | =head2 execute | ||
| 1721 | |||
| 1722 | $sth->execute || die( $sth->error ); | ||
| 1723 | $sth->execute( $val1, $val2 ) || die( $sth->error ); | ||
| 1724 | # explicitly specify types | ||
| 1725 | # Here in this mixed example, $val1 and $val3 have known types | ||
| 1726 | $tbl->where( $dbh->AND( | ||
| 1727 | $tbl->fo->name == '?', | ||
| 1728 | $tbl->fo->city == '?', | ||
| 1729 | '?' == $dbh->ANY( $tbl->fo->alias ) | ||
| 1730 | ) ); | ||
| 1731 | my $sth = $tbl->select || die( $tbl->error ); | ||
| 1732 | $sth->execute( $val1, $val2, { $val3 => 'varchar' } ) || die( $sth->error ); | ||
| 1733 | |||
| 1734 | If binded values have been prepared, they are applied here before executing the query. | ||
| 1735 | |||
| 1736 | Sometime, you need to clearly specify what the datatype are for the value provided with C<execute>, because L<DB::Object::Query> could not figure it out. | ||
| 1737 | |||
| 1738 | Thus, if you do: | ||
| 1739 | |||
| 1740 | $tbl->where( | ||
| 1741 | $tbl->fo->name == '?' | ||
| 1742 | ); | ||
| 1743 | |||
| 1744 | L<DB::Object::Query> knows the datatype, because you are using a field object (C<fo>), but if you were doing: | ||
| 1745 | |||
| 1746 | $tbl->where( | ||
| 1747 | '?' == $dbh->ANY( $tbl->fo->alias ) | ||
| 1748 | ); | ||
| 1749 | |||
| 1750 | In this scenario, L<DB::Object::Query> does not know what the bind value would be, although we could venture a guess by looking at the right-hand side, but this is a bit hazardous. So you are left with a placeholder, but no datatype. So you would execute like: | ||
| 1751 | |||
| 1752 | $sth->execute({ $val => 'varchar' }); | ||
| 1753 | |||
| 1754 | If the total number of binded values does not match the total number of binded type, this will trigger a warning. | ||
| 1755 | |||
| 1756 | L<DBI/execute> will be called with the binded values and if this method was called in an object context, the current object is returned, otherwise the returned value from L<DBI/execute> is returned. | ||
| 1757 | |||
| 1758 | With the version C<0.5.0> of this module, this method is more able to find out the data type of the table field. To achieve this, it uses the L<field object|DB::Object::Fields::Field> set in each L<element object|DB::Object::Query::Element>. Those element objects are instantiated upon C<insert> or C<update> query. | ||
| 1759 | |||
| 1760 | Also, if you provide a value during an C<insert> or C<update> for a field that the database expects an array, this method will automatically convert it into an array. | ||
| 1761 | |||
| 1762 | Likewise, if the table field is of type C<json> or C<jsonb> and an hash reference value is provided, this method will encode the hash reference into a C<JSON> string. | ||
| 1763 | |||
| 1764 | =head2 executed | ||
| 1765 | |||
| 1766 | Returns true if this statement has already been executed, and false otherwise. | ||
| 1767 | |||
| 1768 | =head2 fetchall_arrayref | ||
| 1769 | |||
| 1770 | Similar to L<DBI/fetchall_arrayref>, this will execute the query and return an array reference of data. | ||
| 1771 | |||
| 1772 | =head2 fetchcol | ||
| 1773 | |||
| 1774 | Provided with an integer that represents a column number, starting from 0, and this will get each row of results and add the value for the column at the given offset. | ||
| 1775 | |||
| 1776 | it returns a list of those column value fetched. | ||
| 1777 | |||
| 1778 | =head2 fetchhash | ||
| 1779 | |||
| 1780 | This will retrieve an hash reference for the given row and return it as a regular hash. | ||
| 1781 | |||
| 1782 | =head2 fetchrow | ||
| 1783 | |||
| 1784 | This will retrieve the data from database using L</fetchrow_arrayref> and return the list of data as array in list context, or the first entry of the array in scalar context. | ||
| 1785 | |||
| 1786 | =head2 fetchrow_hashref | ||
| 1787 | |||
| 1788 | This will retrieve the data from the database as an hash reference. | ||
| 1789 | |||
| 1790 | It will convert any data from json to hash reference if L<DB::Object/auto_decode_json> is set to true. | ||
| 1791 | |||
| 1792 | it will also convert any datetime data into a L<DateTime> object if L<DB::Object/auto_convert_datetime_to_object> is true. | ||
| 1793 | |||
| 1794 | It returns the hash reference retrieved. | ||
| 1795 | |||
| 1796 | =head2 fetchrow_object | ||
| 1797 | |||
| 1798 | This will create dynamically a package named C<DB::Object::Postgres::Result::SomeTable> for example and load the hash reference retrieved from the database into this dynamically created packackage. | ||
| 1799 | |||
| 1800 | It returns the object thus created. | ||
| 1801 | |||
| 1802 | =head2 field_names | ||
| 1803 | |||
| 1804 | my $array_ref = $sth->field_names; | ||
| 1805 | |||
| 1806 | Returns an array reference of field names for the query. | ||
| 1807 | This must be called after executing the query, and before finishing retrieving all data from the database. | ||
| 1808 | |||
| 1809 | See also L<https://metacpan.org/pod/DBI#NAME1> | ||
| 1810 | |||
| 1811 | =head2 field_names_lc | ||
| 1812 | |||
| 1813 | my $array_ref = $sth->field_names_lc; | ||
| 1814 | |||
| 1815 | Same as L<field_names|/field_names>, except this makes all the column names in lower case. | ||
| 1816 | |||
| 1817 | See also L<https://metacpan.org/pod/DBI#NAME_lc> | ||
| 1818 | |||
| 1819 | =head2 field_names_uc | ||
| 1820 | |||
| 1821 | my $array_ref = $sth->field_names_uc; | ||
| 1822 | |||
| 1823 | Same as L<field_names|/field_names>, except this makes all the column names in lower case. | ||
| 1824 | |||
| 1825 | See also L<https://metacpan.org/pod/DBI#NAME_uc> | ||
| 1826 | |||
| 1827 | =head2 field_nullables | ||
| 1828 | |||
| 1829 | my $array_ref = $sth->field_nullables; | ||
| 1830 | |||
| 1831 | Returns an array reference of value for each field indicating if they can be null or not. | ||
| 1832 | |||
| 1833 | Possible values are: C<0> (or an empty string) = no, C<1> = yes, C<2> = unknown. | ||
| 1834 | |||
| 1835 | See also L<https://metacpan.org/pod/DBI#NULLABLE> | ||
| 1836 | |||
| 1837 | =head2 field_precisions | ||
| 1838 | |||
| 1839 | my $array_ref = $sth->field_precisions; | ||
| 1840 | |||
| 1841 | Returns an array reference of integer value foe each field indicating their precision. | ||
| 1842 | |||
| 1843 | As per DBI documentation: "For numeric columns, the value is the maximum number of digits (without considering a sign character or decimal point). Note that the "display size" for floating point types (REAL, FLOAT, DOUBLE) can be up to 7 characters greater than the precision (for the sign + decimal point + the letter E + a sign + 2 or 3 digits). | ||
| 1844 | |||
| 1845 | For any character type column the value is the OCTET_LENGTH, in other words the number of bytes, not characters." | ||
| 1846 | |||
| 1847 | See also L<https://metacpan.org/pod/DBI#PRECISION> | ||
| 1848 | |||
| 1849 | =head2 field_scales | ||
| 1850 | |||
| 1851 | my $array_ref = $sth->field_scales; | ||
| 1852 | |||
| 1853 | Returns an array reference of integer value foe each field. "C<NULL> (C<undef>) values indicate columns where scale is not applicable." | ||
| 1854 | |||
| 1855 | See also L<https://metacpan.org/pod/DBI#SCALE> | ||
| 1856 | |||
| 1857 | =head2 field_types | ||
| 1858 | |||
| 1859 | my $array_ref = $sth->field_types; | ||
| 1860 | |||
| 1861 | Returns an array reference of integer value foe each field. "The value indicates the data type of the corresponding column." | ||
| 1862 | |||
| 1863 | You can important those constant with C<use DBI ':sql_types'> | ||
| 1864 | |||
| 1865 | See also L<https://metacpan.org/pod/DBI#TYPE> | ||
| 1866 | |||
| 1867 | =head2 finish | ||
| 1868 | |||
| 1869 | Calls L<DBI/finish> and return the returned value, or an error if an error occurred. | ||
| 1870 | |||
| 1871 | =head2 ignore | ||
| 1872 | |||
| 1873 | This will change the query prepared and add the keyword C<IGNORE>. | ||
| 1874 | |||
| 1875 | If called in void context, this will execute the resulting statement handler immediately. | ||
| 1876 | |||
| 1877 | =head2 join | ||
| 1878 | |||
| 1879 | Provided with a target and an hash reference, or list or array reference of condition for the join and this will prepare the join statement. | ||
| 1880 | |||
| 1881 | If the original query is not of type C<select>, this will trigger an error. | ||
| 1882 | |||
| 1883 | The target mentioned above can be either a L<DB::Object::Statement> object, or a table object (L<DB::Object::Tables>), or even just a string representing the name of a table. | ||
| 1884 | |||
| 1885 | $tbl->select->join( $sth ); | ||
| 1886 | $tbl->select->join( $other_tbl ); | ||
| 1887 | $tbl->select->join( 'table_name' ); | ||
| 1888 | |||
| 1889 | The condition mentioned above can be a L<DB::Object::Operator> (C<AND>, C<OR> or C<NOT>), in which case the actual condition will be taken from that operator embedded value. | ||
| 1890 | |||
| 1891 | The condition can also be a L<DB::Object::Fields::Overloaded> object, which implies a table field with some operator and some value. | ||
| 1892 | |||
| 1893 | $tbl->select->join( $other_tbl, $other_tbl->fo->id == 2 ); | ||
| 1894 | |||
| 1895 | Here C<$other_tbl->fo->id == 2> will become a L<DB::Object::Fields::Overloaded> object. | ||
| 1896 | |||
| 1897 | The condition can also be an array reference or array object of conditions and implicitly the array entry will be joined with C<AND>: | ||
| 1898 | |||
| 1899 | $tbl->select->join( $other_tbl, ["user = 'joe'", $other_tbl->fo->id == 2] ); | ||
| 1900 | |||
| 1901 | The condition can also be an hash reference with each key being a table name to join and each value an hash reference of condition for that particular join with each key being a column name and each value the value of the join for that column. | ||
| 1902 | |||
| 1903 | my $tbl = $dbh->first_table; | ||
| 1904 | $tbl->select->join({ | ||
| 1905 | other_table => | ||
| 1906 | { | ||
| 1907 | id => 'first_table.id', | ||
| 1908 | user => 'first_table.user', | ||
| 1909 | }, | ||
| 1910 | yet_another_table => | ||
| 1911 | { | ||
| 1912 | id => 'other_table.id', | ||
| 1913 | }, | ||
| 1914 | }); | ||
| 1915 | |||
| 1916 | would become something like: | ||
| 1917 | |||
| 1918 | SELECT * | ||
| 1919 | FROM first_table | ||
| 1920 | LEFT JOIN other_table ON | ||
| 1921 | first_table.id = id AND | ||
| 1922 | first_table.user = user | ||
| 1923 | LEFT JOIN yet_another_table ON | ||
| 1924 | other_table.id = id | ||
| 1925 | |||
| 1926 | Each condition will be formatted assuming an C<AND> expression, so this is less flexible than using operator objects and table field objects. | ||
| 1927 | |||
| 1928 | If no condition is provided, this is taken to be a straight join. | ||
| 1929 | |||
| 1930 | $tbl->where( $tbl->fo->id == 2 ); | ||
| 1931 | $other_tbl->where( $other_tbl->fo->user 'john' ); | ||
| 1932 | $tbl->select->join( $other_tbl ); | ||
| 1933 | |||
| 1934 | Would become something like: | ||
| 1935 | |||
| 1936 | SELECT * | ||
| 1937 | FROM first_table, other_table | ||
| 1938 | WHERE id = 2 AND user = 'john' | ||
| 1939 | |||
| 1940 | If called in void context, this will execute the resulting statement handler immediately. | ||
| 1941 | |||
| 1942 | It returns the resulting statement handler. | ||
| 1943 | |||
| 1944 | It returns the statement handler. | ||
| 1945 | |||
| 1946 | =head2 number_of_fields | ||
| 1947 | |||
| 1948 | $sth->exec || die( $sth->error ); | ||
| 1949 | say "There are ", $sth->number_of_fields, " columns in this tuple."; | ||
| 1950 | |||
| 1951 | Returns an integer representing the number of fields in the SQL query executed. | ||
| 1952 | |||
| 1953 | See also L<https://metacpan.org/pod/DBI#NUM_OF_FIELDS> | ||
| 1954 | |||
| 1955 | =head2 number_of_params | ||
| 1956 | |||
| 1957 | $sth->exec || die( $sth->error ); | ||
| 1958 | say "There are ", $sth->number_of_params, " placeholders for this query."; | ||
| 1959 | |||
| 1960 | Returns the number of parameters (placeholders) in the prepared statement. | ||
| 1961 | |||
| 1962 | See also L<https://metacpan.org/pod/DBI#NUM_OF_PARAMS> | ||
| 1963 | |||
| 1964 | =head2 object | ||
| 1965 | |||
| 1966 | Returns the statement object explicitly. | ||
| 1967 | |||
| 1968 | my $sth = $tbl->select->object; | ||
| 1969 | |||
| 1970 | which is really equivalent to: | ||
| 1971 | |||
| 1972 | my $sth = $tbl->select; | ||
| 1973 | |||
| 1974 | =head2 priority | ||
| 1975 | |||
| 1976 | Provided with a priority integer that can be 0 or 1 with 0 being C<LOW_PRIORITY> and 1 being C<HIGH_PRIORITY> and this will adjust the query formatted to add the priority. This works only on Mysql drive though. | ||
| 1977 | |||
| 1978 | If used on queries other than C<DELETE>, C<INSERT>, C<REPLACE>, C<SELECT>, C<UPDATE> an error will be returned. | ||
| 1979 | |||
| 1980 | If called in void context, this will execute the newly create statement handler immediately. | ||
| 1981 | |||
| 1982 | It returns the newly create statement handler. | ||
| 1983 | |||
| 1984 | =head2 promise | ||
| 1985 | |||
| 1986 | This the same as calling L</execute>, except that the query will be executed asynchronously and a L<Promise::Me> object will be returned, so you can do asynchronous queries like this: | ||
| 1987 | |||
| 1988 | my $sth = $dbh->prepare( "SELECT some_slow_function(?)" ) || die( $dbh->error ); | ||
| 1989 | my $p = $sth->promise(10)->then(sub | ||
| 1990 | { | ||
| 1991 | my $st = shift( @_ ); | ||
| 1992 | my $ref = $st->fetchrow_hashref; | ||
| 1993 | my $obj = My::Module->new( %$ref ); | ||
| 1994 | })->catch(sub | ||
| 1995 | { | ||
| 1996 | $log->warn( "Failed to execute query: ", @_ ); | ||
| 1997 | }); | ||
| 1998 | my( $obj ) = await( $p ); | ||
| 1999 | |||
| 2000 | =head2 query | ||
| 2001 | |||
| 2002 | Sets or gets the previously formatted query as a regular string. | ||
| 2003 | |||
| 2004 | =head2 query_object | ||
| 2005 | |||
| 2006 | Sets or gets the query object used in this query. | ||
| 2007 | |||
| 2008 | =head2 query_time | ||
| 2009 | |||
| 2010 | Sets or gets the query time as a L<DateTime> object. | ||
| 2011 | |||
| 2012 | =head2 rollback | ||
| 2013 | |||
| 2014 | If there is a statement handler and the database parameter C<autocommit> is set to true, this will prepare a C<ROLLBACK> query and execute it. | ||
| 2015 | |||
| 2016 | =head2 rows | ||
| 2017 | |||
| 2018 | Returns the number of rows affected by the last query. | ||
| 2019 | |||
| 2020 | =head2 statement | ||
| 2021 | |||
| 2022 | Returns the SQL statement that was sent to the server to be prepared. | ||
| 2023 | |||
| 2024 | This is different from L<as_string|/as_string> in that L<as_string|/as_string> returns the SQL query built by L<DB::Object>. Obviously, both should be the same, but they come from different sources. | ||
| 2025 | |||
| 2026 | =head2 sth | ||
| 2027 | |||
| 2028 | Sets or gets the L<DBI> statement handler. | ||
| 2029 | |||
| 2030 | =head2 table | ||
| 2031 | |||
| 2032 | Sets or gets the table object (L<DB::Object::Tables>) for this query. | ||
| 2033 | |||
| 2034 | =head2 table_object | ||
| 2035 | |||
| 2036 | Sets or get the table object (L<DB::Object::Tables>) | ||
| 2037 | |||
| 2038 | =head2 undo | ||
| 2039 | |||
| 2040 | This is an alias for L</rollback> | ||
| 2041 | |||
| 2042 | =head2 wait | ||
| 2043 | |||
| 2044 | The implementation is driver dependent, and in this case, this is implemented only in L<DB::Object::Mysql> | ||
| 2045 | |||
| 2046 | =head2 _convert_datetime2object | ||
| 2047 | |||
| 2048 | A convenient short to enable or disable L<DB::Object/_convert_datetime2object> | ||
| 2049 | |||
| 2050 | =head2 _convert_json2hash | ||
| 2051 | |||
| 2052 | A convenient short to enable or disable L<DB::Object/_convert_json2hash> | ||
| 2053 | |||
| 2054 | =head1 SEE ALSO | ||
| 2055 | |||
| 2056 | L<DB::Object::Query>, L<DB::Object::Mysql::Query>, L<DB::Object::Postgres::Query>, L<DB::Object::SQLite::Query> | ||
| 2057 | |||
| 2058 | =head1 AUTHOR | ||
| 2059 | |||
| 2060 | Jacques Deguest E<lt>F<jack@deguest.jp>E<gt> | ||
| 2061 | |||
| 2062 | =head1 COPYRIGHT & LICENSE | ||
| 2063 | |||
| 2064 | Copyright (c) 2019-2021 DEGUEST Pte. Ltd. | ||
| 2065 | |||
| 2066 | You can use, copy, modify and redistribute this package and associated | ||
| 2067 | files under the same terms as Perl itself. | ||
| 2068 | |||
| 2069 | =cut |