pkgdb

package module
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 10 Imported by: 0

README

⛁ Pkg DB

This library contains a test helper to set up a package-level database server using testcontainers, and provides a function to create databases within it for individual tests. This is an improvement over survivorbat/go-db-suite which relies on testify's suites and as a result makes tests run in sequentially. By using TestMain, tests can be run in parallel.

⬇️ Installation

go get github.com/survivorbat/go-pkg-db

📋 Usage

import (
 "context"
 "os"
 "testing"

 pkgdb "github.com/survivorbat/go-pkg-db"
)

var createDB pkgdb.CreateFunc

func TestMain(m *testing.M) {
  ctx, cancel := context.WithCancel(context.Background())

  // Setup the postgres server
  createFunc, teardown, err := pkgdb.SetupPostgres(ctx, "postgres:18-alpine", nil)
  if err != nil {
    panic(err)
  }

  // Set the creation func as a global, allowing tests to use it
  createDB = createFunc

  // Run the unit tests
  code := m.Run()

  // Cleanup
  err = teardown()
  if err != nil {
    panic(err)
  }

  cancel()

  // Exit the process with the test's code
  os.Exit(code)
}

🔭 Plans

  • More databases

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CreateFunc

type CreateFunc func(t *testing.T) *sql.DB

CreateFunc describes a function to create a fresh database for the test

func NewPostgresFactory

func NewPostgresFactory(rootDB *sql.DB, connectionURL *url.URL, callback func(*sql.DB)) CreateFunc

NewPostgresFactory creates a new db creation func to create databases for tests. The final callback may be added to apply operations on the database after its creation.

func SetupPostgres

func SetupPostgres(ctx context.Context, image string, callback func(*sql.DB)) (CreateFunc, func() error, error)

SetupPostgres will spin upo a postgres container using testcontainers and return a CreateFunc that can be used in tests to create fresh databases in the postgres container. The second argument is the cancellation function.

Jump to

Keyboard shortcuts

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