1 package Catalyst::Model::DBIC::Schema;
5 extends 'Catalyst::Model';
6 with 'CatalystX::Component::Traits';
10 use namespace::autoclean;
11 use Carp::Clan '^Catalyst::Model::DBIC::Schema';
15 use Class::Inspector ();
17 use Catalyst::Model::DBIC::Schema::Types
18 qw/ConnectInfo LoadedClass/;
20 use MooseX::Types::Moose qw/ArrayRef Str ClassName Undef/;
24 Catalyst::Model::DBIC::Schema - DBIx::Class::Schema Model Class
28 Manual creation of a DBIx::Class::Schema and a Catalyst::Model::DBIC::Schema:
34 Create the DBIx:Class schema in MyApp/Schema/FilmDB.pm:
36 package MyApp::Schema::FilmDB;
37 use base qw/DBIx::Class::Schema/;
39 __PACKAGE__->load_classes(qw/Actor Role/);
43 Create some classes for the tables in the database, for example an
44 Actor in MyApp/Schema/FilmDB/Actor.pm:
46 package MyApp::Schema::FilmDB::Actor;
47 use base qw/DBIx::Class/
49 __PACKAGE__->load_components(qw/Core/);
50 __PACKAGE__->table('actor');
54 and a Role in MyApp/Schema/FilmDB/Role.pm:
56 package MyApp::Schema::FilmDB::Role;
57 use base qw/DBIx::Class/
59 __PACKAGE__->load_components(qw/Core/);
60 __PACKAGE__->table('role');
64 Notice that the schema is in MyApp::Schema, not in MyApp::Model. This way it's
65 usable as a standalone module and you can test/run it without Catalyst.
69 To expose it to Catalyst as a model, you should create a DBIC Model in
70 MyApp/Model/FilmDB.pm:
72 package MyApp::Model::FilmDB;
73 use base qw/Catalyst::Model::DBIC::Schema/;
76 schema_class => 'MyApp::Schema::FilmDB',
80 password => "password",
84 See below for a full list of the possible config parameters.
88 Now you have a working Model which accesses your separate DBIC Schema. This can
89 be used/accessed in the normal Catalyst manner, via $c->model():
91 my $actor = $c->model('FilmDB::Actor')->find(1);
93 You can also use it to set up DBIC authentication with
94 L<Catalyst::Authentication::Store::DBIx::Class> in MyApp.pm:
98 use Catalyst qw/... Authentication .../;
102 __PACKAGE__->config->{authentication} =
104 default_realm => 'members',
109 password_field => 'password',
110 password_type => 'hashed'
111 password_hash_type => 'SHA-256'
114 class => 'DBIx::Class',
115 user_model => 'DB::User',
116 role_relation => 'roles',
117 role_field => 'rolename',
123 C<< $c->model('Schema::Source') >> returns a L<DBIx::Class::ResultSet> for
124 the source name parameter passed. To find out more about which methods can
125 be called on a ResultSet, or how to add your own methods to it, please see
126 the ResultSet documentation in the L<DBIx::Class> distribution.
128 Some examples are given below:
130 # to access schema methods directly:
131 $c->model('FilmDB')->schema->source(...);
133 # to access the source object, resultset, and class:
134 $c->model('FilmDB')->source(...);
135 $c->model('FilmDB')->resultset(...);
136 $c->model('FilmDB')->class(...);
138 # For resultsets, there's an even quicker shortcut:
139 $c->model('FilmDB::Actor')
140 # is the same as $c->model('FilmDB')->resultset('Actor')
142 # To get the composed schema for making new connections:
143 my $newconn = $c->model('FilmDB')->composed_schema->connect(...);
145 # Or the same thing via a convenience shortcut:
146 my $newconn = $c->model('FilmDB')->connect(...);
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(...);
153 # and again, a convenience shortcut
154 my $newconn = $c->model('FilmDB')->clone();
155 $newconn->storage_type('::LDAP');
156 $newconn->connection(...);
160 This is a Catalyst Model for L<DBIx::Class::Schema>-based Models. See
161 the documentation for L<Catalyst::Helper::Model::DBIC::Schema> for
162 information on generating these Models via Helper scripts.
164 When your Catalyst app starts up, a thin Model layer is created as an
165 interface to your DBIC Schema. It should be clearly noted that the model
166 object returned by C<< $c->model('FilmDB') >> is NOT itself a DBIC schema or
167 resultset object, but merely a wrapper proving L<methods|/METHODS> to access
168 the underlying schema.
170 In addition to this model class, a shortcut class is generated for each
171 source in the schema, allowing easy and direct access to a resultset of the
172 corresponding type. These generated classes are even thinner than the model
173 class, providing no public methods but simply hooking into Catalyst's
174 model() accessor via the
175 L<ACCEPT_CONTEXT|Catalyst::Component/ACCEPT_CONTEXT> mechanism. The complete
176 contents of each generated class is roughly equivalent to the following:
178 package MyApp::Model::FilmDB::Actor
181 $c->model('FilmDB')->resultset('Actor');
184 In short, there are three techniques available for obtaining a DBIC
188 my $rs = $c->model('FilmDB')->schema->resultset('Actor');
190 # using the shortcut method on the model object
191 my $rs = $c->model('FilmDB')->resultset('Actor');
193 # using the generated class directly
194 my $rs = $c->model('FilmDB::Actor');
196 In order to add methods to a DBIC resultset, you cannot simply add them to
197 the source (row, table) definition class; you must define a separate custom
198 resultset class. See L<DBIx::Class::Manual::Cookbook/"Predefined searches">
201 =head1 CONFIG PARAMETERS
205 This is the classname of your L<DBIx::Class::Schema> Schema. It needs
206 to be findable in C<@INC>, but it does not need to be inside the
207 C<Catalyst::Model::> namespace. This parameter is required.
211 This is an arrayref of connection parameters, which are specific to your
212 C<storage_type> (see your storage type documentation for more details).
213 If you only need one parameter (e.g. the DSN), you can just pass a string
214 instead of an arrayref.
216 This is not required if C<schema_class> already has connection information
217 defined inside itself (which isn't highly recommended, but can be done)
219 For L<DBIx::Class::Storage::DBI>, which is the only supported
220 C<storage_type> in L<DBIx::Class> at the time of this writing, the
221 parameters are your dsn, username, password, and connect options hashref.
223 See L<DBIx::Class::Storage::DBI/connect_info> for a detailed explanation
224 of the arguments supported.
229 dsn => 'dbi:Pg:dbname=mypgdb',
235 dsn => 'dbi:SQLite:dbname=foo.db',
237 'PRAGMA synchronous = OFF',
242 dsn => 'dbi:Pg:dbname=mypgdb',
247 'some SQL statement',
248 'another SQL statement',
252 Or using L<Config::General>:
255 schema_class MyApp::Schema::FilmDB
258 dsn dbi:Pg:dbname=mypgdb
263 on_connect_do some SQL statement
264 on_connect_do another SQL statement
271 schema_class MyApp::Schema::FilmDB
272 connect_info dbi:SQLite:dbname=foo.db
285 on_connect_do: [ "alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS'" ]
286 cursor_class: 'DBIx::Class::Cursor::Cached'
289 The old arrayref style with hashrefs for L<DBI> then L<DBIx::Class> options is also
293 'dbi:Pg:dbname=mypgdb',
302 'some SQL statement',
303 'another SQL statement',
310 Array of Traits to apply to the instance. Traits are L<Moose::Role>s.
312 They are relative to the C<< MyApp::TraitFor::Model::DBIC::Schema:: >>, then the C<<
313 Catalyst::TraitFor::Model::DBIC::Schema:: >> namespaces, unless prefixed with C<+>
314 in which case they are taken to be a fully qualified name. E.g.:
317 traits +MyApp::TraitFor::Model::Foo
319 A new instance is created at application time, so any consumed required
320 attributes, coercions and modifiers will work.
322 Traits are applied at L<Catalyst::Component/COMPONENT> time using
323 L<CatalystX::Component::Traits>.
325 C<ref $self> will be an anon class if any traits are applied, C<<
326 $self->_original_class_name >> will be the original class.
328 When writing a Trait, interesting points to modify are C<BUILD>, L</setup> and
331 Traits that come with the distribution:
335 =item L<Catalyst::TraitFor::Model::DBIC::Schema::Caching>
337 =item L<Catalyst::TraitFor::Model::DBIC::Schema::Replicated>
343 Allows the use of a different C<storage_type> than what is set in your
344 C<schema_class> (which in turn defaults to C<::DBI> if not set in current
345 L<DBIx::Class>). Completely optional, and probably unnecessary for most
346 people until other storage backends become available for L<DBIx::Class>.
350 The keys you pass in the model configuration are available as attributes.
352 Other attributes available:
356 Your connect_info args normalized to hashref form (with dsn/user/password.) See
357 L<DBIx::Class::Storage::DBI/connect_info> for more info on the hashref form of
362 The model name L<Catalyst> uses to resolve this model, the part after
363 C<::Model::> or C<::M::> in your class name. E.g. if your class name is
364 C<MyApp::Model::DB> the L</model_name> will be C<DB>.
366 =head2 _default_cursor_class
368 What to reset your L<DBIx::Class::Storage::DBI/cursor_class> to if a custom one
369 doesn't work out. Defaults to L<DBIx::Class::Storage::DBI::Cursor>.
371 =head1 ATTRIBUTES FROM L<MooseX::Traits::Pluggable>
373 =head2 _original_class_name
375 The class name of your model before any L</traits> are applied. E.g.
380 Unresolved arrayref of traits passed in the config.
382 =head2 _resolved_traits
384 Traits you used resolved to full class names.
388 Methods not listed here are delegated to the connected schema used by the model
389 instance, so the following are equivalent:
391 $c->model('DB')->schema->my_accessor('foo');
393 $c->model('DB')->my_accessor('foo');
395 Methods on the model take precedence over schema methods.
399 Instantiates the Model based on the above-documented ->config parameters.
400 The only required parameter is C<schema_class>. C<connect_info> is
401 required in the case that C<schema_class> does not already have connection
402 information defined for it.
406 Accessor which returns the connected schema being used by the this model.
407 There are direct shortcuts on the model class itself for
408 schema->resultset, schema->source, and schema->class.
410 =head2 composed_schema
412 Accessor which returns the composed schema, which has no connection info,
413 which was used in constructing the C<schema> above. Useful for creating
414 new connections based on the same schema/model. There are direct shortcuts
415 from the model object for composed_schema->clone and composed_schema->connect
419 Shortcut for ->composed_schema->clone
423 Shortcut for ->composed_schema->connect
427 Shortcut for ->schema->source
431 Shortcut for ->schema->class
435 Shortcut for ->schema->resultset
439 Provides an accessor for the connected schema's storage object.
440 Used often for debugging and controlling transactions.
444 has schema_class => (
451 has storage_type => (is => 'rw', isa => Str);
453 has connect_info => (is => 'rw', isa => ConnectInfo, coerce => 1);
462 has _default_cursor_class => (
465 default => 'DBIx::Class::Storage::DBI::Cursor',
471 my $class = $self->_original_class_name;
472 my $schema_class = $self->schema_class;
474 if( !$self->connect_info ) {
475 if($schema_class->storage && $schema_class->storage->connect_info) {
476 $self->connect_info($schema_class->storage->connect_info);
479 die "Either ->config->{connect_info} must be defined for $class"
480 . " or $schema_class must have connect info defined on it."
481 . " Here's what we got:\n"
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}.": $@";
494 $self->composed_schema($schema_class->compose_namespace($class));
496 $self->meta->make_mutable;
497 $self->meta->add_attribute('schema',
499 isa => 'DBIx::Class::Schema',
500 handles => $self->_delegates
502 $self->meta->make_immutable;
504 $self->schema($self->composed_schema->clone);
506 $self->_pass_options_to_schema;
508 $self->schema->storage_type($self->storage_type)
509 if $self->storage_type;
511 $self->schema->connection($self->connect_info);
513 $self->_install_rs_models;
516 sub clone { shift->composed_schema->clone(@_); }
518 sub connect { shift->composed_schema->connect(@_); }
522 Called at C<BUILD> time before configuration, but after L</connect_info> is
523 set. To do something after configuuration use C<< after BUILD => >>.
529 =head2 ACCEPT_CONTEXT
531 Point of extension for doing things at C<< $c->model >> time with context,
532 returns the model instance, see L<Catalyst::Manual::Intro/ACCEPT_CONTEXT> for
537 sub ACCEPT_CONTEXT { shift }
539 sub _install_rs_models {
541 my $class = $self->_original_class_name;
545 my @sources = $self->schema->sources;
547 die "No sources found (did you forget to define your tables?)"
550 foreach my $moniker (@sources) {
551 my $classname = "${class}::$moniker";
552 *{"${classname}::ACCEPT_CONTEXT"} = sub {
554 shift->model($self->model_name)->resultset($moniker);
559 sub _reset_cursor_class {
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;
571 sub composed_schema {
573 my $class = $self->_original_class_name;
574 my $store = \$COMPOSED_CACHE{$class}{$self->schema_class};
576 $$store = shift if @_;
582 sub _build_model_name {
584 my $class = $self->_original_class_name;
585 (my $model_name = $class) =~ s/^[\w:]+::(?:Model|M):://;
593 # XXX change this to CMOP once CAG is updated
594 my @schema_methods = @{ Class::Inspector->methods($self->schema_class) };
596 # combine with any already added by other schemas
598 @{ $self->meta->find_attribute_by_name('schema')->handles }
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') };
606 @schema_methods{ @schema_methods, @handles } = ();
607 @schema_methods = keys %schema_methods;
609 my @my_methods = $self->meta->get_all_method_names;
611 @my_methods{@my_methods} = ();
614 for my $method (@schema_methods) {
615 push @delegates, $method unless exists $my_methods{$method};
621 sub _pass_options_to_schema {
624 my @attributes = map $_->name, $self->meta->get_all_attributes;
626 @attributes{@attributes} = ();
628 for my $opt (keys %$self) {
629 if (not exists $attributes{$opt}) {
630 die "Invalid schema option: $opt" unless $self->schema->can($opt);
632 $self->schema->$opt($self->{$opt});
637 __PACKAGE__->meta->make_immutable;
641 General Catalyst Stuff:
643 L<Catalyst::Manual>, L<Catalyst::Test>, L<Catalyst::Request>,
644 L<Catalyst::Response>, L<Catalyst::Helper>, L<Catalyst>,
646 Stuff related to DBIC and this Model style:
648 L<DBIx::Class>, L<DBIx::Class::Schema>,
649 L<DBIx::Class::Schema::Loader>, L<Catalyst::Helper::Model::DBIC::Schema>,
650 L<CatalystX::Component::Traits>, L<MooseX::Traits::Pluggable>
654 L<Catalyst::TraitFor::Model::DBIC::Schema::Caching>,
655 L<Catalyst::TraitFor::Model::DBIC::Schema::Replicated>
659 Brandon L Black C<blblack at gmail.com>
663 caelum: Rafael Kitover C<rkitover at cpan.org>
667 This program is free software, you can redistribute it and/or modify it
668 under the same terms as Perl itself.