🦮 A practical introduction to PostgreSQL in Go
tour postgresql db sqlPostgreSQL, also known as Postgres, is an object-relational database system with over 30 years of history. Appreciated for its high stability, performance, and open source, it has been used as the primary database in many advanced and enterprise projects. It is perfect as a database for web, mobile, geospatial and analytical applications. Its ease of use and advanced features make it the choice of both small startups and large enterprises as a long-term relational database.
According to StackShare many of the biggest tech companies use PostgreSQL in their stacks:
- Uber
- Netflix
- Spotify
and many others.
In this tutorial, we are going to show you how to use PostgreSQL in Go. We will create a simple application that connects to the database, define a data access layer using the Repository pattern, and implement CRUD (create, read, update, delete) operations. Finally, we will show how to easily replace the database implementation by using the Repository pattern.
Who is this tutorial for?
This tutorial is suitable for both beginners and advanced programmers who want to learn or remember how to perform basic operations on a PostgreSQL database from within the Go language. However, it does not teach SQL and does not explain in detail how PostgreSQL works. The purpose is to connect and perform operations in a Go application.
It is a tour on how to build a data access layer using clean code practices and what are the popular ways to connect to PostgreSQL. Since we use very simple examples in the tutorial, it is a great introduction to building something more advanced, and we encourage you to come back to it whenever you need to create a data access layer in your new project.
The project code
The full code of the project created in this tutorial is available on Github here.
Table of Contents
- A practical introduction to PostgreSQL in Go ⭢ you are here
- Pure SQL or ORM
- Repository pattern
- Install PostgreSQL
- What we are going to build
- Init project structure
- Domain object and repository
- Repository methods
- Repository errors
- Init classic
database/sql
repository - Implement Create method
- Implement reading methods
- Implement Update method
- Implement Delete method
- Init the main function and the demo procedure
- Complete the demo procedure
- Repository based on the
pgx
client - Run the demo procedure for
pgx
-based repository - GORM repository
- Run the demo procedure for GORM repository
- Summary
Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.
Have a great day!