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