github.com/wdesplas/cloud-service-broker@v0.0.0-20211027135251-516a8547ca4c/db_service/db_service.go (about) 1 // Copyright 2018 the Service Broker Project Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 //go:generate go run dao_generator.go 16 17 package db_service 18 19 import ( 20 "fmt" 21 "sync" 22 23 "code.cloudfoundry.org/lager" 24 "gorm.io/gorm" 25 26 _ "gorm.io/driver/sqlite" 27 ) 28 29 var DbConnection *gorm.DB 30 var once sync.Once 31 32 // New instantiates the db connection and runs migrations 33 func New(logger lager.Logger) *gorm.DB { 34 once.Do(func() { 35 DbConnection = SetupDb(logger) 36 if err := RunMigrations(DbConnection); err != nil { 37 panic(fmt.Sprintf("Error migrating database: %s", err.Error())) 38 } 39 }) 40 return DbConnection 41 } 42 43 // defaultDatastore gets the default datastore for the given default database 44 // instantiated in New(). In the future, all accesses of DbConnection will be 45 // done through SqlDatastore and it will become the globally shared instance. 46 func defaultDatastore() *SqlDatastore { 47 return &SqlDatastore{db: DbConnection} 48 } 49 50 type SqlDatastore struct { 51 db *gorm.DB 52 }