Added docs for quote_char, name_sep and offset RS attrib.
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBI.pm
1 package DBIx::Class::Storage::DBI;
2
3 use base 'DBIx::Class::Storage';
4
5 use strict;
6 use warnings;
7 use DBI;
8 use SQL::Abstract::Limit;
9 use DBIx::Class::Storage::DBI::Cursor;
10 use IO::File;
11 use Carp::Clan qw/DBIx::Class/;
12
13 BEGIN {
14
15 package DBIC::SQL::Abstract; # Would merge upstream, but nate doesn't reply :(
16
17 use base qw/SQL::Abstract::Limit/;
18
19 sub select {
20   my ($self, $table, $fields, $where, $order, @rest) = @_;
21   $table = $self->_quote($table) unless ref($table);
22   @rest = (-1) unless defined $rest[0];
23   die "LIMIT 0 Does Not Compute" if $rest[0] == 0;
24     # and anyway, SQL::Abstract::Limit will cause a barf if we don't first
25   local $self->{having_bind} = [];
26   my ($sql, @ret) = $self->SUPER::select(
27     $table, $self->_recurse_fields($fields), $where, $order, @rest
28   );
29   return wantarray ? ($sql, @ret, @{$self->{having_bind}}) : $sql;
30 }
31
32 sub insert {
33   my $self = shift;
34   my $table = shift;
35   $table = $self->_quote($table) unless ref($table);
36   $self->SUPER::insert($table, @_);
37 }
38
39 sub update {
40   my $self = shift;
41   my $table = shift;
42   $table = $self->_quote($table) unless ref($table);
43   $self->SUPER::update($table, @_);
44 }
45
46 sub delete {
47   my $self = shift;
48   my $table = shift;
49   $table = $self->_quote($table) unless ref($table);
50   $self->SUPER::delete($table, @_);
51 }
52
53 sub _emulate_limit {
54   my $self = shift;
55   if ($_[3] == -1) {
56     return $_[1].$self->_order_by($_[2]);
57   } else {
58     return $self->SUPER::_emulate_limit(@_);
59   }
60 }
61
62 sub _recurse_fields {
63   my ($self, $fields) = @_;
64   my $ref = ref $fields;
65   return $self->_quote($fields) unless $ref;
66   return $$fields if $ref eq 'SCALAR';
67
68   if ($ref eq 'ARRAY') {
69     return join(', ', map { $self->_recurse_fields($_) } @$fields);
70   } elsif ($ref eq 'HASH') {
71     foreach my $func (keys %$fields) {
72       return $self->_sqlcase($func)
73         .'( '.$self->_recurse_fields($fields->{$func}).' )';
74     }
75   }
76 }
77
78 sub _order_by {
79   my $self = shift;
80   my $ret = '';
81   my @extra;
82   if (ref $_[0] eq 'HASH') {
83     if (defined $_[0]->{group_by}) {
84       $ret = $self->_sqlcase(' group by ')
85                .$self->_recurse_fields($_[0]->{group_by});
86     }
87     if (defined $_[0]->{having}) {
88       my $frag;
89       ($frag, @extra) = $self->_recurse_where($_[0]->{having});
90       push(@{$self->{having_bind}}, @extra);
91       $ret .= $self->_sqlcase(' having ').$frag;
92     }
93     if (defined $_[0]->{order_by}) {
94       $ret .= $self->SUPER::_order_by($_[0]->{order_by});
95     }
96   } elsif(ref $_[0] eq 'SCALAR') {
97     $ret = $self->_sqlcase(' order by ').${ $_[0] };
98   } else {
99     $ret = $self->SUPER::_order_by(@_);
100   }
101   return $ret;
102 }
103
104 sub _order_directions {
105   my ($self, $order) = @_;
106   $order = $order->{order_by} if ref $order eq 'HASH';
107   return $self->SUPER::_order_directions($order);
108 }
109
110 sub _table {
111   my ($self, $from) = @_;
112   if (ref $from eq 'ARRAY') {
113     return $self->_recurse_from(@$from);
114   } elsif (ref $from eq 'HASH') {
115     return $self->_make_as($from);
116   } else {
117     return $from; # would love to quote here but _table ends up getting called
118                   # twice during an ->select without a limit clause due to
119                   # the way S::A::Limit->select works. should maybe consider
120                   # bypassing this and doing S::A::select($self, ...) in
121                   # our select method above. meantime, quoting shims have
122                   # been added to select/insert/update/delete here
123   }
124 }
125
126 sub _recurse_from {
127   my ($self, $from, @join) = @_;
128   my @sqlf;
129   push(@sqlf, $self->_make_as($from));
130   foreach my $j (@join) {
131     my ($to, $on) = @$j;
132
133     # check whether a join type exists
134     my $join_clause = '';
135     if (ref($to) eq 'HASH' and exists($to->{-join_type})) {
136       $join_clause = ' '.uc($to->{-join_type}).' JOIN ';
137     } else {
138       $join_clause = ' JOIN ';
139     }
140     push(@sqlf, $join_clause);
141
142     if (ref $to eq 'ARRAY') {
143       push(@sqlf, '(', $self->_recurse_from(@$to), ')');
144     } else {
145       push(@sqlf, $self->_make_as($to));
146     }
147     push(@sqlf, ' ON ', $self->_join_condition($on));
148   }
149   return join('', @sqlf);
150 }
151
152 sub _make_as {
153   my ($self, $from) = @_;
154   return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) }
155                      reverse each %{$self->_skip_options($from)});
156 }
157
158 sub _skip_options {
159   my ($self, $hash) = @_;
160   my $clean_hash = {};
161   $clean_hash->{$_} = $hash->{$_}
162     for grep {!/^-/} keys %$hash;
163   return $clean_hash;
164 }
165
166 sub _join_condition {
167   my ($self, $cond) = @_;
168   if (ref $cond eq 'HASH') {
169     my %j;
170     for (keys %$cond) {
171       my $x = '= '.$self->_quote($cond->{$_}); $j{$_} = \$x;
172     };
173     return $self->_recurse_where(\%j);
174   } elsif (ref $cond eq 'ARRAY') {
175     return join(' OR ', map { $self->_join_condition($_) } @$cond);
176   } else {
177     die "Can't handle this yet!";
178   }
179 }
180
181 sub _quote {
182   my ($self, $label) = @_;
183   return '' unless defined $label;
184   return "*" if $label eq '*';
185   return $label unless $self->{quote_char};
186   if(ref $self->{quote_char} eq "ARRAY"){
187     return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1]
188       if !defined $self->{name_sep};
189     my $sep = $self->{name_sep};
190     return join($self->{name_sep},
191         map { $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1]  }
192        split(/\Q$sep\E/,$label));
193   }
194   return $self->SUPER::_quote($label);
195 }
196
197 sub _RowNum {
198    my $self = shift;
199    my $c;
200    $_[0] =~ s/SELECT (.*?) FROM/
201      'SELECT '.join(', ', map { $_.' AS col'.++$c } split(', ', $1)).' FROM'/e;
202    $self->SUPER::_RowNum(@_);
203 }
204
205 # Accessor for setting limit dialect. This is useful
206 # for JDBC-bridge among others where the remote SQL-dialect cannot
207 # be determined by the name of the driver alone.
208 #
209 sub limit_dialect {
210     my $self = shift;
211     $self->{limit_dialect} = shift if @_;
212     return $self->{limit_dialect};
213 }
214
215 sub quote_char {
216     my $self = shift;
217     $self->{quote_char} = shift if @_;
218     return $self->{quote_char};
219 }
220
221 sub name_sep {
222     my $self = shift;
223     $self->{name_sep} = shift if @_;
224     return $self->{name_sep};
225 }
226
227
228
229
230 package DBIx::Class::Storage::DBI::DebugCallback;
231
232 sub print {
233   my ($self, $string) = @_;
234   $string =~ m/^(\w+)/;
235   ${$self}->($1, $string);
236 }
237
238 } # End of BEGIN block
239
240 use base qw/DBIx::Class/;
241
242 __PACKAGE__->load_components(qw/AccessorGroup/);
243
244 __PACKAGE__->mk_group_accessors('simple' =>
245   qw/connect_info _dbh _sql_maker _conn_pid _conn_tid debug debugfh
246      cursor on_connect_do transaction_depth/);
247
248 sub new {
249   my $new = bless({}, ref $_[0] || $_[0]);
250   $new->cursor("DBIx::Class::Storage::DBI::Cursor");
251   $new->transaction_depth(0);
252   if (defined($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG}) &&
253      ($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG} =~ /=(.+)$/)) {
254     $new->debugfh(IO::File->new($1, 'w'))
255       or $new->throw_exception("Cannot open trace file $1");
256   } else {
257     $new->debugfh(IO::File->new('>&STDERR'));
258   }
259   $new->debug(1) if $ENV{DBIX_CLASS_STORAGE_DBI_DEBUG};
260   return $new;
261 }
262
263 sub throw_exception {
264   my ($self, $msg) = @_;
265   croak($msg);
266 }
267
268 =head1 NAME
269
270 DBIx::Class::Storage::DBI - DBI storage handler
271
272 =head1 SYNOPSIS
273
274 =head1 DESCRIPTION
275
276 This class represents the connection to the database
277
278 =head1 METHODS
279
280 =cut
281
282 =head2 on_connect_do
283
284 Executes the sql statements given as a listref on every db connect.
285
286 =head2 quote_char
287
288 Specifies what characters to use to quote table and column names. If 
289 you use this you will want to specify L<name_sep> as well.
290
291 quote_char expectes either a single character, in which case is it is placed
292 on either side of the table/column, or an array of length 2 in which case the
293 table/column name is placed between the elements.
294
295 For example under MySQL you'd use C<quote_char('`')>, and user SQL Server you'd 
296 use C<quote_char(qw/[ ]/)>.
297
298 =head2 name_sep
299
300 This only needs to be used in conjunction with L<quote_char>, and is used to 
301 specify the charecter that seperates elements (schemas, tables, columns) from 
302 each other. In most cases this is simply a C<.>.
303
304 =head2 debug
305
306 Causes SQL trace information to be emitted on C<debugfh> filehandle
307 (or C<STDERR> if C<debugfh> has not specifically been set).
308
309 =head2 debugfh
310
311 Sets or retrieves the filehandle used for trace/debug output.  This
312 should be an IO::Handle compatible object (only the C<print> method is
313 used).  Initially set to be STDERR - although see information on the
314 L<DBIX_CLASS_STORAGE_DBI_DEBUG> environment variable.
315
316 =head2 debugcb
317
318 Sets a callback to be executed each time a statement is run; takes a sub
319 reference. Overrides debugfh. Callback is executed as $sub->($op, $info)
320 where $op is SELECT/INSERT/UPDATE/DELETE and $info is what would normally
321 be printed.
322
323 =cut
324
325 sub debugcb {
326   my ($self, $cb) = @_;
327   my $cb_obj = bless(\$cb, 'DBIx::Class::Storage::DBI::DebugCallback');
328   $self->debugfh($cb_obj);
329 }
330
331 sub disconnect {
332   my ($self) = @_;
333
334   if( $self->connected ) {
335     $self->_dbh->rollback unless $self->_dbh->{AutoCommit};
336     $self->_dbh->disconnect;
337     $self->_dbh(undef);
338   }
339 }
340
341 sub connected {
342   my ($self) = @_;
343
344   if(my $dbh = $self->_dbh) {
345       if(defined $self->_conn_tid && $self->_conn_tid != threads->tid) {
346           $self->_sql_maker(undef);
347           return $self->_dbh(undef);
348       }
349       elsif($self->_conn_pid != $$) {
350           $self->_dbh->{InactiveDestroy} = 1;
351           $self->_sql_maker(undef);
352           return $self->_dbh(undef)
353       }
354       return ($dbh->FETCH('Active') && $dbh->ping);
355   }
356
357   return 0;
358 }
359
360 sub ensure_connected {
361   my ($self) = @_;
362
363   unless ($self->connected) {
364     $self->_populate_dbh;
365   }
366 }
367
368 =head2 dbh
369
370 Returns the dbh - a data base handle of class L<DBI>.
371
372 =cut
373
374 sub dbh {
375   my ($self) = @_;
376
377   $self->ensure_connected;
378   return $self->_dbh;
379 }
380
381 sub sql_maker {
382   my ($self) = @_;
383   unless ($self->_sql_maker) {
384     $self->_sql_maker(new DBIC::SQL::Abstract( limit_dialect => $self->dbh ));
385   }
386   return $self->_sql_maker;
387 }
388
389 sub _populate_dbh {
390   my ($self) = @_;
391   my @info = @{$self->connect_info || []};
392   $self->_dbh($self->_connect(@info));
393   my $driver = $self->_dbh->{Driver}->{Name};
394   eval "require DBIx::Class::Storage::DBI::${driver}";
395   unless ($@) {
396     bless $self, "DBIx::Class::Storage::DBI::${driver}";
397   }
398   # if on-connect sql statements are given execute them
399   foreach my $sql_statement (@{$self->on_connect_do || []}) {
400     $self->_dbh->do($sql_statement);
401   }
402
403   $self->_conn_pid($$);
404   $self->_conn_tid(threads->tid) if $INC{'threads.pm'};
405 }
406
407 sub _connect {
408   my ($self, @info) = @_;
409
410   $self->throw_exception("You failed to provide any connection info")
411       if !@info;
412
413   my ($old_connect_via, $dbh);
414
415   if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
416       $old_connect_via = $DBI::connect_via;
417       $DBI::connect_via = 'connect';
418   }
419
420   eval {
421     if(ref $info[0] eq 'CODE') {
422         $dbh = &{$info[0]};
423     }
424     else {
425         $dbh = DBI->connect(@info);
426     }
427   };
428
429   $DBI::connect_via = $old_connect_via if $old_connect_via;
430
431   if (!$dbh || $@) {
432     $self->throw_exception("DBI Connection failed: " . ($@ || $DBI::errstr));
433   }
434
435   $dbh;
436 }
437
438 =head2 txn_begin
439
440 Calls begin_work on the current dbh.
441
442 See L<DBIx::Class::Schema> for the txn_do() method, which allows for
443 an entire code block to be executed transactionally.
444
445 =cut
446
447 sub txn_begin {
448   my $self = shift;
449   if ($self->{transaction_depth}++ == 0) {
450     my $dbh = $self->dbh;
451     if ($dbh->{AutoCommit}) {
452       $self->debugfh->print("BEGIN WORK\n")
453         if ($self->debug);
454       $dbh->begin_work;
455     }
456   }
457 }
458
459 =head2 txn_commit
460
461 Issues a commit against the current dbh.
462
463 =cut
464
465 sub txn_commit {
466   my $self = shift;
467   my $dbh = $self->dbh;
468   if ($self->{transaction_depth} == 0) {
469     unless ($dbh->{AutoCommit}) {
470       $self->debugfh->print("COMMIT\n")
471         if ($self->debug);
472       $dbh->commit;
473     }
474   }
475   else {
476     if (--$self->{transaction_depth} == 0) {
477       $self->debugfh->print("COMMIT\n")
478         if ($self->debug);
479       $dbh->commit;
480     }
481   }
482 }
483
484 =head2 txn_rollback
485
486 Issues a rollback against the current dbh. A nested rollback will
487 throw a L<DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION> exception,
488 which allows the rollback to propagate to the outermost transaction.
489
490 =cut
491
492 sub txn_rollback {
493   my $self = shift;
494
495   eval {
496     my $dbh = $self->dbh;
497     if ($self->{transaction_depth} == 0) {
498       unless ($dbh->{AutoCommit}) {
499         $self->debugfh->print("ROLLBACK\n")
500           if ($self->debug);
501         $dbh->rollback;
502       }
503     }
504     else {
505       if (--$self->{transaction_depth} == 0) {
506         $self->debugfh->print("ROLLBACK\n")
507           if ($self->debug);
508         $dbh->rollback;
509       }
510       else {
511         die DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION->new;
512       }
513     }
514   };
515
516   if ($@) {
517     my $error = $@;
518     my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
519     $error =~ /$exception_class/ and $self->throw_exception($error);
520     $self->{transaction_depth} = 0;          # ensure that a failed rollback
521     $self->throw_exception($error);          # resets the transaction depth
522   }
523 }
524
525 sub _execute {
526   my ($self, $op, $extra_bind, $ident, @args) = @_;
527   my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
528   unshift(@bind, @$extra_bind) if $extra_bind;
529   if ($self->debug) {
530     my $bind_str = join(', ', map {
531       defined $_ ? qq{`$_'} : q{`NULL'}
532     } @bind);
533     $self->debugfh->print("$sql ($bind_str)\n");
534   }
535   my $sth = eval { $self->sth($sql,$op) };
536
537   if (!$sth || $@) {
538     $self->throw_exception(
539       'no sth generated via sql (' . ($@ || $self->_dbh->errstr) . "): $sql"
540     );
541   }
542   @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
543   my $rv = eval { $sth->execute(@bind) };
544   if ($@ || !$rv) {
545     my $bind_str = join(', ', map {
546       defined $_ ? qq{`$_'} : q{`NULL'}
547     } @bind);
548     $self->throw_exception(
549       "Error executing '$sql' ($bind_str): ".($@ || $sth->errstr)
550     );
551   }
552   return (wantarray ? ($rv, $sth, @bind) : $rv);
553 }
554
555 sub insert {
556   my ($self, $ident, $to_insert) = @_;
557   $self->throw_exception(
558     "Couldn't insert ".join(', ',
559       map "$_ => $to_insert->{$_}", keys %$to_insert
560     )." into ${ident}"
561   ) unless ($self->_execute('insert' => [], $ident, $to_insert));
562   return $to_insert;
563 }
564
565 sub update {
566   return shift->_execute('update' => [], @_);
567 }
568
569 sub delete {
570   return shift->_execute('delete' => [], @_);
571 }
572
573 sub _select {
574   my ($self, $ident, $select, $condition, $attrs) = @_;
575   my $order = $attrs->{order_by};
576   if (ref $condition eq 'SCALAR') {
577     $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
578   }
579   if (exists $attrs->{group_by} || $attrs->{having}) {
580     $order = {
581       group_by => $attrs->{group_by},
582       having => $attrs->{having},
583       ($order ? (order_by => $order) : ())
584     };
585   }
586   my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order);
587   if ($attrs->{software_limit} ||
588       $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
589         $attrs->{software_limit} = 1;
590   } else {
591     $self->throw_exception("rows attribute must be positive if present")
592       if (defined($attrs->{rows}) && !($attrs->{rows} > 0));
593     push @args, $attrs->{rows}, $attrs->{offset};
594   }
595   return $self->_execute(@args);
596 }
597
598 sub select {
599   my $self = shift;
600   my ($ident, $select, $condition, $attrs) = @_;
601   return $self->cursor->new($self, \@_, $attrs);
602 }
603
604 # Need to call finish() to work round broken DBDs
605
606 sub select_single {
607   my $self = shift;
608   my ($rv, $sth, @bind) = $self->_select(@_);
609   my @row = $sth->fetchrow_array;
610   $sth->finish();
611   return @row;
612 }
613
614 sub sth {
615   my ($self, $sql) = @_;
616   # 3 is the if_active parameter which avoids active sth re-use
617   return $self->dbh->prepare_cached($sql, {}, 3);
618 }
619
620 =head2 columns_info_for
621
622 Returns database type info for a given table columns.
623
624 =cut
625
626 sub columns_info_for {
627   my ($self, $table) = @_;
628
629   my $dbh = $self->dbh;
630
631   if ($dbh->can('column_info')) {
632     my %result;
633     my $old_raise_err = $dbh->{RaiseError};
634     my $old_print_err = $dbh->{PrintError};
635     $dbh->{RaiseError} = 1;
636     $dbh->{PrintError} = 0;
637     eval {
638       my $sth = $dbh->column_info( undef, undef, $table, '%' );
639       $sth->execute();
640       while ( my $info = $sth->fetchrow_hashref() ){
641         my %column_info;
642         $column_info{data_type}   = $info->{TYPE_NAME};
643         $column_info{size}      = $info->{COLUMN_SIZE};
644         $column_info{is_nullable}   = $info->{NULLABLE} ? 1 : 0;
645         $column_info{default_value} = $info->{COLUMN_DEF};
646
647         $result{$info->{COLUMN_NAME}} = \%column_info;
648       }
649     };
650     $dbh->{RaiseError} = $old_raise_err;
651     $dbh->{PrintError} = $old_print_err;
652     return \%result if !$@;
653   }
654
655   my %result;
656   my $sth = $dbh->prepare("SELECT * FROM $table WHERE 1=0");
657   $sth->execute;
658   my @columns = @{$sth->{NAME_lc}};
659   for my $i ( 0 .. $#columns ){
660     my %column_info;
661     my $type_num = $sth->{TYPE}->[$i];
662     my $type_name;
663     if(defined $type_num && $dbh->can('type_info')) {
664       my $type_info = $dbh->type_info($type_num);
665       $type_name = $type_info->{TYPE_NAME} if $type_info;
666     }
667     $column_info{data_type} = $type_name ? $type_name : $type_num;
668     $column_info{size} = $sth->{PRECISION}->[$i];
669     $column_info{is_nullable} = $sth->{NULLABLE}->[$i] ? 1 : 0;
670
671     if ($column_info{data_type} =~ m/^(.*?)\((.*?)\)$/) {
672       $column_info{data_type} = $1;
673       $column_info{size}    = $2;
674     }
675
676     $result{$columns[$i]} = \%column_info;
677   }
678
679   return \%result;
680 }
681
682 sub last_insert_id {
683   my ($self, $row) = @_;
684     
685   return $self->dbh->func('last_insert_rowid');
686
687 }
688
689 sub sqlt_type { shift->dbh->{Driver}->{Name} }
690
691 sub deployment_statements {
692   my ($self, $schema, $type, $sqltargs) = @_;
693   $type ||= $self->sqlt_type;
694   eval "use SQL::Translator";
695   $self->throw_exception("Can't deploy without SQL::Translator: $@") if $@;
696   eval "use SQL::Translator::Parser::DBIx::Class;";
697   $self->throw_exception($@) if $@;
698   eval "use SQL::Translator::Producer::${type};";
699   $self->throw_exception($@) if $@;
700   my $tr = SQL::Translator->new(%$sqltargs);
701   SQL::Translator::Parser::DBIx::Class::parse( $tr, $schema );
702   return "SQL::Translator::Producer::${type}"->can('produce')->($tr);
703 }
704
705 sub deploy {
706   my ($self, $schema, $type, $sqltargs) = @_;
707   foreach my $statement ( $self->deployment_statements($schema, $type, $sqltargs) ) {
708     for ( split(";\n", $statement)) {
709       $self->debugfh->print("$_\n") if $self->debug;
710       $self->dbh->do($_) or warn "SQL was:\n $_";
711     }
712   }
713 }
714
715 sub DESTROY { shift->disconnect }
716
717 1;
718
719 =head1 ENVIRONMENT VARIABLES
720
721 =head2 DBIX_CLASS_STORAGE_DBI_DEBUG
722
723 If C<DBIX_CLASS_STORAGE_DBI_DEBUG> is set then SQL trace information
724 is produced (as when the L<debug> method is set).
725
726 If the value is of the form C<1=/path/name> then the trace output is
727 written to the file C</path/name>.
728
729 This environment variable is checked when the storage object is first
730 created (when you call connect on your schema).  So, run-time changes 
731 to this environment variable will not take effect unless you also 
732 re-connect on your schema.
733
734 =head1 AUTHORS
735
736 Matt S. Trout <mst@shadowcatsystems.co.uk>
737
738 Andy Grundman <andy@hybridized.org>
739
740 =head1 LICENSE
741
742 You may distribute this code under the same terms as Perl itself.
743
744 =cut
745