forked from tomyl/pg-dump-upsert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
71 lines (59 loc) · 2.04 KB
/
main.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
package main
import (
"database/sql"
"flag"
"fmt"
"log"
"os"
"strings"
"github.com/tomyl/pg-dump-upsert/pgdump"
)
func main() {
dsn := flag.String("dsn", "", "Connection string. Example: postgres://user:password@host:5432/db")
sourceTable := flag.String("from", "", "Source table to dump.")
destTable := flag.String("to", "", "Table name to use in INSERT statements. Defaults to the source table.")
insert := flag.String("insert-columns", "", "Comma-separated list of columns to include in INSERT statement. Defaults to all columns.")
conflict := flag.String("conflict-column", "", "Append an ON CONFLICT clause for this column. All other columns will be included in a DO UPDATE SET list.")
noconflict := flag.Bool("noconflict", false, "Append ON CONFLICT DO NOTHING.")
tx := flag.Bool("tx", false, "Wrap INSERT statements in transaction.")
query := flag.String("query", "", "Use custom SELECT query. By default fetches all rows. Note that column order must match -insert-columns. It is also valid to just specify a WHERE clause. It will be appended to the default query.")
verbose := flag.Bool("verbose", false, "Log query statement to stderr.")
flag.Parse()
if *dsn == "" {
log.Fatal("-dsn not supplied")
}
if *sourceTable == "" {
log.Fatal("-from not supplied")
}
if *noconflict && *conflict != "" {
log.Fatal("cannot combine -noconflict and -conflict-column")
}
var opts pgdump.Options
opts.InsertTable = *destTable
opts.Query = strings.TrimSpace(*query)
opts.ConflictColumn = strings.TrimSpace(*conflict)
opts.NoConflict = *noconflict
opts.Verbose = *verbose
if *insert != "" {
for _, col := range strings.Split(*insert, ",") {
col = strings.TrimSpace(col)
if col != "" {
opts.InsertColumns = append(opts.InsertColumns, col)
}
}
}
db, err := sql.Open("postgres", *dsn)
if err != nil {
log.Fatal(err)
}
defer db.Close()
if *tx {
fmt.Printf("BEGIN;\n")
}
if err := pgdump.DumpStream(os.Stdout, pgdump.NewQuerier(db), *sourceTable, &opts); err != nil {
log.Fatal(err)
}
if *tx {
fmt.Printf("COMMIT;\n")
}
}