switch M::DBIC::Schema to MRO::Compat from NEXT
[catagits/Catalyst-Model-DBIC-Schema.git] / lib / Catalyst / Model / DBIC / Schema.pm
1 package Catalyst::Model::DBIC::Schema;
2
3 use strict;
4 use warnings;
5
6 our $VERSION = '0.23';
7
8 use base qw/Catalyst::Model Class::Accessor::Fast Class::Data::Accessor/;
9 use MRO::Compat;
10 use mro 'c3';
11 use UNIVERSAL::require;
12 use Carp;
13 use Data::Dumper;
14 require DBIx::Class;
15
16 __PACKAGE__->mk_classaccessor('composed_schema');
17 __PACKAGE__->mk_accessors('schema');
18
19 =head1 NAME
20
21 Catalyst::Model::DBIC::Schema - DBIx::Class::Schema Model Class
22
23 =head1 SYNOPSIS
24
25 Manual creation of a DBIx::Class::Schema and a Catalyst::Model::DBIC::Schema:
26
27 =over
28
29 =item 1.
30
31 Create the DBIx:Class schema in MyApp/Schema/FilmDB.pm:
32
33   package MyApp::Schema::FilmDB;
34   use base qw/DBIx::Class::Schema/;
35
36   __PACKAGE__->load_classes(qw/Actor Role/);
37
38 =item 2.
39
40 Create some classes for the tables in the database, for example an 
41 Actor in MyApp/Schema/FilmDB/Actor.pm:
42
43   package MyApp::Schema::FilmDB::Actor;
44   use base qw/DBIx::Class/
45
46   __PACKAGE__->load_components(qw/Core/);
47   __PACKAGE__->table('actor');
48
49   ...
50
51 and a Role in MyApp/Schema/FilmDB/Role.pm:
52
53   package MyApp::Schema::FilmDB::Role;
54   use base qw/DBIx::Class/
55
56   __PACKAGE__->load_components(qw/Core/);
57   __PACKAGE__->table('role');
58
59   ...    
60
61 Notice that the schema is in MyApp::Schema, not in MyApp::Model. This way it's 
62 usable as a standalone module and you can test/run it without Catalyst. 
63
64 =item 3.
65
66 To expose it to Catalyst as a model, you should create a DBIC Model in
67 MyApp/Model/FilmDB.pm:
68
69   package MyApp::Model::FilmDB;
70   use base qw/Catalyst::Model::DBIC::Schema/;
71
72   __PACKAGE__->config(
73       schema_class => 'MyApp::Schema::FilmDB',
74       connect_info => [
75                         "DBI:...",
76                         "username",
77                         "password",
78                         {AutoCommit => 1}
79                       ]
80   );
81
82 See below for a full list of the possible config parameters.
83
84 =back
85
86 Now you have a working Model which accesses your separate DBIC Schema. This can
87 be used/accessed in the normal Catalyst manner, via $c->model():
88
89   my $actor = $c->model('FilmDB::Actor')->find(1);
90
91 You can also use it to set up DBIC authentication with 
92 Authentication::Store::DBIC in MyApp.pm:
93
94   package MyApp;
95
96   use Catalyst qw/... Authentication::Store::DBIC/;
97
98   ...
99
100   __PACKAGE__->config->{authentication}{dbic} = {
101       user_class      => 'FilmDB::Actor',
102       user_field      => 'name',
103       password_field  => 'password'
104   }
105
106 C<< $c->model('Schema::Source') >> returns a L<DBIx::Class::ResultSet> for 
107 the source name parameter passed. To find out more about which methods can 
108 be called on a ResultSet, or how to add your own methods to it, please see 
109 the ResultSet documentation in the L<DBIx::Class> distribution.
110
111 Some examples are given below:
112
113   # to access schema methods directly:
114   $c->model('FilmDB')->schema->source(...);
115
116   # to access the source object, resultset, and class:
117   $c->model('FilmDB')->source(...);
118   $c->model('FilmDB')->resultset(...);
119   $c->model('FilmDB')->class(...);
120
121   # For resultsets, there's an even quicker shortcut:
122   $c->model('FilmDB::Actor')
123   # is the same as $c->model('FilmDB')->resultset('Actor')
124
125   # To get the composed schema for making new connections:
126   my $newconn = $c->model('FilmDB')->composed_schema->connect(...);
127
128   # Or the same thing via a convenience shortcut:
129   my $newconn = $c->model('FilmDB')->connect(...);
130
131   # or, if your schema works on different storage drivers:
132   my $newconn = $c->model('FilmDB')->composed_schema->clone();
133   $newconn->storage_type('::LDAP');
134   $newconn->connection(...);
135
136   # and again, a convenience shortcut
137   my $newconn = $c->model('FilmDB')->clone();
138   $newconn->storage_type('::LDAP');
139   $newconn->connection(...);
140
141 =head1 DESCRIPTION
142
143 This is a Catalyst Model for L<DBIx::Class::Schema>-based Models.  See
144 the documentation for L<Catalyst::Helper::Model::DBIC::Schema> for
145 information on generating these Models via Helper scripts.
146
147 When your Catalyst app starts up, a thin Model layer is created as an 
148 interface to your DBIC Schema. It should be clearly noted that the model 
149 object returned by C<< $c->model('FilmDB') >> is NOT itself a DBIC schema or 
150 resultset object, but merely a wrapper proving L<methods|/METHODS> to access 
151 the underlying schema. 
152
153 In addition to this model class, a shortcut class is generated for each 
154 source in the schema, allowing easy and direct access to a resultset of the 
155 corresponding type. These generated classes are even thinner than the model 
156 class, providing no public methods but simply hooking into Catalyst's 
157 model() accessor via the 
158 L<ACCEPT_CONTEXT|Catalyst::Component/ACCEPT_CONTEXT> mechanism. The complete 
159 contents of each generated class is roughly equivalent to the following:
160
161   package MyApp::Model::FilmDB::Actor
162   sub ACCEPT_CONTEXT {
163       my ($self, $c) = @_;
164       $c->model('FilmDB')->resultset('Actor');
165   }
166
167 In short, there are three techniques available for obtaining a DBIC 
168 resultset object: 
169
170   # the long way
171   my $rs = $c->model('FilmDB')->schema->resultset('Actor');
172
173   # using the shortcut method on the model object
174   my $rs = $c->model('FilmDB')->resultset('Actor');
175
176   # using the generated class directly
177   my $rs = $c->model('FilmDB::Actor');
178
179 In order to add methods to a DBIC resultset, you cannot simply add them to 
180 the source (row, table) definition class; you must define a separate custom 
181 resultset class. See L<DBIx::Class::Manual::Cookbook/"Predefined searches"> 
182 for more info.
183
184 =head1 CONFIG PARAMETERS
185
186 =over 4
187
188 =item schema_class
189
190 This is the classname of your L<DBIx::Class::Schema> Schema.  It needs
191 to be findable in C<@INC>, but it does not need to be inside the 
192 C<Catalyst::Model::> namespace.  This parameter is required.
193
194 =item connect_info
195
196 This is an arrayref of connection parameters, which are specific to your
197 C<storage_type> (see your storage type documentation for more details). 
198 If you only need one parameter (e.g. the DSN), you can just pass a string 
199 instead of an arrayref.
200
201 This is not required if C<schema_class> already has connection information
202 defined inside itself (which isn't highly recommended, but can be done)
203
204 For L<DBIx::Class::Storage::DBI>, which is the only supported
205 C<storage_type> in L<DBIx::Class> at the time of this writing, the
206 parameters are your dsn, username, password, and connect options hashref.
207
208 See L<DBIx::Class::Storage::DBI/connect_info> for a detailed explanation
209 of the arguments supported.
210
211 Examples:
212
213   connect_info => [ 'dbi:Pg:dbname=mypgdb', 'postgres', '' ],
214
215   connect_info => [
216                     'dbi:SQLite:dbname=foo.db',
217                     {
218                       on_connect_do => [
219                         'PRAGMA synchronous = OFF',
220                       ],
221                     }
222                   ],
223
224   connect_info => [
225                     'dbi:Pg:dbname=mypgdb',
226                     'postgres',
227                     '',
228                     { AutoCommit => 0 },
229                     {
230                       on_connect_do => [
231                         'some SQL statement',
232                         'another SQL statement',
233                       ],
234                     }
235                   ],
236
237 Or using L<Config::General>:
238
239     <Model::FilmDB>
240         schema_class   MyApp::Schema::FilmDB
241         connect_info   dbi:Pg:dbname=mypgdb
242         connect_info   postgres
243         connect_info
244         <connect_info>
245             AutoCommit   0
246             on_connect_do   some SQL statement
247             on_connect_do   another SQL statement
248         </connect_info>
249     </Model::FilmDB>
250
251 or
252
253     <Model::FilmDB>
254         schema_class   MyApp::Schema::FilmDB
255         connect_info   dbi:SQLite:dbname=foo.db
256     </Model::FilmDB>
257
258
259 =item storage_type
260
261 Allows the use of a different C<storage_type> than what is set in your
262 C<schema_class> (which in turn defaults to C<::DBI> if not set in current
263 L<DBIx::Class>).  Completely optional, and probably unnecessary for most
264 people until other storage backends become available for L<DBIx::Class>.
265
266 =back
267
268 =head1 METHODS
269
270 =over 4
271
272 =item new
273
274 Instantiates the Model based on the above-documented ->config parameters.
275 The only required parameter is C<schema_class>.  C<connect_info> is
276 required in the case that C<schema_class> does not already have connection
277 information defined for it.
278
279 =item schema
280
281 Accessor which returns the connected schema being used by the this model.
282 There are direct shortcuts on the model class itself for
283 schema->resultset, schema->source, and schema->class.
284
285 =item composed_schema
286
287 Accessor which returns the composed schema, which has no connection info,
288 which was used in constructing the C<schema> above.  Useful for creating
289 new connections based on the same schema/model.  There are direct shortcuts
290 from the model object for composed_schema->clone and composed_schema->connect
291
292 =item clone
293
294 Shortcut for ->composed_schema->clone
295
296 =item connect
297
298 Shortcut for ->composed_schema->connect
299
300 =item source
301
302 Shortcut for ->schema->source
303
304 =item class
305
306 Shortcut for ->schema->class
307
308 =item resultset
309
310 Shortcut for ->schema->resultset
311
312 =item storage
313
314 Provides an accessor for the connected schema's storage object.
315 Used often for debugging and controlling transactions.
316
317 =back
318
319 =cut
320
321 sub new {
322     my $self = shift->next::method(@_);
323     
324     my $class = ref($self);
325     my $model_name = $class;
326     $model_name =~ s/^[\w:]+::(?:Model|M):://;
327
328     croak "->config->{schema_class} must be defined for this model"
329         unless $self->{schema_class};
330
331     my $schema_class = $self->{schema_class};
332
333     $schema_class->require
334         or croak "Cannot load schema class '$schema_class': $@";
335
336     if( !$self->{connect_info} ) {
337         if($schema_class->storage && $schema_class->storage->connect_info) {
338             $self->{connect_info} = $schema_class->storage->connect_info;
339         }
340         else {
341             croak "Either ->config->{connect_info} must be defined for $class"
342                   . " or $schema_class must have connect info defined on it."
343                   . " Here's what we got:\n"
344                   . Dumper($self);
345         }
346     }
347
348     $self->composed_schema($schema_class->compose_namespace($class));
349     $self->schema($self->composed_schema->clone);
350
351     $self->schema->storage_type($self->{storage_type})
352         if $self->{storage_type};
353
354     $self->schema->connection( 
355         ref $self->{connect_info} eq 'ARRAY' ? 
356         @{$self->{connect_info}} : 
357         $self->{connect_info}
358     );
359     
360     no strict 'refs';
361     foreach my $moniker ($self->schema->sources) {
362         my $classname = "${class}::$moniker";
363         *{"${classname}::ACCEPT_CONTEXT"} = sub {
364             shift;
365             shift->model($model_name)->resultset($moniker);
366         }
367     }
368
369     return $self;
370 }
371
372 sub clone { shift->composed_schema->clone(@_); }
373
374 sub connect { shift->composed_schema->connect(@_); }
375
376 sub storage { shift->schema->storage(@_); }
377
378 =head1 SEE ALSO
379
380 General Catalyst Stuff:
381
382 L<Catalyst::Manual>, L<Catalyst::Test>, L<Catalyst::Request>,
383 L<Catalyst::Response>, L<Catalyst::Helper>, L<Catalyst>,
384
385 Stuff related to DBIC and this Model style:
386
387 L<DBIx::Class>, L<DBIx::Class::Schema>,
388 L<DBIx::Class::Schema::Loader>, L<Catalyst::Helper::Model::DBIC::Schema>
389
390 =head1 AUTHOR
391
392 Brandon L Black, C<blblack@gmail.com>
393
394 =head1 COPYRIGHT
395
396 This program is free software, you can redistribute it and/or modify it
397 under the same terms as Perl itself.
398
399 =cut
400
401 1;