Merge 'trunk' into 'sqla_1.50_compat'
Norbert Buchmuller [Sat, 20 Dec 2008 21:47:11 +0000 (21:47 +0000)]
r5340@vger:  mendel | 2008-12-20 22:01:53 +0100
 r5134@vger (orig r5117):  ribasushi | 2008-11-13 08:34:26 +0100
 result_class goodies by Caelum:
 - result_class can now be specified as a search attribute, attaching it to the returned resultset
 - the specified class is now autoloaded via ensure_loaded()

 r5136@vger (orig r5119):  ribasushi | 2008-11-13 19:34:29 +0100
 resultset attribute from can now take a scalarref and use it verbatim
 r5145@vger (orig r5128):  ribasushi | 2008-11-14 10:46:00 +0100
 Document the new from usage
 r5152@vger (orig r5134):  ribasushi | 2008-11-14 18:44:25 +0100
 we use register_extra_source() now
 r5162@vger (orig r5140):  castaway | 2008-11-15 22:08:30 +0100
 Added failing create-multi test

 r5163@vger (orig r5141):  ribasushi | 2008-11-16 10:53:07 +0100
 whops
 r5166@vger (orig r5142):  norbi | 2008-11-16 20:12:42 +0100
  r5165@vger:  mendel | 2008-11-16 20:11:42 +0100
   * Merged in changes from 'resultsetcolumn_custom_columns' branch,

 r5179@vger (orig r5149):  ribasushi | 2008-11-16 23:14:13 +0100
 Revert castaway's test - mildly bogus
 r5180@vger (orig r5150):  ribasushi | 2008-11-16 23:16:31 +0100
 Add new test relationship - a track can have a relates single_cd
 r5181@vger (orig r5151):  ribasushi | 2008-11-16 23:23:38 +0100
 might_have test for castaway to break
 r5182@vger (orig r5152):  ribasushi | 2008-11-17 01:33:51 +0100
 rip away a horribly wrong create_via_update test (will pass when multicreate is merged)
 r5183@vger (orig r5153):  ribasushi | 2008-11-17 02:00:28 +0100
 One more (passing) multicreate test and a bit of cleanup
 r5184@vger (orig r5154):  ribasushi | 2008-11-17 02:59:53 +0100
 Two more sets of might_have - has_many relationships for extra tests
 r5185@vger (orig r5155):  ribasushi | 2008-11-17 03:09:18 +0100
 Two failing multicreate tests (the root cause of castaway's problem)
 r5186@vger (orig r5156):  ribasushi | 2008-11-17 03:48:57 +0100
 Silence cdbi tests like everything else
 r5187@vger (orig r5157):  ribasushi | 2008-11-17 04:01:39 +0100
 Failing tests by zby, showing that recursing insert() gets in the way of some exotic insert scenarious - waiting for mst to decide course of action
 r5188@vger (orig r5158):  ribasushi | 2008-11-17 12:04:54 +0100
 Extend might_have test with ideas from zby
 r5192@vger (orig r5161):  ribasushi | 2008-11-20 11:25:32 +0100
 Trunk passes tests again - todoify everything multicreate related to branch it out, as the task turned out to be more complex (no indentation to aid future merging)
 r5195@vger (orig r5164):  ribasushi | 2008-11-20 12:01:14 +0100
 CDBI-compat tests by Dave Horwoth:

     OK. I've attached a patch to t/cdbi-t/15-accessor.t that does several
     things:

     (1) Fixes the way the arguments are built so the sheep argument is
     correct in the tests.

     (2) Adds explicit tests for the number of sheep so we can be sure which
     database record is actually returned.

     (3) Adds tests for find_or_create() with modified accessor names.

     (4) Fixes the test for search() to report all errors

     I still don't fully understand what's going on in the output below but I
     think they are genuine test failures. I'd appreciate it if somebody else
     could run the tests to make sure the results are not some artefact of my
     test environment. I also attached a copy of the modified test script so
     you don't even have to apply the patch first :)

     I don't know what the DestroyWarning at the end is all about.

 r5196@vger (orig r5165):  ribasushi | 2008-11-20 12:09:11 +0100
 Minor doc patch by Caelum
 r5199@vger (orig r5168):  castaway | 2008-11-20 14:49:39 +0100
 Fix pod errors so that some storage subclasses show up in cpan properly

 r5291@vger (orig r5222):  ash | 2008-12-03 18:23:00 +0100
 Make the many-to-many warning use warnings::register;
 r5317@vger (orig r5239):  jnapiorkowski | 2008-12-15 23:02:19 +0100
 changes to replication so that if a replicant is offline when we do the initial connection (or if we need to globally reconnect later) the connection does not die.  This is different from when a replicant is available just not listening, or if the replicant is too laggy.  Thanks David Steinbrunner for the patch suggestions.
 r5323@vger (orig r5245):  groditi | 2008-12-16 23:56:07 +0100
  r24740@martha (orig r5230):  groditi | 2008-12-09 20:28:10 -0500
  fix for bug. all tests seem to pass, we still need a new test and more research

 r5324@vger (orig r5246):  groditi | 2008-12-16 23:56:29 +0100
  r24754@martha (orig r5241):  groditi | 2008-12-16 16:27:06 -0500
  Introduce 'any_null_means_no_value' option to eliminate wasteful queries. The option is off by default and must be explicitly turned on. Tests, + docs included

 r5325@vger (orig r5247):  groditi | 2008-12-16 23:57:11 +0100
  r24756@martha (orig r5243):  groditi | 2008-12-16 17:42:10 -0500
  rename option to undef_on_null_fk and make it default for belongs_to

 r5326@vger (orig r5248):  groditi | 2008-12-16 23:57:34 +0100
  r24757@martha (orig r5244):  groditi | 2008-12-16 17:52:12 -0500
  minor typo and style change

 r5328@vger (orig r5250):  groditi | 2008-12-17 00:27:57 +0100
 somehow i messed up the merge. this fixes it
 r5329@vger (orig r5251):  ash | 2008-12-17 00:45:51 +0100
 Try to fix test on 5.10
 r5332@vger (orig r5254):  ribasushi | 2008-12-18 12:28:38 +0100
 Some cleanups to the m2m warnings test
 r5336@vger (orig r5258):  jnapiorkowski | 2008-12-19 20:52:44 +0100
 more noise debugging messages if debug is on, minor doc tweaks, changes so that the fake sqlite tests will work and laid the groundwork for replication without dbatabase native replication support.
 r5337@vger (orig r5259):  jnapiorkowski | 2008-12-19 21:48:35 +0100
 altered schema->populate so that it is a very thin wrapper on top of resultset->populate and changed resultset_populate so that is accepted both the arrayref of hashes and the arrayref of arrayref style of args.  Documented this, updated the tests a bit to make sure it is all good.
 r5338@vger (orig r5260):  ribasushi | 2008-12-19 22:09:17 +0100
 Todoify cdbi failing tests, waiting for schwern

49 files changed:
Changes
lib/DBIx/Class/InflateColumn/DateTime.pm
lib/DBIx/Class/Manual/Cookbook.pod
lib/DBIx/Class/Relationship.pm
lib/DBIx/Class/Relationship/Accessor.pm
lib/DBIx/Class/Relationship/BelongsTo.pm
lib/DBIx/Class/Relationship/ManyToMany.pm
lib/DBIx/Class/ResultSet.pm
lib/DBIx/Class/ResultSetColumn.pm
lib/DBIx/Class/ResultSourceProxy/Table.pm
lib/DBIx/Class/Row.pm
lib/DBIx/Class/Schema.pm
lib/DBIx/Class/Storage/DBI.pm
lib/DBIx/Class/Storage/DBI/ODBC/ACCESS.pm
lib/DBIx/Class/Storage/DBI/Oracle/Generic.pm
lib/DBIx/Class/Storage/DBI/Replicated/Balancer.pm
lib/DBIx/Class/Storage/DBI/Replicated/Pool.pm
lib/DBIx/Class/Storage/DBI/Replicated/Replicant.pm
lib/DBIx/Class/Storage/DBI/Role/QueryCounter.pm
t/101populate_rs.t
t/103many_to_many_warning.t [new file with mode: 0644]
t/50fork.t
t/51threads.t
t/51threadtxn.t
t/60core.t
t/66relationship.t
t/68inflate_resultclass_hashrefinflator.t
t/74mssql.t
t/76select.t
t/77prefetch.t
t/88result_set_column.t
t/91debug.t
t/93storage_replication.t
t/96multi_create.t
t/97result_class.t
t/99dbic_sqlt_parser.t
t/cdbi-t/02-Film.t
t/cdbi-t/15-accessor.t
t/cdbi-t/23-cascade.t
t/lib/DBICTest/Schema.pm
t/lib/DBICTest/Schema/Artwork.pm [new file with mode: 0644]
t/lib/DBICTest/Schema/CD.pm
t/lib/DBICTest/Schema/Image.pm [new file with mode: 0644]
t/lib/DBICTest/Schema/LyricVersion.pm [new file with mode: 0644]
t/lib/DBICTest/Schema/Lyrics.pm [new file with mode: 0644]
t/lib/DBICTest/Schema/Producer.pm
t/lib/DBICTest/Schema/Track.pm
t/lib/sqlite.sql
t/testlib/MyBase.pm

diff --git a/Changes b/Changes
index 6b93887..55a45ee 100644 (file)
--- a/Changes
+++ b/Changes
@@ -1,4 +1,12 @@
 Revision history for DBIx::Class
+        - Allow a scalarref to be supplied to the 'from' resultset attribute
+        - Classes submitted as result_class for a resultsource are now
+          automatically loaded via ensure_loaded()
+        - 'result_class' resultset attribute, identical to result_class()
+        - add 'undef_on_null_fk' option for relationship accessors of type 'single'. 
+          This will prevent DBIC from querying the database if one or more of
+          the key columns IS NULL. Tests + docs (groditi)
+           - for 'belongs_to' rels, 'null_on_fk' defaults to true.
 
 0.08099_05 2008-10-30 21:30:00 (UTC)
         - Rewritte of Storage::DBI::connect_info(), extended with an
index a46da64..8e2e2d5 100644 (file)
@@ -19,6 +19,9 @@ columns to be of the datetime, timestamp or date datatype.
     starts_when => { data_type => 'datetime' }
   );
 
+NOTE: You B<must> load C<InflateColumn::DateTime> B<before> C<Core>. See
+L<DBIx::Class::Manual::Component> for details.
+
 Then you can treat the specified column as a L<DateTime> object.
 
   print "This event starts the month of ".
index f63f067..9a642f9 100644 (file)
@@ -141,7 +141,7 @@ you have to add to your User class:
   SQL 
 
   # Finally, register your new ResultSource with your Schema
-  My::Schema->register_source( 'UserFriendsComplex' => $new_source );
+  My::Schema->register_extra_source( 'UserFriendsComplex' => $new_source );
 
 Next, you can execute your complex query using bind parameters like this:
 
index b3f8507..3479ac2 100644 (file)
@@ -208,6 +208,11 @@ Cascading deletes are off by default on a C<belongs_to>
 relationship. To turn them on, pass C<< cascade_delete => 1 >>
 in the $attr hashref.
 
+By default, DBIC will return undef and avoid querying the database if a
+C<belongs_to> accessor is called when any part of the foreign key IS NULL. To
+disable this behavior, pass C<< undef_on_null_fk => 0 >> in the C<$attr>
+hashref.
+
 NOTE: If you are used to L<Class::DBI> relationships, this is the equivalent
 of C<has_a>.
 
index fb15f10..dcb906e 100644 (file)
@@ -18,6 +18,7 @@ sub add_relationship_accessor {
   my ($class, $rel, $acc_type) = @_;
   my %meth;
   if ($acc_type eq 'single') {
+    my $rel_info = $class->relationship_info($rel);
     $meth{$rel} = sub {
       my $self = shift;
       if (@_) {
@@ -26,6 +27,12 @@ sub add_relationship_accessor {
       } elsif (exists $self->{_relationship_data}{$rel}) {
         return $self->{_relationship_data}{$rel};
       } else {
+        my $cond = $self->result_source->resolve_condition(
+          $rel_info->{cond}, $rel, $self
+        );
+        if ($rel_info->{attrs}->{undef_on_null_fk}){
+          return if grep { not defined } values %$cond;
+        }
         my $val = $self->find_related($rel, {}, {});
         return unless $val;
         return $self->{_relationship_data}{$rel} = $val;
index 272b01b..eb10752 100644 (file)
@@ -13,6 +13,8 @@ sub belongs_to {
   # assume a foreign key contraint unless defined otherwise
   $attrs->{is_foreign_key_constraint} = 1 
     if not exists $attrs->{is_foreign_key_constraint};
+  $attrs->{undef_on_null_fk} = 1
+    if not exists $attrs->{undef_on_null_fk};
 
   # no join condition or just a column name
   if (!ref $cond) {
index 76042c0..163ac36 100644 (file)
@@ -3,6 +3,7 @@ package # hide from PAUSE
 
 use strict;
 use warnings;
+use warnings::register;
 use Sub::Name ();
 
 sub many_to_many {
@@ -26,10 +27,21 @@ sub many_to_many {
     my $rs_meth = "${meth}_rs";
 
     for ($add_meth, $remove_meth, $set_meth, $rs_meth) {
-      warn "***************************************************************************\n".
-           "The many-to-many relationship $meth is trying to create a utility method called $_. This will overwrite the existing method on $class. You almost certainly want to rename your method or the many-to-many relationship, as your method will not be callable (it will use the one from the relationship instead.) YOU HAVE BEEN WARNED\n".
-           "***************************************************************************\n"
-        if $class->can($_);
+      if ( $class->can ($_) ) {
+        warnings::warnif(<<"EOW")
+***************************************************************************
+The many-to-many relationship $meth is trying to create a utility method called
+$_. This will overwrite the existing method on $class. You almost certainly
+want to rename your method or the many-to-many relationship, as your method
+will not be callable (it will use the one from the relationship instead.)
+
+To disable this warning add the following to $class
+
+  no warnings 'DBIx::Class::Relationship::ManyToMany';
+
+***************************************************************************
+EOW
+      }
     }
 
     $rel_attrs->{alias} ||= $f_rel;
index f700f7a..e637aee 100644 (file)
@@ -15,7 +15,7 @@ use List::Util ();
 use Scalar::Util ();
 use base qw/DBIx::Class/;
 
-__PACKAGE__->mk_group_accessors('simple' => qw/result_class _source_handle/);
+__PACKAGE__->mk_group_accessors('simple' => qw/_result_class _source_handle/);
 
 =head1 NAME
 
@@ -108,7 +108,6 @@ sub new {
   # see https://bugzilla.redhat.com/show_bug.cgi?id=196836
   my $self = {
     _source_handle => $source,
-    result_class => $attrs->{result_class} || $source->resolve->result_class,
     cond => $attrs->{where},
     count => undef,
     pager => undef,
@@ -117,6 +116,10 @@ sub new {
 
   bless $self, $class;
 
+  $self->result_class(
+    $attrs->{result_class} || $source->resolve->result_class
+  );
+
   return $self;
 }
 
@@ -988,6 +991,14 @@ L<"table"|DBIx::Class::Manual::Glossary/"ResultSource"> class.
 
 =cut
 
+sub result_class {
+  my ($self, $result_class) = @_;
+  if ($result_class) {
+    $self->ensure_class_loaded($result_class);
+    $self->_result_class($result_class);
+  }
+  $self->_result_class;
+}
 
 =head2 count
 
@@ -1351,8 +1362,9 @@ sub delete_all {
 
 =back
 
-Pass an arrayref of hashrefs. Each hashref should be a structure suitable for
-submitting to a $resultset->create(...) method.
+Accepts either an arrayref of hashrefs or alternatively an arrayref of arrayrefs.
+For the arrayref of hashrefs style each hashref should be a structure suitable
+forsubmitting to a $resultset->create(...) method.
 
 In void context, C<insert_bulk> in L<DBIx::Class::Storage::DBI> is used
 to insert the data, as this is a faster method.  
@@ -1392,7 +1404,18 @@ Example:  Assuming an Artist Class that has many CDs Classes relating:
   
   print $ArtistOne->name; ## response is 'Artist One'
   print $ArtistThree->cds->count ## reponse is '2'
-  
+
+For the arrayref of arrayrefs style,  the first element should be a list of the
+fieldsnames to which the remaining elements are rows being inserted.  For
+example:
+
+  $Arstist_rs->populate([
+    [qw/artistid name/],
+    [100, 'A Formally Unknown Singer'],
+    [101, 'A singer that jumped the shark two albums ago'],
+    [102, 'An actually cool singer.'],
+  ]);
+
 Please note an important effect on your data when choosing between void and
 wantarray context. Since void context goes straight to C<insert_bulk> in 
 L<DBIx::Class::Storage::DBI> this will skip any component that is overriding
@@ -1404,7 +1427,10 @@ values.
 =cut
 
 sub populate {
-  my ($self, $data) = @_;
+  my $self = shift @_;
+  my $data = ref $_[0][0] eq 'HASH'
+    ? $_[0] : ref $_[0][0] eq 'ARRAY' ? $self->_normalize_populate_args($_[0]) :
+    $self->throw_exception('Populate expects an arrayref of hashes or arrayref of arrayrefs');
   
   if(defined wantarray) {
     my @created;
@@ -1478,6 +1504,28 @@ sub populate {
   }
 }
 
+=head2 _normalize_populate_args ($args)
+
+Private method used by L</populate> to normalize it's incoming arguments.  Factored
+out in case you want to subclass and accept new argument structures to the
+L</populate> method.
+
+=cut
+
+sub _normalize_populate_args {
+  my ($self, $data) = @_;
+  my @names = @{shift(@$data)};
+  my @results_to_create;
+  foreach my $datum (@$data) {
+    my %result_to_create;
+    foreach my $index (0..$#names) {
+      $result_to_create{$names[$index]} = $$datum[$index];
+    }
+    push @results_to_create, \%result_to_create;    
+  }
+  return \@results_to_create;
+}
+
 =head2 pager
 
 =over 4
@@ -2791,6 +2839,58 @@ with a father in the person table, we could explicitly use C<INNER JOIN>:
     # SELECT child.* FROM person child
     # INNER JOIN person father ON child.father_id = father.id
 
+If you need to express really complex joins or you need a subselect, you
+can supply literal SQL to C<from> via a scalar reference. In this case
+the contents of the scalar will replace the table name asscoiated with the
+resultsource.
+
+WARNING: This technique might very well not work as expected on chained
+searches - you have been warned.
+
+    # Assuming the Event resultsource is defined as:
+
+        MySchema::Event->add_columns (
+            sequence => {
+                data_type => 'INT',
+                is_auto_increment => 1,
+            },
+            location => {
+                data_type => 'INT',
+            },
+            type => {
+                data_type => 'INT',
+            },
+        );
+        MySchema::Event->set_primary_key ('sequence');
+
+    # This will get back the latest event for every location. The column
+    # selector is still provided by DBIC, all we do is add a JOIN/WHERE
+    # combo to limit the resultset
+
+    $rs = $schema->resultset('Event');
+    $table = $rs->result_source->name;
+    $latest = $rs->search (
+        undef,
+        { from => \ " 
+            (SELECT e1.* FROM $table e1 
+                JOIN $table e2 
+                    ON e1.location = e2.location 
+                    AND e1.sequence < e2.sequence 
+                WHERE e2.sequence is NULL 
+            ) me",
+        },
+    );
+
+    # Equivalent SQL (with the DBIC chunks added):
+
+    SELECT me.sequence, me.location, me.type FROM
+       (SELECT e1.* FROM events e1
+           JOIN events e2
+               ON e1.location = e2.location
+               AND e1.sequence < e2.sequence
+           WHERE e2.sequence is NULL
+       ) me;
+
 =head2 for
 
 =over 4
index 68cc4e0..7b0fee6 100644 (file)
@@ -2,6 +2,7 @@ package DBIx::Class::ResultSetColumn;
 use strict;
 use warnings;
 use base 'DBIx::Class';
+use List::Util;
 
 =head1 NAME
 
@@ -36,8 +37,19 @@ sub new {
   my ($class, $rs, $column) = @_;
   $class = ref $class if ref $class;
   my $new_parent_rs = $rs->search_rs; # we don't want to mess up the original, so clone it
-  $new_parent_rs->{attrs}->{prefetch} = undef; # prefetch causes additional columns to be fetched
-  my $new = bless { _column => $column, _parent_resultset => $new_parent_rs }, $class;
+  my $attrs = $new_parent_rs->_resolved_attrs;
+  $new_parent_rs->{attrs}->{$_} = undef for qw(prefetch include_columns +select +as); # prefetch, include_columns, +select, +as cause additional columns to be fetched
+
+  # If $column can be found in the 'as' list of the parent resultset, use the
+  # corresponding element of its 'select' list (to keep any custom column
+  # definition set up with 'select' or '+select' attrs), otherwise use $column
+  # (to create a new column definition on-the-fly).
+  my $as_list = $attrs->{as} || [];
+  my $select_list = $attrs->{select} || [];
+  my $as_index = List::Util::first { ($as_list->[$_] || "") eq $column } 0..$#$as_list;
+  my $select = defined $as_index ? $select_list->[$as_index] : $column;
+
+  my $new = bless { _select => $select, _as => $column, _parent_resultset => $new_parent_rs }, $class;
   $new->throw_exception("column must be supplied") unless $column;
   return $new;
 }
@@ -62,8 +74,7 @@ one value.
 
 sub next {
   my $self = shift;
-  $self->{_resultset} = $self->{_parent_resultset}->search(undef, {select => [$self->{_column}], as => [$self->{_column}]}) unless ($self->{_resultset});
-  my ($row) = $self->{_resultset}->cursor->next;
+  my ($row) = $self->_resultset->cursor->next;
   return $row;
 }
 
@@ -87,7 +98,53 @@ than row objects.
 
 sub all {
   my $self = shift;
-  return map {$_->[0]} $self->{_parent_resultset}->search(undef, {select => [$self->{_column}], as => [$self->{_column}]})->cursor->all;
+  return map { $_->[0] } $self->_resultset->cursor->all;
+}
+
+=head2 reset
+
+=over 4
+
+=item Arguments: none
+
+=item Return Value: $self
+
+=back
+
+Resets the underlying resultset's cursor, so you can iterate through the
+elements of the column again.
+
+Much like L<DBIx::Class::ResultSet/reset>.
+
+=cut
+
+sub reset {
+  my $self = shift;
+  $self->_resultset->cursor->reset;
+  return $self;
+}
+
+=head2 first
+
+=over 4
+
+=item Arguments: none
+
+=item Return Value: $value
+
+=back
+
+Resets the underlying resultset and returns the next value of the column in the
+resultset (or C<undef> if there is none).
+
+Much like L<DBIx::Class::ResultSet/first> but just returning the one value.
+
+=cut
+
+sub first {
+  my $self = shift;
+  my ($row) = $self->_resultset->cursor->reset->next;
+  return $row;
 }
 
 =head2 min
@@ -175,7 +232,7 @@ value. Produces the following SQL:
 
 sub func {
   my ($self,$function) = @_;
-  my $cursor = $self->{_parent_resultset}->search(undef, {select => {$function => $self->{_column}}, as => [$self->{_column}]})->cursor;
+  my $cursor = $self->{_parent_resultset}->search(undef, {select => {$function => $self->{_select}}, as => [$self->{_as}]})->cursor;
   
   if( wantarray ) {
     return map { $_->[ 0 ] } $cursor->all;
@@ -184,6 +241,44 @@ sub func {
   return ( $cursor->next )[ 0 ];
 }
 
+=head2 throw_exception
+
+See L<DBIx::Class::Schema/throw_exception> for details.
+  
+=cut 
+    
+sub throw_exception {
+  my $self=shift;
+  if (ref $self && $self->{_parent_resultset}) {
+    $self->{_parent_resultset}->throw_exception(@_)
+  } else {
+    croak(@_);
+  }
+}
+
+# _resultset
+#
+# Arguments: none
+#
+# Return Value: $resultset
+#
+#  $year_col->_resultset->next
+#
+# Returns the underlying resultset. Creates it from the parent resultset if
+# necessary.
+# 
+sub _resultset {
+  my $self = shift;
+
+  return $self->{_resultset} ||= $self->{_parent_resultset}->search(undef,
+    {
+      select => [$self->{_select}],
+      as => [$self->{_as}]
+    }
+  );
+}
+
+
 1;
 
 =head1 AUTHORS
index 61b53fa..a1abb1b 100644 (file)
@@ -40,7 +40,7 @@ sub _init_result_source_instance {
 
     $class->result_source_instance($table);
 
-    if ($class->can('schema_instance')) {
+    if ($class->can('schema_instance') && $class->schema_instance) {
         $class =~ m/([^:]+)$/;
         $class->schema_instance->register_class($class, $class);
     }
index 0d08638..c1fb2b0 100644 (file)
@@ -761,24 +761,17 @@ sub set_inflated_columns {
       {
         my $rel = delete $upd->{$key};
         $self->set_from_related($key => $rel);
-        $self->{_relationship_data}{$key} = $rel;          
+        $self->{_relationship_data}{$key} = $rel;
       } elsif ($info && $info->{attrs}{accessor}
-        && $info->{attrs}{accessor} eq 'multi'
-        && ref $upd->{$key} eq 'ARRAY') {
-        my $others = delete $upd->{$key};
-        foreach my $rel_obj (@$others) {
-          if(!Scalar::Util::blessed($rel_obj)) {
-            $rel_obj = $self->create_related($key, $rel_obj);
-          }
-        }
-        $self->{_relationship_data}{$key} = $others; 
-#            $related->{$key} = $others;
-        next;
+        && $info->{attrs}{accessor} eq 'multi') {
+          $self->throw_exception(
+            "Recursive update is not supported over relationships of type multi ($key)"
+          );
       }
       elsif ($self->has_column($key)
         && exists $self->column_info($key)->{_inflate_info})
       {
-        $self->set_inflated_column($key, delete $upd->{$key});          
+        $self->set_inflated_column($key, delete $upd->{$key});
       }
     }
   }
index a65c0a9..cf054d0 100644 (file)
@@ -707,26 +707,15 @@ wantarray context if you want the PKs automatically created.
 
 sub populate {
   my ($self, $name, $data) = @_;
-  my $rs = $self->resultset($name);
-  my @names = @{shift(@$data)};
-  if(defined wantarray) {
-    my @created;
-    foreach my $item (@$data) {
-      my %create;
-      @create{@names} = @$item;
-      push(@created, $rs->create(\%create));
+  if(my $rs = $self->resultset($name)) {
+    if(defined wantarray) {
+        return $rs->populate($data);
+    } else {
+        $rs->populate($data);
     }
-    return @created;
-  }
-  my @results_to_create;
-  foreach my $datum (@$data) {
-    my %result_to_create;
-    foreach my $index (0..$#names) {
-      $result_to_create{$names[$index]} = $$datum[$index];
-    }
-    push @results_to_create, \%result_to_create;
+  } else {
+      $self->throw_exception("$name is not a resultset"); 
   }
-  $rs->populate(\@results_to_create);
 }
 
 =head2 connection
index 3d23970..5eefa25 100644 (file)
@@ -65,7 +65,12 @@ sub _find_syntax {
 
 sub select {
   my ($self, $table, $fields, $where, $order, @rest) = @_;
-  $table = $self->_quote($table) unless ref($table);
+  if (ref $table eq 'SCALAR') {
+    $table = $$table;
+  }
+  elsif (not ref $table) {
+    $table = $self->_quote($table);
+  }
   local $self->{rownum_hack_count} = 1
     if (defined $rest[0] && $self->{limit_dialect} eq 'RowNum');
   @rest = (-1) unless defined $rest[0];
index 710be6e..7d5bf10 100644 (file)
@@ -54,7 +54,7 @@ sub sqlt_type { 'ACCESS' }
 \r
 =head1 NAME\r
 \r
-DBIx::Class::Storage::ODBC::ACCESS - Support specific to MS Access over ODBC\r
+DBIx::Class::Storage::DBI::ODBC::ACCESS - Support specific to MS Access over ODBC\r
 \r
 =head1 WARNING\r
 \r
index 07abe57..5fbd994 100644 (file)
@@ -6,7 +6,7 @@ use warnings;
 
 =head1 NAME
 
-DBIx::Class::Storage::DBI::Oracle - Automatic primary key class for Oracle
+DBIx::Class::Storage::DBI::Oracle::Generic - Automatic primary key class for Oracle
 
 =head1 SYNOPSIS
 
index 5021ed9..8af899c 100644 (file)
@@ -126,19 +126,20 @@ or just just forgot to create them :)
 around 'next_storage' => sub {
   my ($next_storage, $self, @args) = @_;
   my $now = time;
-    
+
   ## Do we need to validate the replicants?
   if(
      $self->has_auto_validate_every && 
      ($self->auto_validate_every + $self->pool->last_validated) <= $now
-  ) {
+  ) {   
       $self->pool->validate_replicants;
   }
-    
+
   ## Get a replicant, or the master if none
   if(my $next = $self->$next_storage(@args)) {
     return $next;
   } else {
+    $self->master->debugobj->print("No Replicants validate, falling back to master reads. ");
     return $self->master;
   }
 };
index b1cdc82..833ffad 100644 (file)
@@ -168,14 +168,38 @@ and return it.
 sub connect_replicant {
   my ($self, $schema, $connect_info) = @_;
   my $replicant = $self->create_replicant($schema);
-    
-  $replicant->connect_info($connect_info);    
-  $replicant->ensure_connected;
-  DBIx::Class::Storage::DBI::Replicated::Replicant->meta->apply($replicant);
-    
+  $replicant->connect_info($connect_info);
+  $self->_safely_ensure_connected($replicant);
+  DBIx::Class::Storage::DBI::Replicated::Replicant->meta->apply($replicant);  
   return $replicant;
 }
 
+=head2 _safely_ensure_connected ($replicant)
+
+The standard ensure_connected method with throw an exception should it fail to
+connect.  For the master database this is desirable, but since replicants are
+allowed to fail, this behavior is not desirable.  This method wraps the call
+to ensure_connected in an eval in order to catch any generated errors.  That
+way a slave to go completely offline (ie, the box itself can die) without
+bringing down your entire pool of databases.
+
+=cut
+
+sub _safely_ensure_connected {
+  my ($self, $replicant, @args) = @_;
+  my $return; eval {
+    $return = $replicant->ensure_connected(@args);
+  }; if ($@) {
+    $replicant
+        ->debugobj
+        ->print(
+            sprintf( "Exception trying to ->ensure_connected for replicant %s, error is %s",
+                $self->_dbi_connect_info->[0], $@)
+        );
+  }
+  return $return;
+}
+
 =head2 connected_replicants
 
 Returns true if there are connected replicants.  Actually is overloaded to
@@ -242,23 +266,43 @@ connection is not following a master or is lagging.
 Calling this method will generate queries on the replicant databases so it is
 not recommended that you run them very often.
 
+This method requires that your underlying storage engine supports some sort of
+native replication mechanism.  Currently only MySQL native replication is
+supported.  Your patches to make other replication types work are welcomed.
+
 =cut
 
 sub validate_replicants {
   my $self = shift @_;
   foreach my $replicant($self->all_replicants) {
-    if(
-      $replicant->is_replicating &&
-      $replicant->lag_behind_master <= $self->maximum_lag &&
-      $replicant->ensure_connected
-    ) {
-      $replicant->active(1)
+    if($self->_safely_ensure_connected($replicant)) {
+      my $is_replicating = $replicant->is_replicating;
+      unless(defined $is_replicating) {
+        $replicant->debugobj->print("Storage Driver ".ref $self." Does not support the 'is_replicating' method.  Assuming you are manually managing.");
+        next;
+      } else {
+        if($is_replicating) {
+          my $lag_behind_master = $replicant->lag_behind_master;
+          unless(defined $lag_behind_master) {
+            $replicant->debugobj->print("Storage Driver ".ref $self." Does not support the 'lag_behind_master' method.  Assuming you are manually managing.");
+            next;
+          } else {
+            if($lag_behind_master <= $self->maximum_lag) {
+              $replicant->active(1);
+            } else {
+              $replicant->active(0);  
+            }
+          }    
+        } else {
+          $replicant->active(0);
+        }
+      }
     } else {
       $replicant->active(0);
     }
   }
   ## Mark that we completed this validation.  
-  $self->_last_validated(time);
+  $self->_last_validated(time);  
 }
 
 =head1 AUTHOR
index d97120b..e9612f3 100644 (file)
@@ -52,7 +52,7 @@ has 'active' => (
 
 This class defines the following methods.
 
-=head2 after: _query_start
+=head2 around: _query_start
 
 advice iof the _query_start method to add more debuggin
 
index 9009f65..3199e75 100644 (file)
@@ -5,7 +5,7 @@ requires '_query_start';
 
 =head1 NAME
 
-DBIx::Class::Storage::DBI::Role::QueryCounter; Role to add a query counter
+DBIx::Class::Storage::DBI::Role::QueryCounter - Role to add a query counter
 
 =head1 SYNOPSIS
 
@@ -78,4 +78,4 @@ You may distribute this code under the same terms as Perl itself.
 =cut
 
 
-1;
\ No newline at end of file
+1;
index 4eca3b5..89b9f41 100644 (file)
@@ -15,7 +15,7 @@ use Test::More;
 use lib qw(t/lib);
 use DBICTest;
 
-plan tests => 134;
+plan tests => 142;
 
 
 ## ----------------------------------------------------------------------------
@@ -601,4 +601,30 @@ VOID_CONTEXT: {
                ok( $cd2->title eq "VOID_Yet More Tweeny-Pop crap", "Got Expected CD Title");
        }
 
+}
+
+ARRAYREF_OF_ARRAYREF_STYLE: {
+  $art_rs->populate([
+    [qw/artistid name/],
+    [1000, 'A Formally Unknown Singer'],
+    [1001, 'A singer that jumped the shark two albums ago'],
+    [1002, 'An actually cool singer.'],
+  ]);
+  
+  ok my $unknown = $art_rs->find(1000), "got Unknown";
+  ok my $jumped = $art_rs->find(1001), "got Jumped";
+  ok my $cool = $art_rs->find(1002), "got Cool";
+  
+  is $unknown->name, 'A Formally Unknown Singer', 'Correct Name';
+  is $jumped->name, 'A singer that jumped the shark two albums ago', 'Correct Name';
+  is $cool->name, 'An actually cool singer.', 'Correct Name';
+  
+  my ($cooler, $lamer) = $art_rs->populate([
+    [qw/artistid name/],
+    [1003, 'Cooler'],
+    [1004, 'Lamer'],   
+  ]);
+  
+  is $cooler->name, 'Cooler', 'Correct Name';
+  is $lamer->name, 'Lamer', 'Correct Name';  
 }
\ No newline at end of file
diff --git a/t/103many_to_many_warning.t b/t/103many_to_many_warning.t
new file mode 100644 (file)
index 0000000..c316820
--- /dev/null
@@ -0,0 +1,102 @@
+use strict;
+use warnings;
+use Test::More;
+
+use lib qw(t/lib);
+use Data::Dumper;
+
+plan tests => 2;
+
+{
+  my @w; 
+  local $SIG{__WARN__} = sub { push @w, @_ };
+
+  my $code = gen_code ( suffix => 1 );
+  eval "$code";
+
+  ok ( (grep { $_ =~ /The many-to-many relationship bars is trying to create/ } @w), "Warning triggered without relevant 'no warnings'");
+}
+
+{
+  my @w; 
+  local $SIG{__WARN__} = sub { push @w, @_ };
+
+  my $code = gen_code ( suffix => 2, no_warn => 1 );
+  eval "$code";
+
+diag Dumper \@w;
+
+  ok ( (not grep { $_ =~ /The many-to-many relationship bars is trying to create/ } @w), "No warning triggered with relevant 'no warnings'");
+}
+
+sub gen_code {
+
+  my $args = { @_ };
+  my $suffix = $args->{suffix};
+  my $no_warn = ( $args->{no_warn}
+    ? "no warnings 'DBIx::Class::Relationship::ManyToMany';"
+    : '',
+  );
+
+  return <<EOF;
+use strict;
+use warnings;
+
+{
+  package #
+    DBICTest::Schema::Foo${suffix};
+  use base 'DBIx::Class::Core';
+  __PACKAGE__->table('foo');
+  __PACKAGE__->add_columns(
+    'fooid' => {
+      data_type => 'integer',
+      is_auto_increment => 1,
+    },
+  );
+  __PACKAGE__->set_primary_key('fooid');
+
+
+  __PACKAGE__->has_many('foo_to_bar' => 'DBICTest::Schema::FooToBar${suffix}' => 'bar');
+  __PACKAGE__->many_to_many( foos => foo_to_bar => 'bar' );
+}
+{
+  package #
+    DBICTest::Schema::FooToBar${suffix};
+
+  use base 'DBIx::Class::Core';
+  __PACKAGE__->table('foo_to_bar');
+  __PACKAGE__->add_columns(
+    'foo' => {
+      data_type => 'integer',
+    },
+    'bar' => {
+      data_type => 'integer',
+    },
+  );
+  __PACKAGE__->belongs_to('foo' => 'DBICTest::Schema::Foo${suffix}');
+  __PACKAGE__->belongs_to('bar' => 'DBICTest::Schema::Foo${suffix}');
+}
+{
+  package #
+    DBICTest::Schema::Bar${suffix};
+
+  use base 'DBIx::Class::Core';
+  __PACKAGE__->table('bar');
+  __PACKAGE__->add_columns(
+    'barid' => {
+      data_type => 'integer',
+      is_auto_increment => 1,
+    },
+  );
+
+  ${no_warn}
+  __PACKAGE__->set_primary_key('barid');
+  __PACKAGE__->has_many('foo_to_bar' => 'DBICTest::Schema::FooToBar${suffix}' => 'foo');
+
+  __PACKAGE__->many_to_many( bars => foo_to_bar => 'foo' );
+
+  sub add_to_bars {}
+}
+EOF
+
+}
index 381872d..df6957c 100644 (file)
@@ -34,7 +34,7 @@ eval {
     {
         local $SIG{__WARN__} = sub {};
         eval { $dbh->do("DROP TABLE cd") };
-        $dbh->do("CREATE TABLE cd (cdid serial PRIMARY KEY, artist INTEGER NOT NULL UNIQUE, title VARCHAR(100) NOT NULL UNIQUE, year VARCHAR(100) NOT NULL, genreid INTEGER);");
+        $dbh->do("CREATE TABLE cd (cdid serial PRIMARY KEY, artist INTEGER NOT NULL UNIQUE, title VARCHAR(100) NOT NULL UNIQUE, year VARCHAR(100) NOT NULL, genreid INTEGER, single_track INTEGER);");
     }
 
     $schema->resultset('CD')->create({ title => 'vacation in antarctica', artist => 123, year => 1901 });
index 45e6247..a7a3a78 100644 (file)
@@ -44,7 +44,7 @@ eval {
     {
         local $SIG{__WARN__} = sub {};
         eval { $dbh->do("DROP TABLE cd") };
-        $dbh->do("CREATE TABLE cd (cdid serial PRIMARY KEY, artist INTEGER NOT NULL UNIQUE, title VARCHAR(100) NOT NULL UNIQUE, year VARCHAR(100) NOT NULL, genreid INTEGER);");
+        $dbh->do("CREATE TABLE cd (cdid serial PRIMARY KEY, artist INTEGER NOT NULL UNIQUE, title VARCHAR(100) NOT NULL UNIQUE, year VARCHAR(100) NOT NULL, genreid INTEGER, single_track INTEGER);");
     }
 
     $schema->resultset('CD')->create({ title => 'vacation in antarctica', artist => 123, year => 1901 });
index 7af0ff8..3cc6779 100644 (file)
@@ -44,7 +44,7 @@ eval {
     {
         local $SIG{__WARN__} = sub {};
         eval { $dbh->do("DROP TABLE cd") };
-        $dbh->do("CREATE TABLE cd (cdid serial PRIMARY KEY, artist INTEGER NOT NULL UNIQUE, title VARCHAR(100) NOT NULL UNIQUE, year VARCHAR(100) NOT NULL, genreid INTEGER);");
+        $dbh->do("CREATE TABLE cd (cdid serial PRIMARY KEY, artist INTEGER NOT NULL UNIQUE, title VARCHAR(100) NOT NULL UNIQUE, year VARCHAR(100) NOT NULL, genreid INTEGER, single_track INTEGER);");
     }
 
     $schema->resultset('CD')->create({ title => 'vacation in antarctica', artist => 123, year => 1901 });
index 808b6b4..a46be69 100644 (file)
@@ -153,7 +153,7 @@ is($schema->resultset("Artist")->count, 4, 'count ok');
 my $cd = $schema->resultset("CD")->find(1);
 my %cols = $cd->get_columns;
 
-cmp_ok(keys %cols, '==', 5, 'get_columns number of columns ok');
+cmp_ok(keys %cols, '==', 6, 'get_columns number of columns ok');
 
 is($cols{title}, 'Spoonful of bees', 'get_columns values ok');
 
@@ -169,7 +169,7 @@ $cd->discard_changes;
 # check whether ResultSource->columns returns columns in order originally supplied
 my @cd = $schema->source("CD")->columns;
 
-is_deeply( \@cd, [qw/cdid artist title year genreid/], 'column order');
+is_deeply( \@cd, [qw/cdid artist title year genreid single_track/], 'column order');
 
 $cd = $schema->resultset("CD")->search({ title => 'Spoonful of bees' }, { columns => ['title'] })->next;
 is($cd->title, 'Spoonful of bees', 'subset of columns returned correctly');
@@ -335,9 +335,9 @@ ok(!$@, "stringify to false value doesn't cause error");
 
 # test remove_columns
 {
-  is_deeply([$schema->source('CD')->columns], [qw/cdid artist title year genreid/]);
+  is_deeply([$schema->source('CD')->columns], [qw/cdid artist title year genreid single_track/]);
   $schema->source('CD')->remove_columns('year');
-  is_deeply([$schema->source('CD')->columns], [qw/cdid artist title genreid/]);
+  is_deeply([$schema->source('CD')->columns], [qw/cdid artist title genreid single_track/]);
   ok(! exists $schema->source('CD')->_columns->{'year'}, 'year still exists in _columns');
 }
 
index 81646fa..fe0196c 100644 (file)
@@ -1,13 +1,14 @@
 use strict;
-use warnings;  
+use warnings;
 
 use Test::More;
+use Test::Exception;
 use lib qw(t/lib);
 use DBICTest;
 
 my $schema = DBICTest->init_schema();
 
-plan tests => 69;
+plan tests => 74;
 
 # has_a test
 my $cd = $schema->resultset("CD")->find(4);
@@ -40,7 +41,20 @@ if ($INC{'DBICTest/HelperRels.pm'}) {
   } );
 }
 
-is( ($artist->search_related('cds'))[3]->title, 'Big Flop', 'create_related ok' );
+my $big_flop_cd = ($artist->search_related('cds'))[3];
+is( $big_flop_cd->title, 'Big Flop', 'create_related ok' );
+
+{ # make sure we are not making pointless select queries when a FK IS NULL
+  my $queries = 0;
+  $schema->storage->debugcb(sub { $queries++; });
+  $schema->storage->debug(1);
+  $big_flop_cd->genre; #should not trigger a select query
+  is($queries, 0, 'No SELECT made for belongs_to if key IS NULL');
+  $big_flop_cd->genre_inefficient; #should trigger a select query
+  is($queries, 1, 'SELECT made for belongs_to if key IS NULL when undef_on_null_fk disabled');
+  $schema->storage->debug(0);
+  $schema->storage->debugcb(undef);
+}
 
 my( $rs_from_list ) = $artist->search_related_rs('cds');
 is( ref($rs_from_list), 'DBIx::Class::ResultSet', 'search_related_rs in list context returns rs' );
@@ -261,6 +275,23 @@ is ($@, '', 'Staged insertion successful');
 ok($new_artist->in_storage, 'artist inserted');
 ok($new_related_cd->in_storage, 'new_related_cd inserted');
 
+TODO: {
+local $TODO = "TODOify for multicreate branch";
+my $new_cd = $schema->resultset("CD")->new_result({});
+my $new_related_artist = $new_cd->new_related('artist', { 'name' => 'Marillion',});
+lives_ok (
+    sub {
+       $new_related_artist->insert;
+       $new_cd->title( 'Misplaced Childhood' );
+       $new_cd->year ( 1985 );
+#       $new_cd->artist( $new_related_artist );  # For exact backward compatibility     # not sure what this means
+       $new_cd->insert;
+    },
+    'Reversed staged insertion successful'
+);
+ok($new_related_artist->in_storage, 'related artist inserted');
+ok($new_cd->in_storage, 'cd inserted');
+
 # check if is_foreign_key_constraint attr is set
 my $rs_normal = $schema->source('Track');
 my $relinfo = $rs_normal->relationship_info ('cd');
@@ -269,3 +300,4 @@ cmp_ok($relinfo->{attrs}{is_foreign_key_constraint}, '==', 1, "is_foreign_key_co
 my $rs_overridden = $schema->source('ForceForeign');
 my $relinfo_with_attr = $rs_overridden->relationship_info ('cd_3');
 cmp_ok($relinfo_with_attr->{attrs}{is_foreign_key_constraint}, '==', 0, "is_foreign_key_constraint defined for belongs_to relationships with attr.");
+}
index 214e11a..7138989 100644 (file)
@@ -4,7 +4,6 @@ use warnings;
 use Test::More qw(no_plan);
 use lib qw(t/lib);
 use DBICTest;
-use DBIx::Class::ResultClass::HashRefInflator;
 my $schema = DBICTest->init_schema();
 
 
@@ -62,6 +61,7 @@ sub check_cols_of {
 $schema->resultset('CD')->create({ title => 'Silence is golden', artist => 3, year => 2006 });
 
 # order_by to ensure both resultsets have the rows in the same order
+# also check result_class-as-an-attribute syntax
 my $rs_dbic = $schema->resultset('CD')->search(undef,
     {
         prefetch    => [ qw/ artist tracks / ],
@@ -72,9 +72,9 @@ my $rs_hashrefinf = $schema->resultset('CD')->search(undef,
     {
         prefetch    => [ qw/ artist tracks / ],
         order_by    => [ 'me.cdid', 'tracks.position' ],
+        result_class => 'DBIx::Class::ResultClass::HashRefInflator',
     }
 );
-$rs_hashrefinf->result_class('DBIx::Class::ResultClass::HashRefInflator');
 
 my @dbic        = $rs_dbic->all;
 my @hashrefinf  = $rs_hashrefinf->all;
@@ -98,8 +98,8 @@ $rs_hashrefinf = $schema->resultset ('Artist')->search ({ 'me.artistid' => 1}, {
     select   => [qw/name   tracks.title      tracks.cd       /],
     as       => [qw/name   cds.tracks.title  cds.tracks.cd   /],
     order_by => [qw/cds.cdid tracks.trackid/],
+    result_class => 'DBIx::Class::ResultClass::HashRefInflator',
 });
-$rs_hashrefinf->result_class('DBIx::Class::ResultClass::HashRefInflator');
 
 @dbic = map { $_->tracks->all } ($rs_dbic->first->cds->all);
 @hashrefinf  = $rs_hashrefinf->all;
index c5b4bb9..238f27a 100644 (file)
@@ -30,7 +30,7 @@ $dbh->do("IF OBJECT_ID('cd', 'U') IS NOT NULL
     DROP TABLE cd");
 
 $dbh->do("CREATE TABLE artist (artistid INT IDENTITY PRIMARY KEY, name VARCHAR(100), rank INT DEFAULT '13', charfield CHAR(10) NULL);");
-$dbh->do("CREATE TABLE cd (cdid INT IDENTITY PRIMARY KEY, artist INT,  title VARCHAR(100), year VARCHAR(100), genreid INT NULL);");
+$dbh->do("CREATE TABLE cd (cdid INT IDENTITY PRIMARY KEY, artist INT,  title VARCHAR(100), year VARCHAR(100), genreid INT NULL, single_track INT NULL);");
 # Just to test compat shim, Auto is in Core
 $schema->class('Artist')->load_components('PK::Auto::MSSQL');
 
index 213ecba..2d60873 100644 (file)
@@ -8,7 +8,7 @@ use DBICTest;
 
 my $schema = DBICTest->init_schema();
 
-plan tests => 7;
+plan tests => 11;
 
 my $rs = $schema->resultset('CD')->search({},
     {
@@ -42,3 +42,22 @@ $rs = $schema->resultset('CD')->search({},
 lives_ok(sub { $rs->first->get_column('count') }, '+select/+as chained search 1st rscolumn present');
 lives_ok(sub { $rs->first->get_column('addedtitle') }, '+select/+as chained search 1st rscolumn present');
 lives_ok(sub { $rs->first->get_column('addedtitle2') }, '+select/+as chained search 3rd rscolumn present');
+
+
+# test the from search attribute (gets between the FROM and WHERE keywords, allows arbitrary subselects)
+# also shows that outer select attributes are ok (i.e. order_by)
+#
+# from doesn't seem to be useful without using a scalarref - there were no initial tests >:(
+#
+my $cds = $schema->resultset ('CD')->search ({}, { order_by => 'me.cdid'}); # make sure order is consistent
+cmp_ok ($cds->count, '>', 2, 'Initially populated with more than 2 CDs');
+
+my $table = $cds->result_source->name;
+my $subsel = $cds->search ({}, {
+    columns => [qw/cdid title/],
+    from => \ "(SELECT cdid, title FROM $table LIMIT 2) me",
+});
+
+is ($subsel->count, 2, 'Subselect correctly limited the rs to 2 cds');
+is ($subsel->next->title, $cds->next->title, 'First CD title match');
+is ($subsel->next->title, $cds->next->title, 'Second CD title match');
index a91c429..608c8eb 100644 (file)
@@ -348,7 +348,6 @@ is($queries, 0, 'chained search_related after has_many->has_many prefetch ran no
 # (the TODO block itself contains tests ensuring that the warns are removed)
 TODO: {
     local $TODO = 'Prefetch of multiple has_many rels at the same level (currently warn to protect the clueless git)';
-    use DBIx::Class::ResultClass::HashRefInflator;
 
     #( 1 -> M + M )
     my $cd_rs = $schema->resultset('CD')->search ({ 'me.title' => 'Forkful of bees' });
index 52221f9..66169f3 100644 (file)
@@ -2,15 +2,16 @@ use strict;
 use warnings;  
 
 use Test::More;
+use Test::Exception;
 use lib qw(t/lib);
 use DBICTest;
 
 my $schema = DBICTest->init_schema();
 
-plan tests => 14;
+plan tests => 18;
 
 my $cd;
-my $rs = $cd = $schema->resultset("CD")->search({});
+my $rs = $cd = $schema->resultset("CD")->search({}, { order_by => 'cdid' });
 
 my $rs_title = $rs->get_column('title');
 my $rs_year = $rs->get_column('year');
@@ -28,22 +29,39 @@ is($rs_title->min, 'Caterwaulin\' Blues', "min okay for title");
 
 cmp_ok($rs_year->sum, '==', 9996, "three artists returned");
 
+$rs_year->reset;
+is($rs_year->next, 1999, "reset okay");
+
+is($rs_year->first, 1999, "first okay");
+
+# test +select/+as for single column
 my $psrs = $schema->resultset('CD')->search({},
     {
         '+select'   => \'COUNT(*)',
         '+as'       => 'count'
     }
 );
-ok(defined($psrs->get_column('count')), '+select/+as count');
+lives_ok(sub { $psrs->get_column('count')->next }, '+select/+as additional column "count" present (scalar)');
+dies_ok(sub { $psrs->get_column('noSuchColumn')->next }, '+select/+as nonexistent column throws exception');
 
+# test +select/+as for multiple columns
 $psrs = $schema->resultset('CD')->search({},
     {
         '+select'   => [ \'COUNT(*)', 'title' ],
         '+as'       => [ 'count', 'addedtitle' ]
     }
 );
-ok(defined($psrs->get_column('count')), '+select/+as arrayref count');
-ok(defined($psrs->get_column('addedtitle')), '+select/+as title');
+lives_ok(sub { $psrs->get_column('count')->next }, '+select/+as multiple additional columns, "count" column present');
+lives_ok(sub { $psrs->get_column('addedtitle')->next }, '+select/+as multiple additional columns, "addedtitle" column present');
+
+# test +select/+as for overriding a column
+$psrs = $schema->resultset('CD')->search({},
+    {
+        'select'   => \"'The Final Countdown'",
+        'as'       => 'title'
+    }
+);
+is($psrs->get_column('title')->next, 'The Final Countdown', '+select/+as overridden column "title"');
 
 {
   my $rs = $schema->resultset("CD")->search({}, { prefetch => 'artist' });
index a9a1b73..d940eaa 100644 (file)
@@ -57,7 +57,7 @@ open(STDERR, '>&STDERRCOPY');
     my @cds = $schema->resultset('CD')->search( { artist => 1, cdid => { -between => [ 1, 3 ] }, } );
     is_same_sql_bind(
         $sql, [],
-        "SELECT me.cdid, me.artist, me.title, me.year, me.genreid FROM cd me WHERE ( artist = ? AND cdid BETWEEN ? AND ? ): '1', '1', '3'", [],
+        "SELECT me.cdid, me.artist, me.title, me.year, me.genreid, me.single_track FROM cd me WHERE ( artist = ? AND cdid BETWEEN ? AND ? ): '1', '1', '3'", [],
         'got correct SQL with all bind parameters (debugcb)'
     );
 
@@ -66,7 +66,7 @@ open(STDERR, '>&STDERRCOPY');
     @cds = $schema->resultset('CD')->search( { artist => 1, cdid => { -between => [ 1, 3 ] }, } );
     is_same_sql_bind(
         $sql, \@bind,
-        "SELECT me.cdid, me.artist, me.title, me.year, me.genreid FROM cd me WHERE ( artist = ? AND cdid BETWEEN ? AND ? )", ["'1'", "'1'", "'3'"],
+        "SELECT me.cdid, me.artist, me.title, me.year, me.genreid, me.single_track FROM cd me WHERE ( artist = ? AND cdid BETWEEN ? AND ? )", ["'1'", "'1'", "'3'"],
         'got correct SQL with all bind parameters (debugobj)'
     );
 }
index ab2ffe4..b72405b 100644 (file)
@@ -249,6 +249,7 @@ $replicated
 $replicated->replicate;
 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(1);
 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(1);
+$replicated->schema->storage->pool->validate_replicants;
 
 ## Make sure we can read the data.
 
@@ -311,7 +312,7 @@ is $artist3->name, "Dead On Arrival"
     => 'Found expected name for first result';
 
 is $replicated->schema->storage->pool->connected_replicants => 1
-    => "One replicant reconnected to handle the job";
+    => "At Least One replicant reconnected to handle the job";
     
 ## What happens when we try to select something that doesn't exist?
 
@@ -355,6 +356,7 @@ ok $replicated->schema->resultset('Artist')->find(2)
 
 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(1);
 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(1);
+$replicated->schema->storage->pool->validate_replicants;
 
 ok $replicated->schema->resultset('Artist')->find(2)
     => 'Returned to replicates';
@@ -576,6 +578,9 @@ ok $replicated->schema->resultset('Artist')->find(1)
 ## Delete the old database files
 $replicated->cleanup;
 
+use Data::Dump qw/dump/;
+#warn dump $replicated->schema->storage->read_handler;
+
 
 
 
index 6461ad7..4445f3f 100644 (file)
@@ -2,10 +2,11 @@ use strict;
 use warnings;
 
 use Test::More;
+use Test::Exception;
 use lib qw(t/lib);
 use DBICTest;
 
-plan tests => 58;
+plan tests => 89;
 
 my $schema = DBICTest->init_schema();
 
@@ -25,7 +26,7 @@ eval {
 };
 diag $@ if $@;
 
-# same as above but the child and parent have no values, 
+# same as above but the child and parent have no values,
 # except for an explicit parent pk
 eval {
   my $bm_rs = $schema->resultset('Bookmark');
@@ -50,40 +51,216 @@ diag $@ if $@;
 
 # create over > 1 levels of has_many create (A => { has_many => { B => has_many => C } } )
 eval {
-  my $artist = $schema->resultset('Artist')->create(
-    { name => 'Fred 2',
+  my $artist = $schema->resultset('Artist')->first;
+  my $cd = $artist->create_related (cds => {
+    title => 'Music to code by',
+    year => 2007,
+    tags => [
+      { 'tag' => 'rock' },
+    ],
+  });
+
+  isa_ok($cd, 'DBICTest::CD', 'Created CD');
+  is($cd->title, 'Music to code by', 'CD created correctly');
+  is($cd->tags->count, 1, 'One tag created for CD');
+  is($cd->tags->first->tag, 'rock', 'Tag created correctly');
+
+};
+diag $@ if $@;
+
+throws_ok (
+  sub {
+    # Create via update - add a new CD <--- THIS SHOULD HAVE NEVER WORKED!
+    $schema->resultset('Artist')->first->update({
       cds => [
-        { title => 'Music to code by',
-          year => 2007,
-          tags => [
-            { 'tag' => 'rock' },
-          ],
+        { title => 'Yet another CD',
+          year => 2006,
         },
-    ],
+      ],
+    });
+  },
+  qr/Recursive update is not supported over relationships of type multi/,
+  'create via update of multi relationships throws an exception'
+);
+
+# Create m2m while originating in the linker table
+eval {
+  my $artist = $schema->resultset('Artist')->first;
+  my $c2p = $schema->resultset('CD_to_Producer')->create ({
+    cd => {
+      artist => $artist,
+      title => 'Bad investment',
+      year => 2008,
+      tracks => [
+        { position => 1, title => 'Just buy' },
+        { position => 2, title => 'Why did we do it' },
+        { position => 3, title => 'Burn baby burn' },
+      ],
+    },
+    producer => {
+      name => 'Lehman Bros.',
+    },
   });
 
-  isa_ok($artist, 'DBICTest::Artist', 'Created Artist');
-  is($artist->name, 'Fred 2', 'Artist created correctly');
-  is($artist->cds->count, 1, 'One CD created for artist');
-  is($artist->cds->first->title, 'Music to code by', 'CD created correctly');
-  is($artist->cds->first->tags->count, 1, 'One tag created for CD');
-  is($artist->cds->first->tags->first->tag, 'rock', 'Tag created correctly');
-
-  # Create via update - add a new CD
-  $artist->update({
-    cds => [ $artist->cds,
-      { title => 'Yet another CD',
-        year => 2006,
+  isa_ok ($c2p, 'DBICTest::CD_to_Producer', 'Linker object created');
+  my $prod = $schema->resultset ('Producer')->find ({ name => 'Lehman Bros.' });
+  isa_ok ($prod, 'DBICTest::Producer', 'Producer row found');
+  is ($prod->cds->count, 1, 'Producer has one production');
+  my $cd = $prod->cds->first;
+  is ($cd->title, 'Bad investment', 'CD created correctly');
+  is ($cd->tracks->count, 3, 'CD has 3 tracks');
+
+};
+diag $@ if $@;
+
+# create over > 1 levels of might_have (A => { might_have => { B => has_many => C } } )
+eval {
+  my $artist = $schema->resultset('Artist')->first;
+  my $cd = $schema->resultset('CD')->create ({
+    artist => $artist,
+    title => 'Music to code by at night',
+    year => 2008,
+    tracks => [
+      {
+        position => 1,
+        title => 'Off by one again',
+      },
+      {
+        position => 2,
+        title => 'The dereferencer',
+        cd_single => {
+          artist => $artist,
+          year => 2008,
+          title => 'Was that a null (Single)',
+          tracks => [
+            { title => 'The dereferencer', position => 1 },
+            { title => 'The dereferencer II', position => 2 },
+          ],
+          cd_to_producer => [
+            {
+              producer => {
+                name => 'K&R',
+              }
+            }
+          ]
+        },
       },
     ],
   });
-  is(($artist->cds->search({}, { order_by => 'year' }))[0]->title, 'Yet another CD', 'Updated and added another CD');
 
-  my $newartist = $schema->resultset('Artist')->find_or_create({ name => 'Fred 2'});
+  isa_ok ($cd, 'DBICTest::CD', 'Main CD object created');
+  is ($cd->title, 'Music to code by at night', 'Correct CD title');
+  is ($cd->tracks->count, 2, 'Two tracks on main CD');
+
+  my ($t1, $t2) = $cd->tracks->all;
+  is ($t1->title, 'Off by one again', 'Correct 1st track name');
+  is ($t1->cd_single, undef, 'No single for 1st track');
+  is ($t2->title, 'The dereferencer', 'Correct 2nd track name');
+  isa_ok ($t2->cd_single, 'DBICTest::CD', 'Created a single for 2nd track');
+
+  my $single = $t2->cd_single;
+  is ($single->tracks->count, 2, 'Two tracks on single CD');
+  is ($single->tracks->find ({ position => 1})->title, 'The dereferencer', 'Correct 1st track title');
+  is ($single->tracks->find ({ position => 2})->title, 'The dereferencer II', 'Correct 2nd track title');
+
+  is ($single->cd_to_producer->count, 1, 'One producer created with the single cd');
+  is ($single->cd_to_producer->first->producer->name, 'K&R', 'Producer name correct');
+};
+diag $@ if $@;
+
+TODO: {
+local $TODO = "Todoify for multicreate branch";
+# test might_have again but with a PK == FK in the middle (obviously not specified)
+eval {
+  my $artist = $schema->resultset('Artist')->first;
+  my $cd = $schema->resultset('CD')->create ({
+    artist => $artist,
+    title => 'Music to code by at twilight',
+    year => 2008,
+    artwork => {
+      images => [
+        { name => 'recursive descent' },
+        { name => 'tail packing' },
+      ],
+    },
+  });
+
+  isa_ok ($cd, 'DBICTest::CD', 'Main CD object created');
+  is ($cd->title, 'Music to code by at twilight', 'Correct CD title');
+  isa_ok ($cd->artwork, 'DBICTest::Artwork', 'Artwork created');
+
+  # this test might look weird, but it failed at one point, keep it there
+  my $art_obj = $cd->artwork;
+  ok ($art_obj->has_column_loaded ('cd_id'), 'PK/FK present on artwork object');
+  is ($art_obj->images->count, 2, 'Correct artwork image count via the new object');
+  is_deeply (
+    [ sort $art_obj->images->get_column ('name')->all ],
+    [ 'recursive descent', 'tail packing' ],
+    'Images named correctly in objects',
+  );
+
+
+  my $artwork = $schema->resultset('Artwork')->search (
+    { 'cd.title' => 'Music to code by at twilight' },
+    { join => 'cd' },
+  )->single;
+
+  is ($artwork->images->count, 2, 'Correct artwork image count via a new search');
+
+  is_deeply (
+    [ sort $artwork->images->get_column ('name')->all ],
+    [ 'recursive descent', 'tail packing' ],
+    'Images named correctly after search',
+  );
+};
+diag $@ if $@;
+
+# test might_have again but with just a PK and FK (neither specified) in the mid-table
+eval {
+  my $cd = $schema->resultset('CD')->first;
+  my $track = $schema->resultset ('Track')->create ({
+    cd => $cd,
+    position => 66,
+    title => 'Black',
+    lyrics => {
+      lyric_versions => [
+        { text => 'The color black' },
+        { text => 'The colour black' },
+      ],
+    },
+  });
+
+  isa_ok ($track, 'DBICTest::Track', 'Main track object created');
+  is ($track->title, 'Black', 'Correct track title');
+  isa_ok ($track->lyrics, 'DBICTest::Lyrics', 'Lyrics created');
+
+  # this test might look weird, but it was failing at one point, keep it there
+  my $lyric_obj = $track->lyrics;
+  ok ($lyric_obj->has_column_loaded ('lyric_id'), 'PK present on lyric object');
+  ok ($lyric_obj->has_column_loaded ('track_id'), 'FK present on lyric object');
+  is ($lyric_obj->lyric_versions->count, 2, 'Correct lyric versions count via the new object');
+  is_deeply (
+    [ sort $lyric_obj->lyric_versions->get_column ('text')->all ],
+    [ 'The color black', 'The colour black' ],
+    'Lyrics text in objects matches',
+  );
+
+
+  my $lyric = $schema->resultset('Lyrics')->search (
+    { 'track.title' => 'Black' },
+    { join => 'track' },
+  )->single;
+
+  is ($lyric->lyric_versions->count, 2, 'Correct lyric versions count via a new search');
 
-  is($newartist->name, 'Fred 2', 'Retrieved the artist');
+  is_deeply (
+    [ sort $lyric->lyric_versions->get_column ('text')->all ],
+    [ 'The color black', 'The colour black' ],
+    'Lyrics text via search matches',
+  );
 };
 diag $@ if $@;
+}
 
 # nested find_or_create
 eval {
@@ -103,7 +280,7 @@ diag $@ if $@;
 # multiple same level has_many create
 eval {
   my $artist2 = $schema->resultset('Artist')->create({
-    name => 'Fred 3',
+    name => 'Fred 4',
     cds => [
       {
         title => 'Music to code by',
@@ -510,3 +687,5 @@ eval {
   );
 };
 diag $@ if $@;
+
+1;
index 7921158..0b0db50 100644 (file)
@@ -2,20 +2,39 @@ use strict;
 use warnings;  
 
 use Test::More;
+use Test::Exception;
 use lib qw(t/lib);
 use DBICTest;
 
 my $schema = DBICTest->init_schema();
 
-plan tests => 9;
+plan tests => 12;
 
 {
   my $cd_rc = $schema->resultset("CD")->result_class;
   
+  throws_ok {
+    $schema->resultset("Artist")
+      ->search_rs({}, {result_class => "IWillExplode"})
+  } qr/Can't locate IWillExplode/, 'nonexistant result_class exception';
+
+# to make ensure_class_loaded happy, dies on inflate
+  eval 'package IWillExplode; sub dummy {}';
+
   my $artist_rs = $schema->resultset("Artist")
     ->search_rs({}, {result_class => "IWillExplode"});
   is($artist_rs->result_class, 'IWillExplode', 'Correct artist result_class');
-  
+
+  throws_ok {
+    $artist_rs->result_class('mtfnpy')
+  } qr/Can't locate mtfnpy/,
+  'nonexistant result_access exception (from accessor)';
+
+  throws_ok {
+    $artist_rs->first
+  } qr/Can't locate object method "inflate_result" via package "IWillExplode"/,
+  'IWillExplode explodes on inflate';
+
   my $cd_rs = $artist_rs->related_resultset('cds');
   is($cd_rs->result_class, $cd_rc, 'Correct cd result_class');
 
index 1ad7832..26d6b50 100644 (file)
@@ -9,7 +9,7 @@ BEGIN {
     eval "use DBD::mysql; use SQL::Translator 0.09;";
     plan $@
         ? ( skip_all => 'needs DBD::mysql and SQL::Translator 0.09 for testing' )
-        : ( tests => 102 );
+        : ( tests => 114 );
 }
 
 my $schema = DBICTest->init_schema();
index ee28a68..bd42d6e 100644 (file)
@@ -231,16 +231,25 @@ ok(
 );
 
 # Test that a disconnect doesnt harm anything.
-Film->db_Main->disconnect;
-@films = Film->search({ Rating => 'NC-17' });
-ok(@films == 1 && $films[0]->id eq $gone->id, 'auto reconnection');
-
-# Test discard_changes().
-my $orig_director = $btaste->Director;
-$btaste->Director('Lenny Bruce');
-is($btaste->Director, 'Lenny Bruce', 'set new Director');
-$btaste->discard_changes;
-is($btaste->Director, $orig_director, 'discard_changes()');
+{
+    # SQLite is loud on disconnect/reconnect. 
+    # This is solved in DBIC but not in ContextualFetch
+    local $SIG{__WARN__} = sub {
+      warn @_ unless $_[0] =~
+        /active statement handles|inactive database handle/;
+    };
+
+    Film->db_Main->disconnect;
+    @films = Film->search({ Rating => 'NC-17' });
+    ok(@films == 1 && $films[0]->id eq $gone->id, 'auto reconnection');
+
+    # Test discard_changes().
+    my $orig_director = $btaste->Director;
+    $btaste->Director('Lenny Bruce');
+    is($btaste->Director, 'Lenny Bruce', 'set new Director');
+    $btaste->discard_changes;
+    is($btaste->Director, $orig_director, 'discard_changes()');
+}
 
 SKIP: {
        skip "ActiveState perl produces additional warnings", 3
index 1f7a985..b487cc6 100644 (file)
@@ -8,7 +8,7 @@ BEGIN {
         next;
     }
     eval "use DBD::SQLite";
-    plan $@ ? (skip_all => 'needs DBD::SQLite for testing') : (tests => 55);
+    plan $@ ? (skip_all => 'needs DBD::SQLite for testing') : (tests => 75);
 }
 
 INIT {
@@ -57,18 +57,61 @@ my $data = {
 };
 
 eval {
-    my $data = $data;
+    my $data = { %$data };
     $data->{NumExplodingSheep} = 1;
     ok my $bt = Film->create($data), "Modified accessor - with column name";
     isa_ok $bt, "Film";
+    is $bt->sheep, 1, 'sheep bursting violently';
 };
 is $@, '', "No errors";
 
 eval {
-    my $data = $data;
-    $data->{sheep} = 1;
+    my $data = { %$data };
+    $data->{sheep} = 2;
     ok my $bt = Film->create($data), "Modified accessor - with accessor";
     isa_ok $bt, "Film";
+    is $bt->sheep, 2, 'sheep bursting violently';
+};
+is $@, '', "No errors";
+
+eval {
+    my $data = { %$data };
+    $data->{NumExplodingSheep} = 1;
+    ok my $bt = Film->find_or_create($data),
+               "find_or_create Modified accessor - find with column name";
+    isa_ok $bt, "Film";
+    is $bt->sheep, 1, 'sheep bursting violently';
+};
+is $@, '', "No errors";
+
+eval {
+    my $data = { %$data };
+    $data->{sheep} = 1;
+    ok my $bt = Film->find_or_create($data),
+               "find_or_create Modified accessor - find with accessor";
+    isa_ok $bt, "Film";
+    is $bt->sheep, 1, 'sheep bursting violently';
+};
+is $@, '', "No errors";
+
+TODO: { local $TODO = 'TODOifying failing tests, waiting for Schwern'; ok (1, 'remove me');
+eval {
+    my $data = { %$data };
+    $data->{NumExplodingSheep} = 3;
+    ok my $bt = Film->find_or_create($data),
+               "find_or_create Modified accessor - create with column name";
+    isa_ok $bt, "Film";
+    is $bt->sheep, 3, 'sheep bursting violently';
+};
+is $@, '', "No errors";
+
+eval {
+    my $data = { %$data };
+    $data->{sheep} = 4;
+    ok my $bt = Film->find_or_create($data),
+               "find_or_create Modified accessor - create with accessor";
+    isa_ok $bt, "Film";
+    is $bt->sheep, 4, 'sheep bursting violently';
 };
 is $@, '', "No errors";
 
@@ -76,6 +119,9 @@ eval {
     my @film = Film->search({ sheep => 1 });
     is @film, 2, "Can search with modified accessor";
 };
+is $@, '', "No errors";
+
+}
 
 {
 
@@ -114,6 +160,9 @@ eval {
     like $@, qr/film/, "no hasa film";
 
     eval {
+        local $SIG{__WARN__} = sub {
+            warn @_ unless $_[0] =~ /Query returned more than one row/;
+        };
         ok my $f = $ac->movie, "hasa movie";
         isa_ok $f, "Film";
         is $f->id, $bt->id, " - Bad Taste";
index 50a1647..af8689b 100644 (file)
@@ -1,5 +1,6 @@
 use strict;
 use Test::More;
+use Data::Dumper;
 
 BEGIN {
   eval "use DBIx::Class::CDBICompat;";
@@ -48,7 +49,8 @@ for my $args ({ no_cascade_delete => 1 }, { cascade => "None" }) {
     is $dir->nasties, 1, "We have one nasty";
 
     ok $dir->delete;
-    ok +Film->retrieve("Alligator"), "has_many with @{[ keys %$args ]} => @{[ values %$args ]}";
+    local $Data::Dumper::Terse = 1;
+    ok +Film->retrieve("Alligator"), 'has_many with ' . Dumper ($args);;
     $kk->delete;
 }
 
index 08f396f..d217e47 100644 (file)
@@ -20,6 +20,10 @@ __PACKAGE__->load_classes(qw/
   /,
   { 'DBICTest::Schema' => [qw/
     LinerNotes
+    Artwork
+    Image
+    Lyrics
+    LyricVersion
     OneKey
     #dummy
     TwoKeys
diff --git a/t/lib/DBICTest/Schema/Artwork.pm b/t/lib/DBICTest/Schema/Artwork.pm
new file mode 100644 (file)
index 0000000..f6e00d2
--- /dev/null
@@ -0,0 +1,16 @@
+package # hide from PAUSE 
+    DBICTest::Schema::Artwork;
+
+use base qw/DBIx::Class::Core/;
+
+__PACKAGE__->table('cd_artwork');
+__PACKAGE__->add_columns(
+  'cd_id' => {
+    data_type => 'integer',
+  },
+);
+__PACKAGE__->set_primary_key('cd_id');
+__PACKAGE__->belongs_to('cd', 'DBICTest::Schema::CD', 'cd_id');
+__PACKAGE__->has_many('images', 'DBICTest::Schema::Image', 'artwork_id');
+
+1;
index 41ed6bd..f222ff9 100644 (file)
@@ -23,6 +23,11 @@ __PACKAGE__->add_columns(
   'genreid' => { 
     data_type => 'integer',
     is_nullable => 1,
+  },
+  'single_track' => {
+    data_type => 'integer',
+    is_nullable => 1,
+    is_foreign_key => 1,
   }
 );
 __PACKAGE__->set_primary_key('cdid');
@@ -32,6 +37,9 @@ __PACKAGE__->belongs_to( artist => 'DBICTest::Schema::Artist', undef, {
     is_deferrable => 1, 
 });
 
+# in case this is a single-cd it promotes a track from another cd
+__PACKAGE__->belongs_to( single_track => 'DBICTest::Schema::Track' );
+
 __PACKAGE__->has_many( tracks => 'DBICTest::Schema::Track' );
 __PACKAGE__->has_many(
     tags => 'DBICTest::Schema::Tag', undef,
@@ -45,6 +53,8 @@ __PACKAGE__->might_have(
     liner_notes => 'DBICTest::Schema::LinerNotes', undef,
     { proxy => [ qw/notes/ ] },
 );
+__PACKAGE__->might_have(artwork => 'DBICTest::Schema::Artwork', 'cd_id');
+
 __PACKAGE__->many_to_many( producers => cd_to_producer => 'producer' );
 __PACKAGE__->many_to_many(
     producers_sorted => cd_to_producer => 'producer',
@@ -57,10 +67,22 @@ __PACKAGE__->belongs_to('genre', 'DBICTest::Schema::Genre',
         join_type => 'left',
         on_delete => 'SET NULL',
         on_update => 'CASCADE',
+    },
+);
 
+#This second relationship was added to test the short-circuiting of pointless
+#queries provided by undef_on_null_fk. the relevant test in 66relationship.t
+__PACKAGE__->belongs_to('genre_inefficient', 'DBICTest::Schema::Genre',
+    { 'foreign.genreid' => 'self.genreid' },
+    {
+        join_type => 'left',
+        on_delete => 'SET NULL',
+        on_update => 'CASCADE',
+        undef_on_null_fk => 0,
     },
 );
 
+
 #__PACKAGE__->add_relationship('genre', 'DBICTest::Schema::Genre',
 #    { 'foreign.genreid' => 'self.genreid' },
 #    { 'accessor' => 'single' }
diff --git a/t/lib/DBICTest/Schema/Image.pm b/t/lib/DBICTest/Schema/Image.pm
new file mode 100644 (file)
index 0000000..8df5add
--- /dev/null
@@ -0,0 +1,28 @@
+package # hide from PAUSE 
+    DBICTest::Schema::Image;
+
+use base qw/DBIx::Class::Core/;
+
+__PACKAGE__->table('images');
+__PACKAGE__->add_columns(
+  'id' => {
+    data_type => 'integer',
+    is_auto_increment => 1,
+  },
+  'artwork_id' => {
+    data_type => 'integer',
+    is_foreign_key => 1,
+  },
+  'name' => {
+    data_type => 'varchar',
+    size => 100,
+  },
+  'data' => {
+    data_type => 'blob',
+    is_nullable => 1,
+  },
+);
+__PACKAGE__->set_primary_key('id');
+__PACKAGE__->belongs_to('artwork', 'DBICTest::Schema::Artwork', 'artwork_id');
+
+1;
diff --git a/t/lib/DBICTest/Schema/LyricVersion.pm b/t/lib/DBICTest/Schema/LyricVersion.pm
new file mode 100644 (file)
index 0000000..d2f9769
--- /dev/null
@@ -0,0 +1,24 @@
+package # hide from PAUSE
+    DBICTest::Schema::LyricVersion;
+
+use base qw/DBIx::Class::Core/;
+
+__PACKAGE__->table('lyric_versions');
+__PACKAGE__->add_columns(
+  'id' => {
+    data_type => 'integer',
+    is_auto_increment => 1,
+  },
+  'lyric_id' => {
+    data_type => 'integer',
+    is_foreign_key => 1,
+  },
+  'text' => {
+    data_type => 'varchar',
+    size => 100,
+  },
+);
+__PACKAGE__->set_primary_key('id');
+__PACKAGE__->belongs_to('lyric', 'DBICTest::Schema::Lyrics', 'lyric_id');
+
+1;
diff --git a/t/lib/DBICTest/Schema/Lyrics.pm b/t/lib/DBICTest/Schema/Lyrics.pm
new file mode 100644 (file)
index 0000000..3e4024e
--- /dev/null
@@ -0,0 +1,21 @@
+package # hide from PAUSE 
+    DBICTest::Schema::Lyrics;
+
+use base qw/DBIx::Class::Core/;
+
+__PACKAGE__->table('lyrics');
+__PACKAGE__->add_columns(
+  'lyric_id' => {
+    data_type => 'integer',
+    is_auto_increment => 1,
+  },
+  'track_id' => {
+    data_type => 'integer',
+    is_foreign_key => 1,
+  },
+);
+__PACKAGE__->set_primary_key('lyric_id');
+__PACKAGE__->belongs_to('track', 'DBICTest::Schema::Track', 'track_id');
+__PACKAGE__->has_many('lyric_versions', 'DBICTest::Schema::LyricVersion', 'lyric_id');
+
+1;
index 26e140e..26ecddb 100644 (file)
@@ -20,5 +20,5 @@ __PACKAGE__->add_unique_constraint(prod_name => [ qw/name/ ]);
 __PACKAGE__->has_many(
     producer_to_cd => 'DBICTest::Schema::CD_to_Producer' => 'producer'
 );
-
+__PACKAGE__->many_to_many('cds', 'producer_to_cd', 'cd');
 1;
index 64eb0ee..ffbd2fd 100644 (file)
@@ -35,4 +35,7 @@ __PACKAGE__->add_unique_constraint([ qw/cd title/ ]);
 __PACKAGE__->belongs_to( cd => 'DBICTest::Schema::CD' );
 __PACKAGE__->belongs_to( disc => 'DBICTest::Schema::CD' => 'cd');
 
+__PACKAGE__->might_have( cd_single => 'DBICTest::Schema::CD', 'single_track' );
+__PACKAGE__->might_have( lyrics => 'DBICTest::Schema::Lyrics', 'track_id' );
+
 1;
index 1db9557..fcdae19 100644 (file)
@@ -1,6 +1,6 @@
 -- 
 -- Created by SQL::Translator::Producer::SQLite
--- Created on Mon Nov 10 23:52:55 2008
+-- Created on Mon Nov 17 02:53:11 2008
 -- 
 BEGIN TRANSACTION;
 
@@ -29,6 +29,15 @@ CREATE INDEX artist_undirected_map_idx_id1_ ON artist_undirected_map (id1);
 CREATE INDEX artist_undirected_map_idx_id2_ ON artist_undirected_map (id2);
 
 --
+-- Table: cd_artwork
+--
+CREATE TABLE cd_artwork (
+  cd_id INTEGER PRIMARY KEY NOT NULL
+);
+
+CREATE INDEX cd_artwork_idx_cd_id_cd_artwor ON cd_artwork (cd_id);
+
+--
 -- Table: bookmark
 --
 CREATE TABLE bookmark (
@@ -58,11 +67,13 @@ CREATE TABLE cd (
   artist integer NOT NULL,
   title varchar(100) NOT NULL,
   year varchar(100) NOT NULL,
-  genreid integer
+  genreid integer,
+  single_track integer
 );
 
 CREATE INDEX cd_idx_artist_cd ON cd (artist);
 CREATE INDEX cd_idx_genreid_cd ON cd (genreid);
+CREATE INDEX cd_idx_single_track_cd ON cd (single_track);
 CREATE UNIQUE INDEX cd_artist_title_cd ON cd (artist, title);
 
 --
@@ -183,6 +194,18 @@ CREATE TABLE genre (
 CREATE UNIQUE INDEX genre_name_genre ON genre (name);
 
 --
+-- Table: images
+--
+CREATE TABLE images (
+  id INTEGER PRIMARY KEY NOT NULL,
+  artwork_id integer NOT NULL,
+  name varchar(100) NOT NULL,
+  data blob
+);
+
+CREATE INDEX images_idx_artwork_id_images ON images (artwork_id);
+
+--
 -- Table: liner_notes
 --
 CREATE TABLE liner_notes (
@@ -203,6 +226,27 @@ CREATE TABLE link (
 
 
 --
+-- Table: lyric_versions
+--
+CREATE TABLE lyric_versions (
+  id INTEGER PRIMARY KEY NOT NULL,
+  lyric_id integer NOT NULL,
+  text varchar(100) NOT NULL
+);
+
+CREATE INDEX lyric_versions_idx_lyric_id_ly ON lyric_versions (lyric_id);
+
+--
+-- Table: lyrics
+--
+CREATE TABLE lyrics (
+  lyric_id INTEGER PRIMARY KEY NOT NULL,
+  track_id integer NOT NULL
+);
+
+CREATE INDEX lyrics_idx_track_id_lyrics ON lyrics (track_id);
+
+--
 -- Table: noprimarykey
 --
 CREATE TABLE noprimarykey (
index 7951482..eeb7cf0 100644 (file)
@@ -8,7 +8,8 @@ use DBI;
 
 use vars qw/$dbh/;
 
-my @connect = ("dbi:mysql:test", "", "");
+# temporary, might get switched to the new test framework someday
+my @connect = ("dbi:mysql:test", "", "", { PrintError => 0});
 
 $dbh = DBI->connect(@connect) or die DBI->errstr;
 my @table;