__PACKAGE__->table_class('DBIx::Class::ResultSource::View');
- # ->table, ->add_columns, etc.
+ # For the time being this is necessary even for virtual views
+ __PACKAGE__->table($view_name);
+
+ #
+ # ->add_columns, etc.
+ #
# do not attempt to deploy() this view
__PACKAGE__->result_source_instance->is_virtual(1);
});
my $rs = $schema->resultset('CD')->search({
- artist_id => { 'IN' => $inside_rs->get_column('id')->as_query },
+ artist_id => { -in => $inside_rs->get_column('id')->as_query },
});
-The usual operators ( =, !=, IN, NOT IN, etc.) are supported.
+The usual operators ( '=', '!=', -in, -not_in, etc.) are supported.
B<NOTE>: You have to explicitly use '=' when doing an equality comparison.
The following will B<not> work:
my $rs = $cdrs->search({
year => {
'=' => $cdrs->search(
- { artist_id => { '=' => \'me.artist_id' } },
- { alias => 'inner' }
+ { artist_id => { -ident => 'me.artist_id' } },
+ { alias => 'sub_query' }
)->get_column('year')->max_rs->as_query,
},
});
SELECT me.cdid, me.artist, me.title, me.year, me.genreid, me.single_track
FROM cd me
- WHERE year = (
- SELECT MAX(inner.year)
- FROM cd inner
- WHERE artist_id = me.artist_id
- )
+ WHERE year = (
+ SELECT MAX(sub_query.year)
+ FROM cd sub_query
+ WHERE artist_id = me.artist_id
+ )
=head2 Predefined searches
good idea since it requires a scan of the entire table. (Unless your RDBMS
supports indexes on expressions - including return values of functions - and
you create an index on the return value of the function in question.) However,
-it can be accomplished with C<DBIx::Class> when necessary.
-
-Your approach for doing so will depend on whether you have turned
-quoting on via the C<quote_char> and C<name_sep> attributes. If you
-explicitly defined C<quote_char> and C<name_sep> in your
-C<connect_info> (see L<DBIx::Class::Storage::DBI/"connect_info">) then
-you are using quoting, otherwise not.
-
-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 literal SQL values with
-placeholders:
+it can be accomplished with C<DBIx::Class> when necessary by resorting to
+literal SQL:
$rs->search(\[ 'YEAR(date_of_birth) = ?', [ plain_value => 1979 ] ]);
# Equivalent SQL:
# SELECT * FROM employee WHERE YEAR(date_of_birth) = ?
- $rs->search({
+ $rs->search({ -and => [
name => 'Bob',
- -nest => \[ 'YEAR(date_of_birth) = ?', [ plain_value => 1979 ] ],
- });
+ \[ 'YEAR(date_of_birth) = ?', [ plain_value => 1979 ] ],
+ ]});
# Equivalent SQL:
# SELECT * FROM employee WHERE name = ? AND YEAR(date_of_birth) = ?
Note: the C<plain_value> string in the C<< [ plain_value => 1979 ] >> part
should be either the same as the name of the column (do this if the type of the
-return value of the function is the same as the type of the column) or
-otherwise it's essentially a dummy string currently (use C<plain_value> as a
-habit). It is used by L<DBIx::Class> to handle special column types.
+return value of the function is the same as the type of the column) or in the
+case of a function it's currently treated as a dummy string (it is a good idea
+to use C<plain_value> or something similar to convey intent). The value is
+currently only significant when handling special column types (BLOBs, arrays,
+etc.), but this may change in the future.
See also L<SQL::Abstract/Literal SQL with placeholders and bind values
(subqueries)>.
+=head2 Software Limits
+
+When your RDBMS does not have a working SQL limit mechanism (e.g. Sybase ASE)
+and L<GenericSubQ|SQL::Abstract::Limit/GenericSubQ> is either too slow or does
+not work at all, you can try the
+L<software_limit|DBIx::Class::ResultSet/software_limit>
+L<DBIx::Class::ResultSet> attribute, which skips over records to simulate limits
+in the Perl layer.
+
+For example:
+
+ my $paged_rs = $rs->search({}, {
+ rows => 25,
+ page => 3,
+ order_by => [ 'me.last_name' ],
+ software_limit => 1,
+ });
+
+You can set it as a default for your schema by placing the following in your
+C<Schema.pm>:
+
+ __PACKAGE__->default_resultset_attributes({ software_limit => 1 });
+
+B<WARNING:> If you are dealing with large resultsets and your L<DBI> or
+ODBC/ADO driver does not have proper cursor support (i.e. it loads the whole
+resultset into memory) then this feature will be extremely slow and use huge
+amounts of memory at best, and may cause your process to run out of memory and
+cause instability on your server at worst, beware!
+
=head1 JOINS AND PREFETCHING
=head2 Using joins and prefetch
=head1 ROW-LEVEL OPERATIONS
-=head2 Retrieving a row object's Schema
+=head2 Retrieving a result object's Schema
-It is possible to get a Schema object from a row object like so:
+It is possible to get a Schema object from a result object like so:
my $schema = $cd->result_source->schema;
# use the schema as normal:
Alternatively you can use L<DBIx::Class::DynamicSubclass> that implements
exactly the above functionality.
-=head2 Skip row object creation for faster results
+=head2 Skip result 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
=head2 Creating a result set from a set of rows
-Sometimes you have a (set of) row objects that you want to put into a
+Sometimes you have a (set of) result objects that you want to put into a
resultset without the need to hit the DB again. You can do that by using the
L<set_cache|DBIx::Class::Resultset/set_cache> method:
__PACKAGE__->has_many('pages' => 'Page', 'book', { where => { scrap => 0 } } );
-=head2 Many-to-many relationships
+=head2 Many-to-many relationship bridges
This is straightforward using L<ManyToMany|DBIx::Class::Relationship/many_to_many>:
L<DBIx::Class::Schema::Loader> will connect to a database and create a
L<DBIx::Class::Schema> and associated sources by examining the database.
-The recommend way of achieving this is to use the
+The recommend way of achieving this is to use the L<dbicdump> utility or the
+L<Catalyst> helper, as described in
+L<Manual::Intro|DBIx::Class::Manual::Intro/Using DBIx::Class::Schema::Loader>.
+
+Alternatively, use the
L<make_schema_at|DBIx::Class::Schema::Loader/make_schema_at> method:
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" ])'
+ -e 'make_schema_at("My::Schema", \
+ { db_schema => 'myschema', components => ["InflateColumn::DateTime"] }, \
+ [ "dbi:Pg:dbname=foo", "username", "password" ])'
-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.
+This will create a tree of files rooted at C<./lib/My/Schema/> containing source
+definitions for all the tables found in the C<myschema> schema in the C<foo>
+database.
=head2 Creating DDL SQL
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.
+generator to put the quotes the correct place, and defaults to
+C<.> if not supplied.
In most cases you should set these as part of the arguments passed to
L<DBIx::Class::Schema/connect>:
placeholders and bind values (subqueries)> for more explanation. Note that
L<DBIx::Class> sets L<SQL::Abstract/bindtype> to C<columns>, so you must pass
the bind values (the C<[1, 2, 3]> arrayref in the above example) wrapped in
-arrayrefs together with the column name, like this: C<< [column_name => value]
->>.
+arrayrefs together with the column name, like this:
+C<< [column_name => value] >>.
+
+=head2 Formatting DateTime objects in queries
+
+To ensure C<WHERE> conditions containing L<DateTime> arguments are properly
+formatted to be understood by your RDBMS, you must use the C<DateTime>
+formatter returned by L<DBIx::Class::Storage::DBI/datetime_parser> to format
+any L<DateTime> objects you pass to L<search|DBIx::Class::ResultSet/search>
+conditions. Any L<Storage|DBIx::Class::Storage> object attached to your
+L<Schema|DBIx::Class::Schema> provides a correct C<DateTime> formatter, so
+all you have to do is:
+
+ my $dtf = $schema->storage->datetime_parser;
+ my $rs = $schema->resultset('users')->search(
+ {
+ signup_date => {
+ -between => [
+ $dtf->format_datetime($dt_start),
+ $dtf->format_datetime($dt_end),
+ ],
+ }
+ },
+ );
+
+Without doing this the query will contain the simple stringification of the
+C<DateTime> object, which almost never matches the RDBMS expectations.
+
+This kludge is necessary only for conditions passed to
+L<DBIx::Class::ResultSet/search>, whereas
+L<create|DBIx::Class::ResultSet/create>,
+L<find|DBIx::Class::ResultSet/find>,
+L<DBIx::Class::Row/update> (but not L<DBIx::Class::ResultSet/update>) are all
+L<DBIx::Class::InflateColumn>-aware and will do the right thing when supplied
+an inflated C<DateTime> object.
=head2 Using Unicode
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
C<squared> be automagically set to the value of C<number> squared.
-You can accomplish this by overriding C<store_column>:
+You can accomplish this by wrapping the C<number> accessor with the C<around>
+method modifier, available through either L<Class::Method::Modifiers>,
+L<Moose|Moose::Manual::MethodModifiers> or L<Moose-like|Moo> modules):
- sub store_column {
- my ( $self, $name, $value ) = @_;
- if ($name eq 'number') {
- $self->squared($value * $value);
+ around number => sub {
+ my ($orig, $self) = (shift, shift);
+
+ if (@_) {
+ my $value = $_[0];
+ $self->squared( $value * $value );
}
- $self->next::method($name, $value);
- }
-Note that the hard work is done by the call to C<next::method>, which
+ $self->$orig(@_);
+ };
+
+Note that the hard work is done by the call to C<< $self->$orig >>, which
redispatches your call to store_column in the superclass(es).
+Generally, if this is a calculation your database can easily do, try
+and avoid storing the calculated value, it is safer to calculate when
+needed, than rely on the data being in sync.
+
=head2 Automatically creating related objects
You might have a class C<Artist> which has many C<CD>s. Further, you
=item *
Use L<populate|DBIx::Class::ResultSet/populate> in void context to insert data
-when you don't need the resulting L<DBIx::Class::Row> objects, if possible, but
-see the caveats.
+when you don't need the resulting L<result|DBIx::Class::Manual::ResultClass> objects,
+if possible, but see the caveats.
When inserting many rows, for best results, populate a large number of rows at a
time, but not so large that the table is locked for an unacceptably long time.