Created
March 1, 2020 11:54
-
-
Save itinance/8d1ba0eafd983ffdc4088a608e8a32bb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func getExistingAddressId(tx *sql.Tx, address string) (int64, error) { | |
var result sql.NullInt64 | |
if err := tx.QueryRow("SELECT id FROM wallet WHERE `address`=?", address). | |
Scan(&result); err != nil && err != sql.ErrNoRows { | |
return 0, err | |
} | |
return result.Int64, nil | |
} | |
func insertNewAddress(tx *sql.Tx, address string) (int64, error) { | |
res, err := tx.Exec("INSERT INTO wallet (address) VALUES (?)", address) | |
if err != nil { | |
return 0, err | |
} | |
return res.LastInsertId() | |
} | |
func getAddressId(db *sql.DB, address string) (id int64, err error) { | |
tx, err := db.Begin() | |
if err != nil { | |
return 0, err | |
} | |
defer func() { | |
if err != nil { | |
tx.Rollback() | |
} else { | |
tx.Commit() | |
} | |
}() | |
if id, err = getExistingAddressId(tx, address); err != nil || id != 0 { | |
return | |
} | |
return insertNewAddress(tx, address) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment