/ migrations / versions / 031_widen_key_hash_columns.py
031_widen_key_hash_columns.py
 1  """Widen key_hash columns for PBKDF2 salted hashes and add key_prefix index."""
 2  import sqlalchemy as sa
 3  from alembic import op
 4  
 5  
 6  revision = '031'
 7  down_revision = '030'
 8  branch_labels = None
 9  depends_on = None
10  
11  
12  def upgrade():
13      try:
14          with op.batch_alter_table('api_keys') as batch_op:
15              batch_op.alter_column('key_hash', type_=sa.String(256), existing_type=sa.String(64))
16      except Exception as e:
17          print(f"Note: api_keys.key_hash resize skipped: {e}")
18  
19      try:
20          with op.batch_alter_table('widgets') as batch_op:
21              batch_op.alter_column('key_hash', type_=sa.String(256), existing_type=sa.String(64))
22      except Exception as e:
23          print(f"Note: widgets.key_hash resize skipped: {e}")
24  
25      try:
26          op.create_index('ix_api_keys_key_prefix', 'api_keys', ['key_prefix'])
27      except Exception as e:
28          print(f"Note: api_keys key_prefix index skipped: {e}")
29  
30      try:
31          op.create_index('ix_widgets_key_prefix', 'widgets', ['key_prefix'])
32      except Exception as e:
33          print(f"Note: widgets key_prefix index skipped: {e}")
34  
35  
36  def downgrade():
37      try:
38          op.drop_index('ix_widgets_key_prefix', table_name='widgets')
39      except Exception:
40          pass
41      try:
42          op.drop_index('ix_api_keys_key_prefix', table_name='api_keys')
43      except Exception:
44          pass