github.com/matrixorigin/matrixone@v0.7.0/pkg/txn/storage/memorystorage/memtable/transaction.go (about) 1 // Copyright 2022 Matrix Origin 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package memtable 16 17 import "github.com/matrixorigin/matrixone/pkg/txn/storage/memorystorage/memorytable" 18 19 type Transaction struct { 20 ID string 21 BeginTime Time 22 Time Time 23 CommitTime Time 24 State *memorytable.Atomic[TransactionState] 25 IsolationPolicy IsolationPolicy 26 committers map[TxCommitter]struct{} 27 } 28 29 type TxCommitter interface { 30 CommitTx(*Transaction) error 31 AbortTx(*Transaction) error 32 } 33 34 func NewTransaction( 35 id string, 36 t Time, 37 isolationPolicy IsolationPolicy, 38 ) *Transaction { 39 return &Transaction{ 40 ID: id, 41 BeginTime: t, 42 Time: t, 43 State: memorytable.NewAtomic[TransactionState](Active), 44 IsolationPolicy: isolationPolicy, 45 committers: make(map[TxCommitter]struct{}), 46 } 47 } 48 49 type TransactionState uint8 50 51 const ( 52 Active = iota 53 Committed 54 Aborted 55 ) 56 57 func (t *Transaction) Commit(commitTime Time) error { 58 t.CommitTime = commitTime 59 for committer := range t.committers { 60 if err := committer.CommitTx(t); err != nil { 61 return err 62 } 63 } 64 t.State.Store(Committed) 65 return nil 66 } 67 68 func (t *Transaction) Abort() error { 69 var e error 70 for committer := range t.committers { 71 if err := committer.AbortTx(t); err != nil { 72 e = err 73 } 74 } 75 t.State.Store(Aborted) 76 return e 77 } 78 79 func (t *Transaction) Copy() *Transaction { 80 newTx := *t 81 newTx.State = new(memorytable.Atomic[TransactionState]) 82 newTx.State.Store(t.State.Load()) 83 newTx.committers = make(map[TxCommitter]struct{}) 84 return &newTx 85 }