首页 > 解决方案 > SQLite 和 PostgreSQL 的用户定义函数?

问题描述

我目前有一个 SQLite 用户定义函数(用 Python 编写)。

我想支持使用 PostgreSQL 作为我的模拟应用程序的备用后端(以允许模拟程序的多个并行执行)。我没有绑定 PostgreSQL,所以我想另一个基于服务器的数据库也可以工作......

跨多个 peewee 后端处理用户定义函数的最佳方法是什么?

SQLite 不支持 SQL 中的用户定义函数,我曾考虑过使用 PL/python,但没有关于如何集成 peewee 和 PL/python 的详细信息(以及如何将应用程序配置数据添加到 PL/python 函数中) )

我可以有两个用户定义函数的实现(用于 PostGreSQL 的 SQL 和用于 SQLite 的 python),但首先用 Python 编写它的好处之一是我不必在 SQL 中解决它 :-)

为了完整起见,这里是用户定义函数的核心,它作为父查询的一部分调用并传递了 id_1 和 id_2 参数。

使用 python set math 对我来说比 SQL 容易得多 :-)

    allowed = False

    try:

        relatives_1 = set()
        relatives_2 = set()

        common_ancestor = censere.models.RelationshipEnum.great_great_great_grandparent

        for r1 in censere.models.Relationship.select(censere.models.Relationship.second).where( 
                ( censere.models.Relationship.first == id_1 ) &
                ( censere.models.Relationship.relationship <= common_ancestor ) 
            ).tuples():
            relatives_1.add( str(r1[0]) )

        for r2 in censere.models.Relationship.select(censere.models.Relationship.second).where( 
                ( censere.models.Relationship.first == id_2 ) &
                ( censere.models.Relationship.relationship <= common_ancestor ) 
            ).tuples():
            relatives_2.add( str(r2[0]) )

        if relatives_1 == relatives_2:
            allowed = False

        if len(relatives_1 & relatives_2) == 0:
            allowed = True

    except Exception as e:

        logging.log( logging.ERROR, 'Caught exception %s', str(e) )

    return allowed

标签: postgresqlsqlitepeewee

解决方案


推荐阅读