ColumnList.utils.ts 2.2 KB

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