Convert Figma logo to code with AI

sqlc-dev logosqlc

Generate type-safe code from SQL

12,095
774
12,095
430

Top Related Projects

12,095

Generate type-safe code from SQL

15,960

general purpose extensions to golang's database/sql

Generate a Go ORM tailored to your database schema.

36,491

The fantastic ORM library for Golang, aims to be developer friendly

15,388

An entity framework for Go

38,831

Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB

Quick Overview

sqlc is a tool that generates type-safe Go code from SQL. It takes SQL queries as input and produces fully type-safe code that can be used to interact with a database. sqlc aims to reduce boilerplate and improve the developer experience when working with databases in Go applications.

Pros

  • Generates type-safe Go code from SQL queries, reducing runtime errors
  • Improves developer productivity by eliminating the need to write repetitive database interaction code
  • Supports multiple database engines, including PostgreSQL, MySQL, and SQLite
  • Integrates well with existing Go tooling and workflows

Cons

  • Limited to Go language support (not suitable for other programming languages)
  • Requires learning sqlc-specific syntax and conventions
  • May not cover all complex SQL use cases or advanced database features
  • Generated code can be verbose for simple queries

Code Examples

  1. Defining a SQL query:
-- name: GetAuthor :one
SELECT * FROM authors
WHERE id = $1 LIMIT 1;
  1. Generated Go code for the query:
func (q *Queries) GetAuthor(ctx context.Context, id int64) (Author, error) {
    row := q.db.QueryRowContext(ctx, getAuthor, id)
    var i Author
    err := row.Scan(
        &i.ID,
        &i.Name,
        &i.Bio,
    )
    return i, err
}
  1. Using the generated code in your application:
author, err := queries.GetAuthor(ctx, 1)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Author: %s\n", author.Name)

Getting Started

  1. Install sqlc:

    go install github.com/sqlc-dev/sqlc/cmd/sqlc@latest
    
  2. Create a sqlc.yaml configuration file in your project:

    version: "2"
    sql:
      - engine: "postgresql"
        queries: "query.sql"
        schema: "schema.sql"
        gen:
          go:
            package: "db"
            out: "db"
    
  3. Write your SQL queries in a .sql file and run:

    sqlc generate
    
  4. Use the generated Go code in your application to interact with the database.

Competitor Comparisons

12,095

Generate type-safe code from SQL

Pros of sqlc

  • More active development and frequent updates
  • Larger community and contributor base
  • Extensive documentation and examples

Cons of sqlc

  • Potentially less stable due to frequent changes
  • May have a steeper learning curve for newcomers

Code Comparison

sqlc:

// Name: GetAuthor
// Prepare: true
SELECT * FROM authors
WHERE id = $1 LIMIT 1;

sqlc>:

// Name: GetAuthor
SELECT * FROM authors
WHERE id = ? LIMIT 1;

The main difference in the code examples is the use of $1 in sqlc versus ? in sqlc> for parameter placeholders. Additionally, sqlc includes a // Prepare: true comment, which is absent in the sqlc> example.

Both repositories aim to generate type-safe code from SQL, but sqlc appears to be the more actively maintained and feature-rich option. It offers broader database support and more advanced features. However, sqlc> might be simpler and more straightforward for basic use cases.

The choice between the two depends on specific project requirements, desired features, and the level of community support needed. sqlc is likely the better choice for most users due to its active development and extensive ecosystem.

15,960

general purpose extensions to golang's database/sql

Pros of sqlx

  • Runtime type-safe database operations with compile-time checks
  • Supports multiple database drivers (PostgreSQL, MySQL, SQLite)
  • Flexible API for both simple and complex queries

Cons of sqlx

  • Requires manual SQL writing, which can be error-prone
  • Less static analysis and code generation compared to sqlc
  • May have a steeper learning curve for developers new to SQL

Code Comparison

sqlx:

var users []User
err := sqlx.Select(db, &users, "SELECT * FROM users WHERE status = ?", "active")

sqlc:

users, err := queries.ListActiveUsers(ctx)

Key Differences

sqlx is a runtime SQL toolkit that provides a more flexible approach to database interactions, allowing developers to write raw SQL queries with some added type safety. It's great for projects that require complex queries or need to support multiple database systems.

sqlc, on the other hand, generates type-safe Go code from SQL, offering stronger compile-time checks and reducing the need for manual SQL writing. It's ideal for projects that prioritize type safety and want to minimize SQL-related errors at runtime.

The choice between sqlx and sqlc depends on the project's requirements, the team's familiarity with SQL, and the desired balance between flexibility and type safety.

Generate a Go ORM tailored to your database schema.

Pros of SQLBoiler

  • Supports more databases (MySQL, PostgreSQL, SQLite, MSSQL)
  • Generates more comprehensive models with relationships and hooks
  • Offers more flexibility in query building and customization

Cons of SQLBoiler

  • Steeper learning curve due to more complex API
  • Generates larger codebase, which may increase compilation time
  • Requires more manual configuration for optimal performance

Code Comparison

SQLBoiler:

users, err := models.Users().All(ctx, db)
if err != nil {
    return err
}

SQLC:

users, err := queries.ListUsers(ctx)
if err != nil {
    return err
}

Both SQLBoiler and SQLC are powerful tools for generating type-safe Go code from SQL schemas. SQLBoiler offers more features and flexibility, supporting a wider range of databases and generating more comprehensive models. However, this comes at the cost of increased complexity and a steeper learning curve.

SQLC, on the other hand, provides a simpler and more straightforward approach, generating clean and efficient code with less configuration required. It's particularly well-suited for PostgreSQL users and those who prefer a more opinionated tool.

The code comparison shows that both libraries offer similar ease of use for basic queries, with SQLBoiler providing a slightly more object-oriented approach and SQLC focusing on direct query execution.

Ultimately, the choice between SQLBoiler and SQLC depends on the specific needs of your project, the databases you're working with, and your preferred level of abstraction and control over the generated code.

36,491

The fantastic ORM library for Golang, aims to be developer friendly

Pros of GORM

  • More flexible and feature-rich ORM with support for various database operations
  • Provides a higher level of abstraction, simplifying complex database interactions
  • Offers hooks and callbacks for custom logic during database operations

Cons of GORM

  • Performance overhead due to reflection and abstraction layers
  • Steeper learning curve for developers new to ORMs
  • May lead to less optimized SQL queries in complex scenarios

Code Comparison

GORM example:

db.Where("name = ?", "jinzhu").First(&user)

SQLC example:

user, err := queries.GetUserByName(ctx, "jinzhu")

Key Differences

  • SQLC generates type-safe Go code from SQL queries, while GORM uses a runtime ORM approach
  • SQLC offers better performance and compile-time safety, but with less flexibility
  • GORM provides a more comprehensive set of features for database manipulation
  • SQLC requires writing raw SQL queries, which can be an advantage for complex queries or a drawback for simple CRUD operations

Use Cases

  • Choose GORM for rapid development, complex object relationships, or when working with multiple database types
  • Opt for SQLC when performance is critical, for projects with complex SQL queries, or when you prefer more control over database interactions
15,388

An entity framework for Go

Pros of ent

  • Provides a full-featured ORM with schema modeling and code generation
  • Offers advanced querying capabilities, including graph traversals
  • Supports multiple database backends (MySQL, PostgreSQL, SQLite, Gremlin)

Cons of ent

  • Steeper learning curve due to its more complex API and concepts
  • May introduce overhead for simpler database operations
  • Less flexibility in raw SQL usage compared to sqlc

Code Comparison

ent schema definition:

type User struct {
    ent.Schema
}

func (User) Fields() []ent.Field {
    return []ent.Field{
        field.String("name"),
        field.Int("age"),
    }
}

sqlc SQL definition:

CREATE TABLE users (
  id   BIGSERIAL PRIMARY KEY,
  name TEXT NOT NULL,
  age  INTEGER NOT NULL
);

ent offers a more programmatic approach to defining schemas, while sqlc relies on raw SQL for schema definition. ent provides a richer set of features for complex data modeling and querying, whereas sqlc focuses on generating type-safe Go code from SQL queries. The choice between the two depends on project requirements, complexity, and developer preferences.

38,831

Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB

Pros of Prisma

  • Offers a more comprehensive ORM solution with database migrations, seeding, and introspection
  • Provides a type-safe query builder and auto-generated client for multiple programming languages
  • Supports real-time database events and subscriptions

Cons of Prisma

  • Steeper learning curve due to its more complex ecosystem and concepts
  • Less flexibility for raw SQL queries and custom database optimizations
  • Potentially higher overhead and performance impact for large-scale applications

Code Comparison

Prisma query:

const users = await prisma.user.findMany({
  where: { age: { gte: 18 } },
  select: { name: true, email: true }
})

SQLC query:

users, err := queries.GetAdultUsers(ctx, 18)

Summary

Prisma offers a more feature-rich ORM experience with cross-language support and advanced features like real-time events. However, it comes with a steeper learning curve and potentially higher overhead. SQLC, on the other hand, provides a simpler, more lightweight approach focused on generating type-safe database access code from SQL queries, offering better performance and flexibility for raw SQL operations.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

sqlc: A SQL Compiler

go Go Report Card

sqlc generates type-safe code from SQL. Here's how it works:

  1. You write queries in SQL.
  2. You run sqlc to generate code with type-safe interfaces to those queries.
  3. You write application code that calls the generated code.

Check out an interactive example to see it in action, and the introductory blog post for the motivation behind sqlc.

Overview

Supported languages

Additional languages can be added via plugins.

Sponsors

Development is possible thanks to our sponsors. If you would like to support sqlc, please consider sponsoring on GitHub.

Riza.io

Coder.com Mint.fun Mux.com

Cyberax - NaNuNaNu - Stumble - WestfalNamur - alecthomas - cameronnewman - danielbprice - davherrmann - dvob - gilcrest - gzuidhof - jeffreylo - mmcloughlin - ryohei1216 - sgielen