dbapi

package module
v0.1.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 15, 2025 License: MIT Imports: 2 Imported by: 0

README

DBAPI - BadgerDB Wrapper Library

A simple and efficient wrapper around BadgerDB providing a clean API for basic key-value store operations.

Features

  • Simple Interface: Clean API for common database operations
  • Type-Safe: Strong typing with Go's type system
  • Error Handling: Consistent error handling with meaningful error messages
  • Transaction Support: Built-in transaction handling for all operations
  • Full Iterator Support: Easy iteration over all key-value pairs

Installation

go get github.com/HashemJaafar7/dbapi

Quick Start

package main

import (
    "fmt"
    "github.com/HashemJaafar7/dbapi"
)

func main() {
    // Open database
    var db dbapi.DB
    err := dbapi.Open(&db, "./my-db")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    // Add a key-value pair
    err = dbapi.Add(db, []byte("key1"), []byte("value1"))
    if err != nil {
        panic(err)
    }

    // Get a value
    value, err := dbapi.Get(db, []byte("key1"))
    if err != nil {
        panic(err)
    }
    fmt.Printf("Value: %s\n", value)
}

API Reference

Open Database
func Open(db *DB, path string) error

Opens or creates a database at the specified path.

Add Key-Value Pair
func Add(db DB, key []byte, value []byte) error

Adds a new key-value pair. Returns error if key already exists.

Update Value
func Update(db DB, key []byte, value []byte) error

Updates the value for an existing key.

Get Value
func Get(db DB, key []byte) ([]byte, error)

Retrieves the value associated with a key.

Delete Key-Value Pair
func Delete(db DB, key []byte) error

Removes a key-value pair from the database.

View All Entries
func View(db DB, function func(key, value []byte)) error

Iterates over all key-value pairs in the database.

Error Handling

The library defines two main error types:

  • ErrKeyIsUsed: Returned when attempting to add a key that already exists
  • ErrKeyNotFound: Returned when trying to access a non-existent key

Example error handling:

value, err := dbapi.Get(db, []byte("nonexistent"))
if err != nil {
    switch err.Error() {
    case dbapi.ErrKeyNotFound:
        fmt.Println("Key not found")
    default:
        fmt.Printf("Unknown error: %v\n", err)
    }
}

Best Practices

  1. Database Path: Use absolute paths when opening databases
  2. Resource Management: Always close the database when done
  3. Error Handling: Check errors returned from all operations
  4. Key Design: Use consistent key naming conventions
  5. Batch Operations: Use View for efficient batch reading

Examples

Iterating Over All Entries
err := dbapi.View(db, func(key, value []byte) {
    fmt.Printf("Key: %s, Value: %s\n", key, value)
})
if err != nil {
    panic(err)
}
Safe Key Addition
err := dbapi.Add(db, []byte("key"), []byte("value"))
if err != nil {
    if err.Error() == dbapi.ErrKeyIsUsed {
        // Handle duplicate key
    } else {
        // Handle other errors
    }
}
Update or Add Pattern
value := []byte("new value")
if err := dbapi.Update(db, key, value); err != nil {
    if err.Error() == dbapi.ErrKeyNotFound {
        err = dbapi.Add(db, key, value)
    }
    if err != nil {
        // Handle error
    }
}

Performance Considerations

  • The library uses BadgerDB's default options which are optimized for SSD

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

License

MIT

Documentation

Overview

Example
package main

import (
	"fmt"
	"log"

	"github.com/HashemJaafar7/dbapi"
)

func main() {
	// Initialize and open database
	var database dbapi.DB
	err := dbapi.Open(&database, "example_db")
	if err != nil {
		log.Fatal(err)
	}
	database.DropAll()
	defer database.Close()
	fmt.Println("1. Database opened successfully")

	// Add a new key-value pair
	err = dbapi.Add(database, []byte("name"), []byte("John"))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("2. Added key 'name' with value 'John'")

	// Try adding duplicate key
	err = dbapi.Add(database, []byte("name"), []byte("Jane"))
	fmt.Printf("3. Error adding duplicate: %v\n", err)

	// Add another value
	err = dbapi.Add(database, []byte("city"), []byte("London"))
	if err != nil {
		log.Fatal(err)
	}

	// Get the value
	value, err := dbapi.Get(database, []byte("city"))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("4. Got value for 'city': %s\n", value)

	// Try getting non-existent key
	_, err = dbapi.Get(database, []byte("country"))
	fmt.Printf("5. Error getting missing key: %v\n", err)

	// Update a value
	err = dbapi.Update(database, []byte("name"), []byte("Jane"))
	if err != nil {
		log.Fatal(err)
	}
	value, _ = dbapi.Get(database, []byte("name"))
	fmt.Printf("6. Updated name to: %s\n", value)

	// Delete a key
	err = dbapi.Delete(database, []byte("city"))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("7. Deleted 'city' key")

	// Try to get deleted value
	_, err = dbapi.Get(database, []byte("city"))
	fmt.Printf("8. Error getting deleted key: %v\n", err)

	// Add more data for viewing
	err = dbapi.Add(database, []byte("email"), []byte("jane@example.com"))
	if err != nil {
		log.Fatal(err)
	}

	// View all entries
	fmt.Println("9. All database entries:")
	err = dbapi.View(database, func(key, value []byte) {
		fmt.Printf("   %s: %s\n", key, value)
	})
	if err != nil {
		log.Fatal(err)
	}

}
Output:
1. Database opened successfully
2. Added key 'name' with value 'John'
3. Error adding duplicate: ErrKeyIsUsed : key [110 97 109 101] is used
4. Got value for 'city': London
5. Error getting missing key: ErrKeyNotFound : key [99 111 117 110 116 114 121] not found
6. Updated name to: Jane
7. Deleted 'city' key
8. Error getting deleted key: ErrKeyNotFound : key [99 105 116 121] not found
9. All database entries:
   email: jane@example.com
   name: Jane

Index

Examples

Constants

View Source
const (
	ErrKeyIsUsed   = "ErrKeyIsUsed"
	ErrKeyNotFound = "ErrKeyNotFound"
)

Variables

This section is empty.

Functions

func Add

func Add(db DB, key []byte, value []byte) error

Add inserts a key-value pair into the database if the key does not already exist. If the key is already in use, it returns an error indicating the key conflict.

Parameters:

  • db: The database instance implementing the DB interface.
  • key: The key to be added as a byte slice.
  • value: The value to be associated with the key as a byte slice.

Returns:

  • error: An error if the key already exists or if there is an issue during the update operation.

func Delete

func Delete(db DB, key []byte) error

Delete removes a key-value pair from the database. It takes a DB instance and a key as input parameters. The function performs a database update operation to delete the specified key. If the operation is successful, it returns nil; otherwise, it returns an error.

Parameters:

  • db: The database instance implementing the DB interface.
  • key: The key to be deleted, represented as a byte slice.

Returns:

  • error: An error if the delete operation fails, or nil if it succeeds.

if the key is not found, it returns nil.

func Get

func Get(db DB, key []byte) ([]byte, error)

Get retrieves the value associated with the given key from the provided database. It performs a read-only transaction to fetch the value.

Parameters:

  • db: The database instance implementing the DB interface.
  • key: A byte slice representing the key to look up.

Returns:

  • A byte slice containing the value associated with the key, or an error if the key is not found or if any other issue occurs during the transaction.

Errors:

  • Returns an error if the key is not found, with a message indicating the missing key.
  • Propagates any other errors encountered during the transaction.

func Open

func Open(db *DB, path string) error

Open initializes and opens a Badger database at the specified path. It takes a pointer to a DB instance and a string representing the database path. The function modifies the provided DB pointer to point to the opened database. Returns an error if the database fails to open.

Parameters:

  • db: A pointer to a DB instance that will be initialized and opened.
  • path: The file path where the Badger database is located.

Returns:

  • error: An error object if the database fails to open, otherwise nil.

func Update

func Update(db DB, key []byte, value []byte) error

Update updates the value associated with the given key in the database. It performs the update operation within a transaction.

Parameters:

  • db: The database instance implementing the DB interface.
  • key: The key for which the value needs to be updated.
  • value: The new value to be associated with the key.

Returns:

  • error: An error if the update operation fails, otherwise nil.

func View

func View(db DB, function func(key, value []byte)) error

View iterates over all key-value pairs in the provided BadgerDB instance and applies the given function to each pair. The function takes two arguments: the key and the value as byte slices.

Parameters:

  • db: The BadgerDB instance to perform the read-only transaction on.
  • function: A callback function that processes each key-value pair.

Returns:

  • error: An error if the transaction fails, or nil if successful.

Example usage:

err := View(db, func(key, value []byte) {
    fmt.Printf("Key: %s, Value: %s\n", key, value)
})
if err != nil {
    log.Fatalf("Error viewing database: %v", err)
}

Types

type DB

type DB = *badger.DB

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL