Fix broken POD links found by App::PodLinkChecker
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Schema / Constraint.pm
index 4f01050..7742bf7 100644 (file)
@@ -1,25 +1,5 @@
 package SQL::Translator::Schema::Constraint;
 
-# ----------------------------------------------------------------------
-# $Id: Constraint.pm,v 1.3 2003-05-09 17:06:11 kycl4rk Exp $
-# ----------------------------------------------------------------------
-# Copyright (C) 2003 Ken Y. Clark <kclark@cpan.org>
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License as
-# published by the Free Software Foundation; version 2.
-#
-# This program is distributed in the hope that it will be useful, but
-# WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-# General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
-# 02111-1307  USA
-# -------------------------------------------------------------------
-
 =pod
 
 =head1 NAME
@@ -43,70 +23,64 @@ C<SQL::Translator::Schema::Constraint> is the constraint object.
 
 =cut
 
-use strict;
-use Class::Base;
+use Moo;
 use SQL::Translator::Schema::Constants;
-use SQL::Translator::Utils 'parse_list_arg';
+use SQL::Translator::Utils qw(ex2err throw);
+use SQL::Translator::Role::ListAttr;
+use SQL::Translator::Types qw(schema_obj enum);
+use Sub::Quote qw(quote_sub);
 
-use base 'Class::Base';
-use vars qw($VERSION $TABLE_COUNT $VIEW_COUNT);
+extends 'SQL::Translator::Schema::Object';
 
-$VERSION = 1.00;
+our $VERSION = '1.59';
 
-use constant VALID_TYPE => {
+my %VALID_CONSTRAINT_TYPE = (
     PRIMARY_KEY, 1,
     UNIQUE,      1,
     CHECK_C,     1,
     FOREIGN_KEY, 1,
-};
-
-# ----------------------------------------------------------------------
-sub init {
-
-=pod
+    NOT_NULL,    1,
+);
 
 =head2 new
 
 Object constructor.
 
   my $schema           =  SQL::Translator::Schema::Constraint->new(
-      table            => $table,        # the table to which it belongs
+      table            => $table,        # table to which it belongs
       type             => 'foreign_key', # type of table constraint
-      name             => 'fk_phone_id', # the name of the constraint
-      fields           => 'phone_id',    # the field in the referring table
-      reference_fields => 'phone_id',    # the referenced table
-      reference_table  => 'phone',       # the referenced fields
+      name             => 'fk_phone_id', # name of the constraint
+      fields           => 'phone_id',    # field in the referring table
+      reference_fields => 'phone_id',    # referenced field
+      reference_table  => 'phone',       # referenced table
       match_type       => 'full',        # how to match
-      on_delete_do     => 'cascade',     # what to do on deletes
-      on_update_do     => '',            # what to do on updates
+      on_delete        => 'cascade',     # what to do on deletes
+      on_update        => '',            # what to do on updates
   );
 
 =cut
 
-    my ( $self, $config ) = @_;
-    my @fields = qw[ 
-        table name type fields reference_fields reference_table 
-        match_type on_delete on_update
-    ];
+# Override to remove empty arrays from args.
+# t/14postgres-parser breaks without this.
+around BUILDARGS => sub {
+    my $orig = shift;
+    my $self = shift;
+    my $args = $self->$orig(@_);
 
-    for my $arg ( @fields ) {
-        next unless $config->{ $arg };
-        $self->$arg( $config->{ $arg } ) or return;
+    foreach my $arg (keys %{$args}) {
+        delete $args->{$arg} if ref($args->{$arg}) eq "ARRAY" && !@{$args->{$arg}};
     }
-
-    return $self;
-}
-
-# ----------------------------------------------------------------------
-sub deferrable {
-
-=pod
+    if (exists $args->{fields}) {
+        $args->{field_names} = delete $args->{fields};
+    }
+    return $args;
+};
 
 =head2 deferrable
 
-Get or set the whether the constraint is deferrable.  If not defined,
+Get or set whether the constraint is deferrable.  If not defined,
 then returns "1."  The argument is evaluated by Perl for True or
-False, so the following are eqivalent:
+False, so the following are equivalent:
 
   $deferrable = $field->deferrable(0);
   $deferrable = $field->deferrable('');
@@ -114,19 +88,11 @@ False, so the following are eqivalent:
 
 =cut
 
-    my ( $self, $arg ) = @_;
-
-    if ( defined $arg ) {
-        $self->{'deferrable'} = $arg ? 1 : 0;
-    }
-
-    return defined $self->{'deferrable'} ? $self->{'deferrable'} : 1;
-}
-
-# ----------------------------------------------------------------------
-sub expression {
-
-=pod
+has deferrable => (
+    is => 'rw',
+    coerce => quote_sub(q{ $_[0] ? 1 : 0 }),
+    default => quote_sub(q{ 1 }),
+);
 
 =head2 expression
 
@@ -136,17 +102,13 @@ Gets and set the expression used in a CHECK constraint.
 
 =cut
 
-    my $self = shift;
-    
-    if ( my $arg = shift ) {
-        # check arg here?
-        $self->{'expression'} = $arg;
-    }
+has expression => ( is => 'rw', default => quote_sub(q{ '' }) );
 
-    return $self->{'expression'} || '';
-}
+around expression => sub {
+    my ($orig, $self, $arg) = @_;
+    $self->$orig($arg || ());
+};
 
-# ----------------------------------------------------------------------
 sub is_valid {
 
 =pod
@@ -181,7 +143,7 @@ Determine whether the constraint is valid or not.
         return $self->error('Only one field allowed for foreign key')
             if scalar @fields > 1;
 
-        my $ref_table_name  = $self->reference_table or 
+        my $ref_table_name  = $self->reference_table or
             return $self->error('No reference table');
 
         my $ref_table = $schema->get_table( $ref_table_name ) or
@@ -195,31 +157,32 @@ Determine whether the constraint is valid or not.
         for my $ref_field ( @ref_fields ) {
             next if $ref_table->get_field( $ref_field );
             return $self->error(
-                "Constraint from field(s) ", 
-                join(', ', map {qq['$table_name.$_']} @fields),
+                "Constraint from field(s) ".
+                join(', ', map {qq['$table_name.$_']} @fields).
                 " to non-existent field '$ref_table_name.$ref_field'"
             );
         }
     }
     elsif ( $type eq CHECK_C ) {
-        return $self->error('No expression for CHECK') unless 
+        return $self->error('No expression for CHECK') unless
             $self->expression;
     }
 
     return 1;
 }
 
-# ----------------------------------------------------------------------
-sub fields {
-
-=pod
-
 =head2 fields
 
 Gets and set the fields the constraint is on.  Accepts a string, list or
 arrayref; returns an array or array reference.  Will unique the field
 names and keep them in order by the first occurrence of a field name.
 
+The fields are returned as Field objects if they exist or as plain
+names if not. (If you just want the names and want to avoid the Field's overload
+magic use L</field_names>).
+
+Returns undef or an empty list if the constraint has no fields set.
+
   $constraint->fields('id');
   $constraint->fields('id', 'name');
   $constraint->fields( 'id, name' );
@@ -230,52 +193,46 @@ names and keep them in order by the first occurrence of a field name.
 
 =cut
 
-    my $self   = shift;
-    my $fields = parse_list_arg( @_ );
+sub fields {
+    my $self = shift;
+    my $table = $self->table;
+    my @fields = map { $table->get_field($_) || $_ } @{$self->field_names(@_) || []};
+    return wantarray ? @fields
+        : @fields ? \@fields
+        : undef;
+}
 
-    if ( @$fields ) {
-        my ( %unique, @unique );
-        for my $f ( @$fields ) {
-            next if $unique{ $f };
-            $unique{ $f } = 1;
-            push @unique, $f;
-        }
+=head2 field_names
 
-        $self->{'fields'} = \@unique;
-    }
+Read-only method to return a list or array ref of the field names. Returns undef
+or an empty list if the constraint has no fields set. Useful if you want to
+avoid the overload magic of the Field objects returned by the fields method.
 
-    return wantarray ? @{ $self->{'fields'} || [] } : $self->{'fields'};
-}
+  my @names = $constraint->field_names;
 
-# ----------------------------------------------------------------------
-sub match_type {
+=cut
 
-=pod
+with ListAttr field_names => ( uniq => 1, undef_if_empty => 1 );
 
 =head2 match_type
 
 Get or set the constraint's match_type.  Only valid values are "full"
-or "partial."
+"partial" and "simple"
 
   my $match_type = $constraint->match_type('FULL');
 
 =cut
 
-    my $self = shift;
-    
-    if ( my $arg = lc shift ) {
-        return $self->error("Invalid match type: $arg")
-            unless $arg eq 'full' || $arg eq 'partial';
-        $self->{'match_type'} = $arg;
-    }
-
-    return $self->{'match_type'} || '';
-}
+has match_type => (
+    is => 'rw',
+    default => quote_sub(q{ '' }),
+    coerce => quote_sub(q{ lc $_[0] }),
+    isa => enum([qw(full partial simple)], {
+        msg => "Invalid match type: %s", allow_false => 1,
+    }),
+);
 
-# ----------------------------------------------------------------------
-sub name {
-
-=pod
+around match_type => \&ex2err;
 
 =head2 name
 
@@ -285,15 +242,24 @@ Get or set the constraint's name.
 
 =cut
 
-    my $self = shift;
-    $self->{'name'} = shift if @_;
-    return $self->{'name'} || '';
-}
+has name => ( is => 'rw', default => quote_sub(q{ '' }) );
 
-# ----------------------------------------------------------------------
-sub on_delete {
+around name => sub {
+    my ($orig, $self, $arg) = @_;
+    $self->$orig($arg || ());
+};
 
-=pod
+=head2 options
+
+Gets or adds to the constraints's options (e.g., "INITIALLY IMMEDIATE").
+Returns an array or array reference.
+
+  $constraint->options('NORELY');
+  my @options = $constraint->options;
+
+=cut
+
+with ListAttr options => ();
 
 =head2 on_delete
 
@@ -303,20 +269,12 @@ Get or set the constraint's "on delete" action.
 
 =cut
 
-    my $self = shift;
-    
-    if ( my $arg = shift ) {
-        # validate $arg?
-        $self->{'on_delete'} = $arg;
-    }
-
-    return $self->{'on_delete'} || '';
-}
-
-# ----------------------------------------------------------------------
-sub on_update {
+has on_delete => ( is => 'rw', default => quote_sub(q{ '' }) );
 
-=pod
+around on_delete => sub {
+    my ($orig, $self, $arg) = @_;
+    $self->$orig($arg || ());
+};
 
 =head2 on_update
 
@@ -326,20 +284,12 @@ Get or set the constraint's "on update" action.
 
 =cut
 
-    my $self = shift;
-    
-    if ( my $arg = shift ) {
-        # validate $arg?
-        $self->{'on_update'} = $arg;
-    }
-
-    return $self->{'on_update'} || '';
-}
-
-# ----------------------------------------------------------------------
-sub reference_fields {
+has on_update => ( is => 'rw', default => quote_sub(q{ '' }) );
 
-=pod
+around on_update => sub {
+    my ($orig, $self, $arg) = @_;
+    $self->$orig($arg || ());
+};
 
 =head2 reference_fields
 
@@ -356,47 +306,33 @@ arrayref; returns an array or array reference.
 
 =cut
 
-    my $self   = shift;
-    my $fields = parse_list_arg( @_ );
+with ListAttr reference_fields => (
+    may_throw => 1,
+    builder => 1,
+    lazy => 1,
+);
 
-    if ( @$fields ) {
-        $self->{'reference_fields'} = $fields;
-    }
+sub _build_reference_fields {
+    my ($self) = @_;
 
-    unless ( ref $self->{'reference_fields'} ) {
-        my $table          = $self->table or return $self->error('No table');
-        my $schema         = $table->schema or return $self->error('No schema');
-        my $ref_table_name = $self->reference_table or 
-            return $self->error('No table');
-        my $ref_table      = $schema->get_table( $ref_table_name ) or
-            return $self->error("Can't find table '$ref_table_name'");
+    my $table   = $self->table   or throw('No table');
+    my $schema  = $table->schema or throw('No schema');
+    if ( my $ref_table_name = $self->reference_table ) {
+        my $ref_table  = $schema->get_table( $ref_table_name ) or
+            throw("Can't find table '$ref_table_name'");
 
-        if ( my $constraint = $ref_table->primary_key ) { 
-            $self->{'reference_fields'} = [ $constraint->fields ];
+        if ( my $constraint = $ref_table->primary_key ) {
+            return [ $constraint->fields ];
         }
         else {
-            $self->error(
+            throw(
                 'No reference fields defined and cannot find primary key in ',
                 "reference table '$ref_table_name'"
             );
         }
     }
-
-    if ( ref $self->{'reference_fields'} ) {
-        return wantarray 
-            ?  @{ $self->{'reference_fields'} || [] } 
-            :     $self->{'reference_fields'};
-    }
-    else {
-        return wantarray ? () : [];
-    }
 }
 
-# ----------------------------------------------------------------------
-sub reference_table {
-
-=pod
-
 =head2 reference_table
 
 Get or set the table referred to by the constraint.
@@ -405,16 +341,19 @@ Get or set the table referred to by the constraint.
 
 =cut
 
-    my $self = shift;
-    $self->{'reference_table'} = shift if @_;
-    return $self->{'reference_table'} || '';
-}
+has reference_table => ( is => 'rw', default => quote_sub(q{ '' }) );
+
+=head2 table
 
+Get or set the constraint's table object.
 
-# ----------------------------------------------------------------------
-sub type {
+  my $table = $field->table;
 
-=pod
+=cut
+
+has table => ( is => 'rw', isa => schema_obj('Table'), weak_ref => 1 );
+
+around table => \&ex2err;
 
 =head2 type
 
@@ -424,83 +363,89 @@ Get or set the constraint's type.
 
 =cut
 
-    my $self = shift;
+has type => (
+    is => 'rw',
+    default => quote_sub(q{ '' }),
+    coerce => quote_sub(q{ (my $t = $_[0]) =~ s/_/ /g; uc $t }),
+    isa => enum([keys %VALID_CONSTRAINT_TYPE], {
+        msg => "Invalid constraint type: %s", allow_false => 1,
+    }),
+);
 
-    if ( my $type = shift ) {
-        return $self->error("Invalid constraint type: $type") 
-            unless VALID_TYPE->{ $type };
-        $self->{'type'} = $type;
-    }
-
-    return $self->{'type'} || '';
-}
+around type => \&ex2err;
 
+=head2 equals
 
-# ----------------------------------------------------------------------
-sub table {
+Determines if this constraint is the same as another
 
-=pod
-
-=head2 table
-
-Get or set the field's table object.
-
-  my $table = $field->table;
+  my $isIdentical = $constraint1->equals( $constraint2 );
 
 =cut
 
+around equals => sub {
+    my $orig = shift;
     my $self = shift;
-    if ( my $arg = shift ) {
-        return $self->error('Not a table object') unless
-            UNIVERSAL::isa( $arg, 'SQL::Translator::Schema::Table' );
-        $self->{'table'} = $arg;
+    my $other = shift;
+    my $case_insensitive = shift;
+    my $ignore_constraint_names = shift;
+
+    return 0 unless $self->$orig($other);
+    return 0 unless $self->type eq $other->type;
+    unless ($ignore_constraint_names) {
+        return 0 unless $case_insensitive ? uc($self->name) eq uc($other->name) : $self->name eq $other->name;
     }
-
-    return $self->{'table'};
-}
-
-# ----------------------------------------------------------------------
-sub options {
-
-=pod
-
-=head2 options
-
-Gets or adds to the constraints's options (e.g., "INITIALLY IMMEDIATE").  
-Returns an array or array reference.
-
-  $constraint->options('NORELY');
-  my @options = $constraint->options;
-
-=cut
-
-    my $self    = shift;
-    my $options = parse_list_arg( @_ );
-
-    push @{ $self->{'options'} }, @$options;
-
-    if ( ref $self->{'options'} ) {
-        return wantarray ? @{ $self->{'options'} || [] } : $self->{'options'};
+    return 0 unless $self->deferrable eq $other->deferrable;
+    #return 0 unless $self->is_valid eq $other->is_valid;
+    return 0 unless $case_insensitive ? uc($self->table->name) eq uc($other->table->name)
+      : $self->table->name eq $other->table->name;
+    return 0 unless $self->expression eq $other->expression;
+
+    # Check fields, regardless of order
+    my %otherFields = ();  # create a hash of the other fields
+    foreach my $otherField ($other->fields) {
+      $otherField = uc($otherField) if $case_insensitive;
+      $otherFields{$otherField} = 1;
     }
-    else {
-        return wantarray ? () : [];
+    foreach my $selfField ($self->fields) { # check for self fields in hash
+      $selfField = uc($selfField) if $case_insensitive;
+      return 0 unless $otherFields{$selfField};
+      delete $otherFields{$selfField};
     }
-}
+    # Check all other fields were accounted for
+    return 0 unless keys %otherFields == 0;
+
+    # Check reference fields, regardless of order
+    my %otherRefFields = ();  # create a hash of the other reference fields
+    foreach my $otherRefField ($other->reference_fields) {
+      $otherRefField = uc($otherRefField) if $case_insensitive;
+      $otherRefFields{$otherRefField} = 1;
+    }
+    foreach my $selfRefField ($self->reference_fields) { # check for self reference fields in hash
+      $selfRefField = uc($selfRefField) if $case_insensitive;
+      return 0 unless $otherRefFields{$selfRefField};
+      delete $otherRefFields{$selfRefField};
+    }
+    # Check all other reference fields were accounted for
+    return 0 unless keys %otherRefFields == 0;
+
+    return 0 unless $case_insensitive ? uc($self->reference_table) eq uc($other->reference_table) : $self->reference_table eq $other->reference_table;
+    return 0 unless $self->match_type eq $other->match_type;
+    return 0 unless $self->on_delete eq $other->on_delete;
+    return 0 unless $self->on_update eq $other->on_update;
+    return 0 unless $self->_compare_objects(scalar $self->options, scalar $other->options);
+    return 0 unless $self->_compare_objects(scalar $self->extra, scalar $other->extra);
+    return 1;
+};
 
-# ----------------------------------------------------------------------
-sub DESTROY {
-    my $self = shift;
-    undef $self->{'table'}; # destroy cyclical reference
-}
+# Must come after all 'has' declarations
+around new => \&ex2err;
 
 1;
 
-# ----------------------------------------------------------------------
-
 =pod
 
 =head1 AUTHOR
 
-Ken Y. Clark E<lt>kclark@cpan.orgE<gt>
+Ken Youens-Clark E<lt>kclark@cpan.orgE<gt>.
 
 =cut