[英]sqlalchemy + postgresql hstore to string
如何将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()
让Postgresql为您执行hstore
转换,而不是尝试手动将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类型代替文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.