From 6525b3efa665edbb406202288ce283474e2199f2 Mon Sep 17 00:00:00 2001 From: Yun Date: Sun, 7 Jun 2026 15:20:10 +0800 Subject: [PATCH] =?UTF-8?q?=E9=BB=98=E8=AE=A4=E5=8D=95=E6=95=B0=E8=A1=A8?= =?UTF-8?q?=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- mysqlx_test.go | 22 +++++++++++++++++++++- options.go | 10 ++++++++-- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/mysqlx_test.go b/mysqlx_test.go index c8055c4..04f20b0 100644 --- a/mysqlx_test.go +++ b/mysqlx_test.go @@ -15,12 +15,14 @@ type testModel struct { } func TestNewWithCustomDialector(t *testing.T) { - sqlDB, _, err := sqlmock.New() + sqlDB, mock, err := sqlmock.New() if err != nil { t.Fatalf("failed to create sqlmock: %v", err) } defer sqlDB.Close() + mock.ExpectQuery("SELECT VERSION()").WillReturnRows(sqlmock.NewRows([]string{"VERSION()"}).AddRow("5.7.0")) + client, err := NewDB( WithDialector(drivermysql.New(drivermysql.Config{Conn: sqlDB})), WithLogger(logger.Default.LogMode(logger.Silent)), @@ -34,6 +36,9 @@ func TestNewWithCustomDialector(t *testing.T) { if client.DB() == nil { t.Fatal("expected non-nil DB") } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("sqlmock expectations were not met: %v", err) + } } func TestBuildDSNWithExpandedConfig(t *testing.T) { @@ -54,6 +59,21 @@ func TestBuildDSNWithExpandedConfig(t *testing.T) { } } +func TestDefaultConfigUsesSingularTable(t *testing.T) { + cfg := defaultConfig() + if !cfg.NamingStrategy.SingularTable { + t.Fatal("expected default naming strategy to use singular table names") + } +} + +func TestWithSingularTableOption(t *testing.T) { + cfg := defaultConfig() + WithSingularTable(false)(cfg) + if cfg.NamingStrategy.SingularTable { + t.Fatal("expected naming strategy singular table to be disabled") + } +} + func TestNewWithoutDSNOrDialector(t *testing.T) { _, err := NewDB() if err == nil { diff --git a/options.go b/options.go index 3d2eb84..62711e5 100644 --- a/options.go +++ b/options.go @@ -43,13 +43,12 @@ type config struct { } type DSN struct { - } func defaultConfig() *config { return &config{ Logger: logger.Default, - NamingStrategy: schema.NamingStrategy{}, + NamingStrategy: schema.NamingStrategy{SingularTable: true}, MaxIdleConns: 10, MaxOpenConns: 100, } @@ -308,6 +307,13 @@ func WithNamingStrategy(strategy schema.NamingStrategy) Option { } } +// WithSingularTable enables or disables singular table names for gorm models. +func WithSingularTable(singular bool) Option { + return func(cfg *config) { + cfg.NamingStrategy.SingularTable = singular + } +} + // WithConnectionPool configures database connection pooling. func WithConnectionPool(maxIdleConns, maxOpenConns int, maxIdleTime, maxLifetime time.Duration) Option { return func(cfg *config) {