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