# sqlc
sqlc is a way to use [[Code generation]] for [[SQL]] and [[ORM]] style code.
From ChatGPT:
---
`sqlc` is a command-line tool that generates type-safe Go code from SQL. It allows you to write queries in raw SQL, and then generates Go code to run those queries. It's a great tool for working with databases in Go because it provides compile-time type safety, auto-completion, and performance benefits.
- **Type-Safe SQL**: `sqlc` generates Go code that is type-safe. This means that if you write a SQL query that selects a string and an integer, `sqlc` will generate a Go struct with a string and an integer field. This gives you compile-time assurance that your SQL queries are correct.
```go
// SQL
CREATE TABLE authors (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL
);
// Generated Go code
type Author struct {
ID int32
Name string
}
```
- **Raw SQL**: With `sqlc`, you write your queries in raw SQL. This means you have the full power of SQL at your disposal, and you don't have to learn a new query language or ORM.
```sql
-- name: GetAuthor :one
SELECT * FROM authors WHERE id = $1 LIMIT 1;
```
- **Performance**: `sqlc` generates code that uses the `database/sql` package in the standard library. This means that the generated code is as performant as hand-written Go code.
```go
func (q *Queries) GetAuthor(ctx context.Context, id int32) (Author, error) {
row := q.db.QueryRowContext(ctx, getAuthor, id)
var i Author
err := row.Scan(&i.ID, &i.Name)
return i, err
}
```
- **Auto-Completion and Tooling**: Because `sqlc` generates Go code, you get all the benefits of Go's tooling. This includes auto-completion, go-to-definition, and automated refactoring.
- **Database Agnostic**: `sqlc` supports multiple databases (PostgreSQL, MySQL). This means you can use the same tool regardless of your database.
---