1 package DBIx::Class::Schema::Loader;
5 use base qw/DBIx::Class::Schema Class::Accessor::Grouped/;
8 use Carp::Clan qw/^DBIx::Class/;
9 use Scalar::Util 'weaken';
10 use Sub::Name 'subname';
11 use DBIx::Class::Schema::Loader::Utils 'array_eq';
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
17 our $VERSION = '0.07012';
19 __PACKAGE__->mk_group_accessors('inherited', qw/
28 __PACKAGE__->_loader_args({});
32 DBIx::Class::Schema::Loader - Create a DBIx::Class::Schema based on a database
36 ### use this module to generate a set of class files
39 use DBIx::Class::Schema::Loader qw/ make_schema_at /;
43 dump_directory => './lib',
45 [ 'dbi:Pg:dbname="foo"', 'myuser', 'mypassword',
46 { loader_class => 'MyLoader' } # optionally
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 \
53 -o components='["InflateColumn::DateTime"]' \
60 ### or generate and load classes at runtime
61 # note: this technique is not recommended
62 # for use in production code
65 use base qw/DBIx::Class::Schema::Loader/;
67 __PACKAGE__->loader_options(
68 constraint => '^foo.*',
72 #### in application code elsewhere:
76 my $schema1 = My::Schema->connect( $dsn, $user, $password, $attrs);
78 my $schema1 = "My::Schema"; $schema1->connection(as above);
82 DBIx::Class::Schema::Loader automates the definition of a
83 L<DBIx::Class::Schema> by scanning database table definitions and setting up
84 the columns, primary keys, unique constraints and relationships.
86 See L<dbicdump> for the C<dbicdump> utility.
88 DBIx::Class::Schema::Loader currently supports only the DBI storage type. It
89 has explicit support for L<DBD::Pg>, L<DBD::mysql>, L<DBD::DB2>,
90 L<DBD::Firebird>, L<DBD::InterBase>, L<DBD::Informix>, L<DBD::SQLAnywhere>,
91 L<DBD::SQLite>, L<DBD::Sybase> (for Sybase ASE and MSSSQL), L<DBD::ODBC> (for
92 MSSQL, MSAccess, Firebird and SQL Anywhere) L<DBD::ADO> (for MSSQL and
93 MSAccess) and L<DBD::Oracle>. Other DBI drivers may function to a greater or
94 lesser degree with this loader, depending on how much of the DBI spec they
95 implement, and how standard their implementation is.
97 Patches to make other DBDs work correctly welcome.
99 See L<DBIx::Class::Schema::Loader::DBI::Writing> for notes on writing
100 your own vendor-specific subclass for an unsupported DBD driver.
102 This module requires L<DBIx::Class> 0.08127 or later, and obsoletes the older
103 L<DBIx::Class::Loader>.
105 See L<DBIx::Class::Schema::Loader::Base> for available options.
111 The loader object, as class data on your Schema. For methods available see
112 L<DBIx::Class::Schema::Loader::Base> and L<DBIx::Class::Schema::Loader::DBI>.
125 =item Argument: $loader_class
129 Set the loader class to be instantiated when L</connection> is called.
130 If the classname starts with "::", "DBIx::Class::Schema::Loader" is
131 prepended. Defaults to L<DBIx::Class::Schema/storage_type> (which must
132 start with "::" when using L<DBIx::Class::Schema::Loader>).
134 This is mostly useful for subclassing existing loaders or in conjunction
135 with L</dump_to_dir>.
137 =head2 loader_options
141 =item Argument: \%loader_options
145 Example in Synopsis above demonstrates a few common arguments. For
146 detailed information on all of the arguments, most of which are
147 only useful in fairly complex scenarios, see the
148 L<DBIx::Class::Schema::Loader::Base> documentation.
150 If you intend to use C<loader_options>, you must call
151 C<loader_options> before any connection is made, or embed the
152 C<loader_options> in the connection information itself as shown
153 below. Setting C<loader_options> after the connection has
154 already been made is useless.
161 my %args = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
162 $self->_loader_args(\%args);
169 my $class = ref $self || $self;
171 my $args = $self->_loader_args;
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;
178 $args->{naming} = $self->naming if $self->naming;
179 $args->{use_namespaces} = $self->use_namespaces if defined $self->use_namespaces;
181 # XXX this only works for relative storage_type, like ::DBI ...
182 my $loader_class = $self->loader_class;
184 $loader_class = "DBIx::Class::Schema::Loader${loader_class}" if $loader_class =~ /^::/;
185 $args->{loader_class} = $loader_class;
188 my $impl = $loader_class || "DBIx::Class::Schema::Loader" . $self->storage_type;
189 eval { $self->ensure_class_loaded($impl) };
190 croak qq/Could not load loader_class "$impl": "$@"/ if $@;
192 $self->loader($impl->new(%$args));
194 $self->_loader_invoked(1);
203 =item Arguments: @args
205 =item Return Value: $new_schema
209 See L<DBIx::Class::Schema/connection> for basic usage.
211 If the final argument is a hashref, and it contains the keys C<loader_options>
212 or C<loader_class>, those keys will be deleted, and their values value will be
213 used for the loader options or class, respectively, just as if set via the
214 L</loader_options> or L</loader_class> methods above.
216 The actual auto-loading operation (the heart of this module) will be invoked
217 as soon as the connection information is defined.
223 my $class = ref $self || $self;
225 if($_[-1] && ref $_[-1] eq 'HASH') {
226 for my $option (qw/loader_class loader_options/) {
227 if(my $value = delete $_[-1]->{$option}) {
228 $self->$option($value);
231 pop @_ if !keys %{$_[-1]};
234 # Make sure we inherit from schema_base_class and load schema_components
236 require DBIx::Class::Schema::Loader::Base;
237 my $temp_loader = DBIx::Class::Schema::Loader::Base->new(
238 %{ $self->_loader_args },
247 if ($temp_loader->schema_base_class || $temp_loader->schema_components) {
248 @components = @{ $temp_loader->schema_components }
249 if $temp_loader->schema_components;
251 push @components, ('+'.$temp_loader->schema_base_class)
252 if $temp_loader->schema_base_class;
259 my @component_classes = map {
260 /^\+/ ? substr($_, 1, length($_) - 1) : "DBIx::Class::$_"
263 $modify_isa++ if not array_eq([ @$class_isa[0..(@components-1)] ], \@component_classes)
267 $class->load_components(@components);
269 # This hack is necessary because we changed @ISA of $self through
270 # ->load_components and we are now in a different place in the mro.
271 no warnings 'redefine';
273 local *connection = subname __PACKAGE__.'::connection' => sub {
275 $self->next::method(@_);
278 my @linear_isa = @{ mro::get_linear_isa($class) };
282 foreach my $i (1..$#linear_isa) {
284 $next_method = *{$linear_isa[$i].'::connection'}{CODE};
285 last if $next_method;
288 $self = $self->$next_method(@_);
291 $self = $self->next::method(@_);
294 if(!$class->_loader_invoked) {
295 $self->_invoke_loader
303 See L<DBIx::Class::Schema/clone>.
310 my $clone = $self->next::method(@_);
312 if($clone->_loader_args) {
313 $clone->_loader_args->{schema} = $clone;
314 weaken($clone->_loader_args->{schema});
324 =item Argument: $directory
328 Calling this as a class method on either L<DBIx::Class::Schema::Loader>
329 or any derived schema class will cause all schemas to dump
330 manual versions of themselves to the named directory when they are
331 loaded. In order to be effective, this must be set before defining a
332 connection on this schema class or any derived object (as the loading
333 happens as soon as both a connection and loader_options are set, and
334 only once per class).
336 See L<DBIx::Class::Schema::Loader::Base/dump_directory> for more
337 details on the dumping mechanism.
339 This can also be set at module import time via the import option
340 C<dump_to_dir:/foo/bar> to L<DBIx::Class::Schema::Loader>, where
341 C</foo/bar> is the target directory.
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
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", ...)'
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:
355 My::Schema->dump_to_dir('/foo/bar');
356 My::Schema->connection(........);
358 # Or as a class method on the DBIx::Class::Schema::Loader itself, which affects all
362 DBIx::Class::Schema::Loader->dump_to_dir('/foo/bar');
363 My::Schema->connection(.......);
364 My::OtherSchema->connection(.......);
366 # Another alternative to the above:
367 use DBIx::Class::Schema::Loader qw| dump_to_dir:/foo/bar |;
370 My::Schema->connection(.......);
371 My::OtherSchema->connection(.......);
380 my $cpkg = (caller)[0];
382 foreach my $opt (@_) {
383 if($opt =~ m{^dump_to_dir:(.*)$}) {
384 $self->dump_to_dir($1)
386 elsif($opt eq 'make_schema_at') {
388 *{"${cpkg}::make_schema_at"} = \&make_schema_at;
390 elsif($opt eq 'naming') {
392 *{"${cpkg}::naming"} = sub { $self->naming(@_) };
394 elsif($opt eq 'use_namespaces') {
396 *{"${cpkg}::use_namespaces"} = sub { $self->use_namespaces(@_) };
401 =head2 make_schema_at
405 =item Arguments: $schema_class_name, \%loader_options, \@connect_info
407 =item Return Value: $schema_class_name
411 This function creates a DBIx::Class schema from an existing RDBMS
412 schema. With the C<dump_directory> option, generates a set of
413 DBIx::Class classes from an existing database schema read from the
414 given dsn. Without a C<dump_directory>, creates schema classes in
415 memory at runtime without generating on-disk class files.
417 For a complete list of supported loader_options, see
418 L<DBIx::Class::Schema::Loader::Base>
420 The last hashref in the C<\@connect_info> can specify the L</loader_class>.
422 This function can be imported in the usual way, as illustrated in
425 # Simple example, creates as a new class 'New::Schema::Name' in
426 # memory in the running perl interpreter.
427 use DBIx::Class::Schema::Loader qw/ make_schema_at /;
431 [ 'dbi:Pg:dbname="foo"','postgres','',
432 { loader_class => 'MyLoader' } # optionally
436 # Inside a script, specifying a dump directory in which to write
438 use DBIx::Class::Schema::Loader qw/ make_schema_at /;
441 { debug => 1, dump_directory => './lib' },
442 [ 'dbi:Pg:dbname="foo"','postgres','',
443 { loader_class => 'MyLoader' } # optionally
447 The last hashref in the C<\@connect_info> is checked for loader arguments such
448 as C<loader_options> and C<loader_class>, see L</connection> for more details.
453 my ($target, $opts, $connect_info) = @_;
457 @{$target . '::ISA'} = qw/DBIx::Class::Schema::Loader/;
460 eval { $target->_loader_invoked(0) };
462 $target->loader_options($opts);
463 $target->connection(@$connect_info);
470 =item Return Value: @new_monikers
474 Re-scans the database for newly added tables since the initial
475 load, and adds them to the schema at runtime, including relationships,
476 etc. Does not process drops or changes.
478 Returns a list of the new monikers added.
482 sub rescan { my $self = shift; $self->loader->rescan($self) }
488 =item Arguments: \%opts | $ver
492 Controls the naming options for backward compatibility, see
493 L<DBIx::Class::Schema::Loader::Base/naming> for details.
495 To upgrade a dynamic schema, use:
497 __PACKAGE__->naming('current');
499 Can be imported into your dump script and called as a function as well:
503 =head2 use_namespaces
511 Controls the use_namespaces options for backward compatibility, see
512 L<DBIx::Class::Schema::Loader::Base/use_namespaces> for details.
514 To upgrade a dynamic schema, use:
516 __PACKAGE__->use_namespaces(1);
518 Can be imported into your dump script and called as a function as well:
524 =head2 Multiple Database Schemas
526 See L<DBIx::Class::Schema::Loader::Base/db_schema>.
528 =head1 ACKNOWLEDGEMENTS
530 Matt S Trout, all of the #dbix-class folks, and everyone who's ever sent
531 in a bug report or suggestion.
533 Based on L<DBIx::Class::Loader> by Sebastian Riedel
535 Based upon the work of IKEBE Tomohiro
539 blblack: Brandon Black <blblack@gmail.com>
543 ilmari: Dagfinn Ilmari MannsE<aring>ker <ilmari@ilmari.org>
545 arcanez: Justin Hunter <justin.d.hunter@gmail.com>
547 ash: Ash Berlin <ash@cpan.org>
549 btilly: Ben Tilly <btilly@gmail.com>
551 Caelum: Rafael Kitover <rkitover@cpan.org>
553 TSUNODA Kazuya <drk@drk7.jp>
555 rbo: Robert Bohne <rbo@cpan.org>
557 ribasushi: Peter Rabbitson <ribasushi@cpan.org>
559 gugu: Andrey Kostenko <a.kostenko@rambler-co.ru>
561 jhannah: Jay Hannah <jay@jays.net>
563 rbuels: Robert Buels <rmb32@cornell.edu>
565 timbunce: Tim Bunce <timb@cpan.org>
567 mst: Matt S. Trout <mst@shadowcatsystems.co.uk>
569 mstratman: Mark A. Stratman <stratman@gmail.com>
571 kane: Jos Boumans <kane@cpan.org>
573 waawaamilk: Nigel McNie <nigel@mcnie.name>
575 acmoore: Andrew Moore <amoore@cpan.org>
577 bphillips: Brian Phillips <bphillips@cpan.org>
579 schwern: Michael G. Schwern <mschwern@cpan.org>
581 hobbs: Andrew Rodland <arodland@cpan.org>
583 domm: Thomas Klausner <domm@plix.at>
585 spb: Stephen Bennett <spb@exherbo.org>
587 Matias E. Fernandez <mfernandez@pisco.ch>
589 alnewkirk: Al Newkirk <awncorp@cpan.org>
591 ... and lots of other folks. If we forgot you, please write the current
594 =head1 COPYRIGHT & LICENSE
596 Copyright (c) 2006 - 2009 by the aforementioned
597 L<DBIx::Class::Schema::Loader/AUTHOR> and
598 L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
600 This library is free software; you can redistribute it and/or modify it under
601 the same terms as Perl itself.
605 L<DBIx::Class>, L<DBIx::Class::Manual::Intro>, L<DBIx::Class::Tutorial>,
606 L<DBIx::Class::Schema::Loader::Base>
611 # vim:et sts=4 sw=4 tw=0: