| 1 | package SPOPS::SQLInterface; | ||
| 2 | |||
| 3 | # $Id: SQLInterface.pm,v 3.12 2004/06/02 00:48:21 lachoy Exp $ | ||
| 4 | |||
| 5 | use strict; | ||
| 6 | use Data::Dumper qw( Dumper ); | ||
| 7 | use DBI; | ||
| 8 | use Log::Log4perl qw( get_logger ); | ||
| 9 | use SPOPS::DBI::TypeInfo; | ||
| 10 | use SPOPS::Exception qw( spops_error ); | ||
| 11 | use SPOPS::Exception::DBI qw( spops_dbi_error ); | ||
| 12 | |||
| 13 | my $log = get_logger(); | ||
| 14 | |||
| 15 | $SPOPS::SQLInterface::VERSION = sprintf("%d.%02d", q$Revision: 3.12 $ =~ /(\d+)\.(\d+)/); | ||
| 16 | |||
| 17 | my %TYPE_INFO = (); | ||
| 18 | |||
| 19 | sub throw_no_database_handle_error { | ||
| 20 | my ( $item ) = @_; | ||
| 21 | my $class = ref $item || $item; | ||
| 22 | spops_error "No database handle available; pass using the 'db' ", | ||
| 23 | "parameter or define ${class}->global_datasource_handle ", | ||
| 24 | "to return a valid DBI handle."; | ||
| 25 | } | ||
| 26 | |||
| 27 | # Drivers that don't support the two-argument form of DBI->quote | ||
| 28 | # should override... | ||
| 29 | |||
| 30 | sub sql_quote { | ||
| 31 | my ( $class, $value, $type, $db ) = @_; | ||
| 32 | return 'NULL' unless ( defined $value ); | ||
| 33 | $db ||= $class->global_datasource_handle; | ||
| 34 | unless ( ref $db ) { | ||
| 35 | spops_error "No database handle could be found!"; | ||
| 36 | } | ||
| 37 | |||
| 38 | # This issues a warning when '$type' is unknown; need to figure | ||
| 39 | # out how to set '$type' to a known value | ||
| 40 | |||
| 41 | return $db->quote( $value, $type ); | ||
| 42 | } | ||
| 43 | |||
| 44 | # Note: not sure how to integrate the fieldtype discovery | ||
| 45 | # stuff in here. What if you do: | ||
| 46 | # | ||
| 47 | # select u.username from users u, logins l | ||
| 48 | # where l.login_date > ? and | ||
| 49 | # l.user_id = u.user_id | ||
| 50 | # | ||
| 51 | # and pass '2000/1/13' is passed in? This seems to be a little | ||
| 52 | # too much in-depth sql processing than this library is | ||
| 53 | # appropriate for; so you can still pass in values for binding, | ||
| 54 | # but they'll all be bound with SQL_VARCHAR | ||
| 55 | # | ||
| 56 | # select => \@ of fields to select | ||
| 57 | # select_modifier => $ to insert between 'SELECT' and fields (e.g., DISTINCT) | ||
| 58 | # from => \@ of tables to select from ($ allowed if only one) | ||
| 59 | # order => $ clause to order by | ||
| 60 | # group => $ clause to group by | ||
| 61 | # where => $ clause to limit results | ||
| 62 | # return => sth | single | list | hash | single-list | ||
| 63 | # value => \@ of values to bind, all as SQL_VARCHAR; they must match order of '?' in where | ||
| 64 | # sql => $ statement to execute | ||
| 65 | |||
| 66 | sub db_select { | ||
| 67 | my ( $class, $p ) = @_; | ||
| 68 | my $db = $p->{db} || $class->global_datasource_handle; | ||
| 69 | $class->throw_no_database_handle_error unless ( $db ); | ||
| 70 | |||
| 71 | # Don't do anything if the SQL isn't passed in and you don't have | ||
| 72 | # either a list of fields to select or a table to select them from | ||
| 73 | |||
| 74 | unless ( $p->{sql} or ( $p->{select} and $p->{from} ) ) { | ||
| 75 | spops_error 'Cannot run without select/from statements!'; | ||
| 76 | } | ||
| 77 | |||
| 78 | $log->is_debug && | ||
| 79 | $log->debug( "Entering db_select with ", Dumper( $p ) ); | ||
| 80 | $p->{return} ||= 'list'; | ||
| 81 | $p->{value} ||= []; | ||
| 82 | my $sql = $p->{sql}; | ||
| 83 | |||
| 84 | # If we don't have any SQL, build it (straightforward). | ||
| 85 | |||
| 86 | unless ( $sql ) { | ||
| 87 | $log->is_info && | ||
| 88 | $log->info( "No SQL passed in to execute directly; building." ); | ||
| 89 | |||
| 90 | $p->{from} ||= $p->{table}; # allow an alias | ||
| 91 | if ( $p->{from} and ref $p->{from} ne 'ARRAY' ) { | ||
| 92 | $p->{from} = [ $p->{from} ]; | ||
| 93 | } | ||
| 94 | |||
| 95 | $p->{select_modifier} ||= ''; | ||
| 96 | my $select = join ', ', @{ $p->{select} }; | ||
| 97 | my $from = join ', ', @{ $p->{from} }; | ||
| 98 | my $order = ( $p->{order} ) ? "ORDER BY $p->{order}" : ''; | ||
| 99 | my $where = ( $p->{where} ) ? "WHERE $p->{where}" : ''; | ||
| 100 | my $group = ( $p->{group} ) ? "GROUP BY $p->{group}" : ''; | ||
| 101 | $sql = qq/ | ||
| 102 | SELECT $p->{select_modifier} $select | ||
| 103 | FROM $from | ||
| 104 | $where | ||
| 105 | $group | ||
| 106 | $order | ||
| 107 | /; | ||
| 108 | } | ||
| 109 | $log->is_info && | ||
| 110 | $log->info( "SQL for select: $sql" ); | ||
| 111 | |||
| 112 | # First prepare and check for errors... | ||
| 113 | |||
| 114 | my $sth = eval { $db->prepare( $sql ) }; | ||
| 115 | if ( $@ ) { | ||
| 116 | spops_dbi_error $@, { sql => $sql, action => 'prepare' }; | ||
| 117 | } | ||
| 118 | |||
| 119 | # Execute with any bound parameters; note that for Sybase you do | ||
| 120 | # not need to pass any types at all. | ||
| 121 | |||
| 122 | $log->is_info && | ||
| 123 | $log->info( "Values bound: ", join( '//', @{ $p->{value} } ) ); | ||
| 124 | eval { $sth->execute( @{ $p->{value} } ) }; | ||
| 125 | if ( $@ ) { | ||
| 126 | spops_dbi_error $@, { sql => $sql, | ||
| 127 | bound_value => $p->{value}, | ||
| 128 | action => 'execute' }; | ||
| 129 | } | ||
| 130 | |||
| 131 | # If they asked for the handle back, give it to them | ||
| 132 | |||
| 133 | if ( $p->{return} eq 'sth' ) { | ||
| 134 | $log->is_info && | ||
| 135 | $log->info( "Returning statement handle (after prepare/execute)" ); | ||
| 136 | return $sth; | ||
| 137 | } | ||
| 138 | |||
| 139 | # If they asked for a single row, return it in arrayref format [ | ||
| 140 | # field1, field2, ...] | ||
| 141 | |||
| 142 | if ( $p->{return} eq 'single' ) { | ||
| 143 | $log->is_info && | ||
| 144 | $log->info( "Returning single row." ); | ||
| 145 | my $row = eval { $sth->fetchrow_arrayref; }; | ||
| 146 | if ( $@ ) { | ||
| 147 | spops_dbi_error $@, { sql => $sql, | ||
| 148 | bound_value => $p->{value}, | ||
| 149 | action => 'fetchrow_arrayref' }; | ||
| 150 | } | ||
| 151 | return $row; | ||
| 152 | } | ||
| 153 | |||
| 154 | # If they asked for a list of results, return an arrayref of arrayrefs | ||
| 155 | |||
| 156 | elsif ( $p->{return} eq 'list' ) { | ||
| 157 | $log->is_info && | ||
| 158 | $log->info( "Returning list of lists." ); | ||
| 159 | my $rows = eval { $sth->fetchall_arrayref; }; | ||
| 160 | if ( $@ ) { | ||
| 161 | spops_dbi_error $@, { sql => $sql, | ||
| 162 | bound_value => $p->{value}, | ||
| 163 | action => 'fetchall_arrayref' }; | ||
| 164 | } | ||
| 165 | return $rows; | ||
| 166 | } | ||
| 167 | |||
| 168 | # return the first element of each record in an arrayref | ||
| 169 | |||
| 170 | elsif ( $p->{return} eq 'single-list' ) { | ||
| 171 | $log->is_info && | ||
| 172 | $log->info( "Returning list of single items." ); | ||
| 173 | my $rows = eval { $sth->fetchall_arrayref }; | ||
| 174 | if ( $@ ) { | ||
| 175 | spops_dbi_error $@, { sql => $sql, | ||
| 176 | bound_value => $p->{value}, | ||
| 177 | action => 'fetchall_arrayref' }; | ||
| 178 | } | ||
| 179 | return [ map { $_->[0] } @{ $rows } ]; | ||
| 180 | } | ||
| 181 | |||
| 182 | # If they asked for a hash, return a list of hashrefs | ||
| 183 | |||
| 184 | elsif ( $p->{return} eq 'hash' ) { | ||
| 185 | $log->is_info && | ||
| 186 | $log->info( "Returning list of hashrefs." ); | ||
| 187 | my @rows = (); | ||
| 188 | |||
| 189 | # Note -- we may need to change this to zip through $row every | ||
| 190 | # time and push a new reference onto @rows | ||
| 191 | |||
| 192 | eval { | ||
| 193 | while ( my $row = $sth->fetchrow_hashref ) { | ||
| 194 | push @rows, \%{ $row }; | ||
| 195 | } | ||
| 196 | }; | ||
| 197 | if ( $@ ) { | ||
| 198 | spops_dbi_error $@, { sql => $sql, | ||
| 199 | bound_value => $p->{value}, | ||
| 200 | action => 'fetchall_arrayref' }; | ||
| 201 | } | ||
| 202 | return \@rows; | ||
| 203 | } | ||
| 204 | return []; | ||
| 205 | } | ||
| 206 | |||
| 207 | # field => \@ of fieldnames | ||
| 208 | # value => \@ of values | ||
| 209 | # table => $ of table to insert into | ||
| 210 | # no_quote => \% of fields not to quote | ||
| 211 | # sql => $ of sql to run | ||
| 212 | # return_sth => $ if true, return the statement handle rather than status | ||
| 213 | |||
| 214 | sub db_insert { | ||
| 215 | my ( $class, $p ) = @_; | ||
| 216 | my $db = $p->{db} || $class->global_datasource_handle; | ||
| 217 | $class->throw_no_database_handle_error unless ( $db ); | ||
| 218 | |||
| 219 | $log->is_debug && | ||
| 220 | $log->debug( "Enter insert procedure\n", Dumper( $p ) ); | ||
| 221 | |||
| 222 | # If we weren't given direct sql or a list of values or table, bail | ||
| 223 | |||
| 224 | unless ( $p->{sql} or ( $p->{value} and $p->{table} ) ) { | ||
| 225 | spops_error 'Cannot continue with no SQL, values or table name'; | ||
| 226 | } | ||
| 227 | |||
| 228 | my $sql = $p->{sql}; | ||
| 229 | |||
| 230 | # If we weren't given SQL, build it. | ||
| 231 | |||
| 232 | unless ( $sql ) { | ||
| 233 | |||
| 234 | # Find the types for all fields in this table (we don't have | ||
| 235 | # to use them all...); let any errors trickle up | ||
| 236 | |||
| 237 | my $type_info = $class->db_discover_types( | ||
| 238 | $p->{table}, | ||
| 239 | { dbi_type_info => $p->{dbi_type_info}, | ||
| 240 | db => $db }); | ||
| 241 | |||
| 242 | my ( $fields, $values ); | ||
| 243 | |||
| 244 | # Be sure these are at least empty hashrefs, otherwise we | ||
| 245 | # will get an error | ||
| 246 | |||
| 247 | $p->{no_quote} ||= {}; | ||
| 248 | $p->{field} ||= []; | ||
| 249 | $p->{value} ||= []; | ||
| 250 | $log->is_debug && | ||
| 251 | $log->debug( "Fields/values: ", Dumper( $p->{field}, $p->{value} ) ); | ||
| 252 | |||
| 253 | # Cycle through the fields and values, creating lists | ||
| 254 | # suitable for join()ing into the SQL statement. | ||
| 255 | |||
| 256 | my @value_list = (); | ||
| 257 | my $count = 0; | ||
| 258 | foreach my $field ( @{ $p->{field} } ) { | ||
| 259 | next unless ( $field ); | ||
| 260 | |||
| 261 | # Quote the value unless the user asked us not to | ||
| 262 | my $value = ( $p->{no_quote}{ $field } ) | ||
| 263 | ? $p->{value}->[ $count ] | ||
| 264 | : $class->sql_quote( $p->{value}->[ $count ], | ||
| 265 | $type_info->get_type( $field ), | ||
| 266 | $db ); | ||
| 267 | $log->is_info && | ||
| 268 | $log->info( "Trying to add quoted value [$value] ", | ||
| 269 | "for field [$field]" ); | ||
| 270 | push @value_list, $value; | ||
| 271 | $count++; | ||
| 272 | } | ||
| 273 | |||
| 274 | my $field_listing = join ', ', @{ $p->{field} }; | ||
| 275 | my $value_listing = join ', ', @value_list; | ||
| 276 | $sql = qq/ | ||
| 277 | INSERT INTO $p->{table} | ||
| 278 | ( $field_listing ) | ||
| 279 | VALUES | ||
| 280 | ( $value_listing ) | ||
| 281 | /; | ||
| 282 | } | ||
| 283 | |||
| 284 | # Note that we use the prepare()/execute() method of | ||
| 285 | # getting this data in rather than the simpler do(), | ||
| 286 | # since the user might want the statement handle afterward; | ||
| 287 | # if this becomes a performance hang (doubtful), we can only | ||
| 288 | # do p/e if the user's asked for the statement handle | ||
| 289 | |||
| 290 | $log->is_info && | ||
| 291 | $log->info( "Preparing\n$sql" ); | ||
| 292 | my $sth = eval { $db->prepare( $sql ) }; | ||
| 293 | if ( $@ ) { | ||
| 294 | spops_dbi_error $@, { sql => $sql, action => 'prepare' }; | ||
| 295 | } | ||
| 296 | |||
| 297 | my $rv = eval { $sth->execute }; | ||
| 298 | if ( $@ ) { | ||
| 299 | spops_dbi_error $@, { sql => $sql, action => 'execute' }; | ||
| 300 | } | ||
| 301 | $log->is_info && | ||
| 302 | $log->info( "Prepare/execute went ok." ); | ||
| 303 | |||
| 304 | # Everything is ok; return either a true value | ||
| 305 | # or the statement handle, if they've asked for it. | ||
| 306 | |||
| 307 | return $sth if ( $p->{return_sth} ); | ||
| 308 | return $rv; | ||
| 309 | } | ||
| 310 | |||
| 311 | |||
| 312 | # field => \@ of fieldnames | ||
| 313 | # value => \@ of values (includes both update values and WHERE params) | ||
| 314 | # table => $ of table to insert into | ||
| 315 | # where => $ clause for which we're updating | ||
| 316 | # no_quote => \% of fields not to quote | ||
| 317 | # sql => $ of sql to run | ||
| 318 | |||
| 319 | sub db_update { | ||
| 320 | my ( $class, $p ) = @_; | ||
| 321 | my $db = $p->{db} || $class->global_datasource_handle; | ||
| 322 | $class->throw_no_database_handle_error unless ( $db ); | ||
| 323 | |||
| 324 | # If we weren't given direct sql or a list of values or table, bail | ||
| 325 | |||
| 326 | unless ( $p->{sql} or ( $p->{value} and $p->{table} ) ) { | ||
| 327 | spops_error 'Cannot continue with no SQL, values or table name'; | ||
| 328 | } | ||
| 329 | my $sql = $p->{sql}; | ||
| 330 | |||
| 331 | my @values = (); | ||
| 332 | $p->{value} ||= []; | ||
| 333 | |||
| 334 | # If SQL provided still pass the values as bound parameters | ||
| 335 | |||
| 336 | if ( $sql ) { | ||
| 337 | @values = @{ $p->{value} }; | ||
| 338 | } | ||
| 339 | |||
| 340 | # Build the SQL | ||
| 341 | |||
| 342 | unless ( $sql ) { | ||
| 343 | |||
| 344 | # Find the types for all fields in this table (we don't have | ||
| 345 | # to use them all...); let the error trickle up | ||
| 346 | |||
| 347 | my $type_info = $class->db_discover_types( | ||
| 348 | $p->{table}, | ||
| 349 | { dbi_type_info => $p->{dbi_type_info}, | ||
| 350 | db => $db } ); | ||
| 351 | my ( @update ); | ||
| 352 | |||
| 353 | # make a copy of the values given so we can modify the list as | ||
| 354 | # we go -- it may include both update parameters and WHERE | ||
| 355 | # parameters | ||
| 356 | |||
| 357 | @values = @{ $p->{value} }; | ||
| 358 | |||
| 359 | # Go through each field and setup an update assign subset | ||
| 360 | # for each; most of them get a bound parameter and push the | ||
| 361 | # value onto the stack, but values that cannot be bound push | ||
| 362 | # the direct information onto the stack. | ||
| 363 | |||
| 364 | $p->{no_quote} ||= {}; | ||
| 365 | foreach my $field ( @{ $p->{field} } ) { | ||
| 366 | my $rawval = shift @values; | ||
| 367 | $log->is_info && | ||
| 368 | $log->info( "Trying to add value [", defined $rawval ? $rawval : '', "] ", | ||
| 369 | "with field [$field] and type ", | ||
| 370 | "[", $type_info->get_type( $field ), "]" ); | ||
| 371 | |||
| 372 | # Quote the value unless the user asked us not to | ||
| 373 | |||
| 374 | my $value = ( $p->{no_quote}{ $field } ) | ||
| 375 | ? $rawval | ||
| 376 | : $class->sql_quote( $rawval, | ||
| 377 | $type_info->get_type( $field ), | ||
| 378 | $db ); | ||
| 379 | push @update, "$field = $value"; | ||
| 380 | } | ||
| 381 | my $update = join ', ', @update; | ||
| 382 | my $where = ( $p->{where} ) ? "WHERE $p->{where}" : ''; | ||
| 383 | $sql = qq/ | ||
| 384 | UPDATE $p->{table} | ||
| 385 | SET $update | ||
| 386 | $where | ||
| 387 | /; | ||
| 388 | } | ||
| 389 | $log->is_info && | ||
| 390 | $log->info( "Prepare/execute\n$sql" ); | ||
| 391 | my $sth = eval { $db->prepare( $sql ) }; | ||
| 392 | if ( $@ ) { | ||
| 393 | spops_dbi_error $@, { sql => $sql, action => 'prepare' }; | ||
| 394 | } | ||
| 395 | |||
| 396 | # assign the remainder of the values in case the 'WHERE' clause | ||
| 397 | # included any | ||
| 398 | |||
| 399 | my $rv = eval { $sth->execute( @values ) }; | ||
| 400 | if ( $@ ) { | ||
| 401 | spops_dbi_error $@, { sql => $sql, action => 'execute' }; | ||
| 402 | } | ||
| 403 | return $rv; | ||
| 404 | } | ||
| 405 | |||
| 406 | |||
| 407 | # table => $ of table we're deleting from | ||
| 408 | # where => $ limiting our deletes | ||
| 409 | # value => \@ of values to bind | ||
| 410 | # sql => $ of statement to execute directly | ||
| 411 | |||
| 412 | sub db_delete { | ||
| 413 | my ( $class, $p ) = @_; | ||
| 414 | my $db = $p->{db} || $class->global_datasource_handle; | ||
| 415 | $class->throw_no_database_handle_error unless ( $db ); | ||
| 416 | |||
| 417 | # Gotta have a table to delete from | ||
| 418 | |||
| 419 | unless ( $p->{table} or $p->{sql} ) { | ||
| 420 | spops_error 'Cannot delete records without SQL or a table name'; | ||
| 421 | } | ||
| 422 | |||
| 423 | # If we weren't given SQL, build it. | ||
| 424 | |||
| 425 | my $sql = $p->{sql}; | ||
| 426 | unless ( $sql ) { | ||
| 427 | |||
| 428 | # Hopefully you'll have a WHERE clause... but we'll let | ||
| 429 | # you shoot yourself in the foot if you forget :) | ||
| 430 | |||
| 431 | my $where = ( $p->{where} ) ? "WHERE $p->{where}" : ''; | ||
| 432 | $sql = qq/ DELETE FROM $p->{table} $where /; | ||
| 433 | } | ||
| 434 | |||
| 435 | $log->is_info && | ||
| 436 | $log->info( "SQL for DELETE:\n$sql" ); | ||
| 437 | $p->{value} ||= []; | ||
| 438 | my $sth = eval { $db->prepare( $sql ) }; | ||
| 439 | if ( $@ ) { | ||
| 440 | spops_dbi_error $@, { sql => $sql, action => 'prepare' }; | ||
| 441 | } | ||
| 442 | |||
| 443 | my $rv = eval { $sth->execute( @{ $p->{value} } ) }; | ||
| 444 | if ( $@ ) { | ||
| 445 | spops_dbi_error $@, { sql => $sql, | ||
| 446 | bound_value => $p->{value}, | ||
| 447 | action => 'execute' }; | ||
| 448 | } | ||
| 449 | return $rv; | ||
| 450 | } | ||
| 451 | |||
| 452 | |||
| 453 | |||
| 454 | sub db_discover_types { | ||
| 455 | my ( $class, $table, $p ) = @_; | ||
| 456 | |||
| 457 | # Create the index used to find the table info later | ||
| 458 | |||
| 459 | my $db = $p->{db} || $class->global_datasource_handle; | ||
| 460 | $class->throw_no_database_handle_error unless ( $db ); | ||
| 461 | |||
| 462 | my $db_name = eval { $db->{Name} } || eval { $db->{name} }; | ||
| 463 | my $type_idx = join( '-', lc $db_name , lc $table ); | ||
| 464 | $log->is_debug && | ||
| 465 | $log->debug( "Type index used to discover data types: [$type_idx]" ); | ||
| 466 | |||
| 467 | # If we've already discovered the types, get the cached copy | ||
| 468 | |||
| 469 | return $TYPE_INFO{ $type_idx } if ( $TYPE_INFO{ $type_idx } ); | ||
| 470 | |||
| 471 | my $type_info = SPOPS::DBI::TypeInfo->new({ database => $db_name, | ||
| 472 | table => $table }); | ||
| 473 | |||
| 474 | my $conf = eval { $class->CONFIG }; | ||
| 475 | my $fake_types = $p->{dbi_type_info} || $conf->{dbi_type_info}; | ||
| 476 | |||
| 477 | # Certain databases (or more specifically, DBD drivers) do not | ||
| 478 | # process $sth->{TYPE} requests properly, so we need the user to | ||
| 479 | # specify the types by hand | ||
| 480 | |||
| 481 | if ( ref $fake_types eq 'HASH' ) { | ||
| 482 | while ( my ( $field, $fake_type ) = each %{ $fake_types } ) { | ||
| 483 | $type_info->add_type( $field, $fake_type ); | ||
| 484 | } | ||
| 485 | } | ||
| 486 | |||
| 487 | # Otherwise, fetch the types from the database | ||
| 488 | |||
| 489 | else { | ||
| 490 | my $sql = $class->sql_fetch_types( $table ); | ||
| 491 | $type_info->fetch_types( $db, $sql ); | ||
| 492 | } | ||
| 493 | |||
| 494 | return $TYPE_INFO{ $type_idx } = $type_info | ||
| 495 | } | ||
| 496 | |||
| 497 | |||
| 498 | # Default data type discovery statement | ||
| 499 | |||
| 500 | sub sql_fetch_types { return "SELECT * FROM $_[1] where 1 = 0" } | ||
| 501 | |||
| 502 | 1; | ||
| 503 | |||
| 504 | __END__ |