f0d12e4fab12_add_counties_table.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. """add_counties_table
  2. Revision ID: f0d12e4fab12
  3. Revises: c1cf3ab2c7fe
  4. Create Date: 2025-05-17 20:39:22.830946
  5. """
  6. from alembic import op
  7. import sqlalchemy as sa
  8. import geoalchemy2
  9. # revision identifiers, used by Alembic.
  10. revision = 'f0d12e4fab12'
  11. down_revision = 'c1cf3ab2c7fe'
  12. branch_labels = None
  13. depends_on = None
  14. def upgrade():
  15. """升级数据库到当前版本"""
  16. # ### commands auto generated by Alembic - please adjust! ###
  17. op.create_table('counties',
  18. sa.Column('id', sa.Integer(), nullable=False),
  19. sa.Column('name', sa.String(length=100), nullable=False, comment='县名'),
  20. sa.Column('code', sa.Integer(), nullable=True, comment='县代码'),
  21. sa.Column('city_name', sa.String(length=100), nullable=True, comment='市名'),
  22. sa.Column('city_code', sa.Integer(), nullable=True, comment='市代码'),
  23. sa.Column('province_name', sa.String(length=100), nullable=True, comment='省名'),
  24. sa.Column('province_code', sa.Integer(), nullable=True, comment='省代码'),
  25. sa.Column('geometry', geoalchemy2.types.Geometry(geometry_type='MULTIPOLYGON', srid=4326, from_text='ST_GeomFromEWKT', name='geometry', nullable=False), nullable=False, comment='县级行政区划的几何数据'),
  26. sa.Column('geojson', sa.JSON(), nullable=False, comment='完整的GeoJSON数据'),
  27. sa.PrimaryKeyConstraint('id')
  28. )
  29. # 检查并删除已存在的索引
  30. connection = op.get_bind()
  31. inspector = sa.inspect(connection)
  32. existing_indexes = inspector.get_indexes('counties')
  33. for index in existing_indexes:
  34. if index['name'] in ['idx_counties_code', 'idx_counties_geometry', 'idx_counties_name', 'ix_counties_id']:
  35. op.drop_index(index['name'], table_name='counties')
  36. # 创建新的索引
  37. op.create_index('idx_counties_code', 'counties', ['code'], unique=False)
  38. op.create_index('idx_counties_geometry', 'counties', ['geometry'], unique=False, postgresql_using='gist')
  39. op.create_index('idx_counties_name', 'counties', ['name'], unique=False)
  40. op.create_index(op.f('ix_counties_id'), 'counties', ['id'], unique=False)
  41. op.create_index(op.f('ix_raster_table_id'), 'raster_table', ['id'], unique=False)
  42. # ### end Alembic commands ###
  43. def downgrade():
  44. """将数据库降级到上一版本"""
  45. # ### commands auto generated by Alembic - please adjust! ###
  46. op.drop_index(op.f('ix_raster_table_id'), table_name='raster_table')
  47. op.drop_index(op.f('ix_counties_id'), table_name='counties')
  48. op.drop_index('idx_counties_name', table_name='counties')
  49. op.drop_index('idx_counties_geometry', table_name='counties', postgresql_using='gist')
  50. op.drop_index('idx_counties_code', table_name='counties')
  51. op.drop_table('counties')
  52. # ### end Alembic commands ###