Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Fix PostgreSQL migration compatibility for boolean defaults and reserved keywords
Murtaza Nasir682143fc176e
diff --git a/VERSION b/VERSIONindex 85c3002d..a935b4b0 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-v0.8.6+v0.8.6.1diff --git a/src/init_db.py b/src/init_db.pyindex 3a4872c0..d6e86434 100644--- a/src/init_db.py+++ b/src/init_db.py@@ -16,7 +16,7 @@ from sqlalchemy import text, inspectfrom src.database import dbfrom src.models import Recording, TranscriptChunk, SystemSettingfrom src.services.embeddings import process_recording_chunks-from src.utils import add_column_if_not_exists, migrate_column_type+from src.utils import add_column_if_not_exists, migrate_column_type, create_index_if_not_exists# ConfigurationENABLE_INQUIRE_MODE = os.environ.get('ENABLE_INQUIRE_MODE', 'false').lower() == 'true'@@ -133,8 +133,8 @@ def initialize_database(app):# Rename new table to userconn.execute(text("ALTER TABLE user_new RENAME TO user"))- # Recreate the unique index on sso_subject- conn.execute(text('CREATE UNIQUE INDEX IF NOT EXISTS ix_user_sso_subject ON user (sso_subject)'))+ # Recreate the unique index on sso_subject (quote "user" for PostgreSQL)+ conn.execute(text('CREATE UNIQUE INDEX IF NOT EXISTS ix_user_sso_subject ON "user" (sso_subject)'))conn.commit()app.logger.info("Successfully made password column nullable for SSO support")@@ -276,19 +276,10 @@ def initialize_database(app):# Create indexes for token lookups (for faster token verification)try:- inspector = inspect(engine)- if 'user' in inspector.get_table_names():- existing_indexes = [idx['name'] for idx in inspector.get_indexes('user')]- if 'ix_user_email_verification_token' not in existing_indexes:- with engine.connect() as conn:- conn.execute(text('CREATE INDEX IF NOT EXISTS ix_user_email_verification_token ON user (email_verification_token)'))- conn.commit()- app.logger.info("Created index ix_user_email_verification_token on user.email_verification_token")- if 'ix_user_password_reset_token' not in existing_indexes:- with engine.connect() as conn:- conn.execute(text('CREATE INDEX IF NOT EXISTS ix_user_password_reset_token ON user (password_reset_token)'))- conn.commit()- app.logger.info("Created index ix_user_password_reset_token on user.password_reset_token")+ if create_index_if_not_exists(engine, 'ix_user_email_verification_token', 'user', 'email_verification_token'):+ app.logger.info("Created index ix_user_email_verification_token on user.email_verification_token")+ if create_index_if_not_exists(engine, 'ix_user_password_reset_token', 'user', 'password_reset_token'):+ app.logger.info("Created index ix_user_password_reset_token on user.password_reset_token")except Exception as e:app.logger.warning(f"Could not create token indexes: {e}")if add_column_if_not_exists(engine, 'tag', 'naming_template_id', 'INTEGER'):@@ -372,15 +363,14 @@ def initialize_database(app):if has_is_starred and not has_is_highlighted:# Rename is_starred to is_highlighted by copying datatry:+ # Add is_highlighted column using utility (handles PostgreSQL boolean defaults)+ add_column_if_not_exists(engine, 'shared_recording_state', 'is_highlighted', 'BOOLEAN DEFAULT 0')+ # Copy data from is_starred to is_highlightedwith engine.connect() as conn:- # Add is_highlighted column (PostgreSQL needs FALSE, SQLite uses 0)- default_val = 'FALSE' if engine.name == 'postgresql' else '0'- conn.execute(text(f'ALTER TABLE shared_recording_state ADD COLUMN is_highlighted BOOLEAN DEFAULT {default_val}'))- # Copy data from is_starred to is_highlightedconn.execute(text('UPDATE shared_recording_state SET is_highlighted = is_starred'))conn.commit()- app.logger.info("Migrated is_starred to is_highlighted in shared_recording_state table")- # Note: We keep is_starred for now to avoid breaking existing code during transition+ app.logger.info("Migrated is_starred to is_highlighted in shared_recording_state table")+ # Note: We keep is_starred for now to avoid breaking existing code during transitionexcept Exception as e:app.logger.warning(f"Could not migrate is_starred to is_highlighted: {e}")elif not has_is_highlighted:@@ -511,31 +501,20 @@ def initialize_database(app):# Add unique index for SSO subject to prevent duplicate linkingtry:- inspector = inspect(engine)- if 'user' in inspector.get_table_names():- existing_indexes = [idx['name'] for idx in inspector.get_indexes('user')]- if 'ix_user_sso_subject' not in existing_indexes:- with engine.connect() as conn:- if engine.name == 'mysql':- conn.execute(text('CREATE UNIQUE INDEX IF NOT EXISTS ix_user_sso_subject ON `user` (sso_subject)'))- else:- conn.execute(text('CREATE UNIQUE INDEX IF NOT EXISTS ix_user_sso_subject ON "user" (sso_subject)'))- conn.commit()- app.logger.info("Created unique index ix_user_sso_subject on user.sso_subject")+ if create_index_if_not_exists(engine, 'ix_user_sso_subject', 'user', 'sso_subject', unique=True):+ app.logger.info("Created unique index ix_user_sso_subject on user.sso_subject")except Exception as e:app.logger.warning(f"Could not create unique index on user.sso_subject: {e}")# Add folder_id column to recording table for folders featureif add_column_if_not_exists(engine, 'recording', 'folder_id', 'INTEGER'):app.logger.info("Added folder_id column to recording table")- # Create index for folder_id- try:- with engine.connect() as conn:- conn.execute(text('CREATE INDEX IF NOT EXISTS ix_recording_folder_id ON recording (folder_id)'))- conn.commit()- app.logger.info("Created index ix_recording_folder_id on recording.folder_id")- except Exception as e:- app.logger.warning(f"Could not create index on recording.folder_id: {e}")+ # Create index for folder_id+ try:+ if create_index_if_not_exists(engine, 'ix_recording_folder_id', 'recording', 'folder_id'):+ app.logger.info("Created index ix_recording_folder_id on recording.folder_id")+ except Exception as e:+ app.logger.warning(f"Could not create index on recording.folder_id: {e}")# Initialize default system settingsif not SystemSetting.query.filter_by(key='transcript_length_limit').first():diff --git a/src/utils/__init__.py b/src/utils/__init__.pyindex 39893bb3..5d909f1a 100644--- a/src/utils/__init__.py+++ b/src/utils/__init__.py@@ -31,7 +31,8 @@ from .security import (from .database import (add_column_if_not_exists,- migrate_column_type+ migrate_column_type,+ create_index_if_not_exists)from .token_auth import (@@ -65,6 +66,7 @@ __all__ = [# Database'add_column_if_not_exists','migrate_column_type',+ 'create_index_if_not_exists',# Token authentication'extract_token_from_request','hash_token',diff --git a/src/utils/database.py b/src/utils/database.pyindex 871be3eb..06777bc2 100644--- a/src/utils/database.py+++ b/src/utils/database.py@@ -5,8 +5,10 @@ IMPORTANT: All migrations must be compatible with both SQLite and PostgreSQL.- Boolean defaults: SQLite uses 0/1, PostgreSQL requires FALSE/TRUE- Reserved keywords: "user", "order" etc. must be quoted- The add_column_if_not_exists() function handles these automatically+- Use create_index_if_not_exists() for index creation with proper quoting"""+import refrom sqlalchemy import inspect, text@@ -51,6 +53,59 @@ def add_column_if_not_exists(engine, table_name, column_name, column_type):return False+def create_index_if_not_exists(engine, index_name, table_name, columns, unique=False):+ """+ Create an index on a table if it doesn't already exist.++ Handles cross-database compatibility by properly quoting table names,+ especially important for reserved keywords like 'user', 'order', etc.++ Args:+ engine: SQLAlchemy engine+ index_name: Name of the index to create+ table_name: Name of the table+ columns: Column(s) to index (string, can be comma-separated for composite)+ unique: Whether to create a unique index (default False)++ Returns:+ bool: True if index was created, False if it already existed or table doesn't exist+ """+ inspector = inspect(engine)++ # Check if table exists+ if table_name not in inspector.get_table_names():+ return False++ # Check if index already exists+ existing_indexes = [idx['name'] for idx in inspector.get_indexes(table_name)]+ if index_name in existing_indexes:+ return False++ unique_clause = 'UNIQUE ' if unique else ''++ with engine.connect() as conn:+ # Quote table name to handle reserved keywords (e.g., "user" in PostgreSQL)+ # MySQL uses backticks, PostgreSQL/SQLite use double quotes+ if engine.name == 'mysql':+ quoted_table = f'`{table_name}`'+ else:+ quoted_table = f'"{table_name}"'++ # Note: IF NOT EXISTS may not be supported on all databases, but we already+ # checked for existence above, so it's just a safety net+ try:+ conn.execute(text(+ f'CREATE {unique_clause}INDEX IF NOT EXISTS {index_name} ON {quoted_table} ({columns})'+ ))+ except Exception:+ # Some databases don't support IF NOT EXISTS, try without+ conn.execute(text(+ f'CREATE {unique_clause}INDEX {index_name} ON {quoted_table} ({columns})'+ ))+ conn.commit()+ return True++def migrate_column_type(engine, table_name, column_name, new_type, transform_sql=None):"""Migrate a column to a new type if it exists.diff --git a/tests/test_migration_compatibility.py b/tests/test_migration_compatibility.pynew file mode 100644index 00000000..b5dc418c--- /dev/null+++ b/tests/test_migration_compatibility.py@@ -0,0 +1,152 @@+"""+Test suite to ensure database migrations are compatible with both SQLite and PostgreSQL.++These tests scan the init_db.py file for patterns that would break on PostgreSQL,+such as SQLite-only boolean defaults (0/1 instead of FALSE/TRUE) and unquoted+reserved keywords.++Run with: python tests/test_migration_compatibility.py+"""++import re+import unittest+import os+++class TestMigrationCompatibility(unittest.TestCase):+ """Tests to ensure init_db.py uses cross-database compatible SQL."""++ @classmethod+ def setUpClass(cls):+ """Load init_db.py content once for all tests."""+ # Find the project root+ test_dir = os.path.dirname(os.path.abspath(__file__))+ project_root = os.path.dirname(test_dir)+ init_db_path = os.path.join(project_root, 'src', 'init_db.py')++ with open(init_db_path, 'r') as f:+ cls.content = f.read()++ def test_no_raw_boolean_defaults_in_alter_table(self):+ """+ Ensure no raw ALTER TABLE statements use SQLite-only boolean defaults.++ The pattern 'BOOLEAN DEFAULT 0' or 'BOOLEAN DEFAULT 1' in raw SQL+ will fail on PostgreSQL, which requires 'DEFAULT FALSE' or 'DEFAULT TRUE'.++ Using add_column_if_not_exists() handles this conversion automatically.+ """+ # Pattern to find raw SQL with text() that has BOOLEAN DEFAULT 0/1+ # This matches: text('... BOOLEAN DEFAULT 0 ...') or text("...")+ pattern = r"conn\.execute\s*\(\s*text\s*\(['\"]([^'\"]*BOOLEAN\s+DEFAULT\s+[01][^'\"]*)['\"]"++ matches = re.findall(pattern, self.content, re.IGNORECASE)++ # Filter out false positives - we're looking for raw ALTER TABLE statements+ # not UPDATE statements or other SQL that legitimately uses 0/1+ problematic = []+ for match in matches:+ match_upper = match.upper()+ # Only flag if it's an ALTER TABLE with BOOLEAN DEFAULT 0/1+ if 'ALTER TABLE' in match_upper and 'BOOLEAN' in match_upper:+ if 'DEFAULT 0' in match or 'DEFAULT 1' in match:+ problematic.append(match)++ self.assertEqual(+ len(problematic), 0,+ f"Found SQLite-only boolean defaults in raw ALTER TABLE statements. "+ f"Use add_column_if_not_exists() instead:\n" ++ "\n".join(f" - {m[:100]}..." if len(m) > 100 else f" - {m}" for m in problematic)+ )++ def test_reserved_keywords_quoted_in_index_creation(self):+ """+ Ensure reserved keywords like 'user' are properly quoted in index creation.++ Raw SQL like 'CREATE INDEX ... ON user (column)' will fail on some databases+ because 'user' is a reserved keyword. It should be quoted as "user" or use+ the create_index_if_not_exists() utility.+ """+ reserved_keywords = ['user', 'order', 'group', 'table', 'select', 'index']++ problematic = []++ for keyword in reserved_keywords:+ # Pattern to find unquoted reserved keyword after ON in index creation+ # Matches: CREATE INDEX ... ON user ( but not ON "user" or ON `user`+ pattern = rf"CREATE\s+(?:UNIQUE\s+)?INDEX[^;]*\s+ON\s+{keyword}\s*\("++ matches = re.findall(pattern, self.content, re.IGNORECASE)++ for match in matches:+ # Skip if the keyword is already quoted+ if f'"{keyword}"' in match.lower() or f'`{keyword}`' in match.lower():+ continue+ problematic.append((keyword, match[:80]))++ self.assertEqual(+ len(problematic), 0,+ f"Found unquoted reserved keywords in index creation. "+ f"Use create_index_if_not_exists() or quote the table name:\n" ++ "\n".join(f" - '{kw}' in: {sql}..." for kw, sql in problematic)+ )++ def test_add_column_uses_utility(self):+ """+ Ensure most ADD COLUMN operations use add_column_if_not_exists().++ Direct ALTER TABLE ADD COLUMN statements should use the utility function+ to ensure cross-database compatibility with boolean defaults and quoting.+ """+ # Count direct ALTER TABLE ADD COLUMN in text() calls+ direct_pattern = r"conn\.execute\s*\(\s*text\s*\(['\"][^'\"]*ALTER\s+TABLE[^'\"]*ADD\s+COLUMN"+ direct_matches = re.findall(direct_pattern, self.content, re.IGNORECASE)++ # Count uses of add_column_if_not_exists+ utility_pattern = r"add_column_if_not_exists\s*\("+ utility_matches = re.findall(utility_pattern, self.content)++ # We expect most ADD COLUMN operations to use the utility+ # Allow some direct usage for special cases (e.g., table recreation)+ # but utility usage should significantly outnumber direct usage+ self.assertGreater(+ len(utility_matches), len(direct_matches),+ f"Found {len(direct_matches)} direct ALTER TABLE ADD COLUMN statements "+ f"vs {len(utility_matches)} add_column_if_not_exists() calls. "+ f"Consider using the utility function for cross-database compatibility."+ )++ def test_create_index_uses_utility_for_user_table(self):+ """+ Ensure index creation on 'user' table uses create_index_if_not_exists().++ The 'user' table name is a reserved keyword that requires special quoting.+ Using create_index_if_not_exists() handles this automatically.+ """+ # Find all index creation on user table+ pattern = r"CREATE\s+(?:UNIQUE\s+)?INDEX[^;]*ON\s+[\"'`]?user[\"'`]?\s*\("++ # Count raw index creation on user table in text() calls+ raw_pattern = r"conn\.execute\s*\(\s*text\s*\(['\"][^'\"]*CREATE\s+(?:UNIQUE\s+)?INDEX[^'\"]*ON\s+[\"'`]?user"+ raw_matches = re.findall(raw_pattern, self.content, re.IGNORECASE)++ # Count uses of create_index_if_not_exists for user table+ utility_pattern = r"create_index_if_not_exists\s*\([^)]*['\"]user['\"]"+ utility_matches = re.findall(utility_pattern, self.content, re.IGNORECASE)++ # All index creation on user table should use the utility+ # (excluding table recreation scenarios which have their own quoting)+ if len(raw_matches) > 0:+ # Check if these are in table recreation blocks (acceptable)+ table_recreation_pattern = r"CREATE\s+TABLE\s+user_new"+ has_table_recreation = re.search(table_recreation_pattern, self.content, re.IGNORECASE)++ if not has_table_recreation or len(raw_matches) > 1:+ self.fail(+ f"Found {len(raw_matches)} raw CREATE INDEX statements on 'user' table. "+ f"Use create_index_if_not_exists() for proper quoting of reserved keywords."+ )+++if __name__ == '__main__':+ unittest.main()