Skip to content

Commit

Permalink
Merge branch 'master' into kkumar-gcc/define-errors
Browse files Browse the repository at this point in the history
  • Loading branch information
kkumar-gcc authored Oct 5, 2024
2 parents 10e3e26 + fe51fc9 commit c2381bf
Show file tree
Hide file tree
Showing 40 changed files with 1,424 additions and 451 deletions.
2 changes: 2 additions & 0 deletions console/application_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ func TestFlagsToCliFlags(t *testing.T) {

// Convert command flags to CLI flags
cliFlags := flagsToCliFlags(flags)
assert.NotNil(t, cliFlags)

// Assert that the number of CLI flags matches the number of command flags
assert.Equal(t, len(cliFlags), len(flags))
Expand All @@ -49,6 +50,7 @@ func TestFlagsToCliFlags(t *testing.T) {
case command.FlagTypeBool:
boolFlag := flag.(*command.BoolFlag)
cliBoolFlag := cliFlags[i].(*cli.BoolFlag)

assert.Equal(t, boolFlag.Name, cliBoolFlag.Name)
assert.Equal(t, boolFlag.Aliases, cliBoolFlag.Aliases)
assert.Equal(t, boolFlag.Usage, cliBoolFlag.Usage)
Expand Down
2 changes: 2 additions & 0 deletions contracts/database/migration/grammar.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ type Grammar interface {
CompileCreate(blueprint Blueprint, query orm.Query) string
// CompileDropIfExists Compile a drop table (if exists) command.
CompileDropIfExists(blueprint Blueprint) string
// CompileTables Compile the query to determine the tables.
CompileTables(database string) string
// GetAttributeCommands Get the commands for the schema build.
GetAttributeCommands() []string
// GetModifiers Get the column modifiers.
Expand Down
48 changes: 26 additions & 22 deletions contracts/database/migration/repository.go
Original file line number Diff line number Diff line change
@@ -1,26 +1,30 @@
package migration

type File struct {
ID uint
Migration string
Batch int
}

type Repository interface {
//// CreateRepository Create the migration repository data store.
//CreateRepository()
//// Delete Remove a migration from the log.
//Delete(migration string)
//// DeleteRepository Delete the migration repository data store.
//DeleteRepository()
//// GetLast Get the last migration batch.
//GetLast()
//// GetMigrationBatches Get the completed migrations with their batch numbers.
//GetMigrationBatches()
//// GetMigrations Get the list of migrations.
//GetMigrations(steps int)
//// GetMigrationsByBatch Get the list of the migrations by batch.
//GetMigrationsByBatch(batch int)
//// GetNextBatchNumber Get the next migration batch number.
//GetNextBatchNumber()
//// GetRan Get the completed migrations.
//GetRan()
//// Log that a migration was run.
//Log(file, batch string)
//// RepositoryExists Determine if the migration repository exists.
//RepositoryExists()
// CreateRepository Create the migration repository data store.
CreateRepository() error
// Delete Remove a migration from the log.
Delete(migration string) error
// DeleteRepository Delete the migration repository data store.
DeleteRepository() error
// GetLast Get the last migration batch.
GetLast() ([]File, error)
// GetMigrations Get the list of migrations.
GetMigrations(steps int) ([]File, error)
// GetMigrationsByBatch Get the list of the migrations by batch.
GetMigrationsByBatch(batch int) ([]File, error)
// GetNextBatchNumber Get the next migration batch number.
GetNextBatchNumber() (int, error)
// GetRan Get the completed migrations.
GetRan() ([]string, error)
// Log that a migration was run.
Log(file string, batch int) error
// RepositoryExists Determine if the migration repository exists.
RepositoryExists() bool
}
21 changes: 17 additions & 4 deletions contracts/database/migration/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@ package migration

type Schema interface {
// Create a new table on the schema.
Create(table string, callback func(table Blueprint))
Create(table string, callback func(table Blueprint)) error
// Connection Get the connection for the schema.
Connection(name string) Schema
// DropIfExists Drop a table from the schema if exists.
DropIfExists(table string)
DropIfExists(table string) error
// GetTables Get the tables that belong to the database.
GetTables() ([]Table, error)
// HasTable Determine if the given table exists.
HasTable(table string) bool
// Register migrations.
Register([]Migration)
// Sql Execute a sql directly.
Expand All @@ -18,14 +22,17 @@ type Schema interface {
type Migration interface {
// Signature Get the migration signature.
Signature() string
// Connection Get the connection for the migration.
Connection() string
// Up Run the migrations.
Up()
// Down Reverse the migrations.
Down()
}

type Connection interface {
// Connection Get the connection for the migration.
Connection() string
}

type Command struct {
Algorithm string
Column ColumnDefinition
Expand All @@ -40,3 +47,9 @@ type Command struct {
References []string
Value string
}

type Table struct {
Comment string
Name string
Size int
}
6 changes: 5 additions & 1 deletion database/gorm/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ func (e *Event) IsDirty(columns ...string) bool {
}

func (e *Event) Query() orm.Query {
return NewQuery(e.query.ctx, e.query.config, e.query.fullConfig, e.query.instance.Session(&gorm.Session{NewDB: true}), nil)
return NewQuery(e.query.ctx, e.query.config, e.query.fullConfig, e.query.instance.Session(&gorm.Session{NewDB: true}), e.query.log, nil)
}

func (e *Event) SetAttribute(key string, value any) {
Expand All @@ -101,6 +101,10 @@ func (e *Event) SetAttribute(key string, value any) {
}

destOfMap := e.getDestOfMap()
if destOfMap == nil {
return
}

destOfMap[e.toDBColumnName(key)] = value
e.destOfMap = destOfMap

Expand Down
26 changes: 15 additions & 11 deletions database/gorm/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"github.com/goravel/framework/contracts/config"
contractsdatabase "github.com/goravel/framework/contracts/database"
contractsorm "github.com/goravel/framework/contracts/database/orm"
"github.com/goravel/framework/contracts/log"
"github.com/goravel/framework/database/db"
"github.com/goravel/framework/database/gorm/hints"
"github.com/goravel/framework/database/orm"
Expand All @@ -29,15 +30,17 @@ type Query struct {
ctx context.Context
fullConfig contractsdatabase.FullConfig
instance *gormio.DB
log log.Log
queries map[string]*Query
}

func NewQuery(ctx context.Context, config config.Config, fullConfig contractsdatabase.FullConfig, db *gormio.DB, conditions *Conditions) *Query {
func NewQuery(ctx context.Context, config config.Config, fullConfig contractsdatabase.FullConfig, db *gormio.DB, log log.Log, conditions *Conditions) *Query {
queryImpl := &Query{
config: config,
ctx: ctx,
fullConfig: fullConfig,
instance: db,
log: log,
queries: make(map[string]*Query),
}

Expand All @@ -48,7 +51,7 @@ func NewQuery(ctx context.Context, config config.Config, fullConfig contractsdat
return queryImpl
}

func BuildQuery(ctx context.Context, config config.Config, connection string) (*Query, error) {
func BuildQuery(ctx context.Context, config config.Config, connection string, log log.Log) (*Query, error) {
configBuilder := db.NewConfigBuilder(config, connection)
writeConfigs := configBuilder.Writes()
if len(writeConfigs) == 0 {
Expand All @@ -60,7 +63,7 @@ func BuildQuery(ctx context.Context, config config.Config, connection string) (*
return nil, err
}

return NewQuery(ctx, config, writeConfigs[0], gorm, nil), nil
return NewQuery(ctx, config, writeConfigs[0], gorm, log, nil), nil
}

func (r *Query) Association(association string) contractsorm.Association {
Expand Down Expand Up @@ -727,11 +730,11 @@ func (r *Query) Table(name string, args ...any) contractsorm.Query {
}

func (r *Query) ToSql() contractsorm.ToSql {
return NewToSql(r.setConditions(r.conditions), false)
return NewToSql(r.setConditions(r.conditions), r.log, false)
}

func (r *Query) ToRawSql() contractsorm.ToSql {
return NewToSql(r.setConditions(r.conditions), true)
return NewToSql(r.setConditions(r.conditions), r.log, true)
}

func (r *Query) Update(column any, value ...any) (*contractsorm.Result, error) {
Expand Down Expand Up @@ -984,7 +987,10 @@ func (r *Query) buildModel() *Query {

query, err := r.refreshConnection(r.conditions.model)
if err != nil {
return nil
query = r.new(r.instance.Session(&gormio.Session{}))
_ = query.instance.AddError(err)

return query
}

return query.new(query.instance.Model(r.conditions.model))
Expand Down Expand Up @@ -1122,7 +1128,7 @@ func (r *Query) buildWith(db *gormio.DB) *gormio.DB {
if arg, ok := item.args[0].(func(contractsorm.Query) contractsorm.Query); ok {
newArgs := []any{
func(tx *gormio.DB) *gormio.DB {
queryImpl := NewQuery(r.ctx, r.config, r.fullConfig, tx, nil)
queryImpl := NewQuery(r.ctx, r.config, r.fullConfig, tx, r.log, nil)
query := arg(queryImpl)
queryImpl = query.(*Query)
queryImpl = queryImpl.buildConditions()
Expand Down Expand Up @@ -1256,9 +1262,7 @@ func (r *Query) event(event contractsorm.EventType, model, dest any) error {
}

func (r *Query) new(db *gormio.DB) *Query {
query := NewQuery(r.ctx, r.config, r.fullConfig, db, &r.conditions)

return query
return NewQuery(r.ctx, r.config, r.fullConfig, db, r.log, &r.conditions)
}

func (r *Query) omitCreate(value any) error {
Expand Down Expand Up @@ -1323,7 +1327,7 @@ func (r *Query) refreshConnection(model any) (*Query, error) {
query, ok := r.queries[connection]
if !ok {
var err error
query, err = BuildQuery(r.ctx, r.config, connection)
query, err = BuildQuery(r.ctx, r.config, connection, r.log)
if err != nil {
return nil, err
}
Expand Down
15 changes: 15 additions & 0 deletions database/gorm/query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2545,6 +2545,21 @@ func (s *QueryTestSuite) TestLoadMissing() {
}
}

func (s *QueryTestSuite) TestModel() {
for driver, query := range s.queries {
s.Run(driver.String(), func() {
// model is valid
user := User{Name: "model_user"}
s.Nil(query.Query().Model(&User{}).Create(&user))
s.True(user.ID > 0)

// model is invalid
user1 := User{Name: "model_user"}
s.EqualError(query.Query().Model("users").Create(&user1), "invalid model")
})
}
}

func (s *QueryTestSuite) TestRaw() {
for driver, query := range s.queries {
s.Run(driver.String(), func() {
Expand Down
23 changes: 6 additions & 17 deletions database/gorm/test_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,6 @@ import (
supportdocker "github.com/goravel/framework/support/docker"
)

// Define different test model, to improve the local testing speed.
// The minimum model only initials one Sqlite and two Postgres,
// and the normal model initials one Mysql, two Postgres, one Sqlite and one Sqlserver.
const (
TestModelMinimum = iota
TestModelNormal

// Switch this value to control the test model.
TestModel = TestModelNormal
)

type TestTable int

const (
Expand Down Expand Up @@ -64,7 +53,7 @@ type TestQueries struct {
}

func NewTestQueries() *TestQueries {
if TestModel == TestModelMinimum {
if supportdocker.TestModel == supportdocker.TestModelMinimum {
return &TestQueries{
sqliteDockers: supportdocker.Sqlites(2),
postgresDockers: supportdocker.Postgreses(2),
Expand Down Expand Up @@ -111,7 +100,7 @@ func (r *TestQueries) QueriesOfReadWrite() map[contractsdatabase.Driver]map[stri
panic(err)
}

if TestModel == TestModelMinimum {
if supportdocker.TestModel == supportdocker.TestModelMinimum {
return map[contractsdatabase.Driver]map[string]orm.Query{
contractsdatabase.DriverPostgres: {
"mix": postgresQuery,
Expand Down Expand Up @@ -197,7 +186,7 @@ func (r *TestQueries) queries(withPrefixAndSingular bool) map[contractsdatabase.
contractsdatabase.DriverSqlite: r.sqliteDockers[0],
}

if TestModel != TestModelMinimum {
if supportdocker.TestModel != supportdocker.TestModelMinimum {
driverToDocker[contractsdatabase.DriverMysql] = r.mysqlDockers[0]
driverToDocker[contractsdatabase.DriverSqlserver] = r.sqlserverDockers[0]
}
Expand Down Expand Up @@ -234,10 +223,10 @@ func NewTestQuery(docker testing.DatabaseDriver, withPrefixAndSingular ...bool)
)
if len(withPrefixAndSingular) > 0 && withPrefixAndSingular[0] {
mockDriver.WithPrefixAndSingular()
query, err = BuildQuery(testContext, mockConfig, docker.Driver().String())
query, err = BuildQuery(testContext, mockConfig, docker.Driver().String(), nil)
} else {
mockDriver.Common()
query, err = BuildQuery(testContext, mockConfig, docker.Driver().String())
query, err = BuildQuery(testContext, mockConfig, docker.Driver().String(), nil)
}

if err != nil {
Expand Down Expand Up @@ -276,7 +265,7 @@ func (r *TestQuery) QueryOfReadWrite(config TestReadWriteConfig) (orm.Query, err
mockDriver := getMockDriver(r.Docker(), mockConfig, r.Docker().Driver().String())
mockDriver.ReadWrite(config)

return BuildQuery(testContext, mockConfig, r.docker.Driver().String())
return BuildQuery(testContext, mockConfig, r.docker.Driver().String(), nil)
}

func getMockDriver(docker testing.DatabaseDriver, mockConfig *mocksconfig.Config, connection string) testMockDriver {
Expand Down
9 changes: 8 additions & 1 deletion database/gorm/to_sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,19 @@ package gorm

import (
"gorm.io/gorm"

"github.com/goravel/framework/contracts/log"
)

type ToSql struct {
log log.Log
query *Query
raw bool
}

func NewToSql(query *Query, raw bool) *ToSql {
func NewToSql(query *Query, log log.Log, raw bool) *ToSql {
return &ToSql{
log: log,
query: query,
raw: raw,
}
Expand Down Expand Up @@ -105,6 +109,9 @@ func (r *ToSql) Update(column any, value ...any) string {

func (r *ToSql) sql(db *gorm.DB) string {
sql := db.Statement.SQL.String()
if db.Statement.Error != nil {
r.log.Errorf("failed to get sql: %v", db.Statement.Error)
}
if !r.raw {
return sql
}
Expand Down
Loading

0 comments on commit c2381bf

Please sign in to comment.