import time


def compose_query_sql(measurement, limit, start_date, end_date, condition=None):
    """
    根据条件构建查询metric db的sql语句
    :param measurement: 表
    :param limit: 条数限制
    :param start_date: 查询起始日期
    :param end_date: 查询结束日期
    :param condition: 查询附带条件
    :return: 查询的sql语句
    """
    # 将年月日转换为时间戳，便于查询
    start = int(time.mktime(time.strptime(f"{start_date}", "%Y%m%d")))
    end = int(time.mktime(time.strptime(f"{end_date}", "%Y%m%d")))
    if condition:
        sql = (
            f"SELECT * FROM {measurement} WHERE {condition} AND time >= {start}s AND time < {end}s "
            f"ORDER BY time DESC LIMIT {limit}"
        )
    else:
        sql = f"SELECT * FROM {measurement} WHERE time >= {start}s AND time < {end}s ORDER BY time DESC LIMIT {limit}"
    return sql