SQLAlchemy核心创建临时表作为

4
我试着在SQLAlchemy Core 中使用 PostgreSQL 的 CREATE TEMPORARY TABLE foo AS SELECT... 查询。我查看了文档,但没有找到实现的方法。
我有一个 SQLA 语句对象。如何从其结果创建一个临时表?

我找到了一篇文章,使用自定义的Select类来实现这个功能:https://groups.google.com/forum/#!msg/sqlalchemy/O4M6srJYzk0/B8Umq9y08EoJ。这篇文章已经有一年了,这仍然是最惯用的方法吗? - skyler
显然,SELECT INTO 格式并不是在 PostgreSQL 中执行此操作的推荐方式,这也是我链接的帖子使用的方式:http://www.postgresql.org/docs/9.1/static/sql-selectinto.html(请参见“注释”部分)。 - skyler
1个回答

3

这是我想到的方法,请告诉我是否行得通。

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


class CreateTableAs(Select):
    """Create a CREATE TABLE AS SELECT ... statement."""

    def __init__(self, columns, new_table_name, is_temporary=False,
            on_commit_delete_rows=False, on_commit_drop=False, *arg, **kw):
        """By default the table sticks around after the transaction. You can
        change this behavior using the `on_commit_delete_rows` or
        `on_commit_drop` arguments.

        :param on_commit_delete_rows: All rows in the temporary table will be
        deleted at the end of each transaction block.
        :param on_commit_drop: The temporary table will be dropped at the end
        of the transaction block.
        """
        super(CreateTableAs, self).__init__(columns, *arg, **kw)

        self.is_temporary = is_temporary
        self.new_table_name = new_table_name
        self.on_commit_delete_rows = on_commit_delete_rows
        self.on_commit_drop = on_commit_drop


@compiles(CreateTableAs)
def s_create_table_as(element, compiler, **kw):
    """Compile the statement."""
    text = compiler.visit_select(element)
    spec = ['CREATE', 'TABLE', element.new_table_name, 'AS SELECT']

    if element.is_temporary:
        spec.insert(1, 'TEMPORARY')

    on_commit = None

    if element.on_commit_delete_rows:
        on_commit = 'ON COMMIT DELETE ROWS'
    elif element.on_commit_drop:
        on_commit = 'ON COMMIT DROP'

    if on_commit:
        spec.insert(len(spec)-1, on_commit)

    text = text.replace('SELECT', ' '.join(spec))
    return text

这与 https://dev59.com/x2HVa4cB1Zd3GeqPkz5u#9597404 中的 cloneTable 函数相比如何? - Conrad.Dean

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接