예외 처리

PostgreSQL에서의 트랜잭션과 오류 처리

Jason Myers

Principal Engineer

에러가 나는 구문

INSERT INTO sales (name, quantity, cost) 
VALUES 
  ('chocolate chip', 6, null);
ERROR:  column "cost"에 null 값이 있어 not-null 제약 조건을 위반했습니다
DETAIL:  실패한 행: 
(1, "chocolate chip", 6, null, 2020-04-28 19:58:55.715886).
PostgreSQL에서의 트랜잭션과 오류 처리

일반 예외 캡처

R

tryCatch(
  sqrt("a"), 
  error=function(e) 
    print("Boom!")
)

Python

try:
   math.sqrt("a")
except Exception as e:
   print("Boom!")

PL/pgSQL

BEGIN 
SELECT 
  SQRT("a");
EXCEPTION WHEN others THEN RAISE INFO 'Boom!';
END;

결과

     R: Boom!
Python: Boom!
   SQL: INFO: Boom!
PostgreSQL에서의 트랜잭션과 오류 처리

PL/pgSQL DO 명령(익명 함수)

DO $$

DECLARE some_variable text;
BEGIN SELECT text from a table; END;
$$ language 'plpgsql';
PostgreSQL에서의 트랜잭션과 오류 처리

예외 처리 함수

DO $$
BEGIN
    SELECT SQRT("a");
EXCEPTION
    WHEN others THEN
       INSERT INTO errors (msg) VALUES ('문자열의 제곱근을 구할 수 없습니다.');
       RAISE INFO '문자열의 제곱근을 구할 수 없습니다.';
END; 
$$ language 'plpgsql';
PostgreSQL에서의 트랜잭션과 오류 처리

예외 처리를 현명하게 사용하기

  • EXCEPTION 절은 큰 오버헤드를 유발합니다
  • Python이나 R의 예외 처리가 더 효율적입니다
  • 예외 해결에 필요한 정확한 컨텍스트를 포기하지 마십시오
  • 예외를 이해하기 전에는 최적화하지 마십시오
1 https://www.postgresql.org/docs/12/plpgsql-control-structures.html {{1}}
PostgreSQL에서의 트랜잭션과 오류 처리

데이터 세트 변경

patients

column type
patient_id integer
a1c double (float)
glucose integer
fasting boolean
created_on timestamp

errors

column type
error_id integer
state string
msg string
detail string
context string
PostgreSQL에서의 트랜잭션과 오류 처리

연습해 봅시다!

PostgreSQL에서의 트랜잭션과 오류 처리

Preparing Video For Download...