database.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. """Database module"""
  2. from datetime import datetime
  3. from app import SESSION
  4. from app.models import State, Region, StateRegion, \
  5. Factory, FactoryTrack, FactoryStat, FactoryLocation
  6. def get_state(state_id):
  7. """Get regions from state"""
  8. session = SESSION()
  9. state = session.query(State).get(state_id)
  10. session.close()
  11. return state
  12. def get_regions(state_id):
  13. """Get region from state"""
  14. session = SESSION()
  15. state_regions = session.query(StateRegion) \
  16. .filter(StateRegion.state_id == state_id) \
  17. .filter(StateRegion.until_date_time == None) \
  18. .all()
  19. regions = []
  20. for state_region in state_regions:
  21. regions.append(state_region.region)
  22. session.close()
  23. return regions
  24. def save_factories(state_id, factories):
  25. """Save factories to database"""
  26. session = SESSION()
  27. session.close()
  28. factory_track = FactoryTrack()
  29. factory_track.state_id = state_id
  30. factory_track.date_time = datetime.now()
  31. session.add(factory_track)
  32. for factory_dict in factories:
  33. factory = session.query(Factory).get(factory_dict['id'])
  34. if factory is None:
  35. factory = save_factory(session, factory_dict)
  36. factory_stat = FactoryStat()
  37. factory_stat.level = factory_dict['level']
  38. factory_stat.experience = factory_dict['experience']
  39. factory_stat.wage = factory_dict['wage']
  40. factory_stat.workers = factory_dict['workers']
  41. factory_stat.factory_id = factory.id
  42. factory_stat.factory_track_id = factory_track.id
  43. session.add(factory_stat)
  44. current_location = session.query(FactoryLocation) \
  45. .filter(FactoryLocation.factory_id == factory.id) \
  46. .filter(FactoryLocation.until_date_time == None).first()
  47. if not current_location or current_location.region_id != factory_dict['region_id']:
  48. region = session.query(Region) \
  49. .filter(Region.id == factory_dict['region_id']).first()
  50. factory_location = FactoryLocation()
  51. factory_location.factory_id = factory.id
  52. factory_location.region_id = region.id
  53. factory_location.from_date_time = datetime.now()
  54. session.add(factory_location)
  55. if current_location:
  56. current_location.until_date_time = datetime.now()
  57. session.commit()
  58. session.close()
  59. def save_factory(session, factory_dict):
  60. """Save factory to database"""
  61. factory = Factory()
  62. factory.id = factory_dict['id']
  63. factory.name = factory_dict['name']
  64. session.add(factory)
  65. return factory