Debian Codegraph @

lmdb/txn.go

raw symbols SCIP
1 package lmdb
2
3 /*
4 #include <stdlib.h>
5 #include <stdio.h>
6 #include "lmdb.h"
7 #include "lmdbgo.h"
8 */
9 import "C"
10
11 import (
12 "log"
13 "runtime"
14 "unsafe"
15 )
16
17 // This flags are used exclusively for Txn.OpenDBI and Txn.OpenRoot. The
18 // Create flag must always be supplied when opening a non-root DBI for the
19 // first time.
20 //
21 // BUG(bmatsuo):
22 // MDB_INTEGERKEY and MDB_INTEGERDUP aren't usable. I'm not sure they would be
23 // faster with the cgo bridge. They need to be tested and benchmarked.
24 const (
25 // Flags for Txn.OpenDBI.
26
27 ReverseKey = C.MDB_REVERSEKEY // Use reverse string keys.
28 DupSort = C.MDB_DUPSORT // Use sorted duplicates.
29 DupFixed = C.MDB_DUPFIXED // Duplicate items have a fixed size (DupSort).
30 ReverseDup = C.MDB_REVERSEDUP // Reverse duplicate values (DupSort).
31 Create = C.MDB_CREATE // Create DB if not already existing.
32 )
33
34 // Txn is a database transaction in an environment.
35 //
36 // WARNING: A writable Txn is not threadsafe and may only be used in the
37 // goroutine that created it.
38 //
39 // See MDB_txn.
40 type Txn struct {
41 // If RawRead is true []byte values retrieved from Get() calls on the Txn
42 // and its cursors will point directly into the memory-mapped structure.
43 // Such slices will be readonly and must only be referenced wthin the
44 // transaction's lifetime.
45 RawRead bool
46
47 // Pooled may be set to true while a Txn is stored in a sync.Pool, after
48 // Txn.Reset reset has been called and before Txn.Renew. This will keep
49 // the Txn finalizer from unnecessarily warning the application about
50 // finalizations.
51 Pooled bool
52
53 managed bool
54 readonly bool
55
56 // The value of Txn.ID() is cached so that the cost of cgo does not have to
57 // be paid. The id of a Txn cannot change over its life, even if it is
58 // reset/renewed
59 id uintptr
60
61 env *Env
62 _txn *C.MDB_txn
63 key *C.MDB_val
64 val *C.MDB_val
65
66 errLogf func(format string, v ...interface{})
67 }
68
69 // beginTxn does not lock the OS thread which is a prerequisite for creating a
70 // write transaction.
71 func beginTxn(env *Env, parent *Txn, flags uint) (*Txn, error) {
72 txn := &Txn{
73 readonly: (flags&Readonly != 0),
74 env: env,
75 }
76
77 var ptxn *C.MDB_txn
78 if parent == nil {
79 if flags&Readonly == 0 {
80 // In a write Txn we can use the shared, C-allocated key and value
81 // allocated by env, and freed when it is closed.
82 txn.key = env.ckey
83 txn.val = env.cval
84 } else {
85 // It is not easy to share C.MDB_val values in this scenario unless
86 // there is a synchronized pool involved, which will increase
87 // overhead. Further, allocating these values with C will add
88 // overhead both here and when the values are freed.
89 txn.key = new(C.MDB_val)
90 txn.val = new(C.MDB_val)
91 }
92 } else {
93 // Because parent Txn objects cannot be used while a sub-Txn is active
94 // it is OK for them to share their C.MDB_val objects.
95 ptxn = parent._txn
96 txn.key = parent.key
97 txn.val = parent.val
98 }
99 ret := C.mdb_txn_begin(env._env, ptxn, C.uint(flags), &txn._txn)
100 if ret != success {
101 return nil, operrno("mdb_txn_begin", ret)
102 }
103 return txn, nil
104 }
105
106 // ID returns the identifier for txn. A view transaction identifier
107 // corresponds to the Env snapshot being viewed and may be shared with other
108 // view transactions.
109 //
110 // See mdb_txn_id.
111 func (txn *Txn) ID() uintptr {
112 // It is possible for a txn to legitimately have ID 0 if it a readonly txn
113 // created before any updates. In practice this does not really happen
114 // because an application typically must do an initial update to initialize
115 // application dbis. Even so, calling C.mdb_txn_id excessively isn't
116 // actually harmful, it is just slow.
117 if txn.id == 0 {
118 txn.id = txn.getID()
119 }
120
121 return txn.id
122 }
123
124 func (txn *Txn) getID() uintptr {
125 return uintptr(C.mdb_txn_id(txn._txn))
126 }
127
128 // RunOp executes fn with txn as an argument. During the execution of fn no
129 // goroutine may call the Commit, Abort, Reset, and Renew methods on txn.
130 // RunOp returns the result of fn without any further action. RunOp will not
131 // abort txn if fn returns an error, unless terminate is true. If terminate is
132 // true then RunOp will attempt to commit txn if fn is successful, otherwise
133 // RunOp will abort txn before returning any failure encountered.
134 //
135 // RunOp primarily exists to allow applications and other packages to provide
136 // variants of the managed transactions provided by lmdb (i.e. View, Update,
137 // etc). For example, the lmdbpool package uses RunOp to provide an
138 // Txn-friendly sync.Pool and a function analogous to Env.View that uses
139 // transactions from that pool.
140 func (txn *Txn) RunOp(fn TxnOp, terminate bool) error {
141 if terminate {
142 return txn.runOpTerm(fn)
143 }
144 return txn.runOp(fn)
145 }
146
147 func (txn *Txn) runOpTerm(fn TxnOp) error {
148 if txn.managed {
149 panic("managed transaction cannot be terminated directly")
150 }
151 defer txn.abort()
152
153 // There is no need to restore txn.managed after fn has executed because
154 // the Txn will terminate one way or another using methods which don't
155 // check txn.managed.
156 txn.managed = true
157
158 err := fn(txn)
159 if err != nil {
160 return err
161 }
162
163 return txn.commit()
164 }
165
166 func (txn *Txn) runOp(fn TxnOp) error {
167 if !txn.managed {
168 // Restoring txn.managed must be done in a deferred call otherwise the
169 // caller may not be able to abort the transaction if a runtime panic
170 // occurs (attempting to do so would cause another panic).
171 txn.managed = true
172 defer func() {
173 txn.managed = false
174 }()
175 }
176 return fn(txn)
177 }
178
179 // Commit persists all transaction operations to the database and clears the
180 // finalizer on txn. A Txn cannot be used again after Commit is called.
181 //
182 // See mdb_txn_commit.
183 func (txn *Txn) Commit() error {
184 if txn.managed {
185 panic("managed transaction cannot be committed directly")
186 }
187
188 runtime.SetFinalizer(txn, nil)
189 return txn.commit()
190 }
191
192 func (txn *Txn) commit() error {
193 ret := C.mdb_txn_commit(txn._txn)
194 txn.clearTxn()
195 return operrno("mdb_txn_commit", ret)
196 }
197
198 // Abort discards pending writes in the transaction and clears the finalizer on
199 // txn. A Txn cannot be used again after Abort is called.
200 //
201 // See mdb_txn_abort.
202 func (txn *Txn) Abort() {
203 if txn.managed {
204 panic("managed transaction cannot be aborted directly")
205 }
206
207 runtime.SetFinalizer(txn, nil)
208 txn.abort()
209 }
210
211 func (txn *Txn) abort() {
212 if txn._txn == nil {
213 return
214 }
215
216 // Get a read-lock on the environment so we can abort txn if needed.
217 // txn.env **should** terminate all readers otherwise when it closes.
218 txn.env.closeLock.RLock()
219 if txn.env._env != nil {
220 C.mdb_txn_abort(txn._txn)
221 }
222 txn.env.closeLock.RUnlock()
223
224 txn.clearTxn()
225 }
226
227 func (txn *Txn) clearTxn() {
228 // Clear the C object to prevent any potential future use of the freed
229 // pointer.
230 txn._txn = nil
231
232 // Clear txn.id because it no longer matches the value of txn._txn (and
233 // future calls to txn.ID() should not see the stale id). Instead of
234 // returning the old ID future calls to txn.ID() will query LMDB to make
235 // sure the value returned for an invalid Txn is more or less consistent
236 // for people familiar with the C semantics.
237 txn.resetID()
238 }
239
240 // resetID has to be called anytime the value of Txn.getID() may change
241 // otherwise the cached value may diverge from the actual value and the
242 // abstraction has failed.
243 func (txn *Txn) resetID() {
244 txn.id = 0
245 }
246
247 // Reset aborts the transaction clears internal state so the transaction may be
248 // reused by calling Renew. If txn is not going to be reused txn.Abort() must
249 // be called to release its slot in the lock table and free its memory. Reset
250 // panics if txn is managed by Update, View, etc.
251 //
252 // See mdb_txn_reset.
253 func (txn *Txn) Reset() {
254 if txn.managed {
255 panic("managed transaction cannot be reset directly")
256 }
257
258 txn.reset()
259 }
260
261 func (txn *Txn) reset() {
262 C.mdb_txn_reset(txn._txn)
263 }
264
265 // Renew reuses a transaction that was previously reset by calling txn.Reset().
266 // Renew panics if txn is managed by Update, View, etc.
267 //
268 // See mdb_txn_renew.
269 func (txn *Txn) Renew() error {
270 if txn.managed {
271 panic("managed transaction cannot be renewed directly")
272 }
273
274 return txn.renew()
275 }
276
277 func (txn *Txn) renew() error {
278 ret := C.mdb_txn_renew(txn._txn)
279
280 // mdb_txn_renew causes txn._txn to pick up a new transaction ID. It's
281 // slightly confusing in the LMDB docs. Txn ID corresponds to database
282 // snapshot the reader is holding, which is good because renewed
283 // transactions can see updates which happened since they were created (or
284 // since they were last renewed). It should follow that renewing a Txn
285 // results in the freeing of stale pages the Txn has been holding, though
286 // this has not been confirmed in any way by bmatsuo as of 2017-02-15.
287 txn.resetID()
288
289 return operrno("mdb_txn_renew", ret)
290 }
291
292 // OpenDBI opens a named database in the environment. An error is returned if
293 // name is empty. The DBI returned by OpenDBI can be used in other
294 // transactions but not before Txn has terminated.
295 //
296 // OpenDBI can only be called after env.SetMaxDBs() has been called to set the
297 // maximum number of named databases.
298 //
299 // The C API uses null terminated strings for database names. A consequence is
300 // that names cannot contain null bytes themselves. OpenDBI does not check for
301 // null bytes in the name argument.
302 //
303 // See mdb_dbi_open.
304 func (txn *Txn) OpenDBI(name string, flags uint) (DBI, error) {
305 cname := C.CString(name)
306 dbi, err := txn.openDBI(cname, flags)
307 C.free(unsafe.Pointer(cname))
308 return dbi, err
309 }
310
311 // CreateDBI is a shorthand for OpenDBI that passed the flag lmdb.Create.
312 func (txn *Txn) CreateDBI(name string) (DBI, error) {
313 return txn.OpenDBI(name, Create)
314 }
315
316 // Flags returns the database flags for handle dbi.
317 func (txn *Txn) Flags(dbi DBI) (uint, error) {
318 var cflags C.uint
319 ret := C.mdb_dbi_flags(txn._txn, C.MDB_dbi(dbi), (*C.uint)(&cflags))
320 return uint(cflags), operrno("mdb_dbi_flags", ret)
321 }
322
323 // OpenRoot opens the root database. OpenRoot behaves similarly to OpenDBI but
324 // does not require env.SetMaxDBs() to be called beforehand. And, OpenRoot can
325 // be called without flags in a View transaction.
326 func (txn *Txn) OpenRoot(flags uint) (DBI, error) {
327 return txn.openDBI(nil, flags)
328 }
329
330 // openDBI returns returns whatever DBI value was set by mdb_open_dbi. In an
331 // error case, LMDB does not currently set DBI in case of failure, so zero is
332 // returned in those cases. This is not a big deal for now because
333 // applications are expected to handle any error encountered opening a
334 // database.
335 func (txn *Txn) openDBI(cname *C.char, flags uint) (DBI, error) {
336 var dbi C.MDB_dbi
337 ret := C.mdb_dbi_open(txn._txn, cname, C.uint(flags), &dbi)
338 return DBI(dbi), operrno("mdb_dbi_open", ret)
339 }
340
341 // Stat returns a Stat describing the database dbi.
342 //
343 // See mdb_stat.
344 func (txn *Txn) Stat(dbi DBI) (*Stat, error) {
345 var _stat C.MDB_stat
346 ret := C.mdb_stat(txn._txn, C.MDB_dbi(dbi), &_stat)
347 if ret != success {
348 return nil, operrno("mdb_stat", ret)
349 }
350 stat := Stat{PSize: uint(_stat.ms_psize),
351 Depth: uint(_stat.ms_depth),
352 BranchPages: uint64(_stat.ms_branch_pages),
353 LeafPages: uint64(_stat.ms_leaf_pages),
354 OverflowPages: uint64(_stat.ms_overflow_pages),
355 Entries: uint64(_stat.ms_entries)}
356 return &stat, nil
357 }
358
359 // Drop empties the database if del is false. Drop deletes and closes the
360 // database if del is true.
361 //
362 // See mdb_drop.
363 func (txn *Txn) Drop(dbi DBI, del bool) error {
364 ret := C.mdb_drop(txn._txn, C.MDB_dbi(dbi), cbool(del))
365 return operrno("mdb_drop", ret)
366 }
367
368 // Sub executes fn in a subtransaction. Sub commits the subtransaction iff a
369 // nil error is returned by fn and otherwise aborts it. Sub returns any error
370 // it encounters.
371 //
372 // Sub may only be called on an Update Txn (one created without the Readonly
373 // flag). Calling Sub on a View transaction will return an error. Sub assumes
374 // the calling goroutine is locked to an OS thread and will not call
375 // runtime.LockOSThread.
376 //
377 // Any call to Abort, Commit, Renew, or Reset on a Txn created by Sub will
378 // panic.
379 func (txn *Txn) Sub(fn TxnOp) error {
380 // As of 0.9.14 Readonly is the only Txn flag and readonly subtransactions
381 // don't make sense.
382 return txn.subFlag(0, fn)
383 }
384
385 func (txn *Txn) subFlag(flags uint, fn TxnOp) error {
386 sub, err := beginTxn(txn.env, txn, flags)
387 if err != nil {
388 return err
389 }
390 sub.managed = true
391 defer sub.abort()
392 err = fn(sub)
393 if err != nil {
394 return err
395 }
396 return sub.commit()
397 }
398
399 func (txn *Txn) bytes(val *C.MDB_val) []byte {
400 if txn.RawRead {
401 return getBytes(val)
402 }
403 return getBytesCopy(val)
404 }
405
406 // Get retrieves items from database dbi. If txn.RawRead is true the slice
407 // returned by Get references a readonly section of memory that must not be
408 // accessed after txn has terminated.
409 //
410 // See mdb_get.
411 func (txn *Txn) Get(dbi DBI, key []byte) ([]byte, error) {
412 kdata, kn := valBytes(key)
413 ret := C.lmdbgo_mdb_get(
414 txn._txn, C.MDB_dbi(dbi),
415 (*C.char)(unsafe.Pointer(&kdata[0])), C.size_t(kn),
416 txn.val,
417 )
418 err := operrno("mdb_get", ret)
419 if err != nil {
420 *txn.val = C.MDB_val{}
421 return nil, err
422 }
423 b := txn.bytes(txn.val)
424 *txn.val = C.MDB_val{}
425 return b, nil
426 }
427
428 func (txn *Txn) putNilKey(dbi DBI, flags uint) error {
429 // mdb_put with an empty key will always fail
430 ret := C.lmdbgo_mdb_put2(txn._txn, C.MDB_dbi(dbi), nil, 0, nil, 0, C.uint(flags))
431 return operrno("mdb_put", ret)
432 }
433
434 // Put stores an item in database dbi.
435 //
436 // See mdb_put.
437 func (txn *Txn) Put(dbi DBI, key []byte, val []byte, flags uint) error {
438 kn := len(key)
439 if kn == 0 {
440 return txn.putNilKey(dbi, flags)
441 }
442 vn := len(val)
443 if vn == 0 {
444 val = []byte{0}
445 }
446
447 ret := C.lmdbgo_mdb_put2(
448 txn._txn, C.MDB_dbi(dbi),
449 (*C.char)(unsafe.Pointer(&key[0])), C.size_t(kn),
450 (*C.char)(unsafe.Pointer(&val[0])), C.size_t(vn),
451 C.uint(flags),
452 )
453 return operrno("mdb_put", ret)
454 }
455
456 // PutReserve returns a []byte of length n that can be written to, potentially
457 // avoiding a memcopy. The returned byte slice is only valid in txn's thread,
458 // before it has terminated.
459 func (txn *Txn) PutReserve(dbi DBI, key []byte, n int, flags uint) ([]byte, error) {
460 if len(key) == 0 {
461 return nil, txn.putNilKey(dbi, flags)
462 }
463 txn.val.mv_size = C.size_t(n)
464 ret := C.lmdbgo_mdb_put1(
465 txn._txn, C.MDB_dbi(dbi),
466 (*C.char)(unsafe.Pointer(&key[0])), C.size_t(len(key)),
467 txn.val,
468 C.uint(flags|C.MDB_RESERVE),
469 )
470 err := operrno("mdb_put", ret)
471 if err != nil {
472 *txn.val = C.MDB_val{}
473 return nil, err
474 }
475 b := getBytes(txn.val)
476 *txn.val = C.MDB_val{}
477 return b, nil
478 }
479
480 // Del deletes an item from database dbi. Del ignores val unless dbi has the
481 // DupSort flag.
482 //
483 // See mdb_del.
484 func (txn *Txn) Del(dbi DBI, key, val []byte) error {
485 kdata, kn := valBytes(key)
486 vdata, vn := valBytes(val)
487 ret := C.lmdbgo_mdb_del(
488 txn._txn, C.MDB_dbi(dbi),
489 (*C.char)(unsafe.Pointer(&kdata[0])), C.size_t(kn),
490 (*C.char)(unsafe.Pointer(&vdata[0])), C.size_t(vn),
491 )
492 return operrno("mdb_del", ret)
493 }
494
495 // OpenCursor allocates and initializes a Cursor to database dbi.
496 //
497 // See mdb_cursor_open.
498 func (txn *Txn) OpenCursor(dbi DBI) (*Cursor, error) {
499 cur, err := openCursor(txn, dbi)
500 if cur != nil && txn.readonly {
501 runtime.SetFinalizer(cur, (*Cursor).close)
502 }
503 return cur, err
504 }
505
506 func (txn *Txn) errf(format string, v ...interface{}) {
507 if txn.errLogf != nil {
508 txn.errLogf(format, v...)
509 return
510 }
511 log.Printf(format, v...)
512 }
513
514 func (txn *Txn) finalize() {
515 if txn._txn != nil {
516 if !txn.Pooled {
517 txn.errf("lmdb: aborting unreachable transaction %#x", uintptr(unsafe.Pointer(txn)))
518 }
519
520 txn.abort()
521 }
522 }
523
524 // TxnOp is an operation applied to a managed transaction. The Txn passed to a
525 // TxnOp is managed and the operation must not call Commit, Abort, Renew, or
526 // Reset on it.
527 //
528 // IMPORTANT:
529 // TxnOps that write to the database (those passed to Env.Update or Txn.Sub)
530 // must not use the Txn in another goroutine (passing it directly or otherwise
531 // through closure). Doing so has undefined results.
532 type TxnOp func(txn *Txn) error