psycopg2 COPY使用cursor.copy_from()冻结大输入

Ada*_*tan 0 python postgresql psycopg2 large-data-volumes

使用psycopg2 cursor对象考虑Python中的以下代码(为清楚起见,更改或省略了一些列名称):

filename='data.csv'
file_columns=('id', 'node_id', 'segment_id', 'elevated', 
              'approximation', 'the_geom', 'azimuth')
self._cur.copy_from(file=open(filename),
                    table=self.new_table_name, columns=file_columns)
Run Code Online (Sandbox Code Playgroud)
  • 数据库位于快速LAN上的远程计算机上.
  • 使用\COPYbash工作速度非常快,即使对于大型(~1,000,000行)文件也是如此.

这段代码超5000行,但data.csv超过10,000 行时,程序完全冻结.

任何想法\解决方案?

亚当

mik*_*pie 5

这只是一种解决方法,但您可以将某些内容传递给psql.有时当我懒得忘掉psycopg2时,我会使用这个配方

import subprocess
def psql_copy_from(filename, tablename, columns = None):
    """Warning, this does not properly quote things"""
    coltxt = ' (%s)' % ', '.join(columns) if columns else ''
    with open(filename) as f:
        subprocess.check_call([
            'psql',
            '-c', 'COPY %s%s FROM STDIN' % (tablename, coltxt),
            '--set=ON_ERROR_STOP=true', # to be safe
            # add your connection args here
        ], stdin=f)
Run Code Online (Sandbox Code Playgroud)

就你的锁定而言,你使用多线程或类似的东西吗?

你的postgres是否记录了诸如关闭连接或死锁之类的内容?锁定后你能看到磁盘活动吗?