kill deprecated options/methods, make relationship loading the default
[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/;
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.03999_01';
16
17 __PACKAGE__->mk_classaccessor('dump_to_dir');
18 __PACKAGE__->mk_classaccessor('_loader_args' => {});
19 __PACKAGE__->mk_classaccessor('_loader_invoked');
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       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, so don't shy away from it just for fears of the transition down
69 the road.
70
71 =head1 METHODS
72
73 =head2 loader_options
74
75 Example in Synopsis above demonstrates a few common arguments.  For
76 detailed information on all of the arguments, most of which are
77 only useful in fairly complex scenarios, see the
78 L<DBIx::Class::Schema::Loader::Base> documentation.
79
80 One must call C<loader_options> before any connection is made,
81 or embed the C<loader_options> in the connection information itself
82 as shown below.  Setting C<loader_options> after the connection has
83 already been made is useless.
84
85 =cut
86
87 sub loader_options {
88     my $self = shift;
89     
90     my %args = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
91     $self->_loader_args(\%args);
92
93     $self;
94 }
95
96 sub _invoke_loader {
97     my $self = shift;
98     my $class = ref $self || $self;
99
100     my $args = $self->_loader_args;
101
102     # set up the schema/schema_class arguments
103     $args->{schema} = $self;
104     $args->{schema_class} = $class;
105     weaken($args->{schema}) if ref $self;
106     $args->{dump_directory} ||= $self->dump_to_dir;
107
108     # XXX this only works for relative storage_type, like ::DBI ...
109     my $impl = "DBIx::Class::Schema::Loader" . $self->storage_type;
110     $impl->require or
111       croak qq/Could not load storage_type loader "$impl": / .
112             qq/"$UNIVERSAL::require::ERROR"/;
113
114     $impl->new(%$args)->load;
115     $self->_loader_invoked(1);
116
117     $self;
118 }
119
120 =head2 connection
121
122 See L<DBIx::Class::Schema> for basic usage.
123
124 If the final argument is a hashref, and it contains a key C<loader_options>,
125 that key will be deleted, and its value will be used for the loader options,
126 just as if set via the L</loader_options> method above.
127
128 The actual auto-loading operation (the heart of this module) will be invoked
129 as soon as the connection information is defined.
130
131 =cut
132
133 sub connection {
134     my $self = shift;
135
136     if($_[-1] && ref $_[-1] eq 'HASH') {
137         if(my $loader_opts = delete $_[-1]->{loader_options}) {
138             $self->loader_options($loader_opts);
139             pop @_ if !keys %{$_[-1]};
140         }
141     }
142
143     $self = $self->next::method(@_);
144
145     my $class = ref $self || $self;
146     if(!$class->_loader_invoked) {
147         $self->_invoke_loader
148     }
149
150     return $self;
151 }
152
153 =head2 clone
154
155 See L<DBIx::Class::Schema>.
156
157 =cut
158
159 sub clone {
160     my $self = shift;
161
162     my $clone = $self->next::method(@_);
163
164     if($clone->_loader_args) {
165         $clone->_loader_args->{schema} = $clone;
166         weaken($clone->_loader_args->{schema});
167     }
168
169     $clone;
170 }
171
172 =head2 dump_to_dir
173
174 Argument: directory name.
175
176 Calling this as a class method on either L<DBIx::Class::Schema::Loader>
177 or any derived schema class will cause all affected schemas to dump
178 manual versions of themselves to the named directory when they are
179 loaded.  In order to be effective, this must be set before defining a
180 connection on this schema class or any derived object (as the loading
181 happens as soon as both a connection and loader_options are set, and
182 only once per class).
183
184 See L<DBIx::Class::Schema::Loader::Base/dump_directory> for more
185 details on the dumping mechanism.
186
187 This can also be set at module import time via the import option
188 C<dump_to_dir:/foo/bar> to L<DBIx::Class::Schema::Loader>, where
189 C</foo/bar> is the target directory.
190
191 Examples:
192
193     # My::Schema isa DBIx::Class::Schema::Loader, and has connection info
194     #   hardcoded in the class itself:
195     perl -MDBIx::Class::Schema::Loader=dump_to_dir:/foo/bar -MMy::Schema -e1
196
197     # Same, but no hard-coded connection, so we must provide one:
198     perl -MDBIx::Class::Schema::Loader=dump_to_dir:/foo/bar -MMy::Schema -e 'My::Schema->connection("dbi:Pg:dbname=foo", ...)'
199
200     # Or as a class method, as long as you get it done *before* defining a
201     #  connection on this schema class or any derived object:
202     use My::Schema;
203     My::Schema->dump_to_dir('/foo/bar');
204     My::Schema->connection(........);
205
206     # Or as a class method on the DBIx::Class::Schema::Loader itself, which affects all
207     #   derived schemas
208     use My::Schema;
209     use My::OtherSchema;
210     DBIx::Class::Schema::Loader->dump_to_dir('/foo/bar');
211     My::Schema->connection(.......);
212     My::OtherSchema->connection(.......);
213
214     # Another alternative to the above:
215     use DBIx::Class::Schema::Loader qw| dump_to_dir:/foo/bar |;
216     use My::Schema;
217     use My::OtherSchema;
218     My::Schema->connection(.......);
219     My::OtherSchema->connection(.......);
220
221 =cut
222
223 sub import {
224     my $self = shift;
225     return if !@_;
226     foreach my $opt (@_) {
227         if($opt =~ m{^dump_to_dir:(.*)$}) {
228             $self->dump_to_dir($1)
229         }
230         elsif($opt eq 'make_schema_at') {
231             no strict 'refs';
232             my $cpkg = (caller)[0];
233             *{"${cpkg}::make_schema_at"} = \&make_schema_at;
234         }
235     }
236 }
237
238 =head2 make_schema_at
239
240 This simple function allows one to create a Loader-based schema
241 in-memory on the fly without any on-disk class files of any
242 kind.  When used with the C<dump_directory> option, you can
243 use this to generate a rough draft manual schema from a dsn
244 without the intermediate step of creating a physical Loader-based
245 schema class.
246
247 The return value is the input class name.
248
249 This function can be exported/imported by the normal means, as
250 illustrated in these Examples:
251
252     # Simple example, creates as a new class 'New::Schema::Name' in
253     #  memory in the running perl interpreter.
254     use DBIx::Class::Schema::Loader qw/ make_schema_at /;
255     make_schema_at(
256         'New::Schema::Name',
257         { debug => 1 },
258         [ 'dbi:Pg:dbname="foo"','postgres' ],
259     );
260
261     # Complex: dump loaded schema to disk, all from the commandline:
262     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" ])'
263
264     # Same, but inside a script, and using a different way to specify the
265     # dump directory:
266     use DBIx::Class::Schema::Loader qw/ make_schema_at /;
267     make_schema_at(
268         'New::Schema::Name',
269         { debug => 1, dump_directory => './lib' },
270         [ 'dbi:Pg:dbname="foo"','postgres' ],
271     );
272
273 =cut
274
275 sub make_schema_at {
276     my ($target, $opts, $connect_info) = @_;
277
278     {
279         no strict 'refs';
280         @{$target . '::ISA'} = qw/DBIx::Class::Schema::Loader/;
281     }
282
283     $target->loader_options($opts);
284     $target->connection(@$connect_info);
285 }
286
287 =head1 EXAMPLE
288
289 Using the example in L<DBIx::Class::Manual::ExampleSchema> as a basis
290 replace the DB::Main with the following code:
291
292   package DB::Main;
293
294   use base qw/DBIx::Class::Schema::Loader/;
295
296   __PACKAGE__->loader_options(
297       debug         => 1,
298   );
299   __PACKAGE__->connection('dbi:SQLite:example.db');
300
301   1;
302
303 and remove the Main directory tree (optional).  Every thing else
304 should work the same
305
306 =head1 KNOWN ISSUES
307
308 =head2 Multiple Database Schemas
309
310 Currently the loader is limited to working within a single schema
311 (using the database vendors' definition of "schema").  If you
312 have a multi-schema database with inter-schema relationships (which
313 is easy to do in PostgreSQL or DB2 for instance), you only get to
314 automatically load the tables of one schema, and any relationships
315 to tables in other schemas will be silently ignored.
316
317 At some point in the future, an intelligent way around this might be
318 devised, probably by allowing the C<db_schema> option to be an
319 arrayref of schemas to load.
320
321 In "normal" L<DBIx::Class::Schema> usage, manually-defined
322 source classes and relationships have no problems crossing vendor schemas.
323
324 =head1 AUTHOR
325
326 Brandon Black, C<blblack@gmail.com>
327
328 Based on L<DBIx::Class::Loader> by Sebastian Riedel
329
330 Based upon the work of IKEBE Tomohiro
331
332 =head1 THANK YOU
333
334 Matt S Trout, all of the #dbix-class folks, and everyone who's ever sent
335 in a bug report or suggestion.
336
337 =head1 LICENSE
338
339 This library is free software; you can redistribute it and/or modify it under
340 the same terms as Perl itself.
341
342 =head1 SEE ALSO
343
344 L<DBIx::Class>, L<DBIx::Class::Manual::ExampleSchema>
345
346 =cut
347
348 1;