CREATE OR REPLACE FUNCTION plperlswish(text, text, text, text, text) RETURNS boolean AS '
	my ($table, $index_path, $query, $properties, $sort) = @_;

	if (! -e $index_path) {
		elog ERROR,"can\'t find swish-e index $index_path";
		return;
	}

	if (! -e $index_path) {
		elog ERROR,"swish-e index $index_path exists, but is not readable";
		return;
	}

	use DBD::PgSPI;
	use SWISH::API;

	$pg_dbh->do("CREATE temporary TABLE $table (
		rank int,
		path text,
		headline text,
		size int,
		properties text[],
		primary key(path)
	)
	");

	my $swish = SWISH::API->new( $index_path );
	$swish->AbortLastError if $swish->Error;

	my $results = $swish->Query( $query );
	$swish->AbortLastError if $swish->Error;

	my $sth = $pg_dbh->prepare("insert into $table values (?, ?, ?, ?, ?)") || die $sth->errstr;

	while ( my $result = $results->NextResult ) {
		my @data = (
			$result->Property( "swishrank" ),
			$result->Property( "swishdocpath" ),
			$result->Property( "swishtitle" ),
			$result->Property( "swishdocsize" ),
		);

		my @props;

		foreach my $p (split(/\s+/,$properties)) {
			push @props, $result->Property( $p );
		}

		push @data, "{\'".join("\',\'", @props)."\'}";

		$sth->execute(@data) || die $sth->errstr;
	}

	return true;
' LANGUAGE plperlu;

drop type __swish_results cascade;
create type __swish_results as (
		rank int,
		path text,
		headline text,
		size int,
		properties text[]
);

create or replace function swish(text,text,text,text) returns setof __swish_results as '
declare
	row record;
begin
	execute ''select plperlswish(''''swish_results'''',
		''''''||$1||'''''',
		''''''||$2||'''''',
		''''''||$3||'''''',
		''''''||$4||'''''') '' ;

	for row in execute ''select * from swish_results'' loop
		return next row;
	end loop;
	execute ''drop table swish_results'' ;
	return;
end;
' language 'plpgsql';
