perf(db): Add indexes on foreign key to improve delete performance

This adds indexes for a few categories:

1. Foreign keys on the session table. These are set to `null` when the
   referenced row is deleted. These indexes will help to more
   efficiently set these `null` values in the case where a target is
   deleted, or and auth token is deleted.
2. Foreign keys from other tables to the session table. These are either
   set to `null` or cascade deleted when a session is deleted. These
   indexes help with these update/deletes when a session is deleted.
3. A multi-column index on session_state. This helps with the query that
   is used to delete all terminated sessions that have been terminated
   for over an hour.

(cherry picked from commit 263a96e9dd)
pull/5128/head
Timothy Messier 2 years ago
parent 62d4f8453b
commit c9578b441a
No known key found for this signature in database
GPG Key ID: EFD2F184F7600572

@ -0,0 +1,46 @@
-- Copyright (c) HashiCorp, Inc.
-- SPDX-License-Identifier: BUSL-1.1
begin;
-- Index to help when setting target_id to null on a session
-- when the corresponding target is deleted.
drop index if exists session_target_id_ix;
create index session_target_id_ix
on session (target_id);
-- Index to help when setting auth_token_id to null on a session
-- when the corresponding auth_token is deleted.
drop index if exists session_auth_token_id_ix;
create index session_auth_token_id_ix
on session (auth_token_id);
-- Index to help when setting session_id to null on a credential_vault_credential
-- when the corresponding session is deleted.
drop index if exists credential_vault_credential_session_id_ix;
create index credential_vault_credential_session_id_ix
on credential_vault_credential (session_id);
-- Index to help delete cascade of session_worker_protocol
-- when the corresponding session is deleted.
drop index if exists session_worker_protocol_session_id_ix;
create index session_worker_protocol_session_id_ix
on session_worker_protocol (session_id);
-- Index to help when setting session_id to null on recording_connection
-- when the corresponding session is deleted.
drop index if exists recording_connection_session_id_ix;
create index recording_connection_session_id_ix
on recording_connection (session_id);
-- Index to help delete of terminated sessions.
drop index if exists session_state_state_start_time_ix;
create index session_state_state_terminated_start_time_ix
on session_state (state, start_time)
where state = 'terminated';
analyze session,
credential_vault_credential,
session_worker_protocol,
recording_connection,
session_state;
commit;
Loading…
Cancel
Save