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

Add version to auditable_index #427

Merged

Conversation

fatkodima
Copy link
Contributor

This will optimize:

  • two scopes from
    scope :from_version, ->(version){ where('version >= ?', version) }
    scope :to_version, ->(version){ where('version <= ?', version) }

    as they always will be used with auditable_id and auditable_type (like in user.audits.from_version(100)), so new index will be used to speed this up;
  • and here
    max = self.class.auditable_finder(auditable_id, auditable_type).descending.first.try(:version) || 0
    Notice also, that now no auditable object will be loaded in this line

Probably, this index should be a UNIQUE index, but there are possible race conditions, at least at previously mentioned line.

Simple data for testing:

INSERT
INTO audits (auditable_id, auditable_type, version)
SELECT i % 1000 + 1, 'User', random() * 1000
FROM generate_series(1, 10000000) AS i;

With old index:

explain analyze select max(version) from audits where auditable_id = 12 and auditable_type = 'User'

Aggregate  (cost=16718.01..16718.02 rows=1 width=4) (actual time=49.106..49.107 rows=1 loops=1)
  ->  Index Scan using auditable_index on audits  (cost=0.43..16694.02 rows=9598 width=4) (actual time=1.541..47.316 rows=10000 loops=1)
        Index Cond: (((auditable_type)::text = 'User'::text) AND (auditable_id = 12))
Planning time: 0.190 ms
Execution time: 49.131 ms

With new index:

explain analyze select max(version) from audits where auditable_id = 525 and auditable_type = 'User'

    ->  Limit  (cost=0.43..1.36 rows=1 width=4) (actual time=0.064..0.064 rows=1 loops=1)
          ->  Index Only Scan Backward using auditable_index on audits  (cost=0.43..8997.91 rows=9735 width=4) (actual time=0.063..0.063 rows=1 loops=1)
                Index Cond: ((auditable_type = 'User'::text) AND (auditable_id = 525) AND (version IS NOT NULL))
                Heap Fetches: 1
Planning time: 2.660 ms
Execution time: 0.082 ms

So, 3 orders of magnitude faster.

Closes #189

@fatkodima fatkodima force-pushed the add-version-to-auditable_index branch from 1cceb62 to 180c721 Compare April 1, 2018 23:12
Copy link
Collaborator

@tbrisker tbrisker left a comment

Choose a reason for hiding this comment

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

Great work @fatkodima !

@tbrisker tbrisker merged commit dc72762 into collectiveidea:master Apr 4, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants