-
Notifications
You must be signed in to change notification settings - Fork 168
/
config.go
795 lines (718 loc) · 19.2 KB
/
config.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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
package config
import (
"fmt"
"net/url"
"os"
"path/filepath"
"strings"
"github.com/aquasecurity/go-version/pkg/version"
"github.com/goccy/go-yaml"
"github.com/k1LoW/expand"
"github.com/k1LoW/tbls/dict"
"github.com/k1LoW/tbls/schema"
ver "github.com/k1LoW/tbls/version"
"github.com/minio/pkg/wildcard"
"github.com/pkg/errors"
)
const DefaultDocPath = "dbdoc"
var DefaultConfigFilePaths = []string{".tbls.yml", "tbls.yml"}
// DefaultERFormat is the default ER diagram format
const DefaultERFormat = "svg"
const SchemaFileName = "schema.json"
// DefaultERDistance is the default distance between tables that display relations in the ER
var DefaultERDistance = 1
// Config is tbls config
type Config struct {
Name string `yaml:"name"`
Desc string `yaml:"desc,omitempty"`
Labels []string `yaml:"labels,omitempty"`
DSN DSN `yaml:"dsn"`
// Directory of schema document
DocPath string `yaml:"docPath"`
Format Format `yaml:"format,omitempty"`
ER ER `yaml:"er,omitempty"`
Include []string `yaml:"include,omitempty"`
Exclude []string `yaml:"exclude,omitempty"`
Distance int `yaml:"distance,omitempty"`
Lint Lint `yaml:"lint,omitempty"`
LintExclude []string `yaml:"lintExclude,omitempty"`
Relations []AdditionalRelation `yaml:"relations,omitempty"`
Comments []AdditionalComment `yaml:"comments,omitempty"`
Dict dict.Dict `yaml:"dict,omitempty"`
Templates Templates `yaml:"templates,omitempty"`
DetectVirtualRelations DetectVirtualRelations `yaml:"detectVirtualRelations,omitempty"`
BaseUrl string `yaml:"baseUrl,omitempty"`
RequiredVersion string `yaml:"requiredVersion,omitempty"`
DisableOutputSchema bool `yaml:"disableOutputSchema,omitempty"`
MergedDict dict.Dict `yaml:"-"`
// Table labels to be included
includeLabels []string
// Path of config file
Path string `yaml:"-"`
root string `yaml:"-"`
}
type DSN struct {
URL string `yaml:"url"`
Headers map[string]string `yaml:"headers,omitempty"`
}
// Format is document format setting
type Format struct {
Adjust bool `yaml:"adjust,omitempty"`
Sort bool `yaml:"sort,omitempty"`
Number bool `yaml:"number,omitempty"`
ShowOnlyFirstParagraph bool `yaml:"showOnlyFirstParagraph,omitempty"`
HideColumnsWithoutValues []string `yaml:"hideColumnsWithoutValues,omitempty"`
}
// ER is er setting
type ER struct {
Skip bool `yaml:"skip,omitempty"`
Format string `yaml:"format,omitempty"`
Comment bool `yaml:"comment,omitempty"`
Distance *int `yaml:"distance,omitempty"`
Font string `yaml:"font,omitempty"`
}
// AdditionalRelation is the struct for table relation from yaml
type AdditionalRelation struct {
Table string `yaml:"table"`
Columns []string `yaml:"columns"`
ParentTable string `yaml:"parentTable"`
ParentColumns []string `yaml:"parentColumns"`
Def string `yaml:"def,omitempty"`
Override bool `yaml:"override,omitempty"`
}
// AdditionalComment is the struct for table relation from yaml
type AdditionalComment struct {
Table string `yaml:"table"`
TableComment string `yaml:"tableComment,omitempty"`
ColumnComments map[string]string `yaml:"columnComments,omitempty"`
ColumnLabels map[string][]string `yaml:"columnLabels,omitempty"`
IndexComments map[string]string `yaml:"indexComments,omitempty"`
ConstraintComments map[string]string `yaml:"constraintComments,omitempty"`
TriggerComments map[string]string `yaml:"triggerComments,omitempty"`
Labels []string `yaml:"labels,omitempty"`
}
type DetectVirtualRelations struct {
Enabled bool `yaml:"enabled,omitempty"`
Strategy string `yaml:"strategy,omitempty"`
}
// Option function change Config
type Option func(*Config) error
// DSNURL return Option set Config.DSN.URL
func DSNURL(dsn string) Option {
return func(c *Config) error {
c.DSN.URL = dsn
return nil
}
}
// DocPath return Option set Config.DocPath
func DocPath(docPath string) Option {
return func(c *Config) error {
c.DocPath = docPath
return nil
}
}
// Adjust return Option set Config.Format.Adjust
func Adjust(adjust bool) Option {
return func(c *Config) error {
if adjust {
c.Format.Adjust = adjust
}
return nil
}
}
// Sort return Option set Config.Format.Sort
func Sort(sort bool) Option {
return func(c *Config) error {
if sort {
c.Format.Sort = sort
}
return nil
}
}
// ERSkip return Option set Config.ER.Skip
func ERSkip(skip bool) Option {
return func(c *Config) error {
c.ER.Skip = skip
return nil
}
}
// ERFormat return Option set Config.ER.Format
func ERFormat(erFormat string) Option {
return func(c *Config) error {
if erFormat != "" {
c.ER.Format = erFormat
}
return nil
}
}
// Distance return Option set Config.Distance
func Distance(distance int) Option {
return func(c *Config) error {
c.Distance = distance
return nil
}
}
// BaseUrl return Option set Config.BaseUrl
func BaseUrl(baseUrl string) Option {
return func(c *Config) error {
if baseUrl != "" {
c.BaseUrl = baseUrl
}
return nil
}
}
// Include return Option set Config.Include
func Include(i []string) Option {
return func(c *Config) error {
if len(i) > 0 {
c.Include = i
}
return nil
}
}
// Exclude return Option set Config.Exclude
func Exclude(e []string) Option {
return func(c *Config) error {
if len(e) > 0 {
c.Exclude = e
}
return nil
}
}
// IncludeLabels return Option set Config.includeLabels
func IncludeLabels(l []string) Option {
return func(c *Config) error {
if len(l) > 0 {
c.includeLabels = l
}
return nil
}
}
// New return Config
func New() (*Config, error) {
c := Config{}
err := c.setDefault()
if err != nil {
return nil, err
}
return &c, nil
}
// Load config with all method
func (c *Config) Load(configPath string, options ...Option) error {
if err := c.LoadConfigFile(configPath); err != nil {
return err
}
if err := c.LoadEnviron(); err != nil {
return err
}
if err := c.LoadOption(options...); err != nil {
return err
}
if err := c.setDefault(); err != nil {
return err
}
if err := c.checkVersion(ver.Version); err != nil {
return err
}
return nil
}
// LoadOptions load options
func (c *Config) LoadOption(options ...Option) error {
for _, option := range options {
if err := option(c); err != nil {
return err
}
}
return nil
}
// set default setting
func (c *Config) setDefault() error {
if c.DocPath == "" {
c.DocPath = DefaultDocPath
}
if c.ER.Format == "" {
c.ER.Format = DefaultERFormat
}
if c.ER.Distance == nil {
c.ER.Distance = &DefaultERDistance
}
return nil
}
func (c *Config) checkVersion(sv string) error {
if sv == "dev" {
return nil
}
if c.RequiredVersion == "" {
return nil
}
cons, err := version.NewConstraints(c.RequiredVersion)
if err != nil {
return err
}
v, err := version.Parse(sv)
if err != nil {
return err
}
if !cons.Check(v) {
return fmt.Errorf("the required tbls version for the configuration is '%s'. however, the running tbls version is '%s'", c.RequiredVersion, sv)
}
return nil
}
// LoadEnviron load environment variables
func (c *Config) LoadEnviron() error {
dsn := os.Getenv("TBLS_DSN")
if dsn != "" {
c.DSN.URL = dsn
}
docPath := os.Getenv("TBLS_DOC_PATH")
if docPath != "" {
c.DocPath = docPath
}
return nil
}
// LoadConfigFile load config file
func (c *Config) LoadConfigFile(path string) error {
if path == "" {
for _, p := range DefaultConfigFilePaths {
if f, err := os.Stat(filepath.Join(c.root, p)); err == nil && !f.IsDir() {
if path != "" {
return errors.Errorf("duplicate config file [%s, %s]", path, p)
}
path = p
}
}
}
if path == "" {
return nil
}
fullPath, err := filepath.Abs(path)
if err != nil {
return errors.Wrap(errors.WithStack(err), "failed to load config file")
}
buf, err := os.ReadFile(filepath.Clean(fullPath))
if err != nil {
return errors.Wrap(errors.WithStack(err), "failed to load config file")
}
c.Path = filepath.Clean(fullPath)
return c.LoadConfig(buf)
}
// LoadConfig load config from []byte
func (c *Config) LoadConfig(in []byte) error {
err := yaml.Unmarshal(expand.ExpandenvYAMLBytes(in), c)
if err != nil {
return errors.Wrap(errors.WithStack(err), "failed to load config file")
}
c.MergedDict.Merge(c.Dict.Dump())
return nil
}
// ModifySchema modify schema.Schema by config
func (c *Config) ModifySchema(s *schema.Schema) error {
if c.Name != "" {
s.Name = c.Name
}
if c.Desc != "" {
s.Desc = c.Desc
}
if len(c.Labels) > 0 {
for _, l := range c.Labels {
s.Labels = s.Labels.Merge(l)
}
}
if err := detectCardinality(s); err != nil {
return err
}
err := c.MergeAdditionalData(s)
if err != nil {
return err
}
err = c.FilterTables(s)
if err != nil {
return err
}
if c.Format.Sort {
err = s.Sort()
if err != nil {
return err
}
}
if c.DetectVirtualRelations.Enabled {
strategy, err := SelectNamingStrategy(c.DetectVirtualRelations.Strategy)
if err != nil {
return err
}
mergeDetectedRelations(s, strategy)
}
c.mergeDictFromSchema(s)
if err := detectCardinality(s); err != nil {
return err
}
return nil
}
// MergeAdditionalData merge relations: comments: to schema.Schema
func (c *Config) MergeAdditionalData(s *schema.Schema) error {
err := mergeAdditionalRelations(s, c.Relations)
if err != nil {
return err
}
err = mergeAdditionalComments(s, c.Comments)
if err != nil {
return err
}
return nil
}
// FilterTables filter tables from schema.Schema
func (c *Config) FilterTables(s *schema.Schema) error {
i := append(c.Include, s.NormalizeTableNames(c.Include)...)
e := append(c.Exclude, s.NormalizeTableNames(c.Exclude)...)
includes := []*schema.Table{}
excludes := []*schema.Table{}
for _, t := range s.Tables {
li, mi := matchLength(i, t.Name)
le, me := matchLength(e, t.Name)
ml := matchLabels(c.includeLabels, t.Labels)
switch {
case mi:
if me && li < le {
excludes = append(excludes, t)
continue
}
includes = append(includes, t)
case ml:
if me {
excludes = append(excludes, t)
continue
}
includes = append(includes, t)
case len(c.Include) == 0 && len(c.includeLabels) == 0:
if me {
excludes = append(excludes, t)
continue
}
includes = append(includes, t)
default:
excludes = append(excludes, t)
}
}
collects := []*schema.Table{}
for _, t := range includes {
ts, _, err := t.CollectTablesAndRelations(c.Distance, true)
if err != nil {
return err
}
for _, tt := range ts {
if !tt.Contains(includes) {
collects = append(collects, tt)
}
}
}
for _, t := range excludes {
if t.Contains(collects) {
continue
}
err := excludeTableFromSchema(t.Name, s)
if err != nil {
return errors.Wrap(errors.WithStack(err), fmt.Sprintf("failed to filter table '%s'", t.Name))
}
}
return nil
}
func (c *Config) mergeDictFromSchema(s *schema.Schema) {
if s.Driver != nil && s.Driver.Meta != nil && s.Driver.Meta.Dict != nil {
c.MergedDict.Merge(s.Driver.Meta.Dict.Dump())
}
}
func excludeTableFromSchema(name string, s *schema.Schema) error {
// Tables
tables := []*schema.Table{}
for _, t := range s.Tables {
if t.Name != name {
tables = append(tables, t)
}
for _, c := range t.Columns {
// ChildRelations
childRelations := []*schema.Relation{}
for _, r := range c.ChildRelations {
if r.Table.Name != name && r.ParentTable.Name != name {
childRelations = append(childRelations, r)
}
}
c.ChildRelations = childRelations
// ParentRelations
parentRelations := []*schema.Relation{}
for _, r := range c.ParentRelations {
if r.Table.Name != name && r.ParentTable.Name != name {
parentRelations = append(parentRelations, r)
}
}
c.ParentRelations = parentRelations
}
}
s.Tables = tables
// Relations
relations := []*schema.Relation{}
for _, r := range s.Relations {
if r.Table.Name != name && r.ParentTable.Name != name {
relations = append(relations, r)
}
}
s.Relations = relations
return nil
}
// MaskedDSN return DSN mask password
func (c *Config) MaskedDSN() (string, error) {
u, err := url.Parse(c.DSN.URL)
if err != nil {
return c.DSN.URL, errors.WithStack(err)
}
_, pset := u.User.Password()
if !pset {
return c.DSN.URL, nil
}
tmp := "-----tbls-----"
u.User = url.UserPassword(u.User.Username(), tmp)
return strings.Replace(u.String(), tmp, "*****", 1), nil
}
func (c *Config) SchemaFilePath() string {
return filepath.Join(c.DocPath, SchemaFileName)
}
func mergeAdditionalRelations(s *schema.Schema, relations []AdditionalRelation) error {
for _, r := range relations {
relation := &schema.Relation{
Virtual: true,
}
if r.Def != "" {
relation.Def = r.Def
} else {
relation.Def = "Additional Relation"
}
var err error
relation.Table, err = s.FindTableByName(r.Table)
if err != nil {
return errors.Wrap(err, "failed to add relation")
}
for _, c := range r.Columns {
column, err := relation.Table.FindColumnByName(c)
if err != nil {
return errors.Wrap(err, "failed to add relation")
}
relation.Columns = append(relation.Columns, column)
column.ParentRelations = append(column.ParentRelations, relation)
}
relation.ParentTable, err = s.FindTableByName(r.ParentTable)
if err != nil {
return errors.Wrap(err, "failed to add relation")
}
for _, c := range r.ParentColumns {
column, err := relation.ParentTable.FindColumnByName(c)
if err != nil {
return errors.Wrap(err, "failed to add relation")
}
relation.ParentColumns = append(relation.ParentColumns, column)
column.ChildRelations = append(column.ChildRelations, relation)
}
if r.Override {
cr, err := s.FindRelation(relation.Columns, relation.ParentColumns)
if err != nil {
s.Relations = append(s.Relations, relation)
} else {
cr.Virtual = true
cr.Def = r.Def
}
} else {
s.Relations = append(s.Relations, relation)
}
}
return nil
}
func mergeAdditionalComments(s *schema.Schema, comments []AdditionalComment) error {
for _, c := range comments {
table, err := s.FindTableByName(c.Table)
if err != nil {
return errors.Wrap(err, "failed to add table comment")
}
if c.TableComment != "" {
table.Comment = c.TableComment
}
if len(c.Labels) > 0 {
for _, l := range c.Labels {
table.Labels = table.Labels.Merge(l)
}
}
for c, comment := range c.ColumnComments {
column, err := table.FindColumnByName(c)
if err != nil {
return errors.Wrap(err, "failed to add column comment")
}
column.Comment = comment
}
for c, labels := range c.ColumnLabels {
column, err := table.FindColumnByName(c)
if err != nil {
return errors.Wrap(err, "failed to add column comment")
}
for _, l := range labels {
column.Labels = column.Labels.Merge(l)
}
}
for i, comment := range c.IndexComments {
index, err := table.FindIndexByName(i)
if err != nil {
return errors.Wrap(err, "failed to add index comment")
}
index.Comment = comment
}
for c, comment := range c.ConstraintComments {
constraint, err := table.FindConstraintByName(c)
if err != nil {
return errors.Wrap(err, "failed to add constraint comment")
}
constraint.Comment = comment
}
for t, comment := range c.TriggerComments {
trigger, err := table.FindTriggerByName(t)
if err != nil {
return errors.Wrap(err, "failed to add trigger comment")
}
trigger.Comment = comment
}
}
return nil
}
func mergeDetectedRelations(s *schema.Schema, strategy *NamingStrategy) {
var (
err error
parentColumn *schema.Column
)
for _, t := range s.Tables {
for _, c := range t.Columns {
relation := &schema.Relation{
Virtual: true,
Def: "Detected Relation",
Table: t,
}
if relation.ParentTable, err = s.FindTableByName(strategy.ParentTableName(c.Name)); err != nil {
continue
}
if parentColumn, err = relation.ParentTable.FindColumnByName(strategy.ParentColumnName(c.Name)); err != nil {
continue
}
relation.Columns = append(relation.Columns, c)
relation.ParentColumns = append(relation.ParentColumns, parentColumn)
if _, err := s.FindRelation(relation.Columns, relation.ParentColumns); err == nil {
// If the relation already exists, do not create a new virtual relation.
continue
}
c.ParentRelations = append(c.ParentRelations, relation)
parentColumn.ChildRelations = append(parentColumn.ChildRelations, relation)
s.Relations = append(s.Relations, relation)
}
}
}
func matchLength(s []string, e string) (int, bool) {
for _, v := range s {
if wildcard.MatchSimple(v, e) {
return len(strings.ReplaceAll(v, "*", "")), true
}
}
return 0, false
}
func detectCardinality(s *schema.Schema) error {
// This function should be applied to the completed schema
for _, r := range s.Relations {
// parent
if r.ParentCardinality != schema.UnknownCardinality {
nullable := true
unique := false
columns := []string{}
for _, c := range r.ParentColumns {
if !c.Nullable {
nullable = false
}
columns = append(columns, c.Name)
}
L:
for _, c := range r.ParentTable.Constraints {
if len(columns) != len(c.Columns) {
continue
}
for _, cc := range c.Columns {
if !contains(columns, cc) {
continue L
}
}
if strings.Contains(strings.ToUpper(c.Def), "UNIQUE") || strings.Contains(strings.ToUpper(c.Def), "PRIMARY KEY") {
unique = true
}
}
switch {
case nullable && unique:
r.ParentCardinality = schema.ZeroOrOne
case !nullable && unique:
r.ParentCardinality = schema.ExactlyOne
case nullable && !unique:
r.ParentCardinality = schema.ZeroOrMore
case !nullable && !unique:
r.ParentCardinality = schema.OneOrMore
}
}
// child
if r.Cardinality != schema.UnknownCardinality {
nullable := true
unique := false
columns := []string{}
for _, c := range r.Columns {
if !c.Nullable {
nullable = false
}
columns = append(columns, c.Name)
}
LL:
for _, c := range r.Table.Constraints {
if len(columns) != len(c.Columns) {
continue
}
for _, cc := range c.Columns {
if !contains(columns, cc) {
continue LL
}
}
if strings.Contains(strings.ToUpper(c.Def), "UNIQUE") || strings.Contains(strings.ToUpper(c.Def), "PRIMARY KEY") {
unique = true
}
}
switch {
case nullable && unique:
r.Cardinality = schema.ZeroOrOne
case !nullable && unique:
r.Cardinality = schema.ExactlyOne
case nullable && !unique:
r.Cardinality = schema.ZeroOrMore
case !nullable && !unique:
r.Cardinality = schema.OneOrMore
}
}
}
return nil
}
func matchLabels(il []string, l schema.Labels) bool {
for _, ll := range l {
for _, ill := range il {
if ll.Name == ill {
return true
}
}
}
return false
}
func match(s []string, e string) bool {
_, m := matchLength(s, e)
return m
}
func contains(s []string, e string) bool {
for _, v := range s {
if e == v {
return true
}
}
return false
}