-
Notifications
You must be signed in to change notification settings - Fork 3
/
db_schema_sync.go
332 lines (277 loc) · 8.17 KB
/
db_schema_sync.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
package pgvertica
import (
"database/sql"
"fmt"
"regexp"
"strings"
)
type SchemasSynchronizator struct {
vdb *sql.DB
pgdb *sql.DB
}
func NewSchemasSynchronizator(vConnStr string, pgConnStr string) (*SchemasSynchronizator, error) {
vdb, vErr := connectToDB(RealDBOpener{}, "vertica", vConnStr, nil)
if vErr != nil {
Logger.Error("Can't connect to Vertica")
return nil, vErr
}
Logger.Info("established connection to Vertica")
pgdb, pgErr := connectToDB(RealDBOpener{}, "postgres", pgConnStr, nil)
if pgErr != nil {
Logger.Error("Can't connect to Postgres")
return nil, vErr
}
Logger.Info("established connection to Postgres")
return &SchemasSynchronizator{
vdb: vdb,
pgdb: pgdb,
}, nil
}
func (s *SchemasSynchronizator) Close() (err error) {
if s.vdb != nil {
if e := s.vdb.Close(); err == nil {
err = e
}
}
if s.pgdb != nil {
if e := s.pgdb.Close(); err == nil {
err = e
}
}
return err
}
func (s *SchemasSynchronizator) SyncDBschemas() error {
var err error
var schemasToSync []string
if schemasToSync, err = s.ListSchemas(); err != nil {
return err
}
if len(schemasToSync) == 0 {
Logger.Info("No schemas to sync")
return nil
}
Logger.Info("Sync schemas", "schemas", schemasToSync)
for _, schemaName := range schemasToSync {
if err = s.recreateSchemaOnPostgres(schemaName); err != nil {
return err
}
if err := s.deleteNonExistentTablesInPG(schemaName); err != nil {
return err
}
}
if err = s.syncRoles(schemasToSync); err != nil {
Logger.Error("Error syncing roles", "error", err)
}
Logger.Info("Schemas synced")
return nil
}
func (s *SchemasSynchronizator) syncRoles(schemas []string) error {
Logger.Debug("Sync roles")
roles, err := s.listRoles()
if err != nil {
return err
}
for _, role := range roles {
if exists, err := s.roleExists(role); err == nil {
if !exists {
create_role_sql := fmt.Sprintf("CREATE ROLE %s", role)
if _, err := s.pgdb.Exec(create_role_sql); err != nil {
return err
}
Logger.Debug("Role created", "role", role)
} else {
Logger.Debug("Role already exists", "role", role)
}
} else {
return err
}
}
for _, schema := range schemas {
for _, role := range roles {
if err := s.grantPermissionToSchema(schema, role); err != nil {
return err
}
if err := s.grantPermissionToTablesInSchema(schema, role); err != nil {
return err
}
}
}
return nil
}
func (s *SchemasSynchronizator) grantPermissionToSchema(schemaName string, role string) error {
grant_sql := fmt.Sprintf("GRANT ALL ON SCHEMA %s TO %s;", schemaName, role)
if _, err := s.pgdb.Exec(grant_sql); err != nil {
Logger.Error("Error on query", "query", grant_sql, "error", err)
return err
}
return nil
}
func (s *SchemasSynchronizator) grantPermissionToTablesInSchema(schemaName string, role string) error {
tables, err := s.listTablesInSchemaPostgres(schemaName)
if err != nil {
return err
}
for _, table := range tables {
sql := fmt.Sprintf("GRANT ALL ON TABLE %s.%s TO %s;", schemaName, table, role)
if _, err := s.pgdb.Exec(sql); err != nil {
Logger.Error("Error on query", "query", sql, "error", err)
return err
}
}
return nil
}
func (s *SchemasSynchronizator) listRoles() ([]string, error) {
rolesSql := "SELECT name from v_catalog.roles;"
roles, err := s.listIds(s.vdb, rolesSql)
if err != nil {
return nil, err
}
usersSql := "SELECT user_name from v_catalog.users;"
users, err := s.listIds(s.vdb, usersSql)
if err != nil {
return nil, err
}
return append(roles, users...), nil
}
func (s *SchemasSynchronizator) roleExists(role string) (bool, error) {
var exists bool
query := fmt.Sprintf("SELECT 1 FROM pg_roles WHERE rolname='%s'", role)
err := s.pgdb.QueryRow(query).Scan(&exists)
if err != nil {
if err == sql.ErrNoRows {
return false, nil
}
return false, err
}
return true, nil
}
func (s *SchemasSynchronizator) deleteNonExistentTablesInPG(schema string) error {
verticaTables, err := s.listTablesInSchemaVertica(schema)
if err != nil {
return err
}
postgresTables, err := s.listTablesInSchemaPostgres(schema)
if err != nil {
return err
}
for _, tableName := range postgresTables {
if !contains(verticaTables, tableName) {
Logger.Debug("Drop table", "table", tableName)
if err := s.dropTablePostgres(schema, tableName); err != nil {
return err
}
}
}
return nil
}
func (s *SchemasSynchronizator) listTablesInSchemaVertica(schema string) ([]string, error) {
query := fmt.Sprintf(`SELECT table_name FROM v_catalog.tables WHERE table_schema='%s';`, schema)
return s.listIds(s.vdb, query)
}
func (s *SchemasSynchronizator) listTablesInSchemaPostgres(schema string) ([]string, error) {
query := fmt.Sprintf(`SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = '%s';`, schema)
return s.listIds(s.pgdb, query)
}
func (s *SchemasSynchronizator) listIds(db *sql.DB, query string) ([]string, error) {
rows, err := db.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
var ids []string
for rows.Next() {
var tableName string
if err := rows.Scan(&tableName); err != nil {
return nil, err
}
ids = append(ids, tableName)
}
return ids, rows.Err()
}
func (s *SchemasSynchronizator) dropTablePostgres(schema, table string) error {
query := fmt.Sprintf("DROP TABLE IF EXISTS %s.%s;", schema, table)
_, err := s.pgdb.Exec(query)
return err
}
func contains(slice []string, item string) bool {
for _, a := range slice {
if a == item {
return true
}
}
return false
}
func (s *SchemasSynchronizator) recreateSchemaOnPostgres(schemaName string) error {
_, err := s.pgdb.Exec(fmt.Sprintf("CREATE SCHEMA IF NOT EXISTS %s", schemaName))
if err != nil {
return err
}
exportedSchema, err := s.exportSchema(schemaName)
if err != nil {
return err
}
for _, createTableQuery := range getCreateTableStatements(exportedSchema) {
translatedQuery := translateCreateTableToPostgres(createTableQuery)
Logger.Debug("Run translated query on postgres", "query", translatedQuery)
if _, err := s.pgdb.Exec(translatedQuery); err != nil {
Logger.Error("Error on query", "query", translatedQuery, "error", err)
}
}
return nil
}
func (s *SchemasSynchronizator) ListSchemas() ([]string, error) {
rows, err := s.vdb.Query("SELECT schema_name FROM v_catalog.schemata")
if err != nil {
return nil, fmt.Errorf("failed to list schemas: %v", err)
}
defer rows.Close()
var schemas []string = make([]string, 0)
for rows.Next() {
var schemaName string
err := rows.Scan(&schemaName)
if err != nil {
return nil, fmt.Errorf("failed to scan schema_name: %v", err)
}
if !strings.HasPrefix(schemaName, "v_") && schemaName != "public" {
schemas = append(schemas, schemaName)
}
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("failed to iterate through rows: %v", err)
}
return schemas, nil
}
func (s *SchemasSynchronizator) exportSchema(schemaName string) (string, error) {
row := s.vdb.QueryRow(fmt.Sprintf("SELECT export_objects('', '%s')", schemaName))
var exportedSchema string
err := row.Scan(&exportedSchema)
if err != nil {
return "", fmt.Errorf("failed to export schema '%s': %v", schemaName, err)
}
return exportedSchema, nil
}
func getCreateTableStatements(schema string) []string {
lines := strings.Split(schema, "\n\n")
var filteredLines []string
for _, line := range lines {
trimmedLine := strings.TrimSpace(line)
if createTableRegex.MatchString(trimmedLine) {
filteredLines = append(filteredLines, line)
}
}
return filteredLines
}
func translateCreateTableToPostgres(createTableStatement string) string {
createTableStatement = strings.Replace(createTableStatement, "CREATE TABLE", "CREATE TABLE IF NOT EXISTS", 15)
for verticaType, postgresType := range VERTICA_TO_POSTGRES_TYPE_MAPPING {
createTableStatement = strings.ReplaceAll(createTableStatement, verticaType, postgresType)
}
createTableStatement = replaceTextRegex.ReplaceAllString(createTableStatement, "text")
createTableStatement = partitionByRegex.ReplaceAllString(createTableStatement, "")
return createTableStatement
}
var (
createTableRegex = regexp.MustCompile(`(?i)^CREATE\s+TABLE`)
replaceTextRegex = regexp.MustCompile(`text\(\d*?\)`)
partitionByRegex = regexp.MustCompile(`PARTITION BY \(.*\)`)
)