-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
74 lines (61 loc) · 1.23 KB
/
parser.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"encoding/csv"
"log"
"os"
"strconv"
"sync"
"time"
"gorm.io/gorm"
)
const workerCount = 10
func parseCaseStudyCSV(db *gorm.DB, filename string) error {
// before parsing clear database table.
clearTable(db)
start := time.Now()
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close()
reader := csv.NewReader(file)
reader.Comma = ','
var wg sync.WaitGroup
jobs := make(chan []string, workerCount)
for i := 0; i < workerCount; i++ {
wg.Add(1)
go worker(db, &wg, jobs)
}
go func() {
for {
record, err := reader.Read()
if err != nil {
close(jobs)
break
}
jobs <- record
}
}()
wg.Wait()
log.Printf("File parsed successfully. Time took: %s \n", time.Since(start).String())
return nil
}
func worker(db *gorm.DB, wg *sync.WaitGroup, jobs <-chan []string) {
defer wg.Done()
for record := range jobs {
id := record[0]
amount, err := strconv.ParseFloat(record[1], 32)
if err != nil {
continue
}
date := record[2]
prm := Promotion{
ID: id,
Price: float32(amount),
ExpirationDate: date,
}
if err := CreatePromotion(db, prm); err != nil {
log.Printf("Error creating promotion in DB: %v", err.Error())
}
}
}