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