Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(sql): auto-resolve query datasources server-side (#19779)

p0ny350991b7bd68
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yaml
index 2b7984b153..1f85867047 100644
--- a/backend/api/mcp/gen/openapi.yaml
+++ b/backend/api/mcp/gen/openapi.yaml
@@ -10913,9 +10913,10 @@ components:
title: data_source_id
description: |-
The id of data source.
- It is used for querying admin data source even if the instance has
- read-only data sources. Or it can be used to query a specific read-only
- data source.
+ If omitted, Export resolves the data source server-side by using the
+ single read-only data source when exactly one exists, or the admin data
+ source otherwise. It can also be set explicitly to export from the admin
+ data source or a specific read-only data source.
schema:
type:
- string
@@ -15259,9 +15260,10 @@ components:
title: data_source_id
description: |-
The id of data source.
- It is used for querying admin data source even if the instance has
- read-only data sources. Or it can be used to query a specific read-only
- data source.
+ If omitted, Query resolves the data source server-side by using the single
+ read-only data source when exactly one exists, or the admin data source
+ otherwise. It can also be set explicitly to query the admin data source or
+ a specific read-only data source.
explain:
type: boolean
title: explain
diff --git a/backend/api/v1/instance_service.go b/backend/api/v1/instance_service.go
index 8de319c705..bdf30385c3 100644
--- a/backend/api/v1/instance_service.go
+++ b/backend/api/v1/instance_service.go
@@ -165,6 +165,9 @@ func (s *InstanceService) CreateInstance(ctx context.Context, req *connect.Reque
if err != nil {
return nil, connect.NewError(connect.CodeInvalidArgument, err)
}
+ if err := s.checkInstanceDataSources(ctx, instanceMessage, instanceMessage.Metadata.GetDataSources()); err != nil {
+ return nil, err
+ }
// Test connection.
if req.Msg.ValidateOnly {
@@ -206,10 +209,6 @@ func (s *InstanceService) CreateInstance(ctx context.Context, req *connect.Reque
}
}
- if err := s.checkInstanceDataSources(ctx, instanceMessage, instanceMessage.Metadata.GetDataSources()); err != nil {
- return nil, err
- }
-
instanceMessage.Workspace = workspaceID
instance, err := s.store.CreateInstance(ctx, instanceMessage)
if err != nil {
@@ -239,17 +238,14 @@ func (s *InstanceService) CreateInstance(ctx context.Context, req *connect.Reque
}
func (s *InstanceService) checkInstanceDataSources(ctx context.Context, instance *store.InstanceMessage, dataSources []*storepb.DataSource) error {
- dsIDMap := map[string]bool{}
for _, ds := range dataSources {
if err := s.checkDataSource(ctx, instance, ds); err != nil {
return err
}
- if dsIDMap[ds.GetId()] {
- return connect.NewError(connect.CodeInvalidArgument, errors.Errorf(`duplicate data source id "%s"`, ds.GetId()))
- }
- dsIDMap[ds.GetId()] = true
}
-
+ if err := store.ValidateDataSources(dataSources); err != nil {
+ return connect.NewError(connect.CodeInvalidArgument, err)
+ }
return nil
}
@@ -635,6 +631,11 @@ func (s *InstanceService) AddDataSource(ctx context.Context, req *connect.Reques
if err := s.checkDataSource(ctx, instance, dataSource); err != nil {
return nil, err
}
+ metadata := proto.CloneOf(instance.Metadata)
+ metadata.DataSources = append(metadata.DataSources, dataSource)
+ if err := s.checkInstanceDataSources(ctx, instance, metadata.GetDataSources()); err != nil {
+ return nil, err
+ }
// Test connection.
if req.Msg.ValidateOnly {
@@ -668,8 +669,6 @@ func (s *InstanceService) AddDataSource(ctx context.Context, req *connect.Reques
return nil, connect.NewError(connect.CodePermissionDenied, err)
}
- metadata := proto.CloneOf(instance.Metadata)
- metadata.DataSources = append(metadata.DataSources, dataSource)
instance, err = s.store.UpdateInstance(ctx, &store.UpdateInstanceMessage{
ResourceID: &instance.ResourceID,
Workspace: instance.Workspace,
@@ -847,7 +846,7 @@ func (s *InstanceService) UpdateDataSource(ctx context.Context, req *connect.Req
clearDataSourceAuthentication(dataSource)
- if err := s.checkDataSource(ctx, instance, dataSource); err != nil {
+ if err := s.checkInstanceDataSources(ctx, instance, metadata.GetDataSources()); err != nil {
return nil, err
}
diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.go
index 0bf75e9298..0965c9450e 100644
--- a/backend/api/v1/sql_service.go
+++ b/backend/api/v1/sql_service.go
@@ -250,7 +250,12 @@ func (s *SQLService) Query(ctx context.Context, req *connect.Request[v1pb.QueryR
}
}
- dataSource, err := checkAndGetDataSourceQueriable(ctx, s.store, s.licenseService, database, request.DataSourceId)
+ resolvedDataSourceID, err := resolveDataSourceID(instance, request.DataSourceId)
+ if err != nil {
+ return nil, err
+ }
+
+ dataSource, err := checkAndGetDataSourceQueriable(ctx, s.store, s.licenseService, database, resolvedDataSourceID)
if err != nil {
return nil, err
}
@@ -862,7 +867,12 @@ func (s *SQLService) Export(ctx context.Context, req *connect.Request[v1pb.Expor
}
}
- dataSource, err := checkAndGetDataSourceQueriable(ctx, s.store, s.licenseService, database, request.DataSourceId)
+ resolvedDataSourceID, err := resolveDataSourceID(instance, request.DataSourceId)
+ if err != nil {
+ return nil, err
+ }
+
+ dataSource, err := checkAndGetDataSourceQueriable(ctx, s.store, s.licenseService, database, resolvedDataSourceID)
if err != nil {
return nil, err
}
@@ -1764,6 +1774,37 @@ func (*SQLService) DiffMetadata(_ context.Context, req *connect.Request[v1pb.Dif
}), nil
}
+func resolveDataSourceID(instance *store.InstanceMessage, dataSourceID string) (string, error) {
+ if dataSourceID != "" {
+ return dataSourceID, nil
+ }
+
+ var adminDataSourceID string
+ var readOnlyDataSourceID string
+ readOnlyCount := 0
+ for _, dataSource := range instance.Metadata.GetDataSources() {
+ switch dataSource.GetType() {
+ case storepb.DataSourceType_ADMIN:
+ adminDataSourceID = dataSource.GetId()
+ case storepb.DataSourceType_READ_ONLY:
+ readOnlyCount++
+ readOnlyDataSourceID = dataSource.GetId()
+ default:
+ }
+ }
+
+ switch {
+ case readOnlyCount == 1:
+ return readOnlyDataSourceID, nil
+ case readOnlyCount > 1:
+ return "", connect.NewError(connect.CodeFailedPrecondition, errors.New("instance has multiple read-only data sources, please specify data_source_id explicitly"))
+ case adminDataSourceID != "":
+ return adminDataSourceID, nil
+ default:
+ return "", connect.NewError(connect.CodeFailedPrecondition, errors.New("instance has no admin data source"))
+ }
+}
+
func checkAndGetDataSourceQueriable(
ctx context.Context,
storeInstance *store.Store,
diff --git a/backend/generated-go/v1/sql_service.pb.go b/backend/generated-go/v1/sql_service.pb.go
index b7d33fa388..31a4b88dad 100644
--- a/backend/generated-go/v1/sql_service.pb.go
+++ b/backend/generated-go/v1/sql_service.pb.go
@@ -552,9 +552,10 @@ type QueryRequest struct {
// The maximum number of rows to return.
Limit int32 `protobuf:"varint,3,opt,name=limit,proto3" json:"limit,omitempty"`
// The id of data source.
- // It is used for querying admin data source even if the instance has
- // read-only data sources. Or it can be used to query a specific read-only
- // data source.
+ // If omitted, Query resolves the data source server-side by using the single
+ // read-only data source when exactly one exists, or the admin data source
+ // otherwise. It can also be set explicitly to query the admin data source or
+ // a specific read-only data source.
DataSourceId string `protobuf:"bytes,4,opt,name=data_source_id,json=dataSourceId,proto3" json:"data_source_id,omitempty"`
// Explain the statement.
Explain bool `protobuf:"varint,5,opt,name=explain,proto3" json:"explain,omitempty"`
@@ -1476,9 +1477,10 @@ type ExportRequest struct {
// The zip password provide by users.
Password string `protobuf:"bytes,6,opt,name=password,proto3" json:"password,omitempty"`
// The id of data source.
- // It is used for querying admin data source even if the instance has
- // read-only data sources. Or it can be used to query a specific read-only
- // data source.
+ // If omitted, Export resolves the data source server-side by using the
+ // single read-only data source when exactly one exists, or the admin data
+ // source otherwise. It can also be set explicitly to export from the admin
+ // data source or a specific read-only data source.
DataSourceId string `protobuf:"bytes,7,opt,name=data_source_id,json=dataSourceId,proto3" json:"data_source_id,omitempty"`
// The default schema to search objects. Equals to the current schema in
// Oracle and search path in Postgres.
@@ -2708,13 +2710,13 @@ const file_v1_sql_service_proto_rawDesc = "" +
"\n" +
"_container\"J\n" +
"\x14AdminExecuteResponse\x122\n" +
- "\aresults\x18\x01 \x03(\v2\x18.bytebase.v1.QueryResultR\aresults\"\xd0\x02\n" +
+ "\aresults\x18\x01 \x03(\v2\x18.bytebase.v1.QueryResultR\aresults\"\xcb\x02\n" +
"\fQueryRequest\x121\n" +
"\x04name\x18\x01 \x01(\tB\x1d\xe0A\x02\xfaA\x17\n" +
"\x15bytebase.com/DatabaseR\x04name\x12\x1c\n" +
"\tstatement\x18\x02 \x01(\tR\tstatement\x12\x14\n" +
- "\x05limit\x18\x03 \x01(\x05R\x05limit\x12)\n" +
- "\x0edata_source_id\x18\x04 \x01(\tB\x03\xe0A\x02R\fdataSourceId\x12\x18\n" +
+ "\x05limit\x18\x03 \x01(\x05R\x05limit\x12$\n" +
+ "\x0edata_source_id\x18\x04 \x01(\tR\fdataSourceId\x12\x18\n" +
"\aexplain\x18\x05 \x01(\bR\aexplain\x12\x1b\n" +
"\x06schema\x18\x06 \x01(\tH\x00R\x06schema\x88\x01\x01\x12;\n" +
"\fquery_option\x18\a \x01(\v2\x18.bytebase.v1.QueryOptionR\vqueryOption\x12!\n" +
diff --git a/backend/migrator/migration/3.17/0015##dedupe_read_only_data_sources.sql b/backend/migrator/migration/3.17/0015##dedupe_read_only_data_sources.sql
new file mode 100644
index 0000000000..9741e67747
--- /dev/null
+++ b/backend/migrator/migration/3.17/0015##dedupe_read_only_data_sources.sql
@@ -0,0 +1,25 @@
+-- Keep only the first READ_ONLY data source in instance metadata.
+-- Legacy rows may contain multiple READ_ONLY data sources, which makes
+-- automatic data source resolution ambiguous.
+
+UPDATE instance
+SET metadata = jsonb_set(
+ metadata,
+ '{dataSources}',
+ (
+ SELECT jsonb_agg(filtered.ds ORDER BY filtered.ord)
+ FROM (
+ SELECT ds, ord,
+ sum(CASE WHEN ds->>'type' = 'READ_ONLY' THEN 1 ELSE 0 END)
+ OVER (ORDER BY ord ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS read_only_rank
+ FROM jsonb_array_elements(metadata->'dataSources') WITH ORDINALITY AS elem(ds, ord)
+ ) AS filtered
+ WHERE filtered.ds->>'type' <> 'READ_ONLY' OR filtered.read_only_rank = 1
+ )
+)
+WHERE jsonb_typeof(metadata->'dataSources') = 'array'
+ AND (
+ SELECT count(*)
+ FROM jsonb_array_elements(metadata->'dataSources') AS ds
+ WHERE ds->>'type' = 'READ_ONLY'
+ ) > 1;
diff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.go
index 44427faa23..4756de9468 100644
--- a/backend/migrator/migrator_test.go
+++ b/backend/migrator/migrator_test.go
@@ -15,8 +15,8 @@ import (
func TestLatestVersion(t *testing.T) {
files, err := getSortedVersionedFiles()
require.NoError(t, err)
- require.Equal(t, semver.MustParse("3.17.14"), *files[len(files)-1].version)
- require.Equal(t, "migration/3.17/0014##add_subscription_table.sql", files[len(files)-1].path)
+ require.Equal(t, semver.MustParse("3.17.15"), *files[len(files)-1].version)
+ require.Equal(t, "migration/3.17/0015##dedupe_read_only_data_sources.sql", files[len(files)-1].path)
}
func TestVersionUnique(t *testing.T) {
@@ -34,6 +34,60 @@ func TestVersionUnique(t *testing.T) {
}
}
+func TestMigration3_17_15_DedupeReadOnlyDataSources(t *testing.T) {
+ ctx := context.Background()
+ container := testcontainer.GetTestPgContainer(ctx, t)
+ t.Cleanup(func() { container.Close(ctx) })
+
+ db := container.GetDB()
+
+ setup := `
+ CREATE TABLE instance (
+ resource_id TEXT PRIMARY KEY,
+ metadata JSONB NOT NULL DEFAULT '{}'
+ );
+
+ INSERT INTO instance (resource_id, metadata) VALUES
+ (
+ 'instance-with-duplicate-read-only',
+ '{"dataSources":[{"id":"admin","type":"ADMIN","username":"admin"},{"id":"read-only-1","type":"READ_ONLY","username":"readonly-1"},{"id":"read-only-2","type":"READ_ONLY","username":"readonly-2"}]}'
+ ),
+ (
+ 'instance-with-single-read-only',
+ '{"dataSources":[{"id":"admin","type":"ADMIN","username":"admin"},{"id":"read-only-1","type":"READ_ONLY","username":"readonly-1"}]}'
+ ),
+ (
+ 'instance-with-non-array-data-sources',
+ '{"dataSources":{"id":"read-only-1","type":"READ_ONLY","username":"readonly-1"}}'
+ ),
+ (
+ 'instance-without-data-sources',
+ '{"engine":"POSTGRES"}'
+ );
+ `
+ _, err := db.ExecContext(ctx, setup)
+ require.NoError(t, err)
+
+ statement, err := migrationFS.ReadFile("migration/3.17/0015##dedupe_read_only_data_sources.sql")
+ require.NoError(t, err)
+
+ _, err = db.ExecContext(ctx, string(statement))
+ require.NoError(t, err)
+
+ getMetadata := func(resourceID string) string {
+ t.Helper()
+ var metadata string
+ err := db.QueryRowContext(ctx, `SELECT metadata::text FROM instance WHERE resource_id = $1`, resourceID).Scan(&metadata)
+ require.NoError(t, err)
+ return metadata
+ }
+
+ require.JSONEq(t, `{"dataSources":[{"id":"admin","type":"ADMIN","username":"admin"},{"id":"read-only-1","type":"READ_ONLY","username":"readonly-1"}]}`, getMetadata("instance-with-duplicate-read-only"))
+ require.JSONEq(t, `{"dataSources":[{"id":"admin","type":"ADMIN","username":"admin"},{"id":"read-only-1","type":"READ_ONLY","username":"readonly-1"}]}`, getMetadata("instance-with-single-read-only"))
+ require.JSONEq(t, `{"dataSources":{"id":"read-only-1","type":"READ_ONLY","username":"readonly-1"}}`, getMetadata("instance-with-non-array-data-sources"))
+ require.JSONEq(t, `{"engine":"POSTGRES"}`, getMetadata("instance-without-data-sources"))
+}
+
// TestMigration3_7_20_ScalarTaskUpdateTasks verifies that the migration 3.7.20
// UPDATE on issue_comment handles scalar (non-array) taskUpdate.tasks values
// without error. Regression test for "cannot get array length of a scalar".
diff --git a/backend/store/instance.go b/backend/store/instance.go
index 54d4dba82f..c0e9c366ee 100644
--- a/backend/store/instance.go
+++ b/backend/store/instance.go
@@ -175,7 +175,7 @@ func (s *Store) ListInstances(ctx context.Context, find *FindInstanceMessage) ([
// CreateInstance creates an instance.
func (s *Store) CreateInstance(ctx context.Context, instanceCreate *InstanceMessage) (*InstanceMessage, error) {
- if err := validateDataSources(instanceCreate.Metadata); err != nil {
+ if err := validateInstanceDataSources(instanceCreate.Metadata); err != nil {
return nil, err
}
@@ -298,24 +298,36 @@ func (s *Store) GetActivatedInstanceCount(ctx context.Context, workspaceID strin
return count, nil
}
-func validateDataSources(metadata *storepb.Instance) error {
+func ValidateDataSources(dataSources []*storepb.DataSource) error {
dataSourceMap := map[string]bool{}
adminCount := 0
- for _, dataSource := range metadata.GetDataSources() {
+ readOnlyCount := 0
+ for _, dataSource := range dataSources {
if dataSourceMap[dataSource.GetId()] {
return errors.Errorf("duplicate data source ID %s", dataSource.GetId())
}
dataSourceMap[dataSource.GetId()] = true
- if dataSource.GetType() == storepb.DataSourceType_ADMIN {
+ switch dataSource.GetType() {
+ case storepb.DataSourceType_ADMIN:
adminCount++
+ case storepb.DataSourceType_READ_ONLY:
+ readOnlyCount++
+ default:
}
}
if adminCount != 1 {
return errors.Errorf("require exactly one admin data source")
}
+ if readOnlyCount > 1 {
+ return errors.Errorf("require at most one read-only data source")
+ }
return nil
}
+func validateInstanceDataSources(metadata *storepb.Instance) error {
+ return ValidateDataSources(metadata.GetDataSources())
+}
+
// IsObjectCaseSensitive returns true if the engine ignores database and table case sensitive.
func IsObjectCaseSensitive(instance *InstanceMessage) bool {
switch instance.Metadata.GetEngine() {
diff --git a/backend/tests/data_source_test.go b/backend/tests/data_source_test.go
index 64deeb079a..67acebca7a 100644
--- a/backend/tests/data_source_test.go
+++ b/backend/tests/data_source_test.go
@@ -116,7 +116,36 @@ func TestDataSource(t *testing.T) {
SslKey: "",
},
}))
- a.NoError(err)
+ a.ErrorContains(err, "require at most one read-only data source")
+
+ _, err = ctl.instanceServiceClient.CreateInstance(ctx, connect.NewRequest(&v1pb.CreateInstanceRequest{
+ InstanceId: generateRandomString("instance"),
+ Instance: &v1pb.Instance{
+ Title: "invalid",
+ Engine: v1pb.Engine_SQLITE,
+ Environment: new("environments/prod"),
+ Activation: true,
+ DataSources: []*v1pb.DataSource{
+ {Type: v1pb.DataSourceType_ADMIN, Id: "admin", Host: instanceDir},
+ {Type: v1pb.DataSourceType_READ_ONLY, Id: "readonly-1", Host: instanceDir},
+ {Type: v1pb.DataSourceType_READ_ONLY, Id: "readonly-2", Host: instanceDir},
+ },
+ },
+ }))
+ a.ErrorContains(err, "require at most one read-only data source")
+
+ _, err = ctl.instanceServiceClient.UpdateInstance(ctx, connect.NewRequest(&v1pb.UpdateInstanceRequest{
+ Instance: &v1pb.Instance{
+ Name: instance.Name,
+ DataSources: []*v1pb.DataSource{
+ {Type: v1pb.DataSourceType_ADMIN, Id: "admin-ds", Host: instanceDir},
+ {Type: v1pb.DataSourceType_READ_ONLY, Id: "readonly", Username: "ro_ds", Host: "127.0.0.1", Port: "8000"},
+ {Type: v1pb.DataSourceType_READ_ONLY, Id: "readonly-2", Host: instanceDir},
+ },
+ },
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"data_sources"}},
+ }))
+ a.ErrorContains(err, "require at most one read-only data source")
_, err = ctl.instanceServiceClient.RemoveDataSource(ctx, connect.NewRequest(&v1pb.RemoveDataSourceRequest{
Name: instance.Name,
diff --git a/backend/tests/sensitive_data_test.go b/backend/tests/sensitive_data_test.go
index ff8eb44057..a0edc88a77 100644
--- a/backend/tests/sensitive_data_test.go
+++ b/backend/tests/sensitive_data_test.go
@@ -173,9 +173,8 @@ func TestSensitiveData(t *testing.T) {
// Validate query syntax error - with new ACL system, syntax errors are returned in query results
syntaxErrorResp, err := ctl.sqlServiceClient.Query(ctx, connect.NewRequest(&v1pb.QueryRequest{
- Name: database.Name,
- Statement: "SELECT hello TO world;",
- DataSourceId: "admin",
+ Name: database.Name,
+ Statement: "SELECT hello TO world;",
}))
a.NoError(err)
a.Equal(1, len(syntaxErrorResp.Msg.Results))
@@ -248,9 +247,8 @@ func TestSensitiveData(t *testing.T) {
// Query masked data.
queryResp, err := ctl.sqlServiceClient.Query(ctx, connect.NewRequest(&v1pb.QueryRequest{
- Name: database.Name,
- Statement: queryTable,
- DataSourceId: "admin",
+ Name: database.Name,
+ Statement: queryTable,
}))
a.NoError(err)
a.Equal(1, len(queryResp.Msg.Results))
@@ -299,9 +297,8 @@ func TestSensitiveData(t *testing.T) {
// The database error message would normally contain the actual column value,
// but the masking pipeline should redact it.
errorLeakResp, err := ctl.sqlServiceClient.Query(ctx, connect.NewRequest(&v1pb.QueryRequest{
- Name: database.Name,
- Statement: "SELECT BIN_TO_UUID(author) FROM tech_book WHERE id = 1",
- DataSourceId: "admin",
+ Name: database.Name,
+ Statement: "SELECT BIN_TO_UUID(author) FROM tech_book WHERE id = 1",
}))
a.NoError(err)
a.Equal(1, len(errorLeakResp.Msg.Results))
@@ -312,9 +309,8 @@ func TestSensitiveData(t *testing.T) {
// Same query on a non-masked column should preserve the original error.
nonMaskedErrorResp, err := ctl.sqlServiceClient.Query(ctx, connect.NewRequest(&v1pb.QueryRequest{
- Name: database.Name,
- Statement: "SELECT BIN_TO_UUID(name) FROM tech_book WHERE id = 1",
- DataSourceId: "admin",
+ Name: database.Name,
+ Statement: "SELECT BIN_TO_UUID(name) FROM tech_book WHERE id = 1",
}))
a.NoError(err)
a.Equal(1, len(nonMaskedErrorResp.Msg.Results))
diff --git a/backend/tests/sql_export_data_source_test.go b/backend/tests/sql_export_data_source_test.go
new file mode 100644
index 0000000000..d0c8b4a1e0
--- /dev/null
+++ b/backend/tests/sql_export_data_source_test.go
@@ -0,0 +1,164 @@
+package tests
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "io"
+ "strings"
+ "testing"
+
+ "connectrpc.com/connect"
+ "github.com/alexmullins/zip"
+ "github.com/pkg/errors"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/proto"
+
+ "github.com/bytebase/bytebase/backend/common"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+func TestSQLExportDataSourceResolution(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ mysqlContainer, err := getMySQLContainer(ctx)
+ defer func() {
+ mysqlContainer.Close(ctx)
+ }()
+ a.NoError(err)
+
+ mysqlDB := mysqlContainer.db
+ _, err = mysqlDB.Exec("DROP USER IF EXISTS 'export_ro'@'%'")
+ a.NoError(err)
+ _, err = mysqlDB.Exec("CREATE USER 'export_ro'@'%' IDENTIFIED WITH mysql_native_password BY 'export_ro_password'")
+ a.NoError(err)
+ _, err = mysqlDB.Exec("GRANT SELECT ON *.* TO 'export_ro'@'%'")
+ a.NoError(err)
+
+ instanceResp, err := ctl.instanceServiceClient.CreateInstance(ctx, connect.NewRequest(&v1pb.CreateInstanceRequest{
+ InstanceId: generateRandomString("instance"),
+ Instance: &v1pb.Instance{
+ Title: "mysqlInstance",
+ Engine: v1pb.Engine_MYSQL,
+ Environment: new("environments/prod"),
+ Activation: true,
+ DataSources: []*v1pb.DataSource{{Type: v1pb.DataSourceType_ADMIN, Host: mysqlContainer.host, Port: mysqlContainer.port, Username: "root", Password: "root-password", Id: "admin"}},
+ },
+ }))
+ a.NoError(err)
+ instance := instanceResp.Msg
+
+ const databaseName = "ExportDataSourceResolution"
+ err = ctl.createDatabase(ctx, ctl.project, instance, nil, databaseName, "")
+ a.NoError(err)
+
+ databaseResp, err := ctl.databaseServiceClient.GetDatabase(ctx, connect.NewRequest(&v1pb.GetDatabaseRequest{
+ Name: fmt.Sprintf("%s/databases/%s", instance.Name, databaseName),
+ }))
+ a.NoError(err)
+ database := databaseResp.Msg
+
+ setupSheetResp, err := ctl.sheetServiceClient.CreateSheet(ctx, connect.NewRequest(&v1pb.CreateSheetRequest{
+ Parent: ctl.project.Name,
+ Sheet: &v1pb.Sheet{Content: []byte(`
+ CREATE TABLE books(id INT PRIMARY KEY, name VARCHAR(64));
+ INSERT INTO books VALUES (1, 'Bytebase');
+ `)},
+ }))
+ a.NoError(err)
+ err = ctl.changeDatabase(ctx, ctl.project, database, setupSheetResp.Msg, false)
+ a.NoError(err)
+
+ assertExportContent := func() {
+ exportResp, err := ctl.sqlServiceClient.Export(ctx, connect.NewRequest(&v1pb.ExportRequest{
+ Name: database.Name,
+ Format: v1pb.ExportFormat_CSV,
+ Statement: "SELECT name FROM books;",
+ }))
+ a.NoError(err)
+ a.Equal("name\n\"Bytebase\"", getExportResultContent(t, exportResp.Msg.Content, ".result.csv"))
+ }
+
+ assertExportContent()
+
+ _, err = ctl.instanceServiceClient.AddDataSource(ctx, connect.NewRequest(&v1pb.AddDataSourceRequest{
+ Name: instance.Name,
+ DataSource: &v1pb.DataSource{
+ Id: "readonly",
+ Type: v1pb.DataSourceType_READ_ONLY,
+ Host: mysqlContainer.host,
+ Port: mysqlContainer.port,
+ Username: "export_ro",
+ Password: "export_ro_password",
+ },
+ }))
+ a.NoError(err)
+
+ assertExportContent()
+
+ instanceID, err := common.GetInstanceID(instance.Name)
+ a.NoError(err)
+ stores := getStore(t, ctl.server)
+ instanceMessage, err := stores.GetInstance(ctx, &store.FindInstanceMessage{Workspace: common.GetWorkspaceIDFromContext(ctx), ResourceID: &instanceID})
+ a.NoError(err)
+ metadata := proto.CloneOf(instanceMessage.Metadata)
+ var readOnly *storepb.DataSource
+ for _, dataSource := range metadata.GetDataSources() {
+ if dataSource.GetType() == storepb.DataSourceType_READ_ONLY {
+ readOnly = proto.CloneOf(dataSource)
+ break
+ }
+ }
+ if readOnly == nil {
+ t.Fatal("expected read-only data source")
+ }
+ readOnly.Id = "readonly-legacy"
+ metadata.DataSources = append(metadata.DataSources, readOnly)
+ _, err = stores.UpdateInstance(ctx, &store.UpdateInstanceMessage{
+ ResourceID: &instanceID,
+ Workspace: common.GetWorkspaceIDFromContext(ctx),
+ Metadata: metadata,
+ })
+ a.NoError(err)
+
+ _, err = ctl.sqlServiceClient.Export(ctx, connect.NewRequest(&v1pb.ExportRequest{
+ Name: database.Name,
+ Format: v1pb.ExportFormat_CSV,
+ Statement: "SELECT name FROM books;",
+ }))
+ a.Error(err)
+ var connectErr *connect.Error
+ a.True(errors.As(err, &connectErr))
+ a.Equal(connect.CodeFailedPrecondition, connectErr.Code())
+ a.Contains(connectErr.Message(), "multiple read-only data sources")
+}
+
+func getExportResultContent(t *testing.T, export []byte, suffix string) string {
+ t.Helper()
+
+ zipReader, err := zip.NewReader(bytes.NewReader(export), int64(len(export)))
+ require.NoError(t, err)
+
+ for _, file := range zipReader.File {
+ if !strings.HasSuffix(file.Name, suffix) {
+ continue
+ }
+ rc, err := file.Open()
+ require.NoError(t, err)
+ content, err := io.ReadAll(rc)
+ require.NoError(t, err)
+ require.NoError(t, rc.Close())
+ return string(content)
+ }
+
+ t.Fatalf("export result with suffix %q not found", suffix)
+ return ""
+}
diff --git a/backend/tests/sql_query_data_source_test.go b/backend/tests/sql_query_data_source_test.go
new file mode 100644
index 0000000000..97104efd12
--- /dev/null
+++ b/backend/tests/sql_query_data_source_test.go
@@ -0,0 +1,151 @@
+package tests
+
+import (
+ "context"
+ "fmt"
+ "reflect"
+ "testing"
+ "unsafe"
+
+ "connectrpc.com/connect"
+ "github.com/pkg/errors"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/proto"
+
+ "github.com/bytebase/bytebase/backend/common"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+ "github.com/bytebase/bytebase/backend/server"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+func TestSQLQueryDataSourceResolution(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ mysqlContainer, err := getMySQLContainer(ctx)
+ defer func() {
+ mysqlContainer.Close(ctx)
+ }()
+ a.NoError(err)
+
+ mysqlDB := mysqlContainer.db
+ _, err = mysqlDB.Exec("DROP USER IF EXISTS 'query_ro'@'%'")
+ a.NoError(err)
+ _, err = mysqlDB.Exec("CREATE USER 'query_ro'@'%' IDENTIFIED WITH mysql_native_password BY 'query_ro_password'")
+ a.NoError(err)
+ _, err = mysqlDB.Exec("GRANT SELECT ON *.* TO 'query_ro'@'%'")
+ a.NoError(err)
+
+ instanceResp, err := ctl.instanceServiceClient.CreateInstance(ctx, connect.NewRequest(&v1pb.CreateInstanceRequest{
+ InstanceId: generateRandomString("instance"),
+ Instance: &v1pb.Instance{
+ Title: "mysqlInstance",
+ Engine: v1pb.Engine_MYSQL,
+ Environment: new("environments/prod"),
+ Activation: true,
+ DataSources: []*v1pb.DataSource{{Type: v1pb.DataSourceType_ADMIN, Host: mysqlContainer.host, Port: mysqlContainer.port, Username: "root", Password: "root-password", Id: "admin"}},
+ },
+ }))
+ a.NoError(err)
+ instance := instanceResp.Msg
+
+ const databaseName = "QueryDataSourceResolution"
+ err = ctl.createDatabase(ctx, ctl.project, instance, nil, databaseName, "")
+ a.NoError(err)
+
+ databaseResp, err := ctl.databaseServiceClient.GetDatabase(ctx, connect.NewRequest(&v1pb.GetDatabaseRequest{
+ Name: fmt.Sprintf("%s/databases/%s", instance.Name, databaseName),
+ }))
+ a.NoError(err)
+ database := databaseResp.Msg
+
+ setupSheetResp, err := ctl.sheetServiceClient.CreateSheet(ctx, connect.NewRequest(&v1pb.CreateSheetRequest{
+ Parent: ctl.project.Name,
+ Sheet: &v1pb.Sheet{Content: []byte(`CREATE TABLE books(id INT PRIMARY KEY, name VARCHAR(64)); INSERT INTO books VALUES (1, 'Bytebase');`)},
+ }))
+ a.NoError(err)
+ err = ctl.changeDatabase(ctx, ctl.project, database, setupSheetResp.Msg, false)
+ a.NoError(err)
+
+ queryResp, err := ctl.sqlServiceClient.Query(ctx, connect.NewRequest(&v1pb.QueryRequest{
+ Name: database.Name,
+ Statement: "SELECT name FROM books;",
+ }))
+ a.NoError(err)
+ a.Len(queryResp.Msg.Results, 1)
+ a.Empty(queryResp.Msg.Results[0].Error)
+
+ _, err = ctl.instanceServiceClient.AddDataSource(ctx, connect.NewRequest(&v1pb.AddDataSourceRequest{
+ Name: instance.Name,
+ DataSource: &v1pb.DataSource{
+ Id: "readonly",
+ Type: v1pb.DataSourceType_READ_ONLY,
+ Host: mysqlContainer.host,
+ Port: mysqlContainer.port,
+ Username: "query_ro",
+ Password: "query_ro_password",
+ },
+ }))
+ a.NoError(err)
+
+ queryResp, err = ctl.sqlServiceClient.Query(ctx, connect.NewRequest(&v1pb.QueryRequest{
+ Name: database.Name,
+ Statement: "SELECT name FROM books;",
+ }))
+ a.NoError(err)
+ a.Len(queryResp.Msg.Results, 1)
+ a.Empty(queryResp.Msg.Results[0].Error)
+ a.Len(queryResp.Msg.Results[0].Rows, 1)
+ a.Equal("Bytebase", queryResp.Msg.Results[0].Rows[0].Values[0].GetStringValue())
+
+ instanceID, err := common.GetInstanceID(instance.Name)
+ a.NoError(err)
+ stores := getStore(t, ctl.server)
+ instanceMessage, err := stores.GetInstance(ctx, &store.FindInstanceMessage{Workspace: common.GetWorkspaceIDFromContext(ctx), ResourceID: &instanceID})
+ a.NoError(err)
+ metadata := proto.CloneOf(instanceMessage.Metadata)
+ var readOnly *storepb.DataSource
+ for _, dataSource := range metadata.GetDataSources() {
+ if dataSource.GetType() == storepb.DataSourceType_READ_ONLY {
+ readOnly = proto.CloneOf(dataSource)
+ break
+ }
+ }
+ if readOnly == nil {
+ t.Fatal("expected read-only data source")
+ }
+ readOnly.Id = "readonly-legacy"
+ metadata.DataSources = append(metadata.DataSources, readOnly)
+ _, err = stores.UpdateInstance(ctx, &store.UpdateInstanceMessage{
+ ResourceID: &instanceID,
+ Workspace: common.GetWorkspaceIDFromContext(ctx),
+ Metadata: metadata,
+ })
+ a.NoError(err)
+
+ _, err = ctl.sqlServiceClient.Query(ctx, connect.NewRequest(&v1pb.QueryRequest{
+ Name: database.Name,
+ Statement: "SELECT name FROM books;",
+ }))
+ a.Error(err)
+ var connectErr *connect.Error
+ a.True(errors.As(err, &connectErr))
+ a.Equal(connect.CodeFailedPrecondition, connectErr.Code())
+ a.Contains(connectErr.Message(), "multiple read-only data sources")
+}
+
+func getStore(t *testing.T, srv *server.Server) *store.Store {
+ t.Helper()
+ field := reflect.ValueOf(srv).Elem().FieldByName("store")
+ stores, ok := reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Elem().Interface().(*store.Store)
+ if !ok {
+ t.Fatal("failed to access server store")
+ }
+ return stores
+}
diff --git a/backend/tests/sql_review_test.go b/backend/tests/sql_review_test.go
index f9bd05e8cf..f3418ecfa2 100644
--- a/backend/tests/sql_review_test.go
+++ b/backend/tests/sql_review_test.go
@@ -362,9 +362,8 @@ func TestSQLReviewForMySQL(t *testing.T) {
countSQL := "SELECT count(*) FROM test WHERE 1=1;"
dmlSQL := "INSERT INTO test SELECT * FROM " + valueTable
originQueryResp, err := ctl.sqlServiceClient.Query(ctx, connect.NewRequest(&v1pb.QueryRequest{
- Name: database.Msg.Name,
- Statement: countSQL,
- DataSourceId: "admin",
+ Name: database.Msg.Name,
+ Statement: countSQL,
}))
a.NoError(err)
a.Equal(1, len(originQueryResp.Msg.Results))
@@ -374,9 +373,8 @@ func TestSQLReviewForMySQL(t *testing.T) {
createIssueAndReturnSQLReviewResult(ctx, a, ctl, ctl.project, database.Msg, dmlSQL, false /* wait */)
finalQueryResp, err := ctl.sqlServiceClient.Query(ctx, connect.NewRequest(&v1pb.QueryRequest{
- Name: database.Msg.Name,
- Statement: countSQL,
- DataSourceId: "admin",
+ Name: database.Msg.Name,
+ Statement: countSQL,
}))
a.NoError(err)
a.Equal(1, len(finalQueryResp.Msg.Results))
diff --git a/backend/tests/sql_stop_on_error_test.go b/backend/tests/sql_stop_on_error_test.go
index f1ca2edeaf..7a2b81507d 100644
--- a/backend/tests/sql_stop_on_error_test.go
+++ b/backend/tests/sql_stop_on_error_test.go
@@ -220,9 +220,8 @@ func TestSQLQueryStopOnError(t *testing.T) {
// Execute the query using the Query API (not AdminExecute)
queryResp, err := ctl.sqlServiceClient.Query(ctx, connect.NewRequest(&v1pb.QueryRequest{
- Name: database.Name,
- Statement: tt.query,
- DataSourceId: "admin",
+ Name: database.Name,
+ Statement: tt.query,
}))
if tt.wantError {
diff --git a/frontend/src/composables/useExecuteSQL.ts b/frontend/src/composables/useExecuteSQL.ts
index 3ffe73827e..192cb205d3 100644
--- a/frontend/src/composables/useExecuteSQL.ts
+++ b/frontend/src/composables/useExecuteSQL.ts
@@ -17,8 +17,6 @@ import {
import type {
BBNotificationStyle,
QueryContextStatus,
- QueryDataSourceType,
- SQLEditorConnection,
SQLEditorDatabaseQueryContext,
SQLEditorQueryParams,
SQLResultSetV1,
@@ -35,7 +33,6 @@ import {
} from "@/types/proto-es/v1/sql_service_pb";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import {
- extractDatabaseResourceName,
getDatabaseProject,
getInstanceResource,
getValidDataSourceByPolicy,
@@ -93,19 +90,6 @@ const useExecuteSQL = () => {
return true;
};
- const getDataSourceId = (
- database: Database,
- connection: SQLEditorConnection,
- mode?: QueryDataSourceType
- ) => {
- const { instance } = extractDatabaseResourceName(database.name);
- if (instance === connection.instance && !!connection.dataSourceId) {
- return connection.dataSourceId;
- }
-
- return getValidDataSourceByPolicy(database, mode) ?? "";
- };
-
const changeContextStatus = (
ctx: SQLEditorDatabaseQueryContext,
status: QueryContextStatus
@@ -220,17 +204,21 @@ const useExecuteSQL = () => {
}
const database = dbStore.getDatabaseByName(databaseName);
- const dataSourceId = await getDataSourceId(
- database,
- params.connection,
- isBatch ? tab.batchQueryContext.dataSourceType : undefined
- );
+ const resolvedDataSourceId =
+ isBatch && tab.batchQueryContext.dataSourceType
+ ? ((await getValidDataSourceByPolicy(
+ database,
+ tab.batchQueryContext.dataSourceType
+ )) ?? "")
+ : params.connection.dataSourceId;
const context: SQLEditorDatabaseQueryContext = {
id: uuidv4(),
params: Object.assign(cloneDeep(params), {
connection: {
...params.connection,
- dataSourceId,
+ ...(resolvedDataSourceId
+ ? { dataSourceId: resolvedDataSourceId }
+ : {}),
},
}),
status: "PENDING",
@@ -271,13 +259,6 @@ const useExecuteSQL = () => {
const sqlStore = useSQLStore();
const dataSourceId = context.params.connection.dataSourceId;
- if (!dataSourceId) {
- return finish({
- error: t("sql-editor.no-data-source"),
- results: [],
- status: Code.NotFound,
- });
- }
if (abortController.signal.aborted) {
// Once any one of the batch queries is aborted, don't go further
@@ -296,7 +277,7 @@ const useExecuteSQL = () => {
const resultSet = await sqlStore.query(
create(QueryRequestSchema, {
name: database.name,
- dataSourceId: dataSourceId,
+ ...(dataSourceId ? { dataSourceId } : {}),
statement: context.params.statement,
limit: context.params.limit ?? sqlEditorStore.resultRowsLimit,
explain: context.params.explain,
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 9f83fbb092..8c95c029ce 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -2035,7 +2035,8 @@
"admin": "Admin",
"read-only": "RO",
"direct-connection": "Direct Connection",
- "select-query-data-source": "Select query data source"
+ "select-query-data-source": "Select query data source",
+ "automatic-query-data-source": "Automatic"
},
"setting": {
"label": {
@@ -2060,7 +2061,6 @@
"can-not-execute-query": "Cannot execute query when loading data.",
"invalid-database": "Invalid database {database}",
"request-aborted": "User aborted the request",
- "no-data-source": "No queriable data source. Please check the data source query policy on environment or project.",
"no-queriable-database": "No queriable database",
"rows": "row | rows",
"vertical-display": "Vertical display",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 00aaa2fe56..81411761b7 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -2035,7 +2035,8 @@
"admin": "Admin",
"read-only": "Solo lectura",
"direct-connection": "Direct Connection",
- "select-query-data-source": "Seleccionar fuente de datos de consulta"
+ "select-query-data-source": "Seleccionar fuente de datos de consulta",
+ "automatic-query-data-source": "Automática"
},
"setting": {
"label": {
@@ -2060,7 +2061,6 @@
"can-not-execute-query": "No se puede ejecutar la consulta al cargar datos.",
"invalid-database": "Base de datos no válida {database}",
"request-aborted": "El usuario abortó la solicitud",
- "no-data-source": "No se puede consultar ninguna fuente de datos. Consulte la política de consulta de fuentes de datos del entorno o proyecto.",
"no-queriable-database": "No hay base de datos consultable",
"rows": "fila | filas",
"vertical-display": "Pantalla vertical",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index c0efd9bbfc..82a696df4d 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -2035,7 +2035,8 @@
"admin": "管理者",
"read-only": "読み取り専用",
"direct-connection": "Direct Connection",
- "select-query-data-source": "クエリデータソースの選択"
+ "select-query-data-source": "クエリデータソースの選択",
+ "automatic-query-data-source": "自動"
},
"setting": {
"label": {
@@ -2060,7 +2061,6 @@
"can-not-execute-query": "データのロード中にクエリを実行できません",
"invalid-database": "無効なデータベース {database}",
"request-aborted": "ユーザーがリクエストを中止しました",
- "no-data-source": "クエリ可能なデータソースがありません。環境またはプロジェクトのデータソースクエリポリシーを確認してください。",
"no-queriable-database": "クエリ可能なデータベースがありません",
"rows": "記録",
"vertical-display": "縦型表示",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 2371e23c39..f2cc25748a 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -2035,7 +2035,8 @@
"admin": "Quản trị",
"read-only": "Chỉ đọc",
"direct-connection": "Kết nối trực tiếp",
- "select-query-data-source": "Chọn nguồn dữ liệu truy vấn"
+ "select-query-data-source": "Chọn nguồn dữ liệu truy vấn",
+ "automatic-query-data-source": "Tự động"
},
"setting": {
"label": {
@@ -2060,7 +2061,6 @@
"can-not-execute-query": "Không thể thực hiện truy vấn khi đang tải dữ liệu.",
"invalid-database": "Cơ sở dữ liệu không hợp lệ {database}",
"request-aborted": "Người dùng đã hủy yêu cầu",
- "no-data-source": "Không có nguồn dữ liệu có thể truy vấn. Vui lòng kiểm tra chính sách truy vấn nguồn dữ liệu trên môi trường hoặc dự án.",
"no-queriable-database": "Không có cơ sở dữ liệu có thể truy vấn",
"rows": "dòng | dòng",
"vertical-display": "Hiển thị dọc",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 2fba40beb4..2859081a47 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -2035,7 +2035,8 @@
"admin": "管理员",
"read-only": "只读",
"direct-connection": "Direct Connection",
- "select-query-data-source": "选择查询数据源"
+ "select-query-data-source": "选择查询数据源",
+ "automatic-query-data-source": "自动"
},
"setting": {
"label": {
@@ -2060,7 +2061,6 @@
"can-not-execute-query": "加载数据时无法执行查询",
"invalid-database": "数据库 {database} 无效",
"request-aborted": "用户中止了请求",
- "no-data-source": "没有可查询的数据源。请检查环境或项目的数据源查询策略。",
"no-queriable-database": "没有可查询的数据库",
"rows": "条记录",
"vertical-display": "竖向展示",
diff --git a/frontend/src/plugins/agent/logic/skills/query.ts b/frontend/src/plugins/agent/logic/skills/query.ts
index 2816b38aa0..da4a11e56c 100644
--- a/frontend/src/plugins/agent/logic/skills/query.ts
+++ b/frontend/src/plugins/agent/logic/skills/query.ts
@@ -35,18 +35,17 @@ Run SQL queries against databases managed by Bytebase.
- \`engine == "MYSQL"\` - MySQL databases only
- \`environment == "environments/prod" && name.matches("user")\` - combine filters
- **Extract \`dataSourceId\`** from \`instanceResource.dataSources\` in the response. Prefer \`type: "READ_ONLY"\` over \`type: "ADMIN"\` when available.
+ **Optionally inspect \`instanceResource.dataSources\`** if you need to target a specific data source. Prefer \`type: "READ_ONLY"\` over \`type: "ADMIN"\` when choosing explicitly.
3. **Execute SQL**:
\`\`\`
call_api(operationId="SQLService/Query", body={
"name": "instances/{instance-id}/databases/{database-name}",
- "dataSourceId": "{data-source-id}",
"statement": "SELECT * FROM users LIMIT 10"
})
\`\`\`
- \`dataSourceId\` is **required**.
+ Include \`dataSourceId\` only when you need to override the server-selected data source.
## Notes
@@ -59,7 +58,6 @@ Run SQL queries against databases managed by Bytebase.
| Error | Cause | Fix |
|-------|-------|-----|
-| data source id is required | Missing dataSourceId field | Get dataSourceId from instanceResource.dataSources in database listing |
| database not found | Wrong instance/database name | List databases first |
| permission denied | Missing bb.sql.query | Check user permissions |
| syntax error | Invalid SQL | Check SQL syntax for the database engine |`,
diff --git a/frontend/src/types/proto-es/v1/sql_service_pb.d.ts b/frontend/src/types/proto-es/v1/sql_service_pb.d.ts
index 7d1bf68013..e69919cb6d 100644
--- a/frontend/src/types/proto-es/v1/sql_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/sql_service_pb.d.ts
@@ -108,9 +108,10 @@ export declare type QueryRequest = Message<"bytebase.v1.QueryRequest"> & {
/**
* The id of data source.
- * It is used for querying admin data source even if the instance has
- * read-only data sources. Or it can be used to query a specific read-only
- * data source.
+ * If omitted, Query resolves the data source server-side by using the single
+ * read-only data source when exactly one exists, or the admin data source
+ * otherwise. It can also be set explicitly to query the admin data source or
+ * a specific read-only data source.
*
* @generated from field: string data_source_id = 4;
*/
@@ -1037,9 +1038,10 @@ export declare type ExportRequest = Message<"bytebase.v1.ExportRequest"> & {
/**
* The id of data source.
- * It is used for querying admin data source even if the instance has
- * read-only data sources. Or it can be used to query a specific read-only
- * data source.
+ * If omitted, Export resolves the data source server-side by using the
+ * single read-only data source when exactly one exists, or the admin data
+ * source otherwise. It can also be set explicitly to export from the admin
+ * data source or a specific read-only data source.
*
* @generated from field: string data_source_id = 7;
*/
diff --git a/frontend/src/types/proto-es/v1/sql_service_pb.js b/frontend/src/types/proto-es/v1/sql_service_pb.js
index 89a9066a86..bf5e1cb8e9 100644
--- a/frontend/src/types/proto-es/v1/sql_service_pb.js
+++ b/frontend/src/types/proto-es/v1/sql_service_pb.js
@@ -15,7 +15,7 @@ import { file_v1_database_service } from "./database_service_pb";
* Describes the file v1/sql_service.proto.
*/
export const file_v1_sql_service = /*@__PURE__*/
- fileDesc("ChR2MS9zcWxfc2VydmljZS5wcm90bxILYnl0ZWJhc2UudjEiqgEKE0FkbWluRXhlY3V0ZVJlcXVlc3QSKwoEbmFtZRgBIAEoCUId4EEC+kEXChVieXRlYmFzZS5jb20vRGF0YWJhc2USEQoJc3RhdGVtZW50GAIgASgJEg0KBWxpbWl0GAMgASgFEhMKBnNj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XRhUmVxdWVzdBohLmJ5dGViYXNlLnYxLkRpZmZNZXRhZGF0YVJlc3BvbnNlIiyA6jABgtPkkwIiOgEqIh0vdjEvc2NoZW1hRGVzaWduOmRpZmZNZXRhZGF0YRJ4CgxBSUNvbXBsZXRpb24SIC5ieXRlYmFzZS52MS5BSUNvbXBsZXRpb25SZXF1ZXN0GiEuYnl0ZWJhc2UudjEuQUlDb21wbGV0aW9uUmVzcG9uc2UiI5DqMAKC0+STAhk6ASoiFC92MS9zcWwvYWlDb21wbGV0aW9uQqUBCg9jb20uYnl0ZWJhc2UudjFCD1NxbFNlcnZpY2VQcm90b1ABWjRnaXRodWIuY29tL2J5dGViYXNlL2J5dGViYXNlL2JhY2tlbmQvZ2VuZXJhdGVkLWdvL3YxogIDQlhYqgILQnl0ZWJhc2UuVjHKAgtCeXRlYmFzZVxWMeICF0J5dGViYXNlXFYxXEdQQk1ldGFkYXRh6gIMQnl0ZWJhc2U6OlYxYgZwcm90bzM", [file_google_api_annotations, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_duration, file_google_protobuf_struct, file_google_protobuf_timestamp, file_v1_annotation, file_v1_common, file_v1_database_service]);
+ fileDesc("ChR2MS9zcWxfc2VydmljZS5wcm90bxILYnl0ZWJhc2UudjEiqgEKE0FkbWluRXhlY3V0ZVJlcXVlc3QSKwoEbmFtZRgBIAEoCUId4EEC+kEXChVieXRlYmFzZS5jb20vRGF0YWJhc2USEQoJc3RhdGVtZW50GAIgASgJEg0KBWxpbWl0GAMgASgFEhMKBnNjaGVtYRgEIAEoCUgAiAEBEhYKCWNvbnRhaW5lchgFIAEoCUgBiAEBQgkKB19zY2hlbWFCDAoKX2NvbnRhaW5lciJBChRBZG1pbkV4ZWN1dGVSZXNwb25zZRIpCgdyZXN1bHRzGAEgAygLMhguYnl0ZWJhc2UudjEuUXVlcnlSZXN1bHQi/AEKDFF1ZXJ5UmVxdWVzdBIrCgRuYW1lGAEgASgJQh3gQQL6QRcKFWJ5dGViYXNlL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ViYXNlLnYxLkFJQ29tcGxldGlvblJlc3BvbnNlIiOQ6jACgtPkkwIZOgEqIhQvdjEvc3FsL2FpQ29tcGxldGlvbkKlAQoPY29tLmJ5dGViYXNlLnYxQg9TcWxTZXJ2aWNlUHJvdG9QAVo0Z2l0aHViLmNvbS9ieXRlYmFzZS9ieXRlYmFzZS9iYWNrZW5kL2dlbmVyYXRlZC1nby92MaICA0JYWKoCC0J5dGViYXNlLlYxygILQnl0ZWJhc2VcVjHiAhdCeXRlYmFzZVxWMVxHUEJNZXRhZGF0YeoCDEJ5dGViYXNlOjpWMWIGcHJvdG8z", [file_google_api_annotations, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_duration, file_google_protobuf_struct, file_google_protobuf_timestamp, file_v1_annotation, file_v1_common, file_v1_database_service]);
/**
* Describes the message bytebase.v1.AdminExecuteRequest.
diff --git a/frontend/src/utils/v1/worksheet.ts b/frontend/src/utils/v1/worksheet.ts
index 2c28e5085e..a5da2249c5 100644
--- a/frontend/src/utils/v1/worksheet.ts
+++ b/frontend/src/utils/v1/worksheet.ts
@@ -1,23 +1,15 @@
-import { head } from "lodash-es";
import {
useCurrentUserV1,
useDatabaseV1Store,
useProjectV1Store,
} from "@/store";
import { extractUserEmail } from "@/store/modules/v1/common";
-import {
- type SQLEditorConnection,
- UNKNOWN_ID,
- UNKNOWN_PROJECT_NAME,
-} from "@/types";
-import type { Database } from "@/types/proto-es/v1/database_service_pb";
-import { DataSourceType } from "@/types/proto-es/v1/instance_service_pb";
+import { UNKNOWN_ID, UNKNOWN_PROJECT_NAME } from "@/types";
import type { Worksheet } from "@/types/proto-es/v1/worksheet_service_pb";
import { Worksheet_Visibility } from "@/types/proto-es/v1/worksheet_service_pb";
import {
emptySQLEditorConnection,
extractDatabaseResourceName,
- getInstanceResource,
hasProjectPermissionV2,
hasWorkspacePermissionV2,
} from "@/utils";
@@ -91,28 +83,6 @@ export const isWorksheetWritableV1 = (sheet: Worksheet) => {
return false;
};
-export const setDefaultDataSourceForConn = (
- conn: SQLEditorConnection,
- database: Database
-) => {
- if (conn.dataSourceId) {
- return;
- }
-
- // Default connect to the first read-only data source if available.
- // Skip checking env/project policy for now.
- const instanceResource = getInstanceResource(database);
- const defaultDataSource =
- head(
- instanceResource.dataSources.filter(
- (d) => d.type === DataSourceType.READ_ONLY
- )
- ) || head(instanceResource.dataSources);
- if (defaultDataSource) {
- conn.dataSourceId = defaultDataSource.id;
- }
-};
-
export const extractWorksheetConnection = async (worksheet: {
database: string;
}) => {
@@ -125,7 +95,6 @@ export const extractWorksheetConnection = async (worksheet: {
const { instance } = extractDatabaseResourceName(database.name);
connection.instance = instance;
connection.database = database.name;
- setDefaultDataSourceForConn(connection, database);
} catch {
// Skip.
}
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/actions.tsx b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/actions.tsx
index b549fd4804..437eaf7ddc 100644
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/actions.tsx
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/actions.tsx
@@ -1,5 +1,5 @@
import { useClipboard } from "@vueuse/core";
-import { cloneDeep, head } from "lodash-es";
+import { cloneDeep } from "lodash-es";
import {
CodeIcon,
CopyIcon,
@@ -42,8 +42,6 @@ import {
type Database,
GetSchemaStringRequest_ObjectType,
} from "@/types/proto-es/v1/database_service_pb";
-import type { DataSource } from "@/types/proto-es/v1/instance_service_pb";
-import { DataSourceType } from "@/types/proto-es/v1/instance_service_pb";
import {
defaultSQLEditorTab,
extractDatabaseResourceName,
@@ -614,7 +612,6 @@ const runQuery = async (
database: database.name,
schema,
table: tableOrViewName,
- dataSourceId: getDefaultQueryableDataSourceOfDatabase(database).id,
};
await nextTick();
execute({
@@ -626,15 +623,6 @@ const runQuery = async (
});
};
-const getDefaultQueryableDataSourceOfDatabase = (database: Database) => {
- const dataSources = getInstanceResource(database).dataSources;
- const readonlyDataSources = dataSources.filter(
- (ds) => ds.type === DataSourceType.READ_ONLY
- );
- // First try to use readonly data source if available.
- return (head(readonlyDataSources) || head(dataSources)) as DataSource;
-};
-
const formatCode = async (code: string, engine: Engine) => {
const lang = languageOfEngineV1(engine);
if (lang !== "sql") {
diff --git a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/actions.tsx b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/actions.tsx
index 330c8c1c2d..414794d574 100644
--- a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/actions.tsx
+++ b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/actions.tsx
@@ -28,7 +28,6 @@ import {
getInstanceResource,
instanceV1HasAlterSchema,
instanceV1HasReadonlyMode,
- setDefaultDataSourceForConn,
} from "@/utils";
import { type SQLEditorContext, useSQLEditorContext } from "../../context";
@@ -192,10 +191,6 @@ export const setConnection = (options: {
: "",
database: database?.name ?? "",
};
- if (database) {
- setDefaultDataSourceForConn(connection, database);
- }
-
const tabStore = useSQLEditorTabStore();
const batchQueryContext: BatchQueryContext = Object.assign(
{ databases: [] },
diff --git a/frontend/src/views/sql-editor/EditorCommon/QueryContextSettingPopover.vue b/frontend/src/views/sql-editor/EditorCommon/QueryContextSettingPopover.vue
index 26a5a86e78..222288442b 100644
--- a/frontend/src/views/sql-editor/EditorCommon/QueryContextSettingPopover.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/QueryContextSettingPopover.vue
@@ -28,6 +28,9 @@
:value="selectedDataSourceId"
@update:value="onDataSourceSelected"
>
+ <NRadio class="w-full" value="">
+ {{ $t("data-source.automatic-query-data-source") }}
+ </NRadio>
<NTooltip
v-for="ds in dataSources"
:key="ds.id"
@@ -101,7 +104,7 @@ import { orderBy } from "lodash-es";
import { ChevronDown } from "lucide-vue-next";
import { NButton, NPopover, NRadio, NRadioGroup, NTooltip } from "naive-ui";
import { storeToRefs } from "pinia";
-import { computed, watch } from "vue";
+import { computed } from "vue";
import { useI18n } from "vue-i18n";
import MaxRowCountSelect from "@/components/RoleGrantPanel/MaxRowCountSelect.vue";
import {
@@ -109,7 +112,6 @@ import {
useSQLEditorStore,
useSQLEditorTabStore,
} from "@/store";
-import { isValidDatabaseName } from "@/types";
import { Engine } from "@/types/proto-es/v1/common_pb";
import type { DataSource } from "@/types/proto-es/v1/instance_service_pb";
import {
@@ -117,11 +119,7 @@ import {
DataSourceType,
} from "@/types/proto-es/v1/instance_service_pb";
import { QueryOption_RedisRunCommandsOn } from "@/types/proto-es/v1/sql_service_pb";
-import {
- getInstanceResource,
- getValidDataSourceByPolicy,
- readableDataSourceType,
-} from "@/utils";
+import { getInstanceResource, readableDataSourceType } from "@/utils";
defineProps<{
disabled?: boolean;
@@ -148,7 +146,7 @@ const showRedisConfig = computed(() => {
});
const selectedDataSourceId = computed(() => {
- return connection.value.dataSourceId;
+ return connection.value.dataSourceId ?? "";
});
const selectedDataSource = computed(() => {
@@ -183,25 +181,14 @@ const dataSourceUnaccessibleReason = (
};
const onDataSourceSelected = (dataSourceId?: string) => {
+ const nextConnection = { ...connection.value };
+ if (dataSourceId) {
+ nextConnection.dataSourceId = dataSourceId;
+ } else {
+ delete nextConnection.dataSourceId;
+ }
tabStore.updateCurrentTab({
- connection: {
- ...connection.value,
- dataSourceId: dataSourceId,
- },
+ connection: nextConnection,
});
};
-
-watch(
- [() => selectedDataSourceId.value, () => database.value],
- async ([current, database]) => {
- if (!isValidDatabaseName(database.name)) return;
- if (!current) {
- const fixed = await getValidDataSourceByPolicy(database);
- onDataSourceSelected(fixed);
- }
- },
- {
- immediate: true,
- }
-);
</script>
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue
index b87c3de9ae..8ae649fc68 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue
@@ -330,7 +330,9 @@ const handleExportBtnClick = async ({
const content = await useSQLStore().exportData(
create(ExportRequestSchema, {
name: props.database.name,
- dataSourceId: props.executeParams.connection.dataSourceId ?? "",
+ ...(props.executeParams.connection.dataSourceId
+ ? { dataSourceId: props.executeParams.connection.dataSourceId }
+ : {}),
format: options.format,
statement,
limit,
diff --git a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vue b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vue
index ede442f76e..17a488446c 100644
--- a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vue
@@ -289,7 +289,9 @@ const handleExportBtnClick = async ({
const content = await sqlStore.exportData(
create(ExportRequestSchema, {
name: databaseName,
- dataSourceId: context.params.connection.dataSourceId ?? "",
+ ...(context.params.connection.dataSourceId
+ ? { dataSourceId: context.params.connection.dataSourceId }
+ : {}),
format: options.format,
statement: context.params.statement,
limit: options.limit,
diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yaml
index 755300a25a..d4e7638fc6 100644
--- a/proto/gen/grpc-doc/openapi.yaml
+++ b/proto/gen/grpc-doc/openapi.yaml
@@ -5241,9 +5241,10 @@ paths:
title: data_source_id
description: |-
The id of data source.
- It is used for querying admin data source even if the instance has
- read-only data sources. Or it can be used to query a specific read-only
- data source.
+ If omitted, Export resolves the data source server-side by using the
+ single read-only data source when exactly one exists, or the admin data
+ source otherwise. It can also be set explicitly to export from the admin
+ data source or a specific read-only data source.
schema:
type:
- string
@@ -5304,9 +5305,10 @@ paths:
title: data_source_id
description: |-
The id of data source.
- It is used for querying admin data source even if the instance has
- read-only data sources. Or it can be used to query a specific read-only
- data source.
+ If omitted, Query resolves the data source server-side by using the single
+ read-only data source when exactly one exists, or the admin data source
+ otherwise. It can also be set explicitly to query the admin data source or
+ a specific read-only data source.
explain:
type: boolean
title: explain
@@ -5331,8 +5333,6 @@ paths:
Container is the container name to execute the query against, used for
CosmosDB only.
title: QueryRequest
- required:
- - dataSourceId
additionalProperties: false
required: true
responses:
@@ -9957,9 +9957,10 @@ paths:
title: data_source_id
description: |-
The id of data source.
- It is used for querying admin data source even if the instance has
- read-only data sources. Or it can be used to query a specific read-only
- data source.
+ If omitted, Export resolves the data source server-side by using the
+ single read-only data source when exactly one exists, or the admin data
+ source otherwise. It can also be set explicitly to export from the admin
+ data source or a specific read-only data source.
schema:
type:
- string
@@ -10034,9 +10035,10 @@ paths:
title: data_source_id
description: |-
The id of data source.
- It is used for querying admin data source even if the instance has
- read-only data sources. Or it can be used to query a specific read-only
- data source.
+ If omitted, Export resolves the data source server-side by using the
+ single read-only data source when exactly one exists, or the admin data
+ source otherwise. It can also be set explicitly to export from the admin
+ data source or a specific read-only data source.
schema:
type:
- string
@@ -20062,9 +20064,10 @@ components:
title: data_source_id
description: |-
The id of data source.
- It is used for querying admin data source even if the instance has
- read-only data sources. Or it can be used to query a specific read-only
- data source.
+ If omitted, Export resolves the data source server-side by using the
+ single read-only data source when exactly one exists, or the admin data
+ source otherwise. It can also be set explicitly to export from the admin
+ data source or a specific read-only data source.
schema:
type:
- string
@@ -24542,9 +24545,10 @@ components:
title: data_source_id
description: |-
The id of data source.
- It is used for querying admin data source even if the instance has
- read-only data sources. Or it can be used to query a specific read-only
- data source.
+ If omitted, Query resolves the data source server-side by using the single
+ read-only data source when exactly one exists, or the admin data source
+ otherwise. It can also be set explicitly to query the admin data source or
+ a specific read-only data source.
explain:
type: boolean
title: explain
@@ -24571,7 +24575,6 @@ components:
title: QueryRequest
required:
- name
- - dataSourceId
additionalProperties: false
bytebase.v1.QueryResponse:
type: object
diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.md
index 4b0c4a2832..c455d9a3e4 100644
--- a/proto/gen/grpc-doc/v1/README.md
+++ b/proto/gen/grpc-doc/v1/README.md
@@ -7328,7 +7328,7 @@ OrgPolicyService manages organizational policies at various resource levels.
| format | [ExportFormat](#bytebase-v1-ExportFormat) | | The export format. |
| admin | [bool](#bool) | | The admin is used for workspace owner and DBA for exporting data from SQL Editor Admin mode. The exported data is not masked. |
| password | [string](#string) | | The zip password provide by users. |
-| data_source_id | [string](#string) | | The id of data source. It is used for querying admin data source even if the instance has read-only data sources. Or it can be used to query a specific read-only data source. |
+| data_source_id | [string](#string) | | The id of data source. If omitted, Export resolves the data source server-side by using the single read-only data source when exactly one exists, or the admin data source otherwise. It can also be set explicitly to export from the admin data source or a specific read-only data source. |
| schema | [string](#string) | optional | The default schema to search objects. Equals to the current schema in Oracle and search path in Postgres. |
@@ -7421,7 +7421,7 @@ OrgPolicyService manages organizational policies at various resource levels.
| name | [string](#string) | | The name is the instance name to execute the query against. Format: instances/{instance}/databases/{databaseName} |
| statement | [string](#string) | | The SQL statement to execute. |
| limit | [int32](#int32) | | The maximum number of rows to return. |
-| data_source_id | [string](#string) | | The id of data source. It is used for querying admin data source even if the instance has read-only data sources. Or it can be used to query a specific read-only data source. |
+| data_source_id | [string](#string) | | The id of data source. If omitted, Query resolves the data source server-side by using the single read-only data source when exactly one exists, or the admin data source otherwise. It can also be set explicitly to query the admin data source or a specific read-only data source. |
| explain | [bool](#bool) | | Explain the statement. |
| schema | [string](#string) | optional | The default schema to search objects. Equals to the current schema in Oracle and search path in Postgres. |
| query_option | [QueryOption](#bytebase-v1-QueryOption) | | |
diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.html
index 4899d7f327..6753aeff9f 100644
--- a/proto/gen/grpc-doc/v1/index.html
+++ b/proto/gen/grpc-doc/v1/index.html
@@ -20865,9 +20865,10 @@ Editor Admin mode. The exported data is not masked. </p></td>
<td><a href="#string">string</a></td>
<td></td>
<td><p>The id of data source.
-It is used for querying admin data source even if the instance has
-read-only data sources. Or it can be used to query a specific read-only
-data source. </p></td>
+If omitted, Export resolves the data source server-side by using the
+single read-only data source when exactly one exists, or the admin data
+source otherwise. It can also be set explicitly to export from the admin
+data source or a specific read-only data source. </p></td>
</tr>
<tr>
@@ -21118,9 +21119,10 @@ Format: instances/{instance}/databases/{databaseName} </p></td>
<td><a href="#string">string</a></td>
<td></td>
<td><p>The id of data source.
-It is used for querying admin data source even if the instance has
-read-only data sources. Or it can be used to query a specific read-only
-data source. </p></td>
+If omitted, Query resolves the data source server-side by using the single
+read-only data source when exactly one exists, or the admin data source
+otherwise. It can also be set explicitly to query the admin data source or
+a specific read-only data source. </p></td>
</tr>
<tr>
diff --git a/proto/v1/v1/sql_service.proto b/proto/v1/v1/sql_service.proto
index e0d65ba6c6..dd791b8f41 100644
--- a/proto/v1/v1/sql_service.proto
+++ b/proto/v1/v1/sql_service.proto
@@ -134,10 +134,11 @@ message QueryRequest {
int32 limit = 3;
// The id of data source.
- // It is used for querying admin data source even if the instance has
- // read-only data sources. Or it can be used to query a specific read-only
- // data source.
- string data_source_id = 4 [(google.api.field_behavior) = REQUIRED];
+ // If omitted, Query resolves the data source server-side by using the single
+ // read-only data source when exactly one exists, or the admin data source
+ // otherwise. It can also be set explicitly to query the admin data source or
+ // a specific read-only data source.
+ string data_source_id = 4;
// Explain the statement.
bool explain = 5;
@@ -426,9 +427,10 @@ message ExportRequest {
string password = 6;
// The id of data source.
- // It is used for querying admin data source even if the instance has
- // read-only data sources. Or it can be used to query a specific read-only
- // data source.
+ // If omitted, Export resolves the data source server-side by using the
+ // single read-only data source when exactly one exists, or the admin data
+ // source otherwise. It can also be set explicitly to export from the admin
+ // data source or a specific read-only data source.
string data_source_id = 7;
// The default schema to search objects. Equals to the current schema in