CREATE TABLE service.task_schedule (
    id bigserial PRIMARY KEY,
    name text NOT NULL,
    cron_task_name text NOT NULL UNIQUE,
    created_at timestamp with time zone NOT NULL DEFAULT now(),
    created_by bigint NOT NULL CHECK (created_by > 0),
    cron_expr text NOT NULL,
    task_type text NOT NULL,
    task_params hstore NOT NULL
);

CREATE UNIQUE INDEX task_schedule_created_by_name_idx
    ON service.task_schedule
    USING btree (created_by, name);

CREATE OR REPLACE FUNCTION task_schedule_insert_trigger() RETURNS trigger AS $$
BEGIN
    NEW.cron_task_name := 'tasks_' || NEW.task_type || '_' || NEW.created_by || '_' || NEW.id;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER task_schedule_insert_trigger
    BEFORE INSERT
    ON service.task_schedule
    FOR EACH ROW
    EXECUTE PROCEDURE task_schedule_insert_trigger();