Query on using Closures

73 views
Skip to first unread message

Suveetha Kamatchi

unread,
Jun 6, 2021, 2:45:01 PM6/6/21
to golan...@googlegroups.com
Hi team
I am a newbie to golang.
I am writing a code that does transactions in postgres.
The list of queries to be executed under one transaction is gathered across multiple handler code.

The way I am maintaining the query structure is as follows
type TxQuery struct {
function TxFunc
data types.TransactionData
}
type TxFunc func(tx *sqlx.Tx, input types.TransactionData) error

var TxQueries []TxQuery

func getHandlerInput() []TxQuery {
// fill with your set of DDL/DML queries.
}

txQueries := getHandlerInput(db.DB)

tx := db.DB.MustBegin()
for index, _ := range txQueries {
fmt.Println(txQueries[index].function, txQueries[index].data)
err = txQueries[index].function(tx, txQueries[index].data)
assert.Nil(t, err)
}

err = tx.Commit()


The issue I am facing is
The function always retains the last assigned closure for all the data in the list i.e previous values of function gets overwritten.

i.e the last query command gets executed twice with first and second argument list.

Logs:
2021/06/04 18:43:40 Added marketplace escrow  entry for  {00000000-0000-0000-0000-000000000000     141b147a-96ab-4dda-a4f6-d142e7e04a97 6789 8 2 1000 255 15 7 7 7 {"wallex"} 282 283 284 false <nil> <nil> 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC}
2021/06/04 18:43:40 Added marketplace escrow  entry for  {00000000-0000-0000-0000-000000000000 2f2fe301-8545-4030-940c-c32937392034  6f2c68ab-ab84-46b6-b70b-6ec5c0205e09 {"project": "software"} 141b147a-96ab-4dda-a4f6-d142e7e04a97 6789 8 2 1000 255 15 7 7 7 {"wallex"} 282 283 284 false <nil> <nil> 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC}

Please let me know what I am missing?

Thanks,
K.R.Suveetha Kamatchi




Jan Mercl

unread,
Jun 6, 2021, 2:53:42 PM6/6/21
to Suveetha Kamatchi, golang-nuts
On Sun, Jun 6, 2021 at 8:44 PM 'Suveetha Kamatchi' via golang-nuts
<golan...@googlegroups.com> wrote:

Please post code as plain text, no colors, no inverted schema in
particular. Or share code via a link at play.golang.org, thank you.

Scott Pakin

unread,
Jun 6, 2021, 4:51:09 PM6/6/21
to golang-nuts
Just a guess: You may need to make a local copy of index inside your loop because index gets overwritten each iteration.
Reply all
Reply to author
Forward
0 new messages