Skip to content

Commit

Permalink
Change regex pattern and add logging
Browse files Browse the repository at this point in the history
  • Loading branch information
bayucandra committed Nov 16, 2019
1 parent e74499f commit 8649fe9
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 13 deletions.
8 changes: 6 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ import (

func main() {

log.SetFlags(log.LstdFlags | log.Lshortfile)
if ( os.Getenv("GO_ENV") == "development" ) {
log.SetFlags(log.LstdFlags | log.Lshortfile)
}

err := loadEnv(".env")

Expand All @@ -27,8 +29,10 @@ func main() {
log.Fatal(err)
}

log.Println(os.Getenv("GO_SEED_SOURCE_PATH"))

db.Init()
files, err := file_operations.DirParse(os.Getenv("SOURCE_PATH"))
files, err := file_operations.DirParse(os.Getenv("GO_SEED_SOURCE_PATH"))
sql_operations.SeedAll(files)

_ = db.DBConn.Close()
Expand Down
25 changes: 14 additions & 11 deletions seed-operations/sql-insert.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,19 @@ import (

func SeedAll( filePaths []string ) {
for _, val := range filePaths {
_ = csvParse(val)
}
}
r := regexp.MustCompile(`.*/(.*)`)
fileName := r.FindStringSubmatch(val)[1]

func csvParse( filePath string ) (err error) {
r = regexp.MustCompile(`^\d{0,3}\.\d{0,3}_(.*)\.((?i)csv)`)
tableName := r.FindStringSubmatch(fileName)[1]

r := regexp.MustCompile(`.*/(.*)`)
fileName := r.FindStringSubmatch(filePath)[1]
log.Println("\n\n\n===== Seeding Table:", tableName, "=========")

r = regexp.MustCompile(`^\d{0,3}\.\d{0,3}_(.*)\.[a-z A-Z]{0,}`)
tableName := r.FindStringSubmatch(fileName)[1]
_ = csvParse(val, tableName)
}
}

func csvParse( filePath string, tableName string ) (err error) {

f, err := os.OpenFile(filePath, os.O_RDONLY, os.ModePerm)
if err != nil {
Expand Down Expand Up @@ -90,20 +92,21 @@ func sqlInsert( cols []string, record []string, table string ) (err error){
valStr += fmt.Sprintf("%v )", val)
}
}

qry := fmt.Sprintf(
`INSERT INTO "%s"."%s" %s VALUES %s`, os.Getenv("GO_SEED_PG_SCHEMA"),
table, colsStr, valStr)

log.Println("Executing Query: ", qry)

res, err := db.DBConn.Exec( qry )

if res == nil {
return errors.New(fmt.Sprintf("not inserted correctly, result is nil: %v", err))
return errors.New(fmt.Sprintf("\n\n\nnot inserted correctly, result is nil: %v", err))
}

rowInserted, _ := res.RowsAffected()
if rowInserted != 1 {
err = errors.New("not inserted correctly, affected rows is not 1")
err = errors.New("\n\n\nnot inserted correctly, affected rows is not 1")
}

return
Expand Down

0 comments on commit 8649fe9

Please sign in to comment.