handle the throw_exception bit. Drop DBIx::Class::Exception
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBI.pm
CommitLineData
8b445e33 1package DBIx::Class::Storage::DBI;
2
20a2c954 3use strict;
4use warnings;
8b445e33 5use DBI;
aeaf3ce2 6use SQL::Abstract::Limit;
28927b50 7use DBIx::Class::Storage::DBI::Cursor;
92b858c9 8use IO::File;
701da8c4 9use Carp::Clan qw/DBIx::Class/;
8b445e33 10
bd7efd39 11BEGIN {
12
cb5f2eea 13package DBIC::SQL::Abstract; # Would merge upstream, but nate doesn't reply :(
bd7efd39 14
15use base qw/SQL::Abstract::Limit/;
16
54540863 17sub select {
18 my ($self, $table, $fields, $where, $order, @rest) = @_;
19 @rest = (-1) unless defined $rest[0];
20 $self->SUPER::select($table, $self->_recurse_fields($fields),
21 $where, $order, @rest);
22}
23
24sub _emulate_limit {
25 my $self = shift;
26 if ($_[3] == -1) {
27 return $_[1].$self->_order_by($_[2]);
28 } else {
29 return $self->SUPER::_emulate_limit(@_);
30 }
31}
32
33sub _recurse_fields {
34 my ($self, $fields) = @_;
35 my $ref = ref $fields;
36 return $self->_quote($fields) unless $ref;
37 return $$fields if $ref eq 'SCALAR';
38
39 if ($ref eq 'ARRAY') {
40 return join(', ', map { $self->_recurse_fields($_) } @$fields);
41 } elsif ($ref eq 'HASH') {
42 foreach my $func (keys %$fields) {
43 return $self->_sqlcase($func)
44 .'( '.$self->_recurse_fields($fields->{$func}).' )';
45 }
46 }
47}
48
49sub _order_by {
50 my $self = shift;
51 my $ret = '';
52 if (ref $_[0] eq 'HASH') {
53 if (defined $_[0]->{group_by}) {
54 $ret = $self->_sqlcase(' group by ')
55 .$self->_recurse_fields($_[0]->{group_by});
56 }
57 if (defined $_[0]->{order_by}) {
58 $ret .= $self->SUPER::_order_by($_[0]->{order_by});
59 }
60 } else {
61 $ret = $self->SUPER::_order_by(@_);
62 }
63 return $ret;
64}
65
2a816814 66sub _table {
bd7efd39 67 my ($self, $from) = @_;
68 if (ref $from eq 'ARRAY') {
69 return $self->_recurse_from(@$from);
70 } elsif (ref $from eq 'HASH') {
71 return $self->_make_as($from);
72 } else {
73 return $from;
74 }
75}
76
77sub _recurse_from {
78 my ($self, $from, @join) = @_;
79 my @sqlf;
80 push(@sqlf, $self->_make_as($from));
81 foreach my $j (@join) {
82 my ($to, $on) = @$j;
73856587 83
54540863 84 # check whether a join type exists
85 my $join_clause = '';
86 if (ref($to) eq 'HASH' and exists($to->{-join_type})) {
87 $join_clause = ' '.uc($to->{-join_type}).' JOIN ';
88 } else {
89 $join_clause = ' JOIN ';
90 }
73856587 91 push(@sqlf, $join_clause);
92
bd7efd39 93 if (ref $to eq 'ARRAY') {
94 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
95 } else {
96cdbbab 96 push(@sqlf, $self->_make_as($to));
bd7efd39 97 }
98 push(@sqlf, ' ON ', $self->_join_condition($on));
99 }
100 return join('', @sqlf);
101}
102
103sub _make_as {
104 my ($self, $from) = @_;
54540863 105 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) }
2a816814 106 reverse each %{$self->_skip_options($from)});
73856587 107}
108
109sub _skip_options {
54540863 110 my ($self, $hash) = @_;
111 my $clean_hash = {};
112 $clean_hash->{$_} = $hash->{$_}
113 for grep {!/^-/} keys %$hash;
114 return $clean_hash;
bd7efd39 115}
116
117sub _join_condition {
118 my ($self, $cond) = @_;
5efe4c79 119 if (ref $cond eq 'HASH') {
120 my %j;
121 for (keys %$cond) { my $x = '= '.$self->_quote($cond->{$_}); $j{$_} = \$x; };
122 return $self->_recurse_where(\%j);
123 } elsif (ref $cond eq 'ARRAY') {
124 return join(' OR ', map { $self->_join_condition($_) } @$cond);
125 } else {
126 die "Can't handle this yet!";
127 }
bd7efd39 128}
129
2a816814 130sub _quote {
131 my ($self, $label) = @_;
132 return '' unless defined $label;
133 return $self->SUPER::_quote($label);
134}
135
7be93b07 136# Accessor for setting limit dialect. This is useful
137# for JDBC-bridge among others where the remote SQL-dialect cannot
138# be determined by the name of the driver alone.
139#
140sub limit_dialect {
141 my $self = shift;
142 $self->{limit_dialect} = shift if @_;
143 return $self->{limit_dialect};
144}
145
bd7efd39 146} # End of BEGIN block
147
8b445e33 148use base qw/DBIx::Class/;
149
438adc0e 150__PACKAGE__->load_components(qw/Exception AccessorGroup/);
8b445e33 151
223b8fe3 152__PACKAGE__->mk_group_accessors('simple' =>
92b858c9 153 qw/connect_info _dbh _sql_maker debug debugfh cursor on_connect_do transaction_depth/);
8091aa91 154
8b445e33 155sub new {
223b8fe3 156 my $new = bless({}, ref $_[0] || $_[0]);
28927b50 157 $new->cursor("DBIx::Class::Storage::DBI::Cursor");
d79f59b9 158 $new->transaction_depth(0);
5e65c358 159 if (defined($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG}) &&
160 ($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG} =~ /=(.+)$/)) {
701da8c4 161 $new->debugfh(IO::File->new($1, 'w')||croak "Cannot open trace file $1");
92b858c9 162 } else {
163 $new->debugfh(IO::File->new('>&STDERR'));
164 }
28927b50 165 $new->debug(1) if $ENV{DBIX_CLASS_STORAGE_DBI_DEBUG};
223b8fe3 166 return $new;
8b445e33 167}
168
8b445e33 169=head1 NAME
170
171DBIx::Class::Storage::DBI - DBI storage handler
172
173=head1 SYNOPSIS
174
175=head1 DESCRIPTION
176
177This class represents the connection to the database
178
179=head1 METHODS
180
8b445e33 181=cut
182
d7c4c15c 183=head2 on_connect_do
184
185Executes the sql statements given as a listref on every db connect.
186
92b858c9 187=head2 debug
188
189Causes SQL trace information to be emitted on C<debugfh> filehandle
190(or C<STDERR> if C<debugfh> has not specifically been set).
191
192=head2 debugfh
193
194Sets or retrieves the filehandle used for trace/debug output. This
195should be an IO::Handle compatible object (only the C<print> method is
196used). Initially set to be STDERR - although see information on the
197L<DBIX_CLASS_STORAGE_DBI_DEBUG> environment variable.
198
d7c4c15c 199=cut
200
8b445e33 201sub dbh {
202 my ($self) = @_;
203 my $dbh;
204 unless (($dbh = $self->_dbh) && $dbh->FETCH('Active') && $dbh->ping) {
205 $self->_populate_dbh;
206 }
207 return $self->_dbh;
208}
209
48c69e7c 210sub sql_maker {
211 my ($self) = @_;
fdc1c3d0 212 unless ($self->_sql_maker) {
bd7efd39 213 $self->_sql_maker(new DBIC::SQL::Abstract( limit_dialect => $self->dbh ));
48c69e7c 214 }
215 return $self->_sql_maker;
216}
217
8b445e33 218sub _populate_dbh {
219 my ($self) = @_;
220 my @info = @{$self->connect_info || []};
221 $self->_dbh($self->_connect(@info));
d7c4c15c 222
223 # if on-connect sql statements are given execute them
224 foreach my $sql_statement (@{$self->on_connect_do || []}) {
225 $self->_dbh->do($sql_statement);
226 }
8b445e33 227}
228
229sub _connect {
230 my ($self, @info) = @_;
231 return DBI->connect(@info);
232}
233
8091aa91 234=head2 txn_begin
8b445e33 235
8091aa91 236Calls begin_work on the current dbh.
8b445e33 237
238=cut
239
8091aa91 240sub txn_begin {
d79f59b9 241 my $self = shift;
242 $self->dbh->begin_work if $self->{transaction_depth}++ == 0 and $self->dbh->{AutoCommit};
8091aa91 243}
8b445e33 244
8091aa91 245=head2 txn_commit
8b445e33 246
8091aa91 247Issues a commit against the current dbh.
8b445e33 248
8091aa91 249=cut
250
251sub txn_commit {
d79f59b9 252 my $self = shift;
253 if ($self->{transaction_depth} == 0) {
254 $self->dbh->commit unless $self->dbh->{AutoCommit};
8091aa91 255 }
256 else {
d79f59b9 257 $self->dbh->commit if --$self->{transaction_depth} == 0;
8091aa91 258 }
259}
260
261=head2 txn_rollback
262
263Issues a rollback against the current dbh.
8b445e33 264
265=cut
266
8091aa91 267sub txn_rollback {
d79f59b9 268 my $self = shift;
269 if ($self->{transaction_depth} == 0) {
270 $self->dbh->rollback unless $self->dbh->{AutoCommit};
8091aa91 271 }
272 else {
d79f59b9 273 --$self->{transaction_depth} == 0 ? $self->dbh->rollback : die $@;
8091aa91 274 }
275}
8b445e33 276
223b8fe3 277sub _execute {
278 my ($self, $op, $extra_bind, $ident, @args) = @_;
279 my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
944f30bf 280 unshift(@bind, @$extra_bind) if $extra_bind;
92b858c9 281 $self->debugfh->print("$sql: @bind\n") if $self->debug;
2f5911b2 282 my $sth = $self->sth($sql,$op);
438adc0e 283 @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
701da8c4 284 my $rv;
285 if ($sth) {
286 $rv = $sth->execute(@bind);
287 } else {
288 croak "'$sql' did not generate a statement.";
289 }
223b8fe3 290 return (wantarray ? ($rv, $sth, @bind) : $rv);
291}
292
8b445e33 293sub insert {
294 my ($self, $ident, $to_insert) = @_;
701da8c4 295 croak( "Couldn't insert ".join(', ', map "$_ => $to_insert->{$_}", keys %$to_insert)." into ${ident}" )
a4b2f17b 296 unless ($self->_execute('insert' => [], $ident, $to_insert));
8b445e33 297 return $to_insert;
298}
299
300sub update {
223b8fe3 301 return shift->_execute('update' => [], @_);
8b445e33 302}
303
304sub delete {
223b8fe3 305 return shift->_execute('delete' => [], @_);
8b445e33 306}
307
de705b51 308sub _select {
8b445e33 309 my ($self, $ident, $select, $condition, $attrs) = @_;
223b8fe3 310 my $order = $attrs->{order_by};
311 if (ref $condition eq 'SCALAR') {
312 $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
313 }
54540863 314 if (exists $attrs->{group_by}) {
315 $order = { group_by => $attrs->{group_by},
316 ($order ? (order_by => $order) : ()) };
317 }
5c91499f 318 my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order);
9229f20a 319 if ($attrs->{software_limit} ||
320 $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
321 $attrs->{software_limit} = 1;
5c91499f 322 } else {
323 push @args, $attrs->{rows}, $attrs->{offset};
324 }
de705b51 325 return $self->_execute(@args);
326}
327
328sub select {
329 my $self = shift;
330 my ($ident, $select, $condition, $attrs) = @_;
cb5f2eea 331 return $self->cursor->new($self, \@_, $attrs);
8b445e33 332}
333
1a14aa3f 334sub select_single {
de705b51 335 my $self = shift;
336 my ($rv, $sth, @bind) = $self->_select(@_);
1a14aa3f 337 return $sth->fetchrow_array;
338}
339
8b445e33 340sub sth {
cb5f2eea 341 my ($self, $sql) = @_;
91fa659e 342 # 3 is the if_active parameter which avoids active sth re-use
343 return $self->dbh->prepare_cached($sql, {}, 3);
8b445e33 344}
345
a953d8d9 346=head2 columns_info_for
347
348Returns database type info for a given table columns.
349
350=cut
351
352sub columns_info_for {
353 my ($self, $table) = @_;
a953d8d9 354 my %result;
103e3e03 355 if ( $self->dbh->can( 'column_info' ) ){
356 my $sth = $self->dbh->column_info( undef, undef, $table, '%' );
357 $sth->execute();
358 while ( my $info = $sth->fetchrow_hashref() ){
359 my %column_info;
a953d8d9 360 $column_info{data_type} = $info->{TYPE_NAME};
361 $column_info{size} = $info->{COLUMN_SIZE};
362 $column_info{is_nullable} = $info->{NULLABLE};
103e3e03 363 $result{$info->{COLUMN_NAME}} = \%column_info;
364 }
365 }else{
366 my $sth = $self->dbh->prepare("SELECT * FROM $table WHERE 1=0");
367 $sth->execute;
368 my @columns = @{$sth->{NAME}};
369 for my $i ( 0 .. $#columns ){
370 $result{$columns[$i]}{data_type} = $sth->{TYPE}->[$i];
a953d8d9 371 }
a953d8d9 372 }
373 return \%result;
374}
375
8b445e33 3761;
377
92b858c9 378=head1 ENVIRONMENT VARIABLES
379
380=head2 DBIX_CLASS_STORAGE_DBI_DEBUG
381
382If C<DBIX_CLASS_STORAGE_DBI_DEBUG> is set then SQL trace information
383is produced (as when the L<debug> method is set).
384
385If the value is of the form C<1=/path/name> then the trace output is
386written to the file C</path/name>.
387
8b445e33 388=head1 AUTHORS
389
daec44b8 390Matt S. Trout <mst@shadowcatsystems.co.uk>
8b445e33 391
9f19b1d6 392Andy Grundman <andy@hybridized.org>
393
8b445e33 394=head1 LICENSE
395
396You may distribute this code under the same terms as Perl itself.
397
398=cut
399