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