Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
Simplify and optimize Postgres query for primary_keys() #27961
Take two on #27949, which was flawed because
In summary, this pull request simplifies the query used to determine the primary keys of a table in Postgres to achieve a ~%66 speedup per table primary key query during application startup.
cc @kamipo (thanks for your patience!)
Thanks for the pull request, and welcome! The Rails team is excited to review your changes, and you should hear from @schneems (or someone else) soon.
If any changes to this PR are deemed necessary, please add them as extra commits. This ensures that the reviewer can see what has changed since they last reviewed the code. Due to the way GitHub handles out-of-date commits, this should also make it reasonably obvious what issues have or haven't been addressed. Large or tricky changes may require several passes of review and changes.
This repository is being automatically checked for code quality issues using Code Climate. You can see results for this analysis in the PR status below. Newly introduced issues should be fixed before a Pull Request is considered ready to review.
Please see the contribution instructions for more information.
While we're touching these, can we just refactor it to use
SELECT column_name FROM information_schema.key_column_usage WHERE constraint_name IN ( SELECT table_constraints.constraint_name FROM information_schema.table_constraints WHERE constraint_type = 'PRIMARY KEY' ) AND table_name = $1 AND table_schema = $2
(If anyone wanted to refactor all of our schema lookup code to use
@sgrif seems like a pretty good idea. The query can't be optimized quite as well this way, but I suppose the gain in DRY in the Rails codebase could be of greater importance. What do you think?
I'm happy to update my patch as you suggest, but I think I'll stick to just modifying
The query diff (before refactoring to the rest of the adapters) would be:
And there's the
@sgrif Good point. My motivation here had more to do with simplifying the query than optimizing it, to improve compatibility for Postgres backends that might not support common table expressions, a feature which is only used in this query - the latter was just a side-effect.
I've updated the patch to modify this query to use
I spent a little time seeing what it would take to move the
Yeah, the definition of "schema" varies by backend (and of the in-tree adapters is only relevant to postgres), so you'll probably want to have the abstract version ask the adapter to split the string into schema and table name (with a default impl returning