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