Skip to content

Commit 3fa298a

Browse files
committed
added a transaction example for db connections, learnt concurrency control
1 parent 896f67b commit 3fa298a

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

connect_with_a_database/main.go

+40
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,42 @@ type DummyTable struct {
1515
Email string `json:"email"`
1616
}
1717

18+
func executeEverythingInASingleTransacton(conn *pgx.Conn) {
19+
20+
tx, err := conn.Begin(context.Background())
21+
22+
if err != nil {
23+
fmt.Fprintf(os.Stderr, "The erros while begining a transaction is \n%v", err)
24+
os.Exit(1)
25+
}
26+
27+
defer tx.Rollback(context.Background())
28+
29+
row, err := tx.Exec(context.Background(), "INSERT INTO dummy_table(id, name, age, email) values($1, $2, $3, $4)", 18, "Tula", 52, "[email protected]")
30+
31+
errRow, errorInSecondInsert := tx.Exec(context.Background(), "INSERT INTO dummy_table(id, name, age, email) values($1, $2, $3, $4)", 19, "Ashneer", 57, "[email protected]")
32+
33+
if err != nil {
34+
fmt.Fprintf(os.Stderr, "error while executing a transaction query \n%v", err)
35+
os.Exit(1)
36+
}
37+
38+
if errorInSecondInsert != nil {
39+
fmt.Fprintf(os.Stderr, "error while executing a transaction query \n%v", errorInSecondInsert)
40+
os.Exit(1)
41+
}
42+
43+
fmt.Println("Rows affected in this transaction", row.RowsAffected(), errRow.RowsAffected())
44+
45+
err = tx.Commit(context.Background())
46+
47+
if err != nil {
48+
fmt.Fprintf(os.Stderr, "The error while commiting is \n%v", err)
49+
os.Exit(1)
50+
}
51+
52+
}
53+
1854
func printAllRowsInTable(conn *pgx.Conn) {
1955
rows, err := conn.Query(context.Background(), "select * from dummy_table")
2056

@@ -109,6 +145,8 @@ func getDBConnectionHandler() *pgx.Conn {
109145

110146
func main() {
111147

148+
// Comment insert and update whenever needed
149+
112150
conn := getDBConnectionHandler()
113151
defer conn.Close(context.Background())
114152

@@ -127,4 +165,6 @@ func main() {
127165
fmt.Println(("\nDeleting one row in dummy table"))
128166
printRowAfterDeleting(conn)
129167

168+
fmt.Println("\nExecuting in a single transaction")
169+
executeEverythingInASingleTransacton(conn)
130170
}

0 commit comments

Comments
 (0)