From 5b7a2f3dc699ed3351f884fd38e6dbaf1469241a Mon Sep 17 00:00:00 2001 From: Andrew Farries Date: Wed, 17 Jan 2024 13:37:01 +0000 Subject: [PATCH] Add `UNIQUE` constraints to internal schema --- pkg/schema/schema.go | 11 +++++++++++ pkg/state/state.go | 17 +++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/pkg/schema/schema.go b/pkg/schema/schema.go index b882f0be..50de06b5 100644 --- a/pkg/schema/schema.go +++ b/pkg/schema/schema.go @@ -52,6 +52,9 @@ type Table struct { // CheckConstraints is a map of all check constraints defined on the table CheckConstraints map[string]CheckConstraint `json:"checkConstraints"` + + // UniqueConstraints is a map of all unique constraints defined on the table + UniqueConstraints map[string]UniqueConstraint `json:"uniqueConstraints"` } type Column struct { @@ -99,6 +102,14 @@ type CheckConstraint struct { Definition string `json:"definition"` } +type UniqueConstraint struct { + // Name is the name of the unique constraint in postgres + Name string `json:"name"` + + // The columns that the unique constraint is defined on + Columns []string `json:"columns"` +} + func (s *Schema) GetTable(name string) *Table { if s.Tables == nil { return nil diff --git a/pkg/state/state.go b/pkg/state/state.go index f05c8c8d..41159229 100644 --- a/pkg/state/state.go +++ b/pkg/state/state.go @@ -190,6 +190,23 @@ BEGIN AND cc_constraint.contype = 'c' GROUP BY cc_constraint.oid ) AS cc_details + ), + 'uniqueConstraints', ( + SELECT json_object_agg(uc_details.conname, json_build_object( + 'name', uc_details.conname, + 'columns', uc_details.columns + )) + FROM ( + SELECT + uc_constraint.conname, + array_agg(uc_attr.attname ORDER BY uc_constraint.conkey::int[]) AS columns, + pg_get_constraintdef(uc_constraint.oid) AS definition + FROM pg_constraint AS uc_constraint + INNER JOIN pg_attribute uc_attr ON uc_attr.attrelid = uc_constraint.conrelid AND uc_attr.attnum = ANY(uc_constraint.conkey) + WHERE uc_constraint.conrelid = t.oid + AND uc_constraint.contype = 'u' + GROUP BY uc_constraint.oid + ) AS uc_details ), 'foreignKeys', ( SELECT json_object_agg(fk_details.conname, json_build_object(