storj/private/dbutil/pgutil/openunique_test.go
paul cannon 378b863b2b private,satellite: unite all the "temp db schema" things
first, so that they all work the same way, because it's getting
complicated, and second, so that we can do the appropriate thing
instead of CREATE SCHEMA for cockroachdb.

Change-Id: I27fbaeeb6223a3e06d97bcf692a2d014b31465f7
2019-12-05 15:36:59 +00:00

59 lines
1.9 KiB
Go

// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package pgutil_test
import (
"database/sql"
"strings"
"testing"
"github.com/stretchr/testify/require"
"storj.io/storj/private/dbutil/pgutil/pgtest"
"storj.io/storj/private/dbutil/tempdb"
"storj.io/storj/private/testcontext"
)
func TestTempPostgresDB(t *testing.T) {
ctx := testcontext.New(t)
defer ctx.Cleanup()
if *pgtest.ConnStr == "" {
t.Skip("PostgreSQL flag missing")
}
prefix := "name#spaced/Test/DB"
testDB, err := tempdb.OpenUnique(*pgtest.ConnStr, prefix)
require.NoError(t, err)
// assert new test db exists and can be connected to again
otherConn, err := sql.Open(testDB.Driver, testDB.ConnStr)
require.NoError(t, err)
defer ctx.Check(otherConn.Close)
// verify the name matches expectation
var name *string
row := otherConn.QueryRow(`SELECT current_schema()`)
err = row.Scan(&name)
require.NoErrorf(t, err, "connStr=%q", testDB.ConnStr)
require.NotNilf(t, name, "PG has no current_schema, which means the one we asked for doesn't exist. connStr=%q", testDB.ConnStr)
require.Truef(t, strings.HasPrefix(*name, prefix), "Expected prefix of %q for current db name, but found %q", prefix, name)
// verify there is an entry in pg_namespace with such a name
var count int
row = otherConn.QueryRow(`SELECT COUNT(*) FROM pg_namespace WHERE nspname = current_schema`)
err = row.Scan(&count)
require.NoError(t, err)
require.Equalf(t, 1, count, "Expected 1 schema with matching name, but counted %d", count)
// close testDB but leave otherConn open
err = testDB.Close()
require.NoError(t, err)
// assert new test schema was deleted
row = otherConn.QueryRow(`SELECT COUNT(*) FROM pg_namespace WHERE nspname = current_schema`)
err = row.Scan(&count)
require.NoError(t, err)
require.Equalf(t, 0, count, "Expected 0 schemas with matching name, but counted %d (deletion failure?)", count)
}