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