1 package Catalyst::Model::DBIC::Schema;
5 extends 'Catalyst::Model';
6 with 'CatalystX::Component::Traits';
9 $VERSION = eval $VERSION;
11 use namespace::autoclean;
12 use Carp::Clan '^Catalyst::Model::DBIC::Schema';
16 use Catalyst::Model::DBIC::Schema::Types
17 qw/ConnectInfo LoadedClass SchemaClass/;
19 use MooseX::Types::Moose qw/ArrayRef Str ClassName Undef/;
23 Catalyst::Model::DBIC::Schema - DBIx::Class::Schema Model Class
27 Manual creation of a DBIx::Class::Schema and a Catalyst::Model::DBIC::Schema:
33 Create the DBIx:Class schema in MyApp/Schema/FilmDB.pm:
35 package MyApp::Schema::FilmDB;
36 use base qw/DBIx::Class::Schema/;
38 __PACKAGE__->load_classes(qw/Actor Role/);
42 Create some classes for the tables in the database, for example an
43 Actor in MyApp/Schema/FilmDB/Actor.pm:
45 package MyApp::Schema::FilmDB::Actor;
46 use base qw/DBIx::Class/
48 __PACKAGE__->load_components(qw/Core/);
49 __PACKAGE__->table('actor');
53 and a Role in MyApp/Schema/FilmDB/Role.pm:
55 package MyApp::Schema::FilmDB::Role;
56 use base qw/DBIx::Class/
58 __PACKAGE__->load_components(qw/Core/);
59 __PACKAGE__->table('role');
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.
68 To expose it to Catalyst as a model, you should create a DBIC Model in
69 MyApp/Model/FilmDB.pm:
71 package MyApp::Model::FilmDB;
72 use base qw/Catalyst::Model::DBIC::Schema/;
75 schema_class => 'MyApp::Schema::FilmDB',
79 password => "password",
83 See below for a full list of the possible config parameters.
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():
90 my $actor = $c->model('FilmDB::Actor')->find(1);
92 You can also use it to set up DBIC authentication with
93 L<Catalyst::Authentication::Store::DBIx::Class> in MyApp.pm:
97 use Catalyst qw/... Authentication .../;
101 __PACKAGE__->config->{authentication} =
103 default_realm => 'members',
108 password_field => 'password',
109 password_type => 'hashed'
110 password_hash_type => 'SHA-256'
113 class => 'DBIx::Class',
114 user_model => 'DB::User',
115 role_relation => 'roles',
116 role_field => 'rolename',
122 C<< $c->model('Schema::Source') >> returns a L<DBIx::Class::ResultSet> for
123 the source name parameter passed. To find out more about which methods can
124 be called on a ResultSet, or how to add your own methods to it, please see
125 the ResultSet documentation in the L<DBIx::Class> distribution.
127 Some examples are given below:
129 # to access schema methods directly:
130 $c->model('FilmDB')->schema->source(...);
132 # to access the source object, resultset, and class:
133 $c->model('FilmDB')->source(...);
134 $c->model('FilmDB')->resultset(...);
135 $c->model('FilmDB')->class(...);
137 # For resultsets, there's an even quicker shortcut:
138 $c->model('FilmDB::Actor')
139 # is the same as $c->model('FilmDB')->resultset('Actor')
141 # To get the composed schema for making new connections:
142 my $newconn = $c->model('FilmDB')->composed_schema->connect(...);
144 # Or the same thing via a convenience shortcut:
145 my $newconn = $c->model('FilmDB')->connect(...);
147 # or, if your schema works on different storage drivers:
148 my $newconn = $c->model('FilmDB')->composed_schema->clone();
149 $newconn->storage_type('::LDAP');
150 $newconn->connection(...);
152 # and again, a convenience shortcut
153 my $newconn = $c->model('FilmDB')->clone();
154 $newconn->storage_type('::LDAP');
155 $newconn->connection(...);
159 This is a Catalyst Model for L<DBIx::Class::Schema>-based Models. See
160 the documentation for L<Catalyst::Helper::Model::DBIC::Schema> for
161 information on generating these Models via Helper scripts.
163 When your Catalyst app starts up, a thin Model layer is created as an
164 interface to your DBIC Schema. It should be clearly noted that the model
165 object returned by C<< $c->model('FilmDB') >> is NOT itself a DBIC schema or
166 resultset object, but merely a wrapper proving L<methods|/METHODS> to access
167 the underlying schema.
169 In addition to this model class, a shortcut class is generated for each
170 source in the schema, allowing easy and direct access to a resultset of the
171 corresponding type. These generated classes are even thinner than the model
172 class, providing no public methods but simply hooking into Catalyst's
173 model() accessor via the
174 L<ACCEPT_CONTEXT|Catalyst::Component/ACCEPT_CONTEXT> mechanism. The complete
175 contents of each generated class is roughly equivalent to the following:
177 package MyApp::Model::FilmDB::Actor
180 $c->model('FilmDB')->resultset('Actor');
183 In short, there are three techniques available for obtaining a DBIC
187 my $rs = $c->model('FilmDB')->schema->resultset('Actor');
189 # using the shortcut method on the model object
190 my $rs = $c->model('FilmDB')->resultset('Actor');
192 # using the generated class directly
193 my $rs = $c->model('FilmDB::Actor');
195 In order to add methods to a DBIC resultset, you cannot simply add them to
196 the source (row, table) definition class; you must define a separate custom
197 resultset class. See L<DBIx::Class::Manual::Cookbook/"Predefined searches">
200 =head1 CONFIG PARAMETERS
202 Any options in your config not listed here are passed to your schema.
206 This is the classname of your L<DBIx::Class::Schema> Schema. It needs
207 to be findable in C<@INC>, but it does not need to be inside the
208 C<Catalyst::Model::> namespace. This parameter is required.
212 This is an arrayref of connection parameters, which are specific to your
213 C<storage_type> (see your storage type documentation for more details).
214 If you only need one parameter (e.g. the DSN), you can just pass a string
215 instead of an arrayref.
217 This is not required if C<schema_class> already has connection information
218 defined inside itself (which isn't highly recommended, but can be done)
220 For L<DBIx::Class::Storage::DBI>, which is the only supported
221 C<storage_type> in L<DBIx::Class> at the time of this writing, the
222 parameters are your dsn, username, password, and connect options hashref.
224 See L<DBIx::Class::Storage::DBI/connect_info> for a detailed explanation
225 of the arguments supported.
230 dsn => 'dbi:Pg:dbname=mypgdb',
236 dsn => 'dbi:SQLite:dbname=foo.db',
238 'PRAGMA synchronous = OFF',
243 dsn => 'dbi:Pg:dbname=mypgdb',
248 'some SQL statement',
249 'another SQL statement',
253 Or using L<Config::General>:
256 schema_class MyApp::Schema::FilmDB
259 dsn dbi:Pg:dbname=mypgdb
264 on_connect_do some SQL statement
265 on_connect_do another SQL statement
267 user_defined_schema_accessor foo
273 schema_class MyApp::Schema::FilmDB
274 connect_info dbi:SQLite:dbname=foo.db
288 on_connect_call: 'datetime_setup'
291 The old arrayref style with hashrefs for L<DBI> then L<DBIx::Class> options is also
295 'dbi:Pg:dbname=mypgdb',
304 'some SQL statement',
305 'another SQL statement',
312 Array of Traits to apply to the instance. Traits are L<Moose::Role>s.
314 They are relative to the C<< MyApp::TraitFor::Model::DBIC::Schema:: >>, then the C<<
315 Catalyst::TraitFor::Model::DBIC::Schema:: >> namespaces, unless prefixed with C<+>
316 in which case they are taken to be a fully qualified name. E.g.:
319 traits +MyApp::TraitFor::Model::Foo
321 A new instance is created at application time, so any consumed required
322 attributes, coercions and modifiers will work.
324 Traits are applied at L<Catalyst::Component/COMPONENT> time using
325 L<CatalystX::Component::Traits>.
327 C<ref $self> will be an anon class if any traits are applied, C<<
328 $self->_original_class_name >> will be the original class.
330 When writing a Trait, interesting points to modify are C<BUILD>, L</setup> and
333 Traits that come with the distribution:
337 =item L<Catalyst::TraitFor::Model::DBIC::Schema::Caching>
339 =item L<Catalyst::TraitFor::Model::DBIC::Schema::Replicated>
345 Allows the use of a different C<storage_type> than what is set in your
346 C<schema_class> (which in turn defaults to C<::DBI> if not set in current
347 L<DBIx::Class>). Completely optional, and probably unnecessary for most
348 people until other storage backends become available for L<DBIx::Class>.
352 The keys you pass in the model configuration are available as attributes.
354 Other attributes available:
358 Your connect_info args normalized to hashref form (with dsn/user/password.) See
359 L<DBIx::Class::Storage::DBI/connect_info> for more info on the hashref form of
364 The model name L<Catalyst> uses to resolve this model, the part after
365 C<::Model::> or C<::M::> in your class name. E.g. if your class name is
366 C<MyApp::Model::DB> the L</model_name> will be C<DB>.
368 =head2 _default_cursor_class
370 What to reset your L<DBIx::Class::Storage::DBI/cursor_class> to if a custom one
371 doesn't work out. Defaults to L<DBIx::Class::Storage::DBI::Cursor>.
373 =head1 ATTRIBUTES FROM L<MooseX::Traits::Pluggable>
375 =head2 _original_class_name
377 The class name of your model before any L</traits> are applied. E.g.
382 Unresolved arrayref of traits passed in the config.
384 =head2 _resolved_traits
386 Traits you used resolved to full class names.
390 Methods not listed here are delegated to the connected schema used by the model
391 instance, so the following are equivalent:
393 $c->model('DB')->schema->my_accessor('foo');
395 $c->model('DB')->my_accessor('foo');
397 Methods on the model take precedence over schema methods.
401 Instantiates the Model based on the above-documented ->config parameters.
402 The only required parameter is C<schema_class>. C<connect_info> is
403 required in the case that C<schema_class> does not already have connection
404 information defined for it.
408 Accessor which returns the connected schema being used by the this model.
409 There are direct shortcuts on the model class itself for
410 schema->resultset, schema->source, and schema->class.
412 =head2 composed_schema
414 Accessor which returns the composed schema, which has no connection info,
415 which was used in constructing the C<schema> above. Useful for creating
416 new connections based on the same schema/model. There are direct shortcuts
417 from the model object for composed_schema->clone and composed_schema->connect
421 Shortcut for ->composed_schema->clone
425 Shortcut for ->composed_schema->connect
429 Shortcut for ->schema->source
433 Shortcut for ->schema->class
437 Shortcut for ->schema->resultset
441 Provides an accessor for the connected schema's storage object.
442 Used often for debugging and controlling transactions.
446 has schema_class => (
453 has storage_type => (is => 'rw', isa => Str);
455 has connect_info => (is => 'rw', isa => ConnectInfo, coerce => 1);
464 has _default_cursor_class => (
467 default => 'DBIx::Class::Storage::DBI::Cursor',
472 my ($self, $args) = @_;
473 my $class = $self->_original_class_name;
474 my $schema_class = $self->schema_class;
476 if( !$self->connect_info ) {
477 if($schema_class->storage && $schema_class->storage->connect_info) {
478 $self->connect_info($schema_class->storage->connect_info);
481 die "Either ->config->{connect_info} must be defined for $class"
482 . " or $schema_class must have connect info defined on it."
483 . " Here's what we got:\n"
488 if (exists $self->connect_info->{cursor_class}) {
489 eval { Class::MOP::load_class($self->connect_info->{cursor_class}) }
490 or croak "invalid connect_info: Cannot load your cursor_class"
491 . " ".$self->connect_info->{cursor_class}.": $@";
496 $self->composed_schema($schema_class->compose_namespace($class));
498 $self->meta->make_mutable;
499 $self->meta->add_attribute('schema',
501 isa => 'DBIx::Class::Schema',
502 handles => $self->_delegates
504 $self->meta->make_immutable;
506 $self->schema($self->composed_schema->clone);
508 $self->_pass_options_to_schema($args);
510 $self->schema->storage_type($self->storage_type)
511 if $self->storage_type;
513 $self->schema->connection($self->connect_info);
515 $self->_install_rs_models;
518 sub clone { shift->composed_schema->clone(@_); }
520 sub connect { shift->composed_schema->connect(@_); }
524 Called at C<BUILD> time before configuration, but after L</connect_info> is
525 set. To do something after configuuration use C<< after BUILD => >>.
531 =head2 ACCEPT_CONTEXT
533 Point of extension for doing things at C<< $c->model >> time with context,
534 returns the model instance, see L<Catalyst::Manual::Intro/ACCEPT_CONTEXT> for
539 sub ACCEPT_CONTEXT { shift }
541 sub _install_rs_models {
543 my $class = $self->_original_class_name;
547 my @sources = $self->schema->sources;
549 die "No sources found (did you forget to define your tables?)"
552 foreach my $moniker (@sources) {
553 my $classname = "${class}::$moniker";
554 *{"${classname}::ACCEPT_CONTEXT"} = sub {
556 shift->model($self->model_name)->resultset($moniker);
561 sub _reset_cursor_class {
564 if ($self->storage->can('cursor_class')) {
565 $self->storage->cursor_class($self->_default_cursor_class)
566 if $self->storage->cursor_class ne $self->_default_cursor_class;
573 sub composed_schema {
575 my $class = $self->_original_class_name;
576 my $store = \$COMPOSED_CACHE{$class}{$self->schema_class};
578 $$store = shift if @_;
584 sub _build_model_name {
586 my $class = $self->_original_class_name;
587 (my $model_name = $class) =~ s/^[\w:]+::(?:Model|M):://;
595 my $schema_meta = Class::MOP::Class->initialize($self->schema_class);
596 my @schema_methods = $schema_meta->get_all_method_names;
598 # combine with any already added by other schemas
600 @{ $self->meta->find_attribute_by_name('schema')->handles }
603 # now kill the attribute, otherwise add_attribute in BUILD will not do the right
604 # thing (it clears the handles for some reason.) May be a Moose bug.
605 eval { $self->meta->remove_attribute('schema') };
608 @schema_methods{ @schema_methods, @handles } = ();
609 @schema_methods = keys %schema_methods;
611 my @my_methods = $self->meta->get_all_method_names;
613 @my_methods{@my_methods} = ();
616 for my $method (@schema_methods) {
617 push @delegates, $method unless exists $my_methods{$method};
623 sub _pass_options_to_schema {
624 my ($self, $args) = @_;
626 my @attributes = map {
628 } $self->meta->get_all_attributes;
631 @attributes{@attributes} = ();
633 for my $opt (keys %$args) {
634 if (not exists $attributes{$opt}) {
635 next unless $self->schema->can($opt);
636 $self->schema->$opt($self->{$opt});
641 __PACKAGE__->meta->make_immutable;
645 General Catalyst Stuff:
647 L<Catalyst::Manual>, L<Catalyst::Test>, L<Catalyst::Request>,
648 L<Catalyst::Response>, L<Catalyst::Helper>, L<Catalyst>,
650 Stuff related to DBIC and this Model style:
652 L<DBIx::Class>, L<DBIx::Class::Schema>,
653 L<DBIx::Class::Schema::Loader>, L<Catalyst::Helper::Model::DBIC::Schema>,
654 L<CatalystX::Component::Traits>, L<MooseX::Traits::Pluggable>
658 L<Catalyst::TraitFor::Model::DBIC::Schema::Caching>,
659 L<Catalyst::TraitFor::Model::DBIC::Schema::Replicated>
663 Brandon L Black C<blblack at gmail.com>
667 caelum: Rafael Kitover C<rkitover at cpan.org>
669 Dan Dascalescu C<dandv at cpan.org>
671 Aran Deltac C<bluefeet@cpan.org>
675 This program is free software. You can redistribute it and/or modify it
676 under the same terms as Perl itself.