modelgen

package
v1.6.5-rc32 Latest Latest
Warning

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

Go to latest
Published: Feb 6, 2024 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	BuilderPkg = "github.com/machinefi/w3bstream/pkg/depends/kit/sqlx/builder"
	SQLxPkg    = "github.com/machinefi/w3bstream/pkg/depends/kit/sqlx"
)

Functions

func IndexCond

func IndexCond(f *g.File, fns ...string) string

Types

type Config

type Config struct {
	StructName string
	TableName  string
	Database   string

	WithComments        bool
	WithTableName       bool
	WithTableInterfaces bool
	WithMethods         bool

	FieldPrimaryKey   string
	FieldKeyDeletedAt string
	FieldKeyCreatedAt string
	FieldKeyUpdatedAt string
}

func (*Config) SetDefault

func (g *Config) SetDefault()

type Generator

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

func New

func New(pkg *pkgx.Pkg) *Generator

func (*Generator) Output

func (g *Generator) Output(cwd string)

func (*Generator) Scan

func (g *Generator) Scan()

type Keys

type Keys struct {
	Primary       []string
	Indexes       builder.Indexes
	UniqueIndexes builder.Indexes
}

func (*Keys) Bind

func (ks *Keys) Bind(tbl *builder.Table)

func (*Keys) WithSoftDelete

func (ks *Keys) WithSoftDelete(f string)

type Model

type Model struct {
	*types.TypeName
	*Config
	*Keys
	*builder.Table
	Fields                map[string]*types.Var
	FieldKeyAutoIncrement string
	HasDeletedAt          bool
	HasCreatedAt          bool
	HasUpdatedAt          bool
	HasAutoIncrement      bool
}

func GetModelByName

func GetModelByName(g *Generator, name string) *Model

func NewModel

func NewModel(pkg *pkgx.Pkg, tn *types.TypeName, doc string, cfg *Config) *Model

func (*Model) AddColumnAndField

func (m *Model) AddColumnAndField(col *builder.Column, tpe *types.Var)

func (*Model) DeletedAtCondAttach

func (m *Model) DeletedAtCondAttach(f *g.File, tbl, cond *g.SnippetIdent) g.SnippetSpec

func (*Model) DeletedAtCondInitial

func (m *Model) DeletedAtCondInitial(f *g.File, tbl, cond *g.SnippetIdent) g.SnippetSpec

func (*Model) FileType

func (m *Model) FileType(f *g.File, fn string) g.SnippetType

func (*Model) GetColDesc

func (m *Model) GetColDesc() map[string][]string

func (*Model) GetColRel

func (m *Model) GetColRel() map[string][]string

func (*Model) GetComments

func (m *Model) GetComments() map[string]string

func (*Model) GetIndexFieldNames

func (m *Model) GetIndexFieldNames() []string

func (*Model) IteratorPtrType

func (m *Model) IteratorPtrType() g.SnippetType

func (*Model) IteratorType

func (m *Model) IteratorType() g.SnippetType

func (*Model) PtrType

func (m *Model) PtrType() g.SnippetType

func (*Model) SetCreatedSnippet

func (m *Model) SetCreatedSnippet(f *g.File) g.Snippet

func (*Model) SetDeletedSnippetForFVs

func (m *Model) SetDeletedSnippetForFVs(f *g.File, fvs *g.SnippetIdent) g.Snippet

func (*Model) SetUpdatedSnippet

func (m *Model) SetUpdatedSnippet(f *g.File) g.Snippet

func (*Model) SetUpdatedSnippetForFVs

func (m *Model) SetUpdatedSnippetForFVs(f *g.File, fvs *g.SnippetIdent) g.Snippet

func (*Model) SnippetCRUDByUniqueKeys

func (m *Model) SnippetCRUDByUniqueKeys(f *g.File, keys ...string) []g.Snippet

SnippetCRUDByUniqueKeys generate below UpdateByXXX to update record by value m XXX is UniqueIndexNames contacted by `And`; function name like `UpdateByNameAndIDAnd...` func (m *`Model`) UpdateByXXX(DBExecutor, zeros...) FetchByXXX to select record by some unique index XXX is UniqueIndexNames contacted by `And`; function name like `FetchByNameAndIDAnd...` func (m *`Model`) FetchByXXX(DBExecutor) error // XXX is UniqueIndexNames Delete by value condition func (m *`Model`) Delete(DBExecutor) error DeleteByXXX to delete record by some unique index XXX is UniqueIndexNames contacted by `And`; function name like `DeleteByNameAndIDAnd...` func (m *`Model`) DeleteByXXX(DBExecutor) error // XXX is UniqueIndexNames SoftDeleteByXXX to update `DeleteAt` flag as current time func (m *`Model`) SoftDeleteByXXX(DBExecutor) error // XXX is UniqueIndexNames

Example
ss := m.SnippetCRUDByUniqueKeys(f, "primary", "ui_name")
for _, s := range ss {
	fmt.Print(string(s.Bytes()))
}
Output:

func (m *User) FetchByID(db sqlx.DBExecutor) error {
tbl := db.T(m)
err := db.QueryAndScan(
builder.Select(nil).
From(
tbl,
builder.Where(
builder.And(
tbl.ColByFieldName("ID").Eq(m.ID),
tbl.ColByFieldName("DeletedAt").Eq(m.DeletedAt),
),
),
builder.Comment("User.FetchByID"),
),
m,
)
return err
}func (m *User) FetchByName(db sqlx.DBExecutor) error {
tbl := db.T(m)
err := db.QueryAndScan(
builder.Select(nil).
From(
tbl,
builder.Where(
builder.And(
tbl.ColByFieldName("Name").Eq(m.Name),
tbl.ColByFieldName("DeletedAt").Eq(m.DeletedAt),
),
),
builder.Comment("User.FetchByName"),
),
m,
)
return err
}func (m *User) UpdateByIDWithFVs(db sqlx.DBExecutor, fvs builder.FieldValues) error {

if _, ok := fvs["UpdatedAt"]; !ok {
fvs["UpdatedAt"] = types.Timestamp{Time: time.Now()}
}
tbl := db.T(m)
res, err := db.Exec(
builder.Update(tbl).
Where(
builder.And(
tbl.ColByFieldName("ID").Eq(m.ID),
tbl.ColByFieldName("DeletedAt").Eq(m.DeletedAt),
),
builder.Comment("User.UpdateByIDWithFVs"),
).
Set(tbl.AssignmentsByFieldValues(fvs)...),
)
if err != nil {
return err
}
if affected, _ := res.RowsAffected(); affected == 0 {
return m.FetchByID(db)
}
return nil
}func (m *User) UpdateByID(db sqlx.DBExecutor, zeros ...string) error {
fvs := builder.FieldValueFromStructByNoneZero(m, zeros...)
return m.UpdateByIDWithFVs(db, fvs)
}func (m *User) UpdateByNameWithFVs(db sqlx.DBExecutor, fvs builder.FieldValues) error {

if _, ok := fvs["UpdatedAt"]; !ok {
fvs["UpdatedAt"] = types.Timestamp{Time: time.Now()}
}
tbl := db.T(m)
res, err := db.Exec(
builder.Update(tbl).
Where(
builder.And(
tbl.ColByFieldName("Name").Eq(m.Name),
tbl.ColByFieldName("DeletedAt").Eq(m.DeletedAt),
),
builder.Comment("User.UpdateByNameWithFVs"),
).
Set(tbl.AssignmentsByFieldValues(fvs)...),
)
if err != nil {
return err
}
if affected, _ := res.RowsAffected(); affected == 0 {
return m.FetchByName(db)
}
return nil
}func (m *User) UpdateByName(db sqlx.DBExecutor, zeros ...string) error {
fvs := builder.FieldValueFromStructByNoneZero(m, zeros...)
return m.UpdateByNameWithFVs(db, fvs)
}func (m *User) Delete(db sqlx.DBExecutor) error {
_, err := db.Exec(
builder.Delete().
From(
db.T(m),
builder.Where(m.CondByValue(db)),
builder.Comment("User.Delete"),
),
)
return err
}func (m *User) DeleteByID(db sqlx.DBExecutor) error {
tbl := db.T(m)
_, err := db.Exec(
builder.Delete().
From(
tbl,
builder.Where(
builder.And(
tbl.ColByFieldName("ID").Eq(m.ID),
tbl.ColByFieldName("DeletedAt").Eq(m.DeletedAt),
),
),
builder.Comment("User.DeleteByID"),
),
)
return err
}func (m *User) SoftDeleteByID(db sqlx.DBExecutor) error {
tbl := db.T(m)
fvs := builder.FieldValues{}

if _, ok := fvs["DeletedAt"]; !ok {
fvs["DeletedAt"] = types.Timestamp{Time: time.Now()}
}

if _, ok := fvs["UpdatedAt"]; !ok {
fvs["UpdatedAt"] = types.Timestamp{Time: time.Now()}
}
_, err := db.Exec(
builder.Update(db.T(m)).
Where(
builder.And(
tbl.ColByFieldName("ID").Eq(m.ID),
tbl.ColByFieldName("DeletedAt").Eq(m.DeletedAt),
),
builder.Comment("User.SoftDeleteByID"),
).
Set(tbl.AssignmentsByFieldValues(fvs)...),
)
return err
}func (m *User) DeleteByName(db sqlx.DBExecutor) error {
tbl := db.T(m)
_, err := db.Exec(
builder.Delete().
From(
tbl,
builder.Where(
builder.And(
tbl.ColByFieldName("Name").Eq(m.Name),
tbl.ColByFieldName("DeletedAt").Eq(m.DeletedAt),
),
),
builder.Comment("User.DeleteByName"),
),
)
return err
}func (m *User) SoftDeleteByName(db sqlx.DBExecutor) error {
tbl := db.T(m)
fvs := builder.FieldValues{}

if _, ok := fvs["DeletedAt"]; !ok {
fvs["DeletedAt"] = types.Timestamp{Time: time.Now()}
}

if _, ok := fvs["UpdatedAt"]; !ok {
fvs["UpdatedAt"] = types.Timestamp{Time: time.Now()}
}
_, err := db.Exec(
builder.Update(db.T(m)).
Where(
builder.And(
tbl.ColByFieldName("Name").Eq(m.Name),
tbl.ColByFieldName("DeletedAt").Eq(m.DeletedAt),
),
builder.Comment("User.SoftDeleteByName"),
).
Set(tbl.AssignmentsByFieldValues(fvs)...),
)
return err
}

func (*Model) SnippetColDesc

func (m *Model) SnippetColDesc(f *g.File) g.Snippet

SnippetColDesc generate below ColDesc implements builder.WithColDesc func (`Model`) ColDesc() map[string][]string

Example
fmt.Println(string(m.SnippetColDesc(f).Bytes()))
Output:

func (*User) ColDesc() map[string][]string {
return map[string][]string{
"Name": []string{
"姓名",
},
"Nickname": []string{
"昵称",
},
"OrgID": []string{
"关联组织",
"组织ID",
},
"Username": []string{
"用户名",
},
}
}

func (*Model) SnippetColRel

func (m *Model) SnippetColRel(f *g.File) g.Snippet

SnippetColRel generate below ColRel implements builder.WithColRel func (`Model`) ColRel() map[string][]string

Example
fmt.Println(string(m.SnippetColRel(f).Bytes()))
Output:

func (*User) ColRel() map[string][]string {
return map[string][]string{
"OrgID": []string{
"Org",
"ID",
},
}
}

func (*Model) SnippetComments

func (m *Model) SnippetComments(f *g.File) g.Snippet

SnippetComments generate below Comments implements builder.WithComments func(`Model`) Comments() map[string]string // field_name: comment line

Example
fmt.Println(string(m.SnippetComments(f).Bytes()))
Output:

func (*User) Comments() map[string]string {
return map[string]string{
"Name": "姓名",
"Nickname": "昵称",
"OrgID": "关联组织",
"Username": "用户名",
}
}

func (*Model) SnippetCondByValue

func (m *Model) SnippetCondByValue(f *g.File) g.Snippet

SnippetCondByValue generate below func (m *`Model`) CondByValue(DBExecutor) builder.SqlCondition // condition of this

Example
fmt.Println(string(m.SnippetCondByValue(f).Bytes()))
Output:

func (m *User) CondByValue(db sqlx.DBExecutor) builder.SqlCondition {
var (
tbl = db.T(m)
fvs = builder.FieldValueFromStructByNoneZero(m)
cond = []builder.SqlCondition{tbl.ColByFieldName("DeletedAt").Eq(0)}
)

for _, fn := range m.IndexFieldNames() {
if v, ok := fvs[fn]; ok {
cond = append(cond, tbl.ColByFieldName(fn).Eq(v))
delete(fvs, fn)
}
}
if len(cond) == 0 {
panic(fmt.Errorf("no field for indexes has value"))
}
for fn, v := range fvs {
cond = append(cond, tbl.ColByFieldName(fn).Eq(v))
}
return builder.And(cond...)
}

func (*Model) SnippetCount

func (m *Model) SnippetCount(f *g.File) g.Snippet

SnippetCount generate below Count by condition and addition(offset, size) func (m *`Model`) Count(DBExecutor, SqlCondition, Additions) (int64, error)

Example
fmt.Print(string(m.SnippetCount(f).Bytes()))
Output:

func (m *User) Count(db sqlx.DBExecutor, cond builder.SqlCondition, adds ...builder.Addition) (cnt int64, err error) {
tbl := db.T(m)
cond = builder.And(tbl.ColByFieldName("DeletedAt").Eq(0), cond)
adds = append([]builder.Addition{builder.Where(cond), builder.Comment("User.List")}, adds...)
err = db.QueryAndScan(builder.Select(builder.Count()).From(tbl, adds...), &cnt)
return
}

func (*Model) SnippetCreate

func (m *Model) SnippetCreate(f *g.File) g.Snippet

SnippetCreate generate below Create to create record by value m func (m *`Model`) Create(DBExecutor) error // Create by this

Example
fmt.Println(string(m.SnippetCreate(f).Bytes()))
Output:

func (m *User) Create(db sqlx.DBExecutor) error {

if m.CreatedAt.IsZero() {
m.CreatedAt.Set(time.Now())
}

if m.UpdatedAt.IsZero() {
m.UpdatedAt.Set(time.Now())
}

_, err := db.Exec(sqlx.InsertToDB(db, m, nil))
return err
}

func (*Model) SnippetFieldMethods

func (m *Model) SnippetFieldMethods(f *g.File) []g.Snippet

SnippetFieldMethods generate below func (m *`Model`) ColXXX() *builder.Column // FOR EACH Field, return field column func (m `Model`) FieldXXX() string // FOR EACH Field, return field name

Example
ss := m.SnippetFieldMethods(f)
for _, s := range ss {
	fmt.Print(string(s.Bytes()))
}
Output:

func (m *User) ColID() *builder.Column {
return UserTable.ColByFieldName(m.FieldID())
}func (*User) FieldID() string {
return "ID"
}func (m *User) ColName() *builder.Column {
return UserTable.ColByFieldName(m.FieldName())
}func (*User) FieldName() string {
return "Name"
}func (m *User) ColNickname() *builder.Column {
return UserTable.ColByFieldName(m.FieldNickname())
}func (*User) FieldNickname() string {
return "Nickname"
}func (m *User) ColUsername() *builder.Column {
return UserTable.ColByFieldName(m.FieldUsername())
}func (*User) FieldUsername() string {
return "Username"
}func (m *User) ColGender() *builder.Column {
return UserTable.ColByFieldName(m.FieldGender())
}func (*User) FieldGender() string {
return "Gender"
}func (m *User) ColBoolean() *builder.Column {
return UserTable.ColByFieldName(m.FieldBoolean())
}func (*User) FieldBoolean() string {
return "Boolean"
}func (m *User) ColGeom() *builder.Column {
return UserTable.ColByFieldName(m.FieldGeom())
}func (*User) FieldGeom() string {
return "Geom"
}func (m *User) ColOrgID() *builder.Column {
return UserTable.ColByFieldName(m.FieldOrgID())
}func (*User) FieldOrgID() string {
return "OrgID"
}func (m *User) ColCreatedAt() *builder.Column {
return UserTable.ColByFieldName(m.FieldCreatedAt())
}func (*User) FieldCreatedAt() string {
return "CreatedAt"
}func (m *User) ColUpdatedAt() *builder.Column {
return UserTable.ColByFieldName(m.FieldUpdatedAt())
}func (*User) FieldUpdatedAt() string {
return "UpdatedAt"
}func (m *User) ColDeletedAt() *builder.Column {
return UserTable.ColByFieldName(m.FieldDeletedAt())
}func (*User) FieldDeletedAt() string {
return "DeletedAt"
}

func (*Model) SnippetIndexFieldNames

func (m *Model) SnippetIndexFieldNames(f *g.File) g.Snippet

SnippetIndexFieldNames generate below func (m *`Model`) IndexFieldNames() []string // index field name list

Example
fmt.Println(string(m.SnippetIndexFieldNames(f).Bytes()))
Output:

func (m *User) IndexFieldNames() []string {
return []string{
"ID",
"Name",
"OrgID",
"Username",
}
}

func (*Model) SnippetIndexes

func (m *Model) SnippetIndexes(f *g.File) g.Snippet

SnippetIndexes generate below Indexes implements builder.WithIndexes func(`Model`) Indexes() builder.Indexes

Example
fmt.Println(string(m.SnippetIndexes(f).Bytes()))
Output:

func (*User) Indexes() builder.Indexes {
return builder.Indexes{
"i_geom/SPATIAL": []string{
"(#Geom)",
},
"i_nickname/BTREE": []string{
"Name",
},
"i_username": []string{
"Username",
},
}
}

func (*Model) SnippetList

func (m *Model) SnippetList(f *g.File) g.Snippet

SnippetList generate below List by condition and additions(offset, size) func (m *`Model`) List(DBExecutor, SqlCondition, Additions) []`Model`

Example
fmt.Println(string(m.SnippetList(f).Bytes()))
Output:

func (m *User) List(db sqlx.DBExecutor, cond builder.SqlCondition, adds ...builder.Addition) ([]User, error) {
var (
tbl = db.T(m)
lst = make([]User, 0)
)
cond = builder.And(tbl.ColByFieldName("DeletedAt").Eq(0), cond)
adds = append([]builder.Addition{builder.Where(cond), builder.Comment("User.List")}, adds...)
err := db.QueryAndScan(builder.Select(nil).From(tbl, adds...), &lst)
return lst, err
}

func (*Model) SnippetPrimaryKey

func (m *Model) SnippetPrimaryKey(f *g.File) g.Snippet

SnippetPrimaryKey generate below PrimaryKey implements builder.WithPrimaryKey func(`Model`) PrimaryKey() []string

Example
fmt.Println(string(m.SnippetPrimaryKey(f).Bytes()))
Output:

func (*User) PrimaryKey() []string {
return []string{
"ID",
}
}

func (*Model) SnippetTableDesc

func (m *Model) SnippetTableDesc(f *g.File) g.Snippet

SnippetTableDesc generate below TableDesc implements builder.WithTableDesc func (`Model`) TableDesc() []string

Example
fmt.Println(string(m.SnippetTableDesc(f).Bytes()))
Output:

func (*User) TableDesc() []string {
return []string{
"User 用户表",
}
}

func (*Model) SnippetTableInstanceAndInit

func (m *Model) SnippetTableInstanceAndInit(f *g.File) []g.Snippet

SnippetTableInstanceAndInit generated below `Model`Table *builder.Table func init() { `Model`Table = `DB`.Register(&`Model`{})

Example
ss := m.SnippetTableInstanceAndInit(f)
for _, s := range ss {
	fmt.Println(string(s.Bytes()))
}
Output:

var UserTable *builder.Table
func init() {
UserTable=DB.Register(&User{})
}

func (*Model) SnippetTableIteratorAndMethods

func (m *Model) SnippetTableIteratorAndMethods(_ *g.File) []g.Snippet

SnippetTableIteratorAndMethods generate below `Model`Iterator struct{} func (`Model`Table) New() interface{} { return &`Model`{} } func (`Model`Table) Resolve(v interface{}) *`Model` { return v.(*`Model`) }

Example
ss := m.SnippetTableIteratorAndMethods(f)
for _, s := range ss {
	fmt.Println(string(s.Bytes()))
}
Output:

type UserIterator struct {
}
func (*UserIterator) New() interface{} {
return &User{}
}
func (*UserIterator) Resolve(v interface{}) *User {
return v.(*User)
}

func (*Model) SnippetTableName

func (m *Model) SnippetTableName(f *g.File) g.Snippet

SnippetTableName generate below TableName implements builder.Model func (`Model`) TableName() string

Example
fmt.Println(string(m.SnippetTableName(f).Bytes()))
Output:

func (*User) TableName() string {
return "t_user"
}

func (*Model) SnippetUniqueIndexes

func (m *Model) SnippetUniqueIndexes(f *g.File) []g.Snippet

SnippetUniqueIndexes generate below UniqueIndexes() implements `builder.WithUniqueIndexes` func(`Model`) UniqueIndexes() builder.Indexes [db_index_name->field_names] func(`Model`) UniqueIndexXXX() string; [for each unique index, XXX is index name]

Example
ss := m.SnippetUniqueIndexes(f)
for _, s := range ss {
	fmt.Println(string(s.Bytes()))
}
Output:

func (*User) UniqueIndexes() builder.Indexes {
return builder.Indexes{
"ui_id_org": []string{
"ID",
"OrgID",
"DeletedAt",
},
"ui_name": []string{
"Name",
"DeletedAt",
},
}
}
func (*User) UniqueIndexUIIDOrg() string {
return "ui_id_org"
}
func (*User) UniqueIndexUIName() string {
return "ui_name"
}

func (*Model) Type

func (m *Model) Type() g.SnippetType

func (*Model) VarTable

func (m *Model) VarTable() string

func (*Model) WriteTo

func (m *Model) WriteTo(f *g.File)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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