sqlcredo

package module
v0.8.1 Latest Latest
Warning

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

Go to latest
Published: Dec 21, 2025 License: MIT Imports: 10 Imported by: 0

README

SQLCredo

GoDoc Go report codecov

SQLCredo is a type-safe generic SQL CRUD operations wrapper for Go, built on top of sqlx and goqu.

The idea of the package to provide basic CRUD and pagination operations out of the box and simplify adding custom raw SQL-queries to extend functionality.

Features

  • Generic type-safe CRUD operations
  • Built-in pagination support
  • SQL query debugging capabilities
  • Support for multiple SQL drivers (tested on sqlite3 and postgres (pgx))
  • Transaction support
  • Prepared statements by default

Installation

go get github.com/Klojer/sqlcredo

Quick Start

package main

import (
 "context"
 "database/sql"
 "fmt"

 _ "github.com/mattn/go-sqlite3"

 sc "github.com/Klojer/sqlcredo"
)

type User struct {
 ID   int    `db:"id"`
 Name string `db:"name"`
}

const schema = `
CREATE TABLE IF NOT EXISTS users (
    id TEXT NOT NULL PRIMARY KEY,
    name TEXT NOT NULL
);
`

func main() {
 ctx := context.Background()

 // Create a new SQLCredo instance
 db, _ := sql.Open("sqlite3", "test.db")
 repo := sc.NewSQLCredo[User, int](db, "sqlite3", "users", "id")

 _, err := repo.InitSchema(ctx, schema)
 orPanic(err)

 // Create
 user := User{ID: 1, Name: "John"}
 _, err = repo.Create(ctx, &user)
 orPanic(err)

 // Read
 users, err := repo.GetAll(ctx)
 orPanic(err)
 fmt.Printf("Users: %+v\n", users)

 // Read with pagination
 page, err := repo.GetPage(ctx,
  sc.WithPageNumber(0),
  sc.WithPageSize(10),
  sc.WithSortBy("name"))
 orPanic(err)
 fmt.Printf("Page: %+v\n", page)

 // Update
 user.Name = "Johnnnn"
 _, err = repo.Update(ctx, 1, &user)
 orPanic(err)

 // Delete
 _, err = repo.Delete(ctx, 1)
 orPanic(err)
}

func orPanic(err error) {
 if err == nil {
  return
 }
 panic(err)
}

See example of repository with custom query: examples/users/users.go

Debug Support

Enable SQL query debugging:

repo.WithDebugFunc(func(sql string, args ...any) {
    log.Printf("SQL: %s Args: %v", sql, args)
})

Documentation

Overview

Package sqlcredo provides a type-safe generic SQL CRUD operations wrapper for Go. It offers built-in CRUD operations, pagination support, transaction management, and SQL query debugging capabilities. The package simplifies database interactions by providing generic implementations for common database operations while allowing custom raw SQL queries for extended functionality. Built on top of sqlx and goqu.

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidPageSize = domain.ErrInvalidPageSize

Functions

This section is empty.

Types

type CRUD added in v0.8.0

type CRUD[T any, I comparable] = domain.CRUD[T, I]

type DebugFunc added in v0.8.0

type DebugFunc = domain.DebugFunc

type NewPageOpt added in v0.8.0

type NewPageOpt[T any] = domain.NewPageOpt[T]

func WithNewPageContent added in v0.8.0

func WithNewPageContent[T any](dest *[]T) NewPageOpt[T]

WithNewPageContent sets page's the desitination slice. If set, ContentInitSize will be ignored

func WithNewPageContentInitSize added in v0.8.0

func WithNewPageContentInitSize[T any](initSize int) NewPageOpt[T]

WithNewPageContentInitSize sets page's the desitination init size.

type Page added in v0.8.0

type Page[T any] = domain.Page[T]

func NewEmptyPage added in v0.8.0

func NewEmptyPage[T any]() Page[T]

NewEmptyPage creates a page with no content and zero counters.

func NewPage added in v0.8.0

func NewPage[T any](opts ...NewPageOpt[T]) Page[T]

NewPage creates a page to fill. By default create new slice for content with capacity equal to DefaultContentInitSize

type PageOpt added in v0.8.0

type PageOpt = domain.PageOpt

func WithPageNumber added in v0.8.0

func WithPageNumber(number uint) PageOpt

WithPageNumber sets the page number. The page number is 0-based, meaning the first page is 0.

func WithPageSize added in v0.8.0

func WithPageSize(size uint) PageOpt

WithPageSize sets the number of items per page. The page size must be greater than 0.

func WithSortBy added in v0.8.0

func WithSortBy(column string) PageOpt

WithSortBy adds a column to sort by. Multiple calls will append to the list of sort columns. If no sort columns are specified, the default is to sort by ID.

func WithSortDesc added in v0.8.0

func WithSortDesc(column string) PageOpt

WithSortDesc sets the sort order to descending. By default, the sort order is ascending.

type PageResolver added in v0.8.0

type PageResolver[T any] = domain.PageResolver[T]

type SQLCredo

type SQLCredo[T any, I comparable] interface {
	SQLExecutor
	CRUD[T, I]
	PageResolver[T]
	TransactionExecutor[T, I]

	// InitSchema executes a SQL query to initialize the database schema.
	// Typically used for creating tables and other database objects.
	InitSchema(ctx context.Context, sql string) (sql.Result, error)

	// WithDebugFunc sets a debug function for SQL query logging.
	// The debug function will be called before executing any SQL query.
	// Returns the modified SQLCredo instance for method chaining.
	WithDebugFunc(newDebugFunc DebugFunc) SQLCredo[T, I]

	// GetDebugFunc returns the currently set debug function.
	// Returns nil if no debug function is set.
	GetDebugFunc() DebugFunc
}

SQLCredo is a comprehensive interface that combines SQL execution, CRUD operations, and pagination capabilities for a specific entity type.

Type Parameters:

  • T: The entity type being managed (can be any type)
  • I: The type of the entity's ID field (must be comparable)

func NewSQLCredo

func NewSQLCredo[T any, I comparable](db *sql.DB, driver string, tableName string, idColumn string) SQLCredo[T, I]

NewSQLCredo creates a new instance of SQLCredo for the specified entity type and ID type.

Parameters:

  • db: A pointer to the underlying database connection
  • driver: The database driver name (e.g., "postgres", "mysql")
  • tableName: The name of the database table for the entity
  • idColumn: The name of the ID column in the table

Returns a fully initialized SQLCredo instance

type SQLExecutor added in v0.8.0

type SQLExecutor = domain.SQLExecutor

type Transaction added in v0.8.0

type Transaction[T any, I comparable] = domain.Transaction[T, I]

type TransactionExecutor added in v0.8.0

type TransactionExecutor[T any, I comparable] = domain.TransactionExecutor[T, I]

Directories

Path Synopsis
examples
users
Package users demonstrates how to extend sqlcredo with custom SQL queries.
Package users demonstrates how to extend sqlcredo with custom SQL queries.
internal
crud
Package crud provides the core CRUD operations implementation for sqlcredo.
Package crud provides the core CRUD operations implementation for sqlcredo.
domain
Package domain defines the core interfaces and types for sqlcredo.
Package domain defines the core interfaces and types for sqlcredo.
goquext
Package goquext provides utilities for working with goqu SQL query builder.
Package goquext provides utilities for working with goqu SQL query builder.
mocks
Package mocks provides mock implementations for testing sqlcredo components.
Package mocks provides mock implementations for testing sqlcredo components.
page
Package page provides the pagination implementation for sqlcredo.
Package page provides the pagination implementation for sqlcredo.
sqlexec
Package sqlexec provides the SQL execution implementation for sqlcredo.
Package sqlexec provides the SQL execution implementation for sqlcredo.
table
Package table provides table metadata structures for sqlcredo.
Package table provides table metadata structures for sqlcredo.
transaction
Package transaction provides transaction management for sqlcredo operations.
Package transaction provides transaction management for sqlcredo operations.