From 66ee52c96af0525f0e678ec60281d4660bd4239e Mon Sep 17 00:00:00 2001 From: Lance Add <1196661499@qq.com> Date: Sat, 28 Sep 2024 12:06:22 +0800 Subject: [PATCH] fix(database/gdb): invalid order by statement generated when multiple order inputs (#3803) --- .../drivers/mysql/mysql_z_unit_model_test.go | 20 +++++++++++++++++++ .../mysql/testdata/fix_gdb_order_by.sql | 9 +++++++++ database/gdb/gdb_model_order_group.go | 2 +- 3 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 contrib/drivers/mysql/testdata/fix_gdb_order_by.sql diff --git a/contrib/drivers/mysql/mysql_z_unit_model_test.go b/contrib/drivers/mysql/mysql_z_unit_model_test.go index c2b5b5fb33d..126f2e2aa7b 100644 --- a/contrib/drivers/mysql/mysql_z_unit_model_test.go +++ b/contrib/drivers/mysql/mysql_z_unit_model_test.go @@ -12,6 +12,7 @@ import ( "database/sql" "fmt" "os" + "strings" "testing" "time" @@ -4818,3 +4819,22 @@ func Test_Model_Year_Date_Time_DateTime_Timestamp(t *testing.T) { t.AssertLT(one["timestamp"].GTime().Sub(now).Seconds(), 5) }) } + +func Test_OrderBy_Statement_Generated(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + array := gstr.SplitAndTrim(gtest.DataContent(`fix_gdb_order_by.sql`), ";") + for _, v := range array { + if _, err := db.Exec(ctx, v); err != nil { + gtest.Error(err) + } + } + defer dropTable(`employee`) + sqlArray, _ := gdb.CatchSQL(ctx, func(ctx context.Context) error { + g.DB("default").Ctx(ctx).Model("employee").Order("name asc", "age desc").All() + return nil + }) + rawSql := strings.ReplaceAll(sqlArray[len(sqlArray)-1], " ", "") + expectSql := strings.ReplaceAll("SELECT * FROM `employee` ORDER BY `name` asc, `age` desc", " ", "") + t.Assert(rawSql, expectSql) + }) +} diff --git a/contrib/drivers/mysql/testdata/fix_gdb_order_by.sql b/contrib/drivers/mysql/testdata/fix_gdb_order_by.sql new file mode 100644 index 00000000000..2ba712641fa --- /dev/null +++ b/contrib/drivers/mysql/testdata/fix_gdb_order_by.sql @@ -0,0 +1,9 @@ +CREATE TABLE IF NOT EXISTS `employee` +( + id BIGINT AUTO_INCREMENT PRIMARY KEY, + name VARCHAR(255) NOT NULL, + age INT NOT NULL +); + +INSERT INTO employee(name, age) VALUES ('John', 30); +INSERT INTO employee(name, age) VALUES ('Mary', 28); \ No newline at end of file diff --git a/database/gdb/gdb_model_order_group.go b/database/gdb/gdb_model_order_group.go index 9f09dabea59..4b1e5926de5 100644 --- a/database/gdb/gdb_model_order_group.go +++ b/database/gdb/gdb_model_order_group.go @@ -36,7 +36,7 @@ func (m *Model) Order(orderBy ...interface{}) *Model { return model } } - model.orderBy += model.db.GetCore().QuoteString(gstr.JoinAny(orderBy, " ")) + model.orderBy += model.db.GetCore().QuoteString(gstr.JoinAny(orderBy, ", ")) return model }