1 package DBIx::Class::Schema::Loader::Base;
5 use base qw/Class::Accessor::Fast/;
8 use UNIVERSAL::require;
9 use DBIx::Class::Schema::Loader::RelBuilder;
10 use Data::Dump qw/ dump /;
14 __PACKAGE__->mk_ro_accessors(qw/
21 additional_base_classes
32 legacy_default_inflections
42 DBIx::Class::Schema::Loader::Base - Base DBIx::Class::Schema::Loader Implementation.
46 See L<DBIx::Class::Schema::Loader>
50 This is the base class for the storage-specific C<DBIx::Class::Schema::*>
51 classes, and implements the common functionality between them.
53 =head1 CONSTRUCTOR OPTIONS
55 These constructor options are the base options for
56 L<DBIx::Class::Schema::Loader/loader_opts>. Available constructor options are:
60 Try to automatically detect/setup has_a and has_many relationships.
64 If set to true, each constructive L<DBIx::Class> statement the loader
65 decides to execute will be C<warn>-ed before execution.
69 Only load tables matching regex. Best specified as a qr// regex.
73 Exclude tables matching regex. Best specified as a qr// regex.
77 Overrides the default tablename -> moniker translation. Can be either
78 a hashref of table => moniker names, or a coderef for a translator
79 function taking a single scalar table name argument and returning
80 a scalar moniker. If the hash entry does not exist, or the function
81 returns a false value, the code falls back to default behavior
84 The default behavior is: C<join '', map ucfirst, split /[\W_]+/, lc $table>,
85 which is to say: lowercase everything, split up the table name into chunks
86 anywhere a non-alpha-numeric character occurs, change the case of first letter
87 of each chunk to upper case, and put the chunks back together. Examples:
89 Table Name | Moniker Name
90 ---------------------------
92 luser_group | LuserGroup
93 luser-opts | LuserOpts
97 Just like L</moniker_map> above (can be hash/code-ref, falls back to default
98 if hash key does not exist or coderef returns false), but acts as a map
99 for pluralizing relationship names. The default behavior is to utilize
100 L<Lingua::EN::Inflect::Number/to_PL>.
102 =head2 inflect_singular
104 As L</inflect_plural> above, but for singularizing relationship names.
105 Default behavior is to utilize L<Lingua::EN::Inflect::Number/to_S>.
107 =head2 additional_base_classes
109 List of additional base classes all of your table classes will use.
111 =head2 left_base_classes
113 List of additional base classes all of your table classes will use
114 that need to be leftmost.
116 =head2 additional_classes
118 List of additional classes which all of your table classes will use.
122 List of additional components to be loaded into all of your table
123 classes. A good example would be C<ResultSetManager>.
125 =head2 resultset_components
127 List of additional resultset components to be loaded into your table
128 classes. A good example would be C<AlwaysRS>. Component
129 C<ResultSetManager> will be automatically added to the above
130 C<components> list if this option is set.
132 =head2 legacy_default_inflections
134 Setting this option changes the default fallback for L</inflect_plural> to
135 utilize L<Lingua::EN::Inflect/PL>, and L</inflect_singlular> to a no-op.
136 Those choices produce substandard results, but might be neccesary to support
137 your existing code if you started developing on a version prior to 0.03 and
138 don't wish to go around updating all your relationship names to the new
141 =head2 dump_directory
143 This option is designed to be a tool to help you transition from this
144 loader to a manually-defined schema when you decide it's time to do so.
146 The value of this option is a perl libdir pathname. Within
147 that directory this module will create a baseline manual
148 L<DBIx::Class::Schema> module set, based on what it creates at runtime
151 The created schema class will have the same classname as the one on
152 which you are setting this option (and the ResultSource classes will be
153 based on this name as well). Therefore it is wise to note that if you
154 point the C<dump_directory> option of a schema class at the live libdir
155 where that class is currently located, it will overwrite itself with a
156 manual version of itself. This might be a really good or bad thing
157 depending on your situation and perspective.
159 Normally you wouldn't hardcode this setting in your schema class, as it
160 is meant for one-time manual usage.
162 See L<DBIx::Class::Schema::Loader/dump_to_dir> for examples of the
163 recommended way to access this functionality.
165 =head1 DEPRECATED CONSTRUCTOR OPTIONS
169 Equivalent to L</inflect_plural>.
173 Equivalent to L</inflect_plural>.
175 =head2 connect_info, dsn, user, password, options
177 You connect these schemas the same way you would any L<DBIx::Class::Schema>,
178 which is by calling either C<connect> or C<connection> on a schema class
179 or object. These options are only supported via the deprecated
180 C<load_from_connection> interface, which will be removed in the future.
184 None of these methods are intended for direct invocation by regular
185 users of L<DBIx::Class::Schema::Loader>. Anything you can find here
186 can also be found via standard L<DBIx::Class::Schema> methods somehow.
190 # ensure that a peice of object data is a valid arrayref, creating
191 # an empty one or encapsulating whatever's there.
192 sub _ensure_arrayref {
197 $self->{$_} = [ $self->{$_} ]
198 unless ref $self->{$_} eq 'ARRAY';
204 Constructor for L<DBIx::Class::Schema::Loader::Base>, used internally
205 by L<DBIx::Class::Schema::Loader>.
210 my ( $class, %args ) = @_;
212 my $self = { %args };
214 bless $self => $class;
216 $self->{db_schema} ||= '';
217 $self->_ensure_arrayref(qw/additional_classes
218 additional_base_classes
224 push(@{$self->{components}}, 'ResultSetManager')
225 if @{$self->{resultset_components}};
227 $self->{monikers} = {};
228 $self->{classes} = {};
230 # Support deprecated arguments
231 for(qw/inflect_map inflect/) {
232 warn "Argument $_ is deprecated in favor of 'inflect_plural'"
235 $self->{inflect_plural} ||= $self->{inflect_map} || $self->{inflect};
237 $self->{schema_class} ||= ( ref $self->{schema} || $self->{schema} );
238 $self->{schema} ||= $self->{schema_class};
246 foreach my $table_class (values %{$self->classes}) {
247 $table_class->require;
248 if($@ && $@ !~ /^Can't locate /) {
249 croak "Failed to load external class definition"
250 . " for '$table_class': $@";
252 next if $@; # "Can't locate" error
254 # If we make it to here, we loaded an external definition
255 warn qq/# Loaded external class definition for '$table_class'\n/
258 if($self->dump_directory) {
259 my $class_path = $table_class;
260 $class_path =~ s{::}{/}g;
261 my $filename = $INC{$class_path};
262 croak 'Failed to locate actual external module file for '
265 open(my $fh, '<', $filename)
266 or croak "Failed to open $filename for reading: $!";
267 $self->_raw_stmt($table_class,
268 q|# These lines loaded from user-supplied external file: |
272 $self->_raw_stmt($table_class, $_);
274 $self->_raw_stmt($table_class,
275 q|# End of lines loaded from user-supplied external file |
278 or croak "Failed to close $filename: $!";
285 Does the actual schema-construction work.
292 $self->_load_classes;
293 $self->_load_relationships if $self->relationships;
294 $self->_load_external;
295 $self->_dump_to_dir if $self->dump_directory;
300 sub _get_dump_filename {
301 my ($self, $class) = (@_);
304 return $self->dump_directory . q{/} . $class . q{.pm};
307 sub _ensure_dump_subdirs {
308 my ($self, $class) = (@_);
310 my @name_parts = split(/::/, $class);
312 my $dir = $self->dump_directory;
313 foreach (@name_parts) {
316 mkdir($dir) or die "mkdir('$dir') failed: $!";
324 my $target_dir = $self->dump_directory;
326 die "Must specify target directory for dumping!" if ! $target_dir;
328 warn "Dumping manual schema to $target_dir ...\n";
330 if(! -d $target_dir) {
331 mkdir($target_dir) or die "mkdir('$target_dir') failed: $!";
334 my $verstr = $DBIx::Class::Schema::Loader::VERSION;
335 my $datestr = POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime);
336 my $tagline = qq|# Created by DBIx::Class::Schema::Loader v$verstr @ $datestr|;
338 my $schema_class = $self->schema_class;
339 $self->_ensure_dump_subdirs($schema_class);
341 my $schema_fn = $self->_get_dump_filename($schema_class);
342 open(my $schema_fh, '>', $schema_fn)
343 or die "Cannot open $schema_fn for writing: $!";
344 print $schema_fh qq|package $schema_class;\n\n$tagline\n\n|;
345 print $schema_fh qq|use strict;\nuse warnings;\n\n|;
346 print $schema_fh qq|use base 'DBIx::Class::Schema';\n\n|;
347 print $schema_fh qq|__PACKAGE__->load_classes;\n|;
348 print $schema_fh qq|\n1;\n\n|;
350 or die "Cannot close $schema_fn: $!";
352 foreach my $src_class (sort keys %{$self->{_dump_storage}}) {
353 $self->_ensure_dump_subdirs($src_class);
354 my $src_fn = $self->_get_dump_filename($src_class);
355 open(my $src_fh, '>', $src_fn)
356 or die "Cannot open $src_fn for writing: $!";
357 print $src_fh qq|package $src_class;\n\n$tagline\n\n|;
358 print $src_fh qq|use strict;\nuse warnings;\n\n|;
359 print $src_fh qq|use base 'DBIx::Class';\n\n|;
360 print $src_fh qq|$_\n|
361 for @{$self->{_dump_storage}->{$src_class}};
362 print $src_fh qq|\n1;\n\n|;
364 or die "Cannot close $src_fn: $!";
367 warn "Schema dump completed.\n";
375 $_->require or croak ($_ . "->require: $@");
376 $self->_raw_stmt($target, "use $_;");
377 warn "$target: use $_" if $self->debug;
378 eval "package $target; use $_;";
379 croak "use $_: $@" if $@;
386 my $schema_class = $self->schema_class;
388 my $blist = join(q{ }, @_);
389 $self->_raw_stmt($target, "use base qw/ $blist /;") if @_;
390 warn "$target: use base qw/ $blist /" if $self->debug;
392 $_->require or croak ($_ . "->require: $@");
393 $schema_class->inject_base($target, $_);
397 # Load and setup classes
401 my $schema = $self->schema;
402 my $schema_class = $self->schema_class;
404 my $constraint = $self->constraint;
405 my $exclude = $self->exclude;
406 my @tables = sort $self->_tables_list;
408 warn "No tables found in database, nothing to load" if !@tables;
411 @tables = grep { /$constraint/ } @tables if $constraint;
412 @tables = grep { ! /$exclude/ } @tables if $exclude;
414 warn "All tables excluded by constraint/exclude, nothing to load"
418 $self->{_tables} = \@tables;
420 foreach my $table (@tables) {
421 my $table_moniker = $self->_table2moniker($table);
422 my $table_class = $schema_class . q{::} . $table_moniker;
424 my $table_normalized = lc $table;
425 $self->classes->{$table} = $table_class;
426 $self->classes->{$table_normalized} = $table_class;
427 $self->monikers->{$table} = $table_moniker;
428 $self->monikers->{$table_normalized} = $table_moniker;
430 no warnings 'redefine';
431 local *Class::C3::reinitialize = sub { };
435 @{"${table_class}::ISA"} = qw/DBIx::Class/;
437 $self->_use ($table_class, @{$self->additional_classes});
438 $self->_inject($table_class, @{$self->additional_base_classes});
440 $self->_dbic_stmt($table_class, 'load_components', @{$self->components}, qw/PK::Auto Core/);
442 $self->_dbic_stmt($table_class, 'load_resultset_components', @{$self->resultset_components})
443 if @{$self->resultset_components};
444 $self->_inject($table_class, @{$self->left_base_classes});
447 Class::C3::reinitialize;
449 foreach my $table (@tables) {
450 my $table_class = $self->classes->{$table};
451 my $table_moniker = $self->monikers->{$table};
453 $self->_dbic_stmt($table_class,'table',$table);
455 my $cols = $self->_table_columns($table);
456 $self->_dbic_stmt($table_class,'add_columns',@$cols);
458 my $pks = $self->_table_pk_info($table) || [];
459 @$pks ? $self->_dbic_stmt($table_class,'set_primary_key',@$pks)
460 : carp("$table has no primary key");
462 my $uniqs = $self->_table_uniq_info($table) || [];
463 $self->_dbic_stmt($table_class,'add_unique_constraint',@$_) for (@$uniqs);
465 $schema_class->register_class($table_moniker, $table_class);
466 $schema->register_class($table_moniker, $table_class) if $schema ne $schema_class;
472 Returns a sorted list of loaded tables, using the original database table
480 return @{$self->_tables};
483 # Make a moniker from a table
485 my ( $self, $table ) = @_;
489 if( ref $self->moniker_map eq 'HASH' ) {
490 $moniker = $self->moniker_map->{$table};
492 elsif( ref $self->moniker_map eq 'CODE' ) {
493 $moniker = $self->moniker_map->($table);
496 $moniker ||= join '', map ucfirst, split /[\W_]+/, lc $table;
501 sub _load_relationships {
504 # Construct the fk_info RelBuilder wants to see, by
505 # translating table names to monikers in the _fk_info output
507 foreach my $table ($self->tables) {
508 my $tbl_fk_info = $self->_table_fk_info($table);
509 foreach my $fkdef (@$tbl_fk_info) {
510 $fkdef->{remote_source} =
511 $self->monikers->{delete $fkdef->{remote_table}};
513 my $moniker = $self->monikers->{$table};
514 $fk_info{$moniker} = $tbl_fk_info;
517 my $relbuilder = DBIx::Class::Schema::Loader::RelBuilder->new(
518 $self->schema_class, \%fk_info, $self->inflect_plural,
519 $self->inflect_singular
522 my $rel_stmts = $relbuilder->generate_code;
523 foreach my $src_class (sort keys %$rel_stmts) {
524 my $src_stmts = $rel_stmts->{$src_class};
525 foreach my $stmt (@$src_stmts) {
526 $self->_dbic_stmt($src_class,$stmt->{method},@{$stmt->{args}});
531 # Overload these in driver class:
533 # Returns an arrayref of column names
534 sub _table_columns { croak "ABSTRACT METHOD" }
536 # Returns arrayref of pk col names
537 sub _table_pk_info { croak "ABSTRACT METHOD" }
539 # Returns an arrayref of uniqs [ [ foo => [ col1, col2 ] ], [ bar => [ ... ] ] ]
540 sub _table_uniq_info { croak "ABSTRACT METHOD" }
542 # Returns an arrayref of foreign key constraints, each
543 # being a hashref with 3 keys:
544 # local_columns (arrayref), remote_columns (arrayref), remote_table
545 sub _table_fk_info { croak "ABSTRACT METHOD" }
547 # Returns an array of lower case table names
548 sub _tables_list { croak "ABSTRACT METHOD" }
550 # Execute a constructive DBIC class method, with debug/dump_to_dir hooks.
556 if(!$self->debug && !$self->dump_directory) {
562 $args = '(' . $args . ')' if @_ < 2;
563 my $stmt = $method . $args . q{;};
565 warn qq|$class\->$stmt\n| if $self->debug;
567 $self->_raw_stmt($class, '__PACKAGE__->' . $stmt);
570 # Store a raw source line for a class (for dumping purposes)
572 my ($self, $class, $stmt) = @_;
573 push(@{$self->{_dump_storage}->{$class}}, $stmt) if $self->dump_directory;
578 Returns a hashref of loaded table-to-moniker mappings. There will
579 be two entries for each table, the original name and the "normalized"
580 name, in the case that the two are different (such as databases
581 that like uppercase table names, or preserve your original mixed-case
582 definitions, or what-have-you).
586 Returns a hashref of table-to-classname mappings. In some cases it will
587 contain multiple entries per table for the original and normalized table
588 names, as above in L</monikers>.
592 L<DBIx::Class::Schema::Loader>