1 package SQL::Translator::Schema::Field;
7 SQL::Translator::Schema::Field - SQL::Translator field object
11 use SQL::Translator::Schema::Field;
12 my $field = SQL::Translator::Schema::Field->new(
19 C<SQL::Translator::Schema::Field> is the field object.
26 use SQL::Translator::Schema::Constants;
27 use SQL::Translator::Types qw(schema_obj);
28 use SQL::Translator::Utils qw(parse_list_arg ex2err throw);
31 SQL::Translator::Schema::Role::BuildArgs
32 SQL::Translator::Schema::Role::Extra
33 SQL::Translator::Schema::Role::Error
34 SQL::Translator::Schema::Role::Compare
37 our ( $TABLE_COUNT, $VIEW_COUNT );
39 our $VERSION = '1.59';
41 # Stringify to our name, being careful not to pass any args through so we don't
42 # accidentally set it to undef. We also have to tweak bool so the object is
43 # still true when it doesn't have a name (which shouldn't happen!).
45 '""' => sub { shift->name },
46 'bool' => sub { $_[0]->name || $_[0] },
50 use DBI qw(:sql_types);
52 # Mapping from string to sql contstant
54 integer => SQL_INTEGER,
57 smallint => SQL_SMALLINT,
58 bigint => 9999, # DBI doesn't export a constatn for this. Le suck
62 decimal => SQL_DECIMAL,
63 numeric => SQL_NUMERIC,
69 datetime => SQL_DATETIME,
70 timestamp => SQL_TIMESTAMP,
74 varchar => SQL_VARCHAR,
76 varbinary => SQL_VARBINARY,
79 text => SQL_LONGVARCHAR
87 my $field = SQL::Translator::Schema::Field->new(
94 Get or set the comments on a field. May be called several times to
95 set and it will accumulate the comments. Called in an array context,
96 returns each comment individually; called in a scalar context, returns
97 all the comments joined on newlines.
99 $field->comments('foo');
100 $field->comments('bar');
101 print join( ', ', $field->comments ); # prints "foo, bar"
107 coerce => sub { ref($_[0]) eq 'ARRAY' ? $_[0] : [$_[0]] },
108 default => sub { [] },
111 around comments => sub {
116 $arg = $arg->[0] if ref $arg;
117 push @{ $self->$orig }, $arg if $arg;
122 : join( "\n", @{ $self->$orig } );
128 Get or set the field's data type.
130 my $data_type = $field->data_type('integer');
134 has data_type => ( is => 'rw', default => sub { '' } );
138 Constant from DBI package representing this data type. See L<DBI/DBI Constants>
143 has sql_data_type => ( is => 'rw', lazy => 1, builder => 1 );
145 sub _build_sql_data_type {
146 $type_mapping{lc $_[0]->data_type} || SQL_UNKNOWN_TYPE;
151 Get or set the field's default value. Will return undef if not defined
152 and could return the empty string (it's a valid default value), so don't
153 assume an error like other methods.
155 my $default = $field->default_value('foo');
159 has default_value => ( is => 'rw' );
163 Get or set the field's "extra" attibutes (e.g., "ZEROFILL" for MySQL).
164 Accepts a hash(ref) of name/value pairs to store; returns a hash.
166 $field->extra( qualifier => 'ZEROFILL' );
167 my %extra = $field->extra;
171 =head2 foreign_key_reference
173 Get or set the field's foreign key reference;
175 my $constraint = $field->foreign_key_reference( $constraint );
179 has foreign_key_reference => (
181 predicate => '_has_foreign_key_reference',
182 isa => schema_obj('Constraint'),
185 around foreign_key_reference => sub {
189 if ( my $arg = shift ) {
191 'Foreign key reference for ', $self->name, 'already defined'
192 ) if $self->_has_foreign_key_reference;
194 return ex2err($orig, $self, $arg);
199 =head2 is_auto_increment
201 Get or set the field's C<is_auto_increment> attribute.
203 my $is_auto = $field->is_auto_increment(1);
207 has is_auto_increment => (
209 coerce => sub { $_[0] ? 1 : 0 },
214 sub _build_is_auto_increment {
217 if ( my $table = $self->table ) {
218 if ( my $schema = $table->schema ) {
220 $schema->database eq 'PostgreSQL' &&
221 $self->data_type eq 'serial'
230 =head2 is_foreign_key
232 Returns whether or not the field is a foreign key.
234 my $is_fk = $field->is_foreign_key;
238 has is_foreign_key => (
240 coerce => sub { $_[0] ? 1 : 0 },
245 sub _build_is_foreign_key {
248 if ( my $table = $self->table ) {
249 for my $c ( $table->get_constraints ) {
250 if ( $c->type eq FOREIGN_KEY ) {
251 my %fields = map { $_, 1 } $c->fields;
252 if ( $fields{ $self->name } ) {
253 $self->foreign_key_reference( $c );
264 Get or set whether the field can be null. If not defined, then
265 returns "1" (assumes the field can be null). The argument is evaluated
266 by Perl for True or False, so the following are eqivalent:
268 $is_nullable = $field->is_nullable(0);
269 $is_nullable = $field->is_nullable('');
270 $is_nullable = $field->is_nullable('0');
272 While this is technically a field constraint, it's probably easier to
273 represent this as an attribute of the field. In order keep things
274 consistent, any other constraint on the field (unique, primary, and
275 foreign keys; checks) are represented as table constraints.
281 coerce => sub { $_[0] ? 1 : 0 },
282 default => sub { 1 },
285 around is_nullable => sub {
286 my ($orig, $self, $arg) = @_;
288 $self->$orig($self->is_primary_key ? 0 : defined $arg ? $arg : ());
291 =head2 is_primary_key
293 Get or set the field's C<is_primary_key> attribute. Does not create
294 a table constraint (should it?).
296 my $is_pk = $field->is_primary_key(1);
300 has is_primary_key => (
302 coerce => sub { $_[0] ? 1 : 0 },
307 sub _build_is_primary_key {
310 if ( my $table = $self->table ) {
311 if ( my $pk = $table->primary_key ) {
312 my %fields = map { $_, 1 } $pk->fields;
313 return $fields{ $self->name } || 0;
321 Determine whether the field has a UNIQUE constraint or not.
323 my $is_unique = $field->is_unique;
327 has is_unique => ( is => 'lazy', init_arg => undef );
329 sub _build_is_unique {
332 if ( my $table = $self->table ) {
333 for my $c ( $table->get_constraints ) {
334 if ( $c->type eq UNIQUE ) {
335 my %fields = map { $_, 1 } $c->fields;
336 if ( $fields{ $self->name } ) {
351 Determine whether the field is valid or not.
353 my $ok = $field->is_valid;
358 return $self->error('No name') unless $self->name;
359 return $self->error('No data type') unless $self->data_type;
360 return $self->error('No table object') unless $self->table;
366 Get or set the field's name.
368 my $name = $field->name('foo');
370 The field object will also stringify to its name.
372 my $setter_name = "set_$field";
374 Errors ("No field name") if you try to set a blank name.
378 has name => ( is => 'rw', isa => sub { throw( "No field name" ) unless $_[0] } );
384 if ( my ($arg) = @_ ) {
385 if ( my $schema = $self->table ) {
386 return $self->error( qq[Can't use field name "$arg": field exists] )
387 if $schema->get_field( $arg );
391 return ex2err($orig, $self, @_);
398 Read only method to return the fields name with its table name pre-pended.
404 return $self->table.".".$self->name;
409 Get or set the field's order.
411 my $order = $field->order(3);
415 has order => ( is => 'rw', default => sub { 0 } );
417 around order => sub {
418 my ( $orig, $self, $arg ) = @_;
420 if ( defined $arg && $arg =~ /^\d+$/ ) {
421 return $self->$orig($arg);
431 Shortcut to get the fields schema ($field->table->schema) or undef if it
434 my $schema = $field->schema;
439 if ( my $table = $self->table ) { return $table->schema || undef; }
445 Get or set the field's size. Accepts a string, array or arrayref of
446 numbers and returns a string.
449 $field->size( [ 255 ] );
450 $size = $field->size( 10, 2 );
451 print $size; # prints "10,2"
453 $size = $field->size( '10, 2' );
454 print $size; # prints "10,2"
460 default => sub { [0] },
462 my @sizes = grep { defined && m/^\d+(?:\.\d+)?$/ } @{parse_list_arg($_[0])};
463 @sizes ? \@sizes : [0];
470 my $numbers = parse_list_arg( @_ );
474 for my $num ( @$numbers ) {
475 if ( defined $num && $num =~ m/^\d+(?:\.\d+)?$/ ) {
479 $self->$orig(\@new) if @new; # only set if all OK
483 ? @{ $self->$orig || [0] }
484 : join( ',', @{ $self->$orig || [0] } )
490 Get or set the field's table object. As the table object stringifies this can
491 also be used to get the table name.
493 my $table = $field->table;
494 print "Table name: $table";
498 has table => ( is => 'rw', isa => schema_obj('Table') );
500 around table => \&ex2err;
504 Returns the field exactly as the parser found it
508 has parsed_field => ( is => 'rw' );
510 around parsed_field => sub {
514 return $self->$orig(@_) || $self;
519 Determines if this field is the same as another
521 my $isIdentical = $field1->equals( $field2 );
525 around equals => sub {
529 my $case_insensitive = shift;
531 return 0 unless $self->$orig($other);
532 return 0 unless $case_insensitive ? uc($self->name) eq uc($other->name) : $self->name eq $other->name;
534 # Comparing types: use sql_data_type if both are not 0. Else use string data_type
535 if ($self->sql_data_type && $other->sql_data_type) {
536 return 0 unless $self->sql_data_type == $other->sql_data_type
538 return 0 unless lc($self->data_type) eq lc($other->data_type)
541 return 0 unless $self->size eq $other->size;
544 my $lhs = $self->default_value;
545 $lhs = \'NULL' unless defined $lhs;
546 my $lhs_is_ref = ! ! ref $lhs;
548 my $rhs = $other->default_value;
549 $rhs = \'NULL' unless defined $rhs;
550 my $rhs_is_ref = ! ! ref $rhs;
552 # If only one is a ref, fail. -- rjbs, 2008-12-02
553 return 0 if $lhs_is_ref xor $rhs_is_ref;
555 my $effective_lhs = $lhs_is_ref ? $$lhs : $lhs;
556 my $effective_rhs = $rhs_is_ref ? $$rhs : $rhs;
558 return 0 if $effective_lhs ne $effective_rhs;
561 return 0 unless $self->is_nullable eq $other->is_nullable;
562 # return 0 unless $self->is_unique eq $other->is_unique;
563 return 0 unless $self->is_primary_key eq $other->is_primary_key;
564 # return 0 unless $self->is_foreign_key eq $other->is_foreign_key;
565 return 0 unless $self->is_auto_increment eq $other->is_auto_increment;
566 # return 0 unless $self->comments eq $other->comments;
567 return 0 unless $self->_compare_objects(scalar $self->extra, scalar $other->extra);
573 # Destroy cyclical references.
576 undef $self->{'table'};
577 undef $self->{'foreign_key_reference'};
580 # Must come after all 'has' declarations
581 around new => \&ex2err;
589 Ken Youens-Clark E<lt>kclark@cpan.orgE<gt>.