ColumnList.utils.ts78 lines · main
1import { POSTGRES_DATA_TYPE_OPTIONS } from '@/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.constants'
2
3type TableConstraintSource = {
4 schema: string
5 name: string
6 primary_keys: ReadonlyArray<{ name: string }>
7 relationships: ReadonlyArray<{
8 source_schema: string
9 source_table_name: string
10 source_column_name: string
11 }>
12 unique_indexes?: ReadonlyArray<{ columns: ReadonlyArray<string> }>
13}
14
15export type ColumnAffordanceKind = 'number' | 'time' | 'text' | 'json' | 'bool' | 'other'
16
17export interface ColumnTypeAffordance {
18 kind: ColumnAffordanceKind
19 label: string
20}
21
22const COLUMN_AFFORDANCE_LABELS: Record<ColumnAffordanceKind, string> = {
23 number: 'Numeric',
24 time: 'Date / time',
25 text: 'Text',
26 json: 'JSON',
27 bool: 'Boolean',
28 other: 'Other',
29}
30
31const normalizeColumnFormat = (format: string) => format.replaceAll('"', '').replace(/\[\]$/, '')
32
33export function getColumnTypeAffordance(format: string): ColumnTypeAffordance {
34 const normalizedFormat = normalizeColumnFormat(format)
35 const optionType = POSTGRES_DATA_TYPE_OPTIONS.find(
36 (option) => option.name === normalizedFormat
37 )?.type
38
39 switch (optionType) {
40 case 'number':
41 case 'time':
42 case 'text':
43 case 'json':
44 case 'bool':
45 return { kind: optionType, label: COLUMN_AFFORDANCE_LABELS[optionType] }
46 default:
47 return { kind: 'other', label: COLUMN_AFFORDANCE_LABELS.other }
48 }
49}
50
51export function getPrimaryKeyColumnNames(table?: TableConstraintSource) {
52 return new Set(table?.primary_keys.map((primaryKey) => primaryKey.name) ?? [])
53}
54
55export function getForeignKeyColumnNames(table?: TableConstraintSource) {
56 if (!table) {
57 return new Set<string>()
58 }
59
60 const { schema, name, relationships } = table
61
62 return new Set(
63 relationships
64 .filter(
65 (relationship) =>
66 relationship.source_schema === schema && relationship.source_table_name === name
67 )
68 .map((relationship) => relationship.source_column_name)
69 )
70}
71
72export function getUniqueIndexColumnNames(table?: TableConstraintSource) {
73 return new Set(
74 table?.unique_indexes
75 ?.filter((uniqueIndex) => uniqueIndex.columns.length === 1)
76 .flatMap((uniqueIndex) => uniqueIndex.columns) ?? []
77 )
78}