Jet

repository·master·Indexed 25 days ago

https://github.com/go-jet/jet

A type-safe SQL builder and code generation tool for Go, designed for high-performance database access without being a full ORM. It provides auto-generated SQL builders, data model types, and automatic query result mapping. Jet supports PostgreSQL (including CockroachDB), MySQL (including MariaDB), and SQLite. Key features include a fluent API for complex SQL statements, a CLI generator for creating Go code from database schemas, and SELECT_JSON support to reduce network latency.

Tokens
3.1K
Snippets
7
Records
20
Agent score
85%

What's inside go-jet

  1. Overview of Jet

    master

    Jet is a high-performance database access solution for Go that combines a type-safe SQL builder with code generation and automatic query result mapping. It is designed to allow writing complex SQL queries directly in Go code while maintaining type safety.

    Note: Jet is NOT an ORM.

    Supported database engines include:

    • PostgreSQL (including CockroachDB via PostgreSQL wire protocol)
    • MySQL (including MariaDB via MySQL protocol)
    • SQLite
  2. Generate SQL Builder and Model types

    master

    Use the jet command to scan your database and generate Go code. The generator creates SQL Builder packages (for table, view, and enum) and Data Model packages (for storing query results).

    Important: The generator will delete all contents in the specified -path directory before generating new files.

    Supported Databases: PostgreSQL, MySQL, CockroachDB, MariaDB, and SQLite.

  3. Install the Jet package

    master

    To use Jet in your Go project, you must have Go version 1.24 or higher installed. Add Jet as a dependency to your go.mod file using the following command:

    $ go get -u github.com/go-jet/jet/v2
  4. Install the Jet generator CLI

    master

    The Jet generator is used to create type-safe SQL builders and data models from your database schema. You can install it via go install or by building from source.

    Option 1: via go install This installs the binary to your $GOPATH/bin (or $HOME/go/bin).

    Option 2: Build from source Clone the repository and build the command to a specific directory. Ensure the target directory is in your system's PATH.

    # Option 1
    go install github.com/go-jet/jet/v2/cmd/jet@latest
    
    # Option 2
    git clone https://github.com/go-jet/jet.git
    cd jet && go build -o <target_directory> ./cmd/jet
  5. Reduce latency with SELECT_JSON statements

    master
    As of version v2.13.0, you can use SELECT_JSON statements to encode query results as JSON directly on the SQL server. This allows the query to return a single row containing one column with the entire result set as JSON, rather than returning a large set of rows. This technique reduces network latency between the database and your application.
  6. Use any Go SQL driver with Jet

    master

    Jet can execute SQL statements using any SQL driver that implements Go's standard database/sql interface.

    By default, the Jet generator executable uses the following drivers to read database schema information:

    • github.com/lib/pq (for PostgreSQL and CockroachDB)
    • github.com/go-sql-driver/mysql (for MySQL and MariaDB)
    • github.com/mattn/go-sqlite3 (for SQLite)

    You can replace the default SQL driver used by the generator by customizing the generator.

  7. Install the Jet library and generator

    master

    To use Jet, you need to install both the library as a Go dependency and the Jet generator CLI tool.

    1. Install the library Add Jet to your go.mod file:

    go get -u github.com/go-jet/jet/v2

    2. Install the Jet generator Choose one of the following methods to install the CLI tool:

    • Using go install (Recommended for Go 1.16+):
      go install github.com/go-jet/jet/v2/cmd/jet@latest
    • Using GOPATH (Legacy):
      cd $GOPATH/src/ && GO111MODULE=off go get -u github.com/go-jet/jet/cmd/jet
    • Building from source:
      git clone https://github.com/go-jet/jet.git
      cd jet && go build -o <dir_path> ./cmd/jet

    Note: Ensure the destination folder is added to your PATH environment variable.

    go get -u github.com/go-jet/jet/v2
  8. Use the jet CLI to generate Go code from a database

    master
    The jet command-line tool generates Go models, SQL builders, and enum types from an existing database schema. It supports PostgreSQL, MySQL, MariaDB, CockroachDB, and SQLite. You can connect via a Data Source Name (DSN) or by providing individual connection parameters.
  9. Write type-safe SQL queries with Jet

    master

    After generating your code, import the generated table and model packages. To write queries that resemble native SQL, it is common to use a dot import for the database-specific Jet package (e.g., postgres).

    Workflow:

    1. Import generated table and model packages.
    2. Import the database driver package (e.g., github.com/go-jet/jet/v2/postgres).
    3. Use the SELECT, FROM, WHERE, and JOIN builders to construct statements.
    4. Execute the statement using .Query(db, &dest) to map results into Go structs.
    5. Use .Sql() to inspect the generated SQL string.
    import . "some_path/.gen/jetdb/dvds/table"
    import "some_path/.gen/jetdb/dvds/model"
    import . "github.com/go-jet/jet/v2/postgres"
    
    // Example Query Construction
    rRatingFilms := SELECT(
        Film.FilmID,
        Film.Title,
        Film.Rating,
    ).FROM(
        Film,
    ).WHERE(
        Film.Rating.EQ(enum.FilmRating.R),
    ).AsTable("rFilms")
    
    rFilmID := Film.FilmID.From(rRatingFilms)
    
    stmt := SELECT(
        Actor.AllColumns,
        FilmActor.AllColumns,
        rRatingFilms.AllColumns(),
    ).FROM(
        rRatingFilms.
            INNER_JOIN(FilmActor, FilmActor.FilmID.EQ(rFilmID)).
            INNER_JOIN(Actor, Actor.ActorID.EQ(FilmActor.ActorID)),
    ).ORDER_BY(
        rFilmID,
        Actor.ActorID,
    )
    
    // Execution
    var dest []struct {
        model.Film
        Actors []model.Actor
    }
    err := stmt.Query(db, &dest)
    
    // Inspect SQL
    fmt.Println(stmt.Sql())
  10. Generate SQL Builder and Model files

    master

    Jet requires an existing database schema to generate type-safe SQL builder and model files. You can run the jet command to perform code generation.

    Command Syntax: jet -dsn=<DSN> -schema=<SCHEMA_NAME> -path=<OUTPUT_PATH>

    Example:

    jet -dsn=postgresql://user:pass@localhost:5432/jetdb -schema=dvds -path=./.gen
    jet -dsn=postgresql://user:pass@localhost:5432/jetdb -schema=dvds -path=./.gen
  11. Explore Jet quick-start examples

    master

    The examples/quick-start package provides sample usage of the Jet framework. It demonstrates how to use Jet-generated files and how to execute queries that output JSON results to files instead of standard output.

    Key components in this example:

    • quick-start.go: Contains the implementation logic explained in the main project documentation, modified to redirect JSON output to dest.json and dest2.json.
    • ./gen: The directory containing Jet-generated code files.
    • dest.json and dest2.json: The resulting JSON output files generated by running the example.
  12. Write type-safe SQL queries in Go

    master

    Once generated, import the table, enum, and model packages. Jet uses a fluent API that closely resembles native SQL. Type safety is enforced: for example, string columns can only be compared with string expressions, and integer columns with integer expressions.

    import (
      . "github.com/go-jet/jet/v2/examples/quick-start/.gen/jetdb/dvds/table"
      . "github.com/go-jet/jet/v2/postgres"
      "github.com/go-jet/jet/v2/examples/quick-start/.gen/jetdb/dvds/enum"
      "github.com/go-jet/jet/v2/examples/quick-start/.gen/jetdb/dvds/model"
    )
    
    stmt := SELECT(
        Actor.ActorID, Actor.FirstName, Actor.LastName, Actor.LastUpdate,
        Film.AllColumns,
        Language.AllColumns.Except(Language.LastUpdate),
        Category.AllColumns,
    ).FROM(
        Actor.
            INNER_JOIN(FilmActor, Actor.ActorID.EQ(FilmActor.ActorID)).
            INNER_JOIN(Film, Film.FilmID.EQ(FilmActor.FilmID)).
            INNER_JOIN(Language, Language.LanguageID.EQ(Film.LanguageID)).
            INNER_JOIN(FilmCategory, FilmCategory.FilmID.EQ(Film.FilmID)).
            INNER_JOIN(Category, Category.CategoryID.EQ(FilmCategory.CategoryID)),
    ).WHERE(
        AND(
            Language.Name.EQ(Char(20)("English")),
            Category.Name.NOT_EQ(Text("Action")),
            Film.Length.GT(Int32(180)),
            Film.Rating.NOT_EQ(enum.MpaaRating.R),
            String("Trailers").EQ(ANY(Film.SpecialFeatures)),
        ),
    ).ORDER_BY(
        Actor.ActorID.ASC(),
        Film.FilmID.ASC(),
    )