repo

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 12, 2025 License: MIT Imports: 7 Imported by: 0

README

repo

This module is mainly an exercise with generics. Although it is a fully functional repository for any Go structs.

Might be useful for pet-projects and like.

Example usage.

import (
    "code.uint32.ru/tiny/repo"
    _ "github.com/mattn/go-sqlite3"
)

type My struct {
	A string
	B int
}

func main() {
    db, err := sql.Open("sqlite3", "test.db")
    if err != nil {
		panic(err)
	}

    defer db.Close()

    ctx := context.Background()

    // init repository for our type "My"
    r, err := repo.OpenOrCreate[My](ctx, db, "my_test_table")
    if err != nil {
        panic(err)
    }

    first := &My{
		A: "hello",
		B: 42,
	}

	if err := r.Create(ctx, "first_record", first); err != nil {
		panic(err)
	}

    duplicate, err = r.Read(ctx, "first_record")
	if err != nil {
		panic(err)
	}

    fmt.Printf("Type: %T, Value: %+v", duplicate)
}

The interface is a plain CRUD.

type Repo[T any] interface {
	// Create inserts object into repository table. If id already exists
	// in the database it is an error.
	Create(ctx context.Context, id string, v *T) error
	// Read returns object with specified id or ErrNotFound
	Read(ctx context.Context, id string) (*T, error)
	// Update updates object with id.
	Update(ctx context.Context, id string, v *T) error
	// Delete deletes object with id.
	Delete(ctx context.Context, id string) error
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInitRepo  = errors.New("error creating table")
	ErrMarshal   = errors.New("error marshal")
	ErrExecQuery = errors.New("error executing DB query")
	ErrNotFound  = errors.New("not found")
)

Functions

This section is empty.

Types

type Repo

type Repo[T any] interface {
	// Create saves object to the repository. If id already exists
	// in the database it is an error.
	Create(ctx context.Context, id string, v *T) error
	// Read returns object with specified id or ErrNotFound
	Read(ctx context.Context, id string) (*T, error)
	// Update updates object with id.
	Update(ctx context.Context, id string, v *T) error
	// Delete deletes object from the database.
	Delete(ctx context.Context, id string) error
}

func OpenOrCreate

func OpenOrCreate[T any](ctx context.Context, db *sql.DB, tablename string) (Repo[T], error)

OpenOrCreate accepts *sql.DB and tablename and tries to create the named table in the database if it does not exist. The DB instance will also be used by the repository.

Jump to

Keyboard shortcuts

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