This repository has been archived by the owner on Aug 22, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
core.go
92 lines (78 loc) · 2.1 KB
/
core.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
87
88
89
90
91
92
package main
import (
"errors"
"fmt"
"reflect"
"strings"
"github.com/jmoiron/sqlx"
"github.com/kr/pretty"
)
func copyRows(pgx *sqlx.Tx, tableName string, kind interface{}, unique string) (err error) {
typ := reflect.TypeOf(kind)
if typ.Kind() != reflect.Struct {
return errors.New("kind given to copyRows is not a struct")
}
nfields := typ.NumField()
columnnames := make([]string, nfields)
valuelabels := make([]string, nfields)
values := make([]interface{}, nfields)
for i := 0; i < nfields; i++ {
valuelabels[i] = fmt.Sprintf("$%d", i+1)
columnnames[i] = typ.Field(i).Tag.Get("db")
}
rows, err := lite.Queryx(`SELECT * FROM ` + tableName)
if err != nil {
fmt.Println("error selecting "+tableName, err)
return err
}
uniqueStmt := ""
if unique != "" {
uniqueStmt = `ON CONFLICT (` + unique + `) DO NOTHING`
}
for rows.Next() {
vpointer := reflect.New(typ).Interface()
err := rows.StructScan(vpointer)
if err != nil {
pretty.Log(vpointer)
fmt.Println("error scanning "+tableName+" row", err)
return err
}
for i := 0; i < nfields; i++ {
values[i] = reflect.Indirect(reflect.ValueOf(vpointer)).Field(i).Interface()
}
_, err = pgx.Exec(`
INSERT INTO `+tableName+` (`+strings.Join(columnnames, ",")+`)
VALUES (`+strings.Join(valuelabels, ",")+`)
`+uniqueStmt,
values...)
if err != nil {
pretty.Log(vpointer)
pretty.Log(err)
fmt.Println("error inserting on '" + tableName + "': " + err.Error())
return err
}
}
return nil
}
func setSequence(sequenceName string) (err error) {
parts := strings.Split(sequenceName, "_")
tableName := strings.Join(parts[0:len(parts)-2], "_")
column := parts[len(parts)-2]
var maxval int
err = lite.Get(&maxval, `SELECT coalesce(max(`+column+`), 0) FROM `+tableName)
if err != nil {
fmt.Println("error fetching maximum value for", sequenceName, tableName, column, err)
return
}
if maxval == 0 {
// all is fine
return
}
nextval := maxval + 1
_, err = pg.Exec(`SELECT setval('`+sequenceName+`', $1)`, nextval)
if err != nil {
fmt.Println("error setting sequence", sequenceName, err)
return
}
return nil
}