| 1 | package Teng; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | use Carp (); | ||
| 5 | use Class::Load (); | ||
| 6 | use DBI 1.33; | ||
| 7 | use Teng::Row; | ||
| 8 | use Teng::Iterator; | ||
| 9 | use Teng::Schema; | ||
| 10 | use DBIx::TransactionManager 1.06; | ||
| 11 | use Teng::QueryBuilder; | ||
| 12 | use Class::Accessor::Lite | ||
| 13 | rw => [ qw( | ||
| 14 | connect_info | ||
| 15 | on_connect_do | ||
| 16 | schema | ||
| 17 | schema_class | ||
| 18 | suppress_row_objects | ||
| 19 | sql_builder | ||
| 20 | sql_comment | ||
| 21 | owner_pid | ||
| 22 | mode | ||
| 23 | fields_case | ||
| 24 | )] | ||
| 25 | ; | ||
| 26 | |||
| 27 | our $VERSION = '0.14_05'; | ||
| 28 | |||
| 29 | sub load_plugin { | ||
| 30 | my ($class, $pkg, $opt) = @_; | ||
| 31 | $pkg = $pkg =~ s/^\+// ? $pkg : "Teng::Plugin::$pkg"; | ||
| 32 | Class::Load::load_class($pkg); | ||
| 33 | |||
| 34 | no strict 'refs'; | ||
| 35 | for my $meth ( @{"${pkg}::EXPORT"} ) { | ||
| 36 | my $dest_meth = | ||
| 37 | ( $opt->{alias} && $opt->{alias}->{$meth} ) | ||
| 38 | ? $opt->{alias}->{$meth} | ||
| 39 | : $meth; | ||
| 40 | *{"${class}::${dest_meth}"} = $pkg->can($meth); | ||
| 41 | } | ||
| 42 | |||
| 43 | $pkg->init($pkg) if $pkg->can('init'); | ||
| 44 | } | ||
| 45 | |||
| 46 | sub new { | ||
| 47 | my $class = shift; | ||
| 48 | my %args = @_ == 1 ? %{$_[0]} : @_; | ||
| 49 | |||
| 50 | my $self = bless { | ||
| 51 | schema_class => "$class\::Schema", | ||
| 52 | owner_pid => $$, | ||
| 53 | mode => 'ping', | ||
| 54 | fields_case => 'NAME_lc', | ||
| 55 | %args, | ||
| 56 | }, $class; | ||
| 57 | |||
| 58 | my @caller = caller(0); | ||
| 59 | if ($caller[0] ne 'Teng::Schema::Loader' && ! $self->schema) { | ||
| 60 | my $schema_class = $self->{schema_class}; | ||
| 61 | Class::Load::load_class( $schema_class ); | ||
| 62 | my $schema = $schema_class->instance; | ||
| 63 | if (! $schema) { | ||
| 64 | Carp::croak("schema object was not passed, and could not get schema instance from $schema_class"); | ||
| 65 | } | ||
| 66 | $schema->namespace($class); | ||
| 67 | $self->schema( $schema ); | ||
| 68 | } | ||
| 69 | |||
| 70 | unless ($self->connect_info || $self->{dbh}) { | ||
| 71 | Carp::croak("'dbh' or 'connect_info' is required."); | ||
| 72 | } | ||
| 73 | |||
| 74 | if ( ! $self->{dbh} ) { | ||
| 75 | $self->connect; | ||
| 76 | } else { | ||
| 77 | $self->_prepare_from_dbh; | ||
| 78 | } | ||
| 79 | |||
| 80 | return $self; | ||
| 81 | } | ||
| 82 | |||
| 83 | # forcefully connect | ||
| 84 | sub connect { | ||
| 85 | my ($self, @args) = @_; | ||
| 86 | |||
| 87 | $self->in_transaction_check; | ||
| 88 | |||
| 89 | if (@args) { | ||
| 90 | $self->connect_info( \@args ); | ||
| 91 | } | ||
| 92 | my $connect_info = $self->connect_info; | ||
| 93 | $connect_info->[3] = { | ||
| 94 | # basic defaults | ||
| 95 | AutoCommit => 1, | ||
| 96 | PrintError => 0, | ||
| 97 | RaiseError => 1, | ||
| 98 | %{ $connect_info->[3] || {} }, | ||
| 99 | }; | ||
| 100 | |||
| 101 | $self->{dbh} = eval { DBI->connect(@$connect_info) } | ||
| 102 | or Carp::croak("Connection error: " . ($@ || $DBI::errstr)); | ||
| 103 | delete $self->{txn_manager}; | ||
| 104 | |||
| 105 | $self->owner_pid($$); | ||
| 106 | |||
| 107 | $self->_on_connect_do; | ||
| 108 | $self->_prepare_from_dbh; | ||
| 109 | } | ||
| 110 | |||
| 111 | sub _on_connect_do { | ||
| 112 | my $self = shift; | ||
| 113 | |||
| 114 | if ( my $on_connect_do = $self->on_connect_do ) { | ||
| 115 | if (not ref($on_connect_do)) { | ||
| 116 | $self->do($on_connect_do); | ||
| 117 | } elsif (ref($on_connect_do) eq 'CODE') { | ||
| 118 | $on_connect_do->($self); | ||
| 119 | } elsif (ref($on_connect_do) eq 'ARRAY') { | ||
| 120 | $self->do($_) for @$on_connect_do; | ||
| 121 | } else { | ||
| 122 | Carp::croak('Invalid on_connect_do: '.ref($on_connect_do)); | ||
| 123 | } | ||
| 124 | } | ||
| 125 | } | ||
| 126 | |||
| 127 | sub reconnect { | ||
| 128 | my $self = shift; | ||
| 129 | |||
| 130 | $self->in_transaction_check; | ||
| 131 | |||
| 132 | my $dbh = $self->{dbh}; | ||
| 133 | |||
| 134 | $self->disconnect(); | ||
| 135 | |||
| 136 | if ( @_ ) { | ||
| 137 | $self->connect(@_); | ||
| 138 | } | ||
| 139 | else { | ||
| 140 | # Why don't use $dbh->clone({InactiveDestroy => 0}) ? | ||
| 141 | # because, DBI v1.616 clone with \%attr has bug. | ||
| 142 | # my $dbh2 = $dbh->clone({}); | ||
| 143 | # my $dbh3 = $dbh2->clone({}); | ||
| 144 | # $dbh2 is ok, but $dbh3 is undef. | ||
| 145 | $self->{dbh} = eval { $dbh->clone } | ||
| 146 | or Carp::croak("ReConnection error: " . ($@ || $DBI::errstr)); | ||
| 147 | $self->{dbh}->{InactiveDestroy} = 0; | ||
| 148 | |||
| 149 | $self->owner_pid($$); | ||
| 150 | $self->_on_connect_do; | ||
| 151 | $self->_prepare_from_dbh; | ||
| 152 | } | ||
| 153 | } | ||
| 154 | |||
| 155 | sub disconnect { | ||
| 156 | my $self = shift; | ||
| 157 | |||
| 158 | delete $self->{txn_manager}; | ||
| 159 | if ( my $dbh = $self->{dbh} ) { | ||
| 160 | if ( $self->owner_pid && ($self->owner_pid != $$) ) { | ||
| 161 | $dbh->{InactiveDestroy} = 1; | ||
| 162 | } | ||
| 163 | else { | ||
| 164 | $dbh->disconnect; | ||
| 165 | } | ||
| 166 | } | ||
| 167 | $self->owner_pid(undef); | ||
| 168 | } | ||
| 169 | |||
| 170 | sub _prepare_from_dbh { | ||
| 171 | my $self = shift; | ||
| 172 | |||
| 173 | $self->{driver_name} = $self->{dbh}->{Driver}->{Name}; | ||
| 174 | my $builder = $self->{sql_builder}; | ||
| 175 | if (! $builder ) { | ||
| 176 | # XXX Hackish | ||
| 177 | $builder = Teng::QueryBuilder->new(driver => $self->{driver_name} ); | ||
| 178 | $self->sql_builder( $builder ); | ||
| 179 | } | ||
| 180 | $self->{dbh}->{FetchHashKeyName} = $self->{fields_case}; | ||
| 181 | |||
| 182 | $self->{schema}->prepare_from_dbh($self->{dbh}) if $self->{schema}; | ||
| 183 | } | ||
| 184 | |||
| 185 | sub _verify_pid { | ||
| 186 | my $self = shift; | ||
| 187 | |||
| 188 | if ( !$self->owner_pid || $self->owner_pid != $$ ) { | ||
| 189 | $self->reconnect; | ||
| 190 | } | ||
| 191 | elsif ( my $dbh = $self->{dbh} ) { | ||
| 192 | if ( !$dbh->FETCH('Active') ) { | ||
| 193 | $self->reconnect; | ||
| 194 | } | ||
| 195 | elsif ( $self->mode eq 'ping' && !$dbh->ping) { | ||
| 196 | $self->reconnect; | ||
| 197 | } | ||
| 198 | } | ||
| 199 | } | ||
| 200 | |||
| 201 | sub dbh { | ||
| 202 | my $self = shift; | ||
| 203 | |||
| 204 | $self->_verify_pid; | ||
| 205 | $self->{dbh}; | ||
| 206 | } | ||
| 207 | |||
| 208 | sub connected { | ||
| 209 | my $self = shift; | ||
| 210 | my $dbh = $self->{dbh}; | ||
| 211 | return $self->owner_pid && $dbh->ping; | ||
| 212 | } | ||
| 213 | |||
| 214 | sub _execute { | ||
| 215 | my ($self, $sql, $binds) = @_; | ||
| 216 | |||
| 217 | if ($ENV{TENG_SQL_COMMENT} || $self->sql_comment) { | ||
| 218 | my $i = 1; # optimize, as we would *NEVER* be called | ||
| 219 | while ( my (@caller) = caller($i++) ) { | ||
| 220 | next if ( $caller[0]->isa( __PACKAGE__ ) ); | ||
| 221 | my $comment = "$caller[1] at line $caller[2]"; | ||
| 222 | $comment =~ s/\*\// /g; | ||
| 223 | $sql = "/* $comment */\n$sql"; | ||
| 224 | last; | ||
| 225 | } | ||
| 226 | } | ||
| 227 | |||
| 228 | my $sth; | ||
| 229 | eval { $sth = $self->__execute($sql, $binds) }; | ||
| 230 | |||
| 231 | if ($@) { | ||
| 232 | if ( $self->mode eq 'fixup' ) { | ||
| 233 | if ( $self->connected ) { | ||
| 234 | $self->handle_error($sql, $binds, $@); | ||
| 235 | } | ||
| 236 | $self->reconnect; | ||
| 237 | eval { $sth = $self->__execute($sql, $binds) }; | ||
| 238 | if ($@) { | ||
| 239 | $self->handle_error($sql, $binds, $@); | ||
| 240 | } | ||
| 241 | } | ||
| 242 | else { | ||
| 243 | $self->handle_error($sql, $binds, $@); | ||
| 244 | } | ||
| 245 | } | ||
| 246 | |||
| 247 | return $sth; | ||
| 248 | } | ||
| 249 | |||
| 250 | sub __execute { | ||
| 251 | my ($self, $sql, $binds) = @_; | ||
| 252 | |||
| 253 | my $sth = $self->dbh->prepare($sql); | ||
| 254 | my $i = 1; | ||
| 255 | for my $v ( @{ $binds || [] } ) { | ||
| 256 | $sth->bind_param( $i++, ref($v) ? @$v : $v ); | ||
| 257 | } | ||
| 258 | $sth->execute(); | ||
| 259 | |||
| 260 | return $sth; | ||
| 261 | } | ||
| 262 | |||
| 263 | sub _last_insert_id { | ||
| 264 | my ($self, $table_name) = @_; | ||
| 265 | |||
| 266 | my $driver = $self->{driver_name}; | ||
| 267 | if ( $driver eq 'mysql' ) { | ||
| 268 | return $self->dbh->{mysql_insertid}; | ||
| 269 | } elsif ( $driver eq 'Pg' ) { | ||
| 270 | return $self->dbh->last_insert_id( undef, undef, undef, undef,{ sequence => join( '_', $table_name, 'id', 'seq' ) } ); | ||
| 271 | } elsif ( $driver eq 'SQLite' ) { | ||
| 272 | return $self->dbh->func('last_insert_rowid'); | ||
| 273 | } elsif ( $driver eq 'Oracle' ) { | ||
| 274 | return; | ||
| 275 | } else { | ||
| 276 | Carp::croak "Don't know how to get last insert id for $driver"; | ||
| 277 | } | ||
| 278 | } | ||
| 279 | |||
| 280 | sub _bind_sql_type_to_args { | ||
| 281 | my ( $self, $table, $args ) = @_; | ||
| 282 | my $bind_args = {}; | ||
| 283 | |||
| 284 | for my $col (keys %{$args}) { | ||
| 285 | # if $args->{$col} is a ref, it is scalar ref or already | ||
| 286 | # sql type bined parameter. so ignored. | ||
| 287 | $bind_args->{$col} = ref $args->{$col} ? $args->{$col} : [ $args->{$col}, $table->get_sql_type($col) ]; | ||
| 288 | } | ||
| 289 | |||
| 290 | return $bind_args; | ||
| 291 | } | ||
| 292 | |||
| 293 | sub _insert { | ||
| 294 | my ($self, $table_name, $args, $prefix) = @_; | ||
| 295 | |||
| 296 | $prefix ||= 'INSERT INTO'; | ||
| 297 | my $table = $self->schema->get_table($table_name); | ||
| 298 | if (! $table) { | ||
| 299 | local $Carp::CarpLevel = $Carp::CarpLevel + 1; | ||
| 300 | Carp::croak( "Table definition for $table_name does not exist (Did you declare it in our schema?)" ); | ||
| 301 | } | ||
| 302 | |||
| 303 | for my $col (keys %{$args}) { | ||
| 304 | $args->{$col} = $table->call_deflate($col, $args->{$col}); | ||
| 305 | } | ||
| 306 | my $bind_args = $self->_bind_sql_type_to_args( $table, $args ); | ||
| 307 | my ($sql, @binds) = $self->{sql_builder}->insert( $table_name, $bind_args, { prefix => $prefix } ); | ||
| 308 | $self->_execute($sql, \@binds); | ||
| 309 | } | ||
| 310 | |||
| 311 | sub fast_insert { | ||
| 312 | my ($self, $table_name, $args, $prefix) = @_; | ||
| 313 | |||
| 314 | $self->_insert($table_name, $args, $prefix); | ||
| 315 | $self->_last_insert_id($table_name); | ||
| 316 | } | ||
| 317 | |||
| 318 | sub insert { | ||
| 319 | my ($self, $table_name, $args, $prefix) = @_; | ||
| 320 | |||
| 321 | $self->_insert($table_name, $args, $prefix); | ||
| 322 | |||
| 323 | my $table = $self->schema->get_table($table_name); | ||
| 324 | my $pk = $table->primary_keys(); | ||
| 325 | if (scalar(@$pk) == 1 && not defined $args->{$pk->[0]}) { | ||
| 326 | $args->{$pk->[0]} = $self->_last_insert_id($table_name); | ||
| 327 | } | ||
| 328 | |||
| 329 | return $args if $self->suppress_row_objects; | ||
| 330 | |||
| 331 | if (scalar(@$pk) == 1) { | ||
| 332 | return $self->single($table_name, {$pk->[0] => $args->{$pk->[0]}}); | ||
| 333 | } | ||
| 334 | |||
| 335 | $table->row_class->new( | ||
| 336 | { | ||
| 337 | row_data => $args, | ||
| 338 | teng => $self, | ||
| 339 | table_name => $table_name, | ||
| 340 | } | ||
| 341 | ); | ||
| 342 | } | ||
| 343 | |||
| 344 | sub bulk_insert { | ||
| 345 | my ($self, $table_name, $args) = @_; | ||
| 346 | |||
| 347 | return unless scalar(@{$args||[]}); | ||
| 348 | |||
| 349 | my $dbh = $self->dbh; | ||
| 350 | my $can_multi_insert = $dbh->{Driver}->{Name} eq 'mysql' ? 1 | ||
| 351 | : $dbh->{Driver}->{Name} eq 'Pg' | ||
| 352 | && $dbh->{ pg_server_version } >= 82000 ? 1 | ||
| 353 | : 0; | ||
| 354 | |||
| 355 | if ($can_multi_insert) { | ||
| 356 | my $table = $self->schema->get_table($table_name); | ||
| 357 | if (! $table) { | ||
| 358 | Carp::croak( "Table definition for $table_name does not exist (Did you declare it in our schema?)" ); | ||
| 359 | } | ||
| 360 | |||
| 361 | if ( $table->has_deflators ) { | ||
| 362 | for my $row (@$args) { | ||
| 363 | for my $col (keys %{$row}) { | ||
| 364 | $row->{$col} = $table->call_deflate($col, $row->{$col}); | ||
| 365 | } | ||
| 366 | } | ||
| 367 | } | ||
| 368 | |||
| 369 | my ($sql, @binds) = $self->sql_builder->insert_multi( $table_name, $args ); | ||
| 370 | $self->_execute($sql, \@binds); | ||
| 371 | } else { | ||
| 372 | # use transaction for better performance and atomicity. | ||
| 373 | my $txn = $self->txn_scope(); | ||
| 374 | for my $arg (@$args) { | ||
| 375 | # do not run trigger for consistency with mysql. | ||
| 376 | $self->insert($table_name, $arg); | ||
| 377 | } | ||
| 378 | $txn->commit; | ||
| 379 | } | ||
| 380 | } | ||
| 381 | |||
| 382 | sub _update { | ||
| 383 | my ($self, $table_name, $args, $where) = @_; | ||
| 384 | |||
| 385 | my ($sql, @binds) = $self->{sql_builder}->update( $table_name, $args, $where ); | ||
| 386 | my $sth = $self->_execute($sql, \@binds); | ||
| 387 | my $rows = $sth->rows; | ||
| 388 | $sth->finish; | ||
| 389 | |||
| 390 | $rows; | ||
| 391 | } | ||
| 392 | |||
| 393 | sub update { | ||
| 394 | my ($self, $table_name, $args, $where) = @_; | ||
| 395 | |||
| 396 | my $table = $self->schema->get_table($table_name); | ||
| 397 | if (! $table) { | ||
| 398 | Carp::croak( "Table definition for $table_name does not exist (Did you declare it in our schema?)" ); | ||
| 399 | } | ||
| 400 | |||
| 401 | for my $col (keys %{$args}) { | ||
| 402 | $args->{$col} = $table->call_deflate($col, $args->{$col}); | ||
| 403 | } | ||
| 404 | |||
| 405 | $self->_update($table_name, $self->_bind_sql_type_to_args( $table, $args ), $where); | ||
| 406 | } | ||
| 407 | |||
| 408 | sub delete { | ||
| 409 | my ($self, $table_name, $where) = @_; | ||
| 410 | |||
| 411 | my ($sql, @binds) = $self->{sql_builder}->delete( $table_name, $where ); | ||
| 412 | my $sth = $self->_execute($sql, \@binds); | ||
| 413 | my $rows = $sth->rows; | ||
| 414 | $sth->finish; | ||
| 415 | |||
| 416 | $rows; | ||
| 417 | } | ||
| 418 | |||
| 419 | #-------------------------------------------------------------------------------- | ||
| 420 | # for transaction | ||
| 421 | sub txn_manager { | ||
| 422 | my $self = shift; | ||
| 423 | $self->_verify_pid; | ||
| 424 | $self->{txn_manager} ||= DBIx::TransactionManager->new($self->dbh); | ||
| 425 | } | ||
| 426 | |||
| 427 | sub in_transaction_check { | ||
| 428 | my $self = shift; | ||
| 429 | |||
| 430 | return unless $self->{txn_manager}; | ||
| 431 | |||
| 432 | if ( my $info = $self->{txn_manager}->in_transaction ) { | ||
| 433 | my $caller = $info->{caller}; | ||
| 434 | my $pid = $info->{pid}; | ||
| 435 | Carp::confess("Detected transaction during a connect operation (last known transaction at $caller->[1] line $caller->[2], pid $pid). Refusing to proceed at"); | ||
| 436 | } | ||
| 437 | } | ||
| 438 | |||
| 439 | sub txn_scope { | ||
| 440 | my $self = shift; | ||
| 441 | my @caller = caller(); | ||
| 442 | |||
| 443 | my $scope; | ||
| 444 | if ( $self->mode eq 'fixup' ) { | ||
| 445 | eval { $scope = $self->txn_manager->txn_scope(caller => \@caller) }; | ||
| 446 | if ( $@ ) { | ||
| 447 | if ( $self->connected ) { | ||
| 448 | die $@; | ||
| 449 | } | ||
| 450 | $self->reconnect; | ||
| 451 | $scope = $self->txn_manager->txn_scope(caller => \@caller); | ||
| 452 | } | ||
| 453 | } | ||
| 454 | else { | ||
| 455 | $scope = $self->txn_manager->txn_scope(caller => \@caller); | ||
| 456 | } | ||
| 457 | return $scope; | ||
| 458 | } | ||
| 459 | |||
| 460 | sub txn_begin { | ||
| 461 | my $self = shift; | ||
| 462 | if ( $self->mode eq 'fixup' ) { | ||
| 463 | eval { $self->txn_manager->txn_begin }; | ||
| 464 | if ( $@ ) { | ||
| 465 | if ( $self->connected ) { | ||
| 466 | die $@; | ||
| 467 | } | ||
| 468 | $self->reconnect; | ||
| 469 | $self->txn_manager->txn_begin; | ||
| 470 | } | ||
| 471 | } | ||
| 472 | else { | ||
| 473 | $self->txn_manager->txn_begin; | ||
| 474 | } | ||
| 475 | } | ||
| 476 | sub txn_rollback { $_[0]->txn_manager->txn_rollback } | ||
| 477 | sub txn_commit { $_[0]->txn_manager->txn_commit } | ||
| 478 | sub txn_end { $_[0]->txn_manager->txn_end } | ||
| 479 | |||
| 480 | #-------------------------------------------------------------------------------- | ||
| 481 | |||
| 482 | sub do { | ||
| 483 | my ($self, $sql, $attr, @bind_vars) = @_; | ||
| 484 | my $ret; | ||
| 485 | eval { $ret = $self->dbh->do($sql, $attr, @bind_vars) }; | ||
| 486 | if ($@) { | ||
| 487 | $self->handle_error($sql, @bind_vars ? \@bind_vars : '', $@); | ||
| 488 | } | ||
| 489 | $ret; | ||
| 490 | } | ||
| 491 | |||
| 492 | sub _get_select_columns { | ||
| 493 | my ($self, $table, $opt) = @_; | ||
| 494 | |||
| 495 | return $opt->{'+columns'} | ||
| 496 | ? [@{$table->{escaped_columns}{$self->{driver_name}}}, @{$opt->{'+columns'}}] | ||
| 497 | : ($opt->{columns} || $table->{escaped_columns}{$self->{driver_name}}) | ||
| 498 | ; | ||
| 499 | } | ||
| 500 | |||
| 501 | sub search { | ||
| 502 | my ($self, $table_name, $where, $opt) = @_; | ||
| 503 | |||
| 504 | my $table = $self->{schema}->get_table( $table_name ); | ||
| 505 | if (! $table) { | ||
| 506 | Carp::croak("No such table $table_name"); | ||
| 507 | } | ||
| 508 | |||
| 509 | my ($sql, @binds) = $self->{sql_builder}->select( | ||
| 510 | $table_name, | ||
| 511 | $self->_get_select_columns($table, $opt), | ||
| 512 | $where, | ||
| 513 | $opt | ||
| 514 | ); | ||
| 515 | |||
| 516 | $self->search_by_sql($sql, \@binds, $table_name); | ||
| 517 | } | ||
| 518 | |||
| 519 | sub search_named { | ||
| 520 | my ($self, $sql, $args, $table_name) = @_; | ||
| 521 | |||
| 522 | my %named_bind = %{$args}; | ||
| 523 | my @bind; | ||
| 524 | $sql =~ s{:([A-Za-z_][A-Za-z0-9_]*)}{ | ||
| 525 | Carp::croak("'$1' does not exist in bind hash") if !exists $named_bind{$1}; | ||
| 526 | if ( ref $named_bind{$1} && ref $named_bind{$1} eq "ARRAY" ) { | ||
| 527 | push @bind, @{ $named_bind{$1} }; | ||
| 528 | my $tmp = join ',', map { '?' } @{ $named_bind{$1} }; | ||
| 529 | "( $tmp )"; | ||
| 530 | } else { | ||
| 531 | push @bind, $named_bind{$1}; | ||
| 532 | '?' | ||
| 533 | } | ||
| 534 | }ge; | ||
| 535 | |||
| 536 | $self->search_by_sql($sql, \@bind, $table_name); | ||
| 537 | } | ||
| 538 | |||
| 539 | sub single { | ||
| 540 | my ($self, $table_name, $where, $opt) = @_; | ||
| 541 | |||
| 542 | $opt->{limit} = 1; | ||
| 543 | |||
| 544 | my $table = $self->{schema}->get_table( $table_name ); | ||
| 545 | Carp::croak("No such table $table_name") unless $table; | ||
| 546 | |||
| 547 | my ($sql, @binds) = $self->{sql_builder}->select( | ||
| 548 | $table_name, | ||
| 549 | $self->_get_select_columns($table, $opt), | ||
| 550 | $where, | ||
| 551 | $opt | ||
| 552 | ); | ||
| 553 | my $sth = $self->_execute($sql, \@binds); | ||
| 554 | my $row = $sth->fetchrow_hashref($self->{fields_case}); | ||
| 555 | |||
| 556 | return unless $row; | ||
| 557 | return $row if $self->{suppress_row_objects}; | ||
| 558 | |||
| 559 | $table->{row_class}->new( | ||
| 560 | { | ||
| 561 | sql => $sql, | ||
| 562 | row_data => $row, | ||
| 563 | teng => $self, | ||
| 564 | table => $table, | ||
| 565 | table_name => $table_name, | ||
| 566 | } | ||
| 567 | ); | ||
| 568 | } | ||
| 569 | |||
| 570 | sub search_by_sql { | ||
| 571 | my ($self, $sql, $bind, $table_name) = @_; | ||
| 572 | |||
| 573 | $table_name ||= $self->_guess_table_name( $sql ); | ||
| 574 | my $sth = $self->_execute($sql, $bind); | ||
| 575 | my $itr = Teng::Iterator->new( | ||
| 576 | teng => $self, | ||
| 577 | sth => $sth, | ||
| 578 | sql => $sql, | ||
| 579 | row_class => $self->{schema}->get_row_class($table_name), | ||
| 580 | table => $self->{schema}->get_table( $table_name ), | ||
| 581 | table_name => $table_name, | ||
| 582 | suppress_object_creation => $self->{suppress_row_objects}, | ||
| 583 | ); | ||
| 584 | return wantarray ? $itr->all : $itr; | ||
| 585 | } | ||
| 586 | |||
| 587 | sub _guess_table_name { | ||
| 588 | my ($class, $sql) = @_; | ||
| 589 | |||
| 590 | if ($sql =~ /\sfrom\s+["`]?([\w]+)["`]?\s*/si) { | ||
| 591 | return $1; | ||
| 592 | } | ||
| 593 | return; | ||
| 594 | } | ||
| 595 | |||
| 596 | sub handle_error { | ||
| 597 | my ($self, $stmt, $bind, $reason) = @_; | ||
| 598 | require Data::Dumper; | ||
| 599 | |||
| 600 | $stmt =~ s/\n/\n /gm; | ||
| 601 | Carp::croak sprintf <<"TRACE", $reason, $stmt, Data::Dumper::Dumper($bind); | ||
| 602 | @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | ||
| 603 | @@@@@ Teng 's Exception @@@@@ | ||
| 604 | Reason : %s | ||
| 605 | SQL : %s | ||
| 606 | BIND : %s | ||
| 607 | @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | ||
| 608 | TRACE | ||
| 609 | } | ||
| 610 | |||
| 611 | sub DESTROY { | ||
| 612 | my $self = shift; | ||
| 613 | |||
| 614 | if ( $self->owner_pid and $self->owner_pid != $$ and my $dbh = $self->{dbh} ) { | ||
| 615 | $dbh->{InactiveDestroy} = 1; | ||
| 616 | } | ||
| 617 | } | ||
| 618 | |||
| 619 | 1; | ||
| 620 | |||
| 621 | __END__ | ||
| 622 | =head1 NAME | ||
| 623 | |||
| 624 | Teng - very simple DBI wrapper/ORMapper | ||
| 625 | |||
| 626 | =head1 SYNOPSIS | ||
| 627 | |||
| 628 | my $db = MyDB->new({ connect_info => [ 'dbi:SQLite:' ] }); | ||
| 629 | my $row = $db->insert( 'table' => { | ||
| 630 | col1 => $value | ||
| 631 | } ); | ||
| 632 | |||
| 633 | =head1 DESCRIPTION | ||
| 634 | |||
| 635 | Teng is very simple DBI wrapper and simple O/R Mapper. | ||
| 636 | It aims to be lightweight, with minimal dependencies so it's easier to install. | ||
| 637 | |||
| 638 | B<THE SOFTWARE IS IT'S IN ALPHA QUALITY. IT MAY CHANGE THE API WITHOUT NOTICE.> | ||
| 639 | |||
| 640 | =head1 BASIC USAGE | ||
| 641 | |||
| 642 | create your db model base class. | ||
| 643 | |||
| 644 | package Your::Model; | ||
| 645 | use parent 'Teng'; | ||
| 646 | 1; | ||
| 647 | |||
| 648 | create your db schema class. | ||
| 649 | See Teng::Schema for docs on defining schema class. | ||
| 650 | |||
| 651 | package Your::Model::Schema; | ||
| 652 | use Teng::Schema::Declare; | ||
| 653 | table { | ||
| 654 | name 'user'; | ||
| 655 | pk 'id'; | ||
| 656 | columns qw( foo bar baz ); | ||
| 657 | }; | ||
| 658 | 1; | ||
| 659 | |||
| 660 | in your script. | ||
| 661 | |||
| 662 | use Your::Model; | ||
| 663 | |||
| 664 | my $teng = Your::Model->new(\%args); | ||
| 665 | # insert new record. | ||
| 666 | my $row = $teng->insert('user', | ||
| 667 | { | ||
| 668 | id => 1, | ||
| 669 | } | ||
| 670 | ); | ||
| 671 | $row->update({name => 'nekokak'}); | ||
| 672 | |||
| 673 | $row = $teng->search_by_sql(q{SELECT id, name FROM user WHERE id = ?}, [ 1 ]); | ||
| 674 | $row->delete(); | ||
| 675 | |||
| 676 | =head1 ARCHITECTURE | ||
| 677 | |||
| 678 | Teng classes are comprised of three distinct components: | ||
| 679 | |||
| 680 | =head2 MODEL | ||
| 681 | |||
| 682 | The C<model> is where you say | ||
| 683 | |||
| 684 | package MyApp::Model; | ||
| 685 | use parent 'Teng'; | ||
| 686 | |||
| 687 | This is the entry point to using Teng. You connect, insert, update, delete, select stuff using this object. | ||
| 688 | |||
| 689 | =head2 SCHEMA | ||
| 690 | |||
| 691 | The C<schema> is a simple class that describes your table definitions. Note that this is different from DBIx::Class terms. | ||
| 692 | DBIC's schema is equivalent to Teng's model + schema, where the actual schema information is scattered across the result classes. | ||
| 693 | |||
| 694 | In Teng, you simply use Teng::Schema's domain specific languaage to define a set of tables | ||
| 695 | |||
| 696 | package MyApp::Model::Schema; | ||
| 697 | use Teng::Schema::Declare; | ||
| 698 | |||
| 699 | table { | ||
| 700 | name $table_name; | ||
| 701 | pk $primary_key_column; | ||
| 702 | columns qw( | ||
| 703 | column1 | ||
| 704 | column2 | ||
| 705 | column3 | ||
| 706 | ); | ||
| 707 | } | ||
| 708 | |||
| 709 | ... and other tables ... | ||
| 710 | |||
| 711 | =head2 ROW | ||
| 712 | |||
| 713 | Unlike DBIx::Class, you don't need to have a set of classes that represent a row type (i.e. "result" classes in DBIC terms). | ||
| 714 | In Teng, the row objects are blessed into anonymous classes that inherit from Teng::Row, | ||
| 715 | so you don't have to create these classes if you just want to use some simple queries. | ||
| 716 | |||
| 717 | If you want to define methods to be performed by your row objects, simply create a row class like so: | ||
| 718 | |||
| 719 | package MyApp::Model::Row::Camelizedtable_name; | ||
| 720 | use parent qw(Teng::Row); | ||
| 721 | |||
| 722 | Note that your table name will be camelized. | ||
| 723 | |||
| 724 | =head1 METHODS | ||
| 725 | |||
| 726 | Teng provides a number of methods to all your classes, | ||
| 727 | |||
| 728 | =over | ||
| 729 | |||
| 730 | =item $teng = Teng->new(\%args) | ||
| 731 | |||
| 732 | Creates a new Teng instance. | ||
| 733 | |||
| 734 | # connect new database connection. | ||
| 735 | my $db = Your::Model->new( | ||
| 736 | connect_info => [ $dsn, $username, $password, \%connect_options ] | ||
| 737 | ); | ||
| 738 | |||
| 739 | Arguments can be: | ||
| 740 | |||
| 741 | =over | ||
| 742 | |||
| 743 | =item * C<connect_info> | ||
| 744 | |||
| 745 | Specifies the information required to connect to the database. | ||
| 746 | The argument should be a reference to a array in the form: | ||
| 747 | |||
| 748 | [ $dsn, $user, $password, \%options ] | ||
| 749 | |||
| 750 | You must pass C<connect_info> or C<dbh> to the constructor. | ||
| 751 | |||
| 752 | =item * C<dbh> | ||
| 753 | |||
| 754 | Specifies the database handle to use. | ||
| 755 | |||
| 756 | =item * C<mode> | ||
| 757 | |||
| 758 | =over | ||
| 759 | |||
| 760 | =item * C<ping(default)> | ||
| 761 | |||
| 762 | reconnect at dbh->ping fail each execute. | ||
| 763 | |||
| 764 | =item * C<fixup> | ||
| 765 | |||
| 766 | reconnect at fail execute. | ||
| 767 | |||
| 768 | =item * C<no_ping> | ||
| 769 | |||
| 770 | no auto reconnect. | ||
| 771 | |||
| 772 | =item * C<fields_case> | ||
| 773 | |||
| 774 | specific DBI.pm's FetchHashKeyName. | ||
| 775 | |||
| 776 | =back | ||
| 777 | |||
| 778 | =item * C<schema> | ||
| 779 | |||
| 780 | Specifies the Teng::Schema instance to use. | ||
| 781 | If not specified, the value specified in C<schema_class> is loaded and | ||
| 782 | instantiated for you. | ||
| 783 | |||
| 784 | =item * C<schema_class> | ||
| 785 | |||
| 786 | Specifies the schema class to use. | ||
| 787 | By default {YOUR_MODEL_CLASS}::Schema is used. | ||
| 788 | |||
| 789 | =item * C<suppress_row_objects> | ||
| 790 | |||
| 791 | Specifies the row object creation mode. By default this value is C<false>. | ||
| 792 | If you specifies this to a C<true> value, no row object will be created when | ||
| 793 | a C<SELECT> statement is issued.. | ||
| 794 | |||
| 795 | =item * C<sql_builder> | ||
| 796 | |||
| 797 | Speficies the SQL builder object. By default SQL::Maker is used, and as such, | ||
| 798 | if you provide your own SQL builder the interface needs to be compatible | ||
| 799 | with SQL::Maker. | ||
| 800 | |||
| 801 | =back | ||
| 802 | |||
| 803 | =item $row = $teng->insert($table_name, \%row_data) | ||
| 804 | |||
| 805 | Inserts a new record. Returns the inserted row object. | ||
| 806 | |||
| 807 | my $row = $teng->insert('user',{ | ||
| 808 | id => 1, | ||
| 809 | name => 'nekokak', | ||
| 810 | }); | ||
| 811 | |||
| 812 | If a primary key is available, it will be fetched after the insert -- so | ||
| 813 | an INSERT followed by SELECT is performed. If you do not want this, use | ||
| 814 | C<fast_insert>. | ||
| 815 | |||
| 816 | =item $last_insert_id = $teng->fast_insert($table_name, \%row_data); | ||
| 817 | |||
| 818 | insert new record and get last_insert_id. | ||
| 819 | |||
| 820 | no creation row object. | ||
| 821 | |||
| 822 | =item $teng->bulk_insert($table_name, \@rows_data) | ||
| 823 | |||
| 824 | Accepts either an arrayref of hashrefs. | ||
| 825 | each hashref should be a structure suitable | ||
| 826 | forsubmitting to a Your::Model->insert(...) method. | ||
| 827 | |||
| 828 | insert many record by bulk. | ||
| 829 | |||
| 830 | example: | ||
| 831 | |||
| 832 | Your::Model->bulk_insert('user',[ | ||
| 833 | { | ||
| 834 | id => 1, | ||
| 835 | name => 'nekokak', | ||
| 836 | }, | ||
| 837 | { | ||
| 838 | id => 2, | ||
| 839 | name => 'yappo', | ||
| 840 | }, | ||
| 841 | { | ||
| 842 | id => 3, | ||
| 843 | name => 'walf443', | ||
| 844 | }, | ||
| 845 | ]); | ||
| 846 | |||
| 847 | =item $update_row_count = $teng->update($table_name, \%update_row_data, [\%update_condition]) | ||
| 848 | |||
| 849 | Calls UPDATE on C<$table_name>, with values specified in C<%update_ro_data>, and returns the number of rows updated. You may optionally specify C<%update_condition> to create a conditional update query. | ||
| 850 | |||
| 851 | my $update_row_count = $teng->update('user', | ||
| 852 | { | ||
| 853 | name => 'nomaneko', | ||
| 854 | }, | ||
| 855 | { | ||
| 856 | id => 1 | ||
| 857 | } | ||
| 858 | ); | ||
| 859 | # Executes UPDATE user SET name = 'nomaneko' WHERE id = 1 | ||
| 860 | |||
| 861 | You can also call update on a row object: | ||
| 862 | |||
| 863 | my $row = $teng->single('user',{id => 1}); | ||
| 864 | $row->update({name => 'nomaneko'}); | ||
| 865 | |||
| 866 | =item $delete_row_count = $teng->delete($table, \%delete_condition) | ||
| 867 | |||
| 868 | Deletes the specified record(s) from C<$table> and returns the number of rows deleted. You may optionally specify C<%delete_condition> to create a conditional delete query. | ||
| 869 | |||
| 870 | my $rows_deleted = $teng->delete( 'user', { | ||
| 871 | id => 1 | ||
| 872 | } ); | ||
| 873 | # Executes DELETE FROM user WHERE id = 1 | ||
| 874 | |||
| 875 | You can also call delete on a row object: | ||
| 876 | |||
| 877 | my $row = $teng->single('user', {id => 1}); | ||
| 878 | $row->delete | ||
| 879 | |||
| 880 | =item $itr = $teng->search($table_name, [\%search_condition, [\%search_attr]]) | ||
| 881 | |||
| 882 | simple search method. | ||
| 883 | search method get Teng::Iterator's instance object. | ||
| 884 | |||
| 885 | see L<Teng::Iterator> | ||
| 886 | |||
| 887 | get iterator: | ||
| 888 | |||
| 889 | my $itr = $teng->search('user',{id => 1},{order_by => 'id'}); | ||
| 890 | |||
| 891 | get rows: | ||
| 892 | |||
| 893 | my @rows = $teng->search('user',{id => 1},{order_by => 'id'}); | ||
| 894 | |||
| 895 | =item $row = $teng->single($table_name, \%search_condition) | ||
| 896 | |||
| 897 | get one record. | ||
| 898 | give back one case of the beginning when it is acquired plural records by single method. | ||
| 899 | |||
| 900 | my $row = $teng->single('user',{id =>1}); | ||
| 901 | |||
| 902 | =item $itr = $teng->search_named($sql, [\%bind_values, [$table_name]]) | ||
| 903 | |||
| 904 | execute named query | ||
| 905 | |||
| 906 | my $itr = $teng->search_named(q{SELECT * FROM user WHERE id = :id}, {id => 1}); | ||
| 907 | |||
| 908 | If you give ArrayRef to value, that is expanded to "(?,?,?,?)" in SQL. | ||
| 909 | It's useful in case use IN statement. | ||
| 910 | |||
| 911 | # SELECT * FROM user WHERE id IN (?,?,?); | ||
| 912 | # bind [1,2,3] | ||
| 913 | my $itr = $teng->search_named(q{SELECT * FROM user WHERE id IN :ids}, {id => [1, 2, 3]}); | ||
| 914 | |||
| 915 | If you give table_name. It is assumed the hint that makes Teng::Row's Object. | ||
| 916 | |||
| 917 | =item $itr = $teng->search_by_sql($sql, [\@bind_vlues, [$table_name]]) | ||
| 918 | |||
| 919 | execute your SQL | ||
| 920 | |||
| 921 | my $itr = $teng->search_by_sql(q{ | ||
| 922 | SELECT | ||
| 923 | id, name | ||
| 924 | FROM | ||
| 925 | user | ||
| 926 | WHERE | ||
| 927 | id = ? | ||
| 928 | },[ 1 ]); | ||
| 929 | |||
| 930 | If $table is specified, it set table infomation to result iterator. | ||
| 931 | So, you can use table row class to search_by_sql result. | ||
| 932 | |||
| 933 | =item $teng->txn_scope | ||
| 934 | |||
| 935 | Creates a new transaction scope guard object. | ||
| 936 | |||
| 937 | do { | ||
| 938 | my $txn = $teng->txn_scope; | ||
| 939 | |||
| 940 | $row->update({foo => 'bar'}); | ||
| 941 | |||
| 942 | $txn->commit; | ||
| 943 | } | ||
| 944 | |||
| 945 | If an exception occurs, or the guard object otherwise leaves the scope | ||
| 946 | before C<< $txn->commit >> is called, the transaction will be rolled | ||
| 947 | back by an explicit L</txn_rollback> call. In essence this is akin to | ||
| 948 | using a L</txn_begin>/L</txn_commit> pair, without having to worry | ||
| 949 | about calling L</txn_rollback> at the right places. Note that since there | ||
| 950 | is no defined code closure, there will be no retries and other magic upon | ||
| 951 | database disconnection. | ||
| 952 | |||
| 953 | =item $txn_manager = $teng->txn_manager | ||
| 954 | |||
| 955 | Get the DBIx::TransactionManager instance. | ||
| 956 | |||
| 957 | =item $teng->txn_begin | ||
| 958 | |||
| 959 | start new transaction. | ||
| 960 | |||
| 961 | =item $teng->txn_commit | ||
| 962 | |||
| 963 | commit transaction. | ||
| 964 | |||
| 965 | =item $teng->txn_rollback | ||
| 966 | |||
| 967 | rollback transaction. | ||
| 968 | |||
| 969 | =item $teng->txn_end | ||
| 970 | |||
| 971 | finish transaction. | ||
| 972 | |||
| 973 | =item $teng->do($sql, [\%option, \@bind_values]) | ||
| 974 | |||
| 975 | Execute the query specified by C<$sql>, using C<%option> and C<@bind_values> as necessary. This pretty much a wrapper around L<http://search.cpan.org/dist/DBI/DBI.pm#do> | ||
| 976 | |||
| 977 | =item $teng->dbh | ||
| 978 | |||
| 979 | get database handle. | ||
| 980 | |||
| 981 | =item $teng->connect(\@connect_info) | ||
| 982 | |||
| 983 | connect database handle. | ||
| 984 | |||
| 985 | connect_info is [$dsn, $user, $password, $options]. | ||
| 986 | |||
| 987 | If you give \@connect_info, create new database connection. | ||
| 988 | |||
| 989 | =item $teng->disconnect() | ||
| 990 | |||
| 991 | Disconnects from the currently connected database. | ||
| 992 | |||
| 993 | =item $teng->suppress_row_objects($flag) | ||
| 994 | |||
| 995 | set row object creation mode. | ||
| 996 | |||
| 997 | =item $teng->load_plugin(); | ||
| 998 | |||
| 999 | load Teng::Plugin's | ||
| 1000 | |||
| 1001 | =item $teng->handle_error | ||
| 1002 | |||
| 1003 | handling error method. | ||
| 1004 | |||
| 1005 | =item How do you use display the profiling result? | ||
| 1006 | |||
| 1007 | use L<Devel::KYTProf>. | ||
| 1008 | |||
| 1009 | =back | ||
| 1010 | |||
| 1011 | =head1 TRIGGERS | ||
| 1012 | |||
| 1013 | Teng does not support triggers (NOTE: do not confuse it with SQL triggers - we're talking about Perl level triggers). If you really want to hook into the various methods, use something like L<Moose>, L<Mouse>, and L<Class::Method::Modifiers>. | ||
| 1014 | |||
| 1015 | =head1 SEE ALSO | ||
| 1016 | |||
| 1017 | =head2 Fork | ||
| 1018 | |||
| 1019 | This module was forked from L<DBIx::Skinny>, around version 0.0732. | ||
| 1020 | many incompatible changes have been made. | ||
| 1021 | |||
| 1022 | =head1 BUGS AND LIMITATIONS | ||
| 1023 | |||
| 1024 | No bugs have been reported. | ||
| 1025 | |||
| 1026 | =head1 AUTHORS | ||
| 1027 | |||
| 1028 | Atsushi Kobayashi C<< <nekokak __at__ gmail.com> >> | ||
| 1029 | |||
| 1030 | Tokuhiro Matsuno E<lt>tokuhirom@gmail.comE<gt> | ||
| 1031 | |||
| 1032 | Daisuke Maki C<< <daisuke@endeworks.jp> >> | ||
| 1033 | |||
| 1034 | =head1 SUPPORT | ||
| 1035 | |||
| 1036 | irc: #dbix-skinny@irc.perl.org | ||
| 1037 | |||
| 1038 | ML: http://groups.google.com/group/dbix-skinny | ||
| 1039 | |||
| 1040 | =head1 REPOSITORY | ||
| 1041 | |||
| 1042 | git clone git://github.com/nekokak/p5-teng.git | ||
| 1043 | |||
| 1044 | =head1 LICENCE AND COPYRIGHT | ||
| 1045 | |||
| 1046 | Copyright (c) 2010, the Teng L</AUTHOR>. All rights reserved. | ||
| 1047 | |||
| 1048 | This module is free software; you can redistribute it and/or | ||
| 1049 | modify it under the same terms as Perl itself. See L<perlartistic>. | ||
| 1050 | |||
| 1051 | =cut | ||
| 1052 |