Call on_connect AFTER actual connection, so we have the correct sqlt_type
[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 Storable 'dclone';
13 use Carp::Clan qw/DBIx::Class/;
14
15 BEGIN {
16
17 package DBIC::SQL::Abstract; # Would merge upstream, but nate doesn't reply :(
18
19 use base qw/SQL::Abstract::Limit/;
20
21 sub select {
22   my ($self, $table, $fields, $where, $order, @rest) = @_;
23   $table = $self->_quote($table) unless ref($table);
24   @rest = (-1) unless defined $rest[0];
25   local $self->{having_bind} = [];
26   my ($sql, @ret) = $self->SUPER::select(
27     $table, $self->_recurse_fields($fields), $where, $order, @rest
28   );
29   return wantarray ? ($sql, @ret, @{$self->{having_bind}}) : $sql;
30 }
31
32 sub insert {
33   my $self = shift;
34   my $table = shift;
35   $table = $self->_quote($table) unless ref($table);
36   $self->SUPER::insert($table, @_);
37 }
38
39 sub update {
40   my $self = shift;
41   my $table = shift;
42   $table = $self->_quote($table) unless ref($table);
43   $self->SUPER::update($table, @_);
44 }
45
46 sub delete {
47   my $self = shift;
48   my $table = shift;
49   $table = $self->_quote($table) unless ref($table);
50   $self->SUPER::delete($table, @_);
51 }
52
53 sub _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
62 sub _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
78 sub _order_by {
79   my $self = shift;
80   my $ret = '';
81   my @extra;
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     }
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     }
93     if (defined $_[0]->{order_by}) {
94       $ret .= $self->SUPER::_order_by($_[0]->{order_by});
95     }
96   } elsif(ref $_[0] eq 'SCALAR') {
97     $ret = $self->_sqlcase(' order by ').${ $_[0] };
98   } else {
99     $ret = $self->SUPER::_order_by(@_);
100   }
101   return $ret;
102 }
103
104 sub _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
110 sub _table {
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 {
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
123   }
124 }
125
126 sub _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;
132
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     }
140     push(@sqlf, $join_clause);
141
142     if (ref $to eq 'ARRAY') {
143       push(@sqlf, '(', $self->_recurse_from(@$to), ')');
144     } else {
145       push(@sqlf, $self->_make_as($to));
146     }
147     push(@sqlf, ' ON ', $self->_join_condition($on));
148   }
149   return join('', @sqlf);
150 }
151
152 sub _make_as {
153   my ($self, $from) = @_;
154   return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) }
155                      reverse each %{$self->_skip_options($from)});
156 }
157
158 sub _skip_options {
159   my ($self, $hash) = @_;
160   my $clean_hash = {};
161   $clean_hash->{$_} = $hash->{$_}
162     for grep {!/^-/} keys %$hash;
163   return $clean_hash;
164 }
165
166 sub _join_condition {
167   my ($self, $cond) = @_;
168   if (ref $cond eq 'HASH') {
169     my %j;
170     for (keys %$cond) {
171       my $x = '= '.$self->_quote($cond->{$_}); $j{$_} = \$x;
172     };
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   }
179 }
180
181 sub _quote {
182   my ($self, $label) = @_;
183   return '' unless defined $label;
184   return "*" if $label eq '*';
185   return $label unless $self->{quote_char};
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   }
194   return $self->SUPER::_quote($label);
195 }
196
197 sub _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
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 #
209 sub limit_dialect {
210     my $self = shift;
211     $self->{limit_dialect} = shift if @_;
212     return $self->{limit_dialect};
213 }
214
215 sub quote_char {
216     my $self = shift;
217     $self->{quote_char} = shift if @_;
218     return $self->{quote_char};
219 }
220
221 sub name_sep {
222     my $self = shift;
223     $self->{name_sep} = shift if @_;
224     return $self->{name_sep};
225 }
226
227
228
229
230 package DBIx::Class::Storage::DBI::DebugCallback;
231
232 sub print {
233   my ($self, $string) = @_;
234   $string =~ m/^(\w+)/;
235   ${$self}->($1, $string);
236 }
237
238 } # End of BEGIN block
239
240 use base qw/DBIx::Class/;
241
242 __PACKAGE__->load_components(qw/AccessorGroup/);
243
244 __PACKAGE__->mk_group_accessors('simple' =>
245   qw/_connect_info _dbh _sql_maker _conn_pid _conn_tid debug debugfh
246      cursor on_connect_do on_connect transaction_depth/);
247
248 sub new {
249   my $new = bless({}, ref $_[0] || $_[0]);
250   $new->cursor("DBIx::Class::Storage::DBI::Cursor");
251   $new->transaction_depth(0);
252   if (defined($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG}) &&
253      ($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG} =~ /=(.+)$/)) {
254     $new->debugfh(IO::File->new($1, 'w'))
255       or $new->throw_exception("Cannot open trace file $1");
256   } else {
257     $new->debugfh(IO::File->new('>&STDERR'));
258   }
259   $new->debug(1) if $ENV{DBIX_CLASS_STORAGE_DBI_DEBUG};
260   return $new;
261 }
262
263 sub throw_exception {
264   my ($self, $msg) = @_;
265   croak($msg);
266 }
267
268 =head1 NAME
269
270 DBIx::Class::Storage::DBI - DBI storage handler
271
272 =head1 SYNOPSIS
273
274 =head1 DESCRIPTION
275
276 This class represents the connection to the database
277
278 =head1 METHODS
279
280 =cut
281
282 =head2 connect_info
283
284 Connection information arrayref.  Can either be the same arguments
285 one would pass to DBI->connect, or a code-reference which returns
286 a connected database handle.  In either case, there is an optional
287 final element in the arrayref, which can hold a hashref of
288 connection-specific Storage::DBI options.  These include
289 C<on_connect_do>, and the sql_maker options C<limit_dialect>,
290 C<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
301 =head2 on_connect_do
302
303 Executes the sql statements given as a listref on every db connect.
304
305 =head2 debug
306
307 Causes 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
312 Sets or retrieves the filehandle used for trace/debug output.  This
313 should be an IO::Handle compatible object (only the C<print> method is
314 used).  Initially set to be STDERR - although see information on the
315 L<DBIX_CLASS_STORAGE_DBI_DEBUG> environment variable.
316
317 =head2 debugcb
318
319 Sets a callback to be executed each time a statement is run; takes a sub
320 reference. Overrides debugfh. Callback is executed as $sub->($op, $info)
321 where $op is SELECT/INSERT/UPDATE/DELETE and $info is what would normally
322 be printed.
323
324 =cut
325
326 sub debugcb {
327   my ($self, $cb) = @_;
328   my $cb_obj = bless(\$cb, 'DBIx::Class::Storage::DBI::DebugCallback');
329   $self->debugfh($cb_obj);
330 }
331
332 sub disconnect {
333   my ($self) = @_;
334
335   if( $self->connected ) {
336     $self->_dbh->rollback unless $self->_dbh->{AutoCommit};
337     $self->_dbh->disconnect;
338     $self->_dbh(undef);
339   }
340 }
341
342 sub connected {
343   my ($self) = @_;
344
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;
359 }
360
361 sub ensure_connected {
362   my ($self) = @_;
363
364   unless ($self->connected) {
365     $self->_populate_dbh;
366   }
367 }
368
369 =head2 dbh
370
371 Returns the dbh - a data base handle of class L<DBI>.
372
373 =cut
374
375 sub dbh {
376   my ($self) = @_;
377
378   $self->ensure_connected;
379   return $self->_dbh;
380 }
381
382 sub sql_maker {
383   my ($self) = @_;
384   unless ($self->_sql_maker) {
385     $self->_sql_maker(new DBIC::SQL::Abstract( limit_dialect => $self->dbh ));
386   }
387   return $self->_sql_maker;
388 }
389
390 sub 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;
400                $self->on_connect_do($on_connect_do);
401             }
402             for my $sql_maker_opt (qw/limit_dialect quote_char name_sep/) {
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
421 sub _populate_dbh {
422   my ($self) = @_;
423   my @info = @{$self->_connect_info || []};
424   $self->_dbh($self->_connect(@info));
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   }
430   eval "require DBIx::Class::Storage::DBI::${driver}";
431   unless ($@) {
432     bless $self, "DBIx::Class::Storage::DBI::${driver}";
433   }
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   }
438   $self->on_connect->();
439
440   $self->_conn_pid($$);
441   $self->_conn_tid(threads->tid) if $INC{'threads.pm'};
442 }
443
444 sub _connect {
445   my ($self, @info) = @_;
446
447   $self->throw_exception("You failed to provide any connection info")
448       if !@info;
449
450   my ($old_connect_via, $dbh);
451
452   if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
453       $old_connect_via = $DBI::connect_via;
454       $DBI::connect_via = 'connect';
455   }
456
457   eval {
458     if(ref $info[0] eq 'CODE') {
459         $dbh = &{$info[0]};
460     }
461     else {
462         $dbh = DBI->connect(@info);
463     }
464   };
465
466   $DBI::connect_via = $old_connect_via if $old_connect_via;
467
468   if (!$dbh || $@) {
469     $self->throw_exception("DBI Connection failed: " . ($@ || $DBI::errstr));
470   }
471
472   $dbh;
473 }
474
475 =head2 txn_begin
476
477 Calls begin_work on the current dbh.
478
479 See L<DBIx::Class::Schema> for the txn_do() method, which allows for
480 an entire code block to be executed transactionally.
481
482 =cut
483
484 sub txn_begin {
485   my $self = shift;
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     }
493   }
494 }
495
496 =head2 txn_commit
497
498 Issues a commit against the current dbh.
499
500 =cut
501
502 sub txn_commit {
503   my $self = shift;
504   if ($self->{transaction_depth} == 0) {
505     my $dbh = $self->dbh;
506     unless ($dbh->{AutoCommit}) {
507       $self->debugfh->print("COMMIT\n")
508         if ($self->debug);
509       $dbh->commit;
510     }
511   }
512   else {
513     if (--$self->{transaction_depth} == 0) {
514       $self->debugfh->print("COMMIT\n")
515         if ($self->debug);
516       $self->dbh->commit;
517     }
518   }
519 }
520
521 =head2 txn_rollback
522
523 Issues a rollback against the current dbh. A nested rollback will
524 throw a L<DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION> exception,
525 which allows the rollback to propagate to the outermost transaction.
526
527 =cut
528
529 sub txn_rollback {
530   my $self = shift;
531
532   eval {
533     if ($self->{transaction_depth} == 0) {
534       my $dbh = $self->dbh;
535       unless ($dbh->{AutoCommit}) {
536         $self->debugfh->print("ROLLBACK\n")
537           if ($self->debug);
538         $dbh->rollback;
539       }
540     }
541     else {
542       if (--$self->{transaction_depth} == 0) {
543         $self->debugfh->print("ROLLBACK\n")
544           if ($self->debug);
545         $self->dbh->rollback;
546       }
547       else {
548         die DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION->new;
549       }
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
559   }
560 }
561
562 sub _execute {
563   my ($self, $op, $extra_bind, $ident, @args) = @_;
564   my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
565   unshift(@bind, @$extra_bind) if $extra_bind;
566   if ($self->debug) {
567       my @debug_bind = map { defined $_ ? qq{'$_'} : q{'NULL'} } @bind;
568       $self->debugfh->print("$sql: " . join(', ', @debug_bind) . "\n");
569   }
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
576   @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
577   my $rv;
578   if ($sth) {
579     $rv = eval { $sth->execute(@bind) };
580
581     if ($@ || !$rv) {
582       $self->throw_exception("Error executing '$sql': ".($@ || $sth->errstr));
583     }
584   } else {
585     $self->throw_exception("'$sql' did not generate a statement.");
586   }
587   return (wantarray ? ($rv, $sth, @bind) : $rv);
588 }
589
590 sub insert {
591   my ($self, $ident, $to_insert) = @_;
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));
597   return $to_insert;
598 }
599
600 sub update {
601   return shift->_execute('update' => [], @_);
602 }
603
604 sub delete {
605   return shift->_execute('delete' => [], @_);
606 }
607
608 sub _select {
609   my ($self, $ident, $select, $condition, $attrs) = @_;
610   my $order = $attrs->{order_by};
611   if (ref $condition eq 'SCALAR') {
612     $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
613   }
614   if (exists $attrs->{group_by} || $attrs->{having}) {
615     $order = {
616       group_by => $attrs->{group_by},
617       having => $attrs->{having},
618       ($order ? (order_by => $order) : ())
619     };
620   }
621   my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order);
622   if ($attrs->{software_limit} ||
623       $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
624         $attrs->{software_limit} = 1;
625   } else {
626     push @args, $attrs->{rows}, $attrs->{offset};
627   }
628   return $self->_execute(@args);
629 }
630
631 sub select {
632   my $self = shift;
633   my ($ident, $select, $condition, $attrs) = @_;
634   return $self->cursor->new($self, \@_, $attrs);
635 }
636
637 # Need to call finish() to work round broken DBDs
638
639 sub select_single {
640   my $self = shift;
641   my ($rv, $sth, @bind) = $self->_select(@_);
642   my @row = $sth->fetchrow_array;
643   $sth->finish();
644   return @row;
645 }
646
647 sub sth {
648   my ($self, $sql) = @_;
649   # 3 is the if_active parameter which avoids active sth re-use
650   return $self->dbh->prepare_cached($sql, {}, 3);
651 }
652
653 =head2 columns_info_for
654
655 Returns database type info for a given table columns.
656
657 =cut
658
659 sub columns_info_for {
660   my ($self, $table) = @_;
661
662   my $dbh = $self->dbh;
663
664   if ($dbh->can('column_info')) {
665     my %result;
666     my $old_raise_err = $dbh->{RaiseError};
667     my $old_print_err = $dbh->{PrintError};
668     $dbh->{RaiseError} = 1;
669     $dbh->{PrintError} = 0;
670     eval {
671       my ($schema,$tab) = $table =~ /^(.+?)\.(.+)$/ ? ($1,$2) : (undef,$table);
672       my $sth = $dbh->column_info( undef,$schema, $tab, '%' );
673       $sth->execute();
674       while ( my $info = $sth->fetchrow_hashref() ){
675         my %column_info;
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     };
684     $dbh->{RaiseError} = $old_raise_err;
685     $dbh->{PrintError} = $old_print_err;
686     return \%result if !$@;
687   }
688
689   my %result;
690   my $sth = $dbh->prepare("SELECT * FROM $table WHERE 1=0");
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;
697     if(defined $type_num && $dbh->can('type_info')) {
698       my $type_info = $dbh->type_info($type_num);
699       $type_name = $type_info->{TYPE_NAME} if $type_info;
700     }
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   }
712
713   return \%result;
714 }
715
716 sub last_insert_id {
717   my ($self, $row) = @_;
718     
719   return $self->dbh->func('last_insert_rowid');
720
721 }
722
723 sub sqlt_type { shift->dbh->{Driver}->{Name} }
724
725 sub create_ddl_dir
726 {
727   my ($self, $schema, $databases, $version, $dir, $preversion, $sqltargs) = @_;
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
738   eval "use SQL::Translator";
739   $self->throw_exception("Can't deploy without SQL::Translator: $@") if $@;
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;
754     my $filename = $schema->ddl_filename($dir, $db, $version);
755     if(-e $filename)
756     {
757       warn("$filename already exists, skipping $db");
758       next;
759     }
760     open($file, ">$filename") 
761       or warn("Can't open $filename for writing ($!)"), next;
762     my $output = $sqlt->translate;
763     if(!$output)
764     {
765       warn("Failed to translate to $db, skipping. (" . $sqlt->error . ")");
766       next;
767     }
768     print $file $output;
769     close($file);
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                                                    );
815       my $difffile = $schema->ddl_filename($dir, $db, $version, $preversion);
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     }
826   }
827
828 }
829
830 sub deployment_statements {
831   my ($self, $schema, $type, $version, $dir, $sqltargs) = @_;
832   $type ||= $self->sqlt_type;
833   $version ||= $schema->VERSION || '1.x';
834   $dir ||= './';
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   }
846
847   my $filename = $schema->ddl_filename($dir, $type, $version);
848   if(!-f $filename)
849   {
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;
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   
862 }
863
864 sub deploy {
865   my ($self, $schema, $type, $sqltargs) = @_;
866   foreach my $statement ( $self->deployment_statements($schema, $type, undef, undef, $sqltargs) ) {
867     for ( split(";\n", $statement)) {
868       next if($_ =~ /^--/);
869       next if(!$_);
870 #      next if($_ =~ /^DROP/m);
871       next if($_ =~ /^BEGIN TRANSACTION/m);
872       next if($_ =~ /^COMMIT/m);
873       $self->debugfh->print("$_\n") if $self->debug;
874       $self->dbh->do($_) or warn "SQL was:\n $_";
875     }
876   }
877 }
878
879 sub backup
880 {
881   my ($self) = @_;
882
883   ## Does nothing, override in DBI::XX classes
884 }
885
886 sub DESTROY { shift->disconnect }
887
888 1;
889
890 =head1 ENVIRONMENT VARIABLES
891
892 =head2 DBIX_CLASS_STORAGE_DBI_DEBUG
893
894 If C<DBIX_CLASS_STORAGE_DBI_DEBUG> is set then SQL trace information
895 is produced (as when the L<debug> method is set).
896
897 If the value is of the form C<1=/path/name> then the trace output is
898 written to the file C</path/name>.
899
900 =head1 AUTHORS
901
902 Matt S. Trout <mst@shadowcatsystems.co.uk>
903
904 Andy Grundman <andy@hybridized.org>
905
906 Jess Robinson <castaway@desert-island.demon.co.uk>
907
908 =head1 LICENSE
909
910 You may distribute this code under the same terms as Perl itself.
911
912 =cut
913