BEGIN;

-- test_tasks_status_enum
CREATE TABLE  test_tasks_status_enum(
    id INTEGER PRIMARY KEY,
    value VARCHAR(15)
);

INSERT INTO test_tasks_status_enum (id, value)
VALUES
    (1, 'created'),
    (2, 'started'),
    (3, 'completed'),
    (4, 'failed');


-- test_tasks
CREATE TABLE test_tasks (
    id INTEGER PRIMARY KEY,
    build_task_id INTEGER REFERENCES build_tasks(id) ON DELETE CASCADE,
    revision INTEGER,
    status_id INTEGER REFERENCES test_tasks_status_enum(id) ON DELETE SET NULL,
    package_fullname VARCHAR(100),
    started_at DOUBLE PRECISION
);

CREATE INDEX test_tasks_build_task_id
ON test_tasks(build_task_id);

CREATE INDEX test_tasks_build_status_id
ON test_tasks(status_id);

CREATE INDEX test_tasks_package_fullname
ON test_tasks(package_fullname);


-- test_steps_enum
CREATE TABLE test_steps_enum (
    id INTEGER PRIMARY KEY,
    value VARCHAR(50)
);

INSERT INTO test_steps_enum (id, value)
VALUES
    (0, 'install_package'),
    (1, 'stop_environment'),
    (2, 'initial_provision'),
    (3, 'start_environment'),
    (4, 'uninstall_package'),
    (5, 'initialize_terraform'),
    (6, 'package_integrity_tests'),
    (7, 'stop_environment');



-- test_steps_stats
CREATE TABLE test_steps_stats(
    test_task_id INTEGER REFERENCES test_tasks(id) ON DELETE CASCADE,
    stat_name_id  INTEGER REFERENCES test_steps_enum(id) ON DELETE SET NULL,
    start_ts DOUBLE PRECISION,
    finish_ts DOUBLE PRECISION
);

ALTER TABLE test_steps_stats
ADD CONSTRAINT test_steps_stats_unique UNIQUE (test_task_id, stat_name_id);

CREATE INDEX test_steps_stats_start_ts
ON test_steps_stats(start_ts);

CREATE INDEX test_steps_stats_end_ts
ON test_steps_stats(finish_ts);

-- increasing size of name field
ALTER TABLE build_tasks ALTER COLUMN name TYPE varchar(150);


UPDATE schema_version
SET version = 3;

COMMIT;