Merge pull request #1076 from matrix-org/erikj/state_storage

Use windowing function to make use of index
This commit is contained in:
Erik Johnston 2016-09-07 14:57:25 +01:00 committed by GitHub
commit 91279fd218

View File

@ -315,6 +315,10 @@ class StateStore(SQLBaseStore):
# against `state_groups_state` to fetch the latest state. # against `state_groups_state` to fetch the latest state.
# It assumes that previous state groups are always numerically # It assumes that previous state groups are always numerically
# lesser. # lesser.
# The PARTITION is used to get the event_id in the greatest state
# group for the given type, state_key.
# This may return multiple rows per (type, state_key), but last_value
# should be the same.
sql = (""" sql = ("""
WITH RECURSIVE state(state_group) AS ( WITH RECURSIVE state(state_group) AS (
VALUES(?::bigint) VALUES(?::bigint)
@ -322,11 +326,12 @@ class StateStore(SQLBaseStore):
SELECT prev_state_group FROM state_group_edges e, state s SELECT prev_state_group FROM state_group_edges e, state s
WHERE s.state_group = e.state_group WHERE s.state_group = e.state_group
) )
SELECT type, state_key, event_id FROM state_groups_state SELECT type, state_key, last_value(event_id) OVER (
WHERE ROW(type, state_key, state_group) IN ( PARTITION BY type, state_key ORDER BY state_group ASC
SELECT type, state_key, max(state_group) FROM state ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
INNER JOIN state_groups_state USING (state_group) ) AS event_id FROM state_groups_state
GROUP BY type, state_key WHERE state_group IN (
SELECT state_group FROM state
) )
%s; %s;
""") % (where_clause,) """) % (where_clause,)