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.

feat(terminal): add hogql query command and interactive prompt (#106313)

Marius Andra2a698ccd21f4
diff --git a/docs/published/handbook/engineering/project-structure.md b/docs/published/handbook/engineering/project-structure.md
index cdf42784bc3f..fc366ef1e5db 100644
--- a/docs/published/handbook/engineering/project-structure.md
+++ b/docs/published/handbook/engineering/project-structure.md
@@ -51,7 +51,10 @@ The app-level terminal lives in `src/scenes/terminal`.
SQL insights appear as editable `.sql` files; their full JSON remains editable under `/posthog/api/insight`.
Saving SQL preserves the insight's other query options, and JSON saves send only changed fields through the existing APIs.
`run report.sql` executes a SQL file in the current project and prints a Markdown table; `--json`, `--csv`, and `--tsv` select export formats.
+`hogql "select 1"` executes SQL directly, `echo "select 1" | hogql` reads a query from stdin, and `hogql` opens an interactive prompt that executes one query per line.
+`hogql --help` lists output formats, `--connection-id`, JSON query options, and additional fields supplied with `--field name=JSON`.
CSV and TSV exports escape text that spreadsheets could interpret as formulas.
+Query warnings go to stderr without changing exported tables. Ctrl+C cancels a running query.
Use `--json` to inspect result metadata, including `hasMore`, and `/tmp` for export files.
The interactive Bash shell completes `ph` command names, aliases, connected tools, and argument names with Tab.
The terminal follows the current resource's folder while its prompt is empty.
diff --git a/frontend/src/scenes/terminal/posthogCommands.test.ts b/frontend/src/scenes/terminal/posthogCommands.test.ts
index 5936521c1062..1f5f147b4cfc 100644
--- a/frontend/src/scenes/terminal/posthogCommands.test.ts
+++ b/frontend/src/scenes/terminal/posthogCommands.test.ts
@@ -1,5 +1,8 @@
import { waitFor } from '@testing-library/react'
+import { ApiRequest } from 'lib/api'
+import { teamLogic } from 'scenes/teamLogic'
+
import { fileSystemList } from '~/generated/core/api'
import type { FileSystemApi } from '~/generated/core/api.schemas'
import { performQuery } from '~/queries/query'
@@ -57,22 +60,181 @@ describe('PostHog terminal commands', () => {
['--markdown', '| answer |\n| --- |\n| 42 |'],
['--csv', 'answer\n42'],
['--tsv', 'answer\n42'],
- ['--json', { columns: ['answer'], results: [[42]], types: ['Int64'], hasMore: true }],
- ])('runs local SQL with %s output', async (format, expected) => {
+ [
+ '--json',
+ {
+ columns: ['answer'],
+ results: [[42]],
+ types: ['Int64'],
+ hasMore: true,
+ warnings: [{ type: 'access_control', resources: ['insight'], message: 'Some insights are excluded.' }],
+ },
+ ],
+ ])('runs SQL from files and hogql with %s output', async (format, expected) => {
jest.mocked(performQuery).mockResolvedValue({
columns: ['answer'],
results: [[42]],
types: ['Int64'],
hasMore: true,
+ warnings: [{ type: 'access_control', resources: ['insight'], message: 'Some insights are excluded.' }],
})
- expect(await commands.execute(['run', '/tmp/report.sql', 'select 42 as answer', format], cwd)).toEqual(expected)
+ const onWarning = jest.fn()
+ expect(
+ await commands.execute(['run', '/tmp/report.sql', 'select 42 as answer', format], cwd, { onWarning })
+ ).toEqual(expected)
+ expect(
+ await commands.execute(
+ ['hogql', '--json', JSON.stringify({ query: 'select 42 as answer', argv: [format] })],
+ cwd,
+ { onWarning }
+ )
+ ).toEqual(expected)
+ expect(onWarning.mock.calls).toEqual([['Some insights are excluded.'], ['Some insights are excluded.']])
expect(performQuery).toHaveBeenCalledWith(
expect.objectContaining({ kind: 'HogQLQuery', query: 'select 42 as answer' }),
expect.objectContaining({ signal: expect.any(AbortSignal) }),
- 'force_blocking'
+ 'force_blocking',
+ expect.any(String)
)
})
+ it.each(['--markdown', '--csv', '--tsv'])(
+ 'fails hogql %s output when a debug query returns an error',
+ async (format) => {
+ jest.mocked(performQuery).mockResolvedValue({ columns: [], results: [], error: 'Unknown table missing' })
+ const request = { query: 'select * from missing', argv: [format, '--modifiers', '{"debug":true}'] }
+ await expect(commands.execute(['hogql', '--json', JSON.stringify(request)], cwd)).rejects.toThrow(
+ 'Unknown table missing'
+ )
+ }
+ )
+
+ it('passes connection options and JSON fields without changing the SQL or losing response metadata', async () => {
+ const result = {
+ columns: ['answer'],
+ results: [[42]],
+ hasMore: false,
+ explain: ['Query plan'],
+ timings: { total: 1 },
+ }
+ jest.mocked(performQuery).mockResolvedValue(result)
+ const query = 'select {value} as answer'
+ const argv = [
+ '--connection-id',
+ 'example-connection',
+ '--raw',
+ '--name',
+ 'Example query',
+ '--values',
+ '{"value":42}',
+ '--filters',
+ '{"dateRange":{"date_from":"-7d"}}',
+ '--variables',
+ '{}',
+ '--modifiers',
+ '{"timings":true}',
+ '--field',
+ 'explain=true',
+ '--json',
+ ]
+ expect(await commands.execute(['hogql', '--json', JSON.stringify({ query, argv })], cwd)).toEqual(result)
+ expect(performQuery).toHaveBeenCalledWith(
+ {
+ kind: 'HogQLQuery',
+ query,
+ connectionId: 'example-connection',
+ sendRawQuery: true,
+ name: 'Example query',
+ values: { value: 42 },
+ filters: { dateRange: { date_from: '-7d' } },
+ variables: {},
+ modifiers: { timings: true },
+ explain: true,
+ tags: { productKey: 'sql_editor', scene: 'Terminal' },
+ },
+ expect.objectContaining({ signal: expect.any(AbortSignal) }),
+ 'force_blocking',
+ expect.any(String)
+ )
+ })
+
+ it.each([
+ ['', [], 'query is empty'],
+ ['select 1', ['--json', '--csv'], 'Choose one output format'],
+ ['select 1', ['--connection-id'], 'Missing value'],
+ ['select 1', ['--values', '{'], 'Invalid JSON'],
+ ['select 1', ['--filters', '[]'], 'requires a JSON object'],
+ ['select 1', ['--field', 'kind="HogQuery"'], 'other than kind or query'],
+ ['select 1', ['--field', 'query="select 2"'], 'other than kind or query'],
+ ['select 1', ['--raw'], 'Raw SQL requires --connection-id'],
+ ['select 1', ['--field', 'sendRawQuery=true'], 'Raw SQL requires --connection-id'],
+ ['select 1', ['--unknown'], 'Unknown option'],
+ ])('rejects invalid hogql input %j %j before executing a query', async (query, argv, message) => {
+ await expect(commands.execute(['hogql', '--json', JSON.stringify({ query, argv })], cwd)).rejects.toThrow(
+ message
+ )
+ expect(performQuery).not.toHaveBeenCalled()
+ })
+
+ it.each(['stopped', 'changed project'])('blocks hogql after the terminal has %s', async (state) => {
+ const controller = new AbortController()
+ commands = new PosthogCommands('42', controller.signal, filesystem, navigate)
+ if (state === 'stopped') {
+ controller.abort()
+ } else {
+ teamLogic.values.currentTeamId = 43
+ }
+ try {
+ await expect(
+ commands.execute(['hogql', '--json', JSON.stringify({ query: 'select 1', argv: [] })], cwd)
+ ).rejects.toThrow('current project changed')
+ expect(performQuery).not.toHaveBeenCalled()
+ } finally {
+ teamLogic.values.currentTeamId = 42
+ }
+ })
+
+ it.each(['command', 'terminal'])(
+ 'cancels the server query in its original project when the %s stops',
+ async (source) => {
+ const terminal = new AbortController()
+ const command = new AbortController()
+ commands = new PosthogCommands('42', terminal.signal, filesystem, navigate)
+ const cancel = jest.spyOn(ApiRequest.prototype, 'queryCancel')
+ const remove = jest.spyOn(ApiRequest.prototype, 'delete').mockResolvedValue(undefined)
+ let queryStarted!: () => void
+ const started = new Promise<void>((resolve) => {
+ queryStarted = resolve
+ })
+ jest.mocked(performQuery).mockImplementation(async (_query, options) => {
+ queryStarted()
+ return await new Promise((_resolve, reject) =>
+ options!.signal!.addEventListener('abort', () => reject(new Error('Query cancelled')), {
+ once: true,
+ })
+ )
+ })
+ try {
+ const result = commands
+ .execute(['hogql', '--json', JSON.stringify({ query: 'select 1', argv: [] })], cwd, {
+ signal: command.signal,
+ })
+ .catch((error: unknown) => error)
+ await started
+ const queryId = jest.mocked(performQuery).mock.calls[0][3]
+ teamLogic.values.currentTeamId = 43
+ ;(source === 'command' ? command : terminal).abort()
+ expect(await result).toEqual(new Error('Query cancelled'))
+ expect(cancel).toHaveBeenCalledWith(queryId, 42)
+ expect(remove).toHaveBeenCalledTimes(1)
+ } finally {
+ teamLogic.values.currentTeamId = 42
+ cancel.mockRestore()
+ remove.mockRestore()
+ }
+ }
+ )
+
it.each(['--csv', '--tsv'])(
'escapes spreadsheet formulas in %s exports while preserving numbers',
async (format) => {
@@ -107,6 +269,8 @@ describe('PostHog terminal commands', () => {
'--json'
)
expect(await commands.execute(['_complete', '3', '', '--json', 'notebook-create'], cwd)).toBe('')
+ expect(await commands.execute(['_complete', '2', 'hog', 'help', 'help'], cwd)).toBe('hogql')
+ expect(await commands.execute(['_complete', '2', '--con', 'hogql', 'hogql'], cwd)).toBe('--connection-id')
for (const command of ['help', 'tools', 'refresh', 'open']) {
expect(await commands.execute(['_complete', '2', '--', command, command], cwd)).toBe('')
}
diff --git a/frontend/src/scenes/terminal/posthogCommands.ts b/frontend/src/scenes/terminal/posthogCommands.ts
index 6e822fe261b1..c419e9c46106 100644
--- a/frontend/src/scenes/terminal/posthogCommands.ts
+++ b/frontend/src/scenes/terminal/posthogCommands.ts
@@ -1,8 +1,11 @@
import { z } from 'zod'
+import { ApiRequest } from 'lib/api'
+import { uuid } from 'lib/utils/dom'
import { teamLogic } from 'scenes/teamLogic'
import { performQuery } from '~/queries/query'
+import type { HogQLQuery, HogQLQueryResponse } from '~/queries/schema/schema-general'
import { dashboardsList, dashboardsRetrieve } from 'products/dashboards/frontend/generated/api'
import { featureFlagsList, featureFlagsRetrieve } from 'products/feature_flags/frontend/generated/api'
@@ -20,7 +23,8 @@ import { NotebooksPartialUpdateBody } from 'products/notebooks/frontend/generate
import { insightsList, insightsRetrieve } from 'products/product_analytics/frontend/generated/api'
import { markdownNode, PosthogFilesystem, terminalFilename } from './posthogFilesystem'
-import { RUN_HELP, TerminalCommands } from './terminalCommands'
+import { RUN_HELP, TerminalCommandContext, TerminalCommands } from './terminalCommands'
+import { HOGQL_FLAGS, HOGQL_HELP, terminalHogqlQuery } from './terminalHogql'
import { parseRemovalArguments, RM_SCRIPT } from './terminalRemove'
import { terminalQueryTable } from './terminalSql'
@@ -53,6 +57,8 @@ ph <command> --json - Read arguments from stdin
ph refresh Reload the project tree and connected tool catalog
run <file.sql> Run SQL and print a Markdown table
run --help Show SQL export formats and examples
+hogql [options] ["SQL"] Run SQL from an argument, stdin, or an interactive prompt
+hogql --help Show query options and output formats
ph open [path] Open a project file or folder in PostHog (defaults to .)
Examples:
@@ -263,7 +269,7 @@ export class PosthogCommands {
for (const tool of builtins) {
this.register(tool)
}
- new TerminalCommands(filesystem, (argv, cwd) => this.execute(argv, cwd))
+ new TerminalCommands(filesystem, (argv, cwd, context) => this.execute(argv, cwd, context))
filesystem.text('rm', filesystem.directory('bin', filesystem.root), RM_SCRIPT)
}
@@ -372,8 +378,59 @@ export class PosthogCommands {
return args
}
- async execute(argv: string[], cwd: string): Promise<unknown> {
+ private async executeQuery(query: HogQLQuery, context: TerminalCommandContext): Promise<HogQLQueryResponse> {
+ if (this.signal.aborted || context.signal?.aborted) {
+ throw new DOMException('Query cancelled', 'AbortError')
+ }
+ const controller = new AbortController()
+ const queryId = uuid()
+ const cancel = (): void => {
+ if (controller.signal.aborted) {
+ return
+ }
+ controller.abort()
+ // Aborting the HTTP request does not stop the ClickHouse query.
+ void new ApiRequest()
+ .queryCancel(queryId, Number(this.projectId))
+ .delete()
+ .catch(() => {})
+ }
+ this.signal.addEventListener('abort', cancel, { once: true })
+ context.signal?.addEventListener('abort', cancel, { once: true })
+ try {
+ return await performQuery(query, { signal: controller.signal }, 'force_blocking', queryId)
+ } finally {
+ this.signal.removeEventListener('abort', cancel)
+ context.signal?.removeEventListener('abort', cancel)
+ }
+ }
+
+ async execute(argv: string[], cwd: string, context: TerminalCommandContext = {}): Promise<unknown> {
const [name = 'help', ...rest] = argv
+ if (name === 'hogql') {
+ if (rest.length === 1 && ['--help', '-h'].includes(rest[0])) {
+ return HOGQL_HELP
+ }
+ if (rest.length !== 2 || rest[0] !== '--json') {
+ throw new Error('Use hogql "SQL" or run hogql --help for examples.')
+ }
+ const request = z
+ .object({ query: z.string(), argv: z.array(z.string()).max(1000) })
+ .strict()
+ .parse(JSON.parse(rest[1]))
+ const { query, format } = terminalHogqlQuery(request.query, request.argv)
+ if (teamLogic.values.currentTeamId !== Number(this.projectId) || this.signal.aborted) {
+ throw new Error('The current project changed. Restart the terminal before running SQL.')
+ }
+ const result = await this.executeQuery(query, context)
+ result.warnings?.forEach((warning) => context.onWarning?.(warning.message))
+ // With `explain` or `modifiers.debug`, a failed query returns `error` instead of throwing.
+ // JSON output shows that field, but a table would hide it behind an empty result.
+ if (format !== 'json' && result.error) {
+ throw new Error(result.error)
+ }
+ return format === 'json' ? result : terminalQueryTable(result, format)
+ }
if (name === '_complete') {
const [position, prefix = '', previous, commandName] = rest
if (position === '1' || (position === '2' && commandName === 'help')) {
@@ -388,6 +445,7 @@ export class PosthogCommands {
'tools',
'refresh',
'run',
+ 'hogql',
'open',
...Object.keys(aliases),
...this.commands.keys(),
@@ -402,13 +460,15 @@ export class PosthogCommands {
? []
: commandName === 'run'
? ['--help', '--markdown', '--json', '--csv', '--tsv']
- : [
- '--help',
- '--json',
- ...Object.keys(object((await this.find(commandName)).inputSchema.properties)).map(
- (key) => `--${key}`
- ),
- ]
+ : commandName === 'hogql'
+ ? HOGQL_FLAGS
+ : [
+ '--help',
+ '--json',
+ ...Object.keys(object((await this.find(commandName)).inputSchema.properties)).map(
+ (key) => `--${key}`
+ ),
+ ]
return flags
.filter((candidate) => /^[A-Za-z0-9_@/.-]+$/.test(candidate) && candidate.startsWith(prefix))
.sort()
@@ -434,13 +494,15 @@ export class PosthogCommands {
if (teamLogic.values.currentTeamId !== Number(this.projectId) || this.signal.aborted) {
throw new Error('The current project changed. Restart the terminal before running SQL.')
}
- const result = await performQuery(query, { signal: this.signal }, 'force_blocking')
+ const result = await this.executeQuery(query, context)
+ result.warnings?.forEach((warning) => context.onWarning?.(warning.message))
if (format === '--json') {
return {
columns: result.columns,
types: result.types,
results: result.results,
hasMore: result.hasMore,
+ ...(result.warnings?.length ? { warnings: result.warnings } : {}),
}
}
return terminalQueryTable(result, format === '--csv' ? 'csv' : format === '--tsv' ? 'tsv' : 'markdown')
@@ -475,6 +537,9 @@ export class PosthogCommands {
if (rest[0] === 'run') {
return RUN_HELP
}
+ if (rest[0] === 'hogql') {
+ return HOGQL_HELP
+ }
const tool = await this.find(rest[0])
const { invoke: _, ...description } = tool
return description
diff --git a/frontend/src/scenes/terminal/posthogFilesystem.ts b/frontend/src/scenes/terminal/posthogFilesystem.ts
index 798ef97f4091..e7fdca48fa1b 100644
--- a/frontend/src/scenes/terminal/posthogFilesystem.ts
+++ b/frontend/src/scenes/terminal/posthogFilesystem.ts
@@ -123,6 +123,8 @@ and Shift runs. Use Capture mouse to turn with the mouse; left-click fires.
Saving a .sql insight updates its query and preserves its query options.
Use run report.sql to execute SQL, or run --help for JSON, CSV, and TSV exports.
+Use hogql "select 1" for a query, echo "select 1" | hogql for piped SQL, or hogql
+for an interactive prompt. Run hogql --help for formats, connections, and query options.
The terminal follows the current resource's folder while its prompt is empty. Active commands and typed input stay intact.
Saving an existing .md notebook updates PostHog using your current permissions.
diff --git a/frontend/src/scenes/terminal/terminalCommands.test.ts b/frontend/src/scenes/terminal/terminalCommands.test.ts
new file mode 100644
index 000000000000..1a7356aca175
--- /dev/null
+++ b/frontend/src/scenes/terminal/terminalCommands.test.ts
@@ -0,0 +1,90 @@
+import { spawnSync } from 'child_process'
+import { mkdtempSync, rmSync, writeFileSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+
+import { PH_SCRIPT, TerminalCommands } from './terminalCommands'
+import { TerminalFilesystem } from './terminalFilesystem'
+
+describe('terminal command bridge', () => {
+ it.each(['markdown', 'csv', 'tsv', 'json'])(
+ 'prints %s warnings on stderr without changing stdout',
+ async (format) => {
+ const result =
+ format === 'json'
+ ? { columns: ['answer'], results: [[42]] }
+ : format === 'markdown'
+ ? '| answer |\n| --- |\n| 42 |'
+ : 'answer\n42'
+ const filesystem = new TerminalFilesystem()
+ new TerminalCommands(filesystem, async (_argv, _cwd, { onWarning }) => {
+ onWarning?.('Some insights are excluded.')
+ return result
+ })
+ const bridge = filesystem.root.children!.get('.ph')!.children!
+ const request = await bridge.get('request')!.open!()
+ await request.save!(new TextEncoder().encode(JSON.stringify({ argv: ['hogql'], cwd: '/tmp' })))
+ const response = (await bridge.get('response')!.open!()).bytes
+ expect(JSON.parse(new TextDecoder().decode(response))).toEqual({
+ ok: true,
+ result,
+ warnings: ['Some insights are excluded.'],
+ })
+ const directory = mkdtempSync(join(tmpdir(), 'terminal-command-'))
+ try {
+ writeFileSync(join(directory, 'response'), response)
+ const command = spawnSync(
+ 'bash',
+ [
+ '-c',
+ PH_SCRIPT.replaceAll('/posthog/.ph', directory).replace(
+ '/tmp/posthog-ph.lock',
+ join(directory, 'lock')
+ ),
+ 'ph',
+ 'help',
+ ],
+ { encoding: 'utf8' }
+ )
+ expect(command.status).toBe(0)
+ expect(command.stderr).toBe('Warning: Some insights are excluded.\n')
+ expect(format === 'json' ? JSON.parse(command.stdout) : command.stdout.trimEnd()).toEqual(result)
+ } finally {
+ rmSync(directory, { recursive: true, force: true })
+ }
+ }
+ )
+
+ it.each(['hogql', 'run'])('cancels %s from the response open and accepts the next command', async (name) => {
+ const filesystem = new TerminalFilesystem()
+ let querySignal: AbortSignal | undefined
+ new TerminalCommands(filesystem, async ([command], _cwd, { signal }) => {
+ if (command === name) {
+ querySignal = signal
+ await new Promise<void>((_resolve, reject) =>
+ signal!.addEventListener('abort', () => reject(new Error('Query cancelled')), { once: true })
+ )
+ }
+ return 'Next command completed'
+ })
+ const bridge = filesystem.root.children!.get('.ph')!.children!
+ const write = async (argv: string[]): Promise<void> =>
+ (await bridge.get('request')!.open!()).save!(
+ new TextEncoder().encode(JSON.stringify({ argv, cwd: '/tmp' }))
+ )
+ await write([name])
+ const controller = new AbortController()
+ const response = bridge.get('response')!.open!(controller.signal)
+ controller.abort()
+ expect(querySignal?.aborted).toBe(true)
+ expect(JSON.parse(new TextDecoder().decode((await response).bytes))).toEqual({
+ ok: false,
+ error: 'Query cancelled',
+ })
+ await write(['help'])
+ expect(JSON.parse(new TextDecoder().decode((await bridge.get('response')!.open!()).bytes))).toEqual({
+ ok: true,
+ result: 'Next command completed',
+ })
+ })
+})
diff --git a/frontend/src/scenes/terminal/terminalCommands.ts b/frontend/src/scenes/terminal/terminalCommands.ts
index 8fd3d7bc0090..80118f43a429 100644
--- a/frontend/src/scenes/terminal/terminalCommands.ts
+++ b/frontend/src/scenes/terminal/terminalCommands.ts
@@ -1,4 +1,5 @@
import { MAX_TERMINAL_FILE_BYTES, TerminalFilesystem } from './terminalFilesystem'
+import { HOGQL_SCRIPT } from './terminalHogql'
const OPEN_SCRIPT = String.raw`#!/bin/sh
set -eu
@@ -52,6 +53,7 @@ cat "$temporary/request" > /posthog/.ph/request
response=$(cat /posthog/.ph/response)
flock -u 9
if printf '%s' "$response" | jq -e '.ok' >/dev/null; then
+ printf '%s' "$response" | jq -r '.warnings[]? | "Warning: " + .' >&2
printf '%s' "$response" | jq -r '.result'
else
printf '%s' "$response" | jq -r '.error' >&2
@@ -94,6 +96,7 @@ Examples:
Use /tmp for exports.
Query errors go to stderr and exit nonzero.
+Query warnings go to stderr in every output format.
`
const RUN_SCRIPT = String.raw`#!/bin/sh
@@ -136,53 +139,97 @@ target=$(readlink -f -- "$file")
exec ph run "$target" "@$target" "$format"
`
+export interface TerminalCommandContext {
+ signal?: AbortSignal
+ onWarning?: (message: string) => void
+}
+
export class TerminalCommands {
- constructor(filesystem: TerminalFilesystem, execute: (argv: string[], cwd: string) => Promise<unknown>) {
+ constructor(
+ filesystem: TerminalFilesystem,
+ execute: (argv: string[], cwd: string, context: TerminalCommandContext) => Promise<unknown>
+ ) {
const encoder = new TextEncoder()
const decoder = new TextDecoder('utf-8', { fatal: true })
const envelope = (value: object): Uint8Array => encoder.encode(JSON.stringify(value))
let response = envelope({ ok: false, error: 'Run a ph command first.' })
+ let pending: { controller: AbortController; result: Promise<void> } | undefined
const directory = filesystem.directory('.ph', filesystem.root)
- const responseNode = filesystem.file('response', directory, async () => ({ bytes: response }))
+ const responseNode = filesystem.file('response', directory, async (signal) => {
+ const command = pending
+ if (command) {
+ const abort = (): void => command.controller.abort()
+ if (signal?.aborted) {
+ abort()
+ }
+ signal?.addEventListener('abort', abort, { once: true })
+ try {
+ await command.result
+ } finally {
+ signal?.removeEventListener('abort', abort)
+ }
+ }
+ return { bytes: response }
+ })
filesystem.file(
'request',
directory,
async () => ({
bytes: new Uint8Array(),
save: async (bytes) => {
- try {
- const request = JSON.parse(decoder.decode(bytes))
- if (
- !request ||
- !Array.isArray(request.argv) ||
- request.argv.length > 1000 ||
- !request.argv.every((value: unknown) => typeof value === 'string') ||
- typeof request.cwd !== 'string'
- ) {
- throw new Error('Invalid command request. Run ph help for usage.')
+ pending?.controller.abort()
+ await pending?.result
+ const controller = new AbortController()
+ const warnings: string[] = []
+ let query = false
+ const run = async (): Promise<void> => {
+ try {
+ const request = JSON.parse(decoder.decode(bytes))
+ if (
+ !request ||
+ !Array.isArray(request.argv) ||
+ request.argv.length > 1000 ||
+ !request.argv.every((value: unknown) => typeof value === 'string') ||
+ typeof request.cwd !== 'string'
+ ) {
+ throw new Error('Invalid command request. Run ph help for usage.')
+ }
+ query = ['hogql', 'run'].includes(request.argv[0])
+ const result = await execute(request.argv, request.cwd, {
+ signal: controller.signal,
+ onWarning: (message) => warnings.push(message),
+ })
+ const encoded = envelope({
+ ok: true,
+ result: result ?? null,
+ ...(warnings.length ? { warnings } : {}),
+ })
+ if (encoded.length > MAX_TERMINAL_FILE_BYTES) {
+ throw new Error('The result exceeds 4 MiB. Reduce the limit or narrow the query.')
+ }
+ response = encoded
+ } catch (error) {
+ // A failed tool can put its whole payload in the message, and the guest reads
+ // this file into a shell variable inside the virtual machine.
+ const encoded = envelope({
+ ok: false,
+ error: error instanceof Error ? error.message : 'The command failed. Try ph help.',
+ })
+ response =
+ encoded.length > MAX_TERMINAL_FILE_BYTES
+ ? envelope({
+ ok: false,
+ error: 'The command failed, and its error exceeds 4 MiB. Check the tool that returned it.',
+ })
+ : encoded
}
- const result = await execute(request.argv, request.cwd)
- const encoded = envelope({ ok: true, result: result ?? null })
- if (encoded.length > MAX_TERMINAL_FILE_BYTES) {
- throw new Error('The result exceeds 4 MiB. Reduce the limit or narrow the query.')
- }
- response = encoded
- } catch (error) {
- // A failed tool can put its whole payload in the message, and the guest reads
- // this file into a shell variable inside the virtual machine.
- const encoded = envelope({
- ok: false,
- error: error instanceof Error ? error.message : 'The command failed. Try ph help.',
- })
- response =
- encoded.length > MAX_TERMINAL_FILE_BYTES
- ? envelope({
- ok: false,
- error: 'The command failed, and its error exceeds 4 MiB. Check the tool that returned it.',
- })
- : encoded
+ responseNode.size = response.length
+ }
+ pending = { controller, result: run() }
+ // Linux does not flush Tclunk on Ctrl+C. Query waits belong in the interruptible response open.
+ if (!query) {
+ await pending.result
}
- responseNode.size = response.length
},
}),
true
@@ -190,6 +237,7 @@ export class TerminalCommands {
const bin = filesystem.directory('bin', filesystem.root)
filesystem.text('ph', bin, PH_SCRIPT)
filesystem.text('run', bin, RUN_SCRIPT)
+ filesystem.text('hogql', bin, HOGQL_SCRIPT)
filesystem.text('shellrc', bin, SHELL_RC)
filesystem.text('open', bin, OPEN_SCRIPT)
}
diff --git a/frontend/src/scenes/terminal/terminalHogql.test.ts b/frontend/src/scenes/terminal/terminalHogql.test.ts
new file mode 100644
index 000000000000..063697c7c057
--- /dev/null
+++ b/frontend/src/scenes/terminal/terminalHogql.test.ts
@@ -0,0 +1,94 @@
+import { spawnSync } from 'child_process'
+import { mkdtempSync, rmSync, writeFileSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+
+import { HOGQL_SCRIPT } from './terminalHogql'
+
+describe('terminal hogql wrapper', () => {
+ let directory: string
+
+ beforeEach(() => {
+ directory = mkdtempSync(join(tmpdir(), 'terminal-hogql-'))
+ writeFileSync(join(directory, 'ph'), '#!/bin/sh\ncat\n', { mode: 0o700 })
+ })
+
+ afterEach(() => {
+ rmSync(directory, { recursive: true, force: true })
+ })
+
+ const run = (argv: string[], input = ''): ReturnType<typeof spawnSync> =>
+ spawnSync('bash', ['-c', HOGQL_SCRIPT, 'hogql', ...argv], {
+ env: { ...process.env, PATH: `${directory}:${process.env.PATH}` },
+ input,
+ encoding: 'utf8',
+ })
+
+ it.each([
+ ['argument', 0],
+ ['stdin', 0],
+ ['stdin', 256 * 1024],
+ ])('preserves SQL quotes, newlines, and shell metacharacters from %s with %i padding bytes', (source, padding) => {
+ const query = "select 'a\\b', '@file', '$(echo untouched)'\n-- another line" + 'x'.repeat(padding)
+ const options = ['--connection-id', 'example-connection', '--values', '{"value":"a b"}', '--csv']
+ const result = source === 'argument' ? run([...options, query]) : run(options, query)
+ expect(result.status).toBe(0)
+ expect(result.stderr).toBe('')
+ expect(JSON.parse(String(result.stdout))).toEqual({ query, argv: options })
+ })
+
+ it('accepts SQL after -- without interpreting its leading comment as an option', () => {
+ const result = run(['--json', '--', '-- comment\nselect 1'])
+ expect(result.status).toBe(0)
+ expect(JSON.parse(String(result.stdout))).toEqual({ query: '-- comment\nselect 1', argv: ['--json'] })
+ })
+
+ it.each([
+ [['--connection-id'], 'Missing value'],
+ [['--unknown'], 'Unknown option'],
+ [['select', '1'], 'Quote the SQL'],
+ ])('rejects invalid shell arguments %j', (argv, message) => {
+ const result = run(argv)
+ expect(result.status).toBe(1)
+ expect(result.stdout).toBe('')
+ expect(result.stderr).toContain(message)
+ })
+
+ it('keeps the interactive prompt open after a failed query until exit', () => {
+ writeFileSync(join(directory, 'hogql'), HOGQL_SCRIPT)
+ writeFileSync(
+ join(directory, 'ph'),
+ '#!/bin/sh\nrequest=$(cat)\ncase "$request" in *missing*) echo "Query failed" >&2; exit 1 ;; esac\nprintf "%s\\n" "$request"\n'
+ )
+ // A real PTY exercises Bash readline on both macOS and Linux.
+ const driver = `
+import os, pty, sys
+sent = False
+def read(fd: int) -> bytes:
+ global sent
+ if not sent:
+ os.write(fd, b'select missing\\nselect 1\\nexit\\n')
+ sent = True
+ return os.read(fd, 65536)
+sys.exit(os.waitstatus_to_exitcode(pty.spawn(['bash', sys.argv[1], '--csv'], read)))
+`
+ const result = spawnSync('python3', ['-c', driver, join(directory, 'hogql')], {
+ env: { ...process.env, PATH: `${directory}:${process.env.PATH}` },
+ input: '',
+ encoding: 'utf8',
+ timeout: 10000,
+ })
+ expect(result.stderr).toBe('')
+ expect(result.status).toBe(0)
+ expect(result.stdout).toContain('Query failed')
+ expect(result.stdout).toContain(JSON.stringify({ query: 'select 1', argv: ['--csv'] }))
+ })
+
+ it('returns query failures on stderr with a nonzero exit status', () => {
+ writeFileSync(join(directory, 'ph'), '#!/bin/sh\ncat >/dev/null\necho "Query failed" >&2\nexit 1\n')
+ const result = run(['select missing'])
+ expect(result.status).toBe(1)
+ expect(result.stdout).toBe('')
+ expect(result.stderr).toBe('Query failed\n')
+ })
+})
diff --git a/frontend/src/scenes/terminal/terminalHogql.ts b/frontend/src/scenes/terminal/terminalHogql.ts
new file mode 100644
index 000000000000..554e04aaef6b
--- /dev/null
+++ b/frontend/src/scenes/terminal/terminalHogql.ts
@@ -0,0 +1,186 @@
+import { HogQLQuery, NodeKind } from '~/queries/schema/schema-general'
+
+export const HOGQL_HELP = `Usage: hogql [options] ["SQL"]
+ echo "SQL" | hogql [options]
+ hogql [options]
+
+Run SQL in the current PostHog project. Without SQL or piped input, start
+an interactive prompt. Enter one query per line; no semicolon is required.
+Use exit, quit, \\q, or Ctrl+D to leave. Query errors keep the prompt open.
+
+Output (choose one):
+ --markdown Markdown table (default)
+ --json Full query response, including metadata and hasMore
+ --csv Comma-separated headers and rows
+ --tsv Tab-separated headers and rows
+
+Query options:
+ --connection-id ID Query an external connection instead of PostHog data
+ --raw Send SQL to that connection without HogQL translation
+ --name NAME Set the query name
+ --values JSON Placeholder values, for example '{"value":42}'
+ --filters JSON Filters used by the {filters} placeholder
+ --variables JSON Saved query variables
+ --modifiers JSON HogQL query modifiers
+ --field NAME=JSON Add a top-level query field; repeat for multiple fields
+ --help, -h Show this help
+ -- Treat the next argument as SQL, even if it starts with -
+
+JSON options must be objects. --field values must be valid JSON; quote strings.
+Fields use API names, such as sendRawQuery. kind and query cannot be overridden.
+Options apply to every query in an interactive session. Use LIMIT and OFFSET
+in SQL to page through results. --json includes hasMore when more rows exist.
+CSV and TSV quote special characters; null values become empty fields.
+Errors go to stderr and exit nonzero outside interactive mode.
+Warnings go to stderr in every output format. Ctrl+C cancels the current query.
+
+Examples:
+ hogql "select 1"
+ echo "select 1" | hogql --json
+ hogql --csv "select event, count() from events group by event" > /tmp/events.csv
+ hogql --values '{"value":42}' "select {value}"
+ hogql --connection-id CONNECTION_ID "select * from orders limit 10"
+ hogql --modifiers '{"debug":true}' --json "select 1"
+ hogql --connection-id CONNECTION_ID --raw
+`
+
+export const HOGQL_FLAGS = [
+ '--markdown',
+ '--json',
+ '--csv',
+ '--tsv',
+ '--connection-id',
+ '--raw',
+ '--name',
+ '--values',
+ '--filters',
+ '--variables',
+ '--modifiers',
+ '--field',
+ '--help',
+]
+
+export const HOGQL_SCRIPT = String.raw`#!/usr/bin/bash
+set -euo pipefail
+usage() {
+ cat <<'HELP'
+${HOGQL_HELP}
+HELP
+}
+options=()
+query=''
+has_query=false
+while [ "$#" -gt 0 ]; do
+ case "$1" in
+ --help|-h) usage; exit 0 ;;
+ --markdown|--json|--csv|--tsv|--raw) options+=("$1") ;;
+ --connection-id|--name|--values|--filters|--variables|--modifiers|--field)
+ [ "$#" -ge 2 ] || { echo "Missing value for $1. Run hogql --help." >&2; exit 1; }
+ options+=("$1" "$2")
+ shift
+ ;;
+ --)
+ shift
+ [ "$#" -eq 1 ] && ! "$has_query" || { usage >&2; exit 1; }
+ query="$1"
+ has_query=true
+ break
+ ;;
+ -*) echo "Unknown option: $1. Run hogql --help." >&2; exit 1 ;;
+ *)
+ ! "$has_query" || { echo 'Quote the SQL as one argument. Run hogql --help.' >&2; exit 1; }
+ query="$1"
+ has_query=true
+ ;;
+ esac
+ shift
+done
+execute_query() {
+ printf '%s' "$1" |
+ jq -cRs --args '{query: ., argv: $ARGS.positional}' -- "${'$'}{options[@]}" |
+ ph hogql --json -
+}
+if "$has_query"; then
+ execute_query "$query"
+elif [ ! -t 0 ]; then
+ execute_query "$(cat)"
+else
+ printf '%s\n' 'Enter one SQL query per line. Use exit or Ctrl+D to leave.' >&2
+ while IFS= read -e -r -p 'hogql> ' query; do
+ case "$query" in exit|quit|'\q') break ;; esac
+ [ -n "${'$'}{query//[[:space:]]/}" ] || continue
+ history -s "$query"
+ execute_query "$query" || true
+ done
+fi
+`
+
+function jsonField(text: string, option: string): unknown {
+ try {
+ return JSON.parse(text)
+ } catch {
+ throw new Error(`Invalid JSON for ${option}. Run hogql --help for examples.`)
+ }
+}
+
+type HogqlFormat = 'markdown' | 'json' | 'csv' | 'tsv'
+
+export function terminalHogqlQuery(text: string, argv: string[]): { query: HogQLQuery; format: HogqlFormat } {
+ if (!text.trim()) {
+ throw new Error('The query is empty. Pass SQL as an argument or pipe it to hogql.')
+ }
+ let format: HogqlFormat | undefined
+ const fields: Record<string, unknown> = {}
+ for (let index = 0; index < argv.length; index++) {
+ const option = argv[index]
+ if (['--markdown', '--json', '--csv', '--tsv'].includes(option)) {
+ if (format) {
+ throw new Error('Choose one output format. Run hogql --help for formats.')
+ }
+ format = option.slice(2) as HogqlFormat
+ continue
+ }
+ if (option === '--raw') {
+ fields.sendRawQuery = true
+ continue
+ }
+ if (!HOGQL_FLAGS.includes(option) || option === '--help') {
+ throw new Error(`Unknown option: ${option}. Run hogql --help.`)
+ }
+ const value = argv[++index]
+ if (value === undefined) {
+ throw new Error(`Missing value for ${option}. Run hogql --help.`)
+ }
+ if (option === '--connection-id' || option === '--name') {
+ if (!value.trim()) {
+ throw new Error(`Provide a nonempty value for ${option}.`)
+ }
+ fields[option === '--connection-id' ? 'connectionId' : 'name'] = value
+ } else if (option === '--field') {
+ const separator = value.indexOf('=')
+ const name = value.slice(0, separator)
+ if (separator <= 0 || ['kind', 'query', '__proto__', 'constructor', 'prototype'].includes(name)) {
+ throw new Error('Use --field name=JSON for a query field other than kind or query.')
+ }
+ fields[name] = jsonField(value.slice(separator + 1), '--field')
+ } else {
+ const parsed = jsonField(value, option)
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
+ throw new Error(`${option} requires a JSON object. Run hogql --help for examples.`)
+ }
+ fields[option.slice(2)] = parsed
+ }
+ }
+ if (fields.sendRawQuery && !fields.connectionId) {
+ throw new Error('Raw SQL requires --connection-id. Run hogql --help.')
+ }
+ return {
+ query: {
+ tags: { productKey: 'sql_editor', scene: 'Terminal' },
+ ...fields,
+ kind: NodeKind.HogQLQuery,
+ query: text,
+ },
+ format: format ?? 'markdown',
+ }
+}
diff --git a/frontend/src/scenes/terminal/terminalRuntime.ts b/frontend/src/scenes/terminal/terminalRuntime.ts
index f48b2bb45110..ab08a028fe22 100644
--- a/frontend/src/scenes/terminal/terminalRuntime.ts
+++ b/frontend/src/scenes/terminal/terminalRuntime.ts
@@ -218,6 +218,7 @@ export class TerminalRuntime {
'cp /posthog/bin/jq /usr/bin/jq && chmod +x /usr/bin/jq || exit',
'cp /posthog/bin/ph /usr/bin/ph && chmod +x /usr/bin/ph || exit',
'cp /posthog/bin/run /usr/bin/run && chmod +x /usr/bin/run || exit',
+ 'cp /posthog/bin/hogql /usr/bin/hogql && chmod +x /usr/bin/hogql || exit',
'[ -e /dev/fd ] || ln -s /proc/self/fd /dev/fd',
'mkdir -p /usr/local/bin && cp /posthog/bin/rm /usr/local/bin/rm && chmod +x /usr/local/bin/rm || exit',
'export PATH=/usr/local/bin:$PATH',