...

Source file src/edge-infra.dev/pkg/sds/emergencyaccess/config/database.go

Documentation: edge-infra.dev/pkg/sds/emergencyaccess/config

     1  package config
     2  
     3  import (
     4  	"database/sql"
     5  	"fmt"
     6  
     7  	"edge-infra.dev/pkg/lib/gcp/cloudsql"
     8  )
     9  
    10  // Returns an initialised connection to the database using the configuration
    11  // defined in config. Database may be accessed through CloudSQL or via a port number
    12  // Returns an error when config includes invalid configuration or an attempt to
    13  // connect to the DB fails
    14  func DB(config SQLConfig) (*sql.DB, func() error, error) {
    15  	check := func() error {
    16  		return fmt.Errorf("error db not initialised")
    17  	}
    18  
    19  	// Use cloudsql to handle connection
    20  	var edgeDb *cloudsql.EdgePostgres
    21  
    22  	// Initialise the correct type of connection: CLoudSQL or local host, port pair,
    23  	// determined by the presence of the ConnectionName configuration param
    24  	switch {
    25  	case config.ConnectionName != "":
    26  		edgeDb = cloudsql.GCPPostgresConnection(config.ConnectionName)
    27  	case config.ConnectionName == "" && config.Host != "":
    28  		if config.Port == "" {
    29  			return nil, check, fmt.Errorf("database port is required")
    30  		}
    31  		edgeDb = cloudsql.PostgresConnection(config.Host, config.Port).
    32  			Password(config.Password)
    33  	default:
    34  		return nil, check, fmt.Errorf("database-connection-name or database-host must be provided")
    35  	}
    36  
    37  	// Open the connection to the configured DB
    38  	edgeDb = edgeDb.
    39  		DBName(config.DatabaseName).
    40  		Username(config.User)
    41  
    42  	// Only set search_path when the schema is a non-empty string
    43  	if config.Schema != "" {
    44  		edgeDb = edgeDb.SearchPath(config.Schema)
    45  	}
    46  
    47  	db, err := edgeDb.NewConnection()
    48  	if err != nil {
    49  		return nil, check, err
    50  	}
    51  
    52  	// Test connection to DB before returning
    53  	if err := db.Ping(); err != nil {
    54  		return nil, check, err
    55  	}
    56  	return db, checkDB(db), nil
    57  }
    58  
    59  func checkDB(db *sql.DB) func() error {
    60  	return func() error {
    61  		if _, err := db.Exec("SELECT 1;"); err != nil {
    62  			return fmt.Errorf("database not ready: %w", err)
    63  		}
    64  		return nil
    65  	}
    66  }
    67  

View as plain text