Timileyin D
Posted on January 3, 2024
What is SQLC
SQLC is a type-safe SQL code generator, it is used to generates fully type-safe idiomatic code from SQL and catch failure before they happen, it support different languages like Golang, Kotlin and Python. The main advantage of using SQLC is that it generate type-safe code from the SQL queries.
How SQLC work
You write SQL queries
You run sqlc to generate Go code that presents type-safe interfaces to those queries
You write application code that calls the methods sqlc generated
SQLC golang sample
To get started, we need to navigate to the desired directory and run the command below in our terminal:
mkdir sqlc_go && cd sqlc_go
also create db/migration and db/queries folder
Implementing SQLC in golang involves installing *golang-migrate * package,this helps to fully utilize SQLC full potential.
We proceed to install the required golang-migrate dependencies with:
$ curl -L https://github.com/golang-migrate/migrate/releases/download/$version/migrate.$os-$arch.tar.gz | tar xvz
The code above install golang-migrate. We can then proceed to creating the migration file for the user by running the below code.
migrate create -ext sql -dir db/migration -seq add_users
This will generate two serialized file that looks like the image attached below.
where the .up.sql file is for the SQL query model definition while the .down.sql file is for changes reversal.
- Insert the SQL query into the .up.sql file. see the code below
while the below code inside the .down.sql file
The code in the .down.sql file will be use to reverse the changes made to the database(DB)
The user.sql file in the db/queries folder will contain the code below which instruct SQLC on the method to be generated.
It will create CreateUser, GetUser among other method
Pull a Postgres image from the docker hub and create a database on the running Postgres instance.
Create sqlc.yaml by running
sqlc init
(image below) to set the configuration for the SQLC
The code above instruct golang-migrate to look out for the db/migration folder when the migration code below is been executed
migrate -path db/migration -database "$(DB_URL)" -verbose up
sqlc generate
the code above will create sqlc folder in the db folder also create a db.go file in the db/sqlc folder
which explicitly define the database architecture and database method that can be used in our controller, remember this method was defined in our db/queries folder. Image attached below
Conclusion
This article demonstrate how to use SQLC in a golang application, its role in building type-safe idiomatic code and how to get started by building a user management service with Golang and Postgres DB.
Posted on January 3, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.