release 0.07005
[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;
65e705c3 5use base qw/DBIx::Class::Schema Class::Accessor::Grouped/;
fa994d3c 6use Carp::Clan qw/^DBIx::Class/;
942bd5e0 7use mro 'c3';
c9f1d7b0 8use Scalar::Util qw/ weaken /;
3980d69c 9
a4a19f3c 10# Always remember to do all digits for the version even if they're 0
11# i.e. first release of 0.XX *must* be 0.XX000. This avoids fBSD ports
12# brain damage and presumably various other packaging systems too
c697835e 13our $VERSION = '0.07005';
457eb8a6 14
65e705c3 15__PACKAGE__->mk_group_accessors('inherited', qw/
16 _loader_args
17 dump_to_dir
18 _loader_invoked
19 _loader
20 loader_class
21 naming
f22644d7 22 use_namespaces
a8d229ff 23/);
65e705c3 24__PACKAGE__->_loader_args({});
a78e3fed 25
26=head1 NAME
27
18fca96a 28DBIx::Class::Schema::Loader - Dynamic definition of a DBIx::Class::Schema
a78e3fed 29
30=head1 SYNOPSIS
31
707fb247 32 ### use this module to generate a set of class files
33
34 # in a script
35 use DBIx::Class::Schema::Loader qw/ make_schema_at /;
36 make_schema_at(
37 'My::Schema',
38 { debug => 1,
39 dump_directory => './lib',
40 },
35a87f06 41 [ 'dbi:Pg:dbname="foo"', 'myuser', 'mypassword',
42 { loader_class => 'MyLoader' } # optionally
43 ],
707fb247 44 );
45
46 # from the command line or a shell script with dbicdump (distributed
47 # with this module). Do `perldoc dbicdump` for usage.
48 dbicdump -o dump_directory=./lib \
49 -o debug=1 \
50 My::Schema \
51 'dbi:Pg:dbname=foo' \
52 myuser \
53 mypassword
54
55 ### or generate and load classes at runtime
56 # note: this technique is not recommended
57 # for use in production code
58
a4a19f3c 59 package My::Schema;
60 use base qw/DBIx::Class::Schema::Loader/;
a78e3fed 61
996be9ee 62 __PACKAGE__->loader_options(
996be9ee 63 constraint => '^foo.*',
64 # debug => 1,
a78e3fed 65 );
af6c2665 66
707fb247 67 #### in application code elsewhere:
a78e3fed 68
a4a19f3c 69 use My::Schema;
a78e3fed 70
a4a19f3c 71 my $schema1 = My::Schema->connect( $dsn, $user, $password, $attrs);
72 # -or-
996be9ee 73 my $schema1 = "My::Schema"; $schema1->connection(as above);
074e81cd 74
996be9ee 75=head1 DESCRIPTION
074e81cd 76
fbd83464 77DBIx::Class::Schema::Loader automates the definition of a
996be9ee 78L<DBIx::Class::Schema> by scanning database table definitions and
d65cda9e 79setting up the columns, primary keys, and relationships.
a78e3fed 80
1065db64 81DBIx::Class::Schema::Loader currently supports only the DBI storage type. It
82has explicit support for L<DBD::Pg>, L<DBD::mysql>, L<DBD::DB2>,
6b0e47fc 83L<DBD::SQLite>, L<DBD::Sybase> (for Sybase ASE and MSSSQL), L<DBD::ODBC> (for
84MSSQL) and L<DBD::Oracle>. Other DBI drivers may function to a greater or
85lesser degree with this loader, depending on how much of the DBI spec they
86implement, and how standard their implementation is.
3fe9c5d9 87
88Patches to make other DBDs work correctly welcome.
a78e3fed 89
996be9ee 90See L<DBIx::Class::Schema::Loader::DBI::Writing> for notes on writing
91your own vendor-specific subclass for an unsupported DBD driver.
a78e3fed 92
3fe9c5d9 93This module requires L<DBIx::Class> 0.07006 or later, and obsoletes
996be9ee 94the older L<DBIx::Class::Loader>.
89ecd854 95
996be9ee 96This module is designed more to get you up and running quickly against
97an existing database, or to be effective for simple situations, rather
98than to be what you use in the long term for a complex database/project.
89ecd854 99
100That being said, transitioning your code from a Schema generated by this
101module to one that doesn't use this module should be straightforward and
59cfa251 102painless, so don't shy away from it just for fears of the transition down
103the road.
89ecd854 104
a78e3fed 105=head1 METHODS
106
29ddb54c 107=head2 loader_class
108
530e0bf6 109=over 4
110
111=item Argument: $loader_class
112
113=back
114
29ddb54c 115Set the loader class to be instantiated when L</connection> is called.
116If the classname starts with "::", "DBIx::Class::Schema::Loader" is
117prepended. Defaults to L<DBIx::Class::Schema/storage_type> (which must
118start with "::" when using L<DBIx::Class::Schema::Loader>).
119
120This is mostly useful for subclassing existing loaders or in conjunction
121with L</dump_to_dir>.
122
996be9ee 123=head2 loader_options
a78e3fed 124
530e0bf6 125=over 4
126
127=item Argument: \%loader_options
128
129=back
130
996be9ee 131Example in Synopsis above demonstrates a few common arguments. For
132detailed information on all of the arguments, most of which are
133only useful in fairly complex scenarios, see the
134L<DBIx::Class::Schema::Loader::Base> documentation.
a78e3fed 135
3fe9c5d9 136If you intend to use C<loader_options>, you must call
137C<loader_options> before any connection is made, or embed the
138C<loader_options> in the connection information itself as shown
139below. Setting C<loader_options> after the connection has
59cfa251 140already been made is useless.
a78e3fed 141
996be9ee 142=cut
1031d4f6 143
996be9ee 144sub loader_options {
145 my $self = shift;
65e705c3 146
d65cda9e 147 my %args = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
996be9ee 148 $self->_loader_args(\%args);
996be9ee 149
150 $self;
151}
152
153sub _invoke_loader {
154 my $self = shift;
155 my $class = ref $self || $self;
156
59cfa251 157 my $args = $self->_loader_args;
158
159 # set up the schema/schema_class arguments
160 $args->{schema} = $self;
161 $args->{schema_class} = $class;
162 weaken($args->{schema}) if ref $self;
163 $args->{dump_directory} ||= $self->dump_to_dir;
a0e0a56a 164 $args->{naming} = $self->naming if $self->naming;
f22644d7 165 $args->{use_namespaces} = $self->use_namespaces if $self->use_namespaces;
af6c2665 166
996be9ee 167 # XXX this only works for relative storage_type, like ::DBI ...
71a6e88a 168 my $loader_class = $self->loader_class;
169 if ($loader_class) {
170 $loader_class = "DBIx::Class::Schema::Loader${loader_class}" if $loader_class =~ /^::/;
171 $args->{loader_class} = $loader_class;
172 };
173
174 my $impl = $loader_class || "DBIx::Class::Schema::Loader" . $self->storage_type;
6ae3f335 175 eval { $self->ensure_class_loaded($impl) };
517a30e2 176 croak qq/Could not load loader_class "$impl": "$@"/ if $@;
af6c2665 177
b97c2c1e 178 $self->_loader($impl->new(%$args));
179 $self->_loader->load;
59cfa251 180 $self->_loader_invoked(1);
996be9ee 181
996be9ee 182 $self;
183}
184
185=head2 connection
186
530e0bf6 187=over 4
188
189=item Arguments: @args
190
191=item Return Value: $new_schema
192
193=back
194
195See L<DBIx::Class::Schema/connection> for basic usage.
d65cda9e 196
29ddb54c 197If the final argument is a hashref, and it contains the keys C<loader_options>
198or C<loader_class>, those keys will be deleted, and their values value will be
199used for the loader options or class, respectively, just as if set via the
200L</loader_options> or L</loader_class> methods above.
d65cda9e 201
202The actual auto-loading operation (the heart of this module) will be invoked
203as soon as the connection information is defined.
996be9ee 204
205=cut
206
207sub connection {
d65cda9e 208 my $self = shift;
209
210 if($_[-1] && ref $_[-1] eq 'HASH') {
17ca645f 211 for my $option (qw/ loader_class loader_options result_base_class schema_base_class/) {
29ddb54c 212 if(my $value = delete $_[-1]->{$option}) {
213 $self->$option($value);
214 }
d65cda9e 215 }
29ddb54c 216 pop @_ if !keys %{$_[-1]};
d65cda9e 217 }
218
219 $self = $self->next::method(@_);
996be9ee 220
221 my $class = ref $self || $self;
59cfa251 222 if(!$class->_loader_invoked) {
fa994d3c 223 $self->_invoke_loader
224 }
996be9ee 225
226 return $self;
227}
228
229=head2 clone
230
530e0bf6 231See L<DBIx::Class::Schema/clone>.
996be9ee 232
233=cut
234
235sub clone {
236 my $self = shift;
237
238 my $clone = $self->next::method(@_);
239
fa994d3c 240 if($clone->_loader_args) {
241 $clone->_loader_args->{schema} = $clone;
242 weaken($clone->_loader_args->{schema});
243 }
996be9ee 244
245 $clone;
246}
247
248=head2 dump_to_dir
249
530e0bf6 250=over 4
251
252=item Argument: $directory
253
254=back
996be9ee 255
256Calling this as a class method on either L<DBIx::Class::Schema::Loader>
707fb247 257or any derived schema class will cause all schemas to dump
996be9ee 258manual versions of themselves to the named directory when they are
259loaded. In order to be effective, this must be set before defining a
260connection on this schema class or any derived object (as the loading
074e81cd 261happens as soon as both a connection and loader_options are set, and
262only once per class).
996be9ee 263
264See L<DBIx::Class::Schema::Loader::Base/dump_directory> for more
265details on the dumping mechanism.
266
267This can also be set at module import time via the import option
268C<dump_to_dir:/foo/bar> to L<DBIx::Class::Schema::Loader>, where
269C</foo/bar> is the target directory.
270
271Examples:
272
273 # My::Schema isa DBIx::Class::Schema::Loader, and has connection info
274 # hardcoded in the class itself:
275 perl -MDBIx::Class::Schema::Loader=dump_to_dir:/foo/bar -MMy::Schema -e1
276
277 # Same, but no hard-coded connection, so we must provide one:
278 perl -MDBIx::Class::Schema::Loader=dump_to_dir:/foo/bar -MMy::Schema -e 'My::Schema->connection("dbi:Pg:dbname=foo", ...)'
279
280 # Or as a class method, as long as you get it done *before* defining a
281 # connection on this schema class or any derived object:
282 use My::Schema;
283 My::Schema->dump_to_dir('/foo/bar');
284 My::Schema->connection(........);
285
286 # Or as a class method on the DBIx::Class::Schema::Loader itself, which affects all
287 # derived schemas
288 use My::Schema;
289 use My::OtherSchema;
290 DBIx::Class::Schema::Loader->dump_to_dir('/foo/bar');
291 My::Schema->connection(.......);
292 My::OtherSchema->connection(.......);
293
294 # Another alternative to the above:
295 use DBIx::Class::Schema::Loader qw| dump_to_dir:/foo/bar |;
296 use My::Schema;
297 use My::OtherSchema;
298 My::Schema->connection(.......);
299 My::OtherSchema->connection(.......);
300
301=cut
302
303sub import {
304 my $self = shift;
a8d229ff 305
996be9ee 306 return if !@_;
a8d229ff 307
308 my $cpkg = (caller)[0];
309
996be9ee 310 foreach my $opt (@_) {
311 if($opt =~ m{^dump_to_dir:(.*)$}) {
312 $self->dump_to_dir($1)
313 }
314 elsif($opt eq 'make_schema_at') {
315 no strict 'refs';
996be9ee 316 *{"${cpkg}::make_schema_at"} = \&make_schema_at;
317 }
a8d229ff 318 elsif($opt eq 'naming') {
319 no strict 'refs';
320 *{"${cpkg}::naming"} = sub { $self->naming(@_) };
321 }
f22644d7 322 elsif($opt eq 'use_namespaces') {
323 no strict 'refs';
324 *{"${cpkg}::use_namespaces"} = sub { $self->use_namespaces(@_) };
325 }
996be9ee 326 }
327}
328
329=head2 make_schema_at
330
530e0bf6 331=over 4
332
707fb247 333=item Arguments: $schema_class_name, \%loader_options, \@connect_info
530e0bf6 334
707fb247 335=item Return Value: $schema_class_name
530e0bf6 336
337=back
338
707fb247 339This function creates a DBIx::Class schema from an existing RDBMS
340schema. With the C<dump_directory> option, generates a set of
341DBIx::Class classes from an existing database schema read from the
342given dsn. Without a C<dump_directory>, creates schema classes in
343memory at runtime without generating on-disk class files.
996be9ee 344
707fb247 345For a complete list of supported loader_options, see
346L<DBIx::Class::Schema::Loader::Base>
483987b9 347
35a87f06 348The last hashref in the C<\@connect_info> can specify the L</loader_class>.
349
707fb247 350This function can be imported in the usual way, as illustrated in
351these Examples:
996be9ee 352
5223f24a 353 # Simple example, creates as a new class 'New::Schema::Name' in
354 # memory in the running perl interpreter.
996be9ee 355 use DBIx::Class::Schema::Loader qw/ make_schema_at /;
356 make_schema_at(
357 'New::Schema::Name',
59cfa251 358 { debug => 1 },
35a87f06 359 [ 'dbi:Pg:dbname="foo"','postgres','',
360 { loader_class => 'MyLoader' } # optionally
361 ],
996be9ee 362 );
363
707fb247 364 # Inside a script, specifying a dump directory in which to write
365 # class files
996be9ee 366 use DBIx::Class::Schema::Loader qw/ make_schema_at /;
367 make_schema_at(
368 'New::Schema::Name',
59cfa251 369 { debug => 1, dump_directory => './lib' },
35a87f06 370 [ 'dbi:Pg:dbname="foo"','postgres','',
371 { loader_class => 'MyLoader' } # optionally
372 ],
996be9ee 373 );
374
b486b265 375The last hashref in the C<\@connect_info> is checked for loader arguments such
376as C<loader_options> and C<loader_class>, see L</connection> for more details.
377
996be9ee 378=cut
379
380sub make_schema_at {
381 my ($target, $opts, $connect_info) = @_;
382
483987b9 383 {
384 no strict 'refs';
385 @{$target . '::ISA'} = qw/DBIx::Class::Schema::Loader/;
386 }
387
71a6e88a 388 eval { $target->_loader_invoked(0) };
389
483987b9 390 $target->loader_options($opts);
391 $target->connection(@$connect_info);
996be9ee 392}
393
b97c2c1e 394=head2 rescan
395
530e0bf6 396=over 4
397
398=item Return Value: @new_monikers
399
400=back
401
b97c2c1e 402Re-scans the database for newly added tables since the initial
403load, and adds them to the schema at runtime, including relationships,
404etc. Does not process drops or changes.
405
a60b5b8d 406Returns a list of the new monikers added.
407
b97c2c1e 408=cut
409
a60b5b8d 410sub rescan { my $self = shift; $self->_loader->rescan($self) }
b97c2c1e 411
a8d229ff 412=head2 naming
413
414=over 4
415
416=item Arguments: \%opts | $ver
417
418=back
419
420Controls the naming options for backward compatibility, see
421L<DBIx::Class::Schema::Loader::Base/naming> for details.
422
423To upgrade a dynamic schema, use:
424
425 __PACKAGE__->naming('current');
426
427Can be imported into your dump script and called as a function as well:
428
429 naming('v4');
996be9ee 430
f22644d7 431=head2 use_namespaces
432
433=over 4
434
435=item Arguments: 1|0
436
437=back
438
439Controls the use_namespaces options for backward compatibility, see
440L<DBIx::Class::Schema::Loader::Base/use_namespaces> for details.
441
442To upgrade a dynamic schema, use:
443
444 __PACKAGE__->use_namespaces(1);
445
446Can be imported into your dump script and called as a function as well:
447
448 use_namespaces(1);
449
996be9ee 450=head1 KNOWN ISSUES
451
452=head2 Multiple Database Schemas
453
454Currently the loader is limited to working within a single schema
707fb247 455(using the underlying RDBMS's definition of "schema"). If you have a
456multi-schema database with inter-schema relationships (which is easy
457to do in PostgreSQL or DB2 for instance), you currently can only
458automatically load the tables of one schema, and relationships to
459tables in other schemas will be silently ignored.
996be9ee 460
461At some point in the future, an intelligent way around this might be
462devised, probably by allowing the C<db_schema> option to be an
d65cda9e 463arrayref of schemas to load.
89ecd854 464
996be9ee 465In "normal" L<DBIx::Class::Schema> usage, manually-defined
466source classes and relationships have no problems crossing vendor schemas.
89ecd854 467
be80bba7 468=head1 ACKNOWLEDGEMENTS
a78e3fed 469
be80bba7 470Matt S Trout, all of the #dbix-class folks, and everyone who's ever sent
471in a bug report or suggestion.
fbd83464 472
8a6b44ef 473Based on L<DBIx::Class::Loader> by Sebastian Riedel
a78e3fed 474
475Based upon the work of IKEBE Tomohiro
476
be80bba7 477=head1 AUTHOR
a78e3fed 478
be80bba7 479blblack: Brandon Black <blblack@gmail.com>
480
481=head1 CONTRIBUTORS
482
a41f1fd4 483ilmari: Dagfinn Ilmari MannsE<aring>ker <ilmari@ilmari.org>
be80bba7 484
485arcanez: Justin Hunter <justin.d.hunter@gmail.com>
486
487ash: Ash Berlin <ash@cpan.org>
488
489Caelum: Rafael Kitover <rkitover@cpan.org>
490
491TSUNODA Kazuya <drk@drk7.jp>
492
f84a7413 493rbo: Robert Bohne <rbo@cpan.org>
be80bba7 494
69fca474 495ribasushi: Peter Rabbitson <ribasushi@cpan.org>
1f625792 496
fdd8ff16 497gugu: Andrey Kostenko <a.kostenko@rambler-co.ru>
498
65e705c3 499jhannah: Jay Hannah <jay@jays.net>
500
7b505bbd 501rbuels: Robert Buels <rmb32@cornell.edu>
502
accc9e96 503timbunce: Tim Bunce <timb@cpan.org>
da21e0cf 504
c21bfb92 505mst: Matt S. Trout <mst@shadowcatsystems.co.uk>
506
827dff19 507kane: Jos Boumans <kane@cpan.org>
508
43b982ea 509waawaamilk: Nigel McNie <nigel@mcnie.name>
510
96f68869 511acmoore: Andrew Moore <amoore@cpan.org>
512
2a5dcfb3 513bphillips: Brian Phillips <bphillips@cpan.org>
514
8763ffda 515schwern: Michael G. Schwern <mschwern@cpan.org>
516
9fd0726a 517hobbs: Andrew Rodland <arodland@cpan.org>
518
c9cf9b4d 519domm: Thomas Klausner <domm@plix.at>
520
12333562 521spb: Stephen Bennett <spb@exherbo.org>
522
71687093 523Matias E. Fernandez <mfernandez@pisco.ch>
524
be80bba7 525... and lots of other folks. If we forgot you, please write the current
526maintainer or RT.
a78e3fed 527
9cc8e7e1 528=head1 COPYRIGHT & LICENSE
529
530Copyright (c) 2006 - 2009 by the aforementioned
531L<DBIx::Class::Schema::Loader/AUTHOR> and
532L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
a78e3fed 533
534This library is free software; you can redistribute it and/or modify it under
535the same terms as Perl itself.
536
537=head1 SEE ALSO
538
996be9ee 539L<DBIx::Class>, L<DBIx::Class::Manual::ExampleSchema>
a78e3fed 540
541=cut
542
5431;
71a6e88a 544# vim:et sts=4 sw=4 tw=0: