Add IF EXISTS to DROP INDEX (except under MySQL)
[DBIx-DBSchema.git] / DBSchema / Table.pm
index b150d30..67e2eea 100644 (file)
@@ -5,9 +5,9 @@ use Carp;
 use DBIx::DBSchema::_util qw(_load_driver _dbh _parse_opt);
 use DBIx::DBSchema::Column 0.14;
 use DBIx::DBSchema::Index;
-use DBIx::DBSchema::ForeignKey;
+use DBIx::DBSchema::ForeignKey 0.13;
 
-our $VERSION = '0.10';
+our $VERSION = '0.12';
 our $DEBUG = 0;
 
 =head1 NAME
@@ -631,8 +631,8 @@ sub sql_alter_table {
     warn "removing obsolete index $table.$old ON ( ".
          $old_indices{$old}->columns_sql. " )\n"
       if $DEBUG > 1;
-    push @r, "DROP INDEX $old".
-             ( $driver eq 'mysql' ? " ON $table" : '');
+    push @r, "DROP INDEX $old ".
+             ( $driver eq 'mysql' ? " ON $table" : ' IF EXISTS');
   }
 
   foreach my $new ( keys %new_indices ) {
@@ -669,8 +669,9 @@ sub sql_alter_table {
 
 =item sql_alter_constraints PROTOTYPE_TABLE, [ DATABASE_HANDLE | DATA_SOURCE [ USERNAME PASSWORD [ ATTR ] ] ]
 
-Returns a list of SQL statements to alter this table so that it is identical
-to the provided table, also a DBIx::DBSchema::Table object.
+Returns a list of SQL statements to alter this table's constraints (foreign
+keys) so that they are identical to the provided table, also a
+DBIx::DBSchema::Table object.
 
 The data source can be specified by passing an open DBI database handle, or by
 passing the DBI data source name, username and password.  
@@ -691,8 +692,6 @@ specified database, will attempt to use generic SQL syntax.
 
 =cut
 
-#gosh, false laziness w/DBSchema::sql_update_schema
-
 sub sql_alter_constraints {
   my($self, $opt, $new, $dbh) = ( shift, _parse_opt(\@_), shift, _dbh(@_) );
 
@@ -702,10 +701,7 @@ sub sql_alter_constraints {
 
   my @at = ();
 
-  ###
   # foreign keys (add)
-  ###
-
   foreach my $foreign_key ( $new->foreign_keys ) {
 
     next if grep $foreign_key->cmp($_), $self->foreign_keys;
@@ -713,8 +709,15 @@ sub sql_alter_constraints {
     push @at, 'ADD '. $foreign_key->sql_foreign_key;
   }
 
-  # XXX foreign keys modify / drop
-  
+  #foreign keys (drop)
+  foreach my $foreign_key ( $self->foreign_keys ) {
+
+    next if grep $foreign_key->cmp($_), $new->foreign_keys;
+    next unless $foreign_key->constraint;
+
+    push @at, 'DROP CONSTRAINT '. $foreign_key->constraint;
+  }
+
   return () unless @at;
   (
     'ALTER TABLE '. $self->name. ' '. join(",\n  ", @at)