Merge 'trunk' into 'versioned_enhancements'
Luke Saunders [Mon, 22 Oct 2007 19:58:39 +0000 (19:58 +0000)]
r4056@luke-mbp (orig r3782):  ash | 2007-09-25 16:39:52 +0100
Throw if "foreign." and "self." are wrong way round in conditions for relationships
r4085@luke-mbp (orig r3794):  bricas | 2007-09-27 19:37:15 +0100
ResultSetColumn::func() now returns all results if called in list context
r4086@luke-mbp (orig r3795):  castaway | 2007-09-28 08:51:40 +0100
Tests from captainL, find_or_new_related fails on belongs_to rels.

r4087@luke-mbp (orig r3796):  wreis | 2007-09-29 01:35:55 +0100
select for patch from justin
r4088@luke-mbp (orig r3797):  castaway | 2007-09-29 23:37:07 +0100
Fix "redefined" errors resulting from loading a Schema twice.

r4089@luke-mbp (orig r3798):  captainL | 2007-10-02 16:38:21 +0100
fixed find_or_new_related bug
r4090@luke-mbp (orig r3799):  captainL | 2007-10-02 16:43:16 +0100
added comment explaining change
r4108@luke-mbp (orig r3800):  ash | 2007-10-03 21:00:32 +0100
Many-to-many relationships now warn if the utility methods would clash
r4109@luke-mbp (orig r3803):  semifor | 2007-10-04 17:29:15 +0100
 r1357@titanic:  mjm | 2007-10-04 08:48:06 -0700
 - Doc patch for using an SQL function on the left side of a comparison.
 - Which lead to the discovery of a bind args ordering bug.  TODO tests added
   for that.
 - Fixed =for hidden with =begin hidden / =end hidden elsewhere.
 - Added myself to the contributors list.

r4110@luke-mbp (orig r3804):  captainL | 2007-10-04 21:54:08 +0100
fixed search_related from object with unset FK behaviour
r4198@luke-mbp (orig r3805):  semifor | 2007-10-05 22:30:19 +0100
 r1365@titanic:  mjm | 2007-10-05 13:49:20 -0700
 Fixed warning on uninitialized value.

r4202@luke-mbp (orig r3809):  ash | 2007-10-07 22:50:33 +0100
Timezone support for InflateColumn::DateTime (sergio)
r4203@luke-mbp (orig r3813):  ash | 2007-10-12 11:26:55 +0100
Add an add_index method on ResultSource (and proxy classes)
r4204@luke-mbp (orig r3814):  ash | 2007-10-12 11:32:41 +0100
s/indices/indexes/ to keep Jess happy.
r4205@luke-mbp (orig r3815):  ash | 2007-10-12 18:46:55 +0100
Remove add_index and replace it with sqlt_deploy_hook
r4206@luke-mbp (orig r3816):  ash | 2007-10-12 19:20:43 +0100
Test sqlt_deploy_hook on the Schema level
r4207@luke-mbp (orig r3817):  ash | 2007-10-13 13:33:33 +0100
Add docs about sqlt_deploy_hook, and reorganise/reorder the Cookbook
r4208@luke-mbp (orig r3821):  nigel | 2007-10-17 16:59:12 +0100
Added reference to RH perl bug at appropriate points
r4209@luke-mbp (orig r3824):  ash | 2007-10-20 12:01:07 +0100
Added startup checks to warn loudly if we appear to be running on RedHat systems from perl-5.8.8-10 and up that have the bless/overload patch applied (badly) which causes 2x -> 100x performance penalty.  (Jon Schutz)
r4210@luke-mbp (orig r3825):  castaway | 2007-10-21 12:46:56 +0100
Documentation clarifications

r4211@luke-mbp (orig r3829):  captainL | 2007-10-22 20:45:46 +0100
fixed problem with duplicate related objects for Row::new/insert

28 files changed:
Changes
lib/DBIx/Class.pm
lib/DBIx/Class/InflateColumn/DateTime.pm
lib/DBIx/Class/Manual/Cookbook.pod
lib/DBIx/Class/Manual/FAQ.pod
lib/DBIx/Class/Manual/Intro.pod
lib/DBIx/Class/Relationship/ManyToMany.pm
lib/DBIx/Class/ResultSet.pm
lib/DBIx/Class/ResultSetColumn.pm
lib/DBIx/Class/ResultSource.pm
lib/DBIx/Class/ResultSourceHandle.pm
lib/DBIx/Class/Row.pm
lib/DBIx/Class/Schema.pm
lib/DBIx/Class/StartupCheck.pm [new file with mode: 0644]
lib/DBIx/Class/Storage.pm
lib/DBIx/Class/Storage/DBI.pm
lib/DBIx/Class/Storage/DBI/Oracle/WhereJoins.pm
lib/SQL/Translator/Parser/DBIx/Class.pm
t/47bind_attribute.t [new file with mode: 0644]
t/66relationship.t
t/72pg.t
t/86sqlt.t
t/88result_set_column.t
t/89inflate_datetime.t
t/96multi_create.t
t/lib/DBICTest/Schema.pm
t/lib/DBICTest/Schema/Artist.pm
t/lib/DBICTest/Schema/EventTZ.pm [new file with mode: 0644]

diff --git a/Changes b/Changes
index ccb5ded..2b81239 100644 (file)
--- a/Changes
+++ b/Changes
@@ -1,4 +1,19 @@
 Revision history for DBIx::Class
+        - Row::insert will now not fall over if passed duplicate related objects
+        - When adding relationships, it will throw an exception if you get the
+          foreign and self parts the wrong way round in the condition
+        - ResultSetColumn::func() now returns all results if called in list
+          context; this makes things like func('DISTINCT') work as expected
+        - Many-to-many relationships now warn if the utility methods would 
+          clash
+        - InflateColumn::DateTime now accepts an extra parameter of timezone
+          to set timezone on the DT object (thanks Sergio Salvi)
+        - Added sqlt_deploy_hook to result classes so that indexes can be 
+          added.
+        - Added startup checks to warn loudly if we appear to be running on 
+          RedHat systems from perl-5.8.8-10 and up that have the bless/overload
+          patch applied (badly) which causes 2x -> 100x performance penalty.
+          (Jon Schutz)
 
 0.08007 2007-09-04 19:36:00
         - patch for Oracle datetime inflation (abram@arin.net)
index 854df8e..3b591cb 100644 (file)
@@ -5,6 +5,7 @@ use warnings;
 
 use vars qw($VERSION);
 use base qw/DBIx::Class::Componentised Class::Accessor::Grouped/;
+use DBIx::Class::StartupCheck;
 
 
 sub mk_classdata { 
@@ -233,6 +234,8 @@ jguenther: Justin Guenther <jguenther@cpan.org>
 
 jnapiorkowski: John Napiorkowski <jjn1056@yahoo.com>
 
+jon: Jon Schutz <jjschutz@cpan.org>
+
 jshirley: J. Shirley <jshirley@gmail.com>
 
 konobi: Scott McWhirter
@@ -261,6 +264,8 @@ sc_: Just Another Perl Hacker
 
 scotty: Scotty Allen <scotty@scottyallen.com>
 
+semifor: Marc Mims <marc@questright.com>
+
 sszabo: Stephan Szabo <sszabo@bigpanda.com>
 
 Todd Lipcon
index df92390..a650d69 100644 (file)
@@ -24,6 +24,12 @@ Then you can treat the specified column as a L<DateTime> object.
   print "This event starts the month of ".
     $event->starts_when->month_name();
 
+If you want to set a specific timezone for that field, use:
+
+  __PACKAGE__->add_columns(
+    starts_when => { data_type => 'datetime', extra => { timezone => "America/Chicago" } }
+  );
+
 =head1 DESCRIPTION
 
 This module figures out the type of DateTime::Format::* class to 
@@ -55,6 +61,11 @@ sub register_column {
   return unless defined($info->{data_type});
   my $type = lc($info->{data_type});
   $type = 'datetime' if ($type =~ /^timestamp/);
+  my $timezone;
+  if ( exists $info->{extra} and exists $info->{extra}{timezone} and defined $info->{extra}{timezone} ) {
+    $timezone = $info->{extra}{timezone};
+  }
+
   if ($type eq 'datetime' || $type eq 'date') {
     my ($parse, $format) = ("parse_${type}", "format_${type}");
     $self->inflate_column(
@@ -62,10 +73,13 @@ sub register_column {
         {
           inflate => sub {
             my ($value, $obj) = @_;
-            $obj->_datetime_parser->$parse($value);
+            my $dt = $obj->_datetime_parser->$parse($value);
+            $dt->set_time_zone($timezone) if $timezone;
+            return $dt;
           },
           deflate => sub {
             my ($value, $obj) = @_;
+            $value->set_time_zone($timezone) if $timezone;
             $obj->_datetime_parser->$format($value);
           },
         }
index 9a96f34..0552a03 100644 (file)
@@ -2,11 +2,9 @@
 
 DBIx::Class::Manual::Cookbook - Miscellaneous recipes
 
-=head1 RECIPES
+=head1 SEARCHING
 
-=head2 Searching
-
-=head3 Paged results
+=head2 Paged results
 
 When you expect a large number of results, you can ask L<DBIx::Class> for a
 paged resultset, which will fetch only a defined number of records at a time:
@@ -37,7 +35,7 @@ resultset (suitable for use in e.g. a template) using the C<pager> method:
 
   return $rs->pager();
 
-=head3 Complex WHERE clauses
+=head2 Complex WHERE clauses
 
 Sometimes you need to formulate a query using specific operators:
 
@@ -70,7 +68,7 @@ This results in the following C<WHERE> clause:
 For more information on generating complex queries, see
 L<SQL::Abstract/WHERE CLAUSES>.
 
-=head3 Arbitrary SQL through a custom ResultSource
+=head2 Arbitrary SQL through a custom ResultSource
 
 Sometimes you have to run arbitrary SQL because your query is too complex
 (e.g. it contains Unions, Sub-Selects, Stored Procedures, etc.) or has to
@@ -120,7 +118,7 @@ Next, you can execute your complex query using bind parameters like this:
   
 ... and you'll get back a perfect L<DBIx::Class::ResultSet>.
 
-=head3 Using specific columns
+=head2 Using specific columns
 
 When you only want specific columns from a table, you can use
 C<columns> to specify which ones you need. This is useful to avoid
@@ -140,7 +138,7 @@ use anyway:
 This is a shortcut for C<select> and C<as>, see below. C<columns>
 cannot be used together with C<select> and C<as>.
 
-=head3 Using database functions or stored procedures
+=head2 Using database functions or stored procedures
 
 The combination of C<select> and C<as> can be used to return the result of a
 database function or stored procedure as a column value. You use C<select> to
@@ -184,7 +182,7 @@ any of your aliases using either of these:
   # Or use DBIx::Class::AccessorGroup:
   __PACKAGE__->mk_group_accessors('column' => 'name_length');
 
-=head3 SELECT DISTINCT with multiple columns
+=head2 SELECT DISTINCT with multiple columns
 
   my $rs = $schema->resultset('Foo')->search(
     {},
@@ -198,7 +196,7 @@ any of your aliases using either of these:
 
   my $count = $rs->next->get_column('count');
 
-=head3 SELECT COUNT(DISTINCT colname)
+=head2 SELECT COUNT(DISTINCT colname)
 
   my $rs = $schema->resultset('Foo')->search(
     {},
@@ -210,7 +208,7 @@ any of your aliases using either of these:
     }
   );
 
-=head3 Grouping results
+=head2 Grouping results
 
 L<DBIx::Class> supports C<GROUP BY> as follows:
 
@@ -233,7 +231,7 @@ Please see L<DBIx::Class::ResultSet/ATTRIBUTES> documentation if you
 are in any way unsure about the use of the attributes above (C< join
 >, C< select >, C< as > and C< group_by >).
 
-=head3 Predefined searches
+=head2 Predefined searches
 
 You can write your own L<DBIx::Class::ResultSet> class by inheriting from it
 and define often used searches as methods:
@@ -263,6 +261,39 @@ Then call your new method in your code:
 
    my $ordered_cds = $schema->resultset('CD')->search_cds_ordered();
 
+=head2 Using SQL functions on the left hand side of a comparison
+
+Using SQL functions on the left hand side of a comparison is generally
+not a good idea since it requires a scan of the entire table.  However,
+it can be accomplished with C<DBIx::Class> when necessary.
+
+If you do not have quoting on, simply include the function in your search
+specification as you would any column:
+
+  $rs->search({ 'YEAR(date_of_birth)' => 1979 });
+
+With quoting on, or for a more portable solution, use the C<where>
+attribute:
+
+  $rs->search({}, { where => \'YEAR(date_of_birth) = 1979' });
+
+=begin hidden
+
+(When the bind args ordering bug is fixed, this technique will be better
+and can replace the one above.)
+
+With quoting on, or for a more portable solution, use the C<where> and
+C<bind> attributes:
+
+  $rs->search({}, {
+      where => \'YEAR(date_of_birth) = ?',
+      bind  => [ 1979 ]
+  });
+
+=end hidden
+
+=head1 JOINS AND PREFETCHING
+
 =head2 Using joins and prefetch
 
 You can use the C<join> attribute to allow searching on, or sorting your
@@ -361,7 +392,7 @@ Also note that C<prefetch> should only be used when you know you will
 definitely use data from a related table. Pre-fetching related tables when you
 only need columns from the main table will make performance worse!
 
-=head3 Multi-step joins
+=head2 Multi-step joins
 
 Sometimes you want to join more than one relationship deep. In this example,
 we want to find all C<Artist> objects who have C<CD>s whose C<LinerNotes>
@@ -442,7 +473,248 @@ SQL statements:
   my $tag = $rs->first;
   print $tag->cd->artist->name;
 
-=head2 Columns of data
+=head1 ROW-LEVEL OPERATIONS
+
+=head2 Retrieving a row object's Schema
+
+It is possible to get a Schema object from a row object like so:
+
+  my $schema = $cd->result_source->schema;
+  # use the schema as normal:
+  my $artist_rs = $schema->resultset('Artist'); 
+
+This can be useful when you don't want to pass around a Schema object to every
+method.
+
+=head2 Getting the value of the primary key for the last database insert
+
+AKA getting last_insert_id
+
+If you are using PK::Auto (which is a core component as of 0.07), this is 
+straightforward:
+
+  my $foo = $rs->create(\%blah);
+  # do more stuff
+  my $id = $foo->id; # foo->my_primary_key_field will also work.
+
+If you are not using autoincrementing primary keys, this will probably
+not work, but then you already know the value of the last primary key anyway.
+
+=head2 Stringification
+
+Employ the standard stringification technique by using the C<overload>
+module.
+
+To make an object stringify itself as a single column, use something
+like this (replace C<foo> with the column/method of your choice):
+
+  use overload '""' => sub { shift->name}, fallback => 1;
+
+For more complex stringification, you can use an anonymous subroutine:
+
+  use overload '""' => sub { $_[0]->name . ", " .
+                             $_[0]->address }, fallback => 1;
+
+=head3 Stringification Example
+
+Suppose we have two tables: C<Product> and C<Category>. The table
+specifications are:
+
+  Product(id, Description, category)
+  Category(id, Description)
+
+C<category> is a foreign key into the Category table.
+
+If you have a Product object C<$obj> and write something like
+
+  print $obj->category
+
+things will not work as expected.
+
+To obtain, for example, the category description, you should add this
+method to the class defining the Category table:
+
+  use overload "" => sub {
+      my $self = shift;
+
+      return $self->Description;
+  }, fallback => 1;
+
+=head2 Want to know if find_or_create found or created a row?
+
+Just use C<find_or_new> instead, then check C<in_storage>:
+
+  my $obj = $rs->find_or_new({ blah => 'blarg' });
+  unless ($obj->in_storage) {
+    $obj->insert;
+    # do whatever else you wanted if it was a new row
+  }
+
+=head2 Dynamic Sub-classing DBIx::Class proxy classes 
+
+AKA multi-class object inflation from one table
+L<DBIx::Class> classes are proxy classes, therefore some different
+techniques need to be employed for more than basic subclassing.  In
+this example we have a single user table that carries a boolean bit
+for admin.  We would like like to give the admin users
+objects(L<DBIx::Class::Row>) the same methods as a regular user but
+also special admin only methods.  It doesn't make sense to create two
+seperate proxy-class files for this.  We would be copying all the user
+methods into the Admin class.  There is a cleaner way to accomplish
+this.
+
+Overriding the C<inflate_result> method within the User proxy-class
+gives us the effect we want.  This method is called by
+L<DBIx::Class::ResultSet> when inflating a result from storage.  So we
+grab the object being returned, inspect the values we are looking for,
+bless it if it's an admin object, and then return it.  See the example
+below:
+B<Schema Definition> 
+    package DB::Schema; 
+     
+    use base qw/DBIx::Class::Schema/; 
+    __PACKAGE__->load_classes(qw/User/); 
+B<Proxy-Class definitions> 
+    package DB::Schema::User; 
+     
+    use strict; 
+    use warnings; 
+    use base qw/DBIx::Class/; 
+     
+    ### Defined what our admin class is for ensure_class_loaded 
+    my $admin_class = __PACKAGE__ . '::Admin'; 
+     
+    __PACKAGE__->load_components(qw/Core/); 
+     
+    __PACKAGE__->table('users'); 
+     
+    __PACKAGE__->add_columns(qw/user_id   email    password  
+                                firstname lastname active 
+                                admin/); 
+     
+    __PACKAGE__->set_primary_key('user_id'); 
+     
+    sub inflate_result { 
+        my $self = shift;  
+        my $ret = $self->next::method(@_); 
+        if( $ret->admin ) {### If this is an admin rebless for extra functions  
+            $self->ensure_class_loaded( $admin_class ); 
+            bless $ret, $admin_class; 
+        } 
+        return $ret; 
+    } 
+     
+    sub hello { 
+        print "I am a regular user.\n"; 
+        return ; 
+    } 
+     
+     
+    package DB::Schema::User::Admin; 
+     
+    use strict; 
+    use warnings; 
+    use base qw/DB::Schema::User/; 
+     
+    sub hello 
+    { 
+        print "I am an admin.\n"; 
+        return; 
+    } 
+     
+    sub do_admin_stuff 
+    { 
+        print "I am doing admin stuff\n"; 
+        return ; 
+    } 
+B<Test File> test.pl 
+    use warnings; 
+    use strict; 
+    use DB::Schema; 
+     
+    my $user_data = { email    => 'someguy@place.com',  
+                      password => 'pass1',  
+                      admin    => 0 }; 
+                           
+    my $admin_data = { email    => 'someadmin@adminplace.com',  
+                       password => 'pass2',  
+                       admin    => 1 }; 
+                           
+    my $schema = DB::Schema->connection('dbi:Pg:dbname=test'); 
+     
+    $schema->resultset('User')->create( $user_data ); 
+    $schema->resultset('User')->create( $admin_data ); 
+     
+    ### Now we search for them 
+    my $user = $schema->resultset('User')->single( $user_data ); 
+    my $admin = $schema->resultset('User')->single( $admin_data ); 
+     
+    print ref $user, "\n"; 
+    print ref $admin, "\n"; 
+     
+    print $user->password , "\n"; # pass1 
+    print $admin->password , "\n";# pass2; inherited from User 
+    print $user->hello , "\n";# I am a regular user. 
+    print $admin->hello, "\n";# I am an admin. 
+    ### The statement below will NOT print 
+    print "I can do admin stuff\n" if $user->can('do_admin_stuff'); 
+    ### The statement below will print 
+    print "I can do admin stuff\n" if $admin->can('do_admin_stuff'); 
+
+=head2 Skip object creation for faster results
+
+DBIx::Class is not built for speed, it's built for convenience and
+ease of use, but sometimes you just need to get the data, and skip the
+fancy objects.
+  
+To do this simply use L<DBIx::Class::ResultClass::HashRefInflator>.
+  
+ my $rs = $schema->resultset('CD');
+ $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
+ my $hash_ref = $rs->find(1);
+  
+Wasn't that easy?
+  
+=head2 Get raw data for blindingly fast results
+
+If the L<HashRefInflator|DBIx::Class::ResultClass::HashRefInflator> solution
+above is not fast enough for you, you can use a DBIx::Class to return values
+exactly as they come out of the data base with none of the convenience methods
+wrapped round them.
+
+This is used like so:-
+
+  my $cursor = $rs->cursor
+  while (my @vals = $cursor->next) {
+      # use $val[0..n] here
+  }
+
+You will need to map the array offsets to particular columns (you can
+use the I<select> attribute of C<search()> to force ordering).
+
+=head1 RESULTSET OPERATIONS
+
+=head2 Getting Schema from a ResultSet
+
+To get the schema object from a result set, do the following:
+
+ $rs->result_source->schema
+
+=head2 Getting Columns Of Data
+
+AKA Aggregating Data
 
 If you want to find the sum of a particular column there are several
 ways, the obvious one is to use search:
@@ -491,25 +763,25 @@ This will cause the following SQL statement to be run:
 Which will of course only work if your database supports this function.
 See L<DBIx::Class::ResultSetColumn> for more documentation.
 
-=head2 Using relationships
+=head1 USING RELATIONSHIPS
 
-=head3 Create a new row in a related table
+=head2 Create a new row in a related table
 
   my $book->create_related('author', { name => 'Fred'});
 
-=head3 Search in a related table
+=head2 Search in a related table
 
 Only searches for books named 'Titanic' by the author in $author.
 
   my $author->search_related('books', { name => 'Titanic' });
 
-=head3 Delete data in a related table
+=head2 Delete data in a related table
 
 Deletes only the book named Titanic by the author in $author.
 
   my $author->delete_related('books', { name => 'Titanic' });
 
-=head3 Ordering a relationship result set
+=head2 Ordering a relationship result set
 
 If you always want a relation to be ordered, you can specify this when you 
 create the relationship.
@@ -518,13 +790,45 @@ To order C<< $book->pages >> by descending page_number.
 
   Book->has_many('pages' => 'Page', 'book', { order_by => \'page_number DESC'} );
 
+=head2 Many-to-many relationships
 
+This is straightforward using L<ManyToMany|DBIx::Class::Relationship/many_to_many>:
 
-=head2 Transactions
+  package My::DB;
+  # ... set up connection ...
 
-As of version 0.04001, there is improved transaction support in
-L<DBIx::Class::Storage> and L<DBIx::Class::Schema>.  Here is an
-example of the recommended way to use it:
+  package My::User;
+  use base 'My::DB';
+  __PACKAGE__->table('user');
+  __PACKAGE__->add_columns(qw/id name/);
+  __PACKAGE__->set_primary_key('id');
+  __PACKAGE__->has_many('user_address' => 'My::UserAddress', 'user');
+  __PACKAGE__->many_to_many('addresses' => 'user_address', 'address');
+
+  package My::UserAddress;
+  use base 'My::DB';
+  __PACKAGE__->table('user_address');
+  __PACKAGE__->add_columns(qw/user address/);
+  __PACKAGE__->set_primary_key(qw/user address/);
+  __PACKAGE__->belongs_to('user' => 'My::User');
+  __PACKAGE__->belongs_to('address' => 'My::Address');
+
+  package My::Address;
+  use base 'My::DB';
+  __PACKAGE__->table('address');
+  __PACKAGE__->add_columns(qw/id street town area_code country/);
+  __PACKAGE__->set_primary_key('id');
+  __PACKAGE__->has_many('user_address' => 'My::UserAddress', 'address');
+  __PACKAGE__->many_to_many('users' => 'user_address', 'user');
+
+  $rs = $user->addresses(); # get all addresses for a user
+  $rs = $address->users(); # get all users for an address
+
+=head1 TRANSACTIONS
+
+As of version 0.04001, there is improved transaction support in
+L<DBIx::Class::Storage> and L<DBIx::Class::Schema>.  Here is an
+example of the recommended way to use it:
 
   my $genus = $schema->resultset('Genus')->find(12);
 
@@ -560,118 +864,22 @@ transaction to fail. Support for savepoints and for true nested
 transactions (for databases that support them) will hopefully be added
 in the future.
 
-=head2 Many-to-many relationships
-
-This is straightforward using L<ManyToMany|DBIx::Class::Relationship/many_to_many>:
-
-  package My::DB;
-  # ... set up connection ...
-
-  package My::User;
-  use base 'My::DB';
-  __PACKAGE__->table('user');
-  __PACKAGE__->add_columns(qw/id name/);
-  __PACKAGE__->set_primary_key('id');
-  __PACKAGE__->has_many('user_address' => 'My::UserAddress', 'user');
-  __PACKAGE__->many_to_many('addresses' => 'user_address', 'address');
-
-  package My::UserAddress;
-  use base 'My::DB';
-  __PACKAGE__->table('user_address');
-  __PACKAGE__->add_columns(qw/user address/);
-  __PACKAGE__->set_primary_key(qw/user address/);
-  __PACKAGE__->belongs_to('user' => 'My::User');
-  __PACKAGE__->belongs_to('address' => 'My::Address');
-
-  package My::Address;
-  use base 'My::DB';
-  __PACKAGE__->table('address');
-  __PACKAGE__->add_columns(qw/id street town area_code country/);
-  __PACKAGE__->set_primary_key('id');
-  __PACKAGE__->has_many('user_address' => 'My::UserAddress', 'address');
-  __PACKAGE__->many_to_many('users' => 'user_address', 'user');
-
-  $rs = $user->addresses(); # get all addresses for a user
-  $rs = $address->users(); # get all users for an address
-
-=head2 Setting default values for a row
-
-It's as simple as overriding the C<new> method.  Note the use of
-C<next::method>.
-
-  sub new {
-    my ( $class, $attrs ) = @_;
-
-    $attrs->{foo} = 'bar' unless defined $attrs->{foo};
-
-    my $new = $class->next::method($attrs);
-
-    return $new;
-  }
-
-For more information about C<next::method>, look in the L<Class::C3> 
-documentation. See also L<DBIx::Class::Manual::Component> for more
-ways to write your own base classes to do this.
-
-People looking for ways to do "triggers" with DBIx::Class are probably
-just looking for this. 
+=head1 SQL 
 
-=head2 Stringification
-
-Employ the standard stringification technique by using the C<overload>
-module.
-
-To make an object stringify itself as a single column, use something
-like this (replace C<foo> with the column/method of your choice):
-
-  use overload '""' => sub { shift->name}, fallback => 1;
-
-For more complex stringification, you can use an anonymous subroutine:
+=head2 Creating Schemas From An Existing Database
 
-  use overload '""' => sub { $_[0]->name . ", " .
-                             $_[0]->address }, fallback => 1;
+L<DBIx::Class::Schema::Loader> will connect to a database and create a 
+L<DBIx::Class::Schema> and associated sources by examining the database.
 
-=head3 Stringification Example
+The recommend way of achieving this is to use the 
+L<make_schema_at|DBIx::Class::Schema::Loader/make_schema_at> method:
 
-Suppose we have two tables: C<Product> and C<Category>. The table
-specifications are:
-
-  Product(id, Description, category)
-  Category(id, Description)
-
-C<category> is a foreign key into the Category table.
-
-If you have a Product object C<$obj> and write something like
-
-  print $obj->category
-
-things will not work as expected.
-
-To obtain, for example, the category description, you should add this
-method to the class defining the Category table:
-
-  use overload "" => sub {
-      my $self = shift;
-
-      return $self->Description;
-  }, fallback => 1;
-
-=head2 Disconnecting cleanly
-
-If you find yourself quitting an app with Control-C a lot during
-development, you might like to put the following signal handler in
-your main database class to make sure it disconnects cleanly:
-
-  $SIG{INT} = sub {
-    __PACKAGE__->storage->disconnect;
-  };
-
-=head2 Schema import/export
+  perl -MDBIx::Class::Schema::Loader=make_schema_at,dump_to_dir:./lib -e 'make_schema_at("My::Schema", { debug => 1 }, [ "dbi:Pg:dbname=foo","postgres" ])'
 
-To create a DBIx::Class schema from an existing database, use
-L<DBIx::Class::Schema::Loader>'s C<make_schema_at>:
+This will create a tree of files rooted at C<./lib/My/Schema/> containing
+source definitions for all the tables found in the C<foo> database.
 
-  perl -MDBIx::Class::Schema::Loader=make_schema_at,dump_to_dir:./lib -e 'make_schema_at("My::Schema", { debug => 1 }, [ "dbi:Pg:dbname=foo","postgres" ])'
+=head2 Creating DDL SQL
 
 The following functionality requires you to have L<SQL::Translator>
 (also known as "SQL Fairy") installed.
@@ -681,7 +889,7 @@ To create a set of database-specific .sql files for the above schema:
  my $schema = My::Schema->connect($dsn);
  $schema->create_ddl_dir(['MySQL', 'SQLite', 'PostgreSQL'],
                         '0.1',
-                        '/dbscriptdir/'
+                        './dbscriptdir/'
                         );
 
 By default this will create schema files in the current directory, for
@@ -698,7 +906,7 @@ To import created .sql files using the mysql client:
 
 To create C<ALTER TABLE> conversion scripts to update a database to a
 newer version of your schema at a later point, first set a new
-$VERSION in your Schema file, then:
+C<$VERSION> in your Schema file, then:
 
  my $schema = My::Schema->connect($dsn);
  $schema->create_ddl_dir(['MySQL', 'SQLite', 'PostgreSQL'],
@@ -712,44 +920,47 @@ of the schema, plus scripts to convert from version 0.1 to 0.2. This
 requires that the files for 0.1 as created above are available in the
 given directory to diff against.
 
+=head2 Adding Indexes And Functions To Your SQL
 
-=head2 Easy migration from class-based to schema-based setup
+Often you will want indexes on columns on your table to speed up searching. To
+do this, create a method called C<sqlt_deploy_hook> in the relevant source 
+class:
 
-You want to start using the schema-based approach to L<DBIx::Class>
-(see L<SchemaIntro.pod>), but have an established class-based setup with lots
-of existing classes that you don't want to move by hand. Try this nifty script
-instead:
+ package My::Schema::Artist;
 
-  use MyDB;
-  use SQL::Translator;
-  
-  my $schema = MyDB->schema_instance;
-  
-  my $translator           =  SQL::Translator->new( 
-      debug                => $debug          ||  0,
-      trace                => $trace          ||  0,
-      no_comments          => $no_comments    ||  0,
-      show_warnings        => $show_warnings  ||  0,
-      add_drop_table       => $add_drop_table ||  0,
-      validate             => $validate       ||  0,
-      parser_args          => {
-         'DBIx::Schema'    => $schema,
-                              },
-      producer_args   => {
-          'prefix'         => 'My::Schema',
-                         },
-  );
-  
-  $translator->parser('SQL::Translator::Parser::DBIx::Class');
-  $translator->producer('SQL::Translator::Producer::DBIx::Class::File');
-  
-  my $output = $translator->translate(@args) or die
-          "Error: " . $translator->error;
-  
-  print $output;
+ __PACKAGE__->table('artist');
+ __PACKAGE__->add_columns(id => { ... }, name => { ... })
 
-You could use L<Module::Find> to search for all subclasses in the MyDB::*
-namespace, which is currently left as an exercise for the reader.
+ sub sqlt_deploy_hook {
+   my ($self, $sqlt_table) = @_;
+
+   $sqlt_table->add_index(name => 'idx_name', fields => ['name']);
+ }
+
+ 1;
+
+Sometimes you might want to change the index depending on the type of the 
+database for which SQL is being generated:
+
+  my ($db_type = $sqlt_table->schema->translator->producer_type)
+    =~ s/^SQL::Translator::Producer:://;
+
+You can also add hooks to the schema level to stop certain tables being 
+created:
+
+ package My::Schema;
+
+ ...
+
+ sub sqlt_deploy_hook {
+   my ($self, $sqlt_schema) = @_;
+
+   $sqlt_schema->drop_table('table_name');
+ }
+
+You could also add views or procedures to the output using 
+L<SQL::Translator::Schema/add_view> or 
+L<SQL::Translator::Schema/add_procedure>.
 
 =head2 Schema versioning
 
@@ -780,17 +991,16 @@ Deploy update to customers
 
 =back
 
-=head3 Create a DBIx::Class schema
+B<Create a DBIx::Class schema>
 
 This can either be done manually, or generated from an existing database as
-described under C<Schema import/export>.
+described under L</Creating Schemas From An Existing Database>
 
-=head3 Save the schema
+B<Save the schema>
 
-Call L<DBIx::Class::Schema/create_ddl_dir> as above under L<Schema
-import/export>.
+Call L<DBIx::Class::Schema/create_ddl_dir> as above under L</Creating DDL SQL>.
 
-=head3 Deploy to customers
+B<Deploy to customers>
 
 There are several ways you could deploy your schema. These are probably
 beyond the scope of this recipe, but might include:
@@ -808,14 +1018,14 @@ all part of your install.
 
 =back
 
-=head3 Modify the schema to change functionality
+B<Modify the schema to change functionality>
 
 As your application evolves, it may be necessary to modify your schema
 to change functionality. Once the changes are made to your schema in
 DBIx::Class, export the modified schema and the conversion scripts as
-in L<Schema import/export>.
+in L</Creating DDL SQL>.
 
-=head3 Deploy update to customers
+B<Deploy update to customers>
 
 Add the L<DBIx::Class::Schema::Versioned> schema component to your
 Schema class. This will add a new table to your database called
@@ -826,6 +1036,36 @@ database thinks it has.
 Alternatively, you can send the conversion sql scripts to your
 customers as above.
 
+=head2 Setting quoting for the generated SQL. 
+
+If the database contains column names with spaces and/or reserved words, they
+need to be quoted in the SQL queries. This is done using:
+
+ __PACKAGE__->storage->sql_maker->quote_char([ qw/[ ]/] );
+ __PACKAGE__->storage->sql_maker->name_sep('.');
+
+The first sets the quote characters. Either a pair of matching
+brackets, or a C<"> or C<'>:
+  
+ __PACKAGE__->storage->sql_maker->quote_char('"');
+
+Check the documentation of your database for the correct quote
+characters to use. C<name_sep> needs to be set to allow the SQL
+generator to put the quotes the correct place.
+
+In most cases you should set these as part of the arguments passed to 
+L<DBIx::Class::Schema/conect>:
+
+ my $schema = My::Schema->connect(
+  'dbi:mysql:my_db',
+  'db_user',
+  'db_password',
+  {
+    quote_char => '"',
+    name_sep   => '.'
+  }
+ )
+
 =head2 Setting limit dialect for SQL::Abstract::Limit
 
 In some cases, SQL::Abstract::Limit cannot determine the dialect of
@@ -841,24 +1081,50 @@ to Microsoft SQL-server (See more names in SQL::Abstract::Limit
 The JDBC bridge is one way of getting access to a MSSQL server from a platform
 that Microsoft doesn't deliver native client libraries for. (e.g. Linux)
 
-=head2 Setting quoting for the generated SQL. 
+The limit dialect can also be set at connect time by specifying a 
+C<limit_dialect> key in the final hash as shown above.
 
-If the database contains column names with spaces and/or reserved words, they
-need to be quoted in the SQL queries. This is done using:
+=head1 BOOTSTRAPPING/MIGRATING 
 
-  __PACKAGE__->storage->sql_maker->quote_char([ qw/[ ]/] );
-  __PACKAGE__->storage->sql_maker->name_sep('.');
+=head2 Easy migration from class-based to schema-based setup
 
-The first sets the quote characters. Either a pair of matching
-brackets, or a C<"> or C<'>:
+You want to start using the schema-based approach to L<DBIx::Class>
+(see L<SchemaIntro.pod>), but have an established class-based setup with lots
+of existing classes that you don't want to move by hand. Try this nifty script
+instead:
+
+  use MyDB;
+  use SQL::Translator;
+  
+  my $schema = MyDB->schema_instance;
   
-  __PACKAGE__->storage->sql_maker->quote_char('"');
+  my $translator           =  SQL::Translator->new( 
+      debug                => $debug          ||  0,
+      trace                => $trace          ||  0,
+      no_comments          => $no_comments    ||  0,
+      show_warnings        => $show_warnings  ||  0,
+      add_drop_table       => $add_drop_table ||  0,
+      validate             => $validate       ||  0,
+      parser_args          => {
+         'DBIx::Schema'    => $schema,
+                              },
+      producer_args   => {
+          'prefix'         => 'My::Schema',
+                         },
+  );
+  
+  $translator->parser('SQL::Translator::Parser::DBIx::Class');
+  $translator->producer('SQL::Translator::Producer::DBIx::Class::File');
+  
+  my $output = $translator->translate(@args) or die
+          "Error: " . $translator->error;
+  
+  print $output;
 
-Check the documentation of your database for the correct quote
-characters to use. C<name_sep> needs to be set to allow the SQL
-generator to put the quotes the correct place.
+You could use L<Module::Find> to search for all subclasses in the MyDB::*
+namespace, which is currently left as an exercise for the reader.
 
-=head2 Overloading methods
+=head1 OVERLOADING METHODS
 
 L<DBIx::Class> uses the L<Class::C3> package, which provides for redispatch of
 method calls, useful for things like default values and triggers. You have to
@@ -866,7 +1132,29 @@ use calls to C<next::method> to overload methods. More information on using
 L<Class::C3> with L<DBIx::Class> can be found in
 L<DBIx::Class::Manual::Component>.
 
-=head3 Changing one field whenever another changes
+=head2 Setting default values for a row
+
+It's as simple as overriding the C<new> method.  Note the use of
+C<next::method>.
+
+  sub new {
+    my ( $class, $attrs ) = @_;
+
+    $attrs->{foo} = 'bar' unless defined $attrs->{foo};
+
+    my $new = $class->next::method($attrs);
+
+    return $new;
+  }
+
+For more information about C<next::method>, look in the L<Class::C3> 
+documentation. See also L<DBIx::Class::Manual::Component> for more
+ways to write your own base classes to do this.
+
+People looking for ways to do "triggers" with DBIx::Class are probably
+just looking for this. 
+
+=head2 Changing one field whenever another changes
 
 For example, say that you have three columns, C<id>, C<number>, and 
 C<squared>.  You would like to make changes to C<number> and have
@@ -884,7 +1172,7 @@ You can accomplish this by overriding C<store_column>:
 Note that the hard work is done by the call to C<next::method>, which
 redispatches your call to store_column in the superclass(es).
 
-=head3 Automatically creating related objects
+=head2 Automatically creating related objects
 
 You might have a class C<Artist> which has many C<CD>s.  Further, if you
 want to create a C<CD> object every time you insert an C<Artist> object.
@@ -900,7 +1188,50 @@ You can accomplish this by overriding C<insert> on your objects:
 where C<fill_from_artist> is a method you specify in C<CD> which sets
 values in C<CD> based on the data in the C<Artist> object you pass in.
 
-=head2 Debugging DBIx::Class objects with Data::Dumper
+=head2 Wrapping/overloading a column accessor
+
+B<Problem:>
+
+Say you have a table "Camera" and want to associate a description
+with each camera. For most cameras, you'll be able to generate the description from
+the other columns. However, in a few special cases you may want to associate a
+custom description with a camera.
+
+B<Solution:>
+
+In your database schema, define a description field in the "Camera" table that
+can contain text and null values.
+
+In DBIC, we'll overload the column accessor to provide a sane default if no
+custom description is defined. The accessor will either return or generate the
+description, depending on whether the field is null or not.
+
+First, in your "Camera" schema class, define the description field as follows:
+
+  __PACKAGE__->add_columns(description => { accessor => '_description' });
+
+Next, we'll define the accessor-wrapper subroutine:
+
+  sub description {
+      my $self = shift;
+
+      # If there is an update to the column, we'll let the original accessor
+      # deal with it.
+      return $self->_description(@_) if @_;
+
+      # Fetch the column value.
+      my $description = $self->_description;
+
+      # If there's something in the description field, then just return that.
+      return $description if defined $description && length $descripton;
+
+      # Otherwise, generate a description.
+      return $self->generate_description;
+  }
+
+=head1 DEBUGGING AND PROFILING
+
+=head2 DBIx::Class objects with Data::Dumper
 
 L<Data::Dumper> can be a very useful tool for debugging, but sometimes it can
 be hard to find the pertinent data in all the data it can generate.
@@ -944,17 +1275,6 @@ base class and set C<$Data::Dumper::Freezer> to its name and L<Data::Dumper>
 will automagically clean up your data before printing it. See
 L<Data::Dumper/EXAMPLES> for more information.
 
-=head2 Retrieving a row object's Schema
-
-It is possible to get a Schema object from a row object like so:
-
-  my $schema = $cd->result_source->schema;
-  # use the schema as normal:
-  my $artist_rs = $schema->resultset('Artist'); 
-
-This can be useful when you don't want to pass around a Schema object to every
-method.
-
 =head2 Profiling
 
 When you enable L<DBIx::Class::Storage>'s debugging it prints the SQL
@@ -1017,218 +1337,5 @@ You could then create average, high and low execution times for an SQL
 statement and dig down to see if certain parameters cause aberrant behavior.
 You might want to check out L<DBIx::Class::QueryLog> as well.
 
-=head2 Getting the value of the primary key for the last database insert
-
-AKA getting last_insert_id
-
-If you are using PK::Auto, this is straightforward:
-
-  my $foo = $rs->create(\%blah);
-  # do more stuff
-  my $id = $foo->id; # foo->my_primary_key_field will also work.
-
-If you are not using autoincrementing primary keys, this will probably
-not work, but then you already know the value of the last primary key anyway.
-
-=head2 Dynamic Sub-classing DBIx::Class proxy classes 
-(AKA multi-class object inflation from one table) 
-L<DBIx::Class> classes are proxy classes, therefore some different
-techniques need to be employed for more than basic subclassing.  In
-this example we have a single user table that carries a boolean bit
-for admin.  We would like like to give the admin users
-objects(L<DBIx::Class::Row>) the same methods as a regular user but
-also special admin only methods.  It doesn't make sense to create two
-seperate proxy-class files for this.  We would be copying all the user
-methods into the Admin class.  There is a cleaner way to accomplish
-this.
-
-Overriding the C<inflate_result> method within the User proxy-class
-gives us the effect we want.  This method is called by
-L<DBIx::Class::ResultSet> when inflating a result from storage.  So we
-grab the object being returned, inspect the values we are looking for,
-bless it if it's an admin object, and then return it.  See the example
-below:
-B<Schema Definition> 
-    package DB::Schema; 
-     
-    use base qw/DBIx::Class::Schema/; 
-    __PACKAGE__->load_classes(qw/User/); 
-B<Proxy-Class definitions> 
-    package DB::Schema::User; 
-     
-    use strict; 
-    use warnings; 
-    use base qw/DBIx::Class/; 
-     
-    ### Defined what our admin class is for ensure_class_loaded 
-    my $admin_class = __PACKAGE__ . '::Admin'; 
-     
-    __PACKAGE__->load_components(qw/Core/); 
-     
-    __PACKAGE__->table('users'); 
-     
-    __PACKAGE__->add_columns(qw/user_id   email    password  
-                                firstname lastname active 
-                                admin/); 
-     
-    __PACKAGE__->set_primary_key('user_id'); 
-     
-    sub inflate_result { 
-        my $self = shift;  
-        my $ret = $self->next::method(@_); 
-        if( $ret->admin ) {### If this is an admin rebless for extra functions  
-            $self->ensure_class_loaded( $admin_class ); 
-            bless $ret, $admin_class; 
-        } 
-        return $ret; 
-    } 
-     
-    sub hello { 
-        print "I am a regular user.\n"; 
-        return ; 
-    } 
-     
-     
-    package DB::Schema::User::Admin; 
-     
-    use strict; 
-    use warnings; 
-    use base qw/DB::Schema::User/; 
-     
-    sub hello 
-    { 
-        print "I am an admin.\n"; 
-        return; 
-    } 
-     
-    sub do_admin_stuff 
-    { 
-        print "I am doing admin stuff\n"; 
-        return ; 
-    } 
-B<Test File> test.pl 
-    use warnings; 
-    use strict; 
-    use DB::Schema; 
-     
-    my $user_data = { email    => 'someguy@place.com',  
-                      password => 'pass1',  
-                      admin    => 0 }; 
-                           
-    my $admin_data = { email    => 'someadmin@adminplace.com',  
-                       password => 'pass2',  
-                       admin    => 1 }; 
-                           
-    my $schema = DB::Schema->connection('dbi:Pg:dbname=test'); 
-     
-    $schema->resultset('User')->create( $user_data ); 
-    $schema->resultset('User')->create( $admin_data ); 
-     
-    ### Now we search for them 
-    my $user = $schema->resultset('User')->single( $user_data ); 
-    my $admin = $schema->resultset('User')->single( $admin_data ); 
-     
-    print ref $user, "\n"; 
-    print ref $admin, "\n"; 
-     
-    print $user->password , "\n"; # pass1 
-    print $admin->password , "\n";# pass2; inherited from User 
-    print $user->hello , "\n";# I am a regular user. 
-    print $admin->hello, "\n";# I am an admin. 
-    ### The statement below will NOT print 
-    print "I can do admin stuff\n" if $user->can('do_admin_stuff'); 
-    ### The statement below will print 
-    print "I can do admin stuff\n" if $admin->can('do_admin_stuff'); 
-
-=head2 Skip object creation for faster results
-
-DBIx::Class is not built for speed, it's built for convenience and
-ease of use, but sometimes you just need to get the data, and skip the
-fancy objects.
-  
-To do this simply use L<DBIx::Class::ResultClass::HashRefInflator>.
-  
- my $rs = $schema->resultset('CD');
- $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
- my $hash_ref = $rs->find(1);
-  
-Wasn't that easy?
-  
-=head2 Get raw data for blindingly fast results
-
-If the C<inflate_result> solution above is not fast enough for you, you
-can use a DBIx::Class to return values exactly as they come out of the
-data base with none of the convenience methods wrapped round them.
-
-This is used like so:-
-
-  my $cursor = $rs->cursor
-  while (my @vals = $cursor->next) {
-      # use $val[0..n] here
-  }
-
-You will need to map the array offsets to particular columns (you can
-use the I<select> attribute of C<search()> to force ordering).
-
-=head2 Want to know if find_or_create found or created a row?
-
-Just use C<find_or_new> instead, then check C<in_storage>:
-
-  my $obj = $rs->find_or_new({ blah => 'blarg' });
-  unless ($obj->in_storage) {
-    $obj->insert;
-    # do whatever else you wanted if it was a new row
-  }
-
-=head3 Wrapping/overloading a column accessor
-
-Problem: Say you have a table "Camera" and want to associate a description
-with each camera. For most cameras, you'll be able to generate the description from
-the other columns. However, in a few special cases you may want to associate a
-custom description with a camera.
-
-Solution:
-
-In your database schema, define a description field in the "Camera" table that
-can contain text and null values.
-
-In DBIC, we'll overload the column accessor to provide a sane default if no
-custom description is defined. The accessor will either return or generate the
-description, depending on whether the field is null or not.
-
-First, in your "Camera" schema class, define the description field as follows:
-
-  __PACKAGE__->add_columns(description => { accessor => '_description' });
-
-Next, we'll define the accessor-wrapper subroutine:
-
-  sub description {
-      my $self = shift;
-
-      # If there is an update to the column, we'll let the original accessor
-      # deal with it.
-      return $self->_description(@_) if @_;
-
-      # Fetch the column value.
-      my $description = $self->_description;
-
-      # If there's something in the description field, then just return that.
-      return $description if defined $description && length $descripton;
-
-      # Otherwise, generate a description.
-      return $self->generate_description;
-  }
 
 =cut
index d372115..434a1b1 100644 (file)
@@ -232,6 +232,25 @@ and not:
  my $interval = "now() - interval '12 hours'";
  ->search({last_attempt => { '<' => \$interval } })
 
+=item .. search with an SQL function on the left hand side?
+
+To use an SQL function on the left hand side of a comparison:
+
+ ->search({}, { where => \'YEAR(date_of_birth)=1979' });
+
+=begin hidden
+
+(When the bind arg ordering bug is fixed, the previous example can be
+replaced with the following.)
+
+ ->search({}, { where => \'YEAR(date_of_birth)=?', bind => [ 1979 ] });
+
+=end hidden
+
+Or, if you have quoting off:
+
+ ->search({ 'YEAR(date_of_birth' => 1979 });
+
 =item .. find more help on constructing searches?
 
 Behind the scenes, DBIx::Class uses L<SQL::Abstract> to help construct
index d4ee303..974efe5 100644 (file)
@@ -373,6 +373,16 @@ L<DBIx::Class::ResultSet/METHODS>.
 For a complete overview of the available attributes, see
 L<DBIx::Class::ResultSet/ATTRIBUTES>.
 
+=head1 NOTES
+
+=head2 Problems on RHEL5/CentOS5
+
+There is a problem with slow performance of certain DBIx::Class operations in
+perl-5.8.8-10 and later on RedHat and related systems, due to a bad backport of
+a "use overload" related bug.  The problem is in the Perl binary itself, not in
+DBIx::Class.  If your system has this problem, you will see a warning on
+startup, with some options as to what to do about it.
+
 =head1 SEE ALSO
 
 =over 4
index 1e6b93b..451e435 100644 (file)
@@ -24,6 +24,13 @@ sub many_to_many {
     my $set_meth = "set_${meth}";
     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($_);
+    }
+
     $rel_attrs->{alias} ||= $f_rel;
 
     *{"${class}::${meth}_rs"} = sub {
index 713bf14..05fbc41 100644 (file)
@@ -95,6 +95,8 @@ sub new {
 
   $attrs->{alias} ||= 'me';
 
+  # Creation of {} and bless separated to mitigate RH perl bug
+  # see https://bugzilla.redhat.com/show_bug.cgi?id=196836
   my $self = {
     _source_handle => $source,
     result_class => $attrs->{result_class} || $source->resolve->result_class,
@@ -138,6 +140,8 @@ L</ATTRIBUTES>. For more examples of using this function, see
 L<Searching|DBIx::Class::Manual::Cookbook/Searching>. For a complete
 documentation for the first argument, see L<SQL::Abstract>.
 
+For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
+
 =cut
 
 sub search {
@@ -264,6 +268,13 @@ sub search_rs {
 Pass a literal chunk of SQL to be added to the conditional part of the
 resultset query.
 
+CAVEAT: C<search_literal> is provided for Class::DBI compatibility and should
+only be used in that context. There are known problems using C<search_literal>
+in chained queries; it can result in bind values in the wrong order.  See
+L<DBIx::Class::Manual::Cookbook/Searching> and
+L<DBIx::Class::Manual::FAQ/Searching> for searching techniques that do not
+require C<search_literal>.
+
 =cut
 
 sub search_literal {
@@ -1449,9 +1460,12 @@ sub new_result {
 
   my $alias = $self->{attrs}{alias};
   my $collapsed_cond = $self->{cond} ? $self->_collapse_cond($self->{cond}) : {};
+
+  # precendence must be given to passed values over values inherited from the cond, 
+  # so the order here is important.
   my %new = (
-    %{ $self->_remove_alias($values, $alias) },
     %{ $self->_remove_alias($collapsed_cond, $alias) },
+    %{ $self->_remove_alias($values, $alias) },
     -source_handle => $self->_source_handle,
     -result_source => $self->result_source, # DO NOT REMOVE THIS, REQUIRED
   );
@@ -2318,6 +2332,7 @@ to Earth' and a cd with title 'Popular'.
 If you want to fetch related objects from other tables as well, see C<prefetch>
 below.
 
+For more help on using joins with search, see L<DBIx::Class::Manual::Joining>.
 =head2 prefetch
 
 =over 4
index f93cbdd..68cc4e0 100644 (file)
@@ -175,8 +175,13 @@ value. Produces the following SQL:
 
 sub func {
   my ($self,$function) = @_;
-  my ($row) = $self->{_parent_resultset}->search(undef, {select => {$function => $self->{_column}}, as => [$self->{_column}]})->cursor->next;
-  return $row;
+  my $cursor = $self->{_parent_resultset}->search(undef, {select => {$function => $self->{_column}}, as => [$self->{_column}]})->cursor;
+  
+  if( wantarray ) {
+    return map { $_->[ 0 ] } $cursor->all;
+  }
+
+  return ( $cursor->next )[ 0 ];
 }
 
 1;
index d21cdb7..d23c765 100644 (file)
@@ -519,6 +519,14 @@ sub add_relationship {
     unless $cond;
   $attrs ||= {};
 
+  # Check foreign and self are right in cond
+  if ( (ref $cond ||'') eq 'HASH') {
+    for (keys %$cond) {
+      $self->throw_exception("Keys of condition should be of form 'foreign.col', not '$_'")
+        if /\./ && !/^foreign\./;
+    }
+  }
+
   my %rels = %{ $self->_relationships };
   $rels{$rel} = { class => $f_source_name,
                   source => $f_source_name,
@@ -782,7 +790,7 @@ sub resolve_condition {
         $self->throw_exception("Invalid rel cond val ${v}");
       if (ref $for) { # Object
         #warn "$self $k $for $v";
-        $ret{$k} = $for->get_column($v);
+        $ret{$k} = $for->get_column($v) if $for->has_column_loaded($v);
         #warn %ret;
       } elsif (!defined $for) { # undef, i.e. "no object"
         $ret{$k} = undef;
@@ -1049,6 +1057,15 @@ sub throw_exception {
   }
 }
 
+=head2 sqlt_deploy_hook($sqlt_table)
+
+An optional sub which you can declare in your own Schema class that will get 
+passed the L<SQL::Translator::Schema::Table> object when you deploy the schema
+via L</create_ddl_dir> or L</deploy>.
+
+For an example of what you can do with this, see 
+L<DBIx::Class::Manual::Cookbook/Adding Indexes And Functions To Your SQL>.
+
 =head1 AUTHORS
 
 Matt S. Trout <mst@shadowcatsystems.co.uk>
index e6ad203..ae11ce6 100644 (file)
@@ -7,6 +7,8 @@ use Storable;
 use base qw/DBIx::Class/;
 
 use overload
+    # on some RH perls the following line causes serious performance problem
+    # see https://bugzilla.redhat.com/show_bug.cgi?id=196836
     q/""/ => sub { __PACKAGE__ . ":" . shift->source_moniker; },
     fallback => 1;
 
index 41c804e..6ac92bf 100644 (file)
@@ -243,7 +243,7 @@ sub insert {
         my $reverse = $source->reverse_relationship_info($relname);
         foreach my $obj (@cands) {
           $obj->set_from_related($_, $self) for keys %$reverse;
-          $obj->insert() if(!$obj->in_storage);
+          $obj->insert() unless ($obj->in_storage || $obj->result_source->resultset->search({$obj->get_columns})->count);
         }
       }
     }
index 6e8b7fc..b668c83 100644 (file)
@@ -484,7 +484,9 @@ DEPRECATED. You probably wanted compose_namespace.
 
 Actually, you probably just wanted to call connect.
 
-=for hidden due to deprecation
+=begin hidden
+
+(hidden due to deprecation)
 
 Calls L<DBIx::Class::Schema/"compose_namespace"> to the target namespace,
 calls L<DBIx::Class::Schema/connection> with @db_info on the new schema,
@@ -498,6 +500,8 @@ L<DBIx::Class::Schema/connect> and use the resulting schema object to operate
 on L<DBIx::Class::ResultSet> objects with L<DBIx::Class::Schema/resultset> for
 more information.
 
+=end hidden
+
 =cut
 
 {
@@ -600,6 +604,7 @@ sub compose_namespace {
   Class::C3->reinitialize();
   {
     no strict 'refs';
+    no warnings 'redefine';
     foreach my $meth (qw/class source resultset/) {
       *{"${target}::${meth}"} =
         sub { shift->schema->$meth(@_) };
@@ -1045,6 +1050,17 @@ sub ddl_filename {
     return $filename;
 }
 
+=head2 sqlt_deploy_hook($sqlt_schema)
+
+An optional sub which you can declare in your own Schema class that will get 
+passed the L<SQL::Translator::Schema> object when you deploy the schema via
+L</create_ddl_dir> or L</deploy>.
+
+For an example of what you can do with this, see 
+L<DBIx::Class::Manual::Cookbook/Adding Indexes And Functions To Your SQL>.
+
+=cut
+
 1;
 
 =head1 AUTHORS
diff --git a/lib/DBIx/Class/StartupCheck.pm b/lib/DBIx/Class/StartupCheck.pm
new file mode 100644 (file)
index 0000000..4710192
--- /dev/null
@@ -0,0 +1,70 @@
+package DBIx::Class::StartupCheck;
+
+BEGIN {
+
+    { package TestRHBug; use overload bool => sub { 0 } }
+
+    sub _has_bug_34925 {
+       my %thing;
+       my $r1 = \%thing;
+       my $r2 = \%thing;
+       bless $r1 => 'TestRHBug';
+       return !!$r2;
+    }
+
+    sub _possibly_has_bad_overload_performance {
+       return $] < 5.008009 && ! _has_bug_34925();
+    }
+
+    unless ($ENV{DBIC_NO_WARN_BAD_PERL}) {
+       if (_possibly_has_bad_overload_performance()) {
+           print STDERR "\n\nWARNING: " . __PACKAGE__ . ": This version of Perl is likely to exhibit\n" .
+               "extremely slow performance for certain critical operations.\n" .
+               "Please consider recompiling Perl.  For more information, see\n" .
+               "https://bugzilla.redhat.com/show_bug.cgi?id=196836 and/or\n" .
+               "http://lists.scsys.co.uk/pipermail/dbix-class/2007-October/005119.html.\n" .
+               "You can suppress this message by setting DBIC_NO_WARN_BAD_PERL=1 in your\n" .
+               "environment.\n\n";
+       }
+    }
+}
+
+=head1 NAME
+
+DBIx::Class::StartupCheck - Run environment checks on startup
+
+=head1 SYNOPSIS
+
+  use DBIx::Class::StartupCheck;
+  
+=head1 DESCRIPTION
+
+Currently this module checks for, and if necessary issues a warning for, a
+particular bug found on RedHat systems from perl-5.8.8-10 and up.  Other checks
+may be added from time to time.
+
+Any checks herein can be disabled by setting an appropriate environment
+variable.  If your system suffers from a particular bug, you will get a warning
+message on startup sent to STDERR, explaining what to do about it and how to
+suppress the message.  If you don't see any messages, you have nothing to worry
+about.
+
+=head1 CONTRIBUTORS
+
+Nigel Metheringham
+
+Brandon Black
+
+Matt S. Trout
+
+=head1 AUTHOR
+
+Jon Schutz
+
+=head1 LICENSE
+
+You may distribute this code under the same terms as Perl itself.
+
+=cut
+
+1;
index a1c551e..cd29601 100644 (file)
@@ -419,6 +419,10 @@ re-connect on your schema.
 
 Old name for DBIC_TRACE
 
+=head1 SEE ALSO
+
+L<DBIx::Class::Storage::DBI> - reference storage inplementation using SQL::Abstract and DBI.
+
 =head1 AUTHORS
 
 Matt S. Trout <mst@shadowcatsystems.co.uk>
index dbddab3..80fce38 100644 (file)
@@ -19,6 +19,9 @@ __PACKAGE__->mk_group_accessors('simple' =>
 
 __PACKAGE__->cursor_class('DBIx::Class::Storage::DBI::Cursor');
 
+__PACKAGE__->mk_group_accessors('inherited' => qw/sql_maker_class/);
+__PACKAGE__->sql_maker_class('DBIC::SQL::Abstract');
+
 BEGIN {
 
 package DBIC::SQL::Abstract; # Would merge upstream, but nate doesn't reply :(
@@ -83,6 +86,15 @@ sub select {
   my ($sql, @ret) = $self->SUPER::select(
     $table, $self->_recurse_fields($fields), $where, $order, @rest
   );
+  $sql .= 
+    $self->{for} ?
+    (
+      $self->{for} eq 'update' ? ' FOR UPDATE' :
+      $self->{for} eq 'shared' ? ' FOR SHARE'  :
+      ''
+    ) :
+    ''
+  ;
   return wantarray ? ($sql, @ret, @{$self->{having_bind}}) : $sql;
 }
 
@@ -706,7 +718,7 @@ sub connected {
 sub _verify_pid {
   my ($self) = @_;
 
-  return if $self->_conn_pid == $$;
+  return if defined $self->_conn_pid && $self->_conn_pid == $$;
 
   $self->_dbh->{InactiveDestroy} = 1;
   $self->_dbh(undef);
@@ -745,7 +757,8 @@ sub _sql_maker_args {
 sub sql_maker {
   my ($self) = @_;
   unless ($self->_sql_maker) {
-    $self->_sql_maker(new DBIC::SQL::Abstract( $self->_sql_maker_args ));
+    my $sql_maker_class = $self->sql_maker_class;
+    $self->_sql_maker($sql_maker_class->new( $self->_sql_maker_args ));
   }
   return $self->_sql_maker;
 }
@@ -1085,9 +1098,15 @@ sub delete {
 sub _select {
   my ($self, $ident, $select, $condition, $attrs) = @_;
   my $order = $attrs->{order_by};
+
   if (ref $condition eq 'SCALAR') {
     $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
   }
+
+  my $for = delete $attrs->{for};
+  my $sql_maker = $self->sql_maker;
+  local $sql_maker->{for} = $for;
+
   if (exists $attrs->{group_by} || $attrs->{having}) {
     $order = {
       group_by => $attrs->{group_by},
@@ -1105,6 +1124,7 @@ sub _select {
       if (defined($attrs->{rows}) && !($attrs->{rows} > 0));
     push @args, $attrs->{rows}, $attrs->{offset};
   }
+
   return $self->_execute(@args);
 }
 
index cd1f7da..f25415a 100644 (file)
@@ -5,6 +5,8 @@ use base qw( DBIx::Class::Storage::DBI::Oracle::Generic );
 use strict;
 use warnings;
 
+__PACKAGE__->sql_maker_class('DBIC::SQL::Abstract::Oracle');
+
 BEGIN {
   package DBIC::SQL::Abstract::Oracle;
 
@@ -91,18 +93,6 @@ BEGIN {
   }
 }
 
-sub sql_maker {
-  my ($self) = @_;
-
-  unless ($self->_sql_maker) {
-    $self->_sql_maker(
-      new DBIC::SQL::Abstract::Oracle( $self->_sql_maker_args )
-    );
-  }
-
-  return $self->_sql_maker;
-}
-
 1;
 
 __END__
index 7f7d66e..4f48015 100644 (file)
@@ -5,6 +5,8 @@ package # hide from PAUSE
 
 # Some mistakes the fault of Matt S Trout
 
+# Others the fault of Ash Berlin
+
 use strict;
 use warnings;
 use vars qw($DEBUG $VERSION @EXPORT_OK);
@@ -65,8 +67,6 @@ sub parse {
 
     foreach my $moniker (@monikers)
     {
-        #eval "use $tableclass";
-        #print("Can't load $tableclass"), next if($@);
         my $source = $dbixschema->source($moniker);
 
         next if $seen_tables{$source->name}++;
@@ -78,7 +78,7 @@ sub parse {
         my $colcount = 0;
         foreach my $col ($source->columns)
         {
-            # assuming column_info in dbix is the same as DBI (?)
+            # assuming column_info in dbic is the same as DBI (?)
             # data_type is a number, column_type is text?
             my %colinfo = (
               name => $col,
@@ -128,7 +128,6 @@ sub parse {
 
             if($rel_table)
             {
-
                 my $reverse_rels = $source->reverse_relationship_info($rel);
                 my ($otherrelname, $otherrelationship) = each %{$reverse_rels};
 
@@ -145,7 +144,6 @@ sub parse {
 
                 #Decide if this is a foreign key based on whether the self
                 #items are our primary columns.
-                $DB::single = 1 if $moniker eq 'Tests::MBTI::Result';
 
                 # If the sets are different, then we assume it's a foreign key from
                 # us to another table.
@@ -179,7 +177,16 @@ sub parse {
                 }
             }
         }
+
+        if ($source->result_class->can('sqlt_deploy_hook')) {
+          $source->result_class->sqlt_deploy_hook($table);
+        }
     }
+
+    if ($dbixschema->can('sqlt_deploy_hook')) {
+      $dbixschema->sqlt_deploy_hook($schema);
+    }
+
     return 1;
 }
 
diff --git a/t/47bind_attribute.t b/t/47bind_attribute.t
new file mode 100644 (file)
index 0000000..afc5b1a
--- /dev/null
@@ -0,0 +1,82 @@
+use strict;
+use warnings;
+
+use Test::More;
+use lib qw(t/lib);
+use DBICTest;
+
+my $schema = DBICTest->init_schema;
+
+BEGIN {
+    eval "use DBD::SQLite";
+    plan $@
+        ? ( skip_all => 'needs DBD::SQLite for testing' )
+        : ( tests => 7 );
+}
+
+### $schema->storage->debug(1);
+
+my $where_bind = {
+    where => \'name like ?',
+    bind  => [ 'Cat%' ],
+};
+
+my $rs;
+
+TODO: {
+    local $TODO = 'bind args order needs fixing (semifor)';
+
+    # First, the simple cases...
+    $rs = $schema->resultset('Artist')->search(
+            { artistid => 1 },
+            $where_bind,
+    );
+
+    is ( $rs->count, 1, 'where/bind combined' );
+
+    $rs= $schema->resultset('Artist')->search({}, $where_bind)
+        ->search({ artistid => 1});
+
+    is ( $rs->count, 1, 'where/bind first' );
+            
+    $rs = $schema->resultset('Artist')->search({ artistid => 1})
+        ->search({}, $where_bind);
+
+    is ( $rs->count, 1, 'where/bind last' );
+}
+
+# More complex cases, based primarily on the Cookbook
+# "Arbitrary SQL through a custom ResultSource" technique,
+# which seems to be the only place the bind attribute is
+# documented.  Breaking this technique probably breaks existing
+# application code.
+my $source = DBICTest::Artist->result_source_instance;
+my $new_source = $source->new($source);
+$new_source->source_name('Complex');
+
+$new_source->name(\<<'');
+( select a.*, cd.cdid as cdid, cd.title as title, cd.year as year 
+  from artist a
+  join cd on cd.artist=a.artistid
+  where cd.year=?)
+
+$schema->register_source('Complex' => $new_source);
+
+$rs = $schema->resultset('Complex')->search({}, { bind => [ 1999 ] });
+is ( $rs->count, 1, 'cookbook arbitrary sql example' );
+
+$rs = $schema->resultset('Complex')->search({ 'artistid' => 1 }, { bind => [ 1999 ] });
+is ( $rs->count, 1, '...coobook + search condition' );
+
+$rs = $schema->resultset('Complex')->search({}, { bind => [ 1999 ] })
+    ->search({ 'artistid' => 1 });
+is ( $rs->count, 1, '...cookbook (bind first) + chained search' );
+
+TODO: {
+    local $TODO = 'bind args order needs fixing (semifor)';
+    $rs = $schema->resultset('Complex')->search({}, { bind => [ 1999 ] })
+        ->search({ 'artistid' => 1 }, {
+            where => \'title like ?',
+            bind => [ 'Spoon%' ] });
+    is ( $rs->count, 1, '...cookbook + chained search with extra bind' );
+}
index 73925d4..192c17a 100644 (file)
@@ -7,7 +7,7 @@ use DBICTest;
 
 my $schema = DBICTest->init_schema();
 
-plan tests => 56;
+plan tests => 62;
 
 # has_a test
 my $cd = $schema->resultset("CD")->find(4);
@@ -90,6 +90,7 @@ $cd = $artist->find_or_create_related( 'cds', {
   year => 2006,
 } );
 is( $cd->title, 'Greatest Hits', 'find_or_create_related new record ok' );
+
 @cds = $artist->search_related('cds');
 is( ($artist->search_related('cds'))[4]->title, 'Greatest Hits', 'find_or_create_related new record search ok' );
 
@@ -109,6 +110,17 @@ $cd = $artist->find_or_new_related( 'cds', {
 is( $cd->title, 'Greatest Hits 2: Louder Than Ever', 'find_or_new_related new record ok' );
 ok( ! $cd->in_storage, 'find_or_new_related on a new record: not in_storage' );
 
+# print STDERR Data::Dumper::Dumper($cd->get_columns);
+# $cd->result_source->schema->storage->debug(1);
+$cd->artist(undef);
+my $newartist = $cd->find_or_new_related( 'artist', {
+  name => 'Random Boy Band Two',
+  artistid => 200,
+} );
+# $cd->result_source->schema->storage->debug(0);
+is($newartist->name, 'Random Boy Band Two', 'find_or_new_related new artist record with id');
+is($newartist->id, 200, 'find_or_new_related new artist id set');
+
 SKIP: {
   skip "relationship checking needs fixing", 1;
   # try to add a bogus relationship using the wrong cols
@@ -191,6 +203,13 @@ is( $twokey->fourkeys->count, 0, 'twokey has no fourkeys' );
 is( $twokey->fourkeys_to_twokeys->count, 0,
     'twokey has no links to fourkey' );
 
+my $undef_artist_cd = $schema->resultset("CD")->new_result({ 'title' => 'badgers', 'year' => 2007 });
+is($undef_artist_cd->has_column_loaded('artist'), '', 'FK not loaded');
+is($undef_artist_cd->search_related('artist')->count, 3, 'open search on undef FK');
+
+my $def_artist_cd = $schema->resultset("CD")->new_result({ 'title' => 'badgers', 'year' => 2007, artist => undef });
+is($def_artist_cd->has_column_loaded('artist'), 1, 'FK loaded');
+is($def_artist_cd->search_related('artist')->count, 0, 'closed search on null FK');
 
 # test undirected many-to-many relationship (e.g. "related artists")
 my $undir_maps = $schema->resultset("Artist")->find(1)->artist_undirected_maps;
index 277248e..7b99451 100644 (file)
--- a/t/72pg.t
+++ b/t/72pg.t
@@ -27,7 +27,7 @@ my ($dsn, $user, $pass) = @ENV{map { "DBICTEST_PG_${_}" } qw/DSN USER PASS/};
 plan skip_all => 'Set $ENV{DBICTEST_PG_DSN}, _USER and _PASS to run this test'
  . ' (note: creates and drops tables named artist and casecheck!)' unless ($dsn && $user);
 
-plan tests => 10;
+plan tests => 16;
 
 DBICTest::Schema->load_classes( 'Casecheck' );
 my $schema = DBICTest::Schema->connect($dsn, $user, $pass);
@@ -99,6 +99,83 @@ is( $NAME_info->{size}, 2, "Case sensitive matching info for 'NAME'" );
 my $uc_name_info = $schema->source('Casecheck')->column_info( 'uc_name' );
 is( $uc_name_info->{size}, 3, "Case insensitive matching info for 'uc_name'" );
 
+# Test SELECT ... FOR UPDATE
+my $HaveSysSigAction = eval "require Sys::SigAction" && !$@;
+if ($HaveSysSigAction) {
+    Sys::SigAction->import( 'set_sig_handler' );
+}
+
+SKIP: {
+    skip "Sys::SigAction is not available", 3 unless $HaveSysSigAction;
+    # create a new schema
+    my $schema2 = DBICTest::Schema->connect($dsn, $user, $pass);
+    $schema2->source("Artist")->name("testschema.artist");
+
+    $schema->txn_do( sub {
+        my $artist = $schema->resultset('Artist')->search(
+            {
+                artistid => 1
+            },
+            {
+                for => 'update'
+            }
+        )->first;
+        is($artist->artistid, 1, "select for update returns artistid = 1");
+
+        my $artist_from_schema2;
+        my $error_ok = 0;
+        eval {
+            my $h = set_sig_handler( 'ALRM', sub { die "DBICTestTimeout" } );
+            alarm(2);
+            $artist_from_schema2 = $schema2->resultset('Artist')->find(1);
+            $artist_from_schema2->name('fooey');
+            $artist_from_schema2->update;
+            alarm(0);
+        };
+        if (my $e = $@) {
+            $error_ok = $e =~ /DBICTestTimeout/;
+        }
+
+        # Make sure that an error was raised, and that the update failed
+        ok($error_ok, "update from second schema times out");
+        ok($artist_from_schema2->is_column_changed('name'), "'name' column is still dirty from second schema");
+    });
+}
+
+SKIP: {
+    skip "Sys::SigAction is not available", 3 unless $HaveSysSigAction;
+    # create a new schema
+    my $schema2 = DBICTest::Schema->connect($dsn, $user, $pass);
+    $schema2->source("Artist")->name("testschema.artist");
+
+    $schema->txn_do( sub {
+        my $artist = $schema->resultset('Artist')->search(
+            {
+                artistid => 1
+            },
+        )->first;
+        is($artist->artistid, 1, "select for update returns artistid = 1");
+
+        my $artist_from_schema2;
+        my $error_ok = 0;
+        eval {
+            my $h = set_sig_handler( 'ALRM', sub { die "DBICTestTimeout" } );
+            alarm(2);
+            $artist_from_schema2 = $schema2->resultset('Artist')->find(1);
+            $artist_from_schema2->name('fooey');
+            $artist_from_schema2->update;
+            alarm(0);
+        };
+        if (my $e = $@) {
+            $error_ok = $e =~ /DBICTestTimeout/;
+        }
+
+        # Make sure that an error was NOT raised, and that the update succeeded
+        ok(! $error_ok, "update from second schema DOES NOT timeout");
+        ok(! $artist_from_schema2->is_column_changed('name'), "'name' column is NOT dirty from second schema");
+    });
+}
+
 END {
     if($dbh) {
         $dbh->do("DROP TABLE testschema.artist;");
index 095a878..0d3a759 100644 (file)
@@ -10,7 +10,7 @@ plan skip_all => 'SQL::Translator required' if $@;
 
 my $schema = DBICTest->init_schema;
 
-plan tests => 54;
+plan tests => 56;
 
 my $translator = SQL::Translator->new( 
   parser_args => {
@@ -213,8 +213,20 @@ my %unique_constraints = (
 #  ],
 );
 
+my %indexes = (
+  artist => [
+    {
+      'fields' => ['name']
+    },
+  ]
+);
+
 my $tschema = $translator->schema();
 
+# Test that the $schema->sqlt_deploy_hook was called okay and that it removed
+# the 'link' table
+ok( !defined($tschema->get_table('link')), "Link table was removed by hook");
+
 # Test that nonexistent constraints are not found
 my $constraint = get_constraint('FOREIGN KEY', 'cd', ['title'], 'cd', ['year']);
 ok( !defined($constraint), 'nonexistent FOREIGN KEY constraint not found' );
@@ -244,6 +256,13 @@ for my $expected_constraints (keys %unique_constraints) {
   }
 }
 
+for my $table_index (keys %indexes) {
+  for my $expected_index ( @{ $indexes{$table_index} } ) {
+
+    ok ( get_index($table_index, $expected_index), "Got a matching index on $table_index table");
+  }
+}
+
 # Returns the Constraint object for the specified constraint type, table and
 # columns from the SQL::Translator schema, or undef if no matching constraint
 # is found.
@@ -293,6 +312,34 @@ sub get_constraint {
   return undef; # didn't find a matching constraint
 }
 
+sub get_index {
+  my ($table_name, $index) = @_;
+
+  my $table = $tschema->get_table($table_name);
+
+ CAND_INDEX:
+  for my $cand_index ( $table->get_indices ) {
+   
+    next CAND_INDEX if $index->{name} && $cand_index->name ne $index->{name}
+                    || $index->{type} && $cand_index->type ne $index->{type};
+
+    my %idx_fields = map { $_ => 1 } $cand_index->fields;
+
+    for my $field ( @{ $index->{fields} } ) {
+      next CAND_INDEX unless $idx_fields{$field};
+    }
+
+    %idx_fields = map { $_ => 1 } @{$index->{fields}};
+    for my $field ( $cand_index->fields) {
+      next CAND_INDEX unless $idx_fields{$field};
+    }
+
+    return $cand_index;
+  }
+
+  return undef; # No matching idx
+}
+
 # Test parameters in a FOREIGN KEY constraint other than columns
 sub test_fk {
   my ($expected, $got) = @_;
index 08828af..ef4912b 100644 (file)
@@ -7,7 +7,7 @@ use DBICTest;
 
 my $schema = DBICTest->init_schema();
 
-plan tests => 9; 
+plan tests => 10; 
 
 my $cd;
 my $rs = $cd = $schema->resultset("CD")->search({});
@@ -17,6 +17,8 @@ my $rs_year = $rs->get_column('year');
 
 is($rs_title->next, 'Spoonful of bees', "next okay");
 
+is_deeply( [ sort $rs_year->func('DISTINCT') ], [ 1997, 1998, 1999, 2001 ],  "wantarray context okay");
+
 my @all = $rs_title->all;
 cmp_ok(scalar @all, '==', 5, "five titles returned");
 
index a3bc582..d92340c 100644 (file)
@@ -10,7 +10,7 @@ my $schema = DBICTest->init_schema();
 eval { require DateTime::Format::MySQL };
 plan skip_all => "Need DateTime::Format::MySQL for inflation tests" if $@;
 
-plan tests => 8;
+plan tests => 17;
 
 # inflation test
 my $event = $schema->resultset("Event")->find(1);
@@ -42,3 +42,31 @@ my $created_cron = $created->created_on;
 
 isa_ok($created->created_on, 'DateTime', 'DateTime returned');
 is("$created_cron", '2006-06-23T00:00:00', 'Correct date/time');
+
+
+# Test "timezone" parameter
+my $event_tz = $schema->resultset('EventTZ')->create({
+    starts_at => DateTime->new(year=>2007, month=>12, day=>31, time_zone => "America/Chicago" ),
+    created_on => DateTime->new(year=>2006, month=>1, day=>31,
+        hour => 13, minute => 34, second => 56, time_zone => "America/New_York" ),
+});
+
+my $starts_at = $event_tz->starts_at;
+is("$starts_at", '2007-12-31T00:00:00', 'Correct date/time using timezone');
+
+my $created_on = $event_tz->created_on;
+is("$created_on", '2006-01-31T12:34:56', 'Correct timestamp using timezone');
+is($event_tz->created_on->time_zone->name, "America/Chicago", "Correct timezone");
+
+my $loaded_event = $schema->resultset('EventTZ')->find( $event_tz->id );
+
+isa_ok($loaded_event->starts_at, 'DateTime', 'DateTime returned');
+$starts_at = $loaded_event->starts_at;
+is("$starts_at", '2007-12-31T00:00:00', 'Loaded correct date/time using timezone');
+is($starts_at->time_zone->name, 'America/Chicago', 'Correct timezone');
+
+isa_ok($loaded_event->created_on, 'DateTime', 'DateTime returned');
+$created_on = $loaded_event->created_on;
+is("$created_on", '2006-01-31T12:34:56', 'Loaded correct timestamp using timezone');
+is($created_on->time_zone->name, 'America/Chicago', 'Correct timezone');
+
index 810b6eb..d898563 100644 (file)
@@ -51,6 +51,23 @@ my $newartist2 = $schema->resultset('Artist')->find_or_create({ name => 'Fred 3'
 
 is($newartist2->name, 'Fred 3', 'Created new artist with cds via find_or_create');
 
+my $artist2 = $schema->resultset('Artist')->create({ artistid => 1000,
+                                                    name => 'Fred 3',
+                                                     cds => [
+                                                             { artist => 1000,
+                                                               title => 'Music to code by',
+                                                               year => 2007,
+                                                             },
+                                                             ],
+                                                    cds_unordered => [
+                                                             { artist => 1000,
+                                                               title => 'Music to code by',
+                                                               year => 2007,
+                                                             },
+                                                             ]
+                                                     });
+
+is($artist2->in_storage, 1, 'artist with duplicate rels inserted okay');
 
 CREATE_RELATED1 :{
 
@@ -161,3 +178,19 @@ SPECIAL_CASE2: {
   is($a->name, 'Pink Floyd', 'Artist insertion ok');
   is($a->cds && $a->cds->first->title, 'The Wall', 'CD insertion ok');
 }
+
+## Create foreign key col obj including PK
+## See test 20 in 66relationships.t
+my $new_cd_hashref = { 
+              cdid => 27, 
+               title => 'Boogie Woogie', 
+              year => '2007', 
+              artist => { artistid => 17, name => 'king luke' }
+             };
+
+my $cd = $schema->resultset("CD")->find(1);
+
+is($cd->artist->id, 1, 'rel okay');
+
+my $new_cd = $schema->resultset("CD")->create($new_cd_hashref);
+is($new_cd->artist->id, 17, 'new id retained okay');
index 7ebd040..979cf84 100644 (file)
@@ -34,9 +34,15 @@ __PACKAGE__->load_classes(qw/
     'Producer',
     'CD_to_Producer',
   ),
-  qw/SelfRefAlias TreeLike TwoKeyTreeLike Event NoPrimaryKey/,
+  qw/SelfRefAlias TreeLike TwoKeyTreeLike Event EventTZ NoPrimaryKey/,
   qw/Collection CollectionObject TypedObject/,
   qw/Owners BooksInLibrary/
 );
 
+sub sqlt_deploy_hook {
+  my ($self, $sqlt_schema) = @_;
+
+  $sqlt_schema->drop_table('link');
+}
+
 1;
index 90eb7bf..ae92606 100644 (file)
@@ -31,6 +31,9 @@ __PACKAGE__->has_many(
     cds => 'DBICTest::Schema::CD', undef,
     { order_by => 'year' },
 );
+__PACKAGE__->has_many(
+    cds_unordered => 'DBICTest::Schema::CD'
+);
 
 __PACKAGE__->has_many( twokeys => 'DBICTest::Schema::TwoKeys' );
 __PACKAGE__->has_many( onekeys => 'DBICTest::Schema::OneKey' );
@@ -41,4 +44,14 @@ __PACKAGE__->has_many(
   { cascade_copy => 0 } # this would *so* not make sense
 );
 
+sub sqlt_deploy_hook {
+  my ($self, $sqlt_table) = @_;
+
+
+  if ($sqlt_table->schema->translator->producer_type =~ /SQLite$/ ) {
+    $sqlt_table->add_index( name => 'artist_name', fields => ['name'] )
+      or die $sqlt_table->error;
+  }
+}
+
 1;
diff --git a/t/lib/DBICTest/Schema/EventTZ.pm b/t/lib/DBICTest/Schema/EventTZ.pm
new file mode 100644 (file)
index 0000000..9922962
--- /dev/null
@@ -0,0 +1,19 @@
+package DBICTest::Schema::EventTZ;
+
+use strict;
+use warnings;
+use base qw/DBIx::Class::Core/;
+
+__PACKAGE__->load_components(qw/InflateColumn::DateTime/);
+
+__PACKAGE__->table('event');
+
+__PACKAGE__->add_columns(
+  id => { data_type => 'integer', is_auto_increment => 1 },
+  starts_at => { data_type => 'datetime', extra => { timezone => "America/Chicago" } },
+  created_on => { data_type => 'timestamp', extra => { timezone => "America/Chicago" } },
+);
+
+__PACKAGE__->set_primary_key('id');
+
+1;