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