X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=blobdiff_plain;f=lib%2FDBIx%2FClass%2FManual%2FCookbook.pod;h=efbc2e8343d639fc4386d911f27166e9482be3ac;hb=3bad9fe15aa3c67afc7772f60cf5c051249320b8;hp=ed00d46c0e638a2ac6d5a3269ced4a621c65bcb1;hpb=79e116f08f795c6ae039c6d9cfca84cabbcdf1ed;p=dbsrgits%2FDBIx-Class.git diff --git a/lib/DBIx/Class/Manual/Cookbook.pod b/lib/DBIx/Class/Manual/Cookbook.pod index ed00d46..efbc2e8 100644 --- a/lib/DBIx/Class/Manual/Cookbook.pod +++ b/lib/DBIx/Class/Manual/Cookbook.pod @@ -2,14 +2,12 @@ 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 for a -paged resultset, which will fetch only a small number of records at a time: +paged resultset, which will fetch only a defined number of records at a time: my $rs = $schema->resultset('Artist')->search( undef, @@ -32,12 +30,12 @@ The C attribute does not have to be specified in your search: return $rs->page(1); # DBIx::Class::ResultSet containing first 10 records -In either of the above cases, you can return a L object for the +In either of the above cases, you can get a L object for the resultset (suitable for use in e.g. a template) using the C method: return $rs->pager(); -=head3 Complex WHERE clauses +=head2 Complex WHERE clauses Sometimes you need to formulate a query using specific operators: @@ -70,10 +68,62 @@ This results in the following C clause: For more information on generating complex queries, see L. -=head3 Using specific columns +=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 +be optimized for your database in a special way, but you still want to +get the results as a L. +The recommended way to accomplish this is by defining a separate ResultSource +for your query. You can then inject complete SQL statements using a scalar +reference (this is a feature of L). + +Say you want to run a complex custom query on your user data, here's what +you have to add to your User class: + + package My::Schema::User; + + use base qw/DBIx::Class/; + + # ->load_components, ->table, ->add_columns, etc. + + # Make a new ResultSource based on the User class + my $source = __PACKAGE__->result_source_instance(); + my $new_source = $source->new( $source ); + $new_source->source_name( 'UserFriendsComplex' ); + + # Hand in your query as a scalar reference + # It will be added as a sub-select after FROM, + # so pay attention to the surrounding brackets! + $new_source->name( \<register_source( 'UserFriendsComplex' => $new_source ); + +Next, you can execute your complex query using bind parameters like this: + + my $friends = [ $schema->resultset( 'UserFriendsComplex' )->search( {}, + { + bind => [ 12345, 12345 ] + } + ) ]; + +... and you'll get back a perfect L. -When you only want selected columns from a table, you can use C to -specify which ones you need: +=head2 Using specific columns + +When you only want specific columns from a table, you can use +C to specify which ones you need. This is useful to avoid +loading columns with large amounts of data that you aren't about to +use anyway: my $rs = $schema->resultset('Artist')->search( undef, @@ -85,7 +135,10 @@ specify which ones you need: # Equivalent SQL: # SELECT artist.name FROM artist -=head3 Using database functions or stored procedures +This is a shortcut for C and C. + +=head2 Using database functions or stored procedures The combination of C to @@ -94,7 +147,7 @@ stored procedure name). You then use C to set the column name you will use to access the returned value: my $rs = $schema->resultset('Artist')->search( - undef, + {}, { select => [ 'name', { LENGTH => 'name' } ], as => [qw/ name name_length /], @@ -102,18 +155,21 @@ to access the returned value: ); # Equivalent SQL: - # SELECT name name, LENGTH( name ) name_length + # SELECT name name, LENGTH( name ) # FROM artist -If your alias exists as a column in your base class (i.e. it was added with -C), you just access it as normal. Our C class has a C -column, so we just use the C accessor: +Note that the C< as > attribute has absolutely nothing to with the sql +syntax C< SELECT foo AS bar > (see the documentation in +L). If your alias exists as a +column in your base class (i.e. it was added with C), you +just access it as normal. Our C class has a C column, so +we just use the C accessor: my $artist = $rs->first(); my $name = $artist->name(); If on the other hand the alias does not correspond to an existing column, you -can get the value using the C accessor: +have to fetch the value using the C accessor: my $name_length = $artist->get_column('name_length'); @@ -126,24 +182,24 @@ 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( - undef, + {}, { select => [ { distinct => [ $source->columns ] } ], - as => [ $source->columns ] + as => [ $source->columns ] # remember 'as' is not the same as SQL AS :-) } ); my $count = $rs->next->get_column('count'); -=head3 SELECT COUNT(DISTINCT colname) +=head2 SELECT COUNT(DISTINCT colname) my $rs = $schema->resultset('Foo')->search( - undef, + {}, { select => [ { count => { distinct => 'colname' } } @@ -152,12 +208,12 @@ any of your aliases using either of these: } ); -=head3 Grouping results +=head2 Grouping results L supports C as follows: my $rs = $schema->resultset('Artist')->search( - undef, + {}, { join => [qw/ cds /], select => [ 'name', { count => 'cds.cdid' } ], @@ -171,9 +227,13 @@ L supports C as follows: # LEFT JOIN cd cds ON ( cds.artist = me.artistid ) # GROUP BY name -=head3 Predefined searches +Please see L 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 >). + +=head2 Predefined searches -You can write your own DBIx::Class::ResultSet class by inheriting from it +You can write your own L class by inheriting from it and define often used searches as methods: package My::DBIC::ResultSet::CD; @@ -201,26 +261,38 @@ 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 -=head3 Predefined searches without writing a ResultSet class +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 when necessary. -Alternatively you can automatically generate a DBIx::Class::ResultSet -class by using the ResultSetManager component and tagging your method -as ResultSet: +If you do not have quoting on, simply include the function in your search +specification as you would any column: - __PACKAGE__->load_components(qw/ ResultSetManager Core /); + $rs->search({ 'YEAR(date_of_birth)' => 1979 }); - sub search_cds_ordered : ResultSet { - my ($self) = @_; - return $self->search( - {}, - { order_by => 'name DESC' }, - ); - } +With quoting on, or for a more portable solution, use the C +attribute: -Then call your method in the same way from your code: + $rs->search({}, { where => \'YEAR(date_of_birth) = 1979' }); - my $ordered_cds = $schema->resultset('CD')->search_cds_ordered(); +=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 and +C attributes: + + $rs->search({}, { + where => \'YEAR(date_of_birth) = ?', + bind => [ 1979 ] + }); + +=end hidden + +=head1 JOINS AND PREFETCHING =head2 Using joins and prefetch @@ -253,7 +325,7 @@ it in your C attribute: join => [qw/ artist /], order_by => [qw/ artist.name /] } - }; + ); # Equivalent SQL: # SELECT cd.* FROM cd @@ -313,15 +385,14 @@ L has now prefetched all matching data from the C table, so no additional SQL statements are executed. You now have a much more efficient query. -Note that as of L 0.04, C cannot be used with -C relationships. You will get an error along the lines of "No -accessor for prefetched ..." if you try. +Note that as of L 0.05999_01, C I be used with +C relationships. Also note that C 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 objects who have Cs whose C @@ -383,7 +454,7 @@ From 0.04999_05 onwards, C can be nested more than one relationship deep using the same syntax as a multi-step join: my $rs = $schema->resultset('Tag')->search( - undef, + {}, { prefetch => { cd => 'artist' @@ -402,32 +473,382 @@ SQL statements: my $tag = $rs->first; print $tag->cd->artist->name; -=head2 Transactions +=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 +module. + +To make an object stringify itself as a single column, use something +like this (replace C 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 and C. The table +specifications are: + + Product(id, Description, category) + Category(id, Description) + +C 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 instead, then check C: + + 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 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) 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 method within the User proxy-class +gives us the effect we want. This method is called by +L 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 + + package DB::Schema; + + use base qw/DBIx::Class::Schema/; + + __PACKAGE__->load_classes(qw/User/); + + +B + + 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.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. + + 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 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 +and C instead of C + + my $rs = $schema->resultset('Dual')->search(undef, + { select => [ 'sydate' ], + as => [ 'now' ] + }, + ); + +All you have to do now is be careful how you access your resultset, the below +will not work because there is no column called 'now' in the Dual table class + + while (my $dual = $rs->next) { + print $dual->now."\n"; + } + # Can't locate object method "now" via package "MyAppDB::Dual" at headshot.pl line 23. + +You could of course use 'dummy' in C instead of 'now', or C to +your Dual class for whatever you wanted to select from dual, but that's just +silly, instead use C + + while (my $dual = $rs->next) { + print $dual->get_column('now')."\n"; + } + +Or use C + + my $cursor = $rs->cursor; + while (my @vals = $cursor->next) { + print $vals[0]."\n"; } + +Or use L + + $rs->result_class('DBIx::Class::ResultClass::HashRefInflator'); + while ( my $dual = $rs->next ) { + print $dual->{now}."\n"; + } + +Here are some example C