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(batch-exports): edit hogql batch export queries in the sql editor (#113208)

Ross3ff11998d0cf
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 1b27a4ef734d..7bb186031326 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9030,6 +9030,10 @@ snapshots:
hash: v1.k794b7964.158bb2510d66c6fe81f144c86fd612bac8c95cc95f56186e4465e8995a1e38b8.YJ_6q5QuNZQJsomF5fYIADEUdgz670SCVgfQtUCRL6Y
scenes-app-batchexports--existing-big-query-export--light:
hash: v1.k794b7964.169c050ced77823af76847e5b432e37172733b51a52fa3e4046ab9ef586d40eb.QA_BL0dNaL6VSVaB5YMB03s3-F4U4WQjVKyOY_xGux4
+ scenes-app-batchexports--existing-hog-ql-export--dark:
+ hash: v1.k794b7964.d5e31173e3e69b7a063b65c63239e8aab0eb7458470b6ab09673d92f7c9bbf11.s1usBPTk3SLC9lrQaQsFVDvYXGsS6-M9NbIxYuROncc
+ scenes-app-batchexports--existing-hog-ql-export--light:
+ hash: v1.k794b7964.b6ba4512c7721d653ea7c8fa2b9fa755894f0071ea904835e44f4ae6434624da.Wb198vJBtGeUMQhPPJxJuSsNVtnhoHiMOlF2QFfqFwc
scenes-app-batchexports--history-empty--dark:
hash: v1.k794b7964.4876ed69bc9129528181a8a663b41e0fb1350b95e3f3a6077a9db2857b081cc4.N_l9zIvhsX-G07IjsNfoWtmuyYaV-o88xTxZz3_w4rM
scenes-app-batchexports--history-empty--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index d8b0d83635a5..0c77322d3923 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -208,6 +208,7 @@ export const FEATURE_FLAGS = {
GAME_CENTER: 'game-center', // owner: everybody, this is just internal for now
HEDGEHOG_SKIN_SPIDERHOG: 'hedgehog-skin-spiderhog', // owner: #team-web-analytics, used to reward beta users for web analytics
HIGH_FREQUENCY_BATCH_EXPORTS: 'high-frequency-batch-exports', // owner: #team-batch-exports, allow batch exports to be run every 5min/15min
+ HOGQL_BATCH_EXPORTS: 'hogql-batch-exports', // owner: #team-batch-exports, export the results of a HogQL query
METALYTICS: 'metalytics', // owner: #team-platform-features, used to allow companies to see (meta) analytics on access to a specific page
PERSON_PROPERTY_INCIDENT_ANNOTATION_JAN_2026: 'person-property-incident-annotation-jan-2026', // owner: #team-platform-features, shows system annotation for Jan 6-7 2026 person property incident
REPLAY_EXCLUDE_FROM_HIDE_RECORDINGS_MENU: 'replay-exclude-from-hide-recordings-menu', // owner: #team-replay, used to exclude what other people are seeing in Replay
diff --git a/frontend/src/scenes/data-pipelines/batch-exports/BatchExportBackfillModal.tsx b/frontend/src/scenes/data-pipelines/batch-exports/BatchExportBackfillModal.tsx
index 6cb44dec6a5a..7db52e8e3971 100644
--- a/frontend/src/scenes/data-pipelines/batch-exports/BatchExportBackfillModal.tsx
+++ b/frontend/src/scenes/data-pipelines/batch-exports/BatchExportBackfillModal.tsx
@@ -13,6 +13,8 @@ import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonInput } from 'lib/lemon-ui/LemonInput'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
+import { BatchExportModelEnumApi } from 'products/batch_exports/frontend/generated/api.schemas'
+
import {
BatchExportBackfillModalLogicProps,
batchExportBackfillModalLogic,
@@ -122,7 +124,7 @@ export function BatchExportBackfillModal({ id, context }: BatchExportBackfillMod
</LemonField>
{/* Note: This is behind a feature flag while we improve backfilling behavior. */}
- {earliestBackfillEnabled && batchExportConfig?.model == 'persons' ? (
+ {earliestBackfillEnabled && batchExportConfig?.model === BatchExportModelEnumApi.Persons ? (
<LemonField name="earliest_backfill">
{({ onChange }) => (
<LemonCheckbox
diff --git a/frontend/src/scenes/data-pipelines/batch-exports/BatchExportConfiguration.tsx b/frontend/src/scenes/data-pipelines/batch-exports/BatchExportConfiguration.tsx
index 05be4c8e62c3..b70b0433ae9f 100644
--- a/frontend/src/scenes/data-pipelines/batch-exports/BatchExportConfiguration.tsx
+++ b/frontend/src/scenes/data-pipelines/batch-exports/BatchExportConfiguration.tsx
@@ -29,6 +29,7 @@ import {
IntegrationType,
} from '~/types'
+import { BatchExportModelEnumApi } from 'products/batch_exports/frontend/generated/api.schemas'
import { SourceDestinationsBanner } from 'products/warehouse_sources/frontend/components/SourceDestinationsBanner'
import { batchExportConfigFormLogic } from './batchExportConfigFormLogic'
@@ -37,6 +38,7 @@ import {
BatchExportConfigurationSaveButton,
} from './BatchExportConfigurationButtons'
import { BatchExportGeneralEditFields, BatchExportsEditFields } from './BatchExportEditForm'
+import { BatchExportHogQLQueryEditor } from './BatchExportHogQLQueryEditor'
import { EVENT_FIELD_DESCRIPTIONS } from './destinations/common'
import { BatchExportConfigurationForm } from './types'
import { dayOptions, hourOptions } from './utils'
@@ -55,12 +57,13 @@ export function BatchExportConfiguration(): JSX.Element {
service,
selectedIntegration,
} = useValues(batchExportConfigFormLogic)
- const { setSelectedModel, setConfigurationValue, runBatchExportConfigTestStep } =
- useActions(batchExportConfigFormLogic)
+ const { setConfigurationValue, runBatchExportConfigTestStep } = useActions(batchExportConfigFormLogic)
const { featureFlags } = useValues(featureFlagLogic)
const { preflight } = useValues(preflightLogic)
const { timezone: teamTimezone, weekStartDay } = useValues(teamLogic)
const highFrequencyBatchExports = featureFlags[FEATURE_FLAGS.HIGH_FREQUENCY_BATCH_EXPORTS]
+ const hogqlBatchExports = !!featureFlags[FEATURE_FLAGS.HOGQL_BATCH_EXPORTS]
+ const isHogQLModel = selectedModel === BatchExportModelEnumApi.Hogql
const showTimezoneAndOffsetSelector = configuration.interval === 'day' || configuration.interval === 'week'
const timezoneOptions =
@@ -77,8 +80,8 @@ export function BatchExportConfiguration(): JSX.Element {
<Form logic={batchExportConfigFormLogic} formKey="configuration" className="flex flex-col gap-3">
<SourceDestinationsBanner />
<div className="flex flex-wrap gap-4 items-start">
- <div className="flex flex-col flex-1 max-w-200 min-w-100 gap-y-3">
- <div className="flex flex-col p-3 rounded border bg-surface-primary gap-y-2">
+ <div className="flex flex-col flex-1 min-w-100 gap-y-3">
+ <div className="flex flex-col p-3 rounded border bg-surface-primary gap-y-2 *:max-w-160">
<div className="flex flex-col gap-y-1 mb-2">
<h3 className="mb-0">Schedule</h3>
<p className="text-secondary text-xs mb-0">Controls when this batch export runs</p>
@@ -222,7 +225,7 @@ export function BatchExportConfiguration(): JSX.Element {
</>
)}
</div>
- <div className="flex flex-col p-3 rounded border bg-surface-primary gap-y-2">
+ <div className="flex flex-col p-3 rounded border bg-surface-primary gap-y-2 *:max-w-160">
<div className="flex flex-col gap-y-1 mb-2">
<h3 className="mb-0">Data</h3>
<p className="text-secondary text-xs mb-0">Controls which data is exported</p>
@@ -235,58 +238,77 @@ export function BatchExportConfiguration(): JSX.Element {
className="flex flex-1"
>
<LemonSelect
- options={tables.map((table) => ({
- value: table.name,
- label: table.id,
- }))}
- value={selectedModel}
- onSelect={(newValue) => {
- setSelectedModel(newValue)
- }}
+ options={[
+ ...tables.map((table) => ({
+ value: table.name,
+ label: table.id,
+ })),
+ {
+ value: BatchExportModelEnumApi.Hogql,
+ label: 'Custom SQL query',
+ hidden: !hogqlBatchExports,
+ },
+ ]}
+ disabledReason={
+ isNew
+ ? undefined
+ : "A saved batch export can't change its model. Create a new one to export different data."
+ }
fullWidth={true}
/>
</LemonField>
</div>
- <div className="flex gap-2">
- <LemonCollapse
- className="flex flex-1"
- panels={[
- {
- key: 'schema',
- header: 'View model schema',
- content: (
- <div className="flex-1">
- {/* TODO: display the data types that will be used in the destination */}
- {isDatabaseDestination && (
- <LemonBanner type="info" className="mb-4">
- This schema is just for reference and does not reflect the
- actual data types that will be used in {service}.
- <br />
- <br />
- <b>
- It is recommended to allow the batch export to create the
- destination table automatically.
- </b>
- </LemonBanner>
- )}
- <DatabaseTable
- table={selectedModel ? selectedModel : 'events'}
- tables={tables}
- inEditSchemaMode={false}
- fieldDescriptions={
- !selectedModel || selectedModel === 'events'
- ? EVENT_FIELD_DESCRIPTIONS
- : undefined
- }
- />
- </div>
- ),
- },
- ]}
- />
- </div>
- {selectedModel === 'events' ? (
+ {isHogQLModel ? (
+ <p className="text-xs text-secondary mb-0">
+ Each run exports the results of the query below.
+ </p>
+ ) : (
+ <div className="flex gap-2">
+ <LemonCollapse
+ className="flex flex-1"
+ panels={[
+ {
+ key: 'schema',
+ header: 'View model schema',
+ content: (
+ <div className="flex-1">
+ {/* TODO: display the data types that will be used in the destination */}
+ {isDatabaseDestination && (
+ <LemonBanner type="info" className="mb-4">
+ This schema is just for reference and does not reflect the
+ actual data types that will be used in {service}.
+ <br />
+ <br />
+ <b>
+ It is recommended to allow the batch export to create
+ the destination table automatically.
+ </b>
+ </LemonBanner>
+ )}
+ <DatabaseTable
+ table={
+ selectedModel
+ ? selectedModel
+ : BatchExportModelEnumApi.Events
+ }
+ tables={tables}
+ inEditSchemaMode={false}
+ fieldDescriptions={
+ !selectedModel ||
+ selectedModel === BatchExportModelEnumApi.Events
+ ? EVENT_FIELD_DESCRIPTIONS
+ : undefined
+ }
+ />
+ </div>
+ ),
+ },
+ ]}
+ />
+ </div>
+ )}
+ {selectedModel === BatchExportModelEnumApi.Events ? (
<>
<div className="flex flex-col gap-2 min-h-16">
<div className="flex gap-2 justify-between w-full">
@@ -353,7 +375,7 @@ export function BatchExportConfiguration(): JSX.Element {
: []) as AnyPropertyFilter[]
}
taxonomicGroupTypes={
- selectedModel === 'events'
+ selectedModel === BatchExportModelEnumApi.Events
? [
TaxonomicFilterGroupType.EventProperties,
TaxonomicFilterGroupType.EventFeatureFlags,
@@ -375,10 +397,23 @@ export function BatchExportConfiguration(): JSX.Element {
</>
) : null}
</div>
+ {isHogQLModel ? (
+ <div className="flex flex-col p-3 rounded border bg-surface-primary gap-y-2">
+ <div className="flex flex-col gap-y-1 mb-2">
+ <h3 className="mb-0">Query</h3>
+ <p className="text-secondary text-xs mb-0">
+ Write the SQL query whose results each run exports. Run it here to preview the data.
+ </p>
+ </div>
+ <LemonField name="hogql_query">
+ <BatchExportHogQLQueryEditor />
+ </LemonField>
+ </div>
+ ) : null}
</div>
<div className="flex flex-col gap-4 flex-1 min-w-100">
- <div className="p-3 rounded border bg-surface-primary">
+ <div className="p-3 rounded border bg-surface-primary *:max-w-160">
<BatchExportConfigurationFields
isNew={isNew}
formValues={configuration as BatchExportConfigurationForm}
diff --git a/frontend/src/scenes/data-pipelines/batch-exports/BatchExportEditForm.tsx b/frontend/src/scenes/data-pipelines/batch-exports/BatchExportEditForm.tsx
index f7a9247c02c3..090162e3c1b2 100644
--- a/frontend/src/scenes/data-pipelines/batch-exports/BatchExportEditForm.tsx
+++ b/frontend/src/scenes/data-pipelines/batch-exports/BatchExportEditForm.tsx
@@ -96,7 +96,7 @@ export function BatchExportsEditFields({
const definition = destination ? DESTINATIONS[destination] : undefined
return (
- <div className="flex flex-col gap-y-4 max-w-200">
+ <div className="flex flex-col gap-y-4">
{definition && (
<definition.Fields
isNew={isNew}
diff --git a/frontend/src/scenes/data-pipelines/batch-exports/BatchExportHogQLQueryEditor.tsx b/frontend/src/scenes/data-pipelines/batch-exports/BatchExportHogQLQueryEditor.tsx
new file mode 100644
index 000000000000..ab4060dcf476
--- /dev/null
+++ b/frontend/src/scenes/data-pipelines/batch-exports/BatchExportHogQLQueryEditor.tsx
@@ -0,0 +1,49 @@
+import { useMountedLogic, useValues } from 'kea'
+
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+import { SQLEditor } from 'scenes/data-warehouse/editor/SQLEditor'
+import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'
+
+import { batchExportConfigFormLogic } from './batchExportConfigFormLogic'
+import {
+ DATA_INTERVAL_END_PLACEHOLDER,
+ DATA_INTERVAL_START_PLACEHOLDER,
+ batchExportHogQLEditorTabId,
+ batchExportHogQLQueryLogic,
+} from './batchExportHogQLQueryLogic'
+
+export function BatchExportHogQLQueryEditor(): JSX.Element {
+ const { props: formLogicProps } = useMountedLogic(batchExportConfigFormLogic)
+ const { previewStart, previewEnd, projectTimezone, usesIntervalPlaceholders } = useValues(
+ batchExportHogQLQueryLogic(formLogicProps)
+ )
+
+ return (
+ <div className="flex flex-col gap-2">
+ {!usesIntervalPlaceholders && (
+ <LemonBanner type="warning">
+ This query doesn't use {`{${DATA_INTERVAL_START_PLACEHOLDER}}`} or{' '}
+ {`{${DATA_INTERVAL_END_PLACEHOLDER}}`}, so every run exports all of its results. To export only new
+ data on each run, filter on these placeholders.
+ </LemonBanner>
+ )}
+ {/* Fixed height, because the embedded editor fills its container and has no height of its own */}
+ <div className="h-160 border rounded overflow-hidden flex flex-col">
+ <SQLEditor
+ tabId={batchExportHogQLEditorTabId(formLogicProps)}
+ mode={SQLEditorMode.Embedded}
+ defaultShowDatabaseTree={false}
+ singleStatement
+ hideAgentHints
+ hideVariables
+ hideFilters
+ />
+ </div>
+ <p className="text-xs text-secondary mb-0">
+ When you run the query here, the placeholders cover the last complete interval:{' '}
+ <span translate="no">{`'${previewStart}'`}</span> to <span translate="no">{`'${previewEnd}'`}</span>{' '}
+ <span translate="no">{`(${projectTimezone})`}</span>. Each export run fills them with its own interval.
+ </p>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/data-pipelines/batch-exports/BatchExportScene.stories.tsx b/frontend/src/scenes/data-pipelines/batch-exports/BatchExportScene.stories.tsx
index ebb9389e20b8..9499c1a4410c 100644
--- a/frontend/src/scenes/data-pipelines/batch-exports/BatchExportScene.stories.tsx
+++ b/frontend/src/scenes/data-pipelines/batch-exports/BatchExportScene.stories.tsx
@@ -1,5 +1,6 @@
import { Meta, StoryObj } from '@storybook/react'
+import { FEATURE_FLAGS } from 'lib/constants'
import { App } from 'scenes/App'
import { urls } from 'scenes/urls'
@@ -29,6 +30,40 @@ const EXISTING_LEGACY_S3_PARQUET_EXPORT = {
},
}
+const EXISTING_HOGQL_EXPORT = {
+ ...batchExports.results[0],
+ id: '018a6fab-2c21-0002-d451-724c2995e2c1',
+ name: 'Signups to BigQuery',
+ interval: 'hour',
+ model: 'hogql',
+ hogql_query: `SELECT
+ distinct_id,
+ timestamp,
+ properties.$current_url AS url,
+ properties.plan AS plan
+FROM events
+WHERE event = 'signed_up'
+ AND timestamp >= {data_interval_start}
+ AND timestamp < {data_interval_end}`,
+ filters: [],
+}
+
+const HOGQL_EXPORT_PREVIEW_RESULTS = {
+ columns: ['distinct_id', 'timestamp', 'url', 'plan'],
+ types: [
+ ['distinct_id', 'String'],
+ ['timestamp', 'DateTime64(6, UTC)'],
+ ['url', 'Nullable(String)'],
+ ['plan', 'Nullable(String)'],
+ ],
+ results: [
+ ['user-1', '2024-01-14T23:12:03Z', 'https://example.com/signup', 'free'],
+ ['user-2', '2024-01-14T23:31:47Z', 'https://example.com/pricing', 'teams'],
+ ['user-3', '2024-01-14T23:58:10Z', 'https://example.com/signup', 'free'],
+ ],
+ hasMore: false,
+}
+
const meta: Meta = {
component: App,
title: 'Scenes-App/BatchExports',
@@ -127,6 +162,39 @@ export const ExistingBigQueryExport: Story = {
},
}
+export const ExistingHogQLExport: Story = {
+ parameters: {
+ pageUrl: urls.batchExport(EXISTING_HOGQL_EXPORT.id),
+ featureFlags: [FEATURE_FLAGS.HOGQL_BATCH_EXPORTS],
+ testOptions: { waitForSelector: '.monaco-editor' },
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ [`/api/environments/:team_id/batch_exports/${EXISTING_HOGQL_EXPORT.id}/`]: EXISTING_HOGQL_EXPORT,
+ [`/api/environments/:team_id/batch_exports/${EXISTING_HOGQL_EXPORT.id}/runs/`]: { results: [] },
+ [`/api/environments/:team_id/batch_exports/${EXISTING_HOGQL_EXPORT.id}/backfills/`]: { results: [] },
+ },
+ post: {
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
+ const kind = body?.query?.kind
+ if (kind === 'DatabaseSchemaQuery') {
+ return [200, { tables: {} }]
+ }
+ if (kind === 'HogQLMetadata') {
+ return [200, { errors: [], warnings: [], notices: [], isValid: true }]
+ }
+ if (kind === 'HogQLAutocomplete') {
+ return [200, { suggestions: [], incomplete_list: false }]
+ }
+ return [200, HOGQL_EXPORT_PREVIEW_RESULTS]
+ },
+ },
+ }),
+ ],
+}
+
export const ExistingAwsS3ExportWithLegacyParquetExtension: Story = {
parameters: {
pageUrl: urls.batchExport(EXISTING_LEGACY_S3_PARQUET_EXPORT.id),
diff --git a/frontend/src/scenes/data-pipelines/batch-exports/batchExportConfigFormLogic.test.ts b/frontend/src/scenes/data-pipelines/batch-exports/batchExportConfigFormLogic.test.ts
index f4e6e505bd35..74f2ef3c52f4 100644
--- a/frontend/src/scenes/data-pipelines/batch-exports/batchExportConfigFormLogic.test.ts
+++ b/frontend/src/scenes/data-pipelines/batch-exports/batchExportConfigFormLogic.test.ts
@@ -381,9 +381,16 @@ const REDSHIFT_COPY_INTEGRATIONS_BATCH_EXPORT = fixture(
}
)
+const HOGQL_BATCH_EXPORT: BatchExportConfiguration = {
+ ...fixture('test-hogql-id', 'HogQL Export', { type: 'AwsS3', integration: 31, config: AWS_S3_CONFIG }),
+ model: 'hogql',
+ hogql_query: 'SELECT event FROM events WHERE timestamp >= {data_interval_start}',
+}
+
// Single map keyed by id; used to register GET + PATCH mocks dynamically below.
const ALL_BATCH_EXPORTS: BatchExportConfiguration[] = [
AWS_S3_BATCH_EXPORT,
+ HOGQL_BATCH_EXPORT,
AWS_S3_GZIP_BATCH_EXPORT,
AWS_S3_LEGACY_EXTENSION_BATCH_EXPORT,
S3_COMPATIBLE_BATCH_EXPORT,
@@ -404,6 +411,8 @@ const ALL_BATCH_EXPORTS: BatchExportConfiguration[] = [
const SAVE_FAILS_ID = 'test-save-fails-id'
const SAVE_FAILS_DETAIL = 'Prefix is not valid'
+const HOGQL_SAVE_FAILS_ID = 'test-hogql-save-fails-id'
+const HOGQL_SAVE_FAILS_DETAIL = 'Invalid HogQL query: Unable to resolve field: not_a_column'
jest.mock('@posthog/lemon-ui', () => ({
...jest.requireActual('@posthog/lemon-ui'),
@@ -449,6 +458,21 @@ describe('batchExportConfigFormLogic', () => {
}
patchMocks[`/api/environments/:team_id/batch_exports/${SAVE_FAILS_ID}/`] = async () =>
[400, { detail: SAVE_FAILS_DETAIL }] as unknown as [number, BatchExportConfiguration]
+ // A HogQL export whose PATCH fails on the query, the way the API reports an invalid query.
+ getMocks[`/api/environments/:team_id/batch_exports/${HOGQL_SAVE_FAILS_ID}`] = {
+ ...HOGQL_BATCH_EXPORT,
+ id: HOGQL_SAVE_FAILS_ID,
+ }
+ patchMocks[`/api/environments/:team_id/batch_exports/${HOGQL_SAVE_FAILS_ID}/`] = async () =>
+ [
+ 400,
+ {
+ type: 'validation_error',
+ code: 'invalid_input',
+ detail: HOGQL_SAVE_FAILS_DETAIL,
+ attr: 'hogql_query',
+ },
+ ] as unknown as [number, BatchExportConfiguration]
useMocks({
get: {
...getMocks,
@@ -882,11 +906,37 @@ describe('batchExportConfigFormLogic', () => {
await expectLogic(logic, () => {
logic.actions.submitConfiguration()
})
- .toDispatchActions(['submitConfiguration', 'submitConfigurationSuccess'])
+ .toDispatchActions(['submitConfiguration', 'submitConfigurationFailure'])
.toFinishAllListeners()
expect(lemonToast.error).toHaveBeenCalledWith(SAVE_FAILS_DETAIL)
expect(logic.values.configurationChanged).toBe(true)
+ expect(logic.values.configurationManualErrors).toEqual({})
+ })
+
+ // The toast can be far from the query editor, so the API's field error also shows under the field. kea-forms
+ // treats it as a form error, so an edit must clear it, or the next save never reaches the API. A model change
+ // hides the query field, so it must clear the error too.
+ it.each([
+ ['the query changes', 'hogql_query', 'SELECT event FROM events'],
+ ['the model changes', 'model', 'events'],
+ ])('shows a field error from the API under its field until %s', async (_, field, value) => {
+ await initLogic({ service: null, id: HOGQL_SAVE_FAILS_ID })
+
+ await expectLogic(logic, () => {
+ logic.actions.submitConfiguration()
+ })
+ .toDispatchActions(['submitConfiguration', 'submitConfigurationFailure'])
+ .toFinishAllListeners()
+
+ expect(lemonToast.error).toHaveBeenCalledWith(HOGQL_SAVE_FAILS_DETAIL)
+ // configurationErrors is what the field renders, so it must hold the error, not only configurationAllErrors
+ expect(logic.values.configurationErrors.hogql_query).toEqual(HOGQL_SAVE_FAILS_DETAIL)
+
+ logic.actions.setConfigurationValue(field, value)
+
+ expect(logic.values.configurationErrors.hogql_query).toBeUndefined()
+ expect(logic.values.configurationHasErrors).toBe(false)
})
})
@@ -1301,6 +1351,7 @@ describe('batchExportConfigFormLogic', () => {
describe('round-trip: load and save preserves destination config', () => {
it.each([
{ name: 'AwsS3', fixture: AWS_S3_BATCH_EXPORT },
+ { name: 'AwsS3 (HogQL model)', fixture: HOGQL_BATCH_EXPORT },
{ name: 'S3Compatible', fixture: S3_COMPATIBLE_BATCH_EXPORT },
{ name: 'BigQuery', fixture: BIGQUERY_BATCH_EXPORT },
{ name: 'Postgres', fixture: POSTGRES_BATCH_EXPORT },
@@ -1325,6 +1376,63 @@ describe('batchExportConfigFormLogic', () => {
const body = patchBodiesById[fixture.id]
expect(body).not.toBeUndefined()
expect(body.destination).toEqual(fixture.destination)
+ // Only the 'hogql' model edits the query, so other models must not send one
+ expect(body.hogql_query).toEqual(fixture.hogql_query)
+ })
+
+ it.each([
+ { model: 'events', fixture: AWS_S3_BATCH_EXPORT, sendsFilters: true },
+ { model: 'persons', fixture: AWS_S3_BATCH_EXPORT, sendsFilters: false },
+ { model: 'sessions', fixture: AWS_S3_BATCH_EXPORT, sendsFilters: false },
+ { model: 'hogql', fixture: HOGQL_BATCH_EXPORT, sendsFilters: false },
+ ])('sends event filters only for the events model ($model)', async ({ model, fixture, sendsFilters }) => {
+ const filters = [{ key: '$browser', operator: 'exact', type: 'event', value: ['Firefox'] }]
+ await initLogic({ service: null, id: fixture.id })
+ logic.actions.setConfigurationValue('model', model)
+ logic.actions.setConfigurationValue('filters', filters)
+
+ await expectLogic(logic, () => {
+ logic.actions.submitConfiguration()
+ })
+ .toDispatchActions(['submitConfiguration', 'updateBatchExportConfigSuccess'])
+ .toFinishAllListeners()
+
+ if (sendsFilters) {
+ expect(patchBodiesById[fixture.id].filters).toEqual(filters)
+ } else {
+ expect(patchBodiesById[fixture.id]).not.toHaveProperty('filters')
+ }
+ })
+ })
+
+ // The model select and the sections below it follow `selectedModel`, while a save sends `configuration.model`.
+ // If a reset moved only one of them, the form would show the query editor and save an events export.
+ it('resets the selected model with the form', async () => {
+ await initLogic({ service: 'AwsS3', id: null })
+ logic.actions.setConfigurationValue('model', 'hogql')
+ expect(logic.values.selectedModel).toEqual('hogql')
+
+ logic.actions.resetConfiguration(getDefaultConfiguration('AwsS3'))
+
+ expect(logic.values.selectedModel).toEqual('events')
+ })
+
+ describe('HogQL query validation', () => {
+ it.each([
+ ['accepts a single statement', 'SELECT event FROM events', undefined],
+ ['accepts a trailing semicolon', 'SELECT event FROM events;', undefined],
+ [
+ 'rejects more than one statement',
+ 'SELECT event FROM events; SELECT 1',
+ 'A batch export runs a single query. Remove the extra statements separated by semicolons.',
+ ],
+ ['requires a query', '', 'This field is required'],
+ ])('%s', async (_, hogqlQuery, expectedError) => {
+ await initLogic({ service: null, id: HOGQL_BATCH_EXPORT.id })
+
+ logic.actions.setConfigurationValue('hogql_query', hogqlQuery)
+
+ expect(logic.values.configurationValidationErrors.hogql_query).toEqual(expectedError)
})
})
diff --git a/frontend/src/scenes/data-pipelines/batch-exports/batchExportConfigFormLogic.tsx b/frontend/src/scenes/data-pipelines/batch-exports/batchExportConfigFormLogic.tsx
index 964bd58f274d..8265f7b68f1f 100644
--- a/frontend/src/scenes/data-pipelines/batch-exports/batchExportConfigFormLogic.tsx
+++ b/frontend/src/scenes/data-pipelines/batch-exports/batchExportConfigFormLogic.tsx
@@ -8,6 +8,7 @@ import { LemonDialog, lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { splitQueries } from 'lib/monaco/multiQueryUtils'
import { addProductIntent } from 'lib/utils/product-intents'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -21,6 +22,8 @@ import {
IntegrationType,
} from '~/types'
+import { BatchExportModelEnumApi } from 'products/batch_exports/frontend/generated/api.schemas'
+
import { batchExportDataLogic } from './batchExportDataLogic'
import { DESTINATIONS } from './destinations'
import { genericPersonEventFields, isSelectedCompressionOptionValid } from './destinations/common'
@@ -44,6 +47,7 @@ const TOP_LEVEL_FORM_FIELDS = new Set([
'start_at',
'end_at',
'model',
+ 'hogql_query',
'filters',
'integration_id',
])
@@ -91,6 +95,24 @@ function buildDestinationPayload(formValues: Record<string, any>): {
return result
}
+function buildBatchExportPayload(formValues: Record<string, any>): Partial<BatchExportConfiguration> {
+ const interval = formValues.interval
+ return {
+ paused: formValues.paused,
+ name: formValues.name,
+ interval,
+ timezone: interval === 'day' || interval === 'week' ? formValues.timezone : null,
+ offset_day: interval === 'week' ? formValues.offset_day : null,
+ offset_hour: interval === 'day' || interval === 'week' ? formValues.offset_hour : null,
+ model: formValues.model,
+ // Only the 'hogql' model edits the query. The events model would save a query as its export schema.
+ hogql_query: formValues.model === BatchExportModelEnumApi.Hogql ? formValues.hogql_query : undefined,
+ // Filters only apply to the events model: the API rejects them for 'hogql' and runs ignore them otherwise
+ filters: formValues.model === BatchExportModelEnumApi.Events ? formValues.filters : undefined,
+ destination: buildDestinationPayload(formValues) as any,
+ }
+}
+
function getConfigurationFromBatchExportConfig(batchExportConfig: BatchExportConfiguration): Record<string, any> {
const destinationType = batchExportConfig.destination.type
const definition = DESTINATIONS[destinationType]
@@ -108,6 +130,7 @@ function getConfigurationFromBatchExportConfig(batchExportConfig: BatchExportCon
offset_day: (batchExportConfig as any).offset_day ?? null,
offset_hour: (batchExportConfig as any).offset_hour ?? null,
model: batchExportConfig.model,
+ hogql_query: batchExportConfig.hogql_query ?? null,
filters: batchExportConfig.filters,
...flatConfig,
}
@@ -128,7 +151,7 @@ export function getDefaultConfiguration(service: string): Record<string, any> {
return {
name: humanizeBatchExportName(service as BatchExportService['type']),
destination: service,
- model: 'events',
+ model: BatchExportModelEnumApi.Events,
paused: true,
exclude_events: [...DEFAULT_EXCLUDE_EVENTS],
...(definition ? definition.defaults() : {}),
@@ -647,9 +670,6 @@ export interface batchExportConfigFormLogicActions {
setSavedConfiguration: (configuration: Record<string, any>) => {
configuration: Record<string, any>
}
- setSelectedModel: (model: string) => {
- model: string
- }
submitConfiguration: () => {
value: boolean
}
@@ -669,9 +689,6 @@ export interface batchExportConfigFormLogicActions {
touchConfigurationField: (key: string) => {
key: string
}
- updateBatchExportConfig: (formdata: Record<string, any>) => {
- formdata: Record<string, any>
- }
updateBatchExportConfigSuccess: (batchExportConfig: BatchExportConfiguration) => {
batchExportConfig: BatchExportConfiguration
}
@@ -697,6 +714,7 @@ export interface batchExportConfigFormLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
logicProps: (arg: any) => any
+ selectedModel: (configuration: Record<string, any>) => string
service: (
batchExportConfig: BatchExportConfiguration | null,
service:
@@ -796,10 +814,8 @@ export const batchExportConfigFormLogic = kea<batchExportConfigFormLogicType>([
})),
actions({
setSavedConfiguration: (configuration: Record<string, any>) => ({ configuration }),
- setSelectedModel: (model: string) => ({ model }),
setRunningStep: (step: number | null) => ({ step }),
deleteBatchExport: () => true,
- updateBatchExportConfig: (formdata: Record<string, any>) => ({ formdata }),
updateBatchExportConfigSuccess: (batchExportConfig: BatchExportConfiguration) => ({ batchExportConfig }),
}),
loaders(({ props, values, actions }) => ({
@@ -844,19 +860,7 @@ export const batchExportConfigFormLogic = kea<batchExportConfigFormLogicType>([
})
}
- const formValues = values.configuration
- const interval = formValues.interval
- const data = {
- paused: formValues.paused,
- name: formValues.name,
- interval,
- timezone: interval === 'day' || interval === 'week' ? formValues.timezone : null,
- offset_day: interval === 'week' ? formValues.offset_day : null,
- offset_hour: interval === 'day' || interval === 'week' ? formValues.offset_hour : null,
- model: formValues.model,
- filters: formValues.filters,
- destination: buildDestinationPayload(formValues),
- } as any
+ const data = buildBatchExportPayload(values.configuration)
if (props.id) {
return await api.batchExports.runTestStep(props.id, step, data)
@@ -888,25 +892,6 @@ export const batchExportConfigFormLogic = kea<batchExportConfigFormLogicType>([
},
},
],
- selectedModel: [
- 'events',
- {
- setSelectedModel: (_, { model }) => model,
- loadBatchExportConfigSuccess: (state, { batchExportConfig }) => {
- if (!batchExportConfig) {
- return state
- }
-
- return batchExportConfig.model
- },
- updateBatchExportConfigSuccess: (state, { batchExportConfig }) => {
- if (!batchExportConfig) {
- return state
- }
- return batchExportConfig.model
- },
- },
- ],
configuration: [
props.service ? getDefaultConfiguration(props.service) : ({} as Record<string, any>),
{
@@ -954,6 +939,10 @@ export const batchExportConfigFormLogic = kea<batchExportConfigFormLogicType>([
})),
selectors(() => ({
logicProps: [() => [(_, props) => props], (props) => props],
+ selectedModel: [
+ (s) => [s.configuration],
+ (configuration: Record<string, any>): string => configuration.model ?? BatchExportModelEnumApi.Events,
+ ],
service: [
(s, p) => [s.batchExportConfig, p.service],
(
@@ -1020,7 +1009,12 @@ export const batchExportConfigFormLogic = kea<batchExportConfigFormLogicType>([
config: Record<string, any>,
selectedIntegration: IntegrationType | null
): string[] => {
- const generalRequiredFields = ['interval', 'name', 'model']
+ const generalRequiredFields = [
+ 'interval',
+ 'name',
+ 'model',
+ ...(config.model === BatchExportModelEnumApi.Hogql ? ['hogql_query'] : []),
+ ]
if (!service) {
return generalRequiredFields
}
@@ -1035,50 +1029,7 @@ export const batchExportConfigFormLogic = kea<batchExportConfigFormLogicType>([
},
],
})),
- listeners(({ props, values, actions }) => ({
- updateBatchExportConfig: async ({ formdata }) => {
- const interval = formdata.interval
- const data: Omit<BatchExportConfiguration, 'id' | 'team_id' | 'created_at' | 'start_at' | 'end_at'> = {
- paused: formdata.paused,
- name: formdata.name,
- interval,
- timezone: interval === 'day' || interval === 'week' ? formdata.timezone : null,
- offset_day: interval === 'week' ? formdata.offset_day : null,
- offset_hour: interval === 'day' || interval === 'week' ? formdata.offset_hour : null,
- model: formdata.model,
- filters: formdata.filters,
- destination: buildDestinationPayload(formdata) as any,
- } as any
-
- try {
- if (props.id) {
- const res = await api.batchExports.update(props.id, data)
- lemonToast.success('Batch export configuration updated successfully')
- void addProductIntent({
- product_type: ProductKey.PIPELINE_BATCH_EXPORTS,
- intent_context: ProductIntentContext.BATCH_EXPORT_UPDATED,
- })
- actions.setBatchExportConfig(res)
- actions.updateBatchExportConfigSuccess(res)
- return
- }
- const res = await api.batchExports.create(data)
- actions.resetConfiguration(getConfigurationFromBatchExportConfig(res))
-
- void addProductIntent({
- product_type: ProductKey.PIPELINE_BATCH_EXPORTS,
- intent_context: ProductIntentContext.BATCH_EXPORT_CREATED,
- })
-
- router.actions.replace(urls.batchExport(res.id))
- lemonToast.success('Batch export created successfully')
- actions.updateBatchExportConfigSuccess(res)
- } catch (error: any) {
- // Not rethrown, matching `deleteBatchExport` below: the unsaved values stay on the
- // form either way, and a rejecting listener escapes kea as an unhandled rejection.
- lemonToast.error(error.detail || error.message || 'Could not save the batch export. Try again.')
- }
- },
+ listeners(({ values, actions }) => ({
updateBatchExportConfigSuccess: ({ batchExportConfig }) => {
if (!batchExportConfig) {
return
@@ -1144,6 +1095,16 @@ export const batchExportConfigFormLogic = kea<batchExportConfigFormLogicType>([
setConfigurationValue: ({ name, value }) => {
const fieldName = Array.isArray(name) ? name[0] : name
+ // kea-forms keeps a manual error until the field is touched, and a manual error blocks submitting.
+ // A save error describes the old value, so it must not outlive an edit.
+ if (fieldName in values.configurationManualErrors) {
+ actions.touchConfigurationField(String(fieldName))
+ }
+ // Other models do not send the query, so its save error must not block them while the field is hidden
+ if (fieldName === 'model' && 'hogql_query' in values.configurationManualErrors) {
+ actions.touchConfigurationField('hogql_query')
+ }
+
if (fieldName === 'file_format') {
// Pick a compression that's valid for the newly-selected format, in priority order:
// 1. keep the current codec if it still fits (e.g. gzip works for both formats);
@@ -1205,7 +1166,7 @@ export const batchExportConfigFormLogic = kea<batchExportConfigFormLogicType>([
}
},
})),
- forms(({ asyncActions, values }) => ({
+ forms(({ actions, props, values }) => ({
configuration: {
errors: (formdata) => {
const requiredFieldErrors = Object.fromEntries(
@@ -1227,6 +1188,13 @@ export const batchExportConfigFormLogic = kea<batchExportConfigFormLogicType>([
errors[field] = message
}
}
+ if (
+ formdata.model === BatchExportModelEnumApi.Hogql &&
+ splitQueries(formdata.hogql_query ?? '').length > 1
+ ) {
+ errors.hogql_query =
+ 'A batch export runs a single query. Remove the extra statements separated by semicolons.'
+ }
return errors
},
submit: async (formdata) => {
@@ -1277,7 +1245,40 @@ export const batchExportConfigFormLogic = kea<batchExportConfigFormLogicType>([
}
}
- await asyncActions.updateBatchExportConfig(formdata)
+ const data = buildBatchExportPayload(formdata)
+
+ try {
+ if (props.id) {
+ const res = await api.batchExports.update(props.id, data)
+ lemonToast.success('Batch export configuration updated successfully')
+ void addProductIntent({
+ product_type: ProductKey.PIPELINE_BATCH_EXPORTS,
+ intent_context: ProductIntentContext.BATCH_EXPORT_UPDATED,
+ })
+ actions.setBatchExportConfig(res)
+ actions.updateBatchExportConfigSuccess(res)
+ return
+ }
+ const res = await api.batchExports.create(data)
+ actions.resetConfiguration(getConfigurationFromBatchExportConfig(res))
+
+ void addProductIntent({
+ product_type: ProductKey.PIPELINE_BATCH_EXPORTS,
+ intent_context: ProductIntentContext.BATCH_EXPORT_CREATED,
+ })
+
+ router.actions.replace(urls.batchExport(res.id))
+ lemonToast.success('Batch export created successfully')
+ actions.updateBatchExportConfigSuccess(res)
+ } catch (error: any) {
+ lemonToast.error(error.detail || error.message || 'Could not save the batch export. Try again.')
+ // The toast can be far from the field at fault, such as the query editor, so the error also shows under it
+ if (error.attr && error.detail && error.attr in values.configuration) {
+ actions.setConfigurationManualErrors({ [error.attr]: error.detail })
+ }
+ // kea-forms hides form errors after a successful submit, so a failed save has to fail the submit
+ throw error
+ }
},
},
})),
diff --git a/frontend/src/scenes/data-pipelines/batch-exports/batchExportHogQLQueryLogic.test.ts b/frontend/src/scenes/data-pipelines/batch-exports/batchExportHogQLQueryLogic.test.ts
new file mode 100644
index 000000000000..7402411acf01
--- /dev/null
+++ b/frontend/src/scenes/data-pipelines/batch-exports/batchExportHogQLQueryLogic.test.ts
@@ -0,0 +1,120 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'
+import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { BatchExportConfiguration } from '~/types'
+
+import { BatchExportConfigFormLogicProps, batchExportConfigFormLogic } from './batchExportConfigFormLogic'
+import { batchExportHogQLEditorTabId, batchExportHogQLQueryLogic } from './batchExportHogQLQueryLogic'
+
+const EXPORT_ID = 'test-hogql-export-id'
+const PROPS: BatchExportConfigFormLogicProps = { id: EXPORT_ID, service: null }
+
+function hogqlExport(): BatchExportConfiguration {
+ return {
+ id: EXPORT_ID,
+ team_id: 997,
+ name: 'HogQL export',
+ destination: {
+ type: 'AwsS3',
+ integration: 31,
+ config: {
+ bucket_name: 'test-bucket',
+ region: 'us-east-1',
+ prefix: 'exports/',
+ exclude_events: [],
+ include_events: [],
+ compression: 'zstd',
+ encryption: null,
+ kms_key_id: null,
+ file_format: 'Parquet',
+ max_file_size_mb: null,
+ },
+ } as BatchExportConfiguration['destination'],
+ interval: 'hour',
+ timezone: null,
+ offset_day: null,
+ offset_hour: null,
+ created_at: '2024-01-01T00:00:00Z',
+ start_at: null,
+ end_at: null,
+ paused: false,
+ model: 'hogql',
+ hogql_query: 'SELECT event FROM events WHERE timestamp >= {data_interval_start}',
+ filters: [],
+ }
+}
+
+describe('batchExportHogQLQueryLogic', () => {
+ let logic: ReturnType<typeof batchExportHogQLQueryLogic.build>
+ let formLogic: ReturnType<typeof batchExportConfigFormLogic.build>
+
+ const editorLogic = (props: BatchExportConfigFormLogicProps = PROPS): ReturnType<typeof sqlEditorLogic.build> =>
+ sqlEditorLogic({ tabId: batchExportHogQLEditorTabId(props), mode: SQLEditorMode.Embedded })
+
+ async function initLogic(props: BatchExportConfigFormLogicProps = PROPS): Promise<void> {
+ formLogic = batchExportConfigFormLogic(props)
+ formLogic.mount()
+ await expectLogic(formLogic).toFinishAllListeners()
+ logic = batchExportHogQLQueryLogic(props)
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ }
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ [`/api/environments/:team_id/batch_exports/${EXPORT_ID}`]: hogqlExport(),
+ '/api/environments/:team_id/batch_exports/test': { steps: [] },
+ '/api/projects/:team_id/integrations/': { count: 0, results: [] },
+ },
+ })
+ initKeaTests()
+ })
+
+ // The form saves `hogql_query`, so it must match what the editor shows. A form reset, such as "Clear changes",
+ // must also reach the editor, or the editor keeps text that the form no longer holds.
+ it('copies editor changes into the form', async () => {
+ await initLogic()
+
+ editorLogic().actions.setQueryInput('SELECT 2')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(formLogic.values.configuration.hogql_query).toEqual('SELECT 2')
+ })
+
+ it('restores the editor when the form resets', async () => {
+ await initLogic()
+ editorLogic().actions.setQueryInput('SELECT 2')
+ await expectLogic(logic).toFinishAllListeners()
+
+ formLogic.actions.resetConfiguration(formLogic.values.savedConfiguration)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(editorLogic().values.queryInput).toEqual(hogqlExport().hogql_query)
+ })
+
+ it('gives the editor preview values that follow the schedule', async () => {
+ await initLogic()
+ const hourlyPlaceholders = editorLogic().values.placeholders
+ expect(hourlyPlaceholders).toEqual(logic.values.placeholders)
+
+ formLogic.actions.setConfigurationValue('interval', 'day')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(editorLogic().values.placeholders).toEqual(logic.values.placeholders)
+ expect(editorLogic().values.placeholders).not.toEqual(hourlyPlaceholders)
+ })
+
+ it('starts a new export with the default query in both the editor and the form', async () => {
+ const newExportProps: BatchExportConfigFormLogicProps = { id: null, service: 'AwsS3' }
+ await initLogic(newExportProps)
+
+ const queryInput = editorLogic(newExportProps).values.queryInput
+ expect(queryInput).toContain('{data_interval_start}')
+ expect(formLogic.values.configuration.hogql_query).toEqual(queryInput)
+ })
+})
diff --git a/frontend/src/scenes/data-pipelines/batch-exports/batchExportHogQLQueryLogic.ts b/frontend/src/scenes/data-pipelines/batch-exports/batchExportHogQLQueryLogic.ts
new file mode 100644
index 000000000000..fbb5616f4032
--- /dev/null
+++ b/frontend/src/scenes/data-pipelines/batch-exports/batchExportHogQLQueryLogic.ts
@@ -0,0 +1,284 @@
+import {
+ LogicWrapper,
+ MakeLogicType,
+ afterMount,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ selectors,
+ sharedListeners,
+} from 'kea'
+import type { BreakPointFunction } from 'kea'
+import { subscriptions } from 'kea-subscriptions'
+
+import { dayjs } from 'lib/dayjs'
+import { queryUsesPlaceholder } from 'scenes/data-warehouse/editor/sql-utils'
+import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'
+import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'
+import { SQLEditorPlaceholder } from 'scenes/data-warehouse/editor/sqlEditorPlaceholders'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { NodeKind } from '~/queries/schema/schema-general'
+import { BatchExportInterval, ChartDisplayType } from '~/types'
+
+import { BatchExportConfigFormLogicProps, batchExportConfigFormLogic } from './batchExportConfigFormLogic'
+import { BatchExportDataInterval, lastCompleteDataInterval } from './utils'
+
+export const DATA_INTERVAL_START_PLACEHOLDER = 'data_interval_start'
+export const DATA_INTERVAL_END_PLACEHOLDER = 'data_interval_end'
+
+const DEFAULT_HOGQL_QUERY = `SELECT
+ uuid,
+ event,
+ timestamp,
+ distinct_id,
+ properties,
+ properties.$current_url AS current_url
+FROM events
+WHERE timestamp >= {${DATA_INTERVAL_START_PLACEHOLDER}}
+ AND timestamp < {${DATA_INTERVAL_END_PLACEHOLDER}}`
+
+// ClickHouse cannot parse a datetime string with a UTC offset.
+const PLACEHOLDER_VALUE_FORMAT = 'YYYY-MM-DD HH:mm:ss'
+
+export function batchExportHogQLEditorTabId({ id, service }: BatchExportConfigFormLogicProps): string {
+ return `batch-export-hogql-${id ?? `new-${service}`}`
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface batchExportHogQLQueryLogicValues {
+ configuration: Record<string, any> // batchExportConfigFormLogic
+ queryInput: string | null // sqlEditorLogic
+ projectTimezone: string // teamLogic
+ placeholders: SQLEditorPlaceholder[]
+ previewEnd: string
+ previewInterval: BatchExportDataInterval
+ previewStart: string
+ scheduleInterval: BatchExportInterval
+ scheduleOffsetDay: number | null
+ scheduleOffsetHour: number | null
+ scheduleTimezone: string | null
+ usesIntervalPlaceholders: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface batchExportHogQLQueryLogicActions {
+ loadBatchExportConfigSuccess: (
+ batchExportConfig: null | import('~/types').BatchExportConfiguration,
+ payload?: any
+ ) => {
+ batchExportConfig: null | import('~/types').BatchExportConfiguration
+ payload?: any
+ } // batchExportConfigFormLogic
+ resetConfiguration: (values?: Record<string, any> | undefined) => {
+ values?: Record<string, any>
+ } // batchExportConfigFormLogic
+ setConfigurationValue: (
+ key: import('node_modules/kea-forms/lib').FieldName,
+ value: any
+ ) => {
+ name: import('node_modules/kea-forms/lib').FieldName
+ value: any
+ } // batchExportConfigFormLogic
+ setConfigurationValues: (values: import('node_modules/kea-forms/lib').DeepPartial<Record<string, any>>) => {
+ values: import('node_modules/kea-forms/lib').DeepPartial<Record<string, any>>
+ } // batchExportConfigFormLogic
+ updateBatchExportConfigSuccess: (batchExportConfig: import('~/types').BatchExportConfiguration) => {
+ batchExportConfig: import('~/types').BatchExportConfiguration
+ } // batchExportConfigFormLogic
+ setPlaceholders: (placeholders: SQLEditorPlaceholder[]) => {
+ placeholders: SQLEditorPlaceholder[]
+ } // sqlEditorLogic
+ setQueryInput: (queryInput: string | null) => {
+ queryInput: string | null
+ } // sqlEditorLogic
+ setSourceQuery: (sourceQuery: import('~/queries/schema/schema-general').DataVisualizationNode) => {
+ sourceQuery: import('~/queries/schema/schema-general').DataVisualizationNode
+ } // sqlEditorLogic
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface batchExportHogQLQueryLogicMeta {
+ key: string
+ sharedListeners: {
+ syncFormToEditor: (
+ payload: any,
+ breakpoint: BreakPointFunction,
+ action: {
+ type: string
+ payload: any
+ },
+ previousState: any
+ ) => void | Promise<void>
+ }
+ __keaTypeGenInternalSelectorTypes: {
+ scheduleInterval: (configuration: Record<string, any>) => BatchExportInterval
+ scheduleTimezone: (configuration: Record<string, any>) => string | null
+ scheduleOffsetDay: (configuration: Record<string, any>) => number | null
+ scheduleOffsetHour: (configuration: Record<string, any>) => number | null
+ previewInterval: (
+ scheduleInterval: BatchExportInterval,
+ scheduleTimezone: string | null,
+ scheduleOffsetDay: number | null,
+ scheduleOffsetHour: number | null,
+ projectTimezone: string
+ ) => BatchExportDataInterval
+ previewStart: (previewInterval: BatchExportDataInterval, projectTimezone: string) => string
+ previewEnd: (previewInterval: BatchExportDataInterval, projectTimezone: string) => string
+ placeholders: (previewStart: string, previewEnd: string) => SQLEditorPlaceholder[]
+ usesIntervalPlaceholders: (queryInput: string | null) => boolean
+ }
+}
+
+export type batchExportHogQLQueryLogicType = MakeLogicType<
+ batchExportHogQLQueryLogicValues,
+ batchExportHogQLQueryLogicActions,
+ BatchExportConfigFormLogicProps,
+ batchExportHogQLQueryLogicMeta
+>
+
+// Keeps the embedded SQL editor and the form's `hogql_query` in step, and gives the editor the
+// interval placeholders with preview values for the export's schedule.
+export const batchExportHogQLQueryLogic: LogicWrapper<batchExportHogQLQueryLogicType> =
+ kea<batchExportHogQLQueryLogicType>([
+ props({ id: null, service: null } as BatchExportConfigFormLogicProps),
+ key(({ service, id }: BatchExportConfigFormLogicProps) => (id ? `ID:${id}` : `NEW:${service}`)),
+ path((key) => ['scenes', 'data-pipelines', 'batch-exports', 'batchExportHogQLQueryLogic', key]),
+ connect((props: BatchExportConfigFormLogicProps) => ({
+ values: [
+ batchExportConfigFormLogic(props),
+ ['configuration'],
+ teamLogic,
+ ['timezone as projectTimezone'],
+ sqlEditorLogic({ tabId: batchExportHogQLEditorTabId(props), mode: SQLEditorMode.Embedded }),
+ ['queryInput'],
+ ],
+ actions: [
+ batchExportConfigFormLogic(props),
+ [
+ 'setConfigurationValue',
+ 'setConfigurationValues',
+ 'resetConfiguration',
+ 'loadBatchExportConfigSuccess',
+ 'updateBatchExportConfigSuccess',
+ ],
+ sqlEditorLogic({ tabId: batchExportHogQLEditorTabId(props), mode: SQLEditorMode.Embedded }),
+ ['setQueryInput', 'setSourceQuery', 'setPlaceholders'],
+ ],
+ })),
+ selectors({
+ scheduleInterval: [
+ (s) => [s.configuration],
+ (configuration: Record<string, any>): BatchExportInterval => configuration.interval ?? 'hour',
+ ],
+ scheduleTimezone: [
+ (s) => [s.configuration],
+ (configuration: Record<string, any>): string | null => configuration.timezone ?? null,
+ ],
+ scheduleOffsetDay: [
+ (s) => [s.configuration],
+ (configuration: Record<string, any>): number | null => configuration.offset_day ?? null,
+ ],
+ scheduleOffsetHour: [
+ (s) => [s.configuration],
+ (configuration: Record<string, any>): number | null => configuration.offset_hour ?? null,
+ ],
+ previewInterval: [
+ (s) => [
+ s.scheduleInterval,
+ s.scheduleTimezone,
+ s.scheduleOffsetDay,
+ s.scheduleOffsetHour,
+ s.projectTimezone,
+ ],
+ (
+ interval: BatchExportInterval,
+ scheduleTimezone: string | null,
+ offsetDay: number | null,
+ offsetHour: number | null,
+ projectTimezone: string
+ ): BatchExportDataInterval => {
+ const scheduleUsesTimezone = interval === 'day' || interval === 'week'
+ return lastCompleteDataInterval({
+ interval,
+ now: dayjs(),
+ timezone: scheduleUsesTimezone ? scheduleTimezone || projectTimezone : 'UTC',
+ offsetDay,
+ offsetHour,
+ })
+ },
+ ],
+ // HogQL reads these strings as times in the project timezone, so convert the bounds to it first.
+ previewStart: [
+ (s) => [s.previewInterval, s.projectTimezone],
+ (previewInterval: BatchExportDataInterval, projectTimezone: string): string =>
+ previewInterval.start.tz(projectTimezone).format(PLACEHOLDER_VALUE_FORMAT),
+ ],
+ previewEnd: [
+ (s) => [s.previewInterval, s.projectTimezone],
+ (previewInterval: BatchExportDataInterval, projectTimezone: string): string =>
+ previewInterval.end.tz(projectTimezone).format(PLACEHOLDER_VALUE_FORMAT),
+ ],
+ placeholders: [
+ (s) => [s.previewStart, s.previewEnd],
+ (previewStart: string, previewEnd: string): SQLEditorPlaceholder[] => [
+ {
+ name: DATA_INTERVAL_START_PLACEHOLDER,
+ description: 'Start of the time range a run exports. Rows at or after this time are included.',
+ previewValue: previewStart,
+ },
+ {
+ name: DATA_INTERVAL_END_PLACEHOLDER,
+ description: 'End of the time range a run exports. Rows before this time are included.',
+ previewValue: previewEnd,
+ },
+ ],
+ ],
+ usesIntervalPlaceholders: [
+ (s) => [s.queryInput],
+ (queryInput: string | null): boolean =>
+ queryInput === null ||
+ queryUsesPlaceholder(queryInput, DATA_INTERVAL_START_PLACEHOLDER) ||
+ queryUsesPlaceholder(queryInput, DATA_INTERVAL_END_PLACEHOLDER),
+ ],
+ }),
+ sharedListeners(({ actions, values }) => ({
+ syncFormToEditor: () => {
+ const formQuery: string = values.configuration.hogql_query ?? ''
+ // An empty form query means the config has not loaded yet, so keep what the editor has
+ if (values.queryInput !== null && formQuery && formQuery !== values.queryInput) {
+ actions.setQueryInput(formQuery)
+ }
+ },
+ })),
+ listeners(({ actions, values, sharedListeners }) => ({
+ setQueryInput: ({ queryInput }) => {
+ if (queryInput !== null && queryInput !== values.configuration.hogql_query) {
+ actions.setConfigurationValue('hogql_query', queryInput)
+ }
+ },
+ // Each listener writes only when the two sides differ, so a write settles instead of bouncing back
+ resetConfiguration: sharedListeners.syncFormToEditor,
+ setConfigurationValues: sharedListeners.syncFormToEditor,
+ loadBatchExportConfigSuccess: sharedListeners.syncFormToEditor,
+ updateBatchExportConfigSuccess: sharedListeners.syncFormToEditor,
+ })),
+ subscriptions(({ actions }) => ({
+ placeholders: (placeholders: SQLEditorPlaceholder[]) => actions.setPlaceholders(placeholders),
+ })),
+ afterMount(({ actions, values }) => {
+ if (values.queryInput !== null) {
+ return
+ }
+ const initialQuery = values.configuration.hogql_query || DEFAULT_HOGQL_QUERY
+ actions.setQueryInput(initialQuery)
+ actions.setSourceQuery({
+ kind: NodeKind.DataVisualizationNode,
+ source: { kind: NodeKind.HogQLQuery, query: initialQuery },
+ display: ChartDisplayType.ActionsTable,
+ })
+ }),
+ ])
diff --git a/frontend/src/scenes/data-pipelines/batch-exports/utils.test.ts b/frontend/src/scenes/data-pipelines/batch-exports/utils.test.ts
index 9e42717630c8..620cc80b83a4 100644
--- a/frontend/src/scenes/data-pipelines/batch-exports/utils.test.ts
+++ b/frontend/src/scenes/data-pipelines/batch-exports/utils.test.ts
@@ -1,6 +1,8 @@
import { dayjs } from 'lib/dayjs'
-import { compareBatchExportScheduleStatus, getBatchExportScheduleStatus } from './utils'
+import { BatchExportInterval } from '~/types'
+
+import { compareBatchExportScheduleStatus, getBatchExportScheduleStatus, lastCompleteDataInterval } from './utils'
const PAST = dayjs().subtract(1, 'day').toISOString()
const FUTURE = dayjs().add(1, 'day').toISOString()
@@ -22,4 +24,57 @@ describe('batch export utils', () => {
expect([paused, ended, active].sort(compareBatchExportScheduleStatus)).toEqual([active, ended, paused])
})
+
+ // `now` is a Wednesday at 14:37 UTC unless a row sets its own. The SQL editor previews a HogQL export over this
+ // interval. The Los Angeles rows sit on DST changes, where a boundary must stay at the same local hour.
+ it.each<[BatchExportInterval, string, number | null, number | null, string, string, string?]>([
+ ['hour', 'UTC', null, null, '2026-09-30T13:00:00.000Z', '2026-09-30T14:00:00.000Z'],
+ ['every 5 minutes', 'UTC', null, null, '2026-09-30T14:30:00.000Z', '2026-09-30T14:35:00.000Z'],
+ ['every 15 minutes', 'UTC', null, null, '2026-09-30T14:15:00.000Z', '2026-09-30T14:30:00.000Z'],
+ ['day', 'UTC', null, 0, '2026-09-29T00:00:00.000Z', '2026-09-30T00:00:00.000Z'],
+ ['day', 'America/New_York', null, 3, '2026-09-29T07:00:00.000Z', '2026-09-30T07:00:00.000Z'],
+ ['day', 'UTC', null, 23, '2026-09-28T23:00:00.000Z', '2026-09-29T23:00:00.000Z'],
+ ['week', 'UTC', 1, 5, '2026-09-21T05:00:00.000Z', '2026-09-28T05:00:00.000Z'],
+ ['week', 'UTC', 5, 0, '2026-09-18T00:00:00.000Z', '2026-09-25T00:00:00.000Z'],
+ [
+ 'day',
+ 'America/Los_Angeles',
+ null,
+ 3,
+ '2025-03-08T11:00:00.000Z',
+ '2025-03-09T10:00:00.000Z',
+ '2025-03-09T15:00:00Z',
+ ],
+ [
+ 'week',
+ 'America/Los_Angeles',
+ 1,
+ 3,
+ '2025-03-03T11:00:00.000Z',
+ '2025-03-10T10:00:00.000Z',
+ '2025-03-11T15:00:00Z',
+ ],
+ [
+ 'day',
+ 'America/Los_Angeles',
+ null,
+ 3,
+ '2025-11-01T10:00:00.000Z',
+ '2025-11-02T11:00:00.000Z',
+ '2025-11-02T15:00:00Z',
+ ],
+ ])(
+ 'finds the last complete %s interval in %s with day offset %s and hour offset %s',
+ (interval, timezone, offsetDay, offsetHour, expectedStart, expectedEnd, now = '2026-09-30T14:37:12Z') => {
+ const { start, end } = lastCompleteDataInterval({
+ interval,
+ now: dayjs(now),
+ timezone,
+ offsetDay,
+ offsetHour,
+ })
+
+ expect([start.toISOString(), end.toISOString()]).toEqual([expectedStart, expectedEnd])
+ }
+ )
})
diff --git a/frontend/src/scenes/data-pipelines/batch-exports/utils.ts b/frontend/src/scenes/data-pipelines/batch-exports/utils.ts
index 5b0c17aa33c3..7690dc78be15 100644
--- a/frontend/src/scenes/data-pipelines/batch-exports/utils.ts
+++ b/frontend/src/scenes/data-pipelines/batch-exports/utils.ts
@@ -1,4 +1,4 @@
-import { dayjs } from 'lib/dayjs'
+import { Dayjs, dayjs } from 'lib/dayjs'
import type { LemonTagType } from 'lib/lemon-ui/LemonTag'
import { capitalizeFirstLetter } from 'lib/utils/strings'
@@ -184,3 +184,66 @@ export function statusToProgressStrokeColor(status: BatchExportStatus): string {
return 'var(--color-border-primary)'
}
}
+
+export interface BatchExportDataInterval {
+ start: Dayjs
+ end: Dayjs
+}
+
+export function lastCompleteDataInterval({
+ interval,
+ now,
+ timezone,
+ offsetDay,
+ offsetHour,
+}: {
+ interval: BatchExportInterval
+ now: Dayjs
+ timezone: string
+ offsetDay: number | null
+ offsetHour: number | null
+}): BatchExportDataInterval {
+ const zonedNow = now.tz(timezone)
+ // Day.js arithmetic keeps the UTC offset, which is wrong after a DST change. Daily and weekly
+ // boundaries are local times, so each one is read again in the timezone.
+ const atLocalTime = (date: Dayjs): Dayjs => dayjs.tz(date.format('YYYY-MM-DDTHH:mm:ss'), timezone)
+ let end: Dayjs
+ let size: 'minute' | 'hour' | 'day' | 'week'
+ let step = 1
+
+ switch (interval) {
+ case 'every 5 minutes':
+ case 'every 15 minutes':
+ step = interval === 'every 5 minutes' ? 5 : 15
+ size = 'minute'
+ end = zonedNow.startOf('minute').minute(Math.floor(zonedNow.minute() / step) * step)
+ break
+ case 'hour':
+ size = 'hour'
+ end = zonedNow.startOf('hour')
+ break
+ case 'day':
+ size = 'day'
+ end = atLocalTime(zonedNow.startOf('day').hour(offsetHour ?? 0))
+ break
+ case 'week':
+ size = 'week'
+ end = atLocalTime(
+ zonedNow
+ .startOf('day')
+ .subtract(zonedNow.day(), 'day')
+ .add(offsetDay ?? 0, 'day')
+ .hour(offsetHour ?? 0)
+ )
+ break
+ }
+
+ const previous = (boundary: Dayjs): Dayjs => {
+ const moved = boundary.subtract(step, size)
+ return size === 'day' || size === 'week' ? atLocalTime(moved) : moved
+ }
+ if (end.isAfter(zonedNow)) {
+ end = previous(end)
+ }
+ return { start: previous(end), end }
+}
diff --git a/frontend/src/scenes/data-warehouse/editor/sql-utils.test.ts b/frontend/src/scenes/data-warehouse/editor/sql-utils.test.ts
index a93832ae807b..1cc91044c4da 100644
--- a/frontend/src/scenes/data-warehouse/editor/sql-utils.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sql-utils.test.ts
@@ -3,6 +3,7 @@ import {
normalizeIdentifier,
parseQueryTablesAndColumns,
queryUsesFiltersPlaceholder,
+ queryUsesPlaceholder,
} from './sql-utils'
describe('sql-utils', () => {
@@ -37,6 +38,17 @@ describe('sql-utils', () => {
})
})
+ describe('queryUsesPlaceholder', () => {
+ test.each([
+ ['placeholder in code', 'SELECT * FROM events WHERE timestamp >= {start}', true],
+ ['line-commented placeholder', 'SELECT * FROM events -- WHERE timestamp >= {start}', false],
+ ['quoted placeholder', "SELECT '{start}' FROM events", false],
+ ['placeholder with a longer name', 'SELECT * FROM events WHERE timestamp >= {start_date}', false],
+ ])('%s', (_name, query, expected) => {
+ expect(queryUsesPlaceholder(query, 'start')).toBe(expected)
+ })
+ })
+
describe('filtersPlaceholderBindings', () => {
test.each([
['no placeholder', 'SELECT * FROM v', null],
diff --git a/frontend/src/scenes/data-warehouse/editor/sql-utils.ts b/frontend/src/scenes/data-warehouse/editor/sql-utils.ts
index f60f607530e2..52e4830532e3 100644
--- a/frontend/src/scenes/data-warehouse/editor/sql-utils.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sql-utils.ts
@@ -50,7 +50,8 @@ const skipNonCode = (query: string, i: number): number | null => {
return null
}
-export const queryUsesFiltersPlaceholder = (query: string | null): boolean => {
+// Whether any of `tokens` appears in the query outside string literals and comments.
+const queryContainsInCode = (query: string | null, tokens: string[]): boolean => {
if (!query) {
return false
}
@@ -63,11 +64,7 @@ export const queryUsesFiltersPlaceholder = (query: string | null): boolean => {
continue
}
- if (
- query.startsWith('{filters}', i) ||
- query.startsWith('{filters.', i) ||
- query.startsWith(FILTERS_BOUND_PREFIX, i)
- ) {
+ if (tokens.some((token) => query.startsWith(token, i))) {
return true
}
@@ -77,6 +74,12 @@ export const queryUsesFiltersPlaceholder = (query: string | null): boolean => {
return false
}
+export const queryUsesFiltersPlaceholder = (query: string | null): boolean =>
+ queryContainsInCode(query, ['{filters}', '{filters.', FILTERS_BOUND_PREFIX])
+
+export const queryUsesPlaceholder = (query: string | null, name: string): boolean =>
+ queryContainsInCode(query, [`{${name}}`])
+
const readBindingArgs = (query: string, start: number): { args: string[]; end: number } => {
const args: string[] = []
let current = ''
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 909534bf6428..27cd7aefa4b9 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -87,6 +87,7 @@ import { QueryContext } from '~/queries/types'
import type { ScopeObjectEnumApi } from 'products/access_control/frontend/generated/api.schemas'
import { AlertType } from 'products/alerts/frontend/types'
+import type { BatchExportApi } from 'products/batch_exports/frontend/generated/api.schemas'
import type { CohortRealtimeReadinessApi } from 'products/cohorts/frontend/generated/api.schemas'
import {
type LineageIssueApi,
@@ -7003,8 +7004,6 @@ export type DataWarehouseSyncInterval =
export type OrNever = 'never'
export type BatchExportConfiguration = {
- // User provided data for the export. This is the data that the user
- // provides when creating the export.
id: string
team_id: number
name: string
@@ -7018,6 +7017,7 @@ export type BatchExportConfiguration = {
end_at: string | null
paused: boolean
model: string
+ hogql_query?: BatchExportApi['hogql_query']
filters: AnyPropertyFilter[]
latest_runs?: BatchExportRun[]
}