golang.org/x/build@v0.0.0-20240506185731-218518f32b70/perfdata/db/dbtest/cloud.go (about)

     1  // Copyright 2017 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build cloud && !plan9
     6  
     7  package dbtest
     8  
     9  import (
    10  	"crypto/rand"
    11  	"database/sql"
    12  	"encoding/base64"
    13  	"flag"
    14  	"fmt"
    15  	"testing"
    16  
    17  	_ "github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/dialers/mysql"
    18  )
    19  
    20  var cloud = flag.Bool("cloud", false, "connect to Cloud SQL database instead of in-memory SQLite")
    21  var cloudsql = flag.String("cloudsql", "golang-org:us-central1:golang-org", "name of Cloud SQL instance to run tests on")
    22  
    23  // createEmptyDB makes a new, empty database for the test.
    24  func createEmptyDB(t *testing.T) (driver, dsn string, cleanup func()) {
    25  	if !*cloud {
    26  		return "sqlite3", ":memory:", nil
    27  	}
    28  	buf := make([]byte, 6)
    29  	if _, err := rand.Read(buf); err != nil {
    30  		t.Fatal(err)
    31  	}
    32  
    33  	name := "perfdata-test-" + base64.RawURLEncoding.EncodeToString(buf)
    34  
    35  	prefix := fmt.Sprintf("root:@cloudsql(%s)/", *cloudsql)
    36  
    37  	db, err := sql.Open("mysql", prefix)
    38  	if err != nil {
    39  		t.Fatal(err)
    40  	}
    41  
    42  	if _, err := db.Exec(fmt.Sprintf("CREATE DATABASE `%s`", name)); err != nil {
    43  		db.Close()
    44  		t.Fatal(err)
    45  	}
    46  
    47  	t.Logf("Using database %q", name)
    48  
    49  	return "mysql", prefix + name + "?interpolateParams=true", func() {
    50  		if _, err := db.Exec(fmt.Sprintf("DROP DATABASE `%s`", name)); err != nil {
    51  			t.Error(err)
    52  		}
    53  		db.Close()
    54  	}
    55  }