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.

fix(sql-editor): keep query column order when copying results (#115634)

posthog[bot]8b5a74abdb35
diff --git a/frontend/src/queries/nodes/DataTable/clipboardUtils.test.ts b/frontend/src/queries/nodes/DataTable/clipboardUtils.test.ts
index 90f78e15267f..9e4ad68ddd99 100644
--- a/frontend/src/queries/nodes/DataTable/clipboardUtils.test.ts
+++ b/frontend/src/queries/nodes/DataTable/clipboardUtils.test.ts
@@ -186,6 +186,31 @@ describe('clipboardUtils', () => {
expect(result[1]).toContain('form')
})
+ it.each([
+ {
+ name: 'keeps the query column order and puts flattened sub-columns after their parent',
+ columns: ['b', 'obj', 'a'],
+ rows: [{ result: ['b1', { z: 1, y: 2 }, 'a1'] }, { result: ['b2', { x: 3 }, 'a2'] }],
+ expected: [
+ ['b', 'obj.z', 'obj.y', 'obj.x', 'a'],
+ ['b1', 1, 2, '', 'a1'],
+ ['b2', '', '', 3, 'a2'],
+ ],
+ },
+ {
+ name: 'keeps every value when two columns have the same name',
+ columns: ['id', 'id'],
+ rows: [{ result: [1, 2] }],
+ expected: [
+ ['id', 'id'],
+ [1, 2],
+ ],
+ },
+ ])('$name', ({ columns, rows, expected }) => {
+ const query = createMockQuery(NodeKind.HogQLQuery, { query: 'SELECT 1' })
+ expect(getCsvTableData(rows, columns, query)).toEqual(expected)
+ })
+
it('returns empty array for unsupported query types', () => {
// Create a query with an unsupported source by bypassing type safety
const query: DataTableNode = {
@@ -357,7 +382,6 @@ describe('clipboardUtils', () => {
describe('copyTableToMarkdown', () => {
it('copies a padded markdown table to clipboard', () => {
const query = createMockQuery(NodeKind.HogQLQuery, { query: 'SELECT * FROM events' })
- // getCsvTableData sorts columns alphabetically: age, city, name
const columns = ['name', 'age', 'city']
const rows: DataTableRow[] = [
{ result: ['Alice', 30, 'New York'] },
@@ -367,10 +391,10 @@ describe('clipboardUtils', () => {
copyTableToMarkdown(rows, columns, query)
const expected = [
- '| age | city | name |',
- '| --- | ------------- | ----- |',
- '| 30 | New York | Alice |',
- '| 25 | San Francisco | Bob |',
+ '| name | age | city |',
+ '| ----- | --- | ------------- |',
+ '| Alice | 30 | New York |',
+ '| Bob | 25 | San Francisco |',
].join('\n')
expect(mockCopyToClipboard).toHaveBeenCalledWith(expected, 'table')
})
diff --git a/frontend/src/queries/nodes/DataTable/clipboardUtils.ts b/frontend/src/queries/nodes/DataTable/clipboardUtils.ts
index fe79f0a407f0..f74c82c6c9ae 100644
--- a/frontend/src/queries/nodes/DataTable/clipboardUtils.ts
+++ b/frontend/src/queries/nodes/DataTable/clipboardUtils.ts
@@ -56,56 +56,40 @@ export const flattenObject = (obj: any, prefix?: string, separator = '.'): Recor
return flattened
}
-// Helper function to process a single row and return flattened data
-const processRowData = (row: DataTableRow, columns: string[], query: DataTableNode): Record<string, any> => {
- const flattenedRecord: Record<string, any> = {}
+const flattenCell = (value: any, col: string): Record<string, any> =>
+ value !== null && typeof value === 'object' && !Array.isArray(value) ? flattenObject(value, col) : { [col]: value }
+// Returns one flattened group per column, so duplicate column names do not overwrite each other
+const processRowData = (row: DataTableRow, columns: string[], query: DataTableNode): Record<string, any>[] => {
if (isHogQLQuery(query.source) || isMarketingAnalyticsTableQuery(query.source)) {
const data = row.result ?? {}
- columns.forEach((col, index) => {
- const value = Array.isArray(data) ? data[index] : (data as Record<string, any>)[index]
- if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
- Object.assign(flattenedRecord, flattenObject(value, col))
- } else {
- flattenedRecord[col] = value
- }
- })
+ return columns.map((col, index) =>
+ flattenCell(Array.isArray(data) ? data[index] : (data as Record<string, any>)[index], col)
+ )
} else if (isEventsQuery(query.source)) {
- columns.forEach((col, colIndex) => {
+ return columns.map((col, colIndex) => {
if (columnDisallowList.includes(col)) {
- return
+ return {}
}
- let value = Array.isArray(row.result)
+ const value = Array.isArray(row.result)
? row.result[colIndex]
: (row.result as Record<string, any>)?.[colIndex]
const colName = extractExpressionComment(col)
if (col === 'person') {
- value = asDisplay(value)
- flattenedRecord[colName] = value
- } else if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
- Object.assign(flattenedRecord, flattenObject(value, colName))
- } else {
- flattenedRecord[colName] = value
+ return { [colName]: asDisplay(value) }
}
+ return flattenCell(value, colName)
})
} else if (isPersonsNode(query.source)) {
const record = row.result as Record<string, any> | undefined
const recordWithPerson = { ...record, person: record?.name } as Record<string, any>
- const filteredColumns = columns.filter((n) => !columnDisallowList.includes(n))
- filteredColumns.forEach((col) => {
- const value = recordWithPerson[col]
- if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
- Object.assign(flattenedRecord, flattenObject(value, col))
- } else {
- flattenedRecord[col] = value
- }
- })
+ return columns.map((col) => (columnDisallowList.includes(col) ? {} : flattenCell(recordWithPerson[col], col)))
}
- return flattenedRecord
+ return []
}
export const getCsvTableData = (dataTableRows: DataTableRow[], columns: string[], query: DataTableNode): string[][] => {
@@ -114,24 +98,25 @@ export const getCsvTableData = (dataTableRows: DataTableRow[], columns: string[]
return []
}
- // Process all rows and collect all possible columns
- const allColumns = new Set<string>()
- const processedRows = dataTableRows.map((row) => {
- const flattenedRecord = processRowData(row, columns, query)
- Object.keys(flattenedRecord).forEach((col) => allColumns.add(col))
- return flattenedRecord
+ const processedRows = dataTableRows.map((row) => processRowData(row, columns, query))
+
+ // Keep the query column order, and put flattened sub-columns right after their parent column
+ const groupKeys = columns.map((_, index) => {
+ const keys = new Set<string>()
+ processedRows.forEach((groups) => Object.keys(groups[index] ?? {}).forEach((key) => keys.add(key)))
+ return Array.from(keys)
})
- // If no columns were discovered, return empty result
- if (allColumns.size === 0) {
+ const header = groupKeys.flat()
+ if (header.length === 0) {
return []
}
- // Create consistent CSV structure with all discovered columns
- const sortedColumns = Array.from(allColumns).sort()
- const csvData = processedRows.map((flattenedRecord) => sortedColumns.map((col) => flattenedRecord[col] ?? ''))
+ const csvData = processedRows.map((groups) =>
+ groupKeys.flatMap((keys, index) => keys.map((key) => groups[index]?.[key] ?? ''))
+ )
- return [sortedColumns, ...csvData]
+ return [header, ...csvData]
}
export const getJsonTableData = (