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