Example #1
0
def save_station(session, data):
    """
    Add or update a station in the DB.
    """
    # If this station is set to "start", we must remove that flag from all other
    # stations. We'll just set them all to False, then update the given station
    # with True. This ensures that we only have one starting station.
    if data.get('is_start'):
        session.execute(update(Station).values(is_start=False))

    if data.get('is_end'):
        session.execute(update(Station).values(is_end=False))

    # Ensure we don't have duplicate values for the "order" field
    same_order = session.query(Station).filter(and_(
        Station.order == data['order'],
        Station.id != data['id'])).first()
    while same_order:  # As long as we have a matching entry, increment by 1
        data['order'] += 1
        same_order = session.query(Station).filter(and_(
            Station.order == data['order'],
            Station.id != data['id'])).first()

    station = Station(
        name=data['name'],
        contact=data['contact'],
        phone=data['phone'],
    )
    station.id = data.get('id')
    station.order = data['order']
    station.is_start = data['is_start']
    station.is_end = data['is_end']
    merged = session.merge(station)
    DB.session.commit()
    return merged