Copyright 2019 The Go Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
Package dbtest supports testing with a database.
package dbtest

import (
	
	
	
	
	
	

imported to register the postgres migration driver
imported to register the file source migration driver
imported to register the postgres database driver
	_ 
)

func (,  string) string {
	if ,  := os.LookupEnv();  {
		return 
	}
	return 
}
DBConnURI generates a postgres connection string in URI format. This is necessary as migrate expects a URI.
func ( string) string {
	var (
		     = getEnv("GO_DISCOVERY_DATABASE_TEST_USER", "postgres")
		 = getEnv("GO_DISCOVERY_DATABASE_TEST_PASSWORD", "")
		     = getEnv("GO_DISCOVERY_DATABASE_TEST_HOST", "localhost")
		     = getEnv("GO_DISCOVERY_DATABASE_TEST_PORT", "5432")
	)
	 := fmt.Sprintf("postgres://%s/%s?sslmode=disable&user=%s&password=%s&port=%s&timezone=UTC",
		, , url.QueryEscape(), url.QueryEscape(), url.QueryEscape())
	return 
}
MultiErr can be used to combine one or more errors into a single error.
type MultiErr []error

func ( MultiErr) () string {
	var  strings.Builder
	for ,  := range  {
		 := ""
		if .Len() > 0 {
			 = "|"
		}
		if  != nil {
			.WriteString( + .Error())
		}
	}
	return .String()
}
ConnectAndExecute connects to the postgres database specified by uri and executes dbFunc, then cleans up the database connection. It returns an error that Is derrors.NotFound if no connection could be made.
func ( string,  func(*sql.DB) error) ( error) {
	,  := sql.Open("postgres", )
	if  == nil {
		 = .Ping()
	}
	if  != nil {
		return fmt.Errorf("%w: %v", derrors.NotFound, )
	}
	defer func() {
		if  := .Close();  != nil {
			 = MultiErr{, }
		}
	}()
	return ()
}
CreateDB creates a new database dbName.
func ( string) error {
	return ConnectAndExecute(DBConnURI(""), func( *sql.DB) error {
		if ,  := .Exec(fmt.Sprintf(`
			CREATE DATABASE %q
				TEMPLATE=template0
				LC_COLLATE='C'
				LC_CTYPE='C';`, ));  != nil {
			return fmt.Errorf("error creating %q: %v", , )
		}

		return nil
	})
}
DropDB drops the database named dbName.
func ( string) error {
	return ConnectAndExecute(DBConnURI(""), func( *sql.DB) error {
		if ,  := .Exec(fmt.Sprintf("DROP DATABASE %q;", ));  != nil {
			return fmt.Errorf("error dropping %q: %v", , )
		}
		return nil
	})
}
CreateDBIfNotExists checks whether the given dbName is an existing database, and creates one if not.
func ( string) error {
	,  := checkIfDBExists()
	if  != nil ||  {
		return 
	}

	log.Printf("Test database %q does not exist, creating.", )
	return CreateDB()
}
checkIfDBExists check if dbName exists.
func ( string) (bool, error) {
	var  bool

	 := ConnectAndExecute(DBConnURI(""), func( *sql.DB) error {
		,  := .Query("SELECT 1 from pg_database WHERE datname = $1 LIMIT 1", )
		if  != nil {
			return 
		}
		defer .Close()

		if .Next() {
			 = true
			return nil
		}

		return .Err()
	})

	return ,