Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(sql-editor): allow to query with selected data source (#13054)
boojacka3d440c51221
diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.goindex 357bdf9825..bbb9c75aa2 100644--- a/backend/api/v1/sql_service.go+++ b/backend/api/v1/sql_service.go@@ -672,6 +672,14 @@ func (s *SQLService) Query(ctx context.Context, request *v1pb.QueryRequest) (*v1return nil, err}+ ok, err := s.checkDataSourceQueriable(ctx, user, database, request.DataSourceId)+ if err != nil {+ return nil, status.Errorf(codes.Internal, "failed to check data source queriable: %v", err)+ }+ if !ok {+ return nil, status.Errorf(codes.PermissionDenied, "data source %q is not queriable", request.DataSourceId)+ }+statement := request.Statement// In Redshift datashare, Rewrite query used for parser.if database.DataShare {@@ -1593,3 +1601,96 @@ func getOffsetAndOriginTable(backupTable string) (int, string, error) {}return offset, strings.Join(parts[3:], "_"), nil}++func (s *SQLService) checkDataSourceQueriable(ctx context.Context, user *store.UserMessage, database *store.DatabaseMessage, dataSourceID string) (bool, error) {+ // Always allow the owner to query the data source.+ ok, err := s.iamManager.CheckPermission(ctx, iam.PermissionInstancesAdminExecute, user, database.ProjectID)+ if err != nil {+ return false, errors.Wrapf(err, "failed to check permission")+ }+ if ok {+ return true, nil+ }++ dataSource, err := s.store.GetDataSource(ctx, &store.FindDataSourceMessage{Name: &dataSourceID})+ if err != nil {+ return false, errors.Wrap(err, "failed to get data source")+ }+ if dataSource == nil {+ return false, errors.Errorf("data source %q not found", dataSourceID)+ }+ // Pass if the data source is not admin type.+ if dataSource.Type != api.Admin {+ return true, nil+ }++ var envAdminDataSourceRestriction, projectAdminDataSourceRestriction v1pb.DataSourceQueryPolicy_Restriction+ environment, err := s.store.GetEnvironmentV2(ctx, &store.FindEnvironmentMessage{ResourceID: &database.EffectiveEnvironmentID})+ if err != nil {+ return false, errors.Wrapf(err, "failed to get environment")+ }+ if environment == nil {+ return false, errors.Errorf("environment %q not found", database.EffectiveEnvironmentID)+ }+ dataSourceQueryPolicyType := api.PolicyTypeDataSourceQuery+ environmentResourceType := api.PolicyResourceTypeEnvironment+ projectResourceType := api.PolicyResourceTypeProject+ environmentPolicy, err := s.store.GetPolicyV2(ctx, &store.FindPolicyMessage{+ ResourceType: &environmentResourceType,+ ResourceUID: &environment.UID,+ Type: &dataSourceQueryPolicyType,+ })+ if err != nil {+ return false, errors.Wrapf(err, "failed to get policy")+ }+ if environmentPolicy != nil {+ envPayload, err := convertToV1PBDataSourceQueryPolicy(environmentPolicy.Payload)+ if err != nil {+ return false, errors.Wrapf(err, "failed to convert policy payload")+ }+ envAdminDataSourceRestriction = envPayload.DataSourceQueryPolicy.GetAdminDataSourceRestriction()+ }++ project, err := s.store.GetProjectV2(ctx, &store.FindProjectMessage{ResourceID: &database.ProjectID})+ if err != nil {+ return false, errors.Wrapf(err, "failed to get project")+ }+ if project == nil {+ return false, errors.Errorf("project %q not found", database.ProjectID)+ }+ projectPolicy, err := s.store.GetPolicyV2(ctx, &store.FindPolicyMessage{+ ResourceType: &projectResourceType,+ ResourceUID: &project.UID,+ Type: &dataSourceQueryPolicyType,+ })+ if err != nil {+ return false, errors.Wrapf(err, "failed to get policy")+ }+ if projectPolicy != nil {+ projectPayload, err := convertToV1PBDataSourceQueryPolicy(projectPolicy.Payload)+ if err != nil {+ return false, errors.Wrapf(err, "failed to convert policy payload")+ }+ projectAdminDataSourceRestriction = projectPayload.DataSourceQueryPolicy.GetAdminDataSourceRestriction()+ }++ // If any of the policy is DISALLOW, then return false.+ if envAdminDataSourceRestriction == v1pb.DataSourceQueryPolicy_DISALLOW || projectAdminDataSourceRestriction == v1pb.DataSourceQueryPolicy_DISALLOW {+ return false, nil+ } else if envAdminDataSourceRestriction == v1pb.DataSourceQueryPolicy_FALLBACK || projectAdminDataSourceRestriction == v1pb.DataSourceQueryPolicy_FALLBACK {+ readOnlyDataSourceType := api.RO+ readOnlyDataSources, err := s.store.ListDataSourcesV2(ctx, &store.FindDataSourceMessage{+ InstanceID: &database.InstanceID,+ Type: &readOnlyDataSourceType,+ })+ if err != nil {+ return false, errors.Wrapf(err, "failed to list read-only data sources")+ }+ // If there is any read-only data source, then return false.+ if len(readOnlyDataSources) > 0 {+ return false, nil+ }+ }++ return true, nil+}diff --git a/backend/legacyapi/policy.go b/backend/legacyapi/policy.goindex 449a1c84a3..5425f0792a 100644--- a/backend/legacyapi/policy.go+++ b/backend/legacyapi/policy.go@@ -90,5 +90,6 @@ var (PolicyTypeMaskingException: {PolicyResourceTypeProject},PolicyTypeRestrictIssueCreationForSQLReview: {PolicyResourceTypeWorkspace, PolicyResourceTypeProject},PolicyTypeIAM: {PolicyResourceTypeWorkspace},+ PolicyTypeDataSourceQuery: {PolicyResourceTypeEnvironment, PolicyResourceTypeProject},})diff --git a/backend/store/data_source.go b/backend/store/data_source.goindex fdf3f3a314..4b1a75b70d 100644--- a/backend/store/data_source.go+++ b/backend/store/data_source.go@@ -61,6 +61,14 @@ type DataSourceMessage struct {MasterObfuscatedPassword string}+// FindDataSourceMessage is the message for finding a database.+type FindDataSourceMessage struct {+ ID *string+ Name *string+ InstanceID *string+ Type *api.DataSourceType+}+// Copy returns a copy of the data source message.func (m *DataSourceMessage) Copy() *DataSourceMessage {deepCopyAdditionalAddresses := slices.Clone[[]*storepb.DataSourceOptions_Address](m.AdditionalAddresses)@@ -150,10 +158,19 @@ type UpdateDataSourceMessage struct {MasterObfuscatedPassword *string}-func (*Store) listDataSourceV2(ctx context.Context, tx *Tx, instanceID *string) (map[string][]*DataSourceMessage, error) {+func (*Store) listDataSourceV2(ctx context.Context, tx *Tx, find *FindDataSourceMessage) (map[string][]*DataSourceMessage, error) {where, args := []string{"TRUE"}, []any{}- if instanceID != nil {- where, args = append(where, fmt.Sprintf("instance.resource_id = $%d", len(args)+1)), append(args, *instanceID)+ if find.ID != nil {+ where, args = append(where, fmt.Sprintf("data_source.id = $%d", len(args)+1)), append(args, *find.ID)+ }+ if find.Name != nil {+ where, args = append(where, fmt.Sprintf("data_source.name = $%d", len(args)+1)), append(args, *find.Name)+ }+ if find.InstanceID != nil {+ where, args = append(where, fmt.Sprintf("instance.resource_id = $%d", len(args)+1)), append(args, *find.InstanceID)+ }+ if find.Type != nil {+ where, args = append(where, fmt.Sprintf("data_source.type = $%d", len(args)+1)), append(args, *find.Type)}instanceDataSourcesMap := make(map[string][]*DataSourceMessage)@@ -239,6 +256,53 @@ func (*Store) listDataSourceV2(ctx context.Context, tx *Tx, instanceID *string)return instanceDataSourcesMap, nil}+func (s *Store) ListDataSourcesV2(ctx context.Context, find *FindDataSourceMessage) (map[string][]*DataSourceMessage, error) {+ tx, err := s.db.BeginTx(ctx, nil)+ if err != nil {+ return nil, errors.New("Failed to begin transaction")+ }+ defer tx.Rollback()++ dataSources, err := s.listDataSourceV2(ctx, tx, find)+ if err != nil {+ return nil, err+ }++ return dataSources, nil+}++func (s *Store) GetDataSource(ctx context.Context, find *FindDataSourceMessage) (*DataSourceMessage, error) {+ tx, err := s.db.BeginTx(ctx, nil)+ if err != nil {+ return nil, errors.New("Failed to begin transaction")+ }+ defer tx.Rollback()++ dataSources, err := s.listDataSourceV2(ctx, tx, find)+ if err != nil {+ return nil, err+ }++ if len(dataSources) == 0 {+ return nil, nil+ }+ if len(dataSources) > 1 {+ return nil, errors.Errorf("found %d data sources, but expected 1", len(dataSources))+ }++ for _, dataSources := range dataSources {+ if len(dataSources) == 0 {+ return nil, nil+ }+ if len(dataSources) > 1 {+ return nil, errors.Errorf("found %d data sources, but expected 1", len(dataSources))+ }+ return dataSources[0], nil+ }++ return nil, nil+}+// AddDataSourceToInstanceV2 adds a RO data source to an instance and return the instance where the data source is added.func (s *Store) AddDataSourceToInstanceV2(ctx context.Context, instanceUID, creatorID int, instanceID string, dataSource *DataSourceMessage) error {tx, err := s.db.BeginTx(ctx, nil)diff --git a/backend/store/instance.go b/backend/store/instance.goindex a6dbe2a099..5e6a980af3 100644--- a/backend/store/instance.go+++ b/backend/store/instance.go@@ -197,7 +197,9 @@ func (s *Store) CreateInstanceV2(ctx context.Context, instanceCreate *InstanceMe}}- instanceDataSourcesMap, err := s.listDataSourceV2(ctx, tx, &instanceCreate.ResourceID)+ instanceDataSourcesMap, err := s.listDataSourceV2(ctx, tx, &FindDataSourceMessage{+ InstanceID: &instanceCreate.ResourceID,+ })if err != nil {return nil, err}@@ -346,7 +348,9 @@ func (s *Store) UpdateInstanceV2(ctx context.Context, patch *UpdateInstanceMessa}}instance.Deleted = convertRowStatusToDeleted(rowStatus)- instanceDataSourcesMap, err := s.listDataSourceV2(ctx, tx, &patch.ResourceID)+ instanceDataSourcesMap, err := s.listDataSourceV2(ctx, tx, &FindDataSourceMessage{+ InstanceID: &patch.ResourceID,+ })if err != nil {return nil, err}@@ -459,9 +463,9 @@ func (s *Store) listInstanceImplV2(ctx context.Context, tx *Tx, find *FindInstan}// Use a single query to list all data sources if there are more than one instance to look at.- var dataSourceFind *string+ dataSourceFind := &FindDataSourceMessage{}if len(instanceMessages) == 1 {- dataSourceFind = &instanceMessages[0].ResourceID+ dataSourceFind.InstanceID = &instanceMessages[0].ResourceID}instanceDataSourcesMap, err := s.listDataSourceV2(ctx, tx, dataSourceFind)if err != nil {diff --git a/frontend/src/components/EnvironmentForm/AccessControlConfigure.vue b/frontend/src/components/EnvironmentForm/AccessControlConfigure.vueindex 32b6213733..65cd267766 100644--- a/frontend/src/components/EnvironmentForm/AccessControlConfigure.vue+++ b/frontend/src/components/EnvironmentForm/AccessControlConfigure.vue@@ -6,23 +6,65 @@</label><FeatureBadge feature="bb.feature.access-control" /></div>- <div>- <div class="inline-flex items-center gap-x-2">+ <div class="w-full flex flex-col gap-4">+ <div class="w-full inline-flex items-center gap-x-2"><Switch:value="disableCopyDataPolicy":text="true"- :disabled="!allowEditDisableCopyData"- @update:value="upsertPolicy"+ :disabled="!allowUpdatePolicy"+ @update:value="updateDisableCopyDataPolicy"/><span class="textlabel">{{$t("environment.access-control.disable-copy-data-from-sql-editor")}}</span></div>+ <div class="">+ <div class="w-full inline-flex items-center gap-x-2">+ <Switch+ :value="adminDataSourceQueruRestrictionEnabled"+ :text="true"+ :disabled="!allowUpdatePolicy"+ @update:value="switchDataSourceQueryPolicyEnabled"+ />+ <span class="textlabel">{{+ $t("environment.access-control.restrict-admin-data-sources.self")+ }}</span>+ </div>+ <div v-if="adminDataSourceQueruRestrictionEnabled" class="ml-12">+ <NRadioGroup+ :value="adminDataSourceQueruRestriction"+ :disabled="!allowUpdatePolicy"+ @update:value="updateAdminDataSourceQueryRestrctionPolicy"+ >+ <NRadio+ class="w-full"+ :value="DataSourceQueryPolicy_Restriction.DISALLOW"+ >+ {{+ $t(+ "environment.access-control.restrict-admin-data-sources.disallow"+ )+ }}+ </NRadio>+ <NRadio+ class="w-full"+ :value="DataSourceQueryPolicy_Restriction.FALLBACK"+ >+ {{+ $t(+ "environment.access-control.restrict-admin-data-sources.fallback"+ )+ }}+ </NRadio>+ </NRadioGroup>+ </div>+ </div></div></div></template><script setup lang="ts">+import { NRadioGroup, NRadio } from "naive-ui";import { computed } from "vue";import { useI18n } from "vue-i18n";import {@@ -32,7 +74,7 @@ import {useCurrentUserV1,} from "@/store";import {- PolicyResourceType,+ DataSourceQueryPolicy_Restriction,PolicyType,} from "@/types/proto/v1/org_policy_service";import { hasWorkspacePermissionV2 } from "@/utils";@@ -55,7 +97,28 @@ const disableCopyDataPolicy = computed(() => {})?.disableCopyDataPolicy?.active;});-const allowEditDisableCopyData = computed(() => {+const dataSourceQueryPolicy = computed(() => {+ return policyStore.getPolicyByParentAndType({+ parentPath: props.resource,+ policyType: PolicyType.DATA_SOURCE_QUERY,+ })?.dataSourceQueryPolicy;+});++const adminDataSourceQueruRestriction = computed(() => {+ return dataSourceQueryPolicy.value?.adminDataSourceRestriction;+});++const adminDataSourceQueruRestrictionEnabled = computed(() => {+ return (+ adminDataSourceQueruRestriction.value &&+ [+ DataSourceQueryPolicy_Restriction.DISALLOW,+ DataSourceQueryPolicy_Restriction.FALLBACK,+ ].includes(adminDataSourceQueruRestriction.value)+ );+});++const allowUpdatePolicy = computed(() => {return (props.allowEdit &&hasWorkspacePermissionV2(me.value, "bb.policies.update") &&@@ -63,10 +126,9 @@ const allowEditDisableCopyData = computed(() => {);});-const upsertPolicy = async (on: boolean) => {+const updateDisableCopyDataPolicy = async (on: boolean) => {await policyStore.createPolicy(props.resource, {type: PolicyType.DISABLE_COPY_DATA,- resourceType: PolicyResourceType.ENVIRONMENT,disableCopyDataPolicy: {active: on,},@@ -77,4 +139,28 @@ const upsertPolicy = async (on: boolean) => {title: t("common.updated"),});};++const switchDataSourceQueryPolicyEnabled = async (on: boolean) => {+ await updateAdminDataSourceQueryRestrctionPolicy(+ on+ ? DataSourceQueryPolicy_Restriction.DISALLOW+ : DataSourceQueryPolicy_Restriction.RESTRICTION_UNSPECIFIED+ );+};++const updateAdminDataSourceQueryRestrctionPolicy = async (+ restrction: DataSourceQueryPolicy_Restriction+) => {+ await policyStore.createPolicy(props.resource, {+ type: PolicyType.DATA_SOURCE_QUERY,+ dataSourceQueryPolicy: {+ adminDataSourceRestriction: restrction,+ },+ });+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.updated"),+ });+};</script>diff --git a/frontend/src/customAppProfile.ts b/frontend/src/customAppProfile.tsindex 1235e102a3..21800a0646 100644--- a/frontend/src/customAppProfile.ts+++ b/frontend/src/customAppProfile.ts@@ -49,7 +49,6 @@ export const overrideAppProfile = () => {"--color-accent-hover": "#00554f","--color-accent-disabled": "#b8c3c3",},- "bb.feature.sql-editor.custom-query-datasource": true,"bb.feature.sql-editor.disallow-export-query-data": true,});if (actuatorStore.appProfile.embedded) {diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex de5406f419..f34986c236 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1550,7 +1550,12 @@"production-environment": "Production environment","access-control": {"title": "Access control",- "disable-copy-data-from-sql-editor": "Restrict data copying in SQL Editor (Admins/DBAs allowed)"+ "disable-copy-data-from-sql-editor": "Restrict data copying in SQL Editor (Admins/DBAs allowed)",+ "restrict-admin-data-sources": {+ "self": "Restrict admin data sources",+ "disallow": "Disallow to query data from admin data source",+ "fallback": "Fallback to admin data source if no read-only data source is available"+ }}},"quick-start": {@@ -2416,6 +2421,10 @@"description": "Auto Completion might be limited or disabled.","disconnected": "WebSocket disconnected"}+ },+ "query-context": {+ "admin-data-source-is-disallowed-to-query": "Admin data source is disallowed to query.",+ "admin-data-source-is-disallowed-to-query-when-read-only-data-source-is-available": "Admin data source is disallowed to query when read-only data source is available."}},"schema-editor": {diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 6e27079531..5d8fb9912b 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -1550,7 +1550,12 @@"production-environment": "Entorno de producción","access-control": {"title": "Control de acceso",- "disable-copy-data-from-sql-editor": "Restringir la copia de datos en el editor SQL (permitido para administradores/DBA)"+ "disable-copy-data-from-sql-editor": "Restringir la copia de datos en el editor SQL (permitido para administradores/DBA)",+ "restrict-admin-data-sources": {+ "self": "Restringir fuentes de datos de administrador",+ "disallow": "No permitir consultar datos de la fuente de datos del administrador",+ "fallback": "Recurrir a la fuente de datos del administrador si no hay ninguna fuente de datos de solo lectura disponible"+ }}},"quick-start": {@@ -2416,6 +2421,10 @@"description": "La finalización automática puede estar limitada o deshabilitada.","disconnected": "WebSocket desconectado"}+ },+ "query-context": {+ "admin-data-source-is-disallowed-to-query": "No se permite realizar consultas a la fuente de datos del administrador.",+ "admin-data-source-is-disallowed-to-query-when-read-only-data-source-is-available": "No se permite realizar consultas a la fuente de datos del administrador cuando la fuente de datos de solo lectura está disponible."}},"schema-editor": {@@ -3622,4 +3631,4 @@"self": "Última actualización"}}-}+}\ No newline at end of filediff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex db120e62a4..034e87e23f 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -1550,7 +1550,12 @@"production-environment": "本番環境","access-control": {"title": "アクセス制御",- "disable-copy-data-from-sql-editor": "SQL エディタにおけるデータコピーの制限 (管理者/DBA はコピー可能)"+ "disable-copy-data-from-sql-editor": "SQL エディタにおけるデータコピーの制限 (管理者/DBA はコピー可能)",+ "restrict-admin-data-sources": {+ "self": "管理者データソースを制限する",+ "disallow": "管理データソースからのデータのクエリを禁止する",+ "fallback": "読み取り専用データソースが利用できない場合は、管理データソースにフォールバックします。"+ }}},"quick-start": {@@ -2416,6 +2421,10 @@"description": "オートコンプリートが制限されているか、無効になっている可能性があります。","disconnected": "WebSocketが切断されました"}+ },+ "query-context": {+ "admin-data-source-is-disallowed-to-query": "管理者データ ソースはクエリできません。",+ "admin-data-source-is-disallowed-to-query-when-read-only-data-source-is-available": "読み取り専用データ ソースが使用可能な場合、管理データ ソースはクエリを実行できません。"}},"schema-editor": {@@ -3622,4 +3631,4 @@"self": "最後の更新"}}-}+}\ No newline at end of filediff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 64813459b0..caee7e7c80 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1550,7 +1550,12 @@"production-environment": "生产环境","access-control": {"title": "访问控制",- "disable-copy-data-from-sql-editor": "限制 SQL 编辑器中的数据复制 (管理员/DBA 可以复制)"+ "disable-copy-data-from-sql-editor": "限制 SQL 编辑器中的数据复制 (管理员/DBA 可以复制)",+ "restrict-admin-data-sources": {+ "self": "限制管理员数据源的查询权限",+ "disallow": "禁止查询管理员数据源",+ "fallback": "如果没有只读数据源,则可以查询管理员数据源"+ }}},"quick-start": {@@ -2252,8 +2257,8 @@"connection-type": "连接类型","additional-node-addresses": "附加节点地址","replica-set": "副本集",- "admin": "主库",- "read-only": "从库",+ "admin": "管理员",+ "read-only": "只读","direct-connection": "Direct Connection"},"setting": {@@ -2416,6 +2421,10 @@"description": "自动补全功能可能会受到限制或无效。","disconnected": "WebSocket 已断开连接"}+ },+ "query-context": {+ "admin-data-source-is-disallowed-to-query": "禁止查询管理员数据源。",+ "admin-data-source-is-disallowed-to-query-when-read-only-data-source-is-available": "当只读数据源可用时,不允许查询管理员数据源。"}},"schema-editor": {@@ -3622,4 +3631,4 @@"self": "最后更新"}}-}\ No newline at end of file+}diff --git a/frontend/src/types/appProfile.ts b/frontend/src/types/appProfile.tsindex 1d109bf89b..37811a35bb 100644--- a/frontend/src/types/appProfile.ts+++ b/frontend/src/types/appProfile.ts@@ -27,7 +27,6 @@ export type AppFeatures = {>;"bb.feature.databases.hide-unassigned": boolean;"bb.feature.databases.hide-inalterable": boolean;- "bb.feature.sql-editor.custom-query-datasource": boolean;"bb.feature.sql-editor.disable-setting": boolean;"bb.feature.sql-editor.disallow-share-worksheet": boolean;"bb.feature.sql-editor.disallow-export-query-data": boolean;@@ -73,7 +72,6 @@ export const defaultAppProfile = (): AppProfile => ({]),"bb.feature.databases.hide-unassigned": false,"bb.feature.databases.hide-inalterable": false,- "bb.feature.sql-editor.custom-query-datasource": false,"bb.feature.sql-editor.disable-setting": false,"bb.feature.sql-editor.disallow-share-worksheet": false,"bb.feature.sql-editor.disallow-export-query-data": false,diff --git a/frontend/src/views/project/ProjectSettingPanel.vue b/frontend/src/views/project/ProjectSettingPanel.vueindex d791777e95..7c484b98a6 100644--- a/frontend/src/views/project/ProjectSettingPanel.vue+++ b/frontend/src/views/project/ProjectSettingPanel.vue@@ -3,16 +3,18 @@</template><script setup lang="ts">-import { computed } from "vue";+import { computed, watchEffect } from "vue";import ProjectSettingPanel from "@/components/ProjectSettingPanel.vue";-import { useProjectV1Store } from "@/store";+import { usePolicyV1Store, useProjectV1Store } from "@/store";import { projectNamePrefix } from "@/store/modules/v1/common";+import { PolicyResourceType } from "@/types/proto/v1/org_policy_service";const props = defineProps<{projectId: string;allowEdit: boolean;}>();+const policyV1Store = usePolicyV1Store();const projectV1Store = useProjectV1Store();const project = computed(() => {@@ -20,4 +22,13 @@ const project = computed(() => {`${projectNamePrefix}${props.projectId}`);});++const preparePolicies = () => {+ policyV1Store.fetchPolicies({+ parent: project.value.name,+ resourceType: PolicyResourceType.PROJECT,+ });+};++watchEffect(preparePolicies);</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vueindex d9c64f5840..edba840eb6 100644--- a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue+++ b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue@@ -148,9 +148,6 @@ const hasSharedSQLScriptFeature = featureToRef("bb.feature.shared-sql-script");const disallowShareWorksheet = useAppFeature("bb.feature.sql-editor.disallow-share-worksheet");-const hasCustomQueryDatasourceFeature = useAppFeature(- "bb.feature.sql-editor.custom-query-datasource"-);const { currentTab, isDisconnected } = storeToRefs(tabStore);@@ -193,7 +190,6 @@ const allowSave = computed(() => {if (!showSheetsFeature.value) {return false;}-if (isEmptyStatement.value) {return false;}@@ -243,11 +239,7 @@ const showQueryContextSettingPopover = computed(() => {if (!tab) {return false;}- return (- Boolean(instance.value) &&- tab.mode !== "ADMIN" &&- hasCustomQueryDatasourceFeature.value- );+ return instance.value && tab.mode !== "ADMIN";});const showQueryModeSelect = computed(() => {diff --git a/frontend/src/views/sql-editor/EditorCommon/QueryContextSettingPopover.vue b/frontend/src/views/sql-editor/EditorCommon/QueryContextSettingPopover.vueindex f4eb71e221..cc22c34582 100644--- a/frontend/src/views/sql-editor/EditorCommon/QueryContextSettingPopover.vue+++ b/frontend/src/views/sql-editor/EditorCommon/QueryContextSettingPopover.vue@@ -8,14 +8,38 @@</NButton></template><div>- <p class="mb-1">{{ $t("data-source.select-data-source") }}</p>- <NSelect- class="!w-40"- :options="dataSourceOptions"+ <p class="mb-1 textinfolabel">+ {{ $t("data-source.select-data-source") }}+ </p>+ <NRadioGroup+ class="max-w-44":value="selectedDataSourceId"- :render-label="renderLabel"- @update:value="handleDataSourceSelect"- />+ @update:value="onDataSourceSelected"+ >+ <NTooltip+ v-for="ds in dataSources"+ :key="ds.id"+ :disabled="!Boolean(dataSourceUnaccessibleReason(ds))"+ >+ <template #trigger>+ <NRadio+ class="w-full"+ :value="ds.id"+ :disabled="Boolean(dataSourceUnaccessibleReason(ds))"+ >+ <div class="max-w-36 flex flex-row justify-start items-center">+ <span class="text-xs opacity-60 shrink-0">{{+ readableDataSourceType(ds.type)+ }}</span>+ <span class="ml-1 truncate">{{ ds.username }}</span>+ </div>+ </NRadio>+ </template>+ <p class="text-nowrap">+ {{ dataSourceUnaccessibleReason(ds) }}+ </p>+ </NTooltip>+ </NRadioGroup></div></NPopover></template>@@ -23,93 +47,112 @@<script lang="ts" setup>import { head, orderBy } from "lodash-es";import { ChevronDown } from "lucide-vue-next";-import type { SelectOption, SelectRenderLabel } from "naive-ui";-import { NButton, NEllipsis, NPopover, NSelect } from "naive-ui";-import { computed, h, watch } from "vue";+import { NButton, NPopover, NRadioGroup, NRadio, NTooltip } from "naive-ui";+import { computed, watch } from "vue";import { useI18n } from "vue-i18n";import {useConnectionOfCurrentSQLEditorTab,+ useCurrentUserV1,+ usePolicyV1Store,useSQLEditorTabStore,} from "@/store";-import type { DataSource } from "@/types/proto/v1/instance_service";-import { DataSourceType } from "@/types/proto/v1/instance_service";--interface DataSourceSelectOption extends SelectOption {- value: string;- dataSource: DataSource;-}+import { isValidDatabaseName } from "@/types";+import { DataSource, DataSourceType } from "@/types/proto/v1/instance_service";+import {+ DataSourceQueryPolicy_Restriction,+ PolicyType,+} from "@/types/proto/v1/org_policy_service";+import { hasWorkspacePermissionV2 } from "@/utils";const { t } = useI18n();const tabStore = useSQLEditorTabStore();-const { connection, instance: selectedInstance } =- useConnectionOfCurrentSQLEditorTab();+const { connection } = useConnectionOfCurrentSQLEditorTab();+const currentUser = useCurrentUserV1();+const policyStore = usePolicyV1Store();+const { database } = useConnectionOfCurrentSQLEditorTab();++const adminDataSourceRestriction = computed(() => {+ if (!database.value) {+ return {+ environmentPolicy:+ DataSourceQueryPolicy_Restriction.RESTRICTION_UNSPECIFIED,+ projectPolicy: DataSourceQueryPolicy_Restriction.RESTRICTION_UNSPECIFIED,+ };+ }+ if (+ hasWorkspacePermissionV2(currentUser.value, "bb.instances.adminExecute")+ ) {+ return {+ environmentPolicy:+ DataSourceQueryPolicy_Restriction.RESTRICTION_UNSPECIFIED,+ projectPolicy: DataSourceQueryPolicy_Restriction.RESTRICTION_UNSPECIFIED,+ };+ }++ const projectLevelPolicy = policyStore.getPolicyByParentAndType({+ parentPath: database.value.project,+ policyType: PolicyType.DATA_SOURCE_QUERY,+ });+ const projectLevelAdminDSRestriction =+ projectLevelPolicy?.dataSourceQueryPolicy?.adminDataSourceRestriction;+ const envLevelPolicy = policyStore.getPolicyByParentAndType({+ parentPath: database.value.effectiveEnvironment,+ policyType: PolicyType.DATA_SOURCE_QUERY,+ });+ const envLevelAdminDSRestriction =+ envLevelPolicy?.dataSourceQueryPolicy?.adminDataSourceRestriction;+ return {+ environmentPolicy:+ envLevelAdminDSRestriction ??+ DataSourceQueryPolicy_Restriction.RESTRICTION_UNSPECIFIED,+ projectPolicy:+ projectLevelAdminDSRestriction ??+ DataSourceQueryPolicy_Restriction.RESTRICTION_UNSPECIFIED,+ };+});+const selectedDataSourceId = computed(() => {return connection.value.dataSourceId;});const dataSources = computed(() => {- return orderBy(selectedInstance.value?.dataSources ?? [], "type");-});--const dataSourceOptions = computed(() => {- return dataSources.value.map((dataSource) => {- return {- value: dataSource.id,- label: dataSource.username,- dataSource: dataSource,- };- });+ return orderBy(database.value.instanceResource.dataSources, "type");});-const renderLabel: SelectRenderLabel = (option) => {- const { dataSource } = option as DataSourceSelectOption;- if (!dataSource) {- return;+const dataSourceUnaccessibleReason = (+ dataSource: DataSource+): string | undefined => {+ if (dataSource.type === DataSourceType.ADMIN) {+ if (+ adminDataSourceRestriction.value.environmentPolicy ===+ DataSourceQueryPolicy_Restriction.DISALLOW ||+ adminDataSourceRestriction.value.projectPolicy ===+ DataSourceQueryPolicy_Restriction.DISALLOW+ ) {+ return t(+ "sql-editor.query-context.admin-data-source-is-disallowed-to-query"+ );+ }+ const readOnlyDataSources = dataSources.value.filter(+ (ds) => ds.type === DataSourceType.READ_ONLY+ );+ if (+ readOnlyDataSources.length > 0 &&+ (adminDataSourceRestriction.value.environmentPolicy ===+ DataSourceQueryPolicy_Restriction.FALLBACK ||+ adminDataSourceRestriction.value.projectPolicy ===+ DataSourceQueryPolicy_Restriction.FALLBACK)+ ) {+ return t(+ "sql-editor.query-context.admin-data-source-is-disallowed-to-query-when-read-only-data-source-is-available"+ );+ }}- const children = [- h(- "span",- {- class: "text-gray-400 text-sm",- },- [readableDataSourceType(dataSource.type)]- ),- h(- NPopover,- {- placement: "top",- trigger: "hover",- class: "ml-1",- },- {- trigger: () => {- return h(- "span",- {- class: "ml-1",- },- [dataSource.username]- );- },- default: () => {- return h("div", {}, [dataSource.host, ":", dataSource.port]);- },- }- ),- ];- return h(- NEllipsis,- {- class: "w-full",- },- {- default: () => children,- }- );+ return undefined;};-const handleDataSourceSelect = (dataSourceId?: string) => {+const onDataSourceSelected = (dataSourceId?: string) => {tabStore.updateCurrentTab({connection: {...connection.value,@@ -141,10 +184,30 @@ watch();// Default set the first read only data source as selected.if (readOnlyDataSources.length > 0) {- handleDataSourceSelect(readOnlyDataSources[0].id);+ onDataSourceSelected(readOnlyDataSources[0].id);} else {- handleDataSourceSelect(head(dataSources.value)?.id);+ onDataSourceSelected(head(dataSources.value)?.id);+ }+ },+ {+ immediate: true,+ }+);++watch(+ () => database.value.name,+ async () => {+ if (!isValidDatabaseName(database.value.name)) {+ return;}+ await policyStore.getOrFetchPolicyByParentAndType({+ parentPath: database.value.effectiveEnvironment,+ policyType: PolicyType.DATA_SOURCE_QUERY,+ });+ await policyStore.getOrFetchPolicyByParentAndType({+ parentPath: database.value.project,+ policyType: PolicyType.DATA_SOURCE_QUERY,+ });},{immediate: true,