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