Allow specifying a custom loader_class in loader_options
[dbsrgits/DBIx-Class-Schema-Loader.git] / lib / DBIx / Class / Schema / Loader.pm
1 package DBIx::Class::Schema::Loader;
2
3 use strict;
4 use warnings;
5 use base qw/DBIx::Class::Schema Class::Data::Accessor/;
6 use Carp::Clan qw/^DBIx::Class/;
7 use UNIVERSAL::require;
8 use Class::C3;
9 use Scalar::Util qw/ weaken /;
10
11 # Always remember to do all digits for the version even if they're 0
12 # i.e. first release of 0.XX *must* be 0.XX000. This avoids fBSD ports
13 # brain damage and presumably various other packaging systems too
14 our $VERSION = '0.04999_04';
15
16 __PACKAGE__->mk_classaccessor('_loader_args' => {});
17 __PACKAGE__->mk_classaccessors(qw/dump_to_dir _loader_invoked _loader/);
18
19 =head1 NAME
20
21 DBIx::Class::Schema::Loader - Dynamic definition of a DBIx::Class::Schema
22
23 =head1 SYNOPSIS
24
25   package My::Schema;
26   use base qw/DBIx::Class::Schema::Loader/;
27
28   __PACKAGE__->loader_options(
29       constraint              => '^foo.*',
30       # debug                 => 1,
31   );
32
33   # in seperate application code ...
34
35   use My::Schema;
36
37   my $schema1 = My::Schema->connect( $dsn, $user, $password, $attrs);
38   # -or-
39   my $schema1 = "My::Schema"; $schema1->connection(as above);
40
41 =head1 DESCRIPTION 
42
43 DBIx::Class::Schema::Loader automates the definition of a
44 L<DBIx::Class::Schema> by scanning database table definitions and
45 setting up the columns, primary keys, and relationships.
46
47 DBIx::Class::Schema::Loader currently supports only the DBI storage type.
48 It has explicit support for L<DBD::Pg>, L<DBD::mysql>, L<DBD::DB2>,
49 L<DBD::SQLite>, and L<DBD::Oracle>.  Other DBI drivers may function to
50 a greater or lesser degree with this loader, depending on how much of the
51 DBI spec they implement, and how standard their implementation is.
52
53 Patches to make other DBDs work correctly welcome.
54
55 See L<DBIx::Class::Schema::Loader::DBI::Writing> for notes on writing
56 your own vendor-specific subclass for an unsupported DBD driver.
57
58 This module requires L<DBIx::Class> 0.07006 or later, and obsoletes
59 the older L<DBIx::Class::Loader>.
60
61 This module is designed more to get you up and running quickly against
62 an existing database, or to be effective for simple situations, rather
63 than to be what you use in the long term for a complex database/project.
64
65 That being said, transitioning your code from a Schema generated by this
66 module to one that doesn't use this module should be straightforward and
67 painless, so don't shy away from it just for fears of the transition down
68 the road.
69
70 =head1 METHODS
71
72 =head2 loader_options
73
74 Example in Synopsis above demonstrates a few common arguments.  For
75 detailed information on all of the arguments, most of which are
76 only useful in fairly complex scenarios, see the
77 L<DBIx::Class::Schema::Loader::Base> documentation.
78
79 If you intend to use C<loader_options>, you must call
80 C<loader_options> before any connection is made, or embed the
81 C<loader_options> in the connection information itself as shown
82 below.  Setting C<loader_options> after the connection has
83 already been made is useless.
84
85 =cut
86
87 sub loader_options {
88     my $self = shift;
89     
90     my %args = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
91     $self->_loader_args(\%args);
92
93     $self;
94 }
95
96 sub _invoke_loader {
97     my $self = shift;
98     my $class = ref $self || $self;
99
100     my $args = $self->_loader_args;
101
102     # set up the schema/schema_class arguments
103     $args->{schema} = $self;
104     $args->{schema_class} = $class;
105     weaken($args->{schema}) if ref $self;
106     $args->{dump_directory} ||= $self->dump_to_dir;
107
108     # XXX this only works for relative storage_type, like ::DBI ...
109     my $impl = $args->{loader_class}
110       || "DBIx::Class::Schema::Loader" . $self->storage_type;
111     $impl->require or
112       croak qq/Could not load storage_type loader "$impl": / .
113             qq/"$UNIVERSAL::require::ERROR"/;
114
115     $self->_loader($impl->new(%$args));
116     $self->_loader->load;
117     $self->_loader_invoked(1);
118
119     $self;
120 }
121
122 =head2 connection
123
124 See L<DBIx::Class::Schema> for basic usage.
125
126 If the final argument is a hashref, and it contains a key C<loader_options>,
127 that key will be deleted, and its value will be used for the loader options,
128 just as if set via the L</loader_options> method above.
129
130 The actual auto-loading operation (the heart of this module) will be invoked
131 as soon as the connection information is defined.
132
133 =cut
134
135 sub connection {
136     my $self = shift;
137
138     if($_[-1] && ref $_[-1] eq 'HASH') {
139         if(my $loader_opts = delete $_[-1]->{loader_options}) {
140             $self->loader_options($loader_opts);
141             pop @_ if !keys %{$_[-1]};
142         }
143     }
144
145     $self = $self->next::method(@_);
146
147     my $class = ref $self || $self;
148     if(!$class->_loader_invoked) {
149         $self->_invoke_loader
150     }
151
152     return $self;
153 }
154
155 =head2 clone
156
157 See L<DBIx::Class::Schema>.
158
159 =cut
160
161 sub clone {
162     my $self = shift;
163
164     my $clone = $self->next::method(@_);
165
166     if($clone->_loader_args) {
167         $clone->_loader_args->{schema} = $clone;
168         weaken($clone->_loader_args->{schema});
169     }
170
171     $clone;
172 }
173
174 =head2 dump_to_dir
175
176 Argument: directory name.
177
178 Calling this as a class method on either L<DBIx::Class::Schema::Loader>
179 or any derived schema class will cause all affected schemas to dump
180 manual versions of themselves to the named directory when they are
181 loaded.  In order to be effective, this must be set before defining a
182 connection on this schema class or any derived object (as the loading
183 happens as soon as both a connection and loader_options are set, and
184 only once per class).
185
186 See L<DBIx::Class::Schema::Loader::Base/dump_directory> for more
187 details on the dumping mechanism.
188
189 This can also be set at module import time via the import option
190 C<dump_to_dir:/foo/bar> to L<DBIx::Class::Schema::Loader>, where
191 C</foo/bar> is the target directory.
192
193 Examples:
194
195     # My::Schema isa DBIx::Class::Schema::Loader, and has connection info
196     #   hardcoded in the class itself:
197     perl -MDBIx::Class::Schema::Loader=dump_to_dir:/foo/bar -MMy::Schema -e1
198
199     # Same, but no hard-coded connection, so we must provide one:
200     perl -MDBIx::Class::Schema::Loader=dump_to_dir:/foo/bar -MMy::Schema -e 'My::Schema->connection("dbi:Pg:dbname=foo", ...)'
201
202     # Or as a class method, as long as you get it done *before* defining a
203     #  connection on this schema class or any derived object:
204     use My::Schema;
205     My::Schema->dump_to_dir('/foo/bar');
206     My::Schema->connection(........);
207
208     # Or as a class method on the DBIx::Class::Schema::Loader itself, which affects all
209     #   derived schemas
210     use My::Schema;
211     use My::OtherSchema;
212     DBIx::Class::Schema::Loader->dump_to_dir('/foo/bar');
213     My::Schema->connection(.......);
214     My::OtherSchema->connection(.......);
215
216     # Another alternative to the above:
217     use DBIx::Class::Schema::Loader qw| dump_to_dir:/foo/bar |;
218     use My::Schema;
219     use My::OtherSchema;
220     My::Schema->connection(.......);
221     My::OtherSchema->connection(.......);
222
223 =cut
224
225 sub import {
226     my $self = shift;
227     return if !@_;
228     foreach my $opt (@_) {
229         if($opt =~ m{^dump_to_dir:(.*)$}) {
230             $self->dump_to_dir($1)
231         }
232         elsif($opt eq 'make_schema_at') {
233             no strict 'refs';
234             my $cpkg = (caller)[0];
235             *{"${cpkg}::make_schema_at"} = \&make_schema_at;
236         }
237     }
238 }
239
240 =head2 make_schema_at
241
242 This simple function allows one to create a Loader-based schema
243 in-memory on the fly without any on-disk class files of any
244 kind.  When used with the C<dump_directory> option, you can
245 use this to generate a rough draft manual schema from a dsn
246 without the intermediate step of creating a physical Loader-based
247 schema class.
248
249 The return value is the input class name.
250
251 This function can be exported/imported by the normal means, as
252 illustrated in these Examples:
253
254     # Simple example, creates as a new class 'New::Schema::Name' in
255     #  memory in the running perl interpreter.
256     use DBIx::Class::Schema::Loader qw/ make_schema_at /;
257     make_schema_at(
258         'New::Schema::Name',
259         { debug => 1 },
260         [ 'dbi:Pg:dbname="foo"','postgres' ],
261     );
262
263     # Complex: dump loaded schema to disk, all from the commandline:
264     perl -MDBIx::Class::Schema::Loader=make_schema_at,dump_to_dir:./lib -e 'make_schema_at("New::Schema::Name", { debug => 1 }, [ "dbi:Pg:dbname=foo","postgres" ])'
265
266     # Same, but inside a script, and using a different way to specify the
267     # dump directory:
268     use DBIx::Class::Schema::Loader qw/ make_schema_at /;
269     make_schema_at(
270         'New::Schema::Name',
271         { debug => 1, dump_directory => './lib' },
272         [ 'dbi:Pg:dbname="foo"','postgres' ],
273     );
274
275 =cut
276
277 sub make_schema_at {
278     my ($target, $opts, $connect_info) = @_;
279
280     {
281         no strict 'refs';
282         @{$target . '::ISA'} = qw/DBIx::Class::Schema::Loader/;
283     }
284
285     $target->loader_options($opts);
286     $target->connection(@$connect_info);
287 }
288
289 =head2 rescan
290
291 Re-scans the database for newly added tables since the initial
292 load, and adds them to the schema at runtime, including relationships,
293 etc.  Does not process drops or changes.
294
295 Returns a list of the new monikers added.
296
297 =cut
298
299 sub rescan { my $self = shift; $self->_loader->rescan($self) }
300
301 =head1 EXAMPLE
302
303 Using the example in L<DBIx::Class::Manual::ExampleSchema> as a basis
304 replace the DB::Main with the following code:
305
306   package DB::Main;
307
308   use base qw/DBIx::Class::Schema::Loader/;
309
310   __PACKAGE__->loader_options(
311       debug         => 1,
312   );
313   __PACKAGE__->connection('dbi:SQLite:example.db');
314
315   1;
316
317 and remove the Main directory tree (optional).  Every thing else
318 should work the same
319
320 =head1 KNOWN ISSUES
321
322 =head2 Multiple Database Schemas
323
324 Currently the loader is limited to working within a single schema
325 (using the database vendors' definition of "schema").  If you
326 have a multi-schema database with inter-schema relationships (which
327 is easy to do in PostgreSQL or DB2 for instance), you only get to
328 automatically load the tables of one schema, and any relationships
329 to tables in other schemas will be silently ignored.
330
331 At some point in the future, an intelligent way around this might be
332 devised, probably by allowing the C<db_schema> option to be an
333 arrayref of schemas to load.
334
335 In "normal" L<DBIx::Class::Schema> usage, manually-defined
336 source classes and relationships have no problems crossing vendor schemas.
337
338 =head1 AUTHOR
339
340 Brandon Black, C<blblack@gmail.com>
341
342 Based on L<DBIx::Class::Loader> by Sebastian Riedel
343
344 Based upon the work of IKEBE Tomohiro
345
346 =head1 THANK YOU
347
348 Matt S Trout, all of the #dbix-class folks, and everyone who's ever sent
349 in a bug report or suggestion.
350
351 =head1 LICENSE
352
353 This library is free software; you can redistribute it and/or modify it under
354 the same terms as Perl itself.
355
356 =head1 SEE ALSO
357
358 L<DBIx::Class>, L<DBIx::Class::Manual::ExampleSchema>
359
360 =cut
361
362 1;