perf(db): Reorder index columns for primary keys

When processing a controller API request, system uses a query to fetch
the grants for the requesting user. This query requires pulling together
information from several tables, and is currently performing many
sequential scans to do so. For a number of the tables involved, there
are indexes from multi-column primary keys, however, due to the order of
the columns in the index, the postgres planner would need to do a full
scan of the index, which can be less efficient than a sequential scan,
so instead it will perform a sequential scan of the table.

This recreates the primary keys while swapping the order of the columns
in the primary key definition, and thus the order in the index. By doing
so, the planner will not need to perform a full index scan, and will be
more likely to use the index when executing the grants query.
pull/5126/head
Timothy Messier 2 years ago
parent 263a96e9dd
commit 5577b3c358
No known key found for this signature in database
GPG Key ID: EFD2F184F7600572

@ -0,0 +1,39 @@
-- Copyright (c) HashiCorp, Inc.
-- SPDX-License-Identifier: BUSL-1.1
begin;
-- For each of these tables, swap the ordering of the
-- columns in the index for the primary key.
-- This helps the grants query that contains
-- several where clauses on what is currently the second
-- column in these indexes. By swapping the order, this
-- will make it more likely that the query planner will
-- choose to use the index.
-- See: https://www.postgresql.org/docs/current/indexes-multicolumn.html
alter table auth_oidc_managed_group_member_account
drop constraint auth_oidc_managed_group_member_account_pkey,
add primary key (member_id, managed_group_id);
alter table iam_managed_group_role
drop constraint iam_managed_group_role_pkey,
add primary key (principal_id, role_id);
alter table iam_group_member_user
drop constraint iam_group_member_user_pkey,
add primary key (member_id, group_id);
alter table iam_group_role
drop constraint iam_group_role_pkey,
add primary key (principal_id, role_id);
alter table iam_user_role
drop constraint iam_user_role_pkey,
add primary key (principal_id, role_id);
analyze auth_oidc_managed_group_member_account,
iam_managed_group_role,
iam_group_member_user,
iam_group_role,
iam_user_role;
commit;
Loading…
Cancel
Save