2018. január 10., szerda 8:05:18 UTC+1 időpontban evan a következőt írta: > > after reading https://golang.org/pkg/database/sql/, i'm still not quite > sure how to do error handling with respect to tx (transaction) operations. > coming from a java/c# background, where once an exception is raised, i know > what to do in the "catch" and "finally" blocks, i'm not as sure with go > errors, so i thought i'd askfor help being a go newbie. > > supposing i'm doing something like this in postgresql within a go func: > > tx, err := db.Begin() > //Question 1: what happens if err != nil in the above statement? will tx > be nil or will i get a non-nil tx that is just unuseable? if the latter, > would it ever make sense for me to just wait until after the tx.Commit() > statement and just do error checking and handling once? i know that if i > get an error with db.Begin(), i really should just forget about trying to > execute the remaining code but i was just curious what other options -- if > any -- might make sense. >
Generally, you can't use tx if err != nil - so here tx is unusable. This should happen only if the DB is on fire. > rows, err := tx.Query(...) > > result, err := tx.Exec(...) > > err = tx.Commit() > > > additional questions: > > (2) kinda related to question 1 above: do i have to check for errors > after each statement above, or is it the case that once an error has > occurred, the tx object is unuseable because it "remembers" the error(s) > that have occurred? > > Yes, you have to check the error - it has nothing to do with tx, that still can be valid! For example a tx.Query returns errorr if the query has syntax error, tx.Exec if you've tried to validate a unique index, and so on. If tx.Commit fails, that means you've lost contant with your DB or your DB is on fire. (3) when an error occurs, is the transaction automatically rollback'ed or > do i have to do this explicitly? > No automatic rolling back. You have to decide what to do in case of error. > > (4) if tx.Commit() fails, does the "go" runtime take care of necessary > resource cleanups / givebacks, etc? any potential gotchas i need to be > aware of? > No, you have to Rollback, and ALWAYS call Close on the Rows of (successful) Query! > > thanks for any help! > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.