github.com/wawandco/ox@v0.13.6-0.20230809142027-913b3d837f2a/pkg/buffalotools/databaseprovider.go (about)

     1  package buffalotools
     2  
     3  import (
     4  	"io/fs"
     5  	"log"
     6  
     7  	"github.com/gobuffalo/pop/v6"
     8  	"github.com/markbates/oncer"
     9  )
    10  
    11  var (
    12  	// connections opened by the DatabaseProvider
    13  	connections = map[string]*pop.Connection{}
    14  )
    15  
    16  // DatabaseProvider returns a function that returns the database connection
    17  // for the current environment.
    18  func DatabaseProvider(config fs.FS) func(name string) *pop.Connection {
    19  	// Loading connections from database.yml in the pop.Connections
    20  	// variable for later usage.
    21  	bf, err := config.Open("database.yml")
    22  	if err != nil {
    23  		log.Fatalf("databaseprovider: %v", err)
    24  	}
    25  
    26  	err = pop.LoadFrom(bf)
    27  	if err != nil {
    28  		log.Fatalf("databaseprovider: %v", err)
    29  	}
    30  
    31  	return func(name string) *pop.Connection {
    32  		// Only open the connection once.
    33  		oncer.Do("pop:connection:"+name, func() {
    34  			c, err := pop.Connect(name)
    35  			if err != nil {
    36  				log.Fatal(err)
    37  			}
    38  
    39  			connections[name] = c
    40  		})
    41  
    42  		return connections[name]
    43  	}
    44  }