fids/flights-domain/flights-information/src/api/cruds/flight.py

78 lines
2.2 KiB
Python

from sqlalchemy import Date
from sqlalchemy.orm import Session
from sqlalchemy.sql import func
from src.api.models.flight import Flight
from src.api.schemas.flight import Flight as FlightPydantic
def get_flight_by_id(db: Session, flight_id: int):
return db.query(Flight).filter(Flight.id == flight_id).first()
def get_flights(db: Session, skip: int = 0, limit: int = 100):
return db.query(Flight).offset(skip).limit(limit).all()
def create_flight(db: Session, flight: FlightPydantic):
db_flight = Flight(
flight_code=flight.flight_code,
status=flight.status,
origin=flight.origin,
destination=flight.destination,
departure_time=flight.departure_time,
arrival_time=flight.arrival_time,
gate=flight.gate,
user_id=flight.user_id,
)
db.add(db_flight)
db.commit()
db.refresh(db_flight)
return db_flight
def update_flight_status(db: Session, status, id):
db_flight = db.query(Flight).filter(Flight.id == id).first()
if db_flight is None:
raise KeyError
if db_flight.user_id != status.user_id:
raise PermissionError
setattr(db_flight, "status", status.status)
setattr(db_flight, "last_updated", func.now())
db.commit()
db.refresh(db_flight)
return db_flight
def get_flights_by_origin(db: Session, origin: str):
return db.query(Flight).filter(Flight.origin == origin).all()
def get_flights_by_destination(db: Session, destination: str):
return db.query(Flight).filter(Flight.destination == destination).all()
def get_flights_update_origin(db: Session, origin: str, lastUpdate: str):
return (
db.query(Flight)
.filter(
(Flight.origin == origin)
& (Flight.last_updated >= lastUpdate)
& (Flight.departure_time.cast(Date) >= func.current_date())
)
.all()
)
def get_flights_update_destination(db: Session, destination: str, lastUpdate: str):
return (
db.query(Flight)
.filter(
(Flight.destination == destination)
& (Flight.last_updated >= lastUpdate)
& (Flight.arrival_time.cast(Date) >= func.current_date())
)
.all()
)