From 81501aefa00f3d1b81f5c9fd31c55bce2e1407b3 Mon Sep 17 00:00:00 2001 From: Laurence Isla Date: Fri, 20 Jan 2023 09:37:15 -0500 Subject: [PATCH] fix: FK pointing to VIEW instead of TABLE in OpenAPI output --- src/PostgREST/Response/OpenAPI.hs | 5 ++++- test/spec/Feature/OpenApi/OpenApiSpec.hs | 17 +++++++++++++++++ test/spec/fixtures/schema.sql | 10 ++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/PostgREST/Response/OpenAPI.hs b/src/PostgREST/Response/OpenAPI.hs index 240551e54..adcf2b9cc 100644 --- a/src/PostgREST/Response/OpenAPI.hs +++ b/src/PostgREST/Response/OpenAPI.hs @@ -103,11 +103,14 @@ makeProperty tbl rels col = (colName col, Inline s) fk :: Maybe Text fk = let + searchedRels = fromMaybe mempty $ HM.lookup (QualifiedIdentifier (tableSchema tbl) (tableName tbl), tableSchema tbl) rels + -- Sorts the relationship list to get tables first + relsSortedByIsView = sortOn relFTableIsView [ r | r@Relationship{} <- searchedRels] -- Finds the relationship that has a single column foreign key rel = find (\case Relationship{relCardinality=(M2O _ relColumns)} -> [colName col] == (fst <$> relColumns) _ -> False - ) $ fromMaybe mempty $ HM.lookup (QualifiedIdentifier (tableSchema tbl) (tableName tbl), tableSchema tbl) rels + ) relsSortedByIsView fCol = (headMay . (\r -> snd <$> relColumns (relCardinality r)) =<< rel) fTbl = qiName . relForeignTable <$> rel fTblCol = (,) <$> fTbl <*> fCol diff --git a/test/spec/Feature/OpenApi/OpenApiSpec.hs b/test/spec/Feature/OpenApi/OpenApiSpec.hs index b7603b111..761ce6d48 100644 --- a/test/spec/Feature/OpenApi/OpenApiSpec.hs +++ b/test/spec/Feature/OpenApi/OpenApiSpec.hs @@ -310,6 +310,23 @@ spec actualPgVersion = describe "OpenAPI" $ do } |] + describe "VIEW created for a TABLE with a O2M relationship" $ do + + it "fk points to destination TABLE instead of the VIEW" $ do + r <- simpleBody <$> get "/" + + let referralLink = r ^? key "definitions" . key "projects" . key "properties" . key "client_id" + + liftIO $ + referralLink `shouldBe` Just + [aesonQQ| + { + "format": "integer", + "type": "integer", + "description": "Note:\nThis is a Foreign Key to `clients.id`." + } + |] + describe "PostgreSQL to Swagger Type Mapping" $ do it "character varying to string" $ do diff --git a/test/spec/fixtures/schema.sql b/test/spec/fixtures/schema.sql index e3a42617c..4d2412004 100644 --- a/test/spec/fixtures/schema.sql +++ b/test/spec/fixtures/schema.sql @@ -3076,3 +3076,13 @@ LANGUAGE sql AS $$ select * from test.yards; $$; + +-- view's name is alphabetically before projects +create view test.alpha_projects as + select c.id, p.name as pro_name, c.name as cli_name + from projects p join clients c on p.client_id = c.id; + +-- view's name is alphabetically after projects +create view test.zeta_projects as + select c.id, p.name as pro_name, c.name as cli_name + from projects p join clients c on p.client_id = c.id; \ No newline at end of file