/
pgcp.go
284 lines (245 loc) · 7.4 KB
/
pgcp.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package main
import "fmt"
import (
"database/sql"
"github.com/joncrlsn/misc"
"github.com/joncrlsn/pgutil"
_ "github.com/lib/pq"
flag "github.com/ogier/pflag"
"log"
"os"
"strings"
"time"
)
const isoFormat = "2006-01-02T15:04:05.000-0700"
const version = "1.0.6"
// out defaults to standard out, but can be overwritten with a traditional file
// via the -o flag
var out *os.File = os.Stdout
func print(a ...interface{}) (int, error) {
return fmt.Fprint(out, a...)
}
func println(a ...interface{}) (int, error) {
return fmt.Fprintln(out, a...)
}
func printf(format string, a ...interface{}) (int, error) {
return fmt.Fprintf(out, format, a...)
}
/*
* Queries the given table name and copies the column values to either an INSERT statement or
* an UPDATE statement.
*
* Example: pgcp -U myuser -d mydb INSERT t_user "WHERE user_id < 4"
*/
func main() {
var outputFileName string
flag.StringVarP(&outputFileName, "output-file", "o", "", "Sends output to a file")
dbInfo := pgutil.DbInfo{}
verFlag, helpFlag := dbInfo.Populate()
if verFlag {
fmt.Fprintf(os.Stderr, "%s version %s\n", os.Args[0], version)
fmt.Fprintln(os.Stderr, "Copyright (c) 2015 Jon Carlson. All rights reserved.")
fmt.Fprintln(os.Stderr, "Use of this source code is governed by the MIT license")
fmt.Fprintln(os.Stderr, "that can be found here: http://opensource.org/licenses/MIT")
os.Exit(1)
}
if helpFlag {
usage()
}
// Remaining args:
args := flag.Args()
if len(args) < 2 {
fmt.Fprintln(os.Stderr, "Missing some arguments")
usage()
}
// genType
genType := strings.ToUpper(args[0])
if genType != "INSERT" && genType != "UPDATE" {
fmt.Fprintf(os.Stderr, "Invalid generation type: %s. Requires either INSERT or UPDATE\n", genType)
usage()
}
if len(outputFileName) > 0 {
var err error
out, err = os.Create(outputFileName)
if err != nil {
fmt.Fprintf(os.Stderr, "Cannot open file: %s. \n", outputFileName)
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
}
// tableName
tableName := args[1]
// idColumn (UPDATE only) and whereClause
whereClause := ""
idCol := ""
if genType == "INSERT" {
if len(args) > 2 {
whereClause = args[2]
}
} else {
if len(args) < 3 {
fmt.Fprintf(os.Stderr, "UPDATE requires an idColumn.")
usage()
}
idCol = args[2]
if len(args) > 3 {
whereClause = args[3]
}
}
if len(whereClause) == 0 {
// Make sure user intended there to be no where clause
if !misc.PromptYesNo("Did you intend to have no where clause?", true) {
os.Exit(1)
}
}
db, err := dbInfo.Open()
check("opening database", err)
query := "SELECT * FROM " + tableName + " " + whereClause
printf("-- Creating %s(s) from query: %s\n", genType, query)
rowChan, columnNames := querySqlValues(db, query)
for row := range rowChan {
if genType == "INSERT" {
generateInsert(tableName, row, columnNames)
} else {
generateUpdate(tableName, row, idCol)
}
}
}
func generateInsert(tableName string, row map[string]string, colNames []string) {
printf("INSERT INTO %s (", tableName)
first := true
for _, name := range colNames {
if !first {
print(", ")
}
printf(name)
first = false
}
print(") VALUES (")
first = true
for _, name := range colNames {
if !first {
print(", ")
}
v := row[name]
printf(v)
first = false
}
println(");")
}
func generateUpdate(tableName string, row map[string]string, idCol string) {
printf("UPDATE %s SET ", tableName)
idVal := ""
idColFound := false
first := true
for k, v := range row {
if k == idCol {
idVal = v
idColFound = true
} else {
if !first {
print(", ")
}
printf("%s=%s", k, v)
first = false
}
}
if !idColFound {
log.Fatalf("\nid column not found: %s\n", idCol)
os.Exit(1)
}
printf(" WHERE %s=%s", idCol, idVal)
println(";")
}
/*
* Returns row maps (keyed by the column name) in a channel.
* Dynamically converts each column value to a SQL string value.
* See http://stackoverflow.com/questions/23507531/is-golangs-sql-package-incapable-of-ad-hoc-exploratory-queries
*/
func querySqlValues(db *sql.DB, query string) (chan map[string]string, []string) {
rowChan := make(chan map[string]string)
rows, err := db.Query(query)
check("running query", err)
columnNames, err := rows.Columns()
check("getting column names", err)
go func() {
defer rows.Close()
vals := make([]interface{}, len(columnNames))
valPointers := make([]interface{}, len(columnNames))
// Copy
for i := 0; i < len(columnNames); i++ {
valPointers[i] = &vals[i]
}
for rows.Next() {
err = rows.Scan(valPointers...)
check("scanning a row", err)
row := make(map[string]string)
// Convert each cell to a SQL-valid string representation
for i, valPtr := range vals {
//println(reflect.TypeOf(valPtr))
switch valueType := valPtr.(type) {
case nil:
row[columnNames[i]] = "null"
case []uint8:
row[columnNames[i]] = "'" + strings.Replace(string(valPtr.([]byte)), "'", "''", -1) + "'"
case string:
row[columnNames[i]] = "'" + strings.Replace(valPtr.(string), "'", "''", -1) + "'"
case int64:
row[columnNames[i]] = fmt.Sprintf("%d", valPtr)
case float64:
row[columnNames[i]] = fmt.Sprintf("%f", valPtr)
case bool:
row[columnNames[i]] = fmt.Sprintf("%t", valPtr)
case time.Time:
row[columnNames[i]] = "'" + valPtr.(time.Time).Format(isoFormat) + "'"
case fmt.Stringer:
row[columnNames[i]] = fmt.Sprintf("%v", valPtr)
default:
row[columnNames[i]] = fmt.Sprintf("%v", valPtr)
println("-- Warning, column %s is an unhandled type: %v", columnNames[i], valueType)
}
}
rowChan <- row
}
close(rowChan)
}()
return rowChan, columnNames
}
func usage() {
fmt.Fprintf(os.Stderr, "usage: %s [database flags] <genType> <tableName> <whereClause> \n", os.Args[0])
fmt.Fprintln(os.Stderr, `
Copies table data as either INSERT or UPDATE statements.
Program flags are:
-V, --version : prints the version of pgcp being run
-?, --help : prints a summary of the commands accepted by pgcp
-U, --user : user in postgres to execute the commands
-h, --host : host name where database is running (default is localhost)
-p, --port : port database is listening on (default is 5432)
-d, --dbname : database name
-O, --options : postgresql connection options (like sslmode=disable)
-w, --no-password : Never issue a password prompt
-W, --password : Force a password prompt
-o, --output-file : Sends output to the given file
<genType> : type of SQL to generate: insert, update
<tableName> : name of table to be copied (fully or partially)
<whereClause> : specifies which rows to copy. Example: WHERE user_id < 100 AND username IS NOT NULL
Database connection information can be specified in two ways:
* Environment variables
* Program flags (overrides environment variables. See above)
* ~/.pgpass file (for the password)
* Note that if password is not specified, you will be prompted.
Optional Environment variables (if program flags are not desirable):
PGHOST : host name where database is running (default is localhost)
PGPORT : port database is listening on (default is 5432)
PGDATABASE : name of database you want to copy
PGUSER : user in postgres you'll be executing the queries as
PGPASSWORD : password for the postgres user
PGOPTION : options (like sslmode=disable)
`)
os.Exit(2)
}
func check(msg string, err error) {
if err != nil {
log.Fatal("Error "+msg, err)
}
}