change code for new version

This commit is contained in:
namhq1989 2022-08-24 15:45:16 +07:00
parent f4da943b5d
commit 2e42b0a20a
6 changed files with 2251 additions and 40 deletions

9
go.mod
View File

@ -4,7 +4,10 @@ go 1.16
require (
github.com/Masterminds/squirrel v1.5.0
github.com/jmoiron/sqlx v1.3.4
github.com/lib/pq v1.10.2
github.com/logrusorgru/aurora v2.0.3+incompatible
github.com/Selly-Modules/logger v0.0.2-0.20220824032830-595811dd1f20
github.com/golang-migrate/migrate/v4 v4.15.2
github.com/jackc/pgx/v4 v4.17.0
github.com/volatiletech/sqlboiler/v4 v4.12.0
golang.org/x/sys v0.0.0-20220823224334-20c2bfdbfe24 // indirect
golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f // indirect
)

2091
go.sum

File diff suppressed because it is too large Load Diff

55
migration.go Normal file
View File

@ -0,0 +1,55 @@
package postgresql
import (
"database/sql"
"fmt"
"github.com/Selly-Modules/logger"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file"
"os"
)
func runMigration(db *sql.DB, server string) {
// init migrate data
driver, _ := postgres.WithInstance(db, &postgres.Config{})
m, err := migrate.NewWithDatabaseInstance(
fmt.Sprintf("file:///%s", getMigrationDirectoryPath(server)),
"postgres",
driver,
)
// up
if err == nil {
if err = m.Up(); err != nil && err.Error() != "no change" {
logger.Error("run migration", logger.LogData{
Source: "runMigration",
Message: err.Error(),
Data: nil,
})
fmt.Println("run schema migration error:", err.Error())
}
fmt.Printf("⚡️[postgres]: done migration \n")
}
}
func getMigrationDirectoryPath(server string) string {
migrationDir := fmt.Sprintf("/external/postgresql/%s/migrations/sql", server)
dirname, err := os.Getwd()
if err != nil {
panic(err)
}
// Check path existed
path := dirname + migrationDir
if _, err = os.Stat(path); os.IsNotExist(err) {
// Create if not existed
err = os.Mkdir(path, 0755)
if err != nil {
panic(err)
}
}
return path
}

10
null.go Normal file
View File

@ -0,0 +1,10 @@
package postgresql
import "github.com/volatiletech/null/v8"
func NewValidNullString(val string) null.String {
return null.String{
String: val,
Valid: true,
}
}

View File

@ -1,50 +1,78 @@
package postgresql
import (
"database/sql"
"fmt"
"log"
"github.com/Selly-Modules/logger"
"time"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq" // For postgres dialect
"github.com/logrusorgru/aurora"
_ "github.com/jackc/pgx/v4/stdlib"
"github.com/volatiletech/sqlboiler/v4/boil"
)
var (
sqlxClient *sqlx.DB
)
type Config struct {
Host string
Port int
User string
Password string
DBName string
SSLMode string
IsDebug bool
MaxOpenConnections int
MaxIdleConnections int
ConnectionLifetime time.Duration
}
// Connect to postgresql database
func Connect(host, user, password, dbname, port, sslmode string) error {
// Connect string
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=%s TimeZone=UTC",
host, user, password, dbname, port, sslmode,
)
var db *sql.DB
// TODO: write case for SSL mode
// Connect ...
func Connect(cfg Config, server string) {
uri := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=%s",
cfg.Host, cfg.Port, cfg.User, cfg.Password, cfg.DBName, cfg.SSLMode)
db, err := sqlx.Connect("postgres", dsn)
// connect
c, err := sql.Open("pgx", uri)
if err != nil {
log.Fatalln(err)
panic(err)
}
fmt.Println(aurora.Green("*** CONNECTED TO POSTGRESQL - SQLX: " + dsn))
// ping
if err = c.Ping(); err != nil {
logger.Error("pgx ping", logger.LogData{
Source: "Connect",
Message: err.Error(),
Data: cfg,
})
panic(err)
}
// Config connection pool
sqlDB := db.DB
sqlDB.SetMaxOpenConns(100)
sqlDB.SetMaxIdleConns(20)
sqlDB.SetConnMaxLifetime(time.Minute * 5)
// assign
db = c
// Assign client
sqlxClient = db
// config
if cfg.MaxOpenConnections == 0 {
cfg.MaxOpenConnections = 25
}
if cfg.MaxIdleConnections == 0 {
cfg.MaxIdleConnections = 25
}
if cfg.ConnectionLifetime == 0 {
cfg.ConnectionLifetime = 5 * time.Minute
}
db.SetMaxOpenConns(cfg.MaxOpenConnections)
db.SetMaxIdleConns(cfg.MaxIdleConnections)
db.SetConnMaxLifetime(cfg.ConnectionLifetime)
return nil
// run migration
runMigration(db, server)
// debug mode
boil.DebugMode = cfg.IsDebug
fmt.Printf("⚡️[postgres]: connected to %s:%d \n", cfg.Host, cfg.Port)
}
// GetSqlxInstance ...
func GetSqlxInstance() *sqlx.DB {
return sqlxClient
// GetDB ...
func GetDB() *sql.DB {
return db
}

38
string.go Normal file
View File

@ -0,0 +1,38 @@
package postgresql
import (
"golang.org/x/text/runes"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
"regexp"
"strings"
"unicode"
)
// RemoveDiacritics ...
func RemoveDiacritics(s string) string {
if s != "" {
s = strings.ToLower(s)
s = replaceStringWithRegex(s, `đ`, "d")
t := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
result, _, _ := transform.String(t, s)
result = replaceStringWithRegex(result, `[^a-zA-Z0-9\s]`, "")
return result
}
return ""
}
// replaceStringWithRegex ...
func replaceStringWithRegex(src string, regex string, replaceText string) string {
reg := regexp.MustCompile(regex)
return reg.ReplaceAllString(src, replaceText)
}
// TransformKeywordToSearchString ...
func TransformKeywordToSearchString(keyword string) string {
s := strings.Trim(keyword, " ")
s = RemoveDiacritics(s)
s = strings.ReplaceAll(s, " ", "&")
return s + ":*" // For prefix search
}