generator

package
v1.3.3 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2017 License: MIT Imports: 24 Imported by: 0

Documentation

Overview

Package generator implements the processor of source code and generator of kallax models based on Go source code.

Index

Constants

View Source
const (
	// BaseModel is the type name of the kallax base model.
	BaseModel = "gopkg.in/src-d/go-kallax.v1.Model"
	//URL is the type name of the net/url.URL.
	URL = "url.URL"
)
View Source
const (
	// StoreNamePattern is the pattern used to name stores.
	StoreNamePattern = "%sStore"
	// QueryNamePattern is the pattern used to name queries.
	QueryNamePattern = "%sQuery"
	// ResultSetNamePattern is the pattern used to name result sets.
	ResultSetNamePattern = "%sResultSet"
)

Variables

View Source
var Base = &Template{template: base}

Base is the default Template instance with all templates preloaded.

Functions

This section is empty.

Types

type AddColumn added in v1.2.0

type AddColumn struct {
	// Column schema.
	Column *ColumnSchema
	// Table to add the column to.
	Table string
}

AddColumn is a change that will add a column.

func (*AddColumn) MarshalText added in v1.2.0

func (c *AddColumn) MarshalText() ([]byte, error)

func (*AddColumn) Reverse added in v1.2.0

func (c *AddColumn) Reverse(old *DBSchema) Change

func (*AddColumn) String added in v1.2.0

func (c *AddColumn) String() string

type Change added in v1.2.0

type Change interface {
	encoding.TextMarshaler
	fmt.Stringer
	// Reverse returns the change that will revert the current change.
	Reverse(old *DBSchema) Change
}

Change represents a change to be made in a migration.

type ChangeSet added in v1.2.0

type ChangeSet []Change

ChangeSet is a set of changes to be made in a migration.

func ColumnSchemaDiff added in v1.2.0

func ColumnSchemaDiff(table string, old, new *ColumnSchema) ChangeSet

ColumnSchemaDiff generates the change set with the diff between two column schemas.

func SchemaDiff added in v1.2.0

func SchemaDiff(old, new *DBSchema) ChangeSet

SchemaDiff generates a change set with the diff between two schemas.

func TableSchemaDiff added in v1.2.0

func TableSchemaDiff(old, new *TableSchema) ChangeSet

TableSchemaDiff generates a change set with the diff between two table schemas.

func (ChangeSet) MarshalText added in v1.2.0

func (cs ChangeSet) MarshalText() ([]byte, error)

func (ChangeSet) Reverse added in v1.2.0

func (cs ChangeSet) Reverse(old *DBSchema) Change

Reverse returns the change that will revert the current change set.

func (ChangeSet) ReverseChangeSet added in v1.2.0

func (cs ChangeSet) ReverseChangeSet(old *DBSchema) ChangeSet

ReverseChangeSet returns the reverse change set of the current one.

func (ChangeSet) String added in v1.2.0

func (cs ChangeSet) String() string

type ColumnSchema added in v1.2.0

type ColumnSchema struct {
	// Name of the column.
	Name string
	// Type of the column.
	Type ColumnType
	// PrimaryKey reports whether the column is a primary key.
	PrimaryKey bool
	// Reference is an optional reference to another table column.
	// If it's not nil, it means this column has a foreign key.
	Reference *Reference
	// NotNull reports whether the column is not nullable.
	NotNull bool
	// Unique reports whether the column has a unique constraint
	Unique bool
}

ColumnSchema represents the schema of a column.

func (*ColumnSchema) Equals added in v1.2.0

func (s *ColumnSchema) Equals(s2 *ColumnSchema) bool

func (*ColumnSchema) String added in v1.2.0

func (s *ColumnSchema) String() string

type ColumnType added in v1.2.0

type ColumnType string

ColumnType represents the SQL column type.

const (
	ByteaColumn       ColumnType = "bytea"
	SmallIntColumn    ColumnType = "smallint"
	IntegerColumn     ColumnType = "integer"
	BigIntColumn      ColumnType = "bigint"
	RealColumn        ColumnType = "real"
	DoubleColumn      ColumnType = "double precision"
	SmallSerialColumn ColumnType = "smallserial"
	SerialColumn      ColumnType = "serial"
	BigSerialColumn   ColumnType = "bigserial"
	TimestamptzColumn ColumnType = "timestamptz"
	TextColumn        ColumnType = "text"
	JSONBColumn       ColumnType = "jsonb"
	BooleanColumn     ColumnType = "boolean"
	UUIDColumn        ColumnType = "uuid"
)

func ArrayColumn added in v1.2.0

func ArrayColumn(typ ColumnType) ColumnType

func DecimalColumn added in v1.2.0

func DecimalColumn(precision, scale int) ColumnType

func NumericColumn added in v1.2.0

func NumericColumn(precision int) ColumnType

type CreateIndex added in v1.3.0

type CreateIndex struct {
	// Table name.
	Table string
	// Column name.
	Column string
	// Kind of index.
	Kind string
}

CreateIndex is a change that will create an index.

func (*CreateIndex) MarshalText added in v1.3.0

func (c *CreateIndex) MarshalText() ([]byte, error)

func (*CreateIndex) Reverse added in v1.3.0

func (c *CreateIndex) Reverse(old *DBSchema) Change

func (*CreateIndex) String added in v1.3.0

func (c *CreateIndex) String() string

type CreateTable added in v1.2.0

type CreateTable struct {
	*TableSchema
}

CreateTable is a change that will add a new table.

func (*CreateTable) MarshalText added in v1.2.0

func (c *CreateTable) MarshalText() ([]byte, error)

func (*CreateTable) Reverse added in v1.2.0

func (c *CreateTable) Reverse(old *DBSchema) Change

func (*CreateTable) String added in v1.2.0

func (c *CreateTable) String() string

type DBSchema added in v1.2.0

type DBSchema struct {
	// Tables are the schema of all the tables.
	Tables []*TableSchema
}

DBSchema represents a schema of all the models in the database.

func SchemaFromPackages added in v1.2.0

func SchemaFromPackages(pkgs ...*Package) (*DBSchema, error)

SchemaFromPackages returns a schema for the given packages models.

func (*DBSchema) MarshalText added in v1.2.0

func (s *DBSchema) MarshalText() ([]byte, error)

func (*DBSchema) Table added in v1.2.0

func (s *DBSchema) Table(name string) *TableSchema

Table finds a table with the given name.

type DropColumn added in v1.2.0

type DropColumn struct {
	// Name of the column.
	Name string
	// Table name.
	Table string
}

DropColumn is a change that will drop a column.

func (*DropColumn) MarshalText added in v1.2.0

func (c *DropColumn) MarshalText() ([]byte, error)

func (*DropColumn) Reverse added in v1.2.0

func (c *DropColumn) Reverse(old *DBSchema) Change

func (*DropColumn) String added in v1.2.0

func (c *DropColumn) String() string

type DropIndex added in v1.3.0

type DropIndex struct {
	// Table name.
	Table string
	// Column name.
	Column string
	// Kind of index.
	Kind string
}

DropIndex is a change that will drop an index.

func (*DropIndex) MarshalText added in v1.3.0

func (c *DropIndex) MarshalText() ([]byte, error)

func (*DropIndex) Reverse added in v1.3.0

func (c *DropIndex) Reverse(old *DBSchema) Change

func (*DropIndex) String added in v1.3.0

func (c *DropIndex) String() string

type DropTable added in v1.2.0

type DropTable struct {
	// Name is the name of the table to drop.
	Name string
}

DropTable is a change that will drop a table.

func (*DropTable) MarshalText added in v1.2.0

func (c *DropTable) MarshalText() ([]byte, error)

func (*DropTable) Reverse added in v1.2.0

func (c *DropTable) Reverse(old *DBSchema) Change

func (*DropTable) String added in v1.2.0

func (c *DropTable) String() string

type Event

type Event string

Event is the name of an event.

const (
	// BeforeInsert is an event that will happen before Insert operations.
	BeforeInsert Event = "BeforeInsert"
	// AfterInsert is an event that will happen after Insert operations.
	AfterInsert Event = "AfterInsert"
	// BeforeUpdate is an event that will happen before Update operations.
	BeforeUpdate Event = "BeforeUpdate"
	// AfterUpdate is an event that will happen after Update operations.
	AfterUpdate Event = "AfterUpdate"
	// BeforeSave is an event that will happen before Insert or Update
	// operations.
	BeforeSave Event = "BeforeSave"
	// AfterSave is an event that will happen after Insert or Update
	// operations.
	AfterSave Event = "AfterSave"
	// BeforeDelete is an event that will happen before Delete.
	BeforeDelete Event = "BeforeDelete"
	// AfterDelete is an event that will happen after Delete.
	AfterDelete Event = "AfterDelete"
)

type Events

type Events []Event

Events is a collection of events.

func (Events) Has

func (s Events) Has(e Event) bool

Has reports whether the event is in the collection.

type Field

type Field struct {
	// Name is the field name.
	Name string
	// Type is the string representation of the field type.
	Type string
	// Kind is the kind of field.
	Kind FieldKind
	// Node is the reference to the field node.
	Node *types.Var
	// Tag is the strug tag of the field.
	Tag reflect.StructTag
	// Fields contains all the children fields of the field. A field has
	// children only if it is a struct.
	Fields []*Field
	// Parent is a reference to the parent field.
	Parent *Field
	// Model is the reference to the model containing this field.
	Model *Model
	// IsPtr reports whether the field is a pointer type or not.
	IsPtr bool
	// IsJSON reports whether the field has to be converted to JSON.
	IsJSON bool
	// IsAlias reports whether the field is of a type that aliases some other type.
	IsAlias bool
	// IsEmbedded reports whether the field is an embedded struct or not.
	// A struct is considered embedded if and only if the struct was embedded
	// as defined in Go.
	IsEmbedded bool
	// contains filtered or unexported fields
}

Field is the representation of a model field.

func NewField

func NewField(n, t string, tag reflect.StructTag) *Field

NewField creates a new field with its name, type and struct tag.

func (*Field) Address

func (f *Field) Address() string

Address returns the string representation of the code used to get the pointer to the field.

func (*Field) ColumnName

func (f *Field) ColumnName() string

ColumnName returns the SQL valid column name of the field. The struct tag `kallax` of the field can be use to set the name, otherwise is the field name converted to lower snake case. If the resultant name is a reserved keyword a _ will be prepended to the name.

func (*Field) ForeignKey

func (f *Field) ForeignKey() string

ForeignKey returns the name of the foreign keys as specified in the struct tag `fk` or the default foreign key, which is the name of the relationship type in lower snake case with "_id" appended.

func (*Field) Inline

func (f *Field) Inline() bool

Inline reports whether the field is inline and its children will be in the root of the model. An inline field is the one having the type kallax.Model, one that has a struct tag `kallax` containing `,inline` or an embedded struct field.

func (*Field) IsAutoIncrement added in v0.13.0

func (f *Field) IsAutoIncrement() bool

IsAutoIncrement reports whether the field is an autoincrementable primary key.

func (*Field) IsInverse added in v0.12.0

func (f *Field) IsInverse() bool

IsInverse returns whether the field is an inverse relationship.

func (*Field) IsOneToManyRelationship added in v0.12.0

func (f *Field) IsOneToManyRelationship() bool

IsOneToManyRelationship returns whether the field is a one to many relationship.

func (*Field) IsPrimaryKey added in v0.13.0

func (f *Field) IsPrimaryKey() bool

IsPrimaryKey reports whether the field is the primary key.

func (*Field) IsUnique added in v1.3.0

func (f *Field) IsUnique() bool

IsUnique reports whether the field is unique.

func (*Field) JSONName added in v0.13.0

func (f *Field) JSONName() string

JSONName returns the name of the field or its JSON name specified in the JSON struct tag.

func (*Field) SQLType added in v1.2.0

func (f *Field) SQLType() string

func (*Field) SetFields

func (f *Field) SetFields(sf []*Field)

SetFields sets all the children fields and the current field as a parent of the children.

func (*Field) String

func (f *Field) String() string

func (*Field) TypeSchemaName

func (f *Field) TypeSchemaName() string

TypeSchemaName returns the name of the Schema for the field type.

func (*Field) Value

func (f *Field) Value() string

Value is the string representation of the code needed to get the value of the field in a way that SQL drivers can process.

type FieldKind

type FieldKind int

FieldKind is the kind of a field.

const (
	// Basic is a field with a basic type.
	// On top of the Go basic types, we consider Basic as well the following
	// types:
	//  - time.Time
	//  - time.Duration
	//  - url.URL
	Basic FieldKind = iota
	// Array is a field with an array type.
	Array
	// Slice is a field with a slice type.
	Slice
	// Map is a field with a map type.
	Map
	// Interface is a field with an interface type.
	Interface
	// Struct is a field with a struct type.
	Struct
	// Relationship is a field which is a relationship to other model/s.
	Relationship
	// Invalid is an invalid field type.
	Invalid
)

func (FieldKind) String added in v0.13.0

func (t FieldKind) String() string

String returns the constant name of the FieldKind

type Generator

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

Generator is in charge of generating files for packages.

func NewGenerator

func NewGenerator(filename string) *Generator

NewGenerator creates a new generator that can save on the given filename.

func (*Generator) Generate

func (g *Generator) Generate(pkg *Package) error

Generate writes the file with the contents of the given package.

type ImplicitFK added in v1.2.10

type ImplicitFK struct {
	Name string
	Type string
}

ImplicitFK is a foreign key that is defined on just one side of the relationship and needs to be added on the other side.

type ManualChange added in v1.2.0

type ManualChange struct {
	Msg string
}

ManualChange is a change that cannot be made automatically and requires the user to write a proper migration.

func (*ManualChange) MarshalText added in v1.2.0

func (c *ManualChange) MarshalText() ([]byte, error)

func (*ManualChange) Reverse added in v1.2.0

func (c *ManualChange) Reverse(old *DBSchema) Change

func (*ManualChange) String added in v1.2.0

func (c *ManualChange) String() string

type Migration added in v1.2.0

type Migration struct {
	// Up contains the changes to update from the previous version to the current one.
	Up ChangeSet
	// Down contains all the changes to downgrade to the previous version.
	Down ChangeSet
	// Lock contains the locked model schema.
	Lock *DBSchema
}

Migration contains all the data to represent a schema migration.

func NewMigration added in v1.2.0

func NewMigration(old, new *DBSchema) (*Migration, error)

NewMigration creates a new migration from the old and the new schema.

type MigrationGenerator added in v1.2.0

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

MigrationGenerator is a generator of migrations.

func NewMigrationGenerator added in v1.2.0

func NewMigrationGenerator(name, dir string) *MigrationGenerator

NewMigrationGenerator returns a new migration generator with the given migrations directory.

func (*MigrationGenerator) Build added in v1.2.0

func (g *MigrationGenerator) Build(pkgs ...*Package) (*Migration, error)

Build creates a new migration from a set of scanned packages.

func (*MigrationGenerator) Generate added in v1.2.0

func (g *MigrationGenerator) Generate(migration *Migration) error

Generate will generate the given migration.

func (*MigrationGenerator) LoadLock added in v1.2.0

func (g *MigrationGenerator) LoadLock() (*DBSchema, error)

LoadLock loads the lock file.

type Model

type Model struct {
	// Name is the model name.
	Name string
	// StoreName is the name of the store for this model.
	StoreName string
	// QueryName is the name of the query for this model.
	QueryName string
	// ResultSetName is the name of the result set for this model.
	ResultSetName string

	// Table is the name of the table, which will be extracted from the `table`
	// struct tag of the kallax.Model field in the model.
	// If one is not provided, it will be the model name transformed to lower
	// snake case. A model with an empty table name is not valid.
	Table string
	// Type is the string representation of the type.
	Type string
	// Fields contains the list of fields in the model.
	Fields []*Field
	// ImplicitFKs contains the list of fks that are implicit based on
	// other models' definitions, such as foreign keys with no explicit inverse
	// on the related model.
	ImplicitFKs []ImplicitFK
	// ID contains the identifier field of the model.
	ID *Field
	// Events contains the list of events implemented by the model.
	Events Events
	// Node is the node where the model was defined.
	Node *types.Named
	// CtorFunc is a reference to the model constructor.
	CtorFunc *types.Func
	// Package is a reference to the package where the model was defined.
	Package *types.Package
}

Model is the representation of an user-defined model.

func NewModel

func NewModel(n string) *Model

NewModel creates a new model with the given name.

func (*Model) Alias

func (m *Model) Alias() string

Alias returns the alias of the model, which is the lowercased name preceded by "__".

func (*Model) CtorArgVars

func (m *Model) CtorArgVars() string

CtorArgVars returns the string representation of the variables to call the scanned constructor in the generated constructor.

func (*Model) CtorArgs

func (m *Model) CtorArgs() string

CtorArgs returns the string with the generated constructor arguments, based on the constructor scanned, if any.

func (*Model) CtorRetVars

func (m *Model) CtorRetVars() string

CtorRetVars returns the string representation of the return variables to receive in the generated constructor based on the ones in the scanned constructor.

func (*Model) CtorReturns

func (m *Model) CtorReturns() string

CtorReturns returns the string representation of the return values of the generated constructor based on the ones in the scanned constructor.

func (*Model) HasInverses added in v1.1.0

func (m *Model) HasInverses() bool

HasInverses returns whether the model has inverse relationships or not.

func (*Model) HasNonInverses added in v1.1.0

func (m *Model) HasNonInverses() bool

HasNonInverses returns whether the model has non inverse relationships or not.

func (*Model) HasRelationships added in v0.12.0

func (m *Model) HasRelationships() bool

HasRelationships returns whether the model has relationships or not.

func (*Model) Inverses added in v1.1.0

func (m *Model) Inverses() []*Field

Inverses returns the inverse relationships of the model.

func (*Model) NonInverses added in v1.1.0

func (m *Model) NonInverses() []*Field

NonInverses returns the relationships of the model that are not inverses.

func (*Model) Relationships

func (m *Model) Relationships() []*Field

Relationships returns the fields of a model that are relationships.

func (*Model) SetFields added in v0.12.0

func (m *Model) SetFields(fields []*Field) error

SetFields sets all the children fields and their model to the current model. It also finds the primary key and sets it in the model. It will return an error if more than one primary key is found. SetFields always sets the primary key as the first field of the model. So, all models can expect to have the primary key in the position 0 of their field slice. This is because the Store will expect the ID in that position.

func (*Model) String

func (m *Model) String() string

String prints the representation of the model.

func (*Model) Validate

func (m *Model) Validate() error

Validate returns an error if the model is not valid. To be valid, a model needs a non-empty table name, a non-repeated set of fields.

type Package

type Package struct {

	// Name is the package name.
	Name string
	// Models are all the models found in the package.
	Models []*Model
	// contains filtered or unexported fields
}

Package is the representation of a scanned package.

func NewPackage added in v0.13.0

func NewPackage(pkg *types.Package) *Package

NewPackage creates a new package.

func (*Package) FindModel added in v0.13.0

func (p *Package) FindModel(name string) *Model

FindModel finds the model with the given name.

func (*Package) SetModels added in v0.13.0

func (p *Package) SetModels(models []*Model)

SetModels sets the models of the packages and indexes them.

type Processor

type Processor struct {
	// Path of the package.
	Path string
	// Ignore is the list of files to ignore when scanning.
	Ignore map[string]struct{}
	// Package is the scanned package.
	Package *types.Package
	// contains filtered or unexported fields
}

Processor is in charge of processing the package in a patch and scan models from it.

func NewProcessor

func NewProcessor(path string, ignore []string) *Processor

NewProcessor creates a new Processor for the given path and ignored files.

func (*Processor) Do

func (p *Processor) Do() (*Package, error)

Do performs all the processing and returns the scanned package.

func (*Processor) Silent added in v1.2.0

func (p *Processor) Silent()

Silent makes the processor not spit any output to stdout.

type Reference added in v1.2.0

type Reference struct {
	// Table is the referenced table.
	Table string
	// Column is the referenced column.
	Column string
	// contains filtered or unexported fields
}

Reference represents a reference to another table column.

func (*Reference) Equals added in v1.2.0

func (r *Reference) Equals(r2 *Reference) bool

func (*Reference) String added in v1.2.0

func (r *Reference) String() string

type TableSchema added in v1.2.0

type TableSchema struct {
	// Name is the table name.
	Name string
	// Columns are the schemas of the columns in the table.
	Columns []*ColumnSchema
}

TableSchema represents the SQL schema of a table.

func (*TableSchema) Column added in v1.2.0

func (s *TableSchema) Column(name string) *ColumnSchema

Columns returns the schema of the column with the given name.

func (*TableSchema) Equals added in v1.2.0

func (s *TableSchema) Equals(s2 *TableSchema) bool

func (*TableSchema) String added in v1.2.0

func (s *TableSchema) String() string

type Template

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

Template renders the kallax templates using given packages.

func (*Template) Execute

func (t *Template) Execute(wr io.Writer, data *Package) error

Execute writes the processed template to the given writer.

type TemplateData

type TemplateData struct {
	*Package
	// Processed is a map to keep track of processed nodes.
	Processed map[interface{}]string
	// contains filtered or unexported fields
}

TemplateData is the structure passed to fill the templates.

func (*TemplateData) GenColumnAddresses

func (td *TemplateData) GenColumnAddresses(model *Model) string

GenColumnAddresses generates the body of the switch that returns the column address given a column name for the given model.

func (*TemplateData) GenColumnValues

func (td *TemplateData) GenColumnValues(model *Model) string

GenColumnValues generates the body of the switch that returns the column address given a column name for the given model.

func (*TemplateData) GenFindBy added in v1.0.0

func (td *TemplateData) GenFindBy(model *Model) string

GenFindBy generates FindByPropertyName for all model properties that are valid types or collection of valid types.

func (*TemplateData) GenModelColumns

func (td *TemplateData) GenModelColumns(model *Model) string

GenModelColumns generates the creation of the list of columns in the given model.

func (*TemplateData) GenModelSchema

func (td *TemplateData) GenModelSchema(model *Model) string

GenModelSchema generates generates the fields of the struct definition in the given model.

func (*TemplateData) GenSchemaInit

func (td *TemplateData) GenSchemaInit(model *Model) string

GenSchemaInit generates the code to initialize all fields in the schema of a model.

func (*TemplateData) GenSubSchemas

func (td *TemplateData) GenSubSchemas() string

GenSubSchemas generates the struct definition of all the subschemas in all models. A subschema is the JSON schema of a field that will be stored as JSON.

func (*TemplateData) GenTimeTruncations added in v1.2.0

func (td *TemplateData) GenTimeTruncations(model *Model) string

func (*TemplateData) GenTypeName

func (td *TemplateData) GenTypeName(f *Field) string

GenTypeName generates the name of the type in the field.

func (*TemplateData) IdentifierType added in v0.13.0

func (td *TemplateData) IdentifierType(f *Field) string

func (*TemplateData) IsPtrSlice added in v0.12.0

func (td *TemplateData) IsPtrSlice(f *Field) bool

IsPtrSlice returns whether the field is a slice of pointers or not.

type Timestamper added in v1.2.0

type Timestamper func() time.Time

Timestamper is a function that returns the current time.

Directories

Path Synopsis
cli

Jump to

Keyboard shortcuts

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