-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
654 lines (617 loc) · 18 KB
/
main.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
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
package main
import (
"database/sql"
"encoding/csv"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/antlr/antlr4/runtime/Go/antlr"
parser "github.com/nycmonkey/sprocs/tsql"
pb "gopkg.in/cheggaaa/pb.v1"
_ "github.com/denisenkom/go-mssqldb"
)
const (
portfolioShortName = `PortfolioShortName`
guggenheimUnitShortName = `GuggenheimUnitShortName`
relationshipShortName = `RelationshipShortName`
clientShortName = `ClientShortName`
accountShortName = `AccountShortName`
portfolioCode = `PortfolioCode`
)
var (
dbHost string
bar *pb.ProgressBar
faster bool
activeSprocQ = `
select ROUTINE_NAME from BRS.information_schema.routines
where routine_type = 'PROCEDURE'
and Left(Routine_Name, 3) NOT IN ('sp_', 'xp_', 'ms_')
`
sprocQ = `
SELECT OBJECT_DEFINITION (OBJECT_ID(?))
`
tableQ = `
SELECT TABLE_NAME FROM BRS.INFORMATION_SCHEMA.Tables WHERE TABLE_SCHEMA = 'dbo'
`
portfolioQ = `
SELECT [PortfolioShortName]
,[GuggenheimUnitShortName]
,[RelationshipShortName]
,[ClientShortName]
,[AccountShortName]
,[PortfolioCode]
FROM [BRS].[dbo].[vw_AMPortfolioMaster]
`
outDir string
whitelist map[string]struct{}
portfolioShortNames map[string]struct{}
clientShortNames map[string]struct{}
businessUnitShortNames map[string]struct{}
relationshipShortNames map[string]struct{}
accountShortNames map[string]struct{}
portfolioCodes map[string]struct{}
)
// TreeShapeListener handles events from a TSQL parser generated by Antlr
type TreeShapeListener struct {
*parser.BasetsqlListener
inProcDef bool
info *SprocInfo
tablesUsedCh chan<- string
idsUsedCh chan<- string
}
// SprocInfo is a structure to record stored procedure metadata
type SprocInfo struct {
Name string
Tables map[string]struct{}
Aliases map[string]struct{}
Codes map[string]struct{}
}
// emailAccount captures sproc report recipient details looked up by email address in CORP DB
type emailAccount struct {
FirstName string
LastName string
LegalEntityName string
BusinessUnit int
BUText string
Position string
Location string
DirectManager string
}
type keyValue struct {
key, value string
}
// errorListener extends the default error listener generated by antlr to send TSQL syntax errors down a channel
type errorListener struct {
*antlr.DefaultErrorListener
errCh chan<- keyValue
sprocName string
}
func init() {
flag.StringVar(&dbHost, "host", "IL1TSTSQL10", "sproc database host server name")
flag.BoolVar(&faster, "fast", false, "use a faster but less error-tolerant parsing strategy")
whitelist = make(map[string]struct{})
portfolioShortNames = make(map[string]struct{})
clientShortNames = make(map[string]struct{})
businessUnitShortNames = make(map[string]struct{})
relationshipShortNames = make(map[string]struct{})
accountShortNames = make(map[string]struct{})
portfolioCodes = make(map[string]struct{})
}
func main() {
flag.Parse()
outDir = outDirPath()
defDir := filepath.Join(outDir, `sproc_definitions`)
err := os.MkdirAll(defDir, os.ModeDir)
if err != nil {
log.Fatalln("Couldn't create output directory:", err)
}
log.Println("Writing output to", outDir)
sprocCh := make(chan keyValue)
tablesCh := make(chan []string, 1)
codesCh := make(chan []string, 1)
tablesHandled := make(chan struct{})
portfoliosHandled := make(chan struct{})
errorsHandled := make(chan struct{})
errCh := make(chan []string, 1)
go handleTables(tablesCh, tablesHandled)
go handleCodes(codesCh, portfoliosHandled)
go handleErrors(errCh, errorsHandled)
wg := new(sync.WaitGroup)
for i := 0; i < 6; i++ {
// spin up a bunch of concurrent sproc parsing routines, and watch the CPU burn
wg.Add(1)
go handleSprocDetails(defDir, sprocCh, tablesCh, codesCh, errCh, wg)
}
err = getSprocs(defDir, sprocCh)
if err != nil {
log.Fatalln("error querying", dbHost+":", err)
}
wg.Wait() // this can take a while
close(tablesCh)
close(errCh)
close(codesCh)
<-tablesHandled
<-errorsHandled
<-portfoliosHandled
bar.FinishPrint("All sprocs parsed")
}
func outDirPath() string {
return fmt.Sprintf("%s_%s", time.Now().Format(`2006-01-02`), dbHost)
}
func getSprocs(defDir string, outCh chan<- keyValue) error {
log.Println("Querying", dbHost)
defer close(outCh)
db, err := sql.Open("mssql", "server="+dbHost+";database=BRS;ApplicationIntent=ReadOnly")
if err != nil {
log.Fatalln(err)
}
defer db.Close()
log.Println("Fetching list of known tables")
fmt.Println(tableQ)
rows, err := db.Query(tableQ)
if err != nil {
return err
}
for rows.Next() {
var tableName string
if err = rows.Scan(&tableName); err != nil {
rows.Close()
return err
}
whitelist[strings.ToUpper(strings.TrimSpace(tableName))] = struct{}{}
}
rows.Close()
log.Println("Loaded table whitelist with", len(whitelist), "values")
log.Println("Fetching account / portfolio identifiers")
{
rows, err := db.Query(portfolioQ)
if err != nil {
return err
}
var count int
var psn, gusn, rsn, csn, asn sql.NullString
var pc sql.NullInt64
for rows.Next() {
if err = rows.Scan(&psn, &gusn, &rsn, &csn, &asn, &pc); err != nil {
rows.Close()
return err
}
if psn.Valid && len(strings.TrimSpace(psn.String)) > 0 {
portfolioShortNames[psn.String] = struct{}{}
}
if gusn.Valid && len(strings.TrimSpace(gusn.String)) > 0 {
businessUnitShortNames[gusn.String] = struct{}{}
}
if rsn.Valid && len(strings.TrimSpace(rsn.String)) > 0 {
relationshipShortNames[rsn.String] = struct{}{}
}
if csn.Valid && len(strings.TrimSpace(csn.String)) > 0 {
clientShortNames[csn.String] = struct{}{}
}
if asn.Valid && len(strings.TrimSpace(asn.String)) > 0 {
accountShortNames[asn.String] = struct{}{}
}
if pc.Valid {
portfolioCodes[fmt.Sprintf("%d", pc.Int64)] = struct{}{}
}
count++
}
rows.Close()
log.Println("Loaded", count, "account master rows")
}
log.Println("Looking up active stored procedures")
fmt.Println(activeSprocQ)
rows, err = db.Query(activeSprocQ)
if err != nil {
return err
}
defer rows.Close()
var sprocNames []string
for rows.Next() {
var sprocName sql.NullString
if err = rows.Scan(&sprocName); err != nil {
rows.Close()
return err
}
if sprocName.Valid {
sprocNames = append(sprocNames, sprocName.String)
}
}
rows.Close()
log.Println("Found", len(sprocNames), "active stored procedures")
var def sql.NullString
// fetch sproc definitions
log.Println("Fetching stored procedure definitions")
fmt.Println(sprocQ)
validIndices := make([]int, 0, len(sprocNames))
for i, sn := range sprocNames {
err := db.QueryRow(sprocQ, `BRS.dbo.`+sn).Scan(&def)
if err != nil {
return errors.New("error while querying definition of " + sn + ": " + err.Error())
}
if !def.Valid {
log.Println("No definition found for", sn)
continue
}
validIndices = append(validIndices, i)
var f *os.File
f, err = os.Create(filepath.Join(defDir, strings.Replace(sn, "/", "_", -1)+".sql"))
if err != nil {
return err
}
_, err = f.WriteString(def.String)
f.Close()
if err != nil {
return err
}
}
db.Close()
log.Println("Found and saved defintions for", len(validIndices), "of", len(sprocNames), "active stored procedures")
log.Println("Starting parsing phase (this can take a while)...")
// initiate progress bar
bar = pb.New(len(validIndices))
bar.ShowFinalTime = true
bar.ShowBar = true
bar.SetMaxWidth(80)
bar.Start()
for _, i := range validIndices {
var def []byte
def, err = ioutil.ReadFile(filepath.Join(defDir, strings.Replace(sprocNames[i], "/", "_", -1)+".sql"))
if err != nil {
return err
}
outCh <- keyValue{key: sprocNames[i], value: string(def)}
}
return nil
}
func handleTables(ch <-chan []string, done chan<- struct{}) {
f, err := os.Create(filepath.Join(outDir, "table_sources.csv"))
if err != nil {
log.Fatalln(err)
}
defer f.Close()
w := csv.NewWriter(f)
w.UseCRLF = true
w.Write([]string{"Stored Procedure", "Table Used"})
for row := range ch {
w.Write(row)
}
w.Flush()
done <- struct{}{}
}
func handleCodes(ch <-chan []string, done chan<- struct{}) {
f, err := os.Create(filepath.Join(outDir, "codes.csv"))
if err != nil {
log.Fatalln(err)
}
defer f.Close()
w := csv.NewWriter(f)
w.UseCRLF = true
w.Write([]string{"Stored Procedure", "Account Master Column", "Account Master Value"})
for row := range ch {
w.Write(row)
}
w.Flush()
done <- struct{}{}
}
func handleErrors(ch <-chan []string, done chan<- struct{}) {
f, err := os.Create(filepath.Join(outDir, "parsing_errors.csv"))
if err != nil {
log.Fatalln(err)
}
defer f.Close()
w := csv.NewWriter(f)
w.UseCRLF = true
w.Write([]string{"Stored Procedure", "Error Count"})
counts := make(map[string]int)
for row := range ch {
counts[row[0]]++
}
for proc, count := range counts {
w.Write([]string{proc, strconv.Itoa(count)})
}
w.Flush()
done <- struct{}{}
}
func handleSprocDetails(defDir string, inCh <-chan keyValue, outCh chan<- []string, idCh chan<- []string, errCh chan<- []string, done *sync.WaitGroup) {
for s := range inCh {
errors, tables, identifiers := parseSproc(s)
for _, e := range errors {
errCh <- []string{s.key, e}
}
for _, t := range tables {
outCh <- []string{s.key, t}
}
for _, id := range identifiers {
idCh <- []string{s.key, id.col, id.val}
}
bar.Increment()
}
done.Done()
}
func removeBrackets(in string) string {
return strings.TrimPrefix(strings.TrimSuffix(in, "]"), "[")
}
func normalizeTableName(in string) (out string) {
elems := strings.Split(strings.ToUpper(strings.TrimSpace(in)), ".")
switch len(elems) {
case 0:
// nothin' here, send back empty string
log.Fatalln("missing table name")
case 1, 2:
// assumption: it's just the table name or dbo.table_name
out = removeBrackets(elems[len(elems)-1])
case 3:
var normalizedElems []string
for _, elem := range elems {
normalizedElems = append(normalizedElems, removeBrackets(elem))
}
if normalizedElems[0] == `BRS` {
out = normalizedElems[2]
} else {
out = strings.Join(normalizedElems, ".")
}
default:
log.Fatalln("unhandled table name format:", in)
}
return
}
func (l *errorListener) SyntaxError(recognizer antlr.Recognizer, offendingSymbol interface{}, line, column int, msg string, e antlr.RecognitionException) {
l.errCh <- keyValue{key: l.sprocName, value: fmt.Sprintf("Line: %d, Column: %d, Error: %s", line, column, msg)}
}
func newErrorListener(ch chan<- keyValue, sprocName string) *errorListener {
return &errorListener{
antlr.NewDefaultErrorListener(),
ch,
sprocName,
}
}
type identifier struct {
col string
val string
}
// parse sproc runs the dumped sproc definition through a parser generated by antlr
// using the TSQL grammar definition from https://github.com/antlr/grammars-v4/tree/master/tsql
// The TreeShapeListener definied in this package extends the default listener generated by antlr to capture the
// data we care about. Similarly, the ErrorListener defined in this package receives and handles parsing errors.
// The caller specifies channels to receive a stream of tables used and errors encountered during parsing. The key of
// the sproc parameter is the (string) name of the stored procedure, and the value is the (string) text of the sproc
// defintion
func parseSproc(sproc keyValue) (errors, tables []string, identifiers []identifier) {
tCh := make(chan string)
idCh := make(chan string)
eCh := make(chan keyValue)
wg := new(sync.WaitGroup)
wg.Add(3)
go func(ch <-chan keyValue) {
for err := range ch {
errors = append(errors, err.value)
}
wg.Done()
}(eCh)
go func(ch <-chan string) {
for table := range ch {
tables = append(tables, table)
}
wg.Done()
}(tCh)
go func(ch <-chan string) {
for id := range ch {
kv := strings.Split(id, `:`)
identifiers = append(identifiers, identifier{col: kv[0], val: kv[1]})
}
wg.Done()
}(idCh)
input := antlr.NewInputStream(sproc.value)
lexer := parser.NewtsqlLexer(input)
stream := antlr.NewCommonTokenStream(lexer, 0)
p := parser.NewtsqlParser(stream)
p.RemoveErrorListeners()
errL := newErrorListener(eCh, sproc.key)
p.AddErrorListener(errL)
p.BuildParseTrees = true
if faster {
p.GetInterpreter().SetPredictionMode(antlr.PredictionModeSLL)
}
tree := p.Tsql_file()
antlr.ParseTreeWalkerDefault.Walk(NewTreeShapeListener(tCh, idCh), tree)
close(tCh)
close(idCh)
close(eCh)
wg.Wait()
return
}
// NewSprocInfo returns a data structure ready to record stored procedure metadata from a listener
func NewSprocInfo() *SprocInfo {
return &SprocInfo{
Tables: make(map[string]struct{}),
Aliases: make(map[string]struct{}),
Codes: make(map[string]struct{}),
}
}
// NewTreeShapeListener returns an allocated TreeShapeListener
func NewTreeShapeListener(tablesCh, identifiersCh chan<- string) *TreeShapeListener {
return &TreeShapeListener{
&parser.BasetsqlListener{},
false,
NewSprocInfo(),
tablesCh,
identifiersCh,
}
}
// EnterTable_name is called when the parser enters a `table_name` node,
// which includes the name of the table from whcih data is sourced
func (l *TreeShapeListener) EnterTable_name(ctx *parser.Table_nameContext) {
n := normalizeTableName(strings.TrimSpace(ctx.GetText()))
if len(n) > 0 {
l.info.Tables[n] = struct{}{}
}
}
// EnterSimple_id is called when the parser enters a `simple_id` node
func (l *TreeShapeListener) EnterSimple_id(ctx *parser.Simple_idContext) {
id := strings.TrimSpace(ctx.GetText())
var ok bool
if _, ok = portfolioShortNames[id]; ok {
l.info.Codes[portfolioCode+":"+id] = struct{}{}
}
if _, ok = businessUnitShortNames[id]; ok {
l.info.Codes[guggenheimUnitShortName+":"+id] = struct{}{}
}
if _, ok = relationshipShortNames[id]; ok {
l.info.Codes[relationshipShortName+":"+id] = struct{}{}
}
if _, ok = clientShortNames[id]; ok {
l.info.Codes[clientShortName+":"+id] = struct{}{}
}
if _, ok = accountShortNames[id]; ok {
l.info.Codes[accountShortName+":"+id] = struct{}{}
}
if _, ok = portfolioCodes[id]; ok {
l.info.Codes[portfolioCode+":"+id] = struct{}{}
}
}
// EnterConstant is called when the parser enters a `simple_id` node
func (l *TreeShapeListener) EnterConstant(ctx *parser.ConstantContext) {
id := strings.TrimSpace(ctx.GetText())
id = strings.TrimPrefix(id, `'`)
id = strings.TrimSuffix(id, `'`)
var ok bool
if _, ok = portfolioShortNames[id]; ok {
l.info.Codes[portfolioCode+":"+id] = struct{}{}
}
if _, ok = businessUnitShortNames[id]; ok {
l.info.Codes[guggenheimUnitShortName+":"+id] = struct{}{}
}
if _, ok = relationshipShortNames[id]; ok {
l.info.Codes[relationshipShortName+":"+id] = struct{}{}
}
if _, ok = clientShortNames[id]; ok {
l.info.Codes[clientShortName+":"+id] = struct{}{}
}
if _, ok = accountShortNames[id]; ok {
l.info.Codes[accountShortName+":"+id] = struct{}{}
}
if _, ok = portfolioCodes[id]; ok {
l.info.Codes[portfolioCode+":"+id] = struct{}{}
}
// handle suffix wildcards
if strings.HasSuffix(id, "%") {
id = strings.TrimSuffix(id, "%")
for k := range portfolioShortNames {
if strings.HasPrefix(k, id) {
l.info.Codes[portfolioCode+":"+id] = struct{}{}
}
}
for k := range businessUnitShortNames {
if strings.HasPrefix(k, id) {
l.info.Codes[guggenheimUnitShortName+":"+id] = struct{}{}
}
}
for k := range relationshipShortNames {
if strings.HasPrefix(k, id) {
l.info.Codes[relationshipShortName+":"+id] = struct{}{}
}
}
for k := range clientShortNames {
if strings.HasPrefix(k, id) {
l.info.Codes[clientShortName+":"+id] = struct{}{}
}
}
for k := range accountShortNames {
if strings.HasPrefix(k, id) {
l.info.Codes[accountShortName+":"+id] = struct{}{}
}
}
for k := range portfolioCodes {
if strings.HasPrefix(k, id) {
l.info.Codes[portfolioCode+":"+id] = struct{}{}
}
}
}
// handle prefix wildcards
if strings.HasPrefix(id, "%") {
id = strings.TrimPrefix(id, "%")
for k := range portfolioShortNames {
if strings.HasSuffix(k, id) {
l.info.Codes[portfolioCode+":"+id] = struct{}{}
}
}
for k := range businessUnitShortNames {
if strings.HasSuffix(k, id) {
l.info.Codes[guggenheimUnitShortName+":"+id] = struct{}{}
}
}
for k := range relationshipShortNames {
if strings.HasSuffix(k, id) {
l.info.Codes[relationshipShortName+":"+id] = struct{}{}
}
}
for k := range clientShortNames {
if strings.HasSuffix(k, id) {
l.info.Codes[clientShortName+":"+id] = struct{}{}
}
}
for k := range accountShortNames {
if strings.HasSuffix(k, id) {
l.info.Codes[accountShortName+":"+id] = struct{}{}
}
}
for k := range portfolioCodes {
if strings.HasSuffix(k, id) {
l.info.Codes[portfolioCode+":"+id] = struct{}{}
}
}
}
}
// EnterTable_alias is called when the parser enters a `table_alias` node,
// which is pulled into a list of table references to ignore
func (l *TreeShapeListener) EnterTable_alias(ctx *parser.Table_aliasContext) {
n := normalizeTableName(strings.TrimSpace(ctx.GetText()))
if len(n) > 0 {
l.info.Aliases[strings.ToUpper(n)] = struct{}{}
}
}
// ExitTsql_file is called when the parser reaches the end of the TSQL input,
// at which point the table names used are analyzed and sent down a channel
func (l *TreeShapeListener) ExitTsql_file(ctx *parser.Tsql_fileContext) {
seen := make(map[string]struct{})
for table := range l.info.Tables {
if strings.HasPrefix(table, "#") {
continue
}
_, ok := l.info.Aliases[strings.ToUpper(table)]
if ok {
// skip it - it's an alias
continue
}
_, ok = seen[strings.ToUpper(table)]
if ok {
// skip it - it's a dupe
continue
}
seen[strings.ToUpper(table)] = struct{}{}
if strings.Contains(table, ".") {
// no need to check the whitelist -- this table refers to a DB other than BRS
l.tablesUsedCh <- table
continue
}
// check to see if the table is in the whitelist populated during getSprocs()
_, ok = whitelist[strings.ToUpper(table)]
if !ok {
// skip it -- it's not in the whitelist
continue
}
l.tablesUsedCh <- table
}
for code := range l.info.Codes {
l.idsUsedCh <- code
}
}