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