6a39f3d8e55c_add_project_table.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. """Add project table
  2. Revision ID: 6a39f3d8e55c
  3. Revises: c0fbf31ca0db
  4. Create Date: 2024-10-01 14:02:35.241684
  5. """
  6. from alembic import op
  7. import sqlalchemy as sa
  8. from sqlalchemy.sql import table, column, select
  9. import json
  10. revision = "6a39f3d8e55c"
  11. down_revision = "c0fbf31ca0db"
  12. branch_labels = None
  13. depends_on = None
  14. def upgrade():
  15. # Creating the 'project' table
  16. print("Creating project table")
  17. project_table = op.create_table(
  18. "project",
  19. sa.Column("id", sa.Text(), primary_key=True),
  20. sa.Column("user_id", sa.Text(), nullable=False),
  21. sa.Column("name", sa.Text(), nullable=False),
  22. sa.Column("description", sa.Text(), nullable=True),
  23. sa.Column("data", sa.JSON(), nullable=True),
  24. sa.Column("meta", sa.JSON(), nullable=True),
  25. sa.Column("created_at", sa.BigInteger(), nullable=False),
  26. sa.Column("updated_at", sa.BigInteger(), nullable=True),
  27. )
  28. print("Migrating data from document table to project table")
  29. # Representation of the existing 'document' table
  30. document_table = table(
  31. "document",
  32. column("collection_name", sa.String()),
  33. column("user_id", sa.String()),
  34. column("name", sa.String()),
  35. column("title", sa.Text()),
  36. column("content", sa.Text()),
  37. column("timestamp", sa.BigInteger()),
  38. )
  39. # Select all from existing document table
  40. documents = op.get_bind().execute(
  41. select(
  42. document_table.c.collection_name,
  43. document_table.c.user_id,
  44. document_table.c.name,
  45. document_table.c.title,
  46. document_table.c.content,
  47. document_table.c.timestamp,
  48. )
  49. )
  50. # Insert data into project table from document table
  51. for doc in documents:
  52. op.get_bind().execute(
  53. project_table.insert().values(
  54. id=doc.collection_name,
  55. user_id=doc.user_id,
  56. description=doc.name,
  57. meta={
  58. "document": True,
  59. "tags": json.loads(doc.content or "{}").get("tags", []),
  60. },
  61. name=doc.title,
  62. created_at=doc.timestamp,
  63. updated_at=doc.timestamp, # using created_at for both created_at and updated_at in project
  64. )
  65. )
  66. def downgrade():
  67. op.drop_table("project")