 $$ LANGUAGE SQL STABLE;
 
 
-CREATE FUNCTION trend.infer_trendstore_type(trend.trendstore)
-    RETURNS trend.storetype
-AS $$
-    SELECT
-        CASE relkind
-            WHEN 'r' THEN 'table'::trend.storetype
-            WHEN 'v' THEN 'view'::trend.storetype
-            ELSE NULL
-        END
-    FROM pg_class
-    WHERE relname = trend.to_base_table_name($1);
-$$ LANGUAGE SQL STABLE;
-
-
 CREATE FUNCTION trend.get_column_names(table_name character varying)
     RETURNS character varying[]
 AS $$
-    SELECT array_agg(format('%I', a.attname)::character varying) FROM pg_class c
-        JOIN pg_attribute a ON a.attrelid = c.oid
+    SELECT
+        array_agg(format('%I', a.attname)::character varying)
+    FROM pg_class c
+    JOIN pg_attribute a ON a.attrelid = c.oid
     WHERE c.relname = $1 AND a.attnum >= 0 AND NOT a.attisdropped;
 $$ LANGUAGE SQL STABLE;
 

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;


