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