Call on_connect AFTER actual connection, so we have the correct sqlt_type
[dbsrgits/DBIx-Class-Historic.git] / lib / DBIx / Class / Storage / DBI.pm
CommitLineData
8b445e33 1package DBIx::Class::Storage::DBI;
e673f011 2# -*- mode: cperl; cperl-indent-level: 2 -*-
8b445e33 3
a62cf8d4 4use base 'DBIx::Class::Storage';
5
20a2c954 6use strict;
7use warnings;
8b445e33 8use DBI;
aeaf3ce2 9use SQL::Abstract::Limit;
28927b50 10use DBIx::Class::Storage::DBI::Cursor;
92b858c9 11use IO::File;
4386b954 12use Storable 'dclone';
701da8c4 13use Carp::Clan qw/DBIx::Class/;
8b445e33 14
bd7efd39 15BEGIN {
16
cb5f2eea 17package DBIC::SQL::Abstract; # Would merge upstream, but nate doesn't reply :(
bd7efd39 18
19use base qw/SQL::Abstract::Limit/;
20
54540863 21sub select {
22 my ($self, $table, $fields, $where, $order, @rest) = @_;
6346a152 23 $table = $self->_quote($table) unless ref($table);
54540863 24 @rest = (-1) unless defined $rest[0];
8839560b 25 local $self->{having_bind} = [];
bc0c9800 26 my ($sql, @ret) = $self->SUPER::select(
27 $table, $self->_recurse_fields($fields), $where, $order, @rest
28 );
8839560b 29 return wantarray ? ($sql, @ret, @{$self->{having_bind}}) : $sql;
54540863 30}
31
6346a152 32sub insert {
33 my $self = shift;
34 my $table = shift;
35 $table = $self->_quote($table) unless ref($table);
36 $self->SUPER::insert($table, @_);
37}
38
39sub update {
40 my $self = shift;
41 my $table = shift;
42 $table = $self->_quote($table) unless ref($table);
43 $self->SUPER::update($table, @_);
44}
45
46sub delete {
47 my $self = shift;
48 my $table = shift;
49 $table = $self->_quote($table) unless ref($table);
50 $self->SUPER::delete($table, @_);
51}
52
54540863 53sub _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
62sub _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
78sub _order_by {
79 my $self = shift;
80 my $ret = '';
8839560b 81 my @extra;
54540863 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 }
8839560b 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 }
54540863 93 if (defined $_[0]->{order_by}) {
94 $ret .= $self->SUPER::_order_by($_[0]->{order_by});
95 }
e535069e 96 } elsif(ref $_[0] eq 'SCALAR') {
97 $ret = $self->_sqlcase(' order by ').${ $_[0] };
54540863 98 } else {
99 $ret = $self->SUPER::_order_by(@_);
100 }
101 return $ret;
102}
103
f48dd03f 104sub _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
2a816814 110sub _table {
bd7efd39 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 {
6346a152 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
bd7efd39 123 }
124}
125
126sub _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;
73856587 132
54540863 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 }
73856587 140 push(@sqlf, $join_clause);
141
bd7efd39 142 if (ref $to eq 'ARRAY') {
143 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
144 } else {
96cdbbab 145 push(@sqlf, $self->_make_as($to));
bd7efd39 146 }
147 push(@sqlf, ' ON ', $self->_join_condition($on));
148 }
149 return join('', @sqlf);
150}
151
152sub _make_as {
153 my ($self, $from) = @_;
54540863 154 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) }
bc0c9800 155 reverse each %{$self->_skip_options($from)});
73856587 156}
157
158sub _skip_options {
54540863 159 my ($self, $hash) = @_;
160 my $clean_hash = {};
161 $clean_hash->{$_} = $hash->{$_}
162 for grep {!/^-/} keys %$hash;
163 return $clean_hash;
bd7efd39 164}
165
166sub _join_condition {
167 my ($self, $cond) = @_;
5efe4c79 168 if (ref $cond eq 'HASH') {
169 my %j;
bc0c9800 170 for (keys %$cond) {
171 my $x = '= '.$self->_quote($cond->{$_}); $j{$_} = \$x;
172 };
5efe4c79 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 }
bd7efd39 179}
180
2a816814 181sub _quote {
182 my ($self, $label) = @_;
183 return '' unless defined $label;
3b24f6ea 184 return "*" if $label eq '*';
41728a6e 185 return $label unless $self->{quote_char};
3b24f6ea 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 }
2a816814 194 return $self->SUPER::_quote($label);
195}
196
f66596f9 197sub _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
7be93b07 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#
209sub limit_dialect {
210 my $self = shift;
211 $self->{limit_dialect} = shift if @_;
212 return $self->{limit_dialect};
213}
214
2437a1e3 215sub quote_char {
216 my $self = shift;
217 $self->{quote_char} = shift if @_;
218 return $self->{quote_char};
219}
220
221sub name_sep {
222 my $self = shift;
223 $self->{name_sep} = shift if @_;
224 return $self->{name_sep};
225}
226
227
228
229
486ad69b 230package DBIx::Class::Storage::DBI::DebugCallback;
231
232sub print {
233 my ($self, $string) = @_;
234 $string =~ m/^(\w+)/;
235 ${$self}->($1, $string);
236}
237
bd7efd39 238} # End of BEGIN block
239
8b445e33 240use base qw/DBIx::Class/;
241
1f692767 242__PACKAGE__->load_components(qw/AccessorGroup/);
8b445e33 243
223b8fe3 244__PACKAGE__->mk_group_accessors('simple' =>
1b45b01e 245 qw/_connect_info _dbh _sql_maker _conn_pid _conn_tid debug debugfh
22829118 246 cursor on_connect_do on_connect transaction_depth/);
8091aa91 247
8b445e33 248sub new {
223b8fe3 249 my $new = bless({}, ref $_[0] || $_[0]);
28927b50 250 $new->cursor("DBIx::Class::Storage::DBI::Cursor");
d79f59b9 251 $new->transaction_depth(0);
5e65c358 252 if (defined($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG}) &&
253 ($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG} =~ /=(.+)$/)) {
bc0c9800 254 $new->debugfh(IO::File->new($1, 'w'))
255 or $new->throw_exception("Cannot open trace file $1");
92b858c9 256 } else {
257 $new->debugfh(IO::File->new('>&STDERR'));
258 }
28927b50 259 $new->debug(1) if $ENV{DBIX_CLASS_STORAGE_DBI_DEBUG};
223b8fe3 260 return $new;
8b445e33 261}
262
1c339d71 263sub throw_exception {
264 my ($self, $msg) = @_;
3b042bcb 265 croak($msg);
1c339d71 266}
267
75d07914 268=head1 NAME
8b445e33 269
270DBIx::Class::Storage::DBI - DBI storage handler
271
272=head1 SYNOPSIS
273
274=head1 DESCRIPTION
275
276This class represents the connection to the database
277
278=head1 METHODS
279
8b445e33 280=cut
281
1b45b01e 282=head2 connect_info
283
284Connection information arrayref. Can either be the same arguments
285one would pass to DBI->connect, or a code-reference which returns
286a connected database handle. In either case, there is an optional
287final element in the arrayref, which can hold a hashref of
288connection-specific Storage::DBI options. These include
289C<on_connect_do>, and the sql_maker options C<limit_dialect>,
290C<quote_char>, and C<name_sep>. Examples:
291
292 ->connect_info([ 'dbi:SQLite:./foo.db' ]);
293 ->connect_info(sub { DBI->connect(...) });
294 ->connect_info([ 'dbi:Pg:dbname=foo',
295 'postgres',
296 '',
297 { AutoCommit => 0 },
298 { quote_char => q{`}, name_sep => q{@} },
299 ]);
300
d7c4c15c 301=head2 on_connect_do
302
303Executes the sql statements given as a listref on every db connect.
304
92b858c9 305=head2 debug
306
307Causes SQL trace information to be emitted on C<debugfh> filehandle
308(or C<STDERR> if C<debugfh> has not specifically been set).
309
310=head2 debugfh
311
312Sets or retrieves the filehandle used for trace/debug output. This
313should be an IO::Handle compatible object (only the C<print> method is
314used). Initially set to be STDERR - although see information on the
315L<DBIX_CLASS_STORAGE_DBI_DEBUG> environment variable.
316
486ad69b 317=head2 debugcb
318
319Sets a callback to be executed each time a statement is run; takes a sub
320reference. Overrides debugfh. Callback is executed as $sub->($op, $info)
321where $op is SELECT/INSERT/UPDATE/DELETE and $info is what would normally
322be printed.
323
d7c4c15c 324=cut
325
486ad69b 326sub debugcb {
327 my ($self, $cb) = @_;
328 my $cb_obj = bless(\$cb, 'DBIx::Class::Storage::DBI::DebugCallback');
329 $self->debugfh($cb_obj);
330}
331
412db1f4 332sub disconnect {
333 my ($self) = @_;
334
92925617 335 if( $self->connected ) {
336 $self->_dbh->rollback unless $self->_dbh->{AutoCommit};
337 $self->_dbh->disconnect;
338 $self->_dbh(undef);
339 }
412db1f4 340}
341
342sub connected {
8b445e33 343 my ($self) = @_;
412db1f4 344
1346e22d 345 if(my $dbh = $self->_dbh) {
346 if(defined $self->_conn_tid && $self->_conn_tid != threads->tid) {
347 $self->_sql_maker(undef);
348 return $self->_dbh(undef);
349 }
350 elsif($self->_conn_pid != $$) {
351 $self->_dbh->{InactiveDestroy} = 1;
352 $self->_sql_maker(undef);
353 return $self->_dbh(undef)
354 }
355 return ($dbh->FETCH('Active') && $dbh->ping);
356 }
357
358 return 0;
412db1f4 359}
360
361sub ensure_connected {
362 my ($self) = @_;
363
364 unless ($self->connected) {
8b445e33 365 $self->_populate_dbh;
366 }
412db1f4 367}
368
c235bbae 369=head2 dbh
370
371Returns the dbh - a data base handle of class L<DBI>.
372
373=cut
374
412db1f4 375sub dbh {
376 my ($self) = @_;
377
378 $self->ensure_connected;
8b445e33 379 return $self->_dbh;
380}
381
48c69e7c 382sub sql_maker {
383 my ($self) = @_;
fdc1c3d0 384 unless ($self->_sql_maker) {
bd7efd39 385 $self->_sql_maker(new DBIC::SQL::Abstract( limit_dialect => $self->dbh ));
48c69e7c 386 }
387 return $self->_sql_maker;
388}
389
1b45b01e 390sub connect_info {
391 my ($self, $info_arg) = @_;
392
393 if($info_arg) {
394 my $info = [ @$info_arg ]; # copy because we can alter it
395 my $last_info = $info->[-1];
396 if(ref $last_info eq 'HASH') {
397 my $used;
398 if(my $on_connect_do = $last_info->{on_connect_do}) {
399 $used = 1;
67008979 400 $self->on_connect_do($on_connect_do);
1b45b01e 401 }
67008979 402 for my $sql_maker_opt (qw/limit_dialect quote_char name_sep/) {
1b45b01e 403 if(my $opt_val = $last_info->{$sql_maker_opt}) {
404 $used = 1;
405 $self->sql_maker->$sql_maker_opt($opt_val);
406 }
407 }
408
409 # remove our options hashref if it was there, to avoid confusing
410 # DBI in the case the user didn't use all 4 DBI options, as in:
411 # [ 'dbi:SQLite:foo.db', { quote_char => q{`} } ]
412 pop(@$info) if $used;
413 }
414
415 $self->_connect_info($info);
416 }
417
418 $self->_connect_info;
419}
420
8b445e33 421sub _populate_dbh {
422 my ($self) = @_;
1b45b01e 423 my @info = @{$self->_connect_info || []};
8b445e33 424 $self->_dbh($self->_connect(@info));
8484b01d 425 my $dbh = $self->_dbh;
426 my $driver = $dbh->{Driver}->{Name};
427 if ( $driver eq 'ODBC' and $dbh->get_info(17) =~ m{^DB2/400} ) {
428 $driver = 'ODBC400';
429 }
34470972 430 eval "require DBIx::Class::Storage::DBI::${driver}";
431 unless ($@) {
843f8ecd 432 bless $self, "DBIx::Class::Storage::DBI::${driver}";
433 }
d7c4c15c 434 # if on-connect sql statements are given execute them
435 foreach my $sql_statement (@{$self->on_connect_do || []}) {
436 $self->_dbh->do($sql_statement);
437 }
22829118 438 $self->on_connect->();
5ef3e508 439
1346e22d 440 $self->_conn_pid($$);
441 $self->_conn_tid(threads->tid) if $INC{'threads.pm'};
8b445e33 442}
443
444sub _connect {
445 my ($self, @info) = @_;
5ef3e508 446
9d31f7dc 447 $self->throw_exception("You failed to provide any connection info")
448 if !@info;
449
90ec6cad 450 my ($old_connect_via, $dbh);
451
5ef3e508 452 if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
90ec6cad 453 $old_connect_via = $DBI::connect_via;
5ef3e508 454 $DBI::connect_via = 'connect';
5ef3e508 455 }
456
75db246c 457 eval {
458 if(ref $info[0] eq 'CODE') {
459 $dbh = &{$info[0]};
460 }
461 else {
462 $dbh = DBI->connect(@info);
463 }
464 };
90ec6cad 465
466 $DBI::connect_via = $old_connect_via if $old_connect_via;
467
75db246c 468 if (!$dbh || $@) {
469 $self->throw_exception("DBI Connection failed: " . ($@ || $DBI::errstr));
470 }
90ec6cad 471
e571e823 472 $dbh;
8b445e33 473}
474
8091aa91 475=head2 txn_begin
8b445e33 476
8091aa91 477Calls begin_work on the current dbh.
8b445e33 478
181a28f4 479See L<DBIx::Class::Schema> for the txn_do() method, which allows for
480an entire code block to be executed transactionally.
481
8b445e33 482=cut
483
8091aa91 484sub txn_begin {
d79f59b9 485 my $self = shift;
a32e8402 486 if ($self->{transaction_depth}++ == 0) {
487 my $dbh = $self->dbh;
488 if ($dbh->{AutoCommit}) {
489 $self->debugfh->print("BEGIN WORK\n")
490 if ($self->debug);
491 $dbh->begin_work;
492 }
986e4fca 493 }
8091aa91 494}
8b445e33 495
8091aa91 496=head2 txn_commit
8b445e33 497
8091aa91 498Issues a commit against the current dbh.
8b445e33 499
8091aa91 500=cut
501
502sub txn_commit {
d79f59b9 503 my $self = shift;
504 if ($self->{transaction_depth} == 0) {
a32e8402 505 my $dbh = $self->dbh;
506 unless ($dbh->{AutoCommit}) {
986e4fca 507 $self->debugfh->print("COMMIT\n")
508 if ($self->debug);
a32e8402 509 $dbh->commit;
986e4fca 510 }
8091aa91 511 }
512 else {
986e4fca 513 if (--$self->{transaction_depth} == 0) {
514 $self->debugfh->print("COMMIT\n")
515 if ($self->debug);
516 $self->dbh->commit;
517 }
8091aa91 518 }
519}
520
521=head2 txn_rollback
522
181a28f4 523Issues a rollback against the current dbh. A nested rollback will
524throw a L<DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION> exception,
525which allows the rollback to propagate to the outermost transaction.
8b445e33 526
527=cut
528
8091aa91 529sub txn_rollback {
d79f59b9 530 my $self = shift;
a62cf8d4 531
532 eval {
533 if ($self->{transaction_depth} == 0) {
a32e8402 534 my $dbh = $self->dbh;
535 unless ($dbh->{AutoCommit}) {
986e4fca 536 $self->debugfh->print("ROLLBACK\n")
537 if ($self->debug);
a32e8402 538 $dbh->rollback;
986e4fca 539 }
a62cf8d4 540 }
541 else {
986e4fca 542 if (--$self->{transaction_depth} == 0) {
543 $self->debugfh->print("ROLLBACK\n")
544 if ($self->debug);
545 $self->dbh->rollback;
546 }
547 else {
1346e22d 548 die DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION->new;
986e4fca 549 }
a62cf8d4 550 }
551 };
552
553 if ($@) {
554 my $error = $@;
555 my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
556 $error =~ /$exception_class/ and $self->throw_exception($error);
557 $self->{transaction_depth} = 0; # ensure that a failed rollback
558 $self->throw_exception($error); # resets the transaction depth
8091aa91 559 }
560}
8b445e33 561
223b8fe3 562sub _execute {
563 my ($self, $op, $extra_bind, $ident, @args) = @_;
564 my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
944f30bf 565 unshift(@bind, @$extra_bind) if $extra_bind;
f59ffc79 566 if ($self->debug) {
e673f011 567 my @debug_bind = map { defined $_ ? qq{'$_'} : q{'NULL'} } @bind;
181a28f4 568 $self->debugfh->print("$sql: " . join(', ', @debug_bind) . "\n");
f59ffc79 569 }
75db246c 570 my $sth = eval { $self->sth($sql,$op) };
571
572 if (!$sth || $@) {
573 $self->throw_exception('no sth generated via sql (' . ($@ || $self->_dbh->errstr) . "): $sql");
574 }
575
438adc0e 576 @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
701da8c4 577 my $rv;
75d07914 578 if ($sth) {
95dad7e2 579 $rv = eval { $sth->execute(@bind) };
580
581 if ($@ || !$rv) {
582 $self->throw_exception("Error executing '$sql': ".($@ || $sth->errstr));
583 }
75d07914 584 } else {
1c339d71 585 $self->throw_exception("'$sql' did not generate a statement.");
701da8c4 586 }
223b8fe3 587 return (wantarray ? ($rv, $sth, @bind) : $rv);
588}
589
8b445e33 590sub insert {
591 my ($self, $ident, $to_insert) = @_;
bc0c9800 592 $self->throw_exception(
593 "Couldn't insert ".join(', ',
594 map "$_ => $to_insert->{$_}", keys %$to_insert
595 )." into ${ident}"
596 ) unless ($self->_execute('insert' => [], $ident, $to_insert));
8b445e33 597 return $to_insert;
598}
599
600sub update {
223b8fe3 601 return shift->_execute('update' => [], @_);
8b445e33 602}
603
604sub delete {
223b8fe3 605 return shift->_execute('delete' => [], @_);
8b445e33 606}
607
de705b51 608sub _select {
8b445e33 609 my ($self, $ident, $select, $condition, $attrs) = @_;
223b8fe3 610 my $order = $attrs->{order_by};
611 if (ref $condition eq 'SCALAR') {
612 $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
613 }
8839560b 614 if (exists $attrs->{group_by} || $attrs->{having}) {
bc0c9800 615 $order = {
616 group_by => $attrs->{group_by},
617 having => $attrs->{having},
618 ($order ? (order_by => $order) : ())
619 };
54540863 620 }
5c91499f 621 my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order);
9229f20a 622 if ($attrs->{software_limit} ||
623 $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
624 $attrs->{software_limit} = 1;
5c91499f 625 } else {
626 push @args, $attrs->{rows}, $attrs->{offset};
627 }
de705b51 628 return $self->_execute(@args);
629}
630
631sub select {
632 my $self = shift;
633 my ($ident, $select, $condition, $attrs) = @_;
cb5f2eea 634 return $self->cursor->new($self, \@_, $attrs);
8b445e33 635}
636
6157db4f 637# Need to call finish() to work round broken DBDs
638
1a14aa3f 639sub select_single {
de705b51 640 my $self = shift;
641 my ($rv, $sth, @bind) = $self->_select(@_);
6157db4f 642 my @row = $sth->fetchrow_array;
643 $sth->finish();
644 return @row;
1a14aa3f 645}
646
8b445e33 647sub sth {
cb5f2eea 648 my ($self, $sql) = @_;
91fa659e 649 # 3 is the if_active parameter which avoids active sth re-use
650 return $self->dbh->prepare_cached($sql, {}, 3);
8b445e33 651}
652
a953d8d9 653=head2 columns_info_for
654
655Returns database type info for a given table columns.
656
657=cut
658
659sub columns_info_for {
0d67fe74 660 my ($self, $table) = @_;
bfe10d87 661
a32e8402 662 my $dbh = $self->dbh;
663
664 if ($dbh->can('column_info')) {
a953d8d9 665 my %result;
a32e8402 666 my $old_raise_err = $dbh->{RaiseError};
667 my $old_print_err = $dbh->{PrintError};
668 $dbh->{RaiseError} = 1;
669 $dbh->{PrintError} = 0;
0d67fe74 670 eval {
4d272ce5 671 my ($schema,$tab) = $table =~ /^(.+?)\.(.+)$/ ? ($1,$2) : (undef,$table);
672 my $sth = $dbh->column_info( undef,$schema, $tab, '%' );
0d67fe74 673 $sth->execute();
674 while ( my $info = $sth->fetchrow_hashref() ){
bfe10d87 675 my %column_info;
0d67fe74 676 $column_info{data_type} = $info->{TYPE_NAME};
677 $column_info{size} = $info->{COLUMN_SIZE};
678 $column_info{is_nullable} = $info->{NULLABLE} ? 1 : 0;
679 $column_info{default_value} = $info->{COLUMN_DEF};
680
681 $result{$info->{COLUMN_NAME}} = \%column_info;
682 }
683 };
a32e8402 684 $dbh->{RaiseError} = $old_raise_err;
685 $dbh->{PrintError} = $old_print_err;
0d67fe74 686 return \%result if !$@;
687 }
688
689 my %result;
a32e8402 690 my $sth = $dbh->prepare("SELECT * FROM $table WHERE 1=0");
0d67fe74 691 $sth->execute;
692 my @columns = @{$sth->{NAME_lc}};
693 for my $i ( 0 .. $#columns ){
694 my %column_info;
695 my $type_num = $sth->{TYPE}->[$i];
696 my $type_name;
a32e8402 697 if(defined $type_num && $dbh->can('type_info')) {
698 my $type_info = $dbh->type_info($type_num);
0d67fe74 699 $type_name = $type_info->{TYPE_NAME} if $type_info;
a953d8d9 700 }
0d67fe74 701 $column_info{data_type} = $type_name ? $type_name : $type_num;
702 $column_info{size} = $sth->{PRECISION}->[$i];
703 $column_info{is_nullable} = $sth->{NULLABLE}->[$i] ? 1 : 0;
704
705 if ($column_info{data_type} =~ m/^(.*?)\((.*?)\)$/) {
706 $column_info{data_type} = $1;
707 $column_info{size} = $2;
708 }
709
710 $result{$columns[$i]} = \%column_info;
711 }
bfe10d87 712
0d67fe74 713 return \%result;
a953d8d9 714}
715
843f8ecd 716sub last_insert_id {
717 my ($self, $row) = @_;
718
719 return $self->dbh->func('last_insert_rowid');
720
721}
722
90ec6cad 723sub sqlt_type { shift->dbh->{Driver}->{Name} }
1c339d71 724
e673f011 725sub create_ddl_dir
726{
4386b954 727 my ($self, $schema, $databases, $version, $dir, $preversion, $sqltargs) = @_;
e673f011 728
729 if(!$dir || !-d $dir)
730 {
731 warn "No directory given, using ./\n";
732 $dir = "./";
733 }
734 $databases ||= ['MySQL', 'SQLite', 'PostgreSQL'];
735 $databases = [ $databases ] if(ref($databases) ne 'ARRAY');
736 $version ||= $schema->VERSION || '1.x';
737
1c339d71 738 eval "use SQL::Translator";
739 $self->throw_exception("Can't deploy without SQL::Translator: $@") if $@;
e673f011 740
741 my $sqlt = SQL::Translator->new({
742# debug => 1,
743 add_drop_table => 1,
744 });
745 foreach my $db (@$databases)
746 {
747 $sqlt->reset();
748 $sqlt->parser('SQL::Translator::Parser::DBIx::Class');
749# $sqlt->parser_args({'DBIx::Class' => $schema);
750 $sqlt->data($schema);
751 $sqlt->producer($db);
752
753 my $file;
4386b954 754 my $filename = $schema->ddl_filename($dir, $db, $version);
e673f011 755 if(-e $filename)
756 {
4386b954 757 warn("$filename already exists, skipping $db");
e673f011 758 next;
759 }
760 open($file, ">$filename")
4386b954 761 or warn("Can't open $filename for writing ($!)"), next;
e673f011 762 my $output = $sqlt->translate;
e673f011 763 if(!$output)
764 {
4386b954 765 warn("Failed to translate to $db, skipping. (" . $sqlt->error . ")");
e673f011 766 next;
767 }
768 print $file $output;
769 close($file);
4386b954 770
771 if($preversion)
772 {
773 eval "use SQL::Translator::Diff";
774 warn("Can't diff versions without SQL::Translator::Diff: $@"), next if $@;
775
776 my $prefilename = $schema->ddl_filename($dir, $db, $preversion);
777 print "Previous version $prefilename\n";
778 if(!-e $prefilename)
779 {
780 warn("No previous schema file found ($prefilename)");
781 next;
782 }
783 #### We need to reparse the SQLite file we just wrote, so that
784 ## Diff doesnt get all confoosed, and Diff is *very* confused.
785 ## FIXME: rip Diff to pieces!
786# my $target_schema = $sqlt->schema;
787# unless ( $target_schema->name ) {
788# $target_schema->name( $filename );
789# }
790 my $sqlt = SQL::Translator->new();
791 $sqlt->parser("SQL::Translator::Parser::$db");
792 $sqlt->filename($filename);
793 $sqlt->translate() or warn("Failed to parse $filename as $db, (" .
794 $sqlt->error . ")"), next;
795 my $target_schema = $sqlt->schema;
796 unless ( $target_schema->name ) {
797 $target_schema->name( $filename );
798 }
799 ## end FIXME
800
801 my $psqlt = SQL::Translator->new();
802 $psqlt->parser("SQL::Translator::Parser::$db");
803 $psqlt->filename($prefilename);
804 $psqlt->translate() or warn("Failed to parse $filename as $db, (" .
805 $sqlt->error . ")"), next ;
806 my $source_schema = $psqlt->schema;
807 unless ( $source_schema->name ) {
808 $source_schema->name( $prefilename );
809 }
810
811 my $diff = SQL::Translator::Diff::schema_diff($source_schema, $db,
812 $target_schema, $db,
813 {}
814 );
200427a4 815 my $difffile = $schema->ddl_filename($dir, $db, $version, $preversion);
4386b954 816 if(-e $difffile)
817 {
818 warn("$difffile already exists, skipping");
819 next;
820 }
821 open $file, ">$difffile" or
822 warn("Can't write to $difffile ($!)"), next;
823 print $file $diff;
824 close($file);
825 }
e673f011 826 }
827
828}
829
830sub deployment_statements {
831 my ($self, $schema, $type, $version, $dir, $sqltargs) = @_;
832 $type ||= $self->sqlt_type;
833 $version ||= $schema->VERSION || '1.x';
834 $dir ||= './';
0382d607 835 eval "use SQL::Translator";
836 if(!$@)
837 {
838 eval "use SQL::Translator::Parser::DBIx::Class;";
839 $self->throw_exception($@) if $@;
840 eval "use SQL::Translator::Producer::${type};";
841 $self->throw_exception($@) if $@;
842 my $tr = SQL::Translator->new(%$sqltargs);
843 SQL::Translator::Parser::DBIx::Class::parse( $tr, $schema );
844 return "SQL::Translator::Producer::${type}"->can('produce')->($tr);
845 }
e673f011 846
4386b954 847 my $filename = $schema->ddl_filename($dir, $type, $version);
e673f011 848 if(!-f $filename)
849 {
0382d607 850# $schema->create_ddl_dir([ $type ], $version, $dir, $sqltargs);
851 $self->throw_exception("No SQL::Translator, and no Schema file found, aborting deploy");
852 return;
e673f011 853 }
854 my $file;
855 open($file, "<$filename")
856 or $self->throw_exception("Can't open $filename ($!)");
857 my @rows = <$file>;
858 close($file);
859
860 return join('', @rows);
861
1c339d71 862}
843f8ecd 863
1c339d71 864sub deploy {
cb561d1a 865 my ($self, $schema, $type, $sqltargs) = @_;
e673f011 866 foreach my $statement ( $self->deployment_statements($schema, $type, undef, undef, $sqltargs) ) {
e4fe9ba3 867 for ( split(";\n", $statement)) {
e673f011 868 next if($_ =~ /^--/);
869 next if(!$_);
870# next if($_ =~ /^DROP/m);
871 next if($_ =~ /^BEGIN TRANSACTION/m);
872 next if($_ =~ /^COMMIT/m);
e4fe9ba3 873 $self->debugfh->print("$_\n") if $self->debug;
874 $self->dbh->do($_) or warn "SQL was:\n $_";
875 }
75d07914 876 }
1c339d71 877}
843f8ecd 878
200427a4 879sub backup
880{
881 my ($self) = @_;
882
883 ## Does nothing, override in DBI::XX classes
884}
885
92925617 886sub DESTROY { shift->disconnect }
887
8b445e33 8881;
889
92b858c9 890=head1 ENVIRONMENT VARIABLES
891
892=head2 DBIX_CLASS_STORAGE_DBI_DEBUG
893
894If C<DBIX_CLASS_STORAGE_DBI_DEBUG> is set then SQL trace information
895is produced (as when the L<debug> method is set).
896
897If the value is of the form C<1=/path/name> then the trace output is
898written to the file C</path/name>.
899
8b445e33 900=head1 AUTHORS
901
daec44b8 902Matt S. Trout <mst@shadowcatsystems.co.uk>
8b445e33 903
9f19b1d6 904Andy Grundman <andy@hybridized.org>
905
4386b954 906Jess Robinson <castaway@desert-island.demon.co.uk>
907
8b445e33 908=head1 LICENSE
909
910You may distribute this code under the same terms as Perl itself.
911
912=cut
913