C::H::M::DBIC::Schema - convert to Moose
[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 'MooseX::Object::Pluggable';
7
8 our $VERSION = '0.24';
9
10 use Carp::Clan '^Catalyst::Model::DBIC::Schema';
11 use Data::Dumper;
12 use DBIx::Class ();
13 use Scalar::Util 'reftype';
14 use MooseX::ClassAttribute;
15 use Moose::Autobox;
16
17 use Catalyst::Model::DBIC::Schema::Types qw/ConnectInfo SchemaClass/;
18
19 use namespace::clean -except => 'meta';
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 Authentication::Store::DBIC in MyApp.pm:
94
95   package MyApp;
96
97   use Catalyst qw/... Authentication::Store::DBIC/;
98
99   ...
100
101   __PACKAGE__->config->{authentication}{dbic} = {
102       user_class      => 'FilmDB::Actor',
103       user_field      => 'name',
104       password_field  => 'password'
105   }
106
107 C<< $c->model('Schema::Source') >> returns a L<DBIx::Class::ResultSet> for 
108 the source name parameter passed. To find out more about which methods can 
109 be called on a ResultSet, or how to add your own methods to it, please see 
110 the ResultSet documentation in the L<DBIx::Class> distribution.
111
112 Some examples are given below:
113
114   # to access schema methods directly:
115   $c->model('FilmDB')->schema->source(...);
116
117   # to access the source object, resultset, and class:
118   $c->model('FilmDB')->source(...);
119   $c->model('FilmDB')->resultset(...);
120   $c->model('FilmDB')->class(...);
121
122   # For resultsets, there's an even quicker shortcut:
123   $c->model('FilmDB::Actor')
124   # is the same as $c->model('FilmDB')->resultset('Actor')
125
126   # To get the composed schema for making new connections:
127   my $newconn = $c->model('FilmDB')->composed_schema->connect(...);
128
129   # Or the same thing via a convenience shortcut:
130   my $newconn = $c->model('FilmDB')->connect(...);
131
132   # or, if your schema works on different storage drivers:
133   my $newconn = $c->model('FilmDB')->composed_schema->clone();
134   $newconn->storage_type('::LDAP');
135   $newconn->connection(...);
136
137   # and again, a convenience shortcut
138   my $newconn = $c->model('FilmDB')->clone();
139   $newconn->storage_type('::LDAP');
140   $newconn->connection(...);
141
142 =head1 DESCRIPTION
143
144 This is a Catalyst Model for L<DBIx::Class::Schema>-based Models.  See
145 the documentation for L<Catalyst::Helper::Model::DBIC::Schema> for
146 information on generating these Models via Helper scripts.
147
148 When your Catalyst app starts up, a thin Model layer is created as an 
149 interface to your DBIC Schema. It should be clearly noted that the model 
150 object returned by C<< $c->model('FilmDB') >> is NOT itself a DBIC schema or 
151 resultset object, but merely a wrapper proving L<methods|/METHODS> to access 
152 the underlying schema. 
153
154 In addition to this model class, a shortcut class is generated for each 
155 source in the schema, allowing easy and direct access to a resultset of the 
156 corresponding type. These generated classes are even thinner than the model 
157 class, providing no public methods but simply hooking into Catalyst's 
158 model() accessor via the 
159 L<ACCEPT_CONTEXT|Catalyst::Component/ACCEPT_CONTEXT> mechanism. The complete 
160 contents of each generated class is roughly equivalent to the following:
161
162   package MyApp::Model::FilmDB::Actor
163   sub ACCEPT_CONTEXT {
164       my ($self, $c) = @_;
165       $c->model('FilmDB')->resultset('Actor');
166   }
167
168 In short, there are three techniques available for obtaining a DBIC 
169 resultset object: 
170
171   # the long way
172   my $rs = $c->model('FilmDB')->schema->resultset('Actor');
173
174   # using the shortcut method on the model object
175   my $rs = $c->model('FilmDB')->resultset('Actor');
176
177   # using the generated class directly
178   my $rs = $c->model('FilmDB::Actor');
179
180 In order to add methods to a DBIC resultset, you cannot simply add them to 
181 the source (row, table) definition class; you must define a separate custom 
182 resultset class. See L<DBIx::Class::Manual::Cookbook/"Predefined searches"> 
183 for more info.
184
185 =head1 CONFIG PARAMETERS
186
187 =over 4
188
189 =item schema_class
190
191 This is the classname of your L<DBIx::Class::Schema> Schema.  It needs
192 to be findable in C<@INC>, but it does not need to be inside the 
193 C<Catalyst::Model::> namespace.  This parameter is required.
194
195 =item connect_info
196
197 This is an arrayref of connection parameters, which are specific to your
198 C<storage_type> (see your storage type documentation for more details). 
199 If you only need one parameter (e.g. the DSN), you can just pass a string 
200 instead of an arrayref.
201
202 This is not required if C<schema_class> already has connection information
203 defined inside itself (which isn't highly recommended, but can be done)
204
205 For L<DBIx::Class::Storage::DBI>, which is the only supported
206 C<storage_type> in L<DBIx::Class> at the time of this writing, the
207 parameters are your dsn, username, password, and connect options hashref.
208
209 See L<DBIx::Class::Storage::DBI/connect_info> for a detailed explanation
210 of the arguments supported.
211
212 Examples:
213
214   connect_info => {
215     dsn => 'dbi:Pg:dbname=mypgdb',
216     user => 'postgres',
217     password => ''
218   }
219
220   connect_info => {
221     dsn => 'dbi:SQLite:dbname=foo.db',
222     on_connect_do => [
223       'PRAGMA synchronous = OFF',
224     ]
225   }
226
227   connect_info => {
228     dsn => 'dbi:Pg:dbname=mypgdb',
229     user => 'postgres',
230     password => '',
231     pg_enable_utf8 => 1,
232     on_connect_do => [
233       'some SQL statement',
234       'another SQL statement',
235     ],
236   }
237
238 Or using L<Config::General>:
239
240     <Model::FilmDB>
241         schema_class   MyApp::Schema::FilmDB
242         roles Caching
243         <connect_info>
244             dsn   dbi:Pg:dbname=mypgdb
245             user   postgres
246             password ''
247             auto_savepoint 1
248             on_connect_do   some SQL statement
249             on_connect_do   another SQL statement
250         </connect_info>
251     </Model::FilmDB>
252
253 or
254
255     <Model::FilmDB>
256         schema_class   MyApp::Schema::FilmDB
257         connect_info   dbi:SQLite:dbname=foo.db
258     </Model::FilmDB>
259
260 Or using L<YAML>:
261
262   Model::MyDB:
263       schema_class: MyDB
264       connect_info:
265           dsn: dbi:Oracle:mydb
266           user: mtfnpy
267           password: mypass
268           LongReadLen: 1000000
269           LongTruncOk: 1
270           on_connect_do: [ "alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS'" ]
271           cursor_class: 'DBIx::Class::Cursor::Cached'
272
273 The old arrayref style with hashrefs for L<DBI> then L<DBIx::Class> options is also
274 supported:
275
276   connect_info => [
277     'dbi:Pg:dbname=mypgdb',
278     'postgres',
279     '',
280     {
281       pg_enable_utf8 => 1,
282     },
283     {
284       auto_savepoint => 1,
285       on_connect_do => [
286         'some SQL statement',
287         'another SQL statement',
288       ],
289     }
290   ]
291
292 =item roles
293
294 Array of Roles to apply at BUILD time. Roles are relative to the
295 C<<MyApp::Model::DB::Role::> then C<<Catalyst::Model::DBIC::Schema::Role::>>
296 namespaces, unless prefixed with C<+> in which case they are taken to be a
297 fully qualified name. E.g.:
298
299     roles Caching
300     roles +MyApp::DB::Role::Foo
301
302 This is done using L<MooseX::Object::Pluggable>.
303
304 A new instance is created at application time, so any consumed required
305 attributes, coercions and modifiers will work.
306
307 Roles are applied before setup, schema and connection are set, and have a chance
308 to modify C<connect_info>.
309
310 C<ref $self> will be an anon class if any roles are applied.
311
312 You cannot modify C<new> or C<BUILD>, modify C<setup> instead.
313
314 L</ACCEPT_CONTEXT> can also be modified.
315
316 Roles that come with the distribution:
317
318 =over 4
319
320 =item L<Catalyst::Model::DBIC::Schema::Role::Caching>
321
322 =back
323
324 =item storage_type
325
326 Allows the use of a different C<storage_type> than what is set in your
327 C<schema_class> (which in turn defaults to C<::DBI> if not set in current
328 L<DBIx::Class>).  Completely optional, and probably unnecessary for most
329 people until other storage backends become available for L<DBIx::Class>.
330
331 =back
332
333 =head1 METHODS
334
335 =over 4
336
337 =item new
338
339 Instantiates the Model based on the above-documented ->config parameters.
340 The only required parameter is C<schema_class>.  C<connect_info> is
341 required in the case that C<schema_class> does not already have connection
342 information defined for it.
343
344 =item schema
345
346 Accessor which returns the connected schema being used by the this model.
347 There are direct shortcuts on the model class itself for
348 schema->resultset, schema->source, and schema->class.
349
350 =item composed_schema
351
352 Accessor which returns the composed schema, which has no connection info,
353 which was used in constructing the C<schema> above.  Useful for creating
354 new connections based on the same schema/model.  There are direct shortcuts
355 from the model object for composed_schema->clone and composed_schema->connect
356
357 =item clone
358
359 Shortcut for ->composed_schema->clone
360
361 =item connect
362
363 Shortcut for ->composed_schema->connect
364
365 =item source
366
367 Shortcut for ->schema->source
368
369 =item class
370
371 Shortcut for ->schema->class
372
373 =item resultset
374
375 Shortcut for ->schema->resultset
376
377 =item storage
378
379 Provides an accessor for the connected schema's storage object.
380 Used often for debugging and controlling transactions.
381
382 =cut
383
384 class_has 'composed_schema' => (is => 'rw', isa => 'DBIx::Class::Schema');
385
386 has 'schema' => (is => 'rw', isa => 'DBIx::Class::Schema');
387
388 has 'schema_class' => (
389     is => 'ro',
390     isa => SchemaClass,
391     coerce => 1,
392     required => 1
393 );
394
395 has 'storage_type' => (is => 'ro', isa => 'Str');
396
397 has 'connect_info' => (is => 'ro', isa => ConnectInfo, coerce => 1);
398
399 # ref $self changes to anon after roles are applied, and _original_class_name is
400 # broken in MX::O::P 0.0009
401 has '_class_name' => (is => 'ro', isa => 'ClassName', default => sub {
402     ref shift
403 });
404
405 has 'model_name' => (is => 'ro', isa => 'Str', default => sub {
406     my $self = shift;
407
408     my $class = ref $self;
409     (my $model_name = $class) =~ s/^[\w:]+::(?:Model|M):://;
410
411     $model_name
412 });
413
414 has 'roles' => (is => 'ro', isa => 'ArrayRef|Str');
415
416 sub BUILD {
417     my $self = shift;
418     my $class = ref $self;
419     my $schema_class = $self->schema_class;
420
421     if( !$self->connect_info ) {
422         if($schema_class->storage && $schema_class->storage->connect_info) {
423             $self->connect_info($schema_class->storage->connect_info);
424         }
425         else {
426             croak "Either ->config->{connect_info} must be defined for $class"
427                   . " or $schema_class must have connect info defined on it."
428                   . " Here's what we got:\n"
429                   . Dumper($self);
430         }
431     }
432
433     if (exists $self->connect_info->{cursor_class}) {
434         eval { Class::MOP::load_class($self->connect_info->{cursor_class}) }
435             or croak "invalid connect_info: Cannot load your cursor_class"
436         . " ".$self->connect_info->{cursor_class}.": $@";
437     }
438
439     $self->_plugin_ns('Role');
440
441     $self->load_plugins($self->roles->flatten) if $self->roles;
442
443     $self->setup;
444
445     $self->composed_schema($schema_class->compose_namespace($class));
446
447     $self->schema($self->composed_schema->clone);
448
449     $self->schema->storage_type($self->storage_type)
450         if $self->storage_type;
451
452     $self->schema->connection($self->connect_info);
453
454     $self->_install_rs_models;
455 }
456
457 sub clone { shift->composed_schema->clone(@_); }
458
459 sub connect { shift->composed_schema->connect(@_); }
460
461 sub storage { shift->schema->storage(@_); }
462
463 =item setup
464
465 Called at C<<BUILD>> time, for modifying in roles/subclasses.
466
467 =cut
468
469 sub setup { 1 }
470
471 =item ACCEPT_CONTEXT
472
473 Point of extension for doing things at C<<$c->model>> time, returns the model
474 instance, see L<Catalyst::Manual::Intro> for more information.
475
476 =cut
477
478 sub ACCEPT_CONTEXT { shift }
479
480 sub _install_rs_models {
481     my $self  = shift;
482     my $class = $self->_class_name;
483
484     no strict 'refs';
485     foreach my $moniker ($self->schema->sources) {
486         my $classname = "${class}::$moniker";
487         *{"${classname}::ACCEPT_CONTEXT"} = sub {
488             shift;
489             shift->model($self->model_name)->resultset($moniker);
490         }
491     }
492 }
493
494 __PACKAGE__->meta->make_immutable;
495
496 =back
497
498 =head1 SEE ALSO
499
500 General Catalyst Stuff:
501
502 L<Catalyst::Manual>, L<Catalyst::Test>, L<Catalyst::Request>,
503 L<Catalyst::Response>, L<Catalyst::Helper>, L<Catalyst>,
504
505 Stuff related to DBIC and this Model style:
506
507 L<DBIx::Class>, L<DBIx::Class::Schema>,
508 L<DBIx::Class::Schema::Loader>, L<Catalyst::Helper::Model::DBIC::Schema>,
509 L<MooseX::Object::Pluggable>
510
511 =head1 AUTHOR
512
513 Brandon L Black, C<blblack@gmail.com>
514
515 Contributors:
516
517 Rafael Kitover, C<<rkitover at cpan.org>>
518
519 =head1 COPYRIGHT
520
521 This program is free software, you can redistribute it and/or modify it
522 under the same terms as Perl itself.
523
524 =cut
525
526 1;