liveBook · Manning

Database transaction

As explained in Build and Orchestrator in Go (From Scratch)

A database transaction is an operation context that provides a consistent view of database data while applying reads or writes.

A database transaction is an operation context that provides a consistent view of data while applying reads or writes. BoltDB supplies read-only and read-write transactions through callback-based View and Update operations. section 11.9

A persistent task store uses transactions to:

  • Count tasks by opening a read-only transaction, selecting the tasks bucket, and iterating over its keys. section 11.9
  • Read individual tasks or list all tasks inside read-only transactions, decoding stored JSON values. section 11.9
  • Create buckets and store task values inside read-write transactions. section 11.9

Counting tasks

Count calls Db.View with a transaction callback, obtains the tasks bucket, increments a counter for each key, checks the returned error, and returns the count. section 11.9

func (t *TaskStore) Count() (int, error) {
    taskCount := 0
    err := t.Db.View(func(tx *bolt.Tx) error {    #1
        b := tx.Bucket([]byte("tasks"))           #2
        b.ForEach(func(k, v []byte) error {       #3
            taskCount++                           #4
            return nil
        })
        return nil
    })
    if err != nil {                               #5
        return -1, err
    }
 
    return taskCount, nil                         #6
}

Inspect the minimal read-only transaction used to count records in a persistent bucket. section 11.9

How Build and Orchestrator in Go (From Scratch) covers it

How deep it goes
Explains transaction types, callback APIs, bucket access, iteration, error handling, and read-write operations through store methods.
Examples
Demonstrates task counting, retrieval, listing, bucket creation, and JSON-backed insertion in a persistent task store.
What it assumes
Assumes familiarity with a store interface, persistent files, buckets, and basic Go callbacks.
What you can do after
Apply it via BoltDB to implement consistent reads and writes for a persistent task store.
How it connects
Connects transactions with persistent storage, key-value buckets, read-only transactions, read-write transactions, and relational databases.

Also explained in

Compare how 14 books explain database transaction →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build and Orchestrator in Go (From Scratch). The section links point to the parts of the book it draws on.