go zero dev template

v3
veypi 4 months ago
parent 54a200f297
commit 852c491e85

@ -19,7 +19,7 @@ fmt:
@goctl api format --dir ./api @goctl api format --dir ./api
gen_sql: gen_sql:
@goctl model mysql ddl -c --database oa -d ./models -s ./protoc/sql/base.sql @goctl model mysql ddl --database oa -d ./models -s ./protoc/sql/20240801061157_base.sql
# add sql script # add sql script
# sqlx migrate --source ./protoc/sql add base # sqlx migrate --source ./protoc/sql add base
@ -32,3 +32,6 @@ gen_db:
gen_api: gen_api:
@goctl api go -api ./protoc/api/all.api -dir ./ @goctl api go -api ./protoc/api/all.api -dir ./
run:
@go run main.go -f ./etc/main.yaml

@ -0,0 +1,32 @@
//
// errors.go
// Copyright (C) 2024 veypi <i@veypi.com>
// 2024-08-01 15:40
// Distributed under terms of the MIT license.
//
package errs
import (
"fmt"
)
type CodeMsg struct {
Code int
Msg string
}
func (c *CodeMsg) Error() string {
return fmt.Sprintf("code: %d, msg: %s", c.Code, c.Msg)
}
// New creates a new CodeMsg.
func New(code int, msg string) error {
return &CodeMsg{Code: code, Msg: msg}
}
var (
AuthFailed = New(401, "auth failed")
AuthExpired = New(401, "auth expired")
AuthInvalid = New(401, "auth invalid")
)

@ -0,0 +1,39 @@
//
// response.go
// Copyright (C) 2024 veypi <i@veypi.com>
// 2024-08-01 16:42
// Distributed under terms of the MIT license.
//
package errs
import (
"fmt"
"net/http"
"github.com/go-sql-driver/mysql"
"github.com/zeromicro/go-zero/rest/httpx"
)
func Response(w http.ResponseWriter, resp interface{}, err error) {
if err != nil {
httpx.Error(w, err)
} else if resp != nil {
httpx.OkJson(w, resp)
} else {
httpx.Ok(w)
}
}
func ErrorHandler(err error) (int, any) {
switch e := err.(type) {
case *CodeMsg:
return e.Code, e.Msg
case *mysql.MySQLError:
fmt.Printf("\nerror: %v| %v\n", e.SQLState, e.Number)
return http.StatusUnprocessableEntity, e.Message
default:
fmt.Printf("\nerror: %T| %v\n", err, err)
return http.StatusInternalServerError, err.Error()
}
}

@ -1,3 +1,10 @@
Name: main name: oa
Host: 0.0.0.0 host: 0.0.0.0
Port: 8888 port: 4000
verbose: true
uuid: FR9P5t8debxc11aFF
db: root:123456@tcp(localhost:3306)/oa
auth:
AccessSecret: AMpjwQHwVjGsb1WC4WG6
AccessExpire: 3600

@ -2,7 +2,10 @@ module oa
go 1.21.5 go 1.21.5
require github.com/zeromicro/go-zero v1.7.0 require (
github.com/zeromicro/go-zero v1.7.0
github.com/zeromicro/x v0.0.0-20240408115609-8224c482b07e
)
require ( require (
filippo.io/edwards25519 v1.1.0 // indirect filippo.io/edwards25519 v1.1.0 // indirect

@ -85,6 +85,8 @@ github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M
github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw= github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
github.com/zeromicro/go-zero v1.7.0 h1:B+y7tUVlo3qVQ6F0I0R9bi+Dq4I1QdO9ZB+dz1r0p1s= github.com/zeromicro/go-zero v1.7.0 h1:B+y7tUVlo3qVQ6F0I0R9bi+Dq4I1QdO9ZB+dz1r0p1s=
github.com/zeromicro/go-zero v1.7.0/go.mod h1:ypW4PzQI+jUrMcNJDDQ+7YW+pE+tMua9Xj/pmtmS1Dc= github.com/zeromicro/go-zero v1.7.0/go.mod h1:ypW4PzQI+jUrMcNJDDQ+7YW+pE+tMua9Xj/pmtmS1Dc=
github.com/zeromicro/x v0.0.0-20240408115609-8224c482b07e h1:F5waakzloTfbJg2lcO1xvrzO6ssn7jQ38lXIDBz+nbQ=
github.com/zeromicro/x v0.0.0-20240408115609-8224c482b07e/go.mod h1:5TP11tc1RHPCi5C/KDL0kIB0KgJAb9FB3ChpT/qM/jA=
go.opentelemetry.io/otel v1.24.0 h1:0LAOdjNmQeSTzGBzduGe/rU4tZhMwL5rWgtp9Ku5Jfo= go.opentelemetry.io/otel v1.24.0 h1:0LAOdjNmQeSTzGBzduGe/rU4tZhMwL5rWgtp9Ku5Jfo=
go.opentelemetry.io/otel v1.24.0/go.mod h1:W7b9Ozg4nkF5tWI5zsXkaKKDjdVjpD4oAt9Qi/MArHo= go.opentelemetry.io/otel v1.24.0/go.mod h1:W7b9Ozg4nkF5tWI5zsXkaKKDjdVjpD4oAt9Qi/MArHo=
go.opentelemetry.io/otel/exporters/jaeger v1.17.0 h1:D7UpUy2Xc2wsi1Ras6V40q806WM07rqoCWzXu7Sqy+4= go.opentelemetry.io/otel/exporters/jaeger v1.17.0 h1:D7UpUy2Xc2wsi1Ras6V40q806WM07rqoCWzXu7Sqy+4=

@ -4,4 +4,5 @@ import "github.com/zeromicro/go-zero/rest"
type Config struct { type Config struct {
rest.RestConf rest.RestConf
DB string
} }

@ -3,6 +3,8 @@ package app
import ( import (
"net/http" "net/http"
"oa/errs"
"github.com/zeromicro/go-zero/rest/httpx" "github.com/zeromicro/go-zero/rest/httpx"
"oa/internal/logic/app" "oa/internal/logic/app"
"oa/internal/svc" "oa/internal/svc"
@ -13,16 +15,12 @@ func LoginHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
var req types.AppReq var req types.AppReq
if err := httpx.Parse(r, &req); err != nil { if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err) errs.Response(w, nil, err)
return return
} }
l := app.NewLoginLogic(r.Context(), svcCtx) l := app.NewLoginLogic(r.Context(), svcCtx)
resp, err := l.Login(&req) resp, err := l.Login(&req)
if err != nil { errs.Response(w, resp, err)
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
} }
} }

@ -26,11 +26,35 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
server.AddRoutes( server.AddRoutes(
[]rest.Route{ []rest.Route{
{ {
Method: http.MethodPost, Method: http.MethodHead,
Path: "/login", Path: "/",
Handler: user.LoginHandler(serverCtx), Handler: user.LoginHandler(serverCtx),
}, },
{
Method: http.MethodPost,
Path: "/",
Handler: user.RegHandler(serverCtx),
},
},
rest.WithPrefix("/api/user"),
)
server.AddRoutes(
rest.WithMiddlewares(
[]rest.Middleware{serverCtx.Auth},
[]rest.Route{
{
Method: http.MethodGet,
Path: "/",
Handler: user.ListHandler(serverCtx),
},
{
Method: http.MethodGet,
Path: "/:id",
Handler: user.GetHandler(serverCtx),
}, },
}...,
),
rest.WithPrefix("/api/user"), rest.WithPrefix("/api/user"),
) )
} }

@ -0,0 +1,26 @@
package user
import (
"net/http"
"oa/errs"
"github.com/zeromicro/go-zero/rest/httpx"
"oa/internal/logic/user"
"oa/internal/svc"
"oa/internal/types"
)
func GetHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.GetReq
if err := httpx.Parse(r, &req); err != nil {
errs.Response(w, nil, err)
return
}
l := user.NewGetLogic(r.Context(), svcCtx)
resp, err := l.Get(&req)
errs.Response(w, resp, err)
}
}

@ -0,0 +1,26 @@
package user
import (
"net/http"
"oa/errs"
"github.com/zeromicro/go-zero/rest/httpx"
"oa/internal/logic/user"
"oa/internal/svc"
"oa/internal/types"
)
func ListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.ListReq
if err := httpx.Parse(r, &req); err != nil {
errs.Response(w, nil, err)
return
}
l := user.NewListLogic(r.Context(), svcCtx)
resp, err := l.List(&req)
errs.Response(w, resp, err)
}
}

@ -3,6 +3,8 @@ package user
import ( import (
"net/http" "net/http"
"oa/errs"
"github.com/zeromicro/go-zero/rest/httpx" "github.com/zeromicro/go-zero/rest/httpx"
"oa/internal/logic/user" "oa/internal/logic/user"
"oa/internal/svc" "oa/internal/svc"
@ -13,16 +15,12 @@ func LoginHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
var req types.LoginReq var req types.LoginReq
if err := httpx.Parse(r, &req); err != nil { if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err) errs.Response(w, nil, err)
return return
} }
l := user.NewLoginLogic(r.Context(), svcCtx) l := user.NewLoginLogic(r.Context(), svcCtx)
resp, err := l.Login(&req) err := l.Login(&req)
if err != nil { errs.Response(w, nil, err)
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
} }
} }

@ -0,0 +1,27 @@
package user
import (
"net/http"
"oa/errs"
"oa/internal/logic/user"
"oa/internal/svc"
"oa/internal/types"
"github.com/zeromicro/go-zero/rest/httpx"
)
func RegHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.RegReq
if err := httpx.Parse(r, &req); err != nil {
errs.Response(w, nil, err)
return
}
l := user.NewRegLogic(r.Context(), svcCtx)
err := l.Reg(&req)
errs.Response(w, nil, err)
}
}

@ -0,0 +1,30 @@
package user
import (
"context"
"oa/internal/svc"
"oa/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type GetLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetLogic {
return &GetLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetLogic) Get(req *types.GetReq) (resp *types.UserResp, err error) {
// todo: add your logic here and delete this line
return
}

@ -0,0 +1,30 @@
package user
import (
"context"
"oa/internal/svc"
"oa/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type ListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
return &ListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *ListLogic) List(req *types.ListReq) (resp []types.UserResp, err error) {
// todo: add your logic here and delete this line
return
}

@ -23,8 +23,8 @@ func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic
} }
} }
func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginResp, err error) { func (l *LoginLogic) Login(req *types.LoginReq) error {
// todo: add your logic here and delete this line // todo: add your logic here and delete this line
return return nil
} }

@ -0,0 +1,43 @@
package user
import (
"context"
"strings"
"time"
"oa/internal/svc"
"oa/internal/types"
"oa/models"
"github.com/google/uuid"
"github.com/zeromicro/go-zero/core/logx"
)
type RegLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewRegLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegLogic {
return &RegLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *RegLogic) Reg(req *types.RegReq) error {
// todo: add your logic here and delete this line
m := models.NewUserModel(l.svcCtx.Sqlx())
u := &models.User{
Id: strings.ReplaceAll(uuid.New().String(), "-", ""),
Created: time.Now(),
Updated: time.Now(),
Username: req.Username,
}
l.Infof("user: %v", u.Id)
_, e := m.Insert(l.ctx, u)
return e
}

@ -0,0 +1,25 @@
package middleware
import (
"context"
"net/http"
)
type AuthMiddleware struct {
ID string `json:"id"`
}
func NewAuthMiddleware() *AuthMiddleware {
return &AuthMiddleware{}
}
func (m *AuthMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// TODO generate middleware implement function, delete after code implementation
// Passthrough to next handler if need
// val := r.Header.Get("User-Agent")
ctx := context.WithValue(r.Context(), "u", "123")
next(w, r.WithContext(ctx))
}
}

@ -2,14 +2,28 @@ package svc
import ( import (
"oa/internal/config" "oa/internal/config"
"oa/internal/middleware"
"github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/rest"
) )
type ServiceContext struct { type ServiceContext struct {
Config config.Config Config config.Config
Auth rest.Middleware
_conn sqlx.SqlConn
}
func (s *ServiceContext) Sqlx() sqlx.SqlConn {
if s._conn == nil {
s._conn = sqlx.NewMysql(s.Config.DB)
}
return s._conn
} }
func NewServiceContext(c config.Config) *ServiceContext { func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{ return &ServiceContext{
Config: c, Config: c,
Auth: middleware.NewAuthMiddleware().Handle,
} }
} }

@ -2,7 +2,6 @@
package types package types
type AppReq struct { type AppReq struct {
Error
Appname string `json:"username"` Appname string `json:"username"`
Password string `json:"password"` Password string `json:"password"`
} }
@ -15,19 +14,38 @@ type AppResp struct {
} }
type LoginReq struct { type LoginReq struct {
Error Id string `json:"id"`
Code string `json:"code"`
Verify string `json:"verify"`
}
type RegReq struct {
Username string `json:"username"` Username string `json:"username"`
Password string `json:"password"` Pwd string `json:"pwd"`
} }
type LoginResp struct { type Auth struct {
Id int64 `json:"id"` Authorization string `header:"authorization"`
Name string `json:"name"` }
Token string `json:"token"`
ExpireAt string `json:"expireAt"` type GetReq struct {
Id int64 `path:"id"`
} }
type Error struct { type ListReq struct {
Status string `json:"status"` Username string `query:"username"`
Code int `json:"code"` }
type UserResp struct {
Id string `json:"id"`
Created uint `json:"created"`
Updated uint `json:"updated"`
Username string `json:"username"`
Nickname string `json:"nickname"`
Email string `json:"email"`
Phone string `json:"phone"`
Icon string `json:"icon"`
Status int64 `json:"status"` // 状态0ok1disabled
Used int64 `json:"used"`
Space int64 `json:"space"`
} }

@ -4,12 +4,14 @@ import (
"flag" "flag"
"fmt" "fmt"
"oa/errs"
"oa/internal/config" "oa/internal/config"
"oa/internal/handler" "oa/internal/handler"
"oa/internal/svc" "oa/internal/svc"
"github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/rest" "github.com/zeromicro/go-zero/rest"
"github.com/zeromicro/go-zero/rest/httpx"
) )
var configFile = flag.String("f", "etc/main.yaml", "the config file") var configFile = flag.String("f", "etc/main.yaml", "the config file")
@ -25,6 +27,7 @@ func main() {
ctx := svc.NewServiceContext(c) ctx := svc.NewServiceContext(c)
handler.RegisterHandlers(server, ctx) handler.RegisterHandlers(server, ctx)
httpx.SetErrorHandler(errs.ErrorHandler)
fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port) fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
server.Start() server.Start()

@ -1,9 +1,6 @@
package models package models
import ( import "github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
var _ AccessModel = (*customAccessModel)(nil) var _ AccessModel = (*customAccessModel)(nil)
@ -12,6 +9,7 @@ type (
// and implement the added methods in customAccessModel. // and implement the added methods in customAccessModel.
AccessModel interface { AccessModel interface {
accessModel accessModel
withSession(session sqlx.Session) AccessModel
} }
customAccessModel struct { customAccessModel struct {
@ -20,8 +18,12 @@ type (
) )
// NewAccessModel returns a model for the database table. // NewAccessModel returns a model for the database table.
func NewAccessModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) AccessModel { func NewAccessModel(conn sqlx.SqlConn) AccessModel {
return &customAccessModel{ return &customAccessModel{
defaultAccessModel: newAccessModel(conn, c, opts...), defaultAccessModel: newAccessModel(conn),
} }
} }
func (m *customAccessModel) withSession(session sqlx.Session) AccessModel {
return NewAccessModel(sqlx.NewSqlConnFromSession(session))
}

@ -10,8 +10,6 @@ import (
"time" "time"
"github.com/zeromicro/go-zero/core/stores/builder" "github.com/zeromicro/go-zero/core/stores/builder"
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/core/stores/sqlc"
"github.com/zeromicro/go-zero/core/stores/sqlx" "github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/core/stringx" "github.com/zeromicro/go-zero/core/stringx"
) )
@ -21,8 +19,6 @@ var (
accessRows = strings.Join(accessFieldNames, ",") accessRows = strings.Join(accessFieldNames, ",")
accessRowsExpectAutoSet = strings.Join(stringx.Remove(accessFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",") accessRowsExpectAutoSet = strings.Join(stringx.Remove(accessFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",")
accessRowsWithPlaceHolder = strings.Join(stringx.Remove(accessFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?" accessRowsWithPlaceHolder = strings.Join(stringx.Remove(accessFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?"
cacheOaAccessIdPrefix = "cache:oa:access:id:"
) )
type ( type (
@ -34,7 +30,7 @@ type (
} }
defaultAccessModel struct { defaultAccessModel struct {
sqlc.CachedConn conn sqlx.SqlConn
table string table string
} }
@ -52,33 +48,27 @@ type (
} }
) )
func newAccessModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) *defaultAccessModel { func newAccessModel(conn sqlx.SqlConn) *defaultAccessModel {
return &defaultAccessModel{ return &defaultAccessModel{
CachedConn: sqlc.NewConn(conn, c, opts...), conn: conn,
table: "`access`", table: "`access`",
} }
} }
func (m *defaultAccessModel) Delete(ctx context.Context, id int64) error { func (m *defaultAccessModel) Delete(ctx context.Context, id int64) error {
oaAccessIdKey := fmt.Sprintf("%s%v", cacheOaAccessIdPrefix, id)
_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("delete from %s where `id` = ?", m.table) query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
return conn.ExecCtx(ctx, query, id) _, err := m.conn.ExecCtx(ctx, query, id)
}, oaAccessIdKey)
return err return err
} }
func (m *defaultAccessModel) FindOne(ctx context.Context, id int64) (*Access, error) { func (m *defaultAccessModel) FindOne(ctx context.Context, id int64) (*Access, error) {
oaAccessIdKey := fmt.Sprintf("%s%v", cacheOaAccessIdPrefix, id)
var resp Access
err := m.QueryRowCtx(ctx, &resp, oaAccessIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error {
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", accessRows, m.table) query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", accessRows, m.table)
return conn.QueryRowCtx(ctx, v, query, id) var resp Access
}) err := m.conn.QueryRowCtx(ctx, &resp, query, id)
switch err { switch err {
case nil: case nil:
return &resp, nil return &resp, nil
case sqlc.ErrNotFound: case sqlx.ErrNotFound:
return nil, ErrNotFound return nil, ErrNotFound
default: default:
return nil, err return nil, err
@ -86,32 +76,17 @@ func (m *defaultAccessModel) FindOne(ctx context.Context, id int64) (*Access, er
} }
func (m *defaultAccessModel) Insert(ctx context.Context, data *Access) (sql.Result, error) { func (m *defaultAccessModel) Insert(ctx context.Context, data *Access) (sql.Result, error) {
oaAccessIdKey := fmt.Sprintf("%s%v", cacheOaAccessIdPrefix, data.Id)
ret, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?, ?)", m.table, accessRowsExpectAutoSet) query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?, ?)", m.table, accessRowsExpectAutoSet)
return conn.ExecCtx(ctx, query, data.Created, data.Updated, data.AppId, data.AccessId, data.Name, data.RoleId, data.UserId, data.Rid, data.Level) ret, err := m.conn.ExecCtx(ctx, query, data.Created, data.Updated, data.AppId, data.AccessId, data.Name, data.RoleId, data.UserId, data.Rid, data.Level)
}, oaAccessIdKey)
return ret, err return ret, err
} }
func (m *defaultAccessModel) Update(ctx context.Context, data *Access) error { func (m *defaultAccessModel) Update(ctx context.Context, data *Access) error {
oaAccessIdKey := fmt.Sprintf("%s%v", cacheOaAccessIdPrefix, data.Id)
_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, accessRowsWithPlaceHolder) query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, accessRowsWithPlaceHolder)
return conn.ExecCtx(ctx, query, data.Created, data.Updated, data.AppId, data.AccessId, data.Name, data.RoleId, data.UserId, data.Rid, data.Level, data.Id) _, err := m.conn.ExecCtx(ctx, query, data.Created, data.Updated, data.AppId, data.AccessId, data.Name, data.RoleId, data.UserId, data.Rid, data.Level, data.Id)
}, oaAccessIdKey)
return err return err
} }
func (m *defaultAccessModel) formatPrimary(primary any) string {
return fmt.Sprintf("%s%v", cacheOaAccessIdPrefix, primary)
}
func (m *defaultAccessModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary any) error {
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", accessRows, m.table)
return conn.QueryRowCtx(ctx, v, query, primary)
}
func (m *defaultAccessModel) tableName() string { func (m *defaultAccessModel) tableName() string {
return m.table return m.table
} }

@ -1,9 +1,6 @@
package models package models
import ( import "github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
var _ AppModel = (*customAppModel)(nil) var _ AppModel = (*customAppModel)(nil)
@ -12,6 +9,7 @@ type (
// and implement the added methods in customAppModel. // and implement the added methods in customAppModel.
AppModel interface { AppModel interface {
appModel appModel
withSession(session sqlx.Session) AppModel
} }
customAppModel struct { customAppModel struct {
@ -20,8 +18,12 @@ type (
) )
// NewAppModel returns a model for the database table. // NewAppModel returns a model for the database table.
func NewAppModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) AppModel { func NewAppModel(conn sqlx.SqlConn) AppModel {
return &customAppModel{ return &customAppModel{
defaultAppModel: newAppModel(conn, c, opts...), defaultAppModel: newAppModel(conn),
} }
} }
func (m *customAppModel) withSession(session sqlx.Session) AppModel {
return NewAppModel(sqlx.NewSqlConnFromSession(session))
}

@ -10,8 +10,6 @@ import (
"time" "time"
"github.com/zeromicro/go-zero/core/stores/builder" "github.com/zeromicro/go-zero/core/stores/builder"
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/core/stores/sqlc"
"github.com/zeromicro/go-zero/core/stores/sqlx" "github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/core/stringx" "github.com/zeromicro/go-zero/core/stringx"
) )
@ -21,8 +19,6 @@ var (
appRows = strings.Join(appFieldNames, ",") appRows = strings.Join(appFieldNames, ",")
appRowsExpectAutoSet = strings.Join(stringx.Remove(appFieldNames, "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",") appRowsExpectAutoSet = strings.Join(stringx.Remove(appFieldNames, "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",")
appRowsWithPlaceHolder = strings.Join(stringx.Remove(appFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?" appRowsWithPlaceHolder = strings.Join(stringx.Remove(appFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?"
cacheOaAppIdPrefix = "cache:oa:app:id:"
) )
type ( type (
@ -34,7 +30,7 @@ type (
} }
defaultAppModel struct { defaultAppModel struct {
sqlc.CachedConn conn sqlx.SqlConn
table string table string
} }
@ -56,33 +52,27 @@ type (
} }
) )
func newAppModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) *defaultAppModel { func newAppModel(conn sqlx.SqlConn) *defaultAppModel {
return &defaultAppModel{ return &defaultAppModel{
CachedConn: sqlc.NewConn(conn, c, opts...), conn: conn,
table: "`app`", table: "`app`",
} }
} }
func (m *defaultAppModel) Delete(ctx context.Context, id string) error { func (m *defaultAppModel) Delete(ctx context.Context, id string) error {
oaAppIdKey := fmt.Sprintf("%s%v", cacheOaAppIdPrefix, id)
_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("delete from %s where `id` = ?", m.table) query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
return conn.ExecCtx(ctx, query, id) _, err := m.conn.ExecCtx(ctx, query, id)
}, oaAppIdKey)
return err return err
} }
func (m *defaultAppModel) FindOne(ctx context.Context, id string) (*App, error) { func (m *defaultAppModel) FindOne(ctx context.Context, id string) (*App, error) {
oaAppIdKey := fmt.Sprintf("%s%v", cacheOaAppIdPrefix, id)
var resp App
err := m.QueryRowCtx(ctx, &resp, oaAppIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error {
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", appRows, m.table) query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", appRows, m.table)
return conn.QueryRowCtx(ctx, v, query, id) var resp App
}) err := m.conn.QueryRowCtx(ctx, &resp, query, id)
switch err { switch err {
case nil: case nil:
return &resp, nil return &resp, nil
case sqlc.ErrNotFound: case sqlx.ErrNotFound:
return nil, ErrNotFound return nil, ErrNotFound
default: default:
return nil, err return nil, err
@ -90,32 +80,17 @@ func (m *defaultAppModel) FindOne(ctx context.Context, id string) (*App, error)
} }
func (m *defaultAppModel) Insert(ctx context.Context, data *App) (sql.Result, error) { func (m *defaultAppModel) Insert(ctx context.Context, data *App) (sql.Result, error) {
oaAppIdKey := fmt.Sprintf("%s%v", cacheOaAppIdPrefix, data.Id)
ret, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", m.table, appRowsExpectAutoSet) query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", m.table, appRowsExpectAutoSet)
return conn.ExecCtx(ctx, query, data.Id, data.Created, data.Updated, data.Key, data.Name, data.Icon, data.Des, data.UserCount, data.Hide, data.JoinMethod, data.RoleId, data.Host, data.Redirect, data.Status) ret, err := m.conn.ExecCtx(ctx, query, data.Id, data.Created, data.Updated, data.Key, data.Name, data.Icon, data.Des, data.UserCount, data.Hide, data.JoinMethod, data.RoleId, data.Host, data.Redirect, data.Status)
}, oaAppIdKey)
return ret, err return ret, err
} }
func (m *defaultAppModel) Update(ctx context.Context, data *App) error { func (m *defaultAppModel) Update(ctx context.Context, data *App) error {
oaAppIdKey := fmt.Sprintf("%s%v", cacheOaAppIdPrefix, data.Id)
_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, appRowsWithPlaceHolder) query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, appRowsWithPlaceHolder)
return conn.ExecCtx(ctx, query, data.Created, data.Updated, data.Key, data.Name, data.Icon, data.Des, data.UserCount, data.Hide, data.JoinMethod, data.RoleId, data.Host, data.Redirect, data.Status, data.Id) _, err := m.conn.ExecCtx(ctx, query, data.Created, data.Updated, data.Key, data.Name, data.Icon, data.Des, data.UserCount, data.Hide, data.JoinMethod, data.RoleId, data.Host, data.Redirect, data.Status, data.Id)
}, oaAppIdKey)
return err return err
} }
func (m *defaultAppModel) formatPrimary(primary any) string {
return fmt.Sprintf("%s%v", cacheOaAppIdPrefix, primary)
}
func (m *defaultAppModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary any) error {
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", appRows, m.table)
return conn.QueryRowCtx(ctx, v, query, primary)
}
func (m *defaultAppModel) tableName() string { func (m *defaultAppModel) tableName() string {
return m.table return m.table
} }

@ -1,9 +1,6 @@
package models package models
import ( import "github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
var _ AppUserModel = (*customAppUserModel)(nil) var _ AppUserModel = (*customAppUserModel)(nil)
@ -12,6 +9,7 @@ type (
// and implement the added methods in customAppUserModel. // and implement the added methods in customAppUserModel.
AppUserModel interface { AppUserModel interface {
appUserModel appUserModel
withSession(session sqlx.Session) AppUserModel
} }
customAppUserModel struct { customAppUserModel struct {
@ -20,8 +18,12 @@ type (
) )
// NewAppUserModel returns a model for the database table. // NewAppUserModel returns a model for the database table.
func NewAppUserModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) AppUserModel { func NewAppUserModel(conn sqlx.SqlConn) AppUserModel {
return &customAppUserModel{ return &customAppUserModel{
defaultAppUserModel: newAppUserModel(conn, c, opts...), defaultAppUserModel: newAppUserModel(conn),
} }
} }
func (m *customAppUserModel) withSession(session sqlx.Session) AppUserModel {
return NewAppUserModel(sqlx.NewSqlConnFromSession(session))
}

@ -10,8 +10,6 @@ import (
"time" "time"
"github.com/zeromicro/go-zero/core/stores/builder" "github.com/zeromicro/go-zero/core/stores/builder"
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/core/stores/sqlc"
"github.com/zeromicro/go-zero/core/stores/sqlx" "github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/core/stringx" "github.com/zeromicro/go-zero/core/stringx"
) )
@ -21,9 +19,6 @@ var (
appUserRows = strings.Join(appUserFieldNames, ",") appUserRows = strings.Join(appUserFieldNames, ",")
appUserRowsExpectAutoSet = strings.Join(stringx.Remove(appUserFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",") appUserRowsExpectAutoSet = strings.Join(stringx.Remove(appUserFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",")
appUserRowsWithPlaceHolder = strings.Join(stringx.Remove(appUserFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?" appUserRowsWithPlaceHolder = strings.Join(stringx.Remove(appUserFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?"
cacheOaAppUserIdPrefix = "cache:oa:appUser:id:"
cacheOaAppUserUserIdAppIdPrefix = "cache:oa:appUser:userId:appId:"
) )
type ( type (
@ -36,7 +31,7 @@ type (
} }
defaultAppUserModel struct { defaultAppUserModel struct {
sqlc.CachedConn conn sqlx.SqlConn
table string table string
} }
@ -50,39 +45,27 @@ type (
} }
) )
func newAppUserModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) *defaultAppUserModel { func newAppUserModel(conn sqlx.SqlConn) *defaultAppUserModel {
return &defaultAppUserModel{ return &defaultAppUserModel{
CachedConn: sqlc.NewConn(conn, c, opts...), conn: conn,
table: "`app_user`", table: "`app_user`",
} }
} }
func (m *defaultAppUserModel) Delete(ctx context.Context, id int64) error { func (m *defaultAppUserModel) Delete(ctx context.Context, id int64) error {
data, err := m.FindOne(ctx, id)
if err != nil {
return err
}
oaAppUserIdKey := fmt.Sprintf("%s%v", cacheOaAppUserIdPrefix, id)
oaAppUserUserIdAppIdKey := fmt.Sprintf("%s%v:%v", cacheOaAppUserUserIdAppIdPrefix, data.UserId, data.AppId)
_, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("delete from %s where `id` = ?", m.table) query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
return conn.ExecCtx(ctx, query, id) _, err := m.conn.ExecCtx(ctx, query, id)
}, oaAppUserIdKey, oaAppUserUserIdAppIdKey)
return err return err
} }
func (m *defaultAppUserModel) FindOne(ctx context.Context, id int64) (*AppUser, error) { func (m *defaultAppUserModel) FindOne(ctx context.Context, id int64) (*AppUser, error) {
oaAppUserIdKey := fmt.Sprintf("%s%v", cacheOaAppUserIdPrefix, id)
var resp AppUser
err := m.QueryRowCtx(ctx, &resp, oaAppUserIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error {
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", appUserRows, m.table) query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", appUserRows, m.table)
return conn.QueryRowCtx(ctx, v, query, id) var resp AppUser
}) err := m.conn.QueryRowCtx(ctx, &resp, query, id)
switch err { switch err {
case nil: case nil:
return &resp, nil return &resp, nil
case sqlc.ErrNotFound: case sqlx.ErrNotFound:
return nil, ErrNotFound return nil, ErrNotFound
default: default:
return nil, err return nil, err
@ -90,19 +73,13 @@ func (m *defaultAppUserModel) FindOne(ctx context.Context, id int64) (*AppUser,
} }
func (m *defaultAppUserModel) FindOneByUserIdAppId(ctx context.Context, userId string, appId string) (*AppUser, error) { func (m *defaultAppUserModel) FindOneByUserIdAppId(ctx context.Context, userId string, appId string) (*AppUser, error) {
oaAppUserUserIdAppIdKey := fmt.Sprintf("%s%v:%v", cacheOaAppUserUserIdAppIdPrefix, userId, appId)
var resp AppUser var resp AppUser
err := m.QueryRowIndexCtx(ctx, &resp, oaAppUserUserIdAppIdKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v any) (i any, e error) {
query := fmt.Sprintf("select %s from %s where `user_id` = ? and `app_id` = ? limit 1", appUserRows, m.table) query := fmt.Sprintf("select %s from %s where `user_id` = ? and `app_id` = ? limit 1", appUserRows, m.table)
if err := conn.QueryRowCtx(ctx, &resp, query, userId, appId); err != nil { err := m.conn.QueryRowCtx(ctx, &resp, query, userId, appId)
return nil, err
}
return resp.Id, nil
}, m.queryPrimary)
switch err { switch err {
case nil: case nil:
return &resp, nil return &resp, nil
case sqlc.ErrNotFound: case sqlx.ErrNotFound:
return nil, ErrNotFound return nil, ErrNotFound
default: default:
return nil, err return nil, err
@ -110,39 +87,17 @@ func (m *defaultAppUserModel) FindOneByUserIdAppId(ctx context.Context, userId s
} }
func (m *defaultAppUserModel) Insert(ctx context.Context, data *AppUser) (sql.Result, error) { func (m *defaultAppUserModel) Insert(ctx context.Context, data *AppUser) (sql.Result, error) {
oaAppUserIdKey := fmt.Sprintf("%s%v", cacheOaAppUserIdPrefix, data.Id)
oaAppUserUserIdAppIdKey := fmt.Sprintf("%s%v:%v", cacheOaAppUserUserIdAppIdPrefix, data.UserId, data.AppId)
ret, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?)", m.table, appUserRowsExpectAutoSet) query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?)", m.table, appUserRowsExpectAutoSet)
return conn.ExecCtx(ctx, query, data.Created, data.Updated, data.AppId, data.UserId, data.Status) ret, err := m.conn.ExecCtx(ctx, query, data.Created, data.Updated, data.AppId, data.UserId, data.Status)
}, oaAppUserIdKey, oaAppUserUserIdAppIdKey)
return ret, err return ret, err
} }
func (m *defaultAppUserModel) Update(ctx context.Context, newData *AppUser) error { func (m *defaultAppUserModel) Update(ctx context.Context, newData *AppUser) error {
data, err := m.FindOne(ctx, newData.Id)
if err != nil {
return err
}
oaAppUserIdKey := fmt.Sprintf("%s%v", cacheOaAppUserIdPrefix, data.Id)
oaAppUserUserIdAppIdKey := fmt.Sprintf("%s%v:%v", cacheOaAppUserUserIdAppIdPrefix, data.UserId, data.AppId)
_, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, appUserRowsWithPlaceHolder) query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, appUserRowsWithPlaceHolder)
return conn.ExecCtx(ctx, query, newData.Created, newData.Updated, newData.AppId, newData.UserId, newData.Status, newData.Id) _, err := m.conn.ExecCtx(ctx, query, newData.Created, newData.Updated, newData.AppId, newData.UserId, newData.Status, newData.Id)
}, oaAppUserIdKey, oaAppUserUserIdAppIdKey)
return err return err
} }
func (m *defaultAppUserModel) formatPrimary(primary any) string {
return fmt.Sprintf("%s%v", cacheOaAppUserIdPrefix, primary)
}
func (m *defaultAppUserModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary any) error {
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", appUserRows, m.table)
return conn.QueryRowCtx(ctx, v, query, primary)
}
func (m *defaultAppUserModel) tableName() string { func (m *defaultAppUserModel) tableName() string {
return m.table return m.table
} }

@ -1,9 +1,6 @@
package models package models
import ( import "github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
var _ ResourceModel = (*customResourceModel)(nil) var _ ResourceModel = (*customResourceModel)(nil)
@ -12,6 +9,7 @@ type (
// and implement the added methods in customResourceModel. // and implement the added methods in customResourceModel.
ResourceModel interface { ResourceModel interface {
resourceModel resourceModel
withSession(session sqlx.Session) ResourceModel
} }
customResourceModel struct { customResourceModel struct {
@ -20,8 +18,12 @@ type (
) )
// NewResourceModel returns a model for the database table. // NewResourceModel returns a model for the database table.
func NewResourceModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) ResourceModel { func NewResourceModel(conn sqlx.SqlConn) ResourceModel {
return &customResourceModel{ return &customResourceModel{
defaultResourceModel: newResourceModel(conn, c, opts...), defaultResourceModel: newResourceModel(conn),
} }
} }
func (m *customResourceModel) withSession(session sqlx.Session) ResourceModel {
return NewResourceModel(sqlx.NewSqlConnFromSession(session))
}

@ -10,8 +10,6 @@ import (
"time" "time"
"github.com/zeromicro/go-zero/core/stores/builder" "github.com/zeromicro/go-zero/core/stores/builder"
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/core/stores/sqlc"
"github.com/zeromicro/go-zero/core/stores/sqlx" "github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/core/stringx" "github.com/zeromicro/go-zero/core/stringx"
) )
@ -21,9 +19,6 @@ var (
resourceRows = strings.Join(resourceFieldNames, ",") resourceRows = strings.Join(resourceFieldNames, ",")
resourceRowsExpectAutoSet = strings.Join(stringx.Remove(resourceFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",") resourceRowsExpectAutoSet = strings.Join(stringx.Remove(resourceFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",")
resourceRowsWithPlaceHolder = strings.Join(stringx.Remove(resourceFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?" resourceRowsWithPlaceHolder = strings.Join(stringx.Remove(resourceFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?"
cacheOaResourceIdPrefix = "cache:oa:resource:id:"
cacheOaResourceAppIdNamePrefix = "cache:oa:resource:appId:name:"
) )
type ( type (
@ -36,7 +31,7 @@ type (
} }
defaultResourceModel struct { defaultResourceModel struct {
sqlc.CachedConn conn sqlx.SqlConn
table string table string
} }
@ -50,39 +45,27 @@ type (
} }
) )
func newResourceModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) *defaultResourceModel { func newResourceModel(conn sqlx.SqlConn) *defaultResourceModel {
return &defaultResourceModel{ return &defaultResourceModel{
CachedConn: sqlc.NewConn(conn, c, opts...), conn: conn,
table: "`resource`", table: "`resource`",
} }
} }
func (m *defaultResourceModel) Delete(ctx context.Context, id int64) error { func (m *defaultResourceModel) Delete(ctx context.Context, id int64) error {
data, err := m.FindOne(ctx, id)
if err != nil {
return err
}
oaResourceAppIdNameKey := fmt.Sprintf("%s%v:%v", cacheOaResourceAppIdNamePrefix, data.AppId, data.Name)
oaResourceIdKey := fmt.Sprintf("%s%v", cacheOaResourceIdPrefix, id)
_, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("delete from %s where `id` = ?", m.table) query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
return conn.ExecCtx(ctx, query, id) _, err := m.conn.ExecCtx(ctx, query, id)
}, oaResourceAppIdNameKey, oaResourceIdKey)
return err return err
} }
func (m *defaultResourceModel) FindOne(ctx context.Context, id int64) (*Resource, error) { func (m *defaultResourceModel) FindOne(ctx context.Context, id int64) (*Resource, error) {
oaResourceIdKey := fmt.Sprintf("%s%v", cacheOaResourceIdPrefix, id)
var resp Resource
err := m.QueryRowCtx(ctx, &resp, oaResourceIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error {
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", resourceRows, m.table) query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", resourceRows, m.table)
return conn.QueryRowCtx(ctx, v, query, id) var resp Resource
}) err := m.conn.QueryRowCtx(ctx, &resp, query, id)
switch err { switch err {
case nil: case nil:
return &resp, nil return &resp, nil
case sqlc.ErrNotFound: case sqlx.ErrNotFound:
return nil, ErrNotFound return nil, ErrNotFound
default: default:
return nil, err return nil, err
@ -90,19 +73,13 @@ func (m *defaultResourceModel) FindOne(ctx context.Context, id int64) (*Resource
} }
func (m *defaultResourceModel) FindOneByAppIdName(ctx context.Context, appId string, name string) (*Resource, error) { func (m *defaultResourceModel) FindOneByAppIdName(ctx context.Context, appId string, name string) (*Resource, error) {
oaResourceAppIdNameKey := fmt.Sprintf("%s%v:%v", cacheOaResourceAppIdNamePrefix, appId, name)
var resp Resource var resp Resource
err := m.QueryRowIndexCtx(ctx, &resp, oaResourceAppIdNameKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v any) (i any, e error) {
query := fmt.Sprintf("select %s from %s where `app_id` = ? and `name` = ? limit 1", resourceRows, m.table) query := fmt.Sprintf("select %s from %s where `app_id` = ? and `name` = ? limit 1", resourceRows, m.table)
if err := conn.QueryRowCtx(ctx, &resp, query, appId, name); err != nil { err := m.conn.QueryRowCtx(ctx, &resp, query, appId, name)
return nil, err
}
return resp.Id, nil
}, m.queryPrimary)
switch err { switch err {
case nil: case nil:
return &resp, nil return &resp, nil
case sqlc.ErrNotFound: case sqlx.ErrNotFound:
return nil, ErrNotFound return nil, ErrNotFound
default: default:
return nil, err return nil, err
@ -110,39 +87,17 @@ func (m *defaultResourceModel) FindOneByAppIdName(ctx context.Context, appId str
} }
func (m *defaultResourceModel) Insert(ctx context.Context, data *Resource) (sql.Result, error) { func (m *defaultResourceModel) Insert(ctx context.Context, data *Resource) (sql.Result, error) {
oaResourceAppIdNameKey := fmt.Sprintf("%s%v:%v", cacheOaResourceAppIdNamePrefix, data.AppId, data.Name)
oaResourceIdKey := fmt.Sprintf("%s%v", cacheOaResourceIdPrefix, data.Id)
ret, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?)", m.table, resourceRowsExpectAutoSet) query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?)", m.table, resourceRowsExpectAutoSet)
return conn.ExecCtx(ctx, query, data.Created, data.Updated, data.AppId, data.Name, data.Des) ret, err := m.conn.ExecCtx(ctx, query, data.Created, data.Updated, data.AppId, data.Name, data.Des)
}, oaResourceAppIdNameKey, oaResourceIdKey)
return ret, err return ret, err
} }
func (m *defaultResourceModel) Update(ctx context.Context, newData *Resource) error { func (m *defaultResourceModel) Update(ctx context.Context, newData *Resource) error {
data, err := m.FindOne(ctx, newData.Id)
if err != nil {
return err
}
oaResourceAppIdNameKey := fmt.Sprintf("%s%v:%v", cacheOaResourceAppIdNamePrefix, data.AppId, data.Name)
oaResourceIdKey := fmt.Sprintf("%s%v", cacheOaResourceIdPrefix, data.Id)
_, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, resourceRowsWithPlaceHolder) query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, resourceRowsWithPlaceHolder)
return conn.ExecCtx(ctx, query, newData.Created, newData.Updated, newData.AppId, newData.Name, newData.Des, newData.Id) _, err := m.conn.ExecCtx(ctx, query, newData.Created, newData.Updated, newData.AppId, newData.Name, newData.Des, newData.Id)
}, oaResourceAppIdNameKey, oaResourceIdKey)
return err return err
} }
func (m *defaultResourceModel) formatPrimary(primary any) string {
return fmt.Sprintf("%s%v", cacheOaResourceIdPrefix, primary)
}
func (m *defaultResourceModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary any) error {
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", resourceRows, m.table)
return conn.QueryRowCtx(ctx, v, query, primary)
}
func (m *defaultResourceModel) tableName() string { func (m *defaultResourceModel) tableName() string {
return m.table return m.table
} }

@ -1,9 +1,6 @@
package models package models
import ( import "github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
var _ RoleModel = (*customRoleModel)(nil) var _ RoleModel = (*customRoleModel)(nil)
@ -12,6 +9,7 @@ type (
// and implement the added methods in customRoleModel. // and implement the added methods in customRoleModel.
RoleModel interface { RoleModel interface {
roleModel roleModel
withSession(session sqlx.Session) RoleModel
} }
customRoleModel struct { customRoleModel struct {
@ -20,8 +18,12 @@ type (
) )
// NewRoleModel returns a model for the database table. // NewRoleModel returns a model for the database table.
func NewRoleModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) RoleModel { func NewRoleModel(conn sqlx.SqlConn) RoleModel {
return &customRoleModel{ return &customRoleModel{
defaultRoleModel: newRoleModel(conn, c, opts...), defaultRoleModel: newRoleModel(conn),
} }
} }
func (m *customRoleModel) withSession(session sqlx.Session) RoleModel {
return NewRoleModel(sqlx.NewSqlConnFromSession(session))
}

@ -10,8 +10,6 @@ import (
"time" "time"
"github.com/zeromicro/go-zero/core/stores/builder" "github.com/zeromicro/go-zero/core/stores/builder"
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/core/stores/sqlc"
"github.com/zeromicro/go-zero/core/stores/sqlx" "github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/core/stringx" "github.com/zeromicro/go-zero/core/stringx"
) )
@ -21,8 +19,6 @@ var (
roleRows = strings.Join(roleFieldNames, ",") roleRows = strings.Join(roleFieldNames, ",")
roleRowsExpectAutoSet = strings.Join(stringx.Remove(roleFieldNames, "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",") roleRowsExpectAutoSet = strings.Join(stringx.Remove(roleFieldNames, "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",")
roleRowsWithPlaceHolder = strings.Join(stringx.Remove(roleFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?" roleRowsWithPlaceHolder = strings.Join(stringx.Remove(roleFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?"
cacheOaRoleIdPrefix = "cache:oa:role:id:"
) )
type ( type (
@ -34,7 +30,7 @@ type (
} }
defaultRoleModel struct { defaultRoleModel struct {
sqlc.CachedConn conn sqlx.SqlConn
table string table string
} }
@ -49,33 +45,27 @@ type (
} }
) )
func newRoleModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) *defaultRoleModel { func newRoleModel(conn sqlx.SqlConn) *defaultRoleModel {
return &defaultRoleModel{ return &defaultRoleModel{
CachedConn: sqlc.NewConn(conn, c, opts...), conn: conn,
table: "`role`", table: "`role`",
} }
} }
func (m *defaultRoleModel) Delete(ctx context.Context, id string) error { func (m *defaultRoleModel) Delete(ctx context.Context, id string) error {
oaRoleIdKey := fmt.Sprintf("%s%v", cacheOaRoleIdPrefix, id)
_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("delete from %s where `id` = ?", m.table) query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
return conn.ExecCtx(ctx, query, id) _, err := m.conn.ExecCtx(ctx, query, id)
}, oaRoleIdKey)
return err return err
} }
func (m *defaultRoleModel) FindOne(ctx context.Context, id string) (*Role, error) { func (m *defaultRoleModel) FindOne(ctx context.Context, id string) (*Role, error) {
oaRoleIdKey := fmt.Sprintf("%s%v", cacheOaRoleIdPrefix, id)
var resp Role
err := m.QueryRowCtx(ctx, &resp, oaRoleIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error {
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", roleRows, m.table) query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", roleRows, m.table)
return conn.QueryRowCtx(ctx, v, query, id) var resp Role
}) err := m.conn.QueryRowCtx(ctx, &resp, query, id)
switch err { switch err {
case nil: case nil:
return &resp, nil return &resp, nil
case sqlc.ErrNotFound: case sqlx.ErrNotFound:
return nil, ErrNotFound return nil, ErrNotFound
default: default:
return nil, err return nil, err
@ -83,32 +73,17 @@ func (m *defaultRoleModel) FindOne(ctx context.Context, id string) (*Role, error
} }
func (m *defaultRoleModel) Insert(ctx context.Context, data *Role) (sql.Result, error) { func (m *defaultRoleModel) Insert(ctx context.Context, data *Role) (sql.Result, error) {
oaRoleIdKey := fmt.Sprintf("%s%v", cacheOaRoleIdPrefix, data.Id)
ret, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?)", m.table, roleRowsExpectAutoSet) query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?)", m.table, roleRowsExpectAutoSet)
return conn.ExecCtx(ctx, query, data.Id, data.Created, data.Updated, data.AppId, data.Name, data.Des, data.UserCount) ret, err := m.conn.ExecCtx(ctx, query, data.Id, data.Created, data.Updated, data.AppId, data.Name, data.Des, data.UserCount)
}, oaRoleIdKey)
return ret, err return ret, err
} }
func (m *defaultRoleModel) Update(ctx context.Context, data *Role) error { func (m *defaultRoleModel) Update(ctx context.Context, data *Role) error {
oaRoleIdKey := fmt.Sprintf("%s%v", cacheOaRoleIdPrefix, data.Id)
_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, roleRowsWithPlaceHolder) query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, roleRowsWithPlaceHolder)
return conn.ExecCtx(ctx, query, data.Created, data.Updated, data.AppId, data.Name, data.Des, data.UserCount, data.Id) _, err := m.conn.ExecCtx(ctx, query, data.Created, data.Updated, data.AppId, data.Name, data.Des, data.UserCount, data.Id)
}, oaRoleIdKey)
return err return err
} }
func (m *defaultRoleModel) formatPrimary(primary any) string {
return fmt.Sprintf("%s%v", cacheOaRoleIdPrefix, primary)
}
func (m *defaultRoleModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary any) error {
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", roleRows, m.table)
return conn.QueryRowCtx(ctx, v, query, primary)
}
func (m *defaultRoleModel) tableName() string { func (m *defaultRoleModel) tableName() string {
return m.table return m.table
} }

@ -0,0 +1,29 @@
package models
import "github.com/zeromicro/go-zero/core/stores/sqlx"
var _ TokenModel = (*customTokenModel)(nil)
type (
// TokenModel is an interface to be customized, add more methods here,
// and implement the added methods in customTokenModel.
TokenModel interface {
tokenModel
withSession(session sqlx.Session) TokenModel
}
customTokenModel struct {
*defaultTokenModel
}
)
// NewTokenModel returns a model for the database table.
func NewTokenModel(conn sqlx.SqlConn) TokenModel {
return &customTokenModel{
defaultTokenModel: newTokenModel(conn),
}
}
func (m *customTokenModel) withSession(session sqlx.Session) TokenModel {
return NewTokenModel(sqlx.NewSqlConnFromSession(session))
}

@ -0,0 +1,90 @@
// Code generated by goctl. DO NOT EDIT.
package models
import (
"context"
"database/sql"
"fmt"
"strings"
"time"
"github.com/zeromicro/go-zero/core/stores/builder"
"github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/core/stringx"
)
var (
tokenFieldNames = builder.RawFieldNames(&Token{})
tokenRows = strings.Join(tokenFieldNames, ",")
tokenRowsExpectAutoSet = strings.Join(stringx.Remove(tokenFieldNames, "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",")
tokenRowsWithPlaceHolder = strings.Join(stringx.Remove(tokenFieldNames, "`code`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?"
)
type (
tokenModel interface {
Insert(ctx context.Context, data *Token) (sql.Result, error)
FindOne(ctx context.Context, code string) (*Token, error)
Update(ctx context.Context, data *Token) error
Delete(ctx context.Context, code string) error
}
defaultTokenModel struct {
conn sqlx.SqlConn
table string
}
Token struct {
Code string `db:"code"`
Created time.Time `db:"created"`
Updated time.Time `db:"updated"`
Expired time.Time `db:"expired"`
ClientId string `db:"client_id"`
AppId string `db:"app_id"`
UserId string `db:"user_id"`
Meta sql.NullString `db:"meta"`
}
)
func newTokenModel(conn sqlx.SqlConn) *defaultTokenModel {
return &defaultTokenModel{
conn: conn,
table: "`token`",
}
}
func (m *defaultTokenModel) Delete(ctx context.Context, code string) error {
query := fmt.Sprintf("delete from %s where `code` = ?", m.table)
_, err := m.conn.ExecCtx(ctx, query, code)
return err
}
func (m *defaultTokenModel) FindOne(ctx context.Context, code string) (*Token, error) {
query := fmt.Sprintf("select %s from %s where `code` = ? limit 1", tokenRows, m.table)
var resp Token
err := m.conn.QueryRowCtx(ctx, &resp, query, code)
switch err {
case nil:
return &resp, nil
case sqlx.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}
func (m *defaultTokenModel) Insert(ctx context.Context, data *Token) (sql.Result, error) {
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?)", m.table, tokenRowsExpectAutoSet)
ret, err := m.conn.ExecCtx(ctx, query, data.Code, data.Created, data.Updated, data.Expired, data.ClientId, data.AppId, data.UserId, data.Meta)
return ret, err
}
func (m *defaultTokenModel) Update(ctx context.Context, data *Token) error {
query := fmt.Sprintf("update %s set %s where `code` = ?", m.table, tokenRowsWithPlaceHolder)
_, err := m.conn.ExecCtx(ctx, query, data.Created, data.Updated, data.Expired, data.ClientId, data.AppId, data.UserId, data.Meta, data.Code)
return err
}
func (m *defaultTokenModel) tableName() string {
return m.table
}

@ -1,9 +1,6 @@
package models package models
import ( import "github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
var _ UserModel = (*customUserModel)(nil) var _ UserModel = (*customUserModel)(nil)
@ -12,6 +9,7 @@ type (
// and implement the added methods in customUserModel. // and implement the added methods in customUserModel.
UserModel interface { UserModel interface {
userModel userModel
withSession(session sqlx.Session) UserModel
} }
customUserModel struct { customUserModel struct {
@ -20,8 +18,12 @@ type (
) )
// NewUserModel returns a model for the database table. // NewUserModel returns a model for the database table.
func NewUserModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) UserModel { func NewUserModel(conn sqlx.SqlConn) UserModel {
return &customUserModel{ return &customUserModel{
defaultUserModel: newUserModel(conn, c, opts...), defaultUserModel: newUserModel(conn),
} }
} }
func (m *customUserModel) withSession(session sqlx.Session) UserModel {
return NewUserModel(sqlx.NewSqlConnFromSession(session))
}

@ -10,8 +10,6 @@ import (
"time" "time"
"github.com/zeromicro/go-zero/core/stores/builder" "github.com/zeromicro/go-zero/core/stores/builder"
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/core/stores/sqlc"
"github.com/zeromicro/go-zero/core/stores/sqlx" "github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/core/stringx" "github.com/zeromicro/go-zero/core/stringx"
) )
@ -21,11 +19,6 @@ var (
userRows = strings.Join(userFieldNames, ",") userRows = strings.Join(userFieldNames, ",")
userRowsExpectAutoSet = strings.Join(stringx.Remove(userFieldNames, "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",") userRowsExpectAutoSet = strings.Join(stringx.Remove(userFieldNames, "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",")
userRowsWithPlaceHolder = strings.Join(stringx.Remove(userFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?" userRowsWithPlaceHolder = strings.Join(stringx.Remove(userFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?"
cacheOaUserIdPrefix = "cache:oa:user:id:"
cacheOaUserEmailPrefix = "cache:oa:user:email:"
cacheOaUserPhonePrefix = "cache:oa:user:phone:"
cacheOaUserUsernamePrefix = "cache:oa:user:username:"
) )
type ( type (
@ -40,7 +33,7 @@ type (
} }
defaultUserModel struct { defaultUserModel struct {
sqlc.CachedConn conn sqlx.SqlConn
table string table string
} }
@ -61,41 +54,27 @@ type (
} }
) )
func newUserModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) *defaultUserModel { func newUserModel(conn sqlx.SqlConn) *defaultUserModel {
return &defaultUserModel{ return &defaultUserModel{
CachedConn: sqlc.NewConn(conn, c, opts...), conn: conn,
table: "`user`", table: "`user`",
} }
} }
func (m *defaultUserModel) Delete(ctx context.Context, id string) error { func (m *defaultUserModel) Delete(ctx context.Context, id string) error {
data, err := m.FindOne(ctx, id)
if err != nil {
return err
}
oaUserEmailKey := fmt.Sprintf("%s%v", cacheOaUserEmailPrefix, data.Email)
oaUserIdKey := fmt.Sprintf("%s%v", cacheOaUserIdPrefix, id)
oaUserPhoneKey := fmt.Sprintf("%s%v", cacheOaUserPhonePrefix, data.Phone)
oaUserUsernameKey := fmt.Sprintf("%s%v", cacheOaUserUsernamePrefix, data.Username)
_, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("delete from %s where `id` = ?", m.table) query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
return conn.ExecCtx(ctx, query, id) _, err := m.conn.ExecCtx(ctx, query, id)
}, oaUserEmailKey, oaUserIdKey, oaUserPhoneKey, oaUserUsernameKey)
return err return err
} }
func (m *defaultUserModel) FindOne(ctx context.Context, id string) (*User, error) { func (m *defaultUserModel) FindOne(ctx context.Context, id string) (*User, error) {
oaUserIdKey := fmt.Sprintf("%s%v", cacheOaUserIdPrefix, id)
var resp User
err := m.QueryRowCtx(ctx, &resp, oaUserIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error {
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", userRows, m.table) query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", userRows, m.table)
return conn.QueryRowCtx(ctx, v, query, id) var resp User
}) err := m.conn.QueryRowCtx(ctx, &resp, query, id)
switch err { switch err {
case nil: case nil:
return &resp, nil return &resp, nil
case sqlc.ErrNotFound: case sqlx.ErrNotFound:
return nil, ErrNotFound return nil, ErrNotFound
default: default:
return nil, err return nil, err
@ -103,19 +82,13 @@ func (m *defaultUserModel) FindOne(ctx context.Context, id string) (*User, error
} }
func (m *defaultUserModel) FindOneByEmail(ctx context.Context, email sql.NullString) (*User, error) { func (m *defaultUserModel) FindOneByEmail(ctx context.Context, email sql.NullString) (*User, error) {
oaUserEmailKey := fmt.Sprintf("%s%v", cacheOaUserEmailPrefix, email)
var resp User var resp User
err := m.QueryRowIndexCtx(ctx, &resp, oaUserEmailKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v any) (i any, e error) {
query := fmt.Sprintf("select %s from %s where `email` = ? limit 1", userRows, m.table) query := fmt.Sprintf("select %s from %s where `email` = ? limit 1", userRows, m.table)
if err := conn.QueryRowCtx(ctx, &resp, query, email); err != nil { err := m.conn.QueryRowCtx(ctx, &resp, query, email)
return nil, err
}
return resp.Id, nil
}, m.queryPrimary)
switch err { switch err {
case nil: case nil:
return &resp, nil return &resp, nil
case sqlc.ErrNotFound: case sqlx.ErrNotFound:
return nil, ErrNotFound return nil, ErrNotFound
default: default:
return nil, err return nil, err
@ -123,19 +96,13 @@ func (m *defaultUserModel) FindOneByEmail(ctx context.Context, email sql.NullStr
} }
func (m *defaultUserModel) FindOneByPhone(ctx context.Context, phone sql.NullString) (*User, error) { func (m *defaultUserModel) FindOneByPhone(ctx context.Context, phone sql.NullString) (*User, error) {
oaUserPhoneKey := fmt.Sprintf("%s%v", cacheOaUserPhonePrefix, phone)
var resp User var resp User
err := m.QueryRowIndexCtx(ctx, &resp, oaUserPhoneKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v any) (i any, e error) {
query := fmt.Sprintf("select %s from %s where `phone` = ? limit 1", userRows, m.table) query := fmt.Sprintf("select %s from %s where `phone` = ? limit 1", userRows, m.table)
if err := conn.QueryRowCtx(ctx, &resp, query, phone); err != nil { err := m.conn.QueryRowCtx(ctx, &resp, query, phone)
return nil, err
}
return resp.Id, nil
}, m.queryPrimary)
switch err { switch err {
case nil: case nil:
return &resp, nil return &resp, nil
case sqlc.ErrNotFound: case sqlx.ErrNotFound:
return nil, ErrNotFound return nil, ErrNotFound
default: default:
return nil, err return nil, err
@ -143,19 +110,13 @@ func (m *defaultUserModel) FindOneByPhone(ctx context.Context, phone sql.NullStr
} }
func (m *defaultUserModel) FindOneByUsername(ctx context.Context, username string) (*User, error) { func (m *defaultUserModel) FindOneByUsername(ctx context.Context, username string) (*User, error) {
oaUserUsernameKey := fmt.Sprintf("%s%v", cacheOaUserUsernamePrefix, username)
var resp User var resp User
err := m.QueryRowIndexCtx(ctx, &resp, oaUserUsernameKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v any) (i any, e error) {
query := fmt.Sprintf("select %s from %s where `username` = ? limit 1", userRows, m.table) query := fmt.Sprintf("select %s from %s where `username` = ? limit 1", userRows, m.table)
if err := conn.QueryRowCtx(ctx, &resp, query, username); err != nil { err := m.conn.QueryRowCtx(ctx, &resp, query, username)
return nil, err
}
return resp.Id, nil
}, m.queryPrimary)
switch err { switch err {
case nil: case nil:
return &resp, nil return &resp, nil
case sqlc.ErrNotFound: case sqlx.ErrNotFound:
return nil, ErrNotFound return nil, ErrNotFound
default: default:
return nil, err return nil, err
@ -163,43 +124,17 @@ func (m *defaultUserModel) FindOneByUsername(ctx context.Context, username strin
} }
func (m *defaultUserModel) Insert(ctx context.Context, data *User) (sql.Result, error) { func (m *defaultUserModel) Insert(ctx context.Context, data *User) (sql.Result, error) {
oaUserEmailKey := fmt.Sprintf("%s%v", cacheOaUserEmailPrefix, data.Email)
oaUserIdKey := fmt.Sprintf("%s%v", cacheOaUserIdPrefix, data.Id)
oaUserPhoneKey := fmt.Sprintf("%s%v", cacheOaUserPhonePrefix, data.Phone)
oaUserUsernameKey := fmt.Sprintf("%s%v", cacheOaUserUsernamePrefix, data.Username)
ret, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", m.table, userRowsExpectAutoSet) query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", m.table, userRowsExpectAutoSet)
return conn.ExecCtx(ctx, query, data.Id, data.Created, data.Updated, data.Username, data.Nickname, data.Email, data.Phone, data.Icon, data.RealCode, data.CheckCode, data.Status, data.Used, data.Space) ret, err := m.conn.ExecCtx(ctx, query, data.Id, data.Created, data.Updated, data.Username, data.Nickname, data.Email, data.Phone, data.Icon, data.RealCode, data.CheckCode, data.Status, data.Used, data.Space)
}, oaUserEmailKey, oaUserIdKey, oaUserPhoneKey, oaUserUsernameKey)
return ret, err return ret, err
} }
func (m *defaultUserModel) Update(ctx context.Context, newData *User) error { func (m *defaultUserModel) Update(ctx context.Context, newData *User) error {
data, err := m.FindOne(ctx, newData.Id)
if err != nil {
return err
}
oaUserEmailKey := fmt.Sprintf("%s%v", cacheOaUserEmailPrefix, data.Email)
oaUserIdKey := fmt.Sprintf("%s%v", cacheOaUserIdPrefix, data.Id)
oaUserPhoneKey := fmt.Sprintf("%s%v", cacheOaUserPhonePrefix, data.Phone)
oaUserUsernameKey := fmt.Sprintf("%s%v", cacheOaUserUsernamePrefix, data.Username)
_, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, userRowsWithPlaceHolder) query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, userRowsWithPlaceHolder)
return conn.ExecCtx(ctx, query, newData.Created, newData.Updated, newData.Username, newData.Nickname, newData.Email, newData.Phone, newData.Icon, newData.RealCode, newData.CheckCode, newData.Status, newData.Used, newData.Space, newData.Id) _, err := m.conn.ExecCtx(ctx, query, newData.Created, newData.Updated, newData.Username, newData.Nickname, newData.Email, newData.Phone, newData.Icon, newData.RealCode, newData.CheckCode, newData.Status, newData.Used, newData.Space, newData.Id)
}, oaUserEmailKey, oaUserIdKey, oaUserPhoneKey, oaUserUsernameKey)
return err return err
} }
func (m *defaultUserModel) formatPrimary(primary any) string {
return fmt.Sprintf("%s%v", cacheOaUserIdPrefix, primary)
}
func (m *defaultUserModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary any) error {
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", userRows, m.table)
return conn.QueryRowCtx(ctx, v, query, primary)
}
func (m *defaultUserModel) tableName() string { func (m *defaultUserModel) tableName() string {
return m.table return m.table
} }

@ -1,9 +1,6 @@
package models package models
import ( import "github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
var _ UserRoleModel = (*customUserRoleModel)(nil) var _ UserRoleModel = (*customUserRoleModel)(nil)
@ -12,6 +9,7 @@ type (
// and implement the added methods in customUserRoleModel. // and implement the added methods in customUserRoleModel.
UserRoleModel interface { UserRoleModel interface {
userRoleModel userRoleModel
withSession(session sqlx.Session) UserRoleModel
} }
customUserRoleModel struct { customUserRoleModel struct {
@ -20,8 +18,12 @@ type (
) )
// NewUserRoleModel returns a model for the database table. // NewUserRoleModel returns a model for the database table.
func NewUserRoleModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) UserRoleModel { func NewUserRoleModel(conn sqlx.SqlConn) UserRoleModel {
return &customUserRoleModel{ return &customUserRoleModel{
defaultUserRoleModel: newUserRoleModel(conn, c, opts...), defaultUserRoleModel: newUserRoleModel(conn),
} }
} }
func (m *customUserRoleModel) withSession(session sqlx.Session) UserRoleModel {
return NewUserRoleModel(sqlx.NewSqlConnFromSession(session))
}

@ -10,8 +10,6 @@ import (
"time" "time"
"github.com/zeromicro/go-zero/core/stores/builder" "github.com/zeromicro/go-zero/core/stores/builder"
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/core/stores/sqlc"
"github.com/zeromicro/go-zero/core/stores/sqlx" "github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/core/stringx" "github.com/zeromicro/go-zero/core/stringx"
) )
@ -21,9 +19,6 @@ var (
userRoleRows = strings.Join(userRoleFieldNames, ",") userRoleRows = strings.Join(userRoleFieldNames, ",")
userRoleRowsExpectAutoSet = strings.Join(stringx.Remove(userRoleFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",") userRoleRowsExpectAutoSet = strings.Join(stringx.Remove(userRoleFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",")
userRoleRowsWithPlaceHolder = strings.Join(stringx.Remove(userRoleFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?" userRoleRowsWithPlaceHolder = strings.Join(stringx.Remove(userRoleFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?"
cacheOaUserRoleIdPrefix = "cache:oa:userRole:id:"
cacheOaUserRoleUserIdRoleIdPrefix = "cache:oa:userRole:userId:roleId:"
) )
type ( type (
@ -36,7 +31,7 @@ type (
} }
defaultUserRoleModel struct { defaultUserRoleModel struct {
sqlc.CachedConn conn sqlx.SqlConn
table string table string
} }
@ -50,39 +45,27 @@ type (
} }
) )
func newUserRoleModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) *defaultUserRoleModel { func newUserRoleModel(conn sqlx.SqlConn) *defaultUserRoleModel {
return &defaultUserRoleModel{ return &defaultUserRoleModel{
CachedConn: sqlc.NewConn(conn, c, opts...), conn: conn,
table: "`user_role`", table: "`user_role`",
} }
} }
func (m *defaultUserRoleModel) Delete(ctx context.Context, id int64) error { func (m *defaultUserRoleModel) Delete(ctx context.Context, id int64) error {
data, err := m.FindOne(ctx, id)
if err != nil {
return err
}
oaUserRoleIdKey := fmt.Sprintf("%s%v", cacheOaUserRoleIdPrefix, id)
oaUserRoleUserIdRoleIdKey := fmt.Sprintf("%s%v:%v", cacheOaUserRoleUserIdRoleIdPrefix, data.UserId, data.RoleId)
_, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("delete from %s where `id` = ?", m.table) query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
return conn.ExecCtx(ctx, query, id) _, err := m.conn.ExecCtx(ctx, query, id)
}, oaUserRoleIdKey, oaUserRoleUserIdRoleIdKey)
return err return err
} }
func (m *defaultUserRoleModel) FindOne(ctx context.Context, id int64) (*UserRole, error) { func (m *defaultUserRoleModel) FindOne(ctx context.Context, id int64) (*UserRole, error) {
oaUserRoleIdKey := fmt.Sprintf("%s%v", cacheOaUserRoleIdPrefix, id)
var resp UserRole
err := m.QueryRowCtx(ctx, &resp, oaUserRoleIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error {
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", userRoleRows, m.table) query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", userRoleRows, m.table)
return conn.QueryRowCtx(ctx, v, query, id) var resp UserRole
}) err := m.conn.QueryRowCtx(ctx, &resp, query, id)
switch err { switch err {
case nil: case nil:
return &resp, nil return &resp, nil
case sqlc.ErrNotFound: case sqlx.ErrNotFound:
return nil, ErrNotFound return nil, ErrNotFound
default: default:
return nil, err return nil, err
@ -90,19 +73,13 @@ func (m *defaultUserRoleModel) FindOne(ctx context.Context, id int64) (*UserRole
} }
func (m *defaultUserRoleModel) FindOneByUserIdRoleId(ctx context.Context, userId string, roleId string) (*UserRole, error) { func (m *defaultUserRoleModel) FindOneByUserIdRoleId(ctx context.Context, userId string, roleId string) (*UserRole, error) {
oaUserRoleUserIdRoleIdKey := fmt.Sprintf("%s%v:%v", cacheOaUserRoleUserIdRoleIdPrefix, userId, roleId)
var resp UserRole var resp UserRole
err := m.QueryRowIndexCtx(ctx, &resp, oaUserRoleUserIdRoleIdKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v any) (i any, e error) {
query := fmt.Sprintf("select %s from %s where `user_id` = ? and `role_id` = ? limit 1", userRoleRows, m.table) query := fmt.Sprintf("select %s from %s where `user_id` = ? and `role_id` = ? limit 1", userRoleRows, m.table)
if err := conn.QueryRowCtx(ctx, &resp, query, userId, roleId); err != nil { err := m.conn.QueryRowCtx(ctx, &resp, query, userId, roleId)
return nil, err
}
return resp.Id, nil
}, m.queryPrimary)
switch err { switch err {
case nil: case nil:
return &resp, nil return &resp, nil
case sqlc.ErrNotFound: case sqlx.ErrNotFound:
return nil, ErrNotFound return nil, ErrNotFound
default: default:
return nil, err return nil, err
@ -110,39 +87,17 @@ func (m *defaultUserRoleModel) FindOneByUserIdRoleId(ctx context.Context, userId
} }
func (m *defaultUserRoleModel) Insert(ctx context.Context, data *UserRole) (sql.Result, error) { func (m *defaultUserRoleModel) Insert(ctx context.Context, data *UserRole) (sql.Result, error) {
oaUserRoleIdKey := fmt.Sprintf("%s%v", cacheOaUserRoleIdPrefix, data.Id)
oaUserRoleUserIdRoleIdKey := fmt.Sprintf("%s%v:%v", cacheOaUserRoleUserIdRoleIdPrefix, data.UserId, data.RoleId)
ret, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?)", m.table, userRoleRowsExpectAutoSet) query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?)", m.table, userRoleRowsExpectAutoSet)
return conn.ExecCtx(ctx, query, data.Created, data.Updated, data.UserId, data.RoleId, data.Status) ret, err := m.conn.ExecCtx(ctx, query, data.Created, data.Updated, data.UserId, data.RoleId, data.Status)
}, oaUserRoleIdKey, oaUserRoleUserIdRoleIdKey)
return ret, err return ret, err
} }
func (m *defaultUserRoleModel) Update(ctx context.Context, newData *UserRole) error { func (m *defaultUserRoleModel) Update(ctx context.Context, newData *UserRole) error {
data, err := m.FindOne(ctx, newData.Id)
if err != nil {
return err
}
oaUserRoleIdKey := fmt.Sprintf("%s%v", cacheOaUserRoleIdPrefix, data.Id)
oaUserRoleUserIdRoleIdKey := fmt.Sprintf("%s%v:%v", cacheOaUserRoleUserIdRoleIdPrefix, data.UserId, data.RoleId)
_, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, userRoleRowsWithPlaceHolder) query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, userRoleRowsWithPlaceHolder)
return conn.ExecCtx(ctx, query, newData.Created, newData.Updated, newData.UserId, newData.RoleId, newData.Status, newData.Id) _, err := m.conn.ExecCtx(ctx, query, newData.Created, newData.Updated, newData.UserId, newData.RoleId, newData.Status, newData.Id)
}, oaUserRoleIdKey, oaUserRoleUserIdRoleIdKey)
return err return err
} }
func (m *defaultUserRoleModel) formatPrimary(primary any) string {
return fmt.Sprintf("%s%v", cacheOaUserRoleIdPrefix, primary)
}
func (m *defaultUserRoleModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary any) error {
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", userRoleRows, m.table)
return conn.QueryRowCtx(ctx, v, query, primary)
}
func (m *defaultUserRoleModel) tableName() string { func (m *defaultUserRoleModel) tableName() string {
return m.table return m.table
} }

@ -4,7 +4,6 @@ import "base.api"
type ( type (
// 定义登录接口的请求体 // 定义登录接口的请求体
AppReq { AppReq {
error
appname string `json:"username"` appname string `json:"username"`
Password string `json:"password"` Password string `json:"password"`
} }

@ -1,5 +1,4 @@
type error { type auth {
status string `json:"status"` Authorization string `header:"authorization"`
code int `json:"code"`
} }

@ -2,38 +2,61 @@ import "base.api"
type ( type (
// 定义登录接口的请求体
LoginReq { LoginReq {
error id string `json:"id"`
Username string `json:"username"` code string `json:"code"`
Password string `json:"password"` verify string `json:"verify"`
}
RegReq {
username string `json:"username"`
pwd string `json:"pwd"`
} }
// 定义登录接口的响应体
LoginResp { getReq {
Id int64 `json:"id"` Id int64 `path:"id"`
Name string `json:"name"` }
Token string `json:"token"` listReq {
ExpireAt string `json:"expireAt"` Username string `query:"username"`
}
userResp {
Id string `json:"id"`
Created uint `json:"created"`
Updated uint `json:"updated"`
Username string `json:"username"`
Nickname string `json:"nickname"`
Email string `json:"email"`
Phone string `json:"phone"`
Icon string `json:"icon"`
Status int64 `json:"status"` // 状态0ok1disabled
Used int64 `json:"used"`
Space int64 `json:"space"`
} }
) )
@server ( @server (
// 代表当前 service 代码块下的路由生成代码时都会被放到 user 目录下
group: user group: user
// 定义路由前缀为 "/v1"
prefix: /api/user prefix: /api/user
) )
// 定义 HTTP 服务
// 微服务名称为main生成的代码目录和配置文件将和 user 值相关
service main { service main {
// 定义 http.HandleFunc 转换的 go 文件名称及方法
@handler Login @handler Login
// 定义接口 head / (LoginReq) returns ()
// 请求方法为 post
// 路由为 /user/login @handler Reg
// 请求体为 LoginReq post / (RegReq) returns ()
// 响应体为 LoginResp响应体必须有 returns 关键字修饰 }
post /login (LoginReq) returns (LoginResp)
@server (
group: user
middleware: Auth
prefix: /api/user
)
service main {
@handler get
get /:id (getReq) returns (userResp)
@handler list
get / (listReq) returns ([]userResp)
} }

Loading…
Cancel
Save