package
0.8.2
Repository: https://github.com/tomcz/gotools.git
Documentation: pkg.go.dev

# README

sqls

SQL helper functions for queries and transactions to remove common boilerplate code.

import (
	"context"
	"database/sql"
	"github.com/tomcz/gotools/sqls"
)

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

	var db *sql.DB // initialisation omitted

	results := make(map[string]string)

	selectLeadersSQL := "select leader, node from current_leaders"
	err := sqls.QueryRowsContext(ctx, db, selectLeadersSQL)(func(row sqls.ScanFunc) error {
		var leader, node string
		if err := row(&leader, &node); err != nil {
			return nil
		}
		results[leader] = node
		return nil
	})
	// error handling omitted

	insertLeaderSQL := "insert into old_leaders (leader, node, created_at) values (?, ?, ?)"
	err = sqls.InTxContext(ctx, db, func(tx *sql.Tx) error {
		for leader, node := range results {
			_, err := tx.ExecContext(ctx, insertLeaderSQL, leader, node, time.Now())
			if err != nil {
				return err // tx will be rolled-back
			}
		}
		return nil // tx will be committed
	})
	// error handling omitted
}

# Packages

Package txx provides transaction helper functions for the github.com/jmoiron/sqlx library.

# Functions

InTx starts a database transaction, executes the callback function, and either commits the transaction if the callback exits without an error, or rolls-back the transaction if the callback returns an error.
InTxContext starts a context-aware database transaction, executes the callback function, and either commits the transaction if the callback exits without an error, or rolls-back the transaction if the callback returns an error.
MapToAny performs a type conversion useful for query arguments.
QueryRows provides the entry point to retrieve a number of rows from a given query and arguments, using database/sql/#DB.QueryRow as inspiration.
QueryRowsContext provides the entry point to retrieve a number of rows from a given query and arguments, using database/sql/#DB.QueryRowContext as inspiration.

# Type aliases

EachRowFunc is called to process each query result row.
PartialQuery is a curried query that passes each result row to EachRowFunc.
ScanFunc provides an interface for the database/sql/#Rows.Scan function so that we can limit what is exposed by EachRowFunc.