6c7c87a78fcdde9866ff5739960500ff980ddf40
[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/;
6 use base qw/Class::Data::Accessor/;
7 use Carp::Clan qw/^DBIx::Class::Schema::Loader/;
8 use UNIVERSAL::require;
9 use Class::C3;
10 use Scalar::Util qw/ weaken /;
11
12 # Always remember to do all digits for the version even if they're 0
13 # i.e. first release of 0.XX *must* be 0.XX000. This avoids fBSD ports
14 # brain damage and presumably various other packaging systems too
15 our $VERSION = '0.03004';
16
17 __PACKAGE__->mk_classaccessor('dump_to_dir');
18 __PACKAGE__->mk_classaccessor('loader');
19 __PACKAGE__->mk_classaccessor('_loader_args');
20
21 =head1 NAME
22
23 DBIx::Class::Schema::Loader - Dynamic definition of a DBIx::Class::Schema
24
25 =head1 SYNOPSIS
26
27   package My::Schema;
28   use base qw/DBIx::Class::Schema::Loader/;
29
30   __PACKAGE__->loader_options(
31       relationships           => 1,
32       constraint              => '^foo.*',
33       # debug                 => 1,
34   );
35
36   # in seperate application code ...
37
38   use My::Schema;
39
40   my $schema1 = My::Schema->connect( $dsn, $user, $password, $attrs);
41   # -or-
42   my $schema1 = "My::Schema"; $schema1->connection(as above);
43
44 =head1 DESCRIPTION 
45
46 DBIx::Class::Schema::Loader automates the definition of a
47 L<DBIx::Class::Schema> by scanning database table definitions and
48 setting up the columns, primary keys, and relationships.
49
50 DBIx::Class::Schema::Loader currently supports only the DBI storage type.
51 It has explicit support for L<DBD::Pg>, L<DBD::mysql>, L<DBD::DB2>, and
52 L<DBD::SQLite>.  Other DBI drivers may function to a greater or lesser
53 degree with this loader, depending on how much of the DBI spec they
54 implement, and how standard their implementation is.  Patches to make
55 other DBDs work correctly welcome.
56
57 See L<DBIx::Class::Schema::Loader::DBI::Writing> for notes on writing
58 your own vendor-specific subclass for an unsupported DBD driver.
59
60 This module requires L<DBIx::Class> 0.06 or later, and obsoletes
61 the older L<DBIx::Class::Loader>.
62
63 This module is designed more to get you up and running quickly against
64 an existing database, or to be effective for simple situations, rather
65 than to be what you use in the long term for a complex database/project.
66
67 That being said, transitioning your code from a Schema generated by this
68 module to one that doesn't use this module should be straightforward and
69 painless (as long as you're not using any methods that are now deprecated
70 in this document), so don't shy away from it just for fears of the
71 transition down the road.
72
73 =head1 METHODS
74
75 =head2 loader_options
76
77 Example in Synopsis above demonstrates a few common arguments.  For
78 detailed information on all of the arguments, most of which are
79 only useful in fairly complex scenarios, see the
80 L<DBIx::Class::Schema::Loader::Base> documentation.
81
82 This method is *required* at this time, for backwards compatibility
83 reasons.  If you do not wish to change any options, just call it
84 with an empty argument list during schema class initialization.
85
86 You should either specify this method before setting the connection
87 information for your schema, or specify these options as a part of
88 your connection information (see below).  For now it will merely
89 warn if the ordering is wrong, but in the future this will cause problems.
90
91 =cut
92
93 sub loader_options {
94     my $self = shift;
95     
96     my %args = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
97
98     my $class = ref $self || $self;
99     $args{schema} = $self;
100     $args{schema_class} = $class;
101     weaken($args{schema}) if ref $self;
102
103     $self->_loader_args(\%args);
104     if($self->storage && !$class->loader) {
105         warn "Do not set loader_options after specifying the connection info";
106         $self->_invoke_loader;
107     }
108
109     $self;
110 }
111
112 sub _invoke_loader {
113     my $self = shift;
114     my $class = ref $self || $self;
115
116     $self->_loader_args->{dump_directory} ||= $self->dump_to_dir;
117
118     # XXX this only works for relative storage_type, like ::DBI ...
119     my $impl = "DBIx::Class::Schema::Loader" . $self->storage_type;
120     $impl->require or
121       croak qq/Could not load storage_type loader "$impl": / .
122             qq/"$UNIVERSAL::require::ERROR"/;
123
124     # XXX in the future when we get rid of ->loader, the next two
125     # lines can be replaced by "$impl->new(%{$self->_loader_args})->load;"
126     $class->loader($impl->new(%{$self->_loader_args}));
127     $class->loader->load;
128
129     $self;
130 }
131
132 =head2 connection
133
134 See L<DBIx::Class::Schema> for basic usage.
135
136 If the final argument is a hashref, and it contains a key C<loader_options>,
137 that key will be deleted, and its value will be used for the loader options,
138 just as if set via the L</loader_options> method above.
139
140 The actual auto-loading operation (the heart of this module) will be invoked
141 as soon as the connection information is defined.
142
143 =cut
144
145 sub connection {
146     my $self = shift;
147
148     if($_[-1] && ref $_[-1] eq 'HASH') {
149         if(my $loader_opts = delete $_[-1]->{loader_options}) {
150             $self->loader_options($loader_opts);
151             pop @_ if !keys %{$_[-1]};
152         }
153     }
154
155     $self = $self->next::method(@_);
156
157     my $class = ref $self || $self;
158     $self->_invoke_loader if $self->_loader_args && !$class->loader;
159
160     return $self;
161 }
162
163 =head2 clone
164
165 See L<DBIx::Class::Schema>.
166
167 =cut
168
169 sub clone {
170     my $self = shift;
171
172     croak "You failed to specify the required loader_options"
173         if !$self->_loader_args;
174
175     my $clone = $self->next::method(@_);
176
177     $clone->_loader_args($self->_loader_args);
178     $clone->_loader_args->{schema} = $clone;
179     weaken($clone->_loader_args->{schema});
180
181     $clone;
182 }
183
184 =head2 dump_to_dir
185
186 Argument: directory name.
187
188 Calling this as a class method on either L<DBIx::Class::Schema::Loader>
189 or any derived schema class will cause all affected schemas to dump
190 manual versions of themselves to the named directory when they are
191 loaded.  In order to be effective, this must be set before defining a
192 connection on this schema class or any derived object (as the loading
193 happens as soon as both a connection and loader_options are set, and
194 only once per class).
195
196 See L<DBIx::Class::Schema::Loader::Base/dump_directory> for more
197 details on the dumping mechanism.
198
199 This can also be set at module import time via the import option
200 C<dump_to_dir:/foo/bar> to L<DBIx::Class::Schema::Loader>, where
201 C</foo/bar> is the target directory.
202
203 Examples:
204
205     # My::Schema isa DBIx::Class::Schema::Loader, and has connection info
206     #   hardcoded in the class itself:
207     perl -MDBIx::Class::Schema::Loader=dump_to_dir:/foo/bar -MMy::Schema -e1
208
209     # Same, but no hard-coded connection, so we must provide one:
210     perl -MDBIx::Class::Schema::Loader=dump_to_dir:/foo/bar -MMy::Schema -e 'My::Schema->connection("dbi:Pg:dbname=foo", ...)'
211
212     # Or as a class method, as long as you get it done *before* defining a
213     #  connection on this schema class or any derived object:
214     use My::Schema;
215     My::Schema->dump_to_dir('/foo/bar');
216     My::Schema->connection(........);
217
218     # Or as a class method on the DBIx::Class::Schema::Loader itself, which affects all
219     #   derived schemas
220     use My::Schema;
221     use My::OtherSchema;
222     DBIx::Class::Schema::Loader->dump_to_dir('/foo/bar');
223     My::Schema->connection(.......);
224     My::OtherSchema->connection(.......);
225
226     # Another alternative to the above:
227     use DBIx::Class::Schema::Loader qw| dump_to_dir:/foo/bar |;
228     use My::Schema;
229     use My::OtherSchema;
230     My::Schema->connection(.......);
231     My::OtherSchema->connection(.......);
232
233 =cut
234
235 sub import {
236     my $self = shift;
237     return if !@_;
238     foreach my $opt (@_) {
239         if($opt =~ m{^dump_to_dir:(.*)$}) {
240             $self->dump_to_dir($1)
241         }
242         elsif($opt eq 'make_schema_at') {
243             no strict 'refs';
244             my $cpkg = (caller)[0];
245             *{"${cpkg}::make_schema_at"} = \&make_schema_at;
246         }
247     }
248 }
249
250 =head2 make_schema_at
251
252 This simple function allows one to create a Loader-based schema
253 in-memory on the fly without any on-disk class files of any
254 kind.  When used with the C<dump_directory> option, you can
255 use this to generate a rough draft manual schema from a dsn
256 without the intermediate step of creating a physical Loader-based
257 schema class.
258
259 The return value is the input class name.
260
261 This function can be exported/imported by the normal means, as
262 illustrated in these Examples:
263
264     # Simple example, creates as a new class 'New::Schema::Name' in
265     #  memory in the running perl interpreter.
266     use DBIx::Class::Schema::Loader qw/ make_schema_at /;
267     make_schema_at(
268         'New::Schema::Name',
269         { relationships => 1, debug => 1 },
270         [ 'dbi:Pg:dbname="foo"','postgres' ],
271     );
272
273     # Complex: dump loaded schema to disk, all from the commandline:
274     perl -MDBIx::Class::Schema::Loader=make_schema_at,dump_to_dir:./lib -e 'make_schema_at("New::Schema::Name", { relationships => 1 }, [ "dbi:Pg:dbname=foo","postgres" ])'
275
276     # Same, but inside a script, and using a different way to specify the
277     # dump directory:
278     use DBIx::Class::Schema::Loader qw/ make_schema_at /;
279     make_schema_at(
280         'New::Schema::Name',
281         { relationships => 1, debug => 1, dump_directory => './lib' },
282         [ 'dbi:Pg:dbname="foo"','postgres' ],
283     );
284
285 =cut
286
287 sub make_schema_at {
288     my ($target, $opts, $connect_info) = @_;
289
290     {
291         no strict 'refs';
292         @{$target . '::ISA'} = qw/DBIx::Class::Schema::Loader/;
293     }
294
295     $target->loader_options($opts);
296     $target->connection(@$connect_info);
297 }
298
299 =head1 EXAMPLE
300
301 Using the example in L<DBIx::Class::Manual::ExampleSchema> as a basis
302 replace the DB::Main with the following code:
303
304   package DB::Main;
305
306   use base qw/DBIx::Class::Schema::Loader/;
307
308   __PACKAGE__->loader_options(
309       relationships => 1,
310       debug         => 1,
311   );
312   __PACKAGE__->connection('dbi:SQLite:example.db');
313
314   1;
315
316 and remove the Main directory tree (optional).  Every thing else
317 should work the same
318
319 =head1 DEPRECATED METHODS
320
321 You don't need to read anything in this section unless you're upgrading
322 code that was written against pre-0.03 versions of this module.  This
323 version is intended to be backwards-compatible with pre-0.03 code, but
324 will issue warnings about your usage of deprecated features/methods.
325
326 B<All of these deprecated methods will dissappear in version 0.04000>,
327 and converting code that uses these methods should be trivial.
328
329 =head2 load_from_connection
330
331 This deprecated method is now roughly an alias for L</loader_options>.
332
333 For now, using this method will invoke the legacy behavior for
334 backwards compatibility, and merely emit a warning about upgrading
335 your code.
336
337 It also reverts the default inflection scheme to
338 use L<Lingua::EN::Inflect> just like pre-0.03 versions of this
339 module did.
340
341 You can force these legacy inflections with the
342 option L<DBIx::Class::Schema::Loader::Base/legacy_default_inflections>,
343 even after switch over to the preferred L</loader_options> way of doing
344 things.  That option will not go away until at least 0.05.
345
346 See the source of this method for more details.
347
348 =cut
349
350 sub load_from_connection {
351     my ($self, %args) = @_;
352
353     my $cmds_ver = $Catalyst::Model::DBIC::Schema::VERSION;
354     if($cmds_ver) {
355         if($cmds_ver < 0.14) {
356             warn 'You should upgrade your installation of'
357                . ' Catalyst::Model::DBIC::Schema to 0.14 or higher, then:';
358         }
359         warn 'You should regenerate your Model files, which may eliminate'
360            . ' the following deprecation warning:';
361     }
362     warn 'load_from_connection deprecated, and will dissappear in 0.04000, '
363        . 'please [re-]read the [new] DBIx::Class::Schema::Loader '
364        . 'documentation';
365
366     # Support the old connect_info / dsn / etc args...
367     $args{connect_info} = [
368         delete $args{dsn},
369         delete $args{user},
370         delete $args{password},
371         delete $args{options},
372     ] if $args{dsn};
373
374     $self->connection(@{delete $args{connect_info}})
375         if $args{connect_info};
376
377     $self->loader_options('legacy_default_inflections' => 1, %args);
378 }
379
380 =head2 loader
381
382 This is an accessor in the generated Schema class for accessing
383 the L<DBIx::Class::Schema::Loader::Base> -based loader object
384 that was used during construction.  See the
385 L<DBIx::Class::Schema::Loader::Base> docs for more information
386 on the available loader methods there.
387
388 This accessor is deprecated.  Do not use it.  Anything you can
389 get from C<loader>, you can get via the normal L<DBIx::Class::Schema>
390 methods, and your code will be more robust and forward-thinking
391 for doing so.
392
393 If you're already using C<loader> in your code, make an effort
394 to get rid of it.  If you think you've found a situation where it
395 is necessary, let me know and we'll see what we can do to remedy
396 that situation.
397
398 In some future version, this accessor *will* disappear.  It was
399 apparently quite a design/API mistake to ever have exposed it to
400 user-land in the first place, all things considered.
401
402 =head1 KNOWN ISSUES
403
404 =head2 Multiple Database Schemas
405
406 Currently the loader is limited to working within a single schema
407 (using the database vendors' definition of "schema").  If you
408 have a multi-schema database with inter-schema relationships (which
409 is easy to do in PostgreSQL or DB2 for instance), you only get to
410 automatically load the tables of one schema, and any relationships
411 to tables in other schemas will be silently ignored.
412
413 At some point in the future, an intelligent way around this might be
414 devised, probably by allowing the C<db_schema> option to be an
415 arrayref of schemas to load.
416
417 In "normal" L<DBIx::Class::Schema> usage, manually-defined
418 source classes and relationships have no problems crossing vendor schemas.
419
420 =head1 AUTHOR
421
422 Brandon Black, C<blblack@gmail.com>
423
424 Based on L<DBIx::Class::Loader> by Sebastian Riedel
425
426 Based upon the work of IKEBE Tomohiro
427
428 =head1 THANK YOU
429
430 Matt S Trout, all of the #dbix-class folks, and everyone who's ever sent
431 in a bug report or suggestion.
432
433 =head1 LICENSE
434
435 This library is free software; you can redistribute it and/or modify it under
436 the same terms as Perl itself.
437
438 =head1 SEE ALSO
439
440 L<DBIx::Class>, L<DBIx::Class::Manual::ExampleSchema>
441
442 =cut
443
444 1;