refactor the classname checking code
[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
dc767cd3 13our $VERSION = '0.05001';
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 ...
29ddb54c 166 my $impl = $self->loader_class
3953cbee 167 || "DBIx::Class::Schema::Loader" . $self->storage_type;
29ddb54c 168 $impl = "DBIx::Class::Schema::Loader${impl}" if $impl =~ /^::/;
6ae3f335 169 eval { $self->ensure_class_loaded($impl) };
170 croak qq/Could not load storage_type loader "$impl": "$@"/ if $@;
af6c2665 171
b97c2c1e 172 $self->_loader($impl->new(%$args));
173 $self->_loader->load;
59cfa251 174 $self->_loader_invoked(1);
996be9ee 175
996be9ee 176 $self;
177}
178
179=head2 connection
180
530e0bf6 181=over 4
182
183=item Arguments: @args
184
185=item Return Value: $new_schema
186
187=back
188
189See L<DBIx::Class::Schema/connection> for basic usage.
d65cda9e 190
29ddb54c 191If the final argument is a hashref, and it contains the keys C<loader_options>
192or C<loader_class>, those keys will be deleted, and their values value will be
193used for the loader options or class, respectively, just as if set via the
194L</loader_options> or L</loader_class> methods above.
d65cda9e 195
196The actual auto-loading operation (the heart of this module) will be invoked
197as soon as the connection information is defined.
996be9ee 198
199=cut
200
201sub connection {
d65cda9e 202 my $self = shift;
203
204 if($_[-1] && ref $_[-1] eq 'HASH') {
17ca645f 205 for my $option (qw/ loader_class loader_options result_base_class schema_base_class/) {
29ddb54c 206 if(my $value = delete $_[-1]->{$option}) {
207 $self->$option($value);
208 }
d65cda9e 209 }
29ddb54c 210 pop @_ if !keys %{$_[-1]};
d65cda9e 211 }
212
213 $self = $self->next::method(@_);
996be9ee 214
215 my $class = ref $self || $self;
59cfa251 216 if(!$class->_loader_invoked) {
fa994d3c 217 $self->_invoke_loader
218 }
996be9ee 219
220 return $self;
221}
222
223=head2 clone
224
530e0bf6 225See L<DBIx::Class::Schema/clone>.
996be9ee 226
227=cut
228
229sub clone {
230 my $self = shift;
231
232 my $clone = $self->next::method(@_);
233
fa994d3c 234 if($clone->_loader_args) {
235 $clone->_loader_args->{schema} = $clone;
236 weaken($clone->_loader_args->{schema});
237 }
996be9ee 238
239 $clone;
240}
241
242=head2 dump_to_dir
243
530e0bf6 244=over 4
245
246=item Argument: $directory
247
248=back
996be9ee 249
250Calling this as a class method on either L<DBIx::Class::Schema::Loader>
707fb247 251or any derived schema class will cause all schemas to dump
996be9ee 252manual versions of themselves to the named directory when they are
253loaded. In order to be effective, this must be set before defining a
254connection on this schema class or any derived object (as the loading
074e81cd 255happens as soon as both a connection and loader_options are set, and
256only once per class).
996be9ee 257
258See L<DBIx::Class::Schema::Loader::Base/dump_directory> for more
259details on the dumping mechanism.
260
261This can also be set at module import time via the import option
262C<dump_to_dir:/foo/bar> to L<DBIx::Class::Schema::Loader>, where
263C</foo/bar> is the target directory.
264
265Examples:
266
267 # My::Schema isa DBIx::Class::Schema::Loader, and has connection info
268 # hardcoded in the class itself:
269 perl -MDBIx::Class::Schema::Loader=dump_to_dir:/foo/bar -MMy::Schema -e1
270
271 # Same, but no hard-coded connection, so we must provide one:
272 perl -MDBIx::Class::Schema::Loader=dump_to_dir:/foo/bar -MMy::Schema -e 'My::Schema->connection("dbi:Pg:dbname=foo", ...)'
273
274 # Or as a class method, as long as you get it done *before* defining a
275 # connection on this schema class or any derived object:
276 use My::Schema;
277 My::Schema->dump_to_dir('/foo/bar');
278 My::Schema->connection(........);
279
280 # Or as a class method on the DBIx::Class::Schema::Loader itself, which affects all
281 # derived schemas
282 use My::Schema;
283 use My::OtherSchema;
284 DBIx::Class::Schema::Loader->dump_to_dir('/foo/bar');
285 My::Schema->connection(.......);
286 My::OtherSchema->connection(.......);
287
288 # Another alternative to the above:
289 use DBIx::Class::Schema::Loader qw| dump_to_dir:/foo/bar |;
290 use My::Schema;
291 use My::OtherSchema;
292 My::Schema->connection(.......);
293 My::OtherSchema->connection(.......);
294
295=cut
296
297sub import {
298 my $self = shift;
a8d229ff 299
996be9ee 300 return if !@_;
a8d229ff 301
302 my $cpkg = (caller)[0];
303
996be9ee 304 foreach my $opt (@_) {
305 if($opt =~ m{^dump_to_dir:(.*)$}) {
306 $self->dump_to_dir($1)
307 }
308 elsif($opt eq 'make_schema_at') {
309 no strict 'refs';
996be9ee 310 *{"${cpkg}::make_schema_at"} = \&make_schema_at;
311 }
a8d229ff 312 elsif($opt eq 'naming') {
313 no strict 'refs';
314 *{"${cpkg}::naming"} = sub { $self->naming(@_) };
315 }
f22644d7 316 elsif($opt eq 'use_namespaces') {
317 no strict 'refs';
318 *{"${cpkg}::use_namespaces"} = sub { $self->use_namespaces(@_) };
319 }
996be9ee 320 }
321}
322
323=head2 make_schema_at
324
530e0bf6 325=over 4
326
707fb247 327=item Arguments: $schema_class_name, \%loader_options, \@connect_info
530e0bf6 328
707fb247 329=item Return Value: $schema_class_name
530e0bf6 330
331=back
332
707fb247 333This function creates a DBIx::Class schema from an existing RDBMS
334schema. With the C<dump_directory> option, generates a set of
335DBIx::Class classes from an existing database schema read from the
336given dsn. Without a C<dump_directory>, creates schema classes in
337memory at runtime without generating on-disk class files.
996be9ee 338
707fb247 339For a complete list of supported loader_options, see
340L<DBIx::Class::Schema::Loader::Base>
483987b9 341
707fb247 342This function can be imported in the usual way, as illustrated in
343these Examples:
996be9ee 344
5223f24a 345 # Simple example, creates as a new class 'New::Schema::Name' in
346 # memory in the running perl interpreter.
996be9ee 347 use DBIx::Class::Schema::Loader qw/ make_schema_at /;
348 make_schema_at(
349 'New::Schema::Name',
59cfa251 350 { debug => 1 },
996be9ee 351 [ 'dbi:Pg:dbname="foo"','postgres' ],
352 );
353
707fb247 354 # Inside a script, specifying a dump directory in which to write
355 # class files
996be9ee 356 use DBIx::Class::Schema::Loader qw/ make_schema_at /;
357 make_schema_at(
358 'New::Schema::Name',
59cfa251 359 { debug => 1, dump_directory => './lib' },
996be9ee 360 [ 'dbi:Pg:dbname="foo"','postgres' ],
361 );
362
363=cut
364
365sub make_schema_at {
366 my ($target, $opts, $connect_info) = @_;
367
483987b9 368 {
369 no strict 'refs';
370 @{$target . '::ISA'} = qw/DBIx::Class::Schema::Loader/;
371 }
372
373 $target->loader_options($opts);
374 $target->connection(@$connect_info);
996be9ee 375}
376
b97c2c1e 377=head2 rescan
378
530e0bf6 379=over 4
380
381=item Return Value: @new_monikers
382
383=back
384
b97c2c1e 385Re-scans the database for newly added tables since the initial
386load, and adds them to the schema at runtime, including relationships,
387etc. Does not process drops or changes.
388
a60b5b8d 389Returns a list of the new monikers added.
390
b97c2c1e 391=cut
392
a60b5b8d 393sub rescan { my $self = shift; $self->_loader->rescan($self) }
b97c2c1e 394
a8d229ff 395=head2 naming
396
397=over 4
398
399=item Arguments: \%opts | $ver
400
401=back
402
403Controls the naming options for backward compatibility, see
404L<DBIx::Class::Schema::Loader::Base/naming> for details.
405
406To upgrade a dynamic schema, use:
407
408 __PACKAGE__->naming('current');
409
410Can be imported into your dump script and called as a function as well:
411
412 naming('v4');
996be9ee 413
f22644d7 414=head2 use_namespaces
415
416=over 4
417
418=item Arguments: 1|0
419
420=back
421
422Controls the use_namespaces options for backward compatibility, see
423L<DBIx::Class::Schema::Loader::Base/use_namespaces> for details.
424
425To upgrade a dynamic schema, use:
426
427 __PACKAGE__->use_namespaces(1);
428
429Can be imported into your dump script and called as a function as well:
430
431 use_namespaces(1);
432
996be9ee 433=head1 KNOWN ISSUES
434
435=head2 Multiple Database Schemas
436
437Currently the loader is limited to working within a single schema
707fb247 438(using the underlying RDBMS's definition of "schema"). If you have a
439multi-schema database with inter-schema relationships (which is easy
440to do in PostgreSQL or DB2 for instance), you currently can only
441automatically load the tables of one schema, and relationships to
442tables in other schemas will be silently ignored.
996be9ee 443
444At some point in the future, an intelligent way around this might be
445devised, probably by allowing the C<db_schema> option to be an
d65cda9e 446arrayref of schemas to load.
89ecd854 447
996be9ee 448In "normal" L<DBIx::Class::Schema> usage, manually-defined
449source classes and relationships have no problems crossing vendor schemas.
89ecd854 450
be80bba7 451=head1 ACKNOWLEDGEMENTS
a78e3fed 452
be80bba7 453Matt S Trout, all of the #dbix-class folks, and everyone who's ever sent
454in a bug report or suggestion.
fbd83464 455
8a6b44ef 456Based on L<DBIx::Class::Loader> by Sebastian Riedel
a78e3fed 457
458Based upon the work of IKEBE Tomohiro
459
be80bba7 460=head1 AUTHOR
a78e3fed 461
be80bba7 462blblack: Brandon Black <blblack@gmail.com>
463
464=head1 CONTRIBUTORS
465
a41f1fd4 466ilmari: Dagfinn Ilmari MannsE<aring>ker <ilmari@ilmari.org>
be80bba7 467
468arcanez: Justin Hunter <justin.d.hunter@gmail.com>
469
470ash: Ash Berlin <ash@cpan.org>
471
472Caelum: Rafael Kitover <rkitover@cpan.org>
473
474TSUNODA Kazuya <drk@drk7.jp>
475
f84a7413 476rbo: Robert Bohne <rbo@cpan.org>
be80bba7 477
69fca474 478ribasushi: Peter Rabbitson <ribasushi@cpan.org>
1f625792 479
fdd8ff16 480gugu: Andrey Kostenko <a.kostenko@rambler-co.ru>
481
65e705c3 482jhannah: Jay Hannah <jay@jays.net>
483
7b505bbd 484rbuels: Robert Buels <rmb32@cornell.edu>
485
accc9e96 486timbunce: Tim Bunce <timb@cpan.org>
da21e0cf 487
c21bfb92 488mst: Matt S. Trout <mst@shadowcatsystems.co.uk>
489
827dff19 490kane: Jos Boumans <kane@cpan.org>
491
43b982ea 492waawaamilk: Nigel McNie <nigel@mcnie.name>
493
96f68869 494acmoore: Andrew Moore <amoore@cpan.org>
495
2a5dcfb3 496bphillips: Brian Phillips <bphillips@cpan.org>
497
be80bba7 498... and lots of other folks. If we forgot you, please write the current
499maintainer or RT.
a78e3fed 500
9cc8e7e1 501=head1 COPYRIGHT & LICENSE
502
503Copyright (c) 2006 - 2009 by the aforementioned
504L<DBIx::Class::Schema::Loader/AUTHOR> and
505L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
a78e3fed 506
507This library is free software; you can redistribute it and/or modify it under
508the same terms as Perl itself.
509
510=head1 SEE ALSO
511
996be9ee 512L<DBIx::Class>, L<DBIx::Class::Manual::ExampleSchema>
a78e3fed 513
514=cut
515
5161;