Updated UUID* module documentation
[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
486ad69b 146package DBIx::Class::Storage::DBI::DebugCallback;
147
148sub print {
149 my ($self, $string) = @_;
150 $string =~ m/^(\w+)/;
151 ${$self}->($1, $string);
152}
153
bd7efd39 154} # End of BEGIN block
155
8b445e33 156use base qw/DBIx::Class/;
157
1f692767 158__PACKAGE__->load_components(qw/AccessorGroup/);
8b445e33 159
223b8fe3 160__PACKAGE__->mk_group_accessors('simple' =>
92b858c9 161 qw/connect_info _dbh _sql_maker debug debugfh cursor on_connect_do transaction_depth/);
8091aa91 162
8b445e33 163sub new {
223b8fe3 164 my $new = bless({}, ref $_[0] || $_[0]);
28927b50 165 $new->cursor("DBIx::Class::Storage::DBI::Cursor");
d79f59b9 166 $new->transaction_depth(0);
5e65c358 167 if (defined($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG}) &&
168 ($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG} =~ /=(.+)$/)) {
701da8c4 169 $new->debugfh(IO::File->new($1, 'w')||croak "Cannot open trace file $1");
92b858c9 170 } else {
171 $new->debugfh(IO::File->new('>&STDERR'));
172 }
28927b50 173 $new->debug(1) if $ENV{DBIX_CLASS_STORAGE_DBI_DEBUG};
223b8fe3 174 return $new;
8b445e33 175}
176
8b445e33 177=head1 NAME
178
179DBIx::Class::Storage::DBI - DBI storage handler
180
181=head1 SYNOPSIS
182
183=head1 DESCRIPTION
184
185This class represents the connection to the database
186
187=head1 METHODS
188
8b445e33 189=cut
190
d7c4c15c 191=head2 on_connect_do
192
193Executes the sql statements given as a listref on every db connect.
194
92b858c9 195=head2 debug
196
197Causes SQL trace information to be emitted on C<debugfh> filehandle
198(or C<STDERR> if C<debugfh> has not specifically been set).
199
200=head2 debugfh
201
202Sets or retrieves the filehandle used for trace/debug output. This
203should be an IO::Handle compatible object (only the C<print> method is
204used). Initially set to be STDERR - although see information on the
205L<DBIX_CLASS_STORAGE_DBI_DEBUG> environment variable.
206
486ad69b 207=head2 debugcb
208
209Sets a callback to be executed each time a statement is run; takes a sub
210reference. Overrides debugfh. Callback is executed as $sub->($op, $info)
211where $op is SELECT/INSERT/UPDATE/DELETE and $info is what would normally
212be printed.
213
d7c4c15c 214=cut
215
486ad69b 216sub debugcb {
217 my ($self, $cb) = @_;
218 my $cb_obj = bless(\$cb, 'DBIx::Class::Storage::DBI::DebugCallback');
219 $self->debugfh($cb_obj);
220}
221
412db1f4 222sub disconnect {
223 my ($self) = @_;
224
92925617 225 if( $self->connected ) {
226 $self->_dbh->rollback unless $self->_dbh->{AutoCommit};
227 $self->_dbh->disconnect;
228 $self->_dbh(undef);
229 }
412db1f4 230}
231
232sub connected {
8b445e33 233 my ($self) = @_;
412db1f4 234
8b445e33 235 my $dbh;
412db1f4 236 (($dbh = $self->_dbh) && $dbh->FETCH('Active') && $dbh->ping)
237}
238
239sub ensure_connected {
240 my ($self) = @_;
241
242 unless ($self->connected) {
8b445e33 243 $self->_populate_dbh;
244 }
412db1f4 245}
246
247sub dbh {
248 my ($self) = @_;
249
250 $self->ensure_connected;
8b445e33 251 return $self->_dbh;
252}
253
48c69e7c 254sub sql_maker {
255 my ($self) = @_;
fdc1c3d0 256 unless ($self->_sql_maker) {
bd7efd39 257 $self->_sql_maker(new DBIC::SQL::Abstract( limit_dialect => $self->dbh ));
48c69e7c 258 }
259 return $self->_sql_maker;
260}
261
8b445e33 262sub _populate_dbh {
263 my ($self) = @_;
264 my @info = @{$self->connect_info || []};
265 $self->_dbh($self->_connect(@info));
843f8ecd 266 my $driver = $self->_dbh->{Driver}->{Name};
267 eval qq{
268require DBIx::Class::Storage::DBI::${driver};
269 };
270 if(!$@) {
271 bless $self, "DBIx::Class::Storage::DBI::${driver}";
272 }
d7c4c15c 273 # if on-connect sql statements are given execute them
274 foreach my $sql_statement (@{$self->on_connect_do || []}) {
275 $self->_dbh->do($sql_statement);
276 }
8b445e33 277}
278
279sub _connect {
280 my ($self, @info) = @_;
281 return DBI->connect(@info);
282}
283
8091aa91 284=head2 txn_begin
8b445e33 285
8091aa91 286Calls begin_work on the current dbh.
8b445e33 287
288=cut
289
8091aa91 290sub txn_begin {
d79f59b9 291 my $self = shift;
292 $self->dbh->begin_work if $self->{transaction_depth}++ == 0 and $self->dbh->{AutoCommit};
8091aa91 293}
8b445e33 294
8091aa91 295=head2 txn_commit
8b445e33 296
8091aa91 297Issues a commit against the current dbh.
8b445e33 298
8091aa91 299=cut
300
301sub txn_commit {
d79f59b9 302 my $self = shift;
303 if ($self->{transaction_depth} == 0) {
304 $self->dbh->commit unless $self->dbh->{AutoCommit};
8091aa91 305 }
306 else {
d79f59b9 307 $self->dbh->commit if --$self->{transaction_depth} == 0;
8091aa91 308 }
309}
310
311=head2 txn_rollback
312
313Issues a rollback against the current dbh.
8b445e33 314
315=cut
316
8091aa91 317sub txn_rollback {
d79f59b9 318 my $self = shift;
319 if ($self->{transaction_depth} == 0) {
320 $self->dbh->rollback unless $self->dbh->{AutoCommit};
8091aa91 321 }
322 else {
d79f59b9 323 --$self->{transaction_depth} == 0 ? $self->dbh->rollback : die $@;
8091aa91 324 }
325}
8b445e33 326
223b8fe3 327sub _execute {
328 my ($self, $op, $extra_bind, $ident, @args) = @_;
329 my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
944f30bf 330 unshift(@bind, @$extra_bind) if $extra_bind;
f59ffc79 331 if ($self->debug) {
332 my @debug_bind = map { defined $_ ? $_ : 'NULL' } @bind;
333 $self->debugfh->print("$sql: @debug_bind\n");
334 }
2f5911b2 335 my $sth = $self->sth($sql,$op);
438adc0e 336 @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
701da8c4 337 my $rv;
338 if ($sth) {
339 $rv = $sth->execute(@bind);
340 } else {
341 croak "'$sql' did not generate a statement.";
342 }
223b8fe3 343 return (wantarray ? ($rv, $sth, @bind) : $rv);
344}
345
8b445e33 346sub insert {
347 my ($self, $ident, $to_insert) = @_;
701da8c4 348 croak( "Couldn't insert ".join(', ', map "$_ => $to_insert->{$_}", keys %$to_insert)." into ${ident}" )
a4b2f17b 349 unless ($self->_execute('insert' => [], $ident, $to_insert));
8b445e33 350 return $to_insert;
351}
352
353sub update {
223b8fe3 354 return shift->_execute('update' => [], @_);
8b445e33 355}
356
357sub delete {
223b8fe3 358 return shift->_execute('delete' => [], @_);
8b445e33 359}
360
de705b51 361sub _select {
8b445e33 362 my ($self, $ident, $select, $condition, $attrs) = @_;
223b8fe3 363 my $order = $attrs->{order_by};
364 if (ref $condition eq 'SCALAR') {
365 $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
366 }
54540863 367 if (exists $attrs->{group_by}) {
368 $order = { group_by => $attrs->{group_by},
369 ($order ? (order_by => $order) : ()) };
370 }
5c91499f 371 my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order);
9229f20a 372 if ($attrs->{software_limit} ||
373 $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
374 $attrs->{software_limit} = 1;
5c91499f 375 } else {
376 push @args, $attrs->{rows}, $attrs->{offset};
377 }
de705b51 378 return $self->_execute(@args);
379}
380
381sub select {
382 my $self = shift;
383 my ($ident, $select, $condition, $attrs) = @_;
cb5f2eea 384 return $self->cursor->new($self, \@_, $attrs);
8b445e33 385}
386
6157db4f 387# Need to call finish() to work round broken DBDs
388
1a14aa3f 389sub select_single {
de705b51 390 my $self = shift;
391 my ($rv, $sth, @bind) = $self->_select(@_);
6157db4f 392 my @row = $sth->fetchrow_array;
393 $sth->finish();
394 return @row;
1a14aa3f 395}
396
8b445e33 397sub sth {
cb5f2eea 398 my ($self, $sql) = @_;
91fa659e 399 # 3 is the if_active parameter which avoids active sth re-use
400 return $self->dbh->prepare_cached($sql, {}, 3);
8b445e33 401}
402
a953d8d9 403=head2 columns_info_for
404
405Returns database type info for a given table columns.
406
407=cut
408
409sub columns_info_for {
410 my ($self, $table) = @_;
a953d8d9 411 my %result;
103e3e03 412 if ( $self->dbh->can( 'column_info' ) ){
413 my $sth = $self->dbh->column_info( undef, undef, $table, '%' );
414 $sth->execute();
415 while ( my $info = $sth->fetchrow_hashref() ){
416 my %column_info;
a953d8d9 417 $column_info{data_type} = $info->{TYPE_NAME};
418 $column_info{size} = $info->{COLUMN_SIZE};
419 $column_info{is_nullable} = $info->{NULLABLE};
103e3e03 420 $result{$info->{COLUMN_NAME}} = \%column_info;
421 }
422 }else{
423 my $sth = $self->dbh->prepare("SELECT * FROM $table WHERE 1=0");
424 $sth->execute;
425 my @columns = @{$sth->{NAME}};
426 for my $i ( 0 .. $#columns ){
427 $result{$columns[$i]}{data_type} = $sth->{TYPE}->[$i];
a953d8d9 428 }
a953d8d9 429 }
430 return \%result;
431}
432
843f8ecd 433sub last_insert_id {
434 my ($self, $row) = @_;
435
436 return $self->dbh->func('last_insert_rowid');
437
438}
439
440
441
92925617 442sub DESTROY { shift->disconnect }
443
8b445e33 4441;
445
92b858c9 446=head1 ENVIRONMENT VARIABLES
447
448=head2 DBIX_CLASS_STORAGE_DBI_DEBUG
449
450If C<DBIX_CLASS_STORAGE_DBI_DEBUG> is set then SQL trace information
451is produced (as when the L<debug> method is set).
452
453If the value is of the form C<1=/path/name> then the trace output is
454written to the file C</path/name>.
455
8b445e33 456=head1 AUTHORS
457
daec44b8 458Matt S. Trout <mst@shadowcatsystems.co.uk>
8b445e33 459
9f19b1d6 460Andy Grundman <andy@hybridized.org>
461
8b445e33 462=head1 LICENSE
463
464You may distribute this code under the same terms as Perl itself.
465
466=cut
467