Repository navigation
Expand file tree
/
Copy pathinfo.go
More file actions
496 lines (430 loc) · 16.1 KB
/
Copy pathinfo.go
File metadata and controls
496 lines (430 loc) · 16.1 KB
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
package sql
import (
"context"
"database/sql"
"fmt"
"regexp"
"strconv"
"strings"
"github.com/acronis/perfkit/db"
)
// GetVersion returns DB version and driver name
// Implements part of databaseDescriber interface
func getVersion(q querier, d dialect) (db.DialectName, string, error) {
var version string
var query string
switch d.name() {
case db.POSTGRES:
query = "SELECT version();"
case db.MYSQL, db.CLICKHOUSE:
query = "SELECT VERSION();"
case db.CASSANDRA:
query = "SELECT release_version FROM system.local;"
case db.MSSQL:
query = "SELECT @@VERSION;"
case db.SQLITE:
query = "SELECT sqlite_version();"
default:
return "", "", fmt.Errorf("unsupported driver: %s", d.name())
}
// Uses queryRowContext from databaseQuerier interface to execute version query
// Returns:
// - DialectName: database type (postgres, mysql, etc.)
// - string: version information
// - error: any execution errors
if err := q.queryRowContext(context.Background(), query).Scan(&version); err != nil {
return "", "", err
}
if d.name() == db.MYSQL {
var versionComment string
query = "SELECT @@VERSION_COMMENT;"
if err := q.queryRowContext(context.Background(), query).Scan(&versionComment); err != nil {
return "", "", err
}
version = fmt.Sprintf("%s (%s)", version, versionComment)
}
return d.name(), version, nil
}
// GetInfo returns DB info
// Implements GetInfo method of databaseDescriber interface
// Returns:
// - []string: Formatted table of database settings
// - *db.Info: Structured settings data with recommendations
// - error: Any execution errors
func getInfo(q querier, d dialect, version string) ([]string, *db.Info, error) {
var ret []string
// Initialize Info struct with recommendations source and version
var dbInfo = db.NewDBInfo(newSQLRecommendationsSource(q, d), version)
switch d.name() {
case db.POSTGRES:
// Execute SHOW ALL command using databaseQuerier interface
var rows, err = q.queryContext(context.Background(), "SHOW ALL")
if err != nil {
return nil, nil, fmt.Errorf("failed to execute query: %s, error: %s", "SHOW ALL", err)
}
defer rows.Close()
header := "|-------------------------------------|--------------------------------------------------------------|------------|"
ret = append(ret, header)
ret = append(ret, fmt.Sprintf("| %-35s | %-60s | %-10s |", "Name", "Setting", "Unit"))
ret = append(ret, header)
for rows.Next() {
var name, setting, unit sql.NullString
if err = rows.Scan(&name, &setting, &unit); err != nil {
return nil, nil, fmt.Errorf("failed to scan row: %s", err)
}
s := db.TernaryStr(name.Valid, name.String, "")
v := db.TernaryStr(setting.Valid, setting.String, "")
dbInfo.AddSetting(s, v)
ret = append(ret, fmt.Sprintf("| %-35s | %-60s | %-10s |", s, v, db.TernaryStr(unit.Valid, setting.String, "")))
}
ret = append(ret, header)
if err = rows.Err(); err != nil {
return nil, nil, fmt.Errorf("error during row iteration: %s", err)
}
case db.MYSQL:
// Uses databaseQuerier interface to get MySQL variables
query := "SHOW VARIABLES;"
rows, err := q.queryContext(context.Background(), query)
if err != nil {
return nil, nil, fmt.Errorf("failed to execute query: %s, error: %s", query, err)
}
defer rows.Close()
var variableName, value string
header := "-----------------------------------------|-----------------------------------------------"
ret = append(ret, header)
ret = append(ret, fmt.Sprintf("%-40s | %-40s", "Variable_Name", "Value"))
ret = append(ret, header)
for rows.Next() {
err = rows.Scan(&variableName, &value)
if err != nil {
return nil, nil, fmt.Errorf("failed to scan row: %s", err)
}
dbInfo.AddSetting(variableName, value)
ret = append(ret, fmt.Sprintf("%-40s | %-40s", variableName, value))
}
ret = append(ret, header)
if err = rows.Err(); err != nil {
return nil, nil, fmt.Errorf("error during row iteration: %s", err)
}
case db.MSSQL:
// Uses databaseQuerier to get MSSQL configurations
query := "SELECT * FROM sys.configurations"
rows, err := q.queryContext(context.Background(), query)
if err != nil {
return nil, nil, fmt.Errorf("failed to execute query: %s, error: %s", query, err)
}
defer rows.Close()
cols, err := rows.Columns()
if err != nil {
return nil, nil, fmt.Errorf("failed to get columns: %s", err)
}
// Create a slice of interface{}'s to represent each column,
// and a second slice to contain pointers to each item in the columns slice.
values := make([]sql.RawBytes, len(cols))
scanArgs := make([]interface{}, len(values))
for i := range values {
scanArgs[i] = &values[i]
}
header := ""
for range cols {
header += strings.Repeat("-", 37)
}
ret = append(ret, header)
str := ""
for _, col := range cols {
str += fmt.Sprintf("%-35s | ", col)
}
ret = append(ret, str)
// Fetch rows
for rows.Next() {
err = rows.Scan(scanArgs...)
if err != nil {
return nil, nil, fmt.Errorf("failed to scan row: %s", err)
}
var value string
str = ""
for _, col := range values {
if col == nil {
value = "NULL"
} else {
value = string(col)
}
str += fmt.Sprintf("%-35s | ", value)
}
ret = append(ret, str)
}
ret = append(ret, header)
if err = rows.Err(); err != nil {
return nil, nil, fmt.Errorf("error during row iteration: %s", err)
}
case db.CASSANDRA:
// Uses databaseQuerier to get Cassandra system info
rows, err := q.queryContext(context.Background(), "SELECT * FROM system.local") // Replace with your actual query
if err != nil {
return nil, nil, fmt.Errorf("failed to execute query: %s, error: %s", "SELECT * FROM system.local", err)
}
defer rows.Close()
// Get column names
columns, err := rows.Columns()
if err != nil {
return nil, nil, fmt.Errorf("failed to get columns: %s", err)
}
// Prepare a slice of interface{}'s to hold each value
values := make([]interface{}, len(columns))
for i := range values {
values[i] = new(interface{})
}
// Iterate over rows
for rows.Next() {
err = rows.Scan(values...)
if err != nil {
return nil, nil, fmt.Errorf("failed to scan row: %s", err)
}
for i, value := range values {
ret = append(ret, fmt.Sprintf("%s: %v", columns[i], *(value.(*interface{}))))
}
}
// Check for errors after iterating
if err = rows.Err(); err != nil {
return nil, nil, fmt.Errorf("error during row iteration: %s", err)
}
case db.SQLITE, db.CLICKHOUSE:
// No specific info queries for these databases
default:
return nil, nil, fmt.Errorf("unsupported driver: %s", d.name())
}
return ret, dbInfo, nil
}
// GetTablesSchemaInfo returns the schema info for a given set of tables
// Implements GetTablesSchemaInfo method of databaseDescriber interface
// Returns formatted strings containing table schema information including:
// - Column definitions
// - Index definitions
// - Primary keys
func getTablesSchemaInfo(q querier, d dialect, tableNames []string) ([]string, error) {
var ret []string
for _, table := range tableNames {
if exists, err := tableExists(q, d, table); err != nil {
return nil, fmt.Errorf("error checking table existence: %w", err)
} else if !exists {
continue
}
ret = append(ret, fmt.Sprintf("TABLE: %s", table)) //nolint:perfsprint
// Query to list columns
var listColumnsQuery string
switch d.name() {
case db.POSTGRES, db.MYSQL, db.MSSQL:
listColumnsQuery = fmt.Sprintf("SELECT column_name, data_type FROM information_schema.columns WHERE table_name = '%s'", table)
case db.CLICKHOUSE:
listColumnsQuery = fmt.Sprintf("SELECT name AS column_name, type AS data_type FROM system.columns WHERE table = '%s'", table)
case db.CASSANDRA:
listColumnsQuery = fmt.Sprintf("SELECT column_name, type FROM system_schema.columns WHERE keyspace_name = '%s' AND table_name = '%s'", d.schema(), table)
case db.SQLITE:
listColumnsQuery = fmt.Sprintf("PRAGMA table_info('%s')", table)
default:
return nil, fmt.Errorf("unsupported database type: %s", d.name())
}
columns, err := q.queryContext(context.Background(), listColumnsQuery)
if err != nil {
return nil, fmt.Errorf("error: %w", err)
}
ret = append(ret, " Columns:")
switch d.name() {
case db.SQLITE:
for columns.Next() {
var columnName, dataType string
var unusedInt int
var unusedBool bool
var unusedVoid interface{}
if err = columns.Scan(&unusedInt, &columnName, &dataType, &unusedBool, &unusedVoid, &unusedInt); err != nil {
return nil, fmt.Errorf("error: %w\nquery: %s", err, listColumnsQuery)
}
ret = append(ret, fmt.Sprintf(" - %s: %s", columnName, dataType))
}
default:
for columns.Next() {
var columnName, dataType string
if err = columns.Scan(&columnName, &dataType); err != nil {
return nil, fmt.Errorf("error: %w\nquery: %s", err, listColumnsQuery)
}
ret = append(ret, fmt.Sprintf(" - %s: %s", columnName, dataType))
}
}
err = columns.Close() //nolint:sqlclosecheck
if err != nil {
return nil, fmt.Errorf("close error: %s\nquery: %s", err, listColumnsQuery)
}
// Query to list indexes
var listIndexesQuery string
switch d.name() {
case db.POSTGRES:
listIndexesQuery = fmt.Sprintf("SELECT indexname, indexdef FROM pg_indexes WHERE tablename = '%s'", table)
case db.MYSQL:
listIndexesQuery = fmt.Sprintf("SELECT TABLE_NAME, NON_UNIQUE, INDEX_NAME, SEQ_IN_INDEX, COLUMN_NAME, COLLATION, "+
" CARDINALITY, SUB_PART, NULLABLE, INDEX_TYPE, COMMENT "+
"FROM "+
" information_schema.STATISTICS "+
"WHERE "+
" TABLE_NAME = '%s';", table)
case db.MSSQL:
listIndexesQuery = fmt.Sprintf("SELECT name FROM sys.indexes WHERE object_id = OBJECT_ID('%s')", table)
case db.SQLITE:
listIndexesQuery = fmt.Sprintf("PRAGMA index_list('%s')", table)
case db.CLICKHOUSE:
listIndexesQuery = fmt.Sprintf("SHOW CREATE TABLE %s", table) //nolint:perfsprint
case db.CASSANDRA:
listIndexesQuery = fmt.Sprintf("select index_name, kind, options from system_schema.indexes where keyspace_name = '%s' and table_name = '%s'", d.schema(), table)
default:
return nil, fmt.Errorf("unsupported database type: %s", d.name())
}
indexes, err := q.queryContext(context.Background(), listIndexesQuery)
if err != nil {
return nil, fmt.Errorf("error: %w", err)
}
ret = append(ret, " Indexes:")
for indexes.Next() {
var indexName, indexDef string
switch d.name() {
case db.POSTGRES:
if err = indexes.Scan(&indexName, &indexDef); err != nil {
return nil, fmt.Errorf("error: %s\nquery: %s", err, listIndexesQuery)
}
ret = append(ret, fmt.Sprintf(" - %s: %s", indexName, indexDef))
case db.MYSQL:
var nonUnique bool
var seqInIndex int
var columnName, collation, indexType, comment string
var cardinality, subPart interface{}
var nullable string
if err = indexes.Scan(&table, &nonUnique, &indexName, &seqInIndex, &columnName, &collation, &cardinality,
&subPart, &nullable, &indexType, &comment); err != nil {
return nil, fmt.Errorf("error: %s\nquery: %s", err, listIndexesQuery)
}
ret = append(ret, fmt.Sprintf(" - %s", indexName)) //nolint:perfsprint
case db.MSSQL:
if err = indexes.Scan(&indexName); err != nil {
return nil, fmt.Errorf("error: %s\nquery: %s", err, listIndexesQuery)
}
ret = append(ret, fmt.Sprintf(" - %s", indexName)) //nolint:perfsprint
case db.SQLITE:
var seq int
var unique, partial bool
var origin string
if err = indexes.Scan(&seq, &indexName, &unique, &origin, &partial); err != nil {
return nil, fmt.Errorf("error: %s\nquery: %s", err, listIndexesQuery)
}
ret = append(ret, fmt.Sprintf(" - %s", indexName)) //nolint:perfsprint
case db.CLICKHOUSE:
var createStatement string
if err = indexes.Scan(&createStatement); err != nil {
return nil, fmt.Errorf("error: %s\nquery: %s", err, listIndexesQuery)
}
// Regular expression to find ORDER BY clause
re := regexp.MustCompile(`ORDER BY (.*?)\n`)
matches := re.FindStringSubmatch(createStatement)
if len(matches) < 2 {
return nil, fmt.Errorf("The 'ORDER BY' clause not found in the output of '%s':\n%s", listIndexesQuery, createStatement)
}
// Extracting columns listed in ORDER BY
pkName := matches[1]
ret = append(ret, fmt.Sprintf(" - %s (primary key)", pkName))
case db.CASSANDRA:
var idxName string
var kind string
var options map[string]string
if err = indexes.Scan(&idxName, &kind, &options); err != nil {
return nil, fmt.Errorf("error: %s\nquery: %s", err, listIndexesQuery)
}
ret = append(ret, fmt.Sprintf(" - %s:%s - %v", idxName, kind, options))
default:
return nil, fmt.Errorf("unsupported database type: %s", d.name())
}
}
err = indexes.Close() //nolint:sqlclosecheck
if err != nil {
return nil, fmt.Errorf("close error: %s\nquery: %s", err, listIndexesQuery)
}
ret = append(ret, "")
}
return ret, nil
}
// GetTableSizeMB returns the size of a table in MB
// Helper function for GetTablesVolumeInfo
// Uses databaseQuerier interface to execute size queries
func getTableSizeMB(q querier, d dialect, tableName string) (int64, error) {
var query string
var args = []interface{}{tableName}
switch d.name() {
case db.POSTGRES:
query = `SELECT pg_total_relation_size('%s') / (1024 * 1024);`
case db.MYSQL:
query = `SELECT CAST(Data_length / (1024 * 1024) AS UNSIGNED) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '%s';`
default:
return -1, nil
}
var check = fmt.Sprintf(query, args...)
var sizeMB int64
if err := q.queryRowContext(context.Background(), check).Scan(&sizeMB); err != nil && err != sql.ErrNoRows {
return 0, err
}
return sizeMB, nil
}
// GetIndexesSizeMB returns the size of indexes of a table in MB
// Helper function for GetTablesVolumeInfo
// Uses databaseQuerier interface to execute index size queries
func getIndexesSizeMB(q querier, d dialect, tableName string) (int64, error) {
var query string
var args = []interface{}{tableName}
switch d.name() {
case db.POSTGRES:
query = "SELECT pg_indexes_size('%s') / (1024 * 1024)"
case db.MYSQL:
query = "SELECT CAST(Index_length / (1024 * 1024) AS UNSIGNED) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '%s'"
default:
return -1, nil
}
var check = fmt.Sprintf(query, args...)
var sizeMB int64
if err := q.queryRowContext(context.Background(), check).Scan(&sizeMB); err != nil && err != sql.ErrNoRows {
return 0, err
}
return sizeMB, nil
}
// GetTablesVolumeInfo returns the volume info for a given set of tables
// Implements GetTablesVolumeInfo method of databaseDescriber interface
// Returns formatted strings containing:
// - Table names
// - Row counts
// - Data sizes in MB
// - Index sizes in MB
func getTablesVolumeInfo(q querier, d dialect, tableNames []string) ([]string, error) {
var ret []string
ret = append(ret, fmt.Sprintf("%-55s %15s %17s %17s", "TABLE NAME", "ROWS", "DATA SIZE (MB)", "IDX SIZE (MB)"))
ret = append(ret, fmt.Sprintf("%-55s %15s %17s %17s", strings.Repeat("-", 55), strings.Repeat("-", 15), strings.Repeat("-", 17), strings.Repeat("-", 17)))
for _, tableName := range tableNames {
str := ""
str += fmt.Sprintf("%-55s ", tableName)
if exists, err := tableExists(q, d, tableName); err != nil {
return nil, fmt.Errorf("error checking table existence: %w", err)
} else if exists {
var rowNum uint64
if err = q.queryRowContext(context.Background(), fmt.Sprintf("SELECT COUNT(*) FROM %s", d.table(tableName))).Scan(&rowNum); err != nil && err != sql.ErrNoRows {
return nil, err
}
var tableSizeMB, idxSizeMB int64
if tableSizeMB, err = getTableSizeMB(q, d, tableName); err != nil {
return nil, fmt.Errorf("error getting table size: %w", err)
}
if idxSizeMB, err = getIndexesSizeMB(q, d, tableName); err != nil {
return nil, fmt.Errorf("error getting indexes size: %w", err)
}
str += fmt.Sprintf("%15d %17s %17s", rowNum,
db.TernaryStr(tableSizeMB >= 0, strconv.FormatInt(tableSizeMB, 10), "?"),
db.TernaryStr(idxSizeMB >= 0, strconv.FormatInt(idxSizeMB, 10), "?"))
} else {
str += fmt.Sprintf("%15s %17s %17s", "-", "-", "-")
}
ret = append(ret, str)
}
return ret, nil
}