sqlalchemy + postgresql hstore转换为字符串

时间:2017-08-31 21:06:16

标签: python postgresql sqlalchemy hstore

如何将sqlalchemy hstore值转换为字符串?

from sqlalchemy.dialects.postgresql import array, hstore

hs = hstore(array(['key1', 'key2', 'key3']), array(['value1', 'value2', 'value3']))

# this triggers sqlalchemy.exc.UnsupportedCompilationError
str(hs)

我期待"key1"=>"value1", "key2"=>"value2", "key3"=>"value3"

之类的东西

我想使用sqlalchemy api而不是编写一个近似我想要的自定义字符串格式化函数。我正在使用使用sqlalchemy的遗留代码库:我需要保留任何内部怪癖并转义格式化的逻辑。

但是,现有的代码库通过ORM表插入使用sqlalchemy,而我想直接将sqlalchemy hstore值转换为字符串?

更新 :我正在尝试这样做:

我有一个包含架构的现有表

create table my_table
(
    id bigint default nextval('my_table_id_seq'::regclass),
    ts timestamp default now(),
    text_col_a text,
    text_col_b text
);

我想让以下Python sqlalchemy代码正常工作:

str_value = some_function()
# Existing code is building an sqlalchemy hstore and inserting
# into a column of type `text`, not an `hstore` column.
# I want it to work with hstore text formatting
hstore_value = legacy_build_my_hstore()

# as is this triggers error:
# ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'hstore'
return db_connection.execute(
    """
    insert into my_table(text_col_a, text_col_b) values (%s, %s)
    returning id, ts
    """,
    (str_value, hstore_value).first()

1 个答案:

答案 0 :(得分:1)

让Postgresql为您执行转换,而不是尝试将hstore构造手动转换为字符串,SQLAlchemy处理转换为合适的文本表示:

return db_connection.execute(
    my_table.insert().
        values(text_col_a=str_value,
               text_col_b=cast(hstore_value, Text)).
        returning(my_table.c.id, my_table.c.ts)).first()

如果可以,请尽快更改您的架构以使用hstore类型而不是文本,如果这是该列所包含的内容。

相关问题