Skip to content

Commit

Permalink
Merge pull request #126 from svanharmelen/fix/primary-keys
Browse files Browse the repository at this point in the history
Fix query to get primary column names for postgres
  • Loading branch information
jorgerojas26 authored Nov 27, 2024
2 parents 105fddb + d785827 commit 4ef1330
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions drivers/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -861,10 +861,13 @@ func (db *Postgres) GetPrimaryKeyColumnNames(database, table string) (primaryKey

splitTableString := strings.Split(table, ".")

if len(splitTableString) == 1 {
if len(splitTableString) != 2 {
return nil, errors.New("table must be in the format schema.table")
}

schemaName := splitTableString[0]
tableName := splitTableString[1]

if database != db.CurrentDatabase {
err = db.SwitchDatabase(database)
if err != nil {
Expand All @@ -878,15 +881,20 @@ func (db *Postgres) GetPrimaryKeyColumnNames(database, table string) (primaryKey
}()
}

tableName := splitTableString[1]

row, err := db.Connection.Query(`
SELECT a.attname AS column_name
FROM pg_index i
JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
WHERE i.indrelid = $1::regclass AND i.indisprimary
`, tableName)
SELECT
a.attname AS column_name
FROM
pg_index i
JOIN pg_class c ON c.oid = i.indrelid
JOIN pg_attribute a ON a.attrelid = c.oid
AND a.attnum = ANY (i.indkey)
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE
relname = $2 AND nspname = $1 AND indisprimary
`, schemaName, tableName)
if err != nil {
logger.Error("GetPrimaryKeyColumnNames", map[string]any{"error": err.Error()})
return nil, err
}

Expand Down

0 comments on commit 4ef1330

Please sign in to comment.