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