internal

package
v0.0.0-...-1ccaee4 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2021 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SchemaEsc = iota
	TableEsc
	ColumnEsc
)
View Source
const (
	LoadQueryFunc = iota
	LoadMapFunc
)

Variables

View Source
var IndexChopSuffixRE = regexp.MustCompile(`(?i)_(ix|idx|index|pkey|ukey|key)$`)

IndexChopSuffixRE is the regexp of index name suffixes that will be chopped off.

View Source
var IntRE = regexp.MustCompile(`^int(32|64)?$`)

IntRE matches Go int types.

View Source
var PrecScaleRE = regexp.MustCompile(`\(([0-9]+)(\s*,[0-9]+)?\)$`)

PrecScaleRE is the regexp that matches "(precision[,scale])" definitions in a database.

View Source
var SchemaLoaders = map[string]Loader{}

SchemaLoaders are the available schema loaders.

Functions

func GenRandomID

func GenRandomID() string

GenRandomID generates a 8 character random string.

func GroupCompatible

func GroupCompatible(args *ArgType, name string) string

因为有个服务的名字叫 Group 和 Group Service 冲突了,这里改为 MGroup

func ProtoName

func ProtoName(name string) string

func SingularizeIdentifier

func SingularizeIdentifier(s string) string

SinguralizeIdentifier will singularize a identifier, returning it in CamelCase.

func SnakeToCamelWithoutInitialisms

func SnakeToCamelWithoutInitialisms(str string) string

proto 对于 id -> Id

Types

type ArgType

type ArgType struct {
	// Verbose enables verbose output.
	Verbose bool `arg:"-v,help:toggle verbose"`

	// DSN is the database string (ie, pgsql://user@blah:localhost:5432/dbname?args=)
	DSN string `arg:"positional,required,help:data source name"`

	// Schema is the name of the schema to query.
	Schema string `arg:"-s,help:schema name to generate Go types for"`

	// Out is the output path. If Out is a file, then that will be used as the
	// path. If Out is a directory, then the output file will be
	// Out/<$CWD>.xo.go
	Out string `arg:"-o,help:output path or file name"`

	// Append toggles to append to the existing types.
	Append bool `arg:"-a,help:append to existing files"`

	// Suffix is the output suffix for filenames.
	Suffix string `arg:"-f,help:output file suffix"`

	// SingleFile when toggled changes behavior so that output is to one f ile.
	SingleFile bool `arg:"--single-file,help:toggle single file output"`

	// Package is the name used to generate package headers. If not specified,
	// the name of the output directory will be used instead.
	Package string `arg:"-p,help:package name used in generated Go code"`

	// CustomTypePackage is the Go package name to use for unknown types.
	CustomTypePackage string `arg:"--custom-type-package,-C,help:Go package name to use for custom or unknown types"`

	// Int32Type is the type to assign those discovered as int32 (ie, serial, integer, etc).
	Int32Type string `arg:"--int32-type,-i,help:Go type to assign to integers"`

	// Uint32Type is the type to assign those discovered as uint32.
	Uint32Type string `arg:"--uint32-type,-u,help:Go type to assign to unsigned integers"`

	// IgnoreFields allows the user to specify field names which should not be
	// handled by xo in the generated code.
	IgnoreFields []string `arg:"--ignore-fields,help:fields to exclude from the generated Go code types"`

	// ForeignKeyMode is the foreign key mode for generating foreign key names.
	ForeignKeyMode *FkMode `arg:"--fk-mode,-k,help:sets mode for naming foreign key funcs in generated Go code [values: <smart|parent|field|key>]"`

	// UseIndexNames toggles using index names.
	//
	// This is not enabled by default, because index names are often generated
	// using database design software which has the nasty habit of giving
	// non-helpful names to indexes as things like 'authors__b124214__u_idx'
	// instead of 'authors_title_idx'.
	UseIndexNames bool `arg:"--use-index-names,-j,help:use index names as defined in schema for generated Go code"`

	// UseReversedEnumConstNames toggles using reversed enum names.
	UseReversedEnumConstNames bool `arg:"--use-reversed-enum-const-names,-R,help:use reversed enum names for generated consts in Go code"`

	// QueryMode toggles whether or not to parse a query from stdin.
	QueryMode bool `arg:"--query-mode,-N,help:enable query mode"`

	// Query is the passed query. If not specified, then os.Stdin will be used.
	// cli args take precedence over stdin.
	Query string `arg:"-Q,help:query to generate Go type and func from"`

	// QueryType is the name to give to the Go type generated from the query.
	QueryType string `arg:"--query-type,-T,help:query's generated Go type"`

	// QueryFunc is the name to assign to the generated query func.
	QueryFunc string `arg:"--query-func,-F,help:query's generated Go func name"`

	// QueryOnlyOne toggles the generated query code to expect only one result.
	QueryOnlyOne bool `arg:"--query-only-one,-1,help:toggle query's generated Go func to return only one result"`

	// QueryTrim enables triming whitespace on the supplied query.
	QueryTrim bool `arg:"--query-trim,-M,help:toggle trimming of query whitespace in generated Go code"`

	// QueryStrip enables stripping the '::<type> AS <name>' from supplied query.
	QueryStrip bool `arg:"--query-strip,-B,help:toggle stripping type casts from query in generated Go code"`

	// QueryInterpolate enables interpolation in generated query.
	QueryInterpolate bool `arg:"--query-interpolate,-I,help:toggle query interpolation in generated Go code"`

	// TypeComment is the type comment for a query.
	QueryTypeComment string `arg:"--query-type-comment,help:comment for query's generated Go type"`

	// FuncComment is the func comment to provide the named query.
	QueryFuncComment string `arg:"--query-func-comment,help:comment for query's generated Go func"`

	// QueryParamDelimiter is the delimiter for parameterized values for a query.
	QueryParamDelimiter string `arg:"--query-delimiter,-D,help:delimiter for query's embedded Go parameters"`

	// QueryFields are the fields to scan the result to.
	QueryFields string `arg:"--query-fields,-Z,help:comma separated list of field names to scan query's results to the query's associated Go type"`

	// QueryAllowNulls indicates that custom query results can contain null types.
	QueryAllowNulls bool `arg:"--query-allow-nulls,-U,help:use query column NULL state"`

	// EscapeAll toggles escaping schema, table, and column names in SQL queries.
	EscapeAll bool `arg:"--escape-all,-X,help:escape all names in SQL queries"`

	// EscapeSchemaName toggles escaping schema name in SQL queries.
	EscapeSchemaName bool `arg:"--escape-schema,-z,help:escape schema name in SQL queries"`

	// EscapeTableNames toggles escaping table names in SQL queries.
	EscapeTableNames bool `arg:"--escape-table,-y,help:escape table names in SQL queries"`

	// EscapeColumnNames toggles escaping column names in SQL queries.
	EscapeColumnNames bool `arg:"--escape-column,-x,help:escape column names in SQL queries"`

	// EnablePostgresOIDs toggles postgres oids.
	EnablePostgresOIDs bool `arg:"--enable-postgres-oids,help:enable postgres oids"`

	// NameConflictSuffix is the suffix used when a name conflicts with a scoped Go variable.
	NameConflictSuffix string `arg:"--name-conflict-suffix,-w,help:suffix to append when a name conflicts with a Go variable"`

	// TemplatePath is the path to use the user supplied templates instead of
	// the built in versions.
	TemplatePath string `arg:"--template-path,help:user supplied template path"`

	// Tags is the list of build tags to add to generated Go files.
	Tags string `arg:"--tags,help:build tags to add to package header"`

	// Path is the output path, as derived from Out.
	Path string `arg:"-"`

	// Filename is the output filename, as derived from Out.
	Filename string `arg:"-"`

	// LoaderType is the loader type.
	LoaderType string `arg:"-"`

	// Loader is the schema loader.
	Loader Loader `arg:"-"`

	// DB is the opened database handle.
	DB *sql.DB `arg:"-"`

	// Generated is the generated templates after a run.
	Generated []TBuf `arg:"-"`

	// Generated is the generated proto templates after a run.
	GeneratedProto []TBuf `arg:"-"`

	// KnownTypeMap is the collection of known Go types.
	KnownTypeMap map[string]bool `arg:"-"`

	// ShortNameTypeMap is the collection of Go style short names for types, mainly
	// used for use with declaring a func receiver on a type.
	ShortNameTypeMap map[string]string `arg:"-"`

	// GeoInfoTypeMap stores geo info type, eg. point, Polygon, MultiPolygon
	GeoInfoTypeMap map[string]bool `arg:"-"`

	// Methods config file controls generation of specified methods for tables.
	MethodsConfigFile string `arg:"--methods-config-file,help: specified methods config for tables"`

	// OnlyConfigTable 只生成在 --methods-config-file 配置文件中的表
	OnlyConfigTable bool `arg:"--only-config-table,help:only genereate tables in config file"`

	// parsed from MethodsConfigFile
	Methods *MethodsConfig `arg:"-"`

	// eg. github.com/sundayfun/rpc/proto/backend/service
	RpcProtoPathPrefix string `arg:"--rpc-proto-path-prefix"`

	// eg. github.com/sundayfun/daycam-server/backend
	ServerProtoPathPrefix string `arg:"--server-proto-path-prefix"`

	Imports map[string][]string `arg:"-"`

	ToPBTypeMap map[string]string `arg:"-"`

	IncompatilbePBType map[string]bool `arg:"-"`

	WrapperTypeMap map[string]string `arg:"-"`

	ImportMap map[string]string `arg:"-"`

	ConfigTables map[string]struct{} `arg:"-"`
	// 加载成功后的 TableMap
	TableMap map[string]*Type `arg:"-"`
	// contains filtered or unexported fields
}

ArgType is the type that specifies the command line arguments.

var Args *ArgType

Args are the application arguments.

func NewDefaultArgs

func NewDefaultArgs() *ArgType

NewDefaultArgs returns the default arguments.

func (*ArgType) BuildIndexFuncName

func (a *ArgType) BuildIndexFuncName(ixTpl *Index)

BuildIndexFuncName builds the index func name for an index and its supplied fields.

func (*ArgType) BuildIndexMapFuncName

func (a *ArgType) BuildIndexMapFuncName(ixTpl *Index)

BuildIndexMapFuncName builds the index map func name for an index and its supplied fields.

func (*ArgType) Description

func (a *ArgType) Description() string

Description provides the description for the command output.

func (*ArgType) ExecuteTemplate

func (a *ArgType) ExecuteTemplate(tt TemplateType, name string, sub string, obj interface{}, isProto bool) error

ExecuteTemplate loads and parses the supplied template with name and executes it with obj as the context.

func (*ArgType) ForeignKeyName

func (a *ArgType) ForeignKeyName(fkMap map[string]*ForeignKey, fk *ForeignKey) string

ForeignKeyName returns the foreign key name for the passed type.

func (*ArgType) NewTemplateFuncs

func (a *ArgType) NewTemplateFuncs() template.FuncMap

NewTemplateFuncs returns a set of template funcs bound to the supplied args.

func (*ArgType) PBToModel

func (a *ArgType) PBToModel(option *MethodsOption) string

func (*ArgType) ParsePrecision

func (a *ArgType) ParsePrecision(dt string) (string, int, int)

ParsePrecision extracts (precision[,scale]) strings from a data type and returns the data type without the string.

func (*ArgType) ParseQuery

func (a *ArgType) ParseQuery(mask string, interpol bool) (string, []*QueryParam)

ParseQuery takes the query in args and looks for strings in the form of "%%<name> <type>[,<option>,...]%%", replacing them with the supplied mask. mask can contain "%d" to indicate current position. The modified query is returned, and the slice of extracted QueryParam's.

func (*ArgType) TemplateLoader

func (a *ArgType) TemplateLoader(name string) ([]byte, error)

TemplateLoader loads templates from the specified name.

func (*ArgType) TemplateSet

func (a *ArgType) TemplateSet() *TemplateSet

TemplateSet retrieves the created template set.

type Enum

type Enum struct {
	Name              string
	Schema            string
	Values            []*EnumValue
	Enum              *models.Enum
	Comment           string
	ReverseConstNames bool
}

Enum is a template item for a enum.

type EnumValue

type EnumValue struct {
	Name    string
	Val     *models.EnumValue
	Comment string
}

EnumValue holds data for a single enum value.

type EscType

type EscType uint

EscType represents the different escape types.

type Field

type Field struct {
	Name    string
	Type    string
	NilType string
	Len     int
	Col     *models.Column
	Comment string
}

Field contains field information.

type FkMode

type FkMode int

FkMode represents the different foreign key naming modes.

const (
	// FkModeSmart is the default FkMode.
	//
	// When there are no naming conflicts, FkModeSmart behaves the same
	// FkModeParent, otherwise it behaves the same as FkModeField.
	FkModeSmart FkMode = iota

	// FkModeParent causes a foreign key field to be named in the form of
	// "<type>.<ParentName>".
	//
	// For example, if you have an `authors` and `books` tables, then the
	// foreign key func will be Book.Author.
	FkModeParent

	// FkModeField causes a foreign key field to be named in the form of
	// "<type>.<ParentName>By<Field>".
	//
	// For example, if you have an `authors` and `books` tables, then the
	// foreign key func will be Book.AuthorByAuthorID.
	FkModeField

	// FkModeKey causes a foreign key field to be named in the form of
	// "<type>.<ParentName>By<ForeignKeyName>".
	//
	// For example, if you have an `authors` and `books` tables with a foreign
	// key name of 'fk_123', then the foreign key func will be
	// Book.AuthorByFk123.
	FkModeKey
)

func (FkMode) String

func (f FkMode) String() string

String satisfies the Stringer interface.

func (*FkMode) UnmarshalText

func (f *FkMode) UnmarshalText(text []byte) error

UnmarshalText unmarshals FkMode from text.

type ForeignKey

type ForeignKey struct {
	Name       string
	Schema     string
	Type       *Type
	Field      *Field
	RefType    *Type
	RefField   *Field
	ForeignKey *models.ForeignKey
	Comment    string
}

ForeignKey is a template item for a foreign relationship on a table.

type Imports

type Imports struct {
	Package string
	Imports []string
	Schema  string
}

type Index

type Index struct {
	FuncName    string
	MapFuncName string
	MapField    *Field
	Schema      string
	Type        *Type
	Fields      []*Field
	Index       *models.Index
	Comment     string
}

Index is a template item for a index into a table.

type LoadType

type LoadType uint

type Loader

type Loader interface {
	// NthParam returns the 0-based Nth param for the Loader.
	NthParam(i int) string

	// Mask returns the mask.
	Mask() string

	// Escape escapes the passed identifier based on its EscType.
	Escape(EscType, string) string

	// Relkind returns the schema's relkind identifier (ie, TABLE, VIEW, BASE TABLE, etc).
	Relkind(RelType) string

	// SchemaName loads the active schema name from the database if not provided on the cli.
	SchemaName(*ArgType) (string, error)

	// ParseQuery parses the ArgType.Query and writes any necessary type(s) to
	// the ArgType from the opened database handle.
	ParseQuery(*ArgType) error

	// LoadSchema loads the ArgType.Schema from the opened database handle,
	// writing any generated types to ArgType.
	LoadSchema(*ArgType) error
}

Loader is the common interface for database drivers that can generate code from a database schema.

type MethodsConfig

type MethodsConfig struct {
	ListFields []string                  `yaml:"list_fields"`
	ModelToPB  map[string][]*TableConfig `yaml:"model_to_pb"`
}

type MethodsOption

type MethodsOption struct {
	Type            *Type
	Sub             string
	ListFields      bool
	ModelToPB       bool
	ModelToPBConfig *ModelToPBConfig
}

type ModelToPBConfig

type ModelToPBConfig struct {
	ImportService string
	SkipFields    map[string]struct{}
}

type Proc

type Proc struct {
	Name       string
	Schema     string
	ProcParams string
	Params     []*Field
	Return     *Field
	Proc       *models.Proc
	Comment    string
}

Proc is a template item for a stored procedure.

type ProtoConfig

type ProtoConfig []*MethodsOption

func (ProtoConfig) Len

func (t ProtoConfig) Len() int

func (ProtoConfig) Less

func (t ProtoConfig) Less(i, j int) bool

func (ProtoConfig) Swap

func (t ProtoConfig) Swap(i, j int)

type Query

type Query struct {
	Schema        string
	Name          string
	Query         []string
	QueryComments []string
	QueryParams   []*QueryParam
	OnlyOne       bool
	Interpolate   bool
	Type          *Type
	Comment       string
}

Query is a template item for a custom query.

type QueryParam

type QueryParam struct {
	Name        string
	Type        string
	Interpolate bool
}

QueryParam is a query parameter for a custom query.

type RelType

type RelType uint

RelType represents the different types of relational storage (table/view).

const (
	// Table reltype
	Table RelType = iota

	// View reltype
	View
)

func (RelType) String

func (rt RelType) String() string

String provides the string representation of RelType.

type TBuf

type TBuf struct {
	TemplateType TemplateType
	Name         string
	Subname      string
	Buf          *bytes.Buffer
}

TBuf is to hold the executed templates.

type TBufSlice

type TBufSlice []TBuf

TBufSlice is a slice of TBuf compatible with sort.Interface.

func (TBufSlice) Len

func (t TBufSlice) Len() int

func (TBufSlice) Less

func (t TBufSlice) Less(i, j int) bool

func (TBufSlice) Swap

func (t TBufSlice) Swap(i, j int)

type TableConfig

type TableConfig struct {
	Name  string   `yaml:"name"`
	Skips []string `yaml:"skips"`
}

type TemplateSet

type TemplateSet struct {
	// contains filtered or unexported fields
}

TemplateSet is a set of templates.

func (*TemplateSet) Execute

func (ts *TemplateSet) Execute(w io.Writer, name string, obj interface{}) error

Execute executes a specified template in the template set using the supplied obj as its parameters and writing the output to w.

type TemplateType

type TemplateType uint

TemplateType represents a template type.

const (
	EnumTemplate TemplateType = iota
	ProcTemplate
	TypeTemplate
	ForeignKeyTemplate
	IndexTemplate
	MapTemplate
	QueryTypeTemplate
	QueryTemplate
	OptionalTemplate
	TypeProtoTemplate

	// always last
	XOTemplate
)

the order here will be the alter the output order per file.

func (TemplateType) String

func (tt TemplateType) String() string

String returns the name for the associated template type.

type Type

type Type struct {
	Name             string
	Schema           string
	RelType          RelType
	PrimaryKey       *Field
	PrimaryKeyFields []*Field
	Fields           []*Field
	Indexes          map[string]*Index
	Table            *models.Table
	Comment          string
	HasDeletedField  bool
}

Type is a template item for a type (ie, table/view/custom query).

type TypeLoader

type TypeLoader struct {
	ParamN          func(int) string
	MaskFunc        func() string
	Esc             map[EscType]func(string) string
	ProcessRelkind  func(RelType) string
	Schema          func(*ArgType) (string, error)
	ParseType       func(*ArgType, string, bool) (int, string, string)
	EnumList        func(models.XODB, string) ([]*models.Enum, error)
	EnumValueList   func(models.XODB, string, string) ([]*models.EnumValue, error)
	ProcList        func(models.XODB, string) ([]*models.Proc, error)
	ProcParamList   func(models.XODB, string, string) ([]*models.ProcParam, error)
	TableList       func(models.XODB, string, string) ([]*models.Table, error)
	ColumnList      func(models.XODB, string, string) ([]*models.Column, error)
	ForeignKeyList  func(models.XODB, string, string) ([]*models.ForeignKey, error)
	IndexList       func(models.XODB, string, string) ([]*models.Index, error)
	IndexColumnList func(models.XODB, string, string, string) ([]*models.IndexColumn, error)
	QueryStrip      func([]string, []string)
	QueryColumnList func(*ArgType, []string) ([]*models.Column, error)
}

TypeLoader provides a common Loader implementation used by the built in schema/query loaders.

func (TypeLoader) Escape

func (tl TypeLoader) Escape(typ EscType, s string) string

Escape escapes the provided identifier based on the EscType.

func (TypeLoader) LoadColumns

func (tl TypeLoader) LoadColumns(args *ArgType, typeTpl *Type) error

LoadColumns loads schema table/view columns.

func (TypeLoader) LoadEnumValues

func (tl TypeLoader) LoadEnumValues(args *ArgType, enumTpl *Enum) error

LoadEnumValues loads schema enum values.

func (TypeLoader) LoadEnums

func (tl TypeLoader) LoadEnums(args *ArgType) (map[string]*Enum, error)

LoadEnums loads schema enums.

func (TypeLoader) LoadForeignKeys

func (tl TypeLoader) LoadForeignKeys(args *ArgType, tableMap map[string]*Type) (map[string]*ForeignKey, error)

LoadForeignKeys loads foreign keys.

func (TypeLoader) LoadIndexColumns

func (tl TypeLoader) LoadIndexColumns(args *ArgType, ixTpl *Index) error

LoadIndexColumns loads the index column information.

func (TypeLoader) LoadIndexes

func (tl TypeLoader) LoadIndexes(args *ArgType, tableMap map[string]*Type) (map[string]*Index, error)

LoadIndexes loads schema index definitions.

func (TypeLoader) LoadIndexesQueryMapFunc

func (tl TypeLoader) LoadIndexesQueryMapFunc(args *ArgType, tableMap map[string]*Type) (map[string]*Index, error)

LoadIndexesQueryMapFunc loads schema index definitions.

func (TypeLoader) LoadOptionalMethods

func (tl TypeLoader) LoadOptionalMethods(args *ArgType, tableMap map[string]*Type) error

LoadIndexes loads schema index definitions.

func (TypeLoader) LoadProcParams

func (tl TypeLoader) LoadProcParams(args *ArgType, procTpl *Proc) error

LoadProcParams loads schema stored procedure parameters.

func (TypeLoader) LoadProcs

func (tl TypeLoader) LoadProcs(args *ArgType) (map[string]*Proc, error)

LoadProcs loads schema stored procedures definitions.

func (TypeLoader) LoadRelkind

func (tl TypeLoader) LoadRelkind(args *ArgType, relType RelType) (map[string]*Type, error)

LoadRelkind loads a schema table/view definition.

func (TypeLoader) LoadSchema

func (tl TypeLoader) LoadSchema(args *ArgType) error

LoadSchema loads schema definitions.

func (TypeLoader) LoadTableForeignKeys

func (tl TypeLoader) LoadTableForeignKeys(args *ArgType, tableMap map[string]*Type, typeTpl *Type, fkMap map[string]*ForeignKey) error

LoadTableForeignKeys loads schema foreign key definitions per table.

func (TypeLoader) LoadTableIndexes

func (tl TypeLoader) LoadTableIndexes(args *ArgType, typeTpl *Type, ixMap map[string]*Index, loadType LoadType) error

LoadTableIndexes loads schema index definitions per table.

func (TypeLoader) Mask

func (tl TypeLoader) Mask() string

Mask returns the parameter mask.

func (TypeLoader) NthParam

func (tl TypeLoader) NthParam(i int) string

NthParam satisifies Loader's NthParam.

func (TypeLoader) ParseQuery

func (tl TypeLoader) ParseQuery(args *ArgType) error

ParseQuery satisfies Loader's ParseQuery.

func (TypeLoader) Relkind

func (tl TypeLoader) Relkind(rt RelType) string

Relkind satisfies Loader's Relkind.

func (TypeLoader) SchemaName

func (tl TypeLoader) SchemaName(args *ArgType) (string, error)

SchemaName returns the active schema name.

Jump to

Keyboard shortcuts

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