PostgreSQL
 SQL >> Datenbank >  >> RDS >> PostgreSQL

Eine Python-Liste von Tupeln in ein PostgreSQL-Array eines zusammengesetzten Typs einfügen

Eine Python-Sequenz von Tupeln auf ein PostgreSQL-Array eines zusammengesetzten Typs abzubilden, gelingt fast schon mit einer kleinen Ergänzung: einem expliziten Cast auf den Array-Typ des zusammengesetzten Typs. Aufbauend auf Ihrer bestehenden Arbeit:

quote_1 = ("monkeys rock", "False") quote_2 = ("donkeys rock", "True") q_list = [ quote_1, quote_2 ] print cur.mogrify( "insert into posts VALUES(%s,%s::quotes[])", ("animals are good", q_list) ) # added explicit cast to quotes[] -> ^^^^^^^

Warum das wichtig ist: Versuchen Sie das entsprechende reine SQL direkt in psql:

insert into posts VALUES( 'animals are good', ARRAY[ ('monkeys rock', 'false'), ('donkeys rock', 'true') ] );

Postgres beschwert sich:

ERROR: column "q" is of type quotes[] but expression is of type record[] LINE 1: insert into posts VALUES('animals are good',ARRAY[('monkeys ... HINT: You will need to rewrite or cast the expression.

Ein anonymes ARRAY[...] von Tupeln wird als record[] typisiert, und PostgreSQL wandelt das nicht stillschweigend in Ihr Array des zusammengesetzten Typs um. Ihm den beabsichtigten Typ mitzuteilen, löst das Problem:

insert into posts VALUES( 'animals are good', ARRAY[ ('monkeys rock', 'false'), ('donkeys rock', 'true') ]::quotes[] ); INSERT 0 1 select * from posts; body | q -------------------+------------------------------------------ animals are good | {"(\"monkeys rock\",false)","(\"donkeys rock\",true)"} (1 row)

Der explizite ::quotes[]-Cast ist die ganze Lösung, egal ob Sie SQL von Hand tippen oder es über das mogrify von psycopg2 aufbauen.