pgx icon indicating copy to clipboard operation
pgx copied to clipboard

Use a struct for named args

Open mxey opened this issue 2 months ago • 3 comments

Is your feature request related to a problem? Please describe.

When querying data with pgx, I can quite easily load the data into structs using the various RowTo functions. However, when inserting data, I have to repeat field names a lot:

_, err := c.db.Exec(ctx, `
	INSERT INTO foo (col)
	VALUES (@col)
`, pgx.StrictNamedArgs{
	"col":                 m.Col,
})

Describe the solution you'd like

A feature similar to (Strict)NamedArgs, but instead of passing a map, passing a struct with the appropriate struct tags:

type Foo struct {
	Col string `db:"col"`
}

_, err := c.db.Exec(ctx, `
	INSERT INTO foo (col)
	VALUES (@col)
`, pgx.StructArgs(m))

Describe alternatives you've considered

None.

Additional context

None.

mxey avatar Oct 13 '25 14:10 mxey

That's definitely doable. In your example, pgx.StructArgs(m) would return a pgx.QueryRewriter that reflected over the struct fields.

jackc avatar Oct 13 '25 22:10 jackc

In your example, pgx.StructArgs(m) would return a pgx.QueryRewriter that reflected over the struct fields.

Yeah I took a quick look at the implementation of NamedArgs when I saw the QueryRewriter interface, but AFAICT I'd have to reimplement the SQL parsing logic, because that's not exposed.

mxey avatar Oct 14 '25 07:10 mxey

The function could return a pgx.NamedArgs.

jackc avatar Oct 14 '25 10:10 jackc