Back to on_connect in connection, rather than populate_dbh, deploy ensures its connected
[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
439   $self->_conn_pid($$);
440   $self->_conn_tid(threads->tid) if $INC{'threads.pm'};
441 }
442
443 sub _connect {
444   my ($self, @info) = @_;
445
446   $self->throw_exception("You failed to provide any connection info")
447       if !@info;
448
449   my ($old_connect_via, $dbh);
450
451   if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
452       $old_connect_via = $DBI::connect_via;
453       $DBI::connect_via = 'connect';
454   }
455
456   eval {
457     if(ref $info[0] eq 'CODE') {
458         $dbh = &{$info[0]};
459     }
460     else {
461         $dbh = DBI->connect(@info);
462     }
463   };
464
465   $DBI::connect_via = $old_connect_via if $old_connect_via;
466
467   if (!$dbh || $@) {
468     $self->throw_exception("DBI Connection failed: " . ($@ || $DBI::errstr));
469   }
470
471   $dbh;
472 }
473
474 =head2 txn_begin
475
476 Calls begin_work on the current dbh.
477
478 See L<DBIx::Class::Schema> for the txn_do() method, which allows for
479 an entire code block to be executed transactionally.
480
481 =cut
482
483 sub txn_begin {
484   my $self = shift;
485   if ($self->{transaction_depth}++ == 0) {
486     my $dbh = $self->dbh;
487     if ($dbh->{AutoCommit}) {
488       $self->debugfh->print("BEGIN WORK\n")
489         if ($self->debug);
490       $dbh->begin_work;
491     }
492   }
493 }
494
495 =head2 txn_commit
496
497 Issues a commit against the current dbh.
498
499 =cut
500
501 sub txn_commit {
502   my $self = shift;
503   if ($self->{transaction_depth} == 0) {
504     my $dbh = $self->dbh;
505     unless ($dbh->{AutoCommit}) {
506       $self->debugfh->print("COMMIT\n")
507         if ($self->debug);
508       $dbh->commit;
509     }
510   }
511   else {
512     if (--$self->{transaction_depth} == 0) {
513       $self->debugfh->print("COMMIT\n")
514         if ($self->debug);
515       $self->dbh->commit;
516     }
517   }
518 }
519
520 =head2 txn_rollback
521
522 Issues a rollback against the current dbh. A nested rollback will
523 throw a L<DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION> exception,
524 which allows the rollback to propagate to the outermost transaction.
525
526 =cut
527
528 sub txn_rollback {
529   my $self = shift;
530
531   eval {
532     if ($self->{transaction_depth} == 0) {
533       my $dbh = $self->dbh;
534       unless ($dbh->{AutoCommit}) {
535         $self->debugfh->print("ROLLBACK\n")
536           if ($self->debug);
537         $dbh->rollback;
538       }
539     }
540     else {
541       if (--$self->{transaction_depth} == 0) {
542         $self->debugfh->print("ROLLBACK\n")
543           if ($self->debug);
544         $self->dbh->rollback;
545       }
546       else {
547         die DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION->new;
548       }
549     }
550   };
551
552   if ($@) {
553     my $error = $@;
554     my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
555     $error =~ /$exception_class/ and $self->throw_exception($error);
556     $self->{transaction_depth} = 0;          # ensure that a failed rollback
557     $self->throw_exception($error);          # resets the transaction depth
558   }
559 }
560
561 sub _execute {
562   my ($self, $op, $extra_bind, $ident, @args) = @_;
563   my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
564   unshift(@bind, @$extra_bind) if $extra_bind;
565   if ($self->debug) {
566       my @debug_bind = map { defined $_ ? qq{'$_'} : q{'NULL'} } @bind;
567       $self->debugfh->print("$sql: " . join(', ', @debug_bind) . "\n");
568   }
569   my $sth = eval { $self->sth($sql,$op) };
570
571   if (!$sth || $@) {
572     $self->throw_exception('no sth generated via sql (' . ($@ || $self->_dbh->errstr) . "): $sql");
573   }
574
575   @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
576   my $rv;
577   if ($sth) {
578     $rv = eval { $sth->execute(@bind) };
579
580     if ($@ || !$rv) {
581       $self->throw_exception("Error executing '$sql': ".($@ || $sth->errstr));
582     }
583   } else {
584     $self->throw_exception("'$sql' did not generate a statement.");
585   }
586   return (wantarray ? ($rv, $sth, @bind) : $rv);
587 }
588
589 sub insert {
590   my ($self, $ident, $to_insert) = @_;
591   $self->throw_exception(
592     "Couldn't insert ".join(', ',
593       map "$_ => $to_insert->{$_}", keys %$to_insert
594     )." into ${ident}"
595   ) unless ($self->_execute('insert' => [], $ident, $to_insert));
596   return $to_insert;
597 }
598
599 sub update {
600   return shift->_execute('update' => [], @_);
601 }
602
603 sub delete {
604   return shift->_execute('delete' => [], @_);
605 }
606
607 sub _select {
608   my ($self, $ident, $select, $condition, $attrs) = @_;
609   my $order = $attrs->{order_by};
610   if (ref $condition eq 'SCALAR') {
611     $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
612   }
613   if (exists $attrs->{group_by} || $attrs->{having}) {
614     $order = {
615       group_by => $attrs->{group_by},
616       having => $attrs->{having},
617       ($order ? (order_by => $order) : ())
618     };
619   }
620   my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order);
621   if ($attrs->{software_limit} ||
622       $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
623         $attrs->{software_limit} = 1;
624   } else {
625     push @args, $attrs->{rows}, $attrs->{offset};
626   }
627   return $self->_execute(@args);
628 }
629
630 sub select {
631   my $self = shift;
632   my ($ident, $select, $condition, $attrs) = @_;
633   return $self->cursor->new($self, \@_, $attrs);
634 }
635
636 # Need to call finish() to work round broken DBDs
637
638 sub select_single {
639   my $self = shift;
640   my ($rv, $sth, @bind) = $self->_select(@_);
641   my @row = $sth->fetchrow_array;
642   $sth->finish();
643   return @row;
644 }
645
646 sub sth {
647   my ($self, $sql) = @_;
648   # 3 is the if_active parameter which avoids active sth re-use
649   return $self->dbh->prepare_cached($sql, {}, 3);
650 }
651
652 =head2 columns_info_for
653
654 Returns database type info for a given table columns.
655
656 =cut
657
658 sub columns_info_for {
659   my ($self, $table) = @_;
660
661   my $dbh = $self->dbh;
662
663   if ($dbh->can('column_info')) {
664     my %result;
665     my $old_raise_err = $dbh->{RaiseError};
666     my $old_print_err = $dbh->{PrintError};
667     $dbh->{RaiseError} = 1;
668     $dbh->{PrintError} = 0;
669     eval {
670       my ($schema,$tab) = $table =~ /^(.+?)\.(.+)$/ ? ($1,$2) : (undef,$table);
671       my $sth = $dbh->column_info( undef,$schema, $tab, '%' );
672       $sth->execute();
673       while ( my $info = $sth->fetchrow_hashref() ){
674         my %column_info;
675         $column_info{data_type}   = $info->{TYPE_NAME};
676         $column_info{size}      = $info->{COLUMN_SIZE};
677         $column_info{is_nullable}   = $info->{NULLABLE} ? 1 : 0;
678         $column_info{default_value} = $info->{COLUMN_DEF};
679
680         $result{$info->{COLUMN_NAME}} = \%column_info;
681       }
682     };
683     $dbh->{RaiseError} = $old_raise_err;
684     $dbh->{PrintError} = $old_print_err;
685     return \%result if !$@;
686   }
687
688   my %result;
689   my $sth = $dbh->prepare("SELECT * FROM $table WHERE 1=0");
690   $sth->execute;
691   my @columns = @{$sth->{NAME_lc}};
692   for my $i ( 0 .. $#columns ){
693     my %column_info;
694     my $type_num = $sth->{TYPE}->[$i];
695     my $type_name;
696     if(defined $type_num && $dbh->can('type_info')) {
697       my $type_info = $dbh->type_info($type_num);
698       $type_name = $type_info->{TYPE_NAME} if $type_info;
699     }
700     $column_info{data_type} = $type_name ? $type_name : $type_num;
701     $column_info{size} = $sth->{PRECISION}->[$i];
702     $column_info{is_nullable} = $sth->{NULLABLE}->[$i] ? 1 : 0;
703
704     if ($column_info{data_type} =~ m/^(.*?)\((.*?)\)$/) {
705       $column_info{data_type} = $1;
706       $column_info{size}    = $2;
707     }
708
709     $result{$columns[$i]} = \%column_info;
710   }
711
712   return \%result;
713 }
714
715 sub last_insert_id {
716   my ($self, $row) = @_;
717     
718   return $self->dbh->func('last_insert_rowid');
719
720 }
721
722 sub sqlt_type { shift->dbh->{Driver}->{Name} }
723
724 sub create_ddl_dir
725 {
726   my ($self, $schema, $databases, $version, $dir, $preversion, $sqltargs) = @_;
727
728   if(!$dir || !-d $dir)
729   {
730     warn "No directory given, using ./\n";
731     $dir = "./";
732   }
733   $databases ||= ['MySQL', 'SQLite', 'PostgreSQL'];
734   $databases = [ $databases ] if(ref($databases) ne 'ARRAY');
735   $version ||= $schema->VERSION || '1.x';
736
737   eval "use SQL::Translator";
738   $self->throw_exception("Can't deploy without SQL::Translator: $@") if $@;
739
740   my $sqlt = SQL::Translator->new({
741 #      debug => 1,
742       add_drop_table => 1,
743   });
744   foreach my $db (@$databases)
745   {
746     $sqlt->reset();
747     $sqlt->parser('SQL::Translator::Parser::DBIx::Class');
748 #    $sqlt->parser_args({'DBIx::Class' => $schema);
749     $sqlt->data($schema);
750     $sqlt->producer($db);
751
752     my $file;
753     my $filename = $schema->ddl_filename($dir, $db, $version);
754     if(-e $filename)
755     {
756       warn("$filename already exists, skipping $db");
757       next;
758     }
759     open($file, ">$filename") 
760       or warn("Can't open $filename for writing ($!)"), next;
761     my $output = $sqlt->translate;
762     if(!$output)
763     {
764       warn("Failed to translate to $db, skipping. (" . $sqlt->error . ")");
765       next;
766     }
767     print $file $output;
768     close($file);
769
770     if($preversion)
771     {
772       eval "use SQL::Translator::Diff";
773       warn("Can't diff versions without SQL::Translator::Diff: $@"), next if $@;
774
775       my $prefilename = $schema->ddl_filename($dir, $db, $preversion);
776       print "Previous version $prefilename\n";
777       if(!-e $prefilename)
778       {
779         warn("No previous schema file found ($prefilename)");
780         next;
781       }
782       #### We need to reparse the SQLite file we just wrote, so that 
783       ##   Diff doesnt get all confoosed, and Diff is *very* confused.
784       ##   FIXME: rip Diff to pieces!
785 #      my $target_schema = $sqlt->schema;
786 #      unless ( $target_schema->name ) {
787 #        $target_schema->name( $filename );
788 #      }
789       my $sqlt = SQL::Translator->new();
790       $sqlt->parser("SQL::Translator::Parser::$db");
791       $sqlt->filename($filename);
792       $sqlt->translate() or warn("Failed to parse $filename as $db, (" .
793                                  $sqlt->error . ")"), next;
794       my $target_schema = $sqlt->schema;
795       unless ( $target_schema->name ) {
796         $target_schema->name( $filename );
797       }
798       ## end FIXME
799
800       my $psqlt = SQL::Translator->new();
801       $psqlt->parser("SQL::Translator::Parser::$db");
802       $psqlt->filename($prefilename);
803       $psqlt->translate() or warn("Failed to parse $filename as $db, (" .
804                                   $sqlt->error . ")"), next ;
805       my $source_schema = $psqlt->schema;
806       unless ( $source_schema->name ) {
807         $source_schema->name( $prefilename );
808       }
809
810       my $diff = SQL::Translator::Diff::schema_diff($source_schema, $db,
811                                                     $target_schema, $db,
812                                                     {}
813                                                    );
814       my $difffile = $schema->ddl_filename($dir, $db, $version, $preversion);
815       if(-e $difffile)
816       {
817         warn("$difffile already exists, skipping");
818         next;
819       }
820       open $file, ">$difffile" or 
821         warn("Can't write to $difffile ($!)"), next;
822       print $file $diff;
823       close($file);
824     }
825   }
826
827 }
828
829 sub deployment_statements {
830   my ($self, $schema, $type, $version, $dir, $sqltargs) = @_;
831   $type ||= $self->sqlt_type;
832   $version ||= $schema->VERSION || '1.x';
833   $dir ||= './';
834   eval "use SQL::Translator";
835   if(!$@)
836   {
837     eval "use SQL::Translator::Parser::DBIx::Class;";
838     $self->throw_exception($@) if $@;
839     eval "use SQL::Translator::Producer::${type};";
840     $self->throw_exception($@) if $@;
841     my $tr = SQL::Translator->new(%$sqltargs);
842     SQL::Translator::Parser::DBIx::Class::parse( $tr, $schema );
843     return "SQL::Translator::Producer::${type}"->can('produce')->($tr);
844   }
845
846   my $filename = $schema->ddl_filename($dir, $type, $version);
847   if(!-f $filename)
848   {
849 #      $schema->create_ddl_dir([ $type ], $version, $dir, $sqltargs);
850       $self->throw_exception("No SQL::Translator, and no Schema file found, aborting deploy");
851       return;
852   }
853   my $file;
854   open($file, "<$filename") 
855       or $self->throw_exception("Can't open $filename ($!)");
856   my @rows = <$file>;
857   close($file);
858
859   return join('', @rows);
860   
861 }
862
863 sub deploy {
864   my ($self, $schema, $type, $sqltargs) = @_;
865   foreach my $statement ( $self->deployment_statements($schema, $type, undef, undef, $sqltargs) ) {
866     for ( split(";\n", $statement)) {
867       next if($_ =~ /^--/);
868       next if(!$_);
869 #      next if($_ =~ /^DROP/m);
870       next if($_ =~ /^BEGIN TRANSACTION/m);
871       next if($_ =~ /^COMMIT/m);
872       $self->debugfh->print("$_\n") if $self->debug;
873       $self->dbh->do($_) or warn "SQL was:\n $_";
874     }
875   }
876 }
877
878 sub backup
879 {
880   my ($self) = @_;
881
882   ## Does nothing, override in DBI::XX classes
883 }
884
885 sub DESTROY { shift->disconnect }
886
887 1;
888
889 =head1 ENVIRONMENT VARIABLES
890
891 =head2 DBIX_CLASS_STORAGE_DBI_DEBUG
892
893 If C<DBIX_CLASS_STORAGE_DBI_DEBUG> is set then SQL trace information
894 is produced (as when the L<debug> method is set).
895
896 If the value is of the form C<1=/path/name> then the trace output is
897 written to the file C</path/name>.
898
899 =head1 AUTHORS
900
901 Matt S. Trout <mst@shadowcatsystems.co.uk>
902
903 Andy Grundman <andy@hybridized.org>
904
905 Jess Robinson <castaway@desert-island.demon.co.uk>
906
907 =head1 LICENSE
908
909 You may distribute this code under the same terms as Perl itself.
910
911 =cut
912