Moving towards instance-based schemas
[dbsrgits/DBIx-Class-Historic.git] / lib / DBIx / Class / Schema.pm
1 package DBIx::Class::Schema;
2
3 use strict;
4 use warnings;
5 use DBIx::Class::DB;
6
7 use base qw/DBIx::Class/;
8
9 __PACKAGE__->load_components(qw/Exception/);
10 __PACKAGE__->mk_classdata('class_registrations' => {});
11 __PACKAGE__->mk_classdata('storage_type' => 'DBI');
12 __PACKAGE__->mk_classdata('storage');
13
14 =head1 NAME
15
16 DBIx::Class::Schema - composable schemas
17
18 =head1 SYNOPSIS
19
20 in My/Schema.pm
21
22   package My::Schema;
23
24   use base qw/DBIx::Class::Schema/;
25
26   __PACKAGE__->load_classes(qw/Foo Bar Baz/);
27
28 in My/Schema/Foo.pm
29
30   package My::Schema::Foo;
31
32   use base qw/DBIx::Class/;
33
34   __PACKAGE__->load_components(qw/PK::Auto::Pg Core/); # for example
35   __PACKAGE__->table('foo');
36   ...
37
38 in My/DB.pm
39
40   use My::Schema;
41
42   My::Schema->compose_connection('My::DB', $dsn, $user, $pass, $attrs);
43
44 then in app code
45
46   my @obj = My::DB::Foo->search({}); # My::DB::Foo isa My::Schema::Foo My::DB
47
48 =head1 DESCRIPTION
49
50 Creates database classes based on a schema. This allows you to have more than
51 one concurrent connection using the same database classes, by making 
52 subclasses under a new namespace for each connection. If you only need one 
53 class, you should probably use L<DBIx::Class::DB> directly instead.
54
55 NB: If you're used to L<Class::DBI> it's worth reading the L</SYNOPSIS>
56 carefully as DBIx::Class does things a little differently. Note in
57 particular which module inherits off which.
58
59 =head1 METHODS
60
61 =head2 register_class <component> <component_class>
62
63 Registers the class in the schema's class_registrations. This is a hash
64 containing database classes, keyed by their monikers. It's used by
65 compose_connection to create/modify all the existing database classes.
66
67 =cut
68
69 sub register_class {
70   my ($class, $name, $to_register) = @_;
71   my %reg = %{$class->class_registrations};
72   $reg{$name} = $to_register;
73   $class->class_registrations(\%reg);
74 }
75
76 =head2 registered_classes
77
78 Simple read-only accessor for the schema's registered classes. See 
79 register_class above if you want to modify it.
80
81
82 =cut
83
84 sub registered_classes {
85   return values %{shift->class_registrations};
86 }
87
88 =head2 class
89
90   my $class = $schema->class('Foo');
91
92 Shortcut to retrieve a single class by its registered name
93
94 =cut
95
96 sub class {
97   my ($self, $class) = @_;
98   return $self->class_registrations->{$class};
99 }
100
101 =head2  load_classes [<classes>, (<class>, <class>), {<namespace> => [<classes>]}]
102
103 Uses L<Module::Find> to find all classes under the database class' namespace,
104 or uses the classes you select.  Then it loads the component (using L<use>), 
105 and registers them (using B<register_class>);
106
107 It is possible to comment out classes with a leading '#', but note that perl
108 will think it's a mistake (trying to use a comment in a qw list) so you'll
109 need to add "no warnings 'qw';" before your load_classes call.
110
111 =cut
112
113 sub load_classes {
114   my ($class, @params) = @_;
115   
116   my %comps_for;
117   
118   if (@params) {
119     foreach my $param (@params) {
120       if (ref $param eq 'ARRAY') {
121         # filter out commented entries
122         my @modules = grep { $_ !~ /^#/ } @$param;
123         
124         push (@{$comps_for{$class}}, @modules);
125       }
126       elsif (ref $param eq 'HASH') {
127         # more than one namespace possible
128         for my $comp ( keys %$param ) {
129           # filter out commented entries
130           my @modules = grep { $_ !~ /^#/ } @{$param->{$comp}};
131
132           push (@{$comps_for{$comp}}, @modules);
133         }
134       }
135       else {
136         # filter out commented entries
137         push (@{$comps_for{$class}}, $param) if $param !~ /^#/;
138       }
139     }
140   } else {
141     eval "require Module::Find;";
142     $class->throw("No arguments to load_classes and couldn't load".
143       " Module::Find ($@)") if $@;
144     my @comp = map { substr $_, length "${class}::"  } Module::Find::findallmod($class);
145     $comps_for{$class} = \@comp;
146   }
147
148   foreach my $prefix (keys %comps_for) {
149     foreach my $comp (@{$comps_for{$prefix}||[]}) {
150       my $comp_class = "${prefix}::${comp}";
151       eval "use $comp_class"; # If it fails, assume the user fixed it
152       if ($@) {
153         die $@ unless $@ =~ /Can't locate/;
154       }
155       $class->register_class($comp => $comp_class);
156     }
157   }
158 }
159
160 =head2 compose_connection <target> <@db_info>
161
162 This is the most important method in this class. it takes a target namespace,
163 as well as dbh connection info, and creates a L<DBIx::Class::DB> class as
164 well as subclasses for each of your database classes in this namespace, using
165 this connection.
166
167 It will also setup a ->class method on the target class, which lets you
168 resolve database classes based on the schema component name, for example
169
170   MyApp::DB->class('Foo') # returns MyApp::DB::Foo, 
171                           # which ISA MyApp::Schema::Foo
172
173 This is the recommended API for accessing Schema generated classes, and 
174 using it might give you instant advantages with future versions of DBIC.
175
176 WARNING: Loading components into Schema classes after compose_connection
177 may not cause them to be seen by the classes in your target namespace due
178 to the dispatch table approach used by Class::C3. If you do this you may find
179 you need to call Class::C3->reinitialize() afterwards to get the behaviour
180 you expect.
181
182 =cut
183
184 sub compose_connection {
185   my ($class, $target, @info) = @_;
186   my $conn_class = "${target}::_db";
187   $class->setup_connection_class($conn_class, @info);
188   my $schema = $class->compose_namespace($target, $conn_class);
189   $schema->storage($conn_class->storage);
190   foreach my $class ($schema->registered_classes) {
191     my $source = $class->result_source;
192     $source = $source->new($source);
193     $source->schema($schema);
194     $source->result_class($class);
195     $class->mk_classdata(result_source => $source);
196   }
197   return $schema;
198 }
199
200 sub compose_namespace {
201   my ($class, $target, $base) = @_;
202   my %reg = %{ $class->class_registrations };
203   my %target;
204   my %map;
205   my $schema = bless({ }, $class);
206   while (my ($comp, $comp_class) = each %reg) {
207     my $target_class = "${target}::${comp}";
208     $class->inject_base($target_class, $comp_class, $base);
209     @map{$comp, $comp_class} = ($target_class, $target_class);
210   }
211   $schema->class_registrations(\%map);
212   {
213     no strict 'refs';
214     *{"${target}::schema"} =
215       sub { $schema };
216     *{"${target}::class"} =
217       sub { shift->schema->class(@_) };
218   }
219   $base->class_resolver($target);
220   return $schema;
221 }
222
223 =head2 setup_connection_class <$target> <@info>
224
225 Sets up a database connection class to inject between the schema
226 and the subclasses the schema creates.
227
228 =cut
229
230 sub setup_connection_class {
231   my ($class, $target, @info) = @_;
232   $class->inject_base($target => 'DBIx::Class::DB');
233   #$target->load_components('DB');
234   $target->connection(@info);
235 }
236
237 1;
238
239 =head1 AUTHORS
240
241 Matt S. Trout <mst@shadowcatsystems.co.uk>
242
243 =head1 LICENSE
244
245 You may distribute this code under the same terms as Perl itself.
246
247 =cut
248