github.com/kyleu/dbaudit@v0.0.2-0.20240321155047-ff2f2c940496/app/db/connections.go (about) 1 // Package db - Content managed by Project Forge, see [projectforge.md] for details. 2 package db 3 4 import ( 5 "slices" 6 7 "github.com/google/uuid" 8 "github.com/samber/lo" 9 10 "github.com/kyleu/dbaudit/app/util" 11 ) 12 13 type Connections []*Connection 14 15 func (c Connections) Get(id uuid.UUID) *Connection { 16 return lo.FindOrElse(c, nil, func(x *Connection) bool { 17 return x.ID == id 18 }) 19 } 20 21 func (c Connections) IDs() []uuid.UUID { 22 return lo.Map(c, func(xx *Connection, _ int) uuid.UUID { 23 return xx.ID 24 }) 25 } 26 27 func (c Connections) IDStrings(includeNil bool) []string { 28 ret := make([]string, 0, len(c)+1) 29 if includeNil { 30 ret = append(ret, "") 31 } 32 lo.ForEach(c, func(x *Connection, _ int) { 33 ret = append(ret, x.ID.String()) 34 }) 35 return ret 36 } 37 38 func (c Connections) TitleStrings(nilTitle string) []string { 39 ret := make([]string, 0, len(c)+1) 40 if nilTitle != "" { 41 ret = append(ret, nilTitle) 42 } 43 lo.ForEach(c, func(x *Connection, _ int) { 44 ret = append(ret, x.TitleString()) 45 }) 46 return ret 47 } 48 49 func (c Connections) GetByID(id uuid.UUID) Connections { 50 return lo.Filter(c, func(xx *Connection, _ int) bool { 51 return xx.ID == id 52 }) 53 } 54 55 func (c Connections) GetByIDs(ids ...uuid.UUID) Connections { 56 return lo.Filter(c, func(xx *Connection, _ int) bool { 57 return lo.Contains(ids, xx.ID) 58 }) 59 } 60 61 func (c Connections) Engines() []Engine { 62 return lo.Map(c, func(xx *Connection, _ int) Engine { 63 return xx.Engine 64 }) 65 } 66 67 func (c Connections) GetByEngine(engine Engine) Connections { 68 return lo.Filter(c, func(xx *Connection, _ int) bool { 69 return xx.Engine == engine 70 }) 71 } 72 73 func (c Connections) GetByEngines(engines ...Engine) Connections { 74 return lo.Filter(c, func(xx *Connection, _ int) bool { 75 return lo.Contains(engines, xx.Engine) 76 }) 77 } 78 79 func (c Connections) ToCSV() ([]string, [][]string) { 80 return FieldDescs.Keys(), lo.Map(c, func(x *Connection, _ int) []string { 81 return x.Strings() 82 }) 83 } 84 85 func (c Connections) Random() *Connection { 86 if len(c) == 0 { 87 return nil 88 } 89 return c[util.RandomInt(len(c))] 90 } 91 92 func (c Connections) Clone() Connections { 93 return slices.Clone(c) 94 }