Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

test: cover the upgrade path by running current migrations over real schemas from five older releases

Murtaza Nasircaf88df0be26
diff --git a/scripts/generate_schema_fixtures.py b/scripts/generate_schema_fixtures.py
new file mode 100755
index 00000000..2ca4c78f
--- /dev/null
+++ b/scripts/generate_schema_fixtures.py
@@ -0,0 +1,154 @@
+#!/usr/bin/env python3
+"""Generate the historical schema fixtures used by tests/test_upgrade_path.py.
+
+Each fixture is the real schema of a tagged release, dumped by checking that tag
+out into a temporary worktree and letting its own models build a database. The
+result is written as plain SQL so the tests need no old dependencies, no network
+and no Docker, and cannot drift as this script changes.
+
+This is a maintenance tool, not part of the test run. You only need it when
+adding a version to cover, and the existing fixtures should not be regenerated
+casually: they are a record of what those releases actually produced.
+
+ python scripts/generate_schema_fixtures.py # default tags
+ python scripts/generate_schema_fixtures.py v0.9.0-alpha ... # specific tags
+
+Old releases need packages the current environment may not have. Anything
+missing is installed into a throwaway directory rather than your virtualenv.
+Heavy optional dependencies that only need to be importable are stubbed.
+"""
+
+import os
+import re
+import shutil
+import sqlite3
+import subprocess
+import sys
+import tempfile
+
+REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+OUT_DIR = os.path.join(REPO, 'tests', 'fixtures', 'schemas')
+PYTHON = sys.executable
+
+DEFAULT_TAGS = [
+ 'v0.5.8-alpha', # pre can_share_publicly; the shape that wedged #379
+ 'v0.7.0-alpha', # SSO arrives, and with it the password-nullable migration
+ 'v0.8.21-alpha',
+ 'v0.9.7-alpha',
+ 'v0.10.3-alpha', # the release before the migration was rewritten
+]
+
+# import name -> pip package, where they differ
+PACKAGES = {
+ 'jwt': 'PyJWT', 'dateutil': 'python-dateutil', 'dotenv': 'python-dotenv',
+ 'yaml': 'PyYAML', 'PIL': 'Pillow', 'magic': 'python-magic',
+ 'sqlalchemy': 'SQLAlchemy', 'bs4': 'beautifulsoup4', 'jose': 'python-jose',
+ 'Crypto': 'pycryptodome', 'pkg_resources': 'setuptools',
+}
+
+# Only needs to import; never called during schema creation. Installing the real
+# thing would pull in the whole scientific stack for nothing.
+STUBS = {
+ 'sklearn/__init__.py': '',
+ 'sklearn/metrics/__init__.py': '',
+ 'sklearn/metrics/pairwise.py':
+ 'def cosine_similarity(*a, **k):\n'
+ ' raise NotImplementedError("stub for schema generation")\n',
+}
+
+BUILD_DB = "from src.app import app, db\nwith app.app_context():\n db.create_all()\nprint('OK')\n"
+
+
+def write_stubs(deps_dir):
+ for path, body in STUBS.items():
+ full = os.path.join(deps_dir, path)
+ os.makedirs(os.path.dirname(full), exist_ok=True)
+ with open(full, 'w') as fh:
+ fh.write(body)
+
+
+def generate(tag, deps_dir):
+ worktree = tempfile.mkdtemp(prefix=f'speakr_{tag}_')
+ data_dir = tempfile.mkdtemp(prefix='speakr_schemagen_')
+ db_path = os.path.join(data_dir, 'schema.db')
+
+ subprocess.run(['git', '-C', REPO, 'worktree', 'add', '-q', '--detach', worktree, tag],
+ check=True)
+ env = dict(
+ os.environ,
+ SQLALCHEMY_DATABASE_URI='sqlite:///' + db_path,
+ UPLOAD_FOLDER=os.path.join(data_dir, 'uploads'),
+ SECRET_KEY='x', TEXT_MODEL_API_KEY='x', TRANSCRIPTION_API_KEY='x', OPENAI_API_KEY='x',
+ TRANSCRIPTION_BASE_URL='https://api.openai.com/v1',
+ TEXT_MODEL_BASE_URL='https://api.openai.com/v1',
+ USE_ASR_ENDPOINT='false', ENABLE_INQUIRE_MODE='false',
+ ENABLE_AUTO_PROCESSING='false', JOB_QUEUE_WORKERS='0', SUMMARY_QUEUE_WORKERS='0',
+ PYTHONPATH=deps_dir + os.pathsep + worktree, PYTHONDONTWRITEBYTECODE='1',
+ )
+
+ try:
+ for _ in range(25):
+ result = subprocess.run([PYTHON, '-c', BUILD_DB], cwd=worktree, env=env,
+ capture_output=True, text=True, timeout=300)
+ if 'OK' in result.stdout:
+ break
+ missing = re.search(r"No module named '([\w.]+)'", result.stderr)
+ if not missing:
+ print(f' {tag}: FAILED\n{result.stderr[-2000:]}')
+ return False
+ module = missing.group(1).split('.')[0]
+ package = PACKAGES.get(module, module)
+ print(f' installing {package}')
+ subprocess.run([PYTHON, '-m', 'pip', 'install', '-q', '--target', deps_dir, package],
+ capture_output=True)
+ else:
+ print(f' {tag}: gave up resolving imports')
+ return False
+
+ con = sqlite3.connect(db_path)
+ objects = con.execute(
+ "SELECT sql FROM sqlite_master WHERE sql IS NOT NULL "
+ "ORDER BY CASE type WHEN 'table' THEN 0 ELSE 1 END, name").fetchall()
+ user_columns = [row[1] for row in con.execute('PRAGMA table_info(user)')]
+ con.close()
+
+ os.makedirs(OUT_DIR, exist_ok=True)
+ path = os.path.join(OUT_DIR, tag + '.sql')
+ with open(path, 'w') as fh:
+ fh.write(f"-- Schema of Speakr {tag}, generated from that tag's own models.\n"
+ f"-- Regenerate with scripts/generate_schema_fixtures.py. Do not hand-edit.\n"
+ f"-- user table: {len(user_columns)} columns\n\n")
+ fh.write(';\n\n'.join(row[0].strip() for row in objects) + ';\n')
+
+ print(f' {tag}: {len(objects)} objects, user has {len(user_columns)} columns')
+ return True
+ finally:
+ subprocess.run(['git', '-C', REPO, 'worktree', 'remove', '--force', worktree],
+ capture_output=True)
+ shutil.rmtree(data_dir, ignore_errors=True)
+
+
+def main():
+ tags = sys.argv[1:] or DEFAULT_TAGS
+ deps_dir = tempfile.mkdtemp(prefix='speakr_olddeps_')
+ write_stubs(deps_dir)
+ print(f'resolving old dependencies into {deps_dir}')
+
+ failed = []
+ try:
+ for tag in tags:
+ print(tag)
+ if not generate(tag, deps_dir):
+ failed.append(tag)
+ finally:
+ shutil.rmtree(deps_dir, ignore_errors=True)
+
+ if failed:
+ print(f'\nfailed: {", ".join(failed)}')
+ return 1
+ print(f'\nwrote {len(tags)} fixture(s) to {OUT_DIR}')
+ return 0
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/tests/fixtures/schemas/v0.10.3-alpha.sql b/tests/fixtures/schemas/v0.10.3-alpha.sql
new file mode 100644
index 00000000..a987569c
--- /dev/null
+++ b/tests/fixtures/schemas/v0.10.3-alpha.sql
@@ -0,0 +1,585 @@
+-- Schema of Speakr v0.10.3-alpha, generated from that tag's own models.
+-- Regenerate with scripts/generate_schema_fixtures.py. Do not hand-edit.
+-- user table: 41 columns
+
+CREATE TABLE api_token (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ token_hash VARCHAR(64) NOT NULL,
+ name VARCHAR(100),
+ created_at DATETIME NOT NULL,
+ last_used_at DATETIME,
+ expires_at DATETIME,
+ revoked BOOLEAN NOT NULL,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE event (
+ id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ description TEXT,
+ start_datetime DATETIME NOT NULL,
+ end_datetime DATETIME,
+ location VARCHAR(500),
+ attendees TEXT,
+ reminder_minutes INTEGER,
+ created_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id)
+);
+
+CREATE TABLE export_template (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ template TEXT NOT NULL,
+ description VARCHAR(500),
+ is_default BOOLEAN,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE folder (
+ id INTEGER NOT NULL,
+ name VARCHAR(50) NOT NULL,
+ user_id INTEGER NOT NULL,
+ group_id INTEGER,
+ color VARCHAR(7),
+ custom_prompt TEXT,
+ default_language VARCHAR(10),
+ default_min_speakers INTEGER,
+ default_max_speakers INTEGER,
+ default_hotwords TEXT,
+ default_initial_prompt TEXT,
+ default_transcription_model VARCHAR(120),
+ protect_from_deletion BOOLEAN,
+ retention_days INTEGER,
+ auto_share_on_apply BOOLEAN,
+ share_with_group_lead BOOLEAN,
+ naming_template_id INTEGER,
+ export_template_id INTEGER,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT _user_folder_uc UNIQUE (name, user_id),
+ FOREIGN KEY(user_id) REFERENCES user (id),
+ FOREIGN KEY(group_id) REFERENCES "group" (id) ON DELETE CASCADE,
+ FOREIGN KEY(naming_template_id) REFERENCES naming_template (id) ON DELETE SET NULL,
+ FOREIGN KEY(export_template_id) REFERENCES export_template (id) ON DELETE SET NULL
+);
+
+CREATE TABLE "group" (
+ id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ description TEXT,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ UNIQUE (name)
+);
+
+CREATE TABLE group_membership (
+ id INTEGER NOT NULL,
+ group_id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ role VARCHAR(20),
+ joined_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT unique_group_membership UNIQUE (group_id, user_id),
+ FOREIGN KEY(group_id) REFERENCES "group" (id) ON DELETE CASCADE,
+ FOREIGN KEY(user_id) REFERENCES user (id) ON DELETE CASCADE
+);
+
+CREATE TABLE initial_prompt_template (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ template TEXT NOT NULL,
+ hotwords TEXT,
+ description VARCHAR(500),
+ is_default BOOLEAN,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE inquire_session (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ session_name VARCHAR(200),
+ filter_tags TEXT,
+ filter_speakers TEXT,
+ filter_date_from DATE,
+ filter_date_to DATE,
+ filter_recording_ids TEXT,
+ created_at DATETIME,
+ last_used DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE internal_share (
+ id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ owner_id INTEGER NOT NULL,
+ shared_with_user_id INTEGER NOT NULL,
+ can_edit BOOLEAN,
+ can_reshare BOOLEAN,
+ source_type VARCHAR(20),
+ source_tag_id INTEGER,
+ source_folder_id INTEGER,
+ created_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT unique_recording_share UNIQUE (recording_id, shared_with_user_id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id) ON DELETE CASCADE,
+ FOREIGN KEY(owner_id) REFERENCES user (id) ON DELETE CASCADE,
+ FOREIGN KEY(shared_with_user_id) REFERENCES user (id) ON DELETE CASCADE,
+ FOREIGN KEY(source_tag_id) REFERENCES tag (id) ON DELETE SET NULL,
+ FOREIGN KEY(source_folder_id) REFERENCES folder (id) ON DELETE SET NULL
+);
+
+CREATE TABLE naming_template (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ template TEXT NOT NULL,
+ description VARCHAR(500),
+ regex_patterns TEXT,
+ is_default BOOLEAN,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE processing_job (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ job_type VARCHAR(50) NOT NULL,
+ status VARCHAR(20) NOT NULL,
+ params TEXT,
+ error_message TEXT,
+ retry_count INTEGER NOT NULL,
+ is_new_upload BOOLEAN NOT NULL,
+ created_at DATETIME NOT NULL,
+ started_at DATETIME,
+ completed_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id) ON DELETE CASCADE
+);
+
+CREATE TABLE push_subscriptions (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ endpoint VARCHAR(500) NOT NULL,
+ p256dh_key VARCHAR(200) NOT NULL,
+ auth_key VARCHAR(100) NOT NULL,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id),
+ UNIQUE (endpoint)
+);
+
+CREATE TABLE recording (
+ user_id INTEGER,
+ id INTEGER NOT NULL,
+ title VARCHAR(200),
+ participants VARCHAR(500),
+ notes TEXT,
+ transcription TEXT,
+ summary TEXT,
+ status VARCHAR(50),
+ audio_path VARCHAR(500),
+ created_at DATETIME,
+ meeting_date DATETIME,
+ file_size INTEGER,
+ original_filename VARCHAR(500),
+ is_inbox BOOLEAN,
+ is_highlighted BOOLEAN,
+ mime_type VARCHAR(100),
+ audio_duration_seconds FLOAT,
+ completed_at DATETIME,
+ processing_time_seconds INTEGER,
+ transcription_duration_seconds INTEGER,
+ summarization_duration_seconds INTEGER,
+ processing_source VARCHAR(50),
+ error_message TEXT,
+ file_hash VARCHAR(64),
+ keep_audio_only BOOLEAN NOT NULL,
+ audio_deleted_at DATETIME,
+ deletion_exempt BOOLEAN,
+ speaker_embeddings JSON,
+ prompt_variables JSON,
+ resolved_hotwords TEXT,
+ resolved_initial_prompt TEXT,
+ export_filename VARCHAR(500),
+ folder_id INTEGER,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id),
+ FOREIGN KEY(folder_id) REFERENCES folder (id) ON DELETE SET NULL
+);
+
+CREATE TABLE recording_session (
+ id VARCHAR(36) NOT NULL,
+ user_id INTEGER NOT NULL,
+ mime_type VARCHAR(100) NOT NULL,
+ status VARCHAR(20) NOT NULL,
+ chunk_count INTEGER NOT NULL,
+ bytes_received BIGINT NOT NULL,
+ finalized_recording_id INTEGER,
+ finalize_metadata TEXT,
+ error_message TEXT,
+ created_at DATETIME NOT NULL,
+ last_seen_at DATETIME NOT NULL,
+ finalized_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id) ON DELETE CASCADE,
+ FOREIGN KEY(finalized_recording_id) REFERENCES recording (id) ON DELETE SET NULL
+);
+
+CREATE TABLE recording_tags (
+ recording_id INTEGER NOT NULL,
+ tag_id INTEGER NOT NULL,
+ added_at DATETIME,
+ "order" INTEGER NOT NULL,
+ PRIMARY KEY (recording_id, tag_id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id),
+ FOREIGN KEY(tag_id) REFERENCES tag (id)
+);
+
+CREATE TABLE share (
+ id INTEGER NOT NULL,
+ public_id VARCHAR(32) NOT NULL,
+ recording_id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ created_at DATETIME,
+ share_summary BOOLEAN,
+ share_notes BOOLEAN,
+ PRIMARY KEY (id),
+ UNIQUE (public_id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE share_audit_log (
+ id INTEGER NOT NULL,
+ action VARCHAR(20) NOT NULL,
+ recording_id INTEGER NOT NULL,
+ actor_id INTEGER NOT NULL,
+ target_user_id INTEGER,
+ permissions_granted JSON,
+ actor_permissions JSON,
+ timestamp DATETIME NOT NULL,
+ share_id INTEGER,
+ notes TEXT,
+ ip_address VARCHAR(45),
+ PRIMARY KEY (id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id) ON DELETE CASCADE,
+ FOREIGN KEY(actor_id) REFERENCES user (id),
+ FOREIGN KEY(target_user_id) REFERENCES user (id)
+);
+
+CREATE TABLE shared_recording_state (
+ id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ personal_notes TEXT,
+ is_inbox BOOLEAN,
+ is_highlighted BOOLEAN,
+ last_viewed DATETIME,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT unique_user_recording_state UNIQUE (recording_id, user_id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id) ON DELETE CASCADE,
+ FOREIGN KEY(user_id) REFERENCES user (id) ON DELETE CASCADE
+);
+
+CREATE TABLE speaker (
+ id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ user_id INTEGER NOT NULL,
+ created_at DATETIME,
+ last_used DATETIME,
+ use_count INTEGER,
+ average_embedding BLOB,
+ embeddings_history JSON,
+ embedding_count INTEGER,
+ confidence_score FLOAT,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE speaker_snippet (
+ id INTEGER NOT NULL,
+ speaker_id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ segment_index INTEGER NOT NULL,
+ text_snippet VARCHAR(200) NOT NULL,
+ timestamp FLOAT,
+ created_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(speaker_id) REFERENCES speaker (id) ON DELETE CASCADE,
+ FOREIGN KEY(recording_id) REFERENCES recording (id) ON DELETE CASCADE
+);
+
+CREATE TABLE system_setting (
+ id INTEGER NOT NULL,
+ "key" VARCHAR(100) NOT NULL,
+ value TEXT,
+ description TEXT,
+ setting_type VARCHAR(50) NOT NULL,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ UNIQUE ("key")
+);
+
+CREATE TABLE tag (
+ id INTEGER NOT NULL,
+ name VARCHAR(50) NOT NULL,
+ user_id INTEGER NOT NULL,
+ group_id INTEGER,
+ color VARCHAR(7),
+ custom_prompt TEXT,
+ default_language VARCHAR(10),
+ default_min_speakers INTEGER,
+ default_max_speakers INTEGER,
+ default_hotwords TEXT,
+ default_initial_prompt TEXT,
+ default_transcription_model VARCHAR(120),
+ protect_from_deletion BOOLEAN,
+ retention_days INTEGER,
+ auto_share_on_apply BOOLEAN,
+ share_with_group_lead BOOLEAN,
+ naming_template_id INTEGER,
+ export_template_id INTEGER,
+ is_auto_process BOOLEAN,
+ auto_process_folder_name VARCHAR(100),
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT _user_tag_uc UNIQUE (name, user_id),
+ FOREIGN KEY(user_id) REFERENCES user (id),
+ FOREIGN KEY(group_id) REFERENCES "group" (id) ON DELETE CASCADE,
+ FOREIGN KEY(naming_template_id) REFERENCES naming_template (id) ON DELETE SET NULL,
+ FOREIGN KEY(export_template_id) REFERENCES export_template (id) ON DELETE SET NULL
+);
+
+CREATE TABLE token_usage (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ date DATE NOT NULL,
+ operation_type VARCHAR(50) NOT NULL,
+ prompt_tokens INTEGER,
+ completion_tokens INTEGER,
+ total_tokens INTEGER,
+ cached_tokens INTEGER,
+ cache_write_tokens INTEGER,
+ cost FLOAT,
+ request_count INTEGER,
+ model_name VARCHAR(100),
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT uq_user_date_op UNIQUE (user_id, date, operation_type),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE transcript_chunk (
+ id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ chunk_index INTEGER NOT NULL,
+ content TEXT NOT NULL,
+ start_time FLOAT,
+ end_time FLOAT,
+ speaker_name VARCHAR(100),
+ embedding BLOB,
+ created_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE transcript_template (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ template TEXT NOT NULL,
+ description VARCHAR(500),
+ is_default BOOLEAN,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE transcription_usage (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ date DATE NOT NULL,
+ connector_type VARCHAR(50) NOT NULL,
+ audio_duration_seconds INTEGER,
+ estimated_cost FLOAT,
+ request_count INTEGER,
+ model_name VARCHAR(100),
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT uq_user_date_connector UNIQUE (user_id, date, connector_type),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE user (
+ id INTEGER NOT NULL,
+ username VARCHAR(20) NOT NULL,
+ email VARCHAR(120) NOT NULL,
+ password VARCHAR(60),
+ sso_provider VARCHAR(100),
+ sso_subject VARCHAR(255),
+ is_admin BOOLEAN,
+ can_share_publicly BOOLEAN,
+ transcription_language VARCHAR(10),
+ output_language VARCHAR(50),
+ ui_language VARCHAR(10),
+ summary_prompt TEXT,
+ extract_events BOOLEAN,
+ name VARCHAR(100),
+ job_title VARCHAR(100),
+ company VARCHAR(100),
+ diarize BOOLEAN,
+ default_naming_template_id INTEGER,
+ monthly_token_budget INTEGER,
+ monthly_transcription_budget INTEGER,
+ email_verified BOOLEAN,
+ email_verification_token VARCHAR(200),
+ email_verification_sent_at DATETIME,
+ password_reset_token VARCHAR(200),
+ password_reset_sent_at DATETIME,
+ auto_speaker_labelling BOOLEAN,
+ auto_speaker_labelling_threshold VARCHAR(10),
+ auto_summarization BOOLEAN,
+ transcription_hotwords TEXT,
+ transcription_initial_prompt TEXT,
+ parse_filename_dates BOOLEAN,
+ filename_date_pattern VARCHAR(50),
+ filename_date_regex VARCHAR(500),
+ export_filename_template VARCHAR(500),
+ summary_include_timestamps BOOLEAN,
+ summary_timestamp_template_id INTEGER,
+ chat_include_timestamps BOOLEAN,
+ chat_timestamp_template_id INTEGER,
+ show_timestamps_simple_view BOOLEAN,
+ editor_autosave BOOLEAN,
+ audio_player_position VARCHAR(10),
+ PRIMARY KEY (id),
+ UNIQUE (username),
+ UNIQUE (email),
+ UNIQUE (sso_subject),
+ FOREIGN KEY(default_naming_template_id) REFERENCES naming_template (id) ON DELETE SET NULL,
+ FOREIGN KEY(summary_timestamp_template_id) REFERENCES transcript_template (id) ON DELETE SET NULL,
+ FOREIGN KEY(chat_timestamp_template_id) REFERENCES transcript_template (id) ON DELETE SET NULL
+);
+
+CREATE TABLE webhook (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ url VARCHAR(500) NOT NULL,
+ allow_http BOOLEAN NOT NULL,
+ secret VARCHAR(120) NOT NULL,
+ events TEXT NOT NULL,
+ enabled BOOLEAN NOT NULL,
+ auto_paused BOOLEAN NOT NULL,
+ consecutive_failures INTEGER NOT NULL,
+ created_at DATETIME NOT NULL,
+ updated_at DATETIME NOT NULL,
+ last_delivery_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id) ON DELETE CASCADE
+);
+
+CREATE TABLE webhook_delivery (
+ id INTEGER NOT NULL,
+ webhook_id INTEGER NOT NULL,
+ event_id VARCHAR(36) NOT NULL,
+ event_type VARCHAR(80) NOT NULL,
+ payload TEXT NOT NULL,
+ attempt_count INTEGER NOT NULL,
+ status VARCHAR(20) NOT NULL,
+ response_status INTEGER,
+ response_body_preview VARCHAR(2000),
+ error_message VARCHAR(500),
+ next_retry_at DATETIME,
+ created_at DATETIME NOT NULL,
+ delivered_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(webhook_id) REFERENCES webhook (id) ON DELETE CASCADE
+);
+
+CREATE INDEX idx_delivery_status_retry ON webhook_delivery (status, next_retry_at);
+
+CREATE INDEX idx_token_user_date ON token_usage (user_id, date);
+
+CREATE INDEX idx_transcription_user_date ON transcription_usage (user_id, date);
+
+CREATE INDEX idx_user_speaker_name ON transcript_chunk (user_id, speaker_name);
+
+CREATE INDEX ix_api_token_revoked ON api_token (revoked);
+
+CREATE UNIQUE INDEX ix_api_token_token_hash ON api_token (token_hash);
+
+CREATE INDEX ix_processing_job_created_at ON processing_job (created_at);
+
+CREATE INDEX ix_processing_job_recording_id ON processing_job (recording_id);
+
+CREATE INDEX ix_processing_job_status ON processing_job (status);
+
+CREATE INDEX ix_processing_job_user_id ON processing_job (user_id);
+
+CREATE INDEX ix_recording_folder_id ON recording (folder_id);
+
+CREATE INDEX ix_recording_session_created_at ON recording_session (created_at);
+
+CREATE INDEX ix_recording_session_finalized_recording_id ON recording_session (finalized_recording_id);
+
+CREATE INDEX ix_recording_session_last_seen_at ON recording_session (last_seen_at);
+
+CREATE INDEX ix_recording_session_status ON recording_session (status);
+
+CREATE INDEX ix_recording_session_user_id ON recording_session (user_id);
+
+CREATE INDEX ix_recording_user_file_hash ON "recording" (user_id, file_hash);
+
+CREATE INDEX ix_transcript_chunk_speaker_name ON transcript_chunk (speaker_name);
+
+CREATE INDEX ix_user_email_verification_token ON user (email_verification_token);
+
+CREATE INDEX ix_user_password_reset_token ON user (password_reset_token);
+
+CREATE UNIQUE INDEX ix_user_sso_subject ON "user" (sso_subject);
+
+CREATE INDEX ix_webhook_delivery_created_at ON webhook_delivery (created_at);
+
+CREATE INDEX ix_webhook_delivery_event_id ON webhook_delivery (event_id);
+
+CREATE INDEX ix_webhook_delivery_event_type ON webhook_delivery (event_type);
+
+CREATE INDEX ix_webhook_delivery_next_retry_at ON webhook_delivery (next_retry_at);
+
+CREATE INDEX ix_webhook_delivery_status ON webhook_delivery (status);
+
+CREATE INDEX ix_webhook_delivery_webhook_id ON webhook_delivery (webhook_id);
+
+CREATE INDEX ix_webhook_enabled ON webhook (enabled);
+
+CREATE INDEX ix_webhook_user_id ON webhook (user_id);
diff --git a/tests/fixtures/schemas/v0.5.8-alpha.sql b/tests/fixtures/schemas/v0.5.8-alpha.sql
new file mode 100644
index 00000000..825e7e3e
--- /dev/null
+++ b/tests/fixtures/schemas/v0.5.8-alpha.sql
@@ -0,0 +1,170 @@
+-- Schema of Speakr v0.5.8-alpha, generated from that tag's own models.
+-- Regenerate with scripts/generate_schema_fixtures.py. Do not hand-edit.
+-- user table: 14 columns
+
+CREATE TABLE event (
+ id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ description TEXT,
+ start_datetime DATETIME NOT NULL,
+ end_datetime DATETIME,
+ location VARCHAR(500),
+ attendees TEXT,
+ reminder_minutes INTEGER,
+ created_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id)
+);
+
+CREATE TABLE inquire_session (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ session_name VARCHAR(200),
+ filter_tags TEXT,
+ filter_speakers TEXT,
+ filter_date_from DATE,
+ filter_date_to DATE,
+ filter_recording_ids TEXT,
+ created_at DATETIME,
+ last_used DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE recording (
+ user_id INTEGER,
+ id INTEGER NOT NULL,
+ title VARCHAR(200),
+ participants VARCHAR(500),
+ notes TEXT,
+ transcription TEXT,
+ summary TEXT,
+ status VARCHAR(50),
+ audio_path VARCHAR(500),
+ created_at DATETIME,
+ meeting_date DATE,
+ file_size INTEGER,
+ original_filename VARCHAR(500),
+ is_inbox BOOLEAN,
+ is_highlighted BOOLEAN,
+ mime_type VARCHAR(100),
+ completed_at DATETIME,
+ processing_time_seconds INTEGER,
+ processing_source VARCHAR(50),
+ error_message TEXT,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE recording_tags (
+ recording_id INTEGER NOT NULL,
+ tag_id INTEGER NOT NULL,
+ added_at DATETIME,
+ "order" INTEGER NOT NULL,
+ PRIMARY KEY (recording_id, tag_id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id),
+ FOREIGN KEY(tag_id) REFERENCES tag (id)
+);
+
+CREATE TABLE share (
+ id INTEGER NOT NULL,
+ public_id VARCHAR(32) NOT NULL,
+ recording_id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ created_at DATETIME,
+ share_summary BOOLEAN,
+ share_notes BOOLEAN,
+ PRIMARY KEY (id),
+ UNIQUE (public_id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE speaker (
+ id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ user_id INTEGER NOT NULL,
+ created_at DATETIME,
+ last_used DATETIME,
+ use_count INTEGER,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE system_setting (
+ id INTEGER NOT NULL,
+ "key" VARCHAR(100) NOT NULL,
+ value TEXT,
+ description TEXT,
+ setting_type VARCHAR(50) NOT NULL,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ UNIQUE ("key")
+);
+
+CREATE TABLE tag (
+ id INTEGER NOT NULL,
+ name VARCHAR(50) NOT NULL,
+ user_id INTEGER NOT NULL,
+ color VARCHAR(7),
+ custom_prompt TEXT,
+ default_language VARCHAR(10),
+ default_min_speakers INTEGER,
+ default_max_speakers INTEGER,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT _user_tag_uc UNIQUE (name, user_id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE transcript_chunk (
+ id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ chunk_index INTEGER NOT NULL,
+ content TEXT NOT NULL,
+ start_time FLOAT,
+ end_time FLOAT,
+ speaker_name VARCHAR(100),
+ embedding BLOB,
+ created_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE transcript_template (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ template TEXT NOT NULL,
+ description VARCHAR(500),
+ is_default BOOLEAN,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE user (
+ id INTEGER NOT NULL,
+ username VARCHAR(20) NOT NULL,
+ email VARCHAR(120) NOT NULL,
+ password VARCHAR(60) NOT NULL,
+ is_admin BOOLEAN,
+ transcription_language VARCHAR(10),
+ output_language VARCHAR(50),
+ ui_language VARCHAR(10),
+ summary_prompt TEXT,
+ extract_events BOOLEAN,
+ name VARCHAR(100),
+ job_title VARCHAR(100),
+ company VARCHAR(100),
+ diarize BOOLEAN,
+ PRIMARY KEY (id),
+ UNIQUE (username),
+ UNIQUE (email)
+);
diff --git a/tests/fixtures/schemas/v0.7.0-alpha.sql b/tests/fixtures/schemas/v0.7.0-alpha.sql
new file mode 100644
index 00000000..7596eabf
--- /dev/null
+++ b/tests/fixtures/schemas/v0.7.0-alpha.sql
@@ -0,0 +1,338 @@
+-- Schema of Speakr v0.7.0-alpha, generated from that tag's own models.
+-- Regenerate with scripts/generate_schema_fixtures.py. Do not hand-edit.
+-- user table: 17 columns
+
+CREATE TABLE api_token (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ token_hash VARCHAR(64) NOT NULL,
+ name VARCHAR(100),
+ created_at DATETIME NOT NULL,
+ last_used_at DATETIME,
+ expires_at DATETIME,
+ revoked BOOLEAN NOT NULL,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE event (
+ id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ description TEXT,
+ start_datetime DATETIME NOT NULL,
+ end_datetime DATETIME,
+ location VARCHAR(500),
+ attendees TEXT,
+ reminder_minutes INTEGER,
+ created_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id)
+);
+
+CREATE TABLE "group" (
+ id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ description TEXT,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ UNIQUE (name)
+);
+
+CREATE TABLE group_membership (
+ id INTEGER NOT NULL,
+ group_id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ role VARCHAR(20),
+ joined_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT unique_group_membership UNIQUE (group_id, user_id),
+ FOREIGN KEY(group_id) REFERENCES "group" (id) ON DELETE CASCADE,
+ FOREIGN KEY(user_id) REFERENCES user (id) ON DELETE CASCADE
+);
+
+CREATE TABLE inquire_session (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ session_name VARCHAR(200),
+ filter_tags TEXT,
+ filter_speakers TEXT,
+ filter_date_from DATE,
+ filter_date_to DATE,
+ filter_recording_ids TEXT,
+ created_at DATETIME,
+ last_used DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE internal_share (
+ id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ owner_id INTEGER NOT NULL,
+ shared_with_user_id INTEGER NOT NULL,
+ can_edit BOOLEAN,
+ can_reshare BOOLEAN,
+ source_type VARCHAR(20),
+ source_tag_id INTEGER,
+ created_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT unique_recording_share UNIQUE (recording_id, shared_with_user_id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id) ON DELETE CASCADE,
+ FOREIGN KEY(owner_id) REFERENCES user (id) ON DELETE CASCADE,
+ FOREIGN KEY(shared_with_user_id) REFERENCES user (id) ON DELETE CASCADE,
+ FOREIGN KEY(source_tag_id) REFERENCES tag (id) ON DELETE SET NULL
+);
+
+CREATE TABLE processing_job (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ job_type VARCHAR(50) NOT NULL,
+ status VARCHAR(20) NOT NULL,
+ params TEXT,
+ error_message TEXT,
+ retry_count INTEGER NOT NULL,
+ is_new_upload BOOLEAN NOT NULL,
+ created_at DATETIME NOT NULL,
+ started_at DATETIME,
+ completed_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id)
+);
+
+CREATE TABLE push_subscriptions (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ endpoint VARCHAR(500) NOT NULL,
+ p256dh_key VARCHAR(200) NOT NULL,
+ auth_key VARCHAR(100) NOT NULL,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id),
+ UNIQUE (endpoint)
+);
+
+CREATE TABLE recording (
+ user_id INTEGER,
+ id INTEGER NOT NULL,
+ title VARCHAR(200),
+ participants VARCHAR(500),
+ notes TEXT,
+ transcription TEXT,
+ summary TEXT,
+ status VARCHAR(50),
+ audio_path VARCHAR(500),
+ created_at DATETIME,
+ meeting_date DATETIME,
+ file_size INTEGER,
+ original_filename VARCHAR(500),
+ is_inbox BOOLEAN,
+ is_highlighted BOOLEAN,
+ mime_type VARCHAR(100),
+ completed_at DATETIME,
+ processing_time_seconds INTEGER,
+ transcription_duration_seconds INTEGER,
+ summarization_duration_seconds INTEGER,
+ processing_source VARCHAR(50),
+ error_message TEXT,
+ audio_deleted_at DATETIME,
+ deletion_exempt BOOLEAN,
+ speaker_embeddings JSON,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE recording_tags (
+ recording_id INTEGER NOT NULL,
+ tag_id INTEGER NOT NULL,
+ added_at DATETIME,
+ "order" INTEGER NOT NULL,
+ PRIMARY KEY (recording_id, tag_id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id),
+ FOREIGN KEY(tag_id) REFERENCES tag (id)
+);
+
+CREATE TABLE share (
+ id INTEGER NOT NULL,
+ public_id VARCHAR(32) NOT NULL,
+ recording_id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ created_at DATETIME,
+ share_summary BOOLEAN,
+ share_notes BOOLEAN,
+ PRIMARY KEY (id),
+ UNIQUE (public_id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE share_audit_log (
+ id INTEGER NOT NULL,
+ action VARCHAR(20) NOT NULL,
+ recording_id INTEGER NOT NULL,
+ actor_id INTEGER NOT NULL,
+ target_user_id INTEGER,
+ permissions_granted JSON,
+ actor_permissions JSON,
+ timestamp DATETIME NOT NULL,
+ share_id INTEGER,
+ notes TEXT,
+ ip_address VARCHAR(45),
+ PRIMARY KEY (id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id),
+ FOREIGN KEY(actor_id) REFERENCES user (id),
+ FOREIGN KEY(target_user_id) REFERENCES user (id)
+);
+
+CREATE TABLE shared_recording_state (
+ id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ personal_notes TEXT,
+ is_inbox BOOLEAN,
+ is_highlighted BOOLEAN,
+ last_viewed DATETIME,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT unique_user_recording_state UNIQUE (recording_id, user_id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id) ON DELETE CASCADE,
+ FOREIGN KEY(user_id) REFERENCES user (id) ON DELETE CASCADE
+);
+
+CREATE TABLE speaker (
+ id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ user_id INTEGER NOT NULL,
+ created_at DATETIME,
+ last_used DATETIME,
+ use_count INTEGER,
+ average_embedding BLOB,
+ embeddings_history JSON,
+ embedding_count INTEGER,
+ confidence_score FLOAT,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE speaker_snippet (
+ id INTEGER NOT NULL,
+ speaker_id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ segment_index INTEGER NOT NULL,
+ text_snippet VARCHAR(200) NOT NULL,
+ timestamp FLOAT,
+ created_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(speaker_id) REFERENCES speaker (id) ON DELETE CASCADE,
+ FOREIGN KEY(recording_id) REFERENCES recording (id) ON DELETE CASCADE
+);
+
+CREATE TABLE system_setting (
+ id INTEGER NOT NULL,
+ "key" VARCHAR(100) NOT NULL,
+ value TEXT,
+ description TEXT,
+ setting_type VARCHAR(50) NOT NULL,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ UNIQUE ("key")
+);
+
+CREATE TABLE tag (
+ id INTEGER NOT NULL,
+ name VARCHAR(50) NOT NULL,
+ user_id INTEGER NOT NULL,
+ group_id INTEGER,
+ color VARCHAR(7),
+ custom_prompt TEXT,
+ default_language VARCHAR(10),
+ default_min_speakers INTEGER,
+ default_max_speakers INTEGER,
+ protect_from_deletion BOOLEAN,
+ retention_days INTEGER,
+ auto_share_on_apply BOOLEAN,
+ share_with_group_lead BOOLEAN,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT _user_tag_uc UNIQUE (name, user_id),
+ FOREIGN KEY(user_id) REFERENCES user (id),
+ FOREIGN KEY(group_id) REFERENCES "group" (id) ON DELETE CASCADE
+);
+
+CREATE TABLE transcript_chunk (
+ id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ chunk_index INTEGER NOT NULL,
+ content TEXT NOT NULL,
+ start_time FLOAT,
+ end_time FLOAT,
+ speaker_name VARCHAR(100),
+ embedding BLOB,
+ created_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE transcript_template (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ template TEXT NOT NULL,
+ description VARCHAR(500),
+ is_default BOOLEAN,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE user (
+ id INTEGER NOT NULL,
+ username VARCHAR(20) NOT NULL,
+ email VARCHAR(120) NOT NULL,
+ password VARCHAR(60),
+ sso_provider VARCHAR(100),
+ sso_subject VARCHAR(255),
+ is_admin BOOLEAN,
+ can_share_publicly BOOLEAN,
+ transcription_language VARCHAR(10),
+ output_language VARCHAR(50),
+ ui_language VARCHAR(10),
+ summary_prompt TEXT,
+ extract_events BOOLEAN,
+ name VARCHAR(100),
+ job_title VARCHAR(100),
+ company VARCHAR(100),
+ diarize BOOLEAN,
+ PRIMARY KEY (id),
+ UNIQUE (username),
+ UNIQUE (email),
+ UNIQUE (sso_subject)
+);
+
+CREATE INDEX idx_user_speaker_name ON transcript_chunk (user_id, speaker_name);
+
+CREATE INDEX ix_api_token_revoked ON api_token (revoked);
+
+CREATE UNIQUE INDEX ix_api_token_token_hash ON api_token (token_hash);
+
+CREATE INDEX ix_processing_job_created_at ON processing_job (created_at);
+
+CREATE INDEX ix_processing_job_recording_id ON processing_job (recording_id);
+
+CREATE INDEX ix_processing_job_status ON processing_job (status);
+
+CREATE INDEX ix_processing_job_user_id ON processing_job (user_id);
+
+CREATE INDEX ix_transcript_chunk_speaker_name ON transcript_chunk (speaker_name);
+
+CREATE UNIQUE INDEX ix_user_sso_subject ON user (sso_subject);
diff --git a/tests/fixtures/schemas/v0.8.21-alpha.sql b/tests/fixtures/schemas/v0.8.21-alpha.sql
new file mode 100644
index 00000000..56e862d9
--- /dev/null
+++ b/tests/fixtures/schemas/v0.8.21-alpha.sql
@@ -0,0 +1,469 @@
+-- Schema of Speakr v0.8.21-alpha, generated from that tag's own models.
+-- Regenerate with scripts/generate_schema_fixtures.py. Do not hand-edit.
+-- user table: 32 columns
+
+CREATE TABLE api_token (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ token_hash VARCHAR(64) NOT NULL,
+ name VARCHAR(100),
+ created_at DATETIME NOT NULL,
+ last_used_at DATETIME,
+ expires_at DATETIME,
+ revoked BOOLEAN NOT NULL,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE event (
+ id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ description TEXT,
+ start_datetime DATETIME NOT NULL,
+ end_datetime DATETIME,
+ location VARCHAR(500),
+ attendees TEXT,
+ reminder_minutes INTEGER,
+ created_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id)
+);
+
+CREATE TABLE export_template (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ template TEXT NOT NULL,
+ description VARCHAR(500),
+ is_default BOOLEAN,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE folder (
+ id INTEGER NOT NULL,
+ name VARCHAR(50) NOT NULL,
+ user_id INTEGER NOT NULL,
+ group_id INTEGER,
+ color VARCHAR(7),
+ custom_prompt TEXT,
+ default_language VARCHAR(10),
+ default_min_speakers INTEGER,
+ default_max_speakers INTEGER,
+ default_hotwords TEXT,
+ default_initial_prompt TEXT,
+ default_transcription_model VARCHAR(120),
+ protect_from_deletion BOOLEAN,
+ retention_days INTEGER,
+ auto_share_on_apply BOOLEAN,
+ share_with_group_lead BOOLEAN,
+ naming_template_id INTEGER,
+ export_template_id INTEGER,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT _user_folder_uc UNIQUE (name, user_id),
+ FOREIGN KEY(user_id) REFERENCES user (id),
+ FOREIGN KEY(group_id) REFERENCES "group" (id) ON DELETE CASCADE,
+ FOREIGN KEY(naming_template_id) REFERENCES naming_template (id) ON DELETE SET NULL,
+ FOREIGN KEY(export_template_id) REFERENCES export_template (id) ON DELETE SET NULL
+);
+
+CREATE TABLE "group" (
+ id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ description TEXT,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ UNIQUE (name)
+);
+
+CREATE TABLE group_membership (
+ id INTEGER NOT NULL,
+ group_id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ role VARCHAR(20),
+ joined_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT unique_group_membership UNIQUE (group_id, user_id),
+ FOREIGN KEY(group_id) REFERENCES "group" (id) ON DELETE CASCADE,
+ FOREIGN KEY(user_id) REFERENCES user (id) ON DELETE CASCADE
+);
+
+CREATE TABLE inquire_session (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ session_name VARCHAR(200),
+ filter_tags TEXT,
+ filter_speakers TEXT,
+ filter_date_from DATE,
+ filter_date_to DATE,
+ filter_recording_ids TEXT,
+ created_at DATETIME,
+ last_used DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE internal_share (
+ id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ owner_id INTEGER NOT NULL,
+ shared_with_user_id INTEGER NOT NULL,
+ can_edit BOOLEAN,
+ can_reshare BOOLEAN,
+ source_type VARCHAR(20),
+ source_tag_id INTEGER,
+ created_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT unique_recording_share UNIQUE (recording_id, shared_with_user_id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id) ON DELETE CASCADE,
+ FOREIGN KEY(owner_id) REFERENCES user (id) ON DELETE CASCADE,
+ FOREIGN KEY(shared_with_user_id) REFERENCES user (id) ON DELETE CASCADE,
+ FOREIGN KEY(source_tag_id) REFERENCES tag (id) ON DELETE SET NULL
+);
+
+CREATE TABLE naming_template (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ template TEXT NOT NULL,
+ description VARCHAR(500),
+ regex_patterns TEXT,
+ is_default BOOLEAN,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE processing_job (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ job_type VARCHAR(50) NOT NULL,
+ status VARCHAR(20) NOT NULL,
+ params TEXT,
+ error_message TEXT,
+ retry_count INTEGER NOT NULL,
+ is_new_upload BOOLEAN NOT NULL,
+ created_at DATETIME NOT NULL,
+ started_at DATETIME,
+ completed_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id) ON DELETE CASCADE
+);
+
+CREATE TABLE push_subscriptions (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ endpoint VARCHAR(500) NOT NULL,
+ p256dh_key VARCHAR(200) NOT NULL,
+ auth_key VARCHAR(100) NOT NULL,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id),
+ UNIQUE (endpoint)
+);
+
+CREATE TABLE recording (
+ user_id INTEGER,
+ id INTEGER NOT NULL,
+ title VARCHAR(200),
+ participants VARCHAR(500),
+ notes TEXT,
+ transcription TEXT,
+ summary TEXT,
+ status VARCHAR(50),
+ audio_path VARCHAR(500),
+ created_at DATETIME,
+ meeting_date DATETIME,
+ file_size INTEGER,
+ original_filename VARCHAR(500),
+ is_inbox BOOLEAN,
+ is_highlighted BOOLEAN,
+ mime_type VARCHAR(100),
+ completed_at DATETIME,
+ processing_time_seconds INTEGER,
+ transcription_duration_seconds INTEGER,
+ summarization_duration_seconds INTEGER,
+ processing_source VARCHAR(50),
+ error_message TEXT,
+ file_hash VARCHAR(64),
+ audio_deleted_at DATETIME,
+ deletion_exempt BOOLEAN,
+ speaker_embeddings JSON,
+ prompt_variables JSON,
+ folder_id INTEGER,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id),
+ FOREIGN KEY(folder_id) REFERENCES folder (id) ON DELETE SET NULL
+);
+
+CREATE TABLE recording_tags (
+ recording_id INTEGER NOT NULL,
+ tag_id INTEGER NOT NULL,
+ added_at DATETIME,
+ "order" INTEGER NOT NULL,
+ PRIMARY KEY (recording_id, tag_id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id),
+ FOREIGN KEY(tag_id) REFERENCES tag (id)
+);
+
+CREATE TABLE share (
+ id INTEGER NOT NULL,
+ public_id VARCHAR(32) NOT NULL,
+ recording_id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ created_at DATETIME,
+ share_summary BOOLEAN,
+ share_notes BOOLEAN,
+ PRIMARY KEY (id),
+ UNIQUE (public_id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE share_audit_log (
+ id INTEGER NOT NULL,
+ action VARCHAR(20) NOT NULL,
+ recording_id INTEGER NOT NULL,
+ actor_id INTEGER NOT NULL,
+ target_user_id INTEGER,
+ permissions_granted JSON,
+ actor_permissions JSON,
+ timestamp DATETIME NOT NULL,
+ share_id INTEGER,
+ notes TEXT,
+ ip_address VARCHAR(45),
+ PRIMARY KEY (id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id) ON DELETE CASCADE,
+ FOREIGN KEY(actor_id) REFERENCES user (id),
+ FOREIGN KEY(target_user_id) REFERENCES user (id)
+);
+
+CREATE TABLE shared_recording_state (
+ id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ personal_notes TEXT,
+ is_inbox BOOLEAN,
+ is_highlighted BOOLEAN,
+ last_viewed DATETIME,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT unique_user_recording_state UNIQUE (recording_id, user_id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id) ON DELETE CASCADE,
+ FOREIGN KEY(user_id) REFERENCES user (id) ON DELETE CASCADE
+);
+
+CREATE TABLE speaker (
+ id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ user_id INTEGER NOT NULL,
+ created_at DATETIME,
+ last_used DATETIME,
+ use_count INTEGER,
+ average_embedding BLOB,
+ embeddings_history JSON,
+ embedding_count INTEGER,
+ confidence_score FLOAT,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE speaker_snippet (
+ id INTEGER NOT NULL,
+ speaker_id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ segment_index INTEGER NOT NULL,
+ text_snippet VARCHAR(200) NOT NULL,
+ timestamp FLOAT,
+ created_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(speaker_id) REFERENCES speaker (id) ON DELETE CASCADE,
+ FOREIGN KEY(recording_id) REFERENCES recording (id) ON DELETE CASCADE
+);
+
+CREATE TABLE system_setting (
+ id INTEGER NOT NULL,
+ "key" VARCHAR(100) NOT NULL,
+ value TEXT,
+ description TEXT,
+ setting_type VARCHAR(50) NOT NULL,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ UNIQUE ("key")
+);
+
+CREATE TABLE tag (
+ id INTEGER NOT NULL,
+ name VARCHAR(50) NOT NULL,
+ user_id INTEGER NOT NULL,
+ group_id INTEGER,
+ color VARCHAR(7),
+ custom_prompt TEXT,
+ default_language VARCHAR(10),
+ default_min_speakers INTEGER,
+ default_max_speakers INTEGER,
+ default_hotwords TEXT,
+ default_initial_prompt TEXT,
+ default_transcription_model VARCHAR(120),
+ protect_from_deletion BOOLEAN,
+ retention_days INTEGER,
+ auto_share_on_apply BOOLEAN,
+ share_with_group_lead BOOLEAN,
+ naming_template_id INTEGER,
+ export_template_id INTEGER,
+ is_auto_process BOOLEAN,
+ auto_process_folder_name VARCHAR(100),
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT _user_tag_uc UNIQUE (name, user_id),
+ FOREIGN KEY(user_id) REFERENCES user (id),
+ FOREIGN KEY(group_id) REFERENCES "group" (id) ON DELETE CASCADE,
+ FOREIGN KEY(naming_template_id) REFERENCES naming_template (id) ON DELETE SET NULL,
+ FOREIGN KEY(export_template_id) REFERENCES export_template (id) ON DELETE SET NULL
+);
+
+CREATE TABLE token_usage (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ date DATE NOT NULL,
+ operation_type VARCHAR(50) NOT NULL,
+ prompt_tokens INTEGER,
+ completion_tokens INTEGER,
+ total_tokens INTEGER,
+ cost FLOAT,
+ request_count INTEGER,
+ model_name VARCHAR(100),
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT uq_user_date_op UNIQUE (user_id, date, operation_type),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE transcript_chunk (
+ id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ chunk_index INTEGER NOT NULL,
+ content TEXT NOT NULL,
+ start_time FLOAT,
+ end_time FLOAT,
+ speaker_name VARCHAR(100),
+ embedding BLOB,
+ created_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE transcript_template (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ template TEXT NOT NULL,
+ description VARCHAR(500),
+ is_default BOOLEAN,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE transcription_usage (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ date DATE NOT NULL,
+ connector_type VARCHAR(50) NOT NULL,
+ audio_duration_seconds INTEGER,
+ estimated_cost FLOAT,
+ request_count INTEGER,
+ model_name VARCHAR(100),
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT uq_user_date_connector UNIQUE (user_id, date, connector_type),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE user (
+ id INTEGER NOT NULL,
+ username VARCHAR(20) NOT NULL,
+ email VARCHAR(120) NOT NULL,
+ password VARCHAR(60),
+ sso_provider VARCHAR(100),
+ sso_subject VARCHAR(255),
+ is_admin BOOLEAN,
+ can_share_publicly BOOLEAN,
+ transcription_language VARCHAR(10),
+ output_language VARCHAR(50),
+ ui_language VARCHAR(10),
+ summary_prompt TEXT,
+ extract_events BOOLEAN,
+ name VARCHAR(100),
+ job_title VARCHAR(100),
+ company VARCHAR(100),
+ diarize BOOLEAN,
+ default_naming_template_id INTEGER,
+ monthly_token_budget INTEGER,
+ monthly_transcription_budget INTEGER,
+ email_verified BOOLEAN,
+ email_verification_token VARCHAR(200),
+ email_verification_sent_at DATETIME,
+ password_reset_token VARCHAR(200),
+ password_reset_sent_at DATETIME,
+ auto_speaker_labelling BOOLEAN,
+ auto_speaker_labelling_threshold VARCHAR(10),
+ auto_summarization BOOLEAN,
+ transcription_hotwords TEXT,
+ transcription_initial_prompt TEXT,
+ show_timestamps_simple_view BOOLEAN,
+ editor_autosave BOOLEAN,
+ PRIMARY KEY (id),
+ UNIQUE (username),
+ UNIQUE (email),
+ UNIQUE (sso_subject),
+ FOREIGN KEY(default_naming_template_id) REFERENCES naming_template (id) ON DELETE SET NULL
+);
+
+CREATE INDEX idx_token_user_date ON token_usage (user_id, date);
+
+CREATE INDEX idx_transcription_user_date ON transcription_usage (user_id, date);
+
+CREATE INDEX idx_user_speaker_name ON transcript_chunk (user_id, speaker_name);
+
+CREATE INDEX ix_api_token_revoked ON api_token (revoked);
+
+CREATE UNIQUE INDEX ix_api_token_token_hash ON api_token (token_hash);
+
+CREATE INDEX ix_processing_job_created_at ON processing_job (created_at);
+
+CREATE INDEX ix_processing_job_recording_id ON processing_job (recording_id);
+
+CREATE INDEX ix_processing_job_status ON processing_job (status);
+
+CREATE INDEX ix_processing_job_user_id ON processing_job (user_id);
+
+CREATE INDEX ix_recording_folder_id ON recording (folder_id);
+
+CREATE INDEX ix_recording_user_file_hash ON "recording" (user_id, file_hash);
+
+CREATE INDEX ix_transcript_chunk_speaker_name ON transcript_chunk (speaker_name);
+
+CREATE INDEX ix_user_email_verification_token ON user (email_verification_token);
+
+CREATE INDEX ix_user_password_reset_token ON user (password_reset_token);
+
+CREATE UNIQUE INDEX ix_user_sso_subject ON "user" (sso_subject);
diff --git a/tests/fixtures/schemas/v0.9.7-alpha.sql b/tests/fixtures/schemas/v0.9.7-alpha.sql
new file mode 100644
index 00000000..8f756014
--- /dev/null
+++ b/tests/fixtures/schemas/v0.9.7-alpha.sql
@@ -0,0 +1,580 @@
+-- Schema of Speakr v0.9.7-alpha, generated from that tag's own models.
+-- Regenerate with scripts/generate_schema_fixtures.py. Do not hand-edit.
+-- user table: 37 columns
+
+CREATE TABLE api_token (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ token_hash VARCHAR(64) NOT NULL,
+ name VARCHAR(100),
+ created_at DATETIME NOT NULL,
+ last_used_at DATETIME,
+ expires_at DATETIME,
+ revoked BOOLEAN NOT NULL,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE event (
+ id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ description TEXT,
+ start_datetime DATETIME NOT NULL,
+ end_datetime DATETIME,
+ location VARCHAR(500),
+ attendees TEXT,
+ reminder_minutes INTEGER,
+ created_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id)
+);
+
+CREATE TABLE export_template (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ template TEXT NOT NULL,
+ description VARCHAR(500),
+ is_default BOOLEAN,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE folder (
+ id INTEGER NOT NULL,
+ name VARCHAR(50) NOT NULL,
+ user_id INTEGER NOT NULL,
+ group_id INTEGER,
+ color VARCHAR(7),
+ custom_prompt TEXT,
+ default_language VARCHAR(10),
+ default_min_speakers INTEGER,
+ default_max_speakers INTEGER,
+ default_hotwords TEXT,
+ default_initial_prompt TEXT,
+ default_transcription_model VARCHAR(120),
+ protect_from_deletion BOOLEAN,
+ retention_days INTEGER,
+ auto_share_on_apply BOOLEAN,
+ share_with_group_lead BOOLEAN,
+ naming_template_id INTEGER,
+ export_template_id INTEGER,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT _user_folder_uc UNIQUE (name, user_id),
+ FOREIGN KEY(user_id) REFERENCES user (id),
+ FOREIGN KEY(group_id) REFERENCES "group" (id) ON DELETE CASCADE,
+ FOREIGN KEY(naming_template_id) REFERENCES naming_template (id) ON DELETE SET NULL,
+ FOREIGN KEY(export_template_id) REFERENCES export_template (id) ON DELETE SET NULL
+);
+
+CREATE TABLE "group" (
+ id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ description TEXT,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ UNIQUE (name)
+);
+
+CREATE TABLE group_membership (
+ id INTEGER NOT NULL,
+ group_id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ role VARCHAR(20),
+ joined_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT unique_group_membership UNIQUE (group_id, user_id),
+ FOREIGN KEY(group_id) REFERENCES "group" (id) ON DELETE CASCADE,
+ FOREIGN KEY(user_id) REFERENCES user (id) ON DELETE CASCADE
+);
+
+CREATE TABLE initial_prompt_template (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ template TEXT NOT NULL,
+ hotwords TEXT,
+ description VARCHAR(500),
+ is_default BOOLEAN,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE inquire_session (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ session_name VARCHAR(200),
+ filter_tags TEXT,
+ filter_speakers TEXT,
+ filter_date_from DATE,
+ filter_date_to DATE,
+ filter_recording_ids TEXT,
+ created_at DATETIME,
+ last_used DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE internal_share (
+ id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ owner_id INTEGER NOT NULL,
+ shared_with_user_id INTEGER NOT NULL,
+ can_edit BOOLEAN,
+ can_reshare BOOLEAN,
+ source_type VARCHAR(20),
+ source_tag_id INTEGER,
+ source_folder_id INTEGER,
+ created_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT unique_recording_share UNIQUE (recording_id, shared_with_user_id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id) ON DELETE CASCADE,
+ FOREIGN KEY(owner_id) REFERENCES user (id) ON DELETE CASCADE,
+ FOREIGN KEY(shared_with_user_id) REFERENCES user (id) ON DELETE CASCADE,
+ FOREIGN KEY(source_tag_id) REFERENCES tag (id) ON DELETE SET NULL,
+ FOREIGN KEY(source_folder_id) REFERENCES folder (id) ON DELETE SET NULL
+);
+
+CREATE TABLE naming_template (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ template TEXT NOT NULL,
+ description VARCHAR(500),
+ regex_patterns TEXT,
+ is_default BOOLEAN,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE processing_job (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ job_type VARCHAR(50) NOT NULL,
+ status VARCHAR(20) NOT NULL,
+ params TEXT,
+ error_message TEXT,
+ retry_count INTEGER NOT NULL,
+ is_new_upload BOOLEAN NOT NULL,
+ created_at DATETIME NOT NULL,
+ started_at DATETIME,
+ completed_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id) ON DELETE CASCADE
+);
+
+CREATE TABLE push_subscriptions (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ endpoint VARCHAR(500) NOT NULL,
+ p256dh_key VARCHAR(200) NOT NULL,
+ auth_key VARCHAR(100) NOT NULL,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id),
+ UNIQUE (endpoint)
+);
+
+CREATE TABLE recording (
+ user_id INTEGER,
+ id INTEGER NOT NULL,
+ title VARCHAR(200),
+ participants VARCHAR(500),
+ notes TEXT,
+ transcription TEXT,
+ summary TEXT,
+ status VARCHAR(50),
+ audio_path VARCHAR(500),
+ created_at DATETIME,
+ meeting_date DATETIME,
+ file_size INTEGER,
+ original_filename VARCHAR(500),
+ is_inbox BOOLEAN,
+ is_highlighted BOOLEAN,
+ mime_type VARCHAR(100),
+ audio_duration_seconds FLOAT,
+ completed_at DATETIME,
+ processing_time_seconds INTEGER,
+ transcription_duration_seconds INTEGER,
+ summarization_duration_seconds INTEGER,
+ processing_source VARCHAR(50),
+ error_message TEXT,
+ file_hash VARCHAR(64),
+ keep_audio_only BOOLEAN NOT NULL,
+ audio_deleted_at DATETIME,
+ deletion_exempt BOOLEAN,
+ speaker_embeddings JSON,
+ prompt_variables JSON,
+ resolved_hotwords TEXT,
+ resolved_initial_prompt TEXT,
+ folder_id INTEGER,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id),
+ FOREIGN KEY(folder_id) REFERENCES folder (id) ON DELETE SET NULL
+);
+
+CREATE TABLE recording_session (
+ id VARCHAR(36) NOT NULL,
+ user_id INTEGER NOT NULL,
+ mime_type VARCHAR(100) NOT NULL,
+ status VARCHAR(20) NOT NULL,
+ chunk_count INTEGER NOT NULL,
+ bytes_received BIGINT NOT NULL,
+ finalized_recording_id INTEGER,
+ finalize_metadata TEXT,
+ error_message TEXT,
+ created_at DATETIME NOT NULL,
+ last_seen_at DATETIME NOT NULL,
+ finalized_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id) ON DELETE CASCADE,
+ FOREIGN KEY(finalized_recording_id) REFERENCES recording (id) ON DELETE SET NULL
+);
+
+CREATE TABLE recording_tags (
+ recording_id INTEGER NOT NULL,
+ tag_id INTEGER NOT NULL,
+ added_at DATETIME,
+ "order" INTEGER NOT NULL,
+ PRIMARY KEY (recording_id, tag_id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id),
+ FOREIGN KEY(tag_id) REFERENCES tag (id)
+);
+
+CREATE TABLE share (
+ id INTEGER NOT NULL,
+ public_id VARCHAR(32) NOT NULL,
+ recording_id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ created_at DATETIME,
+ share_summary BOOLEAN,
+ share_notes BOOLEAN,
+ PRIMARY KEY (id),
+ UNIQUE (public_id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE share_audit_log (
+ id INTEGER NOT NULL,
+ action VARCHAR(20) NOT NULL,
+ recording_id INTEGER NOT NULL,
+ actor_id INTEGER NOT NULL,
+ target_user_id INTEGER,
+ permissions_granted JSON,
+ actor_permissions JSON,
+ timestamp DATETIME NOT NULL,
+ share_id INTEGER,
+ notes TEXT,
+ ip_address VARCHAR(45),
+ PRIMARY KEY (id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id) ON DELETE CASCADE,
+ FOREIGN KEY(actor_id) REFERENCES user (id),
+ FOREIGN KEY(target_user_id) REFERENCES user (id)
+);
+
+CREATE TABLE shared_recording_state (
+ id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ personal_notes TEXT,
+ is_inbox BOOLEAN,
+ is_highlighted BOOLEAN,
+ last_viewed DATETIME,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT unique_user_recording_state UNIQUE (recording_id, user_id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id) ON DELETE CASCADE,
+ FOREIGN KEY(user_id) REFERENCES user (id) ON DELETE CASCADE
+);
+
+CREATE TABLE speaker (
+ id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ user_id INTEGER NOT NULL,
+ created_at DATETIME,
+ last_used DATETIME,
+ use_count INTEGER,
+ average_embedding BLOB,
+ embeddings_history JSON,
+ embedding_count INTEGER,
+ confidence_score FLOAT,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE speaker_snippet (
+ id INTEGER NOT NULL,
+ speaker_id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ segment_index INTEGER NOT NULL,
+ text_snippet VARCHAR(200) NOT NULL,
+ timestamp FLOAT,
+ created_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(speaker_id) REFERENCES speaker (id) ON DELETE CASCADE,
+ FOREIGN KEY(recording_id) REFERENCES recording (id) ON DELETE CASCADE
+);
+
+CREATE TABLE system_setting (
+ id INTEGER NOT NULL,
+ "key" VARCHAR(100) NOT NULL,
+ value TEXT,
+ description TEXT,
+ setting_type VARCHAR(50) NOT NULL,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ UNIQUE ("key")
+);
+
+CREATE TABLE tag (
+ id INTEGER NOT NULL,
+ name VARCHAR(50) NOT NULL,
+ user_id INTEGER NOT NULL,
+ group_id INTEGER,
+ color VARCHAR(7),
+ custom_prompt TEXT,
+ default_language VARCHAR(10),
+ default_min_speakers INTEGER,
+ default_max_speakers INTEGER,
+ default_hotwords TEXT,
+ default_initial_prompt TEXT,
+ default_transcription_model VARCHAR(120),
+ protect_from_deletion BOOLEAN,
+ retention_days INTEGER,
+ auto_share_on_apply BOOLEAN,
+ share_with_group_lead BOOLEAN,
+ naming_template_id INTEGER,
+ export_template_id INTEGER,
+ is_auto_process BOOLEAN,
+ auto_process_folder_name VARCHAR(100),
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT _user_tag_uc UNIQUE (name, user_id),
+ FOREIGN KEY(user_id) REFERENCES user (id),
+ FOREIGN KEY(group_id) REFERENCES "group" (id) ON DELETE CASCADE,
+ FOREIGN KEY(naming_template_id) REFERENCES naming_template (id) ON DELETE SET NULL,
+ FOREIGN KEY(export_template_id) REFERENCES export_template (id) ON DELETE SET NULL
+);
+
+CREATE TABLE token_usage (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ date DATE NOT NULL,
+ operation_type VARCHAR(50) NOT NULL,
+ prompt_tokens INTEGER,
+ completion_tokens INTEGER,
+ total_tokens INTEGER,
+ cached_tokens INTEGER,
+ cache_write_tokens INTEGER,
+ cost FLOAT,
+ request_count INTEGER,
+ model_name VARCHAR(100),
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT uq_user_date_op UNIQUE (user_id, date, operation_type),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE transcript_chunk (
+ id INTEGER NOT NULL,
+ recording_id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ chunk_index INTEGER NOT NULL,
+ content TEXT NOT NULL,
+ start_time FLOAT,
+ end_time FLOAT,
+ speaker_name VARCHAR(100),
+ embedding BLOB,
+ created_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(recording_id) REFERENCES recording (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE transcript_template (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ template TEXT NOT NULL,
+ description VARCHAR(500),
+ is_default BOOLEAN,
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE transcription_usage (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ date DATE NOT NULL,
+ connector_type VARCHAR(50) NOT NULL,
+ audio_duration_seconds INTEGER,
+ estimated_cost FLOAT,
+ request_count INTEGER,
+ model_name VARCHAR(100),
+ created_at DATETIME,
+ updated_at DATETIME,
+ PRIMARY KEY (id),
+ CONSTRAINT uq_user_date_connector UNIQUE (user_id, date, connector_type),
+ FOREIGN KEY(user_id) REFERENCES user (id)
+);
+
+CREATE TABLE user (
+ id INTEGER NOT NULL,
+ username VARCHAR(20) NOT NULL,
+ email VARCHAR(120) NOT NULL,
+ password VARCHAR(60),
+ sso_provider VARCHAR(100),
+ sso_subject VARCHAR(255),
+ is_admin BOOLEAN,
+ can_share_publicly BOOLEAN,
+ transcription_language VARCHAR(10),
+ output_language VARCHAR(50),
+ ui_language VARCHAR(10),
+ summary_prompt TEXT,
+ extract_events BOOLEAN,
+ name VARCHAR(100),
+ job_title VARCHAR(100),
+ company VARCHAR(100),
+ diarize BOOLEAN,
+ default_naming_template_id INTEGER,
+ monthly_token_budget INTEGER,
+ monthly_transcription_budget INTEGER,
+ email_verified BOOLEAN,
+ email_verification_token VARCHAR(200),
+ email_verification_sent_at DATETIME,
+ password_reset_token VARCHAR(200),
+ password_reset_sent_at DATETIME,
+ auto_speaker_labelling BOOLEAN,
+ auto_speaker_labelling_threshold VARCHAR(10),
+ auto_summarization BOOLEAN,
+ transcription_hotwords TEXT,
+ transcription_initial_prompt TEXT,
+ summary_include_timestamps BOOLEAN,
+ summary_timestamp_template_id INTEGER,
+ chat_include_timestamps BOOLEAN,
+ chat_timestamp_template_id INTEGER,
+ show_timestamps_simple_view BOOLEAN,
+ editor_autosave BOOLEAN,
+ audio_player_position VARCHAR(10),
+ PRIMARY KEY (id),
+ UNIQUE (username),
+ UNIQUE (email),
+ UNIQUE (sso_subject),
+ FOREIGN KEY(default_naming_template_id) REFERENCES naming_template (id) ON DELETE SET NULL,
+ FOREIGN KEY(summary_timestamp_template_id) REFERENCES transcript_template (id) ON DELETE SET NULL,
+ FOREIGN KEY(chat_timestamp_template_id) REFERENCES transcript_template (id) ON DELETE SET NULL
+);
+
+CREATE TABLE webhook (
+ id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ name VARCHAR(100) NOT NULL,
+ url VARCHAR(500) NOT NULL,
+ allow_http BOOLEAN NOT NULL,
+ secret VARCHAR(120) NOT NULL,
+ events TEXT NOT NULL,
+ enabled BOOLEAN NOT NULL,
+ auto_paused BOOLEAN NOT NULL,
+ consecutive_failures INTEGER NOT NULL,
+ created_at DATETIME NOT NULL,
+ updated_at DATETIME NOT NULL,
+ last_delivery_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(user_id) REFERENCES user (id) ON DELETE CASCADE
+);
+
+CREATE TABLE webhook_delivery (
+ id INTEGER NOT NULL,
+ webhook_id INTEGER NOT NULL,
+ event_id VARCHAR(36) NOT NULL,
+ event_type VARCHAR(80) NOT NULL,
+ payload TEXT NOT NULL,
+ attempt_count INTEGER NOT NULL,
+ status VARCHAR(20) NOT NULL,
+ response_status INTEGER,
+ response_body_preview VARCHAR(2000),
+ error_message VARCHAR(500),
+ next_retry_at DATETIME,
+ created_at DATETIME NOT NULL,
+ delivered_at DATETIME,
+ PRIMARY KEY (id),
+ FOREIGN KEY(webhook_id) REFERENCES webhook (id) ON DELETE CASCADE
+);
+
+CREATE INDEX idx_delivery_status_retry ON webhook_delivery (status, next_retry_at);
+
+CREATE INDEX idx_token_user_date ON token_usage (user_id, date);
+
+CREATE INDEX idx_transcription_user_date ON transcription_usage (user_id, date);
+
+CREATE INDEX idx_user_speaker_name ON transcript_chunk (user_id, speaker_name);
+
+CREATE INDEX ix_api_token_revoked ON api_token (revoked);
+
+CREATE UNIQUE INDEX ix_api_token_token_hash ON api_token (token_hash);
+
+CREATE INDEX ix_processing_job_created_at ON processing_job (created_at);
+
+CREATE INDEX ix_processing_job_recording_id ON processing_job (recording_id);
+
+CREATE INDEX ix_processing_job_status ON processing_job (status);
+
+CREATE INDEX ix_processing_job_user_id ON processing_job (user_id);
+
+CREATE INDEX ix_recording_folder_id ON recording (folder_id);
+
+CREATE INDEX ix_recording_session_created_at ON recording_session (created_at);
+
+CREATE INDEX ix_recording_session_finalized_recording_id ON recording_session (finalized_recording_id);
+
+CREATE INDEX ix_recording_session_last_seen_at ON recording_session (last_seen_at);
+
+CREATE INDEX ix_recording_session_status ON recording_session (status);
+
+CREATE INDEX ix_recording_session_user_id ON recording_session (user_id);
+
+CREATE INDEX ix_recording_user_file_hash ON "recording" (user_id, file_hash);
+
+CREATE INDEX ix_transcript_chunk_speaker_name ON transcript_chunk (speaker_name);
+
+CREATE INDEX ix_user_email_verification_token ON user (email_verification_token);
+
+CREATE INDEX ix_user_password_reset_token ON user (password_reset_token);
+
+CREATE UNIQUE INDEX ix_user_sso_subject ON "user" (sso_subject);
+
+CREATE INDEX ix_webhook_delivery_created_at ON webhook_delivery (created_at);
+
+CREATE INDEX ix_webhook_delivery_event_id ON webhook_delivery (event_id);
+
+CREATE INDEX ix_webhook_delivery_event_type ON webhook_delivery (event_type);
+
+CREATE INDEX ix_webhook_delivery_next_retry_at ON webhook_delivery (next_retry_at);
+
+CREATE INDEX ix_webhook_delivery_status ON webhook_delivery (status);
+
+CREATE INDEX ix_webhook_delivery_webhook_id ON webhook_delivery (webhook_id);
+
+CREATE INDEX ix_webhook_enabled ON webhook (enabled);
+
+CREATE INDEX ix_webhook_user_id ON webhook (user_id);
diff --git a/tests/test_upgrade_path.py b/tests/test_upgrade_path.py
new file mode 100644
index 00000000..90f042c3
--- /dev/null
+++ b/tests/test_upgrade_path.py
@@ -0,0 +1,326 @@
+"""Boot the current migrations against databases created by older Speakr versions.
+
+Speakr is self-hosted, so people upgrade from whatever version they happened to
+stop at, sometimes years old. Every other test in this suite runs against a
+database that `db.create_all()` just built from today's models, which is the one
+shape no upgrading user ever has. This module covers the gap.
+
+The fixtures in tests/fixtures/schemas/ are real schemas, dumped from each tag's
+own models by scripts/generate_schema_fixtures.py. They are checked in as plain
+SQL so the tests need no old dependencies, no network and no Docker, and cannot
+drift as the tooling changes.
+
+The assertions are deliberately about what a *bad* migration takes away rather
+than what a good one adds. #379 shipped a migration that did its stated job
+perfectly while destroying 27 unrelated columns; a test that only checked the
+intended change would have passed.
+"""
+
+import os
+import sqlite3
+
+import pytest
+from flask import Flask
+from sqlalchemy import inspect
+
+from src.database import db
+from src.init_db import initialize_database
+from src.models import User
+
+
+FIXTURE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "schemas")
+FIXTURES = sorted(f for f in os.listdir(FIXTURE_DIR) if f.endswith(".sql"))
+
+# Columns whose values must survive an upgrade. Seeded only where the fixture
+# already has them, so one list covers every version.
+SKIP_SEED = {"id", "username", "email", "password"}
+
+# Some columns are validated or normalised by their own one-shot migrations, so
+# a nonsense marker would legitimately be rewritten. Seed those with values a
+# real installation would hold.
+REALISTIC = {
+ "transcription_language": "en",
+ "ui_language": "en",
+ "output_language": "English",
+ "auto_speaker_labelling_threshold": "medium",
+ "audio_player_position": "bottom",
+ "filename_date_pattern": "auto",
+ "speaker_count_mode": "range",
+}
+
+
+def _fixture_app(db_path):
+ """A second Flask app bound to the fixture database.
+
+ Flask-SQLAlchemy supports one db instance across several apps, so this runs
+ the real initialize_database() against an arbitrary file without disturbing
+ the suite-wide app that conftest configured.
+ """
+ app = Flask(f"upgrade_test_{os.path.basename(db_path)}")
+ app.config["SQLALCHEMY_DATABASE_URI"] = f"sqlite:///{db_path}"
+ app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
+ db.init_app(app)
+ return app
+
+
+def _seed(db_path):
+ """Populate the old database the way a real installation would be."""
+ con = sqlite3.connect(db_path)
+ columns = {row[1]: row[2].upper() for row in con.execute('PRAGMA table_info("user")')}
+
+ con.execute(
+ 'INSERT INTO "user" (id, username, email, password) VALUES (1, ?, ?, ?)',
+ ("existing", "[email protected]", "bcrypt-hash-preserved"),
+ )
+
+ seeded = {}
+ for name, sql_type in columns.items():
+ if name in SKIP_SEED or name.endswith("_id"):
+ continue
+ if name in REALISTIC:
+ value = REALISTIC[name]
+ elif "CHAR" in sql_type or "TEXT" in sql_type:
+ value = f"keep-{name}"
+ elif "INT" in sql_type or "BOOL" in sql_type or "FLOAT" in sql_type:
+ value = 7
+ else:
+ continue
+ con.execute(f'UPDATE "user" SET "{name}" = ? WHERE id = 1', (value,))
+ seeded[name] = value
+
+ con.commit()
+ snapshot = {
+ "columns": set(columns),
+ "indexes": {
+ row[0] for row in con.execute(
+ "SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='user'"
+ )
+ },
+ "seeded": seeded,
+ }
+ con.close()
+ return snapshot
+
+
[email protected](params=FIXTURES, ids=[f[:-4] for f in FIXTURES])
+def upgraded(request, tmp_path):
+ """An old database, seeded, then upgraded by the current migrations."""
+ version = request.param[:-4]
+ db_path = str(tmp_path / f"{version}.db")
+
+ with open(os.path.join(FIXTURE_DIR, request.param)) as fh:
+ schema_sql = fh.read()
+ con = sqlite3.connect(db_path)
+ con.executescript(schema_sql)
+ con.commit()
+ con.close()
+
+ snapshot = _seed(db_path)
+
+ app = _fixture_app(db_path)
+ with app.app_context():
+ initialize_database(app)
+
+ return {"version": version, "path": db_path, "app": app, "before": snapshot}
+
+
+def _live(db_path):
+ con = sqlite3.connect(db_path)
+ columns = [row[1] for row in con.execute('PRAGMA table_info("user")')]
+ indexes = {
+ row[0] for row in con.execute(
+ "SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='user'"
+ )
+ }
+ tables = {row[0] for row in con.execute("SELECT name FROM sqlite_master WHERE type='table'")}
+ con.close()
+ return columns, indexes, tables
+
+
+def test_no_column_is_lost(upgraded):
+ """The failure mode of #379: an upgrade that silently discards user settings."""
+ columns, _, _ = _live(upgraded["path"])
+
+ missing = upgraded["before"]["columns"] - set(columns)
+
+ assert not missing, (
+ f"upgrading from {upgraded['version']} destroyed {len(missing)} column(s): "
+ f"{sorted(missing)}"
+ )
+
+
+def test_no_value_is_lost(upgraded):
+ """Columns surviving as empty is the same data loss, one step later."""
+ con = sqlite3.connect(upgraded["path"])
+ row = con.execute('SELECT * FROM "user" WHERE id = 1').fetchone()
+ names = [d[0] for d in con.execute('SELECT * FROM "user" WHERE id = 1').description]
+ con.close()
+ actual = dict(zip(names, row))
+
+ changed = {
+ name: (expected, actual.get(name))
+ for name, expected in upgraded["before"]["seeded"].items()
+ if actual.get(name) != expected
+ }
+
+ assert not changed, f"upgrading from {upgraded['version']} altered values: {changed}"
+ assert actual["password"] == "bcrypt-hash-preserved"
+ assert actual["username"] == "existing"
+
+
+def test_no_index_is_lost(upgraded):
+ _, indexes, _ = _live(upgraded["path"])
+
+ missing = upgraded["before"]["indexes"] - indexes
+
+ assert not missing, f"upgrading from {upgraded['version']} dropped indexes: {sorted(missing)}"
+
+
+def test_schema_reaches_the_current_model(upgraded):
+ """The upgrade has to actually finish, not merely avoid breaking things."""
+ columns, _, _ = _live(upgraded["path"])
+
+ expected = {column.name for column in User.__table__.columns}
+
+ assert expected - set(columns) == set()
+
+
+def test_password_ends_up_nullable(upgraded):
+ """SSO and LDAP provisioning depend on this, and it is what #379 blocked."""
+ with upgraded["app"].app_context():
+ password = next(
+ column for column in inspect(db.engine).get_columns("user")
+ if column["name"] == "password"
+ )
+
+ assert password["nullable"] is True
+
+
+def test_no_scratch_tables_are_left_behind(upgraded):
+ _, _, tables = _live(upgraded["path"])
+
+ leftovers = {name for name in tables if name.endswith("_new")}
+
+ assert not leftovers, f"migration left scratch tables behind: {sorted(leftovers)}"
+
+
+def test_second_startup_is_a_no_op(upgraded):
+ """Migrations run about five times per container start, and on every restart."""
+ before = _live(upgraded["path"])
+
+ with upgraded["app"].app_context():
+ initialize_database(upgraded["app"])
+ initialize_database(upgraded["app"])
+
+ assert _live(upgraded["path"]) == before
+
+
+class TestIssue379:
+ """The specific database state reported in #379, on a real historical schema."""
+
+ @pytest.fixture
+ def wedged(self, tmp_path):
+ """v0.5.8 predates can_share_publicly, so the old migration stranded user_new here."""
+ db_path = str(tmp_path / "wedged.db")
+ with open(os.path.join(FIXTURE_DIR, "v0.5.8-alpha.sql")) as fh:
+ schema_sql = fh.read()
+ con = sqlite3.connect(db_path)
+ con.executescript(schema_sql)
+ con.execute(
+ 'INSERT INTO "user" (id, username, email, password) VALUES (1, ?, ?, ?)',
+ ("existing", "[email protected]", "bcrypt-hash-preserved"),
+ )
+ # Exactly what the old migration left behind: created, never populated.
+ con.execute(
+ "CREATE TABLE user_new (id INTEGER NOT NULL, username VARCHAR(20) NOT NULL, "
+ "email VARCHAR(120) NOT NULL, password VARCHAR(60), PRIMARY KEY (id))"
+ )
+ con.commit()
+ con.close()
+ return db_path
+
+ def test_starts_clean_from_the_wedged_state(self, wedged):
+ app = _fixture_app(wedged)
+ with app.app_context():
+ initialize_database(app)
+
+ columns, _, tables = _live(wedged)
+ assert "user_new" not in tables
+ assert {c.name for c in User.__table__.columns} - set(columns) == set()
+
+ con = sqlite3.connect(wedged)
+ assert con.execute('SELECT password FROM "user" WHERE id = 1').fetchone()[0] == (
+ "bcrypt-hash-preserved"
+ )
+ con.close()
+
+ def test_a_long_wedged_database_keeps_its_settings(self, tmp_path):
+ """The trap in #379: unwedging the old migration is what destroys data.
+
+ A database stuck since v0.5.8 kept collecting columns while the old
+ migration failed every boot, so by v0.10.3 it holds 41 of them behind a
+ password column that is still NOT NULL. The old migration would finally
+ run here and rebuild the table from its frozen 17-column list.
+ """
+ db_path = str(tmp_path / "long_wedged.db")
+ with open(os.path.join(FIXTURE_DIR, "v0.10.3-alpha.sql")) as fh:
+ schema_sql = fh.read()
+ con = sqlite3.connect(db_path)
+ con.executescript(schema_sql)
+
+ # Restore the NOT NULL the migration never managed to remove.
+ con.execute("PRAGMA writable_schema=ON")
+ user_sql = con.execute(
+ "SELECT sql FROM sqlite_master WHERE type='table' AND name='user'"
+ ).fetchone()[0]
+ assert "\tpassword VARCHAR(60), " in user_sql
+ con.execute(
+ "UPDATE sqlite_master SET sql=? WHERE type='table' AND name='user'",
+ (user_sql.replace("\tpassword VARCHAR(60), ", "\tpassword VARCHAR(60) NOT NULL, "),),
+ )
+ con.commit()
+ con.execute("PRAGMA writable_schema=OFF")
+ con.close()
+
+ snapshot = _seed(db_path)
+ assert len(snapshot["columns"]) == 41
+
+ app = _fixture_app(db_path)
+ with app.app_context():
+ initialize_database(app)
+
+ columns, indexes, _ = _live(db_path)
+ assert snapshot["columns"] - set(columns) == set(), "settings columns were destroyed"
+
+ # Check the values before the indexes. A rebuild's damage is invisible at
+ # the column-name level, because the add_column_if_not_exists() calls
+ # further down the same function immediately put the names back, empty.
+ con = sqlite3.connect(db_path)
+ row = con.execute('SELECT * FROM "user" WHERE id = 1').fetchone()
+ names = [d[0] for d in con.execute('SELECT * FROM "user" WHERE id = 1').description]
+ con.close()
+ actual = dict(zip(names, row))
+ emptied = {
+ name: (expected, actual.get(name))
+ for name, expected in snapshot["seeded"].items()
+ if actual.get(name) != expected
+ }
+ assert emptied == {}, f"settings were silently emptied: {emptied}"
+
+ assert snapshot["indexes"] - indexes == set(), "indexes were destroyed"
+
+ def test_sso_user_can_be_created_afterwards(self, wedged):
+ app = _fixture_app(wedged)
+ with app.app_context():
+ initialize_database(app)
+
+ con = sqlite3.connect(wedged)
+ con.execute(
+ 'INSERT INTO "user" (username, email, password, sso_provider, sso_subject) '
+ "VALUES ('sso', '[email protected]', NULL, 'oidc', 'subject-1')"
+ )
+ con.commit()
+ assert con.execute(
+ 'SELECT COUNT(*) FROM "user" WHERE password IS NULL'
+ ).fetchone()[0] == 1
+ con.close()