From 88c374a380b0ff39150cbf7b6dc80f256f242a8c Mon Sep 17 00:00:00 2001 From: Wenbo Han Date: Sun, 9 Feb 2025 10:08:52 +0800 Subject: [PATCH 1/7] feat: Move bindings to config (#868) --- auth/service_provider.go | 18 ++++----- cache/service_provider.go | 13 +++--- config/service_provider.go | 9 ++--- console/service_provider.go | 13 +++--- contracts/binding.go | 28 +++++++++++++ crypt/service_provider.go | 9 ++--- database/orm/orm.go | 5 +-- database/schema/schema.go | 2 - database/seeder/seeder.go | 2 - database/service_provider.go | 7 ++-- event/service_provider.go | 13 +++--- filesystem/service_provider.go | 9 ++--- foundation/application_test.go | 52 ++++++++++++------------ foundation/container.go | 71 ++++++++++++--------------------- grpc/service_provider.go | 9 ++--- hash/service_provider.go | 9 ++--- http/service_provider.go | 18 ++++----- log/service_provider.go | 9 ++--- mail/service_provider.go | 15 +++---- queue/service_provider.go | 13 +++--- route/service_provider.go | 9 ++--- schedule/service_provider.go | 9 ++--- session/service_provider.go | 9 ++--- testing/service_provider.go | 9 ++--- translation/service_provider.go | 7 ++-- validation/service_provider.go | 9 ++--- 26 files changed, 179 insertions(+), 197 deletions(-) create mode 100644 contracts/binding.go diff --git a/auth/service_provider.go b/auth/service_provider.go index f3696b17e..95a793f0f 100644 --- a/auth/service_provider.go +++ b/auth/service_provider.go @@ -5,22 +5,18 @@ import ( "github.com/goravel/framework/auth/access" "github.com/goravel/framework/auth/console" + "github.com/goravel/framework/contracts" contractconsole "github.com/goravel/framework/contracts/console" "github.com/goravel/framework/contracts/foundation" "github.com/goravel/framework/contracts/http" "github.com/goravel/framework/errors" ) -const ( - BindingAuth = "goravel.auth" - BindingGate = "goravel.gate" -) - type ServiceProvider struct { } -func (database *ServiceProvider) Register(app foundation.Application) { - app.BindWith(BindingAuth, func(app foundation.Application, parameters map[string]any) (any, error) { +func (r *ServiceProvider) Register(app foundation.Application) { + app.BindWith(contracts.BindingAuth, func(app foundation.Application, parameters map[string]any) (any, error) { config := app.MakeConfig() if config == nil { return nil, errors.ConfigFacadeNotSet.SetModule(errors.ModuleAuth) @@ -44,16 +40,16 @@ func (database *ServiceProvider) Register(app foundation.Application) { return NewAuth(config.GetString("auth.defaults.guard"), cacheFacade, config, ctx, ormFacade), nil }) - app.Singleton(BindingGate, func(app foundation.Application) (any, error) { + app.Singleton(contracts.BindingGate, func(app foundation.Application) (any, error) { return access.NewGate(context.Background()), nil }) } -func (database *ServiceProvider) Boot(app foundation.Application) { - database.registerCommands(app) +func (r *ServiceProvider) Boot(app foundation.Application) { + r.registerCommands(app) } -func (database *ServiceProvider) registerCommands(app foundation.Application) { +func (r *ServiceProvider) registerCommands(app foundation.Application) { app.Commands([]contractconsole.Command{ console.NewJwtSecretCommand(app.MakeConfig()), console.NewPolicyMakeCommand(), diff --git a/cache/service_provider.go b/cache/service_provider.go index 7914fba4b..e1f797364 100644 --- a/cache/service_provider.go +++ b/cache/service_provider.go @@ -2,18 +2,17 @@ package cache import ( "github.com/goravel/framework/cache/console" + "github.com/goravel/framework/contracts" contractsconsole "github.com/goravel/framework/contracts/console" "github.com/goravel/framework/contracts/foundation" "github.com/goravel/framework/errors" ) -const Binding = "goravel.cache" - type ServiceProvider struct { } -func (database *ServiceProvider) Register(app foundation.Application) { - app.Singleton(Binding, func(app foundation.Application) (any, error) { +func (r *ServiceProvider) Register(app foundation.Application) { + app.Singleton(contracts.BindingCache, func(app foundation.Application) (any, error) { config := app.MakeConfig() if config == nil { return nil, errors.ConfigFacadeNotSet.SetModule(errors.ModuleCache) @@ -30,11 +29,11 @@ func (database *ServiceProvider) Register(app foundation.Application) { }) } -func (database *ServiceProvider) Boot(app foundation.Application) { - database.registerCommands(app) +func (r *ServiceProvider) Boot(app foundation.Application) { + r.registerCommands(app) } -func (database *ServiceProvider) registerCommands(app foundation.Application) { +func (r *ServiceProvider) registerCommands(app foundation.Application) { app.Commands([]contractsconsole.Command{ console.NewClearCommand(app.MakeCache()), }) diff --git a/config/service_provider.go b/config/service_provider.go index 12416d990..df72adcbe 100644 --- a/config/service_provider.go +++ b/config/service_provider.go @@ -1,21 +1,20 @@ package config import ( + "github.com/goravel/framework/contracts" "github.com/goravel/framework/contracts/foundation" "github.com/goravel/framework/support" ) -const Binding = "goravel.config" - type ServiceProvider struct { } -func (config *ServiceProvider) Register(app foundation.Application) { - app.Singleton(Binding, func(app foundation.Application) (any, error) { +func (r *ServiceProvider) Register(app foundation.Application) { + app.Singleton(contracts.BindingConfig, func(app foundation.Application) (any, error) { return NewApplication(support.EnvPath), nil }) } -func (config *ServiceProvider) Boot(app foundation.Application) { +func (r *ServiceProvider) Boot(app foundation.Application) { } diff --git a/console/service_provider.go b/console/service_provider.go index 67674254b..b1b33305c 100644 --- a/console/service_provider.go +++ b/console/service_provider.go @@ -2,18 +2,17 @@ package console import ( "github.com/goravel/framework/console/console" + "github.com/goravel/framework/contracts" consolecontract "github.com/goravel/framework/contracts/console" "github.com/goravel/framework/contracts/foundation" "github.com/goravel/framework/support/color" ) -const Binding = "goravel.console" - type ServiceProvider struct { } -func (receiver *ServiceProvider) Register(app foundation.Application) { - app.Singleton(Binding, func(app foundation.Application) (any, error) { +func (r *ServiceProvider) Register(app foundation.Application) { + app.Singleton(contracts.BindingConsole, func(app foundation.Application) (any, error) { name := "artisan" usage := "Goravel Framework" usageText := "artisan [global options] command [options] [arguments...]" @@ -21,11 +20,11 @@ func (receiver *ServiceProvider) Register(app foundation.Application) { }) } -func (receiver *ServiceProvider) Boot(app foundation.Application) { - receiver.registerCommands(app) +func (r *ServiceProvider) Boot(app foundation.Application) { + r.registerCommands(app) } -func (receiver *ServiceProvider) registerCommands(app foundation.Application) { +func (r *ServiceProvider) registerCommands(app foundation.Application) { artisanFacade := app.MakeArtisan() if artisanFacade == nil { color.Warningln("Artisan Facade is not initialized. Skipping command registration.") diff --git a/contracts/binding.go b/contracts/binding.go new file mode 100644 index 000000000..05b6b5379 --- /dev/null +++ b/contracts/binding.go @@ -0,0 +1,28 @@ +package contracts + +const ( + BindingAuth = "goravel.auth" + BindingCache = "goravel.cache" + BindingConfig = "goravel.config" + BindingConsole = "goravel.console" + BindingCrypt = "goravel.crypt" + BindingEvent = "goravel.event" + BindingFilesystem = "goravel.filesystem" + BindingGate = "goravel.gate" + BindingGrpc = "goravel.grpc" + BindingHash = "goravel.hash" + BindingLog = "goravel.log" + BindingMail = "goravel.mail" + BindingOrm = "goravel.orm" + BindingQueue = "goravel.queue" + BindingRateLimiter = "goravel.rate_limiter" + BindingRoute = "goravel.route" + BindingSchedule = "goravel.schedule" + BindingSchema = "goravel.schema" + BindingSeeder = "goravel.seeder" + BindingSession = "goravel.session" + BindingTesting = "goravel.testing" + BindingTranslation = "goravel.translation" + BindingValidation = "goravel.validation" + BindingView = "goravel.view" +) diff --git a/crypt/service_provider.go b/crypt/service_provider.go index b90811278..44aea1665 100644 --- a/crypt/service_provider.go +++ b/crypt/service_provider.go @@ -1,17 +1,16 @@ package crypt import ( + "github.com/goravel/framework/contracts" "github.com/goravel/framework/contracts/foundation" "github.com/goravel/framework/errors" ) -const Binding = "goravel.crypt" - type ServiceProvider struct { } -func (crypt *ServiceProvider) Register(app foundation.Application) { - app.Singleton(Binding, func(app foundation.Application) (any, error) { +func (r *ServiceProvider) Register(app foundation.Application) { + app.Singleton(contracts.BindingCrypt, func(app foundation.Application) (any, error) { config := app.MakeConfig() if config == nil { return nil, errors.ConfigFacadeNotSet.SetModule(errors.ModuleCrypt) @@ -26,6 +25,6 @@ func (crypt *ServiceProvider) Register(app foundation.Application) { }) } -func (crypt *ServiceProvider) Boot(app foundation.Application) { +func (r *ServiceProvider) Boot(app foundation.Application) { } diff --git a/database/orm/orm.go b/database/orm/orm.go index 9b145abe0..af3c275cc 100644 --- a/database/orm/orm.go +++ b/database/orm/orm.go @@ -5,6 +5,7 @@ import ( "database/sql" "sync" + "github.com/goravel/framework/contracts" "github.com/goravel/framework/contracts/config" "github.com/goravel/framework/contracts/database" contractsorm "github.com/goravel/framework/contracts/database/orm" @@ -14,8 +15,6 @@ import ( "github.com/goravel/framework/database/gorm" ) -const BindingOrm = "goravel.orm" - type Orm struct { ctx context.Context config config.Config @@ -135,7 +134,7 @@ func (r *Orm) SetQuery(query contractsorm.Query) { } func (r *Orm) Refresh() { - r.refresh(BindingOrm) + r.refresh(contracts.BindingOrm) } func (r *Orm) Transaction(txFunc func(tx contractsorm.Query) error) error { diff --git a/database/schema/schema.go b/database/schema/schema.go index 7a9a858c0..ce7254197 100644 --- a/database/schema/schema.go +++ b/database/schema/schema.go @@ -12,8 +12,6 @@ import ( "github.com/goravel/framework/errors" ) -const BindingSchema = "goravel.schema" - var _ contractsschema.Schema = (*Schema)(nil) type Schema struct { diff --git a/database/seeder/seeder.go b/database/seeder/seeder.go index e484b188d..f257a604f 100644 --- a/database/seeder/seeder.go +++ b/database/seeder/seeder.go @@ -5,8 +5,6 @@ import ( "github.com/goravel/framework/support/color" ) -const BindingSeeder = "goravel.seeder" - var _ seeder.Facade = (*SeederFacade)(nil) type SeederFacade struct { diff --git a/database/service_provider.go b/database/service_provider.go index 77852d33f..1ac2f66a2 100644 --- a/database/service_provider.go +++ b/database/service_provider.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/goravel/framework/contracts" contractsconsole "github.com/goravel/framework/contracts/console" "github.com/goravel/framework/contracts/database/driver" "github.com/goravel/framework/contracts/foundation" @@ -21,7 +22,7 @@ type ServiceProvider struct { } func (r *ServiceProvider) Register(app foundation.Application) { - app.Singleton(databaseorm.BindingOrm, func(app foundation.Application) (any, error) { + app.Singleton(contracts.BindingOrm, func(app foundation.Application) (any, error) { ctx := context.Background() config := app.MakeConfig() if config == nil { @@ -47,7 +48,7 @@ func (r *ServiceProvider) Register(app foundation.Application) { return orm, nil }) - app.Singleton(databaseschema.BindingSchema, func(app foundation.Application) (any, error) { + app.Singleton(contracts.BindingSchema, func(app foundation.Application) (any, error) { config := app.MakeConfig() if config == nil { return nil, errors.ConfigFacadeNotSet.SetModule(errors.ModuleSchema) @@ -76,7 +77,7 @@ func (r *ServiceProvider) Register(app foundation.Application) { return databaseschema.NewSchema(config, log, orm, driver, nil), nil }) - app.Singleton(databaseseeder.BindingSeeder, func(app foundation.Application) (any, error) { + app.Singleton(contracts.BindingSeeder, func(app foundation.Application) (any, error) { return databaseseeder.NewSeederFacade(), nil }) } diff --git a/event/service_provider.go b/event/service_provider.go index 444dff206..8b0288fd0 100644 --- a/event/service_provider.go +++ b/event/service_provider.go @@ -1,19 +1,18 @@ package event import ( + "github.com/goravel/framework/contracts" "github.com/goravel/framework/contracts/console" "github.com/goravel/framework/contracts/foundation" "github.com/goravel/framework/errors" eventConsole "github.com/goravel/framework/event/console" ) -const Binding = "goravel.event" - type ServiceProvider struct { } -func (receiver *ServiceProvider) Register(app foundation.Application) { - app.Singleton(Binding, func(app foundation.Application) (any, error) { +func (r *ServiceProvider) Register(app foundation.Application) { + app.Singleton(contracts.BindingEvent, func(app foundation.Application) (any, error) { queueFacade := app.MakeQueue() if queueFacade == nil { return nil, errors.QueueFacadeNotSet.SetModule(errors.ModuleEvent) @@ -23,11 +22,11 @@ func (receiver *ServiceProvider) Register(app foundation.Application) { }) } -func (receiver *ServiceProvider) Boot(app foundation.Application) { - receiver.registerCommands(app) +func (r *ServiceProvider) Boot(app foundation.Application) { + r.registerCommands(app) } -func (receiver *ServiceProvider) registerCommands(app foundation.Application) { +func (r *ServiceProvider) registerCommands(app foundation.Application) { app.Commands([]console.Command{ &eventConsole.EventMakeCommand{}, &eventConsole.ListenerMakeCommand{}, diff --git a/filesystem/service_provider.go b/filesystem/service_provider.go index 5363b2914..b6e9c140e 100644 --- a/filesystem/service_provider.go +++ b/filesystem/service_provider.go @@ -1,14 +1,13 @@ package filesystem import ( + "github.com/goravel/framework/contracts" configcontract "github.com/goravel/framework/contracts/config" filesystemcontract "github.com/goravel/framework/contracts/filesystem" "github.com/goravel/framework/contracts/foundation" "github.com/goravel/framework/errors" ) -const Binding = "goravel.filesystem" - var ( ConfigFacade configcontract.Config StorageFacade filesystemcontract.Storage @@ -17,8 +16,8 @@ var ( type ServiceProvider struct { } -func (database *ServiceProvider) Register(app foundation.Application) { - app.Singleton(Binding, func(app foundation.Application) (any, error) { +func (r *ServiceProvider) Register(app foundation.Application) { + app.Singleton(contracts.BindingFilesystem, func(app foundation.Application) (any, error) { config := app.MakeConfig() if config == nil { return nil, errors.ConfigFacadeNotSet.SetModule(errors.ModuleFilesystem) @@ -28,7 +27,7 @@ func (database *ServiceProvider) Register(app foundation.Application) { }) } -func (database *ServiceProvider) Boot(app foundation.Application) { +func (r *ServiceProvider) Boot(app foundation.Application) { ConfigFacade = app.MakeConfig() StorageFacade = app.MakeStorage() } diff --git a/foundation/application_test.go b/foundation/application_test.go index 552a58aff..158c1c5b2 100644 --- a/foundation/application_test.go +++ b/foundation/application_test.go @@ -12,9 +12,9 @@ import ( "github.com/goravel/framework/cache" frameworkconfig "github.com/goravel/framework/config" "github.com/goravel/framework/console" + "github.com/goravel/framework/contracts" "github.com/goravel/framework/contracts/foundation" "github.com/goravel/framework/crypt" - "github.com/goravel/framework/database/orm" "github.com/goravel/framework/event" "github.com/goravel/framework/filesystem" "github.com/goravel/framework/foundation/json" @@ -84,7 +84,7 @@ func (s *ApplicationTestSuite) TestLangPath() { mockConfig := mocksconfig.NewConfig(s.T()) mockConfig.EXPECT().GetString("app.lang_path", "lang").Return("test").Once() - s.app.Singleton(frameworkconfig.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingConfig, func(app foundation.Application) (any, error) { return mockConfig, nil }) @@ -150,13 +150,13 @@ func (s *ApplicationTestSuite) TestMakeAuth() { mockConfig := mocksconfig.NewConfig(s.T()) mockConfig.EXPECT().GetString("auth.defaults.guard").Return("user").Once() - s.app.Singleton(frameworkconfig.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingConfig, func(app foundation.Application) (any, error) { return mockConfig, nil }) - s.app.Singleton(cache.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingCache, func(app foundation.Application) (any, error) { return &mockscache.Cache{}, nil }) - s.app.Singleton(orm.BindingOrm, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingOrm, func(app foundation.Application) (any, error) { return &mocksorm.Orm{}, nil }) @@ -172,10 +172,10 @@ func (s *ApplicationTestSuite) TestMakeCache() { mockConfig.EXPECT().GetString("cache.stores.memory.driver").Return("memory").Once() mockConfig.EXPECT().GetString("cache.prefix").Return("goravel").Once() - s.app.Singleton(frameworkconfig.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingConfig, func(app foundation.Application) (any, error) { return mockConfig, nil }) - s.app.Singleton(frameworklog.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingLog, func(app foundation.Application) (any, error) { return &mockslog.Log{}, nil }) @@ -196,7 +196,7 @@ func (s *ApplicationTestSuite) TestMakeCrypt() { mockConfig := mocksconfig.NewConfig(s.T()) mockConfig.EXPECT().GetString("app.key").Return("12345678901234567890123456789012").Once() - s.app.Singleton(frameworkconfig.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingConfig, func(app foundation.Application) (any, error) { return mockConfig, nil }) s.app.SetJson(json.NewJson()) @@ -208,7 +208,7 @@ func (s *ApplicationTestSuite) TestMakeCrypt() { } func (s *ApplicationTestSuite) TestMakeEvent() { - s.app.Singleton(queue.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingQueue, func(app foundation.Application) (any, error) { return &mocksqueue.Queue{}, nil }) @@ -226,7 +226,7 @@ func (s *ApplicationTestSuite) TestMakeGate() { } func (s *ApplicationTestSuite) TestMakeGrpc() { - s.app.Singleton(frameworkconfig.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingConfig, func(app foundation.Application) (any, error) { return &mocksconfig.Config{}, nil }) @@ -243,7 +243,7 @@ func (s *ApplicationTestSuite) TestMakeHash() { mockConfig.EXPECT().GetInt("hashing.argon2id.memory", 65536).Return(65536).Once() mockConfig.EXPECT().GetInt("hashing.argon2id.threads", 1).Return(1).Once() - s.app.Singleton(frameworkconfig.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingConfig, func(app foundation.Application) (any, error) { return mockConfig, nil }) @@ -259,10 +259,10 @@ func (s *ApplicationTestSuite) TestMakeLang() { mockConfig.EXPECT().GetString("app.fallback_locale").Return("en").Once() mockConfig.EXPECT().GetString("app.lang_path", "lang").Return("lang").Once() - s.app.Singleton(frameworkconfig.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingConfig, func(app foundation.Application) (any, error) { return mockConfig, nil }) - s.app.Singleton(frameworklog.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingLog, func(app foundation.Application) (any, error) { return &mockslog.Log{}, nil }) @@ -275,7 +275,7 @@ func (s *ApplicationTestSuite) TestMakeLang() { func (s *ApplicationTestSuite) TestMakeLog() { mockConfig := mocksconfig.NewConfig(s.T()) - s.app.Singleton(frameworkconfig.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingConfig, func(app foundation.Application) (any, error) { return mockConfig, nil }) @@ -290,10 +290,10 @@ func (s *ApplicationTestSuite) TestMakeLog() { } func (s *ApplicationTestSuite) TestMakeMail() { - s.app.Singleton(frameworkconfig.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingConfig, func(app foundation.Application) (any, error) { return &mocksconfig.Config{}, nil }) - s.app.Singleton(queue.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingQueue, func(app foundation.Application) (any, error) { return &mocksqueue.Queue{}, nil }) @@ -304,11 +304,11 @@ func (s *ApplicationTestSuite) TestMakeMail() { } func (s *ApplicationTestSuite) TestMakeQueue() { - s.app.Singleton(frameworkconfig.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingConfig, func(app foundation.Application) (any, error) { return &mocksconfig.Config{}, nil }) - s.app.Singleton(frameworklog.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingLog, func(app foundation.Application) (any, error) { return &mockslog.Log{}, nil }) @@ -328,11 +328,11 @@ func (s *ApplicationTestSuite) TestMakeRateLimiter() { func (s *ApplicationTestSuite) TestMakeRoute() { mockConfig := mocksconfig.NewConfig(s.T()) - s.app.Singleton(frameworkconfig.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingConfig, func(app foundation.Application) (any, error) { return mockConfig, nil }) - s.app.Singleton("goravel.route", func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingRoute, func(app foundation.Application) (any, error) { return &mocksroute.Route{}, nil }) @@ -343,16 +343,16 @@ func (s *ApplicationTestSuite) TestMakeSchedule() { mockConfig := mocksconfig.NewConfig(s.T()) mockConfig.EXPECT().GetBool("app.debug").Return(false).Once() - s.app.Singleton(frameworkconfig.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingConfig, func(app foundation.Application) (any, error) { return mockConfig, nil }) - s.app.Singleton(console.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingConsole, func(app foundation.Application) (any, error) { return &mocksconsole.Artisan{}, nil }) - s.app.Singleton(frameworklog.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingLog, func(app foundation.Application) (any, error) { return &mockslog.Log{}, nil }) - s.app.Singleton(cache.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingCache, func(app foundation.Application) (any, error) { return &mockscache.Cache{}, nil }) @@ -368,7 +368,7 @@ func (s *ApplicationTestSuite) TestMakeSession() { mockConfig.EXPECT().GetInt("session.gc_interval", 30).Return(30).Once() mockConfig.EXPECT().GetString("session.files").Return("storage/framework/sessions").Once() - s.app.Singleton(frameworkconfig.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingConfig, func(app foundation.Application) (any, error) { return mockConfig, nil }) s.app.SetJson(json.NewJson()) @@ -388,7 +388,7 @@ func (s *ApplicationTestSuite) TestMakeStorage() { mockConfig.EXPECT().GetString("filesystems.disks.local.root").Return("").Once() mockConfig.EXPECT().GetString("filesystems.disks.local.url").Return("").Once() - s.app.Singleton(frameworkconfig.Binding, func(app foundation.Application) (any, error) { + s.app.Singleton(contracts.BindingConfig, func(app foundation.Application) (any, error) { return mockConfig, nil }) diff --git a/foundation/container.go b/foundation/container.go index cedf52b3b..1485ce902 100644 --- a/foundation/container.go +++ b/foundation/container.go @@ -5,10 +5,7 @@ import ( "fmt" "sync" - "github.com/goravel/framework/auth" - "github.com/goravel/framework/cache" - "github.com/goravel/framework/config" - "github.com/goravel/framework/console" + "github.com/goravel/framework/contracts" contractsauth "github.com/goravel/framework/contracts/auth" contractsaccess "github.com/goravel/framework/contracts/auth/access" contractscache "github.com/goravel/framework/contracts/cache" @@ -33,25 +30,7 @@ import ( contractstesting "github.com/goravel/framework/contracts/testing" contractstranslation "github.com/goravel/framework/contracts/translation" contractsvalidation "github.com/goravel/framework/contracts/validation" - "github.com/goravel/framework/crypt" - "github.com/goravel/framework/database/orm" - "github.com/goravel/framework/database/schema" - "github.com/goravel/framework/database/seeder" - "github.com/goravel/framework/event" - "github.com/goravel/framework/filesystem" - "github.com/goravel/framework/grpc" - "github.com/goravel/framework/hash" - "github.com/goravel/framework/http" - frameworklog "github.com/goravel/framework/log" - "github.com/goravel/framework/mail" - "github.com/goravel/framework/queue" - "github.com/goravel/framework/route" - "github.com/goravel/framework/schedule" - "github.com/goravel/framework/session" "github.com/goravel/framework/support/color" - "github.com/goravel/framework/testing" - "github.com/goravel/framework/translation" - "github.com/goravel/framework/validation" ) type instance struct { @@ -85,7 +64,7 @@ func (c *Container) Make(key any) (any, error) { } func (c *Container) MakeArtisan() contractsconsole.Artisan { - instance, err := c.Make(console.Binding) + instance, err := c.Make(contracts.BindingConsole) if err != nil { color.Errorln(err) return nil @@ -95,7 +74,7 @@ func (c *Container) MakeArtisan() contractsconsole.Artisan { } func (c *Container) MakeAuth(ctx contractshttp.Context) contractsauth.Auth { - instance, err := c.MakeWith(auth.BindingAuth, map[string]any{ + instance, err := c.MakeWith(contracts.BindingAuth, map[string]any{ "ctx": ctx, }) if err != nil { @@ -110,7 +89,7 @@ func (c *Container) MakeAuth(ctx contractshttp.Context) contractsauth.Auth { } func (c *Container) MakeCache() contractscache.Cache { - instance, err := c.Make(cache.Binding) + instance, err := c.Make(contracts.BindingCache) if err != nil { color.Errorln(err) return nil @@ -120,7 +99,7 @@ func (c *Container) MakeCache() contractscache.Cache { } func (c *Container) MakeConfig() contractsconfig.Config { - instance, err := c.Make(config.Binding) + instance, err := c.Make(contracts.BindingConfig) if err != nil { color.Errorln(err) return nil @@ -130,7 +109,7 @@ func (c *Container) MakeConfig() contractsconfig.Config { } func (c *Container) MakeCrypt() contractscrypt.Crypt { - instance, err := c.Make(crypt.Binding) + instance, err := c.Make(contracts.BindingCrypt) if err != nil { color.Errorln(err) return nil @@ -140,7 +119,7 @@ func (c *Container) MakeCrypt() contractscrypt.Crypt { } func (c *Container) MakeEvent() contractsevent.Instance { - instance, err := c.Make(event.Binding) + instance, err := c.Make(contracts.BindingEvent) if err != nil { color.Errorln(err) return nil @@ -150,7 +129,7 @@ func (c *Container) MakeEvent() contractsevent.Instance { } func (c *Container) MakeGate() contractsaccess.Gate { - instance, err := c.Make(auth.BindingGate) + instance, err := c.Make(contracts.BindingGate) if err != nil { color.Errorln(err) return nil @@ -160,7 +139,7 @@ func (c *Container) MakeGate() contractsaccess.Gate { } func (c *Container) MakeGrpc() contractsgrpc.Grpc { - instance, err := c.Make(grpc.Binding) + instance, err := c.Make(contracts.BindingGrpc) if err != nil { color.Errorln(err) return nil @@ -170,7 +149,7 @@ func (c *Container) MakeGrpc() contractsgrpc.Grpc { } func (c *Container) MakeHash() contractshash.Hash { - instance, err := c.Make(hash.Binding) + instance, err := c.Make(contracts.BindingHash) if err != nil { color.Errorln(err) return nil @@ -180,7 +159,7 @@ func (c *Container) MakeHash() contractshash.Hash { } func (c *Container) MakeLang(ctx context.Context) contractstranslation.Translator { - instance, err := c.MakeWith(translation.Binding, map[string]any{ + instance, err := c.MakeWith(contracts.BindingTranslation, map[string]any{ "ctx": ctx, }) if err != nil { @@ -192,7 +171,7 @@ func (c *Container) MakeLang(ctx context.Context) contractstranslation.Translato } func (c *Container) MakeLog() contractslog.Log { - instance, err := c.Make(frameworklog.Binding) + instance, err := c.Make(contracts.BindingLog) if err != nil { color.Errorln(err) return nil @@ -202,7 +181,7 @@ func (c *Container) MakeLog() contractslog.Log { } func (c *Container) MakeMail() contractsmail.Mail { - instance, err := c.Make(mail.Binding) + instance, err := c.Make(contracts.BindingMail) if err != nil { color.Errorln(err) return nil @@ -212,7 +191,7 @@ func (c *Container) MakeMail() contractsmail.Mail { } func (c *Container) MakeOrm() contractsorm.Orm { - instance, err := c.Make(orm.BindingOrm) + instance, err := c.Make(contracts.BindingOrm) if err != nil { color.Errorln(err) return nil @@ -225,7 +204,7 @@ func (c *Container) MakeOrm() contractsorm.Orm { } func (c *Container) MakeQueue() contractsqueue.Queue { - instance, err := c.Make(queue.Binding) + instance, err := c.Make(contracts.BindingQueue) if err != nil { color.Errorln(err) return nil @@ -235,7 +214,7 @@ func (c *Container) MakeQueue() contractsqueue.Queue { } func (c *Container) MakeRateLimiter() contractshttp.RateLimiter { - instance, err := c.Make(http.BindingRateLimiter) + instance, err := c.Make(contracts.BindingRateLimiter) if err != nil { color.Errorln(err) return nil @@ -245,7 +224,7 @@ func (c *Container) MakeRateLimiter() contractshttp.RateLimiter { } func (c *Container) MakeRoute() contractsroute.Route { - instance, err := c.Make(route.Binding) + instance, err := c.Make(contracts.BindingRoute) if err != nil { color.Errorln(err) return nil @@ -255,7 +234,7 @@ func (c *Container) MakeRoute() contractsroute.Route { } func (c *Container) MakeSchedule() contractsschedule.Schedule { - instance, err := c.Make(schedule.Binding) + instance, err := c.Make(contracts.BindingSchedule) if err != nil { color.Errorln(err) return nil @@ -265,7 +244,7 @@ func (c *Container) MakeSchedule() contractsschedule.Schedule { } func (c *Container) MakeSchema() contractsmigration.Schema { - instance, err := c.Make(schema.BindingSchema) + instance, err := c.Make(contracts.BindingSchema) if err != nil { color.Errorln(err) return nil @@ -278,7 +257,7 @@ func (c *Container) MakeSchema() contractsmigration.Schema { } func (c *Container) MakeSession() contractsession.Manager { - instance, err := c.Make(session.Binding) + instance, err := c.Make(contracts.BindingSession) if err != nil { color.Errorln(err) return nil @@ -288,7 +267,7 @@ func (c *Container) MakeSession() contractsession.Manager { } func (c *Container) MakeStorage() contractsfilesystem.Storage { - instance, err := c.Make(filesystem.Binding) + instance, err := c.Make(contracts.BindingFilesystem) if err != nil { color.Errorln(err) return nil @@ -298,7 +277,7 @@ func (c *Container) MakeStorage() contractsfilesystem.Storage { } func (c *Container) MakeTesting() contractstesting.Testing { - instance, err := c.Make(testing.Binding) + instance, err := c.Make(contracts.BindingTesting) if err != nil { color.Errorln(err) return nil @@ -308,7 +287,7 @@ func (c *Container) MakeTesting() contractstesting.Testing { } func (c *Container) MakeValidation() contractsvalidation.Validation { - instance, err := c.Make(validation.Binding) + instance, err := c.Make(contracts.BindingValidation) if err != nil { color.Errorln(err) return nil @@ -318,7 +297,7 @@ func (c *Container) MakeValidation() contractsvalidation.Validation { } func (c *Container) MakeView() contractshttp.View { - instance, err := c.Make(http.BindingView) + instance, err := c.Make(contracts.BindingView) if err != nil { color.Errorln(err) return nil @@ -328,7 +307,7 @@ func (c *Container) MakeView() contractshttp.View { } func (c *Container) MakeSeeder() contractsseerder.Facade { - instance, err := c.Make(seeder.BindingSeeder) + instance, err := c.Make(contracts.BindingSeeder) if err != nil { color.Errorln(err) diff --git a/grpc/service_provider.go b/grpc/service_provider.go index daeb89443..29b17e773 100644 --- a/grpc/service_provider.go +++ b/grpc/service_provider.go @@ -1,17 +1,16 @@ package grpc import ( + "github.com/goravel/framework/contracts" "github.com/goravel/framework/contracts/foundation" "github.com/goravel/framework/errors" ) -const Binding = "goravel.grpc" - type ServiceProvider struct { } -func (route *ServiceProvider) Register(app foundation.Application) { - app.Singleton(Binding, func(app foundation.Application) (any, error) { +func (r *ServiceProvider) Register(app foundation.Application) { + app.Singleton(contracts.BindingGrpc, func(app foundation.Application) (any, error) { config := app.MakeConfig() if config == nil { return nil, errors.ConfigFacadeNotSet.SetModule(errors.ModuleGrpc) @@ -21,5 +20,5 @@ func (route *ServiceProvider) Register(app foundation.Application) { }) } -func (route *ServiceProvider) Boot(app foundation.Application) { +func (r *ServiceProvider) Boot(app foundation.Application) { } diff --git a/hash/service_provider.go b/hash/service_provider.go index 9d28d1cf9..2586f2e53 100644 --- a/hash/service_provider.go +++ b/hash/service_provider.go @@ -1,17 +1,16 @@ package hash import ( + "github.com/goravel/framework/contracts" "github.com/goravel/framework/contracts/foundation" "github.com/goravel/framework/errors" ) -const Binding = "goravel.hash" - type ServiceProvider struct { } -func (hash *ServiceProvider) Register(app foundation.Application) { - app.Singleton(Binding, func(app foundation.Application) (any, error) { +func (r *ServiceProvider) Register(app foundation.Application) { + app.Singleton(contracts.BindingHash, func(app foundation.Application) (any, error) { config := app.MakeConfig() if config == nil { return nil, errors.ConfigFacadeNotSet.SetModule(errors.ModuleHash) @@ -21,6 +20,6 @@ func (hash *ServiceProvider) Register(app foundation.Application) { }) } -func (hash *ServiceProvider) Boot(foundation.Application) { +func (r *ServiceProvider) Boot(foundation.Application) { } diff --git a/http/service_provider.go b/http/service_provider.go index 373c0e407..c8bd55794 100644 --- a/http/service_provider.go +++ b/http/service_provider.go @@ -1,6 +1,7 @@ package http import ( + "github.com/goravel/framework/contracts" "github.com/goravel/framework/contracts/cache" consolecontract "github.com/goravel/framework/contracts/console" "github.com/goravel/framework/contracts/foundation" @@ -8,11 +9,6 @@ import ( "github.com/goravel/framework/http/console" ) -const ( - BindingRateLimiter = "goravel.rate_limiter" - BindingView = "goravel.view" -) - type ServiceProvider struct{} var ( @@ -20,23 +16,23 @@ var ( RateLimiterFacade http.RateLimiter ) -func (http *ServiceProvider) Register(app foundation.Application) { - app.Singleton(BindingRateLimiter, func(app foundation.Application) (any, error) { +func (r *ServiceProvider) Register(app foundation.Application) { + app.Singleton(contracts.BindingRateLimiter, func(app foundation.Application) (any, error) { return NewRateLimiter(), nil }) - app.Singleton(BindingView, func(app foundation.Application) (any, error) { + app.Singleton(contracts.BindingView, func(app foundation.Application) (any, error) { return NewView(), nil }) } -func (http *ServiceProvider) Boot(app foundation.Application) { +func (r *ServiceProvider) Boot(app foundation.Application) { CacheFacade = app.MakeCache() RateLimiterFacade = app.MakeRateLimiter() - http.registerCommands(app) + r.registerCommands(app) } -func (http *ServiceProvider) registerCommands(app foundation.Application) { +func (r *ServiceProvider) registerCommands(app foundation.Application) { app.Commands([]consolecontract.Command{ &console.RequestMakeCommand{}, &console.ControllerMakeCommand{}, diff --git a/log/service_provider.go b/log/service_provider.go index 35605b173..92295a4c8 100644 --- a/log/service_provider.go +++ b/log/service_provider.go @@ -1,17 +1,16 @@ package log import ( + "github.com/goravel/framework/contracts" "github.com/goravel/framework/contracts/foundation" "github.com/goravel/framework/errors" ) -const Binding = "goravel.log" - type ServiceProvider struct { } -func (log *ServiceProvider) Register(app foundation.Application) { - app.Singleton(Binding, func(app foundation.Application) (any, error) { +func (r *ServiceProvider) Register(app foundation.Application) { + app.Singleton(contracts.BindingLog, func(app foundation.Application) (any, error) { config := app.MakeConfig() if config == nil { return nil, errors.ConfigFacadeNotSet.SetModule(errors.ModuleLog) @@ -25,6 +24,6 @@ func (log *ServiceProvider) Register(app foundation.Application) { }) } -func (log *ServiceProvider) Boot(app foundation.Application) { +func (r *ServiceProvider) Boot(app foundation.Application) { } diff --git a/mail/service_provider.go b/mail/service_provider.go index 14cb51de0..24add75cf 100644 --- a/mail/service_provider.go +++ b/mail/service_provider.go @@ -1,7 +1,8 @@ package mail import ( - consolecontract "github.com/goravel/framework/contracts/console" + "github.com/goravel/framework/contracts" + contractsconsole "github.com/goravel/framework/contracts/console" "github.com/goravel/framework/contracts/foundation" "github.com/goravel/framework/contracts/queue" "github.com/goravel/framework/errors" @@ -14,8 +15,8 @@ const Binding = "goravel.mail" type ServiceProvider struct { } -func (route *ServiceProvider) Register(app foundation.Application) { - app.Bind(Binding, func(app foundation.Application) (any, error) { +func (r *ServiceProvider) Register(app foundation.Application) { + app.Bind(contracts.BindingMail, func(app foundation.Application) (any, error) { config := app.MakeConfig() if config == nil { return nil, errors.ConfigFacadeNotSet.SetModule(errors.ModuleMail) @@ -29,15 +30,15 @@ func (route *ServiceProvider) Register(app foundation.Application) { }) } -func (route *ServiceProvider) Boot(app foundation.Application) { - app.Commands([]consolecontract.Command{ +func (r *ServiceProvider) Boot(app foundation.Application) { + app.Commands([]contractsconsole.Command{ console.NewMailMakeCommand(), }) - route.registerJobs(app) + r.registerJobs(app) } -func (route *ServiceProvider) registerJobs(app foundation.Application) { +func (r *ServiceProvider) registerJobs(app foundation.Application) { queueFacade := app.MakeQueue() if queueFacade == nil { color.Warningln("Queue Facade is not initialized. Skipping job registration.") diff --git a/queue/service_provider.go b/queue/service_provider.go index c96a352e5..d767f23fe 100644 --- a/queue/service_provider.go +++ b/queue/service_provider.go @@ -1,6 +1,7 @@ package queue import ( + "github.com/goravel/framework/contracts" "github.com/goravel/framework/contracts/console" "github.com/goravel/framework/contracts/database/orm" "github.com/goravel/framework/contracts/foundation" @@ -9,8 +10,6 @@ import ( queueconsole "github.com/goravel/framework/queue/console" ) -const Binding = "goravel.queue" - var ( LogFacade log.Log OrmFacade orm.Orm @@ -19,8 +18,8 @@ var ( type ServiceProvider struct { } -func (receiver *ServiceProvider) Register(app foundation.Application) { - app.Singleton(Binding, func(app foundation.Application) (any, error) { +func (r *ServiceProvider) Register(app foundation.Application) { + app.Singleton(contracts.BindingQueue, func(app foundation.Application) (any, error) { config := app.MakeConfig() if config == nil { return nil, errors.ConfigFacadeNotSet.SetModule(errors.ModuleQueue) @@ -30,14 +29,14 @@ func (receiver *ServiceProvider) Register(app foundation.Application) { }) } -func (receiver *ServiceProvider) Boot(app foundation.Application) { +func (r *ServiceProvider) Boot(app foundation.Application) { LogFacade = app.MakeLog() OrmFacade = app.MakeOrm() - receiver.registerCommands(app) + r.registerCommands(app) } -func (receiver *ServiceProvider) registerCommands(app foundation.Application) { +func (r *ServiceProvider) registerCommands(app foundation.Application) { app.MakeArtisan().Register([]console.Command{ &queueconsole.JobMakeCommand{}, }) diff --git a/route/service_provider.go b/route/service_provider.go index f4b25b9b2..50e0ed4c0 100644 --- a/route/service_provider.go +++ b/route/service_provider.go @@ -1,17 +1,16 @@ package route import ( + "github.com/goravel/framework/contracts" "github.com/goravel/framework/contracts/foundation" "github.com/goravel/framework/errors" ) -const Binding = "goravel.route" - type ServiceProvider struct { } -func (route *ServiceProvider) Register(app foundation.Application) { - app.Singleton(Binding, func(app foundation.Application) (any, error) { +func (r *ServiceProvider) Register(app foundation.Application) { + app.Singleton(contracts.BindingRoute, func(app foundation.Application) (any, error) { config := app.MakeConfig() if config == nil { return nil, errors.ConfigFacadeNotSet.SetModule(errors.ModuleRoute) @@ -21,6 +20,6 @@ func (route *ServiceProvider) Register(app foundation.Application) { }) } -func (route *ServiceProvider) Boot(app foundation.Application) { +func (r *ServiceProvider) Boot(app foundation.Application) { } diff --git a/schedule/service_provider.go b/schedule/service_provider.go index 89a72f7e8..005631148 100644 --- a/schedule/service_provider.go +++ b/schedule/service_provider.go @@ -1,17 +1,16 @@ package schedule import ( + "github.com/goravel/framework/contracts" "github.com/goravel/framework/contracts/foundation" "github.com/goravel/framework/errors" ) -const Binding = "goravel.schedule" - type ServiceProvider struct { } -func (receiver *ServiceProvider) Register(app foundation.Application) { - app.Singleton(Binding, func(app foundation.Application) (any, error) { +func (r *ServiceProvider) Register(app foundation.Application) { + app.Singleton(contracts.BindingSchedule, func(app foundation.Application) (any, error) { config := app.MakeConfig() if config == nil { return nil, errors.ConfigFacadeNotSet.SetModule(errors.ModuleSchedule) @@ -36,6 +35,6 @@ func (receiver *ServiceProvider) Register(app foundation.Application) { }) } -func (receiver *ServiceProvider) Boot(app foundation.Application) { +func (r *ServiceProvider) Boot(app foundation.Application) { } diff --git a/session/service_provider.go b/session/service_provider.go index 7325d9490..41dab1977 100644 --- a/session/service_provider.go +++ b/session/service_provider.go @@ -1,6 +1,7 @@ package session import ( + "github.com/goravel/framework/contracts" "github.com/goravel/framework/contracts/config" "github.com/goravel/framework/contracts/foundation" "github.com/goravel/framework/contracts/session" @@ -12,13 +13,11 @@ var ( ConfigFacade config.Config ) -const Binding = "goravel.session" - type ServiceProvider struct { } -func (receiver *ServiceProvider) Register(app foundation.Application) { - app.Singleton(Binding, func(app foundation.Application) (any, error) { +func (r *ServiceProvider) Register(app foundation.Application) { + app.Singleton(contracts.BindingSession, func(app foundation.Application) (any, error) { c := app.MakeConfig() if c == nil { return nil, errors.ConfigFacadeNotSet.SetModule(errors.ModuleSession) @@ -33,7 +32,7 @@ func (receiver *ServiceProvider) Register(app foundation.Application) { }) } -func (receiver *ServiceProvider) Boot(app foundation.Application) { +func (r *ServiceProvider) Boot(app foundation.Application) { SessionFacade = app.MakeSession() ConfigFacade = app.MakeConfig() } diff --git a/testing/service_provider.go b/testing/service_provider.go index 31e59741d..3b77f81e5 100644 --- a/testing/service_provider.go +++ b/testing/service_provider.go @@ -1,6 +1,7 @@ package testing import ( + "github.com/goravel/framework/contracts" contractsconsole "github.com/goravel/framework/contracts/console" "github.com/goravel/framework/contracts/foundation" contractsroute "github.com/goravel/framework/contracts/route" @@ -9,8 +10,6 @@ import ( "github.com/goravel/framework/support/color" ) -const Binding = "goravel.testing" - var ( json foundation.Json artisanFacade contractsconsole.Artisan @@ -21,13 +20,13 @@ var ( type ServiceProvider struct { } -func (receiver *ServiceProvider) Register(app foundation.Application) { - app.Singleton(Binding, func(app foundation.Application) (any, error) { +func (r *ServiceProvider) Register(app foundation.Application) { + app.Singleton(contracts.BindingTesting, func(app foundation.Application) (any, error) { return NewApplication(app), nil }) } -func (receiver *ServiceProvider) Boot(app foundation.Application) { +func (r *ServiceProvider) Boot(app foundation.Application) { artisanFacade = app.MakeArtisan() if artisanFacade == nil { color.Errorln(errors.ArtisanFacadeNotSet.SetModule(errors.ModuleTesting)) diff --git a/translation/service_provider.go b/translation/service_provider.go index 9892f2afa..5d3f157be 100644 --- a/translation/service_provider.go +++ b/translation/service_provider.go @@ -3,6 +3,7 @@ package translation import ( "context" + "github.com/goravel/framework/contracts" "github.com/goravel/framework/contracts/foundation" "github.com/goravel/framework/errors" ) @@ -12,8 +13,8 @@ const Binding = "goravel.translation" type ServiceProvider struct { } -func (translation *ServiceProvider) Register(app foundation.Application) { - app.BindWith(Binding, func(app foundation.Application, parameters map[string]any) (any, error) { +func (r *ServiceProvider) Register(app foundation.Application) { + app.BindWith(contracts.BindingTranslation, func(app foundation.Application, parameters map[string]any) (any, error) { config := app.MakeConfig() if config == nil { return nil, errors.ConfigFacadeNotSet.SetModule(errors.ModuleLang) @@ -34,6 +35,6 @@ func (translation *ServiceProvider) Register(app foundation.Application) { }) } -func (translation *ServiceProvider) Boot(app foundation.Application) { +func (r *ServiceProvider) Boot(app foundation.Application) { } diff --git a/validation/service_provider.go b/validation/service_provider.go index 6d0658ba0..10df5c5f0 100644 --- a/validation/service_provider.go +++ b/validation/service_provider.go @@ -1,23 +1,22 @@ package validation import ( + "github.com/goravel/framework/contracts" consolecontract "github.com/goravel/framework/contracts/console" "github.com/goravel/framework/contracts/foundation" "github.com/goravel/framework/validation/console" ) -const Binding = "goravel.validation" - type ServiceProvider struct { } -func (database *ServiceProvider) Register(app foundation.Application) { - app.Singleton(Binding, func(app foundation.Application) (any, error) { +func (r *ServiceProvider) Register(app foundation.Application) { + app.Singleton(contracts.BindingValidation, func(app foundation.Application) (any, error) { return NewValidation(), nil }) } -func (database *ServiceProvider) Boot(app foundation.Application) { +func (r *ServiceProvider) Boot(app foundation.Application) { app.Commands([]consolecontract.Command{ &console.RuleMakeCommand{}, &console.FilterMakeCommand{}, From c63da33a6ac2a04fb04b9408a17bc980ff2c2f70 Mon Sep 17 00:00:00 2001 From: ALMAS Date: Sun, 9 Feb 2025 13:07:36 +0800 Subject: [PATCH 2/7] feat: [#572] migrator support to rename column (#851) --- contracts/database/schema/blueprint.go | 4 +- contracts/database/schema/column.go | 1 + contracts/database/schema/grammar.go | 2 + database/schema/blueprint.go | 30 +++++++++++-- database/schema/blueprint_test.go | 3 +- database/schema/column.go | 7 ++++ mocks/database/schema/Blueprint.go | 54 +++++++++++++++++++++--- mocks/database/schema/Grammar.go | 58 ++++++++++++++++++++++++++ tests/query.go | 6 ++- tests/schema_test.go | 20 +++++++++ tests/table.go | 56 ++++++++++++------------- 11 files changed, 201 insertions(+), 40 deletions(-) diff --git a/contracts/database/schema/blueprint.go b/contracts/database/schema/blueprint.go index 30fd1df4a..a9f1f453a 100644 --- a/contracts/database/schema/blueprint.go +++ b/contracts/database/schema/blueprint.go @@ -103,6 +103,8 @@ type Blueprint interface { Primary(column ...string) // Rename the table to a given name. Rename(to string) + // RenameColumn Indicate that the given columns should be renamed. + RenameColumn(from, to string) // RenameIndex Indicate that the given indexes should be renamed. RenameIndex(from, to string) // SetTable Set the table that the blueprint operates on. @@ -138,7 +140,7 @@ type Blueprint interface { // TinyText Create a new tiny text column on the table. TinyText(column string) ColumnDefinition // ToSql Get the raw SQL statements for the blueprint. - ToSql(grammar Grammar) []string + ToSql(grammar Grammar) ([]string, error) // Unique Specify a unique index for the table. Unique(column ...string) IndexDefinition // UnsignedBigInteger Create a new unsigned big integer (8-byte) column on the table. diff --git a/contracts/database/schema/column.go b/contracts/database/schema/column.go index fbd929992..ae55942ca 100644 --- a/contracts/database/schema/column.go +++ b/contracts/database/schema/column.go @@ -64,6 +64,7 @@ type Column struct { Collation string Comment string Default string + Extra string Name string Nullable bool Type string diff --git a/contracts/database/schema/grammar.go b/contracts/database/schema/grammar.go index 0f85099b4..b70360eab 100644 --- a/contracts/database/schema/grammar.go +++ b/contracts/database/schema/grammar.go @@ -49,6 +49,8 @@ type Grammar interface { CompilePrimary(blueprint Blueprint, command *Command) string // CompileRename Compile a rename table command. CompileRename(blueprint Blueprint, command *Command) string + // CompileRenameColumn Compile a rename column command. + CompileRenameColumn(schema Schema, blueprint Blueprint, command *Command) (string, error) // CompileRenameIndex Compile a rename index command. CompileRenameIndex(schema Schema, blueprint Blueprint, command *Command) []string // CompileTables Compile the query to determine the tables. diff --git a/database/schema/blueprint.go b/database/schema/blueprint.go index dd54f31ef..c947e5649 100644 --- a/database/schema/blueprint.go +++ b/database/schema/blueprint.go @@ -27,6 +27,7 @@ const ( CommandIndex = "index" CommandPrimary = "primary" CommandRename = "rename" + CommandRenameColumn = "renameColumn" CommandRenameIndex = "renameIndex" CommandUnique = "unique" DefaultStringLength = 255 @@ -61,8 +62,13 @@ func (r *Blueprint) Boolean(column string) schema.ColumnDefinition { } func (r *Blueprint) Build(query orm.Query, grammar schema.Grammar) error { - for _, sql := range r.ToSql(grammar) { - if _, err := query.Exec(sql); err != nil { + statements, err := r.ToSql(grammar) + if err != nil { + return err + } + + for _, sql := range statements { + if _, err = query.Exec(sql); err != nil { return err } } @@ -335,6 +341,16 @@ func (r *Blueprint) Rename(to string) { r.addCommand(command) } +func (r *Blueprint) RenameColumn(from, to string) { + command := &schema.Command{ + Name: CommandRenameColumn, + From: from, + To: to, + } + + r.addCommand(command) +} + func (r *Blueprint) RenameIndex(from, to string) { command := &schema.Command{ Name: CommandRenameIndex, @@ -449,7 +465,7 @@ func (r *Blueprint) TinyText(column string) schema.ColumnDefinition { return r.createAndAddColumn("tinyText", column) } -func (r *Blueprint) ToSql(grammar schema.Grammar) []string { +func (r *Blueprint) ToSql(grammar schema.Grammar) ([]string, error) { r.addImpliedCommands(grammar) var statements []string @@ -503,6 +519,12 @@ func (r *Blueprint) ToSql(grammar schema.Grammar) []string { statements = append(statements, grammar.CompilePrimary(r, command)) case CommandRename: statements = append(statements, grammar.CompileRename(r, command)) + case CommandRenameColumn: + statement, err := grammar.CompileRenameColumn(r.schema, r, command) + if err != nil { + return statements, err + } + statements = append(statements, statement) case CommandRenameIndex: statements = append(statements, grammar.CompileRenameIndex(r.schema, r, command)...) case CommandUnique: @@ -510,7 +532,7 @@ func (r *Blueprint) ToSql(grammar schema.Grammar) []string { } } - return statements + return statements, nil } func (r *Blueprint) Unique(column ...string) schema.IndexDefinition { diff --git a/database/schema/blueprint_test.go b/database/schema/blueprint_test.go index afaa490c2..af9603077 100644 --- a/database/schema/blueprint_test.go +++ b/database/schema/blueprint_test.go @@ -661,7 +661,8 @@ func (s *BlueprintTestSuite) TestToSql() { test.setup() // Execute ToSql - statements := s.blueprint.ToSql(mockGrammar) + statements, err := s.blueprint.ToSql(mockGrammar) + s.NoError(err) // Verify results s.Equal(test.expectedSQL, statements) diff --git a/database/schema/column.go b/database/schema/column.go index af5152fef..71cf9849d 100644 --- a/database/schema/column.go +++ b/database/schema/column.go @@ -24,6 +24,13 @@ type ColumnDefinition struct { useCurrentOnUpdate *bool } +func NewColumnDefinition(name string, ttype string) schema.ColumnDefinition { + return &ColumnDefinition{ + name: &name, + ttype: convert.Pointer(ttype), + } +} + func (r *ColumnDefinition) AutoIncrement() schema.ColumnDefinition { r.autoIncrement = convert.Pointer(true) diff --git a/mocks/database/schema/Blueprint.go b/mocks/database/schema/Blueprint.go index e753a575b..5491f2b51 100644 --- a/mocks/database/schema/Blueprint.go +++ b/mocks/database/schema/Blueprint.go @@ -2306,6 +2306,40 @@ func (_c *Blueprint_Rename_Call) RunAndReturn(run func(string)) *Blueprint_Renam return _c } +// RenameColumn provides a mock function with given fields: from, to +func (_m *Blueprint) RenameColumn(from string, to string) { + _m.Called(from, to) +} + +// Blueprint_RenameColumn_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RenameColumn' +type Blueprint_RenameColumn_Call struct { + *mock.Call +} + +// RenameColumn is a helper method to define mock.On call +// - from string +// - to string +func (_e *Blueprint_Expecter) RenameColumn(from interface{}, to interface{}) *Blueprint_RenameColumn_Call { + return &Blueprint_RenameColumn_Call{Call: _e.mock.On("RenameColumn", from, to)} +} + +func (_c *Blueprint_RenameColumn_Call) Run(run func(from string, to string)) *Blueprint_RenameColumn_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(string), args[1].(string)) + }) + return _c +} + +func (_c *Blueprint_RenameColumn_Call) Return() *Blueprint_RenameColumn_Call { + _c.Call.Return() + return _c +} + +func (_c *Blueprint_RenameColumn_Call) RunAndReturn(run func(string, string)) *Blueprint_RenameColumn_Call { + _c.Run(run) + return _c +} + // RenameIndex provides a mock function with given fields: from, to func (_m *Blueprint) RenameIndex(from string, to string) { _m.Called(from, to) @@ -3191,7 +3225,7 @@ func (_c *Blueprint_TinyText_Call) RunAndReturn(run func(string) schema.ColumnDe } // ToSql provides a mock function with given fields: grammar -func (_m *Blueprint) ToSql(grammar schema.Grammar) []string { +func (_m *Blueprint) ToSql(grammar schema.Grammar) ([]string, error) { ret := _m.Called(grammar) if len(ret) == 0 { @@ -3199,6 +3233,10 @@ func (_m *Blueprint) ToSql(grammar schema.Grammar) []string { } var r0 []string + var r1 error + if rf, ok := ret.Get(0).(func(schema.Grammar) ([]string, error)); ok { + return rf(grammar) + } if rf, ok := ret.Get(0).(func(schema.Grammar) []string); ok { r0 = rf(grammar) } else { @@ -3207,7 +3245,13 @@ func (_m *Blueprint) ToSql(grammar schema.Grammar) []string { } } - return r0 + if rf, ok := ret.Get(1).(func(schema.Grammar) error); ok { + r1 = rf(grammar) + } else { + r1 = ret.Error(1) + } + + return r0, r1 } // Blueprint_ToSql_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ToSql' @@ -3228,12 +3272,12 @@ func (_c *Blueprint_ToSql_Call) Run(run func(grammar schema.Grammar)) *Blueprint return _c } -func (_c *Blueprint_ToSql_Call) Return(_a0 []string) *Blueprint_ToSql_Call { - _c.Call.Return(_a0) +func (_c *Blueprint_ToSql_Call) Return(_a0 []string, _a1 error) *Blueprint_ToSql_Call { + _c.Call.Return(_a0, _a1) return _c } -func (_c *Blueprint_ToSql_Call) RunAndReturn(run func(schema.Grammar) []string) *Blueprint_ToSql_Call { +func (_c *Blueprint_ToSql_Call) RunAndReturn(run func(schema.Grammar) ([]string, error)) *Blueprint_ToSql_Call { _c.Call.Return(run) return _c } diff --git a/mocks/database/schema/Grammar.go b/mocks/database/schema/Grammar.go index a6f183dc9..c25356dbd 100644 --- a/mocks/database/schema/Grammar.go +++ b/mocks/database/schema/Grammar.go @@ -1175,6 +1175,64 @@ func (_c *Grammar_CompileRename_Call) RunAndReturn(run func(schema.Blueprint, *s return _c } +// CompileRenameColumn provides a mock function with given fields: _a0, blueprint, command +func (_m *Grammar) CompileRenameColumn(_a0 schema.Schema, blueprint schema.Blueprint, command *schema.Command) (string, error) { + ret := _m.Called(_a0, blueprint, command) + + if len(ret) == 0 { + panic("no return value specified for CompileRenameColumn") + } + + var r0 string + var r1 error + if rf, ok := ret.Get(0).(func(schema.Schema, schema.Blueprint, *schema.Command) (string, error)); ok { + return rf(_a0, blueprint, command) + } + if rf, ok := ret.Get(0).(func(schema.Schema, schema.Blueprint, *schema.Command) string); ok { + r0 = rf(_a0, blueprint, command) + } else { + r0 = ret.Get(0).(string) + } + + if rf, ok := ret.Get(1).(func(schema.Schema, schema.Blueprint, *schema.Command) error); ok { + r1 = rf(_a0, blueprint, command) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Grammar_CompileRenameColumn_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CompileRenameColumn' +type Grammar_CompileRenameColumn_Call struct { + *mock.Call +} + +// CompileRenameColumn is a helper method to define mock.On call +// - _a0 schema.Schema +// - blueprint schema.Blueprint +// - command *schema.Command +func (_e *Grammar_Expecter) CompileRenameColumn(_a0 interface{}, blueprint interface{}, command interface{}) *Grammar_CompileRenameColumn_Call { + return &Grammar_CompileRenameColumn_Call{Call: _e.mock.On("CompileRenameColumn", _a0, blueprint, command)} +} + +func (_c *Grammar_CompileRenameColumn_Call) Run(run func(_a0 schema.Schema, blueprint schema.Blueprint, command *schema.Command)) *Grammar_CompileRenameColumn_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(schema.Schema), args[1].(schema.Blueprint), args[2].(*schema.Command)) + }) + return _c +} + +func (_c *Grammar_CompileRenameColumn_Call) Return(_a0 string, _a1 error) *Grammar_CompileRenameColumn_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *Grammar_CompileRenameColumn_Call) RunAndReturn(run func(schema.Schema, schema.Blueprint, *schema.Command) (string, error)) *Grammar_CompileRenameColumn_Call { + _c.Call.Return(run) + return _c +} + // CompileRenameIndex provides a mock function with given fields: _a0, blueprint, command func (_m *Grammar) CompileRenameIndex(_a0 schema.Schema, blueprint schema.Blueprint, command *schema.Command) []string { ret := _m.Called(_a0, blueprint, command) diff --git a/tests/query.go b/tests/query.go index 7d37c9ee6..25f5cc1a8 100644 --- a/tests/query.go +++ b/tests/query.go @@ -51,7 +51,11 @@ func (r *TestQuery) CreateTable(testTables ...TestTable) { for table, sql := range newTestTables(driverName, r.Driver().Grammar()).All() { if (len(testTables) == 0 && table != TestTableSchema) || slices.Contains(testTables, table) { - if _, err := r.query.Exec(sql()); err != nil { + statements, err := sql() + if err == nil { + _, err = r.query.Exec(statements[0]) + } + if err != nil { panic(fmt.Sprintf("create table %v failed: %v", table, err)) } } diff --git a/tests/schema_test.go b/tests/schema_test.go index 746bd5208..d61d0f154 100644 --- a/tests/schema_test.go +++ b/tests/schema_test.go @@ -1851,6 +1851,26 @@ func (s *SchemaSuite) TestPrimary() { } } +func (s *SchemaSuite) TestRenameColumn() { + for driver, testQuery := range s.driverToTestQuery { + s.Run(driver, func() { + schema := newSchema(testQuery, s.driverToTestQuery) + table := "rename_column" + + s.NoError(schema.Create(table, func(table contractsschema.Blueprint) { + table.String("before") + })) + s.True(schema.HasColumn(table, "before")) + + s.NoError(schema.Table(table, func(table contractsschema.Blueprint) { + table.RenameColumn("before", "after") + })) + s.False(schema.HasColumn(table, "before")) + s.True(schema.HasColumn(table, "after")) + }) + } +} + func (s *SchemaSuite) TestID_Postgres() { if s.driverToTestQuery[postgres.Name] == nil { s.T().Skip("Skip test") diff --git a/tests/table.go b/tests/table.go index 72df3ee3d..7e9805dcf 100644 --- a/tests/table.go +++ b/tests/table.go @@ -32,8 +32,8 @@ func newTestTables(driver string, grammar contractsschema.Grammar) *testTables { return &testTables{driver: driver, grammar: grammar} } -func (r *testTables) All() map[TestTable]func() string { - return map[TestTable]func() string{ +func (r *testTables) All() map[TestTable]func() ([]string, error) { + return map[TestTable]func() ([]string, error){ TestTableAddresses: r.addresses, TestTableAuthors: r.authors, TestTableBooks: r.books, @@ -50,7 +50,7 @@ func (r *testTables) All() map[TestTable]func() string { } } -func (r *testTables) peoples() string { +func (r *testTables) peoples() ([]string, error) { blueprint := schema.NewBlueprint(nil, "", "peoples") blueprint.Create() blueprint.BigIncrements("id") @@ -58,10 +58,10 @@ func (r *testTables) peoples() string { blueprint.Timestamps() blueprint.SoftDeletes() - return blueprint.ToSql(r.grammar)[0] + return blueprint.ToSql(r.grammar) } -func (r *testTables) reviews() string { +func (r *testTables) reviews() ([]string, error) { blueprint := schema.NewBlueprint(nil, "", "reviews") blueprint.Create() blueprint.BigIncrements("id") @@ -69,10 +69,10 @@ func (r *testTables) reviews() string { blueprint.Timestamps() blueprint.SoftDeletes() - return blueprint.ToSql(r.grammar)[0] + return blueprint.ToSql(r.grammar) } -func (r *testTables) products() string { +func (r *testTables) products() ([]string, error) { blueprint := schema.NewBlueprint(nil, "", "products") blueprint.Create() blueprint.BigIncrements("id") @@ -80,10 +80,10 @@ func (r *testTables) products() string { blueprint.Timestamps() blueprint.SoftDeletes() - return blueprint.ToSql(r.grammar)[0] + return blueprint.ToSql(r.grammar) } -func (r *testTables) users() string { +func (r *testTables) users() ([]string, error) { blueprint := schema.NewBlueprint(nil, "", "users") blueprint.Create() blueprint.BigIncrements("id") @@ -93,10 +93,10 @@ func (r *testTables) users() string { blueprint.Timestamps() blueprint.SoftDeletes() - return blueprint.ToSql(r.grammar)[0] + return blueprint.ToSql(r.grammar) } -func (r *testTables) user() string { +func (r *testTables) user() ([]string, error) { blueprint := schema.NewBlueprint(nil, "", "user") blueprint.Create() blueprint.BigIncrements("id") @@ -106,10 +106,10 @@ func (r *testTables) user() string { blueprint.Timestamps() blueprint.SoftDeletes() - return blueprint.ToSql(r.grammar)[0] + return blueprint.ToSql(r.grammar) } -func (r *testTables) addresses() string { +func (r *testTables) addresses() ([]string, error) { blueprint := schema.NewBlueprint(nil, "", "addresses") blueprint.Create() blueprint.BigIncrements("id") @@ -119,10 +119,10 @@ func (r *testTables) addresses() string { blueprint.Timestamps() blueprint.SoftDeletes() - return blueprint.ToSql(r.grammar)[0] + return blueprint.ToSql(r.grammar) } -func (r *testTables) books() string { +func (r *testTables) books() ([]string, error) { blueprint := schema.NewBlueprint(nil, "", "books") blueprint.Create() blueprint.BigIncrements("id") @@ -131,10 +131,10 @@ func (r *testTables) books() string { blueprint.Timestamps() blueprint.SoftDeletes() - return blueprint.ToSql(r.grammar)[0] + return blueprint.ToSql(r.grammar) } -func (r *testTables) authors() string { +func (r *testTables) authors() ([]string, error) { blueprint := schema.NewBlueprint(nil, "", "authors") blueprint.Create() blueprint.BigIncrements("id") @@ -143,10 +143,10 @@ func (r *testTables) authors() string { blueprint.Timestamps() blueprint.SoftDeletes() - return blueprint.ToSql(r.grammar)[0] + return blueprint.ToSql(r.grammar) } -func (r *testTables) roles() string { +func (r *testTables) roles() ([]string, error) { blueprint := schema.NewBlueprint(nil, "", "roles") blueprint.Create() blueprint.BigIncrements("id") @@ -155,10 +155,10 @@ func (r *testTables) roles() string { blueprint.Timestamps() blueprint.SoftDeletes() - return blueprint.ToSql(r.grammar)[0] + return blueprint.ToSql(r.grammar) } -func (r *testTables) houses() string { +func (r *testTables) houses() ([]string, error) { blueprint := schema.NewBlueprint(nil, "", "houses") blueprint.Create() blueprint.BigIncrements("id") @@ -168,10 +168,10 @@ func (r *testTables) houses() string { blueprint.Timestamps() blueprint.SoftDeletes() - return blueprint.ToSql(r.grammar)[0] + return blueprint.ToSql(r.grammar) } -func (r *testTables) phones() string { +func (r *testTables) phones() ([]string, error) { blueprint := schema.NewBlueprint(nil, "", "phones") blueprint.Create() blueprint.BigIncrements("id") @@ -181,10 +181,10 @@ func (r *testTables) phones() string { blueprint.Timestamps() blueprint.SoftDeletes() - return blueprint.ToSql(r.grammar)[0] + return blueprint.ToSql(r.grammar) } -func (r *testTables) roleUser() string { +func (r *testTables) roleUser() ([]string, error) { blueprint := schema.NewBlueprint(nil, "", "role_user") blueprint.Create() blueprint.BigIncrements("id") @@ -193,15 +193,15 @@ func (r *testTables) roleUser() string { blueprint.Timestamps() blueprint.SoftDeletes() - return blueprint.ToSql(r.grammar)[0] + return blueprint.ToSql(r.grammar) } -func (r *testTables) schema() string { +func (r *testTables) schema() ([]string, error) { blueprint := schema.NewBlueprint(nil, "", "goravel.schemas") blueprint.Create() blueprint.BigIncrements("id") blueprint.String("name") blueprint.Timestamps() - return blueprint.ToSql(r.grammar)[0] + return blueprint.ToSql(r.grammar) } From ddf6081158708e27b22c9a9ead6e20b6640dfe19 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 10 Feb 2025 01:33:41 +0000 Subject: [PATCH 3/7] chore: Update upgrade DB packages (#870) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- tests/go.mod | 10 +++++----- tests/go.sum | 20 ++++++++++---------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/tests/go.mod b/tests/go.mod index 7ff85933d..c0d58e401 100644 --- a/tests/go.mod +++ b/tests/go.mod @@ -8,9 +8,9 @@ require ( github.com/brianvoe/gofakeit/v7 v7.2.1 github.com/goravel/framework v1.15.3 github.com/goravel/mysql v0.0.0-20250207111224-4bae3e237ee0 - github.com/goravel/postgres v0.0.2-0.20250207111220-68d6cc2ff906 - github.com/goravel/sqlite v0.0.0-20250207134526-6d6f47272b5e - github.com/goravel/sqlserver v0.0.0-20250207134558-db7397b26496 + github.com/goravel/postgres v0.0.2-0.20250209093646-f147df26ffa6 + github.com/goravel/sqlite v0.0.0-20250209093531-a5c49bfab180 + github.com/goravel/sqlserver v0.0.0-20250209093547-712da67f16de github.com/spf13/cast v1.7.1 github.com/stretchr/testify v1.10.0 gorm.io/gorm v1.25.12 @@ -56,12 +56,12 @@ require ( github.com/sirupsen/logrus v1.9.3 // indirect github.com/stretchr/objx v0.5.2 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect - golang.org/x/crypto v0.32.0 // indirect + golang.org/x/crypto v0.33.0 // indirect golang.org/x/exp v0.0.0-20250207012021-f9890c6ad9f3 // indirect golang.org/x/net v0.34.0 // indirect golang.org/x/sync v0.11.0 // indirect golang.org/x/sys v0.30.0 // indirect - golang.org/x/term v0.28.0 // indirect + golang.org/x/term v0.29.0 // indirect golang.org/x/text v0.22.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20250127172529-29210b9bc287 // indirect google.golang.org/grpc v1.70.0 // indirect diff --git a/tests/go.sum b/tests/go.sum index a005dfc97..5254e68b0 100644 --- a/tests/go.sum +++ b/tests/go.sum @@ -103,12 +103,12 @@ github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0= github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w= github.com/goravel/mysql v0.0.0-20250207111224-4bae3e237ee0 h1:AfUyYGuNvuugmEFTbHLicS5xJCsba8izEdX5lx0zJGw= github.com/goravel/mysql v0.0.0-20250207111224-4bae3e237ee0/go.mod h1:qZmtQQsZeAyBm92h4lGtDgpOGOrZr6u6VQfSvDkA96E= -github.com/goravel/postgres v0.0.2-0.20250207111220-68d6cc2ff906 h1:9/d3f0DOdLQafD4bHeVTTTElRRcyvO4GGiTjY5XmKzg= -github.com/goravel/postgres v0.0.2-0.20250207111220-68d6cc2ff906/go.mod h1:ETLmwHBYGFkTv7xLL6YylwyTHT4MU+ubm497MXsg5Bo= -github.com/goravel/sqlite v0.0.0-20250207134526-6d6f47272b5e h1:f+QN+O9esk0uxOLUaigYd6FNePivF6X5pylin0x5PYA= -github.com/goravel/sqlite v0.0.0-20250207134526-6d6f47272b5e/go.mod h1:Tc4DvdctzZSajSw/0EzG2iH0566VLHk4bDe4C8aJU/s= -github.com/goravel/sqlserver v0.0.0-20250207134558-db7397b26496 h1:lmxVK+iVaCtM+h/X9NDoUqQQ6qizvPfXOP0vpw8kQbw= -github.com/goravel/sqlserver v0.0.0-20250207134558-db7397b26496/go.mod h1:EYwwNY2KpXv1j3imm3sNv5dRKYA6N0eb7yzEccsYqZM= +github.com/goravel/postgres v0.0.2-0.20250209093646-f147df26ffa6 h1:gyGjYKqOWbafD/PjIONX4N9Pi0lXXuad0BImnq/QFBs= +github.com/goravel/postgres v0.0.2-0.20250209093646-f147df26ffa6/go.mod h1:CjWylVxDa9zI6oF4HPlXNigSfbA5WSa4LCAGOPk8w1Y= +github.com/goravel/sqlite v0.0.0-20250209093531-a5c49bfab180 h1:MQidY/OsKETY0/PQN8zR1/VH7La0crcJdLFnow+jJYs= +github.com/goravel/sqlite v0.0.0-20250209093531-a5c49bfab180/go.mod h1:yAKZlbg04IJLHUYvjPHoRbLwz7B8pRcLi92FggkP2zA= +github.com/goravel/sqlserver v0.0.0-20250209093547-712da67f16de h1:OYgOvw4nMGmCibP6lAxeeoqjkv8dT4fS17okTk2UE7o= +github.com/goravel/sqlserver v0.0.0-20250209093547-712da67f16de/go.mod h1:lEyZza5IL8Y5zsMwB+MRLBjWK14jbAp2IEwwnHi9UmI= github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= @@ -231,8 +231,8 @@ golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf golang.org/x/crypto v0.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg= -golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc= -golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc= +golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus= +golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M= golang.org/x/exp v0.0.0-20250207012021-f9890c6ad9f3 h1:qNgPs5exUA+G0C96DrPwNrvLSj7GT/9D+3WMWUcUg34= golang.org/x/exp v0.0.0-20250207012021-f9890c6ad9f3/go.mod h1:tujkw807nyEEAamNbDrEGzRav+ilXA7PCRAd6xsmwiU= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= @@ -293,8 +293,8 @@ golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU= golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U= golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0= golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY= -golang.org/x/term v0.28.0 h1:/Ts8HFuMR2E6IP/jlo7QVLZHggjKQbhu/7H0LJFr3Gg= -golang.org/x/term v0.28.0/go.mod h1:Sw/lC2IAUZ92udQNf3WodGtn4k/XoLyZoh8v/8uiwek= +golang.org/x/term v0.29.0 h1:L6pJp37ocefwRRtYPKSWOWzOtWSxVajvz2ldH/xi3iU= +golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= From 0b10d264b216964f0e6834ca1be91e375e017abf Mon Sep 17 00:00:00 2001 From: ALMAS Date: Mon, 10 Feb 2025 09:53:44 +0800 Subject: [PATCH 4/7] chore(deps): Update tests module (#871) --- tests/go.mod | 3 ++- tests/go.sum | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/go.mod b/tests/go.mod index c0d58e401..1c992f57c 100644 --- a/tests/go.mod +++ b/tests/go.mod @@ -7,7 +7,7 @@ toolchain go1.23.6 require ( github.com/brianvoe/gofakeit/v7 v7.2.1 github.com/goravel/framework v1.15.3 - github.com/goravel/mysql v0.0.0-20250207111224-4bae3e237ee0 + github.com/goravel/mysql v0.0.0-20250210011254-9206b07db4b9 github.com/goravel/postgres v0.0.2-0.20250209093646-f147df26ffa6 github.com/goravel/sqlite v0.0.0-20250209093531-a5c49bfab180 github.com/goravel/sqlserver v0.0.0-20250209093547-712da67f16de @@ -21,6 +21,7 @@ require ( atomicgo.dev/keyboard v0.2.9 // indirect atomicgo.dev/schedule v0.1.0 // indirect filippo.io/edwards25519 v1.1.0 // indirect + github.com/Masterminds/semver/v3 v3.3.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/containerd/console v1.0.4 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect diff --git a/tests/go.sum b/tests/go.sum index 5254e68b0..960dc4124 100644 --- a/tests/go.sum +++ b/tests/go.sum @@ -38,6 +38,8 @@ github.com/MarvinJWendt/testza v0.3.0/go.mod h1:eFcL4I0idjtIx8P9C6KkAuLgATNKpX4/ github.com/MarvinJWendt/testza v0.4.2/go.mod h1:mSdhXiKH8sg/gQehJ63bINcCKp7RtYewEjXsvsVUPbE= github.com/MarvinJWendt/testza v0.5.2 h1:53KDo64C1z/h/d/stCYCPY69bt/OSwjq5KpFNwi+zB4= github.com/MarvinJWendt/testza v0.5.2/go.mod h1:xu53QFE5sCdjtMCKk8YMQ2MnymimEctc4n3EjyIYvEY= +github.com/Masterminds/semver/v3 v3.3.1 h1:QtNSWtVZ3nBfk8mAOu/B6v7FMJ+NHTIgUPi7rj+4nv4= +github.com/Masterminds/semver/v3 v3.3.1/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= github.com/atomicgo/cursor v0.0.1/go.mod h1:cBON2QmmrysudxNBFthvMtN32r3jxVRIvzkUiF/RuIk= github.com/brianvoe/gofakeit/v7 v7.2.1 h1:AGojgaaCdgq4Adzrd2uWdbGNDyX6MWNhHdQBraNfOHI= github.com/brianvoe/gofakeit/v7 v7.2.1/go.mod h1:QXuPeBw164PJCzCUZVmgpgHJ3Llj49jSLVkKPMtxtxA= @@ -103,6 +105,8 @@ github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0= github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w= github.com/goravel/mysql v0.0.0-20250207111224-4bae3e237ee0 h1:AfUyYGuNvuugmEFTbHLicS5xJCsba8izEdX5lx0zJGw= github.com/goravel/mysql v0.0.0-20250207111224-4bae3e237ee0/go.mod h1:qZmtQQsZeAyBm92h4lGtDgpOGOrZr6u6VQfSvDkA96E= +github.com/goravel/mysql v0.0.0-20250210011254-9206b07db4b9 h1:H3gRmhiYMibTTVm75GR6uBWtOuVQblQMjp8TIeQcVbo= +github.com/goravel/mysql v0.0.0-20250210011254-9206b07db4b9/go.mod h1:2lmFlKyjcZqwa+9NuJTQeX2obXIkpCL1ptlAL1sL5+4= github.com/goravel/postgres v0.0.2-0.20250209093646-f147df26ffa6 h1:gyGjYKqOWbafD/PjIONX4N9Pi0lXXuad0BImnq/QFBs= github.com/goravel/postgres v0.0.2-0.20250209093646-f147df26ffa6/go.mod h1:CjWylVxDa9zI6oF4HPlXNigSfbA5WSa4LCAGOPk8w1Y= github.com/goravel/sqlite v0.0.0-20250209093531-a5c49bfab180 h1:MQidY/OsKETY0/PQN8zR1/VH7La0crcJdLFnow+jJYs= From 7edffd9b4390580b0a321bcd92f466cf9a608983 Mon Sep 17 00:00:00 2001 From: ALMAS Date: Mon, 10 Feb 2025 15:39:17 +0800 Subject: [PATCH 5/7] feat: [#549] migrator supports table comments (#873) --- contracts/database/schema/blueprint.go | 2 ++ contracts/database/schema/grammar.go | 2 ++ database/schema/blueprint.go | 12 +++++++ mocks/database/schema/Blueprint.go | 33 ++++++++++++++++++ mocks/database/schema/Grammar.go | 47 ++++++++++++++++++++++++++ tests/schema_test.go | 27 +++++++++++++++ 6 files changed, 123 insertions(+) diff --git a/contracts/database/schema/blueprint.go b/contracts/database/schema/blueprint.go index a9f1f453a..d420313db 100644 --- a/contracts/database/schema/blueprint.go +++ b/contracts/database/schema/blueprint.go @@ -17,6 +17,8 @@ type Blueprint interface { Char(column string, length ...int) ColumnDefinition // Column Create a new custom type column on the table. Column(column string, ttype string) ColumnDefinition + // Comment Add a comment to the table. + Comment(value string) // Create Indicate that the table needs to be created. Create() // Date Create a new date column on the table. diff --git a/contracts/database/schema/grammar.go b/contracts/database/schema/grammar.go index b70360eab..dac3c4c3b 100644 --- a/contracts/database/schema/grammar.go +++ b/contracts/database/schema/grammar.go @@ -55,6 +55,8 @@ type Grammar interface { CompileRenameIndex(schema Schema, blueprint Blueprint, command *Command) []string // CompileTables Compile the query to determine the tables. CompileTables(database string) string + // CompileTableComment Compile a table comment command. + CompileTableComment(blueprint Blueprint, command *Command) string // CompileTypes Compile the query to determine the types. CompileTypes() string // CompileUnique Compile a unique key command. diff --git a/database/schema/blueprint.go b/database/schema/blueprint.go index c947e5649..bdf7a29cb 100644 --- a/database/schema/blueprint.go +++ b/database/schema/blueprint.go @@ -29,6 +29,7 @@ const ( CommandRename = "rename" CommandRenameColumn = "renameColumn" CommandRenameIndex = "renameIndex" + CommandTableComment = "tableComment" CommandUnique = "unique" DefaultStringLength = 255 ) @@ -92,6 +93,13 @@ func (r *Blueprint) Column(column, ttype string) schema.ColumnDefinition { return r.createAndAddColumn(ttype, column) } +func (r *Blueprint) Comment(comment string) { + r.addCommand(&schema.Command{ + Name: CommandTableComment, + Value: comment, + }) +} + func (r *Blueprint) Create() { r.addCommand(&schema.Command{ Name: CommandCreate, @@ -527,6 +535,10 @@ func (r *Blueprint) ToSql(grammar schema.Grammar) ([]string, error) { statements = append(statements, statement) case CommandRenameIndex: statements = append(statements, grammar.CompileRenameIndex(r.schema, r, command)...) + case CommandTableComment: + if statement := grammar.CompileTableComment(r, command); statement != "" { + statements = append(statements, statement) + } case CommandUnique: statements = append(statements, grammar.CompileUnique(r, command)) } diff --git a/mocks/database/schema/Blueprint.go b/mocks/database/schema/Blueprint.go index 5491f2b51..fcdde9826 100644 --- a/mocks/database/schema/Blueprint.go +++ b/mocks/database/schema/Blueprint.go @@ -324,6 +324,39 @@ func (_c *Blueprint_Column_Call) RunAndReturn(run func(string, string) schema.Co return _c } +// Comment provides a mock function with given fields: value +func (_m *Blueprint) Comment(value string) { + _m.Called(value) +} + +// Blueprint_Comment_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Comment' +type Blueprint_Comment_Call struct { + *mock.Call +} + +// Comment is a helper method to define mock.On call +// - value string +func (_e *Blueprint_Expecter) Comment(value interface{}) *Blueprint_Comment_Call { + return &Blueprint_Comment_Call{Call: _e.mock.On("Comment", value)} +} + +func (_c *Blueprint_Comment_Call) Run(run func(value string)) *Blueprint_Comment_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(string)) + }) + return _c +} + +func (_c *Blueprint_Comment_Call) Return() *Blueprint_Comment_Call { + _c.Call.Return() + return _c +} + +func (_c *Blueprint_Comment_Call) RunAndReturn(run func(string)) *Blueprint_Comment_Call { + _c.Run(run) + return _c +} + // Create provides a mock function with no fields func (_m *Blueprint) Create() { _m.Called() diff --git a/mocks/database/schema/Grammar.go b/mocks/database/schema/Grammar.go index c25356dbd..25f2ebbc8 100644 --- a/mocks/database/schema/Grammar.go +++ b/mocks/database/schema/Grammar.go @@ -1283,6 +1283,53 @@ func (_c *Grammar_CompileRenameIndex_Call) RunAndReturn(run func(schema.Schema, return _c } +// CompileTableComment provides a mock function with given fields: blueprint, command +func (_m *Grammar) CompileTableComment(blueprint schema.Blueprint, command *schema.Command) string { + ret := _m.Called(blueprint, command) + + if len(ret) == 0 { + panic("no return value specified for CompileTableComment") + } + + var r0 string + if rf, ok := ret.Get(0).(func(schema.Blueprint, *schema.Command) string); ok { + r0 = rf(blueprint, command) + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// Grammar_CompileTableComment_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CompileTableComment' +type Grammar_CompileTableComment_Call struct { + *mock.Call +} + +// CompileTableComment is a helper method to define mock.On call +// - blueprint schema.Blueprint +// - command *schema.Command +func (_e *Grammar_Expecter) CompileTableComment(blueprint interface{}, command interface{}) *Grammar_CompileTableComment_Call { + return &Grammar_CompileTableComment_Call{Call: _e.mock.On("CompileTableComment", blueprint, command)} +} + +func (_c *Grammar_CompileTableComment_Call) Run(run func(blueprint schema.Blueprint, command *schema.Command)) *Grammar_CompileTableComment_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(schema.Blueprint), args[1].(*schema.Command)) + }) + return _c +} + +func (_c *Grammar_CompileTableComment_Call) Return(_a0 string) *Grammar_CompileTableComment_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *Grammar_CompileTableComment_Call) RunAndReturn(run func(schema.Blueprint, *schema.Command) string) *Grammar_CompileTableComment_Call { + _c.Call.Return(run) + return _c +} + // CompileTables provides a mock function with given fields: database func (_m *Grammar) CompileTables(database string) string { ret := _m.Called(database) diff --git a/tests/schema_test.go b/tests/schema_test.go index d61d0f154..3e6891789 100644 --- a/tests/schema_test.go +++ b/tests/schema_test.go @@ -1871,6 +1871,33 @@ func (s *SchemaSuite) TestRenameColumn() { } } +func (s *SchemaSuite) TestTableComment() { + for driver, testQuery := range s.driverToTestQuery { + if driver == sqlite.Name || driver == sqlserver.Name { + continue + } + s.Run(driver, func() { + schema := newSchema(testQuery, s.driverToTestQuery) + table := "table_with_comment" + comment := "It's a table with comment" + + s.NoError(schema.Create(table, func(table contractsschema.Blueprint) { + table.ID() + table.Comment(comment) + })) + s.True(schema.HasTable(table)) + + tables, err := schema.GetTables() + s.NoError(err) + for _, t := range tables { + if t.Name == table { + s.Equal(comment, t.Comment) + } + } + }) + } +} + func (s *SchemaSuite) TestID_Postgres() { if s.driverToTestQuery[postgres.Name] == nil { s.T().Skip("Skip test") From c378d7d39de925b6f70da5959a03794e1b48a6f5 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 10 Feb 2025 08:44:17 +0000 Subject: [PATCH 6/7] chore: Update upgrade DB packages (#875) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- tests/go.mod | 8 ++++---- tests/go.sum | 18 ++++++++---------- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/tests/go.mod b/tests/go.mod index 1c992f57c..33fbcb812 100644 --- a/tests/go.mod +++ b/tests/go.mod @@ -7,10 +7,10 @@ toolchain go1.23.6 require ( github.com/brianvoe/gofakeit/v7 v7.2.1 github.com/goravel/framework v1.15.3 - github.com/goravel/mysql v0.0.0-20250210011254-9206b07db4b9 - github.com/goravel/postgres v0.0.2-0.20250209093646-f147df26ffa6 - github.com/goravel/sqlite v0.0.0-20250209093531-a5c49bfab180 - github.com/goravel/sqlserver v0.0.0-20250209093547-712da67f16de + github.com/goravel/mysql v0.0.0-20250210074846-5e7ae5bdeda5 + github.com/goravel/postgres v0.0.2-0.20250210074923-55c799056495 + github.com/goravel/sqlite v0.0.0-20250210074940-7a05cbb1dd50 + github.com/goravel/sqlserver v0.0.0-20250210074958-b94e2314a481 github.com/spf13/cast v1.7.1 github.com/stretchr/testify v1.10.0 gorm.io/gorm v1.25.12 diff --git a/tests/go.sum b/tests/go.sum index 960dc4124..e4072f1fc 100644 --- a/tests/go.sum +++ b/tests/go.sum @@ -103,16 +103,14 @@ github.com/gookit/color v1.4.2/go.mod h1:fqRyamkC1W8uxl+lxCQxOT09l/vYfZ+QeiX3rKQ github.com/gookit/color v1.5.0/go.mod h1:43aQb+Zerm/BWh2GnrgOQm7ffz7tvQXEKV6BFMl7wAo= github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0= github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w= -github.com/goravel/mysql v0.0.0-20250207111224-4bae3e237ee0 h1:AfUyYGuNvuugmEFTbHLicS5xJCsba8izEdX5lx0zJGw= -github.com/goravel/mysql v0.0.0-20250207111224-4bae3e237ee0/go.mod h1:qZmtQQsZeAyBm92h4lGtDgpOGOrZr6u6VQfSvDkA96E= -github.com/goravel/mysql v0.0.0-20250210011254-9206b07db4b9 h1:H3gRmhiYMibTTVm75GR6uBWtOuVQblQMjp8TIeQcVbo= -github.com/goravel/mysql v0.0.0-20250210011254-9206b07db4b9/go.mod h1:2lmFlKyjcZqwa+9NuJTQeX2obXIkpCL1ptlAL1sL5+4= -github.com/goravel/postgres v0.0.2-0.20250209093646-f147df26ffa6 h1:gyGjYKqOWbafD/PjIONX4N9Pi0lXXuad0BImnq/QFBs= -github.com/goravel/postgres v0.0.2-0.20250209093646-f147df26ffa6/go.mod h1:CjWylVxDa9zI6oF4HPlXNigSfbA5WSa4LCAGOPk8w1Y= -github.com/goravel/sqlite v0.0.0-20250209093531-a5c49bfab180 h1:MQidY/OsKETY0/PQN8zR1/VH7La0crcJdLFnow+jJYs= -github.com/goravel/sqlite v0.0.0-20250209093531-a5c49bfab180/go.mod h1:yAKZlbg04IJLHUYvjPHoRbLwz7B8pRcLi92FggkP2zA= -github.com/goravel/sqlserver v0.0.0-20250209093547-712da67f16de h1:OYgOvw4nMGmCibP6lAxeeoqjkv8dT4fS17okTk2UE7o= -github.com/goravel/sqlserver v0.0.0-20250209093547-712da67f16de/go.mod h1:lEyZza5IL8Y5zsMwB+MRLBjWK14jbAp2IEwwnHi9UmI= +github.com/goravel/mysql v0.0.0-20250210074846-5e7ae5bdeda5 h1:KNLNNS0c8x7+RNvexJxl6ePzU+D0UcoiDvUwsCl6kLw= +github.com/goravel/mysql v0.0.0-20250210074846-5e7ae5bdeda5/go.mod h1:CNNvjBIrBjv3MiTqfbAw3+xpB0EtT5Bpd+cQE994lBo= +github.com/goravel/postgres v0.0.2-0.20250210074923-55c799056495 h1:BjXMC4YB9aaun50hc6YJy+2zdIar+a4NzWOsIRztl04= +github.com/goravel/postgres v0.0.2-0.20250210074923-55c799056495/go.mod h1:rELvAG0qApR/T2Y/KAoQqZ0/4DqleHcFaYecD2j7d24= +github.com/goravel/sqlite v0.0.0-20250210074940-7a05cbb1dd50 h1:glK89GzKWXB4VCAgL2wBT9sZfSFHPhorgfq7w7BbCI4= +github.com/goravel/sqlite v0.0.0-20250210074940-7a05cbb1dd50/go.mod h1:NGDwJuAL4ds6cdLgvLzmBTIRanrtb8l88nyqdIdStKA= +github.com/goravel/sqlserver v0.0.0-20250210074958-b94e2314a481 h1:FtScgHirApvT4mp9iEFTTZrjiQdAUlnpHPzZOx/bX8A= +github.com/goravel/sqlserver v0.0.0-20250210074958-b94e2314a481/go.mod h1:SIexFbCn4FFLfLnKru/Khe3djQ5FGpcf6hq+paEBrmA= github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= From da0832eee9c26ca9d660eb459e4c43af8ab9eae1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=80=97=E5=AD=90?= Date: Mon, 10 Feb 2025 19:50:28 +0800 Subject: [PATCH 7/7] feat: optimize queue error (#874) * feat: optimize queue error * feat: optimize queue error * Update queue/worker.go Co-authored-by: Wenbo Han --------- Co-authored-by: Wenbo Han --- errors/list.go | 16 +++++++--------- queue/driver_async.go | 4 ++-- queue/worker.go | 18 +++++++++++++++++- 3 files changed, 26 insertions(+), 12 deletions(-) diff --git a/errors/list.go b/errors/list.go index 24c018391..10818247e 100644 --- a/errors/list.go +++ b/errors/list.go @@ -102,15 +102,13 @@ var ( OrmRecordNotFound = New("record not found") OrmDeletedAtColumnNotFound = New("deleted at column not found") - QueueDriverAsyncNoJobFound = New("no job found in %s queue") - QueueDriverSyncNotNeedRun = New("queue %s driver sync not need run") - QueueDriverNotSupported = New("unknown queue driver: %s") - QueueDriverInvalid = New("%s doesn't implement contracts/queue/driver") - QueueDuplicateJobSignature = New("job signature duplicate: %s, the names of Job and Listener cannot be duplicated") - QueueEmptyJobSignature = New("the Signature of job can't be empty") - QueueEmptyListenerSignature = New("the Signature of listener can't be empty") - QueueJobNotFound = New("job not found: %s") - QueueFailedToSaveFailedJob = New("failed to save failed job: %v") + QueueDriverNoJobFound = New("no job found in %s queue") + QueueDriverSyncNotNeedRun = New("queue %s driver sync not need run") + QueueDriverNotSupported = New("unknown queue driver: %s") + QueueDriverInvalid = New("%s doesn't implement contracts/queue/driver") + QueueDriverFailedToPop = New("failed to pop job from %s queue: %v") + QueueJobNotFound = New("job not found: %s") + QueueFailedToSaveFailedJob = New("failed to save failed job: %v") RouteDefaultDriverNotSet = New("please set default driver") RouteInvalidDriver = New("init %s route driver fail: route must be implement route.Route or func() (route.Route, error)") diff --git a/queue/driver_async.go b/queue/driver_async.go index aad334964..943fb44c2 100644 --- a/queue/driver_async.go +++ b/queue/driver_async.go @@ -58,7 +58,7 @@ func (r *Async) Later(delay time.Time, job contractsqueue.Job, args []any, queue func (r *Async) Pop(queue string) (contractsqueue.Job, []any, error) { ch, ok := asyncQueues.Load(queue) if !ok { - return nil, nil, errors.QueueDriverAsyncNoJobFound.Args(queue) + return nil, nil, errors.QueueDriverNoJobFound.Args(queue) } queueChan := ch.(chan contractsqueue.Jobs) @@ -66,7 +66,7 @@ func (r *Async) Pop(queue string) (contractsqueue.Job, []any, error) { case job := <-queueChan: return job.Job, job.Args, nil default: - return nil, nil, errors.QueueDriverAsyncNoJobFound.Args(queue) + return nil, nil, errors.QueueDriverNoJobFound.Args(queue) } } diff --git a/queue/worker.go b/queue/worker.go index 59a83b792..621374d9c 100644 --- a/queue/worker.go +++ b/queue/worker.go @@ -21,6 +21,8 @@ type Worker struct { job queue.JobRepository queue string wg sync.WaitGroup + currentDelay time.Duration + maxDelay time.Duration } func NewWorker(config queue.Config, concurrent int, connection string, queue string, job queue.JobRepository) *Worker { @@ -31,6 +33,8 @@ func NewWorker(config queue.Config, concurrent int, connection string, queue str job: job, queue: queue, failedJobChan: make(chan FailedJob, concurrent), + currentDelay: 1 * time.Second, + maxDelay: 32 * time.Second, } } @@ -56,10 +60,22 @@ func (r *Worker) Run() error { job, args, err := driver.Pop(r.queue) if err != nil { - time.Sleep(1 * time.Second) + if !errors.Is(err, errors.QueueDriverNoJobFound) { + LogFacade.Error(errors.QueueDriverFailedToPop.Args(r.queue, err)) + + r.currentDelay *= 2 + if r.currentDelay > r.maxDelay { + r.currentDelay = r.maxDelay + } + } + + time.Sleep(r.currentDelay) + continue } + r.currentDelay = 1 * time.Second + if err = r.job.Call(job.Signature(), args); err != nil { r.failedJobChan <- FailedJob{ UUID: uuid.New(),