SqlHelper.pm 29.9 KB
Newer Older
1 2
=head1 LICENSE

3
  Copyright (c) 1999-2011 The European Bioinformatics Institute and
4 5 6 7 8 9 10 11 12 13
  Genome Research Limited.  All rights reserved.

  This software is distributed under a modified Apache license.
  For license details, please see

    http://www.ensembl.org/info/about/code_licence.html

=head1 CONTACT

  Please email comments or questions to the public Ensembl
14
  developers list at <dev@ensembl.org>.
15 16 17 18

  Questions may also be sent to the Ensembl help desk at
  <helpdesk@ensembl.org>.

19
=cut
20 21 22 23 24 25 26 27 28 29 30

=head1 NAME

Bio::EnsEMBL::Utils::SqlHelper

=head1 VERSION

$Revision$

=head1 SYNOPSIS

31
  use Bio::EnsEMBL::Utils::SqlHelper;
32

33 34
  my $helper =
    Bio::EnsEMBL::Utils::SqlHelper->new( -DB_CONNECTION => $dbc );
35

36 37 38 39 40 41 42
  my $arr_ref = $helper->execute(
    -SQL      => 'select name, age from tab where col =?',
    -CALLBACK => sub {
      my @row = @{ shift @_ };
      return { name => $row[0], age => $row[1] };
    },
    -PARAMS => ['A'] );
43

44 45 46
  use Data::Dumper;
  print Dumper($arr_ref), "\n";
  # Prints out [name=>'name', age=>1] maybe ....
47 48


49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  # For transactional work; only works if your MySQL table
  # engine/database supports transactional work (such as InnoDB)

  $helper->transaction(
    -CALLBACK => sub {
      if ( $helper->execute_single_result(
                                      -SQL => 'select count(*) from tab'
           ) )
      {
        return $helper->execute_update('delete from tab');
      } else {
        return
          $helper->batch( -SQL  => 'insert into tab (?,?)',
                          -DATA => [ [ 1, 2 ], [ 1, 3 ], [ 1, 4 ] ] );
      }
    } );

=head1 DESCRIPTION
67

68
Easier database interaction
69 70 71 72 73 74 75

=head1 METHODS

See subrotuines.

=cut

76 77
package Bio::EnsEMBL::Utils::SqlHelper;

78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
use warnings;
use strict;

use Bio::EnsEMBL::Utils::Argument qw(rearrange);
use Bio::EnsEMBL::Utils::Scalar qw(assert_ref check_ref);
use Bio::EnsEMBL::Utils::Exception qw(throw warning);
use English qw( -no_match_vars ); #Used for $PROCESS_ID
use Scalar::Util qw(weaken); #Used to not hold a strong ref to DBConnection

=pod

=head2 new()

  Arg [DB_CONNECTION] : DBConnection instance to use
  Returntype          : Instance of helper
93 94
  Exceptions          : If the object given as a DBConnection is not one or it
                        was undefined
95 96 97 98
  Status              : Stable

Creates a new instance of this object.

99 100 101 102 103 104
  my $dba = get_dba('mydb');    # New DBAdaptor from somewhere
  my $helper = Bio::EnsEMBL::Utils::SqlHelper->new(
                                        -DB_CONNECTION => $dba->dbc() );

  $helper->execute_update( -SQL    => 'update tab set flag=?',
                           -PARAMS => [1] );
105 106 107 108 109 110 111 112 113

=cut

sub new {
	my ( $class, @args ) = @_;
	
	my ($db_connection) = rearrange([qw(db_connection)], @args);
	 
	my $self = bless( {}, ref($class) || $class );
114 115
	throw('-DB_CONNECTION construction parameter was undefined.') 
	 unless defined $db_connection;
116 117 118 119 120 121 122
	$self->db_connection($db_connection);
	
	return $self;
}

=pod

123 124
=head2 db_connection()

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
  Arg [1]     : DBConnection instance to use
  Description : Sets and retrieves the DBConnection 
  Returntype  : DBConnection if set; otherwise undef
  Exceptions  : If the object given as a DBConnection is not one or if an 
                attempt is made to set the value more than once
  Status      : Stable

=cut

sub db_connection {
  my ($self, $db_connection) = @_;
  if(defined $db_connection) {
    if(exists $self->{db_connection}) {
      throw('Cannot reset the DBConnection object; already defined ');
    }
    assert_ref($db_connection, 'Bio::EnsEMBL::DBSQL::DBConnection');
    $self->{db_connection} = $db_connection;
    weaken $self->{db_connection};
  }
  return $self->{db_connection};
}

# --------- SQL Methods

=pod

=head2 execute() - Execute a SQL statement with a custom row handler

153 154 155 156 157 158 159 160
  Arg [SQL]             : SQL to execute
  Arg [CALLBACK]        : The callback to use for mapping a row to a data point; 
                          leave blank for a default mapping to a 2D array
  Arg [USE_HASHREFS]    : If set to true will cause HashRefs to be returned 
                          to the callback & not ArrayRefs
  Arg [PARAMS]          : The binding parameters to the SQL statement
  Arg [PREPARE_PARAMS]  : Parameters to be passed onto the Statement Handle 
                          prepare call
161 162 163 164
  Returntype : 2D array containing the return of the callback
  Exceptions : If errors occur in the execution of the SQL
  Status     : Stable

165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
  my $arr_ref = $helper->execute(
    -SQL      => 'select a,b,c from tab where col =?',
    -CALLBACK => sub {
      my @row = @{ shift @_ };
      return { A => $row[0], B => $row[1], C => $row[2] };
    },
    -PARAMS => ['A'] );

  #Or with hashrefs
  my $arr_ref = $helper->execute(
    -SQL          => 'select a,b,c from tab where col =?',
    -USE_HASHREFS => 1,
    -CALLBACK     => sub {
      my $row = shift @_;
      return { A => $row->{a}, B => $row->{b}, C => $row->{c} };
    },
    -PARAMS => ['A'] );
182

183 184 185
Uses a callback defined by the C<sub> decalaration. Here we specify how
the calling code will deal with each row of a database's result set. The
sub can return any type of Object/hash/data structure you require.
186

187 188
Should you not specify a callback then a basic one will be assigned to
you which will return a 2D array structure e.g.
189 190

  my $arr_ref = $helper->execute(
191 192 193
                           -SQL => 'select a,b,c from tab where col =?',
                           -PARAMS => ['A'] );

194 195 196
This is equivalent to DBI's c<selectall_arrayref()> subroutine.

As an extension to this method you can write a closure subroutine which
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
takes in two parameters. The first is the array/hash reference & the
second is the statement handle used to execute. 99% of the time you will
not need it but there are occasions where you do need it. An example of
usage would be:

  my $conn = get_conn();    #From somwewhere
  my $arr_ref = $conn->execute(
    -SQL          => 'select a,b,c from tab where col =?',
    -USE_HASHREFS => 1,
    -CALLBACK     => sub {
      my ( $row, $sth ) = @_;
      #Then do something with sth
      return { A => $row->[0], B => $row->[1], C => $row->[2] };
    },
    -PARAMS => ['A'] );
212 213 214 215

Any arguments to bind to the incoming statement. This can be a set of scalars
or a 2D array if you need to specify any kind of types of sql objects i.e.

216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
  use DBI qw(:sql_types);

  my $conn = get_conn();
  my $arr_ref = $conn->execute(
    -SQL =>
      'select a,b,c from tab where col =? and num_col=? and other=?',
    -USE_HASHREFS => 1,
    -CALLBACK     => sub {
      my @row = @{ shift @_ };
      return { A => $row[0], B => $row[1], C => $row[2] };
    },
    -PARAMS => [ '1', SQL_VARCHAR ],
    [ 2, SQL_INTEGER ],
    'hello' );

Here we import DBI's sql types into our package and then pass in
multiple anonymous array references as parameters. Each param is
tested in the input and if it is detected to be an ARRAY reference we
dereference the array and run DBI's bind_param method. In fact you can
see each part of the incoming paramaters array as the contents to call
C<bind_param> with. The only difference is the package tracks the bind
position for you.
238 239 240 241 242

=cut

sub execute {
	my ( $self, @args ) = @_;
243
	my ($sql, $callback, $use_hashrefs, $params, $prepare_params) = rearrange([qw(sql callback use_hashrefs params prepare_params)], @args);
244 245 246 247 248 249 250 251
	my $has_return = 1;
	
	#If no callback then we execute using a default one which returns a 2D array
	if(!defined $callback) {
    throw('Cannot use fetchrow_hashref() with default mappers. Turn off this option') if $use_hashrefs;
    $callback = $self->_mappers()->{array_ref};
	}
	
252
	return $self->_execute( $sql, $callback, $has_return, $use_hashrefs, $params, $prepare_params );
253 254 255 256 257 258 259 260
}

=pod

=head2 execute_simple()

  Arg [SQL]           : SQL to execute
  Arg [PARAMS]        : The binding parameters to the SQL statement
261
  Arg [CALLBACK]      : Allows you to give a callback to do the mapping with
262 263 264 265
  Returntype : 1D array of data points
  Exceptions : If errors occur in the execution of the SQL
  Status     : Stable

266 267 268 269 270
  my $classification =
    $helper->execute_simple(
       -SQL =>
         'select meta_val from meta where meta_key =? order by meta_id',
       -PARAMS => ['species.classification'] );
271 272 273 274 275 276 277 278 279

Identical to C<execute> except you do not specify a sub-routine reference. 
Using this code assumes you want an array of single scalar values as returned 
by the given SQL statement.

=cut

sub execute_simple {
  my ( $self, @args ) = @_;
280
	my ($sql, $params, $callback) = rearrange([qw(sql params callback)], @args);
281 282
	my $has_return = 1;
	my $use_hashrefs = 0;
283
	$callback ||= $self->_mappers()->{first_element};
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
	return $self->_execute($sql, $callback, $has_return, $use_hashrefs, $params);
}

=pod

=head2 execute_no_return()

  Arg [SQL]           : SQL to execute
  Arg [CALLBACK]      : The callback to use for mapping a row to a data point;
                        we assume you are assigning into a data structure which
                        has requirements other than simple translation into an
                        array
  Arg [USE_HASHREFS]  : If set to true will cause HashRefs to be returned 
                        to the callback & not ArrayRefs
  Arg [PARAMS]        : The binding parameters to the SQL statement
  Returntype : None
  Exceptions : If errors occur in the execution of the SQL
  Status     : Stable

Whilst all other execute methods will return something; this assumes that the
given mapper subroutine will be performing the business of placing values
somewhere or doing something with them.

There is a huge temptation to nest queries using this method; do not! Execute
the values into an array using one of the other methods then run your subqueries
on them; or make a better first query. SQL is flexible; so use it.

=cut

sub execute_no_return {
	my ( $self, @args ) = @_;
	my ($sql, $callback, $use_hashrefs, $params) = rearrange([qw(sql callback use_hashrefs params)], @args);
	throw('No callback defined but this is a required parameter for execute_no_return()') if ! $callback;
	my $has_return = 0;
	$self->_execute( $sql, $callback, $has_return, $use_hashrefs, $params );
	return;
}

=pod

=head2 execute_into_hash()

326 327 328 329 330 331 332 333 334
  Arg [SQL]           : SQL to execute
  Arg [CALLBACK]      : The callback to use for mapping to a value in a hash
                        keyed by the first element in your result set; 
                        leave blank for a default mapping to a scalar value
                        of the second element
  Arg [PARAMS]        : The binding parameters to the SQL statement
  Returntype : A HashRef keyed by column 1 & value is the return of callback
  Exceptions : If errors occur in the execution of the SQL
  Status     : Stable
335

336 337 338 339
A variant of the execute methods but rather than returning a list of
mapped results this will assume the first column of a returning map &
the calling subroutine will map the remainder of your return as the
hash's key.
340

341 342
B<This code can handle simple queries to hashes, complex value mappings
and repeated mappings for the same key>.
343

344
For example:
345

346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
  my $sql    = 'select key, one, two from table where something =?';
  my $mapper = sub {
    my ( $row, $value ) = @_;
    #Ignore field 0 as that is being used for the key
    my $obj = Some::Obj->new( one => $row->[1], two => $row->[2] );
    return $obj;
  };

  my $hash =
    $helper->execute_into_hash( -SQL      => $sql,
                                -CALLBACK => $mapper,
                                -PARAMS   => ['val'] );

  #Or for a more simple usage
  my $sql = 'select biotype, count(gene_id) from gene group by biotype';
  my $biotype_hash = $conn->execute_into_hash( -SQL => $sql );
  print $biotype_hash->{protein_coding} || 0, "\n";

The basic pattern assumes a scenario where you are mapping in a one
key to one value. For more advanced mapping techniques you can use the
second value passed to the subroutine paramater set. This is shown as
C<$value> in the above examples. This value is what is found in the HASH
being populated in the background. So on the first time you encounter it
for the given key it will be undefined. For future invocations it will
be set to the value you gave it. This allows us to setup code like the
following

  my %args = ( -SQL => 'select meta_key, meta_value from meta '
                 . 'where meta_key =? order by meta_id',
               -PARAMS => ['species.classification'] );

  my $hash = $helper->execute_into_hash(
    %args,
    -CALLBACK => sub {
      my ( $row, $value ) = @_;
      $value = [] if !defined $value;
      push( @{$value}, $row->[1] );
      return $value;
    } );
385

386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
  #OR

  $hash = $helper->execute_into_hash(
    %args,
    -CALLBACK => sub {
      my ( $row, $value ) = @_;
      if ( defined $value ) {
        push( @{$value}, $row->[1] );
        return;
      }
      my $new_value = [ $row->[1] ];
      return $new_value;
    } );

The code understands that returning a defined value means to push this
value into the background hash. In example one we keep on re-inserting
the Array of classifications into the hash. Example two shows an early
return from the callback which indicates to the code we do not have any
value to re-insert into the hash. Of the two methods example one is
clearer but is possibliy slower.

B<Remember that the row you are given is the full row & not a view of
the reminaing fields.> Therefore indexing for the data you are concerned
with begins at position 1.
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424

=cut

sub execute_into_hash {
	my ( $self, @args ) = @_;
	my ($sql, $callback, $params) = rearrange([qw(sql callback params)], @args);
	my $hash = {};
	
	#If no callback then we execute using a default one which sets value to 2nd element
	if(!defined $callback) {
	 $callback = $self->_mappers()->{second_element};
	}
	
	#Default mapper uses the 1st key + something else from the mapper
	my $mapper = sub {
425 426 427 428 429 430 431
		my $row = shift @_;
		my $key = $row->[0];
		my $value = $hash->{$key};
		my $new_value = $callback->($row, $value);
		if($new_value) {
		 $hash->{ $key } = $new_value;
		}
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
		return;
	};
	
	$self->execute_no_return(
	  -SQL => $sql, 
	  -CALLBACK => $mapper,
	  -PARAMS => $params
	);
	
	return $hash;
}

=pod

=head2 execute_single_result()

  Arg [SQL]           : SQL to execute
  Arg [CALLBACK]      : The callback to use for mapping a row to a data point; 
                        leave blank for a default scalar mapping
  Arg [USE_HASHREFS]  : If set to true will cause HashRefs to be returned 
                        to the callback & not ArrayRefs
  Arg [PARAMS]        : The binding parameters to the SQL statement
454 455 456
  Returntype : One data point
  Exceptions : If errors occur in the execution of the SQL
  Status     : Stable
457

458 459 460 461
  my $meta_count =
    $helper->execute_single_result(
                -SQL => 'select count(*) from meta where species_id =?',
                -PARAMS => [1] );
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495

Very similar to C<execute()> except it will raise an exception if we have more 
or less than one row returned

=cut

sub execute_single_result {
	my ( $self, @args ) = @_;
	my ($sql, $callback, $use_hashrefs, $params) = rearrange(
	 [qw(sql callback use_hashrefs params)], @args);
	
	my $results = $self->execute_simple( 
	  -SQL => $sql, 
	  -CALLBACK => $callback, 
	  -USE_HASHREFS => $use_hashrefs, 
	  -PARAMS => $params
	);
	
	my $result_count = scalar(@{$results});
	if($result_count != 1) {
	  $params = [] if ! $params;
	  my $type = ($result_count == 0) ? 'No' : 'Too many';
		my $msg = "${type} results returned. Expected 1 but got $result_count for query '${sql}' with params [";
		$msg .= join( ',', map {(defined $_) ? $_ : '-undef-';} @{$params} );
		$msg .= ']';
		throw($msg);
	}
	return $results->[0];
}

=pod

=head2 transaction()

496 497 498 499 500 501
  Arg [CALLBACK]      : The callback used for transaction isolation; once 
                        the subroutine exists the code will decide on rollback
                        or commit
  Returntype : Return of the callback
  Exceptions : If errors occur in the execution of the SQL
  Status     : Stable
502

503 504 505 506 507 508 509
  my $val = $helper->transaction(
    -CALLBACK => sub {
      my ($dbc) = @_;
      #Do something
      return 1;
    } );

510
  #Or because of the arguments method we use
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
  my $val = $helper->transaction(
    sub {
      my ($dbc) = @_;
      #Do something
      return 1;
    } );

Creates a transactional block which will ensure that the connection is
committed when your submmited subroutine has finished or will rollback
in the event of an error occuring in your block.

The code will always force AutoCommit off but will restore it to its
previous setting. If your DBI/DBD driver does not support manual
commits then this code will break. The code will turn off the
C<disconnect_when_idle()> method to allow transactions to work as
expected.

An effect of using REPEATABLE READ transaction isolation (InnoDB's
default) is that your data is as fresh as when you started your current
transaction. To ensure the freshest data use C<SELECT ... from ... LOCK
IN SHARE MODE> or C<SELECT ... from ... LOCK FOR UPDATE> if you are
going to issue updates.

Creating a transaction within a transaction results in the commit
rollback statements occuring in the top level transaction. That way any
block of code which is meant to to be transaction can be wrapped in
this block ( assuming the same instance of SQLHelper is passed around &
used).
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553

=cut

sub transaction {
  my ($self, @args) = @_;
  
  my ($callback) = rearrange([qw(callback)], @args);
  
  throw('Callback was not a CodeRef. Got a reference of type ['.ref($callback).']') 
    unless check_ref($callback, 'CODE');
 
  my $dbc = $self->db_connection();
  my $original_dwi;
  my $ac;
  
554 555 556
  my $error;
  my $result;
  
557 558 559 560 561
  #If we were already in a transaction then we do not do any management of the
  #session & wait for the parent transaction(s) to finish
  my $perform_transaction = $self->_perform_transaction_code();
  if($perform_transaction) {
    $original_dwi = $dbc->disconnect_when_inactive();
562
    $dbc->disconnect_when_inactive(0);
563 564
    $ac = $dbc->db_handle()->{'AutoCommit'};
    $dbc->db_handle()->{'AutoCommit'} = 0;
565
    $self->_enable_transaction();
566 567
  }
  
568 569 570 571 572 573 574
  if(!$error) {
    eval {
      $result = $callback->($dbc);
      $dbc->db_handle()->commit() if $perform_transaction;
    };
    $error = $@;
  }
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
  
  if($perform_transaction) {
    if($error) {
      eval { $dbc->db_handle()->rollback(); };
    }
    $dbc->db_handle()->{'AutoCommit'} = $ac;
    $dbc->disconnect_when_inactive($original_dwi);
    $self->_disable_transaction();
  }
  
  throw("Transaction aborted because of error: ${error}") if $error;
  
  return $result;
}

=pod

=head2 execute_update()

594 595 596 597 598
  Arg [SQL]           : SQL to execute
  Arg [CALLBACK]      : The callback to use for calling methods on the 
                        DBI statement handle or DBConnection object after an 
                        update command
  Arg [PARAMS]        : The binding parameters to the SQL statement
599
  Arg [PREPARE_PARAMS] : Parameters to bind to the prepare() StatementHandle call
600 601 602
  Returntype : Number of rows affected
  Exceptions : If errors occur in the execution of the SQL
  Status     : Stable
603 604 605 606

Used for performing updates but conforms to the normal execute statement
subroutines.

607 608 609
  use DBI qw(:sql_types);
  $helper->execute_update(-SQL => 'update tab set name = ? where id =?',
                          -PARAMS => [ 'andy', [ 1, SQL_INTEGER ] ] );
610 611 612 613 614

If you need to do something a bit more advanced with your DML then you can
give the method a closure and this will be called after the execute has been
issued i.e.

615 616 617 618 619 620 621 622
  my $obj;
  $helper->execute_update(
    -SQL      => 'insert into tab (name) values(?)',
    -CALLBACK => sub {
      my ( $sth, $dbh ) = @_;
      $obj->{id} = $dbh->{mysql_insertid};
    },
    -PARAMS => [ $obj->name() ] );
623 624 625 626 627 628 629 630

This lets us access the statement handle & database handle to access other
properties such as the last identifier inserted.

=cut

sub execute_update {
  my ($self, @args) = @_;
631
  my ($sql, $callback, $params, $prepare_params) = rearrange([qw(sql callback params prepare_params)], @args);
632 633 634
  my $rv = 0;
  my $sth;
  eval {
635 636 637
    my @prepare_params;
    @prepare_params = @{$prepare_params} if check_ref($prepare_params, 'ARRAY');
    $sth = $self->db_connection()->prepare($sql, @prepare_params);
638 639
    $self->_bind_params($sth, $params);
    $rv = $sth->execute();
640
    $callback->($sth, $self->db_connection()->db_handle()) if $callback;
641 642 643 644 645 646 647 648 649 650
  };
  my $error = $@;
  $self->_finish_sth($sth);
  if($error) {
    my $params = join ' ', map { (defined $_) ? $_ : q{undef} } @{$params};
    throw("Cannot apply sql '${sql}' with params '${params}': ${error}");
  }
  return $rv;
}

651 652
=head2 execute_with_sth()

653 654 655 656 657 658
  Arg [SQL]             : SQL to execute
  Arg [CALLBACK]        : The callback to use for working with the statement
                          handle once returned. This is B<not> a mapper.
  Arg [PARAMS]          : The binding parameters to the SQL statement
  Arg [PREPARE_PARAMS]  : Used to pass parameters to the statement handle 
                          prepare method
659 660 661 662 663 664 665 666
  Description : A subrotuine which abstracts resource handling and statement
                preparing leaving the developer to define how to handle
                and process the statement.
  Returntype  : Anything you wish to return from the callback
  Exceptions  : If errors occur in the execution of the SQL
  Status      : Stable

  my $meta_count = $helper->execute_with_sth(
667 668
    -SQL      => 'select count(*) from meta where species_id =?',
    -PARAMS   => [1],
669 670 671
    -CALLBACK => sub {
      my ($sth) = @_;
      my $count;
672 673
      $sth->bind_columns( \($count) );
      while ( $sth->fetch ) {
674 675 676
        print $count, "\n";
      }
      return $count;
677
    } );
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692

Very similar to C<execute()> except this gives you full control over the
lifecycle of the statement handle & how you wish to proceed with working
with a statement handle. This is for situations where you believe going through
the mappers causes too much of a slow-down (since we have to execute a
subroutine for every row in order to map it correctly).

However please benchmark before adopting this method as it increases the 
complexity of your code and the mapper slow down only becomes apparent when
working with very large numbers of rows.

=cut

sub execute_with_sth {
  my ($self, @args) = @_;
693 694
  my ($sql, $callback, $params, $prepare_params) = rearrange([qw(sql callback params prepare_params)], @args);
  return $self->_base_execute( $sql, 1, $params, $callback, $prepare_params );
695 696
}

697 698
=pod

Andy Yates's avatar
Bad POD  
Andy Yates committed
699
=head2 batch()
700

701 702 703 704 705 706 707 708 709 710
  Arg [SQL]           : SQL to execute
  Arg [CALLBACK]      : The callback to use for working with the statement
                        handle once returned; specify this or -DATA
  Arg [DATA]          : The data to insert; specify this or -CALLBACK
  Arg [COMMIT_EVERY]  : Integer; defines the rate at which to issue commits to
                        the DB handle. This is important when working with 
                        InnoDB databases since it affects the speed of rollback
                        (larger gaps inbetween commits means more to rollback).
                        
                        Ignored if using the callback version.
711 712
  Arg [PREPARE_PARAMS]  : Used to pass parameters to the statement handle 
                          prepare method
713 714 715
  Returntype : Numbers of rows updated
  Exceptions : If errors occur in the execution of the SQL
  Status     : Stable
716 717

  my $alotofdata = getitfromsomewhere();
718 719 720 721 722 723 724 725 726
  $helper->batch(
    -SQL      => 'insert into table (one,two) values(?,?)',
    -CALLBACk => sub {
      my ( $sth, $dbc ) = @_;
      foreach my $data (@alotofdata) {
        $sth->execute( @{$data} );
      }
    } );

727
  #Or for a 2D array data driven approach
728 729
  $helper->batch( -SQL  => 'insert into table (one,two) values(?,?)',
                  -DATA => $alotofdata );
730 731 732 733 734 735 736 737 738 739 740 741 742 743

Takes in a sql statement & a code reference. Your SQL is converted into a 
prepared statement & then given as the first parameter to the closure. The
second parameter is the DBH which created the statement. This is intended
to let you do mass insertion into a database without the need to
re-preparing the same statement.

This can be combined with the transaction() code to provide a construct
which does batch insertion & is transactionally aware.

We can also use data based batch insertions i.e.

  #Needs to be like:
  #   [ [1,2], [3,4] ]
744 745 746 747 748 749 750 751
  #Or if using the DBI types:
  #  [ [ [ 1, SQL_INTEGER ], [ 2, SQL_INTEGER ] ],
  #    [ [ 3, SQL_INTEGER ], [ 4, SQL_INTEGER ] ] ];

  my $alotofdata = getitfromsomewhere();
  $helper->batch( -SQL  => 'insert into table (one,two) values(?,?)',
                  -DATA => $alotofdata );

752 753 754 755
This does exactly what the previous example.

All batch statements will return the value the callback computes. If you are 
using the previous example with a data array then the code will return the
756
number affected rows by the query.
757 758 759 760 761

=cut

sub batch {
  my ($self, @args) = @_;
762 763
  my ($sql, $callback, $data, $commit_every, $prepare_params) = 
    rearrange([qw(sql callback data commit_every prepare_params)], @args);
764 765 766 767 768 769 770
  
  if(! defined $callback && ! defined $data) {
    throw('You need to define a callback for insertion work or the 2D data array');
  }
  
  my $result;
  if(defined $callback) {
771
    $result = $self->_callback_batch($sql, $callback, $prepare_params);
772 773
  }
  else {
774
    $result = $self->_data_batch($sql, $data, $commit_every, $prepare_params);
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
  }
  return $result if defined $result;
  return;
}

#------- Internal methods

sub _mappers {
  my ($self) = @_;
  if(! exists $self->{_mappers}) {
    $self->{_mappers} = {
      first_element => sub {
        my ($row) = @_;
        return $row->[0];
      },
      second_element => sub {
        my ($row) = @_;
        return $row->[1];
      },
      array_ref => sub {
        my $row = shift @_;
	     return [@{$row}];
      }
    };
  }
  return $self->{_mappers};
}

sub _perform_transaction_code {
  my ($self) = @_;
  return $self->{_transaction_active}->{$PROCESS_ID} ? 0 : 1;
}

sub _enable_transaction {
  my ($self) = @_;
  $self->{_transaction_active}->{$PROCESS_ID} = 1;
  return;
}

sub _disable_transaction {
  my ($self) = @_;
  delete $self->{_transaction_active}->{$PROCESS_ID};
  return;
}

sub _bind_params {
	my ( $self, $sth, $params ) = @_;
	
	return if ! defined $params; #Return quickly if we had no data
	
	if(! check_ref($params, 'ARRAY')) {
	  throw(qq{The given parameters reference '${params}' is not an ARRAY; wrap in an ArrayRef});
	}
	
	my $count = 1;
	foreach my $param (@{$params}) {
		if ( check_ref($param, 'ARRAY') ) {
			$sth->bind_param( $count, @{$param} );
		}
		else {
			$sth->bind_param( $count, $param );
		}
		$count++;
	}
	return;
}

sub _execute {
843
	my ( $self, $sql, $callback, $has_return, $use_hashrefs, $params, $prepare_params ) = @_;
844

845 846
	throw('Not given a mapper. _execute() must always been given a CodeRef') unless check_ref($callback, 'CODE');
	
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
  my @results;
  
  my $sth_processor;
  if($use_hashrefs) {
    
    $sth_processor = sub {
      my ($sth) = @_;
      while( my $row = $sth->fetchrow_hashref() ) {
		    push(@results, $callback->($row, $sth));
		  }
    };
  }
  else {
    
    $sth_processor = sub {
      my ($sth) = @_;
      while ( my $row = $sth->fetchrow_arrayref() ) {
  			push(@results, $callback->($row, $sth));
  		}
    };
  }
  
869
  $self->_base_execute($sql, $has_return, $params, $sth_processor, $prepare_params);
870 871 872 873 874 875
  
  return \@results if $has_return;
	return;
}

sub _base_execute {
876
  my ( $self, $sql, $has_return, $params, $sth_processor, $prepare_params ) = @_;
877 878 879
  
  throw('Not given a sth_processor. _base_execute() must always been given a CodeRef') unless check_ref($sth_processor, 'CODE');
	
880 881 882 883 884 885 886 887 888 889
	$params = [] unless $params;
	
	my $conn = $self->db_connection;
	my @results;

	my $error;
	my $sth_close_error;
	my $sth;

	eval {
890 891 892 893 894
	  my @prepare_params;
	  @prepare_params = @{$prepare_params} if check_ref($prepare_params, 'ARRAY');
		$sth = $conn->prepare($sql, @prepare_params);
		throw("Cannot continue as prepare() did not return a handle with prepare params '@prepare_params'") 
		  unless $sth;
895 896
		$self->_bind_params( $sth, $params );
		$sth->execute();
897
    	$sth_processor->($sth);
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
	};
	
	$error = $@;
	$self->_finish_sth($sth);
	if($error) {
  	throw("Cannot run '${sql}' with params '@{$params}' due to error: $error") if $error;
	}
	return \@results if $has_return;
	return;
}

sub _finish_sth {
  my ($self, $sth) = @_;
  eval { $sth->finish() if defined $sth; };
  warning('Cannot finish() the statement handle: $@') if $@;
  return;
}

sub _callback_batch {
917
  my ($self, $sql, $callback, $prepare_params) = @_;
918 919 920 921
  my $error;
  my $sth;
  my $closure_return;
  eval {
922 923 924
    my @prepare_params;
    @prepare_params = @{$prepare_params} if check_ref($prepare_params, 'ARRAY');
    $sth = $self->db_connection()->prepare($sql, @prepare_params); 
925 926 927 928 929 930 931 932 933 934 935
    $closure_return = $callback->($sth, $self->db_connection());
  };
  $error = $@;
  $self->_finish_sth($sth);
	throw("Problem detected during batch work: $error") if $error;
  
  return $closure_return if defined $closure_return;
  return;
}

sub _data_batch {
936
  my ($self, $sql, $data, $commit_every, $prepare_params) = @_;
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
  
  #Input checks
  assert_ref($data, 'ARRAY');
  my $data_length = scalar(@{$data});
  return 0 unless $data_length > 0;
  my $first_row = $data->[0];
  throw('I expect to work with a 2D ArrayRef but this is not one') unless check_ref($first_row, 'ARRAY');

  my $callback = sub {
    my ($sth, $dbc) = @_;
    my $total_affected = 0;
    #Iterate over each data point
    for(my $data_index = 0; $data_index < $data_length; $data_index++) {
      my $row = $data->[$data_index];
      $self->_bind_params($sth, $row);
      my $affected = eval {$sth->execute()};
      if($@) {
        throw("Problem working with $sql with params @{$row}: $@");
      }
      my $num_affected = ($affected) ? $affected :  0; #Get around DBI's 0E0
      $total_affected += $num_affected;
958 959 960 961 962 963 964 965 966 967 968 969 970
      
      #Lets us do a commit once every x rows apart from 0. We also finish
      #off with a commit if the code told us we were doing it
      if($commit_every) {
        if( ($data_index % $commit_every == 0) && $data_index != 0) {
          $dbc->db_handle()->commit();
        }
      }
    }
    
    #finish off with a commit if the code told us we were doing it
    if($commit_every) {
      $dbc->db_handle()->commit();
971
    }
972
    
973 974 975
    return $total_affected || 0;
  };
  
976
  return $self->_callback_batch($sql, $callback, $prepare_params)
977 978
}

979
1;