Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(oracle): set the current schema on every session the driver opens (#21672)
rebelice9884e3a5e7f7
diff --git a/backend/common/testcontainer/shared.go b/backend/common/testcontainer/shared.goindex e1d15fa14b..685e92605c 100644--- a/backend/common/testcontainer/shared.go+++ b/backend/common/testcontainer/shared.go@@ -108,6 +108,10 @@ func SharedTiDBContainer(t testing.TB) *Container { return shared(t, sharedTiDB)// each with NewMongoDatabase.func SharedMongoDBContainer(t testing.TB) *Container { return shared(t, sharedMongo) }+// SharedOracleContainer is SharedPgContainer for Oracle, reached through+// OracleServiceName; tests take a schema each with NewOracleSchema.+func SharedOracleContainer(t testing.TB) *Container { return shared(t, sharedOracle) }+// SharedMariaDBContainer is SharedPgContainer for MariaDB 11.8; tests take a// database each with NewMariaDBDatabase.func SharedMariaDBContainer(t testing.TB) *Container { return shared(t, sharedMariaDB) }@@ -206,6 +210,18 @@ func NewMongoDatabase(t testing.TB) (*Container, string) {return SharedMongoDBContainer(t), newDatabaseName()}+// NewOracleSchema creates an empty schema for the test on the shared Oracle+// container and returns the container with the schema's name. The schema is a+// user that can't sign in, with quota for the objects the admin creates in it.+func NewOracleSchema(t testing.TB) (*Container, string) {+ t.Helper()+ container := SharedOracleContainer(t)+ name := strings.ToUpper(newDatabaseName())+ _, err := container.GetDB().Exec(fmt.Sprintf("CREATE USER %s NO AUTHENTICATION QUOTA UNLIMITED ON USERS", name))+ require.NoError(t, err)+ return container, name+}+// newDatabaseName is unique across the test binary, so tests that run in// parallel, on the same container or not, never share a database.func newDatabaseName() string {diff --git a/backend/common/testcontainer/testcontainer.go b/backend/common/testcontainer/testcontainer.goindex 965e06e048..4c616e6714 100644--- a/backend/common/testcontainer/testcontainer.go+++ b/backend/common/testcontainer/testcontainer.go@@ -337,6 +337,31 @@ func getTiDBContainer(ctx context.Context) (*Container, error) {})}+// OracleServiceName is the pluggable database the Oracle container's tests connect to.+const OracleServiceName = "FREEPDB1"++// getOracleContainer starts Oracle Database Free. The admin handle signs in as+// SYSTEM, which may create users and objects in any schema; the caller's test+// binary must link go-ora, which registers the "oracle" driver.+func getOracleContainer(ctx context.Context) (*Container, error) {+ const user, password = "SYSTEM", "Test123"+ return start(ctx, testcontainers.ContainerRequest{+ Image: "gvenzl/oracle-free:23.26.3-slim-faststart",+ Env: map[string]string{+ "ORACLE_PASSWORD": password,+ },+ WaitingFor: wait.ForLog("DATABASE IS READY TO USE!").WithStartupTimeout(5 * time.Minute),+ }, spec{+ port: "1521/tcp",+ username: user,+ password: password,+ driver: "oracle",+ dsn: func(c *Container) string {+ return fmt.Sprintf("oracle://%s:%s@%s:%s/%s", c.username, c.password, c.host, c.port, OracleServiceName)+ },+ })+}+// getMongoDBContainer starts MongoDB, which has no database/sql driver: its// tests open the Mongo driver themselves from the container's credentials.func getMongoDBContainer(ctx context.Context) (*Container, error) {diff --git a/backend/plugin/db/oracle/oracle.go b/backend/plugin/db/oracle/oracle.goindex c45107135b..045ab99690 100644--- a/backend/plugin/db/oracle/oracle.go+++ b/backend/plugin/db/oracle/oracle.go@@ -68,11 +68,12 @@ func (d *Driver) Open(ctx context.Context, _ storepb.Engine, config db.Connectio}options := connectionOptions(config.DataSource.GetSid(), config.DataSource.GetExtraConnectionParameters(), tlsConfig != nil)dsn := goora.BuildUrl(config.DataSource.Host, port, config.DataSource.GetServiceName(), config.DataSource.Username, config.Password, options)- db := sql.OpenDB(&connector{dsn: dsn, tlsConfig: tlsConfig})+ db := sql.OpenDB(&connector{dsn: dsn, tlsConfig: tlsConfig, currentSchema: config.ConnectionContext.DatabaseName})if config.ConnectionContext.DatabaseName != "" {- if _, err := db.ExecContext(ctx, fmt.Sprintf("ALTER SESSION SET CURRENT_SCHEMA = \"%s\"", config.ConnectionContext.DatabaseName)); err != nil {+ // Connect now so that a schema the session can't switch to fails Open, not the first statement.+ if err := db.PingContext(ctx); err != nil {_ = db.Close()- return nil, errors.Wrapf(err, "failed to set current schema to %q", config.ConnectionContext.DatabaseName)+ return nil, err}}d.db = db@@ -99,9 +100,14 @@ func getTLSConfig(dataSource *storepb.DataSource) (*tls.Config, error) {// connector opens each connection through go-ora's default driver, as sql.Open("oracle") does,// with its own copy of the TLS configuration: go-ora sets ServerName on the configuration it is// given, so connections opened in parallel can't share one.+//+// It also sets currentSchema on every session it opens, because the pool opens a new session+// whenever none is idle or one goes bad. go-ora's AddSessionParam can't do this: it stores the+// parameter on the default driver, which every Bytebase Oracle connection shares.type connector struct {- dsn string- tlsConfig *tls.Config+ dsn string+ tlsConfig *tls.Config+ currentSchema string}func (c *connector) Connect(ctx context.Context) (driver.Conn, error) {@@ -110,7 +116,18 @@ func (c *connector) Connect(ctx context.Context) (driver.Conn, error) {return nil, err}oracleConnector.(*goora.OracleConnector).WithTLSConfig(c.tlsConfig.Clone())- return oracleConnector.Connect(ctx)+ conn, err := oracleConnector.Connect(ctx)+ if err != nil {+ return nil, err+ }+ if c.currentSchema == "" {+ return conn, nil+ }+ if _, err := conn.(driver.ExecerContext).ExecContext(ctx, fmt.Sprintf("ALTER SESSION SET CURRENT_SCHEMA = \"%s\"", c.currentSchema), nil); err != nil {+ _ = conn.Close()+ return nil, errors.Wrapf(err, "failed to set current schema to %q", c.currentSchema)+ }+ return conn, nil}func (*connector) Driver() driver.Driver {diff --git a/backend/plugin/db/oracle/oracle_test.go b/backend/plugin/db/oracle/oracle_test.goindex 091d96ff94..1e023c84e0 100644--- a/backend/plugin/db/oracle/oracle_test.go+++ b/backend/plugin/db/oracle/oracle_test.go@@ -26,6 +26,7 @@ import ("github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/common"+ "github.com/bytebase/bytebase/backend/common/testcontainer"storepb "github.com/bytebase/bytebase/backend/generated-go/store""github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/plugin/parser/base"@@ -450,6 +451,52 @@ func TestOpenAppliesTLSSettings(t *testing.T) {})}+func TestCurrentSchemaOnNewSessions(t *testing.T) {+ ctx := context.Background()+ container, schema := testcontainer.NewOracleSchema(t)+ open := func(schema string) (db.Driver, error) {+ return (&Driver{}).Open(ctx, storepb.Engine_ORACLE, db.ConnectionConfig{+ DataSource: &storepb.DataSource{+ Host: container.GetHost(),+ Port: container.GetPort(),+ Username: container.GetUsername(),+ ServiceName: testcontainer.OracleServiceName,+ },+ Password: container.GetPassword(),+ ConnectionContext: db.ConnectionContext{DatabaseName: schema},+ })+ }+ driver, err := open(schema)+ require.NoError(t, err)+ defer driver.Close(ctx)+ // With no idle connection kept, the pool opens a new session for every connection it hands out.+ driver.GetDB().SetMaxIdleConns(0)++ t.Run("QueryConn", func(t *testing.T) {+ conn, err := driver.GetDB().Conn(ctx)+ require.NoError(t, err)+ defer conn.Close()+ results, err := driver.QueryConn(ctx, conn, "SELECT SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA') FROM DUAL", db.QueryContext{MaximumSQLResultSize: 1024})+ require.NoError(t, err)+ require.Len(t, results, 1)+ require.Empty(t, results[0].Error)+ require.Equal(t, schema, results[0].Rows[0].Values[0].GetStringValue())+ })++ t.Run("Execute", func(t *testing.T) {+ _, err := driver.Execute(ctx, "CREATE TABLE SESSION_SCHEMA AS SELECT SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA') AS NAME FROM DUAL", db.ExecuteOptions{})+ require.NoError(t, err)+ var name string+ require.NoError(t, container.GetDB().QueryRowContext(ctx, fmt.Sprintf("SELECT NAME FROM %s.SESSION_SCHEMA", schema)).Scan(&name))+ require.Equal(t, schema, name)+ })++ t.Run("Open fails on a schema that doesn't exist", func(t *testing.T) {+ _, err := open("NO_SUCH_SCHEMA")+ require.ErrorContains(t, err, `failed to set current schema to "NO_SUCH_SCHEMA"`)+ })+}+func closedPort(t *testing.T) string {t.Helper()listener, err := net.Listen("tcp", "127.0.0.1:0")