CREATE VIEW queryCurrentActiveVersions as
SELECT DISTINCT
        av.queryId,
        (FIRST_VALUE(av.versionId) OVER (PARTITION BY av.queryId ORDER BY av.id DESC))::int as id
    FROM queryActiveVersions as av;

CREATE VIEW queryLatestVersions as
    SELECT queryId, max(id)::int as id
        FROM queryVersions
        GROUP BY queryId;

CREATE VIEW fullActiveQueries AS
with config as (
SELECT c.queryId, c.config
    FROM queries AS q
    LEFT JOIN queryCurrentActiveVersions as av on q.id = av.queryId
    LEFT JOIN queryConfigs AS c ON q.id = c.queryId
        and isInVersion(av.id, c.addedVersion, c.removedVersion)
),
requiredIds as (
    SELECT r.queryId,
        ARRAY_AGG(DISTINCT r.requiredQueryId)
        FILTER (WHERE r.requiredQueryId != '00000000-0000-0000-0000-000000000000')::uuid[]
        as requiredIds
    FROM queries AS q
    LEFT JOIN queryCurrentActiveVersions as av on q.id = av.queryId
    LEFT JOIN requiredQueries AS r ON q.id = r.queryId
        and isInVersion(av.id, r.addedVersion, r.removedVersion)
    GROUP BY r.queryId
)
SELECT DISTINCT q.id, q.type, coalesce(av.id, 0) as activeVersion, coalesce(lv.id, 0) as latestVersion, c.config,
    coalesce(
        r.requiredIds,
        array[]::uuid[]
    )::uuid[] as requiredIds
    FROM queries AS q
    LEFT JOIN queryCurrentActiveVersions as av on q.id = av.queryId
    LEFT JOIN queryLatestVersions as lv on lv.queryId = q.id
    LEFT JOIN config AS c ON q.id = c.queryId
    LEFT JOIN requiredIds AS r ON q.id = r.queryId;

CREATE VIEW queryActiveDependencies AS
    with recursive queryActiveDependencies AS (
        SELECT q.id, r.requiredQueryId
        FROM queries AS q
        LEFT JOIN queryCurrentActiveVersions as av on q.id = av.queryId
        LEFT JOIN requiredQueries AS r ON q.id = r.queryId
            and isInVersion(av.id, r.addedVersion, r.removedVersion)

        UNION ALL

        SELECT qd.id, r.requiredQueryId
        FROM queries AS q
        LEFT JOIN queryCurrentActiveVersions as av on q.id = av.queryId
        LEFT JOIN requiredQueries AS r ON q.id = r.queryId
            and isInVersion(av.id, r.addedVersion, r.removedVersion)
        JOIN queryActiveDependencies as qd on q.id = qd.requiredQueryId
    )
    SELECT DISTINCT id, requiredQueryId FROM queryActiveDependencies;