database.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. """Main application"""
  2. from datetime import datetime, timedelta, timezone
  3. from sqlalchemy import or_
  4. from app import SESSION, RESOURCE_MAX
  5. from app.models import State, Region, DeepExploration, DeepExplorationOrder, StateRegion
  6. def save_deep_explorations(region_id, deep_explorations):
  7. """Save resources to database"""
  8. session = SESSION()
  9. for deep_exploration_id, deep_exploration_dict in deep_explorations.items():
  10. deep_exploration = session.query(DeepExploration).get(deep_exploration_id)
  11. if deep_exploration:
  12. break
  13. deep_exploration = DeepExploration()
  14. deep_exploration.id = deep_exploration_id
  15. region = session.query(Region).get(region_id)
  16. if not region:
  17. region = save_region(session, region_id)
  18. deep_exploration.region_id = region_id
  19. deep_exploration.resource_type = deep_exploration_dict['resource_type']
  20. deep_exploration.until_date_time = deep_exploration_dict['until_date_time']
  21. session.add(deep_exploration)
  22. session.commit()
  23. session.close()
  24. def get_active_deep_exploration(region_id):
  25. """Get active deep exploration in a region"""
  26. session = SESSION()
  27. deep_exploration = session.query(DeepExploration) \
  28. .filter(DeepExploration.region_id == region_id) \
  29. .filter(DeepExploration.until_date_time >= datetime.now()) \
  30. .first()
  31. session.close()
  32. return deep_exploration
  33. def save_region(session, region_id):
  34. """Save player to database"""
  35. region = Region()
  36. region.id = region_id
  37. region.name = 'UNKNOWN'
  38. session.add(region)
  39. return region
  40. def get_orders():
  41. """Get deep exploration orders"""
  42. session = SESSION()
  43. date_time_now = datetime.now()
  44. orders = session.query(DeepExplorationOrder) \
  45. .filter(DeepExplorationOrder.from_date_time <= date_time_now) \
  46. .filter(or_(
  47. DeepExplorationOrder.until_date_time >= date_time_now,
  48. DeepExplorationOrder.until_date_time == None
  49. )) \
  50. .all()
  51. session.close()
  52. return orders
  53. def get_order(order_id):
  54. """Get order by id"""
  55. session = SESSION()
  56. order = session.query(DeepExplorationOrder).get(order_id)
  57. session.close()
  58. return order
  59. def get_region(region_id):
  60. """Get region by id"""
  61. session = SESSION()
  62. region = session.query(Region).get(region_id)
  63. session.close()
  64. return region
  65. def get_state(region_id):
  66. """Get state from region"""
  67. session = SESSION()
  68. state = session.query(State) \
  69. .join(State.state_regions) \
  70. .filter(StateRegion.region_id == region_id) \
  71. .filter(StateRegion.until_date_time == None) \
  72. .first()
  73. session.close()
  74. return state