Skip to content

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

feat(sql-editor): export to SharePoint and allow turning off download (#21640)

p0ny0859adf31b42
diff --git a/CONTEXT.md b/CONTEXT.md
index ad1c39182c..128450a3c7 100644
--- a/CONTEXT.md
+++ b/CONTEXT.md
@@ -4,6 +4,18 @@ Bytebase is a governed database development workspace. It turns proposed databas
## Language
+**Export Destination**:
+Where an export goes: Download to the caller's machine, or a configured storage location such as the Project Export Destination. Download is available unless the workspace query data policy disables it, and configuring a storage location approves exports to it; the Export Permission decides who may export, and an export access grant never adds a destination.
+_Avoid_: Export delivery, export target, download location
+
+**Project Export Destination**:
+The single configured storage location for a project's exports, which receives them directly from Bytebase. Its readers and retention are governed by the customer's storage administrators, independently of who initiates an export.
+_Avoid_: User export folder
+
+**Download**:
+The Export Destination that returns an exported file from Bytebase to the caller's machine. It is distinct from viewing query results in SQL Editor or opening a file already sent to a Project Export Destination.
+_Avoid_: Local export, local export download, query access
+
**Workspace**:
The top-level collaboration boundary that contains projects, database connections, environments, users, and policies.
_Avoid_: Project, organization
@@ -95,11 +107,3 @@ _Avoid_: Exporter role, export right, export approval
**Access Grant**:
An approved, time-limited permission for one user to run one specific query on its target databases. A grant that includes export satisfies the Export Permission for that query.
_Avoid_: JIT access, temporary role, export ticket
-
-**Export Destination**:
-A place exported query results may go. Local Export is the only destination today.
-_Avoid_: Export target, export format
-
-**Local Export**:
-An export whose results are returned to the requester as a file.
-_Avoid_: Download, data export
diff --git a/backend/api/v1/org_policy_service_converter.go b/backend/api/v1/org_policy_service_converter.go
index 3bd70a922a..18d9732b46 100644
--- a/backend/api/v1/org_policy_service_converter.go
+++ b/backend/api/v1/org_policy_service_converter.go
@@ -174,6 +174,7 @@ func convertToV1PBQueryDataPolicy(payloadStr string) (*v1pb.Policy_QueryDataPoli
MaximumResultRows: payload.MaximumResultRows,
DisableCopyData: payload.DisableCopyData,
AllowAdminDataSource: payload.AllowAdminDataSource,
+ DisableDownload: payload.DisableDownload,
},
}, nil
}
@@ -188,6 +189,7 @@ func convertToQueryDataPolicyPayload(policy *v1pb.QueryDataPolicy) (*storepb.Que
MaximumResultRows: policy.GetMaximumResultRows(),
DisableCopyData: policy.GetDisableCopyData(),
AllowAdminDataSource: policy.GetAllowAdminDataSource(),
+ DisableDownload: policy.GetDisableDownload(),
}, nil
}
diff --git a/backend/api/v1/org_policy_service_query_data_test.go b/backend/api/v1/org_policy_service_query_data_test.go
index 29505b58a8..9e37e7a0a2 100644
--- a/backend/api/v1/org_policy_service_query_data_test.go
+++ b/backend/api/v1/org_policy_service_query_data_test.go
@@ -6,6 +6,7 @@ import (
"connectrpc.com/connect"
"github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/encoding/protojson"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
@@ -60,3 +61,22 @@ func TestConvertToPolicyQueryDataIgnoresStoredDisableExport(t *testing.T) {
require.Equal(t, int32(10), queryData.GetMaximumResultRows())
require.True(t, queryData.GetDisableCopyData())
}
+
+func TestQueryDataPolicyDisableDownloadRoundTrip(t *testing.T) {
+ t.Parallel()
+ payload, err := convertToQueryDataPolicyPayload(&v1pb.QueryDataPolicy{DisableDownload: true})
+ require.NoError(t, err)
+ data, err := protojson.Marshal(payload)
+ require.NoError(t, err)
+ require.JSONEq(t, `{"disableDownload":true}`, string(data))
+
+ policy, err := convertToPolicy(&store.PolicyMessage{
+ Resource: "workspaces/example",
+ ResourceType: storepb.Policy_WORKSPACE,
+ Type: storepb.Policy_QUERY_DATA,
+ Payload: string(data),
+ Enforce: true,
+ })
+ require.NoError(t, err)
+ require.True(t, policy.GetQueryDataPolicy().GetDisableDownload())
+}
diff --git a/backend/api/v1/project_service.go b/backend/api/v1/project_service.go
index 6c192b6813..9f6bf20c10 100644
--- a/backend/api/v1/project_service.go
+++ b/backend/api/v1/project_service.go
@@ -24,11 +24,13 @@ import (
"github.com/bytebase/bytebase/backend/component/config"
"github.com/bytebase/bytebase/backend/component/iam"
"github.com/bytebase/bytebase/backend/component/sample"
+ "github.com/bytebase/bytebase/backend/enterprise"
"github.com/bytebase/bytebase/backend/utils"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/generated-go/v1/v1connect"
+ "github.com/bytebase/bytebase/backend/plugin/sharepoint"
webhookplugin "github.com/bytebase/bytebase/backend/plugin/webhook"
"github.com/bytebase/bytebase/backend/store"
)
@@ -36,10 +38,13 @@ import (
// ProjectService implements the project service.
type ProjectService struct {
v1connect.UnimplementedProjectServiceHandler
- store *store.Store
- profile *config.Profile
- iamManager *iam.Manager
- sampleManager sample.Manager
+ store *store.Store
+ profile *config.Profile
+ iamManager *iam.Manager
+ sampleManager sample.Manager
+ licenseService *enterprise.LicenseService
+ // newSharePointClient is sharepoint.NewClient when nil.
+ newSharePointClient func(sharepoint.Config) (sharepoint.Client, error)
}
// NewProjectService creates a new ProjectService.
@@ -48,12 +53,14 @@ func NewProjectService(
profile *config.Profile,
iamManager *iam.Manager,
sampleManager sample.Manager,
+ licenseService *enterprise.LicenseService,
) *ProjectService {
return &ProjectService{
- store: store,
- profile: profile,
- iamManager: iamManager,
- sampleManager: sampleManager,
+ store: store,
+ profile: profile,
+ iamManager: iamManager,
+ sampleManager: sampleManager,
+ licenseService: licenseService,
}
}
@@ -374,6 +381,20 @@ func (s *ProjectService) UpdateProject(ctx context.Context, req *connect.Request
}
projectSettings.Labels = req.Msg.Project.Labels
patch.Setting = projectSettings
+ case "export_setting":
+ rawURL := strings.TrimSpace(req.Msg.Project.GetExportSetting().GetSharepoint().GetUrl())
+ if rawURL == "" {
+ projectSettings.ExportSetting = nil
+ } else {
+ canonicalURL, err := s.resolveSharePointDestination(ctx, project.Workspace, rawURL)
+ if err != nil {
+ return nil, err
+ }
+ projectSettings.ExportSetting = &storepb.Project_ExportSetting{
+ Sharepoint: &storepb.Project_SharePointDestination{Url: canonicalURL},
+ }
+ }
+ patch.Setting = projectSettings
default:
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf(`unsupport update_mask "%s"`, path))
}
@@ -389,6 +410,53 @@ func (s *ProjectService) UpdateProject(ctx context.Context, req *connect.Request
return connect.NewResponse(convertToProject(project)), nil
}
+func (s *ProjectService) resolveSharePointDestination(ctx context.Context, workspaceID, rawURL string) (string, error) {
+ if err := s.licenseService.IsFeatureEnabled(ctx, workspaceID, v1pb.PlanFeature_FEATURE_SHAREPOINT_EXPORT); err != nil {
+ return "", connect.NewError(connect.CodePermissionDenied, err)
+ }
+ setting, err := s.store.GetExportSetting(ctx, workspaceID)
+ if err != nil {
+ return "", connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to get export setting"))
+ }
+ newClient := s.newSharePointClient
+ if newClient == nil {
+ newClient = sharepoint.NewClient
+ }
+ return resolveSharePointURL(ctx, rawURL, setting.GetSharepoint(), newClient)
+}
+
+// resolveSharePointURL normalizes rawURL and resolves it with the workspace's
+// SharePoint application, returning the canonical URL. Resolving proves only
+// that the destination is readable, not that exports can be written to it.
+func resolveSharePointURL(ctx context.Context, rawURL string, setting *storepb.SharePointSetting, newClient func(sharepoint.Config) (sharepoint.Client, error)) (string, error) {
+ canonicalURL, err := sharepoint.NormalizeURL(rawURL)
+ if err != nil {
+ return "", connect.NewError(connect.CodeInvalidArgument, err)
+ }
+ if setting.GetTenantId() == "" || setting.GetClientId() == "" || setting.GetClientSecret() == "" {
+ return "", connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("SharePoint is not configured for this workspace"))
+ }
+ client, err := newClient(sharepoint.Config{
+ TenantID: setting.GetTenantId(),
+ ClientID: setting.GetClientId(),
+ ClientSecret: setting.GetClientSecret(),
+ })
+ if err != nil {
+ return "", connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to create SharePoint client"))
+ }
+ if _, err := client.Resolve(ctx, canonicalURL); err != nil {
+ switch {
+ case errors.Is(err, sharepoint.ErrNotFoundOrNoAccess):
+ return "", connect.NewError(connect.CodeFailedPrecondition, sharepoint.ErrNotFoundOrNoAccess)
+ case errors.Is(err, sharepoint.ErrCredential):
+ return "", connect.NewError(connect.CodeFailedPrecondition, sharepoint.ErrCredential)
+ default:
+ return "", connect.NewError(connect.CodeUnavailable, errors.Wrap(err, "failed to resolve the SharePoint destination"))
+ }
+ }
+ return canonicalURL, nil
+}
+
// DeleteProject deletes a project.
func (s *ProjectService) DeleteProject(ctx context.Context, req *connect.Request[v1pb.DeleteProjectRequest]) (*connect.Response[emptypb.Empty], error) {
project, err := s.getProjectMessage(ctx, req.Msg.Name)
diff --git a/backend/api/v1/project_service_converter.go b/backend/api/v1/project_service_converter.go
index 8e5f96bf32..7ab13d0c59 100644
--- a/backend/api/v1/project_service_converter.go
+++ b/backend/api/v1/project_service_converter.go
@@ -303,6 +303,17 @@ func convertToProject(projectMessage *store.ProjectMessage) *v1pb.Project {
AllowRequestRole: projectMessage.Setting.AllowRequestRole,
AllowJustInTimeAccess: projectMessage.Setting.AllowJustInTimeAccess,
AllowLastPlanEditorApproval: projectMessage.Setting.AllowLastPlanEditorApproval,
+ ExportSetting: convertToV1ProjectExportSetting(projectMessage.Setting.GetExportSetting()),
+ }
+}
+
+func convertToV1ProjectExportSetting(setting *storepb.Project_ExportSetting) *v1pb.Project_ExportSetting {
+ url := setting.GetSharepoint().GetUrl()
+ if url == "" {
+ return nil
+ }
+ return &v1pb.Project_ExportSetting{
+ Sharepoint: &v1pb.SharePointDestination{Url: url},
}
}
diff --git a/backend/api/v1/project_service_export_setting_test.go b/backend/api/v1/project_service_export_setting_test.go
new file mode 100644
index 0000000000..4a4ca45177
--- /dev/null
+++ b/backend/api/v1/project_service_export_setting_test.go
@@ -0,0 +1,178 @@
+package v1
+
+import (
+ "context"
+ "testing"
+
+ "connectrpc.com/connect"
+ "github.com/pkg/errors"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/types/known/fieldmaskpb"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/enterprise"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+ "github.com/bytebase/bytebase/backend/plugin/sharepoint"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+type fakeSharePointResolver struct {
+ location *sharepoint.Location
+ err error
+ resolved []string
+}
+
+func (c *fakeSharePointResolver) Resolve(_ context.Context, canonicalURL string) (*sharepoint.Location, error) {
+ c.resolved = append(c.resolved, canonicalURL)
+ return c.location, c.err
+}
+
+func (*fakeSharePointResolver) Upload(context.Context, *sharepoint.Location, string, []sharepoint.File) (*sharepoint.Folder, error) {
+ return nil, errors.New("not used")
+}
+
+func TestResolveSharePointURL(t *testing.T) {
+ t.Parallel()
+ const folderURL = "https://contoso.sharepoint.com/sites/Finance/Shared%20Documents/Exports"
+ configured := &storepb.SharePointSetting{TenantId: "tenant", ClientId: "client", ClientSecret: "secret"}
+ newClient := func(client *fakeSharePointResolver) func(sharepoint.Config) (sharepoint.Client, error) {
+ return func(cfg sharepoint.Config) (sharepoint.Client, error) {
+ require.Equal(t, sharepoint.Config{TenantID: "tenant", ClientID: "client", ClientSecret: "secret"}, cfg)
+ return client, nil
+ }
+ }
+
+ t.Run("a URL that does not normalize is invalid", func(t *testing.T) {
+ t.Parallel()
+ client := &fakeSharePointResolver{}
+ _, err := resolveSharePointURL(context.Background(), "not a url", configured, newClient(client))
+ require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err))
+ require.Empty(t, client.resolved)
+ })
+
+ t.Run("missing credentials cannot resolve", func(t *testing.T) {
+ t.Parallel()
+ for _, setting := range []*storepb.SharePointSetting{nil, {TenantId: "tenant", ClientId: "client"}} {
+ client := &fakeSharePointResolver{}
+ _, err := resolveSharePointURL(context.Background(), folderURL, setting, newClient(client))
+ require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err))
+ require.Empty(t, client.resolved)
+ }
+ })
+
+ t.Run("an unresolvable destination reports both possibilities", func(t *testing.T) {
+ t.Parallel()
+ client := &fakeSharePointResolver{err: errors.Wrap(sharepoint.ErrNotFoundOrNoAccess, "403 accessDenied")}
+ _, err := resolveSharePointURL(context.Background(), folderURL, configured, newClient(client))
+ require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err))
+ require.Contains(t, err.Error(), "the SharePoint destination does not exist or Bytebase cannot access it")
+ })
+
+ t.Run("rejected credentials are reported", func(t *testing.T) {
+ t.Parallel()
+ client := &fakeSharePointResolver{err: errors.Wrap(sharepoint.ErrCredential, "AADSTS7000215")}
+ _, err := resolveSharePointURL(context.Background(), folderURL, configured, newClient(client))
+ require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err))
+ require.Contains(t, err.Error(), sharepoint.ErrCredential.Error())
+ })
+
+ t.Run("a resolved destination returns the canonical URL", func(t *testing.T) {
+ t.Parallel()
+ canonicalURL, err := sharepoint.NormalizeURL(folderURL)
+ require.NoError(t, err)
+ client := &fakeSharePointResolver{location: &sharepoint.Location{DriveID: "drive", ItemID: "item", WebURL: folderURL}}
+ got, err := resolveSharePointURL(context.Background(), folderURL, configured, newClient(client))
+ require.NoError(t, err)
+ require.Equal(t, canonicalURL, got)
+ require.Equal(t, []string{canonicalURL}, client.resolved)
+ })
+}
+
+func TestConvertToV1ProjectExportSetting(t *testing.T) {
+ t.Parallel()
+ require.Nil(t, convertToV1ProjectExportSetting(nil))
+ require.Nil(t, convertToV1ProjectExportSetting(&storepb.Project_ExportSetting{}), "a cleared setting is absent")
+ require.Nil(t, convertToV1ProjectExportSetting(&storepb.Project_ExportSetting{Sharepoint: &storepb.Project_SharePointDestination{}}))
+ require.True(t, proto.Equal(&v1pb.Project_ExportSetting{
+ Sharepoint: &v1pb.SharePointDestination{Url: "https://contoso.sharepoint.com/sites/Finance/Shared%20Documents"},
+ }, convertToV1ProjectExportSetting(&storepb.Project_ExportSetting{
+ Sharepoint: &storepb.Project_SharePointDestination{Url: "https://contoso.sharepoint.com/sites/Finance/Shared%20Documents"},
+ })))
+}
+
+func TestUpdateProjectExportSetting(t *testing.T) {
+ t.Parallel()
+ const rawURL = "https://contoso.sharepoint.com/sites/Finance/Shared%20Documents/Forms/AllItems.aspx?id=%2Fsites%2FFinance%2FShared%20Documents%2FExports"
+ canonicalURL, err := sharepoint.NormalizeURL(rawURL)
+ require.NoError(t, err)
+ require.NotEqual(t, rawURL, canonicalURL)
+
+ ctx, stores, projectID, _, _ := setupProjectInstanceLifecycleAPITest(t)
+ client := &fakeSharePointResolver{location: &sharepoint.Location{DriveID: "drive", ItemID: "item"}}
+ newService := func(licenseService *enterprise.LicenseService) *ProjectService {
+ return &ProjectService{store: stores, licenseService: licenseService, newSharePointClient: func(sharepoint.Config) (sharepoint.Client, error) { return client, nil }}
+ }
+ update := func(service *ProjectService, exportSetting *v1pb.Project_ExportSetting) (*v1pb.Project, error) {
+ resp, err := service.UpdateProject(ctx, connect.NewRequest(&v1pb.UpdateProjectRequest{
+ Project: &v1pb.Project{Name: common.FormatProject(projectID), ExportSetting: exportSetting},
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"export_setting"}},
+ }))
+ if err != nil {
+ return nil, err
+ }
+ return resp.Msg, nil
+ }
+ withURL := func(url string) *v1pb.Project_ExportSetting {
+ return &v1pb.Project_ExportSetting{Sharepoint: &v1pb.SharePointDestination{Url: url}}
+ }
+ storedSetting := func() *storepb.Project_ExportSetting {
+ project, err := stores.GetProject(ctx, &store.FindProjectMessage{Workspace: "default", ResourceID: &projectID})
+ require.NoError(t, err)
+ return project.Setting.GetExportSetting()
+ }
+
+ licensed := newService(newEnterpriseLicenseService(ctx, t, stores, "default"))
+ _, err = update(licensed, withURL(rawURL))
+ require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err), "the workspace has no SharePoint credentials")
+ require.Empty(t, client.resolved)
+ _, err = stores.UpsertSetting(ctx, &store.SettingMessage{
+ Name: storepb.SettingName_EXPORT,
+ Workspace: "default",
+ Value: &storepb.ExportSetting{Sharepoint: &storepb.SharePointSetting{TenantId: "tenant", ClientId: "client", ClientSecret: "secret"}},
+ })
+ require.NoError(t, err)
+
+ _, err = update(licensed, withURL("not a url"))
+ require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err))
+
+ updated, err := update(licensed, withURL(rawURL))
+ require.NoError(t, err)
+ require.True(t, proto.Equal(withURL(canonicalURL), updated.ExportSetting))
+ require.Equal(t, []string{canonicalURL}, client.resolved)
+ require.True(t, proto.Equal(&storepb.Project_ExportSetting{
+ Sharepoint: &storepb.Project_SharePointDestination{Url: canonicalURL},
+ }, storedSetting()), "only the canonical URL is stored")
+
+ client.err = sharepoint.ErrNotFoundOrNoAccess
+ _, err = update(licensed, withURL("https://contoso.sharepoint.com/sites/Finance/Shared%20Documents/Gone"))
+ require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err))
+ client.err = nil
+
+ freeLicenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, stores, false, "")
+ require.NoError(t, err)
+ unlicensed := newService(freeLicenseService)
+ _, err = update(unlicensed, withURL(rawURL))
+ require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err), "setting a destination needs the license")
+ require.True(t, proto.Equal(&storepb.Project_ExportSetting{
+ Sharepoint: &storepb.Project_SharePointDestination{Url: canonicalURL},
+ }, storedSetting()))
+
+ for _, cleared := range []*v1pb.Project_ExportSetting{withURL(""), nil} {
+ updated, err = update(unlicensed, cleared)
+ require.NoError(t, err, "clearing does not need the license")
+ require.Nil(t, updated.ExportSetting)
+ require.Nil(t, storedSetting())
+ }
+}
diff --git a/backend/api/v1/project_service_test.go b/backend/api/v1/project_service_test.go
index c9eba527c5..2c1fbb96f6 100644
--- a/backend/api/v1/project_service_test.go
+++ b/backend/api/v1/project_service_test.go
@@ -607,7 +607,7 @@ func TestProjectPurgeCleansSampleBeforeDeletingMetadata(t *testing.T) {
}
return nil
}
- projectService := NewProjectService(stores, nil, nil, manager)
+ projectService := NewProjectService(stores, nil, nil, manager, nil)
projectName := common.FormatProject(projectID)
_, err := projectService.DeleteProject(ctx, connect.NewRequest(&v1pb.DeleteProjectRequest{Name: projectName}))
@@ -671,7 +671,7 @@ func TestProjectPurgeRemovesSelfHostSample(t *testing.T) {
nil,
sample.ManagerOptions{ReplicaID: replicaID},
)
- projectService := NewProjectService(stores, nil, nil, manager)
+ projectService := NewProjectService(stores, nil, nil, manager, nil)
projectName := common.FormatProject(projectID)
_, err = projectService.DeleteProject(ctx, connect.NewRequest(&v1pb.DeleteProjectRequest{Name: projectName}))
diff --git a/backend/api/v1/setting_service.go b/backend/api/v1/setting_service.go
index 175c3a8d79..4b1970616d 100644
--- a/backend/api/v1/setting_service.go
+++ b/backend/api/v1/setting_service.go
@@ -318,6 +318,8 @@ func (s *SettingService) UpdateSetting(ctx context.Context, request *connect.Req
storeSettingValue = storeSemanticTypeSetting
case storepb.SettingName_AI:
return s.updateAISetting(ctx, request, workspaceID)
+ case storepb.SettingName_EXPORT:
+ return s.updateExportSetting(ctx, request, workspaceID)
case storepb.SettingName_ENVIRONMENT:
if serr := s.validateEnvironments(ctx, workspaceID, request.Msg.Setting.Value.GetEnvironment().GetEnvironments()); serr != nil {
return nil, serr
@@ -574,6 +576,129 @@ func mergeAISetting(stored, payload *storepb.AISetting, paths []string) (*storep
return merged, nil
}
+// updateExportSetting merges the update mask onto the locked EXPORT setting
+// row, as updateAISetting does. Workspace creation does not seed this row, so a
+// missing row starts empty.
+func (s *SettingService) updateExportSetting(ctx context.Context, request *connect.Request[v1pb.UpdateSettingRequest], workspaceID string) (*connect.Response[v1pb.Setting], error) {
+ if s.profile.SaaS {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("SharePoint export is not available in Bytebase Cloud"))
+ }
+ if err := s.licenseService.IsFeatureEnabled(ctx, workspaceID, v1pb.PlanFeature_FEATURE_SHAREPOINT_EXPORT); err != nil {
+ return nil, connect.NewError(connect.CodePermissionDenied, err)
+ }
+ if request.Msg.UpdateMask == nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("update mask is required"))
+ }
+ payload := convertExportSetting(request.Msg.Setting.Value.GetExport())
+ paths := request.Msg.UpdateMask.Paths
+
+ if request.Msg.ValidateOnly {
+ stored := &storepb.ExportSetting{}
+ existing, err := s.store.GetSettingUncached(ctx, workspaceID, storepb.SettingName_EXPORT)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to find export setting: %v", err))
+ }
+ if existing != nil {
+ value, ok := existing.Value.(*storepb.ExportSetting)
+ if !ok {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("invalid setting value type for %s", storepb.SettingName_EXPORT))
+ }
+ stored = value
+ }
+ merged, err := mergeExportSetting(stored, payload, paths)
+ if err != nil {
+ return nil, err
+ }
+ settingMessage, err := convertToSettingMessage(&store.SettingMessage{
+ Name: storepb.SettingName_EXPORT,
+ Workspace: workspaceID,
+ Value: merged,
+ })
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to convert setting message: %v", err))
+ }
+ return connect.NewResponse(settingMessage), nil
+ }
+
+ var lockedBefore *storepb.ExportSetting
+ setting, err := s.store.UpsertSettingAtomic(ctx, workspaceID, storepb.SettingName_EXPORT, func(current proto.Message, existed bool) (proto.Message, error) {
+ stored, ok := current.(*storepb.ExportSetting)
+ if !ok {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("invalid setting value type for %s", storepb.SettingName_EXPORT))
+ }
+ if existed {
+ lockedBefore = stored
+ }
+ return mergeExportSetting(stored, payload, paths)
+ }, nil)
+
+ // The audit before-image is the locked row the merge ran against; a save
+ // that fails validation is audited too.
+ if setServiceData, ok := getSetServiceDataFromContext(ctx); ok && lockedBefore != nil {
+ v1pbSetting, err := convertToSettingMessage(&store.SettingMessage{
+ Name: storepb.SettingName_EXPORT,
+ Workspace: workspaceID,
+ Value: lockedBefore,
+ })
+ if err != nil {
+ slog.Warn("audit: failed to convert to v1.Setting", log.BBError(err))
+ }
+ p, err := anypb.New(v1pbSetting)
+ if err != nil {
+ slog.Warn("audit: failed to convert to anypb.Any", log.BBError(err))
+ }
+ setServiceData(p)
+ }
+ if err != nil {
+ var connectErr *connect.Error
+ if errors.As(err, &connectErr) {
+ return nil, err
+ }
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to set setting: %v", err))
+ }
+
+ settingMessage, err := convertToSettingMessage(setting)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to convert setting message: %v", err))
+ }
+ return connect.NewResponse(settingMessage), nil
+}
+
+// mergeExportSetting applies the update mask to a copy of stored and validates
+// the result. An empty client secret keeps the stored one, because the secret
+// is never returned for a client to send back. Clearing both SharePoint IDs
+// removes the application, secret included.
+func mergeExportSetting(stored, payload *storepb.ExportSetting, paths []string) (*storepb.ExportSetting, error) {
+ merged := proto.CloneOf(stored)
+ sharePoint := proto.CloneOf(stored.GetSharepoint())
+ if sharePoint == nil {
+ sharePoint = &storepb.SharePointSetting{}
+ }
+ for _, path := range paths {
+ switch path {
+ case "value.export.sharepoint.tenant_id":
+ sharePoint.TenantId = strings.TrimSpace(payload.GetSharepoint().GetTenantId())
+ case "value.export.sharepoint.client_id":
+ sharePoint.ClientId = strings.TrimSpace(payload.GetSharepoint().GetClientId())
+ case "value.export.sharepoint.client_secret":
+ if secret := payload.GetSharepoint().GetClientSecret(); secret != "" {
+ sharePoint.ClientSecret = secret
+ }
+ default:
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("invalid update mask path %v", path))
+ }
+ }
+ if sharePoint.TenantId == "" && sharePoint.ClientId == "" {
+ merged.Sharepoint = nil
+ return merged, nil
+ }
+ if sharePoint.TenantId == "" || sharePoint.ClientId == "" || sharePoint.ClientSecret == "" {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("tenant ID, client ID, and client secret are all required"))
+ }
+ merged.Sharepoint = sharePoint
+ return merged, nil
+}
+
// appIMSettingMaskPath maps each accepted APP_IM mask path to the provider it
// addresses. The paths do not name real proto fields — AppIMSetting holds one
// repeated `settings`, and AIP-161 does not let a mask address a repeated
diff --git a/backend/api/v1/setting_service_converter.go b/backend/api/v1/setting_service_converter.go
index 88d2ce56e9..20b18774ef 100644
--- a/backend/api/v1/setting_service_converter.go
+++ b/backend/api/v1/setting_service_converter.go
@@ -147,6 +147,19 @@ func convertToSettingMessage(setting *store.SettingMessage) (*v1pb.Setting, erro
},
},
}, nil
+ case storepb.SettingName_EXPORT:
+ storeValue, ok := setting.Value.(*storepb.ExportSetting)
+ if !ok {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("invalid setting value type for %s", setting.Name))
+ }
+ return &v1pb.Setting{
+ Name: settingName,
+ Value: &v1pb.SettingValue{
+ Value: &v1pb.SettingValue_Export{
+ Export: convertToExportSetting(storeValue),
+ },
+ },
+ }, nil
default:
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("unsupported setting %v", setting.Name))
}
@@ -190,10 +203,10 @@ func convertStoreSettingNameToV1(storeName storepb.SettingName) v1pb.Setting_Set
return v1pb.Setting_EMAIL
case storepb.SettingName_MCP:
return v1pb.Setting_MCP
+ case storepb.SettingName_EXPORT:
+ return v1pb.Setting_EXPORT
case storepb.SettingName_SYSTEM:
// Backend-only setting, not exposed in v1 API
- case storepb.SettingName_EXPORT:
- // Not served until its value conversion exists.
default:
}
return v1pb.Setting_SETTING_NAME_UNSPECIFIED
@@ -224,8 +237,7 @@ func convertV1SettingNameToStore(v1Name v1pb.Setting_SettingName) storepb.Settin
case v1pb.Setting_MCP:
return storepb.SettingName_MCP
case v1pb.Setting_EXPORT:
- // Not served until its value conversion exists.
- return storepb.SettingName_SETTING_NAME_UNSPECIFIED
+ return storepb.SettingName_EXPORT
default:
return storepb.SettingName_SETTING_NAME_UNSPECIFIED
}
@@ -874,6 +886,36 @@ func convertToAISetting(storeSetting *storepb.AISetting) *v1pb.AISetting {
}
}
+func convertExportSetting(v1Setting *v1pb.ExportSetting) *storepb.ExportSetting {
+ return &storepb.ExportSetting{Sharepoint: convertSharePointSetting(v1Setting.GetSharepoint())}
+}
+
+func convertToExportSetting(storeSetting *storepb.ExportSetting) *v1pb.ExportSetting {
+ return &v1pb.ExportSetting{Sharepoint: convertToSharePointSetting(storeSetting.GetSharepoint())}
+}
+
+func convertSharePointSetting(v1Setting *v1pb.SharePointSetting) *storepb.SharePointSetting {
+ if v1Setting == nil {
+ return nil
+ }
+ return &storepb.SharePointSetting{
+ TenantId: v1Setting.GetTenantId(),
+ ClientId: v1Setting.GetClientId(),
+ ClientSecret: v1Setting.GetClientSecret(),
+ }
+}
+
+func convertToSharePointSetting(storeSetting *storepb.SharePointSetting) *v1pb.SharePointSetting {
+ if storeSetting == nil {
+ return nil
+ }
+ return &v1pb.SharePointSetting{
+ TenantId: storeSetting.GetTenantId(),
+ ClientId: storeSetting.GetClientId(),
+ ClientSecretSet: storeSetting.GetClientSecret() != "",
+ }
+}
+
func convertEmailSetting(v1Setting *v1pb.EmailSetting) *storepb.EmailSetting {
if v1Setting == nil {
return nil
diff --git a/backend/api/v1/setting_service_converter_test.go b/backend/api/v1/setting_service_converter_test.go
index 30ebaaa5e7..f1610acb5c 100644
--- a/backend/api/v1/setting_service_converter_test.go
+++ b/backend/api/v1/setting_service_converter_test.go
@@ -4,9 +4,11 @@ import (
"testing"
"github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/proto"
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 TestConvertAISetting(t *testing.T) {
@@ -38,3 +40,33 @@ func TestConvertAISetting(t *testing.T) {
require.False(t, convertToAISetting(&storepb.AISetting{Enabled: true}).SqlReviewEnabled, "the review is off until it is switched on")
}
+
+func TestConvertExportSettingNeverReturnsSecret(t *testing.T) {
+ t.Parallel()
+
+ stored := convertExportSetting(&v1pb.ExportSetting{Sharepoint: &v1pb.SharePointSetting{
+ TenantId: "tenant",
+ ClientId: "client",
+ ClientSecret: "secret",
+ ClientSecretSet: false,
+ }})
+ require.True(t, proto.Equal(&storepb.ExportSetting{Sharepoint: &storepb.SharePointSetting{TenantId: "tenant", ClientId: "client", ClientSecret: "secret"}}, stored))
+
+ setting, err := convertToSettingMessage(&store.SettingMessage{Name: storepb.SettingName_EXPORT, Value: stored})
+ require.NoError(t, err)
+ require.Equal(t, "settings/EXPORT", setting.Name)
+ require.True(t, proto.Equal(&v1pb.ExportSetting{Sharepoint: &v1pb.SharePointSetting{TenantId: "tenant", ClientId: "client", ClientSecretSet: true}}, setting.Value.GetExport()))
+
+ require.False(t, convertToSharePointSetting(&storepb.SharePointSetting{TenantId: "tenant"}).ClientSecretSet)
+ require.Nil(t, convertExportSetting(nil).Sharepoint)
+ require.Nil(t, convertToExportSetting(&storepb.ExportSetting{}).Sharepoint, "unset when SharePoint is not configured")
+}
+
+func TestSettingNameMappingRoundTrips(t *testing.T) {
+ t.Parallel()
+
+ for value, name := range v1pb.Setting_SettingName_name {
+ v1Name := v1pb.Setting_SettingName(value)
+ require.Equal(t, v1Name, convertStoreSettingNameToV1(convertV1SettingNameToStore(v1Name)), name)
+ }
+}
diff --git a/backend/api/v1/setting_service_test.go b/backend/api/v1/setting_service_test.go
index 3964e7e74d..41c18ac197 100644
--- a/backend/api/v1/setting_service_test.go
+++ b/backend/api/v1/setting_service_test.go
@@ -390,6 +390,75 @@ func TestMergeAISetting(t *testing.T) {
})
}
+func TestMergeExportSetting(t *testing.T) {
+ t.Parallel()
+ stored := func() *storepb.ExportSetting {
+ return &storepb.ExportSetting{Sharepoint: &storepb.SharePointSetting{TenantId: "tenant", ClientId: "client", ClientSecret: "stored-secret"}}
+ }
+ sharePoint := func(tenantID, clientID, clientSecret string) *storepb.ExportSetting {
+ return &storepb.ExportSetting{Sharepoint: &storepb.SharePointSetting{TenantId: tenantID, ClientId: clientID, ClientSecret: clientSecret}}
+ }
+ allPaths := []string{"value.export.sharepoint.tenant_id", "value.export.sharepoint.client_id", "value.export.sharepoint.client_secret"}
+
+ t.Run("an empty secret keeps the stored one", func(t *testing.T) {
+ t.Parallel()
+ before := stored()
+ merged, err := mergeExportSetting(before, sharePoint("new-tenant", "client", ""), allPaths)
+ require.NoError(t, err)
+ require.Equal(t, "new-tenant", merged.Sharepoint.TenantId)
+ require.Equal(t, "stored-secret", merged.Sharepoint.ClientSecret)
+ require.Equal(t, "tenant", before.Sharepoint.TenantId)
+ })
+
+ t.Run("a new secret replaces the stored one", func(t *testing.T) {
+ t.Parallel()
+ merged, err := mergeExportSetting(stored(), sharePoint("", "", "rotated"), []string{"value.export.sharepoint.client_secret"})
+ require.NoError(t, err)
+ require.Equal(t, "rotated", merged.Sharepoint.ClientSecret)
+ require.Equal(t, "client", merged.Sharepoint.ClientId)
+ })
+
+ t.Run("a first save needs every field", func(t *testing.T) {
+ t.Parallel()
+ _, err := mergeExportSetting(&storepb.ExportSetting{}, sharePoint("tenant", "client", ""), allPaths)
+ require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err))
+ merged, err := mergeExportSetting(&storepb.ExportSetting{}, sharePoint(" tenant ", "client", "secret"), allPaths)
+ require.NoError(t, err)
+ require.Equal(t, "tenant", merged.Sharepoint.TenantId)
+ })
+
+ t.Run("clearing one ID is refused", func(t *testing.T) {
+ t.Parallel()
+ _, err := mergeExportSetting(stored(), &storepb.ExportSetting{}, []string{"value.export.sharepoint.client_id"})
+ require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err))
+ })
+
+ t.Run("clearing both IDs removes SharePoint, secret included", func(t *testing.T) {
+ t.Parallel()
+ merged, err := mergeExportSetting(stored(), &storepb.ExportSetting{}, allPaths)
+ require.NoError(t, err)
+ require.Nil(t, merged.Sharepoint)
+ })
+
+ t.Run("unknown and pre-EXPORT paths are refused", func(t *testing.T) {
+ t.Parallel()
+ for _, path := range []string{"value.export.sharepoint.client_secret_set", "value.sharepoint.tenant_id", "value.export.sharepoint"} {
+ _, err := mergeExportSetting(stored(), &storepb.ExportSetting{}, []string{path})
+ require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err), path)
+ }
+ })
+}
+
+func TestUpdateExportSettingRejectedInSaaS(t *testing.T) {
+ t.Parallel()
+ saas := &SettingService{profile: &config.Profile{SaaS: true}}
+ _, err := saas.updateExportSetting(context.Background(), connect.NewRequest(&v1pb.UpdateSettingRequest{
+ Setting: &v1pb.Setting{Value: &v1pb.SettingValue{Value: &v1pb.SettingValue_Export{Export: &v1pb.ExportSetting{Sharepoint: &v1pb.SharePointSetting{}}}}},
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"value.export.sharepoint.tenant_id"}},
+ }), "ws")
+ require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err))
+}
+
func TestCanUpdateAISettingInSaaS(t *testing.T) {
t.Parallel()
diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.go
index 7391caedd1..95a239ec00 100644
--- a/backend/api/v1/sql_service.go
+++ b/backend/api/v1/sql_service.go
@@ -1,7 +1,6 @@
package v1
import (
- "bytes"
"context"
"database/sql"
"fmt"
@@ -15,7 +14,6 @@ import (
"log/slog"
"connectrpc.com/connect"
- "github.com/alexmullins/zip"
"github.com/pkg/errors"
"google.golang.org/protobuf/types/known/durationpb"
@@ -33,6 +31,7 @@ import (
"github.com/bytebase/bytebase/backend/plugin/advisor/code"
"github.com/bytebase/bytebase/backend/plugin/db"
parserbase "github.com/bytebase/bytebase/backend/plugin/parser/base"
+ "github.com/bytebase/bytebase/backend/plugin/sharepoint"
"github.com/bytebase/bytebase/backend/runner/schemasync"
"github.com/bytebase/bytebase/backend/store"
"github.com/bytebase/bytebase/backend/store/model"
@@ -50,6 +49,8 @@ type SQLService struct {
// queryHistoryService backs the deprecated query history aliases until
// they are removed.
queryHistoryService *QueryHistoryService
+ // newSharePointClient defaults to sharepoint.NewClient when nil.
+ newSharePointClient func(sharepoint.Config) (sharepoint.Client, error)
}
// NewSQLService creates a SQLService.
@@ -1222,6 +1223,7 @@ func executeWithTimeout(
// Export exports the SQL query result.
func (s *SQLService) Export(ctx context.Context, req *connect.Request[v1pb.ExportRequest]) (*connect.Response[v1pb.ExportResponse], error) {
request := req.Msg
+ exportTime := time.Now()
// Prepare related message.
user, instance, database, err := s.prepareRelatedMessage(ctx, request.Name)
if err != nil {
@@ -1263,6 +1265,11 @@ func (s *SQLService) Export(ctx context.Context, req *connect.Request[v1pb.Expor
return nil, err
}
+ sharePointTarget, err := s.prepareExportDestination(ctx, request, database)
+ if err != nil {
+ return nil, err
+ }
+
// The JIT grant satisfies bb.sql.export only on its target databases, so
// span-level ACL still runs for every other database.
optionalAccessCheck := s.accessCheckWithGrant(accessGrant, true /* export */)
@@ -1270,7 +1277,11 @@ func (s *SQLService) Export(ctx context.Context, req *connect.Request[v1pb.Expor
if accessGrant != nil {
skipMasking = accessGrant.Payload.Unmask
}
- bytes, duration, exportErr := doExport(ctx, s.store, s.dbFactory, s.licenseService, request, user, instance, database, optionalAccessCheck, s.schemaSyncer, dataSource, skipMasking)
+ files, duration, exportErr := doExport(ctx, s.store, s.dbFactory, s.licenseService, request, user, instance, database, optionalAccessCheck, s.schemaSyncer, dataSource, skipMasking)
+ var exportResponse *v1pb.ExportResponse
+ if exportErr == nil {
+ exportResponse, exportErr = sendExport(ctx, sharePointTarget, user, database, files, request, exportTime)
+ }
s.createQueryHistory(instance, database, store.QueryHistoryTypeExport, statement, user.Email, duration, exportErr)
@@ -1278,9 +1289,6 @@ func (s *SQLService) Export(ctx context.Context, req *connect.Request[v1pb.Expor
return nil, exportConnectError(exportErr)
}
- exportResponse := &v1pb.ExportResponse{
- Content: bytes,
- }
if accessGrant != nil {
exportResponse.AppliedAccessGrant = common.FormatAccessGrant(accessGrant.ProjectID, accessGrant.ID)
}
@@ -1304,7 +1312,8 @@ func exportConnectError(err error) *connect.Error {
return connect.NewError(connect.CodeInternal, err)
}
-// doExport performs SQL Editor exports with masking applied.
+// doExport runs an SQL Editor export with masking applied and returns its
+// statement and result files.
func doExport(
ctx context.Context,
stores *store.Store,
@@ -1318,7 +1327,7 @@ func doExport(
schemaSyncer *schemasync.Syncer,
dataSource *storepb.DataSource,
skipMasking bool,
-) ([]byte, time.Duration, error) {
+) ([]sharepoint.File, time.Duration, error) {
if dataSource == nil {
return nil, 0, connect.NewError(connect.CodeNotFound, errors.Errorf("cannot found valid data source"))
}
@@ -1385,82 +1394,23 @@ func doExport(
}
}
- var buf bytes.Buffer
- zipw := zip.NewWriter(&buf)
-
- exportCount := 0
- for i, result := range results {
- if result.GetError() != "" {
- return nil, duration, errors.Errorf("failed to exec the SQL with error: %v", result.GetError())
- }
-
- if err := exportResultToZip(ctx, zipw, stores, instance, database, result, request, i+1); err != nil {
- return nil, duration, errors.Wrap(err, "failed to export result to zip")
- }
-
- exportCount++
- // Help GC by clearing the result data we've already processed
- result.Rows = nil
- }
-
- if exportCount == 0 {
- return nil, duration, errors.Errorf("empty export data for database %s", database.DatabaseName)
- }
-
- if err := zipw.Close(); err != nil {
- return nil, duration, errors.Wrap(err, "failed to close zip writer")
- }
-
- return buf.Bytes(), duration, nil
-}
-
-// exportResultToZip exports a single query result to the ZIP archive.
-// It writes both the SQL statement and the formatted result data.
-func exportResultToZip(
- ctx context.Context,
- zipw *zip.Writer,
- stores *store.Store,
- instance *store.InstanceMessage,
- database *store.DatabaseMessage,
- result *v1pb.QueryResult,
- request *v1pb.ExportRequest,
- statementNumber int,
-) error {
- baseFilename := fmt.Sprintf("%s/%s/statement-%d", database.InstanceID, database.DatabaseName, statementNumber)
-
- // Write statement file
- statementFilename := fmt.Sprintf("%s.sql", baseFilename)
- if err := export.WriteZipEntry(zipw, statementFilename, []byte(result.Statement), request.GetPassword()); err != nil {
- return errors.Wrap(err, "failed to write statement")
- }
-
- // Write result file by streaming directly to ZIP
- resultExt := strings.ToLower(request.Format.String())
- resultFilename := fmt.Sprintf("%s.result.%s", baseFilename, resultExt)
- if err := formatExportToZip(ctx, zipw, resultFilename, stores, instance, database, result, request); err != nil {
- return errors.Wrap(err, "failed to write formatted result")
+ files, err := buildExportFiles(ctx, stores, instance, database, results, request)
+ if err != nil {
+ return nil, duration, err
}
-
- return nil
+ return files, duration, nil
}
-// formatExportToZip formats query results and writes them directly to a ZIP entry.
-// This function streams the formatted data to minimize memory usage.
-func formatExportToZip(
+// formatExportResult writes a query result in the requested format.
+func formatExportResult(
ctx context.Context,
- zipw *zip.Writer,
- filename string,
+ writer io.Writer,
stores *store.Store,
instance *store.InstanceMessage,
database *store.DatabaseMessage,
result *v1pb.QueryResult,
request *v1pb.ExportRequest,
) error {
- writer, err := export.CreateZipWriter(zipw, filename, request.GetPassword())
- if err != nil {
- return err
- }
-
switch request.Format {
case v1pb.ExportFormat_CSV:
return export.CSVToWriter(writer, result)
diff --git a/backend/api/v1/sql_service_export.go b/backend/api/v1/sql_service_export.go
new file mode 100644
index 0000000000..6da16b9181
--- /dev/null
+++ b/backend/api/v1/sql_service_export.go
@@ -0,0 +1,267 @@
+package v1
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "encoding/hex"
+ "fmt"
+ "strings"
+ "time"
+
+ "connectrpc.com/connect"
+ "github.com/alexmullins/zip"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/component/export"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+ "github.com/bytebase/bytebase/backend/plugin/sharepoint"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+// exportDestinationInput holds the state an export's destination is decided on.
+// The SharePoint fields are read only for the SharePoint destination.
+type exportDestinationInput struct {
+ destination v1pb.ExportDestination
+ disableDownload bool
+ password string
+ sharePointFeatureEnabled bool
+ destinationURL string
+ sharePointSetting *storepb.SharePointSetting
+}
+
+// decideExportDestination returns DOWNLOAD or SHAREPOINT. Nothing unlocks a
+// disabled Download: not an export grant, admin mode, or a lapsed license.
+func decideExportDestination(in exportDestinationInput) (v1pb.ExportDestination, error) {
+ destination := in.destination
+ if destination == v1pb.ExportDestination_EXPORT_DESTINATION_UNSPECIFIED {
+ destination = v1pb.ExportDestination_DOWNLOAD
+ }
+ switch destination {
+ case v1pb.ExportDestination_DOWNLOAD:
+ if in.disableDownload {
+ return 0, connect.NewError(connect.CodeFailedPrecondition, errors.New("the Download export destination is disabled by the workspace query data policy"))
+ }
+ return v1pb.ExportDestination_DOWNLOAD, nil
+ case v1pb.ExportDestination_SHAREPOINT:
+ default:
+ return 0, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("unsupported export destination %v", destination))
+ }
+ if !in.sharePointFeatureEnabled {
+ return 0, connect.NewError(connect.CodePermissionDenied, errors.Errorf("SharePoint export requires the %s feature", v1pb.PlanFeature_FEATURE_SHAREPOINT_EXPORT))
+ }
+ if in.password != "" {
+ return 0, connect.NewError(connect.CodeInvalidArgument, errors.New("password applies only to download"))
+ }
+ if in.destinationURL == "" {
+ return 0, connect.NewError(connect.CodeFailedPrecondition, errors.New("the project has no SharePoint export destination"))
+ }
+ setting := in.sharePointSetting
+ if setting.GetTenantId() == "" || setting.GetClientId() == "" || setting.GetClientSecret() == "" {
+ return 0, connect.NewError(connect.CodeFailedPrecondition, errors.New("SharePoint is not configured in workspace settings"))
+ }
+ return v1pb.ExportDestination_SHAREPOINT, nil
+}
+
+// sharePointExportTarget is the destination an export captured when it started.
+type sharePointExportTarget struct {
+ client sharepoint.Client
+ location *sharepoint.Location
+}
+
+// prepareExportDestination decides the destination and, for SharePoint,
+// resolves the project's destination so the export captures it before running
+// the query.
+func (s *SQLService) prepareExportDestination(ctx context.Context, request *v1pb.ExportRequest, database *store.DatabaseMessage) (*sharePointExportTarget, error) {
+ workspaceID := common.GetWorkspaceIDFromContext(ctx)
+ // Read without the license check, so the policy outlives the license.
+ policy, err := s.store.GetWorkspaceQueryDataPolicy(ctx, workspaceID)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to get the workspace query data policy"))
+ }
+ in := exportDestinationInput{
+ destination: request.GetDestination(),
+ disableDownload: policy.GetDisableDownload(),
+ password: request.GetPassword(),
+ }
+ if in.destination == v1pb.ExportDestination_SHAREPOINT {
+ in.sharePointFeatureEnabled = s.licenseService.IsFeatureEnabled(ctx, workspaceID, v1pb.PlanFeature_FEATURE_SHAREPOINT_EXPORT) == nil
+ project, err := s.store.GetProject(ctx, &store.FindProjectMessage{Workspace: workspaceID, ResourceID: &database.ProjectID})
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get project %q", database.ProjectID))
+ }
+ if project == nil {
+ return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("project %q not found", database.ProjectID))
+ }
+ in.destinationURL = project.Setting.GetExportSetting().GetSharepoint().GetUrl()
+ exportSetting, err := s.store.GetExportSetting(ctx, workspaceID)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to get export setting"))
+ }
+ in.sharePointSetting = exportSetting.GetSharepoint()
+ }
+
+ destination, err := decideExportDestination(in)
+ if err != nil {
+ return nil, err
+ }
+ if destination != v1pb.ExportDestination_SHAREPOINT {
+ return nil, nil
+ }
+ return resolveSharePointExportTarget(ctx, s.sharePointClientFactory(), in.sharePointSetting, in.destinationURL)
+}
+
+func (s *SQLService) sharePointClientFactory() func(sharepoint.Config) (sharepoint.Client, error) {
+ if s.newSharePointClient != nil {
+ return s.newSharePointClient
+ }
+ return sharepoint.NewClient
+}
+
+func resolveSharePointExportTarget(ctx context.Context, newClient func(sharepoint.Config) (sharepoint.Client, error), setting *storepb.SharePointSetting, destinationURL string) (*sharePointExportTarget, error) {
+ client, err := newClient(sharepoint.Config{
+ TenantID: setting.GetTenantId(),
+ ClientID: setting.GetClientId(),
+ ClientSecret: setting.GetClientSecret(),
+ })
+ if err != nil {
+ return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Wrap(err, "invalid SharePoint configuration"))
+ }
+ location, err := client.Resolve(ctx, destinationURL)
+ if err != nil {
+ if errors.Is(err, sharepoint.ErrNotFoundOrNoAccess) || errors.Is(err, sharepoint.ErrCredential) {
+ return nil, connect.NewError(connect.CodeFailedPrecondition, err)
+ }
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to resolve the SharePoint export destination"))
+ }
+ return &sharePointExportTarget{client: client, location: location}, nil
+}
+
+// uploadSharePointExport uploads files into folderName under the captured
+// destination and returns the folder's web URL. A failure may leave some files
+// uploaded, so every error names the folder.
+func uploadSharePointExport(ctx context.Context, target *sharePointExportTarget, folderName string, files []sharepoint.File) (string, error) {
+ folder, err := target.client.Upload(ctx, target.location, folderName, files)
+ if err != nil {
+ if errors.Is(err, sharepoint.ErrUnconfirmed) {
+ return "", connect.NewError(connect.CodeUnavailable, errors.Errorf("the upload to SharePoint could not be confirmed; files may exist in folder %q", folderName))
+ }
+ code := connect.CodeInternal
+ if errors.Is(err, sharepoint.ErrNotFoundOrNoAccess) || errors.Is(err, sharepoint.ErrCredential) {
+ code = connect.CodeFailedPrecondition
+ }
+ if errors.Is(err, sharepoint.ErrNothingUploaded) {
+ return "", connect.NewError(code, errors.Wrap(err, "the upload to SharePoint failed; nothing was uploaded"))
+ }
+ return "", connect.NewError(code, errors.Wrapf(err, "the upload to SharePoint failed; some files may already exist in folder %q", folderName))
+ }
+ return folder.WebURL, nil
+}
+
+const (
+ sharePointFolderComponentMaxLength = 64
+ sharePointFolderNameMaxLength = 200
+)
+
+// sharePointExportFolderName names the per-export folder. SharePoint attributes
+// files to the application, so the name carries the exporter.
+func sharePointExportFolderName(exportTime time.Time, exporterEmail, databaseName, exportID string) string {
+ name := strings.Join([]string{
+ exportTime.UTC().Format("20060102T150405Z"),
+ sanitizeSharePointName(exporterEmail, sharePointFolderComponentMaxLength),
+ sanitizeSharePointName(databaseName, sharePointFolderComponentMaxLength),
+ exportID,
+ }, "-")
+ return sanitizeSharePointName(name, sharePointFolderNameMaxLength)
+}
+
+// sanitizeSharePointName replaces characters SharePoint rejects in file and
+// folder names, trims the leading and trailing spaces and dots it rejects, and
+// caps the length in runes.
+func sanitizeSharePointName(name string, maxLength int) string {
+ name = strings.Map(func(r rune) rune {
+ if r < 0x20 || strings.ContainsRune("\"*:<>?/\\|#%", r) {
+ return '_'
+ }
+ return r
+ }, name)
+ name = strings.Trim(name, " .")
+ if runes := []rune(name); len(runes) > maxLength {
+ name = strings.TrimRight(string(runes[:maxLength]), " .")
+ }
+ return name
+}
+
+func newExportID() (string, error) {
+ b := make([]byte, 4)
+ if _, err := rand.Read(b); err != nil {
+ return "", errors.Wrap(err, "failed to generate export ID")
+ }
+ return hex.EncodeToString(b), nil
+}
+
+// buildExportFiles formats each result into its statement and result files.
+func buildExportFiles(ctx context.Context, stores *store.Store, instance *store.InstanceMessage, database *store.DatabaseMessage, results []*v1pb.QueryResult, request *v1pb.ExportRequest) ([]sharepoint.File, error) {
+ var files []sharepoint.File
+ for i, result := range results {
+ if result.GetError() != "" {
+ return nil, errors.Errorf("failed to exec the SQL with error: %v", result.GetError())
+ }
+ baseName := fmt.Sprintf("statement-%d", i+1)
+ var buf bytes.Buffer
+ if err := formatExportResult(ctx, &buf, stores, instance, database, result, request); err != nil {
+ return nil, errors.Wrap(err, "failed to write formatted result")
+ }
+ files = append(files,
+ sharepoint.File{Name: baseName + ".sql", Content: []byte(result.Statement)},
+ sharepoint.File{Name: fmt.Sprintf("%s.result.%s", baseName, strings.ToLower(request.Format.String())), Content: buf.Bytes()},
+ )
+ // Help GC by clearing the result data already formatted.
+ result.Rows = nil
+ }
+ if len(files) == 0 {
+ return nil, errors.Errorf("empty export data for database %s", database.DatabaseName)
+ }
+ return files, nil
+}
+
+// zipExportFiles packs files for download under <instance>/<database>/.
+func zipExportFiles(database *store.DatabaseMessage, files []sharepoint.File, password string) ([]byte, error) {
+ var buf bytes.Buffer
+ zipw := zip.NewWriter(&buf)
+ for _, file := range files {
+ name := fmt.Sprintf("%s/%s/%s", database.InstanceID, database.DatabaseName, file.Name)
+ if err := export.WriteZipEntry(zipw, name, file.Content, password); err != nil {
+ return nil, err
+ }
+ }
+ if err := zipw.Close(); err != nil {
+ return nil, errors.Wrap(err, "failed to close zip writer")
+ }
+ return buf.Bytes(), nil
+}
+
+// sendExport hands the export's files to their destination: a zip in the
+// response for download, or an upload to the captured SharePoint target.
+func sendExport(ctx context.Context, target *sharePointExportTarget, user *store.UserMessage, database *store.DatabaseMessage, files []sharepoint.File, request *v1pb.ExportRequest, exportTime time.Time) (*v1pb.ExportResponse, error) {
+ if target == nil {
+ content, err := zipExportFiles(database, files, request.GetPassword())
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, err)
+ }
+ return &v1pb.ExportResponse{Content: content}, nil
+ }
+
+ exportID, err := newExportID()
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, err)
+ }
+ folderName := sharePointExportFolderName(exportTime, user.Email, database.DatabaseName, exportID)
+ uri, err := uploadSharePointExport(ctx, target, folderName, files)
+ if err != nil {
+ return nil, err
+ }
+ return &v1pb.ExportResponse{Uri: uri}, nil
+}
diff --git a/backend/api/v1/sql_service_export_test.go b/backend/api/v1/sql_service_export_test.go
new file mode 100644
index 0000000000..f1fe060aa9
--- /dev/null
+++ b/backend/api/v1/sql_service_export_test.go
@@ -0,0 +1,547 @@
+package v1
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "crypto/rsa"
+ "crypto/x509"
+ "encoding/pem"
+ "io"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+
+ "connectrpc.com/connect"
+ "github.com/alexmullins/zip"
+ "github.com/pkg/errors"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/encoding/protojson"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ "github.com/bytebase/bytebase/backend/component/export"
+ "github.com/bytebase/bytebase/backend/enterprise"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+ "github.com/bytebase/bytebase/backend/plugin/sharepoint"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+func TestDecideExportDestination(t *testing.T) {
+ t.Parallel()
+ configured := &storepb.SharePointSetting{TenantId: "tenant", ClientId: "client", ClientSecret: "secret"}
+ sharePointReady := func(in exportDestinationInput) exportDestinationInput {
+ in.destination = v1pb.ExportDestination_SHAREPOINT
+ in.sharePointFeatureEnabled = true
+ in.destinationURL = "https://contoso.sharepoint.com/sites/data/Exports"
+ in.sharePointSetting = configured
+ return in
+ }
+ for _, tc := range []struct {
+ name string
+ in exportDestinationInput
+ want v1pb.ExportDestination
+ wantCode connect.Code
+ }{
+ {name: "unspecified is download", in: exportDestinationInput{}, want: v1pb.ExportDestination_DOWNLOAD},
+ {name: "download", in: exportDestinationInput{destination: v1pb.ExportDestination_DOWNLOAD, password: "pw"}, want: v1pb.ExportDestination_DOWNLOAD},
+ {name: "download disabled", in: exportDestinationInput{destination: v1pb.ExportDestination_DOWNLOAD, disableDownload: true}, wantCode: connect.CodeFailedPrecondition},
+ {name: "unspecified with download disabled", in: exportDestinationInput{disableDownload: true}, wantCode: connect.CodeFailedPrecondition},
+ {name: "sharepoint", in: sharePointReady(exportDestinationInput{}), want: v1pb.ExportDestination_SHAREPOINT},
+ {name: "sharepoint with download disabled", in: sharePointReady(exportDestinationInput{disableDownload: true}), want: v1pb.ExportDestination_SHAREPOINT},
+ {
+ name: "sharepoint without the feature",
+ in: func() exportDestinationInput {
+ in := sharePointReady(exportDestinationInput{})
+ in.sharePointFeatureEnabled = false
+ return in
+ }(),
+ wantCode: connect.CodePermissionDenied,
+ },
+ {
+ name: "sharepoint with password",
+ in: func() exportDestinationInput {
+ in := sharePointReady(exportDestinationInput{})
+ in.password = "pw"
+ return in
+ }(),
+ wantCode: connect.CodeInvalidArgument,
+ },
+ {
+ name: "sharepoint without destination",
+ in: func() exportDestinationInput {
+ in := sharePointReady(exportDestinationInput{})
+ in.destinationURL = ""
+ return in
+ }(),
+ wantCode: connect.CodeFailedPrecondition,
+ },
+ {
+ name: "sharepoint without destination and download disabled",
+ in: func() exportDestinationInput {
+ in := sharePointReady(exportDestinationInput{disableDownload: true})
+ in.destinationURL = ""
+ return in
+ }(),
+ wantCode: connect.CodeFailedPrecondition,
+ },
+ {
+ name: "sharepoint without credentials",
+ in: func() exportDestinationInput {
+ in := sharePointReady(exportDestinationInput{})
+ in.sharePointSetting = nil
+ return in
+ }(),
+ wantCode: connect.CodeFailedPrecondition,
+ },
+ {
+ name: "sharepoint without client secret",
+ in: func() exportDestinationInput {
+ in := sharePointReady(exportDestinationInput{})
+ in.sharePointSetting = &storepb.SharePointSetting{TenantId: "tenant", ClientId: "client"}
+ return in
+ }(),
+ wantCode: connect.CodeFailedPrecondition,
+ },
+ {name: "unknown destination", in: exportDestinationInput{destination: v1pb.ExportDestination(99)}, wantCode: connect.CodeInvalidArgument},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ got, err := decideExportDestination(tc.in)
+ if tc.wantCode != 0 {
+ require.Equal(t, tc.wantCode, connect.CodeOf(err))
+ return
+ }
+ require.NoError(t, err)
+ require.Equal(t, tc.want, got)
+ })
+ }
+}
+
+func TestSanitizeSharePointName(t *testing.T) {
+ t.Parallel()
+ for _, tc := range []struct {
+ name string
+ input string
+ maxLength int
+ want string
+ }{
+ {name: "plain", input: "[email protected]", maxLength: 64, want: "[email protected]"},
+ {name: "reserved characters", input: "a\"b*c:d<e>f?g/h\\i|j#k%l", maxLength: 64, want: "a_b_c_d_e_f_g_h_i_j_k_l"},
+ {name: "control characters", input: "a\tb\nc", maxLength: 64, want: "a_b_c"},
+ {name: "leading and trailing spaces and dots", input: " ..db.. ", maxLength: 64, want: "db"},
+ {name: "capped in runes", input: "数据库数据库", maxLength: 3, want: "数据库"},
+ {name: "cap exposes trailing dot", input: "abc.def", maxLength: 4, want: "abc"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ require.Equal(t, tc.want, sanitizeSharePointName(tc.input, tc.maxLength))
+ })
+ }
+}
+
+func TestSharePointExportFolderName(t *testing.T) {
+ t.Parallel()
+ exportTime := time.Date(2026, 10, 22, 9, 5, 7, 0, time.FixedZone("CST", 8*60*60))
+ require.Equal(t,
+ "[email protected]_prod-0a1b2c3d",
+ sharePointExportFolderName(exportTime, "[email protected]", "hr/prod", "0a1b2c3d"),
+ )
+
+ long := sharePointExportFolderName(exportTime, strings.Repeat("e", 300)+"@example.com", strings.Repeat("d", 300), "0a1b2c3d")
+ require.LessOrEqual(t, len([]rune(long)), sharePointFolderNameMaxLength)
+ require.True(t, strings.HasSuffix(long, "-0a1b2c3d"), long)
+
+ id, err := newExportID()
+ require.NoError(t, err)
+ require.Regexp(t, regexp.MustCompile("^[0-9a-f]{8}$"), id)
+}
+
+// TestZipExportFilesMatchesStreamedZip compares the download zip with the one the
+// export wrote before files were built first: entries were streamed directly
+// into the zip under <instance>/<database>/.
+func TestZipExportFilesMatchesStreamedZip(t *testing.T) {
+ t.Parallel()
+ database := &store.DatabaseMessage{InstanceID: "prod-instance", DatabaseName: "hr"}
+ files := []sharepoint.File{
+ {Name: "statement-1.sql", Content: []byte("SELECT * FROM employee")},
+ {Name: "statement-1.result.csv", Content: []byte(strings.Repeat("1,alice\n2,bob\n", 5000))},
+ {Name: "statement-2.sql", Content: []byte("SELECT 1")},
+ {Name: "statement-2.result.csv", Content: []byte("1\n")},
+ }
+ for _, password := range []string{"", "secret"} {
+ t.Run("password="+password, func(t *testing.T) {
+ t.Parallel()
+ got, err := zipExportFiles(database, files, password)
+ require.NoError(t, err)
+ want := streamedZip(t, database, files, password)
+
+ gotEntries, wantEntries := readZip(t, got, password), readZip(t, want, password)
+ require.Equal(t, []string{
+ "prod-instance/hr/statement-1.sql",
+ "prod-instance/hr/statement-1.result.csv",
+ "prod-instance/hr/statement-2.sql",
+ "prod-instance/hr/statement-2.result.csv",
+ }, zipEntryNames(gotEntries))
+ require.Equal(t, wantEntries, gotEntries)
+ if password == "" {
+ require.Equal(t, len(want), len(got))
+ }
+ })
+ }
+}
+
+type zipEntry struct {
+ name string
+ method uint16
+ encrypted bool
+ crc32 uint32
+ compressedSize uint64
+ uncompressedSize uint64
+ content []byte
+}
+
+func zipEntryNames(entries []zipEntry) []string {
+ var names []string
+ for _, e := range entries {
+ names = append(names, e.name)
+ }
+ return names
+}
+
+func streamedZip(t *testing.T, database *store.DatabaseMessage, files []sharepoint.File, password string) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ zipw := zip.NewWriter(&buf)
+ for i, file := range files {
+ name := database.InstanceID + "/" + database.DatabaseName + "/" + file.Name
+ if i%2 == 0 {
+ require.NoError(t, export.WriteZipEntry(zipw, name, file.Content, password))
+ continue
+ }
+ w, err := export.CreateZipWriter(zipw, name, password)
+ require.NoError(t, err)
+ for content := file.Content; len(content) > 0; {
+ n := min(len(content), 4096)
+ _, err := w.Write(content[:n])
+ require.NoError(t, err)
+ content = content[n:]
+ }
+ }
+ require.NoError(t, zipw.Close())
+ return buf.Bytes()
+}
+
+func readZip(t *testing.T, content []byte, password string) []zipEntry {
+ t.Helper()
+ r, err := zip.NewReader(bytes.NewReader(content), int64(len(content)))
+ require.NoError(t, err)
+ var entries []zipEntry
+ for _, f := range r.File {
+ if f.IsEncrypted() {
+ f.SetPassword(password)
+ }
+ rc, err := f.Open()
+ require.NoError(t, err)
+ data, err := io.ReadAll(rc)
+ require.NoError(t, err)
+ require.NoError(t, rc.Close())
+ entries = append(entries, zipEntry{
+ name: f.Name,
+ method: f.Method,
+ encrypted: f.IsEncrypted(),
+ crc32: f.CRC32,
+ compressedSize: f.CompressedSize64,
+ uncompressedSize: f.UncompressedSize64,
+ content: data,
+ })
+ }
+ return entries
+}
+
+type exportSharePointClient struct {
+ location *sharepoint.Location
+ resolveErr error
+ uploadErr error
+
+ resolvedURL string
+ uploadedTo *sharepoint.Location
+ uploadedFolder string
+ uploadedFiles []sharepoint.File
+}
+
+func (c *exportSharePointClient) Resolve(_ context.Context, canonicalURL string) (*sharepoint.Location, error) {
+ c.resolvedURL = canonicalURL
+ if c.resolveErr != nil {
+ return nil, c.resolveErr
+ }
+ return c.location, nil
+}
+
+func (c *exportSharePointClient) Upload(_ context.Context, loc *sharepoint.Location, folderName string, files []sharepoint.File) (*sharepoint.Folder, error) {
+ c.uploadedTo, c.uploadedFolder, c.uploadedFiles = loc, folderName, files
+ if c.uploadErr != nil {
+ return nil, c.uploadErr
+ }
+ return &sharepoint.Folder{Name: folderName, WebURL: loc.WebURL + "/" + folderName}, nil
+}
+
+func TestSharePointExportUploadsToCapturedTarget(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+ client := &exportSharePointClient{location: &sharepoint.Location{DriveID: "drive", ItemID: "item", WebURL: "https://contoso.sharepoint.com/sites/data/Exports"}}
+ var gotConfig sharepoint.Config
+ newClient := func(cfg sharepoint.Config) (sharepoint.Client, error) {
+ gotConfig = cfg
+ return client, nil
+ }
+ setting := &storepb.SharePointSetting{TenantId: "tenant", ClientId: "client", ClientSecret: "secret"}
+ target, err := resolveSharePointExportTarget(ctx, newClient, setting, "https://contoso.sharepoint.com/sites/data/Exports")
+ require.NoError(t, err)
+ require.Equal(t, sharepoint.Config{TenantID: "tenant", ClientID: "client", ClientSecret: "secret"}, gotConfig)
+ require.Equal(t, "https://contoso.sharepoint.com/sites/data/Exports", client.resolvedURL)
+
+ files := []sharepoint.File{
+ {Name: "statement-1.sql", Content: []byte("SELECT 1")},
+ {Name: "statement-1.result.csv", Content: []byte("1\n")},
+ }
+ user := &store.UserMessage{Email: "[email protected]"}
+ database := &store.DatabaseMessage{InstanceID: "prod", DatabaseName: "hr"}
+ exportTime := time.Date(2026, 10, 22, 1, 5, 7, 0, time.UTC)
+ resp, err := sendExport(ctx, target, user, database, files, &v1pb.ExportRequest{Format: v1pb.ExportFormat_CSV}, exportTime)
+ require.NoError(t, err)
+ require.Empty(t, resp.Content)
+ require.Equal(t, "https://contoso.sharepoint.com/sites/data/Exports/"+client.uploadedFolder, resp.Uri)
+ require.Same(t, client.location, client.uploadedTo)
+ require.Regexp(t, regexp.MustCompile("^[email protected][0-9a-f]{8}$"), client.uploadedFolder)
+ require.Equal(t, files, client.uploadedFiles)
+}
+
+// nothingUploadedError stands in for the SharePoint client's marking of an
+// upload that failed before any file was uploaded.
+type nothingUploadedError struct{ error }
+
+func (e nothingUploadedError) Unwrap() error { return e.error }
+func (nothingUploadedError) Is(target error) bool { return target == sharepoint.ErrNothingUploaded }
+
+func TestSharePointExportErrors(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+ setting := &storepb.SharePointSetting{TenantId: "tenant", ClientId: "client", ClientSecret: "secret"}
+ for _, tc := range []struct {
+ name string
+ resolveErr error
+ uploadErr error
+ wantCode connect.Code
+ wantInMsg []string
+ wantNotInMsg []string
+ }{
+ {name: "resolve not found", resolveErr: errors.Wrap(sharepoint.ErrNotFoundOrNoAccess, "graph"), wantCode: connect.CodeFailedPrecondition},
+ {name: "resolve credential", resolveErr: sharepoint.ErrCredential, wantCode: connect.CodeFailedPrecondition},
+ {name: "resolve other", resolveErr: errors.New("boom"), wantCode: connect.CodeInternal},
+ {name: "upload not found", uploadErr: sharepoint.ErrNotFoundOrNoAccess, wantCode: connect.CodeFailedPrecondition, wantInMsg: []string{"may already exist", "[email protected]"}},
+ {name: "folder not created", uploadErr: nothingUploadedError{sharepoint.ErrNotFoundOrNoAccess}, wantCode: connect.CodeFailedPrecondition, wantInMsg: []string{"nothing was uploaded"}, wantNotInMsg: []string{"may already exist", "[email protected]"}},
+ {name: "upload credential", uploadErr: errors.Wrap(sharepoint.ErrCredential, "token"), wantCode: connect.CodeFailedPrecondition, wantInMsg: []string{"may already exist", "[email protected]"}},
+ {name: "upload unconfirmed", uploadErr: errors.Wrap(sharepoint.ErrUnconfirmed, "upload"), wantCode: connect.CodeUnavailable, wantInMsg: []string{"could not be confirmed", "[email protected]"}},
+ {name: "upload failed after some files", uploadErr: errors.New("upload statement-1.result.csv: 507 insufficientStorage"), wantCode: connect.CodeInternal, wantInMsg: []string{"the upload to SharePoint failed", "may already exist", "insufficientStorage", "[email protected]"}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ client := &exportSharePointClient{location: &sharepoint.Location{WebURL: "https://contoso.sharepoint.com/sites/data/Exports"}, resolveErr: tc.resolveErr, uploadErr: tc.uploadErr}
+ newClient := func(sharepoint.Config) (sharepoint.Client, error) { return client, nil }
+ target, err := resolveSharePointExportTarget(ctx, newClient, setting, "https://contoso.sharepoint.com/sites/data/Exports")
+ if tc.resolveErr != nil {
+ require.Equal(t, tc.wantCode, connect.CodeOf(err))
+ return
+ }
+ require.NoError(t, err)
+ _, err = uploadSharePointExport(ctx, target, "[email protected]", nil)
+ require.Equal(t, tc.wantCode, connect.CodeOf(err))
+ for _, want := range tc.wantInMsg {
+ require.Contains(t, err.Error(), want)
+ }
+ for _, unwanted := range tc.wantNotInMsg {
+ require.NotContains(t, err.Error(), unwanted)
+ }
+ })
+ }
+}
+
+// newEnterpriseLicenseService returns a license service under which
+// workspaceID holds a valid ENTERPRISE license.
+func newEnterpriseLicenseService(ctx context.Context, t *testing.T, stores *store.Store, workspaceID string) *enterprise.LicenseService {
+ t.Helper()
+ privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
+ require.NoError(t, err)
+ privateKeyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)})
+ licenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, stores, false, string(privateKeyPEM))
+ require.NoError(t, err)
+ setLicenseServicePublicKey(t, licenseService, &privateKey.PublicKey)
+ _, err = stores.UpsertSetting(ctx, &store.SettingMessage{Name: storepb.SettingName_SYSTEM, Workspace: workspaceID, Value: &storepb.SystemSetting{}})
+ require.NoError(t, err)
+ license, err := licenseService.CreateLicense(&enterprise.LicenseParams{Plan: v1pb.PlanType_ENTERPRISE.String(), Seats: 10, Instances: 10, WorkspaceID: workspaceID})
+ require.NoError(t, err)
+ require.NoError(t, licenseService.StoreLicense(ctx, workspaceID, license))
+ require.NoError(t, licenseService.IsFeatureEnabled(ctx, workspaceID, v1pb.PlanFeature_FEATURE_SHAREPOINT_EXPORT))
+ return licenseService
+}
+
+func setWorkspaceDisableDownload(ctx context.Context, t *testing.T, stores *store.Store, disableDownload bool) {
+ t.Helper()
+ payload, err := protojson.Marshal(&storepb.QueryDataPolicy{DisableDownload: disableDownload})
+ require.NoError(t, err)
+ _, err = stores.CreatePolicy(ctx, &store.PolicyMessage{
+ Workspace: "default",
+ ResourceType: storepb.Policy_WORKSPACE,
+ Resource: common.FormatWorkspace("default"),
+ Type: storepb.Policy_QUERY_DATA,
+ Payload: string(payload),
+ Enforce: true,
+ })
+ require.NoError(t, err)
+}
+
+// newExportDestinationFixture seeds workspace SharePoint credentials and a
+// project that has sharePointURL as its SharePoint folder, or none when empty.
+func newExportDestinationFixture(t *testing.T, sharePointURL string) (context.Context, *store.Store, *store.DatabaseMessage) {
+ t.Helper()
+ ctx := context.WithValue(context.Background(), common.WorkspaceIDContextKey, "default")
+ db, stores, _ := testcontainer.NewMetadataDB(t)
+ projectSetting := &storepb.Project{}
+ if sharePointURL != "" {
+ projectSetting.ExportSetting = &storepb.Project_ExportSetting{Sharepoint: &storepb.Project_SharePointDestination{Url: sharePointURL}}
+ }
+ projectSettingJSON, err := protojson.Marshal(projectSetting)
+ require.NoError(t, err)
+ _, err = db.ExecContext(ctx, `
+ INSERT INTO workspace (resource_id) VALUES ('default');
+ INSERT INTO setting (name, workspace, value)
+ VALUES ('EXPORT', 'default', '{"sharepoint":{"tenantId":"tenant","clientId":"client","clientSecret":"secret"}}');`)
+ require.NoError(t, err)
+ _, err = db.ExecContext(ctx, `INSERT INTO project (resource_id, workspace, name, setting) VALUES ('export-project', 'default', 'Export Project', $1)`, string(projectSettingJSON))
+ require.NoError(t, err)
+ return ctx, stores, &store.DatabaseMessage{ProjectID: "export-project", InstanceID: "prod", DatabaseName: "hr"}
+}
+
+const exportFixtureSharePointURL = "https://contoso.sharepoint.com/sites/data/Exports"
+
+// TestPrepareExportDestinationReadsPolicyWithoutLicense runs on a free plan, as
+// after a lapsed license: disable_download still applies.
+func TestPrepareExportDestinationReadsPolicyWithoutLicense(t *testing.T) {
+ t.Parallel()
+ ctx, stores, database := newExportDestinationFixture(t, exportFixtureSharePointURL)
+ licenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, stores, false, "")
+ require.NoError(t, err)
+ require.Error(t, licenseService.IsFeatureEnabled(ctx, "default", v1pb.PlanFeature_FEATURE_QUERY_POLICY))
+ service := &SQLService{store: stores, licenseService: licenseService}
+
+ target, err := service.prepareExportDestination(ctx, &v1pb.ExportRequest{Destination: v1pb.ExportDestination_DOWNLOAD}, database)
+ require.NoError(t, err, "a workspace without a policy allows download")
+ require.Nil(t, target)
+
+ setWorkspaceDisableDownload(ctx, t, stores, true)
+ for _, destination := range []v1pb.ExportDestination{v1pb.ExportDestination_EXPORT_DESTINATION_UNSPECIFIED, v1pb.ExportDestination_DOWNLOAD} {
+ _, err := service.prepareExportDestination(ctx, &v1pb.ExportRequest{Destination: destination}, database)
+ require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err), destination.String())
+ }
+ _, err = service.prepareExportDestination(ctx, &v1pb.ExportRequest{Destination: v1pb.ExportDestination_SHAREPOINT}, database)
+ require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err), "the SharePoint destination needs the license")
+
+ setWorkspaceDisableDownload(ctx, t, stores, false)
+ target, err = service.prepareExportDestination(ctx, &v1pb.ExportRequest{}, database)
+ require.NoError(t, err)
+ require.Nil(t, target)
+}
+
+func TestPrepareExportDestinationAllowsSharePointWithDownloadDisabled(t *testing.T) {
+ t.Parallel()
+ ctx, stores, database := newExportDestinationFixture(t, exportFixtureSharePointURL)
+ licenseService := newEnterpriseLicenseService(ctx, t, stores, "default")
+ client := &exportSharePointClient{location: &sharepoint.Location{DriveID: "drive", ItemID: "item"}}
+ service := &SQLService{store: stores, licenseService: licenseService, newSharePointClient: func(cfg sharepoint.Config) (sharepoint.Client, error) {
+ require.Equal(t, sharepoint.Config{TenantID: "tenant", ClientID: "client", ClientSecret: "secret"}, cfg)
+ return client, nil
+ }}
+ setWorkspaceDisableDownload(ctx, t, stores, true)
+
+ target, err := service.prepareExportDestination(ctx, &v1pb.ExportRequest{Destination: v1pb.ExportDestination_SHAREPOINT}, database)
+ require.NoError(t, err)
+ require.Same(t, client.location, target.location)
+ require.Equal(t, exportFixtureSharePointURL, client.resolvedURL)
+
+ _, err = service.prepareExportDestination(ctx, &v1pb.ExportRequest{Destination: v1pb.ExportDestination_DOWNLOAD}, database)
+ require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err), "the license does not unlock download")
+}
+
+// TestPrepareExportDestinationRefusesWithoutAnyDestination covers a workspace
+// with downloads disabled and a project with no SharePoint folder.
+func TestPrepareExportDestinationRefusesWithoutAnyDestination(t *testing.T) {
+ t.Parallel()
+ ctx, stores, database := newExportDestinationFixture(t, "")
+ licenseService := newEnterpriseLicenseService(ctx, t, stores, "default")
+ service := &SQLService{store: stores, licenseService: licenseService, newSharePointClient: func(sharepoint.Config) (sharepoint.Client, error) {
+ return nil, errors.New("no SharePoint client is expected")
+ }}
+ setWorkspaceDisableDownload(ctx, t, stores, true)
+
+ for _, destination := range []v1pb.ExportDestination{v1pb.ExportDestination_EXPORT_DESTINATION_UNSPECIFIED, v1pb.ExportDestination_DOWNLOAD, v1pb.ExportDestination_SHAREPOINT} {
+ _, err := service.prepareExportDestination(ctx, &v1pb.ExportRequest{Destination: destination}, database)
+ require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err), destination.String())
+ }
+}
+
+// TestExportRejectsDownloadDespiteExportGrant calls Export with an active
+// export grant for the exact statement. disable_download rejects the request
+// before any connection to the target database.
+func TestExportRejectsDownloadDespiteExportGrant(t *testing.T) {
+ t.Parallel()
+ ctx := context.WithValue(context.Background(), common.WorkspaceIDContextKey, "default")
+ ctx = context.WithValue(ctx, common.UserContextKey, &store.UserMessage{Email: "[email protected]"})
+ db, stores, _ := testcontainer.NewMetadataDB(t)
+ _, err := db.ExecContext(ctx, `
+ INSERT INTO workspace (resource_id) VALUES ('default');
+ INSERT INTO project (resource_id, workspace, name, setting)
+ VALUES ('grant-project', 'default', 'Grant Project', '{"allowJustInTimeAccess":true}');`)
+ require.NoError(t, err)
+ instance, err := stores.CreateInstance(ctx, &store.InstanceMessage{
+ ResourceID: "prod",
+ Workspace: "default",
+ Metadata: &storepb.Instance{
+ Engine: storepb.Engine_POSTGRES,
+ Activation: true,
+ DataSources: []*storepb.DataSource{{Id: "admin", Type: storepb.DataSourceType_ADMIN}},
+ },
+ })
+ require.NoError(t, err)
+ database, err := stores.UpsertDatabase(ctx, &store.DatabaseMessage{
+ InstanceID: "prod", DatabaseName: "hr", ProjectID: "grant-project", Metadata: &storepb.DatabaseMetadata{},
+ })
+ require.NoError(t, err)
+ const statement = "SELECT 1"
+ expires := time.Now().Add(time.Hour)
+ grant, err := stores.CreateAccessGrant(ctx, &store.AccessGrantMessage{
+ ProjectID: "grant-project", Creator: "[email protected]", Status: storepb.AccessGrant_ACTIVE, ExpireTime: &expires,
+ Payload: &storepb.AccessGrantPayload{Query: statement, Targets: []string{"instances/prod/databases/hr"}, Export: true, Unmask: true},
+ })
+ require.NoError(t, err)
+ licenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, stores, false, "")
+ require.NoError(t, err)
+ service := &SQLService{store: stores, licenseService: licenseService}
+ got := service.preCheckAccess(ctx, statement, instance, database, nil, "", true /* requireExport */)
+ require.NotNil(t, got)
+ require.Equal(t, grant.ID, got.ID)
+
+ setWorkspaceDisableDownload(ctx, t, stores, true)
+ for _, destination := range []v1pb.ExportDestination{v1pb.ExportDestination_EXPORT_DESTINATION_UNSPECIFIED, v1pb.ExportDestination_DOWNLOAD} {
+ _, err := service.Export(ctx, connect.NewRequest(&v1pb.ExportRequest{
+ Name: "instances/prod/databases/hr",
+ Statement: statement,
+ Format: v1pb.ExportFormat_CSV,
+ Destination: destination,
+ }))
+ require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err), destination.String())
+ require.ErrorContains(t, err, "the Download export destination is disabled", destination.String())
+ }
+}
diff --git a/backend/enterprise/plan.yaml b/backend/enterprise/plan.yaml
index ac1e68eb6e..d5f9f8fe2e 100644
--- a/backend/enterprise/plan.yaml
+++ b/backend/enterprise/plan.yaml
@@ -125,6 +125,7 @@ plans:
- FEATURE_INSTANCE_READ_ONLY_CONNECTION
- FEATURE_QUERY_POLICY
- FEATURE_RESTRICT_COPYING_DATA
+ - FEATURE_SHAREPOINT_EXPORT
# Security & Compliance
- FEATURE_IAM
- FEATURE_INSTANCE_SSL_CONNECTION
diff --git a/backend/migrator/migration/LATEST.sql b/backend/migrator/migration/LATEST.sql
index 6ac2e8e85f..6d99f5c39b 100644
--- a/backend/migrator/migration/LATEST.sql
+++ b/backend/migrator/migration/LATEST.sql
@@ -81,7 +81,8 @@ ALTER SEQUENCE principal_id_seq RESTART WITH 101;
-- Setting
CREATE TABLE setting (
-- name: SYSTEM, WORKSPACE_PROFILE, WORKSPACE_APPROVAL,
- -- APP_IM, AI, DATA_CLASSIFICATION, SEMANTIC_TYPES, ENVIRONMENT, EMAIL, MCP
+ -- APP_IM, AI, DATA_CLASSIFICATION, SEMANTIC_TYPES, ENVIRONMENT, EMAIL, MCP,
+ -- EXPORT
-- Enum: SettingName (proto/store/store/setting.proto)
name text NOT NULL,
workspace text NOT NULL REFERENCES workspace(resource_id),
diff --git a/backend/plugin/sharepoint/client.go b/backend/plugin/sharepoint/client.go
new file mode 100644
index 0000000000..78e6c7da60
--- /dev/null
+++ b/backend/plugin/sharepoint/client.go
@@ -0,0 +1,333 @@
+package sharepoint
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+ "regexp"
+ "strings"
+ "time"
+
+ "github.com/Azure/azure-sdk-for-go/sdk/azcore"
+ "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
+ "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
+ "github.com/pkg/errors"
+ "golang.org/x/sync/errgroup"
+)
+
+const (
+ graphBaseURL = "https://graph.microsoft.com/v1.0"
+ graphScope = "https://graph.microsoft.com/.default"
+ // Graph requires upload chunks to be multiples of 320 KiB.
+ uploadChunkSize = 16 * 320 * 1024
+ // Files up to this size upload in one request; larger files use a
+ // resumable upload session.
+ simpleUploadMaxSize = 4 << 20
+ maxConcurrentUploads = 4
+ maxAttempts = 5
+ requestTimeout = 5 * time.Minute
+)
+
+var aadstsPattern = regexp.MustCompile(`AADSTS\d+`)
+
+type tokenSource func(ctx context.Context) (string, error)
+
+type graphClient struct {
+ baseURL string
+ clientID string
+ token tokenSource
+ httpClient *http.Client
+ chunkSize int
+ simpleUploadMaxSize int
+ maxConcurrentUploads int
+ maxAttempts int
+ wait func(ctx context.Context, d time.Duration) error
+}
+
+func newGraphClient(cfg Config) (Client, error) {
+ if cfg.TenantID == "" || cfg.ClientID == "" || cfg.ClientSecret == "" {
+ return nil, errors.New("SharePoint requires a tenant ID, client ID, and client secret")
+ }
+ cred, err := azidentity.NewClientSecretCredential(cfg.TenantID, cfg.ClientID, cfg.ClientSecret, nil)
+ if err != nil {
+ return nil, errors.Wrapf(ErrCredential, "invalid application configuration: %v", err)
+ }
+ return &graphClient{
+ baseURL: graphBaseURL,
+ clientID: cfg.ClientID,
+ token: credentialTokenSource(cred),
+ httpClient: &http.Client{Timeout: requestTimeout},
+ chunkSize: uploadChunkSize,
+ simpleUploadMaxSize: simpleUploadMaxSize,
+ maxConcurrentUploads: maxConcurrentUploads,
+ maxAttempts: maxAttempts,
+ wait: sleepContext,
+ }, nil
+}
+
+func credentialTokenSource(cred azcore.TokenCredential) tokenSource {
+ return func(ctx context.Context) (string, error) {
+ token, err := cred.GetToken(ctx, policy.TokenRequestOptions{Scopes: []string{graphScope}})
+ if err == nil {
+ return token.Token, nil
+ }
+ var authErr *azidentity.AuthenticationFailedError
+ if errors.As(err, &authErr) && (authErr.RawResponse == nil || authErr.RawResponse.StatusCode < http.StatusInternalServerError) {
+ // Report only the Entra error code; the full error is verbose.
+ if code := aadstsPattern.FindString(authErr.Error()); code != "" {
+ return "", errors.Wrap(ErrCredential, code)
+ }
+ return "", errors.WithStack(ErrCredential)
+ }
+ return "", errors.Wrap(err, "failed to get a Microsoft Entra token")
+ }
+}
+
+func sleepContext(ctx context.Context, d time.Duration) error {
+ timer := time.NewTimer(d)
+ defer timer.Stop()
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-timer.C:
+ return nil
+ }
+}
+
+type driveItem struct {
+ ID string `json:"id"`
+ WebURL string `json:"webUrl"`
+ Size int64 `json:"size"`
+ Folder *struct{} `json:"folder"`
+ Root *struct{} `json:"root"`
+
+ ParentReference struct {
+ DriveID string `json:"driveId"`
+ } `json:"parentReference"`
+ CreatedBy struct {
+ Application *struct {
+ ID string `json:"id"`
+ } `json:"application"`
+ } `json:"createdBy"`
+}
+
+func (c *graphClient) Resolve(ctx context.Context, canonicalURL string) (*Location, error) {
+ canonical, err := NormalizeURL(canonicalURL)
+ if err != nil {
+ return nil, err
+ }
+ u, err := url.Parse(canonical)
+ if err != nil {
+ return nil, errors.Wrap(err, "invalid SharePoint URL")
+ }
+ // /shares accepts the URL with unescaped spaces.
+ shareID := "u!" + base64.RawURLEncoding.EncodeToString([]byte("https://"+u.Host+u.Path))
+ var item driveItem
+ if err := c.graphJSON(ctx, http.MethodGet, "/shares/"+shareID+"/driveItem?$select=id,webUrl,folder,root,parentReference", nil, &item); err != nil {
+ return nil, errors.Wrapf(err, "failed to resolve %s", canonical)
+ }
+ if item.Folder == nil && item.Root == nil {
+ return nil, errors.Errorf("%s is a file; use a document library or folder", canonical)
+ }
+ if item.ID == "" || item.ParentReference.DriveID == "" {
+ return nil, errors.Errorf("Microsoft Graph did not return the document library of %s", canonical)
+ }
+ return &Location{DriveID: item.ParentReference.DriveID, ItemID: item.ID, WebURL: item.WebURL}, nil
+}
+
+func (c *graphClient) Upload(ctx context.Context, loc *Location, folderName string, files []File) (*Folder, error) {
+ if loc == nil || loc.DriveID == "" || loc.ItemID == "" {
+ return nil, errors.New("the SharePoint destination is not resolved")
+ }
+ if folderName == "" {
+ return nil, errors.New("the SharePoint folder name is empty")
+ }
+ seen := make(map[string]bool, len(files))
+ for _, file := range files {
+ key := strings.ToLower(file.Name)
+ if file.Name == "" || seen[key] {
+ return nil, errors.Errorf("invalid or duplicate export file name %q", file.Name)
+ }
+ seen[key] = true
+ }
+
+ folder, err := c.ensureFolder(ctx, loc, folderName)
+ if err != nil {
+ return nil, &nothingUploadedError{err: err}
+ }
+ g, gctx := errgroup.WithContext(ctx)
+ g.SetLimit(max(c.maxConcurrentUploads, 1))
+ for _, file := range files {
+ g.Go(func() error {
+ return c.uploadFile(gctx, loc.DriveID, folder.ID, file)
+ })
+ }
+ if err := g.Wait(); err != nil {
+ return nil, err
+ }
+ return &Folder{Name: folderName, WebURL: folder.WebURL}, nil
+}
+
+func (c *graphClient) ensureFolder(ctx context.Context, loc *Location, folderName string) (*driveItem, error) {
+ parent := itemPath(loc.DriveID, loc.ItemID)
+ body := map[string]any{
+ "name": folderName,
+ "folder": map[string]any{},
+ "@microsoft.graph.conflictBehavior": "fail",
+ }
+ var folder driveItem
+ err := c.graphJSON(ctx, http.MethodPost, parent+"/children", body, &folder)
+ if statusOf(err) == http.StatusConflict {
+ folder = driveItem{}
+ err = c.graphJSON(ctx, http.MethodGet, parent+":/"+escapeSegment(folderName)+"?$select=id,webUrl,folder", nil, &folder)
+ if err == nil && folder.Folder == nil {
+ return nil, errors.Errorf("a file named %q already exists in the SharePoint destination", folderName)
+ }
+ }
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to create SharePoint folder %q", folderName)
+ }
+ if folder.ID == "" {
+ return nil, errors.Errorf("Microsoft Graph did not return SharePoint folder %q", folderName)
+ }
+ return &folder, nil
+}
+
+func (c *graphClient) uploadFile(ctx context.Context, driveID, folderID string, file File) error {
+ err := c.putFile(ctx, driveID, folderID, file)
+ if err == nil {
+ return nil
+ }
+ if statusOf(err) == http.StatusConflict {
+ return c.reconcile(ctx, driveID, folderID, file, false)
+ }
+ var unknown *unknownOutcomeError
+ if errors.As(err, &unknown) {
+ return c.reconcile(ctx, driveID, folderID, file, true)
+ }
+ return errors.Wrapf(err, "failed to upload %q", file.Name)
+}
+
+func (c *graphClient) putFile(ctx context.Context, driveID, folderID string, file File) error {
+ target := itemPath(driveID, folderID) + ":/" + escapeSegment(file.Name) + ":"
+ if len(file.Content) <= c.simpleUploadMaxSize {
+ return c.graphRaw(ctx, http.MethodPut, target+"/[email protected]=fail", file.Content)
+ }
+ body := map[string]any{"item": map[string]any{"@microsoft.graph.conflictBehavior": "fail"}}
+ var session struct {
+ UploadURL string `json:"uploadUrl"`
+ }
+ if err := c.graphJSON(ctx, http.MethodPost, target+"/createUploadSession", body, &session); err != nil {
+ return err
+ }
+ if session.UploadURL == "" {
+ return errors.New("Microsoft Graph did not return an upload session")
+ }
+ return c.uploadChunks(ctx, session.UploadURL, file.Content)
+}
+
+// uploadChunks uploads content to an upload session. The upload URL is
+// pre-authenticated, so it is sent without a token and kept out of errors.
+func (c *graphClient) uploadChunks(ctx context.Context, uploadURL string, content []byte) error {
+ total := len(content)
+ // Bound the loop in case the session keeps asking for the same range.
+ maxRequests := 2*(total/c.chunkSize+1) + c.maxAttempts
+ offset := 0
+ for range maxRequests {
+ end := min(offset+c.chunkSize, total)
+ header := http.Header{}
+ header.Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", offset, end-1, total))
+ resp, err := c.send(ctx, http.MethodPut, uploadURL, content[offset:end], header, false)
+ if err != nil {
+ return err
+ }
+ switch resp.status {
+ case http.StatusOK, http.StatusCreated:
+ return nil
+ case http.StatusAccepted:
+ offset, err = nextExpectedOffset(resp.body, end)
+ case http.StatusRequestedRangeNotSatisfiable:
+ // The previous attempt of this chunk may have been received.
+ offset, err = c.uploadSessionOffset(ctx, uploadURL)
+ case http.StatusNotFound:
+ // The session is gone, possibly because the last chunk completed it.
+ return &unknownOutcomeError{cause: errors.New("the upload session no longer exists")}
+ default:
+ return newGraphError(resp)
+ }
+ if err != nil {
+ return err
+ }
+ if offset < 0 || offset >= total {
+ return &unknownOutcomeError{cause: errors.Errorf("the upload session expects an invalid offset %d", offset)}
+ }
+ }
+ return &unknownOutcomeError{cause: errors.New("the upload session did not complete")}
+}
+
+func (c *graphClient) uploadSessionOffset(ctx context.Context, uploadURL string) (int, error) {
+ resp, err := c.send(ctx, http.MethodGet, uploadURL, nil, nil, false)
+ if err != nil {
+ return 0, err
+ }
+ if resp.status != http.StatusOK {
+ return 0, &unknownOutcomeError{cause: newGraphError(resp)}
+ }
+ offset, err := nextExpectedOffset(resp.body, -1)
+ if err != nil || offset < 0 {
+ return 0, &unknownOutcomeError{cause: errors.New("the upload session status is invalid")}
+ }
+ return offset, nil
+}
+
+// nextExpectedOffset returns the start of the first range in an upload
+// session's nextExpectedRanges, or fallback when there is none.
+func nextExpectedOffset(body []byte, fallback int) (int, error) {
+ var status struct {
+ NextExpectedRanges []string `json:"nextExpectedRanges"`
+ }
+ if err := json.Unmarshal(body, &status); err != nil {
+ return 0, errors.Wrap(err, "failed to parse the upload session status")
+ }
+ if len(status.NextExpectedRanges) == 0 {
+ return fallback, nil
+ }
+ start, _, _ := strings.Cut(status.NextExpectedRanges[0], "-")
+ var offset int
+ if _, err := fmt.Sscanf(start, "%d", &offset); err != nil {
+ return 0, errors.Errorf("invalid upload range %q", status.NextExpectedRanges[0])
+ }
+ return offset, nil
+}
+
+// reconcile accepts an existing file as uploaded only if this application
+// created it with the same size; export folder names are unique per export.
+func (c *graphClient) reconcile(ctx context.Context, driveID, folderID string, file File, outcomeUnknown bool) error {
+ var item driveItem
+ err := c.graphJSON(ctx, http.MethodGet, itemPath(driveID, folderID)+":/"+escapeSegment(file.Name)+"?$select=size,folder,createdBy", nil, &item)
+ if err == nil && item.Folder == nil && item.Size == int64(len(file.Content)) &&
+ item.CreatedBy.Application != nil && strings.EqualFold(item.CreatedBy.Application.ID, c.clientID) {
+ return nil
+ }
+ var unknown *unknownOutcomeError
+ if outcomeUnknown || errors.As(err, &unknown) {
+ return errors.Wrapf(ErrUnconfirmed, "file %q", file.Name)
+ }
+ if err != nil {
+ return errors.Wrapf(err, "failed to check the existing file %q", file.Name)
+ }
+ return errors.Errorf("a different file named %q already exists in the SharePoint folder", file.Name)
+}
+
+func itemPath(driveID, itemID string) string {
+ return "/drives/" + escapeSegment(driveID) + "/items/" + escapeSegment(itemID)
+}
+
+// escapeSegment escapes one path segment. Graph treats ":" as the start of
+// path-based addressing, so it is escaped too.
+func escapeSegment(s string) string {
+ return strings.ReplaceAll(url.PathEscape(s), ":", "%3A")
+}
diff --git a/backend/plugin/sharepoint/client_live_test.go b/backend/plugin/sharepoint/client_live_test.go
new file mode 100644
index 0000000000..f3295074cc
--- /dev/null
+++ b/backend/plugin/sharepoint/client_live_test.go
@@ -0,0 +1,45 @@
+package sharepoint
+
+import (
+ "bytes"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+)
+
+// TestLiveSharePoint uploads a small export into a new subfolder of a real
+// destination. The application needs write access to that destination.
+func TestLiveSharePoint(t *testing.T) {
+ cfg := Config{
+ TenantID: os.Getenv("SHAREPOINT_TEST_TENANT_ID"),
+ ClientID: os.Getenv("SHAREPOINT_TEST_CLIENT_ID"),
+ ClientSecret: os.Getenv("SHAREPOINT_TEST_CLIENT_SECRET"),
+ }
+ rawURL := os.Getenv("SHAREPOINT_TEST_URL")
+ if cfg.TenantID == "" || cfg.ClientID == "" || cfg.ClientSecret == "" || rawURL == "" {
+ t.Skip("set SHAREPOINT_TEST_TENANT_ID, SHAREPOINT_TEST_CLIENT_ID, SHAREPOINT_TEST_CLIENT_SECRET, and SHAREPOINT_TEST_URL to run")
+ }
+ ctx := t.Context()
+ canonical, err := NormalizeURL(rawURL)
+ require.NoError(t, err)
+ client, err := NewClient(cfg)
+ require.NoError(t, err)
+ loc, err := client.Resolve(ctx, canonical)
+ require.NoError(t, err)
+ t.Logf("resolved %s", loc.WebURL)
+
+ folderName := "bytebase-live-test " + time.Now().UTC().Format("20060102T150405Z")
+ files := []File{
+ {Name: "statement.sql", Content: []byte("SELECT 1;\n")},
+ {Name: "result.csv", Content: bytes.Repeat([]byte("a,b\n"), uploadChunkSize/4+1)},
+ }
+ folder, err := client.Upload(ctx, loc, folderName, files)
+ require.NoError(t, err)
+ t.Logf("uploaded to %s", folder.WebURL)
+
+ again, err := client.Upload(ctx, loc, folderName, files)
+ require.NoError(t, err)
+ require.Equal(t, folder, again)
+}
diff --git a/backend/plugin/sharepoint/client_test.go b/backend/plugin/sharepoint/client_test.go
new file mode 100644
index 0000000000..7ca6f5a521
--- /dev/null
+++ b/backend/plugin/sharepoint/client_test.go
@@ -0,0 +1,494 @@
+package sharepoint
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/pkg/errors"
+ "github.com/stretchr/testify/require"
+)
+
+const testAppID = "11111111-2222-3333-4444-555555555555"
+
+func newTestClient(t *testing.T, handler http.Handler) (*graphClient, *[]time.Duration) {
+ t.Helper()
+ srv := httptest.NewServer(handler)
+ t.Cleanup(srv.Close)
+ var (
+ mu sync.Mutex
+ waits []time.Duration
+ )
+ client := &graphClient{
+ baseURL: srv.URL,
+ clientID: testAppID,
+ token: func(context.Context) (string, error) { return "test-token", nil },
+ httpClient: srv.Client(),
+ chunkSize: 4,
+ // Files larger than 4 bytes use upload sessions, and uploads run one
+ // at a time so tests can assert their order.
+ simpleUploadMaxSize: 4,
+ maxConcurrentUploads: 1,
+ maxAttempts: 3,
+ wait: func(_ context.Context, d time.Duration) error {
+ mu.Lock()
+ defer mu.Unlock()
+ waits = append(waits, d)
+ return nil
+ },
+ }
+ return client, &waits
+}
+
+func writeJSON(w http.ResponseWriter, status int, body any) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(body)
+}
+
+func writeGraphError(w http.ResponseWriter, status int, code string) {
+ writeJSON(w, status, map[string]any{"error": map[string]any{"code": code, "message": code}})
+}
+
+// resolveShareURL is the decoded form of the URL every resolve test asks for.
+const resolveShareURL = "https://contoso.sharepoint.com/sites/finance/Shared Documents/My Exports/project a"
+
+func resolveServer(t *testing.T, itemStatus int, item map[string]any) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ require.Equal(t, "Bearer test-token", r.Header.Get("Authorization"))
+ shareID := "u!" + base64.RawURLEncoding.EncodeToString([]byte(resolveShareURL))
+ switch r.URL.Path {
+ case "/shares/" + shareID + "/driveItem":
+ require.Equal(t, "id,webUrl,folder,root,parentReference", r.URL.Query().Get("$select"))
+ if itemStatus != http.StatusOK {
+ writeGraphError(w, itemStatus, "accessDenied")
+ return
+ }
+ writeJSON(w, http.StatusOK, item)
+ default:
+ t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
+ writeGraphError(w, http.StatusNotFound, "itemNotFound")
+ }
+ })
+}
+
+func TestResolve(t *testing.T) {
+ const canonical = "https://contoso.sharepoint.com/sites/finance/Shared%20Documents/My%20Exports/project%20a"
+ parent := map[string]any{"driveId": "d1"}
+
+ t.Run("library root", func(t *testing.T) {
+ client, _ := newTestClient(t, resolveServer(t, http.StatusOK, map[string]any{
+ "id": "root1", "name": "root", "webUrl": "https://contoso.sharepoint.com/sites/finance/Shared%20Documents",
+ "folder": map[string]any{"childCount": 2}, "root": map[string]any{}, "parentReference": parent,
+ }))
+ loc, err := client.Resolve(context.Background(), canonical)
+ require.NoError(t, err)
+ require.Equal(t, &Location{DriveID: "d1", ItemID: "root1", WebURL: "https://contoso.sharepoint.com/sites/finance/Shared%20Documents"}, loc)
+ })
+
+ t.Run("folder", func(t *testing.T) {
+ client, _ := newTestClient(t, resolveServer(t, http.StatusOK, map[string]any{
+ "id": "item1", "name": "project a", "webUrl": canonical, "folder": map[string]any{"childCount": 0}, "parentReference": parent,
+ }))
+ loc, err := client.Resolve(context.Background(), canonical)
+ require.NoError(t, err)
+ require.Equal(t, &Location{DriveID: "d1", ItemID: "item1", WebURL: canonical}, loc)
+ })
+
+ t.Run("file", func(t *testing.T) {
+ client, _ := newTestClient(t, resolveServer(t, http.StatusOK, map[string]any{
+ "id": "item1", "name": "project a", "file": map[string]any{}, "parentReference": parent,
+ }))
+ _, err := client.Resolve(context.Background(), canonical)
+ require.ErrorContains(t, err, "is a file")
+ })
+
+ t.Run("forbidden", func(t *testing.T) {
+ client, _ := newTestClient(t, resolveServer(t, http.StatusForbidden, nil))
+ _, err := client.Resolve(context.Background(), canonical)
+ require.ErrorIs(t, err, ErrNotFoundOrNoAccess)
+ })
+
+ t.Run("unauthorized", func(t *testing.T) {
+ client, _ := newTestClient(t, resolveServer(t, http.StatusUnauthorized, nil))
+ _, err := client.Resolve(context.Background(), canonical)
+ require.ErrorIs(t, err, ErrCredential)
+ })
+}
+
+type fakeFile struct {
+ content []byte
+ appID string
+}
+
+type fakeSession struct {
+ key string
+ data []byte
+}
+
+// fakeGraph serves a library root "dest" in drive "d1".
+type fakeGraph struct {
+ t *testing.T
+ mu sync.Mutex
+ // folderIDs maps folder IDs to names.
+ folderIDs map[string]string
+ // files is keyed by "folderName/fileName".
+ files map[string]fakeFile
+ sessions map[string]*fakeSession
+ sessionCount int
+ requestCount int
+ contentRanges []string
+ // override handles a request instead of the fake when it returns true.
+ override func(w http.ResponseWriter, r *http.Request) bool
+ // dropUploadResponse stores the next chunk and then drops the connection.
+ dropUploadResponse bool
+}
+
+func newFakeGraph(t *testing.T) *fakeGraph {
+ return &fakeGraph{t: t, folderIDs: map[string]string{}, files: map[string]fakeFile{}, sessions: map[string]*fakeSession{}}
+}
+
+func (f *fakeGraph) folderID(name string) string {
+ for id, folderName := range f.folderIDs {
+ if folderName == name {
+ return id
+ }
+ }
+ return ""
+}
+
+func (f *fakeGraph) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.requestCount++
+ if f.override != nil && f.override(w, r) {
+ return
+ }
+ if strings.HasPrefix(r.URL.Path, "/upload/") {
+ f.serveUpload(w, r)
+ return
+ }
+ require.Equal(f.t, "Bearer test-token", r.Header.Get("Authorization"))
+ rest, ok := strings.CutPrefix(r.URL.Path, "/drives/d1/items/")
+ if !ok {
+ writeGraphError(w, http.StatusNotFound, "itemNotFound")
+ return
+ }
+ if rest == "dest/children" && r.Method == http.MethodPost {
+ var body map[string]any
+ require.NoError(f.t, json.NewDecoder(r.Body).Decode(&body))
+ require.Equal(f.t, "fail", body["@microsoft.graph.conflictBehavior"])
+ name, ok := body["name"].(string)
+ require.True(f.t, ok)
+ if f.folderID(name) != "" {
+ writeGraphError(w, http.StatusConflict, "nameAlreadyExists")
+ return
+ }
+ id := fmt.Sprintf("folder%d", len(f.folderIDs)+1)
+ f.folderIDs[id] = name
+ writeJSON(w, http.StatusCreated, map[string]any{"id": id, "name": name, "webUrl": "https://sp/" + id, "folder": map[string]any{}})
+ return
+ }
+ itemID, sub, _ := strings.Cut(rest, ":/")
+ if itemID == "dest" && r.Method == http.MethodGet {
+ id := f.folderID(sub)
+ if id == "" {
+ writeGraphError(w, http.StatusNotFound, "itemNotFound")
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"id": id, "webUrl": "https://sp/" + id, "folder": map[string]any{}})
+ return
+ }
+ folderName, ok := f.folderIDs[itemID]
+ if !ok {
+ writeGraphError(w, http.StatusNotFound, "itemNotFound")
+ return
+ }
+ switch {
+ case r.Method == http.MethodPost && strings.HasSuffix(sub, ":/createUploadSession"):
+ key := folderName + "/" + strings.TrimSuffix(sub, ":/createUploadSession")
+ if _, exists := f.files[key]; exists {
+ writeGraphError(w, http.StatusConflict, "nameAlreadyExists")
+ return
+ }
+ f.sessionCount++
+ id := fmt.Sprint(f.sessionCount)
+ f.sessions[id] = &fakeSession{key: key}
+ writeJSON(w, http.StatusOK, map[string]any{"uploadUrl": "http://" + r.Host + "/upload/" + id + "?tempauth=secret"})
+ case r.Method == http.MethodPut && strings.HasSuffix(sub, ":/content"):
+ key := folderName + "/" + strings.TrimSuffix(sub, ":/content")
+ if _, exists := f.files[key]; exists {
+ writeGraphError(w, http.StatusConflict, "nameAlreadyExists")
+ return
+ }
+ data, _ := io.ReadAll(r.Body)
+ f.files[key] = fakeFile{content: data, appID: testAppID}
+ writeJSON(w, http.StatusCreated, map[string]any{"id": key})
+ case r.Method == http.MethodGet:
+ file, exists := f.files[folderName+"/"+sub]
+ if !exists {
+ writeGraphError(w, http.StatusNotFound, "itemNotFound")
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{
+ "size": len(file.content),
+ "createdBy": map[string]any{"application": map[string]any{"id": file.appID}},
+ })
+ default:
+ f.t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
+ writeGraphError(w, http.StatusBadRequest, "invalidRequest")
+ }
+}
+
+func (f *fakeGraph) serveUpload(w http.ResponseWriter, r *http.Request) {
+ require.Empty(f.t, r.Header.Get("Authorization"))
+ session, ok := f.sessions[strings.TrimPrefix(r.URL.Path, "/upload/")]
+ if !ok {
+ writeGraphError(w, http.StatusNotFound, "itemNotFound")
+ return
+ }
+ if r.Method == http.MethodGet {
+ writeJSON(w, http.StatusOK, map[string]any{"nextExpectedRanges": []string{fmt.Sprintf("%d-", len(session.data))}})
+ return
+ }
+ contentRange := r.Header.Get("Content-Range")
+ var start, end, total int
+ _, err := fmt.Sscanf(contentRange, "bytes %d-%d/%d", &start, &end, &total)
+ require.NoError(f.t, err)
+ data, err := io.ReadAll(r.Body)
+ require.NoError(f.t, err)
+ require.Len(f.t, data, end-start+1)
+ if start != len(session.data) {
+ writeGraphError(w, http.StatusRequestedRangeNotSatisfiable, "invalidRange")
+ return
+ }
+ f.contentRanges = append(f.contentRanges, contentRange)
+ session.data = append(session.data, data...)
+ if f.dropUploadResponse {
+ f.dropUploadResponse = false
+ conn, _, err := w.(http.Hijacker).Hijack()
+ require.NoError(f.t, err)
+ _ = conn.Close()
+ return
+ }
+ if len(session.data) < total {
+ writeJSON(w, http.StatusAccepted, map[string]any{"nextExpectedRanges": []string{fmt.Sprintf("%d-", len(session.data))}})
+ return
+ }
+ f.files[session.key] = fakeFile{content: session.data, appID: testAppID}
+ writeJSON(w, http.StatusCreated, map[string]any{"id": session.key})
+}
+
+const testFolder = "20261022T010203Z [email protected] db 42"
+
+var (
+ testLocation = &Location{DriveID: "d1", ItemID: "dest"}
+ testFiles = []File{
+ {Name: "statement.sql", Content: []byte("SELECT 1;\n")},
+ {Name: "result #1.csv", Content: []byte("a,b\n1,2\n")},
+ {Name: "empty.json", Content: []byte{}},
+ }
+)
+
+func requireUploaded(t *testing.T, fake *fakeGraph) {
+ t.Helper()
+ for _, file := range testFiles {
+ got, ok := fake.files[testFolder+"/"+file.Name]
+ require.True(t, ok, file.Name)
+ require.Equal(t, string(file.Content), string(got.content))
+ }
+}
+
+func TestUpload(t *testing.T) {
+ fake := newFakeGraph(t)
+ client, waits := newTestClient(t, fake)
+ folder, err := client.Upload(context.Background(), testLocation, testFolder, testFiles)
+ require.NoError(t, err)
+ require.Equal(t, &Folder{Name: testFolder, WebURL: "https://sp/folder1"}, folder)
+ requireUploaded(t, fake)
+ require.Equal(t, []string{
+ "bytes 0-3/10", "bytes 4-7/10", "bytes 8-9/10",
+ "bytes 0-3/8", "bytes 4-7/8",
+ }, fake.contentRanges)
+ require.Empty(t, *waits)
+
+ // Retrying the same export reuses the folder and the uploaded files.
+ folder, err = client.Upload(context.Background(), testLocation, testFolder, testFiles)
+ require.NoError(t, err)
+ require.Equal(t, &Folder{Name: testFolder, WebURL: "https://sp/folder1"}, folder)
+ require.Len(t, fake.folderIDs, 1)
+ require.Equal(t, 2, fake.sessionCount)
+}
+
+func TestUploadReusesExistingFolder(t *testing.T) {
+ fake := newFakeGraph(t)
+ fake.folderIDs["existing"] = testFolder
+ client, _ := newTestClient(t, fake)
+ folder, err := client.Upload(context.Background(), testLocation, testFolder, testFiles)
+ require.NoError(t, err)
+ require.Equal(t, "https://sp/existing", folder.WebURL)
+ requireUploaded(t, fake)
+}
+
+func TestUploadFileConflict(t *testing.T) {
+ files := []File{{Name: "result.csv", Content: []byte("a,b\n")}}
+ tests := []struct {
+ name string
+ existing fakeFile
+ wantErr string
+ }{
+ {name: "uploaded by this application", existing: fakeFile{content: []byte("x,y\n"), appID: testAppID}},
+ {name: "different application", existing: fakeFile{content: []byte("a,b\n"), appID: "someone-else"}, wantErr: "a different file named"},
+ {name: "different size", existing: fakeFile{content: []byte("a,b,c\n"), appID: testAppID}, wantErr: "a different file named"},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ fake := newFakeGraph(t)
+ fake.folderIDs["existing"] = testFolder
+ fake.files[testFolder+"/result.csv"] = tc.existing
+ client, _ := newTestClient(t, fake)
+ _, err := client.Upload(context.Background(), testLocation, testFolder, files)
+ require.Zero(t, fake.sessionCount)
+ if tc.wantErr == "" {
+ require.NoError(t, err)
+ return
+ }
+ require.ErrorContains(t, err, tc.wantErr)
+ require.NotErrorIs(t, err, ErrUnconfirmed)
+ require.NotErrorIs(t, err, ErrNothingUploaded)
+ })
+ }
+}
+
+func TestUploadFolderCreationFailureUploadsNothing(t *testing.T) {
+ fake := newFakeGraph(t)
+ fake.override = func(w http.ResponseWriter, r *http.Request) bool {
+ if r.URL.Path != "/drives/d1/items/dest/children" {
+ return false
+ }
+ writeGraphError(w, http.StatusForbidden, "accessDenied")
+ return true
+ }
+ client, _ := newTestClient(t, fake)
+ _, err := client.Upload(context.Background(), testLocation, testFolder, testFiles)
+ require.ErrorIs(t, err, ErrNothingUploaded)
+ require.ErrorIs(t, err, ErrNotFoundOrNoAccess)
+ require.Zero(t, fake.sessionCount)
+}
+
+func TestUploadHonorsRetryAfter(t *testing.T) {
+ fake := newFakeGraph(t)
+ throttled := false
+ fake.override = func(w http.ResponseWriter, r *http.Request) bool {
+ if throttled || r.URL.Path != "/drives/d1/items/dest/children" {
+ return false
+ }
+ throttled = true
+ w.Header().Set("Retry-After", "2")
+ writeGraphError(w, http.StatusTooManyRequests, "activityLimitReached")
+ return true
+ }
+ client, waits := newTestClient(t, fake)
+ _, err := client.Upload(context.Background(), testLocation, testFolder, testFiles)
+ require.NoError(t, err)
+ require.Equal(t, []time.Duration{2 * time.Second}, *waits)
+ requireUploaded(t, fake)
+}
+
+func TestUploadResumesAfterLostChunkResponse(t *testing.T) {
+ fake := newFakeGraph(t)
+ fake.override = func(_ http.ResponseWriter, r *http.Request) bool {
+ if r.Method == http.MethodPut && r.Header.Get("Content-Range") == "bytes 4-7/10" && len(fake.contentRanges) == 1 {
+ fake.dropUploadResponse = true
+ }
+ return false
+ }
+ client, waits := newTestClient(t, fake)
+ _, err := client.Upload(context.Background(), testLocation, testFolder, testFiles)
+ require.NoError(t, err)
+ requireUploaded(t, fake)
+ require.Equal(t, []time.Duration{time.Second}, *waits)
+}
+
+func TestUploadUnconfirmed(t *testing.T) {
+ fake := newFakeGraph(t)
+ fake.override = func(w http.ResponseWriter, r *http.Request) bool {
+ if !strings.HasPrefix(r.URL.Path, "/upload/") {
+ return false
+ }
+ writeGraphError(w, http.StatusGatewayTimeout, "gatewayTimeout")
+ return true
+ }
+ client, waits := newTestClient(t, fake)
+ _, err := client.Upload(context.Background(), testLocation, testFolder, testFiles)
+ require.ErrorIs(t, err, ErrUnconfirmed)
+ require.ErrorContains(t, err, "statement.sql")
+ require.NotContains(t, err.Error(), "tempauth")
+ require.Equal(t, []time.Duration{time.Second, 2 * time.Second}, *waits)
+}
+
+func TestUploadForbidden(t *testing.T) {
+ client, _ := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ writeGraphError(w, http.StatusForbidden, "accessDenied")
+ }))
+ _, err := client.Upload(context.Background(), testLocation, testFolder, testFiles)
+ require.ErrorIs(t, err, ErrNotFoundOrNoAccess)
+}
+
+func TestTransportErrorOmitsURL(t *testing.T) {
+ client, _ := newTestClient(t, http.NotFoundHandler())
+ client.maxAttempts = 1
+ _, err := client.send(context.Background(), http.MethodPut, "http://127.0.0.1:1/upload/1?tempauth=secret", []byte("x"), nil, false)
+ var unknown *unknownOutcomeError
+ require.True(t, errors.As(err, &unknown))
+ require.NotContains(t, err.Error(), "tempauth")
+}
+
+func TestUploadSmallFilesInOneRequestEach(t *testing.T) {
+ fake := newFakeGraph(t)
+ client, _ := newTestClient(t, fake)
+ client.simpleUploadMaxSize = simpleUploadMaxSize
+ _, err := client.Upload(context.Background(), testLocation, testFolder, testFiles)
+ require.NoError(t, err)
+ requireUploaded(t, fake)
+ require.Zero(t, fake.sessionCount)
+ // One request creates the folder and one uploads each file.
+ require.Equal(t, 1+len(testFiles), fake.requestCount)
+}
+
+func TestUploadInParallel(t *testing.T) {
+ files := []File{{Name: "a.sql", Content: []byte("a")}, {Name: "b.csv", Content: []byte("b")}, {Name: "c.json", Content: []byte("c")}}
+ var mu sync.Mutex
+ inFlight := 0
+ allInFlight := make(chan struct{})
+ client, _ := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodPost {
+ writeJSON(w, http.StatusCreated, map[string]any{"id": "folder1", "webUrl": "https://sp/folder1", "folder": map[string]any{}})
+ return
+ }
+ mu.Lock()
+ inFlight++
+ if inFlight == len(files) {
+ close(allInFlight)
+ }
+ mu.Unlock()
+ select {
+ case <-allInFlight:
+ writeJSON(w, http.StatusCreated, map[string]any{"id": r.URL.Path})
+ case <-time.After(5 * time.Second):
+ writeGraphError(w, http.StatusBadRequest, "uploadsNotConcurrent")
+ }
+ }))
+ client.simpleUploadMaxSize = simpleUploadMaxSize
+ client.maxConcurrentUploads = len(files)
+ _, err := client.Upload(context.Background(), testLocation, testFolder, files)
+ require.NoError(t, err)
+}
diff --git a/backend/plugin/sharepoint/sharepoint.go b/backend/plugin/sharepoint/sharepoint.go
new file mode 100644
index 0000000000..c239acbd2c
--- /dev/null
+++ b/backend/plugin/sharepoint/sharepoint.go
@@ -0,0 +1,96 @@
+// Package sharepoint uploads export files to a SharePoint document library
+// through Microsoft Graph, authenticating as a workspace's Entra application.
+package sharepoint
+
+import (
+ "context"
+ "sync"
+
+ "github.com/pkg/errors"
+)
+
+// Config is the workspace's Entra application.
+type Config struct {
+ TenantID string
+ ClientID string
+ ClientSecret string
+}
+
+// Location is a document library root or folder that a URL resolved to.
+type Location struct {
+ DriveID string
+ ItemID string
+ WebURL string
+}
+
+// File is one file of an export.
+type File struct {
+ Name string
+ Content []byte
+}
+
+// Folder is the folder an export was uploaded into.
+type Folder struct {
+ Name string
+ WebURL string
+}
+
+var (
+ // ErrNotFoundOrNoAccess means the destination does not exist or the
+ // application cannot access it. SharePoint does not distinguish the two.
+ ErrNotFoundOrNoAccess = errors.New("the SharePoint destination does not exist or Bytebase cannot access it")
+ // ErrCredential means Entra rejected the application's credentials.
+ ErrCredential = errors.New("Microsoft Entra rejected the SharePoint application credentials")
+ // ErrUnconfirmed means an upload could not be confirmed after retries and
+ // reconciliation; some files may exist in SharePoint.
+ ErrUnconfirmed = errors.New("the upload to SharePoint could not be confirmed; files may exist in the destination")
+ // ErrNothingUploaded marks an Upload failure before any file was
+ // uploaded. It wraps the cause, so errors.Is still matches the cause.
+ ErrNothingUploaded = errors.New("nothing was uploaded to SharePoint")
+)
+
+type nothingUploadedError struct{ err error }
+
+func (e *nothingUploadedError) Error() string { return e.err.Error() }
+func (e *nothingUploadedError) Unwrap() error { return e.err }
+func (*nothingUploadedError) Is(target error) bool { return target == ErrNothingUploaded }
+
+// Client resolves destinations and uploads exports.
+type Client interface {
+ // Resolve resolves a canonical URL from NormalizeURL to a library root or
+ // folder. Resolving proves only that the destination is readable.
+ Resolve(ctx context.Context, canonicalURL string) (*Location, error)
+ // Upload creates folderName under loc and uploads files into it. Retrying
+ // Upload with the same arguments reuses the folder and files already
+ // uploaded by the application instead of creating copies.
+ Upload(ctx context.Context, loc *Location, folderName string, files []File) (*Folder, error)
+}
+
+type cachedClient struct {
+ cfg Config
+ client Client
+}
+
+var (
+ clientsMu sync.Mutex
+ // clients holds one client per Entra application, so exports reuse its
+ // cached access token.
+ clients = map[string]cachedClient{}
+)
+
+// NewClient returns a Client for the Microsoft global commercial cloud. It
+// returns the same Client for the same Config until the Config changes.
+func NewClient(cfg Config) (Client, error) {
+ key := cfg.TenantID + "/" + cfg.ClientID
+ clientsMu.Lock()
+ defer clientsMu.Unlock()
+ if cached, ok := clients[key]; ok && cached.cfg == cfg {
+ return cached.client, nil
+ }
+ client, err := newGraphClient(cfg)
+ if err != nil {
+ return nil, err
+ }
+ clients[key] = cachedClient{cfg: cfg, client: client}
+ return client, nil
+}
diff --git a/backend/plugin/sharepoint/transport.go b/backend/plugin/sharepoint/transport.go
new file mode 100644
index 0000000000..5402d15949
--- /dev/null
+++ b/backend/plugin/sharepoint/transport.go
@@ -0,0 +1,227 @@
+package sharepoint
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "strconv"
+ "time"
+
+ "github.com/pkg/errors"
+)
+
+const (
+ maxResponseBytes = 4 << 20
+ maxRetryDelay = 2 * time.Minute
+ maxBackoff = 30 * time.Second
+)
+
+type response struct {
+ status int
+ header http.Header
+ body []byte
+}
+
+// unknownOutcomeError means a request may or may not have taken effect.
+type unknownOutcomeError struct {
+ cause error
+}
+
+func (e *unknownOutcomeError) Error() string {
+ return "could not reach Microsoft Graph: " + e.cause.Error()
+}
+
+func (e *unknownOutcomeError) Unwrap() error {
+ return e.cause
+}
+
+type graphError struct {
+ status int
+ code string
+ message string
+}
+
+func newGraphError(resp *response) *graphError {
+ var body struct {
+ Error struct {
+ Code string `json:"code"`
+ Message string `json:"message"`
+ } `json:"error"`
+ }
+ _ = json.Unmarshal(resp.body, &body)
+ return &graphError{status: resp.status, code: body.Error.Code, message: body.Error.Message}
+}
+
+func (e *graphError) sentinel() error {
+ switch e.status {
+ case http.StatusUnauthorized:
+ return ErrCredential
+ case http.StatusForbidden, http.StatusNotFound:
+ return ErrNotFoundOrNoAccess
+ default:
+ return nil
+ }
+}
+
+func (e *graphError) Error() string {
+ detail := fmt.Sprintf("Microsoft Graph returned HTTP %d", e.status)
+ if e.code != "" {
+ detail += " " + e.code
+ }
+ if e.message != "" {
+ detail += ": " + e.message
+ }
+ if sentinel := e.sentinel(); sentinel != nil {
+ return sentinel.Error() + " (" + detail + ")"
+ }
+ return detail
+}
+
+func (e *graphError) Unwrap() error {
+ return e.sentinel()
+}
+
+func statusOf(err error) int {
+ var graphErr *graphError
+ if errors.As(err, &graphErr) {
+ return graphErr.status
+ }
+ return 0
+}
+
+// graphJSON calls a Graph API path with an optional JSON body and decodes a
+// successful JSON response into out.
+func (c *graphClient) graphJSON(ctx context.Context, method, path string, in, out any) error {
+ var body []byte
+ header := http.Header{}
+ if in != nil {
+ data, err := json.Marshal(in)
+ if err != nil {
+ return errors.Wrap(err, "failed to encode Microsoft Graph request")
+ }
+ body = data
+ header.Set("Content-Type", "application/json")
+ }
+ resp, err := c.send(ctx, method, c.baseURL+path, body, header, true)
+ if err != nil {
+ return err
+ }
+ if resp.status < 200 || resp.status >= 300 {
+ return newGraphError(resp)
+ }
+ if out != nil {
+ if err := json.Unmarshal(resp.body, out); err != nil {
+ return errors.Wrap(err, "failed to parse Microsoft Graph response")
+ }
+ }
+ return nil
+}
+
+// graphRaw calls a Graph API path with a binary body and ignores a successful
+// response's body.
+func (c *graphClient) graphRaw(ctx context.Context, method, path string, body []byte) error {
+ header := http.Header{}
+ header.Set("Content-Type", "application/octet-stream")
+ resp, err := c.send(ctx, method, c.baseURL+path, body, header, true)
+ if err != nil {
+ return err
+ }
+ if resp.status < 200 || resp.status >= 300 {
+ return newGraphError(resp)
+ }
+ return nil
+}
+
+// send sends a request, retrying throttling, unavailability, and transport
+// errors. If any attempt's outcome is unknown and the retries do not produce a
+// response, the error is an *unknownOutcomeError.
+func (c *graphClient) send(ctx context.Context, method, target string, body []byte, header http.Header, authorize bool) (*response, error) {
+ outcomeUnknown := false
+ for attempt := 1; ; attempt++ {
+ resp, err := c.sendOnce(ctx, method, target, body, header, authorize)
+ var lastErr error
+ switch {
+ case err != nil:
+ var unknown *unknownOutcomeError
+ if !errors.As(err, &unknown) {
+ return nil, err
+ }
+ outcomeUnknown = true
+ lastErr = unknown.cause
+ if ctx.Err() != nil {
+ return nil, err
+ }
+ case resp.status == http.StatusTooManyRequests:
+ lastErr = newGraphError(resp)
+ case resp.status == http.StatusServiceUnavailable || resp.status == http.StatusGatewayTimeout:
+ outcomeUnknown = true
+ lastErr = newGraphError(resp)
+ default:
+ return resp, nil
+ }
+ if attempt >= c.maxAttempts {
+ if outcomeUnknown {
+ return nil, &unknownOutcomeError{cause: lastErr}
+ }
+ return nil, lastErr
+ }
+ if err := c.wait(ctx, retryDelay(resp, attempt)); err != nil {
+ return nil, &unknownOutcomeError{cause: err}
+ }
+ }
+}
+
+func (c *graphClient) sendOnce(ctx context.Context, method, target string, body []byte, header http.Header, authorize bool) (*response, error) {
+ var reader io.Reader
+ if body != nil {
+ reader = bytes.NewReader(body)
+ }
+ req, err := http.NewRequestWithContext(ctx, method, target, reader)
+ if err != nil {
+ // The error would include the URL, which may be a pre-authenticated upload URL.
+ return nil, errors.New("invalid Microsoft Graph request URL")
+ }
+ for key, values := range header {
+ req.Header[key] = values
+ }
+ req.Header.Set("Accept", "application/json")
+ if authorize {
+ token, err := c.token(ctx)
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Authorization", "Bearer "+token)
+ }
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return nil, &unknownOutcomeError{cause: transportError(err)}
+ }
+ defer resp.Body.Close()
+ data, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes))
+ if err != nil {
+ return nil, &unknownOutcomeError{cause: transportError(err)}
+ }
+ return &response{status: resp.StatusCode, header: resp.Header, body: data}, nil
+}
+
+// transportError drops the request URL from err.
+func transportError(err error) error {
+ var urlErr *url.Error
+ if errors.As(err, &urlErr) {
+ return errors.Errorf("%s request failed: %v", urlErr.Op, urlErr.Err)
+ }
+ return err
+}
+
+func retryDelay(resp *response, attempt int) time.Duration {
+ if resp != nil {
+ if seconds, err := strconv.Atoi(resp.header.Get("Retry-After")); err == nil && seconds >= 0 {
+ return min(time.Duration(seconds)*time.Second, maxRetryDelay)
+ }
+ }
+ return min(time.Second<<(attempt-1), maxBackoff)
+}
diff --git a/backend/plugin/sharepoint/url.go b/backend/plugin/sharepoint/url.go
new file mode 100644
index 0000000000..e562db2e5c
--- /dev/null
+++ b/backend/plugin/sharepoint/url.go
@@ -0,0 +1,77 @@
+package sharepoint
+
+import (
+ "net/url"
+ "regexp"
+ "strings"
+
+ "github.com/pkg/errors"
+)
+
+var (
+ // copiedLinkPattern matches links copied from SharePoint, such as
+ // /:f:/r/sites/finance/Exports (a path) or /:f:/s/finance/EaBc (a token).
+ copiedLinkPattern = regexp.MustCompile(`^/:[A-Za-z]:/([^/]*)(/.*)?$`)
+ libraryViewPattern = regexp.MustCompile(`(?i)/Forms/[^/]+\.aspx$`)
+)
+
+// NormalizeURL returns the canonical URL of a SharePoint library root or folder
+// from a URL pasted from a browser.
+func NormalizeURL(raw string) (string, error) {
+ u, err := url.Parse(strings.TrimSpace(raw))
+ if err != nil || u.Host == "" {
+ return "", errors.New("enter the full SharePoint URL of a document library or folder, starting with https://")
+ }
+ if u.Scheme != "https" {
+ return "", errors.New("the SharePoint URL must start with https://")
+ }
+ if u.User != nil || u.Port() != "" {
+ return "", errors.New("the SharePoint URL must not contain a user name or port")
+ }
+ host := strings.ToLower(u.Hostname())
+ tenant, ok := strings.CutSuffix(host, ".sharepoint.com")
+ if !ok || tenant == "" || strings.Contains(tenant, ".") {
+ return "", errors.Errorf("%q is not a SharePoint Online host; the URL must be on a *.sharepoint.com host", host)
+ }
+ if strings.HasSuffix(tenant, "-my") {
+ return "", errors.New("OneDrive URLs are not supported; use a document library or folder on a SharePoint site")
+ }
+
+ p := u.Path
+ if m := copiedLinkPattern.FindStringSubmatch(p); m != nil {
+ if !strings.EqualFold(m[1], "r") {
+ return "", errors.New("sharing links are not supported; open the folder in SharePoint and paste the URL from the browser's address bar")
+ }
+ p = m[2]
+ } else if strings.HasSuffix(strings.ToLower(p), ".aspx") {
+ query := u.Query()
+ if id := query.Get("id"); id != "" {
+ p = id
+ } else if rootFolder := query.Get("RootFolder"); rootFolder != "" {
+ p = rootFolder
+ } else {
+ p = libraryViewPattern.ReplaceAllString(p, "")
+ }
+ }
+
+ var segments []string
+ for _, segment := range strings.Split(p, "/") {
+ switch {
+ case segment == "":
+ case segment == "." || segment == "..":
+ return "", errors.New("the SharePoint URL must not contain . or .. path segments")
+ case strings.EqualFold(segment, "_layouts") || strings.HasSuffix(strings.ToLower(segment), ".aspx"):
+ return "", errors.New("the SharePoint URL is a page, not a document library or folder; open the folder in SharePoint and paste the URL from the browser's address bar")
+ default:
+ segments = append(segments, segment)
+ }
+ }
+ if len(segments) == 0 {
+ return "", errors.New("the SharePoint URL points to a site, not a document library or folder")
+ }
+ if first := strings.ToLower(segments[0]); (first == "sites" || first == "teams") && len(segments) <= 2 {
+ return "", errors.New("the SharePoint URL points to a site, not a document library or folder")
+ }
+ canonical := url.URL{Scheme: "https", Host: host, Path: "/" + strings.Join(segments, "/")}
+ return canonical.String(), nil
+}
diff --git a/backend/plugin/sharepoint/url_test.go b/backend/plugin/sharepoint/url_test.go
new file mode 100644
index 0000000000..7a30316f1e
--- /dev/null
+++ b/backend/plugin/sharepoint/url_test.go
@@ -0,0 +1,113 @@
+package sharepoint
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestNormalizeURL(t *testing.T) {
+ tests := []struct {
+ name string
+ raw string
+ want string
+ wantErr string
+ }{
+ {
+ name: "site folder",
+ raw: "https://contoso.sharepoint.com/sites/finance/Exports/project-a",
+ want: "https://contoso.sharepoint.com/sites/finance/Exports/project-a",
+ },
+ {
+ name: "root site folder",
+ raw: "https://contoso.sharepoint.com/Exports/project-a",
+ want: "https://contoso.sharepoint.com/Exports/project-a",
+ },
+ {
+ name: "root site library",
+ raw: "https://contoso.sharepoint.com/Shared%20Documents",
+ want: "https://contoso.sharepoint.com/Shared%20Documents",
+ },
+ {
+ name: "teams site library",
+ raw: "https://contoso.sharepoint.com/teams/data/Exports",
+ want: "https://contoso.sharepoint.com/teams/data/Exports",
+ },
+ {
+ name: "multi-geo host and uppercase host",
+ raw: "https://Contoso-EU.SharePoint.com/sites/finance/Exports",
+ want: "https://contoso-eu.sharepoint.com/sites/finance/Exports",
+ },
+ {
+ name: "query, fragment, duplicate and trailing slashes",
+ raw: " https://contoso.sharepoint.com//sites/finance//Exports/project-a/?web=1#top ",
+ want: "https://contoso.sharepoint.com/sites/finance/Exports/project-a",
+ },
+ {
+ name: "spaces and unicode",
+ raw: "https://contoso.sharepoint.com/sites/finance/Shared Documents/Q1 报表",
+ want: "https://contoso.sharepoint.com/sites/finance/Shared%20Documents/Q1%20%E6%8A%A5%E8%A1%A8",
+ },
+ {
+ name: "library view with id",
+ raw: "https://contoso.sharepoint.com/sites/finance/Exports/Forms/AllItems.aspx?id=%2Fsites%2Ffinance%2FExports%2Fproject%20a&viewid=6c2b3f0e-0000-0000-0000-000000000000",
+ want: "https://contoso.sharepoint.com/sites/finance/Exports/project%20a",
+ },
+ {
+ name: "root site library view with id",
+ raw: "https://contoso.sharepoint.com/Exports/Forms/AllItems.aspx?id=%2FExports%2Fproject-a",
+ want: "https://contoso.sharepoint.com/Exports/project-a",
+ },
+ {
+ name: "library view without id",
+ raw: "https://contoso.sharepoint.com/sites/finance/Shared%20Documents/Forms/AllItems.aspx",
+ want: "https://contoso.sharepoint.com/sites/finance/Shared%20Documents",
+ },
+ {
+ name: "copied folder link",
+ raw: "https://contoso.sharepoint.com/:f:/r/sites/finance/Exports/project-a?csf=1&web=1&e=AbCdEf",
+ want: "https://contoso.sharepoint.com/sites/finance/Exports/project-a",
+ },
+ {
+ name: "copied link with another type",
+ raw: "https://contoso.sharepoint.com/:u:/r/sites/finance/Exports",
+ want: "https://contoso.sharepoint.com/sites/finance/Exports",
+ },
+ {
+ name: "canonical URL is stable",
+ raw: "https://contoso.sharepoint.com/sites/finance/Shared%20Documents/Q1%20%E6%8A%A5%E8%A1%A8",
+ want: "https://contoso.sharepoint.com/sites/finance/Shared%20Documents/Q1%20%E6%8A%A5%E8%A1%A8",
+ },
+ {name: "token sharing link", raw: "https://contoso.sharepoint.com/:x:/s/finance/EaBcDeF", wantErr: "sharing links are not supported"},
+ {name: "guest sharing link", raw: "https://contoso.sharepoint.com/:x:/g/finance/EaBcDeF", wantErr: "browser's address bar"},
+ {name: "http", raw: "http://contoso.sharepoint.com/sites/finance/Exports", wantErr: "https://"},
+ {name: "not sharepoint", raw: "https://contoso.example.com/sites/finance/Exports", wantErr: "not a SharePoint Online host"},
+ {name: "lookalike host", raw: "https://contoso.sharepoint.com.evil.com/sites/finance/Exports", wantErr: "not a SharePoint Online host"},
+ {name: "bare sharepoint host", raw: "https://sharepoint.com/sites/finance/Exports", wantErr: "not a SharePoint Online host"},
+ {name: "onedrive", raw: "https://contoso-my.sharepoint.com/personal/alice_contoso_com/Documents", wantErr: "OneDrive"},
+ {name: "port", raw: "https://contoso.sharepoint.com:8443/sites/finance/Exports", wantErr: "port"},
+ {name: "host only", raw: "https://contoso.sharepoint.com/", wantErr: "points to a site"},
+ {name: "site only", raw: "https://contoso.sharepoint.com/sites/finance/", wantErr: "points to a site"},
+ {name: "teams site only", raw: "https://contoso.sharepoint.com/teams/data", wantErr: "points to a site"},
+ {name: "sites only", raw: "https://contoso.sharepoint.com/sites", wantErr: "points to a site"},
+ {name: "site page", raw: "https://contoso.sharepoint.com/sites/finance/SitePages/Home.aspx", wantErr: "is a page"},
+ {name: "layouts page", raw: "https://contoso.sharepoint.com/sites/finance/_layouts/15/viewlsts.aspx?view=14", wantErr: "is a page"},
+ {name: "dot segment", raw: "https://contoso.sharepoint.com/sites/finance/Exports/..", wantErr: "path segments"},
+ {name: "not a URL", raw: "sites/finance/Exports", wantErr: "full SharePoint URL"},
+ {name: "empty", raw: "", wantErr: "full SharePoint URL"},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ got, err := NormalizeURL(tc.raw)
+ if tc.wantErr != "" {
+ require.ErrorContains(t, err, tc.wantErr)
+ return
+ }
+ require.NoError(t, err)
+ require.Equal(t, tc.want, got)
+ again, err := NormalizeURL(got)
+ require.NoError(t, err)
+ require.Equal(t, got, again)
+ })
+ }
+}
diff --git a/backend/server/grpc_routes.go b/backend/server/grpc_routes.go
index 20d9388f93..e16abdb25d 100644
--- a/backend/server/grpc_routes.go
+++ b/backend/server/grpc_routes.go
@@ -107,7 +107,7 @@ func configureGrpcRouters(
issueService := apiv1.NewIssueService(stores, webhookManager, bus, licenseService, iamManager, profile)
orgPolicyService := apiv1.NewOrgPolicyService(stores, licenseService, iamManager)
planService := apiv1.NewPlanService(stores, bus, iamManager, webhookManager, licenseService, profile)
- projectService := apiv1.NewProjectService(stores, profile, iamManager, sampleManager)
+ projectService := apiv1.NewProjectService(stores, profile, iamManager, sampleManager, licenseService)
queryHistoryService := apiv1.NewQueryHistoryService(stores)
releaseService := apiv1.NewReleaseService(stores, sheetManager, dbFactory, licenseService)
reviewConfigService := apiv1.NewReviewConfigService(stores)
diff --git a/backend/store/policy.go b/backend/store/policy.go
index 8ff42cccd0..619ac45730 100644
--- a/backend/store/policy.go
+++ b/backend/store/policy.go
@@ -434,6 +434,12 @@ func (s *Store) GetEffectiveQueryDataPolicy(ctx context.Context, workspaceID str
}, nil
}
+// GetWorkspaceQueryDataPolicy gets the workspace-level query data policy as
+// stored, without the project policy or the license applied.
+func (s *Store) GetWorkspaceQueryDataPolicy(ctx context.Context, workspaceID string) (*storepb.QueryDataPolicy, error) {
+ return s.getQueryDataPolicy(ctx, workspaceID, common.FormatWorkspace(workspaceID))
+}
+
func (s *Store) getQueryDataPolicy(ctx context.Context, workspaceID string, resource string) (*storepb.QueryDataPolicy, error) {
resourceType, _, err := common.GetPolicyResourceTypeAndResource(resource)
if err != nil {
diff --git a/backend/store/setting.go b/backend/store/setting.go
index 4c25c23a84..f809341105 100644
--- a/backend/store/setting.go
+++ b/backend/store/setting.go
@@ -47,6 +47,8 @@ func getSettingMessage(name storepb.SettingName) (proto.Message, error) {
return &storepb.EmailSetting{}, nil
case storepb.SettingName_MCP:
return &storepb.MCPSetting{}, nil
+ case storepb.SettingName_EXPORT:
+ return &storepb.ExportSetting{}, nil
default:
return nil, errors.Errorf("unknown setting name: %v", name)
}
@@ -250,6 +252,24 @@ func aiSettingValue(setting *SettingMessage) (*storepb.AISetting, error) {
return val, nil
}
+// GetExportSetting gets the workspace's export destination credentials.
+// Workspace creation does not seed this row, so a missing row returns an empty
+// setting.
+func (s *Store) GetExportSetting(ctx context.Context, workspaceID string) (*storepb.ExportSetting, error) {
+ setting, err := s.GetSetting(ctx, workspaceID, storepb.SettingName_EXPORT)
+ if err != nil {
+ return nil, err
+ }
+ if setting == nil {
+ return &storepb.ExportSetting{}, nil
+ }
+ val, ok := setting.Value.(*storepb.ExportSetting)
+ if !ok {
+ return nil, errors.Errorf("invalid setting value type for %s", storepb.SettingName_EXPORT)
+ }
+ return val, nil
+}
+
func (s *Store) GetEnvironment(ctx context.Context, workspaceID string) (*storepb.EnvironmentSetting, error) {
setting, err := s.GetSetting(ctx, workspaceID, storepb.SettingName_ENVIRONMENT)
if err != nil {
diff --git a/backend/store/setting_export_test.go b/backend/store/setting_export_test.go
new file mode 100644
index 0000000000..b0e354c4c4
--- /dev/null
+++ b/backend/store/setting_export_test.go
@@ -0,0 +1,70 @@
+package store_test
+
+import (
+ "testing"
+
+ "github.com/google/go-cmp/cmp"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/testing/protocmp"
+
+ "github.com/bytebase/bytebase/backend/common"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+func TestGetExportSetting(t *testing.T) {
+ t.Parallel()
+ fixture := newStorePostgresFixture(t, "")
+ ctx, s := fixture.ctx, fixture.store
+
+ setting, err := s.GetExportSetting(ctx, "default")
+ require.NoError(t, err)
+ require.Empty(t, cmp.Diff(&storepb.ExportSetting{}, setting, protocmp.Transform()), "a workspace has no row until a destination is configured")
+
+ want := &storepb.ExportSetting{Sharepoint: &storepb.SharePointSetting{TenantId: "tenant", ClientId: "client", ClientSecret: "secret"}}
+ _, err = s.UpsertSetting(ctx, &store.SettingMessage{
+ Name: storepb.SettingName_EXPORT,
+ Workspace: "default",
+ Value: want,
+ })
+ require.NoError(t, err)
+ setting, err = s.GetExportSetting(ctx, "default")
+ require.NoError(t, err)
+ require.Empty(t, cmp.Diff(want, setting, protocmp.Transform()))
+}
+
+func TestGetWorkspaceQueryDataPolicy(t *testing.T) {
+ t.Parallel()
+ fixture := newStorePostgresFixture(t, "")
+ ctx, s := fixture.ctx, fixture.store
+
+ policy, err := s.GetWorkspaceQueryDataPolicy(ctx, "default")
+ require.NoError(t, err)
+ require.False(t, policy.GetDisableDownload(), "a workspace without a policy allows download")
+
+ _, err = s.CreatePolicy(ctx, &store.PolicyMessage{
+ Workspace: "default",
+ ResourceType: storepb.Policy_PROJECT,
+ Resource: common.FormatProject("default"),
+ Type: storepb.Policy_QUERY_DATA,
+ Payload: `{"disableDownload":true}`,
+ Enforce: true,
+ })
+ require.NoError(t, err)
+ policy, err = s.GetWorkspaceQueryDataPolicy(ctx, "default")
+ require.NoError(t, err)
+ require.False(t, policy.GetDisableDownload(), "a project policy does not set the workspace policy")
+
+ _, err = s.CreatePolicy(ctx, &store.PolicyMessage{
+ Workspace: "default",
+ ResourceType: storepb.Policy_WORKSPACE,
+ Resource: common.FormatWorkspace("default"),
+ Type: storepb.Policy_QUERY_DATA,
+ Payload: `{"disableDownload":true}`,
+ Enforce: true,
+ })
+ require.NoError(t, err)
+ policy, err = s.GetWorkspaceQueryDataPolicy(ctx, "default")
+ require.NoError(t, err)
+ require.True(t, policy.GetDisableDownload())
+}
diff --git a/docs/adr/0007-sharepoint-export-ownership-boundary.md b/docs/adr/0007-sharepoint-export-ownership-boundary.md
new file mode 100644
index 0000000000..e0c2ddcff8
--- /dev/null
+++ b/docs/adr/0007-sharepoint-export-ownership-boundary.md
@@ -0,0 +1,176 @@
+# Leave delivered export governance with SharePoint administrators
+
+For the proposed SharePoint export integration, delivering an export to SharePoint
+means Bytebase sends the exported file directly to SharePoint instead of returning
+its bytes to the caller. It does not promise to prevent copying visible query
+results or downloading a delivered file through SharePoint.
+
+Customer administrators provision destination sites, libraries, and folders and
+configure their reader permissions. Authorized Bytebase users maintain each
+project's destination mapping. Bytebase validates destinations and uploads files; it does not manage
+SharePoint permissions, retention, or deletion. Reader policies may allow project-wide access or narrower
+access, but Bytebase does not promise that file access matches database access.
+
+After delivery, database grant expiration does not revoke access to the exported
+file. This boundary leaves storage governance with the customer rather than
+requiring Bytebase to reproduce and continuously synchronize database access
+rules in SharePoint.
+
+Live validation on October 21–22, 2026, using an application token that carried
+only `Lists.SelectedOperations.Selected`, established how a library write grant
+behaves:
+
+- The grant is an ordinary SharePoint permission entry for the application. It
+ does not bypass a folder's unique permissions; a folder without the entry
+ returns `404 itemNotFound`, and an ungranted library returns `403`.
+- Creating a grant adds the application to the library and to every folder in it
+ that already has unique permissions. The SharePoint UI's Stop Inheriting copies
+ the entry; scripted inheritance breaks that do not copy entries drop it.
+- Re-issuing an existing grant changes nothing. Deleting and re-creating it
+ restores the entry in every folder scope; deleting it removes the entry
+ everywhere in the library.
+- Delete unique permissions on a granted library removes Bytebase's write access,
+ widens readers to the whole site, and removes the grant from Graph's permission
+ list.
+- The classic SharePoint permissions pages do not show the application.
+- Libraries on a second site behaved the same as on the root site.
+- After any grant on a site, the application can read the site name and every
+ library's name and root on it, including libraries it cannot write to.
+- A full SharePoint URL of a library root or folder, on the root site or another
+ site, resolves to its drive item through Graph's `/shares` endpoint with only
+ the Selected permission. A URL that does not exist returns the same
+ `403 accessDenied` as one the application cannot access.
+
+Customers are responsible for ensuring effective application write access on
+each configured destination, including after permission inheritance changes.
+Bytebase reports failures; it does not repair SharePoint permissions. Direct
+per-folder application grants and end-user read access were not tested.
+Evidence is in Linear issue BOT-156.
+
+Each project has one configured destination: a document library root or a folder
+within a document library. Projects may target different libraries across
+multiple SharePoint sites using the workspace's shared application identity.
+Bytebase does not select a different destination based on the exporting user.
+Multiple Microsoft tenants or independently configured application identities are not
+implied by support for multiple sites.
+
+Configuring a storage destination approves exports to it. SharePoint is
+offered when the workspace has the SharePoint plan feature and SharePoint
+credentials and the project has a SharePoint folder. Download is the only
+Export Destination with a policy switch: the workspace query data policy's
+`disable_download` turns it off. It defaults to false, so an upgrade keeps
+Download. A separate SharePoint switch was dropped because configuring a
+storage destination is itself the approval. The Export Permission
+(`bb.sql.export`, ADR 0006) decides who may export, and the available
+destinations decide where exports may go. An approved export access grant
+satisfies the Export Permission but never adds a destination, so with Download
+disabled and no project SharePoint folder, export is refused for everyone,
+grant holders too. The Export API enforces `disable_download` for every
+caller, including MCP; hiding the UI is not enforcement. The setting stays in
+effect if the workspace license lapses; only changing it requires the license.
+
+Bytebase is neutral about how customers isolate projects. It uses whatever
+library root or folder is configured and does not recommend one structure or
+warn about folder destinations. Keeping Bytebase's access intact through later
+permission changes is the customer's SharePoint administration. Customers make
+grants with their own administrator account; Bytebase never holds
+`Sites.FullControl.All` or performs grants itself.
+
+Upload failures return an actionable error after bounded retries, without a
+fallback to Download or durable background delivery in the initial version.
+
+A project's destination is part of the project's settings and is changed with
+the existing `bb.projects.update` permission, so Project Owners can change it.
+
+A user who can update the project can select any library root or folder writable by the
+workspace application identity, including a destination used by another project.
+There is no separate approved-site, library, or folder allowlist. Customers grant
+the application access to the required libraries in SharePoint. Bytebase
+resolves the destination and audits mapping changes; customers remain
+responsible for its audience.
+
+Each export is delivered into its own uniquely named subfolder of the destination
+to preserve existing files. Retries of the same export target the same subfolder
+and file names rather than creating additional copies.
+The subfolder name contains the UTC export time, the exporter's email, the
+database, and the export ID, because SharePoint attributes the files to the
+Bytebase application rather than to the exporting user.
+
+An export captures its destination when it starts: the configured URL and the
+folder it resolved to. Mapping changes affect subsequent exports; the running
+export and its retries upload to the captured folder. The audit log records the
+actual destination.
+
+Delivery is confirmed only when every file of the export is confirmed. Confirmed
+delivery returns the URL of the export subfolder. Delivery success does not
+imply that the exporting user can read the file; SharePoint
+enforces that user's access independently, and Bytebase does not grant access.
+
+If an upload response is lost, Bytebase attempts bounded reconciliation against
+the same export file names. If delivery remains uncertain, Bytebase reports that
+delivery could not be confirmed and files may exist in SharePoint. It does
+not claim that no file was created.
+
+Bytebase checks the destination once, before the query runs. A change made
+while an export is running applies to the next export. A rejected destination
+is never redirected to another one.
+
+Internal upload retries reuse the generated files, file names, and captured
+destination without rerunning the query. A new Export action starts a new export
+and reruns the query.
+
+The initial release supports self-hosted Bytebase on any hosting platform using
+client-secret authentication. It does not require AKS or another platform
+identity provider. Bytebase Cloud support, workload identity federation, and
+certificate authentication are outside the initial scope.
+
+The client secret is configured in the workspace export setting through a
+write-only field. Workspace credential configuration uses the existing
+`bb.settings.set` permission, following other workspace integrations. Workspace
+Admin and Workspace DBA have that permission by default; custom roles can
+delegate it with its existing broader settings authority.
+
+A destination is configured as the full SharePoint URL of a library root or a
+folder, which carries the site and hostname. Administrators may paste a browser
+URL, including a library view with an `id` parameter or a copied folder link;
+Bytebase normalizes it to the canonical URL and resolves it on save, rejecting a
+URL that does not resolve. It stores and returns only the canonical URL; resolved
+names go stale on rename and are not kept. A SharePoint browsing picker is
+outside the initial scope.
+
+Bytebase resolves the stored URL at each export rather than pinning item IDs.
+Renaming or moving the folder makes exports fail as not found; a folder
+recreated at the same URL receives subsequent exports.
+
+Customers create and rotate Entra client secrets. Expired or invalid credentials
+cause affected exports to fail with a clear credential error. An authorized user
+can replace the secret without changing project mappings; Bytebase does not
+create or renew Entra credentials.
+
+When both destinations are available, Export defaults to SharePoint and offers
+Download as an explicit alternative. Disabling Download removes that
+alternative.
+
+Destination validation in the initial release only resolves the configured URL.
+A destination that resolves is accepted, not verified: the application can read a library root it
+cannot write to, so a successful read does not prove upload access. The first
+export is the actual write check. SharePoint does not distinguish a missing
+destination from one Bytebase cannot access, so errors report both
+possibilities. A write probe is a later improvement.
+
+The initial release preserves existing export limits and result formats. Changing
+the export destination does not expand export capacity.
+
+SharePoint delivery uploads the export's statement and result files directly
+instead of a zip, so readers can open each result in the browser without
+downloading it. Readers of the destination therefore also see the query text.
+Zip passwords apply only to Download. Batch export
+is a client-side composition of per-database exports: each database delivers
+its own files, and the batch reports delivered, failed, and unconfirmed
+databases separately without rolling back delivered files.
+
+The initial release supports the Microsoft global commercial cloud only.
+Government and sovereign clouds use different sign-in and Graph endpoints.
+
+SharePoint delivery is an Enterprise plan feature, on the same plan as
+restricting data copying.
diff --git a/docs/design/mcp-capability-ladder.md b/docs/design/mcp-capability-ladder.md
index a9cdbe2369..68cc1aaa11 100644
--- a/docs/design/mcp-capability-ladder.md
+++ b/docs/design/mcp-capability-ladder.md
@@ -77,7 +77,7 @@ the product.
| write | Approve or reject issues | Each decision is confirmed in the user's MCP client before it is made · Role requests are decided in the console · The approval rules and the project's self-approval setting apply, as in the console | 2 WRITE methods: `ApproveIssue`, `RejectIssue`, served only through the `decide_issue` tool, which asks the user to confirm each decision and refuses role requests |
| write | Run rollouts and tasks | Create a rollout · Run, skip or cancel its tasks, under the project's approval policy | 4 WRITE methods: `CreateRollout`, `BatchRunTasks`, `BatchSkipTasks`, `BatchCancelTaskRuns` |
| write | Run DML and DDL statements | INSERT, UPDATE, DELETE, CREATE, ALTER, DROP through queries, as far as the engine and the user's own permissions allow · Where the user's MCP client supports confirmations, a query that is not a read as far as the engine can check it runs only after the user confirms it · In other clients such a query can run without asking | Not a method: the statement clamp in `mcp_sql_clamp.go`, which Read-write lifts. A statement Bytebase cannot show is a read runs only through the `query_database` tool, which asks the user to confirm it when the client can show the form (`mcp_sql_write.go`) |
-| write | Export query results | Download results as a file. Data leaves Bytebase | 1 WRITE method: `SQLService/Export`, which requires the user's own `bb.sql.export` on the data it reads, from a role or a matching export grant, and runs only statements Bytebase can show are reads |
+| write | Export query results | Export results as files. Data leaves Bytebase | 1 WRITE method: `SQLService/Export`, which requires the user's own `bb.sql.export` on the data it reads, from a role or a matching export grant, and runs only statements Bytebase can show are reads |
| write | Manage database housekeeping | Sync instances and databases · Saved queries | 9 WRITE methods: sync, saved-query writes |
| — | *Read-write stops here* | | 111 methods |
| floor | Never, in any mode: administer the workspace, handle credentials, open an Admin mode session, or read anyone else's query history. | | 109 methods: 34 FORBIDDEN, 75 EXCLUDED |
diff --git a/frontend/src/app/router/handles.ts b/frontend/src/app/router/handles.ts
index 9a4591145c..b5d2d49ce4 100644
--- a/frontend/src/app/router/handles.ts
+++ b/frontend/src/app/router/handles.ts
@@ -31,6 +31,7 @@ export const WORKSPACE_ROUTE_IDENTITY_PROVIDER_DETAIL = `${WORKSPACE_ROUTE_IDENT
export const WORKSPACE_ROUTE_INTEGRATION = "workspace.integration";
export const WORKSPACE_ROUTE_IM = `${WORKSPACE_ROUTE_INTEGRATION}.im`;
export const WORKSPACE_ROUTE_MCP = `${WORKSPACE_ROUTE_INTEGRATION}.mcp`;
+export const WORKSPACE_ROUTE_EXPORT_DESTINATIONS = `${WORKSPACE_ROUTE_INTEGRATION}.export-destinations`;
export const WORKSPACE_ROUTE_403 = "error.403";
export const WORKSPACE_ROUTE_404 = "error.404";
diff --git a/frontend/src/app/router/index.ts b/frontend/src/app/router/index.ts
index a528812955..bd66ebf28f 100644
--- a/frontend/src/app/router/index.ts
+++ b/frontend/src/app/router/index.ts
@@ -55,6 +55,7 @@ export {
WORKSPACE_ROUTE_ROLES,
WORKSPACE_ROUTE_SEMANTIC_TYPES,
WORKSPACE_ROUTE_SERVICE_ACCOUNTS,
+ WORKSPACE_ROUTE_EXPORT_DESTINATIONS,
WORKSPACE_ROUTE_SQL_REVIEW,
WORKSPACE_ROUTE_USERS,
WORKSPACE_ROUTE_WORKLOAD_IDENTITIES,
diff --git a/frontend/src/app/router/routes/dashboard.tsx b/frontend/src/app/router/routes/dashboard.tsx
index e6f5a80b32..02b62c9c1f 100644
--- a/frontend/src/app/router/routes/dashboard.tsx
+++ b/frontend/src/app/router/routes/dashboard.tsx
@@ -58,6 +58,7 @@ import {
WORKSPACE_ROUTE_AUDIT_LOG,
WORKSPACE_ROUTE_CUSTOM_APPROVAL,
WORKSPACE_ROUTE_DATA_CLASSIFICATION,
+ WORKSPACE_ROUTE_EXPORT_DESTINATIONS,
WORKSPACE_ROUTE_GLOBAL_MASKING,
WORKSPACE_ROUTE_GROUPS,
WORKSPACE_ROUTE_IDENTITY_PROVIDER_DETAIL,
@@ -431,6 +432,20 @@ const workspaceLevelRoutes: RouteObject[] = [
(m) => m.MCPPage
),
},
+ {
+ path: "export-destinations",
+ handle: {
+ name: WORKSPACE_ROUTE_EXPORT_DESTINATIONS,
+ requiredPermissionList: (): Permission[] => ["bb.settings.get"],
+ },
+ lazy: lazyPage(
+ () =>
+ import(
+ "@/routes/workspace/export-destinations/ExportDestinationsPage"
+ ),
+ (m) => m.ExportDestinationsPage
+ ),
+ },
],
},
];
diff --git a/frontend/src/assets/css/tailwind.css b/frontend/src/assets/css/tailwind.css
index 51e38542a0..c667713dbd 100644
--- a/frontend/src/assets/css/tailwind.css
+++ b/frontend/src/assets/css/tailwind.css
@@ -2,6 +2,17 @@
@theme {
--radius-full: 9999px;
+ --animate-progress-indeterminate: progress-indeterminate 1.2s ease-in-out
+ infinite;
+
+ @keyframes progress-indeterminate {
+ from {
+ transform: translateX(-100%);
+ }
+ to {
+ transform: translateX(300%);
+ }
+ }
}
/*
diff --git a/frontend/src/assets/export/sharepoint.svg b/frontend/src/assets/export/sharepoint.svg
new file mode 100644
index 0000000000..a789f11952
--- /dev/null
+++ b/frontend/src/assets/export/sharepoint.svg
@@ -0,0 +1,70 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 450 500" version="1.1">
+<defs>
+<linearGradient id="linear0" gradientUnits="userSpaceOnUse" x1="92.18" y1="477.480011" x2="292.290009" y2="214.839996" gradientTransform="matrix(1,0,0,-1,0,502)">
+<stop offset="0" style="stop-color:rgb(0%,89.019608%,87.45098%);stop-opacity:1;"/>
+<stop offset="0.41" style="stop-color:rgb(0%,59.215686%,65.882353%);stop-opacity:1;"/>
+<stop offset="1" style="stop-color:rgb(0%,46.666667%,56.862745%);stop-opacity:1;"/>
+</linearGradient>
+<radialGradient id="radial0" gradientUnits="userSpaceOnUse" cx="-777.140015" cy="770.840027" fx="-777.140015" fy="770.840027" r="0.9" gradientTransform="matrix(-98.022052,-236.879968,-426.555517,175.978041,252868.125,-319393.71875)">
+<stop offset="0.29" style="stop-color:rgb(0%,23.137255%,36.470588%);stop-opacity:0.2;"/>
+<stop offset="0.61" style="stop-color:rgb(0%,29.019608%,42.352941%);stop-opacity:0.138039;"/>
+<stop offset="0.97" style="stop-color:rgb(0%,43.529412%,58.039216%);stop-opacity:0;"/>
+</radialGradient>
+<radialGradient id="radial1" gradientUnits="userSpaceOnUse" cx="-785.22998" cy="766.900024" fx="-785.22998" fy="766.900024" r="0.9" gradientTransform="matrix(-81.368639,-200.487205,-360.582879,145.895883,212855.734375,-269057.375)">
+<stop offset="0.26" style="stop-color:rgb(0%,16.470588%,25.882353%);stop-opacity:0.309804;"/>
+<stop offset="0.61" style="stop-color:rgb(0%,25.882353%,38.039216%);stop-opacity:0.213825;"/>
+<stop offset="0.97" style="stop-color:rgb(0%,43.529412%,58.039216%);stop-opacity:0;"/>
+</radialGradient>
+<radialGradient id="radial2" gradientUnits="userSpaceOnUse" cx="-739.840027" cy="872.710022" fx="-739.840027" fy="872.710022" r="0.9" gradientTransform="matrix(-102.53313,149.242437,149.468015,102.381369,-206024.5,21094.220703)">
+<stop offset="0" style="stop-color:rgb(47.058824%,92.941176%,100%);stop-opacity:0.698039;"/>
+<stop offset="1" style="stop-color:rgb(17.254902%,81.176471%,79.215686%);stop-opacity:0;"/>
+</radialGradient>
+<linearGradient id="linear1" gradientUnits="userSpaceOnUse" x1="245.139999" y1="331.570007" x2="411.899994" y2="112.699997" gradientTransform="matrix(1,0,0,-1,0,502)">
+<stop offset="0" style="stop-color:rgb(0%,89.019608%,87.45098%);stop-opacity:1;"/>
+<stop offset="0.48" style="stop-color:rgb(0%,63.529412%,72.156863%);stop-opacity:1;"/>
+<stop offset="0.95" style="stop-color:rgb(0%,38.823529%,48.627451%);stop-opacity:1;"/>
+</linearGradient>
+<radialGradient id="radial3" gradientUnits="userSpaceOnUse" cx="-746.380005" cy="743.75" fx="-746.380005" fy="743.75" r="0.9" gradientTransform="matrix(56.607296,-162.280342,-292.839823,-101.831895,260296.265625,-45019.25)">
+<stop offset="0" style="stop-color:rgb(0%,23.137255%,36.470588%);stop-opacity:0.501961;"/>
+<stop offset="0.49" style="stop-color:rgb(0%,29.803922%,42.352941%);stop-opacity:0.362199;"/>
+<stop offset="0.97" style="stop-color:rgb(0%,47.843137%,52.54902%);stop-opacity:0;"/>
+</radialGradient>
+<radialGradient id="radial4" gradientUnits="userSpaceOnUse" cx="-741.460022" cy="888.909973" fx="-741.460022" fy="888.909973" r="0.9" gradientTransform="matrix(-85.443327,124.367318,124.552559,85.31498,-173675.6875,16546.900391)">
+<stop offset="0" style="stop-color:rgb(47.058824%,92.941176%,100%);stop-opacity:0.698039;"/>
+<stop offset="1" style="stop-color:rgb(17.254902%,81.176471%,79.215686%);stop-opacity:0;"/>
+</radialGradient>
+<linearGradient id="linear2" gradientUnits="userSpaceOnUse" x1="153.419998" y1="214.529999" x2="259.709991" y2="1.97" gradientTransform="matrix(1,0,0,-1,0,502)">
+<stop offset="0.05" style="stop-color:rgb(45.882353%,100%,96.470588%);stop-opacity:1;"/>
+<stop offset="0.51" style="stop-color:rgb(0%,78.039216%,81.960784%);stop-opacity:1;"/>
+<stop offset="0.96" style="stop-color:rgb(0%,58.823529%,67.843137%);stop-opacity:1;"/>
+</linearGradient>
+<linearGradient id="linear3" gradientUnits="userSpaceOnUse" x1="292.440002" y1="-12.27" x2="235.630005" y2="67.449997" gradientTransform="matrix(1,0,0,-1,0,502)">
+<stop offset="0.26" style="stop-color:rgb(5.490196%,35.294118%,36.470588%);stop-opacity:0.321569;"/>
+<stop offset="0.54" style="stop-color:rgb(7.058824%,42.352941%,41.960784%);stop-opacity:0.221945;"/>
+<stop offset="0.97" style="stop-color:rgb(10.980392%,58.039216%,54.117647%);stop-opacity:0;"/>
+</linearGradient>
+<radialGradient id="radial5" gradientUnits="userSpaceOnUse" cx="-686.599976" cy="804.179993" fx="-686.599976" fy="804.179993" r="0.9" gradientTransform="matrix(222.887003,222.576004,222.926115,-222.537381,-26208.169922,332025.53125)">
+<stop offset="0.06" style="stop-color:rgb(0%,71.372549%,74.117647%);stop-opacity:1;"/>
+<stop offset="0.89" style="stop-color:rgb(0%,28.627451%,36.078431%);stop-opacity:1;"/>
+</radialGradient>
+<radialGradient id="radial6" gradientUnits="userSpaceOnUse" cx="-686.070007" cy="864.409973" fx="-686.070007" fy="864.409973" r="0.9" gradientTransform="matrix(0.000000000000009539,155.789993,177.619995,-0.000000000000010876,-153439.140625,107241.640625)">
+<stop offset="0.57" style="stop-color:rgb(11.764706%,52.156863%,50.588235%);stop-opacity:0;"/>
+<stop offset="0.97" style="stop-color:rgb(11.764706%,79.607843%,90.196078%);stop-opacity:0.6;"/>
+</radialGradient>
+</defs>
+<g id="surface1">
+<path style=" stroke:none;fill-rule:nonzero;fill:url(#linear0);" d="M 187.789062 300 C 270.761719 300 338.019531 232.839844 338.019531 150 C 338.019531 67.160156 270.75 0 187.789062 0 C 104.828125 0 37.558594 67.160156 37.558594 150 C 37.558594 232.839844 104.820312 300 187.789062 300 Z M 187.789062 300 "/>
+<path style=" stroke:none;fill-rule:nonzero;fill:url(#radial0);" d="M 187.789062 300 C 270.761719 300 338.019531 232.839844 338.019531 150 C 338.019531 67.160156 270.75 0 187.789062 0 C 104.828125 0 37.558594 67.160156 37.558594 150 C 37.558594 232.839844 104.820312 300 187.789062 300 Z M 187.789062 300 "/>
+<path style=" stroke:none;fill-rule:nonzero;fill:url(#radial1);" d="M 187.789062 300 C 270.761719 300 338.019531 232.839844 338.019531 150 C 338.019531 67.160156 270.75 0 187.789062 0 C 104.828125 0 37.558594 67.160156 37.558594 150 C 37.558594 232.839844 104.820312 300 187.789062 300 Z M 187.789062 300 "/>
+<path style=" stroke:none;fill-rule:nonzero;fill:url(#radial2);" d="M 187.789062 300 C 270.761719 300 338.019531 232.839844 338.019531 150 C 338.019531 67.160156 270.75 0 187.789062 0 C 104.828125 0 37.558594 67.160156 37.558594 150 C 37.558594 232.839844 104.820312 300 187.789062 300 Z M 187.789062 300 "/>
+<path style=" stroke:none;fill-rule:nonzero;fill:url(#linear1);" d="M 324.808594 400 C 393.949219 400 450 344.039062 450 275 C 450 205.960938 393.949219 150 324.808594 150 C 255.671875 150 199.621094 205.960938 199.621094 275 C 199.621094 344.039062 255.671875 400 324.808594 400 Z M 324.808594 400 "/>
+<path style=" stroke:none;fill-rule:nonzero;fill:url(#radial3);" d="M 324.808594 400 C 393.949219 400 450 344.039062 450 275 C 450 205.960938 393.949219 150 324.808594 150 C 255.671875 150 199.621094 205.960938 199.621094 275 C 199.621094 344.039062 255.671875 400 324.808594 400 Z M 324.808594 400 "/>
+<path style=" stroke:none;fill-rule:nonzero;fill:url(#radial4);" d="M 324.808594 400 C 393.949219 400 450 344.039062 450 275 C 450 205.960938 393.949219 150 324.808594 150 C 255.671875 150 199.621094 205.960938 199.621094 275 C 199.621094 344.039062 255.671875 400 324.808594 400 Z M 324.808594 400 "/>
+<path style=" stroke:none;fill-rule:nonzero;fill:url(#linear2);" d="M 206.558594 500 C 265.328125 500 312.96875 452.429688 312.96875 393.75 C 312.96875 335.070312 265.328125 287.5 206.558594 287.5 C 147.789062 287.5 100.148438 335.070312 100.148438 393.75 C 100.148438 452.429688 147.789062 500 206.558594 500 Z M 206.558594 500 "/>
+<path style=" stroke:none;fill-rule:nonzero;fill:url(#linear3);" d="M 206.558594 500 C 265.328125 500 312.96875 452.429688 312.96875 393.75 C 312.96875 335.070312 265.328125 287.5 206.558594 287.5 C 147.789062 287.5 100.148438 335.070312 100.148438 393.75 C 100.148438 452.429688 147.789062 500 206.558594 500 Z M 206.558594 500 "/>
+<path style=" stroke:none;fill-rule:nonzero;fill:url(#radial5);" d="M 40.660156 237.5 L 159.640625 237.5 C 182.097656 237.5 200.300781 255.703125 200.300781 278.160156 L 200.300781 396.839844 C 200.300781 419.296875 182.097656 437.5 159.640625 437.5 L 40.660156 437.5 C 18.203125 437.5 0 419.296875 0 396.839844 L 0 278.160156 C 0 255.703125 18.203125 237.5 40.660156 237.5 Z M 40.660156 237.5 "/>
+<path style=" stroke:none;fill-rule:nonzero;fill:url(#radial6);" d="M 40.660156 237.5 L 159.640625 237.5 C 182.097656 237.5 200.300781 255.703125 200.300781 278.160156 L 200.300781 396.839844 C 200.300781 419.296875 182.097656 437.5 159.640625 437.5 L 40.660156 437.5 C 18.203125 437.5 0 419.296875 0 396.839844 L 0 278.160156 C 0 255.703125 18.203125 237.5 40.660156 237.5 Z M 40.660156 237.5 "/>
+<path style=" stroke:none;fill-rule:nonzero;fill:rgb(100%,100%,100%);fill-opacity:1;" d="M 57 372.148438 L 78.71875 360.828125 C 81.171875 365.769531 84.359375 369.410156 88.300781 371.75 C 92.289062 374.089844 96.660156 375.261719 101.390625 375.261719 C 106.660156 375.261719 110.679688 374.199219 113.441406 372.070312 C 116.210938 369.890625 117.589844 366.621094 117.589844 362.269531 C 117.589844 358.871094 116.261719 356 113.601562 353.660156 C 110.941406 351.269531 106.230469 349.460938 99.46875 348.238281 C 86.589844 345.898438 77.21875 341.808594 71.371094 335.960938 C 65.570312 330.109375 62.671875 322.828125 62.671875 314.121094 C 62.671875 303.28125 66.5 294.621094 74.171875 288.128906 C 81.828125 281.648438 91.949219 278.410156 104.511719 278.410156 C 112.96875 278.410156 120.421875 280.140625 126.859375 283.589844 C 133.300781 287.039062 138.410156 291.988281 142.191406 298.421875 L 120.960938 309.339844 C 118.621094 305.730469 116.089844 303.121094 113.378906 301.53125 C 110.660156 299.878906 107.261719 299.058594 103.160156 299.058594 C 98.261719 299.058594 94.539062 300.121094 91.980469 302.25 C 89.480469 304.378906 88.230469 307.140625 88.230469 310.539062 C 88.230469 313.460938 89.429688 316.039062 91.820312 318.269531 C 94.269531 320.449219 99.160156 322.230469 106.511719 323.609375 C 118.859375 325.949219 128.070312 330.199219 134.128906 336.371094 C 140.25 342.480469 143.308594 350.210938 143.308594 359.570312 C 143.308594 370.941406 139.660156 379.949219 132.371094 386.589844 C 125.078125 393.230469 114.671875 396.550781 101.160156 396.550781 C 91.371094 396.550781 82.53125 394.421875 74.660156 390.171875 C 66.839844 385.871094 60.960938 379.859375 57.019531 372.148438 Z M 57 372.148438 "/>
+</g>
+</svg>
diff --git a/frontend/src/components/DashboardSidebar.test.tsx b/frontend/src/components/DashboardSidebar.test.tsx
index eccac28da8..85a415aa09 100644
--- a/frontend/src/components/DashboardSidebar.test.tsx
+++ b/frontend/src/components/DashboardSidebar.test.tsx
@@ -147,6 +147,7 @@ vi.mock("@/app/router", () => ({
WORKSPACE_ROUTE_ROLES: "workspace.roles",
WORKSPACE_ROUTE_SEMANTIC_TYPES: "workspace.semantic-types",
WORKSPACE_ROUTE_SERVICE_ACCOUNTS: "workspace.service-accounts",
+ WORKSPACE_ROUTE_EXPORT_DESTINATIONS: "workspace.integration.export-destinations",
WORKSPACE_ROUTE_SQL_REVIEW: "workspace.sql-review",
WORKSPACE_ROUTE_USERS: "workspace.users",
WORKSPACE_ROUTE_WORKLOAD_IDENTITIES: "workspace.workload-identities",
diff --git a/frontend/src/components/DashboardSidebar.tsx b/frontend/src/components/DashboardSidebar.tsx
index e09eaa52c9..866ca2fe8b 100644
--- a/frontend/src/components/DashboardSidebar.tsx
+++ b/frontend/src/components/DashboardSidebar.tsx
@@ -26,6 +26,7 @@ import {
WORKSPACE_ROUTE_AUDIT_LOG,
WORKSPACE_ROUTE_CUSTOM_APPROVAL,
WORKSPACE_ROUTE_DATA_CLASSIFICATION,
+ WORKSPACE_ROUTE_EXPORT_DESTINATIONS,
WORKSPACE_ROUTE_GLOBAL_MASKING,
WORKSPACE_ROUTE_GROUPS,
WORKSPACE_ROUTE_IDENTITY_PROVIDERS,
@@ -227,6 +228,11 @@ function useSidebarItems(): SidebarItem[] {
name: WORKSPACE_ROUTE_MCP,
type: "route",
},
+ {
+ title: t("settings.sidebar.export-destinations"),
+ name: WORKSPACE_ROUTE_EXPORT_DESTINATIONS,
+ type: "route",
+ },
],
},
{
diff --git a/frontend/src/components/DataExportButton.test.tsx b/frontend/src/components/DataExportButton.test.tsx
new file mode 100644
index 0000000000..3a37c3c6e2
--- /dev/null
+++ b/frontend/src/components/DataExportButton.test.tsx
@@ -0,0 +1,140 @@
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { ExportDestination, ExportFormat } from "@/types/proto-es/v1/common_pb";
+import { type DataExportRequest, DataExportButton } from "./DataExportButton";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/stores", () => ({ pushNotification: vi.fn() }));
+
+vi.mock("./MaxRowCountSelect", () => ({
+ MaxRowCountSelect: () => null,
+}));
+
+const sharepointUrl =
+ "https://contoso.sharepoint.com/sites/Finance/Shared%20Documents/Exports";
+const folderUri = `${sharepointUrl}/20261022-main`;
+
+const onExport = vi.fn<(request: DataExportRequest) => void>();
+
+const renderButton = (destinations: ExportDestination[]) =>
+ render(
+ <DataExportButton
+ viewMode="DRAWER"
+ supportFormats={[ExportFormat.CSV]}
+ supportPassword
+ destinations={destinations}
+ sharepointUrl={sharepointUrl}
+ onExport={onExport}
+ />
+ );
+
+const openDrawer = () =>
+ fireEvent.click(screen.getByRole("button", { name: "common.export" }));
+
+describe("DataExportButton destination", () => {
+ beforeEach(() => {
+ onExport.mockReset();
+ });
+
+ test("defaults to SharePoint and hides the zip password for it", () => {
+ renderButton([ExportDestination.SHAREPOINT, ExportDestination.DOWNLOAD]);
+ openDrawer();
+
+ const radios = screen.getAllByRole("radio");
+ expect(radios).toHaveLength(2);
+ expect(radios[0]).toHaveAttribute("aria-checked", "true");
+ expect(screen.getByText(decodeURI(sharepointUrl))).toBeInTheDocument();
+ expect(
+ screen.queryByLabelText("export-data.password-optional")
+ ).not.toBeInTheDocument();
+
+ fireEvent.click(radios[1]);
+ expect(
+ screen.getByLabelText("export-data.password-optional")
+ ).toBeInTheDocument();
+ });
+
+ test("shows the exported folder instead of downloading", async () => {
+ onExport.mockImplementation(({ options, resolve }) => {
+ expect(options.destination).toBe(ExportDestination.SHAREPOINT);
+ expect(options.password).toBe("");
+ resolve({
+ sharepoint: [{ database: "main", status: "EXPORTED", uri: folderUri }],
+ });
+ });
+ renderButton([ExportDestination.SHAREPOINT]);
+ openDrawer();
+
+ expect(screen.queryAllByRole("radio")).toHaveLength(0);
+ expect(
+ screen.queryByLabelText("export-data.password-optional")
+ ).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "common.confirm" }));
+
+ await waitFor(() => {
+ expect(
+ screen.getByText("export-data.sharepoint.exported-title")
+ ).toBeInTheDocument();
+ });
+ expect(screen.getByText(decodeURI(folderUri))).toBeInTheDocument();
+ expect(
+ screen.getByRole("link", { name: "export-data.sharepoint.open" })
+ ).toHaveAttribute("href", folderUri);
+ });
+
+ test("offers download alone with the zip password", () => {
+ renderButton([ExportDestination.DOWNLOAD]);
+ openDrawer();
+
+ expect(screen.queryAllByRole("radio")).toHaveLength(0);
+ expect(
+ screen.queryByText("export-data.destination.self")
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByLabelText("export-data.password-optional")
+ ).toBeInTheDocument();
+ });
+
+ test("disables export when no destination is available", () => {
+ renderButton([]);
+ expect(
+ screen.getByRole("button", { name: "common.export" })
+ ).toBeDisabled();
+ });
+
+ test("shows progress while the export runs", async () => {
+ let finish: (() => void) | undefined;
+ let reportProgress: DataExportRequest["onProgress"];
+ onExport.mockImplementation(({ resolve, onProgress }) => {
+ reportProgress = onProgress;
+ finish = () => resolve({ sharepoint: [] });
+ });
+ renderButton([ExportDestination.SHAREPOINT]);
+ openDrawer();
+ fireEvent.click(screen.getByRole("button", { name: "common.confirm" }));
+
+ expect(screen.getByRole("progressbar")).toHaveAccessibleName(
+ "export-data.progress.sharepoint"
+ );
+ act(() => reportProgress?.(1, 3));
+ expect(screen.getByRole("progressbar")).toHaveAttribute(
+ "aria-valuenow",
+ "1"
+ );
+ expect(screen.getByRole("progressbar")).toHaveAccessibleName(
+ "export-data.progress.databases"
+ );
+
+ await act(async () => finish?.());
+ expect(screen.queryByRole("progressbar")).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/components/DataExportButton.tsx b/frontend/src/components/DataExportButton.tsx
index 6c9d9c8484..bc28d7e76d 100644
--- a/frontend/src/components/DataExportButton.tsx
+++ b/frontend/src/components/DataExportButton.tsx
@@ -24,8 +24,11 @@ import {
FormControlRow,
FormField,
FormFieldGroup,
+ FormLabel,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
+import { Progress } from "@/components/ui/progress";
+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import {
Select,
SelectContent,
@@ -45,8 +48,13 @@ import { Tooltip } from "@/components/ui/tooltip";
import { writeTextToClipboard } from "@/lib/clipboard";
import { cn } from "@/lib/utils";
import { pushNotification } from "@/stores";
-import { ExportFormat } from "@/types/proto-es/v1/common_pb";
+import { ExportDestination, ExportFormat } from "@/types/proto-es/v1/common_pb";
import { MaxRowCountSelect } from "./MaxRowCountSelect";
+import {
+ formatSharePointUrl,
+ type SharePointExportResult,
+ SharePointExportResultDialog,
+} from "./SharePointExportResultDialog";
export type DownloadContent = {
content: Uint8Array;
@@ -56,13 +64,23 @@ export type DownloadContent = {
export interface ExportOption {
limit: number;
format: ExportFormat;
+ // Applies only to DOWNLOAD.
password: string;
+ destination: ExportDestination;
}
+// Downloads resolve with the files to save; SharePoint exports resolve with
+// each database's export result.
+export type ExportOutcome =
+ | DownloadContent[]
+ | { sharepoint: SharePointExportResult[] };
+
export type DataExportRequest = {
options: ExportOption;
- resolve: (content: DownloadContent[]) => void;
+ resolve: (outcome: ExportOutcome) => void;
reject: (reason?: unknown) => void;
+ // Reports progress of an export that covers several databases.
+ onProgress?: (done: number, total: number) => void;
};
type Size = "tiny" | "sm" | "md" | "lg";
@@ -80,10 +98,16 @@ interface DataExportButtonProps {
maximumExportCount?: number;
/** Custom form content rendered above the row-count / format / password fields in DRAWER mode. */
formContent?: ReactNode;
+ /** Offered destinations in DRAWER mode; the first is the default. Empty disables export. */
+ destinations?: ExportDestination[];
+ /** The project's SharePoint destination URL, shown beside that destination. */
+ sharepointUrl?: string;
onExport: (req: DataExportRequest) => void;
className?: string;
}
+const DOWNLOAD_ONLY = [ExportDestination.DOWNLOAD];
+
const SIZE_TO_BUTTON: Record<Size, ButtonProps["size"]> = {
tiny: "xs",
sm: "sm",
@@ -196,6 +220,8 @@ export function DataExportButton({
validate,
maximumExportCount = Number.MAX_VALUE,
formContent,
+ destinations = DOWNLOAD_ONLY,
+ sharepointUrl,
onExport,
className,
}: DataExportButtonProps) {
@@ -204,6 +230,14 @@ export function DataExportButton({
const [isRequesting, setIsRequesting] = useState(false);
const [showDrawer, setShowDrawer] = useState(false);
const [showPasswordDialog, setShowPasswordDialog] = useState(false);
+ const [progress, setProgress] = useState<{ done: number; total: number }>();
+ const [sharePointResults, setSharePointResults] = useState<
+ SharePointExportResult[]
+ >([]);
+ const exportUnavailable = destinations.length === 0;
+ const triggerTooltip = exportUnavailable
+ ? t("export-data.no-destination")
+ : tooltip;
const presetMax = useMemo(
() => computeMaximumPreset(maximumExportCount),
@@ -214,12 +248,17 @@ export function DataExportButton({
const [limit, setLimit] = useState<number>(defaultLimit);
const [format, setFormat] = useState<ExportFormat>(supportFormats[0]);
const [password, setPassword] = useState("");
+ const [destination, setDestination] = useState<ExportDestination>(
+ destinations[0] ?? ExportDestination.DOWNLOAD
+ );
+ const isDownload = destination !== ExportDestination.SHAREPOINT;
const resetForm = useCallback(() => {
setLimit(defaultLimit);
setFormat(supportFormats[0]);
setPassword("");
- }, [defaultLimit, supportFormats]);
+ setDestination(destinations[0] ?? ExportDestination.DOWNLOAD);
+ }, [defaultLimit, supportFormats, destinations]);
// Reset form whenever the drawer transitions to OPEN. Depending on
// `resetForm` here would re-fire the reset on every parent re-render
@@ -247,23 +286,41 @@ export function DataExportButton({
const buttonText = text ?? t("common.export");
const currentOption: ExportOption = useMemo(
- () => ({ limit, format, password }),
- [limit, format, password]
+ () => ({
+ limit,
+ format,
+ password: isDownload ? password : "",
+ destination,
+ }),
+ [limit, format, password, destination, isDownload]
);
const validateOption = validate ?? (() => true);
- const formIsValid = limit > 0 && validateOption(currentOption);
+ const formIsValid =
+ limit > 0 &&
+ destinations.includes(destination) &&
+ validateOption(currentOption);
const doExport = useCallback(() => {
if (isRequesting) return;
setIsRequesting(true);
+ setProgress(undefined);
const options: ExportOption = { ...currentOption };
- new Promise<DownloadContent[]>((resolve, reject) => {
- onExport({ options, resolve, reject });
+ new Promise<ExportOutcome>((resolve, reject) => {
+ onExport({
+ options,
+ resolve,
+ reject,
+ onProgress: (done, total) => setProgress({ done, total }),
+ });
})
- .then((contents) => downloadAll(contents, options.format))
- .then(() => {
+ .then(async (outcome) => {
+ if (!Array.isArray(outcome)) {
+ setSharePointResults(outcome.sharepoint);
+ return;
+ }
+ await downloadAll(outcome, options.format);
pushNotification({
module: "bytebase",
style: "SUCCESS",
@@ -281,6 +338,7 @@ export function DataExportButton({
})
.finally(() => {
setIsRequesting(false);
+ setProgress(undefined);
setShowDrawer(false);
setShowPasswordDialog(false);
});
@@ -330,7 +388,7 @@ export function DataExportButton({
const handleSelectDropdownFormat = (selected: ExportFormat) => {
setFormat(selected);
- if (supportPassword) {
+ if (supportPassword && isDownload) {
setShowPasswordDialog(true);
} else {
// Run after state batched.
@@ -342,7 +400,7 @@ export function DataExportButton({
<Button
variant="default"
size={SIZE_TO_BUTTON[size]}
- disabled={disabled || isRequesting}
+ disabled={disabled || isRequesting || exportUnavailable}
onClick={(e) => {
e.preventDefault();
if (viewMode === "DRAWER") setShowDrawer(true);
@@ -357,13 +415,13 @@ export function DataExportButton({
const dropdownTrigger = (
<DropdownMenu>
- <Tooltip content={tooltip} side="bottom">
+ <Tooltip content={triggerTooltip} side="bottom">
<DropdownMenuTrigger
render={
<Button
variant="default"
size={SIZE_TO_BUTTON[size]}
- disabled={disabled || isRequesting}
+ disabled={disabled || isRequesting || exportUnavailable}
className={cn("gap-x-1", className)}
aria-label={buttonText}
>
@@ -394,7 +452,7 @@ export function DataExportButton({
{viewMode === "DROPDOWN" ? (
dropdownTrigger
) : (
- <Tooltip content={tooltip} side="bottom">
+ <Tooltip content={triggerTooltip} side="bottom">
{triggerButton}
</Tooltip>
)}
@@ -411,6 +469,37 @@ export function DataExportButton({
<FormFieldGroup>
{formContent}
+ {destinations.length > 1 ? (
+ <FormField title={t("export-data.destination.self")}>
+ <RadioGroup
+ aria-label={t("export-data.destination.self")}
+ className="flex-col items-start gap-y-2"
+ value={String(destination)}
+ onValueChange={(value) =>
+ setDestination(Number(value) as ExportDestination)
+ }
+ >
+ {destinations.map((option) => (
+ <RadioGroupItem key={option} value={String(option)}>
+ <DestinationLabel
+ destination={option}
+ sharepointUrl={sharepointUrl}
+ />
+ </RadioGroupItem>
+ ))}
+ </RadioGroup>
+ </FormField>
+ ) : (
+ destination === ExportDestination.SHAREPOINT && (
+ <FormField title={t("export-data.destination.self")}>
+ <DestinationLabel
+ destination={destination}
+ sharepointUrl={sharepointUrl}
+ />
+ </FormField>
+ )
+ )}
+
<FormField title={t("export-data.export-rows")}>
<MaxRowCountSelect
value={limit}
@@ -427,7 +516,10 @@ export function DataExportButton({
if (value) setFormat(Number(value) as ExportFormat);
}}
>
- <SelectTrigger className="w-full">
+ <SelectTrigger
+ className="w-full"
+ aria-label={t("export-data.export-format")}
+ >
<SelectValue>{ExportFormat[format]}</SelectValue>
</SelectTrigger>
<SelectContent>
@@ -440,9 +532,16 @@ export function DataExportButton({
</Select>
</FormField>
- {supportPassword && (
- <FormField title={t("export-data.password-optional")}>
+ {supportPassword && isDownload && (
+ <FormField
+ title={
+ <FormLabel htmlFor="data-export-password">
+ {t("export-data.password-optional")}
+ </FormLabel>
+ }
+ >
<Input
+ id="data-export-password"
type="password"
autoComplete="new-password"
value={password}
@@ -456,7 +555,7 @@ export function DataExportButton({
size="sm"
onClick={handleGeneratePassword}
>
- <Wand2 className="size-4 mr-1" />
+ <Wand2 className="size-4" />
{t("export-data.generate-password")}
</Button>
<Button
@@ -466,7 +565,7 @@ export function DataExportButton({
disabled={!password}
onClick={() => void copyPasswordToClipboard(password)}
>
- <Copy className="size-4 mr-1" />
+ <Copy className="size-4" />
{t("common.copy")}
</Button>
</FormControlRow>
@@ -476,6 +575,24 @@ export function DataExportButton({
</FormFieldGroup>
</SheetBody>
<SheetFooter>
+ {isRequesting && (
+ <div className="min-w-0 flex-1">
+ <Progress
+ className="max-w-80"
+ value={
+ progress && progress.total > 1 ? progress.done : null
+ }
+ max={progress?.total}
+ label={
+ progress && progress.total > 1
+ ? t("export-data.progress.databases", progress)
+ : isDownload
+ ? t("export-data.progress.download")
+ : t("export-data.progress.sharepoint")
+ }
+ />
+ </div>
+ )}
<Button appearance="outline" onClick={() => setShowDrawer(false)}>
{t("common.cancel")}
</Button>
@@ -527,6 +644,34 @@ export function DataExportButton({
</DialogContent>
</Dialog>
)}
+
+ <SharePointExportResultDialog
+ results={sharePointResults}
+ onClose={() => setSharePointResults([])}
+ />
</>
);
}
+
+function DestinationLabel({
+ destination,
+ sharepointUrl,
+}: {
+ destination: ExportDestination;
+ sharepointUrl?: string;
+}) {
+ const { t } = useTranslation();
+ if (destination !== ExportDestination.SHAREPOINT) {
+ return <span>{t("export-data.destination.download")}</span>;
+ }
+ return (
+ <span className="flex flex-col">
+ <span>{t("export-data.destination.sharepoint")}</span>
+ {sharepointUrl && (
+ <span className="break-all text-xs text-control-light">
+ {formatSharePointUrl(sharepointUrl)}
+ </span>
+ )}
+ </span>
+ );
+}
diff --git a/frontend/src/components/SharePointExportResultDialog.test.tsx b/frontend/src/components/SharePointExportResultDialog.test.tsx
new file mode 100644
index 0000000000..a79414c62c
--- /dev/null
+++ b/frontend/src/components/SharePointExportResultDialog.test.tsx
@@ -0,0 +1,110 @@
+import { Code, ConnectError } from "@connectrpc/connect";
+import { render, screen } from "@testing-library/react";
+import { describe, expect, test, vi } from "vitest";
+import {
+ SharePointExportResultDialog,
+ toExportedSharePointResult,
+ toFailedSharePointExport,
+} from "./SharePointExportResultDialog";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+describe("toFailedSharePointExport", () => {
+ test("treats UNAVAILABLE as an upload that could not be confirmed", () => {
+ expect(
+ toFailedSharePointExport(
+ "db",
+ new ConnectError("files may exist", Code.Unavailable)
+ )
+ ).toEqual({ database: "db", status: "UNCONFIRMED", reason: "files may exist" });
+ });
+
+ test("treats other errors as failures", () => {
+ expect(
+ toFailedSharePointExport(
+ "db",
+ new ConnectError("not found", Code.FailedPrecondition)
+ )
+ ).toEqual({ database: "db", status: "FAILED", reason: "not found" });
+ expect(toFailedSharePointExport("db", new Error("boom"))).toEqual({
+ database: "db",
+ status: "FAILED",
+ reason: "Error: boom",
+ });
+ });
+});
+
+describe("toExportedSharePointResult", () => {
+ test("uses the exported folder URI", () => {
+ expect(
+ toExportedSharePointResult("db", "https://folder", "https://destination")
+ ).toEqual({
+ database: "db",
+ status: "EXPORTED",
+ uri: "https://folder",
+ });
+ });
+
+ test("links to the destination when the response has no URI", () => {
+ expect(
+ toExportedSharePointResult("db", "", "https://destination")
+ ).toEqual({
+ database: "db",
+ status: "EXPORTED",
+ uri: "https://destination",
+ });
+ });
+});
+
+describe("SharePointExportResultDialog", () => {
+ test("shows exported, failed, and unconfirmed databases separately", () => {
+ render(
+ <SharePointExportResultDialog
+ results={[
+ {
+ database: "a",
+ status: "EXPORTED",
+ uri: "https://contoso.sharepoint.com/Exports/20261022-a",
+ },
+ { database: "b", status: "FAILED", reason: "not found" },
+ { database: "c", status: "UNCONFIRMED", reason: "files may exist" },
+ ]}
+ onClose={vi.fn()}
+ />
+ );
+
+ expect(
+ screen.getByText("export-data.sharepoint.result-title")
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText("https://contoso.sharepoint.com/Exports/20261022-a")
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("link", { name: "export-data.sharepoint.open" })
+ ).toHaveAttribute(
+ "href",
+ "https://contoso.sharepoint.com/Exports/20261022-a"
+ );
+ expect(screen.getByText("not found")).toBeInTheDocument();
+ expect(screen.getByText("files may exist")).toBeInTheDocument();
+ expect(
+ screen.getByText("export-data.sharepoint.status.unconfirmed")
+ ).toBeInTheDocument();
+ });
+
+ test("titles an all-exported result as exported", () => {
+ render(
+ <SharePointExportResultDialog
+ results={[
+ { database: "a", status: "EXPORTED", uri: "https://a" },
+ ]}
+ onClose={vi.fn()}
+ />
+ );
+ expect(
+ screen.getByText("export-data.sharepoint.exported-title")
+ ).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/components/SharePointExportResultDialog.tsx b/frontend/src/components/SharePointExportResultDialog.tsx
new file mode 100644
index 0000000000..e53c60157c
--- /dev/null
+++ b/frontend/src/components/SharePointExportResultDialog.tsx
@@ -0,0 +1,144 @@
+import { Code, ConnectError } from "@connectrpc/connect";
+import { ExternalLink } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
+
+// SharePoint URLs arrive percent-encoded; show them as people typed them.
+export function formatSharePointUrl(url: string): string {
+ try {
+ return decodeURI(url);
+ } catch {
+ return url;
+ }
+}
+
+export type SharePointExportResult = {
+ database: string;
+} & (
+ | { status: "EXPORTED"; uri: string }
+ | { status: "FAILED" | "UNCONFIRMED"; reason: string }
+);
+
+// `uri` is the folder created for this export; falls back to the destination
+// URL when the response omits it.
+export function toExportedSharePointResult(
+ database: string,
+ uri: string,
+ destinationUrl: string
+): SharePointExportResult {
+ return { database, status: "EXPORTED", uri: uri || destinationUrl };
+}
+
+// The Export API reports an upload it could not confirm as UNAVAILABLE.
+export function toFailedSharePointExport(
+ database: string,
+ error: unknown
+): SharePointExportResult {
+ if (error instanceof ConnectError) {
+ return {
+ database,
+ status: error.code === Code.Unavailable ? "UNCONFIRMED" : "FAILED",
+ reason: error.rawMessage,
+ };
+ }
+ return { database, status: "FAILED", reason: String(error) };
+}
+
+interface Props {
+ results: SharePointExportResult[];
+ onClose: () => void;
+}
+
+export function SharePointExportResultDialog({ results, onClose }: Props) {
+ const { t } = useTranslation();
+ const allExported = results.every((r) => r.status === "EXPORTED");
+
+ return (
+ <Dialog
+ open={results.length > 0}
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <DialogContent className="max-w-lg">
+ <div className="flex flex-col gap-y-4">
+ <DialogTitle>
+ {allExported
+ ? t("export-data.sharepoint.exported-title")
+ : t("export-data.sharepoint.result-title")}
+ </DialogTitle>
+ <ul className="flex flex-col divide-y divide-block-border rounded-sm border border-block-border">
+ {results.map((result) => (
+ <li
+ key={result.database}
+ className="flex flex-col gap-y-1 px-4 py-3 text-sm"
+ >
+ <div className="flex items-center justify-between gap-x-2">
+ <span className="truncate font-medium">
+ {result.database}
+ </span>
+ <ExportStatusBadge status={result.status} />
+ </div>
+ {result.status === "EXPORTED" ? (
+ result.uri && (
+ <>
+ <span className="break-all text-control-light">
+ {formatSharePointUrl(result.uri)}
+ </span>
+ <a
+ href={result.uri}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex w-fit items-center gap-x-1 text-accent hover:underline"
+ >
+ {t("export-data.sharepoint.open")}
+ <ExternalLink className="size-3" />
+ </a>
+ </>
+ )
+ ) : (
+ <span className="break-words text-control-light">
+ {result.reason}
+ </span>
+ )}
+ </li>
+ ))}
+ </ul>
+ <div className="flex justify-end">
+ <Button onClick={onClose}>{t("common.close")}</Button>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function ExportStatusBadge({
+ status,
+}: {
+ status: SharePointExportResult["status"];
+}) {
+ const { t } = useTranslation();
+ switch (status) {
+ case "EXPORTED":
+ return (
+ <Badge variant="success">
+ {t("export-data.sharepoint.status.exported")}
+ </Badge>
+ );
+ case "UNCONFIRMED":
+ return (
+ <Badge variant="warning">
+ {t("export-data.sharepoint.status.unconfirmed")}
+ </Badge>
+ );
+ case "FAILED":
+ return (
+ <Badge variant="destructive">
+ {t("export-data.sharepoint.status.failed")}
+ </Badge>
+ );
+ }
+}
diff --git a/frontend/src/components/ui/progress.tsx b/frontend/src/components/ui/progress.tsx
new file mode 100644
index 0000000000..59bdfdee2a
--- /dev/null
+++ b/frontend/src/components/ui/progress.tsx
@@ -0,0 +1,31 @@
+import { Progress as BaseProgress } from "@base-ui/react/progress";
+import type { ReactNode } from "react";
+import { cn } from "@/lib/utils";
+
+interface ProgressProps {
+ /** Progress toward `max`; null shows an indeterminate bar. */
+ value: number | null;
+ max?: number;
+ /** Visible text above the bar that also names it for assistive technology. */
+ label: ReactNode;
+ className?: string;
+}
+
+function Progress({ value, max = 100, label, className }: ProgressProps) {
+ return (
+ <BaseProgress.Root
+ value={value}
+ max={max}
+ className={cn("flex w-full flex-col gap-y-1.5", className)}
+ >
+ <BaseProgress.Label className="text-xs text-control-light">
+ {label}
+ </BaseProgress.Label>
+ <BaseProgress.Track className="relative h-1 w-full overflow-hidden rounded-xs bg-control-bg">
+ <BaseProgress.Indicator className="h-full bg-accent transition-all duration-300 data-indeterminate:w-1/3 data-indeterminate:animate-progress-indeterminate" />
+ </BaseProgress.Track>
+ </BaseProgress.Root>
+ );
+}
+
+export { Progress };
diff --git a/frontend/src/locales/dynamic/en-US.json b/frontend/src/locales/dynamic/en-US.json
index e15afddb20..d7621562bb 100644
--- a/frontend/src/locales/dynamic/en-US.json
+++ b/frontend/src/locales/dynamic/en-US.json
@@ -273,6 +273,10 @@
"desc": "System for Cross-domain Identity Management support.",
"title": "SCIM"
},
+ "FEATURE_SHAREPOINT_EXPORT": {
+ "desc": "Upload SQL Editor exports to SharePoint document libraries.",
+ "title": "SharePoint export"
+ },
"FEATURE_SQL_EDITOR_ADMIN_MODE": {
"desc": "Access administrative functions in the SQL editor.",
"title": "SQL editor admin mode"
diff --git a/frontend/src/locales/dynamic/es-ES.json b/frontend/src/locales/dynamic/es-ES.json
index 26a4c93114..04c38ba2b1 100644
--- a/frontend/src/locales/dynamic/es-ES.json
+++ b/frontend/src/locales/dynamic/es-ES.json
@@ -273,6 +273,10 @@
"desc": "Soporte para Sistema de Gestión de Identidad entre Dominios.",
"title": "SCIM"
},
+ "FEATURE_SHAREPOINT_EXPORT": {
+ "desc": "Sube las exportaciones del Editor SQL a bibliotecas de documentos de SharePoint.",
+ "title": "Exportación a SharePoint"
+ },
"FEATURE_SQL_EDITOR_ADMIN_MODE": {
"desc": "Acceda a funciones administrativas en el editor SQL.",
"title": "Modo administrador del editor SQL"
diff --git a/frontend/src/locales/dynamic/ja-JP.json b/frontend/src/locales/dynamic/ja-JP.json
index fca4dea127..30a2c31aca 100644
--- a/frontend/src/locales/dynamic/ja-JP.json
+++ b/frontend/src/locales/dynamic/ja-JP.json
@@ -273,6 +273,10 @@
"desc": "クロスドメインアイデンティティ管理のためのシステムサポート。",
"title": "SCIM"
},
+ "FEATURE_SHAREPOINT_EXPORT": {
+ "desc": "SQL エディターのエクスポートを SharePoint ドキュメントライブラリにアップロードします。",
+ "title": "SharePoint エクスポート"
+ },
"FEATURE_SQL_EDITOR_ADMIN_MODE": {
"desc": "SQLエディターで管理機能にアクセスします。",
"title": "SQLエディター管理者モード"
diff --git a/frontend/src/locales/dynamic/vi-VN.json b/frontend/src/locales/dynamic/vi-VN.json
index 18b74f4a5b..b0c5a5735f 100644
--- a/frontend/src/locales/dynamic/vi-VN.json
+++ b/frontend/src/locales/dynamic/vi-VN.json
@@ -273,6 +273,10 @@
"desc": "Hỗ trợ System for Cross-domain Identity Management.",
"title": "SCIM"
},
+ "FEATURE_SHAREPOINT_EXPORT": {
+ "desc": "Tải các bản xuất từ SQL Editor lên thư viện tài liệu SharePoint.",
+ "title": "Xuất sang SharePoint"
+ },
"FEATURE_SQL_EDITOR_ADMIN_MODE": {
"desc": "Truy cập các chức năng quản trị trong trình soạn thảo SQL.",
"title": "Chế độ quản trị SQL editor"
diff --git a/frontend/src/locales/dynamic/zh-CN.json b/frontend/src/locales/dynamic/zh-CN.json
index 5476c96e8f..6bfecad915 100644
--- a/frontend/src/locales/dynamic/zh-CN.json
+++ b/frontend/src/locales/dynamic/zh-CN.json
@@ -273,6 +273,10 @@
"desc": "跨域身份管理系统支持。",
"title": "SCIM"
},
+ "FEATURE_SHAREPOINT_EXPORT": {
+ "desc": "将 SQL 编辑器的导出文件上传到 SharePoint 文档库。",
+ "title": "SharePoint 导出"
+ },
"FEATURE_SQL_EDITOR_ADMIN_MODE": {
"desc": "在 SQL 编辑器中访问管理功能。",
"title": "SQL 编辑器管理员模式"
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index d4f3fb1b13..041ac75664 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1081,11 +1081,32 @@
"unexpected-error-description": "An unexpected error occurred while displaying this page. Refreshing usually fixes it; if it keeps happening, please report the issue to your administrator."
},
"export-data": {
+ "destination": {
+ "download": "Download",
+ "self": "Destination",
+ "sharepoint": "SharePoint"
+ },
"export-format": "Export format",
"export-rows": "Export rows",
"generate-password": "Generate password",
+ "no-destination": "No available export destinations",
"password-info": "Provide a password to encrypt the export file.",
- "password-optional": "Encrypt with password (Optional)"
+ "password-optional": "Encrypt with password (Optional)",
+ "progress": {
+ "databases": "Exported {{done}} of {{total}} databases",
+ "download": "Exporting…",
+ "sharepoint": "Exporting to SharePoint…"
+ },
+ "sharepoint": {
+ "exported-title": "Exported to SharePoint",
+ "open": "Open in SharePoint",
+ "result-title": "SharePoint export results",
+ "status": {
+ "exported": "Exported",
+ "failed": "Failed",
+ "unconfirmed": "Not confirmed"
+ }
+ }
},
"gitops": {
"back-to-releases": "Back to Releases",
@@ -2406,6 +2427,12 @@
"settings": {
"confirm-archive-project": "Archiving \"{{name}}\" will make it read-only and hide it from active project lists. All issues, databases, and settings will be preserved. You can restore it later from the archived projects list.",
"confirm-delete-project": "Deleting \"{{name}}\" will permanently remove the project and all associated data including issues, configurations, and history. All databases in this project will be moved to the default project. This action cannot be undone.",
+ "export-destination": {
+ "description": "Where exports from this project are uploaded.",
+ "self": "Export destinations",
+ "sharepoint-placeholder": "https://contoso.sharepoint.com/sites/Finance/Shared Documents/Exports",
+ "update-failed": "The export destination was not saved"
+ },
"issue-related": {
"allow-access-grants": {
"description": "Allow project members to request time-boxed access grants for specific read-only statements. Grants can also cover exporting results and viewing unmasked data.",
@@ -2806,6 +2833,12 @@
"self": "Account settings",
"update-password": "Update password"
},
+ "export-destinations": {
+ "configured": "Configured",
+ "description": "Where SQL Editor exports can be uploaded. Each project chooses its destination folder in Project Settings.",
+ "not-configured": "Not configured",
+ "provider": "Provider"
+ },
"general": {
"workspace": {
"access-token-duration": {
@@ -2852,6 +2885,10 @@
"description": "When enabled, users can choose between admin and read-only data sources. When disabled, users are forced to use read-only data sources if configured, otherwise fall back to admin data sources.",
"self": "Allow querying the admin data source"
},
+ "allow-download": {
+ "description": "When off, exports can go only to a storage destination configured for the project, such as SharePoint, even with an approved export access grant.",
+ "self": "Allow download"
+ },
"allow-email-code-signin": {
"description": "Users can sign in or sign up by entering a 6-digit code delivered to their email address.",
"enable": "Allow sign-in with email code",
@@ -3077,7 +3114,7 @@
"title": "Approve or reject issues"
},
"export": {
- "details": "Download results as a file. Data leaves Bytebase.",
+ "details": "Export results as files. Data leaves Bytebase.",
"title": "Export query results"
},
"manage": {
@@ -3403,11 +3440,30 @@
}
}
},
+ "sharepoint": {
+ "caption": "Microsoft Entra application",
+ "client-id": "Client ID",
+ "client-secret": "Client secret",
+ "client-secret-description": "The client secret of the Microsoft Entra application. It cannot be read back after saving.",
+ "client-secret-saved": "A client secret is saved. Enter a new one to replace it.",
+ "remove": {
+ "description": "The application credentials are deleted. Projects keep their SharePoint folders, but exports to SharePoint fail until an application is configured again.",
+ "title": "Remove SharePoint?"
+ },
+ "setup": {
+ "grant": "Grant the application write access to each destination library. Bytebase does not manage SharePoint permissions, retention, or deletion.",
+ "project": "Set each project's destination folder in Project Settings.",
+ "register": "Register an application in Microsoft Entra ID with the Lists.SelectedOperations.Selected application permission, and create a client secret.",
+ "title": "Before you start"
+ },
+ "tenant-id": "Tenant ID"
+ },
"sidebar": {
"audit-log": "Audit Logs",
"custom-roles": "Custom Roles",
"data-access": "Data Access",
"data-classification": "Data Classification",
+ "export-destinations": "Export Destinations",
"general": "General",
"global-masking": "Global Masking",
"iam-and-admin": "IAM & Admin",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 1402478b0d..059c0bdef9 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1081,11 +1081,32 @@
"unexpected-error-description": "Se produjo un error inesperado al mostrar esta página. Actualizar suele solucionarlo; si persiste, informa el problema a tu administrador."
},
"export-data": {
+ "destination": {
+ "download": "Descarga",
+ "self": "Destino",
+ "sharepoint": "SharePoint"
+ },
"export-format": "Formato de exportación",
"export-rows": "Exportar filas",
"generate-password": "Generar contraseña",
+ "no-destination": "No hay destinos de exportación disponibles",
"password-info": "Proporcione una contraseña para cifrar el archivo de exportación.",
- "password-optional": "Cifrar con contraseña (opcional)"
+ "password-optional": "Cifrar con contraseña (opcional)",
+ "progress": {
+ "databases": "{{done}} de {{total}} bases de datos exportadas",
+ "download": "Exportando…",
+ "sharepoint": "Exportando a SharePoint…"
+ },
+ "sharepoint": {
+ "exported-title": "Exportado a SharePoint",
+ "open": "Abrir en SharePoint",
+ "result-title": "Resultados de la exportación a SharePoint",
+ "status": {
+ "exported": "Exportado",
+ "failed": "Error",
+ "unconfirmed": "Sin confirmar"
+ }
+ }
},
"gitops": {
"back-to-releases": "Volver a Lanzamientos",
@@ -2406,6 +2427,12 @@
"settings": {
"confirm-archive-project": "Archivar \"{{name}}\" lo hará de solo lectura y lo ocultará de las listas de proyectos activos. Se conservarán todos los issues, bases de datos y configuraciones. Puede restaurarlo más tarde desde la lista de proyectos archivados.",
"confirm-delete-project": "Eliminar \"{{name}}\" eliminará permanentemente el proyecto y todos los datos asociados, incluidos issues, configuraciones e historial. Todas las bases de datos de este proyecto se moverán al proyecto predeterminado. Esta acción no se puede deshacer.",
+ "export-destination": {
+ "description": "Dónde se suben las exportaciones de este proyecto.",
+ "self": "Destinos de exportación",
+ "sharepoint-placeholder": "https://contoso.sharepoint.com/sites/Finance/Shared Documents/Exports",
+ "update-failed": "No se guardó el destino de exportación"
+ },
"issue-related": {
"allow-access-grants": {
"description": "Permite a los miembros del proyecto solicitar concesiones de acceso con límite de tiempo para sentencias específicas de solo lectura. Las concesiones también pueden incluir la exportación de resultados y la visualización de datos sin enmascarar.",
@@ -2806,6 +2833,12 @@
"self": "Configuración de la cuenta",
"update-password": "Actualizar contraseña"
},
+ "export-destinations": {
+ "configured": "Configurado",
+ "description": "Dónde se pueden subir las exportaciones del Editor de SQL. Cada proyecto elige su carpeta de destino en la configuración del proyecto.",
+ "not-configured": "Sin configurar",
+ "provider": "Proveedor"
+ },
"general": {
"workspace": {
"access-token-duration": {
@@ -2852,6 +2885,10 @@
"description": "Cuando está habilitado, los usuarios pueden elegir entre fuentes de datos de administración y de solo lectura. Cuando está deshabilitado, los usuarios se ven obligados a usar fuentes de datos de solo lectura si están configuradas; de lo contrario, vuelven a usar fuentes de datos de administración.",
"self": "Permitir consultar la fuente de datos de administración"
},
+ "allow-download": {
+ "description": "Si se desactiva, las exportaciones solo pueden ir a un destino de almacenamiento configurado para el proyecto, como SharePoint, incluso con una concesión de acceso de exportación aprobada.",
+ "self": "Permitir descarga"
+ },
"allow-email-code-signin": {
"description": "Los usuarios pueden iniciar sesión o registrarse introduciendo un código de 6 dígitos enviado a su correo electrónico.",
"enable": "Permitir inicio de sesión con código por email",
@@ -3077,7 +3114,7 @@
"title": "Aprobar o rechazar issues"
},
"export": {
- "details": "Descargar resultados como archivo. Los datos salen de Bytebase.",
+ "details": "Exportar resultados como archivos. Los datos salen de Bytebase.",
"title": "Exportar resultados de consulta"
},
"manage": {
@@ -3403,11 +3440,30 @@
}
}
},
+ "sharepoint": {
+ "caption": "Aplicación de Microsoft Entra",
+ "client-id": "ID de cliente",
+ "client-secret": "Secreto de cliente",
+ "client-secret-description": "El secreto de cliente de la aplicación de Microsoft Entra. No se puede volver a leer después de guardarlo.",
+ "client-secret-saved": "Hay un secreto de cliente guardado. Introduzca uno nuevo para reemplazarlo.",
+ "remove": {
+ "description": "Se eliminan las credenciales de la aplicación. Los proyectos conservan sus carpetas de SharePoint, pero las exportaciones a SharePoint fallarán hasta que se vuelva a configurar una aplicación.",
+ "title": "¿Eliminar SharePoint?"
+ },
+ "setup": {
+ "grant": "Conceda a la aplicación acceso de escritura a cada biblioteca de destino. Bytebase no administra los permisos, la retención ni la eliminación en SharePoint.",
+ "project": "Configure la carpeta de destino de cada proyecto en la configuración del proyecto.",
+ "register": "Registre una aplicación en Microsoft Entra ID con el permiso de aplicación Lists.SelectedOperations.Selected y cree un secreto de cliente.",
+ "title": "Antes de empezar"
+ },
+ "tenant-id": "ID de inquilino"
+ },
"sidebar": {
"audit-log": "Registros de auditoría",
"custom-roles": "Roles personalizados",
"data-access": "Acceso a datos",
"data-classification": "Clasificación de datos",
+ "export-destinations": "Destinos de exportación",
"general": "General",
"global-masking": "Enmascaramiento Global",
"iam-and-admin": "IAM y administración",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index ab4773fdfc..85bfea9ab5 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -1081,11 +1081,32 @@
"unexpected-error-description": "このページの表示中に予期しないエラーが発生しました。通常は更新すると解決します。問題が続く場合は、管理者にご報告ください。"
},
"export-data": {
+ "destination": {
+ "download": "ダウンロード",
+ "self": "エクスポート先",
+ "sharepoint": "SharePoint"
+ },
"export-format": "エクスポート形式",
"export-rows": "エクスポート行数",
"generate-password": "パスワードを生成",
+ "no-destination": "利用可能なエクスポート先がありません",
"password-info": "エクスポートされたファイルを暗号化するためのパスワードを入力します",
- "password-optional": "パスワード暗号化の設定 (オプション)"
+ "password-optional": "パスワード暗号化の設定 (オプション)",
+ "progress": {
+ "databases": "{{total}} 件中 {{done}} 件のデータベースをエクスポートしました",
+ "download": "エクスポートしています…",
+ "sharepoint": "SharePoint にエクスポートしています…"
+ },
+ "sharepoint": {
+ "exported-title": "SharePoint にエクスポートしました",
+ "open": "SharePoint で開く",
+ "result-title": "SharePoint エクスポートの結果",
+ "status": {
+ "exported": "エクスポート済み",
+ "failed": "失敗",
+ "unconfirmed": "未確認"
+ }
+ }
},
"gitops": {
"back-to-releases": "リリースに戻る",
@@ -2406,6 +2427,12 @@
"settings": {
"confirm-archive-project": "\"{{name}}\" をアーカイブすると、読み取り専用になり、アクティブなプロジェクト一覧から非表示になります。すべての Issue、データベース、設定は保持されます。後でアーカイブ済みプロジェクト一覧から復元できます。",
"confirm-delete-project": "\"{{name}}\" を削除すると、Issue、設定、履歴を含むプロジェクトとそれに関連するすべてのデータが完全に削除されます。このプロジェクト内のすべてのデータベースはデフォルトプロジェクトに移動されます。この操作は元に戻せません。",
+ "export-destination": {
+ "description": "このプロジェクトのエクスポートのアップロード先です。",
+ "self": "エクスポート先",
+ "sharepoint-placeholder": "https://contoso.sharepoint.com/sites/Finance/Shared Documents/Exports",
+ "update-failed": "エクスポート先は保存されませんでした"
+ },
"issue-related": {
"allow-access-grants": {
"description": "プロジェクトメンバーが特定の読み取り専用ステートメントに対して期限付きのアクセス付与をリクエストできるようにします。付与には結果のエクスポートやマスク解除データの閲覧を含めることもできます。",
@@ -2806,6 +2833,12 @@
"self": "アカウント設定",
"update-password": "パスワードを更新"
},
+ "export-destinations": {
+ "configured": "設定済み",
+ "description": "SQLエディタのエクスポートをアップロードできる場所です。各プロジェクトはプロジェクト設定で保存先フォルダーを選択します。",
+ "not-configured": "未設定",
+ "provider": "プロバイダー"
+ },
"general": {
"workspace": {
"access-token-duration": {
@@ -2852,6 +2885,10 @@
"description": "有効にすると、ユーザーは管理データソースと読み取り専用データソースのどちらかを選択できます。無効にすると、読み取り専用データソースが設定されている場合は強制的に読み取り専用データソースを使用し、設定されていない場合は管理データソースにフォールバックします。",
"self": "管理データソースのクエリを許可する"
},
+ "allow-download": {
+ "description": "オフにすると、エクスポートはプロジェクトに設定されたストレージ先(SharePoint など)にのみ送信できます。承認済みのエクスポートアクセス許可があってもダウンロードはできません。",
+ "self": "ダウンロードを許可する"
+ },
"allow-email-code-signin": {
"description": "ユーザーはメールアドレスに送信された6桁のコードを入力してサインインまたはサインアップできます。",
"enable": "メール認証コードによるサインインを許可する",
@@ -3077,7 +3114,7 @@
"title": "Issue の承認・却下"
},
"export": {
- "details": "結果をファイルとしてダウンロードします。データが Bytebase の外に出ます。",
+ "details": "結果をファイルとしてエクスポートします。データが Bytebase の外に出ます。",
"title": "クエリ結果をエクスポートする"
},
"manage": {
@@ -3403,11 +3440,30 @@
}
}
},
+ "sharepoint": {
+ "caption": "Microsoft Entra アプリケーション",
+ "client-id": "クライアント ID",
+ "client-secret": "クライアントシークレット",
+ "client-secret-description": "Microsoft Entra アプリケーションのクライアントシークレットです。保存後は読み取れません。",
+ "client-secret-saved": "クライアントシークレットは保存済みです。置き換えるには新しい値を入力してください。",
+ "remove": {
+ "description": "アプリケーションの資格情報が削除されます。プロジェクトの SharePoint フォルダー設定は残りますが、アプリケーションを再設定するまで SharePoint へのエクスポートは失敗します。",
+ "title": "SharePoint を削除しますか?"
+ },
+ "setup": {
+ "grant": "各保存先ライブラリへの書き込みアクセスをアプリケーションに付与します。Bytebase は SharePoint の権限、保持、削除を管理しません。",
+ "project": "各プロジェクトの保存先フォルダーはプロジェクト設定で指定します。",
+ "register": "Microsoft Entra ID にアプリケーションを登録して Lists.SelectedOperations.Selected アプリケーション権限を付与し、クライアントシークレットを作成します。",
+ "title": "始める前に"
+ },
+ "tenant-id": "テナント ID"
+ },
"sidebar": {
"audit-log": "監査ログ",
"custom-roles": "カスタムロール",
"data-access": "データアクセス",
"data-classification": "データ分類",
+ "export-destinations": "エクスポート先",
"general": "全般",
"global-masking": "グローバルマスキング",
"iam-and-admin": "IAM と管理",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index cdb22217a0..b419f443f1 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -1081,11 +1081,32 @@
"unexpected-error-description": "Đã xảy ra lỗi không mong muốn khi hiển thị trang này. Tải lại thường sẽ khắc phục được; nếu lỗi tiếp diễn, vui lòng báo cáo cho quản trị viên."
},
"export-data": {
+ "destination": {
+ "download": "Tải xuống",
+ "self": "Đích xuất",
+ "sharepoint": "SharePoint"
+ },
"export-format": "Định dạng xuất",
"export-rows": "Xuất số dòng",
"generate-password": "Tạo mật khẩu",
+ "no-destination": "Không có đích xuất khả dụng",
"password-info": "Cung cấp mật khẩu để mã hóa tệp xuất.",
- "password-optional": "Mã hóa bằng mật khẩu (Tùy chọn)"
+ "password-optional": "Mã hóa bằng mật khẩu (Tùy chọn)",
+ "progress": {
+ "databases": "Đã xuất {{done}}/{{total}} cơ sở dữ liệu",
+ "download": "Đang xuất…",
+ "sharepoint": "Đang xuất sang SharePoint…"
+ },
+ "sharepoint": {
+ "exported-title": "Đã xuất sang SharePoint",
+ "open": "Mở trong SharePoint",
+ "result-title": "Kết quả xuất sang SharePoint",
+ "status": {
+ "exported": "Đã xuất",
+ "failed": "Thất bại",
+ "unconfirmed": "Chưa xác nhận"
+ }
+ }
},
"gitops": {
"back-to-releases": "Quay lại Bản phát hành",
@@ -2406,6 +2427,12 @@
"settings": {
"confirm-archive-project": "Việc lưu trữ \"{{name}}\" sẽ khiến nó trở thành chỉ đọc và ẩn khỏi danh sách dự án đang hoạt động. Tất cả issue, cơ sở dữ liệu và cài đặt sẽ được giữ lại. Bạn có thể khôi phục lại sau từ danh sách dự án đã lưu trữ.",
"confirm-delete-project": "Việc xóa \"{{name}}\" sẽ xóa vĩnh viễn dự án và tất cả dữ liệu liên quan bao gồm issue, cấu hình và lịch sử. Tất cả cơ sở dữ liệu trong dự án này sẽ được chuyển sang dự án mặc định. Hành động này không thể hoàn tác.",
+ "export-destination": {
+ "description": "Nơi tải lên các bản xuất của dự án này.",
+ "self": "Đích xuất",
+ "sharepoint-placeholder": "https://contoso.sharepoint.com/sites/Finance/Shared Documents/Exports",
+ "update-failed": "Chưa lưu đích xuất"
+ },
"issue-related": {
"allow-access-grants": {
"description": "Cho phép thành viên dự án yêu cầu cấp quyền truy cập có thời hạn cho các câu lệnh chỉ đọc cụ thể. Quyền được cấp cũng có thể bao gồm xuất kết quả và xem dữ liệu chưa che.",
@@ -2806,6 +2833,12 @@
"self": "Cài đặt tài khoản",
"update-password": "Cập nhật mật khẩu"
},
+ "export-destinations": {
+ "configured": "Đã cấu hình",
+ "description": "Nơi có thể tải lên các bản xuất từ Trình soạn thảo SQL. Mỗi dự án chọn thư mục đích trong Cài đặt dự án.",
+ "not-configured": "Chưa cấu hình",
+ "provider": "Nhà cung cấp"
+ },
"general": {
"workspace": {
"access-token-duration": {
@@ -2852,6 +2885,10 @@
"description": "Khi được bật, người dùng có thể chọn giữa nguồn dữ liệu quản trị và nguồn dữ liệu chỉ đọc. Khi bị tắt, người dùng buộc phải sử dụng nguồn dữ liệu chỉ đọc nếu được cấu hình, nếu không sẽ quay lại sử dụng nguồn dữ liệu quản trị.",
"self": "Cho phép truy vấn nguồn dữ liệu quản trị"
},
+ "allow-download": {
+ "description": "Khi tắt, dữ liệu xuất chỉ có thể được gửi đến đích lưu trữ đã cấu hình cho dự án, chẳng hạn như SharePoint, kể cả với quyền truy cập xuất đã được phê duyệt.",
+ "self": "Cho phép tải xuống"
+ },
"allow-email-code-signin": {
"description": "Người dùng có thể đăng nhập hoặc đăng ký bằng cách nhập mã 6 chữ số được gửi đến email của họ.",
"enable": "Cho phép đăng nhập bằng mã qua email",
@@ -3077,7 +3114,7 @@
"title": "Phê duyệt hoặc từ chối Issue"
},
"export": {
- "details": "Tải kết quả về dưới dạng tệp. Dữ liệu rời khỏi Bytebase.",
+ "details": "Xuất kết quả dưới dạng tệp. Dữ liệu rời khỏi Bytebase.",
"title": "Xuất kết quả truy vấn"
},
"manage": {
@@ -3403,11 +3440,30 @@
}
}
},
+ "sharepoint": {
+ "caption": "Ứng dụng Microsoft Entra",
+ "client-id": "ID client",
+ "client-secret": "Client secret",
+ "client-secret-description": "Client secret của ứng dụng Microsoft Entra. Không thể đọc lại sau khi lưu.",
+ "client-secret-saved": "Đã lưu client secret. Nhập giá trị mới để thay thế.",
+ "remove": {
+ "description": "Thông tin xác thực của ứng dụng sẽ bị xóa. Các dự án vẫn giữ thư mục SharePoint, nhưng việc xuất sang SharePoint sẽ thất bại cho đến khi ứng dụng được cấu hình lại.",
+ "title": "Gỡ bỏ SharePoint?"
+ },
+ "setup": {
+ "grant": "Cấp cho ứng dụng quyền ghi vào từng thư viện đích. Bytebase không quản lý quyền, lưu giữ hoặc xóa trong SharePoint.",
+ "project": "Đặt thư mục đích của từng dự án trong Cài đặt dự án.",
+ "register": "Đăng ký một ứng dụng trong Microsoft Entra ID với quyền ứng dụng Lists.SelectedOperations.Selected và tạo client secret.",
+ "title": "Trước khi bắt đầu"
+ },
+ "tenant-id": "ID tenant"
+ },
"sidebar": {
"audit-log": "Nhật ký kiểm tra",
"custom-roles": "Vai trò tùy chỉnh",
"data-access": "Truy cập dữ liệu",
"data-classification": "Phân loại dữ liệu",
+ "export-destinations": "Đích xuất",
"general": "Chung",
"global-masking": "Che giấu toàn cục",
"iam-and-admin": "IAM & Quản trị",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 1608fc4a30..d91ca1dddf 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1081,11 +1081,32 @@
"unexpected-error-description": "显示此页面时发生意外错误。刷新通常可以解决;如果问题持续出现,请联系管理员反馈。"
},
"export-data": {
+ "destination": {
+ "download": "下载",
+ "self": "导出目标",
+ "sharepoint": "SharePoint"
+ },
"export-format": "导出格式",
"export-rows": "导出行数",
"generate-password": "生成密码",
+ "no-destination": "没有可用的导出目标",
"password-info": "提供密码来对导出的文件进行加密",
- "password-optional": "设置密码加密(可选)"
+ "password-optional": "设置密码加密(可选)",
+ "progress": {
+ "databases": "已导出 {{done}}/{{total}} 个数据库",
+ "download": "正在导出…",
+ "sharepoint": "正在导出到 SharePoint…"
+ },
+ "sharepoint": {
+ "exported-title": "已导出到 SharePoint",
+ "open": "在 SharePoint 中打开",
+ "result-title": "SharePoint 导出结果",
+ "status": {
+ "exported": "已导出",
+ "failed": "失败",
+ "unconfirmed": "未确认"
+ }
+ }
},
"gitops": {
"back-to-releases": "返回发布包",
@@ -2406,6 +2427,12 @@
"settings": {
"confirm-archive-project": "归档「{{name}}」将使其变为只读并从活跃项目列表中隐藏。所有工单、数据库和设置将被保留。您可以稍后从已归档项目列表中恢复。",
"confirm-delete-project": "删除「{{name}}」将永久移除该项目及所有关联数据,包括工单、配置和历史记录。该项目中的所有数据库将被移至默认项目。此操作无法撤销。",
+ "export-destination": {
+ "description": "此项目的导出文件上传到的位置。",
+ "self": "导出目标",
+ "sharepoint-placeholder": "https://contoso.sharepoint.com/sites/Finance/Shared Documents/Exports",
+ "update-failed": "导出目标未保存"
+ },
"issue-related": {
"allow-access-grants": {
"description": "允许项目成员为特定只读语句申请限时访问授权。授权还可包含导出查询结果和查看未脱敏数据。",
@@ -2806,6 +2833,12 @@
"self": "账号设置",
"update-password": "更新密码"
},
+ "export-destinations": {
+ "configured": "已配置",
+ "description": "SQL 编辑器导出文件可上传到的位置。每个项目在项目设置中选择自己的目标文件夹。",
+ "not-configured": "未配置",
+ "provider": "提供方"
+ },
"general": {
"workspace": {
"access-token-duration": {
@@ -2852,6 +2885,10 @@
"description": "启用时,用户可以在主数据源和只读数据源之间进行选择。禁用时,如果配置了只读数据源,则强制用户使用只读数据源,否则回退到使用主数据源。",
"self": "允许查询主数据源"
},
+ "allow-download": {
+ "description": "关闭后,导出只能发送到项目配置的存储目标(如 SharePoint),已批准的导出访问授权也不能下载。",
+ "self": "允许下载"
+ },
"allow-email-code-signin": {
"description": "用户可以通过输入发送到邮箱的 6 位验证码进行登录或注册。",
"enable": "允许使用邮箱验证码登录",
@@ -3077,7 +3114,7 @@
"title": "批准或拒绝工单"
},
"export": {
- "details": "将结果下载为文件。数据会离开 Bytebase。",
+ "details": "将结果导出为文件。数据会离开 Bytebase。",
"title": "导出查询结果"
},
"manage": {
@@ -3403,11 +3440,30 @@
}
}
},
+ "sharepoint": {
+ "caption": "Microsoft Entra 应用",
+ "client-id": "客户端 ID",
+ "client-secret": "客户端密钥",
+ "client-secret-description": "Microsoft Entra 应用的客户端密钥。保存后无法读取。",
+ "client-secret-saved": "已保存客户端密钥。输入新密钥即可替换。",
+ "remove": {
+ "description": "应用凭据将被删除。项目会保留各自的 SharePoint 文件夹,但在重新配置应用之前,导出到 SharePoint 会失败。",
+ "title": "移除 SharePoint?"
+ },
+ "setup": {
+ "grant": "为该应用授予每个目标文档库的写入权限。Bytebase 不管理 SharePoint 的权限、保留或删除。",
+ "project": "在项目设置中为每个项目设置目标文件夹。",
+ "register": "在 Microsoft Entra ID 中注册应用,授予 Lists.SelectedOperations.Selected 应用程序权限,并创建客户端密钥。",
+ "title": "开始之前"
+ },
+ "tenant-id": "租户 ID"
+ },
"sidebar": {
"audit-log": "审计日志",
"custom-roles": "自定义角色",
"data-access": "数据访问",
"data-classification": "数据分类",
+ "export-destinations": "导出目标",
"general": "通用",
"global-masking": "全局数据脱敏",
"iam-and-admin": "IAM & 管理",
diff --git a/frontend/src/modules/sql-editor/components/ResultPanel/BatchQuerySelect.test.tsx b/frontend/src/modules/sql-editor/components/ResultPanel/BatchQuerySelect.test.tsx
index 979f647fac..2e7e76b8f3 100644
--- a/frontend/src/modules/sql-editor/components/ResultPanel/BatchQuerySelect.test.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultPanel/BatchQuerySelect.test.tsx
@@ -1,7 +1,8 @@
+import { Code, ConnectError } from "@connectrpc/connect";
import { act, type ReactNode } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { Engine } from "@/types/proto-es/v1/common_pb";
+import { Engine, ExportDestination } from "@/types/proto-es/v1/common_pb";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import { BatchQuerySelect } from "./BatchQuerySelect";
@@ -23,6 +24,10 @@ const mocks = vi.hoisted(() => ({
deleteDatabaseQueryContext: vi.fn(),
databasesWithExport: [] as string[],
useExportGrantBypass: vi.fn(),
+ destinations: [] as number[],
+ exportData: vi.fn(),
+ resolveExport: vi.fn(),
+ reportProgress: vi.fn(),
}));
vi.mock("react-i18next", () => ({
@@ -34,21 +39,53 @@ vi.mock("@/components/DataExportButton", () => ({
DataExportButton: ({
formContent,
text,
+ onExport,
}: {
formContent: ReactNode;
text: string;
+ onExport: (request: unknown) => void;
}) => (
<div data-testid="batch-export">
<span>{text}</span>
{formContent}
+ <button
+ type="button"
+ data-testid="batch-export-submit"
+ onClick={() =>
+ onExport({
+ options: {
+ format: 1,
+ limit: 100,
+ password: "",
+ destination: 2,
+ },
+ resolve: mocks.resolveExport,
+ reject: vi.fn(),
+ onProgress: mocks.reportProgress,
+ })
+ }
+ />
</div>
),
}));
vi.mock("@/components/database", () => ({
- DatabaseTableView: ({ databases }: { databases: Database[] }) => (
+ DatabaseTableView: ({
+ databases,
+ onSelectedNamesChange,
+ }: {
+ databases: Database[];
+ onSelectedNamesChange: (names: Set<string>) => void;
+ }) => (
<span data-testid="exportable">
{databases.map((database) => database.name).join(",")}
+ <button
+ type="button"
+ data-testid="select-all"
+ onClick={() =>
+ onSelectedNamesChange(new Set(databases.map((db) => db.name)))
+ }
+ />
</span>
),
}));
@@ -87,6 +124,13 @@ vi.mock("@/modules/sql-editor/components/useExportGrantBypass", () => ({
useExportGrantBypass: mocks.useExportGrantBypass,
}));
+vi.mock("@/modules/sql-editor/components/useExportDestination", () => ({
+ useExportDestination: () => ({
+ destinations: mocks.destinations,
+ sharepointUrl: "https://contoso.sharepoint.com/sites/x/Exports",
+ }),
+}));
+
vi.mock("@/modules/sql-editor/hooks/useSQLEditorState", () => ({
useSQLEditorDatabasesWithExport: (databases: Database[]) =>
new Set(
@@ -132,9 +176,10 @@ vi.mock("@/stores/app", () => {
const state = () => ({
databasesByName: mocks.databasesByName,
environmentList: [mocks.environment],
- exportData: vi.fn(),
+ exportData: mocks.exportData,
getDatabaseByName: (name: string) => mocks.databasesByName[name],
getEnvironmentByName: () => mocks.environment,
+ notify: vi.fn(),
});
return {
useAppStore: Object.assign(
@@ -171,6 +216,7 @@ describe("BatchQuerySelect", () => {
document.body.append(container);
root = createRoot(container);
mocks.databasesWithExport = [];
+ mocks.destinations = [ExportDestination.DOWNLOAD];
grantLookup([], []);
cellA = {
@@ -316,4 +362,63 @@ describe("BatchQuerySelect", () => {
`${cellA.name},${cellB.name}`
);
});
+
+ it("keeps Export but hides Request export when no destination is offered", () => {
+ mocks.destinations = [];
+ mocks.databasesWithExport = [cellA.name];
+ grantLookup([], [cellB.name]);
+ render();
+
+ expect(testId("batch-export")).not.toBeNull();
+ expect(testId("request-export")).toBeNull();
+ });
+
+ it("reports each database's SharePoint export separately", async () => {
+ mocks.databasesWithExport = [cellA.name, cellB.name];
+ mocks.destinations = [ExportDestination.SHAREPOINT];
+ mocks.exportData
+ .mockResolvedValueOnce({
+ content: new Uint8Array(),
+ uri: "https://contoso.sharepoint.com/sites/x/Exports/folder-a",
+ })
+ .mockRejectedValueOnce(
+ new ConnectError("destination not found", Code.FailedPrecondition)
+ );
+ render();
+
+ act(() => {
+ container
+ .querySelector<HTMLButtonElement>('[data-testid="select-all"]')
+ ?.click();
+ });
+ await act(async () => {
+ container
+ .querySelector<HTMLButtonElement>('[data-testid="batch-export-submit"]')
+ ?.click();
+ });
+
+ await vi.waitFor(() => {
+ expect(mocks.resolveExport).toHaveBeenCalledWith({
+ sharepoint: [
+ {
+ database: "cell-a/linear",
+ status: "EXPORTED",
+ uri: "https://contoso.sharepoint.com/sites/x/Exports/folder-a",
+ },
+ {
+ database: "cell-b/linear",
+ status: "FAILED",
+ reason: "destination not found",
+ },
+ ],
+ });
+ });
+ expect(mocks.exportData).toHaveBeenCalledWith(
+ expect.objectContaining({ destination: ExportDestination.SHAREPOINT })
+ );
+ expect(mocks.reportProgress.mock.calls).toEqual([
+ [0, 2],
+ [1, 2],
+ ]);
+ });
});
diff --git a/frontend/src/modules/sql-editor/components/ResultPanel/BatchQuerySelect.tsx b/frontend/src/modules/sql-editor/components/ResultPanel/BatchQuerySelect.tsx
index 87344d9891..791118b82e 100644
--- a/frontend/src/modules/sql-editor/components/ResultPanel/BatchQuerySelect.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultPanel/BatchQuerySelect.tsx
@@ -11,10 +11,17 @@ import {
type DownloadContent,
} from "@/components/DataExportButton";
import { DatabaseTableView } from "@/components/database";
+import {
+ type SharePointExportResult,
+ toExportedSharePointResult,
+ toFailedSharePointExport,
+} from "@/components/SharePointExportResultDialog";
import { Button } from "@/components/ui/button";
import { Tooltip } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { RequestExportButton } from "@/modules/sql-editor/components/RequestExportButton";
+import { sharePointExportDatabaseLabel } from "@/modules/sql-editor/components/sharePointExportLabel";
+import { useExportDestination } from "@/modules/sql-editor/components/useExportDestination";
import { useExportGrantBypass } from "@/modules/sql-editor/components/useExportGrantBypass";
import {
useSQLEditorDatabasesWithExport,
@@ -27,7 +34,7 @@ import {
useSQLEditorTabState,
} from "@/modules/sql-editor/store/tab";
import { useAppStore } from "@/stores/app";
-import { ExportFormat } from "@/types/proto-es/v1/common_pb";
+import { ExportDestination, ExportFormat } from "@/types/proto-es/v1/common_pb";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import { ExportRequestSchema } from "@/types/proto-es/v1/sql_service_pb";
import type { SQLEditorDatabaseQueryContext } from "@/types/sqlEditor/tab";
@@ -86,6 +93,7 @@ export function BatchQuerySelect({
const currentTab = useCurrentSQLEditorTab();
const project = useSQLEditorEditorState((s) => s.project);
const queryDataPolicy = useSQLEditorQueryDataPolicy(project);
+ const exportDestination = useExportDestination(project);
const [showEmpty, setShowEmpty] = useState(true);
const [selectedDatabaseNames, setSelectedDatabaseNames] = useState<
@@ -216,13 +224,14 @@ export function BatchQuerySelect({
() => exportableDatabaseNames.map((name) => getDatabaseByName(name)),
[exportableDatabaseNames, getDatabaseByName]
);
-
+ const hasDestination = exportDestination.destinations.length > 0;
+ // With no destination offered, Export stays visible but disabled.
const showExport = exportableDatabaseNames.length > 0;
- // Surface "Request Export" whenever the batch contains uncovered DBs.
// Visible alongside Export in the partial-coverage case (e.g. 2 of 5
// covered) so users can request grants for the missing ones without
- // losing the immediate export of the covered set.
- const showRequestExport = unmatchedDatabases.length > 0;
+ // losing the immediate export of the covered set. A grant never adds a
+ // destination, so this hides when no destination is offered.
+ const showRequestExport = hasDestination && unmatchedDatabases.length > 0;
// Partial-coverage flag: some matched, some not. Drives the Export
// button label change from "Batch export" to "Partial batch export"
// so the user knows up-front the action operates on a strict subset.
@@ -283,24 +292,36 @@ export function BatchQuerySelect({
const validateExport = () =>
selectedDatabaseNames.size > 0 && selectedDatabaseNames.size <= MAX_EXPORT;
- const handleExport = ({ options, resolve }: DataExportRequest) => {
+ const handleExport = ({
+ options,
+ resolve,
+ onProgress,
+ }: DataExportRequest) => {
void (async () => {
// === Prod path: per-database backend Export RPC ===
+ const toSharePoint = options.destination === ExportDestination.SHAREPOINT;
const contents: DownloadContent[] = [];
+ const sharePointResults: SharePointExportResult[] = [];
const tabsState = getSQLEditorTabsState();
const tab = tabsState.tabsById.get(tabsState.currentTabId);
// Defensive intersect — the drawer already filters to authorized
- // DBs, but if a stale name lingers in `selectedDatabaseNames` we
- // skip it here rather than firing a doomed backend call that
- // would produce a "failed for db" toast.
+ // DBs, but if a stale name lingers in `selectedDatabaseNames` we skip it here rather
+ // than firing a doomed backend call.
const exportableSet = new Set(exportableDatabaseNames);
- for (const databaseName of Array.from(selectedDatabaseNames)) {
- if (!exportableSet.has(databaseName)) continue;
+ const targets = Array.from(selectedDatabaseNames).filter((name) =>
+ exportableSet.has(name)
+ );
+ for (const [index, databaseName] of targets.entries()) {
+ onProgress?.(index, targets.length);
const database = getDatabaseByName(databaseName);
+ const { databaseName: shortName } = extractDatabaseResourceName(
+ database.name
+ );
+ const label = sharePointExportDatabaseLabel(database);
const context = head(tab?.databaseQueryContexts?.get(databaseName));
if (!context) continue;
try {
- const content = await exportData(
+ const { content, uri } = await exportData(
create(ExportRequestSchema, {
name: databaseName,
...(context.params.connection.dataSourceId
@@ -313,15 +334,28 @@ export function BatchQuerySelect({
password: options.password,
schema: context.params.connection.schema,
container: context.params.connection.table,
+ destination: options.destination,
})
);
+ if (toSharePoint) {
+ sharePointResults.push(
+ toExportedSharePointResult(
+ label,
+ uri,
+ exportDestination.sharepointUrl ?? ""
+ )
+ );
+ continue;
+ }
contents.push({
content,
- filename: `${
- extractDatabaseResourceName(database.name).databaseName
- }.${dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss")}.zip`,
+ filename: `${shortName}.${dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss")}.zip`,
});
} catch (e) {
+ if (toSharePoint) {
+ sharePointResults.push(toFailedSharePointExport(label, e));
+ continue;
+ }
useAppStore.getState().notify({
module: "bytebase",
style: "CRITICAL",
@@ -332,7 +366,7 @@ export function BatchQuerySelect({
});
}
}
- resolve(contents);
+ resolve(toSharePoint ? { sharepoint: sharePointResults } : contents);
setSelectedDatabaseNames(new Set());
})();
};
@@ -390,15 +424,16 @@ export function BatchQuerySelect({
? t("sql-editor.batch-export.partial")
: t("sql-editor.batch-export.self")
}
- // Surface the grant-bypass explanation when the export is
- // only available because of a JIT grant; otherwise keep the
- // long-standing "select at most N databases" hint.
+ // Surface the grant explanation when one matched; otherwise keep
+ // the long-standing "select at most N databases" hint.
tooltip={
exportTooltip ??
t("sql-editor.batch-export.tooltip", { max: MAX_EXPORT })
}
validate={validateExport}
maximumExportCount={queryDataPolicy.maximumResultRows}
+ destinations={exportDestination.destinations}
+ sharepointUrl={exportDestination.sharepointUrl}
onExport={handleExport}
formContent={
<div className="w-full flex flex-col gap-y-2">
@@ -412,9 +447,9 @@ export function BatchQuerySelect({
</span>
</div>
{/*
- Filtered to `exportableDatabaseList` so users can only
- check authorized DBs. Unauthorized ones are routed to
- the Request Export button next to this one.
+ Filtered to `exportableDatabaseList` so users can only check authorized DBs.
+ Unauthorized ones are routed to the Request Export button
+ next to this one.
*/}
<DatabaseTableView
databases={exportableDatabaseList}
diff --git a/frontend/src/modules/sql-editor/components/ResultView/ResultView.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/ResultView.test.tsx
index 301d57d818..6fbd5f78e8 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/ResultView.test.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/ResultView.test.tsx
@@ -1,8 +1,13 @@
import { create } from "@bufbuild/protobuf";
+import { Code, ConnectError } from "@connectrpc/connect";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, test, vi } from "vitest";
import type { SQLEditorQueryParams } from "@/types";
-import { Engine, ExportFormat } from "@/types/proto-es/v1/common_pb";
+import {
+ Engine,
+ ExportDestination,
+ ExportFormat,
+} from "@/types/proto-es/v1/common_pb";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import {
QueryResult_QueryPlanSchema,
@@ -12,9 +17,24 @@ import {
} from "@/types/proto-es/v1/sql_service_pb";
import { ResultView } from "./ResultView";
-const { exportData, exportAccess, useExportGrantBypass } = vi.hoisted(() => ({
+const {
+ exportData,
+ exportAccess,
+ exportDestination,
+ exportRequest,
+ useExportGrantBypass,
+} = vi.hoisted(() => ({
exportData: vi.fn(),
exportAccess: { databasesWithExport: [] as string[] },
+ exportDestination: {
+ destinations: [] as number[],
+ sharepointUrl: undefined as string | undefined,
+ },
+ exportRequest: {
+ destination: 1,
+ resolve: (_outcome: unknown) => {},
+ reject: (_reason: unknown) => {},
+ },
useExportGrantBypass: vi.fn(),
}));
@@ -44,6 +64,10 @@ vi.mock("@/modules/sql-editor/components/useExportGrantBypass", () => ({
useExportGrantBypass,
}));
+vi.mock("@/modules/sql-editor/components/useExportDestination", () => ({
+ useExportDestination: () => exportDestination,
+}));
+
vi.mock("@/modules/sql-editor/hooks/useSQLEditorState", () => ({
useSQLEditorDatabasesWithExport: (databases: Database[]) =>
new Set(
@@ -119,9 +143,14 @@ vi.mock("./SingleResultView", () => ({
type="button"
onClick={() =>
onExport({
- options: { format: ExportFormat.CSV, limit: 100, password: "" },
- resolve: vi.fn(),
- reject: vi.fn(),
+ options: {
+ format: ExportFormat.CSV,
+ limit: 100,
+ password: "",
+ destination: exportRequest.destination,
+ },
+ resolve: exportRequest.resolve,
+ reject: exportRequest.reject,
statement: "SELECT * FROM c",
})
}
@@ -167,8 +196,14 @@ const grantLookup = ({
describe("ResultView", () => {
beforeEach(() => {
exportData.mockReset();
- exportData.mockResolvedValue(new Uint8Array());
+ exportData.mockResolvedValue({ content: new Uint8Array(), uri: "" });
exportAccess.databasesWithExport = [];
+ exportDestination.destinations = [ExportDestination.SHAREPOINT, ExportDestination.DOWNLOAD];
+ exportDestination.sharepointUrl =
+ "https://contoso.sharepoint.com/sites/x/Exports";
+ exportRequest.destination = ExportDestination.DOWNLOAD;
+ exportRequest.resolve = vi.fn();
+ exportRequest.reject = vi.fn();
grantLookup({});
});
@@ -307,6 +342,109 @@ describe("ResultView", () => {
);
});
+ test("keeps Export but hides Request export when no destination is offered", () => {
+ exportDestination.destinations = [];
+ exportDestination.sharepointUrl = undefined;
+ exportAccess.databasesWithExport = [database.name];
+ const { unmount } = render(
+ <ResultView
+ executeParams={executeParams}
+ database={database}
+ resultSet={queryResult}
+ />
+ );
+ expect(screen.getByRole("button", { name: "export" })).toBeInTheDocument();
+ unmount();
+
+ exportAccess.databasesWithExport = [];
+ grantLookup({ unmatchedDatabases: [database.name] });
+ render(
+ <ResultView
+ executeParams={executeParams}
+ database={database}
+ resultSet={queryResult}
+ />
+ );
+ expect(screen.queryByTestId("request-export")).not.toBeInTheDocument();
+ });
+
+ test("offers Export when only SharePoint is offered", () => {
+ exportDestination.destinations = [ExportDestination.SHAREPOINT];
+ exportAccess.databasesWithExport = [database.name];
+ render(
+ <ResultView
+ executeParams={executeParams}
+ database={database}
+ resultSet={queryResult}
+ />
+ );
+
+ expect(screen.getByRole("button", { name: "export" })).toBeInTheDocument();
+ });
+
+ test("resolves a SharePoint export with its exported folder", async () => {
+ exportAccess.databasesWithExport = [database.name];
+ exportRequest.destination = ExportDestination.SHAREPOINT;
+ exportData.mockResolvedValue({
+ content: new Uint8Array(),
+ uri: "https://contoso.sharepoint.com/sites/x/Exports/20261022-main",
+ });
+ render(
+ <ResultView
+ executeParams={executeParams}
+ database={database}
+ resultSet={queryResult}
+ />
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "export" }));
+
+ await waitFor(() => {
+ expect(exportRequest.resolve).toHaveBeenCalledWith({
+ sharepoint: [
+ {
+ database: "main",
+ status: "EXPORTED",
+ uri: "https://contoso.sharepoint.com/sites/x/Exports/20261022-main",
+ },
+ ],
+ });
+ });
+ expect(exportData).toHaveBeenCalledWith(
+ expect.objectContaining({ destination: ExportDestination.SHAREPOINT })
+ );
+ });
+
+ test("reports an unconfirmed SharePoint export instead of rejecting", async () => {
+ exportAccess.databasesWithExport = [database.name];
+ exportRequest.destination = ExportDestination.SHAREPOINT;
+ exportData.mockRejectedValue(
+ new ConnectError("could not be confirmed", Code.Unavailable)
+ );
+ render(
+ <ResultView
+ executeParams={executeParams}
+ database={database}
+ resultSet={queryResult}
+ />
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "export" }));
+
+ await waitFor(() => {
+ expect(exportRequest.resolve).toHaveBeenCalledWith({
+ sharepoint: [
+ {
+ database: "main",
+ status: "UNCONFIRMED",
+ reason: "could not be confirmed",
+ },
+ ],
+ });
+ });
+ expect(exportRequest.reject).not.toHaveBeenCalled();
+ });
+
/** A PostgreSQL plan result whose root costs `totalCost`. */
const planResult = (totalCost: number) =>
create(QueryResultSchema, {
diff --git a/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsx
index 297aa98670..d684ebe753 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsx
@@ -9,6 +9,10 @@ import {
DataExportButton,
type DataExportRequest,
} from "@/components/DataExportButton";
+import {
+ toExportedSharePointResult,
+ toFailedSharePointExport,
+} from "@/components/SharePointExportResultDialog";
import { Button } from "@/components/ui/button";
import { Tabs, TabsList, TabsPanel, TabsTrigger } from "@/components/ui/tabs";
import { Tooltip } from "@/components/ui/tooltip";
@@ -16,6 +20,8 @@ import { isDisallowChangeDatabaseError } from "@/hooks/useExecuteSQL";
import { cn } from "@/lib/utils";
import { RequestExportButton } from "@/modules/sql-editor/components/RequestExportButton";
import { RequestQueryButton } from "@/modules/sql-editor/components/RequestQueryButton";
+import { sharePointExportDatabaseLabel } from "@/modules/sql-editor/components/sharePointExportLabel";
+import { useExportDestination } from "@/modules/sql-editor/components/useExportDestination";
import { useExportGrantBypass } from "@/modules/sql-editor/components/useExportGrantBypass";
import {
useSQLEditorDatabasesWithExport,
@@ -27,6 +33,7 @@ import { useAppStore } from "@/stores/app";
import type { SQLEditorQueryParams, SQLResultSetV1 } from "@/types";
import { isValidDatabaseName } from "@/types";
import {
+ ExportDestination,
ExportFormat,
type PermissionDeniedDetail,
} from "@/types/proto-es/v1/common_pb";
@@ -163,6 +170,10 @@ export function ResultView({
],
});
+ // With no destination offered, Export stays visible but disabled to explain
+ // why, and Request export hides because a grant never adds a destination.
+ const exportDestination = useExportDestination(database.project);
+ const hasDestination = exportDestination.destinations.length > 0;
const showExport = allowExport || !!exportGrantName;
// When direct export is unavailable, offer a "Request export" affordance that
@@ -176,7 +187,7 @@ export function ResultView({
failed={failedDatabases.length > 0}
onRetry={retry}
/>
- ) : executeParams && unmatchedDatabases.length > 0 ? (
+ ) : hasDestination && executeParams && unmatchedDatabases.length > 0 ? (
<RequestExportButton
statement={executeParams.statement}
targets={[database.name]}
@@ -213,13 +224,15 @@ export function ResultView({
req: DataExportRequest & { statement: string }
) => {
const { options, resolve, reject, statement } = req;
+ const { databaseName } = extractDatabaseResourceName(database.name);
+ const toSharePoint = options.destination === ExportDestination.SHAREPOINT;
// === Prod path: backend Export RPC ===
const tabsState = getSQLEditorTabsState();
const admin =
tabsState.tabsById.get(tabsState.currentTabId)?.mode === "ADMIN";
try {
- const content = await useAppStore.getState().exportData(
+ const { content, uri } = await useAppStore.getState().exportData(
create(ExportRequestSchema, {
name: database.name,
...(executeParams.connection.dataSourceId
@@ -232,15 +245,39 @@ export function ResultView({
password: options.password,
schema: executeParams.connection.schema,
container: executeParams.connection.table,
+ destination: options.destination,
})
);
+ if (toSharePoint) {
+ resolve({
+ sharepoint: [
+ toExportedSharePointResult(
+ sharePointExportDatabaseLabel(database),
+ uri,
+ exportDestination.sharepointUrl ?? ""
+ ),
+ ],
+ });
+ return;
+ }
resolve([
{
content,
- filename: `${extractDatabaseResourceName(database.name).databaseName}.${dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss")}.zip`,
+ filename: `${databaseName}.${dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss")}.zip`,
},
]);
} catch (e) {
+ if (toSharePoint) {
+ resolve({
+ sharepoint: [
+ toFailedSharePointExport(
+ sharePointExportDatabaseLabel(database),
+ e
+ ),
+ ],
+ });
+ return;
+ }
reject(e);
}
};
@@ -289,11 +326,10 @@ export function ResultView({
result={resultSet.results[0]}
showExport={showExport}
exportTooltip={exportTooltip}
+ exportDestination={exportDestination}
maximumExportCount={queryDataPolicy?.maximumResultRows}
onExport={handleExport}
- requestExportSlot={
- !showExport ? requestExportButton : undefined
- }
+ requestExportSlot={requestExportButton}
compact={compact}
presentation={presentation}
/>
@@ -344,8 +380,8 @@ export function ResultView({
);
})}
</TabsList>
- {showExport ? (
- <div className="mb-1">
+ <div className="mb-1 flex items-center gap-x-2">
+ {showExport && (
<DataExportButton
size="sm"
disabled={false}
@@ -353,6 +389,8 @@ export function ResultView({
viewMode="DRAWER"
supportPassword
tooltip={exportTooltip}
+ destinations={exportDestination.destinations}
+ sharepointUrl={exportDestination.sharepointUrl}
maximumExportCount={queryDataPolicy?.maximumResultRows}
onExport={(req) =>
handleExport({
@@ -361,10 +399,9 @@ export function ResultView({
})
}
/>
- </div>
- ) : (
- <div className="mb-1">{requestExportButton}</div>
- )}
+ )}
+ {requestExportButton}
+ </div>
</div>
{filteredResults.map((result, i) => (
<TabsPanel
diff --git a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx
index 26ac77c509..89ba89b537 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx
@@ -39,6 +39,7 @@ import { useAppDatabaseMetadata } from "@/hooks/useAppDatabaseMetadata";
import { useExecuteSQL } from "@/hooks/useExecuteSQL";
import { writeTextToClipboard } from "@/lib/clipboard";
import { cn } from "@/lib/utils";
+import type { ExportDestinationState } from "@/modules/sql-editor/components/useExportDestination";
import { useSQLEditorQueryDataPolicy } from "@/modules/sql-editor/hooks/useSQLEditorState";
import { useSQLEditorEditorState } from "@/modules/sql-editor/store/editor";
import { useSQLEditorTabState } from "@/modules/sql-editor/store/tab";
@@ -123,10 +124,11 @@ export interface SingleResultViewProps {
// Optional tooltip shown on the export button — used to explain when the
// export is enabled by a JIT access grant rather than bb.sql.export.
exportTooltip?: ReactNode;
+ exportDestination?: ExportDestinationState;
maximumExportCount?: number;
onExport?: (req: DataExportRequest & { statement: string }) => void;
- // Rendered in the toolbar when `showExport` is false — e.g. a
- // "Request export" affordance when the user lacks bb.sql.export.
+ // Rendered in the toolbar after the export button — e.g. a "Request export"
+ // affordance when the user lacks bb.sql.export.
requestExportSlot?: ReactNode;
// Compact layout (fixed-height, non-growing body) used by the terminal /
// admin result panel. Defaults to the flex-grow saved query layout.
@@ -307,6 +309,7 @@ function SingleResultViewInner({
resultIndex = 0,
showExport,
exportTooltip,
+ exportDestination,
maximumExportCount,
onExport,
requestExportSlot,
@@ -782,7 +785,7 @@ function SingleResultViewInner({
{!disallowCopyingData && rows.length > 0 && !isJSONView && (
<CopyAllButton />
)}
- {showExport ? (
+ {showExport && (
<DataExportButton
size="sm"
disabled={!result || isEmpty(result)}
@@ -790,13 +793,14 @@ function SingleResultViewInner({
viewMode="DRAWER"
supportPassword
tooltip={exportTooltip}
+ destinations={exportDestination?.destinations}
+ sharepointUrl={exportDestination?.sharepointUrl}
maximumExportCount={maximumExportCount}
formContent={<DatabaseInfo database={database} />}
onExport={handleExport}
/>
- ) : (
- requestExportSlot
)}
+ {requestExportSlot}
</div>
{!isJSONView && <SelectionCopyTooltips />}
</div>
diff --git a/frontend/src/modules/sql-editor/components/sharePointExportLabel.ts b/frontend/src/modules/sql-editor/components/sharePointExportLabel.ts
new file mode 100644
index 0000000000..e242fb858d
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/sharePointExportLabel.ts
@@ -0,0 +1,15 @@
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import {
+ extractDatabaseResourceName,
+ getInstanceResource,
+} from "@/utils/v1/database";
+
+// Labels a database by its instance title, which tells same-named databases
+// apart in a batch.
+export function sharePointExportDatabaseLabel(database: Database): string {
+ const { instanceName, databaseName } = extractDatabaseResourceName(
+ database.name
+ );
+ const instance = getInstanceResource(database)?.title || instanceName;
+ return instance ? `${instance}/${databaseName}` : databaseName;
+}
diff --git a/frontend/src/modules/sql-editor/components/useExportDestination.test.ts b/frontend/src/modules/sql-editor/components/useExportDestination.test.ts
new file mode 100644
index 0000000000..d186158eb4
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/useExportDestination.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, test, vi } from "vitest";
+import { ExportDestination } from "@/types/proto-es/v1/common_pb";
+
+vi.mock("@/hooks/useAppState", () => ({ usePlanFeature: () => true }));
+vi.mock("@/hooks/useProjectByName", () => ({ useProjectByName: vi.fn() }));
+vi.mock("@/modules/sql-editor/hooks/useSQLEditorState", () => ({
+ useSQLEditorQueryDataPolicy: vi.fn(),
+}));
+vi.mock("@/stores/app", () => ({ useAppStore: vi.fn() }));
+
+import { resolveExportDestination } from "./useExportDestination";
+
+const url = "https://contoso.sharepoint.com/sites/Finance/Shared%20Documents";
+
+describe("resolveExportDestination", () => {
+ test("defaults to SharePoint and keeps download as the alternative", () => {
+ expect(
+ resolveExportDestination({
+ hasSharePointFeature: true,
+ sharepointUrl: url,
+ disableDownload: false,
+ })
+ ).toEqual({
+ destinations: [ExportDestination.SHAREPOINT, ExportDestination.DOWNLOAD],
+ sharepointUrl: url,
+ });
+ });
+
+ test("offers only SharePoint when download is disabled", () => {
+ expect(
+ resolveExportDestination({
+ hasSharePointFeature: true,
+ sharepointUrl: url,
+ disableDownload: true,
+ })
+ ).toEqual({
+ destinations: [ExportDestination.SHAREPOINT],
+ sharepointUrl: url,
+ });
+ });
+
+ test("offers only download without a SharePoint destination or the feature", () => {
+ for (const input of [
+ { hasSharePointFeature: true, sharepointUrl: "" },
+ { hasSharePointFeature: false, sharepointUrl: url },
+ ]) {
+ expect(
+ resolveExportDestination({ ...input, disableDownload: false })
+ ).toEqual({ destinations: [ExportDestination.DOWNLOAD] });
+ }
+ });
+
+ test("offers nothing when download is disabled and SharePoint is not available", () => {
+ for (const input of [
+ { hasSharePointFeature: true, sharepointUrl: "" },
+ { hasSharePointFeature: false, sharepointUrl: url },
+ ]) {
+ expect(
+ resolveExportDestination({ ...input, disableDownload: true })
+ ).toEqual({ destinations: [] });
+ }
+ });
+});
diff --git a/frontend/src/modules/sql-editor/components/useExportDestination.ts b/frontend/src/modules/sql-editor/components/useExportDestination.ts
new file mode 100644
index 0000000000..120b4bca0e
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/useExportDestination.ts
@@ -0,0 +1,64 @@
+import { useEffect } from "react";
+import { usePlanFeature } from "@/hooks/useAppState";
+import { useProjectByName } from "@/hooks/useProjectByName";
+import { useSQLEditorQueryDataPolicy } from "@/modules/sql-editor/hooks/useSQLEditorState";
+import { useAppStore } from "@/stores/app";
+import { ExportDestination } from "@/types/proto-es/v1/common_pb";
+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
+
+export interface ExportDestinationAvailability {
+ // The offered destinations; the first is the default. Empty means the caller
+ // hides export.
+ destinations: ExportDestination[];
+ // Set only when SharePoint is offered.
+ sharepointUrl?: string;
+}
+
+// An export access grant never adds a destination: Download is offered unless
+// the workspace disables it, and SharePoint only when the project has a
+// SharePoint folder.
+export function resolveExportDestination({
+ hasSharePointFeature,
+ sharepointUrl,
+ disableDownload,
+}: {
+ hasSharePointFeature: boolean;
+ sharepointUrl: string;
+ disableDownload: boolean;
+}): ExportDestinationAvailability {
+ const destinations: ExportDestination[] = [];
+ const offersSharePoint = hasSharePointFeature && sharepointUrl !== "";
+ if (offersSharePoint) {
+ destinations.push(ExportDestination.SHAREPOINT);
+ }
+ if (!disableDownload) {
+ destinations.push(ExportDestination.DOWNLOAD);
+ }
+ return offersSharePoint ? { destinations, sharepointUrl } : { destinations };
+}
+
+export function useExportDestination(projectName: string) {
+ const project = useProjectByName(projectName);
+ const hasSharePointFeature = usePlanFeature(
+ PlanFeature.FEATURE_SHAREPOINT_EXPORT
+ );
+ // The server enforces disable_download without a license check, so it is
+ // read regardless of FEATURE_QUERY_POLICY.
+ const { disableDownload } = useSQLEditorQueryDataPolicy(projectName);
+
+ useEffect(() => {
+ if (!projectName) return;
+ void useAppStore
+ .getState()
+ .getOrFetchProjectByName(projectName, true)
+ .catch(() => undefined);
+ }, [projectName]);
+
+ return resolveExportDestination({
+ hasSharePointFeature,
+ sharepointUrl: project.exportSetting?.sharepoint?.url ?? "",
+ disableDownload,
+ });
+}
+
+export type ExportDestinationState = ReturnType<typeof useExportDestination>;
diff --git a/frontend/src/modules/sql-editor/hooks/useSQLEditorState.ts b/frontend/src/modules/sql-editor/hooks/useSQLEditorState.ts
index 7804aa59e6..102b3bdf78 100644
--- a/frontend/src/modules/sql-editor/hooks/useSQLEditorState.ts
+++ b/frontend/src/modules/sql-editor/hooks/useSQLEditorState.ts
@@ -46,6 +46,8 @@ export const useSQLEditorFeature = (feature: PlanFeature): boolean => {
// policy limits.
type FormattedQueryDataPolicy = {
disableCopyData: boolean;
+ // Workspace-level only.
+ disableDownload: boolean;
allowAdminDataSource: boolean;
maximumResultRows: number;
};
@@ -56,6 +58,7 @@ const formatQueryDataPolicy = (
const max = policy?.maximumResultRows ?? -1;
return {
disableCopyData: policy?.disableCopyData ?? false,
+ disableDownload: policy?.disableDownload ?? false,
allowAdminDataSource: policy?.allowAdminDataSource ?? false,
maximumResultRows: max <= 0 ? Number.MAX_VALUE : max,
};
diff --git a/frontend/src/routes/project/ProjectExportDestinationField.test.tsx b/frontend/src/routes/project/ProjectExportDestinationField.test.tsx
new file mode 100644
index 0000000000..f53dcb3e6f
--- /dev/null
+++ b/frontend/src/routes/project/ProjectExportDestinationField.test.tsx
@@ -0,0 +1,90 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { describe, expect, test, vi } from "vitest";
+import { ProjectExportDestinationField } from "./ProjectExportDestinationField";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+vi.mock("@/components/FeatureBadge", () => ({ FeatureBadge: () => null }));
+
+const savedUrl = "https://contoso.sharepoint.com/sites/Finance/Shared%20Documents";
+
+describe("ProjectExportDestinationField", () => {
+ test("shows the saved URL and nothing resolved from it", () => {
+ render(
+ <ProjectExportDestinationField
+ value={savedUrl}
+ onChange={vi.fn()}
+ disabled={false}
+ canClear
+ />
+ );
+ expect(
+ screen.getByLabelText("export-data.destination.sharepoint")
+ ).toHaveValue(savedUrl);
+ expect(screen.queryByRole("link")).not.toBeInTheDocument();
+ });
+
+ test("shows the server error beside the field", () => {
+ render(
+ <ProjectExportDestinationField
+ value={savedUrl}
+ onChange={vi.fn()}
+ disabled={false}
+ canClear
+ error="does not exist or Bytebase cannot access it"
+ />
+ );
+ expect(screen.getByRole("alert")).toHaveTextContent(
+ "does not exist or Bytebase cannot access it"
+ );
+ expect(
+ screen.getByLabelText("export-data.destination.sharepoint")
+ ).toHaveAttribute("aria-invalid", "true");
+ });
+
+ test("clears the destination", () => {
+ const onChange = vi.fn();
+ render(
+ <ProjectExportDestinationField
+ value={savedUrl}
+ onChange={onChange}
+ disabled={false}
+ canClear
+ />
+ );
+ fireEvent.click(screen.getByRole("button", { name: "common.clear" }));
+ expect(onChange).toHaveBeenCalledWith("");
+ });
+
+ test("hides the clear button when there is nothing to clear", () => {
+ render(
+ <ProjectExportDestinationField
+ value=""
+ onChange={vi.fn()}
+ disabled={false}
+ canClear
+ />
+ );
+ expect(
+ screen.queryByRole("button", { name: "common.clear" })
+ ).not.toBeInTheDocument();
+ });
+
+ test("can clear a destination after the license lapses", () => {
+ const onChange = vi.fn();
+ render(
+ <ProjectExportDestinationField
+ value={savedUrl}
+ onChange={onChange}
+ disabled
+ canClear
+ />
+ );
+ expect(
+ screen.getByLabelText("export-data.destination.sharepoint")
+ ).toBeDisabled();
+ fireEvent.click(screen.getByRole("button", { name: "common.clear" }));
+ expect(onChange).toHaveBeenCalledWith("");
+ });
+});
diff --git a/frontend/src/routes/project/ProjectExportDestinationField.tsx b/frontend/src/routes/project/ProjectExportDestinationField.tsx
new file mode 100644
index 0000000000..dce6420aa2
--- /dev/null
+++ b/frontend/src/routes/project/ProjectExportDestinationField.tsx
@@ -0,0 +1,123 @@
+import { X } from "lucide-react";
+import { useRef } from "react";
+import { useTranslation } from "react-i18next";
+import { FeatureBadge } from "@/components/FeatureBadge";
+import { Button } from "@/components/ui/button";
+import {
+ FormControlGroup,
+ FormControlRow,
+ FormError,
+ FormField,
+ FormLabel,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
+
+interface Props {
+ value: string;
+ onChange: (value: string) => void;
+ disabled: boolean;
+ // Clearing needs no license, so it stays available after a license lapses.
+ canClear: boolean;
+ error?: string;
+}
+
+// One row per destination provider, so another provider adds a row.
+export function ProjectExportDestinationField({
+ value,
+ onChange,
+ disabled,
+ canClear,
+ error,
+}: Props) {
+ const { t } = useTranslation();
+
+ return (
+ <FormField
+ title={
+ <span className="flex items-center gap-x-2">
+ {t("project.settings.export-destination.self")}
+ <FeatureBadge feature={PlanFeature.FEATURE_SHAREPOINT_EXPORT} />
+ </span>
+ }
+ description={t("project.settings.export-destination.description")}
+ >
+ <FormControlGroup>
+ <DestinationRow
+ id="project-export-destination-sharepoint"
+ label={t("export-data.destination.sharepoint")}
+ placeholder={t(
+ "project.settings.export-destination.sharepoint-placeholder"
+ )}
+ value={value}
+ onChange={onChange}
+ disabled={disabled}
+ canClear={canClear}
+ invalid={!!error}
+ />
+ </FormControlGroup>
+ {error && <FormError>{error}</FormError>}
+ </FormField>
+ );
+}
+
+function DestinationRow({
+ id,
+ label,
+ placeholder,
+ value,
+ onChange,
+ disabled,
+ canClear,
+ invalid,
+}: {
+ id: string;
+ label: string;
+ placeholder: string;
+ value: string;
+ onChange: (value: string) => void;
+ disabled: boolean;
+ canClear: boolean;
+ invalid: boolean;
+}) {
+ const { t } = useTranslation();
+ const inputRef = useRef<HTMLInputElement>(null);
+ const showClear = canClear && value !== "";
+
+ return (
+ <FormControlRow className="w-full max-w-2xl">
+ <FormLabel htmlFor={id} className="w-24 shrink-0">
+ {label}
+ </FormLabel>
+ <div className="relative min-w-0 flex-1">
+ <Input
+ ref={inputRef}
+ id={id}
+ type="url"
+ className={showClear ? "pr-10" : undefined}
+ value={value}
+ disabled={disabled}
+ aria-invalid={invalid}
+ placeholder={placeholder}
+ onChange={(event) => onChange(event.target.value)}
+ />
+ {showClear && (
+ <Button
+ type="button"
+ appearance="secondary"
+ size="sm"
+ className="absolute right-1 top-1"
+ aria-label={t("common.clear")}
+ title={t("common.clear")}
+ onClick={() => {
+ onChange("");
+ inputRef.current?.focus();
+ }}
+ >
+ <X size={16} />
+ </Button>
+ )}
+ </div>
+ </FormControlRow>
+ );
+}
diff --git a/frontend/src/routes/project/ProjectSettingsPage.tsx b/frontend/src/routes/project/ProjectSettingsPage.tsx
index a569eb53e6..0c72f0c9db 100644
--- a/frontend/src/routes/project/ProjectSettingsPage.tsx
+++ b/frontend/src/routes/project/ProjectSettingsPage.tsx
@@ -1,4 +1,5 @@
import { create } from "@bufbuild/protobuf";
+import { ConnectError } from "@connectrpc/connect";
import { cloneDeep, isEqual } from "lodash-es";
import { ShieldCheck, TriangleAlert, X } from "lucide-react";
import {
@@ -55,6 +56,7 @@ import type { Label } from "@/types/proto-es/v1/project_service_pb";
import {
LabelSchema,
Project_ExecutionRetryPolicySchema,
+ Project_ExportSettingSchema,
} from "@/types/proto-es/v1/project_service_pb";
import { WorkspaceApprovalSetting_Rule_Source } from "@/types/proto-es/v1/setting_service_pb";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
@@ -69,6 +71,7 @@ import {
sqlReviewPolicySlug,
} from "@/utils";
import { sqlReviewV2Enabled } from "@/utils/featureGates";
+import { ProjectExportDestinationField } from "./ProjectExportDestinationField";
// ---------------------------------------------------------------------------
// ApprovalFlowIndicator
@@ -212,6 +215,23 @@ export function ProjectSettingsPage() {
const hasQueryPolicyFeature = useAppStore((s) =>
s.hasInstanceFeature(PlanFeature.FEATURE_QUERY_POLICY)
);
+ const hasSharePointExportFeature = useAppStore((s) =>
+ s.hasFeature(PlanFeature.FEATURE_SHAREPOINT_EXPORT)
+ );
+
+ // -----------------------------------------------------------------------
+ // Export destination state
+ // -----------------------------------------------------------------------
+ const savedExportDestinationUrl =
+ project?.exportSetting?.sharepoint?.url ?? "";
+ const [exportDestinationUrl, setExportDestinationUrl] = useState(
+ savedExportDestinationUrl
+ );
+ const [exportDestinationError, setExportDestinationError] = useState("");
+ const handleExportDestinationChange = useCallback((value: string) => {
+ setExportDestinationUrl(value);
+ setExportDestinationError("");
+ }, []);
// -----------------------------------------------------------------------
// Issue-related state
@@ -335,6 +355,7 @@ export function ProjectSettingsPage() {
(parallelTasksPerRollout ?? 0) !== (project.parallelTasksPerRollout ?? 0)
)
return true;
+ if (exportDestinationUrl.trim() !== savedExportDestinationUrl) return true;
return false;
}, [
project,
@@ -359,6 +380,8 @@ export function ProjectSettingsPage() {
maxRetries,
ciSamplingSize,
parallelTasksPerRollout,
+ exportDestinationUrl,
+ savedExportDestinationUrl,
]);
useUnsavedChangesGuard(isDirty);
@@ -387,7 +410,14 @@ export function ProjectSettingsPage() {
setMaxRetries(project.executionRetryPolicy?.maximumRetries ?? 0);
setCiSamplingSize(project.ciSamplingSize);
setParallelTasksPerRollout(project.parallelTasksPerRollout);
- }, [project, currentReviewPolicy, getInitialMaxRows]);
+ setExportDestinationUrl(savedExportDestinationUrl);
+ setExportDestinationError("");
+ }, [
+ project,
+ currentReviewPolicy,
+ getInitialMaxRows,
+ savedExportDestinationUrl,
+ ]);
// -----------------------------------------------------------------------
// Save
@@ -531,6 +561,40 @@ export function ProjectSettingsPage() {
}
}
+ // Saved on its own so a URL that does not resolve is reported beside the
+ // field without discarding the other changes.
+ const nextExportDestinationUrl = exportDestinationUrl.trim();
+ if (nextExportDestinationUrl !== savedExportDestinationUrl) {
+ try {
+ const destinationPatch = cloneDeep(project);
+ // An unset sharepoint clears the destination.
+ destinationPatch.exportSetting = create(
+ Project_ExportSettingSchema,
+ nextExportDestinationUrl
+ ? { sharepoint: { url: nextExportDestinationUrl } }
+ : {}
+ );
+ const updatedProject = await useAppStore
+ .getState()
+ .updateProject(destinationPatch, ["export_setting"], {
+ byCaller: true,
+ });
+ setExportDestinationUrl(
+ updatedProject.exportSetting?.sharepoint?.url ?? ""
+ );
+ } catch (error) {
+ setExportDestinationError(
+ error instanceof ConnectError ? error.rawMessage : String(error)
+ );
+ pushNotification({
+ module: "bytebase",
+ style: "WARN",
+ title: t("project.settings.export-destination.update-failed"),
+ });
+ return;
+ }
+ }
+
pushNotification({
module: "bytebase",
style: "SUCCESS",
@@ -571,6 +635,8 @@ export function ProjectSettingsPage() {
maxRetries,
ciSamplingSize,
parallelTasksPerRollout,
+ exportDestinationUrl,
+ savedExportDestinationUrl,
t,
]);
@@ -825,6 +891,14 @@ export function ProjectSettingsPage() {
</>
)}
+ <ProjectExportDestinationField
+ value={exportDestinationUrl}
+ onChange={handleExportDestinationChange}
+ disabled={!canUpdateProject || !hasSharePointExportFeature}
+ canClear={canUpdateProject}
+ error={exportDestinationError}
+ />
+
{/* Allow Request Role */}
<ToggleRow
checked={allowRequestRole}
diff --git a/frontend/src/routes/workspace/LandingPage.tsx b/frontend/src/routes/workspace/LandingPage.tsx
index fe81878858..ef07d5ef37 100644
--- a/frontend/src/routes/workspace/LandingPage.tsx
+++ b/frontend/src/routes/workspace/LandingPage.tsx
@@ -39,6 +39,7 @@ import {
WORKSPACE_ROUTE_AUDIT_LOG,
WORKSPACE_ROUTE_CUSTOM_APPROVAL,
WORKSPACE_ROUTE_DATA_CLASSIFICATION,
+ WORKSPACE_ROUTE_EXPORT_DESTINATIONS,
WORKSPACE_ROUTE_GLOBAL_MASKING,
WORKSPACE_ROUTE_IDENTITY_PROVIDERS,
WORKSPACE_ROUTE_IM,
@@ -240,6 +241,11 @@ function useFullQuickLinkList(): QuickLinkDef[] {
titleKey: "settings.sidebar.mcp",
icon: Link,
},
+ {
+ id: WORKSPACE_ROUTE_EXPORT_DESTINATIONS,
+ titleKey: "settings.sidebar.export-destinations",
+ icon: Link,
+ },
// Settings
{
id: SETTING_ROUTE_WORKSPACE_GENERAL,
diff --git a/frontend/src/routes/workspace/export-destinations/ExportDestinationsPage.test.tsx b/frontend/src/routes/workspace/export-destinations/ExportDestinationsPage.test.tsx
new file mode 100644
index 0000000000..852eed9bc0
--- /dev/null
+++ b/frontend/src/routes/workspace/export-destinations/ExportDestinationsPage.test.tsx
@@ -0,0 +1,80 @@
+import { create } from "@bufbuild/protobuf";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import {
+ type SharePointSetting,
+ SharePointSettingSchema,
+} from "@/types/proto-es/v1/setting_service_pb";
+
+const mocks = vi.hoisted(() => ({
+ stored: undefined as SharePointSetting | undefined,
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+vi.mock("@/components/FeatureAttention", () => ({
+ FeatureAttention: () => null,
+}));
+vi.mock("@/hooks/useAppState", () => ({ usePlanFeature: () => true }));
+vi.mock("@/utils", () => ({ hasWorkspacePermissionV2: () => true }));
+vi.mock("./SharePointSheet", () => ({
+ SharePointSheet: ({ open }: { open: boolean }) =>
+ open ? <div>sharepoint-sheet</div> : null,
+}));
+vi.mock("@/stores/app", () => {
+ const state = () => ({
+ settingsByName: {},
+ getSettingByName: () =>
+ mocks.stored && {
+ value: {
+ value: { case: "export", value: { sharepoint: mocks.stored } },
+ },
+ },
+ getOrFetchSettingByName: async () => undefined,
+ });
+ return {
+ useAppStore: Object.assign(
+ (selector: (s: ReturnType<typeof state>) => unknown) => selector(state()),
+ { getState: state }
+ ),
+ };
+});
+
+import { ExportDestinationsPage } from "./ExportDestinationsPage";
+
+describe("ExportDestinationsPage", () => {
+ beforeEach(() => {
+ mocks.stored = undefined;
+ });
+
+ test("offers to configure SharePoint when it is not set up", async () => {
+ render(<ExportDestinationsPage />);
+ expect(
+ await screen.findByText("settings.export-destinations.not-configured")
+ ).toBeInTheDocument();
+ fireEvent.click(
+ screen.getByRole("button", {
+ name: "common.configure export-data.destination.sharepoint",
+ })
+ );
+ expect(screen.getByText("sharepoint-sheet")).toBeInTheDocument();
+ });
+
+ test("shows a configured SharePoint application", async () => {
+ mocks.stored = create(SharePointSettingSchema, {
+ tenantId: "tenant",
+ clientId: "client",
+ clientSecretSet: true,
+ });
+ render(<ExportDestinationsPage />);
+ expect(
+ await screen.findByText("settings.export-destinations.configured")
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", {
+ name: "common.edit export-data.destination.sharepoint",
+ })
+ ).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/routes/workspace/export-destinations/ExportDestinationsPage.tsx b/frontend/src/routes/workspace/export-destinations/ExportDestinationsPage.tsx
new file mode 100644
index 0000000000..4e88a99c4b
--- /dev/null
+++ b/frontend/src/routes/workspace/export-destinations/ExportDestinationsPage.tsx
@@ -0,0 +1,163 @@
+import { create } from "@bufbuild/protobuf";
+import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import sharePointIcon from "@/assets/export/sharepoint.svg";
+import { FeatureAttention } from "@/components/FeatureAttention";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import {
+ WorkspacePageInfo,
+ WorkspacePageLayout,
+} from "@/components/WorkspacePageLayout";
+import { usePlanFeature } from "@/hooks/useAppState";
+import { useAppStore } from "@/stores/app";
+import {
+ Setting_SettingName,
+ type SharePointSetting,
+ SharePointSettingSchema,
+} from "@/types/proto-es/v1/setting_service_pb";
+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
+import { hasWorkspacePermissionV2 } from "@/utils";
+import { SharePointSheet } from "./SharePointSheet";
+
+function getStoredSharePointSetting(): SharePointSetting {
+ const setting = useAppStore
+ .getState()
+ .getSettingByName(Setting_SettingName.EXPORT);
+ const value = setting?.value?.value;
+ if (value?.case !== "export" || !value.value.sharepoint) {
+ return create(SharePointSettingSchema, {});
+ }
+ return value.value.sharepoint;
+}
+
+export function ExportDestinationsPage() {
+ const { t } = useTranslation();
+ const settingsByName = useAppStore((s) => s.settingsByName);
+ const sharePoint = useMemo(
+ () => getStoredSharePointSetting(),
+ [settingsByName]
+ );
+ const hasFeature = usePlanFeature(PlanFeature.FEATURE_SHAREPOINT_EXPORT);
+ const allowEdit = hasWorkspacePermissionV2("bb.settings.set") && hasFeature;
+ const [initialized, setInitialized] = useState(false);
+ const [sharePointOpen, setSharePointOpen] = useState(false);
+ const [sessionKey, setSessionKey] = useState(0);
+
+ useEffect(() => {
+ void useAppStore
+ .getState()
+ .getOrFetchSettingByName(Setting_SettingName.EXPORT, true)
+ .finally(() => setInitialized(true));
+ }, []);
+
+ const openSharePoint = () => {
+ setSessionKey((key) => key + 1);
+ setSharePointOpen(true);
+ };
+
+ return (
+ <WorkspacePageLayout>
+ <WorkspacePageInfo
+ description={t("settings.export-destinations.description")}
+ />
+ <FeatureAttention feature={PlanFeature.FEATURE_SHAREPOINT_EXPORT} />
+ {initialized && (
+ <div className="overflow-hidden rounded-sm border border-block-border">
+ <Table>
+ <TableHeader>
+ <TableRow className="bg-control-bg">
+ <TableHead>
+ {t("settings.export-destinations.provider")}
+ </TableHead>
+ <TableHead>{t("common.status")}</TableHead>
+ <TableHead />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ <DestinationRow
+ icon={sharePointIcon}
+ title={t("export-data.destination.sharepoint")}
+ caption={t("settings.sharepoint.caption")}
+ configured={sharePoint.tenantId !== ""}
+ allowEdit={allowEdit}
+ onOpen={openSharePoint}
+ />
+ </TableBody>
+ </Table>
+ </div>
+ )}
+ <SharePointSheet
+ open={sharePointOpen}
+ sessionKey={sessionKey}
+ stored={sharePoint}
+ allowEdit={allowEdit}
+ onClose={() => setSharePointOpen(false)}
+ />
+ </WorkspacePageLayout>
+ );
+}
+
+function DestinationRow({
+ icon,
+ title,
+ caption,
+ configured,
+ allowEdit,
+ onOpen,
+}: {
+ icon: string;
+ title: string;
+ caption: string;
+ configured: boolean;
+ allowEdit: boolean;
+ onOpen: () => void;
+}) {
+ const { t } = useTranslation();
+ const action = !configured
+ ? t("common.configure")
+ : allowEdit
+ ? t("common.edit")
+ : t("common.view");
+ return (
+ <TableRow>
+ <TableCell>
+ <div className="flex items-center gap-x-3">
+ <img src={icon} alt="" className="size-6" />
+ <div className="flex flex-col">
+ <span className="font-medium text-main">{title}</span>
+ <span className="text-xs text-control-light">{caption}</span>
+ </div>
+ </div>
+ </TableCell>
+ <TableCell>
+ {configured ? (
+ <Badge variant="success">
+ {t("settings.export-destinations.configured")}
+ </Badge>
+ ) : (
+ <Badge>{t("settings.export-destinations.not-configured")}</Badge>
+ )}
+ </TableCell>
+ <TableCell className="text-right">
+ <Button
+ appearance="outline"
+ size="sm"
+ aria-label={`${action} ${title}`}
+ disabled={!configured && !allowEdit}
+ onClick={onOpen}
+ >
+ {action}
+ </Button>
+ </TableCell>
+ </TableRow>
+ );
+}
diff --git a/frontend/src/routes/workspace/export-destinations/SharePointSheet.test.tsx b/frontend/src/routes/workspace/export-destinations/SharePointSheet.test.tsx
new file mode 100644
index 0000000000..d72b597e77
--- /dev/null
+++ b/frontend/src/routes/workspace/export-destinations/SharePointSheet.test.tsx
@@ -0,0 +1,161 @@
+import { create } from "@bufbuild/protobuf";
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from "@testing-library/react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import {
+ Setting_SettingName,
+ type SettingValue,
+ SharePointSettingSchema,
+} from "@/types/proto-es/v1/setting_service_pb";
+
+const mocks = vi.hoisted(() => ({
+ upsertSetting: vi.fn(
+ async (_params: {
+ name: Setting_SettingName;
+ value: SettingValue;
+ updateMask: { paths: string[] };
+ }) => undefined
+ ),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+vi.mock("@/stores", () => ({ pushNotification: vi.fn() }));
+vi.mock("@/stores/app", () => ({
+ useAppStore: { getState: () => ({ upsertSetting: mocks.upsertSetting }) },
+}));
+
+import { buildSharePointUpdate, SharePointSheet } from "./SharePointSheet";
+
+const storedSetting = () =>
+ create(SharePointSettingSchema, {
+ tenantId: "tenant",
+ clientId: "client",
+ clientSecretSet: true,
+ });
+
+const renderSheet = ({
+ stored = storedSetting(),
+ allowEdit = true,
+ onClose = vi.fn(),
+} = {}) => {
+ render(
+ <SharePointSheet
+ open
+ sessionKey={1}
+ stored={stored}
+ allowEdit={allowEdit}
+ onClose={onClose}
+ />
+ );
+ return { onClose };
+};
+
+describe("buildSharePointUpdate", () => {
+ test("masks only the changed fields and keeps the stored secret", () => {
+ const { paths, setting } = buildSharePointUpdate(storedSetting(), {
+ tenantId: " tenant-2 ",
+ clientId: "client",
+ clientSecret: undefined,
+ });
+ expect(paths).toEqual(["value.export.sharepoint.tenant_id"]);
+ expect(setting.tenantId).toBe("tenant-2");
+ expect(setting.clientSecret).toBe("");
+ });
+
+ test("masks a replacement secret", () => {
+ expect(
+ buildSharePointUpdate(storedSetting(), {
+ tenantId: "tenant",
+ clientId: "client",
+ clientSecret: "new-secret",
+ }).paths
+ ).toEqual(["value.export.sharepoint.client_secret"]);
+ });
+});
+
+describe("SharePointSheet", () => {
+ beforeEach(() => {
+ mocks.upsertSetting.mockClear();
+ });
+
+ test("shows that a secret is saved without revealing it", () => {
+ renderSheet();
+ expect(
+ screen.getByText("settings.sharepoint.client-secret-saved")
+ ).toBeInTheDocument();
+ expect(
+ screen.getByLabelText("settings.sharepoint.client-secret")
+ ).toHaveValue("");
+ });
+
+ test("saves a changed client ID and closes", async () => {
+ const { onClose } = renderSheet();
+ fireEvent.change(screen.getByLabelText("settings.sharepoint.client-id"), {
+ target: { value: "client-2" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "common.save" }));
+
+ await waitFor(() => expect(onClose).toHaveBeenCalled());
+ const params = mocks.upsertSetting.mock.calls[0][0];
+ expect(params.name).toBe(Setting_SettingName.EXPORT);
+ expect(params.updateMask.paths).toEqual([
+ "value.export.sharepoint.client_id",
+ ]);
+ expect(params.value.value).toMatchObject({
+ case: "export",
+ value: { sharepoint: { clientId: "client-2" } },
+ });
+ });
+
+ test("requires a secret before the first save", () => {
+ renderSheet({ stored: create(SharePointSettingSchema, {}) });
+ fireEvent.change(screen.getByLabelText("settings.sharepoint.tenant-id"), {
+ target: { value: "tenant" },
+ });
+ fireEvent.change(screen.getByLabelText("settings.sharepoint.client-id"), {
+ target: { value: "client" },
+ });
+ expect(screen.getByRole("button", { name: "common.save" })).toBeDisabled();
+ expect(
+ screen.queryByRole("button", { name: "common.remove" })
+ ).not.toBeInTheDocument();
+ });
+
+ test("removes the application after confirmation", async () => {
+ const { onClose } = renderSheet();
+ fireEvent.click(screen.getByRole("button", { name: "common.remove" }));
+ const confirm = await screen.findByRole("alertdialog");
+ fireEvent.click(
+ within(confirm).getByRole("button", { name: "common.remove" })
+ );
+
+ await waitFor(() => expect(onClose).toHaveBeenCalled());
+ const params = mocks.upsertSetting.mock.calls[0][0];
+ expect(params.updateMask.paths).toEqual([
+ "value.export.sharepoint.tenant_id",
+ "value.export.sharepoint.client_id",
+ ]);
+ expect(params.value.value).toMatchObject({
+ case: "export",
+ value: { sharepoint: { tenantId: "", clientId: "" } },
+ });
+ });
+
+ test("is read-only without edit access", () => {
+ renderSheet({ allowEdit: false });
+ expect(screen.getByLabelText("settings.sharepoint.tenant-id")).toBeDisabled();
+ expect(
+ screen.queryByRole("button", { name: "common.save" })
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "common.remove" })
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/routes/workspace/export-destinations/SharePointSheet.tsx b/frontend/src/routes/workspace/export-destinations/SharePointSheet.tsx
new file mode 100644
index 0000000000..2b2eca5f71
--- /dev/null
+++ b/frontend/src/routes/workspace/export-destinations/SharePointSheet.tsx
@@ -0,0 +1,306 @@
+import { create } from "@bufbuild/protobuf";
+import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
+import { useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { SecretInput } from "@/components/SecretInput";
+import { Alert } from "@/components/ui/alert";
+import {
+ AlertDialog,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import { FormField, FormFieldGroup, FormLabel } from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Sheet,
+ SheetBody,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from "@/components/ui/sheet";
+import { pushNotification } from "@/stores";
+import { useAppStore } from "@/stores/app";
+import {
+ ExportSettingSchema,
+ Setting_SettingName,
+ SettingValueSchema,
+ type SharePointSetting,
+ SharePointSettingSchema,
+} from "@/types/proto-es/v1/setting_service_pb";
+
+const MASK_PREFIX = "value.export.sharepoint";
+
+export interface SharePointDraft {
+ tenantId: string;
+ clientId: string;
+ // Undefined keeps the stored secret.
+ clientSecret: string | undefined;
+}
+
+export function buildSharePointUpdate(
+ stored: SharePointSetting,
+ draft: SharePointDraft
+): { setting: SharePointSetting; paths: string[] } {
+ const tenantId = draft.tenantId.trim();
+ const clientId = draft.clientId.trim();
+ const paths: string[] = [];
+ if (tenantId !== stored.tenantId) paths.push(`${MASK_PREFIX}.tenant_id`);
+ if (clientId !== stored.clientId) paths.push(`${MASK_PREFIX}.client_id`);
+ if (draft.clientSecret) paths.push(`${MASK_PREFIX}.client_secret`);
+ return {
+ setting: create(SharePointSettingSchema, {
+ tenantId,
+ clientId,
+ clientSecret: draft.clientSecret ?? "",
+ }),
+ paths,
+ };
+}
+
+async function saveSharePointSetting(
+ setting: SharePointSetting,
+ paths: string[]
+) {
+ await useAppStore.getState().upsertSetting({
+ name: Setting_SettingName.EXPORT,
+ value: create(SettingValueSchema, {
+ value: {
+ case: "export",
+ value: create(ExportSettingSchema, { sharepoint: setting }),
+ },
+ }),
+ updateMask: create(FieldMaskSchema, { paths }),
+ });
+}
+
+interface Props {
+ open: boolean;
+ // Changes on every open so the form starts from the stored setting.
+ sessionKey: number;
+ stored: SharePointSetting;
+ allowEdit: boolean;
+ onClose: () => void;
+}
+
+export function SharePointSheet({
+ open,
+ sessionKey,
+ stored,
+ allowEdit,
+ onClose,
+}: Props) {
+ // Keep the last open setting so the form stays stable through the close
+ // animation after a save or removal updates the store.
+ const storedRef = useRef(stored);
+ if (open) {
+ storedRef.current = stored;
+ }
+ return (
+ <Sheet open={open} onOpenChange={(next) => !next && onClose()}>
+ <SheetContent width="standard">
+ <SharePointForm
+ key={sessionKey}
+ stored={storedRef.current}
+ allowEdit={allowEdit}
+ onClose={onClose}
+ />
+ </SheetContent>
+ </Sheet>
+ );
+}
+
+function SharePointForm({
+ stored,
+ allowEdit,
+ onClose,
+}: {
+ stored: SharePointSetting;
+ allowEdit: boolean;
+ onClose: () => void;
+}) {
+ const { t } = useTranslation();
+ const configured = stored.tenantId !== "";
+ const [tenantId, setTenantId] = useState(stored.tenantId);
+ const [clientId, setClientId] = useState(stored.clientId);
+ const [clientSecret, setClientSecret] = useState<string | undefined>(
+ undefined
+ );
+ const [saving, setSaving] = useState(false);
+ const [confirmingRemove, setConfirmingRemove] = useState(false);
+
+ const update = buildSharePointUpdate(stored, {
+ tenantId,
+ clientId,
+ clientSecret,
+ });
+ const isDirty = update.paths.length > 0 || clientSecret === "";
+ const isValid =
+ update.setting.tenantId !== "" &&
+ update.setting.clientId !== "" &&
+ (stored.clientSecretSet ? clientSecret !== "" : !!clientSecret);
+
+ const run = async (action: () => Promise<void>, title: string) => {
+ setSaving(true);
+ try {
+ await action();
+ pushNotification({ module: "bytebase", style: "SUCCESS", title });
+ onClose();
+ } catch {
+ setSaving(false);
+ }
+ };
+
+ const save = () =>
+ run(
+ () => saveSharePointSetting(update.setting, update.paths),
+ t("common.updated")
+ );
+
+ // Clearing both IDs removes the application, secret included.
+ const remove = () =>
+ run(
+ () =>
+ saveSharePointSetting(create(SharePointSettingSchema, {}), [
+ `${MASK_PREFIX}.tenant_id`,
+ `${MASK_PREFIX}.client_id`,
+ ]),
+ t("common.removed")
+ );
+
+ return (
+ <>
+ <SheetHeader>
+ <SheetTitle>{t("export-data.destination.sharepoint")}</SheetTitle>
+ <SheetDescription>{t("settings.sharepoint.caption")}</SheetDescription>
+ </SheetHeader>
+ <SheetBody className="gap-y-6">
+ <Alert
+ variant="info"
+ title={t("settings.sharepoint.setup.title")}
+ description={
+ <ol className="list-decimal pl-4">
+ <li>{t("settings.sharepoint.setup.register")}</li>
+ <li>{t("settings.sharepoint.setup.grant")}</li>
+ <li>{t("settings.sharepoint.setup.project")}</li>
+ </ol>
+ }
+ />
+ <FormFieldGroup>
+ <FormField
+ title={
+ <FormLabel htmlFor="sharepoint-tenant-id">
+ {t("settings.sharepoint.tenant-id")}
+ </FormLabel>
+ }
+ >
+ <Input
+ id="sharepoint-tenant-id"
+ value={tenantId}
+ disabled={!allowEdit}
+ required
+ onChange={(event) => setTenantId(event.target.value)}
+ />
+ </FormField>
+ <FormField
+ title={
+ <FormLabel htmlFor="sharepoint-client-id">
+ {t("settings.sharepoint.client-id")}
+ </FormLabel>
+ }
+ >
+ <Input
+ id="sharepoint-client-id"
+ value={clientId}
+ disabled={!allowEdit}
+ required
+ onChange={(event) => setClientId(event.target.value)}
+ />
+ </FormField>
+ <FormField
+ title={
+ <FormLabel htmlFor="sharepoint-client-secret">
+ {t("settings.sharepoint.client-secret")}
+ </FormLabel>
+ }
+ description={
+ stored.clientSecretSet
+ ? t("settings.sharepoint.client-secret-saved")
+ : t("settings.sharepoint.client-secret-description")
+ }
+ >
+ <SecretInput
+ id="sharepoint-client-secret"
+ value={clientSecret}
+ isCreating={!stored.clientSecretSet}
+ allowEmpty={false}
+ disabled={!allowEdit}
+ placeholder={t("common.sensitive-placeholder")}
+ onValueChange={setClientSecret}
+ />
+ </FormField>
+ </FormFieldGroup>
+ </SheetBody>
+ <SheetFooter>
+ {configured && allowEdit && (
+ <Button
+ variant="destructive"
+ appearance="outline"
+ className="mr-auto"
+ disabled={saving}
+ onClick={() => setConfirmingRemove(true)}
+ >
+ {t("common.remove")}
+ </Button>
+ )}
+ <Button appearance="outline" disabled={saving} onClick={onClose}>
+ {t("common.cancel")}
+ </Button>
+ {allowEdit && (
+ <Button
+ disabled={!isValid || !isDirty || saving}
+ onClick={() => void save()}
+ >
+ {t("common.save")}
+ </Button>
+ )}
+ </SheetFooter>
+ <AlertDialog
+ open={confirmingRemove}
+ onOpenChange={(next) => !next && setConfirmingRemove(false)}
+ >
+ <AlertDialogContent>
+ <AlertDialogTitle>
+ {t("settings.sharepoint.remove.title")}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t("settings.sharepoint.remove.description")}
+ </AlertDialogDescription>
+ <AlertDialogFooter>
+ <Button
+ appearance="outline"
+ disabled={saving}
+ onClick={() => setConfirmingRemove(false)}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ variant="destructive"
+ disabled={saving}
+ onClick={() => {
+ setConfirmingRemove(false);
+ void remove();
+ }}
+ >
+ {t("common.remove")}
+ </Button>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ );
+}
diff --git a/frontend/src/routes/workspace/general/SQLEditorSection.test.tsx b/frontend/src/routes/workspace/general/SQLEditorSection.test.tsx
index 19fad3c756..82f02c6dbf 100644
--- a/frontend/src/routes/workspace/general/SQLEditorSection.test.tsx
+++ b/frontend/src/routes/workspace/general/SQLEditorSection.test.tsx
@@ -25,6 +25,7 @@ const mocks = vi.hoisted(() => {
disableCopyData: false,
allowAdminDataSource: false,
maximumResultRows: 0n,
+ disableDownload: false,
},
updateWorkspaceProfile: vi.fn(
async (_params: {
@@ -354,20 +355,39 @@ describe("SQLEditorSection theme", () => {
});
});
-// Export is controlled by the bb.sql.export permission, so the query data
-// policy toggles cover only copying and the admin data source.
describe("SQLEditorSection query data policy toggles", () => {
+ beforeEach(() => {
+ mocks.policy.disableDownload = false;
+ });
+
// The theme preview renders switches of its own; keep the settings ones.
- function settingSwitchLabels(): string[] {
- return Array.from(container.querySelectorAll('[role="switch"]'))
- .map((control) => control.parentElement?.textContent ?? "")
- .filter((label) => label.startsWith("settings.general.workspace."));
+ function settingSwitches(): HTMLElement[] {
+ return Array.from(
+ container.querySelectorAll<HTMLElement>('[role="switch"]')
+ ).filter((control) =>
+ (control.parentElement?.textContent ?? "").startsWith(
+ "settings.general.workspace."
+ )
+ );
+ }
+
+ function settingSwitch(label: string): HTMLElement {
+ const control = settingSwitches().find(
+ (candidate) => candidate.parentElement?.textContent === label
+ );
+ expect(control).toBeTruthy();
+ return control as HTMLElement;
}
- test("offers no workspace export setting", () => {
+ const ALLOW_DOWNLOAD = "settings.general.workspace.allow-download.self";
+
+ test("offers a download switch beside the copy and admin data source switches", () => {
render(<SQLEditorSection title="SQL Editor" onDirtyChange={() => {}} />);
- expect(settingSwitchLabels()).toEqual([
+ expect(
+ settingSwitches().map((control) => control.parentElement?.textContent)
+ ).toEqual([
+ ALLOW_DOWNLOAD,
"settings.general.workspace.data-copy",
"settings.general.workspace.allow-admin-data-source.self",
]);
@@ -378,9 +398,8 @@ describe("SQLEditorSection query data policy toggles", () => {
render(
<SQLEditorSection ref={ref} title="SQL Editor" onDirtyChange={() => {}} />
);
- const copySwitch = container.querySelector<HTMLElement>('[role="switch"]');
act(() => {
- copySwitch!.click();
+ settingSwitch("settings.general.workspace.data-copy").click();
});
expect(ref.current?.isDirty()).toBe(true);
@@ -393,9 +412,63 @@ describe("SQLEditorSection query data policy toggles", () => {
policy: {
policy: {
case: "queryDataPolicy",
- value: { disableCopyData: true, allowAdminDataSource: false },
+ value: {
+ disableCopyData: true,
+ disableDownload: false,
+ allowAdminDataSource: false,
+ },
},
},
});
});
+
+ test("allows download by default", () => {
+ render(<SQLEditorSection title="SQL Editor" onDirtyChange={() => {}} />);
+
+ expect(settingSwitch(ALLOW_DOWNLOAD)).toHaveAttribute(
+ "aria-checked",
+ "true"
+ );
+ });
+
+ test("turning off download saves disable_download", async () => {
+ const ref = createRef<SectionHandle>();
+ render(
+ <SQLEditorSection ref={ref} title="SQL Editor" onDirtyChange={() => {}} />
+ );
+ act(() => {
+ settingSwitch(ALLOW_DOWNLOAD).click();
+ });
+ expect(settingSwitch(ALLOW_DOWNLOAD)).toHaveAttribute(
+ "aria-checked",
+ "false"
+ );
+ expect(ref.current?.isDirty()).toBe(true);
+
+ await act(async () => {
+ await ref.current?.update();
+ });
+
+ expect(mocks.upsertPolicy.mock.calls[0][0]).toMatchObject({
+ policy: {
+ policy: {
+ value: { disableDownload: true },
+ },
+ },
+ });
+ });
+
+ test("reads the stored setting", () => {
+ mocks.policy.disableDownload = true;
+ const ref = createRef<SectionHandle>();
+ render(
+ <SQLEditorSection ref={ref} title="SQL Editor" onDirtyChange={() => {}} />
+ );
+
+ expect(settingSwitch(ALLOW_DOWNLOAD)).toHaveAttribute(
+ "aria-checked",
+ "false"
+ );
+ expect(ref.current?.isDirty()).toBe(false);
+ });
});
diff --git a/frontend/src/routes/workspace/general/SQLEditorSection.tsx b/frontend/src/routes/workspace/general/SQLEditorSection.tsx
index 8f2f88943e..a0aa7df99a 100644
--- a/frontend/src/routes/workspace/general/SQLEditorSection.tsx
+++ b/frontend/src/routes/workspace/general/SQLEditorSection.tsx
@@ -76,6 +76,7 @@ interface SQLEditorSectionProps {
interface LocalState {
disableCopyData: boolean;
+ disableDownload: boolean;
allowAdminDataSource: boolean;
// `null` represents an empty input while the user is typing; coerced to a
// number on save.
@@ -149,6 +150,7 @@ export const SQLEditorSection = forwardRef<
}
return {
disableCopyData: policyPayload.disableCopyData,
+ disableDownload: policyPayload.disableDownload,
allowAdminDataSource: policyPayload.allowAdminDataSource,
maximumResultSize: Math.round(Number(size) / 1024 / 1024),
maximumResultRows: rows,
@@ -290,6 +292,7 @@ export const SQLEditorSection = forwardRef<
const maximumResultRows = state.maximumResultRows ?? 0;
return (
init.disableCopyData !== state.disableCopyData ||
+ init.disableDownload !== state.disableDownload ||
init.allowAdminDataSource !== state.allowAdminDataSource ||
init.maximumResultRows !== maximumResultRows
);
@@ -354,6 +357,7 @@ export const SQLEditorSection = forwardRef<
value: create(QueryDataPolicySchema, {
...policyPayload,
disableCopyData: state.disableCopyData,
+ disableDownload: state.disableDownload,
allowAdminDataSource: state.allowAdminDataSource,
maximumResultRows,
}),
@@ -402,7 +406,7 @@ export const SQLEditorSection = forwardRef<
}, [state, selectedThemeId, customDraft, onDirtyChange]);
const handleToggle = (
- field: "disableCopyData" | "allowAdminDataSource",
+ field: "disableCopyData" | "disableDownload" | "allowAdminDataSource",
value: boolean
) => {
setState((prev) => ({ ...prev, [field]: value }));
@@ -418,6 +422,28 @@ export const SQLEditorSection = forwardRef<
return (
<FormSection id="security" title={title}>
<FormFieldGroup>
+ {/* Allow Download toggle */}
+ <PermissionGuard permissions={["bb.policies.update"]} display="block">
+ <FormField
+ title={
+ <span className="w-full inline-flex items-center gap-x-2">
+ <Switch
+ checked={!state.disableDownload}
+ disabled={!canUpdatePolicy || !hasQueryPolicyFeature}
+ onCheckedChange={(checked) =>
+ handleToggle("disableDownload", !checked)
+ }
+ />
+ {t("settings.general.workspace.allow-download.self")}
+ <FeatureBadge feature={PlanFeature.FEATURE_QUERY_POLICY} />
+ </span>
+ }
+ description={t(
+ "settings.general.workspace.allow-download.description"
+ )}
+ />
+ </PermissionGuard>
+
{/* Data Copy toggle */}
<PermissionGuard permissions={["bb.policies.update"]} display="block">
<FormField
diff --git a/frontend/src/stores/app/project.ts b/frontend/src/stores/app/project.ts
index 5b7cb82eff..cfc90cc4e2 100644
--- a/frontend/src/stores/app/project.ts
+++ b/frontend/src/stores/app/project.ts
@@ -361,12 +361,13 @@ export const createProjectSlice: AppSliceCreator<ProjectSlice> = (set, get) => {
return result;
},
- updateProject: async (project, updateMask) => {
+ updateProject: async (project, updateMask, report) => {
const response = await projectServiceClientConnect.updateProject(
createProto(UpdateProjectRequestSchema, {
project,
updateMask: { paths: updateMask },
- })
+ }),
+ callOptions(report)
);
upsertProjects([response]);
return response;
diff --git a/frontend/src/stores/app/sql.test.ts b/frontend/src/stores/app/sql.test.ts
new file mode 100644
index 0000000000..8e381eb777
--- /dev/null
+++ b/frontend/src/stores/app/sql.test.ts
@@ -0,0 +1,54 @@
+// @vitest-environment node
+import { create } from "@bufbuild/protobuf";
+import type { ContextValues } from "@connectrpc/connect";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { silentContextKey } from "@/api/context-key";
+import { ExportDestination } from "@/types/proto-es/v1/common_pb";
+import {
+ ExportRequestSchema,
+ ExportResponseSchema,
+} from "@/types/proto-es/v1/sql_service_pb";
+import { createSQLSlice } from "./sql";
+
+const mocks = vi.hoisted(() => ({ export: vi.fn() }));
+
+vi.mock("@/api", () => ({
+ sqlServiceClientConnect: { export: mocks.export },
+}));
+
+const slice = () =>
+ createSQLSlice((() => {}) as never, (() => ({})) as never, {} as never);
+
+const contextValuesOfLastCall = () =>
+ (mocks.export.mock.calls[0][1] as { contextValues: ContextValues })
+ .contextValues;
+
+describe("exportData", () => {
+ beforeEach(() => {
+ mocks.export.mockReset();
+ });
+
+ test("returns download content and reports errors normally", async () => {
+ const content = new Uint8Array([1, 2]);
+ mocks.export.mockResolvedValue(create(ExportResponseSchema, { content }));
+
+ const result = await slice().exportData(
+ create(ExportRequestSchema, { destination: ExportDestination.DOWNLOAD })
+ );
+
+ expect(result).toEqual({ content, uri: "" });
+ expect(contextValuesOfLastCall().get(silentContextKey)).toBe(false);
+ });
+
+ test("returns the exported folder URI and leaves failures to the export result", async () => {
+ const uri = "https://contoso.sharepoint.com/sites/Finance/Exports/20261022";
+ mocks.export.mockResolvedValue(create(ExportResponseSchema, { uri }));
+
+ const result = await slice().exportData(
+ create(ExportRequestSchema, { destination: ExportDestination.SHAREPOINT })
+ );
+
+ expect(result).toEqual({ content: new Uint8Array(), uri });
+ expect(contextValuesOfLastCall().get(silentContextKey)).toBe(true);
+ });
+});
diff --git a/frontend/src/stores/app/sql.ts b/frontend/src/stores/app/sql.ts
index 96dd37f607..11a6facfaf 100644
--- a/frontend/src/stores/app/sql.ts
+++ b/frontend/src/stores/app/sql.ts
@@ -1,6 +1,7 @@
import { Code, ConnectError, createContextValues } from "@connectrpc/connect";
import { sqlServiceClientConnect } from "@/api";
import { ignoredCodesContextKey, silentContextKey } from "@/api/context-key";
+import { ExportDestination } from "@/types/proto-es/v1/common_pb";
import { extractGrpcErrorMessage } from "@/utils/connect";
import type { AppSliceCreator, SQLSlice } from "./types";
@@ -8,7 +9,8 @@ import type { AppSliceCreator, SQLSlice } from "./types";
* Stateless — just RPC wrappers around `query` / `export` with the SQL
* editor's permission-denied + silent context conventions. Query failures are
* swallowed into the returned `SQLResultSetV1.error` so the result table can
- * render the error inline instead of bubbling a thrown exception.
+ * render the error inline instead of bubbling a thrown exception. SharePoint
+ * export failures are silent because the export result reports them.
*/
export const createSQLSlice: AppSliceCreator<SQLSlice> = () => ({
query: async (params, signal) => {
@@ -35,10 +37,13 @@ export const createSQLSlice: AppSliceCreator<SQLSlice> = () => ({
exportData: async (params) => {
const response = await sqlServiceClientConnect.export(params, {
- contextValues: createContextValues().set(ignoredCodesContextKey, [
- Code.PermissionDenied,
- ]),
+ contextValues: createContextValues()
+ .set(ignoredCodesContextKey, [Code.PermissionDenied])
+ .set(
+ silentContextKey,
+ params.destination === ExportDestination.SHAREPOINT
+ ),
});
- return response.content;
+ return { content: response.content, uri: response.uri };
},
});
diff --git a/frontend/src/stores/app/types.ts b/frontend/src/stores/app/types.ts
index 944e19f87c..a331f6095f 100644
--- a/frontend/src/stores/app/types.ts
+++ b/frontend/src/stores/app/types.ts
@@ -447,7 +447,11 @@ export type ProjectSlice = {
resourceId: string,
report?: ErrorReport
) => Promise<Project>;
- updateProject: (project: Project, updateMask: string[]) => Promise<Project>;
+ updateProject: (
+ project: Project,
+ updateMask: string[],
+ report?: ErrorReport
+ ) => Promise<Project>;
archiveProject: (project: Project) => Promise<void>;
restoreProject: (project: Project) => Promise<void>;
deleteProject: (project: string) => Promise<void>;
@@ -1046,7 +1050,14 @@ export type IssueSlice = {
// permission-denied / silent context conventions.
export type SQLSlice = {
query: (params: QueryRequest, signal: AbortSignal) => Promise<SQLResultSetV1>;
- exportData: (params: ExportRequest) => Promise<Uint8Array>;
+ exportData: (params: ExportRequest) => Promise<ExportDataResult>;
+};
+
+// For an export to a storage destination such as SharePoint, `uri` locates the
+// exported folder and `content` is empty.
+export type ExportDataResult = {
+ content: Uint8Array;
+ uri: string;
};
export interface GetOrFetchDatabaseMetadataParams {