package Index;

use strict;
use XML;

use FieldRef;

use methods;

use members scalar => [ 'name',
			'title',
			'old',
			'unique',
			'fulltext'],
	      text => 'description' ,
	      list => 'fields:FieldRef';

sub sql_create {
	my ($this, $table) = @_;
	my $ret = "create";
	$ret .= " unique" if $this->unique;
	$ret .= " fulltext" if $this->fulltext;
	$ret .= qq{ index $Table::QUOTE$this->{name}$Table::QUOTE on $Table::QUOTE$table->{name}$Table::QUOTE (\n\t};
	$ret .= join ",\n\t", $this->recurse;
	$ret .= " )";
	return $ret;
}

sub sql_drop {
	my ($this, $table) = @_;
	return qq{drop index $Table::QUOTE$this->{name}$Table::QUOTE on $Table::QUOTE$table->{name}$Table::QUOTE};
}

sub sql_alter {
	my ($old, $diff, $new, $table) = @_;
	return $old->sql_drop($table),
	       $new->sql_create($table);
}

sub sql_rename {
	my ($this, $new_name, $table) = @_;
	my $old_name = $this->name;
	my @commands;
	push @commands, $this->sql_drop($table);
	$this->name($new_name);
	push @commands, $this->sql_create($table);
	$this->name($old_name);
	return @commands;
}

sub sql_parse {
	my ($this, $sql) = @_;
	$this = $this->new unless ref $this;
	while (1) {
		$$sql =~ s/^\s+//s;
		return if $$sql eq '';
		if ($$sql =~ s/^"?(\w+)"?(?:\s*\(([\d,\s]+)\))?(?:\s"?\w*"?)?//si) {
			my $name = $1;
			my $size = $2;
			my $field;
#			if ($size eq '') {
#				$field = FieldRef->new(name => $name);
#			} else {
				$field = FieldRef->new(name => $name, size => $size);
#			}
			$this->add_field($field);
			last unless $$sql =~ s/^\s*,//;
		} else {
			last;
		}
	}
	return $this;
}

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

1
