From: Ash Berlin Date: Sat, 13 Oct 2007 12:33:33 +0000 (+0000) Subject: Add docs about sqlt_deploy_hook, and reorganise/reorder the Cookbook X-Git-Tag: v0.08010~48 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=d2f3e87bbb670790a5572e1f7b92f33cc57585ab;p=dbsrgits%2FDBIx-Class.git Add docs about sqlt_deploy_hook, and reorganise/reorder the Cookbook --- diff --git a/lib/DBIx/Class/Manual/Cookbook.pod b/lib/DBIx/Class/Manual/Cookbook.pod index 2fdb3ad..0552a03 100644 --- a/lib/DBIx/Class/Manual/Cookbook.pod +++ b/lib/DBIx/Class/Manual/Cookbook.pod @@ -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 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 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( {}, @@ -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 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: @@ -263,7 +261,7 @@ Then call your new method in your code: my $ordered_cds = $schema->resultset('CD')->search_cds_ordered(); -=head3 Using SQL functions on the left hand side of a comparison +=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, @@ -294,6 +292,8 @@ C attributes: =end hidden +=head1 JOINS AND PREFETCHING + =head2 Using joins and prefetch You can use the C attribute to allow searching on, or sorting your @@ -392,7 +392,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 @@ -473,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 +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 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 diff --git a/lib/DBIx/Class/ResultSource.pm b/lib/DBIx/Class/ResultSource.pm index 4efa0d7..d23c765 100644 --- a/lib/DBIx/Class/ResultSource.pm +++ b/lib/DBIx/Class/ResultSource.pm @@ -1057,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 object when you deploy the schema +via L or L. + +For an example of what you can do with this, see +L. + =head1 AUTHORS Matt S. Trout diff --git a/lib/DBIx/Class/Schema.pm b/lib/DBIx/Class/Schema.pm index 79988b8..b668c83 100644 --- a/lib/DBIx/Class/Schema.pm +++ b/lib/DBIx/Class/Schema.pm @@ -1050,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 object when you deploy the schema via +L or L. + +For an example of what you can do with this, see +L. + +=cut + 1; =head1 AUTHORS