f3852e1349c4_all_files_only_on_disk.py 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """all files only on disk
  2. Revision ID: f3852e1349c4
  3. Revises: 913efdf409e5
  4. Create Date: 2017-07-24 17:15:54.278141
  5. """
  6. from alembic import context
  7. from alembic import op
  8. from depot.fields.sqlalchemy import UploadedFileField
  9. from depot.manager import DepotManager
  10. import sqlalchemy as sa
  11. from sqlalchemy.sql.expression import func
  12. # revision identifiers, used by Alembic.
  13. revision = 'f3852e1349c4'
  14. down_revision = '913efdf409e5'
  15. def configure_depot():
  16. """Configure Depot."""
  17. depot_storage_name = context.config.get_main_option('depot_storage_name')
  18. depot_storage_path = context.config.get_main_option('depot_storage_dir')
  19. depot_storage_settings = {'depot.storage_path': depot_storage_path}
  20. DepotManager.configure(
  21. depot_storage_name,
  22. depot_storage_settings,
  23. )
  24. revision_helper = sa.Table(
  25. 'content_revisions',
  26. sa.MetaData(),
  27. sa.Column('revision_id', sa.Integer, primary_key=True),
  28. sa.Column('label', sa.String(1024), nullable=False),
  29. sa.Column('file_extension', sa.String(255), nullable=False),
  30. sa.Column('file_mimetype', sa.String(255), nullable=False),
  31. sa.Column('file_content', sa.LargeBinary),
  32. sa.Column('depot_file', UploadedFileField, nullable=True),
  33. sa.Column('type', sa.String(32), nullable=False),
  34. )
  35. def upgrade():
  36. """Drops the file content from revision."""
  37. with op.batch_alter_table('content_revisions') as batch_op:
  38. batch_op.drop_column('file_content')
  39. def downgrade():
  40. """Adds the file content in revision."""
  41. with op.batch_alter_table('content_revisions') as batch_op:
  42. batch_op.add_column(sa.Column('file_content', sa.LargeBinary))
  43. configure_depot()
  44. depot = DepotManager.get()
  45. connection = op.get_bind()
  46. select_query = revision_helper.select() \
  47. .where(revision_helper.c.type == 'file') \
  48. .where(revision_helper.c.depot_file.isnot(None)) \
  49. .where(func.length(revision_helper.c.depot_file) > 0)
  50. files = connection.execute(select_query).fetchall()
  51. for file in files:
  52. depot_file_content = depot.get(file.depot_file)
  53. update_query = revision_helper.update() \
  54. .where(revision_helper.c.revision_id == file.revision_id) \
  55. .values(file_content=depot_file_content)
  56. connection.execute(update_query)