gen

package
v1.0.17 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 1, 2026 License: MIT Imports: 15 Imported by: 0

README

gen

The gen package provides a function to generate Go schema files from a PostgreSQL database.

Usage

To use the gen package, you need to import it in your Go code:

import "github.com/kataras/pg/gen"

The main function of the gen package is GenerateSchemaFromDatabase, which takes a context, an ImportOptions struct and an ExportOptions struct as arguments. The ImportOptions struct contains the connection string and the list of tables to import from the database. The ExportOptions struct contains the root directory and the file name generator for the schema files.

For example, this code snippet shows how to generate schema files for all tables in a test database:

package main

import (
  "context"
  "fmt"
  "os"
  "time"

  "github.com/kataras/pg/gen"
)

func main() {
  rootDir := "./_testdata"

  i := gen.ImportOptions{
    ConnString: "postgres://postgres:admin!123@localhost:5432/test_db?sslmode=disable",
  }

  e := gen.ExportOptions{
    RootDir: rootDir,
  }

  if err := gen.GenerateSchemaFromDatabase(context.Background(), i, e); err != nil {
    fmt.Println(err.Error())
    return
  }

  fmt.Println("OK")
}

The GenerateSchemaFromDatabase function will create a directory named _testdata and write schema files for each table in the test database. The schema files will have the same name as the table name (on its singular form), with a .go extension.

You can also customize the import and export options by using the fields of the ImportOptions and ExportOptions structs. For example, you can use the ListTables.Filter field to filter out some tables or columns, or use the GetFileName field to change how the schema files are named.

For more details on how to use the gen package, please refer to the godoc documentation.

License

The gen package is licensed under the MIT license. See LICENSE for more information.

Documentation

Overview

Package gen generates Go source code from a PostgreSQL database schema or from a registered pg.Schema, so that hand-writing struct definitions and column constants is not required. GenerateSchemaFromDatabase connects to a live database, converts its tables to pg.Table definitions (via pg.DB.ListTables) and writes one Go struct per table plus a schema.go that registers them all. GenerateColumnsFromSchema instead starts from an already-registered pg.Schema and writes a package of typed column-name constants, useful for building type-safe queries. Both generators are driven by an ExportOptions value that controls the output directory, file naming and package layout.

Index

Examples

Constants

This section is empty.

Variables

View Source
var GoImportsTool = "goimports"

GoImportsTool is the name of the tool that will be used to format the generated code.

It is resolved with exec.LookPath against the current process's PATH and, if found, invoked directly on the generated output directory. This is a trusted developer-tooling knob: it is meant to be set by the developer running the code generator locally or in CI, never derived from untrusted input (e.g. database contents or network responses).

Functions

func EachTableGroupToItsOwnPackage

func EachTableGroupToItsOwnPackage() func(rootDir, tableName string) string

EachTableGroupToItsOwnPackage returns a GetFileName strategy that groups related tables into the same package: the first table seen with a given prefix (e.g. "customer") establishes the group, and any later table whose singular name starts with "<group>_" (e.g. "customer_address") is placed in that same group's package instead of getting one of its own.

func EachTableToItsOwnPackage

func EachTableToItsOwnPackage(rootDir, tableName string) string

EachTableToItsOwnPackage is a GetFileName strategy that places every table's generated file in its own package, named after the table's singular form: rootDir/customer/customer.go for a "customers" table.

func GenerateColumnsFromSchema

func GenerateColumnsFromSchema(s *pg.Schema, e ExportOptions) error

GenerateColumnsFromSchema generates Go code for the given schema. The generated code includes a struct for each table which contains struct fields for each column information.

Example Code:

schema := pg.NewSchema() schema.MustRegister("companies", Company{}) schema.MustRegister("customers", Customer{})

opts := &ExportOptions{
	RootDir: "./definition",
}

if err := GenerateColumnsFromSchema(schema, opts); err != nil {
	t.Fatal(err)
}

Usage: definition.Company.Name.String() // returns "name" definition.Customer.Email.String() // returns "email"

Useful for type-safe column constants, consumed by the WHERE/OrderBy/pagination helpers (pg.Where/pg.Conditions, Repository.OrderBy, pg.PageOptions) instead of hand-typed column name strings, e.g.:

where := pg.Where(definition.Customer.Email.String()+" = $1", email)
orderBy, err := repo.OrderBy(definition.Customer.CreatedAt.String(), true)

func GenerateSchemaFromDatabase

func GenerateSchemaFromDatabase(ctx context.Context, i ImportOptions, e ExportOptions) error

GenerateSchemaFromDatabase connects to the database identified by i.ConnString, reads its tables (via pg.DB.ListTables, filtered by i.ListTables) and writes one Go source file per table plus a schema.go that registers all of them under a pg.Schema, laid out according to e. It also runs goimports (see GoImportsTool) over e.RootDir afterwards, if the tool is found on PATH.

Example
package main

import (
	"context"
	"fmt"
	"os"
	"reflect"
	"time"

	"github.com/kataras/pg"
)

type Features []Feature

type Feature struct {
	IsFeatured bool `json:"is_featured"`
}

type Tag struct {
	Name  string `json:"name"`
	Value any    `json:"value"`
}

func main() {
	const (
		rootDir = "./_testdata"
	)
	defer func() {
		os.RemoveAll(rootDir)
		time.Sleep(1 * time.Second)
	}()

	i := ImportOptions{
		ConnString: getTestConnString(),
		ListTables: pg.ListTablesOptions{
			Filter: pg.TableFilterFunc(func(table *pg.Table) bool {
				columnFilter := func(column *pg.Column) bool {
					columnName := column.Name

					switch table.Name {
					case "blog_posts":
						switch columnName {
						case "feature":
							column.FieldType = reflect.TypeFor[Feature]()
						case "other_features":
							column.FieldType = reflect.TypeFor[Features]()
						case "tags":
							column.FieldType = reflect.TypeFor[[]Tag]()
						}
					}

					return true
				}

				table.FilterColumns(columnFilter)
				return true
			}),
		},
	}

	e := ExportOptions{
		RootDir: rootDir,
		// Optionally:
		// GetFileName: EachTableToItsOwnPackage,
		GetFileName: EachTableGroupToItsOwnPackage(),
	}

	if err := GenerateSchemaFromDatabase(context.Background(), i, e); err != nil {
		fmt.Println(err.Error())
		return
	}

	fmt.Println("OK")

}

// getTestConnString returns the connection string to test against, read from the
// PG_CONNSTRING environment variable when set. This package (gen) cannot reuse the root
// pg package's own getTestConnString (package pg, unexported), so this is a small local
// equivalent: when PG_CONNSTRING is unset or empty, it falls back to the same hardcoded
// literal this example used before, so CI's postgres service container (see
// .github/workflows/ci.yml) keeps working unchanged.
func getTestConnString() string {
	if override := os.Getenv("PG_CONNSTRING"); override != "" {
		return override
	}

	return "postgres://postgres:admin!123@localhost:5432/test_db?sslmode=disable"
}
Output:
OK

Types

type ExportOptions

type ExportOptions struct {
	// RootDir is the directory generated files are written under. It defaults to "./"
	// and is resolved to an absolute path by apply, since GetPackageName's default
	// implementation derives the root package name from it.
	RootDir string
	// FileMode is the file mode used when writing generated Go source files.
	// It defaults to 0o644 (owner read/write, group/other read-only) so that
	// generated source is not left world-writable; set it explicitly to
	// override that default.
	FileMode fs.FileMode

	// ToSingular converts a table name to its singular form, used by the default
	// GetFileName and GetPackageName strategies. Defaults to desc.Singular.
	ToSingular func(string) string
	// GetFileName returns the Go source file path for a given table name (or, called
	// with an empty tableName, the root/schema file). Defaults to one file per table
	// under RootDir, named after ToSingular(tableName); see EachTableToItsOwnPackage
	// and EachTableGroupToItsOwnPackage for alternative, ready-made strategies.
	GetFileName func(rootDir, tableName string) string
	// GetPackageName returns the Go package name a generated table's file belongs to,
	// derived by default from the directory GetFileName places it in.
	GetPackageName func(tableName string) string
}

ExportOptions is the options for the GenerateColumnsFromSchema function.

type ImportOptions

type ImportOptions struct {
	// ConnString is the PostgreSQL connection string GenerateSchemaFromDatabase opens to
	// read the source schema from. See pg.Open for its accepted formats.
	ConnString string

	// ListTables customizes which tables are read and how their columns are resolved
	// into Go field types; it is passed as-is to pg.DB.ListTables.
	ListTables pg.ListTablesOptions
}

ImportOptions is the options for importing (reading) the source database schema that GenerateSchemaFromDatabase generates Go code from.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL