package Constraint;

use strict;
use XML;

use methods;
use Message;
use Field; # for $type_pattern

use members ( scalar => [ 'name',
			  'title',
			  'old',
			  'check' ],
	        text => 'description' );

sub sql_create {
	my ($this) = @_;
	return qq{constraint $this->{name} check ($this->{check})};
}

sub sql_drop {
	my ($this) = @_;
	die "I don't know how to remove a constraint!";
}

# XXX this $type_pattern is duplicated in Field.pm
my $type_pattern = 'character varying|time(?:stamp)? with(?:out)? time zone|double precision|[a-z0-9]+';
sub sql_parse {
	my ($this, $sql) = @_;
	$this = $this->new() unless ref $this;
	$$sql =~ s/^\s+//s;
	# TODO - balance brackets in constraints!

	if ($$sql =~ s/^check\s+\(([^\n]*?)\)(?=,|\n|\);)//si) {
		my $check = $1;
		# remove PostgreSQL's bogus ::type stuff:
		$check =~ s/\(([^()]*)\)::($type_pattern)/$1/gso;
		1 while $check =~ s/^\((.*?)\)$/$1/;
		$this->check($check);
	} else {
		print substr $$sql, 0, 100;
		die "parse error: constraint has no check";	
	}
	# TODO: parse grants - a little weird as they might occur anywhere!
	return $this;
}

sub realize {
	my ($this) = @_;
	$this->$_(undef) for qw(description title);
	$this->recurse();
}

1
