89cf56fe471bdcd4e5ad10e45e7ef080b39d9eed
[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::Accessor::Grouped/;
6 use Carp::Clan qw/^DBIx::Class/;
7 use Class::C3;
8 use Scalar::Util qw/ weaken /;
9
10 # Always remember to do all digits for the version even if they're 0
11 # i.e. first release of 0.XX *must* be 0.XX000. This avoids fBSD ports
12 # brain damage and presumably various other packaging systems too
13 our $VERSION = '0.04999_12';
14
15 __PACKAGE__->mk_group_accessors('inherited', qw/
16                                 _loader_args
17                                 dump_to_dir
18                                 _loader_invoked
19                                 _loader
20                                 loader_class
21                                 naming
22 /);
23 __PACKAGE__->_loader_args({});
24
25 =head1 NAME
26
27 DBIx::Class::Schema::Loader - Dynamic definition of a DBIx::Class::Schema
28
29 =head1 SYNOPSIS
30
31   ### use this module to generate a set of class files
32
33   # in a script
34   use DBIx::Class::Schema::Loader qw/ make_schema_at /;
35   make_schema_at(
36       'My::Schema',
37       { debug => 1,
38         dump_directory => './lib',
39       },
40       [ 'dbi:Pg:dbname="foo"', 'myuser', 'mypassword' ],
41   );
42
43   # from the command line or a shell script with dbicdump (distributed
44   # with this module).  Do `perldoc dbicdump` for usage.
45   dbicdump -o dump_directory=./lib \
46            -o debug=1 \
47            My::Schema \
48            'dbi:Pg:dbname=foo' \
49            myuser \
50            mypassword
51
52   ### or generate and load classes at runtime
53   # note: this technique is not recommended
54   # for use in production code
55
56   package My::Schema;
57   use base qw/DBIx::Class::Schema::Loader/;
58
59   __PACKAGE__->loader_options(
60       constraint              => '^foo.*',
61       # debug                 => 1,
62   );
63
64   #### in application code elsewhere:
65
66   use My::Schema;
67
68   my $schema1 = My::Schema->connect( $dsn, $user, $password, $attrs);
69   # -or-
70   my $schema1 = "My::Schema"; $schema1->connection(as above);
71
72 =head1 DESCRIPTION 
73
74 DBIx::Class::Schema::Loader automates the definition of a
75 L<DBIx::Class::Schema> by scanning database table definitions and
76 setting up the columns, primary keys, and relationships.
77
78 DBIx::Class::Schema::Loader currently supports only the DBI storage type.
79 It has explicit support for L<DBD::Pg>, L<DBD::mysql>, L<DBD::DB2>,
80 L<DBD::SQLite>, and L<DBD::Oracle>.  Other DBI drivers may function to
81 a greater or lesser degree with this loader, depending on how much of the
82 DBI spec they implement, and how standard their implementation is.
83
84 Patches to make other DBDs work correctly welcome.
85
86 See L<DBIx::Class::Schema::Loader::DBI::Writing> for notes on writing
87 your own vendor-specific subclass for an unsupported DBD driver.
88
89 This module requires L<DBIx::Class> 0.07006 or later, and obsoletes
90 the older L<DBIx::Class::Loader>.
91
92 This module is designed more to get you up and running quickly against
93 an existing database, or to be effective for simple situations, rather
94 than to be what you use in the long term for a complex database/project.
95
96 That being said, transitioning your code from a Schema generated by this
97 module to one that doesn't use this module should be straightforward and
98 painless, so don't shy away from it just for fears of the transition down
99 the road.
100
101 =head1 METHODS
102
103 =head2 loader_class
104
105 =over 4
106
107 =item Argument: $loader_class
108
109 =back
110
111 Set the loader class to be instantiated when L</connection> is called.
112 If the classname starts with "::", "DBIx::Class::Schema::Loader" is
113 prepended. Defaults to L<DBIx::Class::Schema/storage_type> (which must
114 start with "::" when using L<DBIx::Class::Schema::Loader>).
115
116 This is mostly useful for subclassing existing loaders or in conjunction
117 with L</dump_to_dir>.
118
119 =head2 loader_options
120
121 =over 4
122
123 =item Argument: \%loader_options
124
125 =back
126
127 Example in Synopsis above demonstrates a few common arguments.  For
128 detailed information on all of the arguments, most of which are
129 only useful in fairly complex scenarios, see the
130 L<DBIx::Class::Schema::Loader::Base> documentation.
131
132 If you intend to use C<loader_options>, you must call
133 C<loader_options> before any connection is made, or embed the
134 C<loader_options> in the connection information itself as shown
135 below.  Setting C<loader_options> after the connection has
136 already been made is useless.
137
138 =cut
139
140 sub loader_options {
141     my $self = shift;
142
143     my %args = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
144     $self->_loader_args(\%args);
145
146     $self;
147 }
148
149 sub _invoke_loader {
150     my $self = shift;
151     my $class = ref $self || $self;
152
153     my $args = $self->_loader_args;
154
155     # set up the schema/schema_class arguments
156     $args->{schema} = $self;
157     $args->{schema_class} = $class;
158     weaken($args->{schema}) if ref $self;
159     $args->{dump_directory} ||= $self->dump_to_dir;
160     $args->{naming} = $self->naming if $self->naming;
161
162     # XXX this only works for relative storage_type, like ::DBI ...
163     my $impl = $self->loader_class
164       || "DBIx::Class::Schema::Loader" . $self->storage_type;
165     $impl = "DBIx::Class::Schema::Loader${impl}" if $impl =~ /^::/;
166     eval { $self->ensure_class_loaded($impl) };
167     croak qq/Could not load storage_type loader "$impl": "$@"/ if $@;
168
169     $self->_loader($impl->new(%$args));
170     $self->_loader->load;
171     $self->_loader_invoked(1);
172
173     $self;
174 }
175
176 =head2 connection
177
178 =over 4
179
180 =item Arguments: @args
181
182 =item Return Value: $new_schema
183
184 =back
185
186 See L<DBIx::Class::Schema/connection> for basic usage.
187
188 If the final argument is a hashref, and it contains the keys C<loader_options>
189 or C<loader_class>, those keys will be deleted, and their values value will be
190 used for the loader options or class, respectively, just as if set via the
191 L</loader_options> or L</loader_class> methods above.
192
193 The actual auto-loading operation (the heart of this module) will be invoked
194 as soon as the connection information is defined.
195
196 =cut
197
198 sub connection {
199     my $self = shift;
200
201     if($_[-1] && ref $_[-1] eq 'HASH') {
202         for my $option (qw/ loader_class loader_options result_base_class schema_base_class/) {
203             if(my $value = delete $_[-1]->{$option}) {
204                 $self->$option($value);
205             }
206         }
207         pop @_ if !keys %{$_[-1]};
208     }
209
210     $self = $self->next::method(@_);
211
212     my $class = ref $self || $self;
213     if(!$class->_loader_invoked) {
214         $self->_invoke_loader
215     }
216
217     return $self;
218 }
219
220 =head2 clone
221
222 See L<DBIx::Class::Schema/clone>.
223
224 =cut
225
226 sub clone {
227     my $self = shift;
228
229     my $clone = $self->next::method(@_);
230
231     if($clone->_loader_args) {
232         $clone->_loader_args->{schema} = $clone;
233         weaken($clone->_loader_args->{schema});
234     }
235
236     $clone;
237 }
238
239 =head2 dump_to_dir
240
241 =over 4
242
243 =item Argument: $directory
244
245 =back
246
247 Calling this as a class method on either L<DBIx::Class::Schema::Loader>
248 or any derived schema class will cause all schemas to dump
249 manual versions of themselves to the named directory when they are
250 loaded.  In order to be effective, this must be set before defining a
251 connection on this schema class or any derived object (as the loading
252 happens as soon as both a connection and loader_options are set, and
253 only once per class).
254
255 See L<DBIx::Class::Schema::Loader::Base/dump_directory> for more
256 details on the dumping mechanism.
257
258 This can also be set at module import time via the import option
259 C<dump_to_dir:/foo/bar> to L<DBIx::Class::Schema::Loader>, where
260 C</foo/bar> is the target directory.
261
262 Examples:
263
264     # My::Schema isa DBIx::Class::Schema::Loader, and has connection info
265     #   hardcoded in the class itself:
266     perl -MDBIx::Class::Schema::Loader=dump_to_dir:/foo/bar -MMy::Schema -e1
267
268     # Same, but no hard-coded connection, so we must provide one:
269     perl -MDBIx::Class::Schema::Loader=dump_to_dir:/foo/bar -MMy::Schema -e 'My::Schema->connection("dbi:Pg:dbname=foo", ...)'
270
271     # Or as a class method, as long as you get it done *before* defining a
272     #  connection on this schema class or any derived object:
273     use My::Schema;
274     My::Schema->dump_to_dir('/foo/bar');
275     My::Schema->connection(........);
276
277     # Or as a class method on the DBIx::Class::Schema::Loader itself, which affects all
278     #   derived schemas
279     use My::Schema;
280     use My::OtherSchema;
281     DBIx::Class::Schema::Loader->dump_to_dir('/foo/bar');
282     My::Schema->connection(.......);
283     My::OtherSchema->connection(.......);
284
285     # Another alternative to the above:
286     use DBIx::Class::Schema::Loader qw| dump_to_dir:/foo/bar |;
287     use My::Schema;
288     use My::OtherSchema;
289     My::Schema->connection(.......);
290     My::OtherSchema->connection(.......);
291
292 =cut
293
294 sub import {
295     my $self = shift;
296
297     return if !@_;
298
299     my $cpkg = (caller)[0];
300
301     foreach my $opt (@_) {
302         if($opt =~ m{^dump_to_dir:(.*)$}) {
303             $self->dump_to_dir($1)
304         }
305         elsif($opt eq 'make_schema_at') {
306             no strict 'refs';
307             *{"${cpkg}::make_schema_at"} = \&make_schema_at;
308         }
309         elsif($opt eq 'naming') {
310             no strict 'refs';
311             *{"${cpkg}::naming"} = sub { $self->naming(@_) };
312         }
313     }
314 }
315
316 =head2 make_schema_at
317
318 =over 4
319
320 =item Arguments: $schema_class_name, \%loader_options, \@connect_info
321
322 =item Return Value: $schema_class_name
323
324 =back
325
326 This function creates a DBIx::Class schema from an existing RDBMS
327 schema.  With the C<dump_directory> option, generates a set of
328 DBIx::Class classes from an existing database schema read from the
329 given dsn.  Without a C<dump_directory>, creates schema classes in
330 memory at runtime without generating on-disk class files.
331
332 For a complete list of supported loader_options, see
333 L<DBIx::Class::Schema::Loader::Base>
334
335 This function can be imported in the usual way, as illustrated in
336 these Examples:
337
338     # Simple example, creates as a new class 'New::Schema::Name' in
339     #  memory in the running perl interpreter.
340     use DBIx::Class::Schema::Loader qw/ make_schema_at /;
341     make_schema_at(
342         'New::Schema::Name',
343         { debug => 1 },
344         [ 'dbi:Pg:dbname="foo"','postgres' ],
345     );
346
347     # Inside a script, specifying a dump directory in which to write
348     # class files
349     use DBIx::Class::Schema::Loader qw/ make_schema_at /;
350     make_schema_at(
351         'New::Schema::Name',
352         { debug => 1, dump_directory => './lib' },
353         [ 'dbi:Pg:dbname="foo"','postgres' ],
354     );
355
356 =cut
357
358 sub make_schema_at {
359     my ($target, $opts, $connect_info) = @_;
360
361     {
362         no strict 'refs';
363         @{$target . '::ISA'} = qw/DBIx::Class::Schema::Loader/;
364     }
365
366     $target->loader_options($opts);
367     $target->connection(@$connect_info);
368 }
369
370 =head2 rescan
371
372 =over 4
373
374 =item Return Value: @new_monikers
375
376 =back
377
378 Re-scans the database for newly added tables since the initial
379 load, and adds them to the schema at runtime, including relationships,
380 etc.  Does not process drops or changes.
381
382 Returns a list of the new monikers added.
383
384 =cut
385
386 sub rescan { my $self = shift; $self->_loader->rescan($self) }
387
388 =head2 naming
389
390 =over 4
391
392 =item Arguments: \%opts | $ver
393
394 =back
395
396 Controls the naming options for backward compatibility, see
397 L<DBIx::Class::Schema::Loader::Base/naming> for details.
398
399 To upgrade a dynamic schema, use:
400
401     __PACKAGE__->naming('current');
402
403 Can be imported into your dump script and called as a function as well:
404
405     naming('v4');
406
407 =head1 KNOWN ISSUES
408
409 =head2 Multiple Database Schemas
410
411 Currently the loader is limited to working within a single schema
412 (using the underlying RDBMS's definition of "schema").  If you have a
413 multi-schema database with inter-schema relationships (which is easy
414 to do in PostgreSQL or DB2 for instance), you currently can only
415 automatically load the tables of one schema, and relationships to
416 tables in other schemas will be silently ignored.
417
418 At some point in the future, an intelligent way around this might be
419 devised, probably by allowing the C<db_schema> option to be an
420 arrayref of schemas to load.
421
422 In "normal" L<DBIx::Class::Schema> usage, manually-defined
423 source classes and relationships have no problems crossing vendor schemas.
424
425 =head1 ACKNOWLEDGEMENTS
426
427 Matt S Trout, all of the #dbix-class folks, and everyone who's ever sent
428 in a bug report or suggestion.
429
430 Based on L<DBIx::Class::Loader> by Sebastian Riedel
431
432 Based upon the work of IKEBE Tomohiro
433
434 =head1 AUTHOR
435
436 blblack: Brandon Black <blblack@gmail.com>
437
438 =head1 CONTRIBUTORS
439
440 ilmarii: Dagfinn Ilmari MannsÃ¥ker <ilmari@ilmari.org>
441
442 arcanez: Justin Hunter <justin.d.hunter@gmail.com>
443
444 ash: Ash Berlin <ash@cpan.org>
445
446 Caelum: Rafael Kitover <rkitover@cpan.org>
447
448 TSUNODA Kazuya <drk@drk7.jp>
449
450 Robert Bohne <rbo@openserv.org>
451
452 ribasushi: Peter Rabbitson <rabbit+dbic@rabbit.us>
453
454 gugu: Andrey Kostenko <a.kostenko@rambler-co.ru>
455
456 jhannah: Jay Hannah <jay@jays.net>
457
458 ... and lots of other folks. If we forgot you, please write the current
459 maintainer or RT.
460
461 =head1 COPYRIGHT & LICENSE
462
463 Copyright (c) 2006 - 2009 by the aforementioned
464 L<DBIx::Class::Schema::Loader/AUTHOR> and
465 L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
466
467 This library is free software; you can redistribute it and/or modify it under
468 the same terms as Perl itself.
469
470 =head1 SEE ALSO
471
472 L<DBIx::Class>, L<DBIx::Class::Manual::ExampleSchema>
473
474 =cut
475
476 1;