beeaf68d0ee1_creat_farmland_orm.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """creat_farmland_orm
  2. Revision ID: beeaf68d0ee1
  3. Revises: f0d12e4fab12
  4. Create Date: 2025-06-14 17:07:57.976453
  5. """
  6. from alembic import op
  7. import sqlalchemy as sa
  8. import geoalchemy2
  9. # revision identifiers, used by Alembic.
  10. revision = 'beeaf68d0ee1'
  11. down_revision = 'f0d12e4fab12'
  12. branch_labels = None
  13. depends_on = None
  14. def upgrade():
  15. """升级数据库到当前版本"""
  16. # ### commands auto generated by Alembic - please adjust! ###
  17. # 检查表是否已存在,如果不存在才创建
  18. connection = op.get_bind()
  19. inspector = sa.inspect(connection)
  20. if 'Farmland_data' not in inspector.get_table_names():
  21. op.create_table('Farmland_data',
  22. sa.Column('Farmland_ID', sa.Integer(), nullable=False, comment='区域农业用地矢量点编号'),
  23. sa.Column('Sample_ID', sa.Integer(), autoincrement=True, nullable=False, comment='采样自增的ID'),
  24. sa.Column('lon', sa.Float(), nullable=True, comment='经度'),
  25. sa.Column('lan', sa.Float(), nullable=True, comment='纬度'),
  26. sa.Column('Type', sa.Float(), nullable=True, comment='用地类型:旱地(0)、水田(1)、水浇地(2)'),
  27. sa.Column('geom', geoalchemy2.types.Geometry(geometry_type='POINT', srid=4326, from_text='ST_GeomFromEWKT', name='geometry'), nullable=True, comment='点几何对象'),
  28. sa.PrimaryKeyConstraint('Farmland_ID', 'Sample_ID')
  29. )
  30. # 为表添加注释
  31. op.execute("COMMENT ON TABLE \"Farmland_data\" IS '耕地样点空间位置与索引数据表,存储农业用地的坐标、类型和空间几何信息'")
  32. # 使用原生SQL安全创建索引
  33. try:
  34. op.execute('CREATE INDEX IF NOT EXISTS idx_Farmland_data_geom ON "Farmland_data" USING gist (geom)')
  35. except Exception as e:
  36. print(f"索引创建警告: {e}")
  37. # ### end Alembic commands ###
  38. def downgrade():
  39. """将数据库降级到上一版本"""
  40. # ### commands auto generated by Alembic - please adjust! ###
  41. # 安全地删除索引和表,检查存在性
  42. connection = op.get_bind()
  43. inspector = sa.inspect(connection)
  44. if 'Farmland_data' in inspector.get_table_names():
  45. # 检查索引是否存在,存在才删除
  46. indexes = inspector.get_indexes('Farmland_data')
  47. index_names = [idx['name'] for idx in indexes]
  48. if 'idx_Farmland_data_geom' in index_names:
  49. op.drop_index('idx_Farmland_data_geom', table_name='Farmland_data', postgresql_using='gist')
  50. # 删除表
  51. op.drop_table('Farmland_data')
  52. # ### end Alembic commands ###