| 1 | # $Id$ | ||
| 2 | |||
| 3 | package Data::ObjectDriver::Driver::DBI; | ||
| 4 | use strict; | ||
| 5 | use warnings; | ||
| 6 | |||
| 7 | use base qw( Data::ObjectDriver Class::Accessor::Fast ); | ||
| 8 | |||
| 9 | use DBI; | ||
| 10 | use Carp (); | ||
| 11 | use Data::ObjectDriver::Errors; | ||
| 12 | use Data::ObjectDriver::SQL; | ||
| 13 | use Data::ObjectDriver::Driver::DBD; | ||
| 14 | use Data::ObjectDriver::Iterator; | ||
| 15 | use Scalar::Util 'blessed'; | ||
| 16 | |||
| 17 | my $ForkSafe = _is_fork_safe(); | ||
| 18 | my %Handles; | ||
| 19 | |||
| 20 | sub _is_fork_safe { | ||
| 21 | return if exists $ENV{DOD_FORK_SAFE} and !$ENV{DOD_FORK_SAFE}; | ||
| 22 | eval { require POSIX::AtFork; 1 } or return; | ||
| 23 | eval { require Scalar::Util; Scalar::Util->import('weaken'); 1 } or return; | ||
| 24 | return 1; | ||
| 25 | } | ||
| 26 | |||
| 27 | __PACKAGE__->mk_accessors(qw( dsn username password connect_options get_dbh dbd prefix reuse_dbh force_no_prepared_cache)); | ||
| 28 | |||
| 29 | |||
| 30 | sub init { | ||
| 31 | my $driver = shift; | ||
| 32 | my %param = @_; | ||
| 33 | for my $key (keys %param) { | ||
| 34 | $driver->$key($param{$key}); | ||
| 35 | } | ||
| 36 | if(!exists $param{dbd}) { | ||
| 37 | ## Create a DSN-specific driver (e.g. "mysql"). | ||
| 38 | my $type; | ||
| 39 | if (my $dsn = $driver->dsn) { | ||
| 40 | ($type) = $dsn =~ /^dbi:(\w*)/i; | ||
| 41 | } elsif (my $dbh = $driver->dbh) { | ||
| 42 | $type = $dbh->{Driver}{Name}; | ||
| 43 | } elsif (my $getter = $driver->get_dbh) { | ||
| 44 | ## Ugly. Shouldn't have to connect just to get the driver name. | ||
| 45 | my $dbh = $getter->(); | ||
| 46 | $type = $dbh->{Driver}{Name}; | ||
| 47 | } | ||
| 48 | $driver->dbd(Data::ObjectDriver::Driver::DBD->new($type)); | ||
| 49 | } | ||
| 50 | |||
| 51 | if ($ForkSafe) { | ||
| 52 | # Purge cached handles | ||
| 53 | weaken(my $driver_weaken = $driver); | ||
| 54 | POSIX::AtFork->add_to_child(sub { | ||
| 55 | return unless $driver_weaken; | ||
| 56 | $driver_weaken->{dbh} = undef; | ||
| 57 | %Handles = (); | ||
| 58 | }); | ||
| 59 | } | ||
| 60 | |||
| 61 | $driver; | ||
| 62 | } | ||
| 63 | |||
| 64 | sub generate_pk { | ||
| 65 | my $driver = shift; | ||
| 66 | if (my $generator = $driver->pk_generator) { | ||
| 67 | return $generator->(@_); | ||
| 68 | } | ||
| 69 | } | ||
| 70 | |||
| 71 | # Some versions of SQLite require the undefing to finalise properly | ||
| 72 | sub _close_sth { | ||
| 73 | my $sth = shift; | ||
| 74 | $sth->finish; | ||
| 75 | undef $sth; | ||
| 76 | } | ||
| 77 | |||
| 78 | # Some versions of SQLite have problems with prepared caching due to finalisation order | ||
| 79 | sub _prepare_cached { | ||
| 80 | my $driver = shift; | ||
| 81 | my $dbh = shift; | ||
| 82 | my $sql = shift; | ||
| 83 | return ($driver->dbd->can_prepare_cached_statements)? $dbh->prepare_cached($sql) : $dbh->prepare($sql); | ||
| 84 | } | ||
| 85 | |||
| 86 | sub init_db { | ||
| 87 | my $driver = shift; | ||
| 88 | my $dbh; | ||
| 89 | if ($driver->reuse_dbh) { | ||
| 90 | $dbh = $Handles{$driver->dsn}; | ||
| 91 | } | ||
| 92 | unless ($dbh) { | ||
| 93 | eval { | ||
| 94 | $dbh = DBI->connect($driver->dsn, $driver->username, $driver->password, | ||
| 95 | { RaiseError => 1, PrintError => 0, AutoCommit => 1, | ||
| 96 | ( $ForkSafe ? ( AutoInactiveDestroy => 1 ) : () ), | ||
| 97 | %{$driver->connect_options || {}} }) | ||
| 98 | or Carp::croak("Connection error: " . $DBI::errstr); | ||
| 99 | }; | ||
| 100 | if ($@) { | ||
| 101 | Carp::croak($@); | ||
| 102 | } | ||
| 103 | } | ||
| 104 | if ($driver->reuse_dbh) { | ||
| 105 | $Handles{$driver->dsn} = $dbh; | ||
| 106 | } | ||
| 107 | $driver->dbd->init_dbh($dbh); | ||
| 108 | $driver->{__dbh_init_by_driver} = 1; | ||
| 109 | return $dbh; | ||
| 110 | } | ||
| 111 | |||
| 112 | sub dbh { | ||
| 113 | my $driver = shift; | ||
| 114 | if (@_) { | ||
| 115 | my $dbh = $driver->{dbh} = shift; | ||
| 116 | if (!$dbh && $driver->reuse_dbh) { | ||
| 117 | $dbh = delete $Handles{$driver->dsn}; | ||
| 118 | $dbh->disconnect if $dbh; | ||
| 119 | } | ||
| 120 | } | ||
| 121 | $driver->{dbh}; | ||
| 122 | } | ||
| 123 | |||
| 124 | sub rw_handle { | ||
| 125 | my $driver = shift; | ||
| 126 | my $db = shift || 'main'; | ||
| 127 | my $dbh; | ||
| 128 | if ($dbh = $driver->dbh) { | ||
| 129 | return $dbh if $dbh->ping; | ||
| 130 | |||
| 131 | ## ping fails, kill cache. | ||
| 132 | delete $Handles{$driver->dsn}; | ||
| 133 | } | ||
| 134 | if (my $getter = $driver->get_dbh) { | ||
| 135 | $dbh = $getter->(); | ||
| 136 | } else { | ||
| 137 | $dbh = $driver->init_db($db) or die $driver->last_error; | ||
| 138 | $driver->dbh($dbh); | ||
| 139 | } | ||
| 140 | return $dbh; | ||
| 141 | } | ||
| 142 | *r_handle = \&rw_handle; | ||
| 143 | |||
| 144 | sub fetch_data { | ||
| 145 | my $driver = shift; | ||
| 146 | my($obj) = @_; | ||
| 147 | return unless $obj->has_primary_key; | ||
| 148 | my $terms = $obj->primary_key_to_terms; | ||
| 149 | my $args = { limit => 1 }; | ||
| 150 | my $rec = {}; | ||
| 151 | my $sth = $driver->fetch($rec, $obj, $terms, $args); | ||
| 152 | $sth->fetch; | ||
| 153 | _close_sth($sth); | ||
| 154 | $driver->end_query($sth); | ||
| 155 | return $rec; | ||
| 156 | } | ||
| 157 | |||
| 158 | sub prepare_fetch { | ||
| 159 | my $driver = shift; | ||
| 160 | my($class, $orig_terms, $orig_args) = @_; | ||
| 161 | |||
| 162 | ## Use (shallow) duplicates so the pre_search trigger can modify them. | ||
| 163 | my $terms = defined $orig_terms ? ( ref $orig_terms eq 'ARRAY' ? [ @$orig_terms ] : { %$orig_terms } ) : {}; | ||
| 164 | my $args = defined $orig_args ? { %$orig_args } : {}; | ||
| 165 | $class->call_trigger('pre_search', $terms, $args); | ||
| 166 | |||
| 167 | my $stmt = $driver->prepare_statement($class, $terms, $args); | ||
| 168 | |||
| 169 | my $sql = $stmt->as_sql; | ||
| 170 | $sql .= "\nFOR UPDATE" if $orig_args->{for_update}; | ||
| 171 | return ($sql, $stmt->{bind}, $stmt) | ||
| 172 | } | ||
| 173 | |||
| 174 | sub fetch { | ||
| 175 | my $driver = shift; | ||
| 176 | my ($rec, $class, $terms_or_stmt, $orig_args) = @_; | ||
| 177 | my ($sql, $stmt); | ||
| 178 | |||
| 179 | if ($Data::ObjectDriver::RESTRICT_IO) { | ||
| 180 | use Data::Dumper; | ||
| 181 | die "Attempted DBI I/O while in restricted mode: fetch() " . Dumper($terms_or_stmt, $orig_args); | ||
| 182 | } | ||
| 183 | |||
| 184 | if (blessed($terms_or_stmt) && $terms_or_stmt->isa('Data::ObjectDriver::SQL')) { | ||
| 185 | $sql = $terms_or_stmt->as_sql; | ||
| 186 | $stmt = $terms_or_stmt; | ||
| 187 | } else { | ||
| 188 | ($sql, undef, $stmt) = $driver->prepare_fetch($class, $terms_or_stmt, $orig_args); | ||
| 189 | } | ||
| 190 | |||
| 191 | my @columns; | ||
| 192 | my $map = $stmt->select_map; | ||
| 193 | for my $col (@{ $stmt->select }) { | ||
| 194 | push @columns, \$rec->{ $map->{$col} }; | ||
| 195 | } | ||
| 196 | |||
| 197 | my $dbh = $driver->r_handle($class->properties->{db}); | ||
| 198 | $driver->start_query($sql, $stmt->{bind}); | ||
| 199 | |||
| 200 | my $sth = $orig_args->{no_cached_prepare} ? $dbh->prepare($sql) : $driver->_prepare_cached($dbh, $sql); | ||
| 201 | $sth->execute(@{ $stmt->{bind} }); | ||
| 202 | $sth->bind_columns(undef, @columns); | ||
| 203 | |||
| 204 | # need to slurp 'offset' rows for DBs that cannot do it themselves | ||
| 205 | if (!$driver->dbd->offset_implemented && $orig_args->{offset}) { | ||
| 206 | for (1..$orig_args->{offset}) { | ||
| 207 | $sth->fetch; | ||
| 208 | } | ||
| 209 | } | ||
| 210 | |||
| 211 | return $sth; | ||
| 212 | } | ||
| 213 | |||
| 214 | sub load_object_from_rec { | ||
| 215 | my $driver = shift; | ||
| 216 | my ($class, $rec, $no_triggers) = @_; | ||
| 217 | |||
| 218 | my $obj = $class->new; | ||
| 219 | $obj->set_values_internal($rec); | ||
| 220 | ## Don't need a duplicate as there's no previous version in memory | ||
| 221 | ## to preserve. | ||
| 222 | $obj->{__is_stored} = 1; | ||
| 223 | $obj->call_trigger('post_load') unless $no_triggers; | ||
| 224 | return $obj; | ||
| 225 | } | ||
| 226 | |||
| 227 | sub search { | ||
| 228 | my ($driver) = shift; | ||
| 229 | my ($class, $terms_or_stmt, $args) = @_; | ||
| 230 | |||
| 231 | my $rec = {}; | ||
| 232 | my $sth = $driver->fetch($rec, $class, $terms_or_stmt, $args); | ||
| 233 | |||
| 234 | my $iter = sub { | ||
| 235 | ## This is kind of a hack--we need $driver to stay in scope, | ||
| 236 | ## so that the DESTROY method isn't called. So we include it | ||
| 237 | ## in the scope of the closure. | ||
| 238 | my $d = $driver; | ||
| 239 | |||
| 240 | unless ($sth->fetch) { | ||
| 241 | _close_sth($sth); | ||
| 242 | $driver->end_query($sth); | ||
| 243 | return; | ||
| 244 | } | ||
| 245 | return $driver->load_object_from_rec($class, $rec, $args->{no_triggers}); | ||
| 246 | }; | ||
| 247 | |||
| 248 | if (wantarray) { | ||
| 249 | my @objs = (); | ||
| 250 | |||
| 251 | while (my $obj = $iter->()) { | ||
| 252 | push @objs, $obj; | ||
| 253 | } | ||
| 254 | return @objs; | ||
| 255 | } else { | ||
| 256 | my $iterator = Data::ObjectDriver::Iterator->new( | ||
| 257 | $iter, sub { _close_sth($sth); $driver->end_query($sth) }, | ||
| 258 | ); | ||
| 259 | return $iterator; | ||
| 260 | } | ||
| 261 | return; | ||
| 262 | } | ||
| 263 | |||
| 264 | sub lookup { | ||
| 265 | my $driver = shift; | ||
| 266 | my($class, $id) = @_; | ||
| 267 | return unless defined $id; | ||
| 268 | my @obj = $driver->search($class, | ||
| 269 | $class->primary_key_to_terms($id), { limit => 1 , is_pk => 1 }); | ||
| 270 | $obj[0]; | ||
| 271 | } | ||
| 272 | |||
| 273 | sub lookup_multi { | ||
| 274 | my $driver = shift; | ||
| 275 | my($class, $ids) = @_; | ||
| 276 | return [] unless @$ids; | ||
| 277 | my @got; | ||
| 278 | ## If it's a single-column PK, assume it's in one partition, and | ||
| 279 | ## use an OR search. FIXME: can we instead check for partitioning? | ||
| 280 | unless (ref($ids->[0])) { | ||
| 281 | my $terms = $class->primary_key_to_terms([ $ids ]); | ||
| 282 | my @sqlgot = $driver->search($class, $terms, { is_pk => 1 }); | ||
| 283 | my %hgot = map { $_->primary_key() => $_ } @sqlgot; | ||
| 284 | @got = map { defined $_ ? $hgot{$_} : undef } @$ids; | ||
| 285 | } else { | ||
| 286 | for my $id (@$ids) { | ||
| 287 | push @got, eval{ $class->driver->lookup($class, $id) }; | ||
| 288 | } | ||
| 289 | } | ||
| 290 | \@got; | ||
| 291 | } | ||
| 292 | |||
| 293 | sub select_one { | ||
| 294 | my $driver = shift; | ||
| 295 | my($sql, $bind) = @_; | ||
| 296 | my $dbh = $driver->r_handle; | ||
| 297 | |||
| 298 | $driver->start_query($sql, $bind); | ||
| 299 | my $sth = $driver->_prepare_cached($dbh, $sql); | ||
| 300 | $sth->execute(@$bind); | ||
| 301 | $sth->bind_columns(undef, \my($val)); | ||
| 302 | unless ($sth->fetch) { | ||
| 303 | _close_sth($sth); | ||
| 304 | $driver->end_query($sth); | ||
| 305 | return; | ||
| 306 | } | ||
| 307 | |||
| 308 | _close_sth($sth); | ||
| 309 | $driver->end_query($sth); | ||
| 310 | |||
| 311 | return $val; | ||
| 312 | } | ||
| 313 | |||
| 314 | sub table_for { | ||
| 315 | my $driver = shift; | ||
| 316 | my($this) = @_; | ||
| 317 | my $src = $this->datasource or return; | ||
| 318 | return $driver->prefix ? join('', $driver->prefix, $src) : $src; | ||
| 319 | } | ||
| 320 | |||
| 321 | sub exists { | ||
| 322 | my $driver = shift; | ||
| 323 | my($obj) = @_; | ||
| 324 | return unless $obj->has_primary_key; | ||
| 325 | |||
| 326 | if ($Data::ObjectDriver::RESTRICT_IO) { | ||
| 327 | die "Attempted DBI I/O while in restricted mode: exists()"; | ||
| 328 | } | ||
| 329 | |||
| 330 | ## should call pre_search trigger so we can use enum in the part of PKs | ||
| 331 | my $terms = $obj->primary_key_to_terms; | ||
| 332 | |||
| 333 | my $class = ref $obj; | ||
| 334 | $terms ||= {}; | ||
| 335 | $class->call_trigger('pre_search', $terms); | ||
| 336 | |||
| 337 | my $tbl = $driver->table_for($obj); | ||
| 338 | my $stmt = $driver->prepare_statement($class, $terms, { limit => 1 }); | ||
| 339 | my $sql = "SELECT 1 FROM $tbl\n"; | ||
| 340 | $sql .= $stmt->as_sql_where; | ||
| 341 | my $dbh = $driver->r_handle($obj->properties->{db}); | ||
| 342 | $driver->start_query($sql, $stmt->{bind}); | ||
| 343 | my $sth = $driver->_prepare_cached($dbh, $sql); | ||
| 344 | $sth->execute(@{ $stmt->{bind} }); | ||
| 345 | my $exists = $sth->fetch; | ||
| 346 | _close_sth($sth); | ||
| 347 | $driver->end_query($sth); | ||
| 348 | |||
| 349 | return $exists; | ||
| 350 | } | ||
| 351 | |||
| 352 | sub replace { | ||
| 353 | my $driver = shift; | ||
| 354 | if ($driver->dbd->can_replace) { | ||
| 355 | return $driver->_insert_or_replace(@_, { replace => 1 }); | ||
| 356 | } | ||
| 357 | if (! $driver->txn_active) { | ||
| 358 | $driver->begin_work; | ||
| 359 | my $res; | ||
| 360 | eval { | ||
| 361 | $driver->remove(@_); | ||
| 362 | $res = $driver->insert(@_); | ||
| 363 | }; | ||
| 364 | if ($@) { | ||
| 365 | $driver->rollback; | ||
| 366 | Carp::croak("REPLACE transaction error $driver: $@"); | ||
| 367 | } | ||
| 368 | $driver->commit; | ||
| 369 | return $res; | ||
| 370 | } | ||
| 371 | $driver->remove(@_); | ||
| 372 | $driver->insert(@_); | ||
| 373 | } | ||
| 374 | |||
| 375 | sub insert { | ||
| 376 | my $driver = shift; | ||
| 377 | my($orig_obj) = @_; | ||
| 378 | $driver->_insert_or_replace($orig_obj, { replace => 0 }); | ||
| 379 | } | ||
| 380 | |||
| 381 | sub _insert_or_replace { | ||
| 382 | my $driver = shift; | ||
| 383 | my($orig_obj, $options) = @_; | ||
| 384 | |||
| 385 | if ($Data::ObjectDriver::RESTRICT_IO) { | ||
| 386 | die "Attempted DBI I/O while in restricted mode: _insert_or_replace()"; | ||
| 387 | } | ||
| 388 | |||
| 389 | ## Syntax switch between INSERT or REPLACE statement based on options | ||
| 390 | $options ||= {}; | ||
| 391 | my $INSERT_OR_REPLACE = $options->{replace} ? 'REPLACE' : 'INSERT'; | ||
| 392 | |||
| 393 | ## Use a duplicate so the pre_save trigger can modify it. | ||
| 394 | my $obj = $orig_obj->clone_all; | ||
| 395 | $obj->call_trigger('pre_save', $orig_obj); | ||
| 396 | $obj->call_trigger('pre_insert', $orig_obj); | ||
| 397 | |||
| 398 | my $cols = $obj->column_names; | ||
| 399 | if (!$obj->is_pkless && ! $obj->has_primary_key) { | ||
| 400 | ## If we don't already have a primary key assigned for this object, we | ||
| 401 | ## may need to generate one (depending on the underlying DB | ||
| 402 | ## driver). If the driver gives us a new ID, we insert that into | ||
| 403 | ## the new record; otherwise, we assume that the DB is using an | ||
| 404 | ## auto-increment column of some sort, so we don't specify an ID | ||
| 405 | ## at all. | ||
| 406 | my $pk = $obj->primary_key_tuple; | ||
| 407 | if(my $generated = $driver->generate_pk($obj)) { | ||
| 408 | ## The ID is the only thing we *are* allowed to change on | ||
| 409 | ## the original object, so copy it back. | ||
| 410 | $orig_obj->$_($obj->$_) for @$pk; | ||
| 411 | } else { | ||
| 412 | ## Filter the undefined key fields out of the columns to include | ||
| 413 | ## in the query, so that we don't specify them in the query. | ||
| 414 | my %pk = map { $_ => 1 } @$pk; | ||
| 415 | $cols = [ grep !$pk{$_} || defined $obj->$_(), @$cols ]; | ||
| 416 | } | ||
| 417 | } | ||
| 418 | my $tbl = $driver->table_for($obj); | ||
| 419 | my $sql = "$INSERT_OR_REPLACE INTO $tbl\n"; | ||
| 420 | my $dbd = $driver->dbd; | ||
| 421 | $sql .= '(' . join(', ', | ||
| 422 | map { $dbd->db_column_name($tbl, $_) } | ||
| 423 | @$cols) . | ||
| 424 | ')' . "\n" . | ||
| 425 | 'VALUES (' . join(', ', ('?') x @$cols) . ')' . "\n"; | ||
| 426 | my $dbh = $driver->rw_handle($obj->properties->{db}); | ||
| 427 | $driver->start_query($sql, $obj->{column_values}); | ||
| 428 | my $sth = $driver->_prepare_cached($dbh, $sql); | ||
| 429 | my $i = 1; | ||
| 430 | my $col_defs = $obj->properties->{column_defs}; | ||
| 431 | for my $col (@$cols) { | ||
| 432 | my $val = $obj->column($col); | ||
| 433 | my $type = $col_defs->{$col} || 'char'; | ||
| 434 | my $attr = $dbd->bind_param_attributes($type, $obj, $col); | ||
| 435 | $sth->bind_param($i++, $val, $attr); | ||
| 436 | } | ||
| 437 | eval { $sth->execute }; | ||
| 438 | die "Failed to execute $sql with ".join(", ",@$cols).": $@" if $@; | ||
| 439 | |||
| 440 | ## Now, if we didn't have an object ID, we need to grab the | ||
| 441 | ## newly-assigned ID. | ||
| 442 | if (!$obj->is_pkless && ! $obj->has_primary_key) { | ||
| 443 | my $pk = $obj->primary_key_tuple; ## but do that only for relation that aren't PK-less | ||
| 444 | my $id_col = $pk->[0]; # XXX are we sure we will always use '0' ? | ||
| 445 | my $id = $dbd->fetch_id(ref($obj), $dbh, $sth, $driver); | ||
| 446 | $obj->$id_col($id); | ||
| 447 | ## The ID is the only thing we *are* allowed to change on | ||
| 448 | ## the original object. | ||
| 449 | $orig_obj->$id_col($id); | ||
| 450 | } | ||
| 451 | |||
| 452 | _close_sth($sth); | ||
| 453 | $driver->end_query($sth); | ||
| 454 | |||
| 455 | $obj->call_trigger('post_save', $orig_obj); | ||
| 456 | $obj->call_trigger('post_insert', $orig_obj); | ||
| 457 | |||
| 458 | $orig_obj->{__is_stored} = 1; | ||
| 459 | $orig_obj->{changed_cols} = {}; | ||
| 460 | 1; | ||
| 461 | } | ||
| 462 | |||
| 463 | sub update { | ||
| 464 | my $driver = shift; | ||
| 465 | |||
| 466 | my($orig_obj, $terms) = @_; | ||
| 467 | |||
| 468 | if ($Data::ObjectDriver::RESTRICT_IO) { | ||
| 469 | use Data::Dumper; | ||
| 470 | die "Attempted DBI I/O while in restricted mode: _update() " . Dumper($terms); | ||
| 471 | } | ||
| 472 | |||
| 473 | ## Use a duplicate so the pre_save trigger can modify it. | ||
| 474 | my $obj = $orig_obj->clone_all; | ||
| 475 | $obj->call_trigger('pre_save', $orig_obj); | ||
| 476 | $obj->call_trigger('pre_update', $orig_obj); | ||
| 477 | |||
| 478 | my $cols = $obj->column_names; | ||
| 479 | my @changed_cols = $obj->changed_cols; | ||
| 480 | |||
| 481 | ## If there's no updated columns, update() is no-op | ||
| 482 | ## but we should call post_* triggers | ||
| 483 | unless (@changed_cols) { | ||
| 484 | $obj->call_trigger('post_save', $orig_obj); | ||
| 485 | $obj->call_trigger('post_update', $orig_obj); | ||
| 486 | return 1; | ||
| 487 | } | ||
| 488 | |||
| 489 | my $tbl = $driver->table_for($obj); | ||
| 490 | my $sql = "UPDATE $tbl SET\n"; | ||
| 491 | my $dbd = $driver->dbd; | ||
| 492 | $sql .= join(', ', | ||
| 493 | map { $dbd->db_column_name($tbl, $_) . " = ?" } | ||
| 494 | @changed_cols) . "\n"; | ||
| 495 | my $stmt = $driver->prepare_statement(ref($obj), { | ||
| 496 | %{ $obj->primary_key_to_terms }, | ||
| 497 | %{ $terms || {} } | ||
| 498 | }); | ||
| 499 | $sql .= $stmt->as_sql_where; | ||
| 500 | |||
| 501 | my $dbh = $driver->rw_handle($obj->properties->{db}); | ||
| 502 | $driver->start_query($sql, $obj->{column_values}); | ||
| 503 | my $sth = $driver->_prepare_cached($dbh, $sql); | ||
| 504 | my $i = 1; | ||
| 505 | my $col_defs = $obj->properties->{column_defs}; | ||
| 506 | for my $col (@changed_cols) { | ||
| 507 | my $val = $obj->column($col); | ||
| 508 | my $type = $col_defs->{$col} || 'char'; | ||
| 509 | my $attr = $dbd->bind_param_attributes($type, $obj, $col); | ||
| 510 | $sth->bind_param($i++, $val, $attr); | ||
| 511 | } | ||
| 512 | |||
| 513 | ## Bind the primary key value(s). | ||
| 514 | for my $val (@{ $stmt->{bind} }) { | ||
| 515 | $sth->bind_param($i++, $val); | ||
| 516 | } | ||
| 517 | |||
| 518 | my $rows = $sth->execute; | ||
| 519 | _close_sth($sth); | ||
| 520 | $driver->end_query($sth); | ||
| 521 | |||
| 522 | $obj->call_trigger('post_save', $orig_obj); | ||
| 523 | $obj->call_trigger('post_update', $orig_obj); | ||
| 524 | |||
| 525 | $orig_obj->{changed_cols} = {}; | ||
| 526 | return $rows; | ||
| 527 | } | ||
| 528 | |||
| 529 | sub remove { | ||
| 530 | my $driver = shift; | ||
| 531 | my $orig_obj = shift; | ||
| 532 | |||
| 533 | ## If remove() is called on class method and we have 'nofetch' | ||
| 534 | ## option, we remove the record using $term and won't create | ||
| 535 | ## $object. This is for efficiency and PK-less tables | ||
| 536 | ## Note: In this case, triggers won't be fired | ||
| 537 | ## Otherwise, Class->remove is a shortcut for search+remove | ||
| 538 | unless (ref($orig_obj)) { | ||
| 539 | if ($_[1] && $_[1]->{nofetch}) { | ||
| 540 | return $driver->direct_remove($orig_obj, @_); | ||
| 541 | } else { | ||
| 542 | my $result = 0; | ||
| 543 | my @obj = $driver->search($orig_obj, @_); | ||
| 544 | for my $obj (@obj) { | ||
| 545 | my $res = $obj->remove(@_) || 0; | ||
| 546 | $result += $res; | ||
| 547 | } | ||
| 548 | return $result || 0E0; | ||
| 549 | } | ||
| 550 | } | ||
| 551 | |||
| 552 | return unless $orig_obj->has_primary_key; | ||
| 553 | |||
| 554 | if ($Data::ObjectDriver::RESTRICT_IO) { | ||
| 555 | die "Attempted DBI I/O while in restricted mode: remove()"; | ||
| 556 | } | ||
| 557 | |||
| 558 | ## Use a duplicate so the pre_save trigger can modify it. | ||
| 559 | my $obj = $orig_obj->clone_all; | ||
| 560 | $obj->call_trigger('pre_remove', $orig_obj); | ||
| 561 | |||
| 562 | my $tbl = $driver->table_for($obj); | ||
| 563 | my $sql = "DELETE FROM $tbl\n"; | ||
| 564 | my $stmt = $driver->prepare_statement(ref($obj), $obj->primary_key_to_terms); | ||
| 565 | $sql .= $stmt->as_sql_where; | ||
| 566 | my $dbh = $driver->rw_handle($obj->properties->{db}); | ||
| 567 | $driver->start_query($sql, $stmt->{bind}); | ||
| 568 | my $sth = $driver->_prepare_cached($dbh, $sql); | ||
| 569 | my $result = $sth->execute(@{ $stmt->{bind} }); | ||
| 570 | _close_sth($sth); | ||
| 571 | $driver->end_query($sth); | ||
| 572 | |||
| 573 | $obj->call_trigger('post_remove', $orig_obj); | ||
| 574 | |||
| 575 | delete $orig_obj->{__is_stored}; | ||
| 576 | return $result; | ||
| 577 | } | ||
| 578 | |||
| 579 | sub direct_remove { | ||
| 580 | my $driver = shift; | ||
| 581 | my($class, $orig_terms, $orig_args) = @_; | ||
| 582 | |||
| 583 | if ($Data::ObjectDriver::RESTRICT_IO) { | ||
| 584 | die "Attempted DBI I/O while in restricted mode: direct_remove() " . Dumper($orig_terms, $orig_args); | ||
| 585 | } | ||
| 586 | |||
| 587 | ## Use (shallow) duplicates so the pre_search trigger can modify them. | ||
| 588 | my $terms = defined $orig_terms ? { %$orig_terms } : {}; | ||
| 589 | my $args = defined $orig_args ? { %$orig_args } : {}; | ||
| 590 | $class->call_trigger('pre_search', $terms, $args); | ||
| 591 | |||
| 592 | my $stmt = $driver->prepare_statement($class, $terms, $args); | ||
| 593 | my $tbl = $driver->table_for($class); | ||
| 594 | my $sql = "DELETE from $tbl\n"; | ||
| 595 | $sql .= $stmt->as_sql_where; | ||
| 596 | |||
| 597 | # not all DBD drivers can do this. check. better to die than do | ||
| 598 | # unbounded DELETE when they requested a limit. | ||
| 599 | if ($stmt->limit) { | ||
| 600 | Carp::croak("Driver doesn't support DELETE with LIMIT") | ||
| 601 | unless $driver->dbd->can_delete_with_limit; | ||
| 602 | $sql .= $stmt->as_limit; | ||
| 603 | } | ||
| 604 | |||
| 605 | my $dbh = $driver->rw_handle($class->properties->{db}); | ||
| 606 | $driver->start_query($sql, $stmt->{bind}); | ||
| 607 | my $sth = $driver->_prepare_cached($dbh, $sql); | ||
| 608 | my $result = $sth->execute(@{ $stmt->{bind} }); | ||
| 609 | _close_sth($sth); | ||
| 610 | $driver->end_query($sth); | ||
| 611 | return $result; | ||
| 612 | } | ||
| 613 | |||
| 614 | sub bulk_insert { | ||
| 615 | my $driver = shift; | ||
| 616 | my $class = shift; | ||
| 617 | my $dbd = $driver->dbd; | ||
| 618 | |||
| 619 | my $cols = shift; | ||
| 620 | my $data = shift; | ||
| 621 | |||
| 622 | |||
| 623 | Carp::croak("Driver doesn't support bulk_insert") | ||
| 624 | unless ($dbd->can('bulk_insert')); | ||
| 625 | |||
| 626 | if ($Data::ObjectDriver::RESTRICT_IO) { | ||
| 627 | die "Attempted DBI I/O while in restricted mode: bulk_insert()"; | ||
| 628 | } | ||
| 629 | |||
| 630 | # check that cols are valid.. | ||
| 631 | my %valid_cols = map {$_ => 1} @{$class->column_names}; | ||
| 632 | |||
| 633 | my $invalid_cols; | ||
| 634 | foreach my $c (@{$cols}) { | ||
| 635 | $invalid_cols .= "$c " if (!$valid_cols{$c}); | ||
| 636 | } | ||
| 637 | if (defined($invalid_cols)) { | ||
| 638 | Carp::croak("Invalid columns $invalid_cols passed to bulk_insert"); | ||
| 639 | } | ||
| 640 | |||
| 641 | |||
| 642 | # pass this directly to the backend DBD | ||
| 643 | my $dbh = $driver->rw_handle($class->properties->{db}); | ||
| 644 | my $tbl = $driver->table_for($class); | ||
| 645 | |||
| 646 | my @db_cols; | ||
| 647 | my %attrs; | ||
| 648 | my $col_defs = $class->properties->{column_defs}; | ||
| 649 | for my $col (@$cols) { | ||
| 650 | my $db_col = $dbd->db_column_name($tbl, $col); | ||
| 651 | push @db_cols, $db_col; | ||
| 652 | my $type = $col_defs->{$col} || 'char'; | ||
| 653 | my $attr = $dbd->bind_param_attributes($type) or next; | ||
| 654 | $attrs{$db_col} = $attr; | ||
| 655 | } | ||
| 656 | |||
| 657 | return $dbd->bulk_insert($dbh, $tbl, \@db_cols, $data, \%attrs); | ||
| 658 | } | ||
| 659 | |||
| 660 | sub begin_work { | ||
| 661 | my $driver = shift; | ||
| 662 | |||
| 663 | return if $driver->txn_active; | ||
| 664 | |||
| 665 | my $dbh = $driver->dbh; | ||
| 666 | |||
| 667 | unless ($dbh) { | ||
| 668 | $driver->{__delete_dbh_after_txn} = 1; | ||
| 669 | $dbh = $driver->rw_handle; | ||
| 670 | $driver->dbh($dbh); | ||
| 671 | } | ||
| 672 | |||
| 673 | if ($dbh->{AutoCommit}) { | ||
| 674 | eval { | ||
| 675 | $dbh->begin_work; | ||
| 676 | }; | ||
| 677 | if (my $err = $@) { | ||
| 678 | $driver->rollback; | ||
| 679 | Carp::croak("Begin work failed for driver $driver: $err"); | ||
| 680 | } | ||
| 681 | } | ||
| 682 | ## if for some reason AutoCommit was 0 but txn_active was false, | ||
| 683 | ## then we set it to true now | ||
| 684 | $driver->txn_active(1); | ||
| 685 | } | ||
| 686 | |||
| 687 | sub commit { shift->_end_txn('commit') } | ||
| 688 | sub rollback { shift->_end_txn('rollback') } | ||
| 689 | |||
| 690 | sub _end_txn { | ||
| 691 | my $driver = shift; | ||
| 692 | my($action) = @_; | ||
| 693 | |||
| 694 | ## if the driver has its own internal txn_active flag | ||
| 695 | ## off, we don't bother ending. Maybe we already did | ||
| 696 | if ($driver->txn_active) { | ||
| 697 | $driver->txn_active(0); | ||
| 698 | |||
| 699 | my $dbh = $driver->dbh | ||
| 700 | or Carp::croak("$action called without a stored handle--begin_work?"); | ||
| 701 | |||
| 702 | unless ($dbh->{AutoCommit}) { | ||
| 703 | eval { $dbh->$action() }; | ||
| 704 | if ($@) { | ||
| 705 | Carp::croak("$action failed for driver $driver: $@"); | ||
| 706 | } | ||
| 707 | } | ||
| 708 | } | ||
| 709 | if ($driver->{__delete_dbh_after_txn}) { | ||
| 710 | $driver->dbh(undef); | ||
| 711 | delete $driver->{__delete_dbh_after_txn}; | ||
| 712 | } | ||
| 713 | return 1; | ||
| 714 | } | ||
| 715 | |||
| 716 | sub DESTROY { | ||
| 717 | my $driver = shift; | ||
| 718 | ## Don't take the responsibility of disconnecting this handler | ||
| 719 | ## if we haven't created it ourself. | ||
| 720 | return unless $driver->{__dbh_init_by_driver}; | ||
| 721 | if (my $dbh = $driver->dbh) { | ||
| 722 | $dbh->disconnect; | ||
| 723 | } | ||
| 724 | } | ||
| 725 | |||
| 726 | sub prepare_statement { | ||
| 727 | my $driver = shift; | ||
| 728 | my($class, $terms, $args) = @_; | ||
| 729 | |||
| 730 | my $dbd = $driver->dbd; | ||
| 731 | my $stmt = $args->{sql_statement} || $dbd->sql_class->new; | ||
| 732 | |||
| 733 | if (my $tbl = $driver->table_for($class)) { | ||
| 734 | my $cols = $class->column_names; | ||
| 735 | my %fetch = $args->{fetchonly} ? | ||
| 736 | (map { $_ => 1 } @{ $args->{fetchonly} }) : (); | ||
| 737 | my $skip = $stmt->select_map_reverse; | ||
| 738 | for my $col (@$cols) { | ||
| 739 | next if $skip->{$col}; | ||
| 740 | if (keys %fetch) { | ||
| 741 | next unless $fetch{$col}; | ||
| 742 | } | ||
| 743 | my $dbcol = join '.', $tbl, $dbd->db_column_name($tbl, $col); | ||
| 744 | $stmt->add_select($dbcol => $col); | ||
| 745 | } | ||
| 746 | |||
| 747 | $stmt->from([ $tbl ]); | ||
| 748 | |||
| 749 | if (defined($terms)) { | ||
| 750 | if (ref $terms eq 'ARRAY') { | ||
| 751 | # Used for translating property names deep within the | ||
| 752 | # $terms structure to column names | ||
| 753 | $stmt->column_mutator(sub { | ||
| 754 | my ($col) = @_; | ||
| 755 | return $dbd->db_column_name($tbl, $col); | ||
| 756 | }); | ||
| 757 | $stmt->add_complex_where($terms); | ||
| 758 | $stmt->column_mutator(undef); | ||
| 759 | } | ||
| 760 | else { | ||
| 761 | for my $col (keys %$terms) { | ||
| 762 | my $db_col = $dbd->db_column_name($tbl, $col); | ||
| 763 | $stmt->add_where(join('.', $tbl, $db_col), $terms->{$col}); | ||
| 764 | } | ||
| 765 | } | ||
| 766 | } | ||
| 767 | |||
| 768 | ## Set statement's ORDER clause if any. | ||
| 769 | if ($args->{sort} || $args->{direction}) { | ||
| 770 | my @order; | ||
| 771 | my $sort = $args->{sort} || 'id'; | ||
| 772 | unless (ref $sort) { | ||
| 773 | $sort = [{column => $sort, | ||
| 774 | direction => $args->{direction}||''}]; | ||
| 775 | } | ||
| 776 | |||
| 777 | foreach my $pair (@$sort) { | ||
| 778 | my $col = $dbd->db_column_name($tbl, $pair->{column} || 'id'); | ||
| 779 | my $dir = $pair->{direction} || ''; | ||
| 780 | push @order, {column => $col, | ||
| 781 | desc => ($dir eq 'descend') ? 'DESC' : 'ASC', | ||
| 782 | } | ||
| 783 | } | ||
| 784 | |||
| 785 | $stmt->order(\@order); | ||
| 786 | } | ||
| 787 | } | ||
| 788 | $stmt->limit( $args->{limit} ) if $args->{limit}; | ||
| 789 | $stmt->offset( $args->{offset} ) if $args->{offset}; | ||
| 790 | $stmt->comment( $args->{comment} ) if $args->{comment}; | ||
| 791 | |||
| 792 | if (my $terms = $args->{having}) { | ||
| 793 | for my $col (keys %$terms) { | ||
| 794 | $stmt->add_having($col => $terms->{$col}); | ||
| 795 | } | ||
| 796 | } | ||
| 797 | |||
| 798 | $stmt; | ||
| 799 | } | ||
| 800 | |||
| 801 | sub last_error { | ||
| 802 | my $driver = shift; | ||
| 803 | return $driver->dbd->map_error_code($DBI::err, $DBI::errstr); | ||
| 804 | } | ||
| 805 | |||
| 806 | 1; |