From 9ddea390849afd5bd6844e3cf1c7148a656f1c67 Mon Sep 17 00:00:00 2001 From: yanghao05 Date: Fri, 23 May 2025 22:27:15 +0800 Subject: [PATCH] feat: add table functions --- pkg/ast/model/generage.go | 16 ++++++++++++---- pkg/ast/model/table_funcs.go.tpl | 11 ++++++++++- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/pkg/ast/model/generage.go b/pkg/ast/model/generage.go index f084c15..f97182b 100644 --- a/pkg/ast/model/generage.go +++ b/pkg/ast/model/generage.go @@ -26,10 +26,12 @@ var tableTestTpl string var providerTplStr string type TableModelParam struct { - PkgName string - CamelTable string // user - PascalTable string // User - SoftDelete bool + PkgName string + CamelTable string // user + PascalTable string // User + SoftDelete bool + HasUpdatedAt bool + HasCreatedAt bool } func Generate(tables []string, transformer Transformer) error { @@ -111,6 +113,12 @@ func Generate(tables []string, transformer Transformer) error { if strings.Contains(table, "DeletedAt") { tableInfo.SoftDelete = true } + if strings.Contains(table, "UpdatedAt") { + tableInfo.HasUpdatedAt = true + } + if strings.Contains(table, "CreatedAt") { + tableInfo.HasCreatedAt = true + } items = append(items, tableInfo) diff --git a/pkg/ast/model/table_funcs.go.tpl b/pkg/ast/model/table_funcs.go.tpl index ad19d2d..1a401ad 100644 --- a/pkg/ast/model/table_funcs.go.tpl +++ b/pkg/ast/model/table_funcs.go.tpl @@ -17,7 +17,15 @@ func (m *{{.PascalTable}}) log() *log.Entry { } func (m *{{.PascalTable}}) Create(ctx context.Context) error { + {{- if .HasCreatedAt}} m.CreatedAt = time.Now() + {{- end}} + + {{- if .HasUpdatedAt}} + m.UpdatedAt = time.Now() + {{- end}} + + stmt := table.Medias.INSERT(table.{{.PascalTable}}.MutableColumns).MODEL(m).RETURNING(table.Medias.AllColumns) m.log().WithField("func","Create").Info( stmt.DebugSql()) @@ -46,7 +54,6 @@ func (m *{{.PascalTable}}) BatchCreate(ctx context.Context, models []*{{.PascalT // if SoftDelete {{- if .SoftDelete }} - func (m *{{.PascalTable}}) Delete(ctx context.Context) error { stmt := table.{{.PascalTable}}.UPDATE().SET(table.{{.PascalTable}}.DeletedAt.Set(TimestampzT(time.Now()))).WHERE(table.{{.PascalTable}}.ID.EQ(Int(m.ID))) m.log().WithField("func", "SoftDelete").Info(stmt.DebugSql()) @@ -111,7 +118,9 @@ func (m *{{.PascalTable}}) BatchForceDelete(ctx context.Context, ids []int64) er } func (m *{{.PascalTable}}) Update(ctx context.Context) error { + {{- if .HasUpdatedAt}} m.UpdatedAt = time.Now() + {{- end}} stmt := table.{{.PascalTable}}.UPDATE(table.{{.PascalTable}}.MutableColumns.Except({{.CamelTable}}UpdateExcludeColumns...)).SET(m).WHERE(table.{{.PascalTable}}.ID.EQ(Int(m.ID))).RETURNING(table.{{.PascalTable}}.AllColumns) m.log().WithField("func", "Update").Info(stmt.DebugSql())