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