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