forked from ThreeDotsLabs/watermill
-
Notifications
You must be signed in to change notification settings - Fork 0
/
postgres.go
66 lines (54 loc) · 1.66 KB
/
postgres.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
package main
import (
"bytes"
stdSQL "database/sql"
"encoding/gob"
"errors"
"fmt"
"strings"
"time"
"github.com/ThreeDotsLabs/watermill-sql/pkg/sql"
"github.com/ThreeDotsLabs/watermill/message"
)
type postgresUser struct {
ID int
Username string
FullName string
CreatedAt time.Time
}
type postgresSchemaAdapter struct{}
func (p postgresSchemaAdapter) SchemaInitializingQueries(topic string) []string {
return []string{
`CREATE TABLE IF NOT EXISTS ` + topic + ` (
id INT NOT NULL PRIMARY KEY,
username VARCHAR(36) NOT NULL,
full_name VARCHAR(36) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);`,
}
}
func (p postgresSchemaAdapter) InsertQuery(topic string, msgs message.Messages) (string, []interface{}, error) {
insertQuery := fmt.Sprintf(
`INSERT INTO %s (id, username, full_name, created_at) VALUES %s`,
topic,
strings.TrimRight(strings.Repeat(`($1,$2,$3,$4),`, len(msgs)), ","),
)
var args []interface{}
for _, msg := range msgs {
user := postgresUser{}
decoder := gob.NewDecoder(bytes.NewBuffer(msg.Payload))
err := decoder.Decode(&user)
if err != nil {
return "", nil, err
}
args = append(args, user.ID, user.Username, user.FullName, user.CreatedAt)
}
return insertQuery, args, nil
}
func (p postgresSchemaAdapter) SelectQuery(topic string, consumerGroup string, offsetsAdapter sql.OffsetsAdapter) (string, []interface{}) {
// No need to implement this method, as PostgreSQL subscriber is not used in this example.
return "", nil
}
func (p postgresSchemaAdapter) UnmarshalMessage(row *stdSQL.Row) (offset int, msg *message.Message, err error) {
return 0, nil, errors.New("not implemented")
}