-
VARCHAR(255) 타입의 컬럼에 255 바이트 이상을 넣으려고 한다면?운영 중인 서비스/Coconut. 2024. 3. 25. 20:17
테스트를 적다가 발견한 이슈에 대해서 정리하려고 합니다. (
테스트 코드 만세)처음 데이터베이스 설계시에 데이터의 길이가 길어질 수 있음을 놓치고 VARCHAR(255)를 타입으로 적용하였습니다.
테스트에서 엣지 케이스를 고려하던 중, 255바이트를 초과하는 데이터를 삽입하려고 하면 에러가 발생합니다.
MySQL에서 VARCHAR(255)타입이 설정된 컬럼에
1000바이트를 넣으면 255만큼만 들어갈까요? 하나도 안들어갈까요?1. 에러의 발생
예시로 생각해본 데이터를 넣기에 255 바이트면 충분하다는 생각이 들어서 requirements의 타입을 VARCHAR(255)를 할당했습니다.
테스트를 작성하면서 엣지 케이스를 생각해보았는데, 경우에 따라서 해당 필드에는 충분히 긴 데이터가 들어갈 수도 있다는 생각을 했습니다. 오!? 255바이트보다 긴 데이터를 넣으면 255만큼만 들어가나? 라는 생각이 들어서 바로 테스트를 해봤습니다.
테스트 환경에서는 H2 데이터베이스를 사용하고 있습니다. 스프링에서 무결성과 관련된 DataIntegrityViolationException 예외를 발생시킵니다. 데이터가 너무 길어서 넣을 수 없다고 알려줍니다.
이번에는 MySQL을 사용하는 개발환경에서는 어떻게 작동하는지 확인해보겠습니다.
MySQL에서 MysqlDataTruncation 예외를 던집니다.
하지만 스프링에서 최종적으로 DataIntegrityViolationException 예외로 변환하여 응답을 전해줍니다.
기본적으로 컬럼에 할당된 바이트 이상을 저장하려고하면 예외를 발생시켜서 막는 것을 확인할 수 있습니다.
데이터 무결성 보장을 위한 데이터베이스의 조치로 볼 수 있겠습니다.
2. strict모드
MySQL에서는 정합성 보장을 위해서 strict 모드를 기본적으로 실행하고 있습니다.
이 strict 모드를 해지할 경우에는 255바이트가 넘는 요청에 대해서 255바이트까지만 저장을 할 수 있습니다. ( 사용하지 않는 편을 권장 )
MySQL의 설정파일인 my.conf에서 strict mode를 해지하거나 세션별로 해지해서 사용할 수 있습니다.
// my.cnf sql_mode = ""
// mysql console mysql> SET SESSION sql_mode = '';
warning으로 데이터가 truncated 되었다고 알려주지만 데이터 삽입을 막지는 않는 것을 확인할 수 있습니다.
감사합니다.
'운영 중인 서비스 > Coconut.' 카테고리의 다른 글
Nginx 로그 살펴보기 ( feat. 웹 스캐닝 ) (0) 2024.04.07 corretto17 openjdk에서 발생한 인코딩 이슈해결 (error: error while writing...) (0) 2024.03.29 쓰기에 시간을 쓸 것인가? 읽기에 시간을 쓸 것인가? (0) 2024.03.21 Patch Package로 의존성 이슈 해결하기 (0) 2024.03.20 문제 해결을 위한 증거자료 수집하기 (feat.로그) (0) 2024.02.17