gpabun

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jan 18, 2026 License: MIT Imports: 17 Imported by: 1

README

GPABun

A Bun adapter for the Go Persistence API (GPA), providing a type-safe database abstraction layer with support for PostgreSQL, MySQL, and SQLite.

Features

  • Type-safe repositories with Go generics
  • Multi-database support (PostgreSQL, MySQL, SQLite)
  • Transaction support with savepoints
  • Connection pooling configuration
  • Query hooks for debugging and logging
  • Comprehensive error handling with typed errors

Installation

go get github.com/lemmego/gpabun

Quick Start

package main

import (
    "context"
    "log"
    
    "github.com/lemmego/gpa"
    "github.com/lemmego/gpabun"
)

type User struct {
    ID   int64  `bun:"id,pk,autoincrement"`
    Name string `bun:"name"`
}

func main() {
    // Configure database connection
    config := gpa.Config{
        Driver:   "postgres",
        Host:     "localhost",
        Port:     5432,
        Database: "myapp",
        Username: "user",
        Password: "password",
    }
    
    // Create provider
    provider, err := gpabun.NewProvider(config)
    if err != nil {
        log.Fatal(err)
    }
    defer provider.Close()
    
    // Get type-safe repository
    userRepo := gpabun.GetRepository[User](provider)
    
    // Use the repository
    user := &User{Name: "John Doe"}
    err = userRepo.Create(context.Background(), user)
    if err != nil {
        log.Fatal(err)
    }
}

Supported Databases

  • PostgreSQL (postgres, postgresql)
  • MySQL (mysql)
  • SQLite (sqlite, sqlite3)

Configuration

config := gpa.Config{
    Driver:           "postgres",
    Host:            "localhost",
    Port:            5432,
    Database:        "myapp",
    Username:        "user",
    Password:        "password",
    MaxOpenConns:    25,
    MaxIdleConns:    5,
    ConnMaxLifetime: time.Hour,
    ConnMaxIdleTime: time.Minute * 5,
    Options: map[string]interface{}{
        "bun": map[string]interface{}{
            "log_level": "debug", // Enable query logging
        },
    },
}

Repository Operations

// Create
user := &User{Name: "Alice"}
err := userRepo.Create(ctx, user)

// Find by ID
user, err := userRepo.FindByID(ctx, 1)

// Find all
users, err := userRepo.FindAll(ctx)

// Update
user.Name = "Alice Updated"
err = userRepo.Update(ctx, user)

// Delete
err = userRepo.Delete(ctx, 1)

// Count
count, err := userRepo.Count(ctx)

// Transactions
err = userRepo.Transaction(ctx, func(tx gpa.Transaction[User]) error {
    // Perform multiple operations within transaction
    return nil
})

Raw Queries

// Raw query
users, err := userRepo.RawQuery(ctx, "SELECT * FROM users WHERE age > ?", []interface{}{18})

// Raw execution
result, err := userRepo.RawExec(ctx, "UPDATE users SET active = ? WHERE id = ?", []interface{}{true, 1})

Error Handling

GPABun provides typed errors for common database scenarios:

user, err := userRepo.FindByID(ctx, 999)
if err != nil {
    var gpaErr gpa.GPAError
    if errors.As(err, &gpaErr) {
        switch gpaErr.Type {
        case gpa.ErrorTypeNotFound:
            // Handle not found
        case gpa.ErrorTypeDuplicate:
            // Handle duplicate key
        case gpa.ErrorTypeConstraint:
            // Handle constraint violation
        }
    }
}

License

MIT License - see LICENSE.md for details.

Documentation

Overview

Package gpabun provides a Bun adapter for the Go Persistence API (GPA)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetRepository

func GetRepository[T any](p *Provider) gpa.SQLRepository[T]

GetRepository returns a type-safe repository for any entity type T This enables the unified provider API: userRepo := gpabun.GetRepository[User](provider)

Types

type Provider

type Provider struct {
	// contains filtered or unexported fields
}

Provider implements gpa.Provider and gpa.SQLProvider using Bun

func NewProvider

func NewProvider(config gpa.Config) (*Provider, error)

NewProvider creates a new Bun provider instance

func (*Provider) BeginTx added in v0.1.1

func (p *Provider) BeginTx(ctx context.Context, opts *gpa.TxOptions) (interface{}, error)

BeginTx starts a transaction with specific isolation level

func (*Provider) Close

func (p *Provider) Close() error

Close closes the database connection

func (*Provider) Configure

func (p *Provider) Configure(config gpa.Config) error

Configure applies configuration changes

func (*Provider) DB added in v0.1.1

func (p *Provider) DB() interface{}

DB returns the underlying database/sql.DB instance

func (*Provider) Health

func (p *Provider) Health() error

Health checks the database connection health

func (*Provider) Migrate added in v0.1.1

func (p *Provider) Migrate(models ...interface{}) error

Migrate runs database migrations

func (*Provider) ProviderInfo

func (p *Provider) ProviderInfo() gpa.ProviderInfo

ProviderInfo returns information about this provider

func (*Provider) RawExec added in v0.1.1

func (p *Provider) RawExec(ctx context.Context, query string, args ...interface{}) (gpa.Result, error)

RawExec executes raw SQL without returning results

func (*Provider) RawQuery added in v0.1.1

func (p *Provider) RawQuery(ctx context.Context, query string, args ...interface{}) (interface{}, error)

RawQuery executes raw SQL and returns results

func (*Provider) SupportedFeatures

func (p *Provider) SupportedFeatures() []gpa.Feature

SupportedFeatures returns the list of supported features

type Repository

type Repository[T any] struct {
	// contains filtered or unexported fields
}

Repository implements gpa.Repository[T] using Bun

func (*Repository[T]) Close

func (r *Repository[T]) Close() error

Close closes the repository

func (*Repository[T]) Count

func (r *Repository[T]) Count(ctx context.Context, opts ...gpa.QueryOption) (int64, error)

Count returns the number of entities matching the query options

func (*Repository[T]) Create

func (r *Repository[T]) Create(ctx context.Context, entity *T) error

Create inserts a new entity

func (*Repository[T]) CreateBatch

func (r *Repository[T]) CreateBatch(ctx context.Context, entities []*T) error

CreateBatch inserts multiple entities

func (*Repository[T]) Delete

func (r *Repository[T]) Delete(ctx context.Context, id interface{}) error

Delete removes an entity by ID

func (*Repository[T]) DeleteByCondition

func (r *Repository[T]) DeleteByCondition(ctx context.Context, condition gpa.Condition) error

DeleteByCondition removes entities matching the condition

func (*Repository[T]) Exists

func (r *Repository[T]) Exists(ctx context.Context, opts ...gpa.QueryOption) (bool, error)

Exists checks if any entities match the query options

func (*Repository[T]) FindAll

func (r *Repository[T]) FindAll(ctx context.Context, opts ...gpa.QueryOption) ([]*T, error)

FindAll retrieves all entities

func (*Repository[T]) FindByID

func (r *Repository[T]) FindByID(ctx context.Context, id interface{}) (*T, error)

FindByID retrieves a single entity by ID

func (*Repository[T]) GetEntityInfo

func (r *Repository[T]) GetEntityInfo() (*gpa.EntityInfo, error)

GetEntityInfo returns metadata about the entity

func (*Repository[T]) Query

func (r *Repository[T]) Query(ctx context.Context, opts ...gpa.QueryOption) ([]*T, error)

Query retrieves entities based on query options

func (*Repository[T]) QueryOne

func (r *Repository[T]) QueryOne(ctx context.Context, opts ...gpa.QueryOption) (*T, error)

QueryOne retrieves a single entity based on query options

func (*Repository[T]) RawExec

func (r *Repository[T]) RawExec(ctx context.Context, query string, args []interface{}) (gpa.Result, error)

RawExec executes a raw command

func (*Repository[T]) RawQuery

func (r *Repository[T]) RawQuery(ctx context.Context, query string, args []interface{}) ([]*T, error)

RawQuery executes a raw query and returns results

func (*Repository[T]) Transaction

func (r *Repository[T]) Transaction(ctx context.Context, fn gpa.TransactionFunc[T]) error

Transaction executes a function within a transaction

func (*Repository[T]) Update

func (r *Repository[T]) Update(ctx context.Context, entity *T) error

Update modifies an existing entity

func (*Repository[T]) UpdatePartial

func (r *Repository[T]) UpdatePartial(ctx context.Context, id interface{}, updates map[string]interface{}) error

UpdatePartial modifies specific fields of an entity

type Result

type Result struct {
	// contains filtered or unexported fields
}

Result implements gpa.Result

func (*Result) LastInsertId

func (r *Result) LastInsertId() (int64, error)

LastInsertId returns the last insert ID

func (*Result) RowsAffected

func (r *Result) RowsAffected() (int64, error)

RowsAffected returns the number of affected rows

type Transaction

type Transaction[T any] struct {
	*Repository[T]
}

Transaction implements gpa.Transaction[T]

func (*Transaction[T]) Commit

func (t *Transaction[T]) Commit() error

Commit commits the transaction

func (*Transaction[T]) Rollback

func (t *Transaction[T]) Rollback() error

Rollback rolls back the transaction

func (*Transaction[T]) RollbackToSavepoint

func (t *Transaction[T]) RollbackToSavepoint(name string) error

RollbackToSavepoint rolls back to a savepoint

func (*Transaction[T]) SetSavepoint

func (t *Transaction[T]) SetSavepoint(name string) error

SetSavepoint creates a savepoint

Jump to

Keyboard shortcuts

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