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

make QueuedQuery.Fn property public, closes #1878 #1996

Merged
merged 1 commit into from
May 12, 2024

Conversation

pashagolub
Copy link
Contributor

@pashagolub pashagolub commented Apr 29, 2024

This commit fixes the overlook of the #1886 where QueuedQuery.SQL and QueuedQuery.Arguments properties were exposed.

And if for SQL and Arguments we had an opportunity to use reflection, for QueuedQuery.fn it's impossible.

One more benefit exposing QueuedQuery.Fn for developers is the ability to execute batched functions without knowing the kind of a queued query and mandatory calling BatchResults.Close(), e.g.

batch := &pgx.Batch{}
batch.Queue("select func42($1)", 42).QueryRow(...)
batch.Queue("select * from foo").Query(...)
batch.Queue("insert").Exec(...)
...
batch.Queue("truncate foo").Exec(...)

br = conn.SendBatch(ctx, batch)
// check first two queued queries
err := batch.QueuedQueries[0].Fn()
err = errors.Join(err, batch.QueuedQueries[1].Fn())
// let BatchResults execute all that left and close 
err = errors.Join(err, br.Close())
if err != nil {
	fmt.Printf("SendBatch error: %v", err)
	return
}

This commit fixes the overlook of the jackc#1886 where SQL and Arguments
properties were exposed
@pashagolub
Copy link
Contributor Author

When this PR will be merged, one will be able to test Batches with pgxmock:

func TestBatch(t *testing.T) {
	t.Parallel()
	mock, _ := NewConn()
	a := assert.New(t)

	// define our expectations
	eb := mock.ExpectBatch()
	eb.ExpectQuery("select").WillReturnRows(NewRows([]string{"sum"}).AddRow(2))
	eb.ExpectExec("update").WithArgs(true, 1).WillReturnResult(NewResult("UPDATE", 1))

	// run the test
	batch := &pgx.Batch{}
	batch.Queue("select 1 + 1").QueryRow(func(row pgx.Row) error {
		var n int32
		return row.Scan(&n)
	})
	batch.Queue("update users set active = $1 where id = $2", true, 1).Exec(func(ct pgconn.CommandTag) (err error) {
		if ct.RowsAffected() != 1 {
			err = errors.New("expected 1 row to be affected")
		}
		return
	})

	err := mock.SendBatch(ctx, batch).Close()
	a.NoError(err)
	a.NoError(mock.ExpectationsWereMet())
}

@jackc jackc merged commit 523411a into jackc:master May 12, 2024
14 checks passed
@pashagolub pashagolub deleted the 1878-expose-queuedquery-fn branch May 13, 2024 10:46
This pull request was closed.
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.

2 participants