-
Notifications
You must be signed in to change notification settings - Fork 2
/
insert_worker.go
86 lines (74 loc) · 1.9 KB
/
insert_worker.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
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"errors"
"flag"
"fmt"
"github.com/benmanns/goworker"
"github.com/coocood/qbs"
"os"
)
type Contact struct {
Id int64
Name string
Email string
Phone string
}
var (
errorTableCreationFailed = errors.New("Table creation failed.")
)
func newInsertWorker(uri string, connections int) (func(string, ...interface{}) error, error) {
dsn, err := postgresDSNFromUri(uri)
if err != nil {
return nil, err
}
qbs.RegisterWithDataSourceName(dsn)
qbs.SetConnectionLimit(connections, true)
migration, err := qbs.GetMigration()
if err != nil {
return nil, err
}
defer migration.Close()
err = func() (err error) {
defer func() {
if r := recover(); r != nil {
err = errorTableCreationFailed
}
}()
err = migration.CreateTableIfNotExists(new(Contact))
return
}()
if err != nil {
return nil, err
}
return func(queue string, args ...interface{}) error {
name, ok := args[0].(string)
if !ok {
return fmt.Errorf("Invalid parameters %v to insert worker. Expected string, was %T.", args, args[0])
}
email, ok := args[1].(string)
if !ok {
return fmt.Errorf("Invalid parameters %v to insert worker. Expected string, was %T.", args, args[1])
}
phone, ok := args[2].(string)
if !ok {
return fmt.Errorf("Invalid parameters %v to insert worker. Expected string, was %T.", args, args[2])
}
return qbs.WithQbs(func(db *qbs.Qbs) error {
contact := &Contact{Name: name, Email: email, Phone: phone}
_, err := db.Save(contact)
return err
})
}, nil
}
func init() {
qbs.StructNameToTableName = toSnakePlural
qbs.TableNameToStructName = snakePluralToUpperCamel
var connections int
flag.IntVar(&connections, "insert-connections", 5, "maximum DB connections for insert worker")
insertWorker, err := newInsertWorker(os.Getenv("DATABASE_URL"), connections)
if err != nil {
fmt.Println("Error:", err)
return
}
goworker.Register("Insert", insertWorker)
}