Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Fix CSV import for postgres array types (#37995)

Joshen Lim13d264a57cc4
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.test.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.test.ts
new file mode 100644
index 00000000000..a6f24e4f38d
--- /dev/null
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.test.ts
@@ -0,0 +1,88 @@
+import { describe, expect, test } from 'vitest'
+import { formatRowsForInsert } from './SidePanelEditor.utils'
+
+describe('SidePanelEditor.utils.test.ts', () => {
+ test('formatRowsForInsert should for format rows with basic data types correctly', () => {
+ const rows = [
+ { id: 1, text: 'A' },
+ { id: 2, text: 'B' },
+ { id: 3, text: 'C' },
+ ]
+ const headers = ['id', 'text']
+ const columns = [
+ { id: '1', name: 'id', data_type: 'bigint', format: 'int8', is_nullable: false },
+ { id: '2', name: 'text', data_type: 'text', format: 'text', is_nullable: true },
+ ]
+
+ const formattedRows = formatRowsForInsert({ rows, headers, columns: columns as any })
+ expect(formattedRows).toEqual(rows)
+ })
+
+ test('formatRowsForInsert should handle nullable columns if value is an empty string', () => {
+ const rows = [
+ { id: 1, text: 'A' },
+ { id: 2, text: '' },
+ { id: 3, text: 'C' },
+ ]
+ const headers = ['id', 'text']
+ const columns = [
+ { id: '1', name: 'id', data_type: 'bigint', format: 'int8', is_nullable: false },
+ { id: '2', name: 'text', data_type: 'text', format: 'text', is_nullable: true },
+ ]
+
+ const formattedRows = formatRowsForInsert({ rows, headers, columns: columns as any })
+ expect(formattedRows).toEqual([
+ { id: 1, text: 'A' },
+ { id: 2, text: null },
+ { id: 3, text: 'C' },
+ ])
+ })
+
+ test('formatRowsForInsert should handle JSON object values properly', () => {
+ const rows = [{ id: 1, value: '{"key": "value"}' }]
+ const headers = ['id', 'value']
+ const columns = [
+ { id: '1', name: 'id', data_type: 'bigint', format: 'int8', is_nullable: false },
+ { id: '2', name: 'value', data_type: 'json', format: 'jsonb', is_nullable: true },
+ ]
+
+ const formattedRows = formatRowsForInsert({ rows, headers, columns: columns as any })
+ expect(formattedRows).toEqual([{ id: 1, value: { key: 'value' } }])
+ })
+
+ test('formatRowsForInsert should handle JSON array values properly', () => {
+ const rows = [{ id: 1, value: '["item1", "item2", "item3"]' }]
+ const headers = ['id', 'value']
+ const columns = [
+ { id: '1', name: 'id', data_type: 'bigint', format: 'int8', is_nullable: false },
+ { id: '2', name: 'value', data_type: 'json', format: 'jsonb', is_nullable: true },
+ ]
+
+ const formattedRows = formatRowsForInsert({ rows, headers, columns: columns as any })
+ expect(formattedRows).toEqual([{ id: 1, value: ['item1', 'item2', 'item3'] }])
+ })
+
+ test('formatRowsForInsert should handle Postgres array values properly', () => {
+ const rows = [{ id: 1, value: '{"item1", "item2", "item3"}' }]
+ const headers = ['id', 'value']
+ const columns = [
+ { id: '1', name: 'id', data_type: 'bigint', format: 'int8', is_nullable: false },
+ { id: '2', name: 'value', data_type: 'ARRAY', format: '_text', is_nullable: true },
+ ]
+
+ const formattedRows = formatRowsForInsert({ rows, headers, columns: columns as any })
+ expect(formattedRows).toEqual([{ id: 1, value: ['item1', 'item2', 'item3'] }])
+ })
+
+ test('formatRowsForInsert should handle Postgres array values properly if provided JSON string', () => {
+ const rows = [{ id: 1, value: '["item1", "item2", "item3"]' }]
+ const headers = ['id', 'value']
+ const columns = [
+ { id: '1', name: 'id', data_type: 'bigint', format: 'int8', is_nullable: false },
+ { id: '2', name: 'value', data_type: 'ARRAY', format: '_text', is_nullable: true },
+ ]
+
+ const formattedRows = formatRowsForInsert({ rows, headers, columns: columns as any })
+ expect(formattedRows).toEqual([{ id: 1, value: ['item1', 'item2', 'item3'] }])
+ })
+})
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
index 18a5554960f..55d4d54cfa1 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
@@ -22,16 +22,16 @@ import { tableRowKeys } from 'data/table-rows/keys'
import { tableKeys } from 'data/tables/keys'
import { createTable as createTableMutation } from 'data/tables/table-create-mutation'
import { deleteTable as deleteTableMutation } from 'data/tables/table-delete-mutation'
-import {
- UpdateTableBody,
- updateTable as updateTableMutation,
-} from 'data/tables/table-update-mutation'
-import { getTables } from 'data/tables/tables-query'
import {
getTable,
RetrievedTableColumn,
RetrieveTableResult,
} from 'data/tables/table-retrieve-query'
+import {
+ UpdateTableBody,
+ updateTable as updateTableMutation,
+} from 'data/tables/table-update-mutation'
+import { getTables } from 'data/tables/tables-query'
import { timeout, tryParseJson } from 'lib/helpers'
import {
generateCreateColumnPayload,
@@ -821,6 +821,47 @@ export const updateTable = async ({
}
}
+/**
+ * Used in insertRowsViaSpreadsheet + insertTableRows
+ */
+export const formatRowsForInsert = ({
+ rows,
+ headers,
+ columns = [],
+}: {
+ rows: any[]
+ headers: string[]
+ columns?: RetrieveTableResult['columns']
+}) => {
+ return rows.map((row: any) => {
+ const formattedRow: any = {}
+ headers.forEach((header) => {
+ const column = columns?.find((c) => c.name === header)
+ const originalValue = row[header]
+
+ if ((column?.format ?? '').includes('json')) {
+ formattedRow[header] = tryParseJson(originalValue)
+ } else if ((column?.data_type ?? '') === 'ARRAY') {
+ if (
+ typeof originalValue === 'string' &&
+ originalValue.startsWith('{') &&
+ originalValue.endsWith('}')
+ ) {
+ const formattedPostgresArraytoJsonArray = `[${originalValue.slice(1, originalValue.length - 1)}]`
+ formattedRow[header] = tryParseJson(formattedPostgresArraytoJsonArray)
+ } else {
+ formattedRow[header] = tryParseJson(originalValue)
+ }
+ } else if (originalValue === '') {
+ formattedRow[header] = column?.is_nullable ? null : ''
+ } else {
+ formattedRow[header] = originalValue
+ }
+ })
+ return formattedRow
+ })
+}
+
export const insertRowsViaSpreadsheet = async (
projectRef: string,
connectionString: string | undefined | null,
@@ -843,20 +884,10 @@ export const insertRowsViaSpreadsheet = async (
chunk: async (results: any, parser: any) => {
parser.pause()
- const formattedData = results.data.map((row: any) => {
- const formattedRow: any = {}
- selectedHeaders.forEach((header) => {
- const column = table.columns?.find((c) => c.name === header)
- if ((column?.data_type ?? '') === 'ARRAY' || (column?.format ?? '').includes('json')) {
- formattedRow[header] = tryParseJson(row[header])
- } else if (row[header] === '') {
- // if the cell is empty string, convert it to NULL
- formattedRow[header] = column?.is_nullable ? null : ''
- } else {
- formattedRow[header] = row[header]
- }
- })
- return formattedRow
+ const formattedData = formatRowsForInsert({
+ rows: results.data,
+ headers: selectedHeaders,
+ columns: table.columns,
})
const insertQuery = new Query().from(table.name, table.schema).insert(formattedData).toSql()
@@ -894,19 +925,10 @@ export const insertTableRows = async (
let insertError = undefined
let insertProgress = 0
- const formattedRows = rows.map((row: any) => {
- const formattedRow: any = {}
- selectedHeaders.forEach((header) => {
- const column = table.columns?.find((c) => c.name === header)
- if ((column?.data_type ?? '') === 'ARRAY' || (column?.format ?? '').includes('json')) {
- formattedRow[header] = tryParseJson(row[header])
- } else if (row[header] === '') {
- formattedRow[header] = column?.is_nullable ? null : ''
- } else {
- formattedRow[header] = row[header]
- }
- })
- return formattedRow
+ const formattedRows = formatRowsForInsert({
+ rows,
+ headers: selectedHeaders,
+ columns: table.columns,
})
const batches = chunk(formattedRows, BATCH_SIZE)
diff --git a/apps/studio/components/layouts/Tabs/Tabs.tsx b/apps/studio/components/layouts/Tabs/Tabs.tsx
index 847a3c11d45..c8d1b017aae 100644
--- a/apps/studio/components/layouts/Tabs/Tabs.tsx
+++ b/apps/studio/components/layouts/Tabs/Tabs.tsx
@@ -142,7 +142,7 @@ export const EditorTabs = () => {
strategy={horizontalListSortingStrategy}
>
{editorTabs.map((tab, index) => (
- <ContextMenu_Shadcn_>
+ <ContextMenu_Shadcn_ key={tab.id}>
<ContextMenuTrigger_Shadcn_>
<SortableTab
key={tab.id}