1 package Catalyst::Model::DBIC::Schema;
6 extends 'Catalyst::Model';
10 use namespace::autoclean;
11 use Carp::Clan '^Catalyst::Model::DBIC::Schema';
16 use Catalyst::Model::DBIC::Schema::Types
17 qw/ConnectInfo SchemaClass CursorClass/;
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 Authentication::Store::DBIC in MyApp.pm:
97 use Catalyst qw/... Authentication::Store::DBIC/;
101 __PACKAGE__->config->{authentication}{dbic} = {
102 user_class => 'FilmDB::Actor',
103 user_field => 'name',
104 password_field => 'password'
107 C<< $c->model('Schema::Source') >> returns a L<DBIx::Class::ResultSet> for
108 the source name parameter passed. To find out more about which methods can
109 be called on a ResultSet, or how to add your own methods to it, please see
110 the ResultSet documentation in the L<DBIx::Class> distribution.
112 Some examples are given below:
114 # to access schema methods directly:
115 $c->model('FilmDB')->schema->source(...);
117 # to access the source object, resultset, and class:
118 $c->model('FilmDB')->source(...);
119 $c->model('FilmDB')->resultset(...);
120 $c->model('FilmDB')->class(...);
122 # For resultsets, there's an even quicker shortcut:
123 $c->model('FilmDB::Actor')
124 # is the same as $c->model('FilmDB')->resultset('Actor')
126 # To get the composed schema for making new connections:
127 my $newconn = $c->model('FilmDB')->composed_schema->connect(...);
129 # Or the same thing via a convenience shortcut:
130 my $newconn = $c->model('FilmDB')->connect(...);
132 # or, if your schema works on different storage drivers:
133 my $newconn = $c->model('FilmDB')->composed_schema->clone();
134 $newconn->storage_type('::LDAP');
135 $newconn->connection(...);
137 # and again, a convenience shortcut
138 my $newconn = $c->model('FilmDB')->clone();
139 $newconn->storage_type('::LDAP');
140 $newconn->connection(...);
144 This is a Catalyst Model for L<DBIx::Class::Schema>-based Models. See
145 the documentation for L<Catalyst::Helper::Model::DBIC::Schema> for
146 information on generating these Models via Helper scripts.
148 When your Catalyst app starts up, a thin Model layer is created as an
149 interface to your DBIC Schema. It should be clearly noted that the model
150 object returned by C<< $c->model('FilmDB') >> is NOT itself a DBIC schema or
151 resultset object, but merely a wrapper proving L<methods|/METHODS> to access
152 the underlying schema.
154 In addition to this model class, a shortcut class is generated for each
155 source in the schema, allowing easy and direct access to a resultset of the
156 corresponding type. These generated classes are even thinner than the model
157 class, providing no public methods but simply hooking into Catalyst's
158 model() accessor via the
159 L<ACCEPT_CONTEXT|Catalyst::Component/ACCEPT_CONTEXT> mechanism. The complete
160 contents of each generated class is roughly equivalent to the following:
162 package MyApp::Model::FilmDB::Actor
165 $c->model('FilmDB')->resultset('Actor');
168 In short, there are three techniques available for obtaining a DBIC
172 my $rs = $c->model('FilmDB')->schema->resultset('Actor');
174 # using the shortcut method on the model object
175 my $rs = $c->model('FilmDB')->resultset('Actor');
177 # using the generated class directly
178 my $rs = $c->model('FilmDB::Actor');
180 In order to add methods to a DBIC resultset, you cannot simply add them to
181 the source (row, table) definition class; you must define a separate custom
182 resultset class. See L<DBIx::Class::Manual::Cookbook/"Predefined searches">
185 =head1 CONFIG PARAMETERS
189 This is the classname of your L<DBIx::Class::Schema> Schema. It needs
190 to be findable in C<@INC>, but it does not need to be inside the
191 C<Catalyst::Model::> namespace. This parameter is required.
195 This is an arrayref of connection parameters, which are specific to your
196 C<storage_type> (see your storage type documentation for more details).
197 If you only need one parameter (e.g. the DSN), you can just pass a string
198 instead of an arrayref.
200 This is not required if C<schema_class> already has connection information
201 defined inside itself (which isn't highly recommended, but can be done)
203 For L<DBIx::Class::Storage::DBI>, which is the only supported
204 C<storage_type> in L<DBIx::Class> at the time of this writing, the
205 parameters are your dsn, username, password, and connect options hashref.
207 See L<DBIx::Class::Storage::DBI/connect_info> for a detailed explanation
208 of the arguments supported.
213 dsn => 'dbi:Pg:dbname=mypgdb',
219 dsn => 'dbi:SQLite:dbname=foo.db',
221 'PRAGMA synchronous = OFF',
226 dsn => 'dbi:Pg:dbname=mypgdb',
231 'some SQL statement',
232 'another SQL statement',
236 Or using L<Config::General>:
239 schema_class MyApp::Schema::FilmDB
242 dsn dbi:Pg:dbname=mypgdb
247 on_connect_do some SQL statement
248 on_connect_do another SQL statement
255 schema_class MyApp::Schema::FilmDB
256 connect_info dbi:SQLite:dbname=foo.db
269 on_connect_do: [ "alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS'" ]
270 cursor_class: 'DBIx::Class::Cursor::Cached'
273 The old arrayref style with hashrefs for L<DBI> then L<DBIx::Class> options is also
277 'dbi:Pg:dbname=mypgdb',
286 'some SQL statement',
287 'another SQL statement',
294 Array of Traits to apply to the instance. Traits are L<Moose::Role>s.
296 They are relative to the C<< MyApp::Model::DB::Trait:: >>, then the C<<
297 Catalyst::Model::DBIC::Schema::Trait:: >> namespaces, unless prefixed with C<+>
298 in which case they are taken to be a fully qualified name. E.g.:
301 traits +MyApp::DB::Trait::Foo
303 A new instance is created at application time, so any consumed required
304 attributes, coercions and modifiers will work.
306 Traits are applied at L<Catalyst::Component/COMPONENT> time using L<MooseX::Traits>.
308 C<ref $self> will be an anon class if any traits are applied, C<<
309 $self->_original_class_name >> will be the original class.
311 When writing a Trait, interesting points to modify are C<BUILD>, L</setup> and
314 Traits that come with the distribution:
318 =item L<Catalyst::Model::DBIC::Schema::Trait::Caching>
320 =item L<Catalyst::Model::DBIC::Schema::Trait::Replicated>
326 Allows the use of a different C<storage_type> than what is set in your
327 C<schema_class> (which in turn defaults to C<::DBI> if not set in current
328 L<DBIx::Class>). Completely optional, and probably unnecessary for most
329 people until other storage backends become available for L<DBIx::Class>.
333 The keys you pass in the model configuration are available as attributes.
335 Other attributes available:
339 Your connect_info args normalized to hashref form (with dsn/user/password.) See
340 L<DBIx::Class::Storage::DBI/connect_info> for more info on the hashref form of
345 The model name L<Catalyst> uses to resolve this model, the part after
346 C<::Model::> or C<::M::> in your class name. E.g. if your class name is
347 C<MyApp::Model::DB> the L</model_name> will be C<DB>.
349 =head2 _original_class_name
351 The class name of your model before any L</traits> are applied. E.g.
354 =head2 _default_cursor_class
356 What to rest your L<DBIx::Class::Storage::DBI/cursor_class> if a custom one
357 doesn't work out. Defaults to L<DBIx::Class::Storage::DBI::Cursor>.
361 Unresolved arrayref of traits passed at C<COMPONENT> time.
363 =head2 _resolved_traits
365 Traits you used resolved to full class names.
371 Instantiates the Model based on the above-documented ->config parameters.
372 The only required parameter is C<schema_class>. C<connect_info> is
373 required in the case that C<schema_class> does not already have connection
374 information defined for it.
378 Accessor which returns the connected schema being used by the this model.
379 There are direct shortcuts on the model class itself for
380 schema->resultset, schema->source, and schema->class.
382 =head2 composed_schema
384 Accessor which returns the composed schema, which has no connection info,
385 which was used in constructing the C<schema> above. Useful for creating
386 new connections based on the same schema/model. There are direct shortcuts
387 from the model object for composed_schema->clone and composed_schema->connect
391 Shortcut for ->composed_schema->clone
395 Shortcut for ->composed_schema->connect
399 Shortcut for ->schema->source
403 Shortcut for ->schema->class
407 Shortcut for ->schema->resultset
411 Provides an accessor for the connected schema's storage object.
412 Used often for debugging and controlling transactions.
416 has schema => (is => 'rw', isa => 'DBIx::Class::Schema');
418 has schema_class => (
425 has storage_type => (is => 'rw', isa => Str);
427 has connect_info => (is => 'ro', isa => ConnectInfo, coerce => 1);
436 has _traits => (is => 'ro', isa => ArrayRef);
437 has _resolved_traits => (is => 'ro', isa => ArrayRef);
439 has _default_cursor_class => (
442 default => 'DBIx::Class::Storage::DBI::Cursor',
446 has _original_class_name => (
450 default => sub { blessed $_[0] },
454 my ($class, $app, $args) = @_;
456 $args = $class->merge_config_hashes($class->config, $args);
458 if (my $traits = delete $args->{traits}) {
459 my @traits = $class->_resolve_traits($traits->flatten);
460 return $class->new_with_traits({
462 _original_class_name => $class,
464 _resolved_traits => \@traits,
469 return $class->new($args);
474 my $class = ref $self;
475 my $schema_class = $self->schema_class;
477 if( !$self->connect_info ) {
478 if($schema_class->storage && $schema_class->storage->connect_info) {
479 $self->connect_info($schema_class->storage->connect_info);
482 die "Either ->config->{connect_info} must be defined for $class"
483 . " or $schema_class must have connect info defined on it."
484 . " Here's what we got:\n"
489 if (exists $self->connect_info->{cursor_class}) {
490 eval { Class::MOP::load_class($self->connect_info->{cursor_class}) }
491 or croak "invalid connect_info: Cannot load your cursor_class"
492 . " ".$self->connect_info->{cursor_class}.": $@";
497 $self->composed_schema($schema_class->compose_namespace($class));
499 $self->schema($self->composed_schema->clone);
501 $self->schema->storage_type($self->storage_type)
502 if $self->storage_type;
504 $self->schema->connection($self->connect_info);
506 $self->_install_rs_models;
509 sub clone { shift->composed_schema->clone(@_); }
511 sub connect { shift->composed_schema->connect(@_); }
513 sub storage { shift->schema->storage(@_); }
515 sub resultset { shift->schema->resultset(@_); }
519 Called at C<BUILD>> time before configuration, but after L</connect_info> is
520 set. To do something after configuuration use C<< after BUILD => >>.
526 =head2 ACCEPT_CONTEXT
528 Point of extension for doing things at C<< $c->model >> time with context,
529 returns the model instance, see L<Catalyst::Manual::Intro/ACCEPT_CONTEXT> for
534 sub ACCEPT_CONTEXT { shift }
536 sub _install_rs_models {
538 my $class = $self->_original_class_name;
542 my @sources = $self->schema->sources;
544 die "No sources found (did you forget to define your tables?)"
547 foreach my $moniker (@sources) {
548 my $classname = "${class}::$moniker";
549 *{"${classname}::ACCEPT_CONTEXT"} = sub {
551 shift->model($self->model_name)->resultset($moniker);
556 sub _reset_cursor_class {
559 if ($self->storage->can('cursor_class')) {
560 $self->storage->cursor_class($self->_default_cursor_class)
561 if $self->storage->cursor_class ne $self->_default_cursor_class;
568 sub composed_schema {
570 my $class = $self->_original_class_name;
571 my $store = \$COMPOSED_CACHE{$class}{$self->schema_class};
573 $$store = shift if @_;
579 sub _resolve_traits {
580 my ($class, @names) = @_;
583 my @search_ns = grep !/^(?:Moose|Class::MOP)::/,
584 $class->meta->class_precedence_list;
588 OUTER: for my $name (@names) {
589 if ($name =~ /^\+(.*)/) {
593 for my $ns (@search_ns) {
594 my $full = "${ns}::${base}::${name}";
595 if (eval { Class::MOP::load_class($full) }) {
605 sub _build_model_name {
607 my $class = $self->_original_class_name;
608 (my $model_name = $class) =~ s/^[\w:]+::(?:Model|M):://;
613 __PACKAGE__->meta->make_immutable;
617 General Catalyst Stuff:
619 L<Catalyst::Manual>, L<Catalyst::Test>, L<Catalyst::Request>,
620 L<Catalyst::Response>, L<Catalyst::Helper>, L<Catalyst>,
622 Stuff related to DBIC and this Model style:
624 L<DBIx::Class>, L<DBIx::Class::Schema>,
625 L<DBIx::Class::Schema::Loader>, L<Catalyst::Helper::Model::DBIC::Schema>,
626 L<MooseX::Object::Pluggable>
630 L<Catalyst::Model::DBIC::Schema::Trait::Caching>,
631 L<Catalyst::Model::DBIC::Schema::Trait::Replicated>
635 Brandon L Black, C<blblack at gmail.com>
639 Rafael Kitover, C<rkitover at cpan.org>
643 This program is free software, you can redistribute it and/or modify it
644 under the same terms as Perl itself.