2017-01-20 53 views
1

영국 회사 하우스 csv 파일의 데이터를 Python을 사용하여 PostgreSQL에 대량로드하려고합니다.Psycopg2를 사용하고 unnest 할 때 "알 수 없음"데이터 유형

데이터의 각 행을 dicts 목록으로 변환 한 다음 불충분 한 명령문을 사용하여 데이터를 단일 대용량 SQL 문으로 압축 해제합니다. 여기에 제가 수행중인 샘플이 있습니다 (더 많은 데이터가 있습니다. 이 코드는 문자열로 좋은만큼 모든 것이 캐스팅으로 작동하지만,

def buildDict(row) 
    clean_name = row[0].decode('utf-8').upper() 
    country_code = lookups.getCountryCodeFromName(row[14]) 
    if len(country_code) > 2: 
     country_code = None 
     insert_dict = { 
      'companyname': row[0], 
      'companynumber': row[1], 
      'regaddress_careof': row[2], 
      'regaddress_pobox': row[3], 
      'dissolutiondate': row[13], 
      } 

      # convert 'None' and '' strings to None 
      for k, v in six.iteritems(insert_dict): 
       insert_dict[k] = set_to_null(v) 


def fastInsert(data): 
    sql=''' 
     INSERT INTO uk_data.companies_house(
      companyname, 
      companynumber, 
      regaddress_careof, 
      regaddress_pobox, 
      dissolutiondate 
     ) 
      SELECT 
      unnest(%(companyname)s), 
      unnest(%(companynumber)s), 
      unnest(%(regaddress_careof)s), 
      unnest(%(regaddress_pobox)s), 
      unnest(%(dissolutiondate)s) 
      ; 
    ''' 

    companyname=[str(r['companyname']) for r in data] 
    companynumber=[str(r['companynumber']) for r in data] 
    regaddress_careof=[str(r['regaddress_careof']) for r in data] 
    regaddress_pobox=[str(r['regaddress_pobox']) for r in data] 
    dissolutiondate=[datetime.strptime(r['dissolutiondate'], "%d/%m/%Y") if r['dissolutiondate'] else None for r in data] 
    execute(sql,locals()) 


def execute(sql,params={}): 
    with connect() as connection: 
     with connection.cursor() as cursor: 
      if params: 
       cursor.execute(sql,params) 
      else: 
       cursor.execute(sql) 

소스의 필드) ... 나는이 (가) 날짜 기록 오류 때마다 다음과 같은 얻을 날짜에 데이터를 시도하고 주조 할 때 (이 값은 조건부에 따라 None으로 설정되었으므로 PostgreSQL에로드해야합니다). 다음과 같이 내가 unnest 성명에서 ::DATE에 유형을 캐스팅하려고했습니다

Error could not determine polymorphic type because input has type "unknown" 

:

sql=''' 
    INSERT INTO uk_data.companies_house(
     companyname, 
     companynumber, 
     regaddress_careof, 
     regaddress_pobox, 
     dissolutiondate 
    ) 
     SELECT 
     unnest(%(companyname)s), 
     unnest(%(companynumber)s), 
     unnest(%(regaddress_careof)s), 
     unnest(%(regaddress_pobox)s), 
     unnest(%(dissolutiondate)s)::DATE 
     ; 
''' 

하지만이 도움이되지 않습니다.

('these are my locals: ', {'regaddress_posttown': ['LEEDS'], 'regaddress_addressline1': ['METROHOUSE 57 PEPPER ROAD'], 'regaddress_addressline2': ['HUNSLET'], 'regaddress_careof': ['None'], 'companystatus': ['Active'], 'companycategory': ['Private Limited Company'], 'companyname': ['! LTD'], 'countryoforigin': ['None'], 'regaddress_pobox': ['None'], 'regaddress_country': ['None'], 'dissolutiondate': None, 'regaddress_postcode': ['LS10 2RU'], 'regaddress_county': ['YORKSHIRE'], 'sql': ' 
     INSERT INTO uk_data.companies_house(
      companyname, 
      companynumber, 
      regaddress_careof, 
      regaddress_pobox, 
      regaddress_addressline1, 
      regaddress_addressline2, 
      regaddress_posttown, 
      regaddress_county, 
      regaddress_country, 
      regaddress_postcode, 
      companycategory, 
      companystatus, 
      countryoforigin, 
      dissolutiondate 
     ) 
      SELECT 
      unnest(%(companyname)s), 
      unnest(%(companynumber)s), 
      unnest(%(regaddress_careof)s), 
      unnest(%(regaddress_pobox)s), 
      unnest(%(regaddress_addressline1)s), 
      unnest(%(regaddress_addressline2)s), 
      unnest(%(regaddress_posttown)s), 
      unnest(%(regaddress_county)s), 
      unnest(%(regaddress_country)s), 
      unnest(%(regaddress_postcode)s), 
      unnest(%(companycategory)s), 
      unnest(%(companystatus)s), 
      unnest(%(countryoforigin)s), 
      unnest(%(dissolutiondate)s) 
      ; 
    ', 'r': {'regaddress_posttown': 'LEEDS', 'regaddress_careof': None, 'companystatus': 'Active', 'companynumber': '08209948', 'regaddress_addressline1': 'METROHOUSE 57 PEPPER ROAD', 'regaddress_addressline2': 'HUNSLET', 'companycategory': 'Private Limited Company', 'companyname': '! LTD', 'countryoforigin': None, 'regaddress_pobox': None, 'regaddress_country': None, 'dissolutiondate': None, 'regaddress_postcode': 'LS10 2RU', 'regaddress_county': 'YORKSHIRE'}, 'data': [{'regaddress_posttown': 'LEEDS', 'regaddress_careof': None, 'companystatus': 'Active', 'companynumber': '08209948', 'regaddress_addressline1': 'METROHOUSE 57 PEPPER ROAD', 'regaddress_addressline2': 'HUNSLET', 'companycategory': 'Private Limited Company', 'companyname': '! LTD', 'countryoforigin': None, 'regaddress_pobox': None, 'regaddress_country': None, 'dissolutiondate': None, 'regaddress_postcode': 'LS10 2RU', 'regaddress_county': 'YORKSHIRE'}], 'companynumber': ['08209948']}) 

나는이 관련이 있는지 모르겠지만, 내가 한 번 DICT에서 촬영 한 지역 변수, 모든 배치되는 것으로 나타났습니다 : 내 주민의 인쇄는 단일 레코드에 대해 다음을 보여줍니다 목록에서 이렇게 : ['None'] 있지만 (dissolutiondate) 문제를 일으키는 날짜 변수는 true None 값으로 제공됩니다.

+0

'unnest (% (dissolutiondate)들) :: DATE'가 교체하려고'unnest (% (dissolutiondate) s) :: DATE []' –

+0

가장 좋은 방법은 http://stackoverflow.com/a/30985541/131874입니다. –

답변

1

그래서 문제는 psycopg2와 postgresql이 배열을 처리 할 때 상호 작용하는 방식으로 밝혀졌습니다. pscyopg의 버그는 이전에 postgres로 가져온 null 값 배열을 허용하지 않습니다.

바오 쭌이 지적 하듯이

https://github.com/psycopg/psycopg2/issues/285

는 솔루션은 명시 적이어야한다 각 unnest 문의 캐스팅에, 또한 모든 데이터 유형 지정 후 [] 브래킷을 포함한다.

은 또한 잘못 여기 파이썬에서 문자열 내 변수를 주조했다 : None 값을 일으키는

companyname=[str(r['companyname']) for r in data] 

'None' 값의 문자열로 전환 할 수 있습니다. 여기

는 올바른 코드의 샘플입니다 :

SELECT 
      unnest(%(companyname)s::TEXT[]), 
      unnest(%(companynumber)s::TEXT[]), 
      unnest(%(regaddress_careof)s::TEXT[]), 
      unnest(%(regaddress_pobox)s::TEXT[]), 
      unnest(%(regaddress_addressline1)s::TEXT[]), 
      unnest(%(regaddress_addressline2)s::TEXT[]), 
      unnest(%(regaddress_posttown)s::TEXT[]), 
      unnest(%(regaddress_county)s::TEXT[]), 
      unnest(%(regaddress_country)s::TEXT[]), 
      unnest(%(regaddress_postcode)s::TEXT[]), 
      unnest(%(companycategory)s::TEXT[]), 
      unnest(%(companystatus)s::TEXT[]), 
      unnest(%(countryoforigin)s::TEXT[]), 
      unnest(%(dissolutiondate)s::TIMESTAMP[]), 

companyname=[(r['companyname']) for r in data] 
    companynumber=[(r['companynumber']) for r in data] 
    regaddress_careof=[(r['regaddress_careof']) for r in data] 
    regaddress_pobox=[(r['regaddress_pobox']) for r in data] 
    regaddress_addressline1=[(r['regaddress_addressline1']) for r in data] 
    regaddress_addressline2=[(r['regaddress_addressline2']) for r in data] 
    regaddress_posttown=[(r['regaddress_posttown']) for r in data] 
    regaddress_county=[(r['regaddress_county']) for r in data] 
    regaddress_country=[(r['regaddress_country']) for r in data] 
    regaddress_postcode=[(r['regaddress_postcode']) for r in data] 
    companycategory=[(r['companycategory']) for r in data] 
    companystatus=[(r['companystatus']) for r in data] 
    countryoforigin=[(r['countryoforigin']) for r in data] 
    dissolutiondate=[datetime.strptime(r['dissolutiondate'], "%d/%m/%Y") if r['dissolutiondate'] else None for r in data]