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