sqlk

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2026 License: MIT Imports: 12 Imported by: 0

README

sqlk - SQL Query Builder

🗄️ Custom Konsultin SQL query builder with PostgreSQL support and schema utilities.

Installation

go get github.com/konsultin/sqlk

Quick Start

import (
    "github.com/konsultin/sqlk"
    "github.com/konsultin/sqlk/pq/query"
)

// Create database connection
db, err := sqlk.NewDatabase(sqlk.Config{
    Driver:   "postgres",
    Host:     "localhost",
    Port:     5432,
    User:     "postgres",
    Password: "password",
    Database: "mydb",
})
if err != nil {
    log.Fatal(err)
}
defer db.Close()

// Build SELECT query
q := query.Select("id", "name", "email").
    From("users").
    Where(query.Equal("status", "active")).
    Limit(10)

sql, args := q.Build()
// SELECT id, name, email FROM users WHERE status = $1 LIMIT 10

// Build INSERT query
q := query.Insert("users").
    Columns("name", "email").
    Values("John", "john@example.com")

Features

  • Query Builder - Fluent API for SELECT, INSERT, UPDATE, DELETE
  • PostgreSQL Support - Native dialect with bindvar support
  • Where Conditions - Equal, NotEqual, In, Like, IsNull, And, Or
  • Transaction Support - Easy transaction management
  • Connection Pooling - Configurable pool settings

License

MIT License - see LICENSE

Documentation

Index

Constants

View Source
const (
	DriverMySQL      = "mysql"
	DriverPostgreSQL = "postgres"

	Null = `null`
)
View Source
const (
	DefaultMaxIdleConn     = 10
	DefaultMaxOpenConn     = 10
	DefaultMaxConnLifetime = 1
)
View Source
const (
	Separator = ", "
)

Variables

View Source
var EmptyObjectJSON = json.RawMessage("{}")
View Source
var RowNotUpdatedError = new(rowNotUpdatedError)

Functions

func CommitOrRollback

func CommitOrRollback(txCtx *TxContext, err error) error

CommitOrRollback commits the transaction if err is nil, otherwise rolls back This is useful for manual transaction control

func ErrorIsPqCancelStatementByUser

func ErrorIsPqCancelStatementByUser(err error) bool

func IsUpdated

func IsUpdated(result sql.Result) error

func NewInt

func NewInt(i int) *int

NewInt returns pointer of a variable that contains integer

func ScanJSON

func ScanJSON(src interface{}, target interface{}) error

ScanJSON is a generic scanner function to parse json from row data

func ToNullString

func ToNullString(str string) sql.NullString

func WithTransaction

func WithTransaction(ctx context.Context, db *sqlx.DB, opts *sql.TxOptions, fn TxFunc) (err error)

WithTransaction executes the given function within a transaction Automatically commits on success, rolls back on error or panic

Types

type AliasSetter

type AliasSetter interface {
	SetTableAs(as string)
}

type ColumnGetter

type ColumnGetter interface {
	GetColumn() string
}

type ColumnWriter

type ColumnWriter interface {
	ColumnQuery() string
	SetFormat(format op.ColumnFormat)
	ColumnGetter
	AliasSetter
	SchemaReference
}

type Config

type Config struct {
	Driver          string
	Host            string
	Port            string
	Username        string
	Password        string
	Database        string
	MaxIdleConn     *int
	MaxOpenConn     *int
	MaxConnLifetime *int
}

type Database

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

func NewDatabase

func NewDatabase(config Config) (*Database, error)

func (*Database) Close

func (db *Database) Close() error

func (*Database) GetConnection

func (db *Database) GetConnection(ctx context.Context) (*sqlx.Conn, error)

func (*Database) Init

func (db *Database) Init() error

func (*Database) InitContext

func (db *Database) InitContext(ctx context.Context) error

func (*Database) IsConnected

func (db *Database) IsConnected() bool

func (*Database) PingContext

func (db *Database) PingContext(ctx context.Context) error

func (*Database) WithContext

func (db *Database) WithContext(ctx context.Context) *DatabaseContext

type DatabaseContext

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

func (*DatabaseContext) MustPrepare

func (s *DatabaseContext) MustPrepare(query string) *sqlx.Stmt

MustPrepare prepare sql statements or exit app if fails or error

func (*DatabaseContext) MustPrepareFmt

func (s *DatabaseContext) MustPrepareFmt(queryFmt string, args ...interface{}) *sqlx.Stmt

MustPrepareFmt prepare sql statements from string format or exit app if fails or error

func (*DatabaseContext) MustPrepareNamed

func (s *DatabaseContext) MustPrepareNamed(query string) *sqlx.NamedStmt

MustPrepareNamed prepare sql statements with named bindvars or exit app if fails or error

func (*DatabaseContext) MustPrepareNamedFmt

func (s *DatabaseContext) MustPrepareNamedFmt(queryFmt string, args ...interface{}) *sqlx.NamedStmt

MustPrepareNamedFmt prepare sql statements from string format with named bindvars or exit app if fails or error

func (*DatabaseContext) MustPrepareRebind

func (s *DatabaseContext) MustPrepareRebind(query string) *sqlx.Stmt

MustPrepareRebind prepare sql statements and rebind with database adapter or exit app if fails or error

func (*DatabaseContext) MustPrepareReplace

func (s *DatabaseContext) MustPrepareReplace(q string, values map[string]string) *sqlx.Stmt

MustPrepareReplace prepare sql statements from a string replacement or exit app if fails or error

func (*DatabaseContext) Rebind

func (s *DatabaseContext) Rebind(query string) string

Rebind transforms a query from using ? placeholders to the driver-specific placeholder format

func (*DatabaseContext) SelectContext

func (s *DatabaseContext) SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error

SelectContext executes a query using the stored context, and BindStructScan each row into dest

type Expander

type Expander interface {
	Expand(args ...interface{}) SelectWriter
}

type FilterParser

type FilterParser = func(queryValue string) (WhereWriter, []interface{})

type FromWriter

type FromWriter interface {
	FromQuery() string
	Join(j JoinWriter)
	SchemaRefGetter
}

FromWriter must be implemented by part of query that will generate query in FROM

type Int64

type Int64 struct {
	sql.NullInt64
}

Int64 add functionality to handle null types of JSON strings

func NewInt64

func NewInt64(input int64) Int64

func (*Int64) MarshalJSON

func (s *Int64) MarshalJSON() (raw []byte, err error)

func (*Int64) UnmarshalJSON

func (s *Int64) UnmarshalJSON(b []byte) error

type JoinWriter

type JoinWriter interface {
	JoinQuery() string
	GetTableName() string
	GetIndex() int
	SetIndex(s int)
	SchemaRefGetter
}

type OrderByWriter

type OrderByWriter interface {
	OrderByQuery() string
	AliasSetter
	SchemaReference
}

type SchemaRefGetter

type SchemaRefGetter interface {
	GetSchemaRef() schema.Reference
}

type SchemaReference

type SchemaReference interface {
	TableGetter
	SchemaRefGetter
	SetSchema(s *schema.Schema)
}

SchemaReference must be implemented by part of query that may not require defining schema, but will be set later. For example, Selected fields can only set without defining schema and will be referred to schema that is defined in FROM

type SelectWriter

type SelectWriter interface {
	SelectQuery() string
	SetFormat(format op.ColumnFormat)
	IsAllColumns() bool
	AliasSetter
	SchemaReference
}

SelectWriter must be implemented by part of query that will generate query in SELECT

type String

type String struct {
	sql.NullString
}

String add functionality to handle null types of JSON strings

func NewString

func NewString(str string) String

func (*String) MarshalJSON

func (s *String) MarshalJSON() (raw []byte, err error)

func (*String) UnmarshalJSON

func (s *String) UnmarshalJSON(b []byte) error

type TableGetter

type TableGetter interface {
	GetTableName() string
}

type TxContext

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

TxContext wraps sqlx.Tx with context

func BeginTx

func BeginTx(ctx context.Context, db *sqlx.DB, opts *sql.TxOptions) (*TxContext, error)

BeginTx starts a new transaction with the given context and options

func (*TxContext) Commit

func (tc *TxContext) Commit() error

Commit commits the transaction

func (*TxContext) Ctx

func (tc *TxContext) Ctx() context.Context

Ctx returns the context

func (*TxContext) Rollback

func (tc *TxContext) Rollback() error

Rollback rolls back the transaction

func (*TxContext) Tx

func (tc *TxContext) Tx() *sqlx.Tx

Tx returns the underlying sqlx.Tx

type TxFunc

type TxFunc func(*TxContext) error

TxFunc is a function that executes within a transaction

type VariableWriter

type VariableWriter interface {
	VariableQuery() string
}

type WhereCompareWriter

type WhereCompareWriter interface {
	GetVariable() VariableWriter
	SetVariable(v VariableWriter)
	ColumnGetter
	AliasSetter
	SchemaReference
}

type WhereLogicWriter

type WhereLogicWriter interface {
	GetConditions() []WhereWriter
	SetConditions(conditions []WhereWriter)
}

type WhereWriter

type WhereWriter interface {
	WhereQuery() string
}

Directories

Path Synopsis
parse
pq

Jump to

Keyboard shortcuts

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