Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

convert query sql to gorm #24

Open
wants to merge 2 commits into
base: scott/sample-gorm
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,4 +204,4 @@ Don't confuse the project level `/src` directory with the `/src` directory Go us

## Notes

A more opinionated project template with sample/reusable configs, scripts and code is a WIP.
A more opinionated project template with sample/reusable configs, scripts and code is a WIP.
20 changes: 19 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,24 @@ require (
gorm.io/gorm v1.25.1
)

require (
github.com/fsnotify/fsnotify v1.5.4 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/magiconair/properties v1.8.6 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/spf13/afero v1.8.2 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/subosito/gotenv v1.4.1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)

require (
github.com/bytedance/sonic v1.8.0 // indirect
github.com/caarlos0/env v3.5.0+incompatible
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
Expand All @@ -26,9 +42,10 @@ require (
github.com/klauspost/cpuid/v2 v2.0.9 // indirect
github.com/leodido/go-urn v1.2.1 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.0.6 // indirect
github.com/spf13/viper v1.13.0
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.9 // indirect
golang.org/x/arch v0.0.0-20210923205945-b76863e36670 // indirect
Expand All @@ -38,4 +55,5 @@ require (
golang.org/x/text v0.7.0 // indirect
google.golang.org/protobuf v1.28.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect

)
93 changes: 93 additions & 0 deletions internal/sqlclient/sqlclient.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package sqlclient

import (
"errors"
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"log"
)

const (
MYSQL = "mysql"
)

type ISqlClientConn interface {
GetDB() *gorm.DB
GetDriver() string
}

type SqlConfig struct {
Driver string
Host string
Port int
Database string
Username string
Password string
Timeout int
DialTimeout int
ReadTimeout int
WriteTimeout int
PoolSize int
MaxIdleConns int
MaxOpenConns int
}

type SqlClientConn struct {
SqlConfig
DB *gorm.DB
}

func NewSqlClient(config SqlConfig) ISqlClientConn {
client := &SqlClientConn{}
client.SqlConfig = config
if err := client.Connect(); err != nil {
log.Fatal(err)
return nil
}
//ping to check connection in gorm
sqlDB, err := client.DB.DB()
if err != nil {
log.Fatal(err)
return nil
}
if err := sqlDB.Ping(); err != nil {
log.Fatal(err)
return nil
}

return client
}

func (c *SqlClientConn) Connect() error {
switch c.Driver {
case MYSQL:
//username:password@protocol(address)/dbname?param=value
connectionString := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?parseTime=true&timeout=%ds", c.Username, c.Password, c.Host, c.Port, c.Database, c.Timeout)
db, err := gorm.Open(mysql.Open(connectionString), &gorm.Config{})
if err != nil {
log.Fatal(err)
return err
}
sqlDB, err := db.DB()
if err != nil {
log.Fatal(err)
return err
}
sqlDB.SetMaxIdleConns(c.MaxIdleConns)
sqlDB.SetMaxOpenConns(c.MaxOpenConns)
c.DB = db
return nil
default:
log.Fatal("driver is missing")
return errors.New("driver is missing")
}
}

func (c *SqlClientConn) GetDB() *gorm.DB {
return c.DB
}

func (c *SqlClientConn) GetDriver() string {
return c.Driver
}
96 changes: 96 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package main

import (
"errors"
"github.com/EngineerProOrg/BE-K01/internal/sqlclient"
"github.com/EngineerProOrg/BE-K01/pkg/repository"
"github.com/caarlos0/env"
"github.com/spf13/viper"
"gorm.io/gorm"
"log"
"time"
)

type Config struct {
Dir string `env:"CONFIG_DIR" envDefault:"configs/config.json"`
DB bool
}

var config Config
var sqlClient sqlclient.ISqlClientConn

func init() {
loc, err := time.LoadLocation("Asia/Ho_Chi_Minh")
if err != nil {
log.Fatal(err)
}
time.Local = loc

if err := env.Parse(&config); err != nil {
log.Fatal(err)
}
viper.SetConfigFile(config.Dir)
if err := viper.ReadInConfig(); err != nil {
log.Println(err.Error())
panic(err)
}

cfg := Config{
Dir: config.Dir,
DB: viper.GetBool(`main.db`),
}

if cfg.DB {
sqlClientConfig := sqlclient.SqlConfig{
Driver: "mysql",
Host: viper.GetString(`db.host`),
Database: viper.GetString(`db.database`),
Username: viper.GetString(`db.username`),
Password: viper.GetString(`db.password`),
Port: viper.GetInt(`db.port`),
DialTimeout: 20,
ReadTimeout: 30,
WriteTimeout: 30,
Timeout: 30,
PoolSize: 10,
MaxIdleConns: 10,
MaxOpenConns: 10,
}
sqlClient = sqlclient.NewSqlClient(sqlClientConfig)
if sqlClient == nil {
panic(errors.New("sqlClient is nil"))
} else {
CreateOrUpdateGradeView(sqlClient.GetDB())
}
}

}

func CreateOrUpdateGradeView(db *gorm.DB) error {
query := `
CREATE OR REPLACE VIEW Grade AS
SELECT e.class_id, e.stud_id,
CASE e.grade
WHEN 'A' THEN 10
WHEN 'B' THEN 8
WHEN 'C' THEN 6
WHEN 'D' THEN 4
WHEN 'E' THEN 2
WHEN 'F' THEN 0
ELSE 0
END
AS Grade
FROM enrolls e
`
err := db.Exec(query).Error
return err
}

func main() {
stuRepo := repository.NewStudentRepository(sqlClient.GetDB())
courses, err := stuRepo.GetAvgGradeOfCourse()
if err != nil {
log.Fatal(err)
}
log.Println(courses)
}
51 changes: 51 additions & 0 deletions pkg/repository/course.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package repository

import (
"github.com/EngineerProOrg/BE-K01/pkg/types"
"gorm.io/gorm"
)

type CourseRepository interface {
GetCourseWithProfessorTeaching() ([]string, error)
GetCourseWithStudentStudying() ([]string, error)
}

func NewCourseRepository(db *gorm.DB) CourseRepository {
return &CourseRepo{
db: db,
}
}

type CourseRepo struct {
db *gorm.DB
}

func (c CourseRepo) GetCourseWithStudentStudying() ([]string, error) {
var courses []string
c.db.Model(&types.Course{}).
Select("DISTINCT(course_name)").
Joins("JOIN Class ON Course.course_id = Class.course_id").
Joins("JOIN Enroll ON Class.class_id = Enroll.class_id").
Scan(&courses)
if err := c.db.Error; err != nil {
return nil, err
}
return courses, nil
}

type a struct {
s int
}

func (c CourseRepo) GetCourseWithProfessorTeaching() ([]string, error) {
var courses []string
c.db.Model(&types.Course{}).
Select("DISTINCT(course_name)").
Joins("JOIN classes ON courses.course_id = classes.course_id").
Scan(&courses)

if err := c.db.Error; err != nil {
return nil, err
}
return courses, nil
}
25 changes: 0 additions & 25 deletions pkg/repository/manager.go

This file was deleted.

50 changes: 50 additions & 0 deletions pkg/repository/professor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package repository

import (
"github.com/EngineerProOrg/BE-K01/pkg/types"
"gorm.io/gorm"
)

type ProfessorRepository interface {
GetProfessorStudentClassNames() ([]QueryResult, error)
}

type ProfessorRepoDb struct {
db *gorm.DB
}

type ProfessorStudentClass struct {
ProfName string `gorm:"column:professors Name"`
StudentName string `gorm:"column:Student Name"`
ClassName string `gorm:"column:classes Name"`
}

type QueryResult struct {
ProfessorsName string `gorm:"column:Professor Name"`
StudentName string `gorm:"column:Student Name"`
ClassName string `gorm:"column:Class Name"`
}

func (p ProfessorRepoDb) GetProfessorStudentClassNames() ([]QueryResult, error) {
var result []QueryResult

p.db.Model(&types.Professor{}).
Select("CONCAT(professors.prof_fname, ' ', professors.prof_lname) AS 'Professor Name'",
"CONCAT(students.stud_fname, ' ', students.stud_lname) AS 'Student Name'",
"classes.class_name AS 'Class Name'").
Joins("JOIN classes ON professors.prof_id = classes.prof_id").
Joins("JOIN enrolls ON classes.class_id = enrolls.class_id").
Joins("JOIN students ON enrolls.stud_id = students.stud_id").
Scan(&result)

if err := p.db.Error; err != nil {
return nil, err
}
return result, nil
}

func NewProfessorRepository(db *gorm.DB) ProfessorRepository {
return &ProfessorRepoDb{
db: db,
}
}
Loading