Published on

sqlc: An Introduction to SQL Compilation

Authors

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.

Getting Started with sqlc

Install sqlc using the following command:


_1
go 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
_24
CREATE 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
_24
CREATE 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
_24
DROP TABLE users;
_24
_24
-- name: drop_posts
_24
-- down
_24
DROP 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
_3
SELECT 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:


_27
package db
_27
_27
import (
_27
"context"
_27
"fmt"
_27
_27
"github.com/jackc/pgx/v4/pgxpool"
_27
)
_27
_27
type DB struct {
_27
*pgxpool.Pool
_27
}
_27
_27
func NewDB(pool *pgxpool.Pool) *DB {
_27
return &DB{
_27
pool,
_27
}
_27
}
_27
_27
func (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:


_33
package main
_33
_33
import (
_33
"context"
_33
"database/sql"
_33
"fmt"
_33
_33
_ "github.com/jackc/pgx/v4/stdlib"
_33
"github.com/myproject/db"
_33
)
_33
_33
func 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!