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