Improve Transaction: deduplicate quads, allow adding/removing a quad in the same tx

This commit is contained in:
Quentin Machu 2015-10-06 15:21:33 -04:00
parent 45d96e14ec
commit 91fc9ee3de
2 changed files with 7 additions and 7 deletions

View file

@ -16,19 +16,19 @@ package graph
import "github.com/google/cayley/quad"
// Transaction stores a bunch of Deltas to apply atomatically on the database
// Transaction stores a bunch of Deltas to apply atomatically on the database.
type Transaction struct {
Deltas map[Delta]struct{}
}
// NewTransaction initialize a new transaction
// NewTransaction initialize a new transaction.
func NewTransaction() *Transaction {
return &Transaction{Deltas: make(map[Delta]struct{}, 100)}
}
// AddQuad adds a new quad to the transaction if it is not already present in it
// AddQuad adds a new quad to the transaction if it is not already present in it.
// If there is a 'remove' delta for that quad, it will remove that delta from
// the transaction instead of actually addind the quad
// the transaction instead of actually addind the quad.
func (t *Transaction) AddQuad(q quad.Quad) {
ad := Delta{
Quad: q,
@ -48,9 +48,9 @@ func (t *Transaction) AddQuad(q quad.Quad) {
}
}
// RemoveQuad adds a quad to remove to the transaction
// RemoveQuad adds a quad to remove to the transaction.
// The quad will be removed from the database if it is not present in the
// transaction, otherwise it simply remove it from the transaction
// transaction, otherwise it simply remove it from the transaction.
func (t *Transaction) RemoveQuad(q quad.Quad) {
ad := Delta{
Quad: q,

View file

@ -29,8 +29,8 @@ func TestTransaction(t *testing.T) {
// remove, add -> nothing
tx = NewTransaction()
tx.AddQuad(quad.Quad{Subject: "E", Predicate: "follows", Object: "G", Label: ""})
tx.RemoveQuad(quad.Quad{Subject: "E", Predicate: "follows", Object: "G", Label: ""})
tx.AddQuad(quad.Quad{Subject: "E", Predicate: "follows", Object: "G", Label: ""})
if len(tx.Deltas) != 0 {
t.Errorf("Expected [add, remove]->[], have %d delta(s)", len(tx.Deltas))
}