### Install and configure MySQL natively Source: https://github.com/sqlc-dev/sqlc/blob/main/internal/endtoend/CLAUDE.md Pre-configure the MySQL root password with debconf, install mysql-server, start the service, and verify the connection with a simple query. ```bash echo "mysql-server mysql-server/root_password password mysecretpassword" | sudo debconf-set-selections ``` ```bash echo "mysql-server mysql-server/root_password_again password mysecretpassword" | sudo debconf-set-selections ``` ```bash sudo DEBIAN_FRONTEND=noninteractive apt-get install -y mysql-server ``` ```bash sudo service mysql start ``` ```bash mysql -uroot -pmysecretpassword -e "SELECT 1;" ``` -------------------------------- ### Install and configure PostgreSQL natively Source: https://github.com/sqlc-dev/sqlc/blob/main/internal/endtoend/CLAUDE.md Install PostgreSQL, start the service, set the postgres user password to 'postgres', locate the hba_file, and reload the configuration after adding md5 authentication for localhost. ```bash sudo DEBIAN_FRONTEND=noninteractive apt-get install -y postgresql postgresql-contrib ``` ```bash sudo service postgresql start ``` ```bash sudo -u postgres psql -c "ALTER USER postgres PASSWORD 'postgres';" ``` ```bash sudo -u postgres psql -t -c "SHOW hba_file;" ``` ```bash sudo service postgresql reload ``` -------------------------------- ### Run full test suite with Docker Source: https://github.com/sqlc-dev/sqlc/blob/main/CLAUDE.md Starts Docker services and runs the full test suite with the 'examples' build tag and a 20-minute timeout. For local development. ```bash docker compose up -d go test --tags=examples -timeout 20m ./... ``` -------------------------------- ### Start databases with sqlc-test-setup Source: https://github.com/sqlc-dev/sqlc/blob/main/CLAUDE.md Starts the configured databases for local development and testing. This command verifies connections and skips already running services. ```bash go run ./cmd/sqlc-test-setup start ``` -------------------------------- ### Run examples tests Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/guides/development.md Execute tests within the examples module using the examples tag. ```bash cd examples && go test --tags=examples ./... ``` -------------------------------- ### Run full test suite without Docker Source: https://github.com/sqlc-dev/sqlc/blob/main/CLAUDE.md Installs and starts test dependencies using sqlc-test-setup, then runs the full test suite. For remote or CI environments. ```bash go run ./cmd/sqlc-test-setup install go run ./cmd/sqlc-test-setup start go test --tags=examples -timeout 20m ./... ``` -------------------------------- ### Install databases with sqlc-test-setup Source: https://github.com/sqlc-dev/sqlc/blob/main/CLAUDE.md Installs necessary database dependencies for testing. This command is idempotent and safe to re-run. ```bash go run ./cmd/sqlc-test-setup install ``` -------------------------------- ### Install sqlc on Ubuntu with Snap Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/overview/install.md Use Snap to install sqlc on Ubuntu. ```bash sudo snap install sqlc ``` -------------------------------- ### Install sqlc with go install Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/overview/install.md Install sqlc using Go's install command. Requires Go 1.21 or later. ```bash go install github.com/sqlc-dev/sqlc/cmd/sqlc@latest ``` -------------------------------- ### Build sqlc locally Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/guides/development.md Build the sqlc binary and install it as sqlc-dev. ```bash go build -o ~/go/bin/sqlc-dev ./cmd/sqlc ``` -------------------------------- ### Fetch driver and build Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/tutorials/getting-started-sqlite.md Install the required SQLite driver and build the Go application. ```shell go get modernc.org/sqlite go build . ``` -------------------------------- ### Example vet rules using EXPLAIN output Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/vet.md Example sqlc vet rules that use postgresql.explain and mysql.explain to check query cost and plan characteristics. ```yaml ... rules: - name: postgresql-query-too-costly message: "Query cost estimate is too high" rule: "postgresql.explain.plan.total_cost > 1.0" - name: postgresql-no-seq-scan message: "Query plan results in a sequential scan" rule: "postgresql.explain.plan.node_type == 'Seq Scan'" - name: mysql-query-too-costly message: "Query cost estimate is too high" rule: "has(mysql.explain.query_block.cost_info) && double(mysql.explain.query_block.cost_info.query_cost) > 2.0" - name: mysql-must-use-primary-key message: "Query plan doesn't use primary key" rule: "has(mysql.explain.query_block.table.key) && mysql.explain.query_block.table.key != 'PRIMARY'" ``` -------------------------------- ### Example query.sql for sqlc analyze Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/analyze.md Example query selecting all columns from authors where id matches a parameter. Used with the schema.sql example. ```sql -- name: GetAuthor :one SELECT * FROM authors WHERE id = $1; ``` -------------------------------- ### Install sqlc on macOS with Homebrew Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/overview/install.md Use Homebrew to install sqlc on macOS. ```bash brew install sqlc ``` -------------------------------- ### Running sqlc analyze on example files Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/analyze.md Command to run sqlc analyze with the postgresql dialect on the example schema.sql and query.sql files. ```sh sqlc analyze --dialect postgresql --schema schema.sql query.sql ``` -------------------------------- ### Start database containers Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/guides/development.md Launch required database instances using Docker Compose. ```bash docker compose up -d ``` -------------------------------- ### Golang-migrate up and down files Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/ddl.md Example of separate up and down migration files for golang-migrate. ```sql CREATE TABLE post ( id int NOT NULL, title text, body text, PRIMARY KEY(id) ); ``` ```sql DROP TABLE post; ``` -------------------------------- ### Create production tables Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/verify.md Defines the `users` and `user_actions` tables used in the example scenario. ```sql CREATE TABLE users ( id UUID PRIMARY KEY ); CREATE TABLE user_actions ( id UUID PRIMARY KEY, user_id UUID NOT NULL, action TEXT, created_at TIMESTAMP ); ``` -------------------------------- ### Go program using generated tutorial package Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/tutorials/getting-started-mysql.md A complete Go program that opens a MySQL connection, creates a tutorial client, and performs list, create, and get operations. It requires the MySQL driver and correct database credentials. ```go package main import ( "context" "database/sql" "log" "reflect" _ "github.com/go-sql-driver/mysql" "tutorial.sqlc.dev/app/tutorial" ) func run() error { ctx := context.Background() db, err := sql.Open("mysql", "user:password@/dbname?parseTime=true") if err != nil { return err } queries := tutorial.New(db) // list all authors authors, err := queries.ListAuthors(ctx) if err != nil { return err } log.Println(authors) // create an author result, err := queries.CreateAuthor(ctx, tutorial.CreateAuthorParams{ Name: "Brian Kernighan", Bio: sql.NullString{String: "Co-author of The C Programming Language and The Go Programming Language", Valid: true}, }) if err != nil { return err } insertedAuthorID, err := result.LastInsertId() if err != nil { return err } log.Println(insertedAuthorID) // get the author we just inserted fetchedAuthor, err := queries.GetAuthor(ctx, insertedAuthorID) if err != nil { return err } // prints true log.Println(reflect.DeepEqual(insertedAuthorID, fetchedAuthor.ID)) return nil } func main() { if err := run(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Example schema.sql for sqlc analyze Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/analyze.md Example schema defining an authors table with id, name, and bio columns. Used with the query.sql example. ```sql CREATE TABLE authors ( id BIGSERIAL PRIMARY KEY, name text NOT NULL, bio text ); ``` -------------------------------- ### Dbmate migration file Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/ddl.md Example of up and down migrations for Dbmate. ```sql -- migrate:up CREATE TABLE foo (bar INT NOT NULL); -- migrate:down DROP TABLE foo; ``` -------------------------------- ### Example trace log output Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/reference/environment-variables.md An example of the execution time log generated by the trace tool. ```text 0.000043897 . 1 task sqlc (id 1, parent 0) created 0.000144923 . 101026 1 region generate started (duration: 47.619781ms) 0.001048975 . 904052 1 region package started (duration: 14.588456ms) 0.001054616 . 5641 1 name=authors dir=/Users/kyle/projects/sqlc/examples/python language=python 0.001071257 . 16641 1 region parse started (duration: 7.966549ms) 0.009043960 . 7972703 1 region codegen started (duration: 6.587086ms) 0.009171704 . 127744 1 new goroutine 35: text/template/parse.lex·dwrap·1 0.010361654 . 1189950 1 new goroutine 36: text/template/parse.lex·dwrap·1 0.015641815 . 5280161 1 region package started (duration: 10.904938ms) 0.015644943 . 3128 1 name=booktest dir=/Users/kyle/projects/sqlc/examples/python language=python 0.015647431 . 2488 1 region parse started (duration: 4.207749ms) 0.019860308 . 4212877 1 region codegen started (duration: 6.681624ms) 0.020028488 . 168180 1 new goroutine 37: text/template/parse.lex·dwrap·1 0.021020310 . 991822 1 new goroutine 8: text/template/parse.lex·dwrap·1 0.026551163 . 5530853 1 region package started (duration: 9.217294ms) 0.026554368 . 3205 1 name=jets dir=/Users/kyle/projects/sqlc/examples/python language=python 0.026556804 . 2436 1 region parse started (duration: 3.491005ms) 0.030051911 . 3495107 1 region codegen started (duration: 5.711931ms) 0.030213937 . 162026 1 new goroutine 20: text/template/parse.lex·dwrap·1 0.031099938 . 886001 1 new goroutine 38: text/template/parse.lex·dwrap·1 0.035772637 . 4672699 1 region package started (duration: 10.267039ms) 0.035775688 . 3051 1 name=ondeck dir=/Users/kyle/projects/sqlc/examples/python language=python 0.035778150 . 2462 1 region parse started (duration: 4.094518ms) 0.039877181 . 4099031 1 region codegen started (duration: 6.156341ms) 0.040010771 . 133590 1 new goroutine 39: text/template/parse.lex·dwrap·1 0.040894567 . 883796 1 new goroutine 40: text/template/parse.lex·dwrap·1 0.046042779 . 5148212 1 region writefiles started (duration: 1.718259ms) 0.047767781 . 1725002 1 task end ``` -------------------------------- ### Sql-migrate migration file Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/ddl.md Example of up and down migrations for sql-migrate. ```sql -- +migrate Up -- SQL in section 'Up' is executed when this migration is applied CREATE TABLE people (id int); -- +migrate Down -- SQL section 'Down' is executed when this migration is rolled back DROP TABLE people; ``` -------------------------------- ### Go implementation for prepared queries Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/prepared_query.md Example Go code demonstrating how to manage prepared statements using the generated Queries struct and DBTX interface. ```go package db import ( "context" "database/sql" "fmt" ) type Record struct { ID int32 } type DBTX interface { PrepareContext(context.Context, string) (*sql.Stmt, error) QueryRowContext(context.Context, string, ...any) *sql.Row } func New(db DBTX) *Queries { return &Queries{db: db} } func Prepare(ctx context.Context, db DBTX) (*Queries, error) { q := Queries{db: db} var err error if q.getRecordStmt, err = db.PrepareContext(ctx, getRecord); err != nil { return nil, fmt.Errorf("error preparing query GetRecord: %w", err) } return &q, nil } func (q *Queries) queryRow(ctx context.Context, stmt *sql.Stmt, query string, args ...any) *sql.Row { switch { case stmt != nil && q.tx != nil: return q.tx.StmtContext(ctx, stmt).QueryRowContext(ctx, args...) case stmt != nil: return stmt.QueryRowContext(ctx, args...) default: return q.db.QueryRowContext(ctx, query, args...) } } type Queries struct { db DBTX tx *sql.Tx getRecordStmt *sql.Stmt } func (q *Queries) WithTx(tx *sql.Tx) *Queries { return &Queries{ db: tx, tx: tx, getRecordStmt: q.getRecordStmt, } } const getRecord = `-- name: GetRecord :one SELECT id FROM records WHERE id = $1 ` func (q *Queries) GetRecord(ctx context.Context, id int32) (int32, error) { row := q.queryRow(ctx, q.getRecordStmt, getRecord, id) err := row.Scan(&id) return id, err } ``` -------------------------------- ### Fetch PostgreSQL driver with go get and build Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/tutorials/getting-started-postgresql.md Commands to fetch the pgx/v5 driver and build the Go program. Required before the program will compile. ```shell go get github.com/jackc/pgx/v5 go build . ``` -------------------------------- ### Format SQL query files Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/fmt.md An example of a raw SQL query file and its canonical representation after running sqlc fmt. ```sql -- name: GetAuthor :one select id,name , bio from authors where id = ? limit 1; -- name: SearchAuthors :many SELECT id, -- the primary key name, bio, created_at FROM authors WHERE name LIKE ? AND bio IS NOT NULL AND id > ? AND created_at > ? AND name <> ? ORDER BY name; ``` ```sql -- name: GetAuthor :one SELECT id, name, bio FROM authors WHERE id = ? LIMIT 1; -- name: SearchAuthors :many SELECT id, -- the primary key name, bio, created_at FROM authors WHERE name LIKE ? AND bio IS NOT NULL AND id > ? AND created_at > ? AND name <> ? ORDER BY name; ``` -------------------------------- ### Goose migration file Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/ddl.md Example of up and down migrations in a single file for Goose. ```sql -- +goose Up CREATE TABLE post ( id int NOT NULL, title text, body text, PRIMARY KEY(id) ); -- +goose Down DROP TABLE post; ``` -------------------------------- ### Current package configuration (YAML) Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/guides/migrating-to-sqlc-gen-kotlin.md Example of existing package configuration using the built-in Kotlin generator in YAML format. ```yaml sql: - schema: "schema.sql" queries: "query.sql" engine: "postgresql" gen: kotlin: out: "src/main/kotlin/com/example/foo" package: "com.example.foo" ``` -------------------------------- ### Build sqlc-gen-json Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/guides/development.md Build and install the sqlc-gen-json tool to prevent test failures. ```bash go build -o ~/go/bin/sqlc-gen-json ./cmd/sqlc-gen-json ``` -------------------------------- ### Tern migration file Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/ddl.md Example of up and down migrations separated by a delimiter for Tern. ```sql CREATE TABLE comment (id int NOT NULL, text text NOT NULL); ---- create above / drop below ---- DROP TABLE comment; ``` -------------------------------- ### Current package configuration (JSON) Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/guides/migrating-to-sqlc-gen-kotlin.md Example of existing package configuration using the built-in Kotlin generator in JSON format. ```json "sql": [ { "schema": "schema.sql", "queries": "query.sql", "engine": "postgresql", "gen": { "kotlin": { "out": "src/main/kotlin/com/example/foo", "package": "com.example.foo" } } } ] ``` -------------------------------- ### Finding All Tables in a Statement Source: https://github.com/sqlc-dev/sqlc/blob/main/internal/sql/astutils/CLAUDE.md Example usage of Walk to populate a visitor with RangeVar nodes from a statement's FromClause. ```go var tv tableVisitor astutils.Walk(&tv, stmt.FromClause) // tv.list now contains all RangeVar nodes ``` -------------------------------- ### Define database schema with DDL Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/ddl.md Example of CREATE and ALTER TABLE statements parsed by sqlc. ```sql CREATE TABLE authors ( id SERIAL PRIMARY KEY, birth_year int NOT NULL ); ALTER TABLE authors ADD COLUMN bio text NOT NULL; ALTER TABLE authors DROP COLUMN birth_year; ALTER TABLE authors RENAME TO writers; ``` -------------------------------- ### Golang-migrate lexicographic ordering warning Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/ddl.md Examples of incorrect and correct numeric filename padding for lexicographic ordering. ```text 1_initial.up.sql ... 9_foo.up.sql # this migration file will be parsed BEFORE 9_foo 10_bar.up.sql ``` ```text 001_initial.up.sql ... 009_foo.up.sql 010_bar.up.sql ``` -------------------------------- ### Configure apt to use HTTP proxy Source: https://github.com/sqlc-dev/sqlc/blob/main/internal/endtoend/CLAUDE.md Before installing packages, verify the HTTP_PROXY variable is set. Then write the proxy configuration to /etc/apt/apt.conf.d/99proxy using a heredoc, and refresh package lists. ```bash echo $HTTP_PROXY ``` ```bash sudo tee /etc/apt/apt.conf.d/99proxy << EOF Acquire::http::Proxy "$HTTP_PROXY"; Acquire::https::Proxy "$HTTPS_PROXY"; EOF ``` ```bash sudo apt-get update -qq ``` -------------------------------- ### Atlas migration schema Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/ddl.md Example of a table definition for Atlas. ```sql -- Create "post" table CREATE TABLE "public"."post" ("id" integer NOT NULL, "title" text NULL, "body" text NULL, PRIMARY KEY ("id")); ``` -------------------------------- ### GitHub Actions configuration for sqlc vet Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/ci-cd.md This workflow runs sqlc vet on every push. It includes a PostgreSQL setup step, which is required if the configuration references the sqlc/db-prepare lint rule. ```yaml name: sqlc on: [push] jobs: vet: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: sqlc-dev/setup-sqlc@v3 with: sqlc-version: '1.31.1' # Start a PostgreSQL server - uses: sqlc-dev/action-setup-postgres@master with: postgres-version: "16" id: postgres - run: sqlc vet env: POSTGRESQL_SERVER_URI: ${{ steps.postgres.outputs.connection-uri }}?sslmode=disable ``` -------------------------------- ### Manage Docker database containers Source: https://github.com/sqlc-dev/sqlc/blob/main/CLAUDE.md Commands to check the status of and start Docker containers for database testing. ```bash docker compose ps docker compose up -d ``` -------------------------------- ### Configuration with dummy rule to debug EXPLAIN output Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/vet.md Example sqlc configuration that uses a dummy rule to trigger EXPLAIN output for debugging with SQLCDEBUG=dumpexplain=1. ```yaml version: 2 sql: - schema: "query.sql" queries: "query.sql" engine: "postgresql" database: uri: "postgresql://postgres:postgres@localhost:5432/postgres" gen: go: package: "db" out: "db" rules: - debug rules: - name: debug rule: "!has(postgresql.explain)" # A dummy rule to trigger explain ``` -------------------------------- ### SQLCEXPERIMENT examples for enabling and disabling experiments Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/reference/environment-variables.md Shows how to set the SQLCEXPERIMENT environment variable to enable or disable experiments. Use a comma-separated list of experiment names, and prefix with 'no' to explicitly disable an experiment. ```bash SQLCEXPERIMENT=foo,bar # enable foo and bar experiments SQLCEXPERIMENT=nofoo # explicitly disable foo experiment SQLCEXPERIMENT=foo,nobar # enable foo, disable bar ``` -------------------------------- ### Select Statement Conversion Method Source: https://github.com/sqlc-dev/sqlc/blob/main/internal/engine/dolphin/CLAUDE.md Example of a converter method mapping a Marino SelectStmt to a sqlc AST SelectStmt. ```go func (c *cc) convertSelectStmt(n *pcast.SelectStmt) *ast.SelectStmt { return &ast.SelectStmt{ FromClause: c.convertTableRefsClause(n.From), WhereClause: c.convert(n.Where), // ... } } ``` -------------------------------- ### Create authors table Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/delete.md SQL schema for the authors table used in the delete example. ```sql CREATE TABLE authors ( id SERIAL PRIMARY KEY, bio text NOT NULL ); ``` -------------------------------- ### Rewriting Nodes In Place Source: https://github.com/sqlc-dev/sqlc/blob/main/internal/sql/astutils/CLAUDE.md Example usage of Apply to replace specific AST nodes during traversal. ```go astutils.Apply(root, func(cr *astutils.Cursor) bool { if _, ok := cr.Node().(*ast.SomeType); ok { cr.Replace(&ast.OtherType{}) } return true }, nil) ``` -------------------------------- ### Version 2 configuration with multiple engines Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/reference/config.md Example of a version 2 sqlc configuration file with two query sets, one for PostgreSQL and one for MySQL, each with their own schema, queries, engine, and Go code generation settings. The PostgreSQL set also includes a managed database and a rule for sqlc vet. ```yaml version: "2" cloud: project: "" sql: - schema: "postgresql/schema.sql" queries: "postgresql/query.sql" engine: "postgresql" gen: go: package: "authors" out: "postgresql" database: managed: true rules: - sqlc/db-prepare - schema: "mysql/schema.sql" queries: "mysql/query.sql" engine: "mysql" gen: go: package: "authors" out: "mysql" ``` -------------------------------- ### Run end-to-end tests with extended timeout Source: https://github.com/sqlc-dev/sqlc/blob/main/CLAUDE.md Execute end-to-end tests with a 20-minute timeout and the examples tag. ```bash go test -timeout 20m --tags=examples ./... ``` -------------------------------- ### Generate and test dialect seeds Source: https://github.com/sqlc-dev/sqlc/blob/main/CLAUDE.md Commands to install database binaries, run dialect verification tests, and regenerate files after changes. ```bash cd internal/goldeneye go run ./cmd/goldeneye install clickhouse # download the pinned clickhouse binary once go run ./cmd/goldeneye install duckdb # download the current DuckDB 2.0 preview build once go run ./cmd/goldeneye install sqlite # build the pinned sqlite3 shells once; needs a C compiler POSTGRESQL_SERVER_URI="postgres://postgres:postgres@127.0.0.1:5432/postgres?sslmode=disable" \ MYSQL_SERVER_URI="root:mysecretpassword@tcp(127.0.0.1:3306)/mysql" \ MSSQL_SERVER_URI="sqlserver://sa:Mysecretpassword1!@127.0.0.1:1433?encrypt=disable" \ SPANNER_SERVER_URI="localhost:15000" go test ./... go run ./cmd/goldeneye generate postgresql # rewrite the files after a change ``` -------------------------------- ### Generated Go database access methods Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/select.md Example of the generated Go code including the Author struct, DBTX interface, and Queries methods. ```go package db import ( "context" "database/sql" ) type Author struct { ID int Bio string BirthYear int } type DBTX interface { QueryContext(context.Context, string, ...any) (*sql.Rows, error) QueryRowContext(context.Context, string, ...any) *sql.Row } func New(db DBTX) *Queries { return &Queries{db: db} } type Queries struct { db DBTX } const getAuthor = `-- name: GetAuthor :one SELECT id, bio, birth_year FROM authors WHERE id = $1 ` func (q *Queries) GetAuthor(ctx context.Context, id int) (Author, error) { row := q.db.QueryRowContext(ctx, getAuthor, id) var i Author err := row.Scan(&i.ID, &i.Bio, &i.BirthYear) return i, err } const listAuthors = `-- name: ListAuthors :many SELECT id, bio, birth_year FROM authors ORDER BY id ` func (q *Queries) ListAuthors(ctx context.Context) ([]Author, error) { rows, err := q.db.QueryContext(ctx, listAuthors) if err != nil { return nil, err } defer rows.Close() var items []Author for rows.Next() { var i Author if err := rows.Scan(&i.ID, &i.Bio, &i.BirthYear); err != nil { return nil, err } items = append(items, i) } if err := rows.Close(); err != nil { return nil, err } if err := rows.Err(); err != nil { return nil, err } return items, nil } ``` -------------------------------- ### Initialize Go module Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/tutorials/getting-started-postgresql.md Run this command in a new directory to initialize a Go module named tutorial.sqlc.dev/app. ```shell go mod init tutorial.sqlc.dev/app ``` -------------------------------- ### Go program using generated tutorial package Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/tutorials/getting-started-postgresql.md A complete Go program that connects to PostgreSQL using pgx/v5, creates an author, fetches it, and verifies equality. Requires the tutorial package generated by sqlc and a database with the authors table. ```go package main import ( "context" "log" "reflect" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" "tutorial.sqlc.dev/app/tutorial" ) func run() error { ctx := context.Background() conn, err := pgx.Connect(ctx, "user=pqgotest dbname=pqgotest sslmode=verify-full") if err != nil { return err } defer conn.Close(ctx) queries := tutorial.New(conn) // list all authors authors, err := queries.ListAuthors(ctx) if err != nil { return err } log.Println(authors) // create an author insertedAuthor, err := queries.CreateAuthor(ctx, tutorial.CreateAuthorParams{ Name: "Brian Kernighan", Bio: pgtype.Text{String: "Co-author of The C Programming Language and The Go Programming Language", Valid: true}, }) if err != nil { return err } log.Println(insertedAuthor) // get the author we just inserted fetchedAuthor, err := queries.GetAuthor(ctx, insertedAuthor.ID) if err != nil { return err } // prints true log.Println(reflect.DeepEqual(insertedAuthor, fetchedAuthor)) return nil } func main() { if err := run(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Use generated code in Go Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/tutorials/getting-started-sqlite.md Create a tutorial.go file to demonstrate using the generated tutorial package to interact with the database. ```go package main import ( "context" "database/sql" _ "embed" "log" "reflect" _ "modernc.org/sqlite" "tutorial.sqlc.dev/app/tutorial" ) //go:embed schema.sql var ddl string func run() error { ctx := context.Background() db, err := sql.Open("sqlite", ":memory:") if err != nil { return err } // create tables if _, err := db.ExecContext(ctx, ddl); err != nil { return err } queries := tutorial.New(db) // list all authors authors, err := queries.ListAuthors(ctx) if err != nil { return err } log.Println(authors) // create an author insertedAuthor, err := queries.CreateAuthor(ctx, tutorial.CreateAuthorParams{ Name: "Brian Kernighan", Bio: sql.NullString{String: "Co-author of The C Programming Language and The Go Programming Language", Valid: true}, }) if err != nil { return err } log.Println(insertedAuthor) // get the author we just inserted fetchedAuthor, err := queries.GetAuthor(ctx, insertedAuthor.ID) if err != nil { return err } // prints true log.Println(reflect.DeepEqual(insertedAuthor, fetchedAuthor)) return nil } func main() { if err := run(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Create query.sql with five queries Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/tutorials/getting-started-postgresql.md Create a query.sql file with these five queries: GetAuthor, ListAuthors, CreateAuthor, UpdateAuthor, and DeleteAuthor. ```sql -- name: GetAuthor :one SELECT * FROM authors WHERE id = $1 LIMIT 1; -- name: ListAuthors :many SELECT * FROM authors ORDER BY name; -- name: CreateAuthor :one INSERT INTO authors ( name, bio ) VALUES ( $1, $2 ) RETURNING *; -- name: UpdateAuthor :exec UPDATE authors set name = $2, bio = $3 WHERE id = $1; -- name: DeleteAuthor :exec DELETE FROM authors WHERE id = $1; ``` -------------------------------- ### Building Development Binaries Source: https://github.com/sqlc-dev/sqlc/blob/main/CLAUDE.md Commands to build the main sqlc binary and the JSON plugin for local development. ```bash # Build main sqlc binary for development go build -o ~/go/bin/sqlc-dev ./cmd/sqlc # Build JSON plugin (required for some tests) go build -o ~/go/bin/sqlc-gen-json ./cmd/sqlc-gen-json ``` -------------------------------- ### Fetch MySQL driver and build Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/tutorials/getting-started-mysql.md Commands to download the MySQL driver and compile the Go program. The program should compile without errors. ```shell go get github.com/go-sql-driver/mysql go build . ``` -------------------------------- ### Using WithTx with database/sql driver Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/transactions.md Shows how to use WithTx with the database/sql driver (github/lib/pq). It begins a transaction, creates a new Queries instance with the transaction, performs GetRecord and UpdateRecord, and commits. ```go // Using `github/lib/pq` as the driver. func bumpCounter(ctx context.Context, db *sql.DB, queries *tutorial.Queries, id int32) error { tx, err := db.Begin() if err != nil { return err } defer tx.Rollback() qtx := queries.WithTx(tx) r, err := qtx.GetRecord(ctx, id) if err != nil { return err } if err := qtx.UpdateRecord(ctx, tutorial.UpdateRecordParams{ ID: r.ID, Counter: r.Counter + 1, }); err != nil { return err } return tx.Commit() } ``` -------------------------------- ### Verify queries with sqlc verify Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/tutorials/getting-started-postgresql.md Run sqlc verify against the 'tutorial' tag to ensure previously published queries work with updated schema. ```shell $ sqlc verify --against tutorial ``` -------------------------------- ### Define authors table schema Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/select.md The SQL schema definition for the authors table used in the examples. ```sql CREATE TABLE authors ( id SERIAL PRIMARY KEY, bio text NOT NULL, birth_year int NOT NULL ); ``` -------------------------------- ### Goose lexicographic ordering warning Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/ddl.md Examples of incorrect and correct numeric filename padding for Goose. ```text 1_initial.sql ... 9_foo.sql # this migration file will be parsed BEFORE 9_foo 10_bar.sql ``` ```text 001_initial.sql ... 009_foo.sql 010_bar.sql ``` -------------------------------- ### Publish queries with sqlc push Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/tutorials/getting-started-postgresql.md Publish your queries to sqlc Cloud using the sqlc push command with the tag 'tutorial'. ```shell $ sqlc push --tag tutorial ``` -------------------------------- ### Basic sqlc.yaml configuration for generate Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/generate.md Minimal configuration for sqlc generate with PostgreSQL, specifying queries and schema files, and Go code generation with package 'tutorial' and output directory 'tutorial' using pgx/v5. ```yaml version: "2" sql: - engine: "postgresql" queries: "query.sql" schema: "schema.sql" gen: go: package: "tutorial" out: "tutorial" sql_package: "pgx/v5" ``` -------------------------------- ### Schema for students and test scores Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/embedding.md Defines the students and test_scores tables used in the embedding examples. ```sql CREATE TABLE students ( id bigserial PRIMARY KEY, name text NOT NULL, age integer NOT NULL ); CREATE TABLE test_scores ( student_id bigint NOT NULL, score integer NOT NULL, grade text NOT NULL ); ``` -------------------------------- ### Initialize and add to ParamSet Source: https://github.com/sqlc-dev/sqlc/blob/main/internal/sql/named/CLAUDE.md Demonstrates creating a new ParamSet and adding a parameter to it, which returns the placeholder number. ```go ps := named.NewParamSet(numbersAlreadyUsed, hasNamedSupport) n := ps.Add(named.NewParam("author_id")) // returns the placeholder number ``` -------------------------------- ### Debugging Panic Message Source: https://github.com/sqlc-dev/sqlc/blob/main/internal/sql/astutils/CLAUDE.md Example of the panic message encountered when a node type is not handled in both walk.go and rewrite.go. ```text panic: walk: unexpected node type *ast.SomeType ``` -------------------------------- ### PostgreSQL slice parameter SQL Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/select.md Example schema and query using the ANY operator for PostgreSQL slice parameters. ```sql CREATE TABLE authors ( id SERIAL PRIMARY KEY, bio text NOT NULL, birth_year int NOT NULL ); -- name: ListAuthorsByIDs :many SELECT * FROM authors WHERE id = ANY($1::int[]); ``` -------------------------------- ### Directory structure after generation Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/tutorials/getting-started-postgresql.md Shows the expected file layout after running sqlc generate, including the generated tutorial package with db.go, models.go, and query.sql.go. ```text ├── go.mod ├── query.sql ├── schema.sql ├── sqlc.yaml └── tutorial ├── db.go ├── models.go └── query.sql.go ``` -------------------------------- ### Configure sqlc.yaml Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/tutorials/getting-started-mysql.md Create a sqlc.yaml file to define the MySQL engine, query and schema file paths, and Go output settings. ```yaml version: "2" sql: - engine: "mysql" queries: "query.sql" schema: "schema.sql" gen: go: package: "tutorial" out: "tutorial" ``` -------------------------------- ### MySQL and SQLite slice parameter SQL Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/select.md Example schema and query using the sqlc.slice() meta-function for MySQL and SQLite. ```sql CREATE TABLE authors ( id SERIAL PRIMARY KEY, bio text NOT NULL, birth_year int NOT NULL ); -- name: ListAuthorsByIDs :many SELECT * FROM authors WHERE id IN (sqlc.slice('ids')); ``` -------------------------------- ### SQL schema and query definition Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/prepared_query.md Example SQL schema and a query definition that will be used to generate prepared statement code. ```sql CREATE TABLE records ( id SERIAL PRIMARY KEY ); -- name: GetRecord :one SELECT * FROM records WHERE id = $1; ``` -------------------------------- ### Default positional parameter generation Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/named_parameters.md Example of SQL generating less than ideal parameter names in the resulting Go struct. ```sql -- name: UpsertAuthorName :one UPDATE author SET name = CASE WHEN $1::bool THEN $2::text ELSE name END RETURNING *; ``` ```go type UpdateAuthorNameParams struct { Column1 bool `json:""` Column2_2 string `json:"_2"` } ``` -------------------------------- ### Enable coreanalyzer experiment Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/reference/environment-variables.md Sets the SQLCEXPERIMENT environment variable to enable the coreanalyzer experiment, which routes sqlc generate through the core catalog and analyzer. ```bash SQLCEXPERIMENT=coreanalyzer ``` -------------------------------- ### Set SQLC_AUTH_TOKEN environment variable Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/push.md Create an auth token and make it available via the SQLC_AUTH_TOKEN environment variable. ```shell export SQLC_AUTH_TOKEN=sqlc_xxxxxxxx ``` -------------------------------- ### MySQL sqlc configuration for CopyFrom Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/insert.md Configuration file for MySQL using database/sql. ```yaml version: "2" sql: - engine: "mysql" queries: "query.sql" schema: "query.sql" gen: go: package: "db" sql_package: "database/sql" sql_driver: "github.com/go-sql-driver/mysql" out: "db" ``` -------------------------------- ### Apply Unexpected Node Type Panic Source: https://github.com/sqlc-dev/sqlc/blob/main/internal/sql/astutils/CLAUDE.md Example of the panic message triggered when a node type is missing from the rewrite.go switch statement. ```text panic: Apply: unexpected node type *ast.YourNewType ``` -------------------------------- ### Walk Unexpected Node Type Panic Source: https://github.com/sqlc-dev/sqlc/blob/main/internal/sql/astutils/CLAUDE.md Example of the panic message triggered when a node type is missing from the walk.go switch statement. ```text panic: walk: unexpected node type *ast.YourNewType ``` -------------------------------- ### Define schema and queries in query.sql Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/guides/using-go-and-pgx.md Create a SQL file containing your table definitions and queries for sqlc to process. ```sql CREATE TABLE authors ( id BIGSERIAL PRIMARY KEY, name text NOT NULL, bio text ); -- name: GetAuthor :one SELECT * FROM authors WHERE id = $1 LIMIT 1; -- name: ListAuthors :many SELECT * FROM authors ORDER BY name; -- name: CreateAuthor :one INSERT INTO authors ( name, bio ) VALUES ( $1, $2 ) RETURNING *; -- name: DeleteAuthor :exec DELETE FROM authors WHERE id = $1; ``` -------------------------------- ### Define tables for struct generation Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/rename.md Example SQL table definitions that result in default struct names like Author and BookPublisher. ```sql CREATE TABLE authors ( id BIGSERIAL PRIMARY KEY, name text NOT NULL, bio text ); CREATE TABLE book_publishers ( id BIGSERIAL PRIMARY KEY, name text NOT NULL ); ``` -------------------------------- ### Using WithTx with pgx driver Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/transactions.md Shows how to use WithTx with the pgx driver (github.com/jackc/pgx/v5). It begins a transaction with context, creates a new Queries instance with the transaction, performs GetRecord and UpdateRecord, and commits with context. ```go // Using `github.com/jackc/pgx/v5` as the driver. func bumpCounter(ctx context.Context, db *pgx.Conn, queries *tutorial.Queries, id int32) error { tx, err := db.Begin(ctx) if err != nil { return err } defer tx.Rollback(ctx) qtx := queries.WithTx(tx) r, err := qtx.GetRecord(ctx, id) if err != nil { return err } if err := qtx.UpdateRecord(ctx, tutorial.UpdateRecordParams{ ID: r.ID, Counter: r.Counter + 1, }); err != nil { return err } return tx.Commit(ctx) } ``` -------------------------------- ### SQL schema for records table Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/transactions.md Defines the records table with an id and counter column. Used as the database schema for the transaction examples. ```sql CREATE TABLE records ( id SERIAL PRIMARY KEY, counter INT NOT NULL ); ``` -------------------------------- ### Configure sqlc/db-prepare with a database URI Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/vet.md YAML configuration for sqlc vet to run the built-in sqlc/db-prepare rule against a PostgreSQL database. The database must have an up-to-date schema; sqlc does not apply migrations. ```yaml version: 2 sql: - schema: "schema.sql" queries: "query.sql" engine: "postgresql" gen: go: package: "authors" out: "db" database: uri: "postgresql://postgres:password@localhost:5432/postgres" rules: - sqlc/db-prepare ``` -------------------------------- ### Run project tests Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/guides/development.md Execute the standard test suite for the project. ```bash go test ./... ``` -------------------------------- ### SQL table definition for JSON tags example Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/structs.md Defines an 'authors' table with 'id' and 'created_at' columns. Used to illustrate JSON tag generation. ```sql CREATE TABLE authors ( id SERIAL PRIMARY KEY, created_at timestamp NOT NULL ); ``` -------------------------------- ### Verify against a tag placeholder Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/verify.md Command to run `sqlc verify` with a tag placeholder, showing the general syntax. ```shell $ sqlc verify --against [tag] ``` -------------------------------- ### Run full test suite Source: https://github.com/sqlc-dev/sqlc/blob/main/CLAUDE.md Executes the full test suite. Requires the databases to be running beforehand. ```bash # Full test suite (requires databases running) go test --tags=examples -timeout 20m ./... ``` -------------------------------- ### Database URI with environment variable Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/reference/config.md Example of using a database URI with environment variable reference. The connection string uses ${PG_PASSWORD} to set the password from the environment variable. ```yaml version: '2' sql: - schema: schema.sql queries: query.sql engine: postgresql database: uri: postgresql://postgres:${PG_PASSWORD}@localhost:5432/authors gen: go: package: authors out: postgresql ``` -------------------------------- ### SQL queries for GetRecord and UpdateRecord Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/transactions.md Defines the named queries GetRecord and UpdateRecord used in the transaction examples. GetRecord fetches a record by id, UpdateRecord updates the counter. ```sql -- name: GetRecord :one SELECT * FROM records WHERE id = $1; -- name: UpdateRecord :exec UPDATE records SET counter = $2 WHERE id = $1; ``` -------------------------------- ### SQL table definition for singular naming example Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/structs.md Defines an 'authors' table with columns 'id' and 'name'. Used to illustrate how sqlc generates a struct with a singular name. ```sql CREATE TABLE authors ( id SERIAL PRIMARY KEY, name text NOT NULL ); ``` -------------------------------- ### Implement MySQL TypeName and Param formatting in format.go Source: https://github.com/sqlc-dev/sqlc/blob/main/internal/engine/dolphin/CLAUDE.md Defines how MySQL types are mapped and how parameters are represented using the '?' placeholder. ```go func (p *Parser) TypeName(ns, name string) string { switch name { case "bigint unsigned": return "UNSIGNED" case "bigint signed": return "SIGNED" } return name } func (p *Parser) Param(n int) string { return "?" // MySQL uses ? for all parameters } ``` -------------------------------- ### JSON output of sqlc analyze for GetAuthor Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/analyze.md Example JSON output showing inferred columns and parameters for the GetAuthor query. Types are reported in lowercase as stored by the catalog. ```json [ { "name": "GetAuthor", "cmd": ":one", "columns": [ { "name": "id", "type": { "name": "bigint" }, "table": "authors" }, { "name": "name", "type": { "name": "text" }, "table": "authors" }, { "name": "bio", "type": { "name": "text", "nullable": true }, "table": "authors" } ], "params": [ { "number": 1, "column": { "name": "id", "type": { "name": "bigint" }, "table": "authors" } } ] } ] ``` -------------------------------- ### Run sqlc fmt command Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/fmt.md The basic usage of the sqlc fmt command. Use the --diff flag to preview changes without modifying files. ```sh sqlc fmt [--diff] ``` -------------------------------- ### Create the node file for VariableExpr Source: https://github.com/sqlc-dev/sqlc/blob/main/internal/sql/ast/CLAUDE.md Define the new AST node structure and implement the Pos and Format methods. ```go package ast type VariableExpr struct { Name string Location int } func (n *VariableExpr) Pos() int { return n.Location } func (n *VariableExpr) Format(buf *TrackedBuffer) { if n == nil { return } buf.WriteString("@") buf.WriteString(n.Name) } ``` -------------------------------- ### Push project to sqlc Cloud Source: https://github.com/sqlc-dev/sqlc/blob/main/docs/howto/push.md Push the project to sqlc Cloud once ready, removing the --dry-run flag. ```shell $ sqlc push ``` -------------------------------- ### Fetch Go modules directly Source: https://github.com/sqlc-dev/sqlc/blob/main/CLAUDE.md Use this command to bypass the Go proxy if you encounter connectivity errors with storage.googleapis.com. ```bash GOPROXY=direct go mod download ```