Transactions on Postgres with Golang

18 Mar 2020 ⏱️ 3 min
Transactions on Postgres with Golang

In this article, I will be discussing how to execute DB operations on Postgres in Golang.

Databases are basic components of any application. Recently building applications in Golang, I too had the use case to persist data and perform queries on it.

Starting with the Basics ✅

I’ll be using GORM library here. If you are using pq, make required modifications but the concept will remain the same.

Let’s first create a DB module and set up our own PostgresStore to increase readability and access only those methods which we need. You can anytime add/remove as per your need.

I have added the following operations —

  • DB() — which is our Postgres DB instance
  • Begin() — which starts a transaction block
  • Commit() — commits the current transaction
  • Rollback() — abort the current transaction
  • Close() — closes the cursor ( Read more here)

Rest is just the implementation of these methods. Please refer to the code below.

Now, once we have done our setup. Do set up your basic table with some data. I created a user table with id,name and gender columns. Let’s do a simple SELECT query on it —

Congrats, you just performed a DB operation. You can do all kinds of SQL magic here 😉

Let’s do some Transactions 💰

For those who are not aware of what Transaction means in database. I’ll recommend reading about it first.

What are DB Transactions?

A database transaction is a single unit of work that may consist of one or more operations. A transaction in a database system must maintain the ACID properties.

  • Atomicity
  • Consistency
  • Isolation
  • Durability

Read awesome geeksforgeeks article here.

Now let’s implement transactions to make our concepts solid.
Note: I’ll recommend to always code out the concepts you learn. It lets you understand the topic better.

A transaction will consist of the following stages —

Same stages in Golang would be like this —

Transactions are highly useful and recommended since they maintain ACID properties. Also, in the case of bulk queries, you can execute let’s say multiple execute queries. But commit only once. This reduces the time taken to execute that bulk operation. Otherwise, each query would commit and increase the overall time.

Try experimenting and clocking the time taken with and without a transaction. Now, get back to your codebases and implement transactions if you were not till now 😊

Liked the article? Consider supporting me ☕️

Upskill yourself with awesome courses on Educative

I hope you learned something new. Feel free to suggest improvements ✔️

I share regular updates and resources on Twitter. Let’s connect!

Keep exploring 🔎 Keep learning 🚀

Liked the content? Do support :)

Paypal - Mohit Khare
Buy me a coffee