firestore를 이용하다 보면 transaction 작업이 필요할 경우가 있다.
먼저, transaction에 대해 알아보자.
데이터베이스 시스템은 각각의 트랜잭션에 대해 원자성(Atomicity), 일관성(Consistency), 독립성(Isolation), 영구성(Durability)을 보장한다.
이 성질을 첫글자를 따 ACID라 부른다.
데이터베이스 기능 중, 트랜잭션을 조작하는 기능은 사용자가 데이터베이스 완전성(Integrity) 유지를 확신하게 한다.
단일 트랜잭션은 데이터베이스 내에 읽거나 스는 여러 개 쿼리를 요구한다. 이때 중요한 것은 데이터베이스가 수행된 일부 쿼리가 남지 않는 것이다. 예를 들면, 송금을 할 때 한 계좌에서인출되면 다른 계좌에서 입금이 확인되는 것이 중요하다. 또한 트랜잭션은 서로 간섭하지 않아야 한다.
- 출처 위키피디어 < 데이터베이스 트랜잭션 >. https://ko.wikipedia.org/wiki/데이터베이스_트랜잭션
데이터베이스 트랜잭션 - 위키백과, 우리 모두의 백과사전
데이터베이스 트랜잭션(Database Transaction)은 데이터베이스 관리 시스템 또는 유사한 시스템에서 상호작용의 단위이다. 여기서 유사한 시스템이란 트랜잭션이 성공과 실패가 분명하고 상호 독립
ko.wikipedia.org
그럼 코드로 어떻게 구현할까?
Firestore _firestore = Firestore.instance;
await _firestore.runTransaction((transaction)async{
CollectionReference accountsRef = _firestore
.collection('accounts');
DocumentReference acc1Ref = accountsRef.document('account1');
DocumentReference acc2Ref = accountsRef.document('account2');
DocumentSnapshot acc1snap = await transaction.get(acc1Ref);
DocumentSnapshot acc2snap = await transaction.get(acc2Ref);
await transaction.update(acc1Ref,{
'amount' : acc1snap.data['balance'] - 200
});
await transaction.update(acc2Ref,{
'amount' : acc2snap.data['balance'] + 200
});
});
위는 은행계좌 account1 -> account2 로 송금하는 과정을 transaction으로 묶은 예제이다.
실제로 runTransaction function의 parameter로 transaction으로 수행하고 싶은 로직을 넣을 경우 해당 함수는 transaction으로 수행되며, 추가적으로 timeout parameter(timeout: Duration)를 추가하여 타임아웃 또한 설정할 수 있다.
위 정보가 이 글을 읽는 여러분에게 도움이 되었으면 좋겠다.
'Programming > Flutter' 카테고리의 다른 글
Container Widget에 Animation 추가하기- AnimatedSwitcher (0) | 2021.12.09 |
---|
댓글