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 carp_ro);
29 use Sub::Quote qw(quote_sub);
32 extends 'SQL::Translator::Schema::Object';
34 our $VERSION = '1.59';
36 # Stringify to our name, being careful not to pass any args through so we don't
37 # accidentally set it to undef. We also have to tweak bool so the object is
38 # still true when it doesn't have a name (which shouldn't happen!).
40 '""' => sub { shift->name },
41 'bool' => sub { $_[0]->name || $_[0] },
45 use DBI qw(:sql_types);
47 # Mapping from string to sql constant
49 integer => SQL_INTEGER,
52 tinyint => SQL_TINYINT,
53 smallint => SQL_SMALLINT,
57 'double precision' => SQL_DOUBLE,
59 decimal => SQL_DECIMAL,
61 numeric => SQL_NUMERIC,
69 datetime => SQL_DATETIME,
70 timestamp => SQL_TIMESTAMP,
74 varchar => SQL_VARCHAR,
76 varbinary => SQL_VARBINARY,
79 text => SQL_LONGVARCHAR
83 has _numeric_sql_data_types => ( is => 'lazy' );
85 sub _build__numeric_sql_data_types {
88 (SQL_INTEGER, SQL_TINYINT, SQL_SMALLINT, SQL_BIGINT, SQL_DOUBLE,
89 SQL_NUMERIC, SQL_DECIMAL, SQL_FLOAT, SQL_REAL)
97 my $field = SQL::Translator::Schema::Field->new(
104 Get or set the comments on a field. May be called several times to
105 set and it will accumulate the comments. Called in an array context,
106 returns each comment individually; called in a scalar context, returns
107 all the comments joined on newlines.
109 $field->comments('foo');
110 $field->comments('bar');
111 print join( ', ', $field->comments ); # prints "foo, bar"
117 coerce => quote_sub(q{ ref($_[0]) eq 'ARRAY' ? $_[0] : [$_[0]] }),
118 default => quote_sub(q{ [] }),
121 around comments => sub {
126 $arg = $arg->[0] if ref $arg;
127 push @{ $self->$orig }, $arg if $arg;
132 : join( "\n", @{ $self->$orig } );
138 Get or set the field's data type.
140 my $data_type = $field->data_type('integer');
144 has data_type => ( is => 'rw', default => quote_sub(q{ '' }) );
148 Constant from DBI package representing this data type. See L<DBI/DBI Constants>
153 has sql_data_type => ( is => 'rw', lazy => 1, builder => 1 );
155 sub _build_sql_data_type {
156 $type_mapping{lc $_[0]->data_type} || SQL_UNKNOWN_TYPE;
161 Get or set the field's default value. Will return undef if not defined
162 and could return the empty string (it's a valid default value), so don't
163 assume an error like other methods.
165 my $default = $field->default_value('foo');
169 has default_value => ( is => 'rw' );
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'),
186 around foreign_key_reference => sub {
190 if ( my $arg = shift ) {
192 'Foreign key reference for ', $self->name, 'already defined'
193 ) if $self->_has_foreign_key_reference;
195 return ex2err($orig, $self, $arg);
200 =head2 is_auto_increment
202 Get or set the field's C<is_auto_increment> attribute.
204 my $is_auto = $field->is_auto_increment(1);
208 has is_auto_increment => (
210 coerce => quote_sub(q{ $_[0] ? 1 : 0 }),
215 sub _build_is_auto_increment {
218 if ( my $table = $self->table ) {
219 if ( my $schema = $table->schema ) {
221 $schema->database eq 'PostgreSQL' &&
222 $self->data_type eq 'serial'
231 =head2 is_foreign_key
233 Returns whether or not the field is a foreign key.
235 my $is_fk = $field->is_foreign_key;
239 has is_foreign_key => (
241 coerce => quote_sub(q{ $_[0] ? 1 : 0 }),
246 sub _build_is_foreign_key {
249 if ( my $table = $self->table ) {
250 for my $c ( $table->get_constraints ) {
251 if ( $c->type eq FOREIGN_KEY ) {
252 my %fields = map { $_, 1 } $c->fields;
253 if ( $fields{ $self->name } ) {
254 $self->foreign_key_reference( $c );
265 Get or set whether the field can be null. If not defined, then
266 returns "1" (assumes the field can be null). The argument is evaluated
267 by Perl for True or False, so the following are equivalent:
269 $is_nullable = $field->is_nullable(0);
270 $is_nullable = $field->is_nullable('');
271 $is_nullable = $field->is_nullable('0');
273 While this is technically a field constraint, it's probably easier to
274 represent this as an attribute of the field. In order keep things
275 consistent, any other constraint on the field (unique, primary, and
276 foreign keys; checks) are represented as table constraints.
282 coerce => quote_sub(q{ $_[0] ? 1 : 0 }),
283 default => quote_sub(q{ 1 }),
286 around is_nullable => sub {
287 my ($orig, $self, $arg) = @_;
289 $self->$orig($self->is_primary_key ? 0 : defined $arg ? $arg : ());
292 =head2 is_primary_key
294 Get or set the field's C<is_primary_key> attribute. Does not create
295 a table constraint (should it?).
297 my $is_pk = $field->is_primary_key(1);
301 has is_primary_key => (
303 coerce => quote_sub(q{ $_[0] ? 1 : 0 }),
308 sub _build_is_primary_key {
311 if ( my $table = $self->table ) {
312 if ( my $pk = $table->primary_key ) {
313 my %fields = map { $_, 1 } $pk->fields;
314 return $fields{ $self->name } || 0;
322 Determine whether the field has a UNIQUE constraint or not.
324 my $is_unique = $field->is_unique;
328 has is_unique => ( is => 'lazy', init_arg => undef );
330 around is_unique => carp_ro('is_unique');
332 sub _build_is_unique {
335 if ( my $table = $self->table ) {
336 for my $c ( $table->get_constraints ) {
337 if ( $c->type eq UNIQUE ) {
338 my %fields = map { $_, 1 } $c->fields;
339 if ( $fields{ $self->name } ) {
354 Determine whether the field is valid or not.
356 my $ok = $field->is_valid;
361 return $self->error('No name') unless $self->name;
362 return $self->error('No data type') unless $self->data_type;
363 return $self->error('No table object') unless $self->table;
369 Get or set the field's name.
371 my $name = $field->name('foo');
373 The field object will also stringify to its name.
375 my $setter_name = "set_$field";
377 Errors ("No field name") if you try to set a blank name.
381 has name => ( is => 'rw', isa => sub { throw( "No field name" ) unless $_[0] } );
387 if ( my ($arg) = @_ ) {
388 if ( my $schema = $self->table ) {
389 return $self->error( qq[Can't use field name "$arg": field exists] )
390 if $schema->get_field( $arg );
394 return ex2err($orig, $self, @_);
401 Read only method to return the fields name with its table name pre-pended.
407 return $self->table.".".$self->name;
412 Get or set the field's order.
414 my $order = $field->order(3);
418 has order => ( is => 'rw', default => quote_sub(q{ 0 }) );
420 around order => sub {
421 my ( $orig, $self, $arg ) = @_;
423 if ( defined $arg && $arg =~ /^\d+$/ ) {
424 return $self->$orig($arg);
434 Shortcut to get the fields schema ($field->table->schema) or undef if it
437 my $schema = $field->schema;
442 if ( my $table = $self->table ) { return $table->schema || undef; }
448 Get or set the field's size. Accepts a string, array or arrayref of
449 numbers and returns a string.
452 $field->size( [ 255 ] );
453 $size = $field->size( 10, 2 );
454 print $size; # prints "10,2"
456 $size = $field->size( '10, 2' );
457 print $size; # prints "10,2"
463 default => quote_sub(q{ [0] }),
465 my @sizes = grep { defined && m/^\d+(?:\.\d+)?$/ } @{parse_list_arg($_[0])};
466 @sizes ? \@sizes : [0];
473 my $numbers = parse_list_arg( @_ );
477 for my $num ( @$numbers ) {
478 if ( defined $num && $num =~ m/^\d+(?:\.\d+)?$/ ) {
482 $self->$orig(\@new) if @new; # only set if all OK
486 ? @{ $self->$orig || [0] }
487 : join( ',', @{ $self->$orig || [0] } )
493 Get or set the field's table object. As the table object stringifies this can
494 also be used to get the table name.
496 my $table = $field->table;
497 print "Table name: $table";
501 has table => ( is => 'rw', isa => schema_obj('Table'), weak_ref => 1 );
503 around table => \&ex2err;
507 Returns the field exactly as the parser found it
511 has parsed_field => ( is => 'rw' );
513 around parsed_field => sub {
517 return $self->$orig(@_) || $self;
522 Determines if this field is the same as another
524 my $isIdentical = $field1->equals( $field2 );
528 around equals => sub {
532 my $case_insensitive = shift;
534 return 0 unless $self->$orig($other);
535 return 0 unless $case_insensitive ? uc($self->name) eq uc($other->name) : $self->name eq $other->name;
537 # Comparing types: use sql_data_type if both are not 0. Else use string data_type
538 if ($self->sql_data_type && $other->sql_data_type) {
539 return 0 unless $self->sql_data_type == $other->sql_data_type
541 return 0 unless lc($self->data_type) eq lc($other->data_type)
544 return 0 unless $self->size eq $other->size;
547 my $lhs = $self->default_value;
548 $lhs = \'NULL' unless defined $lhs;
549 my $lhs_is_ref = ! ! ref $lhs;
551 my $rhs = $other->default_value;
552 $rhs = \'NULL' unless defined $rhs;
553 my $rhs_is_ref = ! ! ref $rhs;
555 # If only one is a ref, fail. -- rjbs, 2008-12-02
556 return 0 if $lhs_is_ref xor $rhs_is_ref;
558 my $effective_lhs = $lhs_is_ref ? $$lhs : $lhs;
559 my $effective_rhs = $rhs_is_ref ? $$rhs : $rhs;
561 if ( $self->_is_numeric_data_type
562 && Scalar::Util::looks_like_number($effective_lhs)
563 && Scalar::Util::looks_like_number($effective_rhs) ) {
564 return 0 if ($effective_lhs + 0) != ($effective_rhs + 0);
567 return 0 if $effective_lhs ne $effective_rhs;
571 return 0 unless $self->is_nullable eq $other->is_nullable;
572 # return 0 unless $self->is_unique eq $other->is_unique;
573 return 0 unless $self->is_primary_key eq $other->is_primary_key;
574 # return 0 unless $self->is_foreign_key eq $other->is_foreign_key;
575 return 0 unless $self->is_auto_increment eq $other->is_auto_increment;
576 # return 0 unless $self->comments eq $other->comments;
577 return 0 unless $self->_compare_objects(scalar $self->extra, scalar $other->extra);
581 # Must come after all 'has' declarations
582 around new => \&ex2err;
584 sub _is_numeric_data_type {
586 return $self->_numeric_sql_data_types->{ $self->sql_data_type };
595 Ken Youens-Clark E<lt>kclark@cpan.orgE<gt>.