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