Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Index the share, tag-link and per-user state columns the recording and sharing lists read by, on new and existing databases (D#483)
Murtaza Nasird83bee849ad0
diff --git a/src/init_db.py b/src/init_db.pyindex f943110a..5d4de081 100644--- a/src/init_db.py+++ b/src/init_db.py@@ -320,6 +320,17 @@ def _run_migrations(app, engine):# Chunks are read and deleted by recording, in order (D#441)create_index_if_not_exists(engine, 'ix_transcript_chunk_recording', 'transcript_chunk','recording_id, chunk_index')+ # The recording lists and the Shared Transcripts list read shares,+ # tag links and per-user states by these columns (D#483)+ for index_name, table_name, columns in (+ ('ix_share_recording_id', 'share', 'recording_id'),+ ('ix_share_user_id', 'share', 'user_id'),+ ('ix_internal_share_shared_with_user_id', 'internal_share', 'shared_with_user_id'),+ ('ix_internal_share_owner_id', 'internal_share', 'owner_id'),+ ('ix_shared_recording_state_user_id', 'shared_recording_state', 'user_id'),+ ('ix_recording_tags_tag_id', 'recording_tags', 'tag_id'),+ ):+ create_index_if_not_exists(engine, index_name, table_name, columns)if add_column_if_not_exists(engine, 'recording', 'processing_time_seconds', 'INTEGER'):app.logger.info("Added processing_time_seconds column to recording table")if add_column_if_not_exists(engine, 'recording', 'transcription_duration_seconds', 'INTEGER'):diff --git a/src/models/organization.py b/src/models/organization.pyindex 99c3cc3f..2d6f6534 100644--- a/src/models/organization.py+++ b/src/models/organization.py@@ -75,6 +75,9 @@ class RecordingTag(db.Model):added_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=True)order = db.Column(db.Integer, nullable=False, default=0)+ # The primary key starts with recording_id; tag counts read by tag (D#483)+ __table_args__ = (db.Index('ix_recording_tags_tag_id', 'tag_id'),)+# Relationshipsrecording = db.relationship('Recording', back_populates='tag_associations')tag = db.relationship('Tag', back_populates='recording_associations')diff --git a/src/models/sharing.py b/src/models/sharing.pyindex ee71042e..96c3d763 100644--- a/src/models/sharing.py+++ b/src/models/sharing.py@@ -31,6 +31,13 @@ class Share(db.Model):user = db.relationship('User', backref=db.backref('shares', lazy=True, cascade='all, delete-orphan'))recording = db.relationship('Recording', backref=db.backref('shares', lazy=True, cascade='all, delete-orphan'))+ # The recording lists count links by recording and the Shared+ # Transcripts list reads them by user (D#483)+ __table_args__ = (+ db.Index('ix_share_recording_id', 'recording_id'),+ db.Index('ix_share_user_id', 'user_id'),+ )+def to_dict(self):"""Convert model to dictionary representation."""return {@@ -77,8 +84,14 @@ class InternalShare(db.Model):owner = db.relationship('User', foreign_keys=[owner_id], backref=db.backref('shared_recordings', lazy=True, cascade='all, delete'))shared_with = db.relationship('User', foreign_keys=[shared_with_user_id], backref=db.backref('received_shares', lazy=True, cascade='all, delete'))- # Unique constraint: can't share same recording with same user twice- __table_args__ = (db.UniqueConstraint('recording_id', 'shared_with_user_id', name='unique_recording_share'),)+ # Unique constraint: can't share same recording with same user twice.+ # The recording lists find a user's shares by recipient and the Shared+ # Transcripts list by owner (D#483).+ __table_args__ = (+ db.UniqueConstraint('recording_id', 'shared_with_user_id', name='unique_recording_share'),+ db.Index('ix_internal_share_shared_with_user_id', 'shared_with_user_id'),+ db.Index('ix_internal_share_owner_id', 'owner_id'),+ )def to_dict(self):"""Convert model to dictionary representation."""@@ -224,8 +237,12 @@ class SharedRecordingState(db.Model):recording = db.relationship('Recording', backref=db.backref('user_states', lazy=True, cascade='all, delete-orphan'))user = db.relationship('User', backref=db.backref('recording_states', lazy=True, cascade='all, delete-orphan'))- # Unique constraint: one state per user per recording- __table_args__ = (db.UniqueConstraint('recording_id', 'user_id', name='unique_user_recording_state'),)+ # Unique constraint: one state per user per recording. The starred and+ # inbox filters of the recording list read a user's states (D#483).+ __table_args__ = (+ db.UniqueConstraint('recording_id', 'user_id', name='unique_user_recording_state'),+ db.Index('ix_shared_recording_state_user_id', 'user_id'),+ )def to_dict(self):"""Convert model to dictionary representation."""diff --git a/tests/test_list_indexes.py b/tests/test_list_indexes.pynew file mode 100644index 00000000..d5ccc15b--- /dev/null+++ b/tests/test_list_indexes.py@@ -0,0 +1,47 @@+"""Indexes behind the recording and sharing lists (D#483).++The batched list queries read shares, tag links and per-user states by+columns that had no index (the primary key of recording_tags and the unique+constraints start with recording_id), so each such lookup scanned its table.+"""++import pytest+from sqlalchemy import inspect, text++from src.app import app, db++INDEXES = [+ ('share', 'ix_share_recording_id', ['recording_id']),+ ('share', 'ix_share_user_id', ['user_id']),+ ('internal_share', 'ix_internal_share_shared_with_user_id', ['shared_with_user_id']),+ ('internal_share', 'ix_internal_share_owner_id', ['owner_id']),+ ('shared_recording_state', 'ix_shared_recording_state_user_id', ['user_id']),+ ('recording_tags', 'ix_recording_tags_tag_id', ['tag_id']),+]++# One query of the lists per index, as the list code issues it+QUERIES = {+ 'ix_share_recording_id': 'SELECT recording_id, count(*) FROM share WHERE recording_id IN (1, 2) GROUP BY recording_id',+ 'ix_share_user_id': 'SELECT * FROM share WHERE user_id = 1 ORDER BY created_at DESC',+ 'ix_internal_share_shared_with_user_id': 'SELECT recording_id FROM internal_share WHERE shared_with_user_id = 1',+ 'ix_internal_share_owner_id': 'SELECT * FROM internal_share WHERE owner_id = 1 ORDER BY created_at DESC',+ 'ix_shared_recording_state_user_id':+ 'SELECT recording_id FROM shared_recording_state WHERE user_id = 1 AND is_highlighted = 1',+ 'ix_recording_tags_tag_id': 'SELECT tag_id, count(*) FROM recording_tags WHERE tag_id IN (1, 2) GROUP BY tag_id',+}++[email protected]('table, name, columns', INDEXES)+def test_list_lookup_columns_are_indexed(table, name, columns):+ with app.app_context():+ indexes = {i['name']: i['column_names'] for i in inspect(db.engine).get_indexes(table)}+ assert indexes.get(name) == columns++[email protected]('name', sorted(QUERIES))+def test_list_lookups_use_the_index(name):+ with app.app_context():+ if db.engine.dialect.name != 'sqlite':+ return+ plan = db.session.execute(text('EXPLAIN QUERY PLAN ' + QUERIES[name])).fetchall()+ assert any(name in str(row) for row in plan), plan