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