Skip to content

Commit

Permalink
fix: FK pointing to VIEW instead of TABLE in OpenAPI output
Browse files Browse the repository at this point in the history
  • Loading branch information
laurenceisla committed Jan 20, 2023
1 parent be6c30a commit 775c006
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/PostgREST/Response/OpenAPI.hs
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,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
Expand Down
17 changes: 17 additions & 0 deletions test/spec/Feature/OpenApi/OpenApiSpec.hs
Original file line number Diff line number Diff line change
Expand Up @@ -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`.<fk table='clients' column='id'/>"
}
|]

describe "PostgreSQL to Swagger Type Mapping" $ do

it "character varying to string" $ do
Expand Down
10 changes: 10 additions & 0 deletions test/spec/fixtures/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -3096,3 +3096,13 @@ create table test.subscriptions(
subscribed int references test.posters(id),
primary key(subscriber, subscribed)
);

-- 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;

0 comments on commit 775c006

Please sign in to comment.