Skip to content

Commit

Permalink
feat: Optimize upgrade code (#748)
Browse files Browse the repository at this point in the history
* feat: Optimize upgrade code

* optimize enum method, TODO: update TestColumnExtraAttributes

* add enum tests

* add ModifyUnsigned, TODO: add test for ModifyUnsigned

* fix test

* fix test

* fix test

* optimize

* add go-viper/mapstructure

* fix #531: An extra log will be printed when using a custom log driver

* sort import

* remove \t
  • Loading branch information
hwbrzzl authored Dec 13, 2024
1 parent 69941b3 commit fc3a6d7
Show file tree
Hide file tree
Showing 45 changed files with 754 additions and 207 deletions.
2 changes: 1 addition & 1 deletion auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func (a *Auth) User(user any) error {
return nil
}

func (a *Auth) Id() (string, error) {
func (a *Auth) ID() (string, error) {
auth, ok := a.ctx.Value(ctxKey).(Guards)
if !ok || auth[a.guard] == nil {
return "", errors.AuthParseTokenFirst
Expand Down
8 changes: 4 additions & 4 deletions auth/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ func (s *AuthTestSuite) TestUser_NoParse() {

func (s *AuthTestSuite) TestID_NoParse() {
// Attempt to get the ID without parsing the token first
id, _ := s.auth.Id()
id, _ := s.auth.ID()
s.Empty(id)
}

Expand All @@ -366,7 +366,7 @@ func (s *AuthTestSuite) TestID_Success() {
s.NotNil(payload)

// Now, call the ID method and expect it to return the correct ID
id, _ := s.auth.Id()
id, _ := s.auth.ID()
s.Equal("1", id)
}

Expand All @@ -388,7 +388,7 @@ func (s *AuthTestSuite) TestID_TokenExpired() {
s.ErrorIs(err, errors.AuthTokenExpired)

// Now, call the ID method and expect it to return an empty value
id, _ := s.auth.Id()
id, _ := s.auth.ID()
s.Empty(id)

carbon.UnsetTestNow()
Expand All @@ -404,7 +404,7 @@ func (s *AuthTestSuite) TestID_TokenInvalid() {
_, err := s.auth.Parse(token)
s.ErrorIs(err, errors.AuthInvalidToken)

id, _ := s.auth.Id()
id, _ := s.auth.ID()
s.Empty(id)
}

Expand Down
16 changes: 16 additions & 0 deletions auth/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package auth

import "github.com/goravel/framework/errors"

// These errors may be used by user's project, so we can't remove them.
var (
ErrorRefreshTimeExceeded = errors.AuthRefreshTimeExceeded
ErrorTokenExpired = errors.AuthTokenExpired
ErrorNoPrimaryKeyField = errors.AuthNoPrimaryKeyField
ErrorEmptySecret = errors.AuthEmptySecret
ErrorTokenDisabled = errors.AuthTokenDisabled
ErrorParseTokenFirst = errors.AuthParseTokenFirst
ErrorInvalidClaims = errors.AuthInvalidClaims
ErrorInvalidToken = errors.AuthInvalidToken
ErrorInvalidKey = errors.AuthInvalidKey
)
4 changes: 2 additions & 2 deletions contracts/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ type Auth interface {
Parse(token string) (*Payload, error)
// User returns the current authenticated user.
User(user any) error
// Id returns the current user id.
Id() (string, error)
// ID returns the current user id.
ID() (string, error)
// Login logs a user into the application.
Login(user any) (token string, err error)
// LoginUsingID logs the given user ID into the application.
Expand Down
4 changes: 3 additions & 1 deletion contracts/database/schema/blueprint.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,10 @@ type Blueprint interface {
DropTimestampsTz()
// DropUnique Indicate that the given unique key should be dropped.
DropUnique(column ...string)
// DropUniqueByName Indicate that the given unique key should be dropped.
DropUniqueByName(name string)
// Enum Create a new enum column on the table.
Enum(column string, array []string) ColumnDefinition
Enum(column string, array []any) ColumnDefinition
// Float Create a new float column on the table.
Float(column string, precision ...int) ColumnDefinition
// Foreign Specify a foreign key for the table.
Expand Down
4 changes: 3 additions & 1 deletion contracts/database/schema/column.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ type ColumnDefinition interface {
// Default set the default value
Default(def any) ColumnDefinition
// GetAllowed returns the allowed value
GetAllowed() []string
GetAllowed() []any
// GetAutoIncrement returns the autoIncrement value
GetAutoIncrement() bool
// GetComment returns the comment value
Expand All @@ -31,6 +31,8 @@ type ColumnDefinition interface {
GetTotal() int
// GetType returns the type value
GetType() string
// GetUnsigned returns the unsigned value
GetUnsigned() bool
// GetUseCurrent returns the useCurrent value
GetUseCurrent() bool
// GetUseCurrentOnUpdate returns the useCurrentOnUpdate value
Expand Down
24 changes: 14 additions & 10 deletions contracts/log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ const (
DebugLevel
)

type Data map[string]any

type Log interface {
// WithContext adds a context to the logger.
WithContext(ctx context.Context) Writer
Expand Down Expand Up @@ -96,28 +98,30 @@ type Hook interface {
}

type Entry interface {
// Code returns the associated code.
Code() string
// Context returns the context of the entry.
Context() context.Context
// Data returns the data of the entry.
Data() Data
// Level returns the level of the entry.
Level() Level
// Time returns the timestamp of the entry.
Time() time.Time
// Message returns the message of the entry.
Message() string
// Code returns the associated code.
Code() string
// With returns additional context data.
With() map[string]any
// User returns the user information.
User() any
// Tags returns the list of tags.
Tags() []string
// Owner returns the log's owner.
Owner() any
// Request returns the request data.
Request() map[string]any
// Response returns the response data.
Response() map[string]any
// Tags returns the list of tags.
Tags() []string
// Time returns the timestamp of the entry.
Time() time.Time
// Trace returns the stack trace or trace data.
Trace() map[string]any
// User returns the user information.
User() any
// With returns additional context data.
With() map[string]any
}
2 changes: 2 additions & 0 deletions contracts/testing/testing.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ type Docker interface {

type Database interface {
DatabaseDriver
// Migrate runs the database migrations.
Migrate() error
// Seed runs the database seeds.
Seed(seeders ...seeder.Seeder) error
}
Expand Down
2 changes: 1 addition & 1 deletion database/factory/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package factory
import (
"reflect"

"github.com/mitchellh/mapstructure"
"github.com/go-viper/mapstructure/v2"

"github.com/goravel/framework/contracts/database/factory"
ormcontract "github.com/goravel/framework/contracts/database/orm"
Expand Down
2 changes: 1 addition & 1 deletion database/gorm/cursor.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"strings"
"time"

"github.com/mitchellh/mapstructure"
"github.com/go-viper/mapstructure/v2"
"gorm.io/gorm"

"github.com/goravel/framework/support/carbon"
Expand Down
12 changes: 8 additions & 4 deletions database/migration/default_creator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,14 @@ func (r *M202410131203CreateUsersTable) Signature() string {
// Up Run the migrations.
func (r *M202410131203CreateUsersTable) Up() error {
return facades.Schema().Create("users", func(table schema.Blueprint) {
table.BigIncrements("id")
table.Timestamps()
})
if !facades.Schema().HasTable("users") {
return facades.Schema().Create("users", func(table schema.Blueprint) {
table.ID()
table.Timestamps()
})
}
return nil
}
// Down Reverse the migrations.
Expand Down
19 changes: 10 additions & 9 deletions database/migration/default_migrator.go
Original file line number Diff line number Diff line change
Expand Up @@ -309,17 +309,18 @@ func (r *DefaultMigrator) runUp(migration contractsschema.Migration, batch int)
r.schema.SetConnection(defaultConnection)
}()

return r.schema.Orm().Transaction(func(tx orm.Query) error {
if err := r.schema.Orm().Transaction(func(tx orm.Query) error {
r.schema.Orm().SetQuery(tx)

if err := migration.Up(); err != nil {
return err
}
return migration.Up()
}); err != nil {
return err
}

// repository.Log should be called in the default connection.
r.schema.Orm().SetQuery(defaultQuery)
r.schema.SetConnection(defaultConnection)
// repository.Log should be called in the default connection.
// The code below can't be set in the transaction, because the connection will conflict.
r.schema.Orm().SetQuery(defaultQuery)
r.schema.SetConnection(defaultConnection)

return r.repository.Log(migration.Signature(), batch)
})
return r.repository.Log(migration.Signature(), batch)
}
12 changes: 8 additions & 4 deletions database/migration/stubs.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,14 @@ func (r *DummyMigration) Signature() string {
// Up Run the migrations.
func (r *DummyMigration) Up() error {
return facades.Schema().Create("DummyTable", func(table schema.Blueprint) {
table.BigIncrements("id")
table.Timestamps()
})
if !facades.Schema().HasTable("DummyTable") {
return facades.Schema().Create("DummyTable", func(table schema.Blueprint) {
table.ID()
table.Timestamps()
})
}
return nil
}
// Down Reverse the migrations.
Expand Down
8 changes: 7 additions & 1 deletion database/schema/blueprint.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,13 @@ func (r *Blueprint) DropUnique(column ...string) {
})
}

func (r *Blueprint) Enum(column string, allowed []string) schema.ColumnDefinition {
func (r *Blueprint) DropUniqueByName(name string) {
r.indexCommand(constants.CommandDropUnique, nil, schema.IndexConfig{
Name: name,
})
}

func (r *Blueprint) Enum(column string, allowed []any) schema.ColumnDefinition {
columnImpl := r.createAndAddColumn("enum", column)
columnImpl.allowed = allowed

Expand Down
48 changes: 28 additions & 20 deletions database/schema/column.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
)

type ColumnDefinition struct {
allowed []string
allowed []any
autoIncrement *bool
comment *string
def any
Expand Down Expand Up @@ -41,44 +41,44 @@ func (r *ColumnDefinition) Default(def any) schema.ColumnDefinition {
return r
}

func (r *ColumnDefinition) GetAllowed() []string {
func (r *ColumnDefinition) GetAllowed() []any {
return r.allowed
}

func (r *ColumnDefinition) GetAutoIncrement() (autoIncrement bool) {
func (r *ColumnDefinition) GetAutoIncrement() bool {
if r.autoIncrement != nil {
return *r.autoIncrement
}

return
return false
}

func (r *ColumnDefinition) GetComment() (comment string) {
func (r *ColumnDefinition) GetComment() string {
if r.comment != nil {
return *r.comment
}

return
return ""
}

func (r *ColumnDefinition) GetDefault() any {
return r.def
}

func (r *ColumnDefinition) GetName() (name string) {
func (r *ColumnDefinition) GetName() string {
if r.name != nil {
return *r.name
}

return
return ""
}

func (r *ColumnDefinition) GetLength() (length int) {
func (r *ColumnDefinition) GetLength() int {
if r.length != nil {
return *r.length
}

return
return 0
}

func (r *ColumnDefinition) GetNullable() bool {
Expand All @@ -93,52 +93,60 @@ func (r *ColumnDefinition) GetOnUpdate() any {
return r.onUpdate
}

func (r *ColumnDefinition) GetPlaces() (places int) {
func (r *ColumnDefinition) GetPlaces() int {
if r.places != nil {
return *r.places
}

return 2
}

func (r *ColumnDefinition) GetPrecision() (precision int) {
func (r *ColumnDefinition) GetPrecision() int {
if r.precision != nil {
return *r.precision
}

return
return 0
}

func (r *ColumnDefinition) GetTotal() (total int) {
func (r *ColumnDefinition) GetTotal() int {
if r.total != nil {
return *r.total
}

return 8
}

func (r *ColumnDefinition) GetType() (ttype string) {
func (r *ColumnDefinition) GetType() string {
if r.ttype != nil {
return *r.ttype
}

return
return ""
}

func (r *ColumnDefinition) GetUnsigned() bool {
if r.unsigned != nil {
return *r.unsigned
}

return false
}

func (r *ColumnDefinition) GetUseCurrent() (useCurrent bool) {
func (r *ColumnDefinition) GetUseCurrent() bool {
if r.useCurrent != nil {
return *r.useCurrent
}

return
return false
}

func (r *ColumnDefinition) GetUseCurrentOnUpdate() (useCurrentOnUpdate bool) {
func (r *ColumnDefinition) GetUseCurrentOnUpdate() bool {
if r.useCurrentOnUpdate != nil {
return *r.useCurrentOnUpdate
}

return
return false
}

func (r *ColumnDefinition) IsSetComment() bool {
Expand Down
Loading

0 comments on commit fc3a6d7

Please sign in to comment.