gorma

package module
v0.0.0-...-e52600c Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2020 License: MIT Imports: 17 Imported by: 0

README

gorma

Gorma is a storage generator for goa.

Note: Gorma is not compatible with Goa v2 or v3 and requires v1.

GoDoc Build Status Go Report Card

Table of Contents

Purpose

Gorma uses a custom goa DSL to generate a working storage system for your API.

Opinionated

Gorma generates Go code that uses gorm to access your database, therefore it is quite opinionated about how the data access layer is generated.

By default, a primary key field is created as type int with name ID. Also Gorm's magic date stamp fields created_at, updated_at and deleted_at are created. Override this behavior with the Automatic* DSL functions on the Store.

Translations

Use the BuildsFrom and RendersTo DSL to have Gorma generate translation functions to translate your model to Media Types and from Payloads (User Types). If you don't have any complex business logic in your controllers, this makes a typical controller function 3-4 lines long.

Use

Write a storage definition using DSL from the dsl package. Example:

var sg = StorageGroup("MyStorageGroup", func() {
	Description("This is the global storage group")
	Store("mysql", gorma.MySQL, func() {
		Description("This is the mysql relational store")
		Model("Bottle", func() {
			BuildsFrom(func() {
				Payload("myresource","actionname")  // e.g. "bottle", "create" resource definition
			})

			RendersTo(Bottle)						// a Media Type definition
			Description("This is the bottle model")

			Field("ID", gorma.Integer, func() {    // Required for CRUD getters to take a PK argument!
				PrimaryKey()
				Description("This is the ID PK field")
			})

			Field("Vintage", gorma.Integer, func() {
				SQLTag("index")						// Add an index
			})

			Field("CreatedAt", gorma.Timestamp)
			Field("UpdatedAt", gorma.Timestamp)			 // Shown for demonstration
			Field("DeletedAt", gorma.NullableTimestamp)  // These are added by default
		})
	})
})

See the dsl GoDoc for all the details and options.

From the root of your application, issue the goagen command as follows:

$ goagen --design=github.com/gopheracademy/congo/design gen --pkg-path=github.com/kaizenplatform/gorma

Be sure to replace github.com/gopheracademy/congo/design with the design package of your goa application.

Documentation

Overview

Package gorma is a plugin generator for Goa (http://goa.design). See the documentation in the `dsl` package for details on how to create a definition for your API.

The `example` folder contains an example Goa design package. The `models.go` file is the Gorma definition, which is responsible for generating all the files in the `example\models` folder.

See specific documentation in the `dsl` package.

Index

Constants

View Source
const (
	// StorageGroup is the constant string used as the index in the
	// GormaConstructs map
	StorageGroup = "storagegroup"
	// MySQL is the StorageType for MySQL databases
	MySQL RelationalStorageType = "mysql"
	// Postgres is the StorageType for Postgres
	Postgres RelationalStorageType = "postgres"
	// SQLite3 is the StorageType for SQLite3 databases
	SQLite3 RelationalStorageType = "sqlite3"
	// None is For tests
	None RelationalStorageType = ""
	// Boolean is a bool field type
	Boolean FieldType = "bool"
	// Integer is an integer field type
	Integer FieldType = "integer"
	// BigInteger is a large integer field type
	BigInteger FieldType = "biginteger"
	// AutoInteger is not implemented
	AutoInteger FieldType = "auto_integer"
	// AutoBigInteger is not implemented
	AutoBigInteger FieldType = "auto_biginteger"
	// Decimal is a float field type
	Decimal FieldType = "decimal"
	// BigDecimal is a large float field type
	BigDecimal FieldType = "bigdecimal"
	// String is a varchar field type
	String FieldType = "string"
	// Text is a large string field type
	Text FieldType = "text"
	// Json is a large json field type
	Json FieldType = "json"
	// UUID is not implemented yet
	UUID FieldType = "uuid"
	// Timestamp is a date/time field in the database
	Timestamp FieldType = "timestamp"
	// NullableTimestamp is a timestamp that may not be
	// populated.  Fields with no value will be null in the database
	NullableTimestamp FieldType = "nulltimestamp"
	// NotFound is used internally
	NotFound FieldType = "notfound"
	// HasOne is used internally
	HasOne FieldType = "hasone"
	// HasOneKey is used internally
	HasOneKey FieldType = "hasonekey"
	// HasMany is used internally
	HasMany FieldType = "hasmany"
	// HasManyKey is used internally
	HasManyKey FieldType = "hasmanykey"
	// Many2Many is used internally
	Many2Many FieldType = "many2many"
	// Many2ManyKey is used internally
	Many2ManyKey FieldType = "many2manykey"
	// BelongsTo is used internally
	BelongsTo FieldType = "belongsto"
)

Variables

This section is empty.

Functions

func AddPlural

func AddPlural(suffix string, repl string)

AddPlural adds a rule that will replace the given suffix with the replacement suffix.

func AddSingular

func AddSingular(ext string, repl string)

AddSingular adds a rule that will replace the given suffix with the replacement suffix.

func Generate

func Generate() (files []string, err error)

Generate is the generator entry point called by the meta generator.

func Pluralize

func Pluralize(s string) string

Pluralize returns a plural version of the string

user = users
person = people
datum = data

func PluralizeWithSize

func PluralizeWithSize(s string, i int) string

PluralizeWithSize will pluralize a string taking a number number into account.

PluralizeWithSize("user", 1) = user
PluralizeWithSize("user", 2) = users

func Singularize

func Singularize(s string) string

Singularize returns a singular version of the string

users = user
data = datum
people = person

func Underscore

func Underscore(s string) string

Underscore a string

bob dylan = bob_dylan
Nice to see you! = nice_to_see_you
widgetID = widget_id

Types

type BuildSource

type BuildSource struct {
	dslengine.Definition
	DefinitionDSL   func()
	Parent          *RelationalModelDefinition
	BuildSourceName string
}

BuildSource stores the BuildsFrom sources for parsing.

func NewBuildSource

func NewBuildSource() *BuildSource

NewBuildSource returns an initialized BuildSource

func (*BuildSource) Context

func (f *BuildSource) Context() string

Context returns the generic definition name used in error messages.

func (*BuildSource) DSL

func (f *BuildSource) DSL() func()

DSL returns this object's DSL.

type BuildSourceIterator

type BuildSourceIterator func(m *BuildSource) error

BuildSourceIterator is a function that iterates over Fields in a RelationalModel.

type FieldIterator

type FieldIterator func(m *RelationalFieldDefinition) error

FieldIterator is a function that iterates over Fields in a RelationalModel.

type FieldType

type FieldType string

FieldType is the storage data type for a database field.

type Generator

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

Generator is the application code generator.

func (*Generator) Cleanup

func (g *Generator) Cleanup()

Cleanup removes the entire "app" directory if it was created by this generator.

func (*Generator) Generate

func (g *Generator) Generate(api *design.APIDefinition) (_ []string, err error)

Generate the application code, implement codegen.Generator.

type Ident

type Ident struct {
	Original string
	Parts    []string
}

Ident represents the string and it's parts

func New

func New(s string) Ident

New creates a new Ident from the string

func (*Ident) LastPart

func (i *Ident) LastPart() string

LastPart returns the last part/word of the original string

func (Ident) MarshalText

func (i Ident) MarshalText() ([]byte, error)

MarshalText marshals Ident into byte array

func (Ident) Pluralize

func (i Ident) Pluralize() Ident

Pluralize returns a plural version of the string

user = users
person = people
datum = data

func (Ident) ReplaceSuffix

func (i Ident) ReplaceSuffix(orig, new string) Ident

ReplaceSuffix creates a new Ident with the original suffix replaced by new

func (Ident) Singularize

func (i Ident) Singularize() Ident

Singularize returns a singular version of the string

users = user
data = datum
people = person

func (Ident) String

func (i Ident) String() string

String implements fmt.Stringer and returns the original string

func (Ident) Underscore

func (i Ident) Underscore() Ident

Underscore a string

bob dylan = bob_dylan
Nice to see you! = nice_to_see_you
widgetID = widget_id

func (*Ident) UnmarshalText

func (i *Ident) UnmarshalText(data []byte) error

UnmarshalText unmarshalls byte array into the Ident

type ManyToManyDefinition

type ManyToManyDefinition struct {
	dslengine.Definition
	DefinitionDSL    func()
	Left             *RelationalModelDefinition
	Right            *RelationalModelDefinition
	RelationshipName string // ??
	DatabaseField    string
}

ManyToManyDefinition stores information about a ManyToMany relationship between two domain objects.

func (*ManyToManyDefinition) LeftName

func (m *ManyToManyDefinition) LeftName() string

LeftName returns the name of the "owner" of the m2m relationship.

func (*ManyToManyDefinition) LeftNamePlural

func (m *ManyToManyDefinition) LeftNamePlural() string

LeftNamePlural returns the pluralized version of the "owner" of the m2m relationship.

func (*ManyToManyDefinition) LowerLeftName

func (m *ManyToManyDefinition) LowerLeftName() string

LowerLeftName returns the lower case name of the "owner" of the m2m relationship.

func (*ManyToManyDefinition) LowerRightName

func (m *ManyToManyDefinition) LowerRightName() string

LowerRightName returns the name of the "child" of the m2m relationship.

func (*ManyToManyDefinition) RightName

func (m *ManyToManyDefinition) RightName() string

RightName returns the name of the "child" of the m2m relationship.

func (*ManyToManyDefinition) RightNamePlural

func (m *ManyToManyDefinition) RightNamePlural() string

RightNamePlural returns the pluralized version of the "child" of the m2m relationship.

type MapDefinition

type MapDefinition struct {
	RemoteType  *design.UserTypeDefinition
	RemoteField string
}

MapDefinition represents field mapping to and from Gorma models.

func NewMapDefinition

func NewMapDefinition() *MapDefinition

NewMapDefinition returns an initialized MapDefinition.

type MediaTypeAdapterDefinition

type MediaTypeAdapterDefinition struct {
	dslengine.Definition
	DefinitionDSL func()
	Name          string
	Description   string
	Left          *design.MediaTypeDefinition
	Right         *RelationalModelDefinition
}

MediaTypeAdapterDefinition represents the transformation of a Goa media type into a Gorma Model.

Unimplemented at this time.

type ModelIterator

type ModelIterator func(m *RelationalModelDefinition) error

ModelIterator is a function that iterates over Models in a RelationalStore.

type PayloadAdapterDefinition

type PayloadAdapterDefinition struct {
	dslengine.Definition
	DefinitionDSL func()
	Name          string
	Description   string
	Left          *design.UserTypeDefinition
	Right         *RelationalModelDefinition
}

PayloadAdapterDefinition represents the transformation of a Goa Payload (which is really a UserTypeDefinition) into a Gorma model.

Unimplemented at this time.

type RelationalFieldDefinition

type RelationalFieldDefinition struct {
	dslengine.Definition
	DefinitionDSL func()
	Parent        *RelationalModelDefinition

	FieldName         string
	TableName         string
	Datatype          FieldType
	SQLTag            string
	DatabaseFieldName string // gorm:column
	Description       string
	Nullable          bool
	PrimaryKey        bool
	Timestamp         bool
	Size              int // string field size
	BelongsTo         string
	HasOne            string
	HasMany           string
	Many2Many         string
	Mappings          map[string]*MapDefinition
	// contains filtered or unexported fields
}

RelationalFieldDefinition represents a field in a relational database.

func NewRelationalFieldDefinition

func NewRelationalFieldDefinition() *RelationalFieldDefinition

NewRelationalFieldDefinition returns an initialized RelationalFieldDefinition.

func (*RelationalFieldDefinition) Attribute

Attribute implements the Container interface of the goa Attribute model.

func (RelationalFieldDefinition) Children

Children returns a slice of this objects children.

func (*RelationalFieldDefinition) Context

func (f *RelationalFieldDefinition) Context() string

Context returns the generic definition name used in error messages.

func (*RelationalFieldDefinition) DSL

func (f *RelationalFieldDefinition) DSL() func()

DSL returns this object's DSL.

func (*RelationalFieldDefinition) FieldDefinition

func (f *RelationalFieldDefinition) FieldDefinition() string

FieldDefinition returns the field's struct definition.

func (*RelationalFieldDefinition) LowerName

func (f *RelationalFieldDefinition) LowerName() string

LowerName returns the field name as a lowercase string.

func (*RelationalFieldDefinition) Tags

Tags returns the sql and gorm struct tags for the Definition.

func (*RelationalFieldDefinition) Underscore

func (f *RelationalFieldDefinition) Underscore() string

Underscore returns the field name as a lowercase string in snake case.

func (*RelationalFieldDefinition) Validate

Validate tests whether the RelationalField definition is consistent.

type RelationalModelDefinition

type RelationalModelDefinition struct {
	dslengine.Definition
	*design.UserTypeDefinition
	DefinitionDSL    func()
	ModelName        string
	Description      string
	GoaType          *design.MediaTypeDefinition
	Parent           *RelationalStoreDefinition
	BuiltFrom        map[string]*design.UserTypeDefinition
	BuildSources     []*BuildSource
	RenderTo         map[string]*design.MediaTypeDefinition
	BelongsTo        map[string]*RelationalModelDefinition
	HasMany          map[string]*RelationalModelDefinition
	HasOne           map[string]*RelationalModelDefinition
	ManyToMany       map[string]*ManyToManyDefinition
	Alias            string // gorm:tablename
	Cached           bool
	CacheDuration    int
	Roler            bool
	DynamicTableName bool
	SQLTag           string
	RelationalFields map[string]*RelationalFieldDefinition
	PrimaryKeys      []*RelationalFieldDefinition
	// contains filtered or unexported fields
}

RelationalModelDefinition implements the storage of a domain model into a table in a relational database.

func NewRelationalModelDefinition

func NewRelationalModelDefinition() *RelationalModelDefinition

NewRelationalModelDefinition returns an initialized RelationalModelDefinition.

func (*RelationalModelDefinition) Attribute

Attribute implements the Container interface of goa.

func (RelationalModelDefinition) Children

Children returns a slice of this objects children.

func (*RelationalModelDefinition) Context

func (f *RelationalModelDefinition) Context() string

Context returns the generic definition name used in error messages.

func (*RelationalModelDefinition) DSL

func (f *RelationalModelDefinition) DSL() func()

DSL returns this object's DSL.

func (*RelationalModelDefinition) IterateBuildSources

func (f *RelationalModelDefinition) IterateBuildSources(it BuildSourceIterator) error

IterateBuildSources runs an iterator function once per Model in the Store's model list.

func (*RelationalModelDefinition) IterateFields

func (f *RelationalModelDefinition) IterateFields(it FieldIterator) error

IterateFields returns an iterator function useful for iterating through this model's field list.

func (*RelationalModelDefinition) LowerName

func (f *RelationalModelDefinition) LowerName() string

LowerName returns the model name as a lowercase string.

func (*RelationalModelDefinition) PKAttributes

func (f *RelationalModelDefinition) PKAttributes() string

PKAttributes constructs a pair of field + definition strings useful for method parameters.

func (*RelationalModelDefinition) PKUpdateFields

func (f *RelationalModelDefinition) PKUpdateFields(modelname string) string

PKUpdateFields returns something? This function doesn't look useful in current form. Perhaps it isn't.

func (*RelationalModelDefinition) PKWhere

func (f *RelationalModelDefinition) PKWhere() string

PKWhere returns an array of strings representing the where clause of a retrieval by primary key(s) -- x = ? and y = ?.

func (*RelationalModelDefinition) PKWhereFields

func (f *RelationalModelDefinition) PKWhereFields() string

PKWhereFields returns the fields for a where clause for the primary keys of a model.

func (*RelationalModelDefinition) PopulateFromModeledType

func (f *RelationalModelDefinition) PopulateFromModeledType()

PopulateFromModeledType creates fields for the model based on the goa UserTypeDefinition it models, which is set using BuildsFrom(). This happens before fields are processed, so it's ok to just assign without testing.

func (*RelationalModelDefinition) Project

Project does something interesting, and I don't remember if I use it anywhere.

TODO find out

func (*RelationalModelDefinition) StructDefinition

func (f *RelationalModelDefinition) StructDefinition() string

StructDefinition returns the struct definition for the model.

func (RelationalModelDefinition) TableName

func (f RelationalModelDefinition) TableName() string

TableName returns the TableName of the struct.

func (*RelationalModelDefinition) Underscore

func (f *RelationalModelDefinition) Underscore() string

Underscore returns the model name as a lowercase string in snake case.

func (*RelationalModelDefinition) Validate

Validate tests whether the RelationalModel definition is consistent.

type RelationalStorageType

type RelationalStorageType string

RelationalStorageType is the type of database.

type RelationalStoreDefinition

type RelationalStoreDefinition struct {
	dslengine.Definition
	DefinitionDSL    func()
	Name             string
	Description      string
	Parent           *StorageGroupDefinition
	Type             RelationalStorageType
	RelationalModels map[string]*RelationalModelDefinition
	NoAutoIDFields   bool
	NoAutoTimestamps bool
	NoAutoSoftDelete bool
}

RelationalStoreDefinition is the parent configuration structure for Gorm relational model definitions.

func NewRelationalStoreDefinition

func NewRelationalStoreDefinition() *RelationalStoreDefinition

NewRelationalStoreDefinition returns an initialized RelationalStoreDefinition.

func (RelationalStoreDefinition) Children

Children returns a slice of this objects children.

func (*RelationalStoreDefinition) Context

func (sd *RelationalStoreDefinition) Context() string

Context returns the generic definition name used in error messages.

func (*RelationalStoreDefinition) DSL

func (sd *RelationalStoreDefinition) DSL() func()

DSL returns this object's DSL.

func (*RelationalStoreDefinition) IterateModels

func (sd *RelationalStoreDefinition) IterateModels(it ModelIterator) error

IterateModels runs an iterator function once per Model in the Store's model list.

func (*RelationalStoreDefinition) Validate

Validate tests whether the RelationalStore definition is consistent.

type StorageGroupDefinition

type StorageGroupDefinition struct {
	dslengine.Definition
	DefinitionDSL    func()
	Name             string
	Description      string
	RelationalStores map[string]*RelationalStoreDefinition
}

StorageGroupDefinition is the parent configuration structure for Gorma definitions.

var GormaDesign *StorageGroupDefinition

GormaDesign is the root definition for Gorma

func NewStorageGroupDefinition

func NewStorageGroupDefinition() *StorageGroupDefinition

NewStorageGroupDefinition returns an initialized StorageGroupDefinition.

func (StorageGroupDefinition) Children

Children returns a slice of this objects children.

func (StorageGroupDefinition) Context

func (sd StorageGroupDefinition) Context() string

Context returns the generic definition name used in error messages.

func (StorageGroupDefinition) DSL

func (sd StorageGroupDefinition) DSL() func()

DSL returns this object's DSL.

func (*StorageGroupDefinition) DSLName

func (sd *StorageGroupDefinition) DSLName() string

DSLName is displayed to the user when the DSL executes.

func (*StorageGroupDefinition) DependsOn

func (sd *StorageGroupDefinition) DependsOn() []dslengine.Root

DependsOn return the DSL roots the Gorma DSL root depends on, that's the goa API DSL.

func (*StorageGroupDefinition) IterateSets

func (sd *StorageGroupDefinition) IterateSets(iterator dslengine.SetIterator)

IterateSets goes over all the definition sets of the StorageGroup: the StorageGroup definition itself, each store definition, models and fields.

func (*StorageGroupDefinition) IterateStores

func (sd *StorageGroupDefinition) IterateStores(it StoreIterator) error

IterateStores runs an iterator function once per Relational Store in the StorageGroup's Store list.

func (*StorageGroupDefinition) Reset

func (sd *StorageGroupDefinition) Reset()

Reset resets the storage group to pre DSL execution state.

func (*StorageGroupDefinition) Validate

Validate tests whether the StorageGroup definition is consistent.

type StoreIterator

type StoreIterator func(m *RelationalStoreDefinition) error

StoreIterator is a function that iterates over Relational Stores in a StorageGroup.

type UserHelperWriter

type UserHelperWriter struct {
	*codegen.SourceFile
	UserHelperTmpl *template.Template
}

UserHelperWriter generate code for a goa application user types. User types are data structures defined in the DSL with "Type".

func NewUserHelperWriter

func NewUserHelperWriter(filename string) (*UserHelperWriter, error)

NewUserHelperWriter returns a contexts code writer. User types contain custom data structured defined in the DSL with "Type".

func (*UserHelperWriter) Execute

func (w *UserHelperWriter) Execute(data *UserTypeTemplateData) error

Execute writes the code for the context types to the writer.

type UserTypeAdapterDefinition

type UserTypeAdapterDefinition struct {
	dslengine.Definition
	DefinitionDSL func()
	Name          string
	Description   string
	Left          *RelationalModelDefinition
	Right         *RelationalModelDefinition
}

UserTypeAdapterDefinition represents the transformation of a Goa user type into a Gorma Model.

Unimplemented at this time.

type UserTypeTemplateData

type UserTypeTemplateData struct {
	APIDefinition *design.APIDefinition
	UserType      *RelationalModelDefinition
	DefaultPkg    string
	AppPkg        string
}

UserTypeTemplateData contains all the information used by the template to redner the media types code.

type UserTypesWriter

type UserTypesWriter struct {
	*codegen.SourceFile
	UserTypeTmpl   *template.Template
	UserHelperTmpl *template.Template
}

UserTypesWriter generate code for a goa application user types. User types are data structures defined in the DSL with "Type".

func NewUserTypesWriter

func NewUserTypesWriter(filename string) (*UserTypesWriter, error)

NewUserTypesWriter returns a contexts code writer. User types contain custom data structured defined in the DSL with "Type".

func (*UserTypesWriter) Execute

func (w *UserTypesWriter) Execute(data *UserTypeTemplateData) error

Execute writes the code for the context types to the writer.

Directories

Path Synopsis
Package dsl uses the Goa DSL engine to generate a data storage layer for your Goa API.
Package dsl uses the Goa DSL engine to generate a data storage layer for your Goa API.

Jump to

Keyboard shortcuts

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