gen

package
v1.0.9 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2024 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

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.

Functions

func EachTableGroupToItsOwnPackage

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

func EachTableToItsOwnPackage

func EachTableToItsOwnPackage(rootDir, tableName string) string

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 query builders.

func GenerateSchemaFromDatabase

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

TODO: Add support for base-type entities. Make base classes, e.g. Accept: { "TargetDater": ["source_id", "target_date"], "Base": "id", "created_at", "updated_at"] }.

Output: $ROOT_DIR/base/target_dater.go $ROOT_DIR/base/base.go

And on each table which contains these columns, replace the column printing with the base.TargetDater and/or base.Base and import this 'base' package to each table's file.

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: "postgres://postgres:admin!123@localhost:5432/test_db?sslmode=disable",
		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.TypeOf(Feature{})
						case "other_features":
							column.FieldType = reflect.TypeOf(Features{})
						case "tags":
							column.FieldType = reflect.TypeOf([]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")

}
Output:

OK

Types

type ExportOptions

type ExportOptions struct {
	RootDir  string
	FileMode fs.FileMode

	ToSingular     func(string) string
	GetFileName    func(rootDir, tableName string) string
	GetPackageName func(tableName string) string
}

ExportOptions is the options for the GenerateColumnsFromSchema function.

type ImportOptions

type ImportOptions struct {
	ConnString string

	ListTables pg.ListTablesOptions
}

ExportOptions is the options for the schema export. Used in GenerateSchemaFromDatabase and GenerateColumnsFromSchema.

Jump to

Keyboard shortcuts

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