Dynamic Calls

Make SQL Scan result be map in golang

sqlx

import (
	"context"
	"fmt"
	"strings"
	"time"

	"github.com/jackc/pgx/v5/pgxpool"
)

func callProcPGX(pool *pgxpool.Pool, schema, proc string, args []any) error {
	ph := make([]string, len(args))
	for i := range args {
		ph[i] = fmt.Sprintf("$%d", i+1)
	}
	q := fmt.Sprintf("CALL %s.%s(%s)", schema, proc, strings.Join(ph, ", "))

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	_, err := pool.Exec(ctx, q, args...)
	return err
}

sql

// Assume you have a *sql.DB or *sqlx.DB instance named db

params := []any{"foo", 123, true} // example slice of parameters

query := "CALL mydatabase.mystoredprocedure($1, $2, $3)" // can be built dynamically

_, err := db.Exec(query, params...)
if err != nil {
    log.Fatal(err)
}

args := []any{10, "seed"} // whatever you have
ph := make([]string, len(args))
for i := range args { ph[i] = fmt.Sprintf("$%d", i+1) }

// For a function:
q := fmt.Sprintf("SELECT * FROM mydb.fn(%s)", strings.Join(ph, ", "))
row := db.QueryRow(q, args...)

// For a procedure:
q = fmt.Sprintf("CALL mydb.proc(%s)", strings.Join(ph, ", "))
row = db.QueryRow(q, args...)