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