import psycopg
from psycopg.types.composite import CompositeInfo, register_composite
def insert_data(self):
pg = psycopg.connect(self.connection_string)
cursor = pg.cursor()
class TradeComposite(CompositeInfo):
def __init__(self, name, oid, attrs, array_oid=None, schema=None):
self.name = name
self.schema = schema
self.oid = oid
self.array_oid = array_oid
self.attnames = [a[0] for a in attrs]
self.atttypes = [a[1] for a in attrs]
# self._create_type(name, self.attnames)
# self.typecaster = _ext.new_type((oid,), name, self.parse)
# if array_oid:
# self.array_typecaster = _ext.new_array_type(
# (array_oid,), "%sARRAY" % name, self.typecaster)
# else:
# self.array_typecaster = None
def make(self, values):
return tuple(values)
info = CompositeInfo.fetch(pg, 'insertable_unique_trade')
register_composite(info, cursor, factory=TradeComposite)
def handle_messages():
trades = [
(55, 'acctname', 0, 69, 66376.07596266, 68, 66386.70210866087, 68, 0.0, 1.00016009, '6043080995', 1641444405.716349),
(55, 'acctname', 0, 69, 2.05263549, 68, 6750.199985115853, 68, 0.0, 3288.55270115, '6215459421', 1642183827.224316)
]
cursor.execute("SELECT insert_unique_trades(%s::insertable_unique_trade[])::insertable_unique_trade[]", [trades])
results = cursor.fetchall()
pg.commit()
复合类型在psql脚本中用CREATE TYPE insertable_unique_trade AS
创建。我可以用pg.commit()
插入数据到数据库,但我不能执行cursor.fetchall()
,因为(我认为)TradeComposite类。psycopg2复合脚轮在psycopg 3.0.9中的等效实现是什么?我必须从psycopg2 2.9.3升级到psycopg 3.0.9。
您可以简单地使用:
type_info = CompositeInfo.fetch(conn=self.Connection, name="your_type")
register_composite(info=type_info, context=self.Connection, factory=None)
您将得到结果类型为namedtuple。