/
repo.go
77 lines (69 loc) · 1.42 KB
/
repo.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
package vacationrentals
import (
"context"
"fmt"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
)
type Repo struct {
conn *pgxpool.Pool
}
func NewRepo(conn *pgxpool.Pool) *Repo {
return &Repo{
conn: conn,
}
}
func (r *Repo) StoreRentals(rentals []*VacationRental) error {
ctx := context.Background()
tx, err := r.conn.BeginTx(ctx, pgx.TxOptions{})
if err != nil {
return err
}
for _, v := range rentals {
sql := `
INSERT INTO
vacation_rentals (
name,
address_name,
type,
bedroom_limit,
guest_limit,
expiration_date,
lng_lat_point_nad83
)
VALUES ($1, $2, $3, $4, $5, $6, %s)
RETURNING id;
`
var id int
// the format could be NAD83 or WGS84, we want to transform the WGS84 ones to NAD83
if v.LngLatPoint.SRID == 4326 {
sql = fmt.Sprintf(sql, "ST_Transform(GeomFromEWKB($7), 3452)")
} else {
sql = fmt.Sprintf(sql, "GeomFromEWKB($7)")
}
err = tx.QueryRow(ctx, sql,
v.Name,
v.AddressName,
v.Type,
v.BedroomLimit,
v.GuestLimit,
v.ExpirationDate.Time,
v.LngLatPoint,
).Scan(&id)
if err != nil && err != pgx.ErrNoRows {
tx.Rollback(ctx)
return err
}
}
err = tx.Commit(ctx)
return err
}
func generateValues(start, end int, extra ...string) (result []string) {
for i := start; i <= end; i++ {
result = append(result, fmt.Sprintf("$%d", i))
}
for _, v := range extra {
result = append(result, v)
}
return result
}