Sin descripción

c29ef01617f5_migrate_notes_directories.py 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. """Migrate notes directories
  2. Revision ID: c29ef01617f5
  3. Revises: e0df2de997cc
  4. Create Date: 2023-12-30 17:24:36.430292
  5. """
  6. from alembic import op
  7. import sqlalchemy as sa
  8. from sqlalchemy import text, Table, MetaData
  9. from app.alembic.alembic_utils import _table_has_column
  10. # revision identifiers, used by Alembic.
  11. revision = 'c29ef01617f5'
  12. down_revision = 'e0df2de997cc'
  13. branch_labels = None
  14. depends_on = None
  15. def upgrade():
  16. if not _table_has_column('notes', 'directory_id'):
  17. metadata = MetaData()
  18. notes_group = Table('notes_group', metadata, autoload_with=op.get_bind())
  19. result = op.get_bind().execute(sa.select(sa.func.max(notes_group.c.group_id)))
  20. max_group_id = result.scalar() or 0
  21. # Set the starting value for the primary key in the note_directory table
  22. op.execute(text(f"SELECT setval('note_directory_id_seq', {max_group_id + 1})"))
  23. op.execute(text("""
  24. INSERT INTO note_directory (id, name, parent_id, case_id)
  25. SELECT group_id, group_title, NULL, group_case_id
  26. FROM notes_group
  27. """))
  28. op.add_column('notes', sa.Column('directory_id', sa.BigInteger, sa.ForeignKey('note_directory.id')))
  29. op.execute(text("""
  30. UPDATE notes
  31. SET directory_id = (
  32. SELECT group_id
  33. FROM notes_group_link
  34. WHERE notes_group_link.note_id = notes.note_id
  35. )
  36. """))
  37. # Commit the transaction
  38. op.execute(text("COMMIT"))
  39. return
  40. def downgrade():
  41. pass