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 ¶
- Variables
- func EachTableGroupToItsOwnPackage() func(rootDir, tableName string) string
- func EachTableToItsOwnPackage(rootDir, tableName string) string
- func GenerateColumnsFromSchema(s *pg.Schema, e ExportOptions) error
- func GenerateSchemaFromDatabase(ctx context.Context, i ImportOptions, e ExportOptions) error
- type ExportOptions
- type ImportOptions
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 ¶
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.