Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sql/postgres: Avoid using referential_constraints view #2025

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions sql/postgres/inspect.go
Original file line number Diff line number Diff line change
Expand Up @@ -1267,8 +1267,8 @@ SELECT
fk.referenced_table_name,
a2.attname AS referenced_column_name,
fk.referenced_schema_name,
rc.update_rule,
rc.delete_rule
fk.update_rule,
fk.delete_rule
FROM
(
SELECT
Expand All @@ -1281,7 +1281,21 @@ SELECT
ns2.nspname AS referenced_schema_name,
generate_series(1,array_length(con.conkey,1)) as ord,
unnest(con.conkey) AS conkey,
unnest(con.confkey) AS confkey
unnest(con.confkey) AS confkey,
CASE con.confupdtype
WHEN 'c' THEN 'CASCADE'
WHEN 'n' THEN 'SET NULL'
WHEN 'd' THEN 'SET DEFAULT'
WHEN 'r' THEN 'RESTRICT'
WHEN 'a' THEN 'NO ACTION'
END AS update_rule,
CASE con.confdeltype
WHEN 'c' THEN 'CASCADE'
WHEN 'n' THEN 'SET NULL'
WHEN 'd' THEN 'SET DEFAULT'
WHEN 'r' THEN 'RESTRICT'
WHEN 'a' THEN 'NO ACTION'
END AS delete_rule
Comment on lines +1285 to +1298
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer to append the con.confupdtype, con.confdeltype to the query and do this mapping in Go.

There are small test cases to change then in inspect_test.go and maybe add another one in internal/integration/testdata/postgres.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the feedback @a8m! I had a look at doing it this way, but the problem is that both MySQL and Postgres go through the same code path in sqlx.SchemaFKs, and I couldn't find a way to resolve this without more refactoring than I'm comfortable with.

I think handing it over to you is better at this point.

FROM pg_constraint con
JOIN pg_class t1 ON t1.oid = con.conrelid
JOIN pg_class t2 ON t2.oid = con.confrelid
Expand All @@ -1293,7 +1307,6 @@ SELECT
) AS fk
JOIN pg_attribute a1 ON a1.attnum = fk.conkey AND a1.attrelid = fk.conrelid
JOIN pg_attribute a2 ON a2.attnum = fk.confkey AND a2.attrelid = fk.confrelid
JOIN information_schema.referential_constraints rc ON rc.constraint_name = fk.constraint_name AND rc.constraint_schema = fk.schema_name
ORDER BY
fk.conrelid, fk.constraint_name, fk.ord
`
Expand Down