X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=blobdiff_plain;f=lib%2FDBIx%2FClass%2FManual%2FCookbook.pod;h=677347966193b3cba7bf4256949e1857c8496b84;hb=3d5658966d987a203d6cb80804ad8d337f57e4b5;hp=1bc0c8abb9f6ffb63cfe46149b9a10505efce2f6;hpb=ab872312383fbf46483519a49c81fe877145c1bf;p=dbsrgits%2FDBIx-Class.git diff --git a/lib/DBIx/Class/Manual/Cookbook.pod b/lib/DBIx/Class/Manual/Cookbook.pod index 1bc0c8a..6773479 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,7 +68,7 @@ This results in the following C clause: For more information on generating complex queries, see L. -=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. -=head3 Using specific columns +=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 @@ -140,7 +138,7 @@ use anyway: This is a shortcut for C and C. -=head3 Using database functions or stored procedures +=head2 Using database functions or stored procedures The combination of C 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( {}, @@ -196,9 +194,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 +206,9 @@ any of your aliases using either of these: } ); -=head3 Grouping results + my $count = $rs->next->get_column('count'); + +=head2 Grouping results L supports C as follows: @@ -233,7 +231,7 @@ 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 >). -=head3 Predefined searches +=head2 Predefined searches You can write your own L class by inheriting from it and define often used searches as methods: @@ -257,12 +255,52 @@ and define often used searches as methods: To use your resultset, first tell DBIx::Class to create an instance of it for you, in your My::DBIC::Schema::CD class: + # class definition as normal + __PACKAGE__->load_components(qw/ Core /); + __PACKAGE__->table('cd'); + + # tell DBIC to use the custom ResultSet class __PACKAGE__->resultset_class('My::DBIC::ResultSet::CD'); +Note that C must be called after C and C, or you will get errors about missing methods. + 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 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 +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 and +C 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 attribute to allow searching on, or sorting your @@ -294,7 +332,7 @@ it in your C attribute: join => [qw/ artist /], order_by => [qw/ artist.name /] } - }; + ); # Equivalent SQL: # SELECT cd.* FROM cd @@ -361,7 +399,7 @@ 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 @@ -442,7 +480,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 +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 attribute of C to force ordering). - -=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 - } - -=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