2017-08-31 51 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