: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-quality): add custom SQL query preview (#92893)
Thiago Salvatored2a82c8e296c
diff --git a/products/data_quality/frontend/CheckEditorModal.tsx b/products/data_quality/frontend/CheckEditorModal.tsxindex c43e58067283..c5c4a969a8ef 100644--- a/products/data_quality/frontend/CheckEditorModal.tsx+++ b/products/data_quality/frontend/CheckEditorModal.tsx@@ -13,7 +13,9 @@ import {Spinner,} from '@posthog/lemon-ui'+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import { LemonField } from 'lib/lemon-ui/LemonField'+import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { CodeEditorResizeable } from 'lib/monaco/CodeEditorResizable'import { urls } from 'scenes/urls'@@ -21,6 +23,7 @@ import type { DataQualitySubjectRef } from './checksApi'import { checkTypeLabel } from './checksConstants'import { dataQualityCheckEditorLogic } from './dataQualityCheckEditorLogic'import { CheckTypeEnumApi, DataQualityCheckSeverityEnumApi, SubjectTypeEnumApi } from './generated/api.schemas'+import { formatPreviewCell } from './previewCell'export function CheckEditorModal(): JSX.Element {const {@@ -254,28 +257,129 @@ function CheckConfigFields({ checkType }: { checkType: CheckTypeEnumApi }): JSX.</LemonField>)case CheckTypeEnumApi.CustomSql:- return (- <LemonField- name="customSql"- label="Query"- help="Return one row per failure. The check passes when the query returns nothing."- >- {({ value, onChange }) => (- <CodeEditorResizeable- language="hogQL"- value={value ?? ''}- onChange={(query) => onChange(query ?? '')}- minHeight="8rem"- maxHeight="40vh"- />- )}- </LemonField>- )+ return <CustomSqlField />default:return null}}+function CustomSqlField(): JSX.Element {+ const {+ customSqlEditorError,+ customSqlPreview,+ customSqlPreviewError,+ customSqlPreviewLoading,+ customSqlPreviewStale,+ customSqlPreviewVerdict,+ customSqlQueryKey,+ customSqlSourceQuery,+ } = useValues(dataQualityCheckEditorLogic)+ const { runCustomSqlPreview, setCustomSqlEditorError, setCustomSqlValidationLoading } =+ useActions(dataQualityCheckEditorLogic)++ const previewRows = customSqlPreview?.rows ?? []+ // Key and index by position, not by column name: HogQL can return two columns with the same name+ // (e.g. `SELECT id, id`), which would collide on an object key and on the React header key.+ const previewColumns: LemonTableColumns<unknown[]> =+ customSqlPreview?.columns.map((column, index) => ({+ title: column,+ key: String(index),+ dataIndex: index,+ // Never hand a raw object to LemonTable: it would spread the value's `props` onto the cell.+ render: (value: unknown) => formatPreviewCell(value),+ })) ?? []++ return (+ <LemonField+ name="customSql"+ label="Query"+ help="Return one row per failure. The check passes when the query returns nothing."+ >+ {({ value, onChange }) => (+ <div className="flex flex-col gap-2">+ <CodeEditorResizeable+ language="hogQL"+ value={value ?? ''}+ onChange={(query) => onChange(query ?? '')}+ queryKey={customSqlQueryKey}+ sourceQuery={customSqlSourceQuery}+ onError={setCustomSqlEditorError}+ onMetadataLoading={setCustomSqlValidationLoading}+ onPressCmdEnter={() => runCustomSqlPreview(undefined)}+ autoFocus+ minHeight="8rem"+ maxHeight="40vh"+ />+ <div className="flex flex-col items-end gap-1">+ <LemonButton+ type="secondary"+ size="small"+ loading={customSqlPreviewLoading}+ disabledReason={+ !value?.trim()+ ? 'Write a query before testing it.'+ : (customSqlEditorError ?? undefined)+ }+ onClick={runCustomSqlPreview}+ data-attr="data-quality-check-test-query"+ >+ Test query+ </LemonButton>+ {customSqlPreviewStale && (+ <span className="text-secondary text-xs">The query changed since the last test.</span>+ )}+ </div>+ {customSqlPreviewError ? (+ <LemonBanner type="error">{customSqlPreviewError}</LemonBanner>+ ) : !customSqlPreviewLoading && customSqlPreview && customSqlPreviewVerdict ? (+ <div className={customSqlPreviewStale ? 'opacity-60' : undefined}>+ {customSqlPreview.warnings.length > 0 && (+ <LemonBanner type="warning" className="mb-2">+ This result may be incomplete or out of date:+ <ul className="list-disc pl-5">+ {customSqlPreview.warnings.map((warning, index) => (+ <li key={index}>{warning.message}</li>+ ))}+ </ul>+ </LemonBanner>+ )}+ {customSqlPreviewVerdict === 'pass' ? (+ <LemonBanner type="success">+ The query returned no rows. This check would pass.+ </LemonBanner>+ ) : (+ <>+ <LemonBanner type="warning">+ The query returned {customSqlPreview.hasMore ? 'at least ' : ''}+ {customSqlPreview.rowCount} rows. This check would fail with{' '}+ {customSqlPreview.hasMore ? 'at least ' : ''}+ {customSqlPreview.rowCount} failures.+ </LemonBanner>+ <LemonTable<unknown[]>+ className="mt-2"+ columns={previewColumns}+ dataSource={previewRows}+ size="small"+ />+ {/* The table caps at 10 rows: flag truncation only when 10 are shown and the+ response held more, or the query system reported more beyond them. */}+ {previewRows.length === 10 &&+ (customSqlPreview.hasMore ||+ customSqlPreview.rowCount > previewRows.length) && (+ <span className="mt-1 text-secondary text-xs">+ Showing the first 10 rows.+ </span>+ )}+ </>+ )}+ </div>+ ) : null}+ </div>+ )}+ </LemonField>+ )+}+function RelationshipFields(): JSX.Element {const { checkForm, relationshipSubjects, databaseLoading } = useValues(dataQualityCheckEditorLogic)const { setCheckFormValues } = useActions(dataQualityCheckEditorLogic)diff --git a/products/data_quality/frontend/dataQualityCheckEditorLogic.test.ts b/products/data_quality/frontend/dataQualityCheckEditorLogic.test.tsindex 300589eb00f9..b7799c85c0a8 100644--- a/products/data_quality/frontend/dataQualityCheckEditorLogic.test.ts+++ b/products/data_quality/frontend/dataQualityCheckEditorLogic.test.ts@@ -3,6 +3,7 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'+import { performQuery } from '~/queries/query'import { initKeaTests } from '~/test/init'import { expectLogic } from '~/test/keaTestUtils'@@ -53,6 +54,10 @@ jest.mock('lib/lemon-ui/LemonDialog', () => ({LemonDialog: { open: jest.fn() },}))+jest.mock('~/queries/query', () => ({+ performQuery: jest.fn(),+}))+// A real logic rather than a stub: the editor connects the catalog's values, and `loadCount` is how// these tests see whether it asked for them.jest.mock('scenes/data-management/database/databaseTableListLogic', () => {@@ -298,6 +303,160 @@ describe('dataQualityCheckEditorLogic', () => {expect(warehouseSavedQueriesChecksCreate).toHaveBeenCalledTimes(1)})+ it('shows a stale failing preview until the custom SQL is tested again', async () => {+ ;(performQuery as jest.Mock).mockResolvedValue({+ columns: ['order_id'],+ results: [['order-1']],+ hasMore: false,+ })+ await mountLogic()+ await openWith(null, { checkType: 'custom_sql', customSql: 'SELECT order_id FROM orders' })++ await expectLogic(logic, () => logic.actions.runCustomSqlPreview(undefined))+ .toDispatchActions(['runCustomSqlPreviewSuccess'])+ .toFinishAllListeners()++ expect(logic.values.customSqlPreviewVerdict).toEqual('fail')+ expect(logic.values.customSqlPreviewStale).toBe(false)++ logic.actions.setCheckFormValue('customSql', "SELECT order_id FROM orders WHERE status = 'failed'")++ expect(logic.values.customSqlPreviewStale).toBe(true)++ ;(performQuery as jest.Mock).mockResolvedValueOnce({ columns: [], results: [], hasMore: false })+ await expectLogic(logic, () => logic.actions.runCustomSqlPreview(undefined))+ .toDispatchActions(['runCustomSqlPreviewSuccess'])+ .toFinishAllListeners()++ expect(logic.values.customSqlPreviewVerdict).toEqual('pass')+ expect(logic.values.customSqlPreviewStale).toBe(false)+ })++ it('forces a fresh calculation for the custom SQL preview so it cannot serve cached data', async () => {+ ;(performQuery as jest.Mock).mockResolvedValue({ columns: [], results: [], hasMore: false })+ await mountLogic()+ await openWith(null, { checkType: 'custom_sql', customSql: 'SELECT order_id FROM orders' })++ await expectLogic(logic, () => logic.actions.runCustomSqlPreview(undefined))+ .toDispatchActions(['runCustomSqlPreviewSuccess'])+ .toFinishAllListeners()++ const refresh = (performQuery as jest.Mock).mock.calls.at(-1)?.[2]+ expect(refresh).toEqual('force_blocking')+ })++ it('carries warehouse-sync warnings onto the preview so a pass is not shown as final', async () => {+ // A query over a source whose last sync failed can still return zero rows, which would+ // otherwise read as a confident pass over data the platform already knows is behind.+ ;(performQuery as jest.Mock).mockResolvedValue({+ columns: [],+ results: [],+ hasMore: false,+ warnings: [+ {+ type: 'warehouse_sync',+ table_name: 'stripe_charges',+ schema_name: 'charges',+ source_type: 'Stripe',+ status: 'Failed',+ message: 'The Stripe charges sync last failed, so this data may be behind.',+ },+ ],+ })+ await mountLogic()+ await openWith(null, { checkType: 'custom_sql', customSql: 'SELECT id FROM stripe_charges WHERE amount < 0' })++ await expectLogic(logic, () => logic.actions.runCustomSqlPreview(undefined))+ .toDispatchActions(['runCustomSqlPreviewSuccess'])+ .toFinishAllListeners()++ expect(logic.values.customSqlPreviewVerdict).toEqual('pass')+ expect(logic.values.customSqlPreview?.warnings).toEqual([+ expect.objectContaining({+ type: 'warehouse_sync',+ message: 'The Stripe charges sync last failed, so this data may be behind.',+ }),+ ])+ })++ it('clears a custom SQL preview error when the query changes', async () => {+ ;(performQuery as jest.Mock).mockRejectedValue({ detail: 'Unknown table' })+ await mountLogic()+ await openWith(null, { checkType: 'custom_sql', customSql: 'SELECT * FROM missing' })++ await expectLogic(logic, () => logic.actions.runCustomSqlPreview(undefined))+ .toDispatchActions(['runCustomSqlPreviewFailure'])+ .toFinishAllListeners()++ expect(logic.values.customSqlPreviewError).toEqual('Unknown table')++ logic.actions.setCheckFormValue('customSql', 'SELECT 1')++ expect(logic.values.customSqlPreviewError).toBeNull()+ })++ it('drops a superseded preview so a late failure keeps the newer result', async () => {+ // Cmd+Enter can start a second preview while the first is still running. If the older+ // request then fails, its error must not replace the newer request's good result.+ let failFirst: (error: unknown) => void = () => {}+ ;(performQuery as jest.Mock)+ .mockImplementationOnce(() => new Promise((_resolve, reject) => (failFirst = reject)))+ .mockResolvedValueOnce({ columns: [], results: [], hasMore: false })++ await mountLogic()+ await openWith(null, { checkType: 'custom_sql', customSql: 'SELECT order_id FROM orders' })++ // First request stays pending; the second supersedes it and passes. Do not wait for all+ // listeners here — the first request is meant to still be in flight.+ logic.actions.runCustomSqlPreview(undefined)+ await expectLogic(logic, () => logic.actions.runCustomSqlPreview(undefined)).toDispatchActions([+ 'runCustomSqlPreviewSuccess',+ ])++ expect(logic.values.customSqlPreviewVerdict).toEqual('pass')++ // The stale first request fails last; the breakpoint must swallow it, not show an error.+ failFirst({ detail: 'Unknown table' })+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.customSqlPreviewError).toBeNull()+ expect(logic.values.customSqlPreviewVerdict).toEqual('pass')+ })++ it('blocks saving custom SQL with a Monaco validation error', async () => {+ await mountLogic()+ await openWith(null, { checkType: 'custom_sql', customSql: 'SELECT * FROM orders' })++ logic.actions.setCustomSqlEditorError('Unknown table')+ logic.actions.submitCheckForm()+ await expectLogic(logic).toFinishAllListeners()++ expect(warehouseSavedQueriesChecksCreate).not.toHaveBeenCalled()+ expect(logic.values.checkFormErrors.customSql).toEqual('Unknown table')+ })++ it('blocks saving custom SQL until Monaco validates an edited query', async () => {+ await mountLogic()+ await openWith(null, { checkType: 'custom_sql', customSql: 'SELECT * FROM orders' })++ logic.actions.setCheckFormValue('customSql', 'SELECT * FROM orders WHERE missing_column = 1')+ logic.actions.submitCheckForm()+ await expectLogic(logic).toFinishAllListeners()++ expect(warehouseSavedQueriesChecksCreate).not.toHaveBeenCalled()+ expect(logic.values.checkFormErrors.customSql).toEqual('Checking query...')+ })++ it('keeps a Monaco error until an edited query receives a new validation result', async () => {+ await mountLogic()+ await openWith(null, { checkType: 'custom_sql', customSql: 'SELECT * FROM orders' })++ logic.actions.setCustomSqlEditorError('Error on line 1, column 15')+ logic.actions.setCheckFormValue('customSql', 'SELECT * FROM orderz')++ expect(logic.values.customSqlEditorError).toEqual('Error on line 1, column 15')+ })+it.each<[string, { detail: string; code?: string; attr?: string }, string, string]>([['a taken name beside the name field',diff --git a/products/data_quality/frontend/dataQualityCheckEditorLogic.ts b/products/data_quality/frontend/dataQualityCheckEditorLogic.tsindex 7962cb73be75..c80d5c83bfec 100644--- a/products/data_quality/frontend/dataQualityCheckEditorLogic.ts+++ b/products/data_quality/frontend/dataQualityCheckEditorLogic.ts@@ -8,6 +8,14 @@ import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'+import { performQuery } from '~/queries/query'+import {+ AccessControlFilterWarning,+ DataWarehouseSyncWarning,+ HogQLQuery,+ NodeKind,+} from '~/queries/schema/schema-general'+import type {DatabaseSchemaDataWarehouseTable,DatabaseSchemaViewTable,@@ -65,6 +73,16 @@ export interface RelationshipSubject {fields: string[]}+export interface CustomSqlPreview {+ sql: string+ columns: string[]+ rows: unknown[][]+ rowCount: number+ hasMore: boolean+ /** Sources this query read that are stale, or resources access control filtered out, so the verdict is not final. */+ warnings: (DataWarehouseSyncWarning | AccessControlFilterWarning)[]+}+export interface DataQualityCheckEditorLogicProps {/** Which surface mounted this editor. One editor per surface, never one per row. */surface: string@@ -233,6 +251,15 @@ export interface dataQualityCheckEditorLogicValues {checkTypes: DataQualityCheckTypeApi[]checkTypesError: booleancheckTypesLoading: boolean+ customSqlEditorError: string | null+ customSqlPreview: CustomSqlPreview | null+ customSqlPreviewError: string | null+ customSqlPreviewLoading: boolean+ customSqlPreviewStale: boolean+ customSqlPreviewVerdict: 'fail' | 'pass' | null+ customSqlQueryKey: string+ customSqlSourceQuery: HogQLQuery+ customSqlValidationLoading: booleaneditingCheck: DataQualityCheckApi | nullisCheckFormSubmitting: booleanisCheckFormValid: boolean@@ -297,6 +324,21 @@ export interface dataQualityCheckEditorLogicActions {resetCheckForm: (values?: CheckFormValues) => {values?: CheckFormValues}+ runCustomSqlPreview: (_: any) => any+ runCustomSqlPreviewFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ runCustomSqlPreviewSuccess: (+ customSqlPreview: CustomSqlPreview,+ payload?: any+ ) => {+ customSqlPreview: CustomSqlPreview+ payload?: any+ }setCheckFormManualErrors: (errors: Record<string, any>) => {errors: Record<string, any>}@@ -310,6 +352,12 @@ export interface dataQualityCheckEditorLogicActions {setCheckFormValues: (values: DeepPartial<CheckFormValues>) => {values: DeepPartial<CheckFormValues>}+ setCustomSqlEditorError: (error: string | null) => {+ error: string | null+ }+ setCustomSqlValidationLoading: (loading: boolean) => {+ loading: boolean+ }setServerError: (serverError: string | null) => {serverError: string | null}@@ -353,6 +401,9 @@ export interface dataQualityCheckEditorLogicMeta {subject: DataQualitySubjectRef | null,relationshipSubjects: RelationshipSubject[]) => string[]+ customSqlSourceQuery: (checkForm: CheckFormValues) => HogQLQuery+ customSqlPreviewStale: (customSqlPreview: CustomSqlPreview | null, checkForm: CheckFormValues) => boolean+ customSqlPreviewVerdict: (customSqlPreview: CustomSqlPreview | null) => 'fail' | 'pass' | nullrequiresColumn: (checkForm: CheckFormValues,checkTypeByName: {@@ -404,6 +455,8 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(requestClose: true,closeEditor: true,setServerError: (serverError: string | null) => ({ serverError }),+ setCustomSqlEditorError: (error: string | null) => ({ error }),+ setCustomSqlValidationLoading: (loading: boolean) => ({ loading }),loadWarehouseCatalog: true,}),loaders(({ values }) => ({@@ -414,8 +467,42 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(values.subject ? await checksApi.checkTypes(values.subject) : values.checkTypes,},],+ customSqlPreview: [+ null as CustomSqlPreview | null,+ {+ runCustomSqlPreview: async (_, breakpoint): Promise<CustomSqlPreview> => {+ const sql = values.checkForm.customSql.trim()+ // Force a fresh calculation: the scheduled check run always reads current data, so the+ // preview must not serve a cached result that could report a different verdict.+ let response: NonNullable<HogQLQuery['response']>+ try {+ response = await performQuery<HogQLQuery>(+ { kind: NodeKind.HogQLQuery, query: sql },+ undefined,+ 'force_blocking'+ )+ } catch (error) {+ // Cmd+Enter can start a second preview while one is in flight. Drop a superseded+ // request so its late failure cannot replace the newer result with a stale error.+ breakpoint()+ throw error+ }+ // Same guard on the success path: a superseded result must not overwrite the newer one.+ breakpoint()+ return {+ sql,+ columns: response.columns ?? [],+ rows: response.results.slice(0, 10) as unknown[][],+ rowCount: response.results.length,+ hasMore: !!response.hasMore,+ warnings: response.warnings ?? [],+ }+ },+ },+ ],})),- reducers({+ reducers(({ props }) => ({+ customSqlQueryKey: [`data-quality-check/${props.surface}`, {}],isOpen: [false,{@@ -480,7 +567,43 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(setSubject: () => false,},],- }),+ customSqlPreview: [+ null as CustomSqlPreview | null,+ {+ runCustomSqlPreviewSuccess: (_, { customSqlPreview }) => customSqlPreview,+ openEditor: () => null,+ },+ ],+ customSqlPreviewError: [+ null as string | null,+ {+ runCustomSqlPreview: () => null,+ runCustomSqlPreviewSuccess: () => null,+ runCustomSqlPreviewFailure: (_, { error, errorObject }) => errorObject?.detail ?? error,+ openEditor: () => null,+ setCheckFormValue: (state, { name }) => (name === 'customSql' ? null : state),+ setCheckFormValues: (state, { values }) => ('customSql' in values ? null : state),+ },+ ],+ customSqlEditorError: [+ null as string | null,+ {+ setCustomSqlEditorError: (_, { error }) => error,+ openEditor: () => null,+ },+ ],+ customSqlValidationLoading: [+ false,+ {+ setCustomSqlValidationLoading: (_, { loading }) => loading,+ openEditor: () => false,+ setCheckFormValue: (state, { name }) =>+ name === 'customSql' ? true : name === 'checkType' ? false : state,+ setCheckFormValues: (state, { values }) =>+ 'checkType' in values && values.checkType !== CheckTypeEnumApi.CustomSql ? false : state,+ },+ ],+ })),selectors({checkTypeByName: [(s) => [s.checkTypes],@@ -520,8 +643,13 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(checkForm: {defaults: EMPTY_CHECK_FORM,errors: [- (s: any) => [s.checkForm, s.checkTypeByName],- (form: CheckFormValues, checkTypeByName: Record<string, DataQualityCheckTypeApi>) => ({+ (s: any) => [s.checkForm, s.checkTypeByName, s.customSqlEditorError, s.customSqlValidationLoading],+ (+ form: CheckFormValues,+ checkTypeByName: Record<string, DataQualityCheckTypeApi>,+ customSqlEditorError: string | null,+ customSqlValidationLoading: boolean+ ) => ({name:form.name && !CHECK_NAME_PATTERN.test(form.name)? 'Use letters, numbers and underscores, starting with a letter.'@@ -558,8 +686,12 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(? 'Set an age of at least one minute.': undefined,customSql:- form.checkType === CheckTypeEnumApi.CustomSql && !form.customSql.trim()- ? 'Write the query that selects the failing rows.'+ form.checkType === CheckTypeEnumApi.CustomSql+ ? !form.customSql.trim()+ ? 'Write the query that selects the failing rows.'+ : customSqlValidationLoading+ ? 'Checking query...'+ : (customSqlEditorError ?? undefined): undefined,}),],@@ -607,6 +739,20 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(},})),selectors({+ customSqlSourceQuery: [+ (s) => [s.checkForm],+ (checkForm: CheckFormValues): HogQLQuery => ({ kind: NodeKind.HogQLQuery, query: checkForm.customSql }),+ ],+ customSqlPreviewStale: [+ (s) => [s.customSqlPreview, s.checkForm],+ (customSqlPreview: CustomSqlPreview | null, checkForm: CheckFormValues) =>+ !!customSqlPreview && customSqlPreview.sql !== checkForm.customSql.trim(),+ ],+ customSqlPreviewVerdict: [+ (s) => [s.customSqlPreview],+ (customSqlPreview: CustomSqlPreview | null) =>+ customSqlPreview ? (customSqlPreview.rowCount === 0 ? 'pass' : 'fail') : null,+ ],requiresColumn: [(s) => [s.checkForm, s.checkTypeByName],(checkForm: CheckFormValues, checkTypeByName: Record<string, DataQualityCheckTypeApi>) =>diff --git a/products/data_quality/frontend/previewCell.test.ts b/products/data_quality/frontend/previewCell.test.tsnew file mode 100644index 000000000000..4fce5ab0d09a--- /dev/null+++ b/products/data_quality/frontend/previewCell.test.ts@@ -0,0 +1,21 @@+import { formatPreviewCell } from './previewCell'++describe('formatPreviewCell', () => {+ it.each<[string, unknown, string]>([+ ['a string', 'orders', 'orders'],+ ['a number', 42, '42'],+ ['a boolean', false, 'false'],+ ['null as empty', null, ''],+ ['undefined as empty', undefined, ''],+ ['an array', [1, 2], '[1,2]'],+ ['an object', { id: 7 }, '{"id":7}'],+ // A raw object like this would otherwise reach LemonTable and inject markup via its props.+ [+ 'a cell-representation shape',+ { props: { dangerouslySetInnerHTML: { __html: '<img src=x onerror=alert(1)>' } } },+ '{"props":{"dangerouslySetInnerHTML":{"__html":"<img src=x onerror=alert(1)>"}}}',+ ],+ ])('renders %s as text', (_case, value, expected) => {+ expect(formatPreviewCell(value)).toEqual(expected)+ })+})diff --git a/products/data_quality/frontend/previewCell.ts b/products/data_quality/frontend/previewCell.tsnew file mode 100644index 000000000000..c502dea721ba--- /dev/null+++ b/products/data_quality/frontend/previewCell.ts@@ -0,0 +1,17 @@+/**+ * Render a raw HogQL result value as plain text for the preview table.+ *+ * LemonTable treats any non-null, non-element object cell as a cell representation and spreads its+ * `props` onto the `<td>`, so a value shaped like `{ props: { dangerouslySetInnerHTML } }` would+ * inject markup. Stringifying objects and arrays keeps every cell a primitive, which also stops+ * array/object columns from rendering as blank cells.+ */+export function formatPreviewCell(value: unknown): string {+ if (value === null || value === undefined) {+ return ''+ }+ if (typeof value === 'object') {+ return JSON.stringify(value)+ }+ return String(value)+}