DB commit과 flush는 다르다.

Alex·2025년 1월 1일

CS를 공부하자

목록 보기
4/40

테스트 코드를 작성하다보면 commit을 하고 아예 새로운 트랜잭션을 시작해야 할 때가 있다.

이런 경우는 롤백이 되지 않으므로 내가 알아서 지워줘야 한다.

EntityManager로 flush()할 때는 자동으로 롤백이 됐는데
커밋한 건 롤백이 안 된다. 어떤 차이가 있는걸까?

SQLAlchemy: What's the difference between flush() and commit()?

이 글에 이런 내용이 이다.

A Session object is basically an ongoing transaction of changes to a database (update, insert, delete). These operations aren't persisted to the database until they are committed
The session object registers transaction operations with session.add(), but doesn't yet communicate them to the database until session.flush() is called.

객체는 커밋이 될 때까지 영속화 되지 않는다.

session.flush() communicates a series of operations to the database (insert, update, delete). The database maintains them as pending operations in a transaction. The changes aren't persisted permanently to disk, or visible to other transactions until the database receives a COMMIT for the current transaction (which is what session.commit() does).
session.commit() commits (persists) those changes to the database.
flush() is always called as part of a call to commit() (1).
Hopefully this example will make this clearer:

flush는 일련의 명령어를 DB로 전달하는 행위다. 그렇다고 해서 영속화가 되는 것은 아니다.

flush()는 DB와 1차 캐시를 동기화해주는것이고, commit을 해야 영속화(그니까 DB에 저장)이 되는 것으로 보인다.

flush()는 영속화가 아니라서 롤백이 가능하지만 commit은 영속화된 것이기에 롤백이 안된다.

profile
답을 찾기 위해서 노력하는 사람

0개의 댓글