2013-05-14 18:15:35 +04:00
|
|
|
package writer
|
|
|
|
|
|
|
|
import (
|
2013-05-15 15:00:42 +04:00
|
|
|
"goposm/database"
|
2013-05-14 18:15:35 +04:00
|
|
|
"log"
|
2013-05-21 09:52:03 +04:00
|
|
|
"runtime"
|
|
|
|
"sync"
|
2013-05-14 18:15:35 +04:00
|
|
|
)
|
|
|
|
|
2013-05-21 11:50:10 +04:00
|
|
|
type ErrorLevel interface {
|
|
|
|
Level() int
|
|
|
|
}
|
|
|
|
|
2013-05-21 09:52:03 +04:00
|
|
|
type DbWriter struct {
|
|
|
|
Db database.DB
|
|
|
|
In chan InsertBatch
|
|
|
|
wg *sync.WaitGroup
|
|
|
|
}
|
2013-05-14 18:15:35 +04:00
|
|
|
|
2013-05-21 09:52:03 +04:00
|
|
|
func NewDbWriter(db database.DB, in chan InsertBatch) *DbWriter {
|
|
|
|
dw := DbWriter{
|
|
|
|
Db: db,
|
|
|
|
In: in,
|
|
|
|
wg: &sync.WaitGroup{},
|
|
|
|
}
|
|
|
|
for i := 0; i < runtime.NumCPU(); i++ {
|
|
|
|
dw.wg.Add(1)
|
|
|
|
go dw.loop()
|
2013-05-14 18:15:35 +04:00
|
|
|
}
|
2013-05-21 09:52:03 +04:00
|
|
|
return &dw
|
2013-05-14 18:15:35 +04:00
|
|
|
}
|
|
|
|
|
2013-05-21 09:52:03 +04:00
|
|
|
func (dw *DbWriter) Close() {
|
|
|
|
dw.wg.Wait()
|
2013-05-14 18:15:35 +04:00
|
|
|
}
|
|
|
|
|
2013-05-21 09:52:03 +04:00
|
|
|
func (dw *DbWriter) loop() {
|
|
|
|
for batch := range dw.In {
|
|
|
|
err := dw.Db.InsertBatch(batch.Table, batch.Rows)
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
2013-05-14 18:15:35 +04:00
|
|
|
}
|
|
|
|
}
|
2013-05-21 09:52:03 +04:00
|
|
|
dw.wg.Done()
|
2013-05-14 18:15:35 +04:00
|
|
|
}
|