dev release
[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::Data::Accessor/;
6 use Carp::Clan qw/^DBIx::Class/;
7 use Class::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.04999_08';
14
15 __PACKAGE__->mk_classaccessor('_loader_args' => {});
16 __PACKAGE__->mk_classaccessors(qw/dump_to_dir _loader_invoked _loader loader_class/);
17
18 =head1 NAME
19
20 DBIx::Class::Schema::Loader - Dynamic definition of a DBIx::Class::Schema
21
22 =head1 SYNOPSIS
23
24   ### use this module to generate a set of class files
25
26   # in a script
27   use DBIx::Class::Schema::Loader qw/ make_schema_at /;
28   make_schema_at(
29       'My::Schema',
30       { debug => 1,
31         dump_directory => './lib',
32       },
33       [ 'dbi:Pg:dbname="foo"', 'myuser', 'mypassword' ],
34   );
35
36   # from the command line or a shell script with dbicdump (distributed
37   # with this module).  Do `perldoc dbicdump` for usage.
38   dbicdump -o dump_directory=./lib \
39            -o debug=1 \
40            My::Schema \
41            'dbi:Pg:dbname=foo' \
42            myuser \
43            mypassword
44
45   ### or generate and load classes at runtime
46   # note: this technique is not recommended
47   # for use in production code
48
49   package My::Schema;
50   use base qw/DBIx::Class::Schema::Loader/;
51
52   __PACKAGE__->loader_options(
53       constraint              => '^foo.*',
54       # debug                 => 1,
55   );
56
57   #### in application code elsewhere:
58
59   use My::Schema;
60
61   my $schema1 = My::Schema->connect( $dsn, $user, $password, $attrs);
62   # -or-
63   my $schema1 = "My::Schema"; $schema1->connection(as above);
64
65 =head1 DESCRIPTION 
66
67 DBIx::Class::Schema::Loader automates the definition of a
68 L<DBIx::Class::Schema> by scanning database table definitions and
69 setting up the columns, primary keys, and relationships.
70
71 DBIx::Class::Schema::Loader currently supports only the DBI storage type.
72 It has explicit support for L<DBD::Pg>, L<DBD::mysql>, L<DBD::DB2>,
73 L<DBD::SQLite>, and L<DBD::Oracle>.  Other DBI drivers may function to
74 a greater or lesser degree with this loader, depending on how much of the
75 DBI spec they implement, and how standard their implementation is.
76
77 Patches to make other DBDs work correctly welcome.
78
79 See L<DBIx::Class::Schema::Loader::DBI::Writing> for notes on writing
80 your own vendor-specific subclass for an unsupported DBD driver.
81
82 This module requires L<DBIx::Class> 0.07006 or later, and obsoletes
83 the older L<DBIx::Class::Loader>.
84
85 This module is designed more to get you up and running quickly against
86 an existing database, or to be effective for simple situations, rather
87 than to be what you use in the long term for a complex database/project.
88
89 That being said, transitioning your code from a Schema generated by this
90 module to one that doesn't use this module should be straightforward and
91 painless, so don't shy away from it just for fears of the transition down
92 the road.
93
94 =head1 METHODS
95
96 =head2 loader_class
97
98 =over 4
99
100 =item Argument: $loader_class
101
102 =back
103
104 Set the loader class to be instantiated when L</connection> is called.
105 If the classname starts with "::", "DBIx::Class::Schema::Loader" is
106 prepended. Defaults to L<DBIx::Class::Schema/storage_type> (which must
107 start with "::" when using L<DBIx::Class::Schema::Loader>).
108
109 This is mostly useful for subclassing existing loaders or in conjunction
110 with L</dump_to_dir>.
111
112 =head2 loader_options
113
114 =over 4
115
116 =item Argument: \%loader_options
117
118 =back
119
120 Example in Synopsis above demonstrates a few common arguments.  For
121 detailed information on all of the arguments, most of which are
122 only useful in fairly complex scenarios, see the
123 L<DBIx::Class::Schema::Loader::Base> documentation.
124
125 If you intend to use C<loader_options>, you must call
126 C<loader_options> before any connection is made, or embed the
127 C<loader_options> in the connection information itself as shown
128 below.  Setting C<loader_options> after the connection has
129 already been made is useless.
130
131 =cut
132
133 sub loader_options {
134     my $self = shift;
135     
136     my %args = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
137     $self->_loader_args(\%args);
138
139     $self;
140 }
141
142 sub _invoke_loader {
143     my $self = shift;
144     my $class = ref $self || $self;
145
146     my $args = $self->_loader_args;
147
148     # set up the schema/schema_class arguments
149     $args->{schema} = $self;
150     $args->{schema_class} = $class;
151     weaken($args->{schema}) if ref $self;
152     $args->{dump_directory} ||= $self->dump_to_dir;
153
154     # XXX this only works for relative storage_type, like ::DBI ...
155     my $impl = $self->loader_class
156       || "DBIx::Class::Schema::Loader" . $self->storage_type;
157     $impl = "DBIx::Class::Schema::Loader${impl}" if $impl =~ /^::/;
158     eval { $self->ensure_class_loaded($impl) };
159     croak qq/Could not load storage_type loader "$impl": "$@"/ if $@;
160
161     $self->_loader($impl->new(%$args));
162     $self->_loader->load;
163     $self->_loader_invoked(1);
164
165     $self;
166 }
167
168 =head2 connection
169
170 =over 4
171
172 =item Arguments: @args
173
174 =item Return Value: $new_schema
175
176 =back
177
178 See L<DBIx::Class::Schema/connection> for basic usage.
179
180 If the final argument is a hashref, and it contains the keys C<loader_options>
181 or C<loader_class>, those keys will be deleted, and their values value will be
182 used for the loader options or class, respectively, just as if set via the
183 L</loader_options> or L</loader_class> methods above.
184
185 The actual auto-loading operation (the heart of this module) will be invoked
186 as soon as the connection information is defined.
187
188 =cut
189
190 sub connection {
191     my $self = shift;
192
193     if($_[-1] && ref $_[-1] eq 'HASH') {
194         for my $option (qw/ loader_class loader_options result_base_class schema_base_class/) {
195             if(my $value = delete $_[-1]->{$option}) {
196                 $self->$option($value);
197             }
198         }
199         pop @_ if !keys %{$_[-1]};
200     }
201
202     $self = $self->next::method(@_);
203
204     my $class = ref $self || $self;
205     if(!$class->_loader_invoked) {
206         $self->_invoke_loader
207     }
208
209     return $self;
210 }
211
212 =head2 clone
213
214 See L<DBIx::Class::Schema/clone>.
215
216 =cut
217
218 sub clone {
219     my $self = shift;
220
221     my $clone = $self->next::method(@_);
222
223     if($clone->_loader_args) {
224         $clone->_loader_args->{schema} = $clone;
225         weaken($clone->_loader_args->{schema});
226     }
227
228     $clone;
229 }
230
231 =head2 dump_to_dir
232
233 =over 4
234
235 =item Argument: $directory
236
237 =back
238
239 Calling this as a class method on either L<DBIx::Class::Schema::Loader>
240 or any derived schema class will cause all schemas to dump
241 manual versions of themselves to the named directory when they are
242 loaded.  In order to be effective, this must be set before defining a
243 connection on this schema class or any derived object (as the loading
244 happens as soon as both a connection and loader_options are set, and
245 only once per class).
246
247 See L<DBIx::Class::Schema::Loader::Base/dump_directory> for more
248 details on the dumping mechanism.
249
250 This can also be set at module import time via the import option
251 C<dump_to_dir:/foo/bar> to L<DBIx::Class::Schema::Loader>, where
252 C</foo/bar> is the target directory.
253
254 Examples:
255
256     # My::Schema isa DBIx::Class::Schema::Loader, and has connection info
257     #   hardcoded in the class itself:
258     perl -MDBIx::Class::Schema::Loader=dump_to_dir:/foo/bar -MMy::Schema -e1
259
260     # Same, but no hard-coded connection, so we must provide one:
261     perl -MDBIx::Class::Schema::Loader=dump_to_dir:/foo/bar -MMy::Schema -e 'My::Schema->connection("dbi:Pg:dbname=foo", ...)'
262
263     # Or as a class method, as long as you get it done *before* defining a
264     #  connection on this schema class or any derived object:
265     use My::Schema;
266     My::Schema->dump_to_dir('/foo/bar');
267     My::Schema->connection(........);
268
269     # Or as a class method on the DBIx::Class::Schema::Loader itself, which affects all
270     #   derived schemas
271     use My::Schema;
272     use My::OtherSchema;
273     DBIx::Class::Schema::Loader->dump_to_dir('/foo/bar');
274     My::Schema->connection(.......);
275     My::OtherSchema->connection(.......);
276
277     # Another alternative to the above:
278     use DBIx::Class::Schema::Loader qw| dump_to_dir:/foo/bar |;
279     use My::Schema;
280     use My::OtherSchema;
281     My::Schema->connection(.......);
282     My::OtherSchema->connection(.......);
283
284 =cut
285
286 sub import {
287     my $self = shift;
288     return if !@_;
289     foreach my $opt (@_) {
290         if($opt =~ m{^dump_to_dir:(.*)$}) {
291             $self->dump_to_dir($1)
292         }
293         elsif($opt eq 'make_schema_at') {
294             no strict 'refs';
295             my $cpkg = (caller)[0];
296             *{"${cpkg}::make_schema_at"} = \&make_schema_at;
297         }
298     }
299 }
300
301 =head2 make_schema_at
302
303 =over 4
304
305 =item Arguments: $schema_class_name, \%loader_options, \@connect_info
306
307 =item Return Value: $schema_class_name
308
309 =back
310
311 This function creates a DBIx::Class schema from an existing RDBMS
312 schema.  With the C<dump_directory> option, generates a set of
313 DBIx::Class classes from an existing database schema read from the
314 given dsn.  Without a C<dump_directory>, creates schema classes in
315 memory at runtime without generating on-disk class files.
316
317 For a complete list of supported loader_options, see
318 L<DBIx::Class::Schema::Loader::Base>
319
320 This function can be imported in the usual way, as illustrated in
321 these Examples:
322
323     # Simple example, creates as a new class 'New::Schema::Name' in
324     #  memory in the running perl interpreter.
325     use DBIx::Class::Schema::Loader qw/ make_schema_at /;
326     make_schema_at(
327         'New::Schema::Name',
328         { debug => 1 },
329         [ 'dbi:Pg:dbname="foo"','postgres' ],
330     );
331
332     # Inside a script, specifying a dump directory in which to write
333     # class files
334     use DBIx::Class::Schema::Loader qw/ make_schema_at /;
335     make_schema_at(
336         'New::Schema::Name',
337         { debug => 1, dump_directory => './lib' },
338         [ 'dbi:Pg:dbname="foo"','postgres' ],
339     );
340
341 =cut
342
343 sub make_schema_at {
344     my ($target, $opts, $connect_info) = @_;
345
346     {
347         no strict 'refs';
348         @{$target . '::ISA'} = qw/DBIx::Class::Schema::Loader/;
349     }
350
351     $target->loader_options($opts);
352     $target->connection(@$connect_info);
353 }
354
355 =head2 rescan
356
357 =over 4
358
359 =item Return Value: @new_monikers
360
361 =back
362
363 Re-scans the database for newly added tables since the initial
364 load, and adds them to the schema at runtime, including relationships,
365 etc.  Does not process drops or changes.
366
367 Returns a list of the new monikers added.
368
369 =cut
370
371 sub rescan { my $self = shift; $self->_loader->rescan($self) }
372
373
374 =head1 KNOWN ISSUES
375
376 =head2 Multiple Database Schemas
377
378 Currently the loader is limited to working within a single schema
379 (using the underlying RDBMS's definition of "schema").  If you have a
380 multi-schema database with inter-schema relationships (which is easy
381 to do in PostgreSQL or DB2 for instance), you currently can only
382 automatically load the tables of one schema, and relationships to
383 tables in other schemas will be silently ignored.
384
385 At some point in the future, an intelligent way around this might be
386 devised, probably by allowing the C<db_schema> option to be an
387 arrayref of schemas to load.
388
389 In "normal" L<DBIx::Class::Schema> usage, manually-defined
390 source classes and relationships have no problems crossing vendor schemas.
391
392 =head1 AUTHOR
393
394 Brandon Black, C<blblack@gmail.com>
395
396 Based on L<DBIx::Class::Loader> by Sebastian Riedel
397
398 Based upon the work of IKEBE Tomohiro
399
400 =head1 THANK YOU
401
402 Matt S Trout, all of the #dbix-class folks, and everyone who's ever sent
403 in a bug report or suggestion.
404
405 =head1 LICENSE
406
407 This library is free software; you can redistribute it and/or modify it under
408 the same terms as Perl itself.
409
410 =head1 SEE ALSO
411
412 L<DBIx::Class>, L<DBIx::Class::Manual::ExampleSchema>
413
414 =cut
415
416 1;