#------------------------------------------------------------------------------
#$Author: andrius $
#$Date: 2020-01-20 11:14:58 -0500 (Mon, 20 Jan 2020) $ 
#$Revision: 5710 $
#$URL: svn://saulius-grazulis.lt/restful/tags/v0.15.2/lib/Database/ForeignKey.pm $
#------------------------------------------------------------------------------
#*
#  An object to encapsulate a foreign key in a database.
#**

package Database::ForeignKey;
use strict;
use warnings;

#=======================================================================
# Constructors

sub new
{
    my( $class, $self ) = @_;

    $self->{relation} = 'N' unless $self->{relation};
    $self->{visualisation} = 'table' unless $self->{visualisation};

    return bless $self, $class;
}

#=======================================================================
# Methods

sub child_table
{
    return $_[0]->{table_from};
}

sub parent_table
{
    return $_[0]->{table_to};
}

sub child_columns
{
    return @{$_[0]->{column_from}};
}

sub child_column
{
    my( $self ) = @_;
    warn 'child_column() called on composite key' if $self->is_composite;
    return $_[0]->{column_from}[0];
}

sub parent_columns
{
    return @{$_[0]->{column_to}};
}

sub parent_column
{
    my( $self ) = @_;
    warn 'parent_column() called on composite key' if $self->is_composite;
    return $_[0]->{column_to}[0];
}

# Number of columns of a key (1 for all non-composite keys)
sub size
{
    return scalar $_[0]->child_columns;
}

sub is_composite
{
    return $_[0]->size != 1;
}

sub is_visualised
{
    return !$_[0]->{visualisation} || $_[0]->{visualisation} ne 'none';
}

sub compound_name
{
    my( $self ) = @_;
    die 'compound_name() called on a composite key' if $self->is_composite;
    return $self->parent_table . '.' . $self->parent_column;
}

sub name
{
    return $_[0]->{name};
}

sub query_string
{
    my( $self, $data, $prefix ) = @_;
    $prefix = '' unless $prefix;

    return join '&',
           map { $prefix . $self->{column_from}[$_] . '=' .
                 $data->{columns}{$self->{column_to}[$_]}{value} }
               0..($self->size-1);
}

sub to_string
{
    my( $self ) = @_;
    return sprintf "FK '%s': '%s' (%s) -> '%s' (%s)",
                   $self->name,
                   $self->child_table,
                   join( ',', map { "'$_'" } $self->child_columns ),
                   $self->parent_table,
                   join( ',', map { "'$_'" } $self->parent_columns );
}

1;
