| 1 | =head1 LICENSE | ||
| 2 | |||
| 3 | See the NOTICE file distributed with this work for additional information | ||
| 4 | regarding copyright ownership. | ||
| 5 | |||
| 6 | Licensed under the Apache License, Version 2.0 (the "License"); | ||
| 7 | you may not use this file except in compliance with the License. | ||
| 8 | You may obtain a copy of the License at | ||
| 9 | |||
| 10 | http://www.apache.org/licenses/LICENSE-2.0 | ||
| 11 | |||
| 12 | Unless required by applicable law or agreed to in writing, software | ||
| 13 | distributed under the License is distributed on an "AS IS" BASIS, | ||
| 14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| 15 | See the License for the specific language governing permissions and | ||
| 16 | limitations under the License. | ||
| 17 | |||
| 18 | =cut | ||
| 19 | |||
| 20 | |||
| 21 | =head1 CONTACT | ||
| 22 | |||
| 23 | Please email comments or questions to the public Ensembl | ||
| 24 | developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. | ||
| 25 | |||
| 26 | Questions may also be sent to the Ensembl help desk at | ||
| 27 | <http://www.ensembl.org/Help/Contact>. | ||
| 28 | |||
| 29 | =cut | ||
| 30 | |||
| 31 | =head1 NAME | ||
| 32 | |||
| 33 | Bio::EnsEMBL::Utils::SqlHelper | ||
| 34 | |||
| 35 | =head1 VERSION | ||
| 36 | |||
| 37 | $Revision$ | ||
| 38 | |||
| 39 | =head1 SYNOPSIS | ||
| 40 | |||
| 41 | use Bio::EnsEMBL::Utils::SqlHelper; | ||
| 42 | |||
| 43 | my $helper = | ||
| 44 | Bio::EnsEMBL::Utils::SqlHelper->new( -DB_CONNECTION => $dbc ); | ||
| 45 | |||
| 46 | my $arr_ref = $helper->execute( | ||
| 47 | -SQL => 'select name, age from tab where col =?', | ||
| 48 | -CALLBACK => sub { | ||
| 49 | my @row = @{ shift @_ }; | ||
| 50 | return { name => $row[0], age => $row[1] }; | ||
| 51 | }, | ||
| 52 | -PARAMS => ['A'] ); | ||
| 53 | |||
| 54 | use Data::Dumper; | ||
| 55 | print Dumper($arr_ref), "\n"; | ||
| 56 | # Prints out [name=>'name', age=>1] maybe .... | ||
| 57 | |||
| 58 | |||
| 59 | # For transactional work; only works if your MySQL table | ||
| 60 | # engine/database supports transactional work (such as InnoDB) | ||
| 61 | |||
| 62 | $helper->transaction( | ||
| 63 | -CALLBACK => sub { | ||
| 64 | if ( $helper->execute_single_result( | ||
| 65 | -SQL => 'select count(*) from tab' | ||
| 66 | ) ) | ||
| 67 | { | ||
| 68 | return $helper->execute_update('delete from tab'); | ||
| 69 | } else { | ||
| 70 | return | ||
| 71 | $helper->batch( -SQL => 'insert into tab (?,?)', | ||
| 72 | -DATA => [ [ 1, 2 ], [ 1, 3 ], [ 1, 4 ] ] ); | ||
| 73 | } | ||
| 74 | } ); | ||
| 75 | |||
| 76 | =head1 DESCRIPTION | ||
| 77 | |||
| 78 | Easier database interaction | ||
| 79 | |||
| 80 | =cut | ||
| 81 | |||
| 82 | package Bio::EnsEMBL::Utils::SqlHelper; | ||
| 83 | $Bio::EnsEMBL::Utils::SqlHelper::VERSION = '114.0.0_50'; # TRIAL | ||
| 84 | $Bio::EnsEMBL::Utils::SqlHelper::VERSION = '114.0.050'; | ||
| 85 | use warnings; | ||
| 86 | use strict; | ||
| 87 | |||
| 88 | use Bio::EnsEMBL::Utils::Argument qw(rearrange); | ||
| 89 | use Bio::EnsEMBL::Utils::Scalar qw(assert_ref check_ref); | ||
| 90 | use Bio::EnsEMBL::Utils::Exception qw(throw); | ||
| 91 | use Bio::EnsEMBL::Utils::Iterator; | ||
| 92 | use English qw( -no_match_vars ); #Used for $PROCESS_ID | ||
| 93 | use Scalar::Util qw(weaken); #Used to not hold a strong ref to DBConnection | ||
| 94 | use Time::HiRes; | ||
| 95 | |||
| 96 | =pod | ||
| 97 | |||
| 98 | =head2 new() | ||
| 99 | |||
| 100 | Arg [DB_CONNECTION] : Bio::EnsEMBL::DBSQL::DBConnection $db_connection | ||
| 101 | Returntype : Instance of helper | ||
| 102 | Exceptions : If the object given as a DBConnection is not one or it | ||
| 103 | was undefined | ||
| 104 | Status : Stable | ||
| 105 | Description : Creates a new instance of this object. | ||
| 106 | Example : | ||
| 107 | my $dba = get_dba('mydb'); # New DBAdaptor from somewhere | ||
| 108 | my $helper = Bio::EnsEMBL::Utils::SqlHelper->new( | ||
| 109 | -DB_CONNECTION => $dba->dbc() | ||
| 110 | ); | ||
| 111 | |||
| 112 | $helper->execute_update( -SQL => 'update tab set flag=?', | ||
| 113 | -PARAMS => [1] ); | ||
| 114 | |||
| 115 | =cut | ||
| 116 | |||
| 117 | sub new { | ||
| 118 | my ( $class, @args ) = @_; | ||
| 119 | |||
| 120 | my ($db_connection) = rearrange([qw(db_connection)], @args); | ||
| 121 | |||
| 122 | my $self = bless( {}, ref($class) || $class ); | ||
| 123 | throw('-DB_CONNECTION construction parameter was undefined.') | ||
| 124 | unless defined $db_connection; | ||
| 125 | $self->db_connection($db_connection); | ||
| 126 | |||
| 127 | return $self; | ||
| 128 | } | ||
| 129 | |||
| 130 | =pod | ||
| 131 | |||
| 132 | =head2 db_connection() | ||
| 133 | |||
| 134 | Arg [1] : Bio::EnsEMBL::DBSQL::DBConnection $db_connection | ||
| 135 | Description : Sets and retrieves the DBConnection | ||
| 136 | Returntype : Bio::EnsEMBL::DBSQL::DBConnection | ||
| 137 | Exceptions : If the object given as a DBConnection is not one or if an | ||
| 138 | attempt is made to set the value more than once | ||
| 139 | Status : Stable | ||
| 140 | |||
| 141 | =cut | ||
| 142 | |||
| 143 | sub db_connection { | ||
| 144 | my ($self, $db_connection) = @_; | ||
| 145 | if(defined $db_connection) { | ||
| 146 | if(exists $self->{db_connection}) { | ||
| 147 | throw('Cannot reset the DBConnection object; already defined '); | ||
| 148 | } | ||
| 149 | assert_ref($db_connection, 'Bio::EnsEMBL::DBSQL::DBConnection', 'db_connection'); | ||
| 150 | $self->{db_connection} = $db_connection; | ||
| 151 | weaken $self->{db_connection}; | ||
| 152 | } | ||
| 153 | return $self->{db_connection}; | ||
| 154 | } | ||
| 155 | |||
| 156 | # --------- SQL Methods | ||
| 157 | |||
| 158 | =pod | ||
| 159 | |||
| 160 | =head2 execute() - Execute a SQL statement with a custom row handler | ||
| 161 | |||
| 162 | Arg [SQL] : string SQL to execute | ||
| 163 | Arg [CALLBACK] : CodeRef; The callback to use for mapping a row to a data | ||
| 164 | point; leave blank for a default mapping to a 2D array | ||
| 165 | Arg [USE_HASHREFS] : boolean If set to true will cause HashRefs to be returned | ||
| 166 | to the callback & not ArrayRefs | ||
| 167 | Arg [PARAMS] : ArrayRef The binding parameters to the SQL statement | ||
| 168 | Arg [PREPARE_PARAMS] : boolean Parameters to be passed onto the Statement Handle | ||
| 169 | prepare call | ||
| 170 | Arg [ITERATOR] : boolean Request a Bio::EnsEMBL::Utils::Iterator | ||
| 171 | rather than a 2D array | ||
| 172 | Returntype : ArrayRef or Bio::EnsEMBL::Utils::Iterator | ||
| 173 | Exceptions : If errors occur in the execution of the SQL | ||
| 174 | Status : Stable | ||
| 175 | Example : | ||
| 176 | my $arr_ref = $helper->execute( | ||
| 177 | -SQL => 'select a,b,c from tab where col =?', | ||
| 178 | -CALLBACK => sub { | ||
| 179 | my @row = @{ shift @_ }; | ||
| 180 | return { A => $row[0], B => $row[1], C => $row[2] }; | ||
| 181 | }, | ||
| 182 | -PARAMS => ['A'] ); | ||
| 183 | |||
| 184 | #Or with hashrefs | ||
| 185 | my $arr_ref = $helper->execute( | ||
| 186 | -SQL => 'select a,b,c from tab where col =?', | ||
| 187 | -USE_HASHREFS => 1, | ||
| 188 | -CALLBACK => sub { | ||
| 189 | my $row = shift @_; | ||
| 190 | return { A => $row->{a}, B => $row->{b}, C => $row->{c} }; | ||
| 191 | }, | ||
| 192 | -PARAMS => ['A'] ); | ||
| 193 | |||
| 194 | Description: | ||
| 195 | Uses a callback defined by the sub decalaration. Here we specify how | ||
| 196 | the calling code will deal with each row of a database's result set. The | ||
| 197 | sub can return any type of Object/hash/data structure you require. | ||
| 198 | |||
| 199 | Should you not specify a callback then a basic one will be assigned to | ||
| 200 | you which will return a 2D array structure e.g. | ||
| 201 | |||
| 202 | my $arr_ref = $helper->execute( | ||
| 203 | -SQL => 'select a,b,c from tab where col =?', | ||
| 204 | -PARAMS => ['A'] ); | ||
| 205 | |||
| 206 | This is equivalent to DBI's selectall_arrayref() subroutine. | ||
| 207 | |||
| 208 | As an extension to this method you can write a closure subroutine which | ||
| 209 | takes in two parameters. The first is the array/hash reference & the | ||
| 210 | second is the statement handle used to execute. 99% of the time you will | ||
| 211 | not need it but there are occasions where you do need it. An example of | ||
| 212 | usage would be: | ||
| 213 | |||
| 214 | my $conn = get_conn(); #From somwewhere | ||
| 215 | my $arr_ref = $conn->execute( | ||
| 216 | -SQL => 'select a,b,c from tab where col =?', | ||
| 217 | -USE_HASHREFS => 1, | ||
| 218 | -CALLBACK => sub { | ||
| 219 | my ( $row, $sth ) = @_; | ||
| 220 | #Then do something with sth | ||
| 221 | return { A => $row->[0], B => $row->[1], C => $row->[2] }; | ||
| 222 | }, | ||
| 223 | -PARAMS => ['A'] ); | ||
| 224 | |||
| 225 | Any arguments to bind to the incoming statement. This can be a set of scalars | ||
| 226 | or a 2D array if you need to specify any kind of types of sql objects i.e. | ||
| 227 | |||
| 228 | use DBI qw(:sql_types); | ||
| 229 | |||
| 230 | my $conn = get_conn(); | ||
| 231 | my $arr_ref = $conn->execute( | ||
| 232 | -SQL => | ||
| 233 | 'select a,b,c from tab where col =? and num_col=? and other=?', | ||
| 234 | -USE_HASHREFS => 1, | ||
| 235 | -CALLBACK => sub { | ||
| 236 | my @row = @{ shift @_ }; | ||
| 237 | return { A => $row[0], B => $row[1], C => $row[2] }; | ||
| 238 | }, | ||
| 239 | -PARAMS => [ '1', SQL_VARCHAR ], | ||
| 240 | [ 2, SQL_INTEGER ], | ||
| 241 | 'hello' ); | ||
| 242 | |||
| 243 | Here we import DBI's sql types into our package and then pass in | ||
| 244 | multiple anonymous array references as parameters. Each param is | ||
| 245 | tested in the input and if it is detected to be an ARRAY reference we | ||
| 246 | dereference the array and run DBI's bind_param method. In fact you can | ||
| 247 | see each part of the incoming paramaters array as the contents to call | ||
| 248 | C<bind_param> with. The only difference is the package tracks the bind | ||
| 249 | position for you. | ||
| 250 | |||
| 251 | We can get back a L<Bio::EnsEMBL::Utils::Iterator> object which can be used | ||
| 252 | to iterate over the results set without first materializing the data into | ||
| 253 | memory. An example would be: | ||
| 254 | |||
| 255 | my $iterator = $helper->execute( | ||
| 256 | -SQL => 'select a,b,c from tab where col =?', | ||
| 257 | -PARAMS => ['A'] | ||
| 258 | -ITERATOR => 1); | ||
| 259 | while($iterator->has_next()) { | ||
| 260 | my $row = $iterator->next(); | ||
| 261 | #Do something | ||
| 262 | } | ||
| 263 | |||
| 264 | This is very useful for very large datasets. | ||
| 265 | |||
| 266 | =cut | ||
| 267 | |||
| 268 | sub execute { | ||
| 269 | my ( $self, @args ) = @_; | ||
| 270 | my ($sql, $callback, $use_hashrefs, $params, $prepare_params, $iterator) = | ||
| 271 | rearrange([qw(sql callback use_hashrefs params prepare_params iterator)], @args); | ||
| 272 | my $has_return = 1; | ||
| 273 | |||
| 274 | #If no callback then we execute using a default one which returns a 2D array | ||
| 275 | if(!defined $callback) { | ||
| 276 | if($use_hashrefs) { | ||
| 277 | $callback = $self->_mappers()->{hash_ref}; | ||
| 278 | } | ||
| 279 | else { | ||
| 280 | $callback = $self->_mappers()->{array_ref}; | ||
| 281 | } | ||
| 282 | } | ||
| 283 | |||
| 284 | return $self->_execute( $sql, $callback, $has_return, $use_hashrefs, $params, $prepare_params, $iterator ); | ||
| 285 | } | ||
| 286 | |||
| 287 | =pod | ||
| 288 | |||
| 289 | =head2 execute_simple() | ||
| 290 | |||
| 291 | Arg [SQL] : string $sql | ||
| 292 | Arg [PARAMS] : ArrayRef $params | ||
| 293 | Arg [CALLBACK] : CodeRef $callback | ||
| 294 | Returntype : ArrayRef of 1D elements | ||
| 295 | Exceptions : If errors occur in the execution of the SQL | ||
| 296 | Status : Stable | ||
| 297 | Example : my $classification = | ||
| 298 | $helper->execute_simple( | ||
| 299 | -SQL => 'select meta_val from meta where meta_key =? order by meta_id', | ||
| 300 | -PARAMS => ['species.classification'] | ||
| 301 | ); | ||
| 302 | Description: Similar to execute() but without a sub-routine reference. | ||
| 303 | Using this code assumes you want an array of single scalar values | ||
| 304 | as returned by the given SQL statement. | ||
| 305 | =cut | ||
| 306 | |||
| 307 | sub execute_simple { | ||
| 308 | my ( $self, @args ) = @_; | ||
| 309 | my ($sql, $params, $callback) = rearrange([qw(sql params callback)], @args); | ||
| 310 | my $has_return = 1; | ||
| 311 | my $use_hashrefs = 0; | ||
| 312 | $callback ||= $self->_mappers()->{first_element}; | ||
| 313 | return $self->_execute($sql, $callback, $has_return, $use_hashrefs, $params); | ||
| 314 | } | ||
| 315 | |||
| 316 | =pod | ||
| 317 | |||
| 318 | =head2 execute_no_return() | ||
| 319 | |||
| 320 | Arg [SQL] : string sql | ||
| 321 | Arg [CALLBACK] : CodeRef The callback to use for mapping a row to a data point; | ||
| 322 | we assume you are assigning into a data structure which | ||
| 323 | has requirements other than simple translation into an | ||
| 324 | array | ||
| 325 | Arg [USE_HASHREFS] : boolean If set to true will cause HashRefs to be returned | ||
| 326 | to the callback and not ArrayRefs | ||
| 327 | Arg [PARAMS] : ArrayRef The binding parameters to the SQL statement | ||
| 328 | Returntype : None | ||
| 329 | Exceptions : If errors occur in the execution of the SQL | ||
| 330 | Status : Stable | ||
| 331 | Description: Whilst all other execute methods will return something; this assumes that the | ||
| 332 | given mapper subroutine will be performing the business of placing values | ||
| 333 | somewhere or doing something with them. | ||
| 334 | |||
| 335 | There is a huge temptation to nest queries using this method; do not! Execute | ||
| 336 | the values into an array using one of the other methods then run your subqueries | ||
| 337 | on them; or make a better first query. SQL is flexible; so use it. | ||
| 338 | |||
| 339 | =cut | ||
| 340 | |||
| 341 | sub execute_no_return { | ||
| 342 | my ( $self, @args ) = @_; | ||
| 343 | my ($sql, $callback, $use_hashrefs, $params) = rearrange([qw(sql callback use_hashrefs params)], @args); | ||
| 344 | throw('No callback defined but this is a required parameter for execute_no_return()') if ! $callback; | ||
| 345 | my $has_return = 0; | ||
| 346 | my $prepare_params = []; | ||
| 347 | $self->_execute( $sql, $callback, $has_return, $use_hashrefs, $params); | ||
| 348 | return; | ||
| 349 | } | ||
| 350 | |||
| 351 | =pod | ||
| 352 | |||
| 353 | =head2 execute_into_hash() | ||
| 354 | |||
| 355 | Arg [SQL] : string $sql | ||
| 356 | Arg [CALLBACK] : CodeRef The callback to use for mapping to a value in a hash | ||
| 357 | keyed by the first element in your result set; | ||
| 358 | leave blank for a default mapping to a scalar value | ||
| 359 | of the second element | ||
| 360 | Arg [PARAMS] : The binding parameters to the SQL statement | ||
| 361 | Returntype : HashRef keyed by column 1 & value is the return of callback | ||
| 362 | Exceptions : If errors occur in the execution of the SQL | ||
| 363 | Status : Stable | ||
| 364 | Description: A variant of the execute methods but rather than returning a list of | ||
| 365 | mapped results, this will assume the first column of a returning map and | ||
| 366 | the calling subroutine will map the remainder of your return as the | ||
| 367 | hash's key. | ||
| 368 | |||
| 369 | This code can handle simple queries to hashes, complex value mappings | ||
| 370 | and repeated mappings for the same key. | ||
| 371 | |||
| 372 | |||
| 373 | |||
| 374 | Example: | ||
| 375 | |||
| 376 | my $sql = 'select key, one, two from table where something =?'; | ||
| 377 | my $mapper = sub { | ||
| 378 | # Argument one is a row from the result, argument two is any previously seen value for the first column of the row | ||
| 379 | my ( $row, $value ) = @_; | ||
| 380 | #Ignore field 0 as that is being used for the key | ||
| 381 | my $obj = Some::Obj->new( one => $row->[1], two => $row->[2] ); | ||
| 382 | return $obj; | ||
| 383 | }; | ||
| 384 | |||
| 385 | my $hash = $helper->execute_into_hash( -SQL => $sql, | ||
| 386 | -CALLBACK => $mapper, | ||
| 387 | -PARAMS => ['val'] ); | ||
| 388 | |||
| 389 | #Or the default simplistic invocation | ||
| 390 | my $sql = 'select biotype, count(gene_id) from gene group by biotype'; | ||
| 391 | my $biotype_hash = $conn->execute_into_hash( -SQL => $sql ); | ||
| 392 | print $biotype_hash->{protein_coding} || 0, "\n"; | ||
| 393 | |||
| 394 | # More complicated mapping, result hash will be keyed on "meta_key" | ||
| 395 | # Hash will contain lists of values linked to their meta_key | ||
| 396 | my %args = ( -SQL => 'select meta_key, meta_value from meta ' | ||
| 397 | . 'where meta_key =? order by meta_id', | ||
| 398 | -PARAMS => ['species.classification'] ); | ||
| 399 | |||
| 400 | my $hash = $helper->execute_into_hash( | ||
| 401 | %args, | ||
| 402 | -CALLBACK => sub { | ||
| 403 | my ( $row, $value ) = @_; | ||
| 404 | $value = [] if !defined $value; | ||
| 405 | push( @{$value}, $row->[1] ); | ||
| 406 | return $value; | ||
| 407 | } ); | ||
| 408 | |||
| 409 | # Add new values to an already seen existing meta_key | ||
| 410 | $hash = $helper->execute_into_hash( | ||
| 411 | %args, | ||
| 412 | -CALLBACK => sub { | ||
| 413 | my ( $row, $value ) = @_; | ||
| 414 | if ( defined $value ) { | ||
| 415 | # Calling code is dealing with $row->[0], so we only have to handle the remaining columns | ||
| 416 | push( @{$value}, $row->[1] ); | ||
| 417 | return; | ||
| 418 | } | ||
| 419 | my $new_value = [ $row->[1] ]; | ||
| 420 | return $new_value; | ||
| 421 | } ); | ||
| 422 | |||
| 423 | =cut | ||
| 424 | |||
| 425 | sub execute_into_hash { | ||
| 426 | my ( $self, @args ) = @_; | ||
| 427 | my ($sql, $callback, $params) = rearrange([qw(sql callback params)], @args); | ||
| 428 | my $hash = {}; | ||
| 429 | |||
| 430 | #If no callback then we execute using a default one which sets value to 2nd element | ||
| 431 | if(!defined $callback) { | ||
| 432 | $callback = $self->_mappers()->{second_element}; | ||
| 433 | } | ||
| 434 | |||
| 435 | #Default mapper uses the 1st key + something else from the mapper | ||
| 436 | my $mapper = sub { | ||
| 437 | my $row = shift @_; | ||
| 438 | my $key = $row->[0]; | ||
| 439 | my $value = $hash->{$key}; | ||
| 440 | my $new_value = $callback->($row, $value); | ||
| 441 | if(defined $new_value) { | ||
| 442 | $hash->{ $key } = $new_value; | ||
| 443 | } | ||
| 444 | return; | ||
| 445 | }; | ||
| 446 | |||
| 447 | $self->execute_no_return( | ||
| 448 | -SQL => $sql, | ||
| 449 | -CALLBACK => $mapper, | ||
| 450 | -PARAMS => $params | ||
| 451 | ); | ||
| 452 | |||
| 453 | return $hash; | ||
| 454 | } | ||
| 455 | |||
| 456 | =pod | ||
| 457 | |||
| 458 | =head2 execute_single_result() | ||
| 459 | |||
| 460 | Arg [SQL] : string $sql | ||
| 461 | Arg [CALLBACK] : CodeRef The callback to use for mapping a row to a data point; | ||
| 462 | leave blank for a default scalar mapping | ||
| 463 | Arg [USE_HASHREFS] : boolean If set to true will cause HashRefs to be returned | ||
| 464 | to the callback & not ArrayRefs | ||
| 465 | Arg [PARAMS] : ArrayRef The binding parameters to the SQL statement | ||
| 466 | Arg [NO_ERROR] : Boolean Flag to indicate that the code should not | ||
| 467 | throw an error when row counts are not equal to 1 | ||
| 468 | Returntype : Scalar | ||
| 469 | Exceptions : If errors occur in the execution of the SQL, if the query | ||
| 470 | returned more than 1 row and if we found no rows. | ||
| 471 | Status : Stable | ||
| 472 | Example : | ||
| 473 | my $meta_count = | ||
| 474 | $helper->execute_single_result( | ||
| 475 | -SQL => 'select count(*) from meta where species_id =?', | ||
| 476 | -PARAMS => [1] ); | ||
| 477 | |||
| 478 | Description : Very similar to execute() except it will raise an exception if we have more | ||
| 479 | or less than one row returned | ||
| 480 | =cut | ||
| 481 | |||
| 482 | sub execute_single_result { | ||
| 483 | my ( $self, @args ) = @_; | ||
| 484 | my ($sql, $callback, $use_hashrefs, $params, $no_error) = rearrange( | ||
| 485 | [qw(sql callback use_hashrefs params no_error)], @args); | ||
| 486 | |||
| 487 | my $results = $self->execute_simple( | ||
| 488 | -SQL => $sql, | ||
| 489 | -CALLBACK => $callback, | ||
| 490 | -USE_HASHREFS => $use_hashrefs, | ||
| 491 | -PARAMS => $params | ||
| 492 | ); | ||
| 493 | |||
| 494 | my $result_count = scalar(@{$results}); | ||
| 495 | if(! $no_error && $result_count != 1) { | ||
| 496 | $params = [] if ! $params; | ||
| 497 | my $type = ($result_count == 0) ? 'No' : 'Too many'; | ||
| 498 | my $msg = "${type} results returned. Expected 1 but got $result_count for query '${sql}' with params ["; | ||
| 499 | $msg .= join( ',', map {(defined $_) ? $_ : '-undef-';} @{$params} ); | ||
| 500 | $msg .= ']'; | ||
| 501 | throw($msg); | ||
| 502 | } | ||
| 503 | return $results->[0] if defined $results->[0]; | ||
| 504 | return; | ||
| 505 | } | ||
| 506 | |||
| 507 | =pod | ||
| 508 | |||
| 509 | =head2 transaction() | ||
| 510 | |||
| 511 | Arg [CALLBACK] : CodeRef The callback used for transaction isolation; once | ||
| 512 | the subroutine exists the code will decide on rollback | ||
| 513 | or commit. Required | ||
| 514 | Arg [RETRY] : integer the number of retries to attempt with this | ||
| 515 | transactional block. Defaults to 0. | ||
| 516 | Arg [PAUSE] : integer the time in seconds to pause in-between retries. | ||
| 517 | Defaults to 1. Fractions are allowed as use delegate to | ||
| 518 | Time::HiRes' sleep function | ||
| 519 | Arg [CONDITION] : CodeRef allows you to inspect the exception raised | ||
| 520 | and should your callback return true then the | ||
| 521 | retry will be attempted. If not given then all | ||
| 522 | exceptions mean attempt a retry (if specified) | ||
| 523 | Returntype : Return of the callback | ||
| 524 | Exceptions : If errors occur in the execution of the SQL | ||
| 525 | Status : Stable | ||
| 526 | Example : | ||
| 527 | my $val = $helper->transaction( | ||
| 528 | -CALLBACK => sub { | ||
| 529 | my ($dbc) = @_; | ||
| 530 | #Do something | ||
| 531 | return 1; | ||
| 532 | } ); | ||
| 533 | |||
| 534 | # Or without named arguments | ||
| 535 | my $val = $helper->transaction( | ||
| 536 | sub { | ||
| 537 | my ($dbc) = @_; | ||
| 538 | #Do something | ||
| 539 | return 1; | ||
| 540 | } ); | ||
| 541 | |||
| 542 | # To allow retries (use sparingly, and see description) | ||
| 543 | my $val = $helper->transaction( | ||
| 544 | -RETRY => 3, | ||
| 545 | -PAUSE => 2, | ||
| 546 | -CALLBACK => sub { | ||
| 547 | my ($dbc) = @_; | ||
| 548 | #Do something | ||
| 549 | return 1; | ||
| 550 | } ); | ||
| 551 | |||
| 552 | # Only retry when we have an error containing the phrase "deadlock" | ||
| 553 | my $val = $helper->transaction( | ||
| 554 | -RETRY => 3, -PAUSE => 2, | ||
| 555 | -CALLBACK => sub { | ||
| 556 | my ($dbc) = @_; | ||
| 557 | #Do something | ||
| 558 | return 1; | ||
| 559 | }, | ||
| 560 | -CONDITION => sub { | ||
| 561 | my ($error) = @_; | ||
| 562 | return ( $error =~ /deadlock/ ) ? 1 : 0; | ||
| 563 | } | ||
| 564 | ); | ||
| 565 | |||
| 566 | Description : | ||
| 567 | Creates a transactional block which will ensure that the connection is | ||
| 568 | committed when your submmited subroutine has finished or will rollback | ||
| 569 | in the event of an error occuring in your block. | ||
| 570 | |||
| 571 | The code will always force AutoCommit off but will restore it to its | ||
| 572 | previous setting. If your DBI/DBD driver does not support manual | ||
| 573 | commits then this code will break. The code will turn off the | ||
| 574 | disconnect_when_idle() method to allow transactions to work as | ||
| 575 | expected. | ||
| 576 | |||
| 577 | An effect of using REPEATABLE READ transaction isolation (InnoDB's | ||
| 578 | default) is that your data is as fresh as when you started your current | ||
| 579 | transaction. To ensure the freshest data use SELECT ... FROM ... LOCK | ||
| 580 | IN SHARE MODE> or SELECT ... FROM ... LOCK FOR UPDATE if you are | ||
| 581 | going to issue updates. | ||
| 582 | |||
| 583 | Creating a transaction within a transaction results in the commit | ||
| 584 | rollback statements occuring in the top level transaction. That way any | ||
| 585 | block of code which is meant to to be transaction can be wrapped in | ||
| 586 | this block ( assuming the same instance of SQLHelper is passed around and | ||
| 587 | used). | ||
| 588 | |||
| 589 | You can also request the -RETRY of a transactional block of code which is | ||
| 590 | causing problems. This can indicate your programming model is broken, | ||
| 591 | so use with care. | ||
| 592 | |||
| 593 | The -RETRY argument indicates the number of times we attempt the transaction | ||
| 594 | and -PAUSE indicates the time in-between attempts. These retries will | ||
| 595 | only occur in the root transaction block i.e. you cannot influence the | ||
| 596 | retry system in a sub-transaction. You can influence if the retry is done with | ||
| 597 | the -CONDITION argument which accepts a Code reference (same as the | ||
| 598 | -CALLBACK parameter). This allows you to inspect the error thrown to | ||
| 599 | retry only in some situations e.g. | ||
| 600 | |||
| 601 | =cut | ||
| 602 | |||
| 603 | sub transaction { | ||
| 604 | my ($self, @args) = @_; | ||
| 605 | |||
| 606 | my ($callback, $retry, $pause, $condition) = rearrange([qw(callback retry pause condition)], @args); | ||
| 607 | |||
| 608 | throw('-CALLBACK was not a CodeRef. Got a reference of type ['.ref($callback).']. Check your parameters') | ||
| 609 | unless check_ref($callback, 'CODE'); | ||
| 610 | |||
| 611 | #Setup defaults | ||
| 612 | $retry = 0 unless defined $retry; | ||
| 613 | $pause = 1 unless defined $pause; | ||
| 614 | if(! defined $condition) { | ||
| 615 | $condition = sub { | ||
| 616 | return 1; | ||
| 617 | }; | ||
| 618 | } | ||
| 619 | |||
| 620 | assert_ref($condition, 'CODE', '-CONDITION'); | ||
| 621 | |||
| 622 | my $dbc = $self->db_connection(); | ||
| 623 | my $original_dwi; | ||
| 624 | my $ac; | ||
| 625 | |||
| 626 | my $error; | ||
| 627 | my $result; | ||
| 628 | |||
| 629 | #If we were already in a transaction then we do not do any management of the | ||
| 630 | #session & wait for the parent transaction(s) to finish | ||
| 631 | my $perform_transaction = $self->_perform_transaction_code(); | ||
| 632 | if($perform_transaction) { | ||
| 633 | ($original_dwi, $ac) = $self->_enable_transaction(); | ||
| 634 | } | ||
| 635 | else { | ||
| 636 | #If we were in a transaction then ignore any attempts at retry here | ||
| 637 | $retry = 0; | ||
| 638 | } | ||
| 639 | |||
| 640 | for(my $iteration = 0; $iteration <= $retry; $iteration++) { | ||
| 641 | eval { | ||
| 642 | $result = $callback->($dbc); | ||
| 643 | $dbc->db_handle()->commit() if $perform_transaction; | ||
| 644 | }; | ||
| 645 | $error = $@; | ||
| 646 | #If we were allowed to deal with the error then we apply rollbacks & then | ||
| 647 | #retry or leave to the remainder of the code to throw | ||
| 648 | if($perform_transaction && $error) { | ||
| 649 | eval { $dbc->db_handle()->rollback(); }; | ||
| 650 | #If we were not on our last iteration then warn & allow the retry | ||
| 651 | if($iteration != $retry) { | ||
| 652 | if($condition->($error)) { | ||
| 653 | warn("Encountered error on attempt ${iteration} of ${retry} and have issued a rollback. Will retry after sleeping for $pause second(s): $error"); | ||
| 654 | Time::HiRes::sleep $pause; | ||
| 655 | } | ||
| 656 | else { | ||
| 657 | last; #break early if condition of error was not matched | ||
| 658 | } | ||
| 659 | } | ||
| 660 | } | ||
| 661 | |||
| 662 | #Always break the loop if we had a successful attempt | ||
| 663 | last if ! $error; | ||
| 664 | } | ||
| 665 | |||
| 666 | if($perform_transaction) { | ||
| 667 | $self->_disable_transaction($original_dwi, $ac); | ||
| 668 | } | ||
| 669 | |||
| 670 | throw("ABORT: Transaction aborted because of error: ${error}") if $error; | ||
| 671 | |||
| 672 | return $result; | ||
| 673 | } | ||
| 674 | |||
| 675 | =pod | ||
| 676 | |||
| 677 | =head2 execute_update() | ||
| 678 | |||
| 679 | Arg [SQL] : string $sql | ||
| 680 | Arg [CALLBACK] : CodeRef The callback to use for calling methods on the | ||
| 681 | DBI statement handle or DBConnection object after an | ||
| 682 | update command | ||
| 683 | Arg [PARAMS] : ArrayRef The binding parameters to the SQL statement | ||
| 684 | Arg [PREPARE_PARAMS] : ArrayRef Parameters to bind to the prepare() StatementHandle call | ||
| 685 | Returntype : integer - Number of rows affected | ||
| 686 | Exceptions : If errors occur in the execution of the SQL | ||
| 687 | Status : Stable | ||
| 688 | Description: Used for performing updates but conforms to the normal execute statement subroutines. | ||
| 689 | Example : | ||
| 690 | use DBI qw(:sql_types); | ||
| 691 | $helper->execute_update(-SQL => 'update tab set name = ? where id =?', | ||
| 692 | -PARAMS => [ 'andy', [ 1, SQL_INTEGER ] ] ); | ||
| 693 | |||
| 694 | #If you need to do something a bit more advanced with your database then you can | ||
| 695 | #give the method a closure and this will be called after the execute has been | ||
| 696 | #issued i.e. | ||
| 697 | |||
| 698 | my $obj; | ||
| 699 | $helper->execute_update( | ||
| 700 | -SQL => 'insert into tab (name) values(?)', | ||
| 701 | -CALLBACK => sub { | ||
| 702 | my ( $sth, $dbh, $rv ) = @_; | ||
| 703 | $obj->{id} = $dbh->{mysql_insertid}; | ||
| 704 | }, | ||
| 705 | -PARAMS => [ $obj->name() ] ); | ||
| 706 | |||
| 707 | #This lets us access the statement handle, the database handle and | ||
| 708 | #the return value from $sth->execute, to access other properties such as | ||
| 709 | #the last identifier inserted. | ||
| 710 | |||
| 711 | =cut | ||
| 712 | |||
| 713 | sub execute_update { | ||
| 714 | my ($self, @args) = @_; | ||
| 715 | my ($sql, $callback, $params, $prepare_params) = rearrange([qw(sql callback params prepare_params)], @args); | ||
| 716 | my $rv = 0; | ||
| 717 | my $sth; | ||
| 718 | eval { | ||
| 719 | my @prepare_params; | ||
| 720 | @prepare_params = @{$prepare_params} if check_ref($prepare_params, 'ARRAY'); | ||
| 721 | $sth = $self->db_connection()->prepare($sql, @prepare_params); | ||
| 722 | $self->_bind_params($sth, $params); | ||
| 723 | $rv = $sth->execute(); | ||
| 724 | $callback->($sth, $self->db_connection()->db_handle(), $rv) if $callback; | ||
| 725 | }; | ||
| 726 | my $error = $@; | ||
| 727 | $self->_finish_sth($sth); | ||
| 728 | if($error) { | ||
| 729 | my $params = join ' ', map { (defined $_) ? $_ : q{undef} } @{$params}; | ||
| 730 | throw("Cannot apply sql '${sql}' with params '${params}': ${error}"); | ||
| 731 | } | ||
| 732 | return $rv; | ||
| 733 | } | ||
| 734 | |||
| 735 | =head2 execute_with_sth() | ||
| 736 | |||
| 737 | Arg [SQL] : string $sql | ||
| 738 | Arg [CALLBACK] : CodeRef The callback to use for working with the statement | ||
| 739 | handle once returned. This is not a mapper. | ||
| 740 | Arg [PARAMS] : ArrayRef The binding parameters to the SQL statement | ||
| 741 | Arg [PREPARE_PARAMS] : ArrayRef Used to pass parameters to the statement handle | ||
| 742 | prepare method | ||
| 743 | Description : Run query without worrying statement handles and such. | ||
| 744 | Very similar to execute() except this gives you full control over the | ||
| 745 | lifecycle of the statement handle and how you wish to proceed with working | ||
| 746 | with a statement handle. This is for situations where you believe going through | ||
| 747 | the mappers causes too much of a slow-down (since we have to execute a | ||
| 748 | subroutine for every row in order to map it correctly). | ||
| 749 | |||
| 750 | However please benchmark before adopting this method as it increases the | ||
| 751 | complexity of your code and the mapper slowness only becomes apparent when | ||
| 752 | working with very large numbers of rows. | ||
| 753 | Returntype : Anything you wish to return from the callback | ||
| 754 | Exceptions : If errors occur in the execution of the SQL | ||
| 755 | Status : Stable | ||
| 756 | Example : | ||
| 757 | my $meta_count = $helper->execute_with_sth( | ||
| 758 | -SQL => 'select count(*) from meta where species_id =?', | ||
| 759 | -PARAMS => [1], | ||
| 760 | -CALLBACK => sub { | ||
| 761 | my ($sth) = @_; | ||
| 762 | my $count; | ||
| 763 | $sth->bind_columns( \$count ); | ||
| 764 | while ( $sth->fetch ) { | ||
| 765 | print $count, "\n"; | ||
| 766 | } | ||
| 767 | return $count; | ||
| 768 | } ); | ||
| 769 | |||
| 770 | |||
| 771 | |||
| 772 | =cut | ||
| 773 | |||
| 774 | sub execute_with_sth { | ||
| 775 | my ($self, @args) = @_; | ||
| 776 | my ($sql, $callback, $params, $prepare_params) = rearrange([qw(sql callback params prepare_params)], @args); | ||
| 777 | my $sth = $self->_base_execute( $sql, $params, $prepare_params, $callback ); | ||
| 778 | my $result = eval {$callback->($sth)}; | ||
| 779 | my $error = $@; | ||
| 780 | $self->_finish_sth($sth); | ||
| 781 | die $error if $error; | ||
| 782 | return $result; | ||
| 783 | } | ||
| 784 | |||
| 785 | =pod | ||
| 786 | |||
| 787 | =head2 batch() | ||
| 788 | |||
| 789 | Arg [SQL] : string $sql | ||
| 790 | Arg [CALLBACK] : CodeRef The callback to use for working with the statement | ||
| 791 | handle once returned; specify this or -DATA | ||
| 792 | Arg [DATA] : ArrayRef The data to insert; specify this or -CALLBACK | ||
| 793 | Arg [COMMIT_EVERY] : Integer defines the rate at which to issue commits to | ||
| 794 | the DB handle. This is important when working with | ||
| 795 | InnoDB databases since it affects the speed of rollback | ||
| 796 | (larger gaps inbetween commits means more to rollback). | ||
| 797 | |||
| 798 | Ignored if using the callback version. | ||
| 799 | Arg [PREPARE_PARAMS] : ArrayRef Used to pass parameters to the statement handle | ||
| 800 | prepare method | ||
| 801 | Returntype : integer rows updated | ||
| 802 | Exceptions : If errors occur in the execution of the SQL | ||
| 803 | Status : Stable | ||
| 804 | Example : | ||
| 805 | my $alotofdata = getitfromsomewhere(); | ||
| 806 | $helper->batch( | ||
| 807 | -SQL => 'insert into table (one,two) values(?,?)', | ||
| 808 | -CALLBACk => sub { | ||
| 809 | my ( $sth, $dbc ) = @_; | ||
| 810 | foreach my $data (@alotofdata) { | ||
| 811 | $sth->execute( @{$data} ); | ||
| 812 | } | ||
| 813 | } ); | ||
| 814 | |||
| 815 | #Or for a 2D array data driven approach | ||
| 816 | $helper->batch( -SQL => 'insert into table (one,two) values(?,?)', | ||
| 817 | -DATA => $alotofdata ); | ||
| 818 | |||
| 819 | |||
| 820 | Description: Takes in a sql statement and a code reference. Your SQL is converted into a | ||
| 821 | prepared statement and then given as the first parameter to the closure. The | ||
| 822 | second parameter is the DBH which created the statement. This is intended | ||
| 823 | to let you do mass insertion into a database without the need to | ||
| 824 | re-preparing the same statement. | ||
| 825 | |||
| 826 | This can be combined with the transaction() code to provide a construct | ||
| 827 | which does batch insertion and is transactionally aware. | ||
| 828 | |||
| 829 | We can also use data based batch insertions i.e. | ||
| 830 | |||
| 831 | #Needs to be like: | ||
| 832 | # [ [1,2], [3,4] ] | ||
| 833 | #Or if using the DBI types: | ||
| 834 | # [ [ [ 1, SQL_INTEGER ], [ 2, SQL_INTEGER ] ], | ||
| 835 | # [ [ 3, SQL_INTEGER ], [ 4, SQL_INTEGER ] ] ]; | ||
| 836 | |||
| 837 | my $alotofdata = getitfromsomewhere(); | ||
| 838 | $helper->batch( -SQL => 'insert into table (one,two) values(?,?)', | ||
| 839 | -DATA => $alotofdata ); | ||
| 840 | |||
| 841 | This does exactly the same as the previous example. | ||
| 842 | |||
| 843 | All batch statements will return the value the callback computes. If you are | ||
| 844 | using the previous example with a data array then the code will return the | ||
| 845 | number affected rows by the query. | ||
| 846 | |||
| 847 | =cut | ||
| 848 | |||
| 849 | sub batch { | ||
| 850 | my ($self, @args) = @_; | ||
| 851 | my ($sql, $callback, $data, $commit_every, $prepare_params) = | ||
| 852 | rearrange([qw(sql callback data commit_every prepare_params)], @args); | ||
| 853 | |||
| 854 | if(! defined $callback && ! defined $data) { | ||
| 855 | throw('You need to define a callback for insertion work or the 2D data array'); | ||
| 856 | } | ||
| 857 | |||
| 858 | my $result; | ||
| 859 | if(defined $callback) { | ||
| 860 | $result = $self->_callback_batch($sql, $callback, $prepare_params); | ||
| 861 | } | ||
| 862 | else { | ||
| 863 | $result = $self->_data_batch($sql, $data, $commit_every, $prepare_params); | ||
| 864 | } | ||
| 865 | return $result if defined $result; | ||
| 866 | return; | ||
| 867 | } | ||
| 868 | |||
| 869 | #------- Internal methods | ||
| 870 | |||
| 871 | my $default_mappers = { | ||
| 872 | first_element => sub { | ||
| 873 | my ($row) = @_; | ||
| 874 | return $row->[0]; | ||
| 875 | }, | ||
| 876 | second_element => sub { | ||
| 877 | my ($row) = @_; | ||
| 878 | return $row->[1]; | ||
| 879 | }, | ||
| 880 | array_ref => sub { | ||
| 881 | my $row = shift @_; | ||
| 882 | return [@{$row}]; #copy of array done because DBI's array is read only | ||
| 883 | }, | ||
| 884 | hash_ref => sub { | ||
| 885 | my $row = shift @_; | ||
| 886 | return {%{$row}}; #applying same logic as above | ||
| 887 | } | ||
| 888 | }; | ||
| 889 | |||
| 890 | sub _mappers { | ||
| 891 | my ($self) = @_; | ||
| 892 | return $default_mappers; | ||
| 893 | } | ||
| 894 | |||
| 895 | sub _perform_transaction_code { | ||
| 896 | my ($self) = @_; | ||
| 897 | return $self->{_transaction_active}->{$PROCESS_ID} ? 0 : 1; | ||
| 898 | } | ||
| 899 | |||
| 900 | sub _enable_transaction { | ||
| 901 | my ($self) = @_; | ||
| 902 | my $dbc = $self->db_connection(); | ||
| 903 | my $original_dwi = $dbc->disconnect_when_inactive(); | ||
| 904 | $dbc->disconnect_when_inactive(0); | ||
| 905 | my $ac = $dbc->db_handle()->{'AutoCommit'}; | ||
| 906 | $dbc->db_handle()->{'AutoCommit'} = 0; | ||
| 907 | $self->{_transaction_active}->{$PROCESS_ID} = 1; | ||
| 908 | return ($original_dwi, $ac); | ||
| 909 | } | ||
| 910 | |||
| 911 | sub _disable_transaction { | ||
| 912 | my ($self, $original_dwi, $ac) = @_; | ||
| 913 | my $dbc = $self->db_connection(); | ||
| 914 | $dbc->db_handle()->{'AutoCommit'} = $ac; | ||
| 915 | $dbc->disconnect_when_inactive($original_dwi); | ||
| 916 | delete $self->{_transaction_active}->{$PROCESS_ID}; | ||
| 917 | return; | ||
| 918 | } | ||
| 919 | |||
| 920 | sub _bind_params { | ||
| 921 | my ( $self, $sth, $params ) = @_; | ||
| 922 | |||
| 923 | return if ! defined $params; #Return quickly if we had no data | ||
| 924 | |||
| 925 | if(! check_ref($params, 'ARRAY')) { | ||
| 926 | throw(qq{The given parameters reference '${params}' is not an ARRAY; wrap in an ArrayRef}); | ||
| 927 | } | ||
| 928 | |||
| 929 | my $count = 1; | ||
| 930 | foreach my $param (@{$params}) { | ||
| 931 | if ( check_ref($param, 'ARRAY') ) { | ||
| 932 | $sth->bind_param( $count, @{$param} ); | ||
| 933 | } | ||
| 934 | else { | ||
| 935 | $sth->bind_param( $count, $param ); | ||
| 936 | } | ||
| 937 | $count++; | ||
| 938 | } | ||
| 939 | return; | ||
| 940 | } | ||
| 941 | |||
| 942 | sub _execute { | ||
| 943 | my ( $self, $sql, $callback, $has_return, $use_hashrefs, $params, $prepare_params, $iterator ) = @_; | ||
| 944 | |||
| 945 | throw('Not given a mapper. _execute() must always been given a CodeRef') unless check_ref($callback, 'CODE'); | ||
| 946 | |||
| 947 | my $sth = $self->_base_execute($sql, $params, $prepare_params); | ||
| 948 | |||
| 949 | my $sth_processor; | ||
| 950 | if($use_hashrefs) { | ||
| 951 | $sth_processor = sub { | ||
| 952 | return unless $sth->{Active}; | ||
| 953 | while( my $row = $sth->fetchrow_hashref() ) { | ||
| 954 | my $v = $callback->($row, $sth); | ||
| 955 | return $v if $has_return; | ||
| 956 | } | ||
| 957 | $self->_finish_sth($sth); | ||
| 958 | return; | ||
| 959 | }; | ||
| 960 | } | ||
| 961 | else { | ||
| 962 | $sth_processor = sub { | ||
| 963 | return unless $sth->{Active}; | ||
| 964 | while( my $row = $sth->fetchrow_arrayref() ) { | ||
| 965 | my $v = $callback->($row, $sth); | ||
| 966 | return $v if $has_return; | ||
| 967 | } | ||
| 968 | $self->_finish_sth($sth); | ||
| 969 | return; | ||
| 970 | }; | ||
| 971 | } | ||
| 972 | |||
| 973 | my $iter = Bio::EnsEMBL::Utils::Iterator->new($sth_processor); | ||
| 974 | if($has_return) { | ||
| 975 | return $iter if $iterator; | ||
| 976 | return $iter->to_arrayref(); | ||
| 977 | } | ||
| 978 | else { | ||
| 979 | #Force iteration if we had no return since the caller is expecting this | ||
| 980 | $iter->each(sub {}); | ||
| 981 | } | ||
| 982 | return; | ||
| 983 | } | ||
| 984 | |||
| 985 | sub _base_execute { | ||
| 986 | my ( $self, $sql, $params, $prepare_params) = @_; | ||
| 987 | |||
| 988 | $params = [] unless $params; | ||
| 989 | |||
| 990 | my $conn = $self->db_connection; | ||
| 991 | |||
| 992 | my $sth; | ||
| 993 | eval { | ||
| 994 | my @prepare_params; | ||
| 995 | @prepare_params = @{$prepare_params} if check_ref($prepare_params, 'ARRAY'); | ||
| 996 | $sth = $conn->prepare($sql, @prepare_params); | ||
| 997 | throw("Cannot continue as prepare() did not return a handle with prepare params '@prepare_params'") | ||
| 998 | unless $sth; | ||
| 999 | $self->_bind_params( $sth, $params ); | ||
| 1000 | $sth->execute(); | ||
| 1001 | }; | ||
| 1002 | |||
| 1003 | my $error = $@; | ||
| 1004 | if($error) { | ||
| 1005 | throw("Cannot run '${sql}' with params '@{$params}' due to error: $error") if $error; | ||
| 1006 | } | ||
| 1007 | |||
| 1008 | return $sth; | ||
| 1009 | } | ||
| 1010 | |||
| 1011 | sub _finish_sth { | ||
| 1012 | my ($self, $sth) = @_; | ||
| 1013 | eval { $sth->finish() if defined $sth; }; | ||
| 1014 | warn('Cannot finish() the statement handle: $@') if $@; | ||
| 1015 | return; | ||
| 1016 | } | ||
| 1017 | |||
| 1018 | sub _callback_batch { | ||
| 1019 | my ($self, $sql, $callback, $prepare_params) = @_; | ||
| 1020 | my $error; | ||
| 1021 | my $sth; | ||
| 1022 | my $closure_return; | ||
| 1023 | eval { | ||
| 1024 | my @prepare_params; | ||
| 1025 | @prepare_params = @{$prepare_params} if check_ref($prepare_params, 'ARRAY'); | ||
| 1026 | $sth = $self->db_connection()->prepare($sql, @prepare_params); | ||
| 1027 | $closure_return = $callback->($sth, $self->db_connection()); | ||
| 1028 | }; | ||
| 1029 | $error = $@; | ||
| 1030 | $self->_finish_sth($sth); | ||
| 1031 | throw("Problem detected during batch work: $error") if $error; | ||
| 1032 | |||
| 1033 | return $closure_return if defined $closure_return; | ||
| 1034 | return; | ||
| 1035 | } | ||
| 1036 | |||
| 1037 | sub _data_batch { | ||
| 1038 | my ($self, $sql, $data, $commit_every, $prepare_params) = @_; | ||
| 1039 | |||
| 1040 | #Input checks | ||
| 1041 | assert_ref($data, 'ARRAY', '-DATA'); | ||
| 1042 | my $data_length = scalar(@{$data}); | ||
| 1043 | return 0 unless $data_length > 0; | ||
| 1044 | my $first_row = $data->[0]; | ||
| 1045 | throw('I expect to work with a 2D ArrayRef but this is not one') unless check_ref($first_row, 'ARRAY'); | ||
| 1046 | |||
| 1047 | my $callback = sub { | ||
| 1048 | my ($sth, $dbc) = @_; | ||
| 1049 | my $total_affected = 0; | ||
| 1050 | #Iterate over each data point | ||
| 1051 | for(my $data_index = 0; $data_index < $data_length; $data_index++) { | ||
| 1052 | my $row = $data->[$data_index]; | ||
| 1053 | $self->_bind_params($sth, $row); | ||
| 1054 | my $affected = eval {$sth->execute()}; | ||
| 1055 | if($@) { | ||
| 1056 | throw("Problem working with $sql with params @{$row}: $@"); | ||
| 1057 | } | ||
| 1058 | my $num_affected = ($affected) ? $affected : 0; #Get around DBI's 0E0 | ||
| 1059 | $total_affected += $num_affected; | ||
| 1060 | |||
| 1061 | #Lets us do a commit once every x rows apart from 0. We also finish | ||
| 1062 | #off with a commit if the code told us we were doing it | ||
| 1063 | if($commit_every) { | ||
| 1064 | if( ($data_index % $commit_every == 0) && $data_index != 0) { | ||
| 1065 | $dbc->db_handle()->commit(); | ||
| 1066 | } | ||
| 1067 | } | ||
| 1068 | } | ||
| 1069 | |||
| 1070 | #finish off with a commit if the code told us we were doing it | ||
| 1071 | if($commit_every) { | ||
| 1072 | $dbc->db_handle()->commit(); | ||
| 1073 | } | ||
| 1074 | |||
| 1075 | return $total_affected || 0; | ||
| 1076 | }; | ||
| 1077 | |||
| 1078 | return $self->_callback_batch($sql, $callback, $prepare_params) | ||
| 1079 | } | ||
| 1080 | |||
| 1081 | 1; |