Refactor SQLA/select interaction (in reality just cleanup)
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Manual / FAQ.pod
1 =head1 NAME
2
3 DBIx::Class::Manual::FAQ - Frequently Asked Questions (in theory)
4
5 =head1 DESCRIPTION
6
7 This document is intended as an anti-map of the documentation. If you
8 know what you want to do, but not how to do it in L<DBIx::Class>, then
9 look here. It does B<not> contain much code or examples, it just gives
10 explanations and pointers to the correct pieces of documentation to
11 read.
12
13 =head1 FAQs
14
15 How Do I:
16
17 =head2 Getting started
18
19 =over 4
20
21 =item .. create a database to use?
22
23 First, choose a database. For testing/experimenting, we reccommend
24 L<DBD::SQLite>, which is a self-contained small database (i.e. all you
25 need to do is to install L<DBD::SQLite> from CPAN, and it's usable).
26
27 Next, spend some time defining which data you need to store, and how
28 it relates to the other data you have. For some help on normalisation,
29 go to L<http://b62.tripod.com/doc/dbbase.htm>.
30
31 Now, decide whether you want to have the database itself be the
32 definitive source of information about the data layout, or your
33 DBIx::Class schema. If it's the former, look up the documentation for
34 your database, eg. L<http://sqlite.org/lang_createtable.html>, on how
35 to create tables, and start creating them. For a nice universal
36 interface to your database, you can try L<DBI::Shell>. If you decided
37 on the latter choice, read the FAQ on setting up your classes
38 manually, and the one on creating tables from your schema.
39
40 =item .. use DBIx::Class with L<Catalyst>?
41
42 Install L<Catalyst::Model::DBIC::Schema> from CPAN. See its
43 documentation, or below, for further details.
44
45 =item .. set up my DBIx::Class classes automatically from my database?
46
47 Install L<DBIx::Class::Schema::Loader> from CPAN, and read its documentation.
48
49 =item .. set up my DBIx::Class classes manually?
50
51 Look at the L<DBIx::Class::Manual::Example> and come back here if you get lost.
52
53 =item .. create my database tables from my DBIx::Class schema?
54
55 Create your classes manually, as above. Write a script that calls
56 L<DBIx::Class::Schema/deploy>. See there for details, or the
57 L<DBIx::Class::Manual::Cookbook>.
58
59 =item .. store/retrieve Unicode data in my database?
60
61 Make sure you database supports Unicode and set the connect
62 attributes appropriately - see
63 L<DBIx::Class::Manual::Cookbook/Using Unicode>
64
65 =item .. connect to my database?
66
67 Once you have created all the appropriate table/source classes, and an
68 overall L<Schema|DBIx::Class::Schema> class, you can start using
69 them in an application. To do this, you need to create a central
70 Schema object, which is used to access all the data in the various
71 tables. See L<DBIx::Class::Schema/connect> for details. The actual
72 connection does not happen until you actually request data, so don't
73 be alarmed if the error from incorrect connection details happens a
74 lot later.
75
76 =item .. use DBIx::Class across multiple databases?
77
78 If your database server allows you to run querys across multiple
79 databases at once, then so can DBIx::Class. All you need to do is make
80 sure you write the database name as part of the
81 L<DBIx::Class::ResultSource/table> call. Eg:
82
83   __PACKAGE__->table('mydb.mytablename');
84
85 And load all the Result classes for both / all databases using one
86 L<DBIx::Class::Schema/load_namespaces> call.
87
88 =item .. use DBIx::Class across PostgreSQL/DB2/Oracle schemas?
89
90 Add the name of the schema to the L<DBIx::Class::ResultSource/table>
91 as part of the name, and make sure you give the one user you are going
92 to connect with rights to read/write all the schemas/tables as
93 necessary.
94
95 =back
96
97 =head2 Relationships
98
99 =over 4
100
101 =item .. tell DBIx::Class about relationships between my tables?
102
103 There are a variety of relationship types that come pre-defined for
104 you to use.  These are all listed in L<DBIx::Class::Relationship>. If
105 you need a non-standard type, or more information, look in
106 L<DBIx::Class::Relationship::Base>.
107
108 =item .. define a one-to-many relationship?
109
110 This is called a C<has_many> relationship on the one side, and a
111 C<belongs_to> relationship on the many side. Currently these need to
112 be set up individually on each side. See L<DBIx::Class::Relationship>
113 for details.
114
115 =item .. define a relationship where this table contains another table's primary key? (foreign key)
116
117 Create a C<belongs_to> relationship for the field containing the
118 foreign key.  See L<DBIx::Class::Relationship/belongs_to>.
119
120 =item .. define a foreign key relationship where the key field may contain NULL?
121
122 Just create a C<belongs_to> relationship, as above. If the column is
123 NULL then the inflation to the foreign object will not happen. This
124 has a side effect of not always fetching all the relevant data, if you
125 use a nullable foreign-key relationship in a JOIN, then you probably
126 want to set the C<join_type> to C<left>.
127
128 =item .. define a relationship where the key consists of more than one column?
129
130 Instead of supplying a single column name, all relationship types also
131 allow you to supply a hashref containing the condition across which
132 the tables are to be joined. The condition may contain as many fields
133 as you like. See L<DBIx::Class::Relationship::Base>.
134
135 =item .. define a relationship across an intermediate table? (many-to-many)
136
137 Read the documentation on L<DBIx::Class::Relationship/many_to_many>.
138
139 =item .. stop DBIx::Class from attempting to cascade deletes on my has_many and might_have relationships?
140
141 By default, DBIx::Class cascades deletes and updates across
142 C<has_many> and C<might_have> relationships. You can disable this
143 behaviour on a per-relationship basis by supplying
144 C<< cascade_delete => 0 >> in the relationship attributes.
145
146 The cascaded operations are performed after the requested delete or
147 update, so if your database has a constraint on the relationship, it
148 will have deleted/updated the related records or raised an exception
149 before DBIx::Class gets to perform the cascaded operation.
150
151 See L<DBIx::Class::Relationship>.
152
153 =item .. use a relationship?
154
155 Use its name. An accessor is created using the name. See examples in
156 L<DBIx::Class::Manual::Cookbook/Using relationships>.
157
158 =back
159
160 =head2 Searching
161
162 =over 4
163
164 =item .. search for data?
165
166 Create a C<$schema> object, as mentioned above in ".. connect to my
167 database". Find the L<ResultSet|DBIx::Class::Manual::Glossary/ResultSet>
168 that you want to search in, and call C<search> on it. See
169 L<DBIx::Class::ResultSet/search>.
170
171 =item .. search using database functions?
172
173 Supplying something like:
174
175  ->search({'mydatefield' => 'now()'})
176
177 to search, will probably not do what you expect. It will quote the
178 text "now()", instead of trying to call the function. To provide
179 literal, unquoted text you need to pass in a scalar reference, like
180 so:
181
182  ->search({'mydatefield' => \'now()'})
183
184 =item .. sort the results of my search?
185
186 Supply a list of columns you want to sort by to the C<order_by>
187 attribute. See L<DBIx::Class::ResultSet/order_by>.
188
189 =item .. sort my results based on fields I've aliased using C<as>?
190
191 You didn't alias anything, since L<as|DBIx::Class::ResultSet/as>
192 B<has nothing to do> with the produced SQL. See
193 L<DBIx::Class::ResultSet/select> for details.
194
195 =item .. group the results of my search?
196
197 Supply a list of columns you want to group on, to the C<group_by>
198 attribute, see L<DBIx::Class::ResultSet/group_by>.
199
200 =item .. group my results based on fields I've aliased using C<as>?
201
202 You don't. See the explanation on ordering by an alias above.
203
204 =item .. filter the results of my search?
205
206 The first argument to C<search> is a hashref of accessor names and
207 values to filter them by, for example:
208
209  ->search({'created_time' => { '>=', '2006-06-01 00:00:00' } })
210
211 Note that to use a function here you need to make it a scalar
212 reference:
213
214  ->search({'created_time' => { '>=', \'yesterday()' } })
215
216 =item .. search in several tables simultaneously?
217
218 To search in two related tables, you first need to set up appropriate
219 relationships between their respective classes. When searching you
220 then supply the name of the relationship to the C<join> attribute in
221 your search, for example when searching in the Books table for all the
222 books by the author "Fred Bloggs":
223
224  ->search({'authors.name' => 'Fred Bloggs'}, { join => 'authors' })
225
226 The type of join created in your SQL depends on the type of
227 relationship between the two tables, see L<DBIx::Class::Relationship>
228 for the join used by each relationship.
229
230 =item .. create joins with conditions other than column equality?
231
232 Currently, L<DBIx::Class> can only create join conditions using
233 equality, so you're probably better off creating a C<view> in your
234 database, and using that as your source. A C<view> is a stored SQL
235 query, which can be accessed similarly to a table, see your database
236 documentation for details.
237
238 =item .. search with an SQL function on the left hand side?
239
240 To use an SQL function on the left hand side of a comparison:
241
242  ->search({ -nest => \[ 'YEAR(date_of_birth) = ?', [ plain_value => 1979 ] ] });
243
244 Note: the C<plain_value> string in the C<< [ plain_value => 1979 ] >> part
245 should be either the same as the name of the column (do this if the type of the
246 return value of the function is the same as the type of the column) or
247 otherwise it's essentially a dummy string currently (use C<plain_value> as a
248 habit). It is used by L<DBIx::Class> to handle special column types.
249
250 Or, if you have quoting off:
251
252  ->search({ 'YEAR(date_of_birth)' => 1979 });
253
254 =item .. find more help on constructing searches?
255
256 Behind the scenes, DBIx::Class uses L<SQL::Abstract> to help construct
257 its SQL searches. So if you fail to find help in the
258 L<DBIx::Class::Manual::Cookbook>, try looking in the SQL::Abstract
259 documentation.
260
261 =item .. make searches in Oracle (10gR2 and newer) case-insensitive?
262
263 To make Oracle behave like most RDBMS use on_connect_do to issue
264 alter session statements on database connection establishment:
265
266  ->on_connect_do("ALTER SESSION SET NLS_COMP = 'LINGUISTIC'");
267  ->on_connect_do("ALTER SESSION SET NLS_SORT = '<NLS>_CI'");
268  e.g.
269  ->on_connect_do("ALTER SESSION SET NLS_SORT = 'BINARY_CI'");
270  ->on_connect_do("ALTER SESSION SET NLS_SORT = 'GERMAN_CI'");
271
272
273 =back
274
275 =head2 Fetching data
276
277 =over 4
278
279 =item .. fetch as much data as possible in as few select calls as possible?
280
281 See the prefetch examples in the L<Cookbook|DBIx::Class::Manual::Cookbook>.
282
283 =item .. fetch a whole column of data instead of a row?
284
285 Call C<get_column> on a L<DBIx::Class::ResultSet>. This returns a
286 L<DBIx::Class::ResultSetColumn>. See its documentation and the
287 L<Cookbook|DBIx::Class::Manual::Cookbook> for details.
288
289 =item .. fetch a formatted column?
290
291 In your table schema class, create a "private" column accessor with:
292
293   __PACKAGE__->add_columns(my_column => { accessor => '_hidden_my_column' });
294
295 Then, in the same class, implement a subroutine called "my_column" that
296 fetches the real value and does the formatting you want.
297
298 See the Cookbook for more details.
299
300 =item .. fetch a single (or topmost) row?
301
302 See L<DBIx::Class::Manual::Cookbook/Retrieve_one_and_only_one_row_from_a_resultset>.
303
304 A less readable way is to ask a regular search to return 1 row, using
305 L<DBIx::Class::ResultSet/slice>:
306
307   ->search->(undef, { order_by => "id DESC" })->slice(0)
308
309 which (if supported by the database) will use LIMIT/OFFSET to hint to the
310 database that we really only need one row. This can result in a significant
311 speed improvement. The method using L<DBIx::Class::ResultSet/single> mentioned
312 in the cookbook can do the same if you pass a C<rows> attribute to the search.
313
314 =item .. refresh a row from storage?
315
316 Use L<DBIx::Class::PK/discard_changes>.
317
318   $row->discard_changes
319
320 Discarding changes and refreshing from storage are two sides fo the same coin.  When you
321 want to discard your local changes, just re-fetch the row from storage.  When you want
322 to get a new, fresh copy of the row, just re-fetch the row from storage.
323 L<DBIx::Class::PK/discard_changes> does just that by re-fetching the row from storage
324 using the row's primary key.
325
326 =item .. fetch my data a "page" at a time?
327
328 Pass the C<rows> and C<page> attributes to your search, eg:
329
330   ->search({}, { rows => 10, page => 1});
331
332 =item .. get a count of all rows even when paging?
333
334 Call C<pager> on the paged resultset, it will return a L<Data::Page>
335 object. Calling C<total_entries> on the pager will return the correct
336 total.
337
338 C<count> on the resultset will only return the total number in the page.
339
340 =back
341
342 =head2 Inserting and updating data
343
344 =over 4
345
346 =item .. insert a row with an auto incrementing primary key?
347
348 In versions of L<DBIx::Class> less than 0.07, you need to ensure your
349 table class loads the L<PK::Auto|DBIx::Class::PK::Auto>
350 component. This will attempt to fetch the value of your primary key
351 from the database after the insert has happened, and store it in the
352 created object. In versions 0.07 and above, this component is
353 automatically loaded.
354
355 =item .. insert a row with a primary key that uses a sequence?
356
357 You need to create a trigger in your database that updates your
358 primary key field from the sequence. To help PK::Auto find your
359 inserted key, you can tell it the name of the sequence in the
360 C<column_info> supplied with C<add_columns>.
361
362  ->add_columns({ id => { sequence => 'mysequence', auto_nextval => 1 } });
363
364 =item .. insert many rows of data efficiently?
365
366 The C<populate> method in L<DBIx::Class::ResultSet> provides
367 efficient bulk inserts.
368
369 =item .. update a collection of rows at the same time?
370
371 Create a resultset using a search, to filter the rows of data you
372 would like to update, then call update on the resultset to change all
373 the rows at once.
374
375 =item .. use database functions when updating rows?
376
377 =item .. update a column using data from another column?
378
379 To stop the column name from being quoted, you'll need to supply a
380 scalar reference:
381
382  ->update({ somecolumn => \'othercolumn' })
383
384 But note that when using a scalar reference the column in the database
385 will be updated but when you read the value from the object with e.g.
386
387  ->somecolumn()
388
389 you still get back the scalar reference to the string, B<not> the new
390 value in the database. To get that you must refresh the row from storage
391 using C<discard_changes()>. Or chain your function calls like this:
392
393   ->update->discard_changes
394
395 to update the database and refresh the object in one step.
396
397 =item .. store JSON/YAML in a column and have it deflate/inflate automatically?
398
399 You can use L<DBIx::Class::InflateColumn> to accomplish YAML/JSON storage transparently.
400
401 If you want to use JSON, then in your table schema class, do the following:
402
403  use JSON;
404
405  __PACKAGE__->add_columns(qw/ ... my_column ../)
406  __PACKAGE__->inflate_column('my_column', {
407      inflate => sub { jsonToObj(shift) },
408      deflate => sub { objToJson(shift) },
409  });
410
411 For YAML, in your table schema class, do the following:
412
413  use YAML;
414
415  __PACKAGE__->add_columns(qw/ ... my_column ../)
416  __PACKAGE__->inflate_column('my_column', {
417      inflate => sub { YAML::Load(shift) },
418      deflate => sub { YAML::Dump(shift) },
419  });
420
421 This technique is an easy way to store supplemental unstructured data in a table. Be
422 careful not to overuse this capability, however. If you find yourself depending more
423 and more on some data within the inflated column, then it may be time to factor that
424 data out.
425
426 =back
427
428 =head2 Custom methods in Result classes
429
430 You can add custom methods that do arbitrary things, even to unrelated tables. 
431 For example, to provide a C<< $book->foo() >> method which searches the 
432 cd table, you'd could add this to Book.pm:
433
434   sub foo {
435     my ($self, $col_data) = @_;
436     return $self->result_source->schema->resultset('cd')->search($col_data);
437   }
438
439 And invoke that on any Book Result object like so:
440
441   my $rs = $book->foo({ title => 'Down to Earth' });
442
443 When two tables ARE related, L<DBIx::Class::Relationship::Base> provides many
444 methods to find or create data in related tables for you. But if you want to
445 write your own methods, you can.
446
447 For example, to provide a C<< $book->foo() >> method to manually implement
448 what create_related() from L<DBIx::Class::Relationship::Base> does, you could 
449 add this to Book.pm:
450
451   sub foo {
452     my ($self, $relname, $col_data) = @_;
453     return $self->related_resultset($relname)->create($col_data);
454   }
455
456 Invoked like this:
457
458   my $author = $book->foo('author', { name => 'Fred' });
459
460 =head2 Misc
461
462 =over 4
463
464 =item How do I store my own (non-db) data in my DBIx::Class objects?
465
466 You can add your own data accessors to your classes.
467
468 One method is to use the built in mk_group_accessors (via L<Class::Accessor::Grouped>)
469
470         package MyTable;
471
472         use parent 'DBIx::Class';
473
474         __PACKAGE__->table('foo'); #etc
475         __PACKAGE__->mk_group_accessors('simple' => qw/non_column_data/); # must use simple group
476
477 An another method is to use L<Moose> with your L<DBIx::Class> package.
478
479         package MyTable;
480
481         use Moose; # import Moose
482         use Moose::Util::TypeConstraint; # import Moose accessor type constraints
483
484         extends 'DBIx::Class'; # Moose changes the way we define our parent (base) package
485
486         has 'non_column_data' => ( is => 'rw', isa => 'Str' ); # define a simple attribute
487
488         __PACKAGE__->table('foo'); # etc
489
490 With either of these methods the resulting use of the accesssor would be
491
492         my $row;
493
494         # assume that somewhere in here $row will get assigned to a MyTable row
495
496         $row->non_column_data('some string'); # would set the non_column_data accessor
497
498         # some other stuff happens here
499
500         $row->update(); # would not inline the non_column_data accessor into the update
501
502
503 =item How do I use DBIx::Class objects in my TT templates?
504
505 Like normal objects, mostly. However you need to watch out for TT
506 calling methods in list context. When calling relationship accessors
507 you will not get resultsets, but a list of all the related objects.
508
509 Starting with version 0.07, you can use L<DBIx::Class::ResultSet/search_rs>
510 to work around this issue.
511
512 =item See the SQL statements my code is producing?
513
514 Turn on debugging! See L<DBIx::Class::Storage> for details of how
515 to turn on debugging in the environment, pass your own filehandle to
516 save debug to, or create your own callback.
517
518 =item Why didn't my search run any SQL?
519
520 L<DBIx::Class> runs the actual SQL statement as late as possible, thus
521 if you create a resultset using C<search> in scalar context, no query
522 is executed. You can create further resultset refinements by calling
523 search again or relationship accessors. The SQL query is only run when
524 you ask the resultset for an actual row object.
525
526 =item How do I deal with tables that lack a primary key?
527
528 If your table lacks a primary key, DBIx::Class can't work out which row
529 it should operate on, for example to delete or update.  However, a
530 UNIQUE constraint on one or more columns allows DBIx::Class to uniquely
531 identify the row, so you can tell L<DBIx::Class::ResultSource> these
532 columns act as a primary key, even if they don't from the database's
533 point of view:
534
535  $resultset->set_primary_key(@column);
536
537 =item How do I make my program start faster?
538
539 Look at the tips in L<DBIx::Class::Manual::Cookbook/"STARTUP SPEED">
540
541 =item How do I reduce the overhead of database queries?
542
543 You can reduce the overhead of object creation within L<DBIx::Class>
544 using the tips in L<DBIx::Class::Manual::Cookbook/"Skip row object creation for faster results">
545 and L<DBIx::Class::Manual::Cookbook/"Get raw data for blindingly fast results">
546
547 =item How do I override a run time method (e.g. a relationship accessor)?
548
549 If you need access to the original accessor, then you must "wrap around" the original method.
550 You can do that either with L<Moose::Manual::MethodModifiers> or L<Class::Method::Modifiers>.
551 The code example works for both modules:
552
553     package Your::Schema::Group;
554     use Class::Method::Modifiers;
555     
556     # ... declare columns ...
557     
558     __PACKAGE__->has_many('group_servers', 'Your::Schema::GroupServer', 'group_id');
559     __PACKAGE__->many_to_many('servers', 'group_servers', 'server');
560     
561     # if the server group is a "super group", then return all servers
562     # otherwise return only servers that belongs to the given group
563     around 'servers' => sub {
564         my $orig = shift;
565         my $self = shift;
566
567         return $self->$orig(@_) unless $self->is_super_group;
568         return $self->result_source->schema->resultset('Server')->all;
569     };
570
571 If you just want to override the original method, and don't care about the data
572 from the original accessor, then you have two options. Either use
573 L<Method::Signatures::Simple> that does most of the work for you, or do
574 it the "dirty way".
575
576 L<Method::Signatures::Simple> way:
577
578     package Your::Schema::Group;
579     use Method::Signatures::Simple;
580     
581     # ... declare columns ...
582     
583     __PACKAGE__->has_many('group_servers', 'Your::Schema::GroupServer', 'group_id');
584     __PACKAGE__->many_to_many('servers', 'group_servers', 'server');
585     
586     # The method keyword automatically injects the annoying my $self = shift; for you.
587     method servers {
588         return $self->result_source->schema->resultset('Server')->search({ ... });
589     }
590
591 The dirty way:
592
593     package Your::Schema::Group;
594     use Sub::Name;
595     
596     # ... declare columns ...
597     
598     __PACKAGE__->has_many('group_servers', 'Your::Schema::GroupServer', 'group_id');
599     __PACKAGE__->many_to_many('servers', 'group_servers', 'server');
600     
601     *servers = subname servers => sub {
602         my $self = shift;
603         return $self->result_source->schema->resultset('Server')->search({ ... });
604     };
605     
606 =back
607
608 =head2 Notes for CDBI users
609
610 =over 4
611
612 =item Is there a way to make an object auto-stringify itself as a
613 particular column or group of columns (a-la cdbi Stringfy column
614 group, or stringify_self method) ?
615
616 See L<DBIx::Class::Manual::Cookbook/Stringification>
617
618 =back
619
620 =head2 Troubleshooting
621
622 =over 4
623
624 =item Help, I can't connect to postgresql!
625
626 If you get an error such as:
627
628   DBI connect('dbname=dbic','user',...) failed: could not connect to server:
629   No such file or directory Is the server running locally and accepting
630   connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
631
632 Likely you have/had two copies of postgresql installed simultaneously, the
633 second one will use a default port of 5433, while L<DBD::Pg> is compiled with a
634 default port of 5432.
635
636 You can change the port setting in C<postgresql.conf>.
637
638 =item I've lost or forgotten my mysql password
639
640 Stop mysqld and restart it with the --skip-grant-tables option.
641
642 Issue the following statements in the mysql client.
643
644   UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';
645   FLUSH PRIVILEGES;
646
647 Restart mysql.
648
649 Taken from:
650
651 L<http://dev.mysql.com/doc/refman/5.1/en/resetting-permissions.html>.
652
653 =back