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