feat: manually mirror opencoze's code from bytedance

Change-Id: I09a73aadda978ad9511264a756b2ce51f5761adf
This commit is contained in:
fanlv
2025-07-20 17:36:12 +08:00
commit 890153324f
14811 changed files with 1923430 additions and 0 deletions

View File

@@ -0,0 +1,33 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package openapiauth
import (
"context"
"github.com/coze-dev/coze-studio/backend/domain/openauth/openapiauth/entity"
)
type APIAuth interface {
Create(ctx context.Context, req *entity.CreateApiKey) (*entity.ApiKey, error)
Delete(ctx context.Context, req *entity.DeleteApiKey) error
Get(ctx context.Context, req *entity.GetApiKey) (*entity.ApiKey, error)
List(ctx context.Context, req *entity.ListApiKey) (*entity.ListApiKeyResp, error)
Save(ctx context.Context, req *entity.SaveMeta) error
CheckPermission(ctx context.Context, req *entity.CheckPermission) (*entity.ApiKey, error)
}

View File

@@ -0,0 +1,141 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package openapiauth
import (
"context"
"time"
"gorm.io/gorm"
"github.com/coze-dev/coze-studio/backend/domain/openauth/openapiauth/entity"
"github.com/coze-dev/coze-studio/backend/domain/openauth/openapiauth/internal/dal"
"github.com/coze-dev/coze-studio/backend/domain/openauth/openapiauth/internal/dal/model"
"github.com/coze-dev/coze-studio/backend/infra/contract/idgen"
"github.com/coze-dev/coze-studio/backend/pkg/lang/slices"
"github.com/coze-dev/coze-studio/backend/pkg/logs"
)
type apiAuthImpl struct {
IDGen idgen.IDGenerator
DB *gorm.DB
dao *dal.ApiKeyDAO
}
type Components struct {
IDGen idgen.IDGenerator
DB *gorm.DB
}
func NewService(c *Components) APIAuth {
return &apiAuthImpl{
IDGen: c.IDGen,
DB: c.DB,
dao: dal.NewApiKeyDAO(c.IDGen, c.DB),
}
}
func (a *apiAuthImpl) Create(ctx context.Context, req *entity.CreateApiKey) (*entity.ApiKey, error) {
apiKeyData, err := a.dao.Create(ctx, req)
if err != nil {
return nil, err
}
return apiKeyData, nil
}
func (a *apiAuthImpl) Delete(ctx context.Context, req *entity.DeleteApiKey) error {
return a.dao.Delete(ctx, req.ID, req.UserID)
}
func (a *apiAuthImpl) Get(ctx context.Context, req *entity.GetApiKey) (*entity.ApiKey, error) {
apiKey, err := a.dao.Get(ctx, req.ID)
logs.CtxInfof(ctx, "apiKey=%v, err:%v", apiKey, err)
if err != nil {
return nil, err
}
if apiKey == nil {
return nil, nil
}
return a.buildPoData2ApiKey([]*model.APIKey{apiKey})[0], nil
}
func (a *apiAuthImpl) buildPoData2ApiKey(apiKey []*model.APIKey) []*entity.ApiKey {
apiKeyData := slices.Transform(apiKey, func(a *model.APIKey) *entity.ApiKey {
return &entity.ApiKey{
ID: a.ID,
Name: a.Name,
ApiKey: a.APIKey,
UserID: a.UserID,
ExpiredAt: a.ExpiredAt,
CreatedAt: a.CreatedAt,
LastUsedAt: a.LastUsedAt,
}
})
return apiKeyData
}
func (a *apiAuthImpl) List(ctx context.Context, req *entity.ListApiKey) (*entity.ListApiKeyResp, error) {
resp := &entity.ListApiKeyResp{
ApiKeys: make([]*entity.ApiKey, 0),
HasMore: false,
}
apiKey, hasMore, err := a.dao.List(ctx, req.UserID, int(req.Limit), int(req.Page))
if err != nil {
return nil, err
}
resp.ApiKeys = a.buildPoData2ApiKey(apiKey)
resp.HasMore = hasMore
return resp, nil
}
func (a *apiAuthImpl) CheckPermission(ctx context.Context, req *entity.CheckPermission) (*entity.ApiKey, error) {
apiKey, err := a.dao.FindByKey(ctx, req.ApiKey)
if err != nil {
return nil, err
}
if apiKey.APIKey != req.ApiKey {
return nil, nil
}
apiKeyDo := &entity.ApiKey{
ID: apiKey.ID,
Name: apiKey.Name,
UserID: apiKey.UserID,
ExpiredAt: apiKey.ExpiredAt,
CreatedAt: apiKey.CreatedAt,
}
return apiKeyDo, nil
}
func (a *apiAuthImpl) Save(ctx context.Context, sm *entity.SaveMeta) error {
updateColumn := make(map[string]any)
if sm.Name != nil {
updateColumn["name"] = sm.Name
}
if sm.LastUsedAt != nil {
updateColumn["last_used_at"] = sm.LastUsedAt
}
updateColumn["updated_at"] = time.Now().Unix()
err := a.dao.Update(ctx, sm.ID, sm.UserID, updateColumn)
return err
}

View File

@@ -0,0 +1,204 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package openapiauth
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"go.uber.org/mock/gomock"
"github.com/coze-dev/coze-studio/backend/domain/openauth/openapiauth/entity"
"github.com/coze-dev/coze-studio/backend/domain/openauth/openapiauth/internal/dal/model"
mock "github.com/coze-dev/coze-studio/backend/internal/mock/infra/contract/idgen"
"github.com/coze-dev/coze-studio/backend/internal/mock/infra/contract/orm"
)
func TestApiAuthImpl_Create(t *testing.T) {
ctx := context.Background()
ctrl := gomock.NewController(t)
idGen := mock.NewMockIDGenerator(ctrl)
idGen.EXPECT().GenID(gomock.Any()).Return(int64(10000000001), nil).Times(1)
mockDBGen := orm.NewMockDB()
mockDBGen.AddTable(&model.APIKey{})
mockDB, err := mockDBGen.DB()
assert.NoError(t, err)
components := &Components{
IDGen: idGen,
DB: mockDB,
}
apiAuth := NewService(components)
apiKey, err := apiAuth.Create(ctx, &entity.CreateApiKey{
Name: "test",
Expire: time.Now().Add(time.Hour).UnixMilli(),
UserID: 666666,
})
t.Logf("apiKey: %v", *apiKey)
assert.NoError(t, err)
assert.NotNil(t, apiKey)
assert.Equal(t, "test", apiKey.Name)
assert.NotEmpty(t, apiKey.ApiKey)
}
func TestApiAuthImpl_Get(t *testing.T) {
ctx := context.Background()
mockDBGen := orm.NewMockDB()
mockDBGen.AddTable(&model.APIKey{})
mockDBGen.AddTable(&model.APIKey{}).
AddRows(
&model.APIKey{
ID: 10000000001,
Name: "test",
APIKey: "a5f58bea9028d49143bff3ee436b2fb663291c0c6ab242f3c9dc6bf6df9f7b74",
Status: 0,
UserID: 666666,
ExpiredAt: time.Now().Add(time.Hour).UnixMilli(),
CreatedAt: time.Now().UnixMilli(),
UpdatedAt: time.Now().UnixMilli(),
},
)
mockDB, err := mockDBGen.DB()
assert.NoError(t, err)
components := &Components{
DB: mockDB,
}
apiAuth := NewService(components)
apiKey, err := apiAuth.Get(ctx, &entity.GetApiKey{
ID: 10000000001,
})
assert.NoError(t, err)
assert.NotNil(t, apiKey)
t.Logf("apiKey: %v", *apiKey)
assert.Equal(t, "test", apiKey.Name)
}
func TestApiAuthImpl_Delete(t *testing.T) {
ctx := context.Background()
mockDBGen := orm.NewMockDB()
mockDBGen.AddTable(&model.APIKey{})
mockDBGen.AddTable(&model.APIKey{}).
AddRows(
&model.APIKey{
ID: 10000000001,
Name: "test",
APIKey: "df9f7b74",
Status: 0,
UserID: 666666,
ExpiredAt: time.Now().Add(time.Hour).UnixMilli(),
CreatedAt: time.Now().UnixMilli(),
UpdatedAt: time.Now().UnixMilli(),
},
)
mockDB, err := mockDBGen.DB()
assert.NoError(t, err)
components := &Components{
DB: mockDB,
}
apiAuth := NewService(components)
err = apiAuth.Delete(ctx, &entity.DeleteApiKey{
ID: 10000000001,
})
assert.NoError(t, err)
}
func TestApiAuthImpl_List(t *testing.T) {
ctx := context.Background()
mockDBGen := orm.NewMockDB()
mockDBGen.AddTable(&model.APIKey{})
mockDBGen.AddTable(&model.APIKey{}).
AddRows(
&model.APIKey{
ID: 10000000001,
Name: "test",
APIKey: "df9f7b74",
Status: 0,
UserID: 666666,
ExpiredAt: time.Now().Add(time.Hour).UnixMilli(),
CreatedAt: time.Now().UnixMilli(),
UpdatedAt: time.Now().UnixMilli(),
},
&model.APIKey{
ID: 10000000002,
Name: "test2",
APIKey: "adfadfad",
Status: 0,
UserID: 666666,
ExpiredAt: time.Now().Add(time.Hour).UnixMilli(),
CreatedAt: time.Now().Add(time.Hour).UnixMilli(),
UpdatedAt: time.Now().UnixMilli(),
},
)
mockDB, err := mockDBGen.DB()
assert.NoError(t, err)
components := &Components{
DB: mockDB,
}
apiAuth := NewService(components)
apiKeys, err := apiAuth.List(ctx, &entity.ListApiKey{
UserID: 666666,
Limit: 1,
Page: 1,
})
assert.NoError(t, err)
assert.NotNil(t, apiKeys)
t.Logf("apiKeys: %v", apiKeys)
assert.Equal(t, true, apiKeys.HasMore)
assert.Equal(t, 1, len(apiKeys.ApiKeys))
}
func TestApiAuthImpl_CheckPermission(t *testing.T) {
ctx := context.Background()
mockDBGen := orm.NewMockDB()
mockDBGen.AddTable(&model.APIKey{})
mockDBGen.AddTable(&model.APIKey{}).
AddRows(
&model.APIKey{
ID: 10000000001,
Name: "test",
APIKey: "df9f7b74",
Status: 0,
UserID: 666666,
ExpiredAt: time.Now().Add(time.Hour).UnixMilli(),
CreatedAt: time.Now().UnixMilli(),
UpdatedAt: time.Now().UnixMilli(),
},
)
mockDB, err := mockDBGen.DB()
assert.NoError(t, err)
components := &Components{
DB: mockDB,
}
apiAuth := NewService(components)
apiKey, err := apiAuth.CheckPermission(ctx, &entity.CheckPermission{
ApiKey: "df9f7b74",
UserID: 666666,
})
assert.NoError(t, err)
assert.Equal(t, "test", apiKey.Name)
}

View File

@@ -0,0 +1,66 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package entity
type ApiKey struct {
ID int64 `json:"id"`
Name string `json:"name"`
ApiKey string `json:"api_key"`
ConnectorID int64 `json:"connector"`
UserID int64 `json:"user_id"`
LastUsedAt int64 `json:"last_used_at"`
ExpiredAt int64 `json:"expired_at"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
type CreateApiKey struct {
Name string `json:"name"`
Expire int64 `json:"expire"`
UserID int64 `json:"user_id"`
}
type DeleteApiKey struct {
ID int64 `json:"id"`
UserID int64 `json:"user_id"`
}
type GetApiKey struct {
ID int64 `json:"id"`
}
type ListApiKey struct {
UserID int64 `json:"user_id"`
Limit int64 `json:"limit"`
Page int64 `json:"page"`
}
type ListApiKeyResp struct {
ApiKeys []*ApiKey `json:"api_keys"`
HasMore bool `json:"has_more"`
}
type SaveMeta struct {
ID int64 `json:"id"`
Name *string `json:"name"`
UserID int64 `json:"user_id"`
LastUsedAt *int64 `json:"last_used_at"`
}
type CheckPermission struct {
ApiKey string `json:"api_key"`
UserID int64 `json:"user_id"`
}

View File

@@ -0,0 +1,142 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dal
import (
"context"
"crypto/md5"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"time"
"gorm.io/gorm"
"github.com/coze-dev/coze-studio/backend/domain/openauth/openapiauth/entity"
"github.com/coze-dev/coze-studio/backend/domain/openauth/openapiauth/internal/dal/model"
"github.com/coze-dev/coze-studio/backend/domain/openauth/openapiauth/internal/dal/query"
"github.com/coze-dev/coze-studio/backend/infra/contract/idgen"
)
type ApiKeyDAO struct {
IDGen idgen.IDGenerator
dbQuery *query.Query
}
func NewApiKeyDAO(idGen idgen.IDGenerator, db *gorm.DB) *ApiKeyDAO {
return &ApiKeyDAO{
IDGen: idGen,
dbQuery: query.Use(db),
}
}
func (a *ApiKeyDAO) Create(ctx context.Context, do *entity.CreateApiKey) (*entity.ApiKey, error) {
poData, err := a.doToPo(ctx, do)
if err != nil {
return nil, err
}
originApiKey, md5Key := a.getAPIKey(poData.ID)
poData.APIKey = md5Key
err = a.dbQuery.APIKey.WithContext(ctx).Create(poData)
if err != nil {
return nil, err
}
doData := a.poToDo(poData)
doData.ApiKey = originApiKey
return doData, nil
}
func (a *ApiKeyDAO) doToPo(ctx context.Context, do *entity.CreateApiKey) (*model.APIKey, error) {
id, err := a.IDGen.GenID(ctx)
if err != nil {
return nil, errors.New("gen id failed")
}
po := &model.APIKey{
ID: id,
Name: do.Name,
ExpiredAt: do.Expire,
UserID: do.UserID,
CreatedAt: time.Now().Unix(),
}
return po, nil
}
func (a *ApiKeyDAO) poToDo(po *model.APIKey) *entity.ApiKey {
do := &entity.ApiKey{
ID: po.ID,
Name: po.Name,
ExpiredAt: po.ExpiredAt,
UserID: po.UserID,
CreatedAt: po.CreatedAt,
}
return do
}
func (a *ApiKeyDAO) getAPIKey(id int64) (string, string) {
hash := sha256.Sum256([]byte(fmt.Sprintf("%d", id)))
apiKey := "pat_" + hex.EncodeToString(hash[:])
md5Hash := md5.Sum([]byte(apiKey))
md5Key := hex.EncodeToString(md5Hash[:])
return apiKey, md5Key
}
func (a *ApiKeyDAO) Delete(ctx context.Context, id int64, userID int64) error {
_, err := a.dbQuery.APIKey.WithContext(ctx).Where(a.dbQuery.APIKey.ID.Eq(id)).Where(a.dbQuery.APIKey.UserID.Eq(userID)).Delete()
return err
}
func (a *ApiKeyDAO) Get(ctx context.Context, id int64) (*model.APIKey, error) {
apikey, err := a.dbQuery.APIKey.WithContext(ctx).Debug().Where(a.dbQuery.APIKey.ID.Eq(id)).First()
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
if err != nil {
return nil, err
}
return apikey, nil
}
func (a *ApiKeyDAO) FindByKey(ctx context.Context, key string) (*model.APIKey, error) {
return a.dbQuery.APIKey.WithContext(ctx).Where(a.dbQuery.APIKey.APIKey.Eq(key)).First()
}
func (a *ApiKeyDAO) List(ctx context.Context, userID int64, limit int, page int) ([]*model.APIKey, bool, error) {
do := a.dbQuery.APIKey.WithContext(ctx).Where(a.dbQuery.APIKey.UserID.Eq(userID))
do = do.Offset((page - 1) * limit).Limit(limit + 1)
list, err := do.Order(a.dbQuery.APIKey.CreatedAt.Desc()).Find()
if err != nil {
return nil, false, err
}
if len(list) > limit {
return list[:limit], true, nil
}
return list, false, nil
}
func (a *ApiKeyDAO) Update(ctx context.Context, id int64, userID int64, columnData map[string]any) error {
_, err := a.dbQuery.APIKey.WithContext(ctx).Where(a.dbQuery.APIKey.ID.Eq(id)).Where(a.dbQuery.APIKey.UserID.Eq(userID)).UpdateColumns(columnData)
if err != nil {
return err
}
return nil
}

View File

@@ -0,0 +1,25 @@
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
package model
const TableNameAPIKey = "api_key"
// APIKey api key table
type APIKey struct {
ID int64 `gorm:"column:id;primaryKey;autoIncrement:true;comment:Primary Key ID" json:"id"` // Primary Key ID
APIKey string `gorm:"column:api_key;not null;comment:API Key hash" json:"api_key"` // API Key hash
Name string `gorm:"column:name;not null;comment:API Key Name" json:"name"` // API Key Name
Status int32 `gorm:"column:status;not null;comment:0 normal, 1 deleted" json:"status"` // 0 normal, 1 deleted
UserID int64 `gorm:"column:user_id;not null;comment:API Key Owner" json:"user_id"` // API Key Owner
ExpiredAt int64 `gorm:"column:expired_at;not null;comment:API Key Expired Time" json:"expired_at"` // API Key Expired Time
CreatedAt int64 `gorm:"column:created_at;not null;autoCreateTime:milli;comment:Create Time in Milliseconds" json:"created_at"` // Create Time in Milliseconds
UpdatedAt int64 `gorm:"column:updated_at;not null;autoUpdateTime:milli;comment:Update Time in Milliseconds" json:"updated_at"` // Update Time in Milliseconds
LastUsedAt int64 `gorm:"column:last_used_at;not null;comment:Used Time in Milliseconds" json:"last_used_at"` // Used Time in Milliseconds
}
// TableName APIKey's table name
func (*APIKey) TableName() string {
return TableNameAPIKey
}

View File

@@ -0,0 +1,413 @@
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
package query
import (
"context"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/schema"
"gorm.io/gen"
"gorm.io/gen/field"
"gorm.io/plugin/dbresolver"
"github.com/coze-dev/coze-studio/backend/domain/openauth/openapiauth/internal/dal/model"
)
func newAPIKey(db *gorm.DB, opts ...gen.DOOption) aPIKey {
_aPIKey := aPIKey{}
_aPIKey.aPIKeyDo.UseDB(db, opts...)
_aPIKey.aPIKeyDo.UseModel(&model.APIKey{})
tableName := _aPIKey.aPIKeyDo.TableName()
_aPIKey.ALL = field.NewAsterisk(tableName)
_aPIKey.ID = field.NewInt64(tableName, "id")
_aPIKey.APIKey = field.NewString(tableName, "api_key")
_aPIKey.Name = field.NewString(tableName, "name")
_aPIKey.Status = field.NewInt32(tableName, "status")
_aPIKey.UserID = field.NewInt64(tableName, "user_id")
_aPIKey.ExpiredAt = field.NewInt64(tableName, "expired_at")
_aPIKey.CreatedAt = field.NewInt64(tableName, "created_at")
_aPIKey.UpdatedAt = field.NewInt64(tableName, "updated_at")
_aPIKey.LastUsedAt = field.NewInt64(tableName, "last_used_at")
_aPIKey.fillFieldMap()
return _aPIKey
}
// aPIKey api key table
type aPIKey struct {
aPIKeyDo
ALL field.Asterisk
ID field.Int64 // Primary Key ID
APIKey field.String // API Key hash
Name field.String // API Key Name
Status field.Int32 // 0 normal, 1 deleted
UserID field.Int64 // API Key Owner
ExpiredAt field.Int64 // API Key Expired Time
CreatedAt field.Int64 // Create Time in Milliseconds
UpdatedAt field.Int64 // Update Time in Milliseconds
LastUsedAt field.Int64 // Used Time in Milliseconds
fieldMap map[string]field.Expr
}
func (a aPIKey) Table(newTableName string) *aPIKey {
a.aPIKeyDo.UseTable(newTableName)
return a.updateTableName(newTableName)
}
func (a aPIKey) As(alias string) *aPIKey {
a.aPIKeyDo.DO = *(a.aPIKeyDo.As(alias).(*gen.DO))
return a.updateTableName(alias)
}
func (a *aPIKey) updateTableName(table string) *aPIKey {
a.ALL = field.NewAsterisk(table)
a.ID = field.NewInt64(table, "id")
a.APIKey = field.NewString(table, "api_key")
a.Name = field.NewString(table, "name")
a.Status = field.NewInt32(table, "status")
a.UserID = field.NewInt64(table, "user_id")
a.ExpiredAt = field.NewInt64(table, "expired_at")
a.CreatedAt = field.NewInt64(table, "created_at")
a.UpdatedAt = field.NewInt64(table, "updated_at")
a.LastUsedAt = field.NewInt64(table, "last_used_at")
a.fillFieldMap()
return a
}
func (a *aPIKey) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
_f, ok := a.fieldMap[fieldName]
if !ok || _f == nil {
return nil, false
}
_oe, ok := _f.(field.OrderExpr)
return _oe, ok
}
func (a *aPIKey) fillFieldMap() {
a.fieldMap = make(map[string]field.Expr, 9)
a.fieldMap["id"] = a.ID
a.fieldMap["api_key"] = a.APIKey
a.fieldMap["name"] = a.Name
a.fieldMap["status"] = a.Status
a.fieldMap["user_id"] = a.UserID
a.fieldMap["expired_at"] = a.ExpiredAt
a.fieldMap["created_at"] = a.CreatedAt
a.fieldMap["updated_at"] = a.UpdatedAt
a.fieldMap["last_used_at"] = a.LastUsedAt
}
func (a aPIKey) clone(db *gorm.DB) aPIKey {
a.aPIKeyDo.ReplaceConnPool(db.Statement.ConnPool)
return a
}
func (a aPIKey) replaceDB(db *gorm.DB) aPIKey {
a.aPIKeyDo.ReplaceDB(db)
return a
}
type aPIKeyDo struct{ gen.DO }
type IAPIKeyDo interface {
gen.SubQuery
Debug() IAPIKeyDo
WithContext(ctx context.Context) IAPIKeyDo
WithResult(fc func(tx gen.Dao)) gen.ResultInfo
ReplaceDB(db *gorm.DB)
ReadDB() IAPIKeyDo
WriteDB() IAPIKeyDo
As(alias string) gen.Dao
Session(config *gorm.Session) IAPIKeyDo
Columns(cols ...field.Expr) gen.Columns
Clauses(conds ...clause.Expression) IAPIKeyDo
Not(conds ...gen.Condition) IAPIKeyDo
Or(conds ...gen.Condition) IAPIKeyDo
Select(conds ...field.Expr) IAPIKeyDo
Where(conds ...gen.Condition) IAPIKeyDo
Order(conds ...field.Expr) IAPIKeyDo
Distinct(cols ...field.Expr) IAPIKeyDo
Omit(cols ...field.Expr) IAPIKeyDo
Join(table schema.Tabler, on ...field.Expr) IAPIKeyDo
LeftJoin(table schema.Tabler, on ...field.Expr) IAPIKeyDo
RightJoin(table schema.Tabler, on ...field.Expr) IAPIKeyDo
Group(cols ...field.Expr) IAPIKeyDo
Having(conds ...gen.Condition) IAPIKeyDo
Limit(limit int) IAPIKeyDo
Offset(offset int) IAPIKeyDo
Count() (count int64, err error)
Scopes(funcs ...func(gen.Dao) gen.Dao) IAPIKeyDo
Unscoped() IAPIKeyDo
Create(values ...*model.APIKey) error
CreateInBatches(values []*model.APIKey, batchSize int) error
Save(values ...*model.APIKey) error
First() (*model.APIKey, error)
Take() (*model.APIKey, error)
Last() (*model.APIKey, error)
Find() ([]*model.APIKey, error)
FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.APIKey, err error)
FindInBatches(result *[]*model.APIKey, batchSize int, fc func(tx gen.Dao, batch int) error) error
Pluck(column field.Expr, dest interface{}) error
Delete(...*model.APIKey) (info gen.ResultInfo, err error)
Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error)
UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error)
Updates(value interface{}) (info gen.ResultInfo, err error)
UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error)
UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error)
UpdateColumns(value interface{}) (info gen.ResultInfo, err error)
UpdateFrom(q gen.SubQuery) gen.Dao
Attrs(attrs ...field.AssignExpr) IAPIKeyDo
Assign(attrs ...field.AssignExpr) IAPIKeyDo
Joins(fields ...field.RelationField) IAPIKeyDo
Preload(fields ...field.RelationField) IAPIKeyDo
FirstOrInit() (*model.APIKey, error)
FirstOrCreate() (*model.APIKey, error)
FindByPage(offset int, limit int) (result []*model.APIKey, count int64, err error)
ScanByPage(result interface{}, offset int, limit int) (count int64, err error)
Scan(result interface{}) (err error)
Returning(value interface{}, columns ...string) IAPIKeyDo
UnderlyingDB() *gorm.DB
schema.Tabler
}
func (a aPIKeyDo) Debug() IAPIKeyDo {
return a.withDO(a.DO.Debug())
}
func (a aPIKeyDo) WithContext(ctx context.Context) IAPIKeyDo {
return a.withDO(a.DO.WithContext(ctx))
}
func (a aPIKeyDo) ReadDB() IAPIKeyDo {
return a.Clauses(dbresolver.Read)
}
func (a aPIKeyDo) WriteDB() IAPIKeyDo {
return a.Clauses(dbresolver.Write)
}
func (a aPIKeyDo) Session(config *gorm.Session) IAPIKeyDo {
return a.withDO(a.DO.Session(config))
}
func (a aPIKeyDo) Clauses(conds ...clause.Expression) IAPIKeyDo {
return a.withDO(a.DO.Clauses(conds...))
}
func (a aPIKeyDo) Returning(value interface{}, columns ...string) IAPIKeyDo {
return a.withDO(a.DO.Returning(value, columns...))
}
func (a aPIKeyDo) Not(conds ...gen.Condition) IAPIKeyDo {
return a.withDO(a.DO.Not(conds...))
}
func (a aPIKeyDo) Or(conds ...gen.Condition) IAPIKeyDo {
return a.withDO(a.DO.Or(conds...))
}
func (a aPIKeyDo) Select(conds ...field.Expr) IAPIKeyDo {
return a.withDO(a.DO.Select(conds...))
}
func (a aPIKeyDo) Where(conds ...gen.Condition) IAPIKeyDo {
return a.withDO(a.DO.Where(conds...))
}
func (a aPIKeyDo) Order(conds ...field.Expr) IAPIKeyDo {
return a.withDO(a.DO.Order(conds...))
}
func (a aPIKeyDo) Distinct(cols ...field.Expr) IAPIKeyDo {
return a.withDO(a.DO.Distinct(cols...))
}
func (a aPIKeyDo) Omit(cols ...field.Expr) IAPIKeyDo {
return a.withDO(a.DO.Omit(cols...))
}
func (a aPIKeyDo) Join(table schema.Tabler, on ...field.Expr) IAPIKeyDo {
return a.withDO(a.DO.Join(table, on...))
}
func (a aPIKeyDo) LeftJoin(table schema.Tabler, on ...field.Expr) IAPIKeyDo {
return a.withDO(a.DO.LeftJoin(table, on...))
}
func (a aPIKeyDo) RightJoin(table schema.Tabler, on ...field.Expr) IAPIKeyDo {
return a.withDO(a.DO.RightJoin(table, on...))
}
func (a aPIKeyDo) Group(cols ...field.Expr) IAPIKeyDo {
return a.withDO(a.DO.Group(cols...))
}
func (a aPIKeyDo) Having(conds ...gen.Condition) IAPIKeyDo {
return a.withDO(a.DO.Having(conds...))
}
func (a aPIKeyDo) Limit(limit int) IAPIKeyDo {
return a.withDO(a.DO.Limit(limit))
}
func (a aPIKeyDo) Offset(offset int) IAPIKeyDo {
return a.withDO(a.DO.Offset(offset))
}
func (a aPIKeyDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IAPIKeyDo {
return a.withDO(a.DO.Scopes(funcs...))
}
func (a aPIKeyDo) Unscoped() IAPIKeyDo {
return a.withDO(a.DO.Unscoped())
}
func (a aPIKeyDo) Create(values ...*model.APIKey) error {
if len(values) == 0 {
return nil
}
return a.DO.Create(values)
}
func (a aPIKeyDo) CreateInBatches(values []*model.APIKey, batchSize int) error {
return a.DO.CreateInBatches(values, batchSize)
}
// Save : !!! underlying implementation is different with GORM
// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values)
func (a aPIKeyDo) Save(values ...*model.APIKey) error {
if len(values) == 0 {
return nil
}
return a.DO.Save(values)
}
func (a aPIKeyDo) First() (*model.APIKey, error) {
if result, err := a.DO.First(); err != nil {
return nil, err
} else {
return result.(*model.APIKey), nil
}
}
func (a aPIKeyDo) Take() (*model.APIKey, error) {
if result, err := a.DO.Take(); err != nil {
return nil, err
} else {
return result.(*model.APIKey), nil
}
}
func (a aPIKeyDo) Last() (*model.APIKey, error) {
if result, err := a.DO.Last(); err != nil {
return nil, err
} else {
return result.(*model.APIKey), nil
}
}
func (a aPIKeyDo) Find() ([]*model.APIKey, error) {
result, err := a.DO.Find()
return result.([]*model.APIKey), err
}
func (a aPIKeyDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.APIKey, err error) {
buf := make([]*model.APIKey, 0, batchSize)
err = a.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error {
defer func() { results = append(results, buf...) }()
return fc(tx, batch)
})
return results, err
}
func (a aPIKeyDo) FindInBatches(result *[]*model.APIKey, batchSize int, fc func(tx gen.Dao, batch int) error) error {
return a.DO.FindInBatches(result, batchSize, fc)
}
func (a aPIKeyDo) Attrs(attrs ...field.AssignExpr) IAPIKeyDo {
return a.withDO(a.DO.Attrs(attrs...))
}
func (a aPIKeyDo) Assign(attrs ...field.AssignExpr) IAPIKeyDo {
return a.withDO(a.DO.Assign(attrs...))
}
func (a aPIKeyDo) Joins(fields ...field.RelationField) IAPIKeyDo {
for _, _f := range fields {
a = *a.withDO(a.DO.Joins(_f))
}
return &a
}
func (a aPIKeyDo) Preload(fields ...field.RelationField) IAPIKeyDo {
for _, _f := range fields {
a = *a.withDO(a.DO.Preload(_f))
}
return &a
}
func (a aPIKeyDo) FirstOrInit() (*model.APIKey, error) {
if result, err := a.DO.FirstOrInit(); err != nil {
return nil, err
} else {
return result.(*model.APIKey), nil
}
}
func (a aPIKeyDo) FirstOrCreate() (*model.APIKey, error) {
if result, err := a.DO.FirstOrCreate(); err != nil {
return nil, err
} else {
return result.(*model.APIKey), nil
}
}
func (a aPIKeyDo) FindByPage(offset int, limit int) (result []*model.APIKey, count int64, err error) {
result, err = a.Offset(offset).Limit(limit).Find()
if err != nil {
return
}
if size := len(result); 0 < limit && 0 < size && size < limit {
count = int64(size + offset)
return
}
count, err = a.Offset(-1).Limit(-1).Count()
return
}
func (a aPIKeyDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) {
count, err = a.Count()
if err != nil {
return
}
err = a.Offset(offset).Limit(limit).Scan(result)
return
}
func (a aPIKeyDo) Scan(result interface{}) (err error) {
return a.DO.Scan(result)
}
func (a aPIKeyDo) Delete(models ...*model.APIKey) (result gen.ResultInfo, err error) {
return a.DO.Delete(models)
}
func (a *aPIKeyDo) withDO(do gen.Dao) *aPIKeyDo {
a.DO = *do.(*gen.DO)
return a
}

View File

@@ -0,0 +1,103 @@
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
package query
import (
"context"
"database/sql"
"gorm.io/gorm"
"gorm.io/gen"
"gorm.io/plugin/dbresolver"
)
var (
Q = new(Query)
APIKey *aPIKey
)
func SetDefault(db *gorm.DB, opts ...gen.DOOption) {
*Q = *Use(db, opts...)
APIKey = &Q.APIKey
}
func Use(db *gorm.DB, opts ...gen.DOOption) *Query {
return &Query{
db: db,
APIKey: newAPIKey(db, opts...),
}
}
type Query struct {
db *gorm.DB
APIKey aPIKey
}
func (q *Query) Available() bool { return q.db != nil }
func (q *Query) clone(db *gorm.DB) *Query {
return &Query{
db: db,
APIKey: q.APIKey.clone(db),
}
}
func (q *Query) ReadDB() *Query {
return q.ReplaceDB(q.db.Clauses(dbresolver.Read))
}
func (q *Query) WriteDB() *Query {
return q.ReplaceDB(q.db.Clauses(dbresolver.Write))
}
func (q *Query) ReplaceDB(db *gorm.DB) *Query {
return &Query{
db: db,
APIKey: q.APIKey.replaceDB(db),
}
}
type queryCtx struct {
APIKey IAPIKeyDo
}
func (q *Query) WithContext(ctx context.Context) *queryCtx {
return &queryCtx{
APIKey: q.APIKey.WithContext(ctx),
}
}
func (q *Query) Transaction(fc func(tx *Query) error, opts ...*sql.TxOptions) error {
return q.db.Transaction(func(tx *gorm.DB) error { return fc(q.clone(tx)) }, opts...)
}
func (q *Query) Begin(opts ...*sql.TxOptions) *QueryTx {
tx := q.db.Begin(opts...)
return &QueryTx{Query: q.clone(tx), Error: tx.Error}
}
type QueryTx struct {
*Query
Error error
}
func (q *QueryTx) Commit() error {
return q.db.Commit().Error
}
func (q *QueryTx) Rollback() error {
return q.db.Rollback().Error
}
func (q *QueryTx) SavePoint(name string) error {
return q.db.SavePoint(name).Error
}
func (q *QueryTx) RollbackTo(name string) error {
return q.db.RollbackTo(name).Error
}