Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

1.7 KB
Raw Blame
import { parseSelect } from './hogqlParserSingleton'
import { SELECTION_LABEL, SaveCandidates } from './SaveTargetCycler'

export const SELECTION_NOT_A_QUERY =
    'The selected text is not a complete query. Close this dialog and clear the selection in the editor, then save again.'

/**
 * Report why the chosen save candidate cannot be saved, or null when it is fine.
 *
 * Only a selection is judged. It is the one candidate a person does not mean to choose: a
 * double-click leaves a single identifier highlighted, and that then wins over the whole editor
 * contents. Clearing the selection is always a way forward, so a wrong verdict here cannot trap
 * anyone. The whole editor contents are left to the API, whose parser is the one that decides.
 *
 * Fails open. When the parser is unavailable we cannot tell a broken query from an unchecked one.
 * Raw connection mode is skipped for the same reason: the text goes to the connection's own engine
 * in its own dialect, so a HogQL parse of it would refuse valid SQL.
 */
export async function findSelectionProblem(
    candidates: SaveCandidates,
    sendRawQueryEnabled: boolean
): Promise<string | null> {
    if (sendRawQueryEnabled || candidates.selectionLabel !== SELECTION_LABEL) {
        return null
    }
    const selected = candidates.queries[candidates.initialIndex] ?? ''
    return (await isParsable(selected)) ? null : SELECTION_NOT_A_QUERY
}

async function isParsable(query: string): Promise<boolean> {
    try {
        // parseSelect reports a syntax error inside its result rather than rejecting, so a
        // rejection here means the parser itself failed to load.
        const parsed = JSON.parse(await parseSelect(query))
        return parsed?.error !== true
    } catch {
        return true
    }
}