-- name: GetQueryConfig :one
SELECT id, config FROM queryConfigs where queryId = $1 and addedVersion >= $2 and COALESCE(removedVersion, $2 - 1) < $2;

-- name: GetQuery :one
SELECT * FROM fullActiveQueries WHERE id = $1;

-- name: ListQueries :many
SELECT * FROM fullActiveQueries;

-- name: CreateQuery :one
INSERT INTO queries (type) VALUES ($1) RETURNING id;

-- name: UpdateQuery :exec
UPDATE queries SET activeVersion = $1, latestVersion = $2 WHERE id = $3;

-- name: AddRequiredQuery :exec
INSERT INTO requiredQueries (queryId, requiredQueryId, addedVersion) VALUES ($1, $2, $3);

-- name: RemoveRequiredQuery :exec
UPDATE requiredQueries SET removedVersion = $1 WHERE requiredQueryId = $2 and queryId = $3 and removedVersion is null;

-- name: AddQueryConfig :exec
INSERT INTO queryConfigs (queryId, config, addedVersion) VALUES ($1, $2, $3);

-- name: RemoveQueryConfig :exec
UPDATE queryConfigs SET removedVersion = $1 WHERE queryId = $2 and removedVersion is null;

-- name: AllQueriesExist :one
SELECT COUNT(*) = COUNT(DISTINCT id) AS all_exist
    FROM unnest($1::uuid[]) AS input_id
    LEFT JOIN queries ON input_id = queries.id;

-- name: IsQueryInDependencyTree :one
SELECT EXISTS (
    SELECT 1 FROM queryActiveDependencies WHERE id = any($1) and requiredQueryId = $2 or $2 = any($1)
);