Merge 'trunk' into 'replication_dedux'
[dbsrgits/DBIx-Class.git] / lib / SQL / Translator / Parser / DBIx / Class.pm
index ad314b2..8305dde 100644 (file)
@@ -69,6 +69,9 @@ sub parse {
     foreach my $moniker (sort @monikers)
     {
         my $source = $dbicschema->source($moniker);
+        
+        # Skip custom query sources
+        next if ref($source->name);
 
         # Its possible to have multiple DBIC source using same table
         next if $seen_tables{$source->name}++;
@@ -112,6 +115,9 @@ sub parse {
         my @rels = $source->relationships();
 
         my %created_FK_rels;
+        
+        # global add_fk_index set in parser_args
+        my $add_fk_index = (exists $args->{add_fk_index} && ($args->{add_fk_index} == 0)) ? 0 : 1;
 
         foreach my $rel (sort @rels)
         {
@@ -123,8 +129,12 @@ sub parse {
             my $othertable = $source->related_source($rel);
             my $rel_table = $othertable->name;
 
+            # Force the order of @cond to match the order of ->add_columns
+            my $idx;
+            my %other_columns_idx = map {'foreign.'.$_ => ++$idx } $othertable->columns;            
+            my @cond = sort { $other_columns_idx{$a} cmp $other_columns_idx{$b} } keys(%{$rel_info->{cond}}); 
+      
             # Get the key information, mapping off the foreign/self markers
-            my @cond = keys(%{$rel_info->{cond}});
             my @refkeys = map {/^\w+\.(\w+)$/} @cond;
             my @keys = map {$rel_info->{cond}->{$_} =~ /^\w+\.(\w+)$/} @cond;
 
@@ -142,6 +152,9 @@ sub parse {
                 }
 
                 my $is_deferrable = $rel_info->{attrs}{is_deferrable};
+                
+                # global parser_args add_fk_index param can be overridden on the rel def
+                my $add_fk_index_rel = (exists $rel_info->{attrs}{add_fk_index}) ? $rel_info->{attrs}{add_fk_index} : $add_fk_index;
 
                 # Make sure we dont create the same foreign key constraint twice
                 my $key_test = join("\x00", @keys);
@@ -176,7 +189,7 @@ sub parse {
                                     (defined $is_deferrable ? ( deferrable => $is_deferrable ) : ()),
                   );
                     
-                  unless (exists $args->{add_fk_index} && ($args->{add_fk_index} == 0)) {
+                  if ($add_fk_index_rel) {
                       my $index = $table->add_index(
                                                     name   => join('_', $table->name, 'idx', @keys),
                                                     fields => \@keys,