     RETURNS text
 AS $$
     SELECT datasource.name || '_' || entitytype.name || '_' || trend.granularity_to_text($1.granularity)
-        FROM directory.datasource, directory.entitytype
-        WHERE datasource.id = $1.datasource_id AND entitytype.id = $1.entitytype_id;
+    FROM directory.datasource, directory.entitytype
+    WHERE datasource.id = $1.datasource_id AND entitytype.id = $1.entitytype_id;
 $$ LANGUAGE SQL STABLE STRICT;
 
 

CREATE FUNCTION trend.update_modified(trendstore_id integer, "timestamp" timestamp with time zone, modified timestamp with time zone)
    RETURNS trend.modified
AS $$
    UPDATE trend.modified SET "end" = greatest("end", $3) WHERE "timestamp" = $2 AND trendstore_id = $1 RETURNING modified;
$$ LANGUAGE SQL VOLATILE;


CREATE FUNCTION trend.store_modified(trendstore_id integer, "timestamp" timestamp with time zone, modified timestamp with time zone)
    RETURNS trend.modified
AS $$
    INSERT INTO trend.modified (trendstore_id, "timestamp", start, "end") VALUES ($1, $2, $3, $3) RETURNING modified;
$$ LANGUAGE SQL VOLATILE;


CREATE FUNCTION trend.mark_modified(trendstore_id integer, "timestamp" timestamp with time zone, modified timestamp with time zone)
    RETURNS trend.modified
AS $$
    SELECT COALESCE(trend.update_modified($1, $2, $3), trend.store_modified($1, $2, $3));
$$ LANGUAGE SQL VOLATILE;


CREATE FUNCTION trend.mark_modified(trendstore_id integer, "timestamp" timestamp with time zone)
    RETURNS trend.modified
AS $$
    SELECT COALESCE(trend.update_modified($1, $2, now()), trend.store_modified($1, $2, now()));
$$ LANGUAGE SQL VOLATILE;



CREATE FUNCTION trend.get_partition(trendstore trend.trendstore, index integer)
    RETURNS trend.partition
AS $$
    SELECT partition
    FROM trend.partition
    WHERE trendstore_id = $1.id AND table_name = trend.partition_name($1, $2);
$$ LANGUAGE SQL STABLE;


CREATE FUNCTION trend.create_partition(trendstore trend.trendstore, index integer)
    RETURNS trend.partition
AS $$
    INSERT INTO trend.partition(
        table_name,
        trendstore_id,
        data_start,
        data_end
    )
    VALUES (
        trend.partition_name($1, $2),
        $1.id,
        trend.index_to_timestamp($1.partition_size, $2),
        trend.index_to_timestamp($1.partition_size, $2 + 1)
    )
    RETURNING partition;
$$ LANGUAGE SQL VOLATILE;


