Merge 'DBIx-Class-current' into 'trunk'
[dbsrgits/DBIx-Class-Historic.git] / lib / DBIx / Class / Storage / DBI.pm
CommitLineData
8b445e33 1package DBIx::Class::Storage::DBI;
2
a62cf8d4 3use base 'DBIx::Class::Storage';
4
20a2c954 5use strict;
6use warnings;
8b445e33 7use DBI;
aeaf3ce2 8use SQL::Abstract::Limit;
28927b50 9use DBIx::Class::Storage::DBI::Cursor;
92b858c9 10use IO::File;
701da8c4 11use Carp::Clan qw/DBIx::Class/;
8b445e33 12
bd7efd39 13BEGIN {
14
cb5f2eea 15package DBIC::SQL::Abstract; # Would merge upstream, but nate doesn't reply :(
bd7efd39 16
17use base qw/SQL::Abstract::Limit/;
18
54540863 19sub select {
20 my ($self, $table, $fields, $where, $order, @rest) = @_;
21 @rest = (-1) unless defined $rest[0];
8839560b 22 local $self->{having_bind} = [];
23 my ($sql, @ret) = $self->SUPER::select($table,
24 $self->_recurse_fields($fields), $where, $order, @rest);
25 return wantarray ? ($sql, @ret, @{$self->{having_bind}}) : $sql;
54540863 26}
27
28sub _emulate_limit {
29 my $self = shift;
30 if ($_[3] == -1) {
31 return $_[1].$self->_order_by($_[2]);
32 } else {
33 return $self->SUPER::_emulate_limit(@_);
34 }
35}
36
37sub _recurse_fields {
38 my ($self, $fields) = @_;
39 my $ref = ref $fields;
40 return $self->_quote($fields) unless $ref;
41 return $$fields if $ref eq 'SCALAR';
42
43 if ($ref eq 'ARRAY') {
44 return join(', ', map { $self->_recurse_fields($_) } @$fields);
45 } elsif ($ref eq 'HASH') {
46 foreach my $func (keys %$fields) {
47 return $self->_sqlcase($func)
48 .'( '.$self->_recurse_fields($fields->{$func}).' )';
49 }
50 }
51}
52
53sub _order_by {
54 my $self = shift;
55 my $ret = '';
8839560b 56 my @extra;
54540863 57 if (ref $_[0] eq 'HASH') {
58 if (defined $_[0]->{group_by}) {
59 $ret = $self->_sqlcase(' group by ')
60 .$self->_recurse_fields($_[0]->{group_by});
61 }
8839560b 62 if (defined $_[0]->{having}) {
63 my $frag;
64 ($frag, @extra) = $self->_recurse_where($_[0]->{having});
65 push(@{$self->{having_bind}}, @extra);
66 $ret .= $self->_sqlcase(' having ').$frag;
67 }
54540863 68 if (defined $_[0]->{order_by}) {
69 $ret .= $self->SUPER::_order_by($_[0]->{order_by});
70 }
71 } else {
72 $ret = $self->SUPER::_order_by(@_);
73 }
74 return $ret;
75}
76
f48dd03f 77sub _order_directions {
78 my ($self, $order) = @_;
79 $order = $order->{order_by} if ref $order eq 'HASH';
80 return $self->SUPER::_order_directions($order);
81}
82
2a816814 83sub _table {
bd7efd39 84 my ($self, $from) = @_;
85 if (ref $from eq 'ARRAY') {
86 return $self->_recurse_from(@$from);
87 } elsif (ref $from eq 'HASH') {
88 return $self->_make_as($from);
89 } else {
90 return $from;
91 }
92}
93
94sub _recurse_from {
95 my ($self, $from, @join) = @_;
96 my @sqlf;
97 push(@sqlf, $self->_make_as($from));
98 foreach my $j (@join) {
99 my ($to, $on) = @$j;
73856587 100
54540863 101 # check whether a join type exists
102 my $join_clause = '';
103 if (ref($to) eq 'HASH' and exists($to->{-join_type})) {
104 $join_clause = ' '.uc($to->{-join_type}).' JOIN ';
105 } else {
106 $join_clause = ' JOIN ';
107 }
73856587 108 push(@sqlf, $join_clause);
109
bd7efd39 110 if (ref $to eq 'ARRAY') {
111 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
112 } else {
96cdbbab 113 push(@sqlf, $self->_make_as($to));
bd7efd39 114 }
115 push(@sqlf, ' ON ', $self->_join_condition($on));
116 }
117 return join('', @sqlf);
118}
119
120sub _make_as {
121 my ($self, $from) = @_;
54540863 122 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) }
2a816814 123 reverse each %{$self->_skip_options($from)});
73856587 124}
125
126sub _skip_options {
54540863 127 my ($self, $hash) = @_;
128 my $clean_hash = {};
129 $clean_hash->{$_} = $hash->{$_}
130 for grep {!/^-/} keys %$hash;
131 return $clean_hash;
bd7efd39 132}
133
134sub _join_condition {
135 my ($self, $cond) = @_;
5efe4c79 136 if (ref $cond eq 'HASH') {
137 my %j;
138 for (keys %$cond) { my $x = '= '.$self->_quote($cond->{$_}); $j{$_} = \$x; };
139 return $self->_recurse_where(\%j);
140 } elsif (ref $cond eq 'ARRAY') {
141 return join(' OR ', map { $self->_join_condition($_) } @$cond);
142 } else {
143 die "Can't handle this yet!";
144 }
bd7efd39 145}
146
2a816814 147sub _quote {
148 my ($self, $label) = @_;
149 return '' unless defined $label;
41728a6e 150 return $label unless $self->{quote_char};
2a816814 151 return $self->SUPER::_quote($label);
152}
153
f66596f9 154sub _RowNum {
155 my $self = shift;
156 my $c;
157 $_[0] =~ s/SELECT (.*?) FROM/
158 'SELECT '.join(', ', map { $_.' AS col'.++$c } split(', ', $1)).' FROM'/e;
159 $self->SUPER::_RowNum(@_);
160}
161
7be93b07 162# Accessor for setting limit dialect. This is useful
163# for JDBC-bridge among others where the remote SQL-dialect cannot
164# be determined by the name of the driver alone.
165#
166sub limit_dialect {
167 my $self = shift;
168 $self->{limit_dialect} = shift if @_;
169 return $self->{limit_dialect};
170}
171
2437a1e3 172sub quote_char {
173 my $self = shift;
174 $self->{quote_char} = shift if @_;
175 return $self->{quote_char};
176}
177
178sub name_sep {
179 my $self = shift;
180 $self->{name_sep} = shift if @_;
181 return $self->{name_sep};
182}
183
184
185
186
486ad69b 187package DBIx::Class::Storage::DBI::DebugCallback;
188
189sub print {
190 my ($self, $string) = @_;
191 $string =~ m/^(\w+)/;
192 ${$self}->($1, $string);
193}
194
bd7efd39 195} # End of BEGIN block
196
8b445e33 197use base qw/DBIx::Class/;
198
1f692767 199__PACKAGE__->load_components(qw/AccessorGroup/);
8b445e33 200
223b8fe3 201__PACKAGE__->mk_group_accessors('simple' =>
5ef3e508 202 qw/connect_info _dbh _sql_maker _connection_pid debug debugfh cursor
203 on_connect_do transaction_depth/);
8091aa91 204
8b445e33 205sub new {
223b8fe3 206 my $new = bless({}, ref $_[0] || $_[0]);
28927b50 207 $new->cursor("DBIx::Class::Storage::DBI::Cursor");
d79f59b9 208 $new->transaction_depth(0);
5e65c358 209 if (defined($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG}) &&
210 ($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG} =~ /=(.+)$/)) {
1c339d71 211 $new->debugfh(IO::File->new($1, 'w')) || $new->throw_exception("Cannot open trace file $1");
92b858c9 212 } else {
213 $new->debugfh(IO::File->new('>&STDERR'));
214 }
28927b50 215 $new->debug(1) if $ENV{DBIX_CLASS_STORAGE_DBI_DEBUG};
223b8fe3 216 return $new;
8b445e33 217}
218
1c339d71 219sub throw_exception {
220 my ($self, $msg) = @_;
3b042bcb 221 croak($msg);
1c339d71 222}
223
8b445e33 224=head1 NAME
225
226DBIx::Class::Storage::DBI - DBI storage handler
227
228=head1 SYNOPSIS
229
230=head1 DESCRIPTION
231
232This class represents the connection to the database
233
234=head1 METHODS
235
8b445e33 236=cut
237
d7c4c15c 238=head2 on_connect_do
239
240Executes the sql statements given as a listref on every db connect.
241
92b858c9 242=head2 debug
243
244Causes SQL trace information to be emitted on C<debugfh> filehandle
245(or C<STDERR> if C<debugfh> has not specifically been set).
246
247=head2 debugfh
248
249Sets or retrieves the filehandle used for trace/debug output. This
250should be an IO::Handle compatible object (only the C<print> method is
251used). Initially set to be STDERR - although see information on the
252L<DBIX_CLASS_STORAGE_DBI_DEBUG> environment variable.
253
486ad69b 254=head2 debugcb
255
256Sets a callback to be executed each time a statement is run; takes a sub
257reference. Overrides debugfh. Callback is executed as $sub->($op, $info)
258where $op is SELECT/INSERT/UPDATE/DELETE and $info is what would normally
259be printed.
260
d7c4c15c 261=cut
262
486ad69b 263sub debugcb {
264 my ($self, $cb) = @_;
265 my $cb_obj = bless(\$cb, 'DBIx::Class::Storage::DBI::DebugCallback');
266 $self->debugfh($cb_obj);
267}
268
412db1f4 269sub disconnect {
270 my ($self) = @_;
271
92925617 272 if( $self->connected ) {
273 $self->_dbh->rollback unless $self->_dbh->{AutoCommit};
274 $self->_dbh->disconnect;
275 $self->_dbh(undef);
276 }
412db1f4 277}
278
279sub connected {
8b445e33 280 my ($self) = @_;
412db1f4 281
8b445e33 282 my $dbh;
412db1f4 283 (($dbh = $self->_dbh) && $dbh->FETCH('Active') && $dbh->ping)
284}
285
286sub ensure_connected {
287 my ($self) = @_;
288
289 unless ($self->connected) {
8b445e33 290 $self->_populate_dbh;
291 }
412db1f4 292}
293
294sub dbh {
295 my ($self) = @_;
296
d1b9a425 297 if($self->_connection_pid && $self->_connection_pid != $$) {
298 $self->_dbh->{InactiveDestroy} = 1;
299 $self->_dbh(undef)
300 }
412db1f4 301 $self->ensure_connected;
8b445e33 302 return $self->_dbh;
303}
304
48c69e7c 305sub sql_maker {
306 my ($self) = @_;
fdc1c3d0 307 unless ($self->_sql_maker) {
bd7efd39 308 $self->_sql_maker(new DBIC::SQL::Abstract( limit_dialect => $self->dbh ));
48c69e7c 309 }
310 return $self->_sql_maker;
311}
312
8b445e33 313sub _populate_dbh {
314 my ($self) = @_;
315 my @info = @{$self->connect_info || []};
316 $self->_dbh($self->_connect(@info));
843f8ecd 317 my $driver = $self->_dbh->{Driver}->{Name};
34470972 318 eval "require DBIx::Class::Storage::DBI::${driver}";
319 unless ($@) {
843f8ecd 320 bless $self, "DBIx::Class::Storage::DBI::${driver}";
321 }
d7c4c15c 322 # if on-connect sql statements are given execute them
323 foreach my $sql_statement (@{$self->on_connect_do || []}) {
324 $self->_dbh->do($sql_statement);
325 }
5ef3e508 326
327 $self->_connection_pid($$);
8b445e33 328}
329
330sub _connect {
331 my ($self, @info) = @_;
5ef3e508 332
333 if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
334 my $old_connect_via = $DBI::connect_via;
335 $DBI::connect_via = 'connect';
336 my $dbh = DBI->connect(@info);
337 $DBI::connect_via = $old_connect_via;
338 return $dbh;
339 }
340
e571e823 341 my $dbh = DBI->connect(@info);
1c339d71 342 $self->throw_exception("DBI Connection failed: $DBI::errstr")
e571e823 343 unless $dbh;
344 $dbh;
8b445e33 345}
346
8091aa91 347=head2 txn_begin
8b445e33 348
8091aa91 349Calls begin_work on the current dbh.
8b445e33 350
181a28f4 351See L<DBIx::Class::Schema> for the txn_do() method, which allows for
352an entire code block to be executed transactionally.
353
8b445e33 354=cut
355
8091aa91 356sub txn_begin {
d79f59b9 357 my $self = shift;
181a28f4 358 $self->dbh->begin_work
359 if $self->{transaction_depth}++ == 0 and $self->dbh->{AutoCommit};
8091aa91 360}
8b445e33 361
8091aa91 362=head2 txn_commit
8b445e33 363
8091aa91 364Issues a commit against the current dbh.
8b445e33 365
8091aa91 366=cut
367
368sub txn_commit {
d79f59b9 369 my $self = shift;
370 if ($self->{transaction_depth} == 0) {
371 $self->dbh->commit unless $self->dbh->{AutoCommit};
8091aa91 372 }
373 else {
d79f59b9 374 $self->dbh->commit if --$self->{transaction_depth} == 0;
8091aa91 375 }
376}
377
378=head2 txn_rollback
379
181a28f4 380Issues a rollback against the current dbh. A nested rollback will
381throw a L<DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION> exception,
382which allows the rollback to propagate to the outermost transaction.
8b445e33 383
384=cut
385
8091aa91 386sub txn_rollback {
d79f59b9 387 my $self = shift;
a62cf8d4 388
389 eval {
390 if ($self->{transaction_depth} == 0) {
391 $self->dbh->rollback unless $self->dbh->{AutoCommit};
392 }
393 else {
394 --$self->{transaction_depth} == 0 ?
395 $self->dbh->rollback :
396 die DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION->new;
397 }
398 };
399
400 if ($@) {
401 my $error = $@;
402 my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
403 $error =~ /$exception_class/ and $self->throw_exception($error);
404 $self->{transaction_depth} = 0; # ensure that a failed rollback
405 $self->throw_exception($error); # resets the transaction depth
8091aa91 406 }
407}
8b445e33 408
223b8fe3 409sub _execute {
410 my ($self, $op, $extra_bind, $ident, @args) = @_;
411 my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
944f30bf 412 unshift(@bind, @$extra_bind) if $extra_bind;
f59ffc79 413 if ($self->debug) {
181a28f4 414 my @debug_bind = map { defined $_ ? qq{`$_'} : q{`NULL'} } @bind;
415 $self->debugfh->print("$sql: " . join(', ', @debug_bind) . "\n");
f59ffc79 416 }
2f5911b2 417 my $sth = $self->sth($sql,$op);
1c339d71 418 $self->throw_exception("no sth generated via sql: $sql") unless $sth;
438adc0e 419 @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
701da8c4 420 my $rv;
421 if ($sth) {
422 $rv = $sth->execute(@bind);
423 } else {
1c339d71 424 $self->throw_exception("'$sql' did not generate a statement.");
701da8c4 425 }
223b8fe3 426 return (wantarray ? ($rv, $sth, @bind) : $rv);
427}
428
8b445e33 429sub insert {
430 my ($self, $ident, $to_insert) = @_;
1c339d71 431 $self->throw_exception( "Couldn't insert ".join(', ', map "$_ => $to_insert->{$_}", keys %$to_insert)." into ${ident}" )
a4b2f17b 432 unless ($self->_execute('insert' => [], $ident, $to_insert));
8b445e33 433 return $to_insert;
434}
435
436sub update {
223b8fe3 437 return shift->_execute('update' => [], @_);
8b445e33 438}
439
440sub delete {
223b8fe3 441 return shift->_execute('delete' => [], @_);
8b445e33 442}
443
de705b51 444sub _select {
8b445e33 445 my ($self, $ident, $select, $condition, $attrs) = @_;
223b8fe3 446 my $order = $attrs->{order_by};
447 if (ref $condition eq 'SCALAR') {
448 $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
449 }
8839560b 450 if (exists $attrs->{group_by} || $attrs->{having}) {
54540863 451 $order = { group_by => $attrs->{group_by},
8839560b 452 having => $attrs->{having},
54540863 453 ($order ? (order_by => $order) : ()) };
454 }
5c91499f 455 my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order);
9229f20a 456 if ($attrs->{software_limit} ||
457 $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
458 $attrs->{software_limit} = 1;
5c91499f 459 } else {
460 push @args, $attrs->{rows}, $attrs->{offset};
461 }
de705b51 462 return $self->_execute(@args);
463}
464
465sub select {
466 my $self = shift;
467 my ($ident, $select, $condition, $attrs) = @_;
cb5f2eea 468 return $self->cursor->new($self, \@_, $attrs);
8b445e33 469}
470
6157db4f 471# Need to call finish() to work round broken DBDs
472
1a14aa3f 473sub select_single {
de705b51 474 my $self = shift;
475 my ($rv, $sth, @bind) = $self->_select(@_);
6157db4f 476 my @row = $sth->fetchrow_array;
477 $sth->finish();
478 return @row;
1a14aa3f 479}
480
8b445e33 481sub sth {
cb5f2eea 482 my ($self, $sql) = @_;
91fa659e 483 # 3 is the if_active parameter which avoids active sth re-use
484 return $self->dbh->prepare_cached($sql, {}, 3);
8b445e33 485}
486
a953d8d9 487=head2 columns_info_for
488
489Returns database type info for a given table columns.
490
491=cut
492
493sub columns_info_for {
494 my ($self, $table) = @_;
a953d8d9 495 my %result;
103e3e03 496 if ( $self->dbh->can( 'column_info' ) ){
497 my $sth = $self->dbh->column_info( undef, undef, $table, '%' );
498 $sth->execute();
499 while ( my $info = $sth->fetchrow_hashref() ){
500 my %column_info;
a953d8d9 501 $column_info{data_type} = $info->{TYPE_NAME};
502 $column_info{size} = $info->{COLUMN_SIZE};
503 $column_info{is_nullable} = $info->{NULLABLE};
103e3e03 504 $result{$info->{COLUMN_NAME}} = \%column_info;
505 }
1c339d71 506 } else {
103e3e03 507 my $sth = $self->dbh->prepare("SELECT * FROM $table WHERE 1=0");
508 $sth->execute;
509 my @columns = @{$sth->{NAME}};
510 for my $i ( 0 .. $#columns ){
511 $result{$columns[$i]}{data_type} = $sth->{TYPE}->[$i];
a953d8d9 512 }
a953d8d9 513 }
514 return \%result;
515}
516
843f8ecd 517sub last_insert_id {
518 my ($self, $row) = @_;
519
520 return $self->dbh->func('last_insert_rowid');
521
522}
523
1c339d71 524sub sqlt_type {
525 my ($self) = @_;
526 my $dsn = $self->connect_info->[0];
527 $dsn =~ /^dbi:(.*?)\d*:/;
528 return $1;
529}
530
531sub deployment_statements {
532 my ($self, $schema, $type) = @_;
533 $type ||= $self->sqlt_type;
534 eval "use SQL::Translator";
535 $self->throw_exception("Can't deploy without SQL::Translator: $@") if $@;
536 eval "use SQL::Translator::Parser::DBIx::Class;";
537 $self->throw_exception($@) if $@;
538 eval "use SQL::Translator::Producer::${type};";
539 $self->throw_exception($@) if $@;
540 my $tr = SQL::Translator->new();
541 SQL::Translator::Parser::DBIx::Class::parse( $tr, $schema );
542 return "SQL::Translator::Producer::${type}"->can('produce')->($tr);
543}
843f8ecd 544
1c339d71 545sub deploy {
546 my ($self, $schema, $type) = @_;
e8d293df 547 foreach(split(";\n", $self->deployment_statements($schema, $type))) {
548 $self->dbh->do($_) or warn "SQL was:\n $_";
549 }
1c339d71 550}
843f8ecd 551
92925617 552sub DESTROY { shift->disconnect }
553
8b445e33 5541;
555
92b858c9 556=head1 ENVIRONMENT VARIABLES
557
558=head2 DBIX_CLASS_STORAGE_DBI_DEBUG
559
560If C<DBIX_CLASS_STORAGE_DBI_DEBUG> is set then SQL trace information
561is produced (as when the L<debug> method is set).
562
563If the value is of the form C<1=/path/name> then the trace output is
564written to the file C</path/name>.
565
8b445e33 566=head1 AUTHORS
567
daec44b8 568Matt S. Trout <mst@shadowcatsystems.co.uk>
8b445e33 569
9f19b1d6 570Andy Grundman <andy@hybridized.org>
571
8b445e33 572=head1 LICENSE
573
574You may distribute this code under the same terms as Perl itself.
575
576=cut
577