-
Notifications
You must be signed in to change notification settings - Fork 4
/
dump.go
367 lines (311 loc) · 9.67 KB
/
dump.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
package cli
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgtype"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/xuri/excelize/v2"
"golang.org/x/exp/slices"
"os"
"os/signal"
"strings"
"time"
"unicode/utf8"
)
const DefaultColumnCnt = 32
var query = `SELECT tab.relname AS table_name
, tabdesc.description AS table_description
, col.column_name
, coldesc.description AS column_description
, col.data_type
, col.is_nullable
, col.column_default
FROM pg_stat_user_tables tab
LEFT OUTER JOIN pg_description tabdesc
ON tab.relid = tabdesc.objoid
AND tabdesc.objsubid = '0'
LEFT OUTER JOIN information_schema.columns col
ON tab.relname = col.table_name
AND tab.schemaname = current_schema()
LEFT OUTER JOIN pg_description coldesc
ON tab.relid = coldesc.objoid
AND col.ordinal_position = coldesc.objsubid
LEFT OUTER JOIN pg_class pc
ON tab.relid = pc.oid
WHERE exists(select 1 FROM tmp_exceltesting_dump_table_name WHERE tab.relname = name)
AND tab.schemaname = current_schema()
AND col.table_schema = current_schema()
AND pc.relispartition = false
ORDER BY tab.relname
, col.ordinal_position
;
`
var queryAll = `SELECT tab.relname AS table_name
, tabdesc.description AS table_description
, col.column_name
, coldesc.description AS column_description
, col.data_type
, col.is_nullable
, col.column_default
FROM pg_stat_user_tables tab
LEFT OUTER JOIN pg_description tabdesc
ON tab.relid = tabdesc.objoid
AND tabdesc.objsubid = '0'
LEFT OUTER JOIN information_schema.columns col
ON tab.relname = col.table_name
AND tab.schemaname = current_schema()
LEFT OUTER JOIN pg_description coldesc
ON tab.relid = coldesc.objoid
AND col.ordinal_position = coldesc.objsubid
LEFT OUTER JOIN pg_class pc
ON tab.relid = pc.oid
WHERE
tab.schemaname = current_schema()
AND col.table_schema = current_schema()
AND pc.relispartition = false
ORDER BY tab.relname
, col.ordinal_position
;
`
type TableDef struct {
Name string
Comment string
Columns []ColumnDef
}
type ColumnDef struct {
Name string
Comment string
DataType string
Constraint string
DefaultValue string
}
func Dump(dbSource, targetFile, tableNameArg, systemColumnArg string, maxDumpSize int) error {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
var tableNames []string
if len(tableNameArg) > 0 {
tableNames = strings.Split(tableNameArg, ",")
}
var systemColumn []string
if len(systemColumnArg) > 0 {
systemColumn = strings.Split(systemColumnArg, ",")
}
conn, err := pgxpool.Connect(ctx, dbSource)
if err != nil {
return fmt.Errorf("pgxpool connect: %w", err)
}
if len(tableNames) > 0 {
_, err = conn.Exec(ctx, `CREATE TEMPORARY TABLE tmp_exceltesting_dump_table_name(name varchar(256))`)
if err != nil {
return fmt.Errorf("cannot temporary table: %w", err)
}
batch := &pgx.Batch{}
for _, v := range tableNames {
batch.Queue("insert into tmp_exceltesting_dump_table_name values($1)", v)
}
if err := conn.SendBatch(ctx, batch).Close(); err != nil {
return fmt.Errorf("batch insert: %w", err)
}
}
defs, err := selectTabColumnDef(ctx, conn, tableNames)
if err != nil {
return err
}
if len(defs) == 0 {
return errors.New("table not found")
}
f := excelize.NewFile()
var (
rowHeaderStyle, _ = f.NewStyle(&excelize.Style{
Border: []excelize.Border{
{Type: "top", Style: 1, Color: "000000"},
{Type: "left", Style: 1, Color: "000000"},
{Type: "right", Style: 1, Color: "000000"},
{Type: "bottom", Style: 1, Color: "000000"},
},
Fill: excelize.Fill{Type: "pattern", Color: []string{"#D9D9D9"}, Pattern: 1},
})
columnHeaderStyle, _ = f.NewStyle(&excelize.Style{
Border: []excelize.Border{
{Type: "top", Style: 1, Color: "#000000"},
{Type: "left", Style: 1, Color: "#000000"},
{Type: "right", Style: 1, Color: "#000000"},
{Type: "bottom", Style: 1, Color: "#000000"},
},
Fill: excelize.Fill{Type: "pattern", Color: []string{"#FCD5B4"}, Pattern: 1},
})
columnHeaderSystemStyle, _ = f.NewStyle(&excelize.Style{
Border: []excelize.Border{
{Type: "top", Style: 1, Color: "000000"},
{Type: "left", Style: 1, Color: "000000"},
{Type: "right", Style: 1, Color: "000000"},
{Type: "bottom", Style: 1, Color: "000000"},
},
Fill: excelize.Fill{Type: "pattern", Color: []string{"#BFBFBF"}, Pattern: 1},
})
rowStyle, _ = f.NewStyle(&excelize.Style{
Border: []excelize.Border{
{Type: "top", Style: 1, Color: "000000"},
{Type: "left", Style: 1, Color: "000000"},
{Type: "right", Style: 1, Color: "000000"},
{Type: "bottom", Style: 1, Color: "000000"},
},
})
)
for i, tableDef := range defs {
sheetName := tableDef.Comment
if len(sheetName) == 0 {
sheetName = tableDef.Name
}
index := f.NewSheet(sheetName)
if i == 0 {
f.SetActiveSheet(index)
}
_ = f.SetCellValue(sheetName, "A1", tableDef.Comment)
_ = f.SetCellValue(sheetName, "A2", tableDef.Name)
_ = f.SetCellValue(sheetName, "A3", "version")
_ = f.SetCellValue(sheetName, "B3", "2.0")
_ = f.SetCellValue(sheetName, "A5", "項目名")
_ = f.SetCellValue(sheetName, "A6", "項目物理名")
_ = f.SetColWidth(sheetName, "A", "A", 12.86)
_ = f.SetCellStyle(sheetName, "A5", "A6", rowHeaderStyle)
for i, columnDef := range tableDef.Columns {
axisComment, _ := excelize.CoordinatesToCellName(2+i, 5)
axisName, _ := excelize.CoordinatesToCellName(2+i, 6)
_ = f.SetCellValue(sheetName, axisComment, columnDef.Comment)
_ = f.SetCellValue(sheetName, axisName, columnDef.Name)
currentCol, _ := excelize.ColumnNumberToName(2 + i)
width := utf8.RuneCountInString(columnDef.Comment) * 2
if width < utf8.RuneCountInString(columnDef.Name) {
width = utf8.RuneCountInString(columnDef.Name)
}
width += 2 // + 2 for margin
_ = f.SetColWidth(sheetName, currentCol, currentCol, float64(width))
style := columnHeaderStyle
if slices.Contains(systemColumn, columnDef.Name) {
style = columnHeaderSystemStyle
}
_ = f.SetCellStyle(sheetName, axisComment, axisName, style)
}
records, err := selectExistsRecords(ctx, conn, tableDef, maxDumpSize)
if err != nil {
return fmt.Errorf("select exists records: %w", err)
}
// Add 3 empty row
vCell, _ := excelize.CoordinatesToCellName(1+len(tableDef.Columns), 12)
_ = f.SetCellStyle(sheetName, "A7", vCell, rowStyle)
_ = f.SetCellValue(sheetName, "A7", "1")
_ = f.SetCellValue(sheetName, "A8", "2")
_ = f.SetCellValue(sheetName, "A9", "3")
// データレコードがあれば上書き
if len(records) > 0 {
// 枠線などのスタイルを設定
vCell, _ := excelize.CoordinatesToCellName(len(records[0])+1, len(records)+9) // 9 is data record start position
_ = f.SetCellStyle(sheetName, "A10", vCell, rowStyle)
for i, record := range records {
rowNum := 7 + i
vCell, _ := excelize.CoordinatesToCellName(1, rowNum)
_ = f.SetCellValue(sheetName, vCell, fmt.Sprint(i+1))
for j, cell := range record {
colNum := j + 2
vCell, _ := excelize.CoordinatesToCellName(colNum, rowNum)
_ = f.SetCellValue(sheetName, vCell, fmtCell(cell))
}
}
}
}
f.DeleteSheet("Sheet1")
if err := f.SaveAs(targetFile); err != nil {
return fmt.Errorf("dump result save: %w", err)
}
return nil
}
func selectTabColumnDef(ctx context.Context, conn *pgxpool.Pool, tableNames []string) ([]TableDef, error) {
sql := query
if len(tableNames) == 0 {
sql = queryAll
}
rows, err := conn.Query(ctx, sql)
if err != nil {
return nil, fmt.Errorf("db access: %w", err)
}
defer rows.Close()
var (
tableDefs = make([]TableDef, 0, len(tableNames))
columnDefs []ColumnDef
currentTable string
)
for rows.Next() {
g := make([]any, 7) // Name, Comment, ColumnName, ColumnComment, DataType, ColumnConstraint, DefaultValue
for i := range g {
g[i] = &g[i]
}
if err := rows.Scan(g...); err != nil {
return nil, err
}
if currentTable != Str(g[0]) {
columnDefs = make([]ColumnDef, 0, DefaultColumnCnt)
tableDefs = append(tableDefs, TableDef{
Name: Str(g[0]),
Comment: Str(g[1]),
})
currentTable = Str(g[0])
}
columnDefs = append(columnDefs, ColumnDef{
Name: Str(g[2]),
Comment: Str(g[3]),
DataType: Str(g[4]),
Constraint: Str(g[5]),
DefaultValue: Str(g[6]),
})
tableDefs[len(tableDefs)-1].Columns = columnDefs
}
if err := rows.Err(); err != nil {
return nil, err
}
return tableDefs, nil
}
func Str(a any) string {
if a == nil {
return ""
}
return a.(string)
}
func selectExistsRecords(ctx context.Context, conn *pgxpool.Pool, tableDef TableDef, maxDumpSize int) ([][]any, error) {
rows, err := conn.Query(ctx, fmt.Sprintf(`select * from %s limit %d`, tableDef.Name, maxDumpSize))
if err != nil {
return nil, fmt.Errorf("db access: %w", err)
}
defer rows.Close()
dataRecords := make([][]any, 0, maxDumpSize)
for rows.Next() {
g := make([]any, len(tableDef.Columns))
for i := range g {
g[i] = &g[i]
}
if err := rows.Scan(g...); err != nil {
return nil, err
}
dataRecords = append(dataRecords, g)
}
if err := rows.Err(); err != nil {
return nil, err
}
return dataRecords, nil
}
func fmtCell(a any) string {
switch v := a.(type) {
case time.Time:
return v.Format("2006-01-02 15:04:05")
case pgtype.Numeric:
var s string
if err := v.AssignTo(&s); err != nil {
return fmt.Sprintf("%v (fmtCell): %v", v, err)
}
return s
default:
return fmt.Sprint(v)
}
}