From 00524c03ffcb4b51696387def7853c8ee586b648 Mon Sep 17 00:00:00 2001 From: Robin Tang Date: Fri, 2 Feb 2024 12:19:18 -0800 Subject: [PATCH] Postgres - Composite key value fix (#77) --- lib/postgres/queries/queries.go | 17 ++++++++++------- lib/postgres/queries/queries_test.go | 2 +- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/lib/postgres/queries/queries.go b/lib/postgres/queries/queries.go index 8c03b3af..554d503d 100644 --- a/lib/postgres/queries/queries.go +++ b/lib/postgres/queries/queries.go @@ -38,14 +38,17 @@ type SelectTableQueryArgs struct { } func SelectTableQuery(args SelectTableQueryArgs) string { - orderByFragment := strings.Join(quotedIdentifiers(args.OrderBy), ",") - if args.Descending { - orderByFragment += " DESC" + var fragments []string + for _, orderBy := range args.OrderBy { + fragment := pgx.Identifier{orderBy}.Sanitize() + if args.Descending { + fragment += " DESC" + } + + fragments = append(fragments, fragment) } - - // TODO: Make sure keys are being escaped properly - return fmt.Sprintf(`SELECT %s FROM %s ORDER BY %s LIMIT 1`, - strings.Join(args.Keys, ","), pgx.Identifier{args.Schema, args.TableName}.Sanitize(), orderByFragment) + return fmt.Sprintf(`SELECT %s FROM %s ORDER BY %s LIMIT 1`, strings.Join(args.Keys, ","), + pgx.Identifier{args.Schema, args.TableName}.Sanitize(), strings.Join(fragments, ",")) } type RetrievePrimaryKeysArgs struct { diff --git a/lib/postgres/queries/queries_test.go b/lib/postgres/queries/queries_test.go index 34b79aee..94d2a051 100644 --- a/lib/postgres/queries/queries_test.go +++ b/lib/postgres/queries/queries_test.go @@ -48,7 +48,7 @@ func TestSelectTableQuery(t *testing.T) { OrderBy: []string{"e", "f", "g"}, Descending: true, }) - assert.Equal(t, `SELECT a,b,c FROM "schema"."table" ORDER BY "e","f","g" DESC LIMIT 1`, query) + assert.Equal(t, `SELECT a,b,c FROM "schema"."table" ORDER BY "e" DESC,"f" DESC,"g" DESC LIMIT 1`, query) } }