1
0
mirror of https://github.com/ManyakRus/starter.git synced 2025-11-29 23:38:14 +02:00

сделал var NamingStrategy

This commit is contained in:
Nikitin Aleksandr
2024-05-03 14:16:12 +03:00
parent 332bca7f27
commit 33b13376bb
2 changed files with 61 additions and 52 deletions

View File

@@ -12,17 +12,11 @@ import (
"strings"
"time"
//"github.com/jackc/pgconn"
"os"
"sync"
//"time"
//"github.com/jmoiron/sqlx"
//_ "github.com/lib/pq"
"github.com/ManyakRus/starter/contextmain"
"github.com/ManyakRus/starter/micro"
"github.com/ManyakRus/starter/stopapp"
"os"
"sync"
"gorm.io/driver/postgres"
"gorm.io/gorm"
@@ -55,6 +49,9 @@ type SettingsINI struct {
DB_PASSWORD string
}
// NamingStrategy - структура для хранения настроек наименования таблиц
var NamingStrategy = schema.NamingStrategy{TablePrefix: Settings.DB_SCHEMA + "."}
// Connect_err - подключается к базе данных
func Connect() {
@@ -89,29 +86,24 @@ func Connect_WithApplicationName_err(ApplicationName string) error {
FillSettings()
}
//ctxMain := context.Background()
//ctxMain := contextmain.GetContext()
//ctx, cancel := context.WithTimeout(ctxMain, 5*time.Second)
//defer cancel()
// get the database connection URL.
//get the database connection URL.
dsn := GetDSN(ApplicationName)
//
conf := &gorm.Config{
Logger: gormlogger.Default.LogMode(gormlogger.Silent),
}
//conn := postgres.Open(dsn)
conf.NamingStrategy = NamingStrategy
dialect := postgres.New(postgres.Config{
//
config := postgres.Config{
DSN: dsn,
PreferSimpleProtocol: true, //для запуска мультизапросов
})
Conn, err = gorm.Open(dialect, conf)
}
//Conn, err = gorm.Open(conn, conf)
Conn.Config.NamingStrategy = schema.NamingStrategy{TablePrefix: Settings.DB_SCHEMA + "."}
//Conn.Config.Logger = gormlogger.Default.LogMode(gormlogger.Error)
//
dialect := postgres.New(config)
Conn, err = gorm.Open(dialect, conf)
if err == nil {
DB, err := Conn.DB()
@@ -271,7 +263,10 @@ func StartDB() {
// Start - делает соединение с БД, отключение и др.
func Start(ApplicationName string) {
Connect_WithApplicationName_err(ApplicationName)
err := Connect_WithApplicationName_err(ApplicationName)
if err != nil {
log.Panic("Postgres gorm Start() error: ", err)
}
stopapp.GetWaitGroup_Main().Add(1)
go WaitStop()
@@ -356,7 +351,10 @@ func GetConnection() *gorm.DB {
// GetConnection_WithApplicationName - возвращает соединение к нужной базе данных, с указанием имени приложения
func GetConnection_WithApplicationName(ApplicationName string) *gorm.DB {
if Conn == nil {
Connect_WithApplicationName_err(ApplicationName)
err := Connect_WithApplicationName_err(ApplicationName)
if err != nil {
log.Panic("GetConnection_WithApplicationName() error: ", err)
}
}
return Conn
@@ -550,3 +548,9 @@ func ReplaceTemporaryTableNamesToUnique(TextSQL string) string {
return Otvet
}
// SetSingularTableNames - меняет настройку "SingularTable" - надо ли НЕ переименовывать имя таблиц во вножественное число
// true = не переименовывать
func SetSingularTableNames(IsSingular bool) {
NamingStrategy.SingularTable = IsSingular
}

View File

@@ -2,6 +2,7 @@ package postgres_gorm
import (
"errors"
"sync"
"testing"
"time"
@@ -178,6 +179,7 @@ SELECT * FROM temp_TestRawMultipleSQL2
func TestRawMultipleSQL3(t *testing.T) {
config_main.LoadEnv()
wg := sync.WaitGroup{}
GetConnection()
defer CloseConnection()
@@ -203,16 +205,17 @@ SELECT * FROM temp_TestRawMultipleSQL2
t.Error("TestRawMultipleSQL3() RowsAffected = ", tx.RowsAffected)
}
wg.Done()
}
//запустим 100 потоков
for i := 0; i < 100; i++ {
stopapp.GetWaitGroup_Main().Add(1)
for i := 0; i < 10; i++ {
wg.Add(1)
go f(t)
stopapp.GetWaitGroup_Main().Done()
}
stopapp.GetWaitGroup_Main().Wait()
//micro.Pause(100)
wg.Wait()
t.Log("Прошло время: ", time.Since(TimeStart))
}
@@ -255,44 +258,30 @@ func TestReplaceSchema(t *testing.T) {
}
}
func TestReplaceTableNamesToUnique1(t *testing.T) {
func TestReplaceTemporaryTableNamesToUnique(t *testing.T) {
tests := []struct {
name string
input string
uuid string
expected string
name string
input string
}{
{
name: "No public schema",
input: "SELECT * FROM TableName",
uuid: "1234567890",
expected: "SELECT * FROM TableName",
name: "One temporary table",
input: "CREATE TEMPORARY TABLE temp_TableName (id int); SELECT * FROM temp_TableName",
},
{
name: "Public schema with no spaces",
input: "SELECT * FROM public.TableName",
uuid: "1234567890",
expected: "SELECT * FROM public.TableName",
name: "Multiple temporary tables",
input: "CREATE TEMPORARY TABLE temp_TableName1 (id int); CREATE TEMPORARY TABLE temp_TableName2 (name varchar); SELECT * FROM temp_TableName1; SELECT * FROM temp_TableName2",
},
{
name: "Public schema with spaces",
input: "SELECT * FROM public.Table Name",
uuid: "1234567890",
expected: "SELECT * FROM public.Table_1234567890 Name",
},
{
name: "Public schema with tabs",
input: "SELECT * FROM public.\tTableName\t",
uuid: "1234567890",
expected: "SELECT * FROM public.\tTableName_1234567890\t",
name: "Temporary table with different cases",
input: "CREATE TEMPORARY TABLE temp_tableName (id int); SELECT * FROM temp_tableName",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := ReplaceTemporaryTableNamesToUnique(tt.input)
if got != tt.expected {
t.Errorf("ReplaceTemporaryTableNamesToUnique() = %v, expected %v", got, tt.expected)
if got == tt.input {
t.Errorf("ReplaceTemporaryTableNamesToUnique() error: no changes")
}
})
}
@@ -331,3 +320,19 @@ func TestReplaceTemporaryTableNamesToUnique_MultipleTempTables(t *testing.T) {
t.Errorf("TestReplaceTemporaryTableNamesToUnique_OneTempTable() error: no changes")
}
}
func TestSetSingularTableNames(t *testing.T) {
// Test case 1: IsSingular is true
IsSingular := true
SetSingularTableNames(IsSingular)
if NamingStrategy.SingularTable != IsSingular {
t.Errorf("Expected SingularTable to be %v, but got %v", IsSingular, NamingStrategy.SingularTable)
}
// Test case 2: IsSingular is false
IsSingular = false
SetSingularTableNames(IsSingular)
if NamingStrategy.SingularTable != IsSingular {
t.Errorf("Expected SingularTable to be %v, but got %v", IsSingular, NamingStrategy.SingularTable)
}
}