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