Klimbo
Klimbo

Reputation: 1438

Is it possible to call Go functions in one transactions?

I store a double linked list in PostgreSQL. I have a Go API to manage this list.

There is a function that creates new Node (in specific position). Let's assume there is an INSERT SQL query inside of it.

Also, there is a function that deletes Node (by id). Let's assume there is a DELETE SQL query inside of it.

It is well known that if you need to move a Node to different position you should call DeleteNode() function and CreateNode() function. So there is the third function called MoveNode()

func MoveNode() error {
  if err := DeleteNode(); err != nil {
    return err
  }
  if err := CreateNode(); err != nil {
    return err
  }
  return nil
}

But these functions (which are inside of MoveNode() should be called in one transaction.

Is there a way to "merge" functions in Go? Or what is the way to solve this problem (except copy & paste code from 2 functions to the third)?

p.s The idea is simple: you have two functions which do some SQL queries and you need to do these queries in one transaction (or call 2 functions in one transaction)

Upvotes: 0

Views: 790

Answers (1)

Kartavya Ramnani
Kartavya Ramnani

Reputation: 828

The better way to go about this here will be to move tx.Commit() outside the query execution functions (DeleteNode() and CreateNode() here)

Suggested Solution :

func MoveNode() error {
   tx, err := db.Begin()
   // err handling

  res, err := DeleteNode(tx)
  // err handling

  res, err := CreateNode(tx)
  // err handling

  tx.Commit()
}

func DeleteNode(transactionFromDbBegin) (responseFromExec, errorFromExec) {
    //...
}

func CreateNode(transactionFromDbBegin) (responseFromExec, errorFromExec) {
    //...
}

This should do the trick.

Upvotes: 2

Related Questions