-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostgres.go
More file actions
77 lines (66 loc) · 2.21 KB
/
postgres.go
File metadata and controls
77 lines (66 loc) · 2.21 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
package indexdiff
import (
"database/sql"
"fmt"
"log"
"regexp"
"strings"
_ "github.com/lib/pq"
)
var postgresIndexesQuery = `
select schemaname, tablename, indexname, indexdef
from pg_indexes
where schemaname <> 'pg_catalog'
order by schemaname, tablename, indexname, indexdef;`
var postgresIndexRe = regexp.MustCompile(`.* USING btree \((.*)\)`)
type PostgresEngine struct {
config *Config
}
func NewPostgresEngine(config *Config) *PostgresEngine {
return &PostgresEngine{config: config}
}
func (e *PostgresEngine) getConnectionString() string {
connStr := fmt.Sprintf("host=%s port=%d database=%s sslmode=disable", e.config.Server, e.config.Port, e.config.Database)
if e.config.User != "" {
connStr += fmt.Sprintf(" user=%s", e.config.User)
}
if e.config.Password != "" {
connStr += fmt.Sprintf(" password=%s", e.config.Password)
}
return connStr
}
func (e *PostgresEngine) GetIndexes() []*index {
conn, err := sql.Open("postgres", e.getConnectionString())
defer conn.Close()
rows, err := conn.Query(postgresIndexesQuery)
if err != nil {
log.Fatal("Query failed:", err.Error())
}
defer rows.Close()
var schemeName, tableName, indexName, indexDef string
indexes := make([]*index, 0)
var prevSchemeName, prevTableName, prevIndexName string
var currentIndex *index
for rows.Next() {
err = rows.Scan(&schemeName, &tableName, &indexName, &indexDef)
if err != nil {
log.Fatal("Scan failed:", err.Error())
}
if schemeName != prevSchemeName || tableName != prevTableName || indexName != prevIndexName {
prevSchemeName, prevTableName, prevIndexName = schemeName, tableName, indexName
isUnique := false
if strings.Contains(indexDef, " UNIQUE ") {
isUnique = true
}
currentIndex = &index{scheme: schemeName, table: tableName, index: indexName, enabled: true, unique: isUnique, columns: make([]string, 0, 10)}
indexes = append(indexes, currentIndex)
match := postgresIndexRe.FindStringSubmatch(indexDef)
columns := strings.Split(match[1], ",")
for _, column := range columns {
column = strings.TrimSpace(column)
currentIndex.columns = append(currentIndex.columns, column)
}
}
}
return indexes
}