- 이미 존재하는 DB에 psql로 데이터를 넣다보면 Integrity Error 가 발생할 떄가 있다. 근데 psql 옵션에는 각 한줄 한줄의 error를 무시할 수 있는 옵션이 없다.
- 그냥 바로 넣기 때문인데... 이것 때문에 짜증이 나서 파이썬으로 한줄씩 읽으면서 DB에 넣고 Error가 발생하면 그 Data는 무시할 수 있게끔 했다.
- 끝까지 넣기만 하면 되는거다. Data 정합성이 중요하다면 이렇게 하면 안되지만 정합성이 중요하지 않은 Data들에서는 충분히 쓸만한 소스다.
Last active
September 7, 2018 16:51
-
-
Save neoneo40/ff5655bde94c1fa353917a9cca1c44bc to your computer and use it in GitHub Desktop.
psql ignore errors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from .models import Url | |
def get_columns(line): | |
column_str = re.search(r'COPY [-_\w\.]+ \(([^\)]+)\)', line).group(1) | |
columns = column_str.split(',') | |
return [column.strip() for column in columns] | |
def is_start(text): | |
if text.startswith('COPY '): | |
return True | |
return False | |
def is_end(text): | |
if text.startswith('\.'): | |
return True | |
return False | |
def input_data_in_db(path, db): | |
start = None | |
columns = None | |
with open(path) as f: | |
for line in f: | |
if not start: | |
start = is_start(line) | |
if start: | |
columns = get_columns(line) | |
continue | |
if is_end(line): | |
break | |
dic = {} | |
for i, column in enumerate(columns): | |
dic[column] = line.split('\t')[i].strip() | |
if dic[column] == '\n' or dic[column] == '': | |
dic[column] = None | |
print(dic) | |
try: | |
obj = db(**dic) | |
obj.save() | |
except Exception as e: | |
print(e) | |
path = 'data.dump' | |
db = Url | |
input_data_in_db(path=path, db=db) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment