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