Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add named arguments along with a function to bind to the named args #298

Merged
merged 1 commit into from
Nov 10, 2024

Conversation

stephenafamo
Copy link
Owner

No description provided.

Copy link

Deploying bob with  Cloudflare Pages  Cloudflare Pages

Latest commit: 4b7fa99
Status: ✅  Deploy successful!
Preview URL: https://baaf4582.bob-8vc.pages.dev
Branch Preview URL: https://prepare.bob-8vc.pages.dev

View logs

@stephenafamo
Copy link
Owner Author

@RangelReale

This is very similar to #104, but with a few differences:

  1. bob.BindNamed now produces the final query. Merging two steps into one.
  2. The args do not have to be a struct. The type can either be:
    • A struct with fields that match the named arguments in the query
    • A map with string keys. When supplied, the values in the map will be used to bind the named arguments in the query.
    • When there is only a single named argument, one of the following can be used:
      • A primitive type (int, bool, string, etc)
      • time.Time
      • Any type that implements driver.Valuer.
package main

import (
	"context"
	"fmt"

	_ "github.com/jackc/pgx/v5/stdlib"
	"github.com/stephenafamo/bob"
	"github.com/stephenafamo/bob/dialect/psql"
	"github.com/stephenafamo/bob/dialect/psql/sm"
)

type Args struct {
	In1 int
	In2 int
	In3 int
	Id1 int
}

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

	query := psql.Select(
		sm.Columns("id", "name"),
		sm.From("users"),
		sm.Where(psql.Quote("id").In(bob.Named("in1", "in2", "in3"))),
		sm.Where(psql.Raw("id >= ?", bob.Named("id1"))),
	)

	// Use as a regular query
	{
		bound := bob.BindNamed(ctx, query, Args{
			In1: 1,
			In2: 2,
			In3: 3,
			Id1: 4,
		})

		// bound is a [Query] and can be used like any other query

		queryStr, args, err := bob.Build(ctx, bound)
		if err != nil {
			panic(err)
		}

		fmt.Println(queryStr)
		fmt.Println(args)
	}

	// Use in prepared statements
	{
		ctx := context.Background()
		db, err := bob.Open("pgx", "postgresql://user:pass@localhost/bob_droppable?sslmode=disable")

		stmt, err := bob.Prepare[Args](ctx, db, query)
		if err != nil {
			panic(err)
		}

		_ = stmt
	}
}

@stephenafamo stephenafamo merged commit b043f04 into main Nov 10, 2024
9 checks passed
@stephenafamo stephenafamo deleted the prepare branch November 10, 2024 11:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant