是否有与SqlAlchemy数据库无关的FROM_UNIXTIME()函数?

时间:2019-02-08 11:23:32

标签: python mysql sqlite sqlalchemy flask-sqlalchemy

目前,我在烧瓶sqlalchemy中有一个类似于以下查询:

from sqlalchemy.sql import func

models = (
  Model.query
  .join(ModelTwo)
  .filter(Model.finish_time >= func.from_unixtime(ModelTwo.start_date))
  .all()
)

这在我正在生产中运行的MySQL上很好用,但是当我使用内存中的SqlLite数据库对该方法运行测试时,它失败了,因为from_unixtime不是SqlLite函数。

除了尽可能在与生产相同的数据库上运行测试外,还有我有两种不同的方式来表示数据库中的数据这一事实,SqlAlchemy中还有一种数据库不可知的方法可用于将日期转换为Unix时间戳,反之亦然?

1 个答案:

答案 0 :(得分:1)

对于对此感兴趣的其他人,我找到了一种基于所用SQL方言在SqlAlchemy中创建自定义函数的方法。因此,以下实现了我所需要的:

from sqlalchemy.sql import expression
from sqlalchemy.ext.compiler import compiles


class convert_timestamp_to_date(expression.FunctionElement):
    name = 'convert_timestamp_to_date'


@compiles(convert_timestamp_to_date)
def mysql_convert_timestamp_to_date(element, compiler, **kwargs):
    return 'from_unixtime({})'.format(compiler.process(element.clauses))


@compiles(convert_timestamp_to_date, 'sqlite')
def sqlite_convert_timestamp_to_date(element, compiler, **kwargs):
    return 'datetime({}, "unixepoch")'.format(compiler.process(element.clauses))

上面的查询现在可以这样重写:

models = (
  Model.query
  .join(ModelTwo)
  .filter(Model.finish_time >= convert_timestamp_to_date(ModelTwo.start_date))
  .all()
)
相关问题