This repository has been archived by the owner on Apr 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
sqlitedb.go
422 lines (394 loc) · 11.8 KB
/
sqlitedb.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
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
package main
import (
"database/sql"
"fmt"
"io/ioutil"
"os"
"sort"
"strconv"
"strings"
"time"
jsoniter "github.com/json-iterator/go"
_ "github.com/mattn/go-sqlite3"
"github.com/ti-community-infra/devstats/internal/pkg/lib"
)
// dashboard stores main dashoard keys title and uid
type dashboard struct {
Title string `json:"title"`
UID string `json:"uid"`
Tags []string `json:"tags"`
}
// dashboardData keeps all dashboard data & metadata
type dashboardData struct {
dash dashboard
id int
title string
slug string
data string
fn string
uid string
}
// String for dashboardData - skip displaying long JSON data
func (dd dashboardData) String() string {
return fmt.Sprintf(
"{dash:'%+v', id:%d, title:'%s', slug:'%s', data:len:%d, fn:'%s'}",
dd.dash, dd.id, dd.title, dd.slug, len(dd.data), dd.fn,
)
}
// sqliteQueryOut outputs SQLite query info
func sqliteQueryOut(query string, args ...interface{}) {
if len(args) > 0 {
lib.Printf("%+v\n", args)
}
lib.Printf("%s\n", query)
}
// sqliteQuery execute SQLite query with eventual logging output
func sqliteQuery(db *sql.DB, ctx *lib.Ctx, query string, args ...interface{}) (*sql.Rows, error) {
if ctx.QOut {
sqliteQueryOut(query, args...)
}
return db.Query(query, args...)
}
// sqliteExec SQLite exec call with eventual logging output
func sqliteExec(db *sql.DB, ctx *lib.Ctx, exec string, args ...interface{}) (sql.Result, error) {
if ctx.QOut {
sqliteQueryOut(exec, args...)
}
return db.Exec(exec, args...)
}
// updateTags make JSON and SQLite tags match each other
func updateTags(db *sql.DB, ctx *lib.Ctx, did int, jsonTags []string, info string) bool {
// Get SQLite DB dashboard tags
rows, err := sqliteQuery(
db,
ctx,
"select term from dashboard_tag where dashboard_id = ? order by term asc",
did,
)
lib.FatalOnError(err)
defer func() { lib.FatalOnError(rows.Close()) }()
tag := ""
dbTags := []string{}
for rows.Next() {
lib.FatalOnError(rows.Scan(&tag))
dbTags = append(dbTags, tag)
}
lib.FatalOnError(rows.Err())
// Sort jsonTags
sort.Strings(jsonTags)
sJSONTags := strings.Join(jsonTags, ",")
sDBTags := strings.Join(dbTags, ",")
// If the same tag set, return false - meaning no update was needed
if sJSONTags == sDBTags {
return false
}
// Now sync tags
allMap := make(map[string]struct{})
dbMap := make(map[string]struct{})
jsonMap := make(map[string]struct{})
for _, tag := range jsonTags {
jsonMap[tag] = struct{}{}
allMap[tag] = struct{}{}
}
for _, tag := range dbTags {
dbMap[tag] = struct{}{}
allMap[tag] = struct{}{}
}
nI := 0
nD := 0
for tag := range allMap {
_, j := jsonMap[tag]
_, d := dbMap[tag]
// We have it in JSOn but not in DB, insert
if j && !d {
_, err = sqliteExec(
db,
ctx,
"insert into dashboard_tag(dashboard_id, term) values(?, ?)",
did, tag,
)
lib.FatalOnError(err)
if ctx.Debug > 0 {
lib.Printf(
"Updating dashboard '%s' id: %d, '%v' -> '%v', inserted '%s' tag\n",
info, did, sDBTags, sJSONTags, tag,
)
}
nI++
}
// We have it in DB but not in JSON, delete
if !j && d {
_, err = sqliteExec(
db,
ctx,
"delete from dashboard_tag where dashboard_id = ? and term = ?",
did, tag,
)
lib.FatalOnError(err)
if ctx.Debug > 0 {
lib.Printf(
"Updating dashboard '%s' id: %d, '%v' -> '%v', deleted '%s' tag\n",
info, did, sDBTags, sJSONTags, tag,
)
}
nD++
}
}
lib.Printf(
"Updated dashboard tags '%s' id: %d, '%v' -> '%v', added: %d, removed: %d\n",
info, did, sDBTags, sJSONTags, nI, nD,
)
return true
}
// deleteUids opens dbFile and delete all dashboards with given uids
func deleteUids(ctx *lib.Ctx, dbFile string, uids []string) {
// Connect to SQLite3
db, err := sql.Open("sqlite3", dbFile)
lib.FatalOnError(err)
defer func() { lib.FatalOnError(db.Close()) }()
// Iterate uids
for _, uid := range uids {
rows, err := sqliteQuery(db, ctx, "select id from dashboard where uid = ?", uid)
lib.FatalOnError(err)
defer func() { lib.FatalOnError(rows.Close()) }()
id := -1
for rows.Next() {
lib.FatalOnError(rows.Scan(&id))
}
lib.FatalOnError(rows.Err())
if id < 0 {
lib.Printf("Dashboard with uid=%s not found, skipping\n", uid)
continue
}
_, err = sqliteExec(db, ctx, "delete from dashboard_tag where dashboard_id = ?", id)
lib.FatalOnError(err)
_, err = sqliteExec(db, ctx, "delete from dashboard where id = ?", id)
lib.FatalOnError(err)
lib.Printf("Deleted dashboard with uid %s\n", uid)
}
}
// exportJsons uses dbFile database to dump all dashboards as JSONs
func exportJsons(ctx *lib.Ctx, dbFile string) {
// Connect to SQLite3
db, err := sql.Open("sqlite3", dbFile)
lib.FatalOnError(err)
defer func() { lib.FatalOnError(db.Close()) }()
// Get all dashboards
rows, err := sqliteQuery(db, ctx, "select slug, title, data from dashboard")
lib.FatalOnError(err)
defer func() { lib.FatalOnError(rows.Close()) }()
var (
slug string
title string
data string
)
// Save all of them as sqlite/slug[i].json for i=0..n
for rows.Next() {
lib.FatalOnError(rows.Scan(&slug, &title, &data))
fn := "sqlite/" + slug + ".json"
lib.FatalOnError(ioutil.WriteFile(fn, lib.PrettyPrintJSON([]byte(data)), 0644))
lib.Printf("Written '%s' to %s\n", title, fn)
}
lib.FatalOnError(rows.Err())
}
// insertDashboard inserts new dashboard into SQLite database
func insertDashboard(db *sql.DB, ctx *lib.Ctx, dd *dashboardData) {
dd.uid = dd.dash.UID
dd.title = dd.dash.Title
dd.slug = lib.Slugify(dd.title)
// Insert new dashboard
_, err := sqliteExec(
db,
ctx,
"insert into dashboard(version, slug, title, data, "+
"org_id, created, updated, created_by, updated_by, "+
"gnet_id, plugin_id, folder_id, is_folder, has_acl, uid) "+
"values(1, ?, ?, ?, 1, ?, ?, 1, 1, 0, '', 0, 0, 0, ?)",
dd.slug, dd.title, dd.data, time.Now(), time.Now(), dd.uid,
)
lib.FatalOnError(err)
rows, err := sqliteQuery(db, ctx, "select max(id) from dashboard")
lib.FatalOnError(err)
defer func() { lib.FatalOnError(rows.Close()) }()
for rows.Next() {
lib.FatalOnError(rows.Scan(&dd.id))
}
lib.FatalOnError(rows.Err())
lib.Printf("Inserted dashboard: id=%d (uid=%s, title=%s, slug=%s)\n", dd.id, dd.uid, dd.title, dd.slug)
updated := updateTags(db, ctx, dd.id, dd.dash.Tags, dd.dash.UID+" "+dd.dash.Title)
if len(dd.dash.Tags) > 0 && !updated {
lib.Fatalf("should add new tags for %+v", dd)
}
}
// importJsons uses dbFile database to update list of JSONs
// It first loads all dashboards titles, slugs, ids and JSONs
// Then it parses all JSONs to get each dashboards UID
// Then it processes all JSONs provided, parses them, and gets each JSONs uid and title
// Each uid from JSON list must be unique
// Then for all JSON titles it creates slugs 'Name of Dashboard' -> 'name-of-dashboard'
// Finally it attempts to update SQLite database's data, tile, slug values by matching using UID
func importJsons(ctx *lib.Ctx, dbFile string, jsons []string) {
// DB backup func, executed when anything is updated
backedUp := false
contents, err := lib.ReadFile(ctx, dbFile)
lib.FatalOnError(err)
backupFunc := func() {
bfn := fmt.Sprintf("%s.%v", dbFile, time.Now().UnixNano())
lib.FatalOnError(ioutil.WriteFile(bfn, contents, 0644))
lib.Printf("Original db file backed up as' %s'\n", bfn)
}
// Connect to SQLite3
db, err := sql.Open("sqlite3", dbFile)
lib.FatalOnError(err)
defer func() { lib.FatalOnError(db.Close()) }()
// Load and parse all dashboards JSONs
// Will keep uid --> sqlite dashboard data map
dbMap := make(map[string]dashboardData)
rows, err := sqliteQuery(db, ctx, "select id, data, title, slug, uid from dashboard")
lib.FatalOnError(err)
defer func() { lib.FatalOnError(rows.Close()) }()
for rows.Next() {
var dd dashboardData
lib.FatalOnError(rows.Scan(&dd.id, &dd.data, &dd.title, &dd.slug, &dd.uid))
lib.FatalOnError(jsoniter.Unmarshal([]byte(dd.data), &dd.dash))
if dd.title != dd.dash.Title {
lib.Printf("SQLite internal inconsistency (title): %s != %s: %+v, using value from dashboard table, not from JSON\n", dd.title, dd.dash.Title, dd)
dd.dash.Title = dd.title
}
if dd.uid != dd.dash.UID {
lib.Printf("SQLite internal inconsistency (uid): %s != %s: %+v, using value from dashboard table, not from JSON\n", dd.uid, dd.dash.UID, dd)
dd.dash.UID = dd.uid
}
dd.data = string(lib.PrettyPrintJSON([]byte(dd.data)))
dd.fn = "*" + dd.slug + ".json*"
dbMap[dd.dash.UID] = dd
}
lib.FatalOnError(rows.Err())
nDbMap := len(dbMap)
// Now load & parse JSON arguments
jsonMap := make(map[string]dashboardData)
nIns := 0
for _, j := range jsons {
var dd dashboardData
bytes, err := lib.ReadFile(ctx, j)
lib.FatalOnError(err)
lib.FatalOnError(jsoniter.Unmarshal(bytes, &dd.dash))
dbDash, ok := dbMap[dd.dash.UID]
if !ok {
dd.data = string(lib.PrettyPrintJSON(bytes))
dd.fn = j
insertDashboard(db, ctx, &dd)
if !backedUp {
backupFunc()
backedUp = true
}
nIns++
continue
}
jsonDash, ok := jsonMap[dd.dash.UID]
if ok {
lib.Fatalf("%s: duplicate json uid, attempt to import %v, collision with %v", j, dd.dash, jsonDash.dash)
}
dd.data = string(lib.PrettyPrintJSON(bytes))
dd.id = dbDash.id
dd.uid = dd.dash.UID
dd.title = dd.dash.Title
dd.slug = lib.Slugify(dd.title)
dd.fn = j
jsonMap[dd.dash.UID] = dd
}
nJSONMap := len(jsonMap)
// Now do updates
nImp := 0
for uid, dd := range jsonMap {
ddWas := dbMap[uid]
if ctx.Debug > 1 {
lib.Printf("\n%+v\n%+v\n\n", dd.String(), ddWas.String())
}
// Update/check tags
updated := updateTags(db, ctx, dd.id, dd.dash.Tags, dd.dash.UID+" "+dd.dash.Title)
// Check if we actually need to update anything
if ddWas.dash.Title == dd.dash.Title && ddWas.slug == dd.slug && ddWas.data == dd.data {
if updated {
if !backedUp {
backupFunc()
backedUp = true
}
nImp++
}
continue
}
// Update JSON inside database
_, err = sqliteExec(
db,
ctx,
"update dashboard set title = ?, slug = ?, data = ? where id = ?",
dd.dash.Title, dd.slug, dd.data, dd.id,
)
lib.FatalOnError(err)
// Info
if ctx.Debug > 0 {
lib.Printf(
"%s: updated uid: %s: tags updated: %v\nnew: %+v\nold: %+v\n",
dd.fn, uid, updated, dd, ddWas,
)
} else {
lib.Printf(
"%s: updated dashboard: uid: %s title: '%s' -> '%s', slug: '%s' -> '%s', tags: %v:%v (data %d -> %d bytes)\n",
dd.fn, uid, ddWas.dash.Title, dd.dash.Title, ddWas.slug, dd.slug, updated, dd.dash.Tags, len(ddWas.data), len(dd.data),
)
}
// And save JSON from DB
lib.FatalOnError(ioutil.WriteFile(dd.fn+".was", []byte(ddWas.data), 0644))
// Something changed, backup original db file
if !backedUp {
backupFunc()
backedUp = true
}
nImp++
}
lib.Printf(
"SQLite DB has %d dashboards, there were %d JSONs to import, updated %d, created %d\n",
nDbMap, nJSONMap+nIns, nImp, nIns)
}
func main() {
dtStart := time.Now()
// Environment context parse
var ctx lib.Ctx
ctx.Init()
if len(os.Args) < 2 {
lib.Printf("Required args: grafana.db file name and list(*) of jsons to import.\n")
lib.Printf("If only db file name given, it will output all dashboards to jsons\n")
lib.Printf("It will import JSONs by matching their internal uid with SQLite database\n")
lib.Printf("If DB name given and single argument with comman separated uids - dashboards with those uids will be removed\n")
os.Exit(1)
}
del := false
uids := []string{}
if len(os.Args) == 3 {
ary := strings.Split(os.Args[2], ",")
brk := false
for _, item := range ary {
_, err := strconv.Atoi(item)
if err != nil {
brk = true
break
}
uids = append(uids, item)
}
if !brk {
del = true
}
}
if del {
deleteUids(&ctx, os.Args[1], uids)
} else {
if len(os.Args) > 2 {
importJsons(&ctx, os.Args[1], os.Args[2:])
} else {
exportJsons(&ctx, os.Args[1])
}
}
dtEnd := time.Now()
lib.Printf("Time: %v\n", dtEnd.Sub(dtStart))
}