38a5e523880562f47b2f287f3a74effc23771747
[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.26';
9
10 use namespace::autoclean;
11 use Carp::Clan '^Catalyst::Model::DBIC::Schema';
12 use Data::Dumper;
13 use DBIx::Class ();
14 use Moose::Autobox;
15
16 use Catalyst::Model::DBIC::Schema::Types
17     qw/ConnectInfo LoadedClass/;
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 Manual creation of a DBIx::Class::Schema and a Catalyst::Model::DBIC::Schema:
28
29 =over
30
31 =item 1.
32
33 Create the DBIx:Class schema in MyApp/Schema/FilmDB.pm:
34
35   package MyApp::Schema::FilmDB;
36   use base qw/DBIx::Class::Schema/;
37
38   __PACKAGE__->load_classes(qw/Actor Role/);
39
40 =item 2.
41
42 Create some classes for the tables in the database, for example an 
43 Actor in MyApp/Schema/FilmDB/Actor.pm:
44
45   package MyApp::Schema::FilmDB::Actor;
46   use base qw/DBIx::Class/
47
48   __PACKAGE__->load_components(qw/Core/);
49   __PACKAGE__->table('actor');
50
51   ...
52
53 and a Role in MyApp/Schema/FilmDB/Role.pm:
54
55   package MyApp::Schema::FilmDB::Role;
56   use base qw/DBIx::Class/
57
58   __PACKAGE__->load_components(qw/Core/);
59   __PACKAGE__->table('role');
60
61   ...    
62
63 Notice that the schema is in MyApp::Schema, not in MyApp::Model. This way it's 
64 usable as a standalone module and you can test/run it without Catalyst. 
65
66 =item 3.
67
68 To expose it to Catalyst as a model, you should create a DBIC Model in
69 MyApp/Model/FilmDB.pm:
70
71   package MyApp::Model::FilmDB;
72   use base qw/Catalyst::Model::DBIC::Schema/;
73
74   __PACKAGE__->config(
75       schema_class => 'MyApp::Schema::FilmDB',
76       connect_info => {
77                         dsn => "DBI:...",
78                         user => "username",
79                         password => "password",
80                       }
81   );
82
83 See below for a full list of the possible config parameters.
84
85 =back
86
87 Now you have a working Model which accesses your separate DBIC Schema. This can
88 be used/accessed in the normal Catalyst manner, via $c->model():
89
90   my $actor = $c->model('FilmDB::Actor')->find(1);
91
92 You can also use it to set up DBIC authentication with 
93 L<Catalyst::Authentication::Store::DBIx::Class> in MyApp.pm:
94
95   package MyApp;
96
97   use Catalyst qw/... Authentication .../;
98
99   ...
100
101   __PACKAGE__->config->{authentication} = 
102                 {  
103                     default_realm => 'members',
104                     realms => {
105                         members => {
106                             credential => {
107                                 class => 'Password',
108                                 password_field => 'password',
109                                 password_type => 'hashed'
110                                 password_hash_type => 'SHA-256'
111                             },
112                             store => {
113                                 class => 'DBIx::Class',
114                                 user_model => 'DB::User',
115                                 role_relation => 'roles',
116                                 role_field => 'rolename',                   
117                             }
118                         }
119                     }
120                 };
121
122 C<< $c->model('Schema::Source') >> returns a L<DBIx::Class::ResultSet> for 
123 the source name parameter passed. To find out more about which methods can 
124 be called on a ResultSet, or how to add your own methods to it, please see 
125 the ResultSet documentation in the L<DBIx::Class> distribution.
126
127 Some examples are given below:
128
129   # to access schema methods directly:
130   $c->model('FilmDB')->schema->source(...);
131
132   # to access the source object, resultset, and class:
133   $c->model('FilmDB')->source(...);
134   $c->model('FilmDB')->resultset(...);
135   $c->model('FilmDB')->class(...);
136
137   # For resultsets, there's an even quicker shortcut:
138   $c->model('FilmDB::Actor')
139   # is the same as $c->model('FilmDB')->resultset('Actor')
140
141   # To get the composed schema for making new connections:
142   my $newconn = $c->model('FilmDB')->composed_schema->connect(...);
143
144   # Or the same thing via a convenience shortcut:
145   my $newconn = $c->model('FilmDB')->connect(...);
146
147   # or, if your schema works on different storage drivers:
148   my $newconn = $c->model('FilmDB')->composed_schema->clone();
149   $newconn->storage_type('::LDAP');
150   $newconn->connection(...);
151
152   # and again, a convenience shortcut
153   my $newconn = $c->model('FilmDB')->clone();
154   $newconn->storage_type('::LDAP');
155   $newconn->connection(...);
156
157 =head1 DESCRIPTION
158
159 This is a Catalyst Model for L<DBIx::Class::Schema>-based Models.  See
160 the documentation for L<Catalyst::Helper::Model::DBIC::Schema> for
161 information on generating these Models via Helper scripts.
162
163 When your Catalyst app starts up, a thin Model layer is created as an 
164 interface to your DBIC Schema. It should be clearly noted that the model 
165 object returned by C<< $c->model('FilmDB') >> is NOT itself a DBIC schema or 
166 resultset object, but merely a wrapper proving L<methods|/METHODS> to access 
167 the underlying schema. 
168
169 In addition to this model class, a shortcut class is generated for each 
170 source in the schema, allowing easy and direct access to a resultset of the 
171 corresponding type. These generated classes are even thinner than the model 
172 class, providing no public methods but simply hooking into Catalyst's 
173 model() accessor via the 
174 L<ACCEPT_CONTEXT|Catalyst::Component/ACCEPT_CONTEXT> mechanism. The complete 
175 contents of each generated class is roughly equivalent to the following:
176
177   package MyApp::Model::FilmDB::Actor
178   sub ACCEPT_CONTEXT {
179       my ($self, $c) = @_;
180       $c->model('FilmDB')->resultset('Actor');
181   }
182
183 In short, there are three techniques available for obtaining a DBIC 
184 resultset object: 
185
186   # the long way
187   my $rs = $c->model('FilmDB')->schema->resultset('Actor');
188
189   # using the shortcut method on the model object
190   my $rs = $c->model('FilmDB')->resultset('Actor');
191
192   # using the generated class directly
193   my $rs = $c->model('FilmDB::Actor');
194
195 In order to add methods to a DBIC resultset, you cannot simply add them to 
196 the source (row, table) definition class; you must define a separate custom 
197 resultset class. See L<DBIx::Class::Manual::Cookbook/"Predefined searches"> 
198 for more info.
199
200 =head1 CONFIG PARAMETERS
201
202 =head2 schema_class
203
204 This is the classname of your L<DBIx::Class::Schema> Schema.  It needs
205 to be findable in C<@INC>, but it does not need to be inside the 
206 C<Catalyst::Model::> namespace.  This parameter is required.
207
208 =head2 connect_info
209
210 This is an arrayref of connection parameters, which are specific to your
211 C<storage_type> (see your storage type documentation for more details). 
212 If you only need one parameter (e.g. the DSN), you can just pass a string 
213 instead of an arrayref.
214
215 This is not required if C<schema_class> already has connection information
216 defined inside itself (which isn't highly recommended, but can be done)
217
218 For L<DBIx::Class::Storage::DBI>, which is the only supported
219 C<storage_type> in L<DBIx::Class> at the time of this writing, the
220 parameters are your dsn, username, password, and connect options hashref.
221
222 See L<DBIx::Class::Storage::DBI/connect_info> for a detailed explanation
223 of the arguments supported.
224
225 Examples:
226
227   connect_info => {
228     dsn => 'dbi:Pg:dbname=mypgdb',
229     user => 'postgres',
230     password => ''
231   }
232
233   connect_info => {
234     dsn => 'dbi:SQLite:dbname=foo.db',
235     on_connect_do => [
236       'PRAGMA synchronous = OFF',
237     ]
238   }
239
240   connect_info => {
241     dsn => 'dbi:Pg:dbname=mypgdb',
242     user => 'postgres',
243     password => '',
244     pg_enable_utf8 => 1,
245     on_connect_do => [
246       'some SQL statement',
247       'another SQL statement',
248     ],
249   }
250
251 Or using L<Config::General>:
252
253     <Model::FilmDB>
254         schema_class   MyApp::Schema::FilmDB
255         traits Caching
256         <connect_info>
257             dsn   dbi:Pg:dbname=mypgdb
258             user   postgres
259             password ""
260             auto_savepoint 1
261             quote_char """
262             on_connect_do   some SQL statement
263             on_connect_do   another SQL statement
264         </connect_info>
265     </Model::FilmDB>
266
267 or
268
269     <Model::FilmDB>
270         schema_class   MyApp::Schema::FilmDB
271         connect_info   dbi:SQLite:dbname=foo.db
272     </Model::FilmDB>
273
274 Or using L<YAML>:
275
276   Model::MyDB:
277       schema_class: MyDB
278       connect_info:
279           dsn: dbi:Oracle:mydb
280           user: mtfnpy
281           password: mypass
282           LongReadLen: 1000000
283           LongTruncOk: 1
284           on_connect_do: [ "alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS'" ]
285           cursor_class: 'DBIx::Class::Cursor::Cached'
286           quote_char: '"'
287
288 The old arrayref style with hashrefs for L<DBI> then L<DBIx::Class> options is also
289 supported:
290
291   connect_info => [
292     'dbi:Pg:dbname=mypgdb',
293     'postgres',
294     '',
295     {
296       pg_enable_utf8 => 1,
297     },
298     {
299       auto_savepoint => 1,
300       on_connect_do => [
301         'some SQL statement',
302         'another SQL statement',
303       ],
304     }
305   ]
306
307 =head2 traits
308
309 Array of Traits to apply to the instance. Traits are L<Moose::Role>s.
310
311 They are relative to the C<< MyApp::TraitFor::Model::DBIC::Schema:: >>, then the C<<
312 Catalyst::TraitFor::Model::DBIC::Schema:: >> namespaces, unless prefixed with C<+>
313 in which case they are taken to be a fully qualified name. E.g.:
314
315     traits Caching
316     traits +MyApp::TraitFor::Model::Foo
317
318 A new instance is created at application time, so any consumed required
319 attributes, coercions and modifiers will work.
320
321 Traits are applied at L<Catalyst::Component/COMPONENT> time using
322 L<CatalystX::Component::Traits>.
323
324 C<ref $self> will be an anon class if any traits are applied, C<<
325 $self->_original_class_name >> will be the original class.
326
327 When writing a Trait, interesting points to modify are C<BUILD>, L</setup> and
328 L</ACCEPT_CONTEXT>.
329
330 Traits that come with the distribution:
331
332 =over 4
333
334 =item L<Catalyst::TraitFor::Model::DBIC::Schema::Caching>
335
336 =item L<Catalyst::TraitFor::Model::DBIC::Schema::Replicated>
337
338 =back
339
340 =head2 storage_type
341
342 Allows the use of a different C<storage_type> than what is set in your
343 C<schema_class> (which in turn defaults to C<::DBI> if not set in current
344 L<DBIx::Class>).  Completely optional, and probably unnecessary for most
345 people until other storage backends become available for L<DBIx::Class>.
346
347 =head1 ATTRIBUTES
348
349 The keys you pass in the model configuration are available as attributes.
350
351 Other attributes available:
352
353 =head2 connect_info
354
355 Your connect_info args normalized to hashref form (with dsn/user/password.) See
356 L<DBIx::Class::Storage::DBI/connect_info> for more info on the hashref form of
357 L</connect_info>.
358
359 =head2 model_name
360
361 The model name L<Catalyst> uses to resolve this model, the part after
362 C<::Model::> or C<::M::> in your class name. E.g. if your class name is
363 C<MyApp::Model::DB> the L</model_name> will be C<DB>.
364
365 =head2 _default_cursor_class
366
367 What to reset your L<DBIx::Class::Storage::DBI/cursor_class> to if a custom one
368 doesn't work out. Defaults to L<DBIx::Class::Storage::DBI::Cursor>.
369
370 =head1 ATTRIBUTES FROM L<MooseX::Traits::Pluggable>
371
372 =head2 _original_class_name
373
374 The class name of your model before any L</traits> are applied. E.g.
375 C<MyApp::Model::DB>.
376
377 =head2 _traits
378
379 Unresolved arrayref of traits passed in the config.
380
381 =head2 _resolved_traits
382
383 Traits you used resolved to full class names.
384
385 =head1 METHODS
386
387 =head2 new
388
389 Instantiates the Model based on the above-documented ->config parameters.
390 The only required parameter is C<schema_class>.  C<connect_info> is
391 required in the case that C<schema_class> does not already have connection
392 information defined for it.
393
394 =head2 schema
395
396 Accessor which returns the connected schema being used by the this model.
397 There are direct shortcuts on the model class itself for
398 schema->resultset, schema->source, and schema->class.
399
400 =head2 composed_schema
401
402 Accessor which returns the composed schema, which has no connection info,
403 which was used in constructing the C<schema> above.  Useful for creating
404 new connections based on the same schema/model.  There are direct shortcuts
405 from the model object for composed_schema->clone and composed_schema->connect
406
407 =head2 clone
408
409 Shortcut for ->composed_schema->clone
410
411 =head2 connect
412
413 Shortcut for ->composed_schema->connect
414
415 =head2 source
416
417 Shortcut for ->schema->source
418
419 =head2 class
420
421 Shortcut for ->schema->class
422
423 =head2 resultset
424
425 Shortcut for ->schema->resultset
426
427 =head2 storage
428
429 Provides an accessor for the connected schema's storage object.
430 Used often for debugging and controlling transactions.
431
432 =cut
433
434 has schema => (is => 'rw', isa => 'DBIx::Class::Schema');
435
436 has schema_class => (
437     is => 'ro',
438     isa => LoadedClass,
439     coerce => 1,
440     required => 1
441 );
442
443 has storage_type => (is => 'rw', isa => Str);
444
445 has connect_info => (is => 'rw', isa => ConnectInfo, coerce => 1);
446
447 has model_name => (
448     is => 'ro',
449     isa => Str,
450     required => 1,
451     lazy_build => 1,
452 );
453
454 has _default_cursor_class => (
455     is => 'ro',
456     isa => LoadedClass,
457     default => 'DBIx::Class::Storage::DBI::Cursor',
458     coerce => 1
459 );
460
461 sub BUILD {
462     my $self = shift;
463     my $class = $self->_original_class_name;
464     my $schema_class = $self->schema_class;
465
466     if( !$self->connect_info ) {
467         if($schema_class->storage && $schema_class->storage->connect_info) {
468             $self->connect_info($schema_class->storage->connect_info);
469         }
470         else {
471             die "Either ->config->{connect_info} must be defined for $class"
472                   . " or $schema_class must have connect info defined on it."
473                   . " Here's what we got:\n"
474                   . Dumper($self);
475         }
476     }
477
478     if (exists $self->connect_info->{cursor_class}) {
479         eval { Class::MOP::load_class($self->connect_info->{cursor_class}) }
480             or croak "invalid connect_info: Cannot load your cursor_class"
481         . " ".$self->connect_info->{cursor_class}.": $@";
482     }
483
484     $self->setup;
485
486     $self->composed_schema($schema_class->compose_namespace($class));
487
488     $self->schema($self->composed_schema->clone);
489
490     $self->schema->storage_type($self->storage_type)
491         if $self->storage_type;
492
493     $self->schema->connection($self->connect_info);
494
495     $self->_install_rs_models;
496 }
497
498 sub clone { shift->composed_schema->clone(@_); }
499
500 sub connect { shift->composed_schema->connect(@_); }
501
502 sub storage { shift->schema->storage(@_); }
503
504 sub resultset { shift->schema->resultset(@_); }
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 =cut
512
513 sub setup { 1 }
514
515 =head2 ACCEPT_CONTEXT
516
517 Point of extension for doing things at C<< $c->model >> time with context,
518 returns the model instance, see L<Catalyst::Manual::Intro/ACCEPT_CONTEXT> for
519 more information.
520
521 =cut
522
523 sub ACCEPT_CONTEXT { shift }
524
525 sub _install_rs_models {
526     my $self  = shift;
527     my $class = $self->_original_class_name;
528
529     no strict 'refs';
530
531     my @sources = $self->schema->sources;
532
533     die "No sources found (did you forget to define your tables?)"
534         unless @sources;
535
536     foreach my $moniker (@sources) {
537         my $classname = "${class}::$moniker";
538         *{"${classname}::ACCEPT_CONTEXT"} = sub {
539             shift;
540             shift->model($self->model_name)->resultset($moniker);
541         }
542     }
543 }
544
545 sub _reset_cursor_class {
546     my $self = shift;
547
548     if ($self->storage->can('cursor_class')) {
549         $self->storage->cursor_class($self->_default_cursor_class)
550             if $self->storage->cursor_class ne $self->_default_cursor_class;
551     }
552 }
553
554 {
555     my %COMPOSED_CACHE;
556
557     sub composed_schema {
558         my $self = shift;
559         my $class = $self->_original_class_name;
560         my $store = \$COMPOSED_CACHE{$class}{$self->schema_class};
561
562         $$store = shift if @_;
563
564         return $$store
565     }
566 }
567
568 sub _build_model_name {
569     my $self  = shift;
570     my $class = $self->_original_class_name;
571     (my $model_name = $class) =~ s/^[\w:]+::(?:Model|M):://;
572
573     return $model_name;
574 }
575
576 __PACKAGE__->meta->make_immutable;
577
578 =head1 SEE ALSO
579
580 General Catalyst Stuff:
581
582 L<Catalyst::Manual>, L<Catalyst::Test>, L<Catalyst::Request>,
583 L<Catalyst::Response>, L<Catalyst::Helper>, L<Catalyst>,
584
585 Stuff related to DBIC and this Model style:
586
587 L<DBIx::Class>, L<DBIx::Class::Schema>,
588 L<DBIx::Class::Schema::Loader>, L<Catalyst::Helper::Model::DBIC::Schema>,
589 L<MooseX::Object::Pluggable>
590
591 Traits:
592
593 L<Catalyst::TraitFor::Model::DBIC::Schema::Caching>,
594 L<Catalyst::TraitFor::Model::DBIC::Schema::Replicated>
595
596 =head1 AUTHOR
597
598 Brandon L Black, C<blblack at gmail.com>
599
600 Contributors:
601
602 Rafael Kitover, C<rkitover at cpan.org>
603
604 =head1 COPYRIGHT
605
606 This program is free software, you can redistribute it and/or modify it
607 under the same terms as Perl itself.
608
609 =cut
610
611 1;
612 # vim:sts=4 sw=4 et: