NewStorage creates a new storage using GORM (which DB to use depends on the StorageOption)
(opts ...StorageOption)
| 124 | |
| 125 | // NewStorage creates a new storage using GORM (which DB to use depends on the StorageOption) |
| 126 | func NewStorage(opts ...StorageOption) (s persistence.Storage, err error) { |
| 127 | log.Println("Creating storage") |
| 128 | // Create storage with default gorm config |
| 129 | g := &storage{ |
| 130 | // We ignore Deepsource issue GO-W1004 (SkipDefaultTransaction of config is "false"): skipcq: GO-W1004 |
| 131 | config: gorm.Config{ |
| 132 | Logger: logger.Default.LogMode(logger.Silent), |
| 133 | }, |
| 134 | types: DefaultTypes, |
| 135 | } |
| 136 | |
| 137 | // Add options and/or override default ones |
| 138 | for _, o := range opts { |
| 139 | o(g) |
| 140 | } |
| 141 | |
| 142 | if g.dialector == nil { |
| 143 | WithInMemory()(g) |
| 144 | } |
| 145 | |
| 146 | g.db, err = gorm.Open(g.dialector, &g.config) |
| 147 | if err != nil { |
| 148 | return nil, err |
| 149 | } |
| 150 | |
| 151 | if g.maxConn > 0 { |
| 152 | sql, err := g.db.DB() |
| 153 | if err != nil { |
| 154 | return nil, fmt.Errorf("could not retrieve sql.DB: %v", err) |
| 155 | } |
| 156 | |
| 157 | sql.SetMaxOpenConns(g.maxConn) |
| 158 | } |
| 159 | |
| 160 | schema.RegisterSerializer("durationpb", &DurationSerializer{}) |
| 161 | schema.RegisterSerializer("timestamppb", &TimestampSerializer{}) |
| 162 | schema.RegisterSerializer("valuepb", &ValueSerializer{}) |
| 163 | schema.RegisterSerializer("anypb", &AnySerializer{}) |
| 164 | |
| 165 | if err = g.db.SetupJoinTable(&orchestrator.CertificationTarget{}, "CatalogsInScope", &orchestrator.AuditScope{}); err != nil { |
| 166 | err = fmt.Errorf("error during join-table: %w", err) |
| 167 | return |
| 168 | } |
| 169 | |
| 170 | if err = g.db.SetupJoinTable(orchestrator.CertificationTarget{}, "ConfiguredMetrics", assessment.MetricConfiguration{}); err != nil { |
| 171 | err = fmt.Errorf("error during join-table: %w", err) |
| 172 | return |
| 173 | } |
| 174 | |
| 175 | // After successful DB initialization, migrate the schema |
| 176 | if err = g.db.AutoMigrate(g.types...); err != nil { |
| 177 | err = fmt.Errorf("error during auto-migration: %w", err) |
| 178 | return |
| 179 | } |
| 180 | |
| 181 | s = g |
| 182 | return |
| 183 | } |