-
Notifications
You must be signed in to change notification settings - Fork 86
/
transaction.go
380 lines (314 loc) · 7.86 KB
/
transaction.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
package database
import (
"errors"
"fmt"
"strings"
"github.com/genjidb/genji/document"
"github.com/genjidb/genji/engine"
"github.com/genjidb/genji/index"
)
var (
internalPrefix = "__genji_"
tableInfoStoreName = internalPrefix + "tables"
indexStoreName = internalPrefix + "indexes"
)
// Transaction represents a database transaction. It provides methods for managing the
// collection of tables and the transaction itself.
// Transaction is either read-only or read/write. Read-only can be used to read tables
// and read/write can be used to read, create, delete and modify tables.
type Transaction struct {
id int64
db *Database
tx engine.Transaction
writable bool
tableInfoStore *tableInfoStore
indexStore *indexStore
}
// DB returns the underlying database that created the transaction.
func (tx *Transaction) DB() *Database {
return tx.db
}
// Rollback the transaction. Can be used safely after commit.
func (tx *Transaction) Rollback() error {
tx.db.attachedTxMu.Lock()
defer tx.db.attachedTxMu.Unlock()
if tx.writable {
tx.tableInfoStore.rollback(tx)
}
err := tx.tx.Rollback()
if err != nil {
return err
}
if tx.db.attachedTransaction != nil {
tx.db.attachedTransaction = nil
}
return nil
}
// Commit the transaction.
func (tx *Transaction) Commit() error {
tx.db.attachedTxMu.Lock()
defer tx.db.attachedTxMu.Unlock()
if tx.writable {
tx.tableInfoStore.commit(tx)
}
err := tx.tx.Commit()
if err != nil {
return err
}
if tx.db.attachedTransaction != nil {
tx.db.attachedTransaction = nil
}
return nil
}
// Writable indicates if the transaction is writable or not.
func (tx *Transaction) Writable() bool {
return tx.writable
}
// CreateTable creates a table with the given name.
// If it already exists, returns ErrTableAlreadyExists.
func (tx *Transaction) CreateTable(name string, info *TableInfo) error {
if strings.HasPrefix(name, internalPrefix) {
return fmt.Errorf("table name must not start with %s", internalPrefix)
}
if info == nil {
info = new(TableInfo)
}
info.tableName = name
err := tx.tableInfoStore.Insert(tx, name, info)
if err != nil {
return err
}
err = tx.tx.CreateStore(info.storeName)
if err != nil {
return fmt.Errorf("failed to create table %q: %w", name, err)
}
return nil
}
// GetTable returns a table by name. The table instance is only valid for the lifetime of the transaction.
func (tx *Transaction) GetTable(name string) (*Table, error) {
ti, err := tx.tableInfoStore.Get(tx, name)
if err != nil {
return nil, err
}
s, err := tx.tx.GetStore(ti.storeName)
if err != nil {
return nil, err
}
return &Table{
tx: tx,
Store: s,
name: name,
infoStore: tx.tableInfoStore,
}, nil
}
func (tx *Transaction) AddField(name string, fc FieldConstraint) error {
return tx.tableInfoStore.modifyTable(tx, name, func(info *TableInfo) error {
for _, field := range info.FieldConstraints {
if field.Path.IsEqual(fc.Path) {
return fmt.Errorf("field %q already exists", fc.Path.String())
}
if field.IsPrimaryKey && fc.IsPrimaryKey {
return fmt.Errorf(
"multiple primary keys are not allowed (%q is primary key)",
field.Path.String(),
)
}
}
info.FieldConstraints = append(info.FieldConstraints, fc)
return nil
})
}
// RenameTable renames a table.
// If it doesn't exist, it returns ErrTableNotFound.
func (tx *Transaction) RenameTable(oldName, newName string) error {
ti, err := tx.tableInfoStore.Get(tx, oldName)
if err != nil {
return err
}
if ti.readOnly {
return errors.New("cannot write to read-only table")
}
ti.tableName = newName
// Insert the TableInfo keyed by the newName name.
err = tx.tableInfoStore.Insert(tx, newName, ti)
if err != nil {
return err
}
// Update the indexes.
idxs, err := tx.ListIndexes()
if err != nil {
return err
}
for _, idx := range idxs {
if idx.TableName == oldName {
idx.TableName = newName
err = tx.indexStore.Replace(idx.IndexName, *idx)
if err != nil {
return err
}
}
}
// Delete the old reference from the tableInfoStore.
return tx.tableInfoStore.Delete(tx, oldName)
}
// DropTable deletes a table from the database.
func (tx *Transaction) DropTable(name string) error {
ti, err := tx.tableInfoStore.Get(tx, name)
if err != nil {
return err
}
if ti.readOnly {
return errors.New("cannot write to read-only table")
}
it := tx.indexStore.st.Iterator(engine.IteratorOptions{})
defer it.Close()
var buf []byte
for it.Seek(nil); it.Valid(); it.Next() {
item := it.Item()
buf, err = item.ValueCopy(buf)
if err != nil {
return err
}
var opts IndexConfig
err = opts.ScanDocument(tx.db.Codec.NewDocument(buf))
if err != nil {
return err
}
// Remove only indexes associated with the target table.
if opts.TableName != name {
continue
}
err = tx.DropIndex(opts.IndexName)
if err != nil {
return err
}
}
if err := it.Err(); err != nil {
return err
}
err = tx.tableInfoStore.Delete(tx, name)
if err != nil {
return err
}
return tx.tx.DropStore(ti.storeName)
}
// CreateIndex creates an index with the given name.
// If it already exists, returns ErrIndexAlreadyExists.
func (tx *Transaction) CreateIndex(opts IndexConfig) error {
t, err := tx.GetTable(opts.TableName)
if err != nil {
return err
}
info, err := t.Info()
if err != nil {
return err
}
// if the index is created on a field on which we know the type,
// create a typed index.
for _, fc := range info.FieldConstraints {
if fc.Path.IsEqual(opts.Path) {
if fc.Type != 0 {
opts.Type = fc.Type
}
break
}
}
return tx.indexStore.Insert(opts)
}
// GetIndex returns an index by name.
func (tx *Transaction) GetIndex(name string) (*Index, error) {
opts, err := tx.indexStore.Get(name)
if err != nil {
return nil, err
}
idx := index.NewIndex(tx.tx, opts.IndexName, index.Options{
Unique: opts.Unique,
Type: opts.Type,
})
return &Index{
Index: idx,
Opts: *opts,
}, nil
}
// DropIndex deletes an index from the database.
func (tx *Transaction) DropIndex(name string) error {
opts, err := tx.indexStore.Get(name)
if err != nil {
return err
}
err = tx.indexStore.Delete(name)
if err != nil {
return err
}
idx := index.NewIndex(tx.tx, opts.IndexName, index.Options{
Unique: opts.Unique,
Type: opts.Type,
})
return idx.Truncate()
}
// ListIndexes lists all indexes.
func (tx *Transaction) ListIndexes() ([]*IndexConfig, error) {
return tx.indexStore.ListAll()
}
// ReIndex truncates and recreates selected index from scratch.
func (tx *Transaction) ReIndex(indexName string) error {
idx, err := tx.GetIndex(indexName)
if err != nil {
return err
}
tb, err := tx.GetTable(idx.Opts.TableName)
if err != nil {
return err
}
err = idx.Truncate()
if err != nil {
return err
}
return tb.Iterate(func(d document.Document) error {
v, err := idx.Opts.Path.GetValue(d)
if err == document.ErrFieldNotFound {
return nil
}
if err != nil {
return err
}
return idx.Set(v, d.(document.Keyer).Key())
})
}
// allIndexNames returns a list of all index names in index store.
func (tx *Transaction) allIndexNames() ([]string, error) {
it := tx.indexStore.st.Iterator(engine.IteratorOptions{})
defer it.Close()
var indexes []string
for it.Seek(nil); it.Valid(); it.Next() {
indexes = append(indexes, string(it.Item().Key()))
}
if err := it.Err(); err != nil {
return nil, err
}
return indexes, nil
}
// ReIndexAll truncates and recreates all indexes of the database from scratch.
func (tx *Transaction) ReIndexAll() error {
indexes, err := tx.allIndexNames()
if err != nil {
return err
}
for _, indexName := range indexes {
err := tx.ReIndex(indexName)
if err != nil {
return err
}
}
return nil
}
func (tx *Transaction) getIndexStore() (*indexStore, error) {
st, err := tx.tx.GetStore([]byte(indexStoreName))
if err != nil {
return nil, err
}
return &indexStore{
st: st,
db: tx.db,
}, nil
}