gomodel

package module
v0.9.2 Latest Latest
Warning

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

Go to latest
Published: Feb 29, 2024 License: BSD-2-Clause Imports: 23 Imported by: 0

README

Model and crud generator

This package contains logic to work with db models

Create model in specific directory

_, _, err := gomodel.MakeModel(base.App.GetDB(), "app/io/db/models", schema, table, "", gomodel.DefaultSystemColumnsSoft)
if err != nil {
    base.App.FatalError(err)
}

Create dictionary table

err := CreateDictionaryTable(base.App.GetDB())
if err != nil {
    base.App.FatalError(err)
}

Example of generated model

// Dictionary model
type Dictionary struct {
	// Dictionary row identifier
	Id *int32 `db:"col~id;prk;req;unq;" json:"id" valid:"required"`
	// Dictionary row type
	Type *string `db:"col~type;req;" json:"type" valid:"required"`
	// Dictionary row code
	Code *string `db:"col~code;req;" json:"code" valid:"required"`
	// Dictionary row value label
	Label *string `db:"col~label;" json:"label"`
	// Dictionary row created time
	CreatedAt *time.Time `db:"col~created_at;req;cat;" json:"createdAt"`
	// Dictionary row updated time
	UpdatedAt *time.Time `db:"col~updated_at;uat;" json:"updatedAt"`
	// Dictionary row deleted time
	DeletedAt *time.Time `db:"col~deleted_at;dat;" json:"deletedAt"`
}

// Table get Dictionary model table name
func (m *Dictionary) Table() string {
	return "dictionary"
}

// Columns get all Dictionary model columns
func (m *Dictionary) Columns() []string {
	return []string{"id", "type", "code", "label", "created_at", "updated_at", "deleted_at"}
}

// Values get all Dictionary model values
func (m *Dictionary) Values() []any {
	return []any{&m.Id, &m.Type, &m.Code, &m.Label, &m.CreatedAt, &m.UpdatedAt, &m.DeletedAt}
}

// NewDictionary init Dictionary model method
func NewDictionary() *Dictionary {
	return &Dictionary{}
}

// NewDictionaryCollection init Dictionary collection
func NewDictionaryCollection() *gomodel.Collection[Dictionary] {
	return gomodel.NewCollection[Dictionary]()
}

You can use collection for load, save, and delete collection items in mass action scenarios. Example

// Update items
c := NewDictionaryCollection()
c.Map(func(item *Dictionary) {
    if item.Label != nil {
        item.Label = nil
    }
})
c.Save(db)

// Load dictionary collection where label is not null and updated_at >= "2022-01-01"
c := NewDictionaryCollection()
c.Where().AddExpression("label IS NOT NULL")
c.Where().AddExpression("updated_at >= ?", time.Date(2022, 1, 1, 0,0,0,1, time.UTC))
e := c.Load(db)
if e != nil {
    return
}

// Delete if found items with such condition
if c.Count() > 0 {
    e = c.Delete(db)
    if e != nil {
        return
    }
}

Create dictionary mapping

err := GenerateDictionaryMapping("app/io/db/models/dictionary_mapping.go", base.App.GetDB())
if err != nil {
    base.App.FatalError(err)
}

Create CRUD operations and http client with swagger docs

crud := gomodel.NewCRUDGenerator("app/core", "app/client", "app/io/web/api", "gost")
err := crud.Generate(base.App.GetDB(), schema, table, "v1", gomodel.CrudNumber(args["num"].GetInt()))
if err != nil {
    base.App.FatalError(err)
}
If you find this project useful or want to support the author, you can send tokens to any of these wallets
  • Bitcoin: bc1qgx5c3n7q26qv0tngculjz0g78u6mzavy2vg3tf
  • Ethereum: 0x62812cb089E0df31347ca32A1610019537bbFe0D
  • Dogecoin: DET7fbNzZftp4sGRrBehfVRoi97RiPKajV

Documentation

Index

Constants

View Source
const (
	// DefaultSchema default database schema
	DefaultSchema = "public"
)

Variables

View Source
var ApiClientTemplate string
View Source
var ApiCreateTemplate string
View Source
var ApiDeleteTemplate string
View Source
var ApiReadTemplate string
View Source
var ApiRouteTemplate string
View Source
var ApiSearchTemplate string
View Source
var ApiUpdateTemplate string
View Source
var CrudTemplate string
View Source
var DefaultDictionaryTemplate string
View Source
var DefaultModelTemplate string
View Source
var DefaultSystemColumns = SystemColumns{Created: "created_at", Updated: "updated_at"}
View Source
var DefaultSystemColumnsSoft = SystemColumns{Created: "created_at", Updated: "updated_at", Deleted: "deleted_at"}
View Source
var SearchFormTemplate string

Functions

func BigSerialPrimaryKeyModifier added in v0.4.5

func BigSerialPrimaryKeyModifier(tb *gosql.Table)

BigSerialPrimaryKeyModifier create id bigserial primary key column

func BigSerialSoftTable added in v0.4.5

func BigSerialSoftTable(name string) *gosql.Table

BigSerialSoftTable init table for soft control model

func BigSerialTable added in v0.4.5

func BigSerialTable(name string) *gosql.Table

BigSerialTable init table for control model

func CreateDictionaryTable added in v0.2.0

func CreateDictionaryTable(q godb.Queryer) error

Create Table

func CreateFile added in v0.3.0

func CreateFile(name, path string) (*os.File, string, error)

CreateFile Create File

func CreateModelFile added in v0.2.0

func CreateModelFile(schema string, table string, path string) (*os.File, string, error)

CreateModelFile Create file in os

func Delete

func Delete(q godb.Queryer, model IModel) porterr.IError

Delete get isql and delete model

func Do

func Do(q godb.Queryer, isql gosql.ISQL) (e porterr.IError)

Do exec query on model

func GenerateDictionaryMapping added in v0.2.0

func GenerateDictionaryMapping(path string, q godb.Queryer) error

Create or update dictionary mapping

func GetColumn

func GetColumn(model IModel, field any) string

GetColumn model column in table

func GetColumns

func GetColumns(model IModel, field ...any) []string

GetColumns model columns by fields

func GetDeleteSQL

func GetDeleteSQL(model IModel) (iSQL gosql.ISQL)

GetDeleteSQL model delete query model - target model

func GetInsertSQL

func GetInsertSQL(model IModel, fields ...any) gosql.ISQL

GetInsertSQL model insert query

func GetLoadSQL

func GetLoadSQL(model IModel) gosql.ISQL

GetLoadSQL return sql query fot load model

func GetSaveSQL

func GetSaveSQL(model IModel) gosql.ISQL

GetSaveSQL prepare save query it can be insert or update or upsert some popular scenario was implemented. not all

func GetUpdateSQL

func GetUpdateSQL(model IModel, fields ...any) gosql.ISQL

GetUpdateSQL model update query model - target model fields - list of fields that you want to update

func GetValues

func GetValues(model IModel, columns ...string) (values []any)

GetValues model values by columns

func Load

func Load(q godb.Queryer, model IModel) porterr.IError

Load get isql and load model

func ParseModelFiledTag

func ParseModelFiledTag(tag string, field *ModelFiledTag)

ParseModelFiledTag parse validation tag for rule and arguments Example db:"col~created_at;seq;sys;prk;frk~master.table(id,name);req;unq'"

func Save

func Save(q godb.Queryer, model IModel) porterr.IError

Save get isql and save model

func SerialPrimaryKeyModifier added in v0.4.5

func SerialPrimaryKeyModifier(tb *gosql.Table)

SerialPrimaryKeyModifier create id serial primary key column

func SerialSoftTable added in v0.4.5

func SerialSoftTable(name string) *gosql.Table

SerialSoftTable init table for soft control model

func SerialTable added in v0.4.5

func SerialTable(name string) *gosql.Table

SerialTable init table for control model

func SoftModifier added in v0.4.5

func SoftModifier(tb *gosql.Table)

SoftModifier create soft deleted_at column

func TimestampModifier added in v0.4.5

func TimestampModifier(tb *gosql.Table)

TimestampModifier create timestamps

Types

type CRUDGenerator added in v0.3.0

type CRUDGenerator struct {
	// Path for crud folder
	CRUDPath string
	// Path for client folder
	ClientPath string
	// Path for api folder
	APIPath string
	// Path for project
	ProjectPath string
	// contains filtered or unexported fields
}

CRUDGenerator struct for crud generation

func NewCRUDGenerator added in v0.3.0

func NewCRUDGenerator(CRUDPath, ClientPath, APIPath, ProjectPath string) *CRUDGenerator

NewCRUDGenerator init crud generator

func (CRUDGenerator) AddToGlobalRoute added in v0.4.0

func (c CRUDGenerator) AddToGlobalRoute(logger gocli.Logger, schema, table, version string) (err error)

AddToGlobalRoute add global route for target entity

func (CRUDGenerator) Generate added in v0.3.0

func (c CRUDGenerator) Generate(q godb.Queryer, schema, table, version string, num CrudNumber) (err error)

Generate generate crud, client, api q - database connection schema - db schema (table namespace) table - name of table num - crud scenario (1 - create, 2 - read, 4 - update, 8 - delete, 16 - list)

func (*CRUDGenerator) GetColumns added in v0.4.2

func (c *CRUDGenerator) GetColumns(q godb.Queryer, schema, table string) (*Columns, error)

GetColumns lazy load for columns

func (*CRUDGenerator) GetPackage added in v0.4.2

func (c *CRUDGenerator) GetPackage(path string) string

GetPackage get package name

func (CRUDGenerator) MakeAPIClient added in v0.3.9

func (c CRUDGenerator) MakeAPIClient(logger gocli.Logger, schema, table, version string, num CrudNumber) (err error)

MakeAPIClient generate qpi search

func (CRUDGenerator) MakeAPICreate added in v0.3.0

func (c CRUDGenerator) MakeAPICreate(logger gocli.Logger, schema, table, version string) (err error)

MakeAPICreate generate qpi create

func (CRUDGenerator) MakeAPIDelete added in v0.3.0

func (c CRUDGenerator) MakeAPIDelete(logger gocli.Logger, schema, table, version string) (err error)

MakeAPIDelete generate qpi delete

func (CRUDGenerator) MakeAPIRead added in v0.3.0

func (c CRUDGenerator) MakeAPIRead(logger gocli.Logger, schema, table, version string) (err error)

MakeAPIRead generate qpi read

func (CRUDGenerator) MakeAPIRoute added in v0.3.6

func (c CRUDGenerator) MakeAPIRoute(logger gocli.Logger, schema, table, version string, num CrudNumber) (err error)

MakeAPIRoute generate qpi route

func (CRUDGenerator) MakeAPISearch added in v0.3.4

func (c CRUDGenerator) MakeAPISearch(logger gocli.Logger, schema, table, version string) (err error)

MakeAPISearch generate qpi search

func (CRUDGenerator) MakeAPIUpdate added in v0.3.0

func (c CRUDGenerator) MakeAPIUpdate(logger gocli.Logger, schema, table, version string) (err error)

MakeAPIUpdate generate api update

func (CRUDGenerator) MakeCoreCrud added in v0.3.0

func (c CRUDGenerator) MakeCoreCrud(logger gocli.Logger, schema, table string) (err error)

MakeCoreCrud generate core file

func (CRUDGenerator) MakeSearchForm added in v0.3.4

func (c CRUDGenerator) MakeSearchForm(logger gocli.Logger, schema, table string) (err error)

MakeSearchForm generate search form

func (CRUDGenerator) UpdateAPIClient added in v0.3.9

func (c CRUDGenerator) UpdateAPIClient(logger gocli.Logger, path string, content []byte, schema, table string, num CrudNumber) (err error)

UpdateAPIClient update client api callbacks

type Collection

type Collection[T any] struct {

	// Iterator
	*gohelp.Iterator
	// Query builder
	*gosql.Select
	// Count
	CountOver int
	// contains filtered or unexported fields
}

Collection struct contain items and collection common methods

func NewCollection

func NewCollection[T any]() *Collection[T]

NewCollection Create new model collection

func (*Collection[T]) AddCountOver

func (c *Collection[T]) AddCountOver()

AddCountOver add count column to SQL

func (*Collection[T]) AddItem

func (c *Collection[T]) AddItem(item ...*T)

AddItem Add item to collection

func (*Collection[T]) Clear added in v0.4.9

func (c *Collection[T]) Clear()

Clear collection

func (*Collection[T]) Delete

func (c *Collection[T]) Delete(q godb.Queryer) (e porterr.IError)

Delete delete items in collection

func (*Collection[T]) Filter

func (c *Collection[T]) Filter(callback func(*T) bool)

Filter collection

func (*Collection[T]) First

func (c *Collection[T]) First() *T

First get item of model collection

func (*Collection[T]) Item

func (c *Collection[T]) Item() *T

Item get item of collection

func (*Collection[T]) Items

func (c *Collection[T]) Items() []*T

Items Get all items

func (*Collection[T]) Last

func (c *Collection[T]) Last() *T

Last get item of model collection

func (*Collection[T]) Load

func (c *Collection[T]) Load(q godb.Queryer) porterr.IError

Load collection

func (*Collection[T]) Map

func (c *Collection[T]) Map(callback func(*T))

Map collection

func (*Collection[T]) RemoveCountOver

func (c *Collection[T]) RemoveCountOver()

RemoveCountOver remove count column from SQL

func (*Collection[T]) Save

func (c *Collection[T]) Save(q godb.Queryer) (e porterr.IError)

Save Create or Update collection items

type Column added in v0.2.0

type Column struct {
	Name              string  // DB column name
	ModelName         string  // Model name
	Default           *string // DB default value
	IsNullable        bool    // DB is nullable
	IsByteArray       bool    // Do not need type pointer for []byte
	DataType          string  // DB column type
	ModelType         string  // Model type
	Schema            string  // DB Schema
	Table             string  // DB table
	Sequence          *string // DB sequence
	ForeignSchema     *string // DB foreign schema name
	ForeignTable      *string // DB foreign table name
	ForeignColumnName *string // DB foreign column name
	ForeignIsSoft     bool    // DB foreign table is soft
	Description       *string // DB column description
	IsPrimaryKey      bool    // DB is primary key
	Tags              string  // Model Tags name
	Import            string  // Model Import custom lib
	IsArray           bool    // Array column
	IsCreated         bool    // Is created at column
	IsUpdated         bool    // Is updated at column
	IsDeleted         bool    // Is deleted at column
	HasUniqueIndex    bool    // If column is a part of unique index
	UniqueIndexName   *string // Unique index name
	TableDescription  *string // Table description
	DefaultTypeValue  *string // Default value for type
	IsPrecision       bool    // If column has float precision
}

Column information

func (Column) GetModelFieldTag added in v0.2.0

func (c Column) GetModelFieldTag() (field ModelFiledTag)

GetModelFieldTag Prepare ModelFiledTag by Column

func (Column) PrepareValidTag added in v0.2.0

func (c Column) PrepareValidTag(dictionary DictionaryItems) string

PrepareValidTag if dictionary item

type Columns added in v0.2.0

type Columns []Column

Array of columns

func GetTableColumns added in v0.2.0

func GetTableColumns(dbo godb.Queryer, schema string, table string, sysCols SystemColumns, dictionary DictionaryItems) (*Columns, error)

Get table columns from db

func MakeModel added in v0.2.0

func MakeModel(db godb.Queryer, dir string, schema string, table string, templatePath string, systemColumns SystemColumns) (modelName string, columns *Columns, err error)

MakeModel Create model

func (Columns) GetImports added in v0.2.0

func (c Columns) GetImports() []string

Get imports

func (Columns) GetTableDescription added in v0.2.0

func (c Columns) GetTableDescription() string

GetTableDescription get table comment

type CrudNumber added in v0.3.9

type CrudNumber uint8

CrudNumber calculate for type of crud method

func (CrudNumber) GetPossibleMethods added in v0.3.9

func (n CrudNumber) GetPossibleMethods() PossibleCrudMethods

GetPossibleMethods Calculate possible methods

func (CrudNumber) GetPossibleMethodsArray added in v0.3.9

func (n CrudNumber) GetPossibleMethodsArray() []string

GetPossibleMethodsArray return list of crud method based on num

type DictionaryItems added in v0.2.0

type DictionaryItems []*DictionaryModel

DictionaryItems dictionary collection items

func (DictionaryItems) GetTypeEnum added in v0.2.0

func (i DictionaryItems) GetTypeEnum(dictionaryType string) string

GetTypeEnum get enum type for validation

func (DictionaryItems) HasType added in v0.2.0

func (i DictionaryItems) HasType(dictionaryType string) bool

HasType check if type in collection

func (DictionaryItems) IsDictionaryColumn added in v0.2.0

func (i DictionaryItems) IsDictionaryColumn(name string) (string, bool)

IsDictionaryColumn check if column name has dictionary reference

type DictionaryModel added in v0.2.0

type DictionaryModel struct {
	// Dictionary row identifier
	Id *int32 `db:"col~id;prk;req;unq;" json:"id" valid:"required"`
	// Dictionary row type
	Type *string `db:"col~type;req;" json:"type" valid:"required"`
	// Dictionary row code
	Code *string `db:"col~code;req;" json:"code" valid:"required"`
	// Dictionary row value label
	Label *string `db:"col~label;" json:"label"`
	// Dictionary row system value
	IsSystem *bool `db:"col~is_system;" json:"isSystem"`
	// Dictionary row created time
	CreatedAt *time.Time `db:"col~created_at;req;cat;" json:"createdAt"`
	// Dictionary row updated time
	UpdatedAt *time.Time `db:"col~updated_at;uat;" json:"updatedAt"`
	// Dictionary row deleted time
	DeletedAt *time.Time `db:"col~deleted_at;dat;" json:"deletedAt"`
}

DictionaryModel model

func (*DictionaryModel) Columns added in v0.2.0

func (m *DictionaryModel) Columns() []string

Columns Model columns

func (*DictionaryModel) Table added in v0.2.0

func (m *DictionaryModel) Table() string

Table Model columns

func (*DictionaryModel) Values added in v0.2.0

func (m *DictionaryModel) Values() (values []interface{})

Values Model values

type IModel

type IModel interface {
	// Table Returns table name
	Table() string
	// Columns returns all columns
	Columns() []string
	// Values returns all model values
	Values() []any
}

IModel DB model interface

type MetaModel

type MetaModel struct {
	// Table name
	TableName string
	// Fields
	Fields ModelFiledTagList
}

MetaModel Meta model contain full information about model and fields

func PrepareMetaModel

func PrepareMetaModel(model IModel) *MetaModel

PrepareMetaModel Prepare Meta Model definition

type ModelFiledTag

type ModelFiledTag struct {
	// DB column name
	Column string `tag:"col"`
	// Foreign key definition
	ForeignKey string `tag:"frk"`
	// Has sequence
	IsSequence bool `tag:"seq"`
	// Is primary key
	IsPrimaryKey bool `tag:"prk"`
	// Is not null
	IsRequired bool `tag:"req"`
	// Is unique
	IsUnique bool `tag:"unq"`
	// Is created at column
	IsCreatedAt bool `tag:"cat"`
	// Is updated at column
	IsUpdatedAt bool `tag:"uat"`
	// Is deleted at column
	IsDeletedAt bool `tag:"dat"`
	// Is ignored column
	IsIgnored bool `tag:"ign"`
	// Is array value
	IsArray bool `tag:"arr"`
	// Interface to value
	Value any
}

ModelFiledTag All possible model field tag properties tag must have 3 symbol length

func (*ModelFiledTag) Clear added in v0.5.0

func (t *ModelFiledTag) Clear()

Clear tags

func (*ModelFiledTag) String

func (t *ModelFiledTag) String() string

Prepare string tag

type ModelFiledTagList

type ModelFiledTagList []ModelFiledTag

ModelFiledTagList list of ModelFiledTag

func (ModelFiledTagList) HasPrimary

func (l ModelFiledTagList) HasPrimary() bool

HasPrimary check if primary key exists

func (ModelFiledTagList) HasUnique

func (l ModelFiledTagList) HasUnique() bool

HasUnique check if unique key exists

func (ModelFiledTagList) IsSoft

func (l ModelFiledTagList) IsSoft() bool

IsSoft check if model possible to soft delete

func (ModelFiledTagList) Len

func (l ModelFiledTagList) Len() int

Len count of fields

type PossibleCrudMethods added in v0.3.9

type PossibleCrudMethods struct {
	// Create method
	Create bool
	// Read method
	Read bool
	// Update method
	Update bool
	// Delete method
	Delete bool
	// Search method
	Search bool
}

PossibleCrudMethods All possible crud methods

type SystemColumns added in v0.2.0

type SystemColumns struct {
	Created string
	Updated string
	Deleted string
}

Jump to

Keyboard shortcuts

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