python-3.x 在psycopg2中,psycopg3.0.9等效于复合脚轮是什么?

ff29svar  于 2022-11-26  发布在  Python
关注(0)|答案(1)|浏览(110)
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类。psycopg3.0.9中psycopg2组合脚轮的等效实现是什么?我不得不从psycopg2 2.9.3升级到psycopg3.0.9。

lyr7nygr

lyr7nygr1#

您可以简单地使用以下命令:

type_info = CompositeInfo.fetch(conn=self.Connection, name="your_type")
register_composite(info=type_info, context=self.Connection, factory=None)

并且您将获得结果类型作为命名元组。

相关问题