add is_deferrable => 1 to belongs_to by default
[dbsrgits/DBIx-Class-Schema-Loader.git] / t / lib / dbixcsl_common_tests.pm
index 35cb49a..81a0d1d 100644 (file)
@@ -10,6 +10,7 @@ use File::Path;
 use DBI;
 use Digest::MD5;
 use File::Find 'find';
+use Class::Unload ();
 
 my $DUMP_DIR = './t/_common_dump';
 rmtree $DUMP_DIR;
@@ -30,7 +31,7 @@ sub new {
     # Only MySQL uses this
     $self->{innodb} ||= '';
 
-    # DB2 doesn't support this
+    # DB2 and Firebird don't support 'field type NULL'
     $self->{null} = 'NULL' unless defined $self->{null};
     
     $self->{verbose} = $ENV{TEST_VERBOSE} || 0;
@@ -38,6 +39,8 @@ sub new {
     # Optional extra tables and tests
     $self->{extra} ||= {};
 
+    $self->{date_datatype} ||= 'DATE';
+
     # Not all DBS do SQL-standard CURRENT_TIMESTAMP
     $self->{default_function} ||= "CURRENT_TIMESTAMP";
     $self->{default_function_def} ||= "TIMESTAMP DEFAULT $self->{default_function}";
@@ -57,44 +60,35 @@ sub _monikerize {
     return undef;
 }
 
-sub _custom_column_info {
-    my $info = shift;
+sub run_tests {
+    my $self = shift;
 
-    if ( lc( $info->{TABLE_NAME} ) eq 'loader_test11' 
-        and lc( $info->{COLUMN_NAME} ) eq 'loader_test10' 
-    ){
-        return { is_numeric => 1 }
+    my @connect_info;
+
+    if ($self->{dsn}) {
+        push @connect_info, [ @{$self}{qw/dsn user password connect_info_opts/ } ];
     }
-    # Set inflate_datetime or  inflate_date to check 
-    #   datetime_timezone and datetime_locale
-    if ( lc( $info->{TABLE_NAME} ) eq 'loader_test36' ){
-        return { inflate_datetime => 1 } if 
-            ( lc( $info->{COLUMN_NAME} ) eq 'b_char_as_data' );
-        return { inflate_date => 1 } if 
-            ( lc( $info->{COLUMN_NAME} ) eq 'c_char_as_data' );
+    else {
+        foreach my $info (@{ $self->{connect_info} || [] }) {
+            push @connect_info, [ @{$info}{qw/dsn user password connect_info_opts/ } ];
+        }
     }
 
-    return;
-}
+    plan tests => @connect_info * (174 + ($self->{extra}->{count} || 0));
 
-sub run_tests {
-    my $self = shift;
+    foreach my $info_idx (0..$#connect_info) {
+        my $info = $connect_info[$info_idx];
 
-    plan tests => 155 + ($self->{extra}->{count} || 0);
+        @{$self}{qw/dsn user password connect_info_opts/} = @$info;
 
-    $self->create();
+        $self->create();
 
-    my @connect_info = (
-       $self->{dsn},
-       $self->{user},
-       $self->{password},
-       $self->{connect_info_opts},
-    );
+        my $schema_class = $self->setup_schema(@$info);
+        $self->test_schema($schema_class);
 
-    # First, with in-memory classes
-    my $schema_class = $self->setup_schema(@connect_info);
-    $self->test_schema($schema_class);
-    $self->drop_tables;
+        rmtree $DUMP_DIR
+            unless $ENV{SCHEMA_LOADER_TESTS_NOCLEANUP} && $info_idx == $#connect_info;
+    }
 }
 
 # defined in sub create
@@ -127,11 +121,16 @@ sub setup_schema {
         use_namespaces          => 0,
         dump_directory          => $DUMP_DIR,
         datetime_timezone       => 'Europe/Berlin',
-        datetime_locale         => 'de_DE'
+        datetime_locale         => 'de_DE',
+        %{ $self->{loader_options} || {} },
     );
 
     $loader_opts{db_schema} = $self->{db_schema} if $self->{db_schema};
 
+    Class::Unload->unload($schema_class);
+
+    my $file_count;
+    my $expected_count = 36;
     {
        my @loader_warnings;
        local $SIG{__WARN__} = sub { push(@loader_warnings, $_[0]); };
@@ -145,11 +144,8 @@ sub setup_schema {
 
        ok(!$@, "Loader initialization") or diag $@;
 
-       my $file_count;
        find sub { return if -d; $file_count++ }, $DUMP_DIR;
 
-       my $expected_count = 36;
-
        $expected_count += grep /CREATE (?:TABLE|VIEW)/i,
            @{ $self->{extra}{create} || [] };
 
@@ -164,13 +160,13 @@ sub setup_schema {
 
        is $file_count, $expected_count, 'correct number of files generated';
 
-       exit if $file_count != $expected_count;
-
        my $warn_count = 2;
        $warn_count++ if grep /ResultSetManager/, @loader_warnings;
 
        $warn_count++ for grep /^Bad table or view/, @loader_warnings;
 
+       $warn_count++ for grep /renaming \S+ relation/, @loader_warnings;
+
        my $vendor = $self->{vendor};
        $warn_count++ for grep /${vendor}_\S+ has no primary key/,
            @loader_warnings;
@@ -186,11 +182,13 @@ sub setup_schema {
            $warn_count++;
             is(scalar(@loader_warnings), $warn_count, "Expected loader warning")
                 or diag @loader_warnings;
-            is(grep(/loader_test9 has no primary key/, @loader_warnings), 1,
+            is(grep(/loader_test9 has no primary key/i, @loader_warnings), 1,
                  "Missing PK warning");
         }
     }
-    
+
+    exit if $file_count != $expected_count;
+   
     return $schema_class;
 }
 
@@ -199,12 +197,22 @@ sub test_schema {
     my $schema_class = shift;
 
     my $conn = $schema_class->clone;
+
+    ($self->{before_tests_run} || sub {})->($conn);
+
     my $monikers = {};
     my $classes = {};
     foreach my $source_name ($schema_class->sources) {
         my $table_name = $schema_class->source($source_name)->from;
+
+        $table_name = $$table_name if ref $table_name;
+
         $monikers->{$table_name} = $source_name;
         $classes->{$table_name} = $schema_class . q{::} . $source_name;
+
+        # some DBs (Firebird) uppercase everything
+        $monikers->{lc $table_name} = $source_name;
+        $classes->{lc $table_name} = $schema_class . q{::} . $source_name;
     }
 
     my $moniker1 = $monikers->{loader_test1s};
@@ -217,12 +225,12 @@ sub test_schema {
     my $rsobj2   = $conn->resultset($moniker2);
     check_no_duplicate_unique_constraints($class2);
 
-    my $moniker23 = $monikers->{LOADER_TEST23};
-    my $class23   = $classes->{LOADER_TEST23};
+    my $moniker23 = $monikers->{LOADER_TEST23} || $monikers->{loader_test23};
+    my $class23   = $classes->{LOADER_TEST23}  || $classes->{loader_test23};
     my $rsobj23   = $conn->resultset($moniker1);
 
-    my $moniker24 = $monikers->{LoAdEr_test24};
-    my $class24   = $classes->{LoAdEr_test24};
+    my $moniker24 = $monikers->{LoAdEr_test24} || $monikers->{loader_test24};
+    my $class24   = $classes->{LoAdEr_test24}  || $classes->{loader_test24};
     my $rsobj24   = $conn->resultset($moniker2);
 
     my $moniker35 = $monikers->{loader_test35};
@@ -316,7 +324,7 @@ sub test_schema {
         is( $rsobj1->loader_test1_rsmeth, 'all is still well', 'Result set method' );
     }
     
-    ok( $class1->column_info('id')->{is_auto_increment}, 'is_auto_incrment detection' );
+    ok( $class1->column_info('id')->{is_auto_increment}, 'is_auto_increment detection' );
 
     my $obj    = $rsobj1->find(1);
     is( $obj->id,  1, "Find got the right row" );
@@ -361,7 +369,7 @@ sub test_schema {
     );
 
     SKIP: {
-        skip $self->{skip_rels}, 96 if $self->{skip_rels};
+        skip $self->{skip_rels}, 116 if $self->{skip_rels};
 
         my $moniker3 = $monikers->{loader_test3};
         my $class3   = $classes->{loader_test3};
@@ -494,6 +502,59 @@ sub test_schema {
         my $rs_rel4 = $obj3->search_related('loader_test4zes');
         isa_ok( $rs_rel4->first, $class4);
 
+        # check rel naming with prepositions
+        ok ($rsobj4->result_source->has_relationship('loader_test5s_to'),
+            "rel with preposition 'to' pluralized correctly");
+
+        ok ($rsobj4->result_source->has_relationship('loader_test5s_from'),
+            "rel with preposition 'from' pluralized correctly");
+
+        # check default relationship attributes
+        is $rsobj3->result_source->relationship_info('loader_test4zes')->{attrs}{cascade_delete}, 0,
+            'cascade_delete => 0 on has_many by default';
+
+        is $rsobj3->result_source->relationship_info('loader_test4zes')->{attrs}{cascade_copy}, 0,
+            'cascade_copy => 0 on has_many by default';
+
+        ok ((not exists $rsobj3->result_source->relationship_info('loader_test4zes')->{attrs}{on_delete}),
+            'has_many does not have on_delete');
+
+        ok ((not exists $rsobj3->result_source->relationship_info('loader_test4zes')->{attrs}{on_update}),
+            'has_many does not have on_update');
+
+        ok ((not exists $rsobj3->result_source->relationship_info('loader_test4zes')->{attrs}{is_deferrable}),
+            'has_many does not have is_deferrable');
+
+        is $rsobj4->result_source->relationship_info('fkid_singular')->{attrs}{on_delete}, 'CASCADE',
+            "on_delete => 'CASCADE' on belongs_to by default";
+
+        is $rsobj4->result_source->relationship_info('fkid_singular')->{attrs}{on_update}, 'CASCADE',
+            "on_update => 'CASCADE' on belongs_to by default";
+
+        is $rsobj4->result_source->relationship_info('fkid_singular')->{attrs}{is_deferrable}, 1,
+            "is_deferrable => 1 on belongs_to by default";
+
+        ok ((not exists $rsobj4->result_source->relationship_info('fkid_singular')->{attrs}{cascade_delete}),
+            'belongs_to does not have cascade_delete');
+
+        ok ((not exists $rsobj4->result_source->relationship_info('fkid_singular')->{attrs}{cascade_copy}),
+            'belongs_to does not have cascade_copy');
+
+        is $rsobj27->result_source->relationship_info('loader_test28')->{attrs}{cascade_delete}, 0,
+            'cascade_delete => 0 on might_have by default';
+
+        is $rsobj27->result_source->relationship_info('loader_test28')->{attrs}{cascade_copy}, 0,
+            'cascade_copy => 0 on might_have by default';
+
+        ok ((not exists $rsobj27->result_source->relationship_info('loader_test28')->{attrs}{on_delete}),
+            'might_have does not have on_delete');
+
+        ok ((not exists $rsobj27->result_source->relationship_info('loader_test28')->{attrs}{on_update}),
+            'might_have does not have on_update');
+
+        ok ((not exists $rsobj27->result_source->relationship_info('loader_test28')->{attrs}{is_deferrable}),
+            'might_have does not have is_deferrable');
+
         # find on multi-col pk
         my $obj5 = 
            eval { $rsobj5->find({id1 => 1, iD2 => 1}) } ||
@@ -587,40 +648,33 @@ sub test_schema {
         is($obj27->loader_test29, undef, "Undef for missing one-to-one row");
 
         # test outer join for nullable referring columns:
-        SKIP: {
-          skip "unreliable column info from db driver",11 unless 
-            ($class32->column_info('rel2')->{is_nullable});
-
-          ok($class32->column_info('rel1')->{is_foreign_key}, 'Foreign key detected');
-          ok($class32->column_info('rel2')->{is_foreign_key}, 'Foreign key detected');
-          
-          my $obj32 = $rsobj32->find(1,{prefetch=>[qw/rel1 rel2/]});
-          my $obj34 = $rsobj34->find(
-            1,{prefetch=>[qw/loader_test33_id_rel1 loader_test33_id_rel2/]}
-          );
-          my $skip_outerjoin;
-          isa_ok($obj32,$class32) or $skip_outerjoin = 1;
-          isa_ok($obj34,$class34) or $skip_outerjoin = 1;
-
-          ok($class34->column_info('id')->{is_foreign_key}, 'Foreign key detected');
-          ok($class34->column_info('rel1')->{is_foreign_key}, 'Foreign key detected');
-          ok($class34->column_info('rel2')->{is_foreign_key}, 'Foreign key detected');
-
-          SKIP: {
-            skip "Pre-requisite test failed", 4 if $skip_outerjoin;
-            my $rs_rel31_one = $obj32->rel1;
-            my $rs_rel31_two = $obj32->rel2;
-            isa_ok($rs_rel31_one, $class31);
-            is($rs_rel31_two, undef);
-
-            my $rs_rel33_one = $obj34->loader_test33_id_rel1;
-            my $rs_rel33_two = $obj34->loader_test33_id_rel2;
-
-            isa_ok($rs_rel33_one,$class33);
-            is($rs_rel33_two, undef);
-
-          }
-        }
+        is $class32->column_info('rel2')->{is_nullable}, 1,
+          'is_nullable detection';
+
+        ok($class32->column_info('rel1')->{is_foreign_key}, 'Foreign key detected');
+        ok($class32->column_info('rel2')->{is_foreign_key}, 'Foreign key detected');
+        
+        my $obj32 = $rsobj32->find(1,{prefetch=>[qw/rel1 rel2/]});
+        my $obj34 = $rsobj34->find(
+          1,{prefetch=>[qw/loader_test33_id_rel1 loader_test33_id_rel2/]}
+        );
+        isa_ok($obj32,$class32);
+        isa_ok($obj34,$class34);
+
+        ok($class34->column_info('id')->{is_foreign_key}, 'Foreign key detected');
+        ok($class34->column_info('rel1')->{is_foreign_key}, 'Foreign key detected');
+        ok($class34->column_info('rel2')->{is_foreign_key}, 'Foreign key detected');
+
+        my $rs_rel31_one = $obj32->rel1;
+        my $rs_rel31_two = $obj32->rel2;
+        isa_ok($rs_rel31_one, $class31);
+        is($rs_rel31_two, undef);
+
+        my $rs_rel33_one = $obj34->loader_test33_id_rel1;
+        my $rs_rel33_two = $obj34->loader_test33_id_rel2;
+
+        isa_ok($rs_rel33_one,$class33);
+        is($rs_rel33_two, undef);
 
         # from Chisel's tests...
         my $moniker10 = $monikers->{loader_test10};
@@ -636,19 +690,6 @@ sub test_schema {
 
         ok($class10->column_info('loader_test11')->{is_foreign_key}, 'Foreign key detected');
         ok($class11->column_info('loader_test10')->{is_foreign_key}, 'Foreign key detected');
-        # Added by custom_column_info
-        ok($class11->column_info('loader_test10')->{is_numeric}, 'is_numeric detected');
-
-        is($class36->column_info('a_date')->{locale},'de_DE','locale is correct');
-        is($class36->column_info('a_date')->{timezone},'Europe/Berlin','locale is correct');
-
-        ok($class36->column_info('b_char_as_data')->{inflate_datetime},'inflate_datetime detected');
-        is($class36->column_info('b_char_as_data')->{locale},'de_DE','locale is correct');
-        is($class36->column_info('b_char_as_data')->{timezone},'Europe/Berlin','locale is correct');
-
-        ok($class36->column_info('c_char_as_data')->{inflate_date},'inflate_date detected');
-        is($class36->column_info('c_char_as_data')->{locale},'de_DE','locale is correct');
-        is($class36->column_info('c_char_as_data')->{timezone},'Europe/Berlin','locale is correct');
 
         my $obj10 = $rsobj10->create({ subject => 'xyzzy' });
 
@@ -661,9 +702,9 @@ sub test_schema {
 
         eval {
             my $obj10_2 = $obj11->loader_test10;
-            $obj10_2->loader_test11( $obj11->id11() );
-            $obj10_2->update();
+            $obj10_2->update({ loader_test11 => $obj11->id11 });
         };
+        diag $@ if $@;
         ok(!$@, "Setting up circular relationship");
 
         SKIP: {
@@ -679,7 +720,7 @@ sub test_schema {
         }
 
         SKIP: {
-            skip 'This vendor cannot do inline relationship definitions', 8
+            skip 'This vendor cannot do inline relationship definitions', 9
                 if $self->{no_inline_rels};
 
             my $moniker12 = $monikers->{loader_test12};
@@ -701,6 +742,9 @@ sub test_schema {
             isa_ok( $obj13->id, $class12 );
             isa_ok( $obj13->loader_test12, $class12);
             isa_ok( $obj13->dat, $class12);
+
+            my $obj12 = $rsobj12->find(1);
+            isa_ok( $obj12->loader_test13, $class13 );
         }
 
         SKIP: {
@@ -724,6 +768,25 @@ sub test_schema {
         }
     }
 
+    # test custom_column_info and datetime_timezone/datetime_locale
+    {
+        my $class35 = $classes->{loader_test35};
+        my $class36 = $classes->{loader_test36};
+
+        ok($class35->column_info('an_int')->{is_numeric}, 'custom_column_info');
+
+        is($class36->column_info('a_date')->{locale},'de_DE','datetime_locale');
+        is($class36->column_info('a_date')->{timezone},'Europe/Berlin','datetime_timezone');
+
+        ok($class36->column_info('b_char_as_data')->{inflate_datetime},'custom_column_info');
+        is($class36->column_info('b_char_as_data')->{locale},'de_DE','datetime_locale');
+        is($class36->column_info('b_char_as_data')->{timezone},'Europe/Berlin','datetime_timezone');
+
+        ok($class36->column_info('c_char_as_data')->{inflate_date},'custom_column_info');
+        is($class36->column_info('c_char_as_data')->{locale},'de_DE','datetime_locale');
+        is($class36->column_info('c_char_as_data')->{timezone},'Europe/Berlin','datetime_timezone');
+    }
+
     # rescan and norewrite test
     SKIP: {
         my @statements_rescan = (
@@ -767,6 +830,7 @@ sub test_schema {
         }
 
         $dbh->disconnect;
+        $conn->storage->disconnect; # needed for Firebird
 
         sleep 1;
 
@@ -797,6 +861,10 @@ sub test_schema {
     }
 
     $self->{extra}->{run}->($conn, $monikers, $classes) if $self->{extra}->{run};
+
+    $self->drop_tables unless $ENV{SCHEMA_LOADER_TESTS_NOCLEANUP};
+
+    $conn->storage->disconnect;
 }
 
 sub check_no_duplicate_unique_constraints {
@@ -815,17 +883,26 @@ sub check_no_duplicate_unique_constraints {
 sub dbconnect {
     my ($self, $complain) = @_;
 
-    my $dbh = DBI->connect(
-         $self->{dsn}, $self->{user},
-         $self->{password},
-         {
-             RaiseError => $complain,
-             PrintError => $complain,
-             AutoCommit => 1,
-         }
-    );
+    require DBIx::Class::Storage::DBI;
+    my $storage = DBIx::Class::Storage::DBI->new;
+
+    $complain = defined $complain ? $complain : 1;
+
+    $storage->connect_info([
+        @{ $self }{qw/dsn user password/},
+        {
+            unsafe => 1,
+            RaiseError => $complain,
+            ShowErrorStatement => $complain,
+            PrintError => 0,
+            %{ $self->{connect_info_opts} || {} },
+        },
+    ]);
+
+    my $dbh = eval { $storage->dbh };
+    die "Failed to connect to database: $@" if !$dbh;
 
-    die "Failed to connect to database: $DBI::errstr" if !$dbh;
+    $self->{storage} = $storage; # storage DESTROY disconnects
 
     return $dbh;
 }
@@ -891,7 +968,7 @@ sub create {
         qq{
             CREATE TABLE loader_test36 (
                 id INTEGER NOT NULL PRIMARY KEY,
-                a_date DATE,
+                a_date $self->{date_datatype},
                 b_char_as_data VARCHAR(100),
                 c_char_as_data VARCHAR(100)
             ) $self->{innodb}
@@ -930,7 +1007,11 @@ sub create {
                 id1 INTEGER NOT NULL,
                 iD2 INTEGER NOT NULL,
                 dat VARCHAR(8),
-                PRIMARY KEY (id1,iD2)
+                from_id INTEGER $self->{null},
+                to_id INTEGER $self->{null},
+                PRIMARY KEY (id1,iD2),
+                FOREIGN KEY (from_id) REFERENCES loader_test4 (id),
+                FOREIGN KEY (to_id) REFERENCES loader_test4 (id)
             ) $self->{innodb}
         },
 
@@ -1357,7 +1438,8 @@ sub drop_tables {
 
     my $dbh = $self->dbconnect(0);
 
-    $dbh->do("DROP TABLE $_") for @{ $self->{extra}->{drop} || [] };
+    $dbh->do($_) for @{ $self->{extra}{pre_drop_ddl} || [] };
+    $dbh->do("DROP TABLE $_") for @{ $self->{extra}{drop} || [] };
 
     my $drop_auto_inc = $self->{auto_inc_drop_cb} || sub {};
 
@@ -1369,8 +1451,8 @@ sub drop_tables {
         else {
             $dbh->do($drop_fk);
         }
-        $dbh->do("DROP TABLE $_") for (@tables_advanced);
         $dbh->do($_) for map { $drop_auto_inc->(@$_) } @tables_advanced_auto_inc;
+        $dbh->do("DROP TABLE $_") for (@tables_advanced);
 
         unless($self->{no_inline_rels}) {
             $dbh->do("DROP TABLE $_") for (@tables_inline_rels);
@@ -1379,11 +1461,39 @@ sub drop_tables {
             $dbh->do("DROP TABLE $_") for (@tables_implicit_rels);
         }
     }
-    $dbh->do("DROP TABLE $_") for (@tables, @tables_rescan);
     $dbh->do($_) for map { $drop_auto_inc->(@$_) } @tables_auto_inc;
+    $dbh->do("DROP TABLE $_") for (@tables, @tables_rescan);
+    $dbh->disconnect;
+
+# fixup for Firebird
+    $dbh = $self->dbconnect(0);
+    $dbh->do('DROP TABLE loader_test2');
     $dbh->disconnect;
 }
 
+sub _custom_column_info {
+    my ( $table_name, $column_name, $column_info ) = @_;
+
+    $table_name = lc ( $table_name );
+    $column_name = lc ( $column_name );
+
+    if ( $table_name eq 'loader_test35' 
+        and $column_name eq 'an_int' 
+    ){
+        return { is_numeric => 1 }
+    }
+    # Set inflate_datetime or  inflate_date to check 
+    #   datetime_timezone and datetime_locale
+    if ( $table_name eq 'loader_test36' ){
+        return { inflate_datetime => 1 } if 
+            ( $column_name eq 'b_char_as_data' );
+        return { inflate_date => 1 } if 
+            ( $column_name eq 'c_char_as_data' );
+    }
+
+    return;
+}
+
 sub DESTROY {
     my $self = shift;
     unless ($ENV{SCHEMA_LOADER_TESTS_NOCLEANUP}) {