Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gen AddMethod not working #1261

Open
TerminalFi opened this issue Feb 17, 2025 · 0 comments
Open

gen AddMethod not working #1261

TerminalFi opened this issue Feb 17, 2025 · 0 comments

Comments

@TerminalFi
Copy link

Your Question

What is wrong with this code that it is not Generating the Common Methods on my models

None of the CommonMethod funcs appear in my model or query package

// USED TO GENERATE THE QUERY INTERFACE
// go run generate_queries.go
package main

import (
	"gorm.io/driver/postgres"
	"gorm.io/gen"
	"gorm.io/gorm"
)

type CommonMethod struct {
	ID   int32
	Name *string
}

func (m *CommonMethod) IsEmpty() bool {
	if m == nil {
		return true
	}
	return m.ID == 0
}

func (m *CommonMethod) GetName() string {
	if m == nil || m.Name == nil {
		return ""
	}
	return *m.Name
}

func main() {
	g := gen.NewGenerator(gen.Config{
		OutPath:          "./query",
		Mode:             gen.WithoutContext | gen.WithDefaultQuery | gen.WithQueryInterface, // generate mode
		WithUnitTest:     true,
		FieldWithTypeTag: true,
	})
	g.WithOpts(gen.WithMethod(CommonMethod{}))
	dsn := "host=127.0.0.1 user=postgres password=postgres dbname=postgres port=54322"
	gormdb, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}

	var dataMap = map[string]func(gorm.ColumnType) (dataType string){
		"uuid": func(columnType gorm.ColumnType) (dataType string) {
			if n, ok := columnType.Nullable(); ok && n {
				return "*uuid.UUID"
			}
			return "uuid.UUID"
		},
		"jsonb": func(columnType gorm.ColumnType) (dataType string) {
			return "datatypes.JSON"
		},
	}

	g.UseDB(gormdb) // reuse your gorm db
	g.WithDataTypeMap(dataMap)
	g.WithImportPkgPath("github.com/randonv/db/types")

	// Generate basic type-safe DAO API for struct `model.User` following conventions

	g.GenerateModel("repositories", gen.FieldType("languages", "datatypes.JSONType[types.RepositoryLanguages]"))

	// Generate the code
	g.Execute()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant