From e7ae287d2fec665a26144308e104e778a7ad5071 Mon Sep 17 00:00:00 2001 From: Simon Ser Date: Wed, 12 Jan 2022 12:46:05 +0000 Subject: [PATCH] database: always include table name in SELECT When JOINs are performed on the auto-generated SELECT query, multiple tables may have the same field names. For instance, in lists.sr.ht the "list" and "subscription" tables both have an "id" column. When performing a "mailingLists" GraphQL query this results in this error: pq: column reference "id" is ambiguous The old query looks like this: SELECT "description", "name", "id", "owner_id", "updated", COALESCE( access.permissions, CASE WHEN list.owner_id = $1 THEN $2 ELSE CASE WHEN sub.id IS NOT NULL THEN list.subscriber_permissions ELSE null END END, list.nonsubscriber_permissions | list.account_permissions), access.id AS access_id, sub.id AS subscription_id FROM list LEFT JOIN access ON access.list_id = list.id AND access.user_id = $3 LEFT JOIN subscription sub ON sub.list_id = list.id AND sub.user_id = $4 WHERE list.owner_id = $5 ORDER BY "updated" DESC LIMIT 26 The new query looks like this: SELECT "description", "name", "list"."id", "list"."owner_id", "list"."updated", COALESCE( access.permissions, CASE WHEN list.owner_id = $1 THEN $2 ELSE CASE WHEN sub.id IS NOT NULL THEN list.subscriber_permissions ELSE null END END, list.nonsubscriber_permissions | list.account_permissions), access.id AS access_id, sub.id AS subscription_id FROM list LEFT JOIN access ON access.list_id = list.id AND access.user_id = $3 LEFT JOIN subscription sub ON sub.list_id = list.id AND sub.user_id = $4 WHERE list.owner_id = $5 ORDER BY "updated" DESC LIMIT 26 --- database/ql.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/database/ql.go b/database/ql.go index 58e6fdf155e10d8c3463582974c01ce00e5d326b..dc9ddaaae911b7a2e517ec9c8d7a5b969349487b 100644 --- a/database/ql.go +++ b/database/ql.go @@ -90,7 +90,11 @@ func Columns(ctx context.Context, m Model) []string { } for _, field := range m.Fields().Anonymous() { - columns = append(columns, WithAlias(m.Alias(), field.SQL)) + alias := m.Alias() + if alias == "" { + alias = m.Table() + } + columns = append(columns, WithAlias(alias, field.SQL)) } return columns