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