SQLC is a tool that generates Go code from SQL queries. This guide provides an overview of all SQLC commands and their usage.
To install SQLC, run:
go install github.com/kyleconroy/sqlc/cmd/sqlc@latest
Initializes a new SQLC project by creating a sqlc.yaml
configuration file in the current directory.
sqlc init
Generates Go code from the SQL queries and schema defined in the sqlc.yaml
configuration file.
sqlc generate
Compiles the SQL queries and prints any parsing errors without generating Go code. This is useful for validating your SQL queries.
sqlc compile
Lints the SQL queries to check for common mistakes and best practices. This command helps ensure your SQL queries are optimized and follow good conventions.
sqlc vet
Generates shell completion scripts for bash, zsh, fish, and PowerShell. This command helps with auto-completion of SQLC commands in the terminal.
sqlc completion [bash|zsh|fish|powershell]
Prints the current version of SQLC.
sqlc version
SQLC uses a sqlc.yaml
file to configure the code generation process. Below is an example configuration file:
version: "1"
packages:
- path: "db"
queries: "./sql/queries.sql"
schema: "./sql/schema.sql"
engine: "postgresql"
version
: The configuration file version. Always set this to"1"
.packages
: A list of packages to generate.path
: The output directory for the generated Go code.queries
: The path to the file containing SQL queries.schema
: The path to the file containing the database schema.engine
: The SQL database engine (e.g.,postgresql
,mysql
,sqlite
).
-
Initialize a new SQLC project:
sqlc init
-
Define SQL queries in
queries.sql
:-- name: GetUserByID :one SELECT id, name, email FROM users WHERE id = $1;
-
Define the database schema in
schema.sql
:CREATE TABLE users ( id SERIAL PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL );
-
Configure SQLC in
sqlc.yaml
:version: "1" packages: - path: "db" queries: "./sql/queries.sql" schema: "./sql/schema.sql" engine: "postgresql"
-
Generate Go code:
sqlc generate
-
Use the generated code in your Go application:
package main import ( "context" "log" "your_project/db" ) func main() { // Assuming db.Conn is your database connection q := db.New(db.Conn) user, err := q.GetUserByID(context.Background(), 1) if err != nil { log.Fatal(err) } log.Printf("User: %+v\n", user) }