My codes
from psycopg2.extras import Jsonfrom psycopg2.extensions import register_adapterregister_adapter(dict, Json)data = [{'end_of_epoch_data': ['GasCoin', [{'Input': 5}, {'Input': 6}, {'Input': 7}]],}]def get_upsert_sql(schema: str, table: str, columns: str, primary_keys: list | tuple | set): return f"""INSERT INTO {schema}.{table} ({', '.join(columns)}) VALUES %s ON CONFLICT ({','.join(primary_keys)}) DO UPDATE SET {', '.join([f"{col}=EXCLUDED.{col}" for col in columns if col not in primary_keys])}"""def upsert(data: list, uri: str, schema: str, table: str, primary_keys: list | tuple | set): connection = psycopg2.connect(uri) cursor = connection.cursor() try: columns = data[0].keys() query = get_upsert_sql(schema, table, columns, primary_keys) values = [[d[col] for col in columns] for d in data] execute_values(cursor, query, values) connection.commit() except Exception as e: connection.rollback() raise e finally: cursor.close() connection.close()
but I got errors like
File "/Users/tests/test_pg_write.py", line 47, in upsert execute_values(cursor, query, values) File "/Users/venv/lib/python3.9/site-packages/psycopg2/extras.py", line 1299, in execute_values cur.execute(b''.join(parts))psycopg2.errors.InvalidTextRepresentation: malformed array literal: "GasCoin"LINE 2: (end_of_epoch_data) VALUES (ARRAY['GasCoin',ARRA... ^DETAIL: Array value must start with "{" or dimension information.
end_of_epoch_data
is jsonb column in postgres table
any idea? thanks
UPDATE
it seems that the error is because i tried to write python list to jsonb column in pg table. but it seems that i can write json.dumps(dataend_of_epoch_data)
which is str of python list into jsonb column of postgres table... is this right solution?