2017-08-31 54 views
0

如何将sqlalchemy hstore值转换为字符串?sqlalchemy + postgresql 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值转换为字符串?

UPDATE:我试图做这样的事情:

我有架构的现有表

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() 
+2

编译错误是由于SQLA使用默认的话,您可以用明确反对编译PostgreSQL的话避免:'hs.compile(方言= postgresql.dialect())',但给你留下一个SQL表达式它拥有占位符(它应该),而不是转换为SQL的值。但是你的实际问题是什么?为什么你不能在Core插入中使用这个hstore构造(假设你是这样做的)?你想达到什么目的? –

回答

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类型,而不是文本的,如果这是列包含。

+0

没有my_table ORM构建,我可以使用sql吗? – clay

+0

准确地说,这是核心,而不是ORM,但如果你感觉特别冒险,那么是的。挖掘SQLAlchemy连接的实际psycopg2连接(如果您使用的话),使用['psycopg2.extras.register_hstore(db_connection.connection.connection)'](http://initd.org/psycopg/docs/extras .html#psycopg2.extras.register_hstore),并将您的hstore值作为字典而不是SQLAlchemy'hstore()'传递,并将所需的强制转换添加到您的文本SQL中。 –

+0

它的工作原理!谢谢!! – clay