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