(name string, ifNotExists bool)
| 294 | |
| 295 | func (prov *DatabaseProvider) CreateCatalog(name string, ifNotExists bool) error { |
| 296 | name = strings.TrimSpace(name) |
| 297 | // in memory database does not need to be created |
| 298 | if name == "" || name == "memory" { |
| 299 | return nil |
| 300 | } |
| 301 | dsn := filepath.Join(prov.dataDir, name+".db") |
| 302 | |
| 303 | _, err := os.Stat(dsn) |
| 304 | shouldInit := os.IsNotExist(err) |
| 305 | |
| 306 | // attach |
| 307 | attachSQL := "ATTACH" |
| 308 | if ifNotExists { |
| 309 | attachSQL += " IF NOT EXISTS" |
| 310 | } |
| 311 | quoted := QuoteIdentifierANSI(name) |
| 312 | attachSQL += " '" + dsn + "' AS " + quoted |
| 313 | _, err = prov.storage.ExecContext(context.Background(), attachSQL) |
| 314 | if err != nil { |
| 315 | return err |
| 316 | } |
| 317 | |
| 318 | if shouldInit { |
| 319 | res, err := prov.storage.QueryContext(context.Background(), "SELECT current_catalog") |
| 320 | if err != nil { |
| 321 | return fmt.Errorf("failed to init catalog: %w", err) |
| 322 | } |
| 323 | lastCatalog := "" |
| 324 | for res.Next() { |
| 325 | if err := res.Scan(&lastCatalog); err != nil { |
| 326 | return fmt.Errorf("failed to init catalog: %w", err) |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | if _, err := prov.storage.ExecContext(context.Background(), "USE "+quoted); err != nil { |
| 331 | return fmt.Errorf("failed to switch to the new catalog: %w", err) |
| 332 | } |
| 333 | |
| 334 | defer func() { |
| 335 | if lastCatalog == "" { |
| 336 | return |
| 337 | } |
| 338 | if _, err := prov.storage.ExecContext(context.Background(), "USE "+QuoteIdentifierANSI(lastCatalog)); err != nil { |
| 339 | logrus.WithError(err).Errorln("Failed to switch back to the old catalog") |
| 340 | } |
| 341 | }() |
| 342 | err = prov.initCatalog() |
| 343 | if err != nil { |
| 344 | return err |
| 345 | } |
| 346 | } |
| 347 | return nil |
| 348 | } |
no test coverage detected