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