SQLAlchemy Harvesine大圆计算错误

时间:2019-01-09 03:19:26

标签: python sql postgresql sqlalchemy

我有下表:

id     zip    city     state    longitude    latitude  timezone    dst
3817   99950    Ketchikan    AK    -131.46633      55.875767    -9           1
....

在我的SQLALchemy模型中,我具有以下@classmethod 我想返回给定经纬度X英里内的所有邮政编码 我创建了两个查询,但是两个查询都在失败的query1,query2下

@classmethod
def getZipsWithinXMiles(cls, lat1: str, lon1: str, dst: str):
    """ Get zip codes within 'dst' miles of lat1,lon1"""

    print(lat1, lon1, dst)
    breakpoint()
    query1 = "SELECT * ," \
        "( 3958.75 * acos(sin(lat1/57.2958) * sin(latitude/57.2958) + " \
        "cos(lat1/57.2958) * cos(latitude/57.2958) * " \
        "cos(longitude/57.2958 - lon1/57.2958))" \
        ") as distanceInMiles " \
        "FROM ZipCode " \
        "HAVING distanceInMiles < dst " \
        "ORDER BY distanceInMiles" \
        % {'lat1': float(lat1), 'lon1': float(lon1), 'dst': int(dst)}

    query2 = "SELECT * FROM " \
        "(SELECT id, city, state, zip, " \
        "( 3958.75 * acos(sin(lat1/57.2958) * sin(latitude/57.2958) + " \
        "cos(lat1/57.2958) * cos(latitude/57.2958) * " \
        "cos(longitude/57.2958 - lon1/57.2958))" \
        ") as distanceInMiles " \
        "FROM ZipCode " \
        " ) inner_query " \
        "HAVING distanceInMiles < dst " \
        "ORDER BY distanceInMiles" \
        % {'lat1': float(lat1), 'lon1': float(lon1), 'dst': int(dst)}

    print(query1)
    print(query2)
    breakpoint()
    zipCodes = cls.query.from_statement(query2).all()
    return zipCodes

这是我得到的错误:

cursor.execute(statement, parameters)
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) relation "zipcode" does not exist
LINE 1: ...57.2958 - lon1/57.2958))) as distanceInMiles FROM ZipCode  )...

有关更多信息,这是我用来创建表格的模型

class ZipCode(db.Model):

    __tablename__ = "zipCode"

    id = db.Column(db.Integer, primary_key=True)
    zip = db.Column(db.String(5), nullable=False)  # 23567
    city = db.Column(db.String(50), nullable=False)  # New York
    state = db.Column(db.String(2), nullable=False)  # Ex: NY
    longitude = db.Column(db.String(15), nullable=False)
    latitude = db.Column(db.String(15), nullable=False)
    timezone = db.Column(db.String(3), nullable=False)  # Ex: -5,-10
    dst = db.Column(db.String(2))  # Ex: 0,1

此代码有什么问题? 我尝试了两个查询,都失败了

1 个答案:

答案 0 :(得分:4)

给予

__tablename__ = "zipCode"

您将必须使用带引号的标识符来引用该表:

query1 = "..." \
    ...
    'FROM "zipCode" ' \
    ...

由于mixed case

  

引用标识符也使其区分大小写,而未加引号的名称总是折叠为小写。例如,PostgreSQL认为标识符FOO,foo和“ foo”相同,但是“ Foo”和“ FOO”彼此不同。

如果给定的table name包含大写字母,保留字或特殊字符,则SQLAlchemy将使用带引号的标识符。


关于其余部分,使用HAVING子句基于选择列表项进行过滤是Postgresql不支持的MySQL“扩展”。 query2在使用子查询时处于正确的轨道,但应改为使用WHERE子句。

似乎您已经将latitudelongitude列定义为字符串,因此必须使用CAST才能对它们进行算术运算。考虑改用适当的类型。

您还使用了%格式,但是在字符串中没有任何转换说明符–这是一件好事,因为您无论如何都不应该进行字符串格式化。而是使用绑定参数/占位符,并将参数传递给SQL驱动程序或库。

您的所有类方法都看起来像这样:

def getZipsWithinXMiles(cls, lat1: str, lon1: str, dst: str):
    """ Get zip codes within 'dst' miles of lat1,lon1"""

    query = db.text("""
        SELECT *
        FROM (
            SELECT "zipCode".*
                 , (3958.75 *
                    acos(sin(:lat1 / 57.2958) * sin(cast(latitude as double precision) / 57.2958) +
                         cos(:lat1 / 57.2958) * cos(cast(latitude as double precision) / 57.2958) *
                         cos(cast(longitude as double precision) / 57.2958 - :lon1 / 57.2958)))
                   as distanceInMiles
            FROM "zipCode") zc
        WHERE zc.distanceInMiles < :dst
        ORDER BY zc.distanceInMiles
        """)

    zipCodes = cls.query.\
        from_statement(query).\
        params(lat1=float(lat1),
               lon1=float(lon1),
               dst=int(dst)).\
        all()

    return zipCodes

尽管我对距离计算的正确性不承担任何责任。