- Published on
sqlc: An Introduction to SQL Compilation
- Authors
- Name
- Moch Lutfi
- @kaptenupi
sqlc
is a powerful tool that lets you write SQL queries in your preferred programming language. It works by parsing your SQL queries into Go code, which you can then compile and run just like any other Go program.
In this article, I will give you a quick introduction to sqlc
and show you how to use it in your own projects.
sqlc
Getting Started with Install sqlc
using the following command:
_1go install `sqlc`.dev/`sqlc`/cmd/`sqlc`@latest
Once you have sqlc
installed, you can create a new project by running the following command:
_1`sqlc` init
This will create a new sqlc
project with a sample schema and query file. You can edit these files to fit your needs.
Creating a Schema
The first thing you'll want to do is create a schema for your database. This is done by creating a .sql
file in the db
directory of your project. Here's an example schema file:
_24-- name: create_users_24-- up_24CREATE TABLE users (_24 id SERIAL PRIMARY KEY,_24 name TEXT NOT NULL,_24 email TEXT NOT NULL UNIQUE_24);_24_24-- name: create_posts_24-- up_24CREATE TABLE posts (_24 id SERIAL PRIMARY KEY,_24 user_id INTEGER NOT NULL REFERENCES users(id),_24 title TEXT NOT NULL,_24 body TEXT NOT NULL_24);_24_24-- name: drop_users_24-- down_24DROP TABLE users;_24_24-- name: drop_posts_24-- down_24DROP TABLE posts;
This schema defines two tables, users
and posts
, with some basic columns.
Writing Queries
Once you have a schema, you can start writing queries to interact with your database. Queries are written in .sql
files in the query
directory of your project.
Here's an example query file:
_3-- name: get_user_by_email_3-- statement: select id, name, email from users where email = $1_3SELECT id, name, email FROM users WHERE email = $1;
This query retrieves a user from the users
table based on their email address.
Compiling Queries
Once you've written your schema and queries, you can compile them using sqlc
. This will generate Go code that you can use in your own projects.
To compile your queries, run the following command:
_1`sqlc` generate
This will generate Go code in the db
directory of your project. Here's an example of what the generated code looks like:
_27package db_27_27import (_27 "context"_27 "fmt"_27_27 "github.com/jackc/pgx/v4/pgxpool"_27)_27_27type DB struct {_27 *pgxpool.Pool_27}_27_27func NewDB(pool *pgxpool.Pool) *DB {_27 return &DB{_27 pool,_27 }_27}_27_27func (db *DB) GetUserByEmail(ctx context.Context, email string) (User, error) {_27 var user User_27 err := db.QueryRow(ctx, `SELECT id, name, email FROM users WHERE email = $1`, email).Scan(&user.ID, &user.Name, &user.Email)_27 if err != nil {_27 return User{}, fmt.Errorf("error getting user by email: %w", err)_27 }_27 return user, nil_27}
This generated code lets you interact with your database using type-safe Go functions.
Using the Generated Code
Now that you have your queries compiled into Go code, you can use them in your own projects.
Here's an example of how you can use the generated code to retrieve a user from the database:
_33package main_33_33import (_33 "context"_33 "database/sql"_33 "fmt"_33_33 _ "github.com/jackc/pgx/v4/stdlib"_33 "github.com/myproject/db"_33)_33_33func main() {_33 // Connect to the database_33 connStr := "postgres://user:password@localhost:5432/mydatabase?sslmode=disable"_33 db, err := sql.Open("pgx", connStr)_33 if err != nil {_33 fmt.Println("Error connecting to the database:", err)_33 return_33 }_33 defer db.Close()_33_33 // Create a new DB object_33 dbConn := db.NewDB(db)_33_33 // Retrieve a user from the database_33 user, err := dbConn.GetUserByEmail(context.Background(), "example@example.com")_33 if err != nil {_33 fmt.Println("Error retrieving user:", err)_33 return_33 }_33_33 fmt.Println("User:", user)_33}
This code connects to a PostgreSQL database and retrieves a user from the users
table using the GetUserByEmail
function generated by sqlc
.
Conclusion
sqlc
is a powerful tool that lets you write SQL queries in your preferred programming language. With sqlc
, you can write type-safe SQL queries in Go and easily integrate them into your projects.
In this article, I've shown you how to get started with sqlc
by creating a schema, writing queries, compiling them into Go code, and using that code in your own projects.
I hope this article has been helpful in getting you started with sqlc
. Happy coding!