Struggling with Transactions

Hi, I am reading the Neo4j Go Driver Manual v4.2 and there is a session with a non-functional piece of code on page #23

I want to create an ACID transaction similar to the code above. Then I'm looking for a gist or Github repository or an example of how to use transactions (BeginTransaction, a few WriteTransaction's, commit or rollback statements depending on the case) so I can take a look at. The samples found in Neo4j documentation show only auto-commit transactions.

I'm really struggling with these statements:

//To attach a metadata to an explicit transaction:
session.BeginTransaction(WithTxMetadata(map[string)interface{}{"work-id": 1}))  <====

// To attach a metadata to a write transaction function:
session.WriteTransaction(DoWork, WithTxMetadata(map[string)interface{}{"work-id": 1}))
session.WriteTransaction(DoWork2, WithTxMetadata(map[string)interface{}{"work-id": 104}))

I don't get why is necessary to set WithTxMetadata to begin a transaction.

Completely lost here...

Hi, the recommended approach is to use session.ReadTransaction or session.WriteTransaction.
Do you need transaction metadata at all?

If not, you can run statements like this one.

Hi Florent.

I checked this code out. But it handles one transaction at time.

What I want to do is handle multiple Write transactions in a single ACID transaction - all successful or all fail. I guess I should use BeginTransaction to do this but not sure, it is not clear if this is the proper approach. Is this the approach of the Golang Neo4j community?

You can do something like this:

	transaction, err := session.BeginTransaction()
	if err != nil {
		panic(err)
	}
	defer transaction.Close()
	params := map[string]interface{}{"prop": "some property"}
	if _, err := transaction.Run("CREATE (n:SomeNode {with: $prop})", params); err != nil {
		err = transaction.Rollback()
        // handle rollback error, if any
	}
	if _, err = transaction.Run("MATCH (n:SomeNode {with: $prop}) SET n:AnotherLabel", params); err != nil {
		err = transaction.Rollback()
        // handle rollback error, if any
	}
	transaction.Commit()

Does that help?
If so, what is this page 23 of the driver manual that needs fixing you referred to in your initial question?

1 Like

Florent, the example will do. Thank you very much.

Regarding the manual, I have downloaded Neo4j Go Driver Manual v4.2 (PDF) from Neo4j Documentation website. At page #25 there is that piece of code that doesn't work.

I just looked at https://neo4j.com/docs/pdf/neo4j-driver-manual-4.2-go.pdf and I could not find any code at page 25. Is this on another page perhaps?