release 0.46
[catagits/Catalyst-Model-DBIC-Schema.git] / lib / Catalyst / Model / DBIC / Schema.pm
1 package Catalyst::Model::DBIC::Schema;
2
3 use Moose;
4 use mro 'c3';
5 extends 'Catalyst::Model';
6 with 'CatalystX::Component::Traits';
7
8 our $VERSION = '0.46';
9 $VERSION = eval $VERSION;
10
11 use namespace::autoclean;
12 use Carp::Clan '^Catalyst::Model::DBIC::Schema';
13 use Data::Dumper;
14 use DBIx::Class ();
15
16 use Catalyst::Model::DBIC::Schema::Types
17     qw/ConnectInfo LoadedClass SchemaClass Schema/;
18
19 use MooseX::Types::Moose qw/ArrayRef Str ClassName Undef/;
20
21 =head1 NAME
22
23 Catalyst::Model::DBIC::Schema - DBIx::Class::Schema Model Class
24
25 =head1 SYNOPSIS
26
27 First, prepare your database schema using L<DBIx::Class>, see
28 L<Catalyst::Helper::Model::DBIC::Schema> for how to generate a
29 L<DBIx::Class::Schema> from your database using the Helper script, and
30 L<DBIx::Class::Schema::Loader::Base>.
31
32 A typical usage of the helper script would be:
33
34     script/myapp_create.pl model FilmDB DBIC::Schema MyApp::Schema::FilmDB \
35         create=static dbi:mysql:filmdb dbusername dbpass \
36         quote_char='`' name_sep='.'
37
38 If you are unfamiliar with L<DBIx::Class>, see L<DBIx::Class::Manual::Intro>
39 first.
40
41 These examples assume that you already have a schema called
42 C<MyApp::Schema::FilmDB>, which defines some Result classes for tables in
43 C<MyApp::Schema::FilmDB::Result::Actor> and
44 C<MyApp::Schema::FilmDB::Result::Film>. Either created by the helper script (as
45 shown above) or manually.
46
47 The helper also creates a Model in C<lib/MyApp/Model/FilmDB.pm>, if you already
48 have a schema you can create just the Model using:
49
50     script/myapp_create.pl model FilmDB DBIC::Schema MyApp::Schema::FilmDB
51         dbi:mysql:filmdb dbusername dbpass
52
53 The connect_info is optional and will be hardcoded into the Model if provided.
54 It's better to configure it in your L<Catalyst> config file, which will also
55 override any hardcoded config, see L</connect_info> for examples.
56
57 Now you have a working Model which accesses your separate DBIC Schema. This can
58 be used/accessed in the normal Catalyst manner, via C<< $c->model() >>:
59
60   my $db_model = $c->model('FilmDB');         # a Catalyst::Model
61   my $dbic     = $c->model('FilmDB')->schema; # the actual DBIC object
62
63 There is also a shortcut, which returns a L<DBIx::Class::ResultSet> directly,
64 instead of a L<Catalyst::Model>:
65
66   my $rs = $c->model('FilmDB::Actor');
67
68 See L<DBIx::Class::ResultSet> to find out more about which methods can be
69 called on ResultSets.
70
71 You can also define your own ResultSet methods to encapsulate the
72 database/business logic of your applications. These go into, for example,
73 C<lib/MyApp/Schema/FilmDB/ResultSet/Actor.pm>. The class must inherit from
74 L<DBIx::Class::ResultSet> and is automatically loaded.
75
76 Then call your methods like any other L<DBIx::Class::ResultSet> method:
77
78     $c->model('FilmDB::Actor')->SAG_members
79
80 =head2 Some examples:
81
82   # to access schema methods directly:
83   $c->model('FilmDB')->schema->source(...);
84
85   # to access the source object, resultset, and class:
86   $c->model('FilmDB')->source(...);
87   $c->model('FilmDB')->resultset(...);
88   $c->model('FilmDB')->class(...);
89
90   # For resultsets, there's an even quicker shortcut:
91   $c->model('FilmDB::Actor')
92   # is the same as $c->model('FilmDB')->resultset('Actor')
93
94   # To get the composed schema for making new connections:
95   my $newconn = $c->model('FilmDB')->composed_schema->connect(...);
96
97   # Or the same thing via a convenience shortcut:
98   my $newconn = $c->model('FilmDB')->connect(...);
99
100   # or, if your schema works on different storage drivers:
101   my $newconn = $c->model('FilmDB')->composed_schema->clone();
102   $newconn->storage_type('::LDAP');
103   $newconn->connection(...);
104
105   # and again, a convenience shortcut
106   my $newconn = $c->model('FilmDB')->clone();
107   $newconn->storage_type('::LDAP');
108   $newconn->connection(...);
109
110 To set up authentication, see L</"Setting up DBIC authentication"> below.
111
112 =head1 DESCRIPTION
113
114 This is a Catalyst Model for L<DBIx::Class::Schema>-based Models.  See
115 the documentation for L<Catalyst::Helper::Model::DBIC::Schema> for
116 information on generating these Models via Helper scripts.
117
118 When your Catalyst app starts up, a thin Model layer is created as an interface
119 to your DBIC Schema. It should be clearly noted that the model object returned
120 by C<< $c->model('FilmDB') >> is NOT itself a DBIC schema or resultset object,
121 but merely a wrapper proving L<methods|/METHODS> to access the underlying
122 schema.
123
124 In addition to this model class, a shortcut class is generated for each 
125 source in the schema, allowing easy and direct access to a resultset of the 
126 corresponding type. These generated classes are even thinner than the model 
127 class, providing no public methods but simply hooking into Catalyst's 
128 model() accessor via the 
129 L<ACCEPT_CONTEXT|Catalyst::Component/ACCEPT_CONTEXT> mechanism. The complete 
130 contents of each generated class is roughly equivalent to the following:
131
132   package MyApp::Model::FilmDB::Actor
133   sub ACCEPT_CONTEXT {
134       my ($self, $c) = @_;
135       $c->model('FilmDB')->resultset('Actor');
136   }
137
138 In short, there are three techniques available for obtaining a DBIC 
139 resultset object: 
140
141   # the long way
142   my $rs = $c->model('FilmDB')->schema->resultset('Actor');
143
144   # using the shortcut method on the model object
145   my $rs = $c->model('FilmDB')->resultset('Actor');
146
147   # using the generated class directly
148   my $rs = $c->model('FilmDB::Actor');
149
150 In order to add methods to a DBIC resultset, you cannot simply add them to 
151 the source (row, table) definition class; you must define a separate custom 
152 resultset class. This is just a matter of making a
153 C<lib/MyApp/Schema/ResultSet/Actor.pm> class that inherits from
154 L<DBIx::Class::ResultSet>, if you are using
155 L<DBIx::Class::Schema/load_namespaces>, the default for helper script generated
156 schemas.
157
158 See L<DBIx::Class::Manual::Cookbook/"Predefined searches"> 
159 for information on definining your own L<DBIx::Class::ResultSet> classes for
160 use with L<DBIx::Class::Schema/load_classes>, the old default.
161
162 =head1 CONFIG PARAMETERS
163
164 =head2 schema_class
165
166 This is the classname of your L<DBIx::Class::Schema> Schema.  It needs
167 to be findable in C<@INC>, but it does not need to be inside the 
168 C<Catalyst::Model::> namespace.  This parameter is required.
169
170 =head2 connect_info
171
172 This is an arrayref of connection parameters, which are specific to your
173 C<storage_type> (see your storage type documentation for more details). 
174 If you only need one parameter (e.g. the DSN), you can just pass a string 
175 instead of an arrayref.
176
177 This is not required if C<schema_class> already has connection information
178 defined inside itself (which isn't highly recommended, but can be done)
179
180 For L<DBIx::Class::Storage::DBI>, which is the only supported
181 C<storage_type> in L<DBIx::Class> at the time of this writing, the
182 parameters are your dsn, username, password, and connect options hashref.
183
184 See L<DBIx::Class::Storage::DBI/connect_info> for a detailed explanation
185 of the arguments supported.
186
187 Examples:
188
189   connect_info => {
190     dsn => 'dbi:Pg:dbname=mypgdb',
191     user => 'postgres',
192     password => ''
193   }
194
195   connect_info => {
196     dsn => 'dbi:SQLite:dbname=foo.db',
197     on_connect_do => [
198       'PRAGMA synchronous = OFF',
199     ]
200   }
201
202   connect_info => {
203     dsn => 'dbi:Pg:dbname=mypgdb',
204     user => 'postgres',
205     password => '',
206     pg_enable_utf8 => 1,
207     on_connect_do => [
208       'some SQL statement',
209       'another SQL statement',
210     ],
211   }
212
213 Or using L<Config::General>:
214
215     <Model::FilmDB>
216         schema_class   MyApp::Schema::FilmDB
217         traits Caching
218         <connect_info>
219             dsn   dbi:Pg:dbname=mypgdb
220             user   postgres
221             password ""
222             auto_savepoint 1
223             quote_char """
224             on_connect_do   some SQL statement
225             on_connect_do   another SQL statement
226         </connect_info>
227         user_defined_schema_accessor foo
228     </Model::FilmDB>
229
230 or
231
232     <Model::FilmDB>
233         schema_class   MyApp::Schema::FilmDB
234         connect_info   dbi:SQLite:dbname=foo.db
235     </Model::FilmDB>
236
237 Or using L<YAML>:
238
239   Model::MyDB:
240       schema_class: MyDB
241       traits: Caching
242       connect_info:
243           dsn: dbi:Oracle:mydb
244           user: mtfnpy
245           password: mypass
246           LongReadLen: 1000000
247           LongTruncOk: 1
248           on_connect_call: 'datetime_setup'
249           quote_char: '"'
250
251 The old arrayref style with hashrefs for L<DBI> then L<DBIx::Class> options is also
252 supported:
253
254   connect_info => [
255     'dbi:Pg:dbname=mypgdb',
256     'postgres',
257     '',
258     {
259       pg_enable_utf8 => 1,
260     },
261     {
262       auto_savepoint => 1,
263       on_connect_do => [
264         'some SQL statement',
265         'another SQL statement',
266       ],
267     }
268   ]
269
270 =head2 traits
271
272 Array of Traits to apply to the instance. Traits are L<Moose::Role>s.
273
274 They are relative to the C<< MyApp::TraitFor::Model::DBIC::Schema:: >>, then
275 the C<< Catalyst::TraitFor::Model::DBIC::Schema:: >> namespaces, unless
276 prefixed with C<+> in which case they are taken to be a fully qualified name.
277 E.g.:
278
279     traits Caching
280     traits +MyApp::TraitFor::Model::Foo
281
282 A new instance is created at application time, so any consumed required
283 attributes, coercions and modifiers will work.
284
285 Traits are applied at L<Catalyst::Component/COMPONENT> time using
286 L<CatalystX::Component::Traits>.
287
288 C<ref $self> will be an anon class if any traits are applied, C<<
289 $self->_original_class_name >> will be the original class.
290
291 When writing a Trait, interesting points to modify are C<BUILD>, L</setup> and
292 L</ACCEPT_CONTEXT>.
293
294 Traits that come with the distribution:
295
296 =over 4
297
298 =item L<Catalyst::TraitFor::Model::DBIC::Schema::Caching>
299
300 =item L<Catalyst::TraitFor::Model::DBIC::Schema::Replicated>
301
302 =item L<Catalyst::TraitFor::Model::DBIC::Schema::SchemaProxy>
303
304 =back
305
306 =head2 storage_type
307
308 Allows the use of a different C<storage_type> than what is set in your
309 C<schema_class> (which in turn defaults to C<::DBI> if not set in current
310 L<DBIx::Class>).  Completely optional, and probably unnecessary for most
311 people until other storage backends become available for L<DBIx::Class>.
312
313 =head1 ATTRIBUTES
314
315 The keys you pass in the model configuration are available as attributes.
316
317 Other attributes available:
318
319 =head2 connect_info
320
321 Your connect_info args normalized to hashref form (with dsn/user/password.) See
322 L<DBIx::Class::Storage::DBI/connect_info> for more info on the hashref form of
323 L</connect_info>.
324
325 =head2 model_name
326
327 The model name L<Catalyst> uses to resolve this model, the part after
328 C<::Model::> or C<::M::> in your class name. E.g. if your class name is
329 C<MyApp::Model::DB> the L</model_name> will be C<DB>.
330
331 =head2 _default_cursor_class
332
333 What to reset your L<DBIx::Class::Storage::DBI/cursor_class> to if a custom one
334 doesn't work out. Defaults to L<DBIx::Class::Storage::DBI::Cursor>.
335
336 =head1 ATTRIBUTES FROM L<MooseX::Traits::Pluggable>
337
338 =head2 _original_class_name
339
340 The class name of your model before any L</traits> are applied. E.g.
341 C<MyApp::Model::DB>.
342
343 =head2 _traits
344
345 Unresolved arrayref of traits passed in the config.
346
347 =head2 _resolved_traits
348
349 Traits you used resolved to full class names.
350
351 =head1 CONFIGURING YOUR SCHEMA AND RESULTSETS
352
353 See the documentation for
354 L<Catalyst::TraitFor::Model::DBIC::Schema::SchemaProxy> for instructions on how
355 to pass config values from your L<Catalyst> config to your
356 L<DBIx::Class::Schema> and/or L<DBIx::Class::ResultSet> classes.
357
358 =head1 METHODS
359
360 =head2 new
361
362 Instantiates the Model based on the above-documented ->config parameters.
363 The only required parameter is C<schema_class>.  C<connect_info> is
364 required in the case that C<schema_class> does not already have connection
365 information defined for it.
366
367 =head2 schema
368
369 Accessor which returns the connected schema being used by the this model.
370 There are direct shortcuts on the model class itself for
371 schema->resultset, schema->source, and schema->class.
372
373 =head2 composed_schema
374
375 Accessor which returns the composed schema, which has no connection info,
376 which was used in constructing the C<schema> above.  Useful for creating
377 new connections based on the same schema/model.  There are direct shortcuts
378 from the model object for composed_schema->clone and composed_schema->connect
379
380 =head2 clone
381
382 Shortcut for ->composed_schema->clone
383
384 =head2 connect
385
386 Shortcut for ->composed_schema->connect
387
388 =head2 source
389
390 Shortcut for ->schema->source
391
392 =head2 class
393
394 Shortcut for ->schema->class
395
396 =head2 resultset
397
398 Shortcut for ->schema->resultset
399
400 =head2 txn_do
401
402 Shortcut for ->schema->txn_do
403
404 =head2 txn_scope_guard
405
406 Shortcut for ->schema->txn_scope_guard
407
408 =head2 storage
409
410 Provides an accessor for the connected schema's storage object.
411
412 See L<DBIx::Class::Storage> and L<DBIx::Class::Storage::DBI>.
413
414 =cut
415
416 has schema_class => (
417     is => 'ro',
418     isa => SchemaClass,
419     coerce => 1,
420     required => 1
421 );
422
423 has storage_type => (is => 'rw', isa => Str);
424
425 has connect_info => (is => 'rw', isa => ConnectInfo, coerce => 1);
426
427 has model_name => (
428     is => 'ro',
429     isa => Str,
430     required => 1,
431     lazy_build => 1,
432 );
433
434 has _default_cursor_class => (
435     is => 'ro',
436     isa => LoadedClass,
437     default => 'DBIx::Class::Storage::DBI::Cursor',
438     coerce => 1
439 );
440
441 has schema => (is => 'rw', isa => Schema);
442
443 my $app_class;
444
445 before COMPONENT => sub {
446     $app_class = ref $_[1] || $_[1];
447 };
448
449 sub app_class { $app_class }
450
451 sub BUILD {
452     my ($self, $args) = @_;
453     my $class = $self->_original_class_name;
454     my $schema_class = $self->schema_class;
455
456     if( !$self->connect_info ) {
457         if($schema_class->storage && $schema_class->storage->connect_info) {
458             $self->connect_info($schema_class->storage->connect_info);
459         }
460         else {
461             die "Either ->config->{connect_info} must be defined for $class"
462                   . " or $schema_class must have connect info defined on it."
463                   . " Here's what we got:\n"
464                   . Dumper($args);
465         }
466     }
467
468     if (exists $self->connect_info->{cursor_class}) {
469         eval { Class::MOP::load_class($self->connect_info->{cursor_class}) }
470             or croak "invalid connect_info: Cannot load your cursor_class"
471         . " ".$self->connect_info->{cursor_class}.": $@";
472     }
473
474     $self->setup($args);
475
476     my $is_installed = defined $self->composed_schema;
477
478     $self->composed_schema($schema_class->compose_namespace($class))
479         unless $is_installed;
480
481     $self->schema($self->composed_schema->clone)
482         unless $self->schema;
483
484     $self->schema->storage_type($self->storage_type)
485         if $self->storage_type;
486
487     $self->schema->connection($self->connect_info);
488
489     $self->_install_rs_models unless $is_installed;
490 }
491
492 sub clone { shift->composed_schema->clone(@_); }
493
494 sub connect { shift->composed_schema->connect(@_); }
495
496 # some proxy methods, see also SchemaProxy
497
498 sub resultset { shift->schema->resultset(@_); }
499
500 sub txn_do { shift->schema->txn_do(@_); }
501
502 sub txn_scope_guard { shift->schema->txn_scope_guard(@_); }
503
504 sub storage { shift->schema->storage(@_); }
505
506 =head2 setup
507
508 Called at C<BUILD> time before configuration, but after L</connect_info> is
509 set. To do something after configuuration use C<< after BUILD => >>.
510
511 Receives a hashref of args passed to C<BUILD>.
512
513 =cut
514
515 sub setup { 1 }
516
517 =head2 ACCEPT_CONTEXT
518
519 Point of extension for doing things at C<< $c->model >> time with context,
520 returns the model instance, see L<Catalyst::Manual::Intro/ACCEPT_CONTEXT> for
521 more information.
522
523 =cut
524
525 sub ACCEPT_CONTEXT { shift }
526
527 sub _install_rs_models {
528     my $self  = shift;
529     my $class = $self->_original_class_name;
530
531     no strict 'refs';
532
533     my @sources = $self->schema->sources;
534
535     unless (@sources) {
536         warn <<'EOF' unless $ENV{CMDS_NO_SOURCES};
537 ******************************* WARNING ***************************************
538 * No sources found (did you forget to define your tables?)                    *
539 *                                                                             *
540 * To turn off this warning, set the CMDS_NO_SOURCES environment variable.     *
541 *******************************************************************************
542 EOF
543     }
544
545     foreach my $moniker (@sources) {
546         my $classname = "${class}::$moniker";
547         *{"${classname}::ACCEPT_CONTEXT"} = sub {
548             shift;
549             shift->model($self->model_name)->resultset($moniker);
550         }
551     }
552 }
553
554 sub _reset_cursor_class {
555     my $self = shift;
556
557     if ($self->storage->can('cursor_class')) {
558         $self->storage->cursor_class($self->_default_cursor_class)
559             if $self->storage->cursor_class ne $self->_default_cursor_class;
560     }
561 }
562
563 {
564     my %COMPOSED_CACHE;
565
566     sub composed_schema {
567         my $self = shift;
568         my $class = $self->_original_class_name;
569         my $store = \$COMPOSED_CACHE{$class}{$self->schema_class};
570
571         $$store = shift if @_;
572
573         return $$store
574     }
575 }
576
577 sub _build_model_name {
578     my $self  = shift;
579     my $class = $self->_original_class_name;
580     (my $model_name = $class) =~ s/^[\w:]+::(?:Model|M):://;
581
582     return $model_name;
583 }
584
585 __PACKAGE__->meta->make_immutable;
586
587 =head1 ENVIRONMENT
588
589 =over 4
590
591 =item CMDS_NO_SOURCES
592
593 Set this variable if you will be using schemas with no sources (Result classes)
594 to disable the warning. The warning is there because having no Result classes
595 is usually a mistake.
596
597 =back
598
599 =head1 Setting up DBIC authentication
600
601 You can set this up with 
602 L<Catalyst::Authentication::Store::DBIx::Class> in MyApp.pm:
603
604   package MyApp;
605
606   use Catalyst qw/... Authentication .../;
607
608   ...
609
610   __PACKAGE__->config('Plugin::Authentication' =>
611                 {
612                     default_realm => 'members',
613                     members => {
614                         credential => {
615                             class => 'Password',
616                             password_field => 'password',
617                             password_type => 'hashed'
618                             password_hash_type => 'SHA-256'
619                         },
620                         store => {
621                             class => 'DBIx::Class',
622                             user_model => 'DB::User',
623                             role_relation => 'roles',
624                             role_field => 'rolename',
625                         }
626                     }
627                 });
628
629 =head1 METHOD PROXYING
630
631 The automatic proxying to the underlying L<DBIx::Class::Schema> has been
632 removed as of version C<0.34>, to enable this feature add C<SchemaProxy> to
633 L</traits>.
634
635 See L<Catalyst::TraitFor::Model::DBIC::Schema::SchemaProxy>.
636
637 =head1 SEE ALSO
638
639 General Catalyst Stuff:
640
641 L<Catalyst::Manual>, L<Catalyst::Test>, L<Catalyst::Request>,
642 L<Catalyst::Response>, L<Catalyst::Helper>, L<Catalyst>,
643
644 Stuff related to DBIC and this Model style:
645
646 L<DBIx::Class>, L<DBIx::Class::Schema>,
647 L<DBIx::Class::Schema::Loader>, L<Catalyst::Helper::Model::DBIC::Schema>,
648 L<CatalystX::Component::Traits>, L<MooseX::Traits::Pluggable>
649
650 Traits:
651
652 L<Catalyst::TraitFor::Model::DBIC::Schema::Caching>,
653 L<Catalyst::TraitFor::Model::DBIC::Schema::Replicated>,
654 L<Catalyst::TraitFor::Model::DBIC::Schema::SchemaProxy>,
655 L<Catalyst::TraitFor::Model::DBIC::Schema::QueryLog>
656
657 =head1 AUTHOR
658
659 Brandon L Black C<blblack at gmail.com>
660
661 =head1 CONTRIBUTORS
662
663 caelum: Rafael Kitover C<rkitover at cpan.org>
664
665 dandv: Dan Dascalescu C<dandv at cpan.org>
666
667 bluefeet: Aran Deltac C<bluefeet@cpan.org>
668
669 t0m: Tomas Doran C<bobtfish@bobtfish.net>
670
671 osfameron: C<osfameron@cpan.org>
672
673 ozum: Ozum Eldogan C<ozum@ozum.net>
674
675 Pavel I. Shaydo C<zwon@trinitum.org>
676
677 =head1 COPYRIGHT
678
679 Copyright (c) 2006 - 2010
680 the Catalyst::Model::DBIC::Schema L</AUTHOR> and L</CONTRIBUTORS>
681 as listed above.
682
683 =head1 LICENSE
684
685 This program is free software. You can redistribute it and/or modify it
686 under the same terms as Perl itself.
687
688 =cut
689
690 1;
691 # vim:sts=4 sw=4 et tw=80: