Skip to content

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

fix: close project instance support gaps (#21248)

p0nyecbc25e8470f
diff --git a/backend/api/lsp/commands.go b/backend/api/lsp/commands.go
index 11237ef489..e68203a52f 100644
--- a/backend/api/lsp/commands.go
+++ b/backend/api/lsp/commands.go
@@ -18,8 +18,8 @@ type SetMetadataCommandParams struct {
// SetMetadataCommandArguments are the arguments to the "setMetadata" command.
type SetMetadataCommandArguments struct {
- // The InstanceID is the instance ID to set metadata for.
- // Format: instances/{instance}
+ // The InstanceID is the instance resource name to set metadata for.
+ // Format: instances/{instance} or projects/{project}/instances/{instance}
InstanceID string `json:"instanceId,omitempty"`
// The DatabaseName is the connection database name.
// For PostgreSQL, it's required.
diff --git a/backend/api/lsp/handler.go b/backend/api/lsp/handler.go
index deb37dfa07..264214fee2 100644
--- a/backend/api/lsp/handler.go
+++ b/backend/api/lsp/handler.go
@@ -135,7 +135,7 @@ func (h *Handler) getInstanceID() string {
if h.metadata == nil {
return ""
}
- id, err := common.GetInstanceID(h.metadata.InstanceID)
+ _, id, err := common.GetInstanceResourceName(h.metadata.InstanceID)
if err != nil {
return ""
}
@@ -157,26 +157,59 @@ func (h *Handler) getScene() base.SceneType {
}
func (h *Handler) getEngineType(ctx context.Context) storepb.Engine {
- instanceID := h.getInstanceID()
- if instanceID == "" {
+ h.mu.Lock()
+ if h.metadata == nil {
+ h.mu.Unlock()
return storepb.Engine_ENGINE_UNSPECIFIED
}
+ instanceName := h.metadata.InstanceID
+ h.mu.Unlock()
- instance, err := h.store.GetInstance(ctx, &store.FindInstanceMessage{
- Workspace: common.GetWorkspaceIDFromContext(ctx),
- ResourceID: &instanceID,
- })
+ instance, err := h.getMetadataInstance(ctx, instanceName)
if err != nil {
slog.Error("Failed to get instance", log.BBError(err))
return storepb.Engine_ENGINE_UNSPECIFIED
}
if instance == nil {
- slog.Error("Instance not found", slog.String("instanceID", instanceID))
+ slog.Error("Instance not found", slog.String("instance", instanceName))
return storepb.Engine_ENGINE_UNSPECIFIED
}
return instance.Metadata.GetEngine()
}
+func (h *Handler) getMetadataInstance(ctx context.Context, instanceName string) (*store.InstanceMessage, error) {
+ projectID, instanceID, err := common.GetInstanceResourceName(instanceName)
+ if err != nil {
+ return nil, err
+ }
+ instance, err := h.store.GetInstance(ctx, &store.FindInstanceMessage{
+ Workspace: common.GetWorkspaceIDFromContext(ctx),
+ ProjectID: projectID,
+ WorkspaceOnly: projectID == nil,
+ ResourceID: &instanceID,
+ })
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get instance")
+ }
+ if instance == nil {
+ return nil, errors.Errorf("instance %q not found", instanceName)
+ }
+ if instance.ProjectID == nil {
+ return instance, nil
+ }
+ project, err := h.store.GetProject(ctx, &store.FindProjectMessage{
+ Workspace: common.GetWorkspaceIDFromContext(ctx),
+ ResourceID: instance.ProjectID,
+ })
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get instance project")
+ }
+ if project == nil || project.Deleted {
+ return nil, errors.Errorf("project %q not found", *instance.ProjectID)
+ }
+ return instance, nil
+}
+
func (h *Handler) checkInitialized(req *jsonrpc2.Request) error {
h.mu.Lock()
defer h.mu.Unlock()
@@ -210,17 +243,19 @@ func (h *Handler) checkMetadataPermissions(ctx context.Context, metadata SetMeta
workspaceID := common.GetWorkspaceIDFromContext(ctx)
- // If database is specified, check database schema permission
- if metadata.DatabaseName != "" && metadata.InstanceID != "" {
- // Need to get database to find its project
- instanceID, err := common.GetInstanceID(metadata.InstanceID)
- if err != nil {
- return err
- }
+ if metadata.InstanceID == "" {
+ return nil
+ }
+ instance, err := h.getMetadataInstance(ctx, metadata.InstanceID)
+ if err != nil {
+ return err
+ }
+ // If database is specified, check database schema permission.
+ if metadata.DatabaseName != "" {
database, err := h.store.GetDatabase(ctx, &store.FindDatabaseMessage{
Workspace: workspaceID,
- InstanceID: &instanceID,
+ InstanceID: &instance.ResourceID,
DatabaseName: &metadata.DatabaseName,
})
if err != nil {
@@ -238,9 +273,13 @@ func (h *Handler) checkMetadataPermissions(ctx context.Context, metadata SetMeta
if !ok {
return errors.Errorf("no permission to access database %q", metadata.DatabaseName)
}
- } else if metadata.InstanceID != "" && metadata.DatabaseName == "" {
- // If only instance is specified, check instance get permission
- ok, err := h.iamManager.CheckPermission(ctx, permission.InstancesGet, user, workspaceID)
+ } else {
+ // If only instance is specified, check instance get permission in its scope.
+ var permissionProjectIDs []string
+ if instance.ProjectID != nil {
+ permissionProjectIDs = append(permissionProjectIDs, *instance.ProjectID)
+ }
+ ok, err := h.iamManager.CheckPermission(ctx, permission.InstancesGet, user, workspaceID, permissionProjectIDs...)
if err != nil {
return errors.Wrap(err, "failed to check permission")
}
diff --git a/backend/api/lsp/project_instance_metadata_test.go b/backend/api/lsp/project_instance_metadata_test.go
new file mode 100644
index 0000000000..3574efc7bb
--- /dev/null
+++ b/backend/api/lsp/project_instance_metadata_test.go
@@ -0,0 +1,68 @@
+package lsp
+
+import (
+ "context"
+ "fmt"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/migrator"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+func TestMetadataProjectInstanceScope(t *testing.T) {
+ ctx := context.WithValue(context.Background(), common.WorkspaceIDContextKey, "default")
+ container := testcontainer.GetTestPgContainer(ctx, t)
+ t.Cleanup(func() { container.Close(ctx) })
+ db := container.GetDB()
+ require.NoError(t, migrator.MigrateSchema(ctx, db))
+ _, err := db.ExecContext(ctx, `
+ INSERT INTO workspace (resource_id) VALUES ('default');
+ INSERT INTO project (resource_id, workspace, name) VALUES
+ ('project-a', 'default', 'Project A'),
+ ('project-b', 'default', 'Project B');
+ `)
+ require.NoError(t, err)
+
+ pgURL := fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=postgres", container.GetHost(), container.GetPort())
+ stores, err := store.New(ctx, pgURL, false)
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, stores.Close()) })
+
+ projectID := "project-a"
+ instanceID := "project-instance"
+ _, err = stores.CreateInstance(ctx, &store.InstanceMessage{
+ ResourceID: instanceID,
+ Workspace: "default",
+ ProjectID: &projectID,
+ Metadata: &storepb.Instance{DataSources: []*storepb.DataSource{{
+ Id: "admin",
+ Type: storepb.DataSourceType_ADMIN,
+ }}},
+ })
+ require.NoError(t, err)
+
+ h := &Handler{store: stores}
+ canonicalName := common.FormatProjectInstance(projectID, instanceID)
+ h.setMetadata(SetMetadataCommandArguments{InstanceID: canonicalName})
+ require.Equal(t, canonicalName, h.metadata.InstanceID)
+ require.Equal(t, instanceID, h.getInstanceID())
+
+ instance, err := h.getMetadataInstance(ctx, canonicalName)
+ require.NoError(t, err)
+ require.Equal(t, instanceID, instance.ResourceID)
+
+ _, err = h.getMetadataInstance(ctx, common.FormatInstance(instanceID))
+ require.Error(t, err)
+ _, err = h.getMetadataInstance(ctx, common.FormatProjectInstance("project-b", instanceID))
+ require.Error(t, err)
+
+ _, err = db.ExecContext(ctx, "UPDATE project SET deleted = TRUE WHERE resource_id = $1", projectID)
+ require.NoError(t, err)
+ _, err = h.getMetadataInstance(ctx, canonicalName)
+ require.Error(t, err)
+}
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yaml
index 144e152336..a88b8a6a8e 100644
--- a/backend/api/mcp/gen/openapi.yaml
+++ b/backend/api/mcp/gen/openapi.yaml
@@ -8497,7 +8497,7 @@ components:
title: targets
description: |-
The target databases for this access grant.
- Format: instances/{instance}/databases/{database}
+ Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
query:
type: string
title: query
@@ -8710,7 +8710,8 @@ components:
title: name
description: |-
The name is the instance name to execute the query against.
- Format: instances/{instance}/databases/{databaseName}
+ Format: instances/{instance}/databases/{databaseName} or
+ projects/{project}/instances/{instance}/databases/{databaseName}
statement:
type: string
title: statement
@@ -9775,7 +9776,7 @@ components:
The syntax and semantics of CEL are documented at https://github.com/google/cel-spec
Support variables:
- resource.database: the database full name in "instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator.
+ resource.database: the canonical database full name in "instances/{instance}/databases/{database}" or "projects/{project}/instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator.
resource.schema_name: the schema name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.
resource.table_name: the table name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.
resource.environment_id: the environment to allow the DDL/DML operation in the SQL Editor, only works for the role with bb.sql.ddl or bb.sql.dml permissions. Support "in" operator.
@@ -12180,8 +12181,8 @@ components:
title: name
description: |-
The name is the resource name to execute the export against.
- Format: instances/{instance}/databases/{database}
- Format: instances/{instance}
+ Format: instances/{instance}/databases/{database} or
+ projects/{project}/instances/{instance}/databases/{database}
statement:
type: string
title: statement
@@ -14043,7 +14044,7 @@ components:
- environment: the environment full name in "environments/{id}" format, support "==" operator.
- name: the database name, support ".contains()" operator.
- project: the project full name in "projects/{id}" format, support "==" operator.
- - instance: the instance full name in "instances/{id}" format, support "==" operator.
+ - instance: the instance full name in "instances/{id}" or "projects/{project}/instances/{id}" format, support "==" operator.
- engine: the database engine, check Engine enum for values. Support "==", "in [xx]", "!(in [xx])" operator.
- exclude_unassigned: should be "true" or "false", will not show unassigned databases if it's true, support "==" operator.
- table: filter by the database table, support "==" and ".contains()" operator.
@@ -14054,6 +14055,7 @@ components:
environment == "" (find databases which environment is not set)
project == "projects/{project resource id}"
instance == "instances/{instance resource id}"
+ instance == "projects/{project resource id}/instances/{instance resource id}"
name.contains("database name")
engine == "MYSQL"
engine in ["MYSQL", "POSTGRES"]
@@ -16332,7 +16334,7 @@ components:
title: target
description: |-
The resource name of the instance on which the database is created.
- Format: instances/{instance}
+ Format: instances/{instance} or projects/{project}/instances/{instance}
database:
type: string
title: database
@@ -16483,7 +16485,7 @@ components:
title: target
description: |-
Target identification for consolidated results.
- Format: instances/{instance}/databases/{database}
+ Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
type:
title: type
$ref: '#/components/schemas/bytebase.v1.PlanCheckRun.Result.Type'
@@ -17150,7 +17152,7 @@ components:
title: database
description: |-
The database name to execute the query.
- Format: instances/{instance}/databases/{databaseName}
+ Format: instances/{instance}/databases/{databaseName} or projects/{project}/instances/{instance}/databases/{databaseName}
creator:
type: string
title: creator
@@ -17212,8 +17214,9 @@ components:
type: string
title: name
description: |-
- The name is the instance name to execute the query against.
- Format: instances/{instance}/databases/{databaseName}
+ The name is the database resource name to execute the query against.
+ Format: instances/{instance}/databases/{databaseName} or
+ projects/{project}/instances/{instance}/databases/{databaseName}
statement:
type: string
title: statement
@@ -18554,7 +18557,7 @@ components:
title: instance
description: |-
The provisioned sample instance.
- Format: instances/{instance}
+ Format: instances/{instance} or projects/{project}/instances/{instance}
expireTime:
title: expire_time
description: The time when the provisioned sample instance expires.
@@ -18582,7 +18585,7 @@ components:
The connected database, which must belong to the saved query's own
project. Empty when none is connected, or when the database no longer
exists.
- Format: instances/{instance}/databases/{database}
+ Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
title:
type: string
title: title
@@ -20287,8 +20290,8 @@ components:
type: string
title: target
description: |-
- Format: instances/{instance} if the task is DatabaseCreate.
- Format: instances/{instance}/databases/{database}
+ Format: instances/{instance} or projects/{project}/instances/{instance} if the task is DatabaseCreate.
+ Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
updateTime:
oneOf:
- $ref: '#/components/schemas/google.protobuf.Timestamp'
@@ -20769,7 +20772,7 @@ components:
title: database
description: |-
The database information.
- Format: instances/{instance}/databases/{database}
+ Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
schema:
type: string
title: schema
diff --git a/backend/api/mcp/skills/database-change.md b/backend/api/mcp/skills/database-change.md
index 91ca21ca31..1795a0b62a 100644
--- a/backend/api/mcp/skills/database-change.md
+++ b/backend/api/mcp/skills/database-change.md
@@ -52,7 +52,7 @@ call_api(operationId="PlanService/CreatePlan", body={
"specs": [{
"id": "spec-1",
"changeDatabaseConfig": {
- "targets": ["instances/{instance-id}/databases/{database-name}"],
+ "targets": ["projects/{project-id}/instances/{instance-id}/databases/{database-name}"],
"sheet": "projects/{project-id}/sheets/{sheet-id}"
}
}]
@@ -90,6 +90,9 @@ call_api(operationId="PlanService/CreatePlan", body={
- `specs` is a flat array directly on the plan (no "steps" wrapper)
- Each `spec` has a unique `id` (any string, used for identification)
- `targets` is an **array** (even for single database)
+- Preserve the exact canonical database name returned by ListDatabases. A project instance
+ uses `projects/{project-id}/instances/{instance-id}/databases/{database-name}`;
+ do not shorten it to `instances/{instance-id}/databases/{database-name}`.
- Specs are executed based on rollout policy (can be sequential or parallel)
**Using database groups:**
@@ -135,7 +138,7 @@ The backend auto-detects whether a change is imperative (DDL/DML) or SDL (declar
| Error | Cause | Fix |
|-------|-------|-----|
-| database not found | Wrong database reference | Verify `instances/{id}/databases/{name}` format |
+| database not found | Wrong database reference | List databases and preserve its exact canonical `name` |
| sheet not found | Sheet doesn't exist | Create sheet first (Step 1) |
| missing engine | Sheet without engine field | Add `engine` field to sheet |
| plan not found | Plan doesn't exist | Create plan before issue |
diff --git a/backend/api/mcp/skills/query.md b/backend/api/mcp/skills/query.md
index 4691886dfd..51fe9d8d0b 100644
--- a/backend/api/mcp/skills/query.md
+++ b/backend/api/mcp/skills/query.md
@@ -13,7 +13,8 @@ Run SQL queries against databases managed by Bytebase.
## Prerequisites
-- Know the instance and database name
+- Know the database's exact canonical resource name. Preserve the `name`
+ returned by ListDatabases; do not shorten a project instance to `instances/{id}`.
- Have `bb.sql.query` permission
## Workflow
@@ -34,7 +35,8 @@ Run SQL queries against databases managed by Bytebase.
Filter examples:
- `name.contains("employee")` - database name contains "employee"
- `project == "projects/{project-id}"` - databases in a project
- - `instance == "instances/{instance-id}"` - databases in an instance
+ - `instance == "instances/{instance-id}"` - databases in a workspace instance
+ - `instance == "projects/{project-id}/instances/{instance-id}"` - databases in a project instance
- `engine == "MYSQL"` - MySQL databases only
- `environment == "environments/prod" && name.contains("user")` - combine filters
@@ -43,7 +45,7 @@ Run SQL queries against databases managed by Bytebase.
3. **Execute SQL**:
```
call_api(operationId="SQLService/Query", body={
- "name": "instances/{instance-id}/databases/{database-name}",
+ "name": "projects/{project-id}/instances/{instance-id}/databases/{database-name}",
"dataSourceId": "{data-source-id}",
"statement": "SELECT * FROM users LIMIT 10"
})
@@ -63,6 +65,6 @@ Run SQL queries against databases managed by Bytebase.
| Error | Cause | Fix |
|-------|-------|-----|
| data source id is required | Missing dataSourceId field | Get dataSourceId from instanceResource.dataSources in database listing |
-| database not found | Wrong instance/database name | List databases first |
+| database not found | Wrong instance/database name | List databases first and use its exact canonical `name` |
| permission denied | Missing bb.sql.query | Check user permissions |
| syntax error | Invalid SQL | Check SQL syntax for the database engine |
diff --git a/backend/api/mcp/tool_call.go b/backend/api/mcp/tool_call.go
index b3e7580631..6db32b1bf7 100644
--- a/backend/api/mcp/tool_call.go
+++ b/backend/api/mcp/tool_call.go
@@ -39,10 +39,12 @@ const callAPIDescription = `Execute a Bytebase API endpoint. **Use search_api fi
| operationId | Yes | e.g., "SQLService/Query" |
| body | No | JSON request body |
-**Resource names:** projects/my-project, instances/prod/databases/main
+**Resource names:** Preserve the exact canonical name returned by ListDatabases:
+instances/prod/databases/main for a workspace instance, or
+projects/my-project/instances/prod/databases/main for a project instance.
**Example:**
-call_api(operationId="SQLService/Query", body={"name": "instances/i/databases/db", "statement": "SELECT 1"})`
+call_api(operationId="SQLService/Query", body={"name": "projects/my-project/instances/i/databases/db", "statement": "SELECT 1"})`
func (s *Server) registerCallTool() {
mcp.AddTool(s.mcpServer, &mcp.Tool{
diff --git a/backend/api/mcp/tool_change.go b/backend/api/mcp/tool_change.go
index f520cdb9ca..15864e9079 100644
--- a/backend/api/mcp/tool_change.go
+++ b/backend/api/mcp/tool_change.go
@@ -136,8 +136,8 @@ Provide plain SQL — the tool handles database resolution, sheet creation, plan
| database | Yes | Database name or substring |
| sql | Yes | SQL statement(s) in plain text (NOT base64) |
| title | Yes | Title for the issue/plan |
-| instance | No | Narrow database resolution |
-| project | No | Narrow to a specific project |
+| instance | No | Workspace instance ID/name, or the full canonical name for a project instance |
+| project | No | Project name or ID to narrow resolution |
| changeType | No | "MIGRATE" (default) or "SDL" |
| createRollout | No | If true, attempts rollout creation after issue |
| reason | No | Context or ticket reference (max 1000 chars) |
diff --git a/backend/api/mcp/tool_query.go b/backend/api/mcp/tool_query.go
index c9c7fd4e93..9ea9118fff 100644
--- a/backend/api/mcp/tool_query.go
+++ b/backend/api/mcp/tool_query.go
@@ -49,13 +49,14 @@ const queryDatabaseDescription = `Execute a SQL query against a Bytebase databas
|-----------|----------|-------------|
| database | Yes | Database name or substring (e.g., "employee_db" or "employee") |
| statement | Yes | SQL query to execute |
-| instance | No | Instance name to narrow resolution |
-| project | No | Project name to narrow resolution |
+| instance | No | Workspace instance ID/name, or the full canonical name for a project instance |
+| project | No | Project name or ID to narrow resolution |
| limit | No | Max rows (default: 100, max: 1000) |
**Examples:**
query_database(database="employee_db", statement="SELECT * FROM users LIMIT 10")
query_database(database="employee", instance="prod-pg", statement="SELECT count(*) FROM orders")
+query_database(database="employee", instance="projects/hr/instances/prod-pg", statement="SELECT count(*) FROM orders")
**Notes:**
- Masked data: a masked column reads back as "******". That is a placeholder, not a value anything holds, so never write it back and never filter on it. Any statement containing it is refused.
diff --git a/backend/api/mcp/tool_query_test.go b/backend/api/mcp/tool_query_test.go
index f6335374bb..4564e3f445 100644
--- a/backend/api/mcp/tool_query_test.go
+++ b/backend/api/mcp/tool_query_test.go
@@ -211,6 +211,12 @@ func TestBuildDatabaseFilter(t *testing.T) {
project: "hr-system",
expect: `name.contains("employee_db") && instance == "instances/prod-pg" && project == "projects/hr-system"`,
},
+ {
+ name: "with canonical project instance",
+ database: "employee_db",
+ instance: "projects/hr-system/instances/prod-pg",
+ expect: `name.contains("employee_db") && instance == "projects/hr-system/instances/prod-pg"`,
+ },
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
@@ -351,6 +357,39 @@ func TestQueryDatabase_AmbiguousWithInstance(t *testing.T) {
require.Equal(t, "ds-admin-1", resolved.dataSourceID)
}
+func TestQueryDatabase_ProjectInstanceRequiresCanonicalInstanceFilter(t *testing.T) {
+ const (
+ instanceName = "projects/hr-system/instances/prod-pg"
+ databaseName = "projects/hr-system/instances/prod-pg/databases/employee_db"
+ )
+ databases := []map[string]any{
+ makeDatabase(databaseName, instanceName, "projects/hr-system", "POSTGRES", "ds-admin-1"),
+ }
+ s := newTestServerWithMock(t, mockListDatabases(databases))
+
+ resolved, err := s.resolveDatabase(testContext(), "employee_db", instanceName, "")
+ require.NoError(t, err)
+ require.Equal(t, databaseName, resolved.resourceName)
+
+ _, err = s.resolveDatabase(testContext(), "employee_db", "prod-pg", "")
+ require.Error(t, err)
+ var te *toolError
+ require.ErrorAs(t, err, &te)
+ require.Equal(t, "DATABASE_NOT_FOUND", te.Code)
+}
+
+func TestQueryDatabase_WorkspaceInstanceWithProjectFilter(t *testing.T) {
+ databaseName := "instances/prod-pg/databases/employee_db"
+ databases := []map[string]any{
+ makeDatabase(databaseName, "instances/prod-pg", "projects/hr-system", "POSTGRES", "ds-admin-1"),
+ }
+ s := newTestServerWithMock(t, mockListDatabases(databases))
+
+ resolved, err := s.resolveDatabase(testContext(), "employee_db", "prod-pg", "hr-system")
+ require.NoError(t, err)
+ require.Equal(t, databaseName, resolved.resourceName)
+}
+
func TestQueryDatabase_ReadOnlyDatasource(t *testing.T) {
databases := []map[string]any{
makeDatabaseWithDualDS("instances/prod-pg/databases/employee_db", "instances/prod-pg", "projects/hr-system", "POSTGRES", "ds-admin-1", "ds-ro-1"),
diff --git a/backend/api/mcp/tool_resolve.go b/backend/api/mcp/tool_resolve.go
index 4370924f2b..f5852d871d 100644
--- a/backend/api/mcp/tool_resolve.go
+++ b/backend/api/mcp/tool_resolve.go
@@ -10,6 +10,8 @@ import (
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/common"
)
const resolveTimeout = 30 * time.Second
@@ -66,14 +68,31 @@ func buildDatabaseFilter(database, instance, project string) string {
// name.contains does substring matching server-side.
filter := fmt.Sprintf("name.contains(%q)", database)
if instance != "" {
- filter += fmt.Sprintf(" && instance == %q", "instances/"+instance)
+ filter += fmt.Sprintf(" && instance == %q", formatInstanceFilter(instance))
}
if project != "" {
- filter += fmt.Sprintf(" && project == %q", "projects/"+project)
+ filter += fmt.Sprintf(" && project == %q", formatProjectFilter(project))
}
return filter
}
+// formatInstanceFilter preserves a canonical instance resource name. A bare ID
+// remains the workspace-instance shorthand for backwards compatibility; it
+// must not be used to address a project instance.
+func formatInstanceFilter(instance string) string {
+ if _, _, err := common.GetInstanceResourceName(instance); err == nil {
+ return instance
+ }
+ return common.FormatInstance(instance)
+}
+
+func formatProjectFilter(project string) string {
+ if _, err := common.GetProjectID(project); err == nil {
+ return project
+ }
+ return common.FormatProject(project)
+}
+
// listDatabases lists databases matching the filter in the user's workspace.
// Uses the workspace ID from the JWT token stored in context.
func (s *Server) listDatabases(ctx context.Context, filter string) ([]databaseEntry, error) {
@@ -292,11 +311,11 @@ func matchSubstring(databases []databaseEntry, name string) []databaseEntry {
return result
}
-// extractDatabaseName extracts the database name from a resource name like "instances/prod-pg/databases/employee_db".
+// extractDatabaseName extracts the database ID from a canonical database resource name.
func extractDatabaseName(resourceName string) string {
- parts := strings.Split(resourceName, "/")
- if len(parts) >= 4 {
- return parts[3]
+ _, _, databaseName, err := common.GetDatabaseResourceName(resourceName)
+ if err == nil {
+ return databaseName
}
return resourceName
}
diff --git a/backend/api/mcp/tool_resolve_test.go b/backend/api/mcp/tool_resolve_test.go
index 7d7f475f89..158ada8833 100644
--- a/backend/api/mcp/tool_resolve_test.go
+++ b/backend/api/mcp/tool_resolve_test.go
@@ -60,6 +60,36 @@ func TestResolve_ProjectInAmbiguous(t *testing.T) {
require.Equal(t, "projects/staging", resolved.projects["instances/staging-pg/databases/app"])
}
+func TestResolve_ProjectInstanceDatabaseAndFilter(t *testing.T) {
+ const (
+ projectInstance = "projects/project-a/instances/instance-a"
+ databaseName = "projects/project-a/instances/instance-a/databases/app"
+ )
+
+ databases := []databaseEntry{{
+ Name: databaseName,
+ Project: "projects/project-a",
+ InstanceResource: instanceResource{
+ Name: projectInstance,
+ Engine: "POSTGRES",
+ DataSources: []dataSource{{ID: "ds-admin-1", Type: "ADMIN"}},
+ },
+ }}
+
+ resolved, err := matchDatabases(databases, "app", "", "")
+ require.NoError(t, err)
+ require.Equal(t, databaseName, resolved.resourceName)
+
+ require.Equal(t,
+ `name.contains("app") && instance == "projects/project-a/instances/instance-a"`,
+ buildDatabaseFilter("app", projectInstance, ""),
+ )
+ require.Equal(t,
+ `name.contains("app") && instance == "instances/instance-a" && project == "projects/project-a"`,
+ buildDatabaseFilter("app", "instance-a", "project-a"),
+ )
+}
+
// TestResolve_PolicyDenialGetsNoRoleAdvice covers the resolve door. It answers
// 403 only when the stored ceiling is unreadable or unserved, which is exactly
// the case where telling the agent to ask for bb.databases.list would send the
diff --git a/backend/api/mcp/tool_schema.go b/backend/api/mcp/tool_schema.go
index c2a5208804..7c7528e189 100644
--- a/backend/api/mcp/tool_schema.go
+++ b/backend/api/mcp/tool_schema.go
@@ -205,8 +205,8 @@ const getSchemaDescription = `Inspect a Bytebase database's schema.
| Parameter | Required | Description |
|-----------|----------|-------------|
| database | Yes | Database name or substring (e.g., "employee_db" or "employee") |
-| instance | No | Instance name to narrow resolution |
-| project | No | Project name to narrow resolution |
+| instance | No | Workspace instance ID/name, or the full canonical name for a project instance |
+| project | No | Project name or ID to narrow resolution |
| schema | No | Schema name for multi-schema engines (PG/MSSQL/Oracle/Snowflake/Redshift/CockroachDB/Databricks/Trino/Spanner/Hive); ignored with a note on MySQL/TiDB/etc. |
| table | No | Drill into a single table; implies include="details" |
| include | No | Detail level: "summary" (default), "columns", "details" |
diff --git a/backend/api/v1/acl.go b/backend/api/v1/acl.go
index c6dd605fe6..b743af7980 100644
--- a/backend/api/v1/acl.go
+++ b/backend/api/v1/acl.go
@@ -649,6 +649,11 @@ func getResourceFromRequest(ctx context.Context, request any, method string) ([]
}
return resources, nil
}
+ if r, ok := request.(*v1pb.BatchSyncDatabasesRequest); ok {
+ // Batch schema sync has the same project-scoped authorization semantics
+ // as SyncDatabase. Resolve every database name to its owning project.
+ return r.Names, nil
+ }
if r, ok := request.(*v1pb.ListInstanceDatabaseRequest); ok && r.GetInstance() != nil {
// During instance creation, the request carries an inline instance so
diff --git a/backend/api/v1/acl_test.go b/backend/api/v1/acl_test.go
index 37ffe945a4..f3ef352850 100644
--- a/backend/api/v1/acl_test.go
+++ b/backend/api/v1/acl_test.go
@@ -276,6 +276,21 @@ func TestPopulateRawResourcesUsesWorkspaceFallback(t *testing.T) {
require.Empty(t, resources)
}
+func TestPopulateRawResourcesBatchSyncUsesDatabaseProject(t *testing.T) {
+ ctx, stores, instanceID, databaseName, _, _ := setupWorkspaceInstanceDescendantServiceTest(t)
+ resources, err := populateRawResources(
+ ctx,
+ stores,
+ &v1pb.BatchSyncDatabasesRequest{
+ Parent: "-",
+ Names: []string{common.FormatDatabase(instanceID, databaseName)},
+ },
+ v1connect.DatabaseServiceBatchSyncDatabasesProcedure,
+ )
+ require.NoError(t, err)
+ require.Equal(t, []*common.Resource{{Type: common.ResourceTypeProject, ID: "project-a"}}, resources)
+}
+
func TestPopulateRawResourcesAllowsDeletedSampleProjectInstanceProject(t *testing.T) {
ctx, stores, projectID, _, _ := setupProjectInstanceLifecycleAPITest(t)
workspaceID := common.GetWorkspaceIDFromContext(ctx)
@@ -442,6 +457,20 @@ func TestGetResourceFromRequest(t *testing.T) {
method: "/bytebase.v1.DatabaseService/BatchUpdateDatabases",
want: []string{"instances/hello/databases/hello", "instances/world/databases/world"},
},
+ {
+ request: &v1pb.BatchSyncDatabasesRequest{
+ Parent: "-",
+ Names: []string{
+ "instances/hello/databases/hello",
+ "projects/project-a/instances/world/databases/world",
+ },
+ },
+ method: "/bytebase.v1.DatabaseService/BatchSyncDatabases",
+ want: []string{
+ "instances/hello/databases/hello",
+ "projects/project-a/instances/world/databases/world",
+ },
+ },
{
request: &v1pb.BatchUpdateDatabasesRequest{
Requests: []*v1pb.UpdateDatabaseRequest{
diff --git a/backend/api/v1/actuator_service_test.go b/backend/api/v1/actuator_service_test.go
index a023da360b..245745d2c1 100644
--- a/backend/api/v1/actuator_service_test.go
+++ b/backend/api/v1/actuator_service_test.go
@@ -144,7 +144,7 @@ func TestAuthenticationInfoAndActuatorBoundary(t *testing.T) {
require.NotEmpty(t, privateResponse.Msg.DefaultProject)
require.True(t, privateResponse.Msg.Sample.Available)
require.Len(t, privateResponse.Msg.Sample.Instances, 1)
- require.Equal(t, common.FormatInstance("sample-instance"), privateResponse.Msg.Sample.Instances[0].Instance)
+ require.Equal(t, common.FormatProjectInstance(projectID, "sample-instance"), privateResponse.Msg.Sample.Instances[0].Instance)
require.True(t, expiresAt.Equal(privateResponse.Msg.Sample.Instances[0].ExpireTime.AsTime()))
cleanupNow := expiresAt.Add(time.Second)
@@ -163,7 +163,7 @@ func TestAuthenticationInfoAndActuatorBoundary(t *testing.T) {
require.NoError(t, err)
require.True(t, deletedResponse.Msg.Sample.Available)
require.Len(t, deletedResponse.Msg.Sample.Instances, 1)
- require.Equal(t, common.FormatInstance("sample-instance"), deletedResponse.Msg.Sample.Instances[0].Instance)
+ require.Equal(t, common.FormatProjectInstance(projectID, "sample-instance"), deletedResponse.Msg.Sample.Instances[0].Instance)
require.Nil(t, deletedResponse.Msg.Sample.Instances[0].ExpireTime)
}
diff --git a/backend/api/v1/database_service.go b/backend/api/v1/database_service.go
index 37a34f8315..c6d48e5e0f 100644
--- a/backend/api/v1/database_service.go
+++ b/backend/api/v1/database_service.go
@@ -491,6 +491,7 @@ func (s *DatabaseService) BatchSyncDatabases(ctx context.Context, req *connect.R
if err != nil {
return nil, connect.NewError(connect.CodeInvalidArgument, err)
}
+ databases := make([]*store.DatabaseMessage, 0, len(req.Msg.Names))
for _, name := range req.Msg.Names {
projectID, instanceID, databaseID, err := common.GetDatabaseResourceName(name)
if err != nil {
@@ -506,7 +507,10 @@ func (s *DatabaseService) BatchSyncDatabases(ctx context.Context, req *connect.R
if err := validateDatabaseParent(projectID, instanceID, databaseID, databaseMessage, parent); err != nil {
return nil, connect.NewError(connect.CodeInvalidArgument, err)
}
- s.schemaSyncer.SyncDatabaseAsync(databaseMessage)
+ databases = append(databases, databaseMessage)
+ }
+ for _, database := range databases {
+ s.schemaSyncer.SyncDatabaseAsync(database)
}
return connect.NewResponse(&v1pb.BatchSyncDatabasesResponse{}), nil
}
diff --git a/backend/api/v1/project_instance_lifecycle_api_test.go b/backend/api/v1/project_instance_lifecycle_api_test.go
index 506b211778..b6942c1175 100644
--- a/backend/api/v1/project_instance_lifecycle_api_test.go
+++ b/backend/api/v1/project_instance_lifecycle_api_test.go
@@ -107,6 +107,22 @@ func TestUndeleteProjectInstanceChecksActivationLimit(t *testing.T) {
require.True(t, instance.Metadata.GetActivation())
}
+func TestBatchSyncDatabasesValidatesAllTargetsBeforeScheduling(t *testing.T) {
+ ctx, stores, projectID, instanceID, databaseName := setupProjectInstanceLifecycleAPITest(t)
+ licenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, stores, false, "")
+ require.NoError(t, err)
+ service := NewDatabaseService(stores, nil, nil, nil, licenseService)
+
+ _, err = service.BatchSyncDatabases(ctx, connect.NewRequest(&v1pb.BatchSyncDatabasesRequest{
+ Parent: common.FormatProjectInstance(projectID, instanceID),
+ Names: []string{
+ common.FormatProjectDatabase(projectID, instanceID, databaseName),
+ "invalid",
+ },
+ }))
+ require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err))
+}
+
type instanceLicenseServiceStub struct {
instanceLimit int
activatedInstanceLimit int
diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.go
index bbd3676bcf..3705c102c4 100644
--- a/backend/api/v1/sql_service.go
+++ b/backend/api/v1/sql_service.go
@@ -1407,9 +1407,8 @@ func (s *SQLService) accessCheckWithGrantedTargets(
}
checkDatabaseAccess := func(perm permission.Permission) error {
- databaseFullName := common.FormatDatabase(instance.ResourceID, database.DatabaseName)
- grantTargetName := formatDatabaseResourceName(instance, database)
- if _, granted := grantedTargets[grantTargetName]; granted {
+ databaseFullName := formatDatabaseResourceName(instance, database)
+ if _, granted := grantedTargets[databaseFullName]; granted {
return nil
}
attributes := map[string]any{
@@ -1549,7 +1548,10 @@ func (s *SQLService) accessCheckWithGrantedTargets(
var deniedResources []string
for column := range span.SourceColumns {
- columnDatabaseFullName := common.FormatDatabase(instance.ResourceID, column.Database)
+ columnDatabaseFullName := formatDatabaseResourceName(instance, &store.DatabaseMessage{
+ InstanceID: instance.ResourceID,
+ DatabaseName: column.Database,
+ })
grantTargetName := formatDatabaseResourceName(instance, &store.DatabaseMessage{
ProjectID: database.ProjectID,
InstanceID: instance.ResourceID,
@@ -1653,7 +1655,10 @@ func (s *SQLService) authorizeWriteTargets(
var deniedResources []string
for _, t := range targets {
- databaseFullName := common.FormatDatabase(instance.ResourceID, t.database)
+ databaseFullName := formatDatabaseResourceName(instance, &store.DatabaseMessage{
+ InstanceID: instance.ResourceID,
+ DatabaseName: t.database,
+ })
grantTargetName := formatDatabaseResourceName(instance, &store.DatabaseMessage{
ProjectID: database.ProjectID,
InstanceID: instance.ResourceID,
diff --git a/backend/api/v1/sql_service_test.go b/backend/api/v1/sql_service_test.go
index b3890eaeee..f4b0af3135 100644
--- a/backend/api/v1/sql_service_test.go
+++ b/backend/api/v1/sql_service_test.go
@@ -13,6 +13,44 @@ import (
"github.com/bytebase/bytebase/backend/store"
)
+func TestSQLIAMDatabaseResourceUsesCanonicalInstanceScope(t *testing.T) {
+ projectID := "project-a"
+ projectInstance := &store.InstanceMessage{ResourceID: "instance-a", ProjectID: &projectID}
+ workspaceInstance := &store.InstanceMessage{ResourceID: "instance-b"}
+ database := &store.DatabaseMessage{DatabaseName: "app"}
+ projectDatabaseName := formatDatabaseResourceName(projectInstance, &store.DatabaseMessage{
+ InstanceID: projectInstance.ResourceID,
+ DatabaseName: database.DatabaseName,
+ })
+
+ require.Equal(t,
+ "projects/project-a/instances/instance-a/databases/app",
+ projectDatabaseName,
+ )
+ require.Equal(t,
+ "instances/instance-b/databases/app",
+ formatDatabaseResourceName(workspaceInstance, &store.DatabaseMessage{
+ InstanceID: workspaceInstance.ResourceID,
+ DatabaseName: database.DatabaseName,
+ }),
+ )
+
+ attributes := map[string]any{common.CELAttributeResourceDatabase: projectDatabaseName}
+ allowed, err := evaluateQueryExportPolicyCondition(
+ `resource.database == "projects/project-a/instances/instance-a/databases/app"`, attributes)
+ require.NoError(t, err)
+ require.True(t, allowed)
+
+ allowed, err = evaluateQueryExportPolicyCondition(
+ `resource.database == "instances/instance-a/databases/app"`, attributes)
+ require.NoError(t, err)
+ require.False(t, allowed)
+ require.Equal(t,
+ "projects/project-a/instances/instance-a/databases/app/schemas/public/tables/users",
+ formatWriteTargetResource(projectDatabaseName, "public", "users"),
+ )
+}
+
// TestExportRejectsRetiredRolloutNames pins the retired export-data routes:
// rollout/stage names must fail name parsing with InvalidArgument, not fall
// through as 500s.
diff --git a/backend/component/sample/saas/manager.go b/backend/component/sample/saas/manager.go
index b1dffa8f07..4c6d7412b3 100644
--- a/backend/component/sample/saas/manager.go
+++ b/backend/component/sample/saas/manager.go
@@ -397,7 +397,7 @@ func (m *Manager) Info(ctx context.Context, workspaceID string) (*sample.Info, e
if err != nil {
return nil, err
}
- instance := sample.InstanceInfo{Instance: common.FormatInstance(payload.InstanceId)}
+ instance := sample.InstanceInfo{Instance: common.FormatProjectInstance(payload.ProjectId, payload.InstanceId)}
if setup.DeletedAt == nil {
instance.ExpireTime = setup.ExpiresAt
}
diff --git a/backend/generated-go/v1/access_grant_service.pb.go b/backend/generated-go/v1/access_grant_service.pb.go
index 8ec1417da0..8c4b79d2bf 100644
--- a/backend/generated-go/v1/access_grant_service.pb.go
+++ b/backend/generated-go/v1/access_grant_service.pb.go
@@ -109,7 +109,7 @@ type AccessGrant struct {
// Format: projects/{project}/issues/{issue}
Issue string `protobuf:"bytes,5,opt,name=issue,proto3" json:"issue,omitempty"`
// The target databases for this access grant.
- // Format: instances/{instance}/databases/{database}
+ // Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
Targets []string `protobuf:"bytes,6,rep,name=targets,proto3" json:"targets,omitempty"`
// The query permission granted.
Query string `protobuf:"bytes,7,opt,name=query,proto3" json:"query,omitempty"`
diff --git a/backend/generated-go/v1/actuator_service.pb.go b/backend/generated-go/v1/actuator_service.pb.go
index ccd242b9c4..c3534f4480 100644
--- a/backend/generated-go/v1/actuator_service.pb.go
+++ b/backend/generated-go/v1/actuator_service.pb.go
@@ -332,7 +332,7 @@ func (x *ActuatorInfo) GetSample() *SampleInfo {
type SampleInfo_Instance struct {
state protoimpl.MessageState `protogen:"open.v1"`
// The provisioned sample instance.
- // Format: instances/{instance}
+ // Format: instances/{instance} or projects/{project}/instances/{instance}
Instance string `protobuf:"bytes,1,opt,name=instance,proto3" json:"instance,omitempty"`
// The time when the provisioned sample instance expires.
ExpireTime *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=expire_time,json=expireTime,proto3" json:"expire_time,omitempty"`
diff --git a/backend/generated-go/v1/database_service.pb.go b/backend/generated-go/v1/database_service.pb.go
index e1b58d03f7..c025b8eb52 100644
--- a/backend/generated-go/v1/database_service.pb.go
+++ b/backend/generated-go/v1/database_service.pb.go
@@ -690,7 +690,7 @@ type ListDatabasesRequest struct {
// - environment: the environment full name in "environments/{id}" format, support "==" operator.
// - name: the database name, support ".contains()" operator.
// - project: the project full name in "projects/{id}" format, support "==" operator.
- // - instance: the instance full name in "instances/{id}" format, support "==" operator.
+ // - instance: the instance full name in "instances/{id}" or "projects/{project}/instances/{id}" format, support "==" operator.
// - engine: the database engine, check Engine enum for values. Support "==", "in [xx]", "!(in [xx])" operator.
// - exclude_unassigned: should be "true" or "false", will not show unassigned databases if it's true, support "==" operator.
// - table: filter by the database table, support "==" and ".contains()" operator.
@@ -701,6 +701,7 @@ type ListDatabasesRequest struct {
// environment == "" (find databases which environment is not set)
// project == "projects/{project resource id}"
// instance == "instances/{instance resource id}"
+ // instance == "projects/{project resource id}/instances/{instance resource id}"
// name.contains("database name")
// engine == "MYSQL"
// engine in ["MYSQL", "POSTGRES"]
diff --git a/backend/generated-go/v1/iam_policy.pb.go b/backend/generated-go/v1/iam_policy.pb.go
index da99ea5b75..7a99f3b9da 100644
--- a/backend/generated-go/v1/iam_policy.pb.go
+++ b/backend/generated-go/v1/iam_policy.pb.go
@@ -266,7 +266,7 @@ type Binding struct {
// The syntax and semantics of CEL are documented at https://github.com/google/cel-spec
//
// Support variables:
- // resource.database: the database full name in "instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator.
+ // resource.database: the canonical database full name in "instances/{instance}/databases/{database}" or "projects/{project}/instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator.
// resource.schema_name: the schema name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.
// resource.table_name: the table name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.
// resource.environment_id: the environment to allow the DDL/DML operation in the SQL Editor, only works for the role with bb.sql.ddl or bb.sql.dml permissions. Support "in" operator.
diff --git a/backend/generated-go/v1/plan_service.pb.go b/backend/generated-go/v1/plan_service.pb.go
index 144b140b10..474c9a799d 100644
--- a/backend/generated-go/v1/plan_service.pb.go
+++ b/backend/generated-go/v1/plan_service.pb.go
@@ -1017,7 +1017,7 @@ func (*Plan_Spec_ChangeDatabaseConfig) isPlan_Spec_Config() {}
type Plan_CreateDatabaseConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
// The resource name of the instance on which the database is created.
- // Format: instances/{instance}
+ // Format: instances/{instance} or projects/{project}/instances/{instance}
Target string `protobuf:"bytes,1,opt,name=target,proto3" json:"target,omitempty"`
// The name of the database to create.
Database string `protobuf:"bytes,2,opt,name=database,proto3" json:"database,omitempty"`
@@ -1317,7 +1317,7 @@ type PlanCheckRun_Result struct {
Content string `protobuf:"bytes,3,opt,name=content,proto3" json:"content,omitempty"`
Code int32 `protobuf:"varint,4,opt,name=code,proto3" json:"code,omitempty"`
// Target identification for consolidated results.
- // Format: instances/{instance}/databases/{database}
+ // Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
Target string `protobuf:"bytes,7,opt,name=target,proto3" json:"target,omitempty"`
Type PlanCheckRun_Result_Type `protobuf:"varint,8,opt,name=type,proto3,enum=bytebase.v1.PlanCheckRun_Result_Type" json:"type,omitempty"`
// Types that are valid to be assigned to Report:
diff --git a/backend/generated-go/v1/query_history_service.pb.go b/backend/generated-go/v1/query_history_service.pb.go
index b8249eaddb..638a13524f 100644
--- a/backend/generated-go/v1/query_history_service.pb.go
+++ b/backend/generated-go/v1/query_history_service.pb.go
@@ -423,7 +423,7 @@ type QueryHistory struct {
// Format: projects/{project}/queryHistories/{id}
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
// The database name to execute the query.
- // Format: instances/{instance}/databases/{databaseName}
+ // Format: instances/{instance}/databases/{databaseName} or projects/{project}/instances/{instance}/databases/{databaseName}
Database string `protobuf:"bytes,2,opt,name=database,proto3" json:"database,omitempty"`
Creator string `protobuf:"bytes,3,opt,name=creator,proto3" json:"creator,omitempty"`
CreateTime *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"`
diff --git a/backend/generated-go/v1/rollout_service.pb.go b/backend/generated-go/v1/rollout_service.pb.go
index 77d2c2247e..6ce4b03b74 100644
--- a/backend/generated-go/v1/rollout_service.pb.go
+++ b/backend/generated-go/v1/rollout_service.pb.go
@@ -1264,8 +1264,8 @@ type Task struct {
// The reason why the task was skipped.
SkippedReason string `protobuf:"bytes,4,opt,name=skipped_reason,json=skippedReason,proto3" json:"skipped_reason,omitempty"`
Type Task_Type `protobuf:"varint,5,opt,name=type,proto3,enum=bytebase.v1.Task_Type" json:"type,omitempty"`
- // Format: instances/{instance} if the task is DatabaseCreate.
- // Format: instances/{instance}/databases/{database}
+ // Format: instances/{instance} or projects/{project}/instances/{instance} if the task is DatabaseCreate.
+ // Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
Target string `protobuf:"bytes,6,opt,name=target,proto3" json:"target,omitempty"`
// Types that are valid to be assigned to Payload:
//
@@ -2982,7 +2982,7 @@ func (x *TaskRunLogEntry_PriorBackup_PriorBackupDetail_Item) GetEndPosition() *P
type TaskRunLogEntry_PriorBackup_PriorBackupDetail_Item_Table struct {
state protoimpl.MessageState `protogen:"open.v1"`
// The database information.
- // Format: instances/{instance}/databases/{database}
+ // Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
Database string `protobuf:"bytes,1,opt,name=database,proto3" json:"database,omitempty"`
// The schema name.
Schema string `protobuf:"bytes,2,opt,name=schema,proto3" json:"schema,omitempty"`
diff --git a/backend/generated-go/v1/saved_query_service.pb.go b/backend/generated-go/v1/saved_query_service.pb.go
index d2341f79fa..dfb8cacce1 100644
--- a/backend/generated-go/v1/saved_query_service.pb.go
+++ b/backend/generated-go/v1/saved_query_service.pb.go
@@ -1074,7 +1074,7 @@ type SavedQuery struct {
// The connected database, which must belong to the saved query's own
// project. Empty when none is connected, or when the database no longer
// exists.
- // Format: instances/{instance}/databases/{database}
+ // Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
Database string `protobuf:"bytes,3,opt,name=database,proto3" json:"database,omitempty"`
// The title of the saved query.
Title string `protobuf:"bytes,4,opt,name=title,proto3" json:"title,omitempty"`
diff --git a/backend/generated-go/v1/sql_service.pb.go b/backend/generated-go/v1/sql_service.pb.go
index 5aca758696..6201480871 100644
--- a/backend/generated-go/v1/sql_service.pb.go
+++ b/backend/generated-go/v1/sql_service.pb.go
@@ -364,7 +364,8 @@ func (Advice_RuleType) EnumDescriptor() ([]byte, []int) {
type AdminExecuteRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// The name is the instance name to execute the query against.
- // Format: instances/{instance}/databases/{databaseName}
+ // Format: instances/{instance}/databases/{databaseName} or
+ // projects/{project}/instances/{instance}/databases/{databaseName}
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
// The SQL statement to execute.
Statement string `protobuf:"bytes,2,opt,name=statement,proto3" json:"statement,omitempty"`
@@ -492,8 +493,9 @@ func (x *AdminExecuteResponse) GetResults() []*QueryResult {
type QueryRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
- // The name is the instance name to execute the query against.
- // Format: instances/{instance}/databases/{databaseName}
+ // The name is the database resource name to execute the query against.
+ // Format: instances/{instance}/databases/{databaseName} or
+ // projects/{project}/instances/{instance}/databases/{databaseName}
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
// The SQL statement to execute.
Statement string `protobuf:"bytes,2,opt,name=statement,proto3" json:"statement,omitempty"`
@@ -1419,8 +1421,8 @@ func (x *Advice) GetRuleType() Advice_RuleType {
type ExportRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// The name is the resource name to execute the export against.
- // Format: instances/{instance}/databases/{database}
- // Format: instances/{instance}
+ // Format: instances/{instance}/databases/{database} or
+ // projects/{project}/instances/{instance}/databases/{database}
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
// The SQL statement to execute.
Statement string `protobuf:"bytes,2,opt,name=statement,proto3" json:"statement,omitempty"`
@@ -2224,16 +2226,16 @@ const file_v1_sql_service_proto_rawDesc = "" +
"_container\"b\n" +
"\x0eExportResponse\x12\x1e\n" +
"\acontent\x18\x01 \x01(\fB\x04\xd0\xea0\x02R\acontent\x120\n" +
- "\x14applied_access_grant\x18\x02 \x01(\tR\x12appliedAccessGrant2\xbd\x06\n" +
+ "\x14applied_access_grant\x18\x02 \x01(\tR\x12appliedAccessGrant2\xb4\a\n" +
"\n" +
- "SQLService\x12\x93\x01\n" +
- "\x05Query\x12\x19.bytebase.v1.QueryRequest\x1a\x1a.bytebase.v1.QueryResponse\"S\x8a\xea0\x10bb.databases.get\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x01\x82\xd3\xe4\x93\x02-:\x01*\"(/v1/{name=instances/*/databases/*}:query\x12\x91\x01\n" +
+ "SQLService\x12\xce\x01\n" +
+ "\x05Query\x12\x19.bytebase.v1.QueryRequest\x1a\x1a.bytebase.v1.QueryResponse\"\x8d\x01\x8a\xea0\x10bb.databases.get\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x01\x82\xd3\xe4\x93\x02g:\x01*Z8:\x01*\"3/v1/{name=projects/*/instances/*/databases/*}:query\"(/v1/{name=instances/*/databases/*}:query\x12\x91\x01\n" +
"\fAdminExecute\x12 .bytebase.v1.AdminExecuteRequest\x1a!.bytebase.v1.AdminExecuteResponse\"8\x8a\xea0\fbb.sql.admin\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x04\xa8\xea0\v\x82\xd3\xe4\x93\x02\x12\x12\x10/v1:adminExecute(\x010\x01\x12x\n" +
"\x14SearchQueryHistories\x12(.bytebase.v1.SearchQueryHistoriesRequest\x1a).bytebase.v1.SearchQueryHistoriesResponse\"\v\x90\xea0\x02\xa0\xea0\x01\x88\x02\x01\x12\x90\x01\n" +
"\x12ListQueryHistories\x12&.bytebase.v1.ListQueryHistoriesRequest\x1a'.bytebase.v1.ListQueryHistoriesResponse\")\x8a\xea0\x16bb.queryHistories.list\x90\xea0\x01\xa0\xea0\x04\xa8\xea0\n" +
"\x88\x02\x01\x12^\n" +
- "\x0fGetQueryHistory\x12#.bytebase.v1.GetQueryHistoryRequest\x1a\x19.bytebase.v1.QueryHistory\"\v\x90\xea0\x02\xa0\xea0\x01\x88\x02\x01\x12\x97\x01\n" +
- "\x06Export\x12\x1a.bytebase.v1.ExportRequest\x1a\x1b.bytebase.v1.ExportResponse\"T\x8a\xea0\x10bb.databases.get\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x02\x82\xd3\xe4\x93\x02.:\x01*\")/v1/{name=instances/*/databases/*}:exportB\xa5\x01\n" +
+ "\x0fGetQueryHistory\x12#.bytebase.v1.GetQueryHistoryRequest\x1a\x19.bytebase.v1.QueryHistory\"\v\x90\xea0\x02\xa0\xea0\x01\x88\x02\x01\x12\xd3\x01\n" +
+ "\x06Export\x12\x1a.bytebase.v1.ExportRequest\x1a\x1b.bytebase.v1.ExportResponse\"\x8f\x01\x8a\xea0\x10bb.databases.get\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x02\x82\xd3\xe4\x93\x02i:\x01*Z9:\x01*\"4/v1/{name=projects/*/instances/*/databases/*}:export\")/v1/{name=instances/*/databases/*}:exportB\xa5\x01\n" +
"\x0fcom.bytebase.v1B\x0fSqlServiceProtoP\x01Z4github.com/bytebase/bytebase/backend/generated-go/v1\xa2\x02\x03BXX\xaa\x02\vBytebase.V1\xca\x02\vBytebase\\V1\xe2\x02\x17Bytebase\\V1\\GPBMetadata\xea\x02\fBytebase::V1b\x06proto3"
var (
diff --git a/backend/generated-go/v1/sql_service.pb.gw.go b/backend/generated-go/v1/sql_service.pb.gw.go
index 3546e0e20f..2f9d7254de 100644
--- a/backend/generated-go/v1/sql_service.pb.gw.go
+++ b/backend/generated-go/v1/sql_service.pb.gw.go
@@ -80,6 +80,51 @@ func local_request_SQLService_Query_0(ctx context.Context, marshaler runtime.Mar
return msg, metadata, err
}
+func request_SQLService_Query_1(ctx context.Context, marshaler runtime.Marshaler, client SQLServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq QueryRequest
+ metadata runtime.ServerMetadata
+ err error
+ )
+ if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
+ }
+ val, ok := pathParams["name"]
+ if !ok {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "name")
+ }
+ protoReq.Name, err = runtime.String(val)
+ if err != nil {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "name", err)
+ }
+ if req.Body != nil {
+ _, _ = io.Copy(io.Discard, req.Body)
+ }
+ msg, err := client.Query(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
+ return msg, metadata, err
+}
+
+func local_request_SQLService_Query_1(ctx context.Context, marshaler runtime.Marshaler, server SQLServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq QueryRequest
+ metadata runtime.ServerMetadata
+ err error
+ )
+ if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
+ }
+ val, ok := pathParams["name"]
+ if !ok {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "name")
+ }
+ protoReq.Name, err = runtime.String(val)
+ if err != nil {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "name", err)
+ }
+ msg, err := server.Query(ctx, &protoReq)
+ return msg, metadata, err
+}
+
func request_SQLService_AdminExecute_0(ctx context.Context, marshaler runtime.Marshaler, client SQLServiceClient, req *http.Request, pathParams map[string]string) (SQLService_AdminExecuteClient, runtime.ServerMetadata, error) {
var metadata runtime.ServerMetadata
stream, err := client.AdminExecute(ctx)
@@ -168,6 +213,51 @@ func local_request_SQLService_Export_0(ctx context.Context, marshaler runtime.Ma
return msg, metadata, err
}
+func request_SQLService_Export_1(ctx context.Context, marshaler runtime.Marshaler, client SQLServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq ExportRequest
+ metadata runtime.ServerMetadata
+ err error
+ )
+ if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
+ }
+ val, ok := pathParams["name"]
+ if !ok {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "name")
+ }
+ protoReq.Name, err = runtime.String(val)
+ if err != nil {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "name", err)
+ }
+ if req.Body != nil {
+ _, _ = io.Copy(io.Discard, req.Body)
+ }
+ msg, err := client.Export(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
+ return msg, metadata, err
+}
+
+func local_request_SQLService_Export_1(ctx context.Context, marshaler runtime.Marshaler, server SQLServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq ExportRequest
+ metadata runtime.ServerMetadata
+ err error
+ )
+ if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
+ }
+ val, ok := pathParams["name"]
+ if !ok {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "name")
+ }
+ protoReq.Name, err = runtime.String(val)
+ if err != nil {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "name", err)
+ }
+ msg, err := server.Export(ctx, &protoReq)
+ return msg, metadata, err
+}
+
// RegisterSQLServiceHandlerServer registers the http handlers for service SQLService to "mux".
// UnaryRPC :call SQLServiceServer directly.
// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.
@@ -194,6 +284,26 @@ func RegisterSQLServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux,
}
forward_SQLService_Query_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
+ mux.Handle(http.MethodPost, pattern_SQLService_Query_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
+ ctx, cancel := context.WithCancel(req.Context())
+ defer cancel()
+ var stream runtime.ServerTransportStream
+ ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
+ annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/bytebase.v1.SQLService/Query", runtime.WithHTTPPathPattern("/v1/{name=projects/*/instances/*/databases/*}:query"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := local_request_SQLService_Query_1(annotatedContext, inboundMarshaler, server, req, pathParams)
+ md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
+ if err != nil {
+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ forward_SQLService_Query_1(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
mux.Handle(http.MethodGet, pattern_SQLService_AdminExecute_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport")
@@ -221,6 +331,26 @@ func RegisterSQLServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux,
}
forward_SQLService_Export_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
+ mux.Handle(http.MethodPost, pattern_SQLService_Export_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
+ ctx, cancel := context.WithCancel(req.Context())
+ defer cancel()
+ var stream runtime.ServerTransportStream
+ ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
+ annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/bytebase.v1.SQLService/Export", runtime.WithHTTPPathPattern("/v1/{name=projects/*/instances/*/databases/*}:export"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := local_request_SQLService_Export_1(annotatedContext, inboundMarshaler, server, req, pathParams)
+ md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
+ if err != nil {
+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ forward_SQLService_Export_1(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
return nil
}
@@ -278,6 +408,23 @@ func RegisterSQLServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux,
}
forward_SQLService_Query_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
+ mux.Handle(http.MethodPost, pattern_SQLService_Query_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
+ ctx, cancel := context.WithCancel(req.Context())
+ defer cancel()
+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
+ annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/bytebase.v1.SQLService/Query", runtime.WithHTTPPathPattern("/v1/{name=projects/*/instances/*/databases/*}:query"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := request_SQLService_Query_1(annotatedContext, inboundMarshaler, client, req, pathParams)
+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
+ if err != nil {
+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ forward_SQLService_Query_1(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
mux.Handle(http.MethodGet, pattern_SQLService_AdminExecute_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
@@ -312,17 +459,38 @@ func RegisterSQLServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux,
}
forward_SQLService_Export_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
+ mux.Handle(http.MethodPost, pattern_SQLService_Export_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
+ ctx, cancel := context.WithCancel(req.Context())
+ defer cancel()
+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
+ annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/bytebase.v1.SQLService/Export", runtime.WithHTTPPathPattern("/v1/{name=projects/*/instances/*/databases/*}:export"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := request_SQLService_Export_1(annotatedContext, inboundMarshaler, client, req, pathParams)
+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
+ if err != nil {
+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ forward_SQLService_Export_1(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
return nil
}
var (
pattern_SQLService_Query_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 2, 2, 1, 0, 4, 4, 5, 3}, []string{"v1", "instances", "databases", "name"}, "query"))
+ pattern_SQLService_Query_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 2, 2, 1, 0, 2, 3, 1, 0, 4, 6, 5, 4}, []string{"v1", "projects", "instances", "databases", "name"}, "query"))
pattern_SQLService_AdminExecute_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0}, []string{"v1"}, "adminExecute"))
pattern_SQLService_Export_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 2, 2, 1, 0, 4, 4, 5, 3}, []string{"v1", "instances", "databases", "name"}, "export"))
+ pattern_SQLService_Export_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 2, 2, 1, 0, 2, 3, 1, 0, 4, 6, 5, 4}, []string{"v1", "projects", "instances", "databases", "name"}, "export"))
)
var (
forward_SQLService_Query_0 = runtime.ForwardResponseMessage
+ forward_SQLService_Query_1 = runtime.ForwardResponseMessage
forward_SQLService_AdminExecute_0 = runtime.ForwardResponseStream
forward_SQLService_Export_0 = runtime.ForwardResponseMessage
+ forward_SQLService_Export_1 = runtime.ForwardResponseMessage
)
diff --git a/backend/store/database.go b/backend/store/database.go
index d0e23e93f7..1aea384f87 100644
--- a/backend/store/database.go
+++ b/backend/store/database.go
@@ -989,11 +989,18 @@ func GetListDatabaseFilter(workspace, filter string) (*qb.Query, error) {
}
return qb.Q().Space("db.project = ?", projectID), nil
case "instance":
- instanceID, err := common.GetInstanceID(value.(string))
+ instanceName, ok := value.(string)
+ if !ok {
+ return nil, errors.Errorf("invalid instance filter %q", value)
+ }
+ if projectID, instanceID, err := common.GetProjectIDInstanceID(instanceName); err == nil {
+ return qb.Q().Space("db.instance = ? AND instance.project = ?", instanceID, projectID), nil
+ }
+ instanceID, err := common.GetInstanceID(instanceName)
if err != nil {
return nil, errors.Errorf("invalid instance filter %q", value)
}
- return qb.Q().Space("db.instance = ?", instanceID), nil
+ return qb.Q().Space("db.instance = ? AND instance.project IS NULL", instanceID), nil
case "environment":
environment, ok := value.(string)
if !ok {
diff --git a/backend/store/database_filter_test.go b/backend/store/database_filter_test.go
new file mode 100644
index 0000000000..309fbcd835
--- /dev/null
+++ b/backend/store/database_filter_test.go
@@ -0,0 +1,41 @@
+package store
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestGetListDatabaseFilterInstanceScope(t *testing.T) {
+ tests := []struct {
+ name string
+ filter string
+ wantSQL string
+ wantArgs []any
+ }{
+ {
+ name: "project instance",
+ filter: `instance == "projects/project-a/instances/instance-a"`,
+ wantSQL: "(db.instance = $1 AND instance.project = $2)",
+ wantArgs: []any{"instance-a", "project-a"},
+ },
+ {
+ name: "workspace instance",
+ filter: `instance == "instances/instance-a"`,
+ wantSQL: "(db.instance = $1 AND instance.project IS NULL)",
+ wantArgs: []any{"instance-a"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ query, err := GetListDatabaseFilter("default", tt.filter)
+ require.NoError(t, err)
+
+ sql, args, err := query.ToSQL()
+ require.NoError(t, err)
+ require.Equal(t, tt.wantSQL, sql)
+ require.Equal(t, tt.wantArgs, args)
+ })
+ }
+}
diff --git a/frontend/src/components/DatabaseResourceSelector.test.tsx b/frontend/src/components/DatabaseResourceSelector.test.tsx
index aa6acdb88d..df58314986 100644
--- a/frontend/src/components/DatabaseResourceSelector.test.tsx
+++ b/frontend/src/components/DatabaseResourceSelector.test.tsx
@@ -53,33 +53,57 @@ vi.mock("@/components/AdvancedSearch", () => ({
AdvancedSearch: ({
params,
onParamsChange,
+ scopeOptions,
}: {
params: { query: string; scopes: { id: string; value: string }[] };
onParamsChange: (params: {
query: string;
scopes: { id: string; value: string }[];
}) => void;
+ scopeOptions: {
+ id: string;
+ onSearch?: (keyword: string) => Promise<unknown>;
+ }[];
}) => (
- <button
- type="button"
- onClick={() =>
- onParamsChange({
- query: "salary",
- scopes: [{ id: "table", value: "employee" }],
- })
- }
- >
- <span>advanced-search:{params.query}</span>
- </button>
+ <>
+ <button
+ type="button"
+ onClick={() =>
+ onParamsChange({
+ query: "salary",
+ scopes: [{ id: "table", value: "employee" }],
+ })
+ }
+ >
+ <span>advanced-search:{params.query}</span>
+ </button>
+ <button
+ type="button"
+ data-testid="search-instances"
+ onClick={() => {
+ void scopeOptions.find((option) => option.id === "instance")?.onSearch?.("");
+ }}
+ >
+ search instances
+ </button>
+ </>
),
}));
+vi.mock("@/types/v1/project", () => ({
+ isDefaultProject: (name: string) => name === "projects/default",
+}));
+
vi.mock("@/stores/app", () => {
const appState = () => ({
getOrFetchDatabaseMetadata: mocks.getOrFetchDatabaseMetadata,
fetchInstanceList: mocks.fetchInstanceList,
fetchDatabases: mocks.fetchDatabases,
environmentList: mocks.environmentStore.environmentList,
+ projectsByName: {
+ "projects/project": { name: "projects/project" },
+ "projects/default": { name: "projects/default" },
+ },
});
return {
useAppStore: Object.assign(
@@ -119,6 +143,8 @@ vi.mock("@/utils", () => ({
extractDatabaseResourceName: mocks.extractDatabaseResourceName,
extractInstanceResourceName: mocks.extractInstanceResourceName,
getDefaultPagination: () => 100,
+ hasWorkspacePermissionV2: () => true,
+ hasProjectPermissionV2: () => true,
supportedEngineV1List: () => [],
}));
@@ -157,17 +183,19 @@ function Harness({
initialValue = [],
onValueChange,
readonly,
+ projectName = "projects/project",
}: {
includeColumns?: boolean;
initialValue?: DatabaseResource[];
onValueChange?: (value: DatabaseResource[]) => void;
readonly?: boolean;
+ projectName?: string;
}) {
const [value, setValue] = useState<DatabaseResource[]>(initialValue);
return (
<DatabaseResourceSelector
- projectName="projects/project"
+ projectName={projectName}
value={value}
includeColumns={includeColumns}
readonly={readonly}
@@ -281,6 +309,38 @@ beforeEach(async () => {
});
describe("DatabaseResourceSelector", () => {
+ test("only searches workspace instances for the default project", async () => {
+ mocks.fetchInstanceList.mockImplementation(async (params) => {
+ if (params?.parent) {
+ throw new Error("the default project cannot own instances");
+ }
+ return {
+ instances: [{ name: "instances/prod", title: "Prod" }],
+ nextPageToken: "",
+ };
+ });
+ const { container, unmount } = renderIntoContainer(
+ <Harness projectName="projects/default" />
+ );
+ await flushPromises();
+
+ const button = container.querySelector(
+ '[data-testid="search-instances"]'
+ ) as HTMLButtonElement;
+ act(() => {
+ button.click();
+ });
+ await flushPromises();
+
+ expect(mocks.fetchInstanceList).toHaveBeenCalledTimes(1);
+ expect(mocks.fetchInstanceList).toHaveBeenCalledWith({
+ pageSize: 1000,
+ filter: undefined,
+ silent: true,
+ });
+ unmount();
+ });
+
test("passes AdvancedSearch query and table scope to database fetch", async () => {
const { container, unmount } = renderIntoContainer(<Harness />);
await flushPromises();
diff --git a/frontend/src/components/DatabaseResourceSelector.tsx b/frontend/src/components/DatabaseResourceSelector.tsx
index af1df761fc..1110a63715 100644
--- a/frontend/src/components/DatabaseResourceSelector.tsx
+++ b/frontend/src/components/DatabaseResourceSelector.tsx
@@ -17,6 +17,7 @@ import {
} from "@/components/AdvancedSearch";
import { DatabaseTargetDisplay } from "@/components/DatabaseTargetDisplay";
import { Checkbox } from "@/components/ui/checkbox";
+import { normalizeInstanceName } from "@/lib/resourceName";
import { useAppStore } from "@/stores/app";
import type { DatabaseResource } from "@/types";
import { Engine } from "@/types/proto-es/v1/common_pb";
@@ -26,9 +27,12 @@ import type {
DatabaseMetadata,
TableMetadata,
} from "@/types/proto-es/v1/database_service_pb";
+import { isDefaultProject } from "@/types/v1/project";
import {
extractDatabaseResourceName,
extractInstanceResourceName,
+ hasProjectPermissionV2,
+ hasWorkspacePermissionV2,
supportedEngineV1List,
} from "@/utils";
@@ -61,7 +65,6 @@ const tableKey = (dbName: string, schemaName: string, tableName: string) =>
`${dbName}/schemas/${schemaName}/tables/${tableName}`;
const environmentNamePrefix = "environments/";
-const instanceNamePrefix = "instances/";
const UNKNOWN_ENVIRONMENT_ID = "-1";
const UNKNOWN_ENVIRONMENT_NAME = `${environmentNamePrefix}${UNKNOWN_ENVIRONMENT_ID}`;
@@ -126,23 +129,43 @@ export function DatabaseResourceSelector({
new Set()
);
const environments = useAppStore((s) => s.environmentList);
+ const project = useAppStore((s) => s.projectsByName[projectName]);
const searchInstances = useCallback(
async (keyword: string): Promise<ValueOption[]> => {
- const result = await useAppStore.getState().fetchInstanceList({
+ const params = {
pageSize: 1000,
filter: keyword.trim() ? { query: keyword } : undefined,
silent: true,
- });
- return result.instances.map((instance) => {
+ };
+ const results = await Promise.all([
+ project &&
+ !isDefaultProject(projectName) &&
+ hasProjectPermissionV2(project, "bb.instances.list")
+ ? useAppStore
+ .getState()
+ .fetchInstanceList({ ...params, parent: projectName })
+ : Promise.resolve({ instances: [], nextPageToken: "" }),
+ hasWorkspacePermissionV2("bb.instances.list")
+ ? useAppStore.getState().fetchInstanceList(params)
+ : Promise.resolve({ instances: [], nextPageToken: "" }),
+ ]);
+ const instances = [
+ ...new Map(
+ results
+ .flatMap((result) => result.instances)
+ .map((instance) => [instance.name, instance])
+ ).values(),
+ ];
+ return instances.map((instance) => {
const id = extractInstanceResourceName(instance.name);
return {
- value: id,
+ value: instance.name,
keywords: [id, instance.title],
};
});
},
- []
+ [project, projectName]
);
const scopeOptions: ScopeOption[] = useMemo(
@@ -224,7 +247,7 @@ export function DatabaseResourceSelector({
environment: environmentId
? `${environmentNamePrefix}${environmentId}`
: undefined,
- instance: instanceId ? `${instanceNamePrefix}${instanceId}` : undefined,
+ instance: instanceId ? normalizeInstanceName(instanceId) : undefined,
labels: labels.length > 0 ? labels : undefined,
engines: engines.length > 0 ? engines : undefined,
table: table || undefined,
diff --git a/frontend/src/components/SampleExpirationAlert.tsx b/frontend/src/components/SampleExpirationAlert.tsx
index 35570d1374..7c93925023 100644
--- a/frontend/src/components/SampleExpirationAlert.tsx
+++ b/frontend/src/components/SampleExpirationAlert.tsx
@@ -1,8 +1,9 @@
import { useTranslation } from "react-i18next";
import { Alert } from "@/components/ui/alert";
+import { normalizeInstanceName } from "@/lib/resourceName";
import { useAppStore } from "@/stores/app";
import { getTimeForPbTimestampProtoEs } from "@/types";
-import { extractInstanceResourceName, formatAbsoluteDateTime } from "@/utils";
+import { formatAbsoluteDateTime } from "@/utils";
const DAY_MS = 24 * 60 * 60 * 1000;
@@ -15,7 +16,7 @@ export function SampleExpirationAlert({
}: SampleExpirationAlertProps) {
const { t } = useTranslation();
const sample = useAppStore((state) => state.serverInfo?.sample);
- const canonicalInstanceName = `instances/${extractInstanceResourceName(instanceName)}`;
+ const canonicalInstanceName = normalizeInstanceName(instanceName);
const expireTime = sample?.instances.find(
({ instance }) => instance === canonicalInstanceName
)?.expireTime;
diff --git a/frontend/src/components/instance/InstanceDetailView.test.tsx b/frontend/src/components/instance/InstanceDetailView.test.tsx
index acd549cb6f..440d5d51f8 100644
--- a/frontend/src/components/instance/InstanceDetailView.test.tsx
+++ b/frontend/src/components/instance/InstanceDetailView.test.tsx
@@ -301,7 +301,7 @@ describe("InstanceDetailView", () => {
sample: {
instances: [
{
- instance: "instances/prod",
+ instance: "projects/app/instances/prod",
expireTime: {
seconds: BigInt(
Math.floor(Date.now() / 1000) + 7 * 24 * 60 * 60
diff --git a/frontend/src/components/monaco/MonacoEditor.test.tsx b/frontend/src/components/monaco/MonacoEditor.test.tsx
index 9ca57e6887..b595aa177b 100644
--- a/frontend/src/components/monaco/MonacoEditor.test.tsx
+++ b/frontend/src/components/monaco/MonacoEditor.test.tsx
@@ -363,7 +363,7 @@ describe("MonacoEditor", () => {
unmount();
});
- test("normalizes project instance names in LSP metadata", async () => {
+ test("preserves project instance names in LSP metadata", async () => {
const { executeCommand } = await import("./lsp-client");
const { unmount } = await renderIntoContainer(
@@ -384,7 +384,7 @@ describe("MonacoEditor", () => {
[
expect.objectContaining({
databaseName: "db",
- instanceId: "instances/instance",
+ instanceId: "projects/project/instances/instance",
}),
]
);
diff --git a/frontend/src/components/monaco/MonacoEditor.tsx b/frontend/src/components/monaco/MonacoEditor.tsx
index b5abb94cf2..d7e6f53395 100644
--- a/frontend/src/components/monaco/MonacoEditor.tsx
+++ b/frontend/src/components/monaco/MonacoEditor.tsx
@@ -12,7 +12,6 @@ import {
import { useTranslation } from "react-i18next";
import { v4 as uuidv4 } from "uuid";
import { Tooltip } from "@/components/ui/tooltip";
-import { instanceNamePrefix } from "@/lib/resourceName";
import { cn } from "@/lib/utils";
import type { Language, SQLDialect } from "@/types";
import { UNKNOWN_ID } from "@/types";
@@ -625,7 +624,7 @@ export function MonacoEditor({
};
const instance = extractInstanceResourceName(ctx.instance);
if (instance && instance !== String(UNKNOWN_ID)) {
- params.instanceId = `${instanceNamePrefix}${instance}`;
+ params.instanceId = ctx.instance;
}
const { databaseName } = extractDatabaseResourceName(ctx.database ?? "");
if (databaseName && databaseName !== String(UNKNOWN_ID)) {
diff --git a/frontend/src/components/useCommonSearchScopeOptions.test.tsx b/frontend/src/components/useCommonSearchScopeOptions.test.tsx
new file mode 100644
index 0000000000..fcc89c2c2c
--- /dev/null
+++ b/frontend/src/components/useCommonSearchScopeOptions.test.tsx
@@ -0,0 +1,102 @@
+import { create } from "@bufbuild/protobuf";
+import { renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { ProjectSchema } from "@/types/proto-es/v1/project_service_pb";
+import { useCommonSearchScopeOptions } from "./useCommonSearchScopeOptions";
+
+const mocks = vi.hoisted(() => ({
+ fetchInstanceList: vi.fn(),
+ hasWorkspacePermission: true,
+ hasProjectPermission: true,
+}));
+
+vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/components/EngineIcon", () => ({
+ EngineIcon: () => null,
+}));
+
+vi.mock("@/stores/app", () => ({
+ useAppStore: {
+ getState: () => ({ fetchInstanceList: mocks.fetchInstanceList }),
+ },
+}));
+
+vi.mock("@/types", () => {
+ return {
+ isDefaultProject: (name: string) => name === "projects/default",
+ isValidProjectName: (name: string) =>
+ name.startsWith("projects/") && name !== "projects/-",
+ };
+});
+
+vi.mock("@/utils", () => {
+ return {
+ extractEnvironmentResourceName: (name: string) =>
+ name.replace(/^environments\//, ""),
+ extractInstanceResourceName: (name: string) =>
+ name.match(/(?:^|\/)instances\/([^/]+)/)?.[1] ?? "",
+ getDefaultPagination: () => 1000,
+ hasWorkspacePermissionV2: () => mocks.hasWorkspacePermission,
+ hasProjectPermissionV2: () => mocks.hasProjectPermission,
+ supportedEngineV1List: () => [],
+ };
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.hasWorkspacePermission = true;
+ mocks.hasProjectPermission = true;
+ mocks.fetchInstanceList.mockImplementation(async ({ parent }) => ({
+ instances: parent
+ ? [
+ {
+ name: "projects/app/instances/project-prod",
+ title: "Project production",
+ },
+ ]
+ : [{ name: "instances/shared", title: "Shared" }],
+ nextPageToken: "",
+ }));
+});
+
+describe("useCommonSearchScopeOptions", () => {
+ test("discovers workspace and project instances with canonical values", async () => {
+ const project = create(ProjectSchema, { name: "projects/app" });
+ const { result } = renderHook(() =>
+ useCommonSearchScopeOptions(["instance"], project)
+ );
+
+ const options = await result.current[0].onSearch?.("prod");
+
+ expect(mocks.fetchInstanceList).toHaveBeenCalledTimes(2);
+ expect(mocks.fetchInstanceList).toHaveBeenCalledWith(
+ expect.objectContaining({ parent: "projects/app" })
+ );
+ expect(options?.map((option) => option.value)).toEqual([
+ "instances/shared",
+ "projects/app/instances/project-prod",
+ ]);
+ });
+
+ test("supports users who can list only project instances", async () => {
+ mocks.hasWorkspacePermission = false;
+ const project = create(ProjectSchema, { name: "projects/app" });
+ const { result } = renderHook(() =>
+ useCommonSearchScopeOptions(["instance"], project)
+ );
+
+ const options = await result.current[0].onSearch?.("");
+
+ expect(mocks.fetchInstanceList).toHaveBeenCalledOnce();
+ expect(mocks.fetchInstanceList).toHaveBeenCalledWith(
+ expect.objectContaining({ parent: "projects/app" })
+ );
+ expect(options?.map((option) => option.value)).toEqual([
+ "projects/app/instances/project-prod",
+ ]);
+ });
+});
diff --git a/frontend/src/components/useCommonSearchScopeOptions.tsx b/frontend/src/components/useCommonSearchScopeOptions.tsx
index 60f45db954..eb1651fc76 100644
--- a/frontend/src/components/useCommonSearchScopeOptions.tsx
+++ b/frontend/src/components/useCommonSearchScopeOptions.tsx
@@ -3,11 +3,15 @@ import { useTranslation } from "react-i18next";
import type { ScopeOption, ValueOption } from "@/components/AdvancedSearch";
import { EngineIcon } from "@/components/EngineIcon";
import { useAppStore } from "@/stores/app";
+import { isDefaultProject, isValidProjectName } from "@/types";
import { Engine } from "@/types/proto-es/v1/common_pb";
+import type { Project } from "@/types/proto-es/v1/project_service_pb";
import {
extractEnvironmentResourceName,
extractInstanceResourceName,
getDefaultPagination,
+ hasProjectPermissionV2,
+ hasWorkspacePermissionV2,
type SearchScopeId,
supportedEngineV1List,
} from "@/utils";
@@ -21,23 +25,44 @@ import {
* short-circuits unknown ids rather than inventing a scope.
*/
export function useCommonSearchScopeOptions(
- supportOptionIdList: SearchScopeId[]
+ supportOptionIdList: SearchScopeId[],
+ project?: Project
): ScopeOption[] {
const { t } = useTranslation();
const searchInstance = useCallback(
async (keyword: string): Promise<ValueOption[]> => {
- const resp = await useAppStore.getState().fetchInstanceList({
+ const params = {
pageToken: undefined,
pageSize: getDefaultPagination(),
filter: { query: keyword },
silent: true,
- });
- return resp.instances.map<ValueOption>((ins) => {
+ };
+ const results = await Promise.all([
+ hasWorkspacePermissionV2("bb.instances.list")
+ ? useAppStore.getState().fetchInstanceList(params)
+ : Promise.resolve({ instances: [], nextPageToken: "" }),
+ project &&
+ isValidProjectName(project.name) &&
+ !isDefaultProject(project.name) &&
+ hasProjectPermissionV2(project, "bb.instances.list")
+ ? useAppStore
+ .getState()
+ .fetchInstanceList({ ...params, parent: project.name })
+ : Promise.resolve({ instances: [], nextPageToken: "" }),
+ ]);
+ const instances = [
+ ...new Map(
+ results
+ .flatMap((result) => result.instances)
+ .map((instance) => [instance.name, instance])
+ ).values(),
+ ];
+ return instances.map<ValueOption>((ins) => {
const name = extractInstanceResourceName(ins.name);
const env = extractEnvironmentResourceName(ins.environment ?? "");
return {
- value: name,
+ value: ins.name,
keywords: [name, ins.title, String(ins.engine), env],
render: () => (
<span className="flex items-center gap-x-1">
@@ -51,7 +76,7 @@ export function useCommonSearchScopeOptions(
};
});
},
- []
+ [project]
);
return useMemo(() => {
diff --git a/frontend/src/lib/resourceName.test.ts b/frontend/src/lib/resourceName.test.ts
new file mode 100644
index 0000000000..5aef0a9fed
--- /dev/null
+++ b/frontend/src/lib/resourceName.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, test } from "vitest";
+import { normalizeInstanceName } from "./resourceName";
+
+describe("normalizeInstanceName", () => {
+ test("normalizes a bare ID as a workspace instance", () => {
+ expect(normalizeInstanceName("prod")).toBe("instances/prod");
+ });
+
+ test.each(["instances/prod", "projects/hr-system/instances/prod"])(
+ "preserves the canonical instance name %s",
+ (name) => {
+ expect(normalizeInstanceName(name)).toBe(name);
+ }
+ );
+});
diff --git a/frontend/src/lib/resourceName.ts b/frontend/src/lib/resourceName.ts
index 42aa205e6b..83788f0ad3 100644
--- a/frontend/src/lib/resourceName.ts
+++ b/frontend/src/lib/resourceName.ts
@@ -1,3 +1,5 @@
+import { isValidInstanceName } from "@/types/v1/instance";
+
export const workspaceNamePrefix = "workspaces/";
export const userNamePrefix = "users/";
export const projectNamePrefix = "projects/";
@@ -5,6 +7,10 @@ export const instanceNamePrefix = "instances/";
export const databaseNamePrefix = "databases/";
export const settingNamePrefix = "settings/";
+export function normalizeInstanceName(name: string): string {
+ return isValidInstanceName(name) ? name : `${instanceNamePrefix}${name}`;
+}
+
export function getResourceId(name: string, prefix: string): string {
if (!name.startsWith(prefix)) {
return "";
diff --git a/frontend/src/modules/agent/logic/skills/databaseChange.ts b/frontend/src/modules/agent/logic/skills/databaseChange.ts
index c241621bc3..82b7eec0b2 100644
--- a/frontend/src/modules/agent/logic/skills/databaseChange.ts
+++ b/frontend/src/modules/agent/logic/skills/databaseChange.ts
@@ -53,7 +53,7 @@ call_api(operationId="PlanService/CreatePlan", body={
"specs": [{
"id": "spec-1",
"changeDatabaseConfig": {
- "targets": ["instances/{instance-id}/databases/{database-name}"],
+ "targets": ["projects/{project-id}/instances/{instance-id}/databases/{database-name}"],
"sheet": "projects/{project-id}/sheets/{sheet-id}",
"type": "MIGRATE"
}
@@ -94,6 +94,7 @@ call_api(operationId="PlanService/CreatePlan", body={
- \`specs\` is a flat array directly on the plan (no "steps" wrapper)
- Each \`spec\` has a unique \`id\` (any string, used for identification)
- \`targets\` is an **array** (even for single database)
+- Preserve each exact canonical database name returned by ListDatabases. Do not remove a \`projects/{project-id}\` instance parent.
- Specs are executed based on rollout policy (can be sequential or parallel)
**Using database groups:**
@@ -142,7 +143,7 @@ call_api(operationId="RolloutService/CreateRollout", body={
| Error | Cause | Fix |
|-------|-------|-----|
-| database not found | Wrong database reference | Verify \`instances/{id}/databases/{name}\` format |
+| database not found | Wrong database reference | Use the exact \`instances/{id}/databases/{name}\` or \`projects/{project}/instances/{id}/databases/{name}\` returned by ListDatabases |
| sheet not found | Sheet doesn't exist | Create sheet first (Step 1) |
| missing engine | Sheet without engine field | Add \`engine\` field to sheet |
| plan not found | Plan doesn't exist | Create plan before issue |
diff --git a/frontend/src/modules/agent/logic/skills/grantPermission.ts b/frontend/src/modules/agent/logic/skills/grantPermission.ts
index c09d3939ca..eb4d9f8b3a 100644
--- a/frontend/src/modules/agent/logic/skills/grantPermission.ts
+++ b/frontend/src/modules/agent/logic/skills/grantPermission.ts
@@ -153,7 +153,7 @@ call_api(operationId="ProjectService/SetIamPolicy", body={
\`\`\`
**CEL variables for sqlEditorUser:**
-- \`resource.database\`: Database name (\`instances/{id}/databases/{name}\`)
+- \`resource.database\`: Canonical database name (\`instances/{id}/databases/{name}\` or \`projects/{project}/instances/{id}/databases/{name}\`)
- \`resource.schema_name\`: Schema name
- \`resource.table_name\`: Table name
- \`request.time\`: For expiration
@@ -161,6 +161,7 @@ call_api(operationId="ProjectService/SetIamPolicy", body={
**CEL examples:**
- Expire at date: \`request.time < timestamp('2024-12-31T23:59:59Z')\`
- Limit to database: \`resource.database == "instances/prod/databases/main"\`
+- Limit to project-instance database: \`resource.database == "projects/acme/instances/prod/databases/main"\`
## Common Errors
diff --git a/frontend/src/modules/agent/logic/skills/query.ts b/frontend/src/modules/agent/logic/skills/query.ts
index 1eba839a0c..2c9b9f2f10 100644
--- a/frontend/src/modules/agent/logic/skills/query.ts
+++ b/frontend/src/modules/agent/logic/skills/query.ts
@@ -31,7 +31,8 @@ Run SQL queries against databases managed by Bytebase.
Filter examples:
- \`name.contains("employee")\` - database name contains "employee"
- \`project == "projects/{project-id}"\` - databases in a project
- - \`instance == "instances/{instance-id}"\` - databases in an instance
+ - \`instance == "instances/{instance-id}"\` - databases in a workspace instance
+ - \`instance == "projects/{project-id}/instances/{instance-id}"\` - databases in a project instance
- \`engine == "MYSQL"\` - MySQL databases only
- \`environment == "environments/prod" && name.contains("user")\` - combine filters
@@ -40,7 +41,7 @@ Run SQL queries against databases managed by Bytebase.
3. **Execute SQL**:
\`\`\`
call_api(operationId="SQLService/Query", body={
- "name": "instances/{instance-id}/databases/{database-name}",
+ "name": "projects/{project-id}/instances/{instance-id}/databases/{database-name}",
"statement": "SELECT * FROM users LIMIT 10"
})
\`\`\`
@@ -53,6 +54,7 @@ Run SQL queries against databases managed by Bytebase.
- Full mask: \`******\`
- Partial mask: \`**rn**\` (only "rn" visible)
- **Displaying partial masks:** Use backticks or code blocks when presenting results. Without escaping, markdown interprets \`**text**\` as bold formatting.
+- Preserve the exact canonical database name returned by ListDatabases. Workspace databases use \`instances/{instance}/databases/{database}\`; project-instance databases use \`projects/{project}/instances/{instance}/databases/{database}\`.
## Common Errors
diff --git a/frontend/src/modules/sql-editor/components/ConnectionPane/ConnectionPane.test.tsx b/frontend/src/modules/sql-editor/components/ConnectionPane/ConnectionPane.test.tsx
index b09b1f2cbb..4eb8c3cef0 100644
--- a/frontend/src/modules/sql-editor/components/ConnectionPane/ConnectionPane.test.tsx
+++ b/frontend/src/modules/sql-editor/components/ConnectionPane/ConnectionPane.test.tsx
@@ -88,6 +88,11 @@ const mocks = vi.hoisted(() => {
.mockResolvedValue({ databases: [], nextPageToken: "" }),
databasesByName: {} as Record<string, unknown>,
};
+ const prepareDatabases = vi.fn().mockResolvedValue(undefined);
+ const searchParams = {
+ query: "",
+ scopes: [] as { id: string; value: string }[],
+ };
const currentUser = { email: "[email protected]" };
return {
tabStore,
@@ -97,6 +102,8 @@ const mocks = vi.hoisted(() => {
databaseStore,
project,
treeStore,
+ prepareDatabases,
+ searchParams,
appStore,
currentUser,
pushNotification: vi.fn(),
@@ -189,10 +196,6 @@ vi.mock("@/modules/sql-editor/store", () => ({
}),
}));
-vi.mock("@/lib/resourceName", () => ({
- instanceNamePrefix: "instances/",
-}));
-
vi.mock("@/modules/sql-editor/model/events", () => ({
sqlEditorEvents: {
emit: vi.fn(),
@@ -253,7 +256,10 @@ vi.mock("@/utils", () => ({
}),
getConnectionForSQLEditorTab: () => ({ database: undefined }),
getInstanceResource: () => ({ engine: "MYSQL" }),
- getValueFromSearchParams: () => "",
+ getValueFromSearchParams: (
+ params: { scopes: { id: string; value: string }[] },
+ id: string
+ ) => params.scopes.find((scope) => scope.id === id)?.value ?? "",
getValuesFromSearchParams: () => [],
instanceV1Name: (i: { title: string }) => i.title,
}));
@@ -286,7 +292,7 @@ vi.mock("@/components/ui/separator", () => ({
vi.mock("@/components/AdvancedSearch", () => ({
AdvancedSearch: () => <div data-testid="advanced-search" />,
- emptySearchParams: () => ({ query: "", scopes: [] }),
+ emptySearchParams: () => mocks.searchParams,
}));
vi.mock("@/components/useCommonSearchScopeOptions", () => ({
@@ -402,7 +408,7 @@ vi.mock("./tree", () => ({
expandedState: { initialized: true, expandedKeys: [] },
setExpandedKeys: vi.fn(),
buildTree: vi.fn(),
- prepareDatabases: vi.fn().mockResolvedValue(undefined),
+ prepareDatabases: mocks.prepareDatabases,
fetchDatabases: vi.fn().mockResolvedValue(undefined),
fetchDataState: { loading: false },
}),
@@ -444,10 +450,34 @@ beforeEach(async () => {
connection: { database: "", instance: "" },
batchQueryContext: { databases: [], databaseGroups: [] },
};
+ mocks.searchParams.query = "";
+ mocks.searchParams.scopes = [];
({ ConnectionPane } = await import("./ConnectionPane"));
});
describe("ConnectionPane", () => {
+ test.each([
+ ["prod", "instances/prod"],
+ [
+ "projects/project-a/instances/prod",
+ "projects/project-a/instances/prod",
+ ],
+ ])("preserves the instance filter scope for %s", async (value, expected) => {
+ mocks.searchParams.scopes = [{ id: "instance", value }];
+ const { render, unmount } = renderIntoContainer(
+ <ConnectionPane show={true} onMissingFeature={() => {}} />
+ );
+ render();
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ expect(mocks.prepareDatabases).toHaveBeenCalledWith(
+ expect.objectContaining({ instance: expected })
+ );
+ unmount();
+ });
+
test("renders DATABASE tab content when show=true and no selection", () => {
const { container, render, unmount } = renderIntoContainer(
<ConnectionPane show={true} onMissingFeature={() => {}} />
diff --git a/frontend/src/modules/sql-editor/components/ConnectionPane/ConnectionPane.tsx b/frontend/src/modules/sql-editor/components/ConnectionPane/ConnectionPane.tsx
index 4ddfebc1a6..5c292c56a0 100644
--- a/frontend/src/modules/sql-editor/components/ConnectionPane/ConnectionPane.tsx
+++ b/frontend/src/modules/sql-editor/components/ConnectionPane/ConnectionPane.tsx
@@ -23,7 +23,7 @@ import { useAppDatabase } from "@/hooks/useAppDatabase";
import { useAppProject } from "@/hooks/useAppProject";
import { useCurrentUser } from "@/hooks/useAppState";
import type { DatabaseFilter } from "@/lib/databaseFilter";
-import { instanceNamePrefix } from "@/lib/resourceName";
+import { normalizeInstanceName } from "@/lib/resourceName";
import { getConnectionForSQLEditorTab } from "@/lib/sqlEditorConnection";
import { cn } from "@/lib/utils";
import { useSQLEditorFeature } from "@/modules/sql-editor/hooks/useSQLEditorState";
@@ -257,11 +257,10 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {
const currentProject = useAppProject(projectName);
const projectTitle = projectName ? currentProject.title : "";
- const scopeOptions = useCommonSearchScopeOptions([
- "instance",
- "label",
- "engine",
- ]);
+ const scopeOptions = useCommonSearchScopeOptions(
+ ["instance", "label", "engine"],
+ currentProject
+ );
// Derive DatabaseFilter fields from the search scopes, matching the Vue
// version's slicing of `state.params` into `instance`, `labels`, and
@@ -270,11 +269,10 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {
() => getValuesFromSearchParams(searchParams, "label"),
[searchParams]
);
- const selectedInstance = useMemo(
- () =>
- getValueFromSearchParams(searchParams, "instance", instanceNamePrefix),
- [searchParams]
- );
+ const selectedInstance = useMemo(() => {
+ const value = getValueFromSearchParams(searchParams, "instance");
+ return value ? normalizeInstanceName(value) : "";
+ }, [searchParams]);
const selectedEngines = useMemo<Engine[]>(
() =>
getValuesFromSearchParams(searchParams, "engine")
diff --git a/frontend/src/routes/project/ProjectDatabaseDetailPage.test.tsx b/frontend/src/routes/project/ProjectDatabaseDetailPage.test.tsx
index 0307e0b5a2..582c43b38a 100644
--- a/frontend/src/routes/project/ProjectDatabaseDetailPage.test.tsx
+++ b/frontend/src/routes/project/ProjectDatabaseDetailPage.test.tsx
@@ -557,7 +557,7 @@ describe("ProjectDatabaseDetailPage", () => {
sample: {
instances: [
{
- instance: "instances/inst1",
+ instance: "projects/proj1/instances/inst1",
expireTime: {
seconds: BigInt(
Math.floor(Date.now() / 1000) + 7 * 24 * 60 * 60
diff --git a/frontend/src/routes/project/ProjectDatabasesPage.test.tsx b/frontend/src/routes/project/ProjectDatabasesPage.test.tsx
index 3de09b8cc0..bac408aa95 100644
--- a/frontend/src/routes/project/ProjectDatabasesPage.test.tsx
+++ b/frontend/src/routes/project/ProjectDatabasesPage.test.tsx
@@ -19,14 +19,18 @@ const mocks = vi.hoisted(() => ({
captureMetric: vi.fn(),
removeDatabaseMetadataCache: vi.fn(),
fetchInstance: vi.fn(),
- fetchInstanceList: vi.fn(async () => ({
+ fetchInstanceList: vi.fn(async (_params?: { parent?: string }) => ({
instances: [] as { name: string; title: string }[],
})),
workspacePermissions: new Set<string>([
"bb.instances.create",
"bb.instances.list",
]),
- projectPermissions: new Set<string>(["bb.instances.create"]),
+ projectPermissions: new Set<string>([
+ "bb.instances.create",
+ "bb.instances.get",
+ "bb.instances.list",
+ ]),
}));
let ProjectDatabasesPage: typeof import("./ProjectDatabasesPage").ProjectDatabasesPage;
@@ -80,7 +84,27 @@ vi.mock("@/app/analytics/provider", () => ({
}));
vi.mock("@/components/AdvancedSearch", () => ({
- AdvancedSearch: () => <div data-testid="advanced-search" />,
+ AdvancedSearch: ({
+ scopeOptions,
+ }: {
+ scopeOptions: {
+ id: string;
+ onSearch?: (keyword: string) => Promise<unknown>;
+ }[];
+ }) => (
+ <div data-testid="advanced-search">
+ <span
+ data-testid="search-instances"
+ onClick={() => {
+ void scopeOptions
+ .find((option) => option.id === "instance")
+ ?.onSearch?.("");
+ }}
+ >
+ search instances
+ </span>
+ </div>
+ ),
getValueFromScopes: () => undefined,
}));
@@ -212,7 +236,9 @@ vi.mock("@/stores/app", () => {
get instancesByName() {
return mocks.instancesByName;
},
- projectsByName: {},
+ projectsByName: {
+ "projects/demo": { name: "projects/demo", title: "Demo Project" },
+ },
environmentList: [],
};
const useAppStore = (selector: (state: typeof appState) => unknown) =>
@@ -237,10 +263,9 @@ vi.mock("@/utils", async () => {
...actual,
engineNameV1: () => "PostgreSQL",
extractInstanceResourceName: (name: string) =>
- name.replace(/^instances\//, ""),
+ name.match(/(?:^|\/)instances\/([^/]+)/)?.[1] ?? name,
getDefaultPagination: () => 1000,
hasProjectPermissionV2: (_project: unknown, permission: string) =>
- permission !== "bb.instances.create" ||
mocks.projectPermissions.has(permission),
hasWorkspacePermissionV2: (permission: string) =>
mocks.workspacePermissions.has(permission),
@@ -251,6 +276,7 @@ vi.mock("@/utils", async () => {
beforeEach(async () => {
vi.clearAllMocks();
+ mocks.fetchInstanceList.mockImplementation(async () => ({ instances: [] }));
mocks.visibleDatabases = [];
mocks.databasesByName = {};
mocks.instancesByName = {};
@@ -262,7 +288,11 @@ beforeEach(async () => {
"bb.instances.get",
"bb.instances.list",
]);
- mocks.projectPermissions = new Set(["bb.instances.create"]);
+ mocks.projectPermissions = new Set([
+ "bb.instances.create",
+ "bb.instances.get",
+ "bb.instances.list",
+ ]);
({ ProjectDatabasesPage } = await import("./ProjectDatabasesPage"));
});
@@ -274,6 +304,9 @@ describe("ProjectDatabasesPage", () => {
await act(async () => {
root.render(<ProjectDatabasesPage projectId="demo" />);
});
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
const toolbarButton = container.querySelector(
'button[data-product-intro-target="connect-database"]'
@@ -380,6 +413,102 @@ describe("ProjectDatabasesPage", () => {
});
});
+ test("only checks workspace instances for the default project", async () => {
+ mocks.fetchInstanceList.mockImplementation(async (params) => {
+ if (params?.parent) {
+ throw new Error("the default project cannot own instances");
+ }
+ return {
+ instances: [{ name: "instances/prod", title: "Prod" }],
+ };
+ });
+ const container = document.createElement("div");
+ const root = createRoot(container);
+
+ await act(async () => {
+ root.render(<ProjectDatabasesPage projectId="default" />);
+ await Promise.resolve();
+ });
+
+ expect(mocks.fetchInstanceList).toHaveBeenCalledTimes(1);
+ expect(mocks.fetchInstanceList).toHaveBeenCalledWith({ pageSize: 2 });
+ expect(container.textContent).toContain("project.add-database");
+ expect(container.textContent).not.toContain("project.connect-instance");
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
+ test("only searches workspace instances for the default project", async () => {
+ mocks.fetchInstanceList.mockImplementation(async (params) => {
+ if (params?.parent) {
+ throw new Error("the default project cannot own instances");
+ }
+ return {
+ instances: [{ name: "instances/prod", title: "Prod" }],
+ };
+ });
+ const container = document.createElement("div");
+ const root = createRoot(container);
+
+ await act(async () => {
+ root.render(<ProjectDatabasesPage projectId="default" />);
+ await Promise.resolve();
+ });
+ mocks.fetchInstanceList.mockClear();
+
+ const button = container.querySelector(
+ '[data-testid="search-instances"]'
+ ) as HTMLElement;
+ await act(async () => {
+ button.click();
+ await Promise.resolve();
+ });
+
+ expect(mocks.fetchInstanceList).toHaveBeenCalledTimes(1);
+ expect(mocks.fetchInstanceList).toHaveBeenCalledWith({
+ pageSize: 1000,
+ filter: undefined,
+ });
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
+ test("opens the add database sheet when the project has a project instance", async () => {
+ mocks.fetchInstanceList.mockImplementation(async (params) => ({
+ instances:
+ params?.parent === "projects/demo"
+ ? [
+ {
+ name: "projects/demo/instances/prod",
+ title: "Project production",
+ },
+ ]
+ : [],
+ }));
+ const container = document.createElement("div");
+ const root = createRoot(container);
+
+ await act(async () => {
+ root.render(<ProjectDatabasesPage projectId="demo" />);
+ await Promise.resolve();
+ });
+
+ expect(container.textContent).toContain("project.add-database");
+ expect(container.textContent).not.toContain("project.connect-database");
+ expect(mocks.fetchInstanceList).toHaveBeenCalledWith({
+ parent: "projects/demo",
+ pageSize: 2,
+ });
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
test("disables the empty project connect action without project instance creation permission", async () => {
mocks.projectPermissions.delete("bb.instances.create");
const container = document.createElement("div");
@@ -388,6 +517,9 @@ describe("ProjectDatabasesPage", () => {
await act(async () => {
root.render(<ProjectDatabasesPage projectId="demo" />);
});
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
const button = container.querySelector(
'button[data-product-intro-target="connect-database"]'
@@ -411,7 +543,10 @@ describe("ProjectDatabasesPage", () => {
test("shows syncing guidance when redirected from project-aware instance creation", async () => {
mocks.routerCurrentQuery = { syncingInstance: "prod" };
mocks.instancesByName = {
- "instances/prod": { name: "instances/prod", title: "Prod Instance" },
+ "projects/demo/instances/prod": {
+ name: "projects/demo/instances/prod",
+ title: "Prod Instance",
+ },
};
const container = document.createElement("div");
const root = createRoot(container);
@@ -449,7 +584,10 @@ describe("ProjectDatabasesPage", () => {
test("updates syncing guidance when the syncing instance query changes", async () => {
mocks.instancesByName = {
- "instances/prod": { name: "instances/prod", title: "Prod Instance" },
+ "projects/demo/instances/prod": {
+ name: "projects/demo/instances/prod",
+ title: "Prod Instance",
+ },
};
const container = document.createElement("div");
const root = createRoot(container);
@@ -677,6 +815,7 @@ describe("ProjectDatabasesPage", () => {
test("hides post-sync guidance without permission to list instances", async () => {
mocks.workspacePermissions.delete("bb.instances.list");
+ mocks.projectPermissions.delete("bb.instances.list");
mocks.routerCurrentQuery = { syncingInstance: "prod" };
mocks.visibleDatabases = [
{
diff --git a/frontend/src/routes/project/ProjectDatabasesPage.tsx b/frontend/src/routes/project/ProjectDatabasesPage.tsx
index 00a5b9e21c..b5d95a1811 100644
--- a/frontend/src/routes/project/ProjectDatabasesPage.tsx
+++ b/frontend/src/routes/project/ProjectDatabasesPage.tsx
@@ -50,11 +50,11 @@ import {
PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO,
useProductIntro,
} from "@/lib/productIntro";
+import { normalizeInstanceName } from "@/lib/resourceName";
import { pushNotification } from "@/stores";
import { useAppStore } from "@/stores/app";
import {
environmentNamePrefix,
- instanceNamePrefix,
projectNamePrefix,
} from "@/stores/modules/v1/common";
import type { Permission } from "@/types";
@@ -83,6 +83,24 @@ import {
} from "@/utils";
import { extractProjectResourceName } from "@/utils/v1/project";
+const fetchAvailableInstanceCount = async (
+ projectName: string,
+ shouldListProjectInstances: boolean
+) => {
+ const results = await Promise.all([
+ hasWorkspacePermissionV2("bb.instances.list")
+ ? useAppStore.getState().fetchInstanceList({ pageSize: 2 })
+ : Promise.resolve({ instances: [], nextPageToken: "" }),
+ shouldListProjectInstances
+ ? useAppStore
+ .getState()
+ .fetchInstanceList({ parent: projectName, pageSize: 2 })
+ : Promise.resolve({ instances: [], nextPageToken: "" }),
+ ]);
+ const instances = results.flatMap((result) => result.instances);
+ return new Set(instances.map((instance) => instance.name)).size;
+};
+
export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
const { t } = useTranslation();
const currentRoute = useCurrentRoute();
@@ -103,6 +121,7 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
project ? hasProjectPermissionV2(project, permission) : false,
[project]
);
+ const canListProjectInstances = hasProjectPermission("bb.instances.list");
const [syncing, setSyncing] = useState(false);
const [showCreateDrawer, setShowCreateDrawer] = useState(false);
@@ -111,13 +130,13 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
const [showTransferDrawer, setShowTransferDrawer] = useState(false);
const [showUnassignConfirm, setShowUnassignConfirm] = useState(false);
const [refreshToken, setRefreshToken] = useState(0);
- const [workspaceInstanceCount, setWorkspaceInstanceCount] = useState<
+ const [availableInstanceCount, setAvailableInstanceCount] = useState<
number | undefined
>(undefined);
- const workspaceHasInstance =
- workspaceInstanceCount === undefined
+ const hasAvailableInstance =
+ availableInstanceCount === undefined
? undefined
- : workspaceInstanceCount > 0;
+ : availableInstanceCount > 0;
const [syncingRefreshExhausted, setSyncingRefreshExhausted] = useState(false);
const autoRefreshCountRef = useRef(0);
@@ -137,17 +156,31 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
const searchInstances = useCallback(
async (keyword: string): Promise<ValueOption[]> => {
- if (!hasWorkspacePermissionV2("bb.instances.list")) return [];
- const { instances } = await useAppStore.getState().fetchInstanceList({
+ const params = {
pageSize: getDefaultPagination(),
filter: keyword.trim() ? { query: keyword } : undefined,
- });
+ };
+ const results = await Promise.all([
+ hasWorkspacePermissionV2("bb.instances.list")
+ ? useAppStore.getState().fetchInstanceList(params)
+ : Promise.resolve({ instances: [], nextPageToken: "" }),
+ canListProjectInstances && !isDefault
+ ? useAppStore
+ .getState()
+ .fetchInstanceList({ ...params, parent: projectName })
+ : Promise.resolve({ instances: [], nextPageToken: "" }),
+ ]);
+ const instances = [
+ ...new Map(
+ results.flatMap((result) => result.instances).map((i) => [i.name, i])
+ ).values(),
+ ];
return instances.map((i) => {
const id = extractInstanceResourceName(i.name);
- return { value: id, keywords: [id, i.title] };
+ return { value: i.name, keywords: [id, i.title] };
});
},
- []
+ [canListProjectInstances, isDefault, projectName]
);
const scopeOptions: ScopeOption[] = useMemo(() => {
@@ -207,7 +240,7 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
const instanceVal = getValueFromScopes(searchParams, "instance");
const selectedInstance = instanceVal
- ? `${instanceNamePrefix}${instanceVal}`
+ ? normalizeInstanceName(instanceVal)
: undefined;
const selectedEngines = useMemo(
@@ -252,7 +285,7 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
: undefined;
}, [currentRoute.query]);
const syncingInstanceName = syncingInstanceId
- ? `${instanceNamePrefix}${syncingInstanceId}`
+ ? `${projectName}/instances/${syncingInstanceId}`
: undefined;
const selectedDatabases = useMemo(() => {
@@ -300,30 +333,27 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
}, [syncingInstanceId, visibleDatabases.length, refresh]);
useEffect(() => {
- if (!hasWorkspacePermissionV2("bb.instances.list")) {
- setWorkspaceInstanceCount(0);
- return;
- }
-
let cancelled = false;
- useAppStore
- .getState()
- .fetchInstanceList({ pageSize: 2 })
- .then(({ instances }) => {
+ setAvailableInstanceCount(undefined);
+ fetchAvailableInstanceCount(
+ projectName,
+ canListProjectInstances && !isDefault
+ )
+ .then((count) => {
if (!cancelled) {
- setWorkspaceInstanceCount(instances.length);
+ setAvailableInstanceCount(count);
}
})
.catch(() => {
if (!cancelled) {
- setWorkspaceInstanceCount(0);
+ setAvailableInstanceCount(0);
}
});
return () => {
cancelled = true;
};
- }, []);
+ }, [canListProjectInstances, isDefault, projectName]);
// Batch operation handlers
const handleSyncSchema = useCallback(async () => {
@@ -508,21 +538,21 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
!!syncingInstanceId && !hasVisibleDatabase && !syncingRefreshExhausted;
const showDatabaseNextAction =
hasVisibleDatabase &&
- ((workspaceInstanceCount === 1 && !!syncingInstanceId) ||
+ ((availableInstanceCount === 1 && !!syncingInstanceId) ||
currentRoute.query[PRODUCT_INTRO_QUERY_KEY] ===
PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO);
- const checkingWorkspaceInstance =
+ const checkingAvailableInstance =
!hasVisibleDatabase &&
!showSyncingInstanceHint &&
!syncingRefreshExhausted &&
- workspaceHasInstance === undefined;
+ hasAvailableInstance === undefined;
const emptyProjectHasInstance =
!hasVisibleDatabase &&
- (workspaceHasInstance === true || syncingRefreshExhausted) &&
+ (hasAvailableInstance === true || syncingRefreshExhausted) &&
!showSyncingInstanceHint;
const emptyProjectShouldConnectInstance =
!hasVisibleDatabase &&
- workspaceHasInstance === false &&
+ hasAvailableInstance === false &&
!syncingRefreshExhausted &&
!showSyncingInstanceHint;
@@ -554,7 +584,7 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
disabled:
showSyncingInstanceHint ||
hasVisibleDatabase ||
- workspaceHasInstance !== false ||
+ hasAvailableInstance !== false ||
!canCreateInstance,
});
useProductIntro({
@@ -565,7 +595,7 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
});
const handleCreateDatabaseAction = useCallback(() => {
- if (checkingWorkspaceInstance) return;
+ if (checkingAvailableInstance) return;
if (emptyProjectShouldConnectInstance) {
if (!hasProjectPermission("bb.instances.create")) return;
behaviorAnalytics.captureMetric(
@@ -582,7 +612,7 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
}
setShowCreateDrawer(true);
}, [
- checkingWorkspaceInstance,
+ checkingAvailableInstance,
emptyProjectShouldConnectInstance,
hasProjectPermission,
projectId,
@@ -618,7 +648,7 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
: undefined
}
disabled={
- checkingWorkspaceInstance
+ checkingAvailableInstance
? true
: hasVisibleDatabase || emptyProjectHasInstance
? !hasProjectPermission("bb.instances.list") ||
diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx
index 59e43df160..c7a2cd68cb 100644
--- a/frontend/src/routes/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx
+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx
@@ -186,12 +186,11 @@ function IssueDetailDatabaseResourceTable({
databaseResourceList.map((resource) => {
const database =
databasesByName[resource.databaseFullName] ?? unknownDatabase();
- const { databaseName, instanceName } = extractDatabaseResourceName(
+ const { databaseName, instance } = extractDatabaseResourceName(
resource.databaseFullName
);
- const instance = instanceName
- ? instancesByName[`instances/${instanceName}`]
- : database.instanceResource;
+ const instanceResource =
+ instancesByName[instance] ?? database.instanceResource;
const environmentName =
database.effectiveEnvironment ??
database.instanceResource?.environment ??
@@ -202,7 +201,7 @@ function IssueDetailDatabaseResourceTable({
return {
databaseName,
environmentTitle: environment.title,
- instanceTitle: instance?.title ?? "",
+ instanceTitle: instanceResource?.title ?? "",
resource,
};
}),
diff --git a/frontend/src/routes/workspace/DatabasesPage.test.tsx b/frontend/src/routes/workspace/DatabasesPage.test.tsx
index e17fe5f3a9..5811680ad6 100644
--- a/frontend/src/routes/workspace/DatabasesPage.test.tsx
+++ b/frontend/src/routes/workspace/DatabasesPage.test.tsx
@@ -18,6 +18,7 @@ const mocks = vi.hoisted(() => ({
hasWorkspacePermission: true,
databaseTableRows: [] as unknown[],
databaseTableLoading: false,
+ scopeValues: {} as Record<string, string | undefined>,
}));
let DatabasesPage: typeof import("./DatabasesPage").DatabasesPage;
@@ -42,7 +43,7 @@ vi.mock("@/app/router", () => ({
vi.mock("@/components/AdvancedSearch", () => ({
AdvancedSearch: () => <div data-testid="advanced-search" />,
- getValueFromScopes: () => undefined,
+ getValueFromScopes: (_params: unknown, id: string) => mocks.scopeValues[id],
}));
vi.mock("@/components/EditEnvironmentSheet", () => ({
@@ -85,17 +86,20 @@ vi.mock("@/components/database", () => ({
),
DatabaseBatchOperationsBar: () => null,
DatabaseTable: ({
+ filter,
emptyPlaceholder,
selectionColumnIntroTarget,
onDatabasesChange,
onLoadingChange,
}: {
+ filter?: { instance?: string };
emptyPlaceholder?: React.ReactNode;
selectionColumnIntroTarget?: string;
onDatabasesChange?: (databases: unknown[]) => void;
onLoadingChange?: (loading: boolean) => void;
}) => (
<DatabaseTableMock
+ filter={filter}
emptyPlaceholder={emptyPlaceholder}
selectionColumnIntroTarget={selectionColumnIntroTarget}
onDatabasesChange={onDatabasesChange}
@@ -107,11 +111,13 @@ vi.mock("@/components/database", () => ({
}));
const DatabaseTableMock = ({
+ filter,
emptyPlaceholder,
selectionColumnIntroTarget,
onDatabasesChange,
onLoadingChange,
}: {
+ filter?: { instance?: string };
emptyPlaceholder?: React.ReactNode;
selectionColumnIntroTarget?: string;
onDatabasesChange?: (databases: unknown[]) => void;
@@ -126,6 +132,7 @@ const DatabaseTableMock = ({
return (
<div
data-testid="database-table"
+ data-instance-filter={filter?.instance ?? ""}
data-has-empty-placeholder={String(!!emptyPlaceholder)}
data-selection-column-intro-target={selectionColumnIntroTarget ?? ""}
>
@@ -181,10 +188,36 @@ beforeEach(async () => {
mocks.currentRoute = { query: {} };
mocks.databaseTableRows = [];
mocks.databaseTableLoading = false;
+ mocks.scopeValues = {};
({ DatabasesPage } = await import("./DatabasesPage"));
});
describe("DatabasesPage", () => {
+ test("preserves a canonical project-instance filter", async () => {
+ mocks.scopeValues.instance = "projects/app/instances/prod";
+ const container = document.createElement("div");
+ const root = createRoot(container);
+
+ await act(async () => {
+ root.render(
+ <MemoryRouter>
+ <DatabasesPage />
+ </MemoryRouter>
+ );
+ await Promise.resolve();
+ });
+
+ expect(
+ container
+ .querySelector("[data-testid='database-table']")
+ ?.getAttribute("data-instance-filter")
+ ).toBe("projects/app/instances/prod");
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
test("does not pass an action as the empty table placeholder", async () => {
const container = document.createElement("div");
const root = createRoot(container);
diff --git a/frontend/src/routes/workspace/DatabasesPage.tsx b/frontend/src/routes/workspace/DatabasesPage.tsx
index 3b7ad455e3..c8257471a9 100644
--- a/frontend/src/routes/workspace/DatabasesPage.tsx
+++ b/frontend/src/routes/workspace/DatabasesPage.tsx
@@ -41,11 +41,11 @@ import {
PRODUCT_INTRO_TIP_QUERY_KEY,
useProductIntro,
} from "@/lib/productIntro";
+import { normalizeInstanceName } from "@/lib/resourceName";
import { pushNotification } from "@/stores";
import { useAppStore } from "@/stores/app";
import {
environmentNamePrefix,
- instanceNamePrefix,
projectNamePrefix,
} from "@/stores/modules/v1/common";
import {
@@ -250,7 +250,7 @@ export function DatabasesPage() {
const instanceVal = getValueFromScopes(searchParams, "instance");
const selectedInstance = instanceVal
- ? `${instanceNamePrefix}${instanceVal}`
+ ? normalizeInstanceName(instanceVal)
: undefined;
const selectedEngines = useMemo(
diff --git a/frontend/src/routes/workspace/MemberDatabaseResourceName.test.tsx b/frontend/src/routes/workspace/MemberDatabaseResourceName.test.tsx
index 3100c474f0..e2d63bd677 100644
--- a/frontend/src/routes/workspace/MemberDatabaseResourceName.test.tsx
+++ b/frontend/src/routes/workspace/MemberDatabaseResourceName.test.tsx
@@ -29,13 +29,17 @@ vi.mock("@/components/EngineIcon", () => ({
vi.mock("@/utils", () => ({
extractDatabaseResourceName: (name: string) => {
- const parts = name.split("/");
+ const match = name.match(
+ /^(?<instance>(?:projects\/[^/]+\/)?instances\/(?<instanceName>[^/]+))\/databases\/(?<databaseName>[^/]+)$/
+ );
return {
- databaseName: parts[3] ?? name,
- instanceName: parts[1] ?? "",
+ instance: match?.groups?.instance ?? "",
+ databaseName: match?.groups?.databaseName ?? name,
+ instanceName: match?.groups?.instanceName ?? "",
};
},
- extractInstanceResourceName: (name: string) => name.split("/")[1] ?? name,
+ extractInstanceResourceName: (name: string) =>
+ name.match(/(?:^|\/)instances\/([^/]+)/)?.[1] ?? name,
getInstanceResource: (database: { instanceResource?: unknown }) =>
database.instanceResource,
}));
@@ -103,4 +107,27 @@ describe("MemberDatabaseResourceName", () => {
expect(screen.getByText("*")).toBeInTheDocument();
});
+
+ test("looks up a project instance by its canonical parent", () => {
+ const projectResource: DatabaseResource = {
+ databaseFullName: "projects/app/instances/prod/databases/hr",
+ };
+ mocks.databasesByName = {
+ [projectResource.databaseFullName]: {
+ name: projectResource.databaseFullName,
+ },
+ };
+ mocks.instancesByName = {
+ "projects/app/instances/prod": {
+ name: "projects/app/instances/prod",
+ title: "Project production",
+ engine: "POSTGRES",
+ },
+ };
+
+ render(<MemberDatabaseResourceName resource={projectResource} />);
+
+ expect(screen.getByText("Project production")).toBeInTheDocument();
+ expect(screen.getByText("hr")).toBeInTheDocument();
+ });
});
diff --git a/frontend/src/routes/workspace/MemberDatabaseResourceName.tsx b/frontend/src/routes/workspace/MemberDatabaseResourceName.tsx
index fdb13508a9..6bda86a243 100644
--- a/frontend/src/routes/workspace/MemberDatabaseResourceName.tsx
+++ b/frontend/src/routes/workspace/MemberDatabaseResourceName.tsx
@@ -13,10 +13,9 @@ export function MemberDatabaseResourceName({
}: {
resource?: DatabaseResource;
}) {
- const { instanceName } = resource
+ const { instance: expectedInstanceName } = resource
? extractDatabaseResourceName(resource.databaseFullName)
- : { instanceName: "" };
- const expectedInstanceName = instanceName ? `instances/${instanceName}` : "";
+ : { instance: "" };
const database = useAppStore((s) =>
resource ? s.databasesByName[resource.databaseFullName] : undefined
);
diff --git a/frontend/src/stores/app/database.test.ts b/frontend/src/stores/app/database.test.ts
new file mode 100644
index 0000000000..4d7739ae94
--- /dev/null
+++ b/frontend/src/stores/app/database.test.ts
@@ -0,0 +1,86 @@
+import { create } from "@bufbuild/protobuf";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import {
+ type BatchSyncDatabasesRequest,
+ DatabaseSchema$,
+} from "@/types/proto-es/v1/database_service_pb";
+import { InstanceSchema } from "@/types/proto-es/v1/instance_service_pb";
+import { createDatabaseSlice } from "./database";
+
+const mocks = vi.hoisted(() => ({
+ batchSyncDatabases: vi.fn(),
+ batchFetchProjects: vi.fn(),
+ removeDatabaseMetadataCache: vi.fn(),
+}));
+
+vi.mock("@/api", () => ({
+ databaseServiceClientConnect: {
+ batchSyncDatabases: mocks.batchSyncDatabases,
+ },
+}));
+
+const createStore = () => {
+ const state: Record<string, unknown> = {
+ batchFetchProjects: mocks.batchFetchProjects,
+ removeDatabaseMetadataCache: mocks.removeDatabaseMetadataCache,
+ };
+ const set = (updater: unknown) => {
+ const patch =
+ typeof updater === "function"
+ ? (updater as (value: typeof state) => object)(state)
+ : updater;
+ Object.assign(state, patch);
+ };
+ const get = () => state;
+ Object.assign(
+ state,
+ createDatabaseSlice(set as never, get as never, {} as never)
+ );
+ return state as ReturnType<typeof createDatabaseSlice>;
+};
+
+describe("database store project instance scope", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.batchSyncDatabases.mockResolvedValue({});
+ });
+
+ test("uses the cross-parent wildcard for batch schema sync", async () => {
+ const store = createStore();
+
+ await store.batchSyncDatabases([
+ "projects/app/instances/prod/databases/main",
+ ]);
+
+ const request = mocks.batchSyncDatabases.mock
+ .calls[0][0] as BatchSyncDatabasesRequest;
+ expect(request.parent).toBe("-");
+ });
+
+ test("updates only databases under the canonical project instance", () => {
+ const store = createStore();
+ store.databasesByName = {
+ "projects/app/instances/prod/databases/main": create(DatabaseSchema$, {
+ name: "projects/app/instances/prod/databases/main",
+ }),
+ "instances/prod/databases/main": create(DatabaseSchema$, {
+ name: "instances/prod/databases/main",
+ }),
+ };
+
+ store.updateDatabaseInstance(
+ create(InstanceSchema, {
+ name: "projects/app/instances/prod",
+ title: "Project production",
+ })
+ );
+
+ expect(
+ store.databasesByName["projects/app/instances/prod/databases/main"]
+ .instanceResource?.title
+ ).toBe("Project production");
+ expect(
+ store.databasesByName["instances/prod/databases/main"].instanceResource
+ ).toBeUndefined();
+ });
+});
diff --git a/frontend/src/stores/app/database.ts b/frontend/src/stores/app/database.ts
index 131dab2778..37651e3741 100644
--- a/frontend/src/stores/app/database.ts
+++ b/frontend/src/stores/app/database.ts
@@ -31,8 +31,13 @@ import { buildDatabaseFilter, toError } from "./utils";
// Inlined to keep the app store's load graph free of the Pinia `@/stores`
// barrel that `@/utils/v1/database` pulls in.
function instanceResourceNameFromDatabase(databaseName: string): string {
- const match = databaseName.match(/(?:^|\/)instances\/([^/]+)\/databases\//);
- return match ? `instances/${match[1]}` : "";
+ const match = databaseName.match(
+ /^(?:(projects\/[^/]+)\/)?instances\/([^/]+)\/databases\//
+ );
+ if (!match) return "";
+ return match[1]
+ ? `${match[1]}/instances/${match[2]}`
+ : `instances/${match[2]}`;
}
export const createDatabaseSlice: AppSliceCreator<DatabaseSlice> = (
@@ -227,7 +232,10 @@ export const createDatabaseSlice: AppSliceCreator<DatabaseSlice> = (
),
}
);
- if (parent.startsWith("instances/") && !skipCacheRemoval) {
+ if (
+ /^(?:projects\/[^/]+\/)?instances\/[^/]+$/.test(parent) &&
+ !skipCacheRemoval
+ ) {
get().removeCacheByInstance(parent);
}
const composed = await upsertDatabases(
@@ -255,7 +263,7 @@ export const createDatabaseSlice: AppSliceCreator<DatabaseSlice> = (
batchSyncDatabases: async (databases) => {
await databaseServiceClientConnect.batchSyncDatabases(
createProto(BatchSyncDatabasesRequestSchema, {
- parent: "instances/-",
+ parent: "-",
names: databases,
})
);
diff --git a/frontend/src/types/proto-es/v1/access_grant_service_pb.d.ts b/frontend/src/types/proto-es/v1/access_grant_service_pb.d.ts
index ea128bc216..a94c758d1c 100644
--- a/frontend/src/types/proto-es/v1/access_grant_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/access_grant_service_pb.d.ts
@@ -79,7 +79,7 @@ export declare type AccessGrant = Message<"bytebase.v1.AccessGrant"> & {
/**
* The target databases for this access grant.
- * Format: instances/{instance}/databases/{database}
+ * Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
*
* @generated from field: repeated string targets = 6;
*/
diff --git a/frontend/src/types/proto-es/v1/actuator_service_pb.d.ts b/frontend/src/types/proto-es/v1/actuator_service_pb.d.ts
index 0987793e42..bf18e96311 100644
--- a/frontend/src/types/proto-es/v1/actuator_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/actuator_service_pb.d.ts
@@ -74,7 +74,7 @@ export declare const SampleInfoSchema: GenMessage<SampleInfo>;
export declare type SampleInfo_Instance = Message<"bytebase.v1.SampleInfo.Instance"> & {
/**
* The provisioned sample instance.
- * Format: instances/{instance}
+ * Format: instances/{instance} or projects/{project}/instances/{instance}
*
* @generated from field: string instance = 1;
*/
diff --git a/frontend/src/types/proto-es/v1/database_service_pb.d.ts b/frontend/src/types/proto-es/v1/database_service_pb.d.ts
index acb0896870..4ccbc85469 100644
--- a/frontend/src/types/proto-es/v1/database_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/database_service_pb.d.ts
@@ -122,7 +122,7 @@ export declare type ListDatabasesRequest = Message<"bytebase.v1.ListDatabasesReq
* - environment: the environment full name in "environments/{id}" format, support "==" operator.
* - name: the database name, support ".contains()" operator.
* - project: the project full name in "projects/{id}" format, support "==" operator.
- * - instance: the instance full name in "instances/{id}" format, support "==" operator.
+ * - instance: the instance full name in "instances/{id}" or "projects/{project}/instances/{id}" format, support "==" operator.
* - engine: the database engine, check Engine enum for values. Support "==", "in [xx]", "!(in [xx])" operator.
* - exclude_unassigned: should be "true" or "false", will not show unassigned databases if it's true, support "==" operator.
* - table: filter by the database table, support "==" and ".contains()" operator.
@@ -133,6 +133,7 @@ export declare type ListDatabasesRequest = Message<"bytebase.v1.ListDatabasesReq
* environment == "" (find databases which environment is not set)
* project == "projects/{project resource id}"
* instance == "instances/{instance resource id}"
+ * instance == "projects/{project resource id}/instances/{instance resource id}"
* name.contains("database name")
* engine == "MYSQL"
* engine in ["MYSQL", "POSTGRES"]
diff --git a/frontend/src/types/proto-es/v1/iam_policy_pb.d.ts b/frontend/src/types/proto-es/v1/iam_policy_pb.d.ts
index 64bdc84237..af9750e9ba 100644
--- a/frontend/src/types/proto-es/v1/iam_policy_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/iam_policy_pb.d.ts
@@ -130,7 +130,7 @@ export declare type Binding = Message<"bytebase.v1.Binding"> & {
* The syntax and semantics of CEL are documented at https://github.com/google/cel-spec
*
* Support variables:
- * resource.database: the database full name in "instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator.
+ * resource.database: the canonical database full name in "instances/{instance}/databases/{database}" or "projects/{project}/instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator.
* resource.schema_name: the schema name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.
* resource.table_name: the table name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.
* resource.environment_id: the environment to allow the DDL/DML operation in the SQL Editor, only works for the role with bb.sql.ddl or bb.sql.dml permissions. Support "in" operator.
diff --git a/frontend/src/types/proto-es/v1/plan_service_pb.d.ts b/frontend/src/types/proto-es/v1/plan_service_pb.d.ts
index 09d16b2ad4..7cd5d4810d 100644
--- a/frontend/src/types/proto-es/v1/plan_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/plan_service_pb.d.ts
@@ -343,7 +343,7 @@ export declare const Plan_SpecSchema: GenMessage<Plan_Spec>;
export declare type Plan_CreateDatabaseConfig = Message<"bytebase.v1.Plan.CreateDatabaseConfig"> & {
/**
* The resource name of the instance on which the database is created.
- * Format: instances/{instance}
+ * Format: instances/{instance} or projects/{project}/instances/{instance}
*
* @generated from field: string target = 1;
*/
@@ -657,7 +657,7 @@ export declare type PlanCheckRun_Result = Message<"bytebase.v1.PlanCheckRun.Resu
/**
* Target identification for consolidated results.
- * Format: instances/{instance}/databases/{database}
+ * Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
*
* @generated from field: string target = 7;
*/
diff --git a/frontend/src/types/proto-es/v1/query_history_service_pb.d.ts b/frontend/src/types/proto-es/v1/query_history_service_pb.d.ts
index e2d2242268..07d911c932 100644
--- a/frontend/src/types/proto-es/v1/query_history_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/query_history_service_pb.d.ts
@@ -215,7 +215,7 @@ export declare type QueryHistory = Message<"bytebase.v1.QueryHistory"> & {
/**
* The database name to execute the query.
- * Format: instances/{instance}/databases/{databaseName}
+ * Format: instances/{instance}/databases/{databaseName} or projects/{project}/instances/{instance}/databases/{databaseName}
*
* @generated from field: string database = 2;
*/
diff --git a/frontend/src/types/proto-es/v1/rollout_service_pb.d.ts b/frontend/src/types/proto-es/v1/rollout_service_pb.d.ts
index 3d3c0e1529..f0530b7913 100644
--- a/frontend/src/types/proto-es/v1/rollout_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/rollout_service_pb.d.ts
@@ -482,8 +482,8 @@ export declare type Task = Message<"bytebase.v1.Task"> & {
type: Task_Type;
/**
- * Format: instances/{instance} if the task is DatabaseCreate.
- * Format: instances/{instance}/databases/{database}
+ * Format: instances/{instance} or projects/{project}/instances/{instance} if the task is DatabaseCreate.
+ * Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
*
* @generated from field: string target = 6;
*/
@@ -1336,7 +1336,7 @@ export declare const TaskRunLogEntry_PriorBackup_PriorBackupDetail_ItemSchema: G
export declare type TaskRunLogEntry_PriorBackup_PriorBackupDetail_Item_Table = Message<"bytebase.v1.TaskRunLogEntry.PriorBackup.PriorBackupDetail.Item.Table"> & {
/**
* The database information.
- * Format: instances/{instance}/databases/{database}
+ * Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
*
* @generated from field: string database = 1;
*/
diff --git a/frontend/src/types/proto-es/v1/saved_query_service_pb.d.ts b/frontend/src/types/proto-es/v1/saved_query_service_pb.d.ts
index 91acdd7f67..324694a3fb 100644
--- a/frontend/src/types/proto-es/v1/saved_query_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/saved_query_service_pb.d.ts
@@ -555,7 +555,7 @@ export declare type SavedQuery = Message<"bytebase.v1.SavedQuery"> & {
* The connected database, which must belong to the saved query's own
* project. Empty when none is connected, or when the database no longer
* exists.
- * Format: instances/{instance}/databases/{database}
+ * Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
*
* @generated from field: string database = 3;
*/
diff --git a/frontend/src/types/proto-es/v1/sql_service_pb.d.ts b/frontend/src/types/proto-es/v1/sql_service_pb.d.ts
index 623f3d9fc1..62d4a96789 100644
--- a/frontend/src/types/proto-es/v1/sql_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/sql_service_pb.d.ts
@@ -19,7 +19,8 @@ export declare const file_v1_sql_service: GenFile;
export declare type AdminExecuteRequest = Message<"bytebase.v1.AdminExecuteRequest"> & {
/**
* The name is the instance name to execute the query against.
- * Format: instances/{instance}/databases/{databaseName}
+ * Format: instances/{instance}/databases/{databaseName} or
+ * projects/{project}/instances/{instance}/databases/{databaseName}
*
* @generated from field: string name = 1;
*/
@@ -85,8 +86,9 @@ export declare const AdminExecuteResponseSchema: GenMessage<AdminExecuteResponse
*/
export declare type QueryRequest = Message<"bytebase.v1.QueryRequest"> & {
/**
- * The name is the instance name to execute the query against.
- * Format: instances/{instance}/databases/{databaseName}
+ * The name is the database resource name to execute the query against.
+ * Format: instances/{instance}/databases/{databaseName} or
+ * projects/{project}/instances/{instance}/databases/{databaseName}
*
* @generated from field: string name = 1;
*/
@@ -1000,8 +1002,8 @@ export declare const Advice_RuleTypeSchema: GenEnum<Advice_RuleType>;
export declare type ExportRequest = Message<"bytebase.v1.ExportRequest"> & {
/**
* The name is the resource name to execute the export against.
- * Format: instances/{instance}/databases/{database}
- * Format: instances/{instance}
+ * Format: instances/{instance}/databases/{database} or
+ * projects/{project}/instances/{instance}/databases/{database}
*
* @generated from field: string name = 1;
*/
diff --git a/frontend/src/types/proto-es/v1/sql_service_pb.js b/frontend/src/types/proto-es/v1/sql_service_pb.js
index 1d8185f77b..0b87d7a374 100644
--- a/frontend/src/types/proto-es/v1/sql_service_pb.js
+++ b/frontend/src/types/proto-es/v1/sql_service_pb.js
@@ -15,7 +15,7 @@ import { file_v1_query_history_service } from "./query_history_service_pb";
* Describes the file v1/sql_service.proto.
*/
export const file_v1_sql_service = /*@__PURE__*/
- fileDesc("ChR2MS9zcWxfc2VydmljZS5wcm90bxILYnl0ZWJhc2UudjEiqgEKE0FkbWluRXhlY3V0ZVJlcXVlc3QSKwoEbmFtZRgBIAEoCUId4EEC+kEXChVieXRlYmFzZS5jb20vRGF0YWJhc2USEQoJc3RhdGVtZW50GAIgASgJEg0KBWxpbWl0GAMgASgFEhMKBnNjaGVtYRgEIAEoCUgAiAEBEhYKCWNvbnRhaW5lchgFIAEoCUgBiAEBQgkKB19zY2hlbWFCDAoKX2NvbnRhaW5lciJBChRBZG1pbkV4ZWN1dGVSZXNwb25zZRIpCgdyZXN1bHRzGAEgAygLMhguYnl0ZWJhc2UudjEuUXVlcnlSZXN1bHQi/AEKDFF1ZXJ5UmVxdWVzdBIrCgRuYW1lGAEgASgJQh3gQQL6QRcKFWJ5dGViYXNlLmNvbS9EYXRhYmFzZRIRCglzdGF0ZW1lbnQYAiABKAkSDQoFbGltaXQYAyABKAUSFgoOZGF0YV9zb3VyY2VfaWQYBCABKAkSDwoHZXhwbGFpbhgFIAEoCBITCgZzY2hlbWEYBiABKAlIAIgBARIuCgxxdWVyeV9vcHRpb24YByABKAsyGC5ieXRlYmFzZS52MS5RdWVyeU9wdGlvbhIWCgljb250YWluZXIYCCABKAlIAYgBAUIJCgdfc2NoZW1hQgwKCl9jb250YWluZXIiWAoNUXVlcnlSZXNwb25zZRIpCgdyZXN1bHRzGAEgAygLMhguYnl0ZWJhc2UudjEuUXVlcnlSZXN1bHQSHAoUYXBwbGllZF9hY2Nlc3NfZ3JhbnQYAiABKAki+QIKC1F1ZXJ5T3B0aW9uEkoKFXJlZGlzX3J1bl9jb21tYW5kc19vbhgBIAEoDjIrLmJ5dGViYXNlLnYxLlF1ZXJ5T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HBvcnRSZXF1ZXN0GhsuYnl0ZWJhc2UudjEuRXhwb3J0UmVzcG9uc2UiVIrqMBBiYi5kYXRhYmFzZXMuZ2V0kOowAZjqMAGg6jACgtPkkwIuOgEqIikvdjEve25hbWU9aW5zdGFuY2VzLyovZGF0YWJhc2VzLyp9OmV4cG9ydEKlAQoPY29tLmJ5dGViYXNlLnYxQg9TcWxTZXJ2aWNlUHJvdG9QAVo0Z2l0aHViLmNvbS9ieXRlYmFzZS9ieXRlYmFzZS9iYWNrZW5kL2dlbmVyYXRlZC1nby92MaICA0JYWKoCC0J5dGViYXNlLlYxygILQnl0ZWJhc2VcVjHiAhdCeXRlYmFzZVxWMVxHUEJNZXRhZGF0YeoCDEJ5dGViYXNlOjpWMWIGcHJvdG8z", [file_google_api_annotations, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_duration, file_google_protobuf_struct, file_google_protobuf_timestamp, file_v1_annotation, file_v1_common, file_v1_query_history_service]);
+ fileDesc("ChR2MS9zcWxfc2VydmljZS5wcm90bxILYnl0ZWJhc2UudjEiqgEKE0FkbWluRXhlY3V0ZVJlcXVlc3QSKwoEbmFtZRgBIAEoCUId4EEC+kEXChVieXRlYmFzZS5jb20vRGF0YWJhc2USEQoJc3RhdGVtZW50GAIgASgJEg0KBWxpbWl0GAMgASgFEhMKBnNjaGVtYRgEIAEoCUgAiAEBEhYKCWNvbnRhaW5lchgFIAEoCUgBiAEBQgkKB19zY2hlbWFCDAoKX2NvbnRhaW5lciJBChRBZG1pbkV4ZWN1dGVSZXNwb25zZRIpCgdyZXN1bHRzGAEgAygLMhguYnl0ZWJhc2UudjEuUXVlcnlSZXN1bHQi/AEKDFF1ZXJ5UmVxdWVzdBIrCgRuYW1lGAEgASgJQh3gQQL6QRcKFWJ5dGViYXNlLmNvbS9EYXRhYmFzZRIRCglzdGF0ZW1lbnQYAiABKAkSDQoFbGltaXQYAyABKAUSFgoOZGF0YV9zb3VyY2VfaWQYBCABKAkSDwoHZXhwbGFpbhg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WJhc2UudjEuU2VhcmNoUXVlcnlIaXN0b3JpZXNSZXNwb25zZSILiAIBkOowAqDqMAESkAEKEkxpc3RRdWVyeUhpc3RvcmllcxImLmJ5dGViYXNlLnYxLkxpc3RRdWVyeUhpc3Rvcmllc1JlcXVlc3QaJy5ieXRlYmFzZS52MS5MaXN0UXVlcnlIaXN0b3JpZXNSZXNwb25zZSIpiAIBiuowFmJiLnF1ZXJ5SGlzdG9yaWVzLmxpc3SQ6jABoOowBKjqMAoSXgoPR2V0UXVlcnlIaXN0b3J5EiMuYnl0ZWJhc2UudjEuR2V0UXVlcnlIaXN0b3J5UmVxdWVzdBoZLmJ5dGViYXNlLnYxLlF1ZXJ5SGlzdG9yeSILiAIBkOowAqDqMAES0wEKBkV4cG9ydBIaLmJ5dGViYXNlLnYxLkV4cG9ydFJlcXVlc3QaGy5ieXRlYmFzZS52MS5FeHBvcnRSZXNwb25zZSKPAYrqMBBiYi5kYXRhYmFzZXMuZ2V0kOowAZjqMAGg6jACgtPkkwJpOgEqWjk6ASoiNC92MS97bmFtZT1wcm9qZWN0cy8qL2luc3RhbmNlcy8qL2RhdGFiYXNlcy8qfTpleHBvcnQiKS92MS97bmFtZT1pbnN0YW5jZXMvKi9kYXRhYmFzZXMvKn06ZXhwb3J0QqUBCg9jb20uYnl0ZWJhc2UudjFCD1NxbFNlcnZpY2VQcm90b1ABWjRnaXRodWIuY29tL2J5dGViYXNlL2J5dGViYXNlL2JhY2tlbmQvZ2VuZXJhdGVkLWdvL3YxogIDQlhYqgILQnl0ZWJhc2UuVjHKAgtCeXRlYmFzZVxWMeICF0J5dGViYXNlXFYxXEdQQk1ldGFkYXRh6gIMQnl0ZWJhc2U6OlYxYgZwcm90bzM", [file_google_api_annotations, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_duration, file_google_protobuf_struct, file_google_protobuf_timestamp, file_v1_annotation, file_v1_common, file_v1_query_history_service]);
/**
* Describes the message bytebase.v1.AdminExecuteRequest.
diff --git a/frontend/src/utils/v1/databaseResource.test.ts b/frontend/src/utils/v1/databaseResource.test.ts
new file mode 100644
index 0000000000..f08a17667a
--- /dev/null
+++ b/frontend/src/utils/v1/databaseResource.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, test } from "vitest";
+import { parseStringToResource } from "./databaseResource";
+
+describe("parseStringToResource", () => {
+ test.each([
+ [
+ "instances/prod/databases/app/schemas/public/tables/users/columns/id",
+ "instances/prod/databases/app",
+ ],
+ [
+ "projects/acme/instances/prod/databases/app/schemas/public/tables/users/columns/id",
+ "projects/acme/instances/prod/databases/app",
+ ],
+ ])("preserves the canonical database parent in %s", (name, database) => {
+ expect(parseStringToResource(name)).toEqual({
+ instanceResourceId: "prod",
+ databaseResourceId: "app",
+ databaseFullName: database,
+ schema: "public",
+ table: "users",
+ columns: ["id"],
+ });
+ });
+
+ test("rejects malformed project database names", () => {
+ expect(
+ parseStringToResource("projects/acme/databases/app")
+ ).toBeUndefined();
+ });
+});
diff --git a/frontend/src/utils/v1/databaseResource.ts b/frontend/src/utils/v1/databaseResource.ts
index 4e6d1beba8..2962fce4bc 100644
--- a/frontend/src/utils/v1/databaseResource.ts
+++ b/frontend/src/utils/v1/databaseResource.ts
@@ -187,28 +187,42 @@ export const flattenTreeOptions = (
export const parseStringToResource = (
key: string
): DatabaseResource | undefined => {
- // The key should in instances/{instance resource id}/databases/{database resource id}/schemas/{schema}/tables/{table}/columns/{column}
+ // The key starts with either instances/{instance} or
+ // projects/{project}/instances/{instance}, followed by a database and
+ // optional schema/table/column descendants.
const sections = key.split("/");
const resource: DatabaseResource = {
databaseFullName: "",
};
+ let projectName = "";
+ let instanceName = "";
while (sections.length > 0) {
- const keyword = sections.shift() as DatabaseResourceType | "instances";
+ const keyword = sections.shift() as
+ | DatabaseResourceType
+ | "projects"
+ | "instances";
const data = sections.shift() || "";
switch (keyword) {
+ case "projects":
+ if (!data) return;
+ projectName = `projects/${data}`;
+ break;
case "instances": {
resource.instanceResourceId = data;
+ instanceName = projectName
+ ? `${projectName}/instances/${data}`
+ : `${instanceNamePrefix}${data}`;
if (resource.databaseResourceId) {
- resource.databaseFullName = `${instanceNamePrefix}${resource.instanceResourceId}/${databaseNamePrefix}${resource.databaseResourceId}`;
+ resource.databaseFullName = `${instanceName}/${databaseNamePrefix}${resource.databaseResourceId}`;
}
break;
}
case "databases": {
resource.databaseResourceId = data;
- if (resource.instanceResourceId) {
- resource.databaseFullName = `${instanceNamePrefix}${resource.instanceResourceId}/${databaseNamePrefix}${resource.databaseResourceId}`;
+ if (instanceName) {
+ resource.databaseFullName = `${instanceName}/${databaseNamePrefix}${resource.databaseResourceId}`;
}
break;
}
diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yaml
index 3ffe14cb02..0e056b9ec4 100644
--- a/proto/gen/grpc-doc/openapi.yaml
+++ b/proto/gen/grpc-doc/openapi.yaml
@@ -2216,7 +2216,7 @@ paths:
- environment: the environment full name in "environments/{id}" format, support "==" operator.
- name: the database name, support ".contains()" operator.
- project: the project full name in "projects/{id}" format, support "==" operator.
- - instance: the instance full name in "instances/{id}" format, support "==" operator.
+ - instance: the instance full name in "instances/{id}" or "projects/{project}/instances/{id}" format, support "==" operator.
- engine: the database engine, check Engine enum for values. Support "==", "in [xx]", "!(in [xx])" operator.
- exclude_unassigned: should be "true" or "false", will not show unassigned databases if it's true, support "==" operator.
- table: filter by the database table, support "==" and ".contains()" operator.
@@ -2227,6 +2227,7 @@ paths:
environment == "" (find databases which environment is not set)
project == "projects/{project resource id}"
instance == "instances/{instance resource id}"
+ instance == "projects/{project resource id}/instances/{instance resource id}"
name.contains("database name")
engine == "MYSQL"
engine in ["MYSQL", "POSTGRES"]
@@ -6698,7 +6699,7 @@ paths:
- environment: the environment full name in "environments/{id}" format, support "==" operator.
- name: the database name, support ".contains()" operator.
- project: the project full name in "projects/{id}" format, support "==" operator.
- - instance: the instance full name in "instances/{id}" format, support "==" operator.
+ - instance: the instance full name in "instances/{id}" or "projects/{project}/instances/{id}" format, support "==" operator.
- engine: the database engine, check Engine enum for values. Support "==", "in [xx]", "!(in [xx])" operator.
- exclude_unassigned: should be "true" or "false", will not show unassigned databases if it's true, support "==" operator.
- table: filter by the database table, support "==" and ".contains()" operator.
@@ -6709,6 +6710,7 @@ paths:
environment == "" (find databases which environment is not set)
project == "projects/{project resource id}"
instance == "instances/{instance resource id}"
+ instance == "projects/{project resource id}/instances/{instance resource id}"
name.contains("database name")
engine == "MYSQL"
engine in ["MYSQL", "POSTGRES"]
@@ -7323,7 +7325,7 @@ paths:
- environment: the environment full name in "environments/{id}" format, support "==" operator.
- name: the database name, support ".contains()" operator.
- project: the project full name in "projects/{id}" format, support "==" operator.
- - instance: the instance full name in "instances/{id}" format, support "==" operator.
+ - instance: the instance full name in "instances/{id}" or "projects/{project}/instances/{id}" format, support "==" operator.
- engine: the database engine, check Engine enum for values. Support "==", "in [xx]", "!(in [xx])" operator.
- exclude_unassigned: should be "true" or "false", will not show unassigned databases if it's true, support "==" operator.
- table: filter by the database table, support "==" and ".contains()" operator.
@@ -7334,6 +7336,7 @@ paths:
environment == "" (find databases which environment is not set)
project == "projects/{project resource id}"
instance == "instances/{instance resource id}"
+ instance == "projects/{project resource id}/instances/{instance resource id}"
name.contains("database name")
engine == "MYSQL"
engine in ["MYSQL", "POSTGRES"]
@@ -9811,6 +9814,183 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/bytebase.v1.DiffSchemaResponse'
+ /v1/projects/{project}/instances/{instance}/databases/{database}:export:
+ post:
+ tags:
+ - SQLService
+ summary: Export
+ description: |-
+ Exports query results to a file format.
+ Permissions required: bb.databases.get
+ operationId: SQLService_Export2
+ parameters:
+ - name: project
+ in: path
+ description: The project id.
+ required: true
+ schema:
+ type: string
+ - name: instance
+ in: path
+ description: The instance id.
+ required: true
+ schema:
+ type: string
+ - name: database
+ in: path
+ description: The database id.
+ required: true
+ schema:
+ type: string
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ statement:
+ type: string
+ title: statement
+ description: The SQL statement to execute.
+ limit:
+ type: integer
+ title: limit
+ format: int32
+ description: The maximum number of rows to return.
+ format:
+ title: format
+ description: The export format.
+ $ref: '#/components/schemas/bytebase.v1.ExportFormat'
+ admin:
+ type: boolean
+ title: admin
+ description: |-
+ The admin is used for workspace owner and DBA for exporting data from SQL
+ Editor Admin mode. The exported data is not masked.
+ password:
+ type: string
+ title: password
+ description: The zip password provide by users.
+ dataSourceId:
+ type: string
+ title: data_source_id
+ description: |-
+ The id of data source.
+ If omitted, Export resolves the data source server-side by using the
+ single read-only data source when exactly one exists, or the admin data
+ source otherwise. It can also be set explicitly to export from the admin
+ data source or a specific read-only data source.
+ schema:
+ type:
+ - string
+ - "null"
+ title: schema
+ description: |-
+ The default schema to search objects. Equals to the current schema in
+ Oracle and search path in Postgres.
+ container:
+ type:
+ - string
+ - "null"
+ title: container
+ description: |-
+ Container is the container name to execute the query against, used for
+ CosmosDB only.
+ title: ExportRequest
+ additionalProperties: false
+ required: true
+ responses:
+ "200":
+ description: Success
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/bytebase.v1.ExportResponse'
+ /v1/projects/{project}/instances/{instance}/databases/{database}:query:
+ post:
+ tags:
+ - SQLService
+ summary: Query
+ description: |-
+ Executes a read-only SQL query against a database.
+ Permissions required: bb.databases.get
+ operationId: SQLService_Query2
+ parameters:
+ - name: project
+ in: path
+ description: The project id.
+ required: true
+ schema:
+ type: string
+ - name: instance
+ in: path
+ description: The instance id.
+ required: true
+ schema:
+ type: string
+ - name: database
+ in: path
+ description: The database id.
+ required: true
+ schema:
+ type: string
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ statement:
+ type: string
+ title: statement
+ description: The SQL statement to execute.
+ limit:
+ type: integer
+ title: limit
+ format: int32
+ description: The maximum number of rows to return.
+ dataSourceId:
+ type: string
+ title: data_source_id
+ description: |-
+ The id of data source.
+ If omitted, Query resolves the data source server-side by using the single
+ read-only data source when exactly one exists, or the admin data source
+ otherwise. It can also be set explicitly to query the admin data source or
+ a specific read-only data source.
+ explain:
+ type: boolean
+ title: explain
+ description: Explain the statement.
+ schema:
+ type:
+ - string
+ - "null"
+ title: schema
+ description: |-
+ The default schema to search objects. Equals to the current schema in
+ Oracle and search path in Postgres.
+ queryOption:
+ title: query_option
+ $ref: '#/components/schemas/bytebase.v1.QueryOption'
+ container:
+ type:
+ - string
+ - "null"
+ title: container
+ description: |-
+ Container is the container name to execute the query against, used for
+ CosmosDB only.
+ title: QueryRequest
+ additionalProperties: false
+ required: true
+ responses:
+ "200":
+ description: Success
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/bytebase.v1.QueryResponse'
/v1/projects/{project}/instances/{instance}/databases/{database}:sync:
post:
tags:
@@ -17941,7 +18121,7 @@ paths:
- environment: the environment full name in "environments/{id}" format, support "==" operator.
- name: the database name, support ".contains()" operator.
- project: the project full name in "projects/{id}" format, support "==" operator.
- - instance: the instance full name in "instances/{id}" format, support "==" operator.
+ - instance: the instance full name in "instances/{id}" or "projects/{project}/instances/{id}" format, support "==" operator.
- engine: the database engine, check Engine enum for values. Support "==", "in [xx]", "!(in [xx])" operator.
- exclude_unassigned: should be "true" or "false", will not show unassigned databases if it's true, support "==" operator.
- table: filter by the database table, support "==" and ".contains()" operator.
@@ -17952,6 +18132,7 @@ paths:
environment == "" (find databases which environment is not set)
project == "projects/{project resource id}"
instance == "instances/{instance resource id}"
+ instance == "projects/{project resource id}/instances/{instance resource id}"
name.contains("database name")
engine == "MYSQL"
engine in ["MYSQL", "POSTGRES"]
@@ -18802,7 +18983,8 @@ paths:
in: query
description: |-
The name is the instance name to execute the query against.
- Format: instances/{instance}/databases/{databaseName}
+ Format: instances/{instance}/databases/{databaseName} or
+ projects/{project}/instances/{instance}/databases/{databaseName}
required: true
schema:
type: string
@@ -19053,7 +19235,7 @@ components:
title: targets
description: |-
The target databases for this access grant.
- Format: instances/{instance}/databases/{database}
+ Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
query:
type: string
title: query
@@ -19296,7 +19478,8 @@ components:
title: name
description: |-
The name is the instance name to execute the query against.
- Format: instances/{instance}/databases/{databaseName}
+ Format: instances/{instance}/databases/{databaseName} or
+ projects/{project}/instances/{instance}/databases/{databaseName}
statement:
type: string
title: statement
@@ -20417,7 +20600,7 @@ components:
The syntax and semantics of CEL are documented at https://github.com/google/cel-spec
Support variables:
- resource.database: the database full name in "instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator.
+ resource.database: the canonical database full name in "instances/{instance}/databases/{database}" or "projects/{project}/instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator.
resource.schema_name: the schema name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.
resource.table_name: the table name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.
resource.environment_id: the environment to allow the DDL/DML operation in the SQL Editor, only works for the role with bb.sql.ddl or bb.sql.dml permissions. Support "in" operator.
@@ -22972,8 +23155,8 @@ components:
title: name
description: |-
The name is the resource name to execute the export against.
- Format: instances/{instance}/databases/{database}
- Format: instances/{instance}
+ Format: instances/{instance}/databases/{database} or
+ projects/{project}/instances/{instance}/databases/{database}
statement:
type: string
title: statement
@@ -24928,7 +25111,7 @@ components:
- environment: the environment full name in "environments/{id}" format, support "==" operator.
- name: the database name, support ".contains()" operator.
- project: the project full name in "projects/{id}" format, support "==" operator.
- - instance: the instance full name in "instances/{id}" format, support "==" operator.
+ - instance: the instance full name in "instances/{id}" or "projects/{project}/instances/{id}" format, support "==" operator.
- engine: the database engine, check Engine enum for values. Support "==", "in [xx]", "!(in [xx])" operator.
- exclude_unassigned: should be "true" or "false", will not show unassigned databases if it's true, support "==" operator.
- table: filter by the database table, support "==" and ".contains()" operator.
@@ -24939,6 +25122,7 @@ components:
environment == "" (find databases which environment is not set)
project == "projects/{project resource id}"
instance == "instances/{instance resource id}"
+ instance == "projects/{project resource id}/instances/{instance resource id}"
name.contains("database name")
engine == "MYSQL"
engine in ["MYSQL", "POSTGRES"]
@@ -27268,7 +27452,7 @@ components:
title: target
description: |-
The resource name of the instance on which the database is created.
- Format: instances/{instance}
+ Format: instances/{instance} or projects/{project}/instances/{instance}
database:
type: string
title: database
@@ -27423,7 +27607,7 @@ components:
title: target
description: |-
Target identification for consolidated results.
- Format: instances/{instance}/databases/{database}
+ Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
type:
title: type
$ref: '#/components/schemas/bytebase.v1.PlanCheckRun.Result.Type'
@@ -28096,7 +28280,7 @@ components:
title: database
description: |-
The database name to execute the query.
- Format: instances/{instance}/databases/{databaseName}
+ Format: instances/{instance}/databases/{databaseName} or projects/{project}/instances/{instance}/databases/{databaseName}
readOnly: true
creator:
type: string
@@ -28164,8 +28348,9 @@ components:
type: string
title: name
description: |-
- The name is the instance name to execute the query against.
- Format: instances/{instance}/databases/{databaseName}
+ The name is the database resource name to execute the query against.
+ Format: instances/{instance}/databases/{databaseName} or
+ projects/{project}/instances/{instance}/databases/{databaseName}
statement:
type: string
title: statement
@@ -29550,7 +29735,7 @@ components:
title: instance
description: |-
The provisioned sample instance.
- Format: instances/{instance}
+ Format: instances/{instance} or projects/{project}/instances/{instance}
readOnly: true
expireTime:
title: expire_time
@@ -29581,7 +29766,7 @@ components:
The connected database, which must belong to the saved query's own
project. Empty when none is connected, or when the database no longer
exists.
- Format: instances/{instance}/databases/{database}
+ Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
title:
type: string
title: title
@@ -31343,8 +31528,8 @@ components:
type: string
title: target
description: |-
- Format: instances/{instance} if the task is DatabaseCreate.
- Format: instances/{instance}/databases/{database}
+ Format: instances/{instance} or projects/{project}/instances/{instance} if the task is DatabaseCreate.
+ Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
updateTime:
oneOf:
- $ref: '#/components/schemas/google.protobuf.Timestamp'
@@ -31832,7 +32017,7 @@ components:
title: database
description: |-
The database information.
- Format: instances/{instance}/databases/{database}
+ Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
schema:
type: string
title: schema
diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.md
index 0832bc33f1..06b9d5d835 100644
--- a/proto/gen/grpc-doc/v1/README.md
+++ b/proto/gen/grpc-doc/v1/README.md
@@ -957,7 +957,7 @@ The line against FORBIDDEN is reversibility. An admin-capable ceiling, if one is
| expire_time | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | The expiration time of the access grant. |
| ttl | [google.protobuf.Duration](#google-protobuf-Duration) | | Input only. The time-to-live duration for the access grant. The server computes `expire_time` from this value at activation time. |
| issue | [string](#string) | | The issue associated with the access grant. Can be empty. Format: projects/{project}/issues/{issue} |
-| targets | [string](#string) | repeated | The target databases for this access grant. Format: instances/{instance}/databases/{database} |
+| targets | [string](#string) | repeated | The target databases for this access grant. Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database} |
| query | [string](#string) | | The query permission granted. |
| unmask | [bool](#bool) | | Whether the grant allows unmasking sensitive data. |
| create_time | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | |
@@ -1214,7 +1214,7 @@ Instance describes one provisioned sample instance.
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
-| instance | [string](#string) | | The provisioned sample instance. Format: instances/{instance} |
+| instance | [string](#string) | | The provisioned sample instance. Format: instances/{instance} or projects/{project}/instances/{instance} |
| expire_time | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | The time when the provisioned sample instance expires. |
@@ -1692,7 +1692,7 @@ Binding associates members with a role and optional conditions.
| members | [string](#string) | repeated | Specifies the principals requesting access for a Bytebase resource. For users, the member should be: user:{email} For groups, the member should be: group:{email} For service accounts, the member should be: serviceAccount:{email} For workload identities, the member should be: workloadIdentity:{email} |
| condition | [google.type.Expr](#google-type-Expr) | | The condition that is associated with this binding, only used in the project IAM policy. If the condition evaluates to true, then this binding applies to the current request. If the condition evaluates to false, then this binding does not apply to the current request. However, a different role binding might grant the same role to one or more of the principals in this binding. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec
-Support variables: resource.database: the database full name in &#34;instances/{instance}/databases/{database}&#34; format, used by any role with SQL Editor read (e.g. &#34;roles/sqlEditorUser&#34;, &#34;roles/sqlEditorReadUser&#34;) or write (bb.sql.ddl / bb.sql.dml) access, support &#34;==&#34; operator. resource.schema_name: the schema name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support &#34;==&#34; operator. resource.table_name: the table name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support &#34;==&#34; operator. resource.environment_id: the environment to allow the DDL/DML operation in the SQL Editor, only works for the role with bb.sql.ddl or bb.sql.dml permissions. Support &#34;in&#34; operator. request.time: the expiration. Only support &#34;&lt;&#34; operation in `request.time &lt; timestamp(&#34;{ISO datetime string format}&#34;)`.
+Support variables: resource.database: the canonical database full name in &#34;instances/{instance}/databases/{database}&#34; or &#34;projects/{project}/instances/{instance}/databases/{database}&#34; format, used by any role with SQL Editor read (e.g. &#34;roles/sqlEditorUser&#34;, &#34;roles/sqlEditorReadUser&#34;) or write (bb.sql.ddl / bb.sql.dml) access, support &#34;==&#34; operator. resource.schema_name: the schema name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support &#34;==&#34; operator. resource.table_name: the table name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support &#34;==&#34; operator. resource.environment_id: the environment to allow the DDL/DML operation in the SQL Editor, only works for the role with bb.sql.ddl or bb.sql.dml permissions. Support &#34;in&#34; operator. request.time: the expiration. Only support &#34;&lt;&#34; operation in `request.time &lt; timestamp(&#34;{ISO datetime string format}&#34;)`.
Known limitations of table/schema-scoped DDL/DML grants: - The scope only gates the write target, not the read sources of a write: e.g. `INSERT INTO granted_table SELECT * FROM other_table` may read `other_table` without a grant on it, so a table-scoped write grant is not an exfiltration boundary. - It must be paired with a database/project-level read grant: a table-scoped grant alone does not satisfy the SQL Editor query method permission (bb.databases.get). - A resource.schema_name-scoped grant only authorizes a write whose schema is unambiguous — qualify the table (schema.table) or select the schema for the SQL Editor session. An unqualified write whose effective schema cannot be determined ahead of execution is denied (qualify it, or use a table-only grant). - Multi-statement batches are authorized at the database level: an earlier statement can rebind the session&#39;s default schema or database mid-batch, so per-table/schema scoping is dropped and a table/schema-scoped grant requires a database-level grant. The database-level check is still per target database — a qualified cross-database write is gated by a grant on its own database, not the request database — but an unqualified write whose session default is rebound mid-batch is evaluated against the database it literally names, so qualify cross-database writes or run them as single statements. - A write target in a different project than the SQL-Editor session&#39;s database is denied: the per-target check evaluates the session project&#39;s IAM policy, so a cross-project write is failed closed (to write it, open the SQL Editor on a database in the target project). - Enforcement is on the statement&#39;s literal write target; writes routed elsewhere by a view/synonym, or into a temporary schema (e.g. pg_temp), are evaluated against what the statement names, not the ultimate base object. - Write-target gating uses an ALLOWLIST of statement types the resolver models. It does NOT cover every syntactically-identifiable cross-database write; statement types off the allowlist are authorized against the request database. The allowlist is: - Modeled table/data writes (per-table/schema-scopable): INSERT/UPDATE/DELETE/TRUNCATE/MERGE, LOAD DATA, IMPORT INTO, CREATE TABLE AS / SELECT INTO, and table-level CREATE/DROP/ALTER/RENAME/index. - Modeled non-table object DDL (gated at the DATABASE level by the object&#39;s own explicit database/schema qualifier; an unqualified name keeps the request-database check): CREATE/ALTER/DROP of view, procedure/function/routine, trigger, sequence, synonym, type, and (Oracle) package and cluster; plus Oracle ALTER/DROP MATERIALIZED VIEW (Oracle CREATE MATERIALIZED VIEW is not modeled — see below). NOT modeled (these fall back to the request-database check, so a qualified cross-database one is authorized against the request database): MySQL CREATE TRIGGER and CREATE/ALTER/DROP EVENT (bare-string AST names); MSSQL ALTER of view/procedure/function/trigger (no ALTER node in the grammar); Oracle CREATE MATERIALIZED VIEW and the niche object DDL — dimension, attribute dimension, hierarchy, analytic view, JSON duality view, materialized zonemap, operator, in-memory join group, property graph, vector index, index type, domain; COPY ... FROM; and engine-specific bulk-load / deprecated text writes. A structural &#34;write-target object database&#34; extraction layer to remove this allowlist dependence is tracked as a follow-up. - Out of scope (read sources / indirect effects): the tables a write READS (INSERT … SELECT, MERGE … USING, CREATE TABLE AS … SELECT) and objects reached indirectly via views/synonyms/function bodies/triggers are NOT gated. Invariant: for a statement ON the modeled allowlist that explicitly names a different database as its write target, the ACL uses that target database, not the request database. Statement types OFF the allowlist are authorized against the request database.
@@ -2321,7 +2321,7 @@ For example: update_time &gt;= &#34;2025-01-02T15:04:05Z07:00&#34; task_type in
| status | [Task.Status](#bytebase-v1-Task-Status) | | Status is the status of the task. |
| skipped_reason | [string](#string) | | The reason why the task was skipped. |
| type | [Task.Type](#bytebase-v1-Task-Type) | | |
-| target | [string](#string) | | Format: instances/{instance} if the task is DatabaseCreate. Format: instances/{instance}/databases/{database} |
+| target | [string](#string) | | Format: instances/{instance} or projects/{project}/instances/{instance} if the task is DatabaseCreate. Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database} |
| database_create | [Task.DatabaseCreate](#bytebase-v1-Task-DatabaseCreate) | | |
| database_update | [Task.DatabaseUpdate](#bytebase-v1-Task-DatabaseUpdate) | | |
| update_time | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | optional | The update_time is the update time of latest task run. If there are no task runs, it will be empty. |
@@ -2606,7 +2606,7 @@ Table information.
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
-| database | [string](#string) | | The database information. Format: instances/{instance}/databases/{database} |
+| database | [string](#string) | | The database information. Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database} |
| schema | [string](#string) | | The schema name. |
| table | [string](#string) | | The table name. |
@@ -2923,7 +2923,7 @@ For example: creator == &#34;users/{email}&#34; |
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| name | [string](#string) | | The name for the query history. Format: projects/{project}/queryHistories/{id} |
-| database | [string](#string) | | The database name to execute the query. Format: instances/{instance}/databases/{databaseName} |
+| database | [string](#string) | | The database name to execute the query. Format: instances/{instance}/databases/{databaseName} or projects/{project}/instances/{instance}/databases/{databaseName} |
| creator | [string](#string) | | |
| create_time | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | |
| statement | [string](#string) | | |
@@ -3023,7 +3023,7 @@ QueryHistoryService manages query history records of SQL Editor queries and expo
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
-| name | [string](#string) | | The name is the instance name to execute the query against. Format: instances/{instance}/databases/{databaseName} |
+| name | [string](#string) | | The name is the instance name to execute the query against. Format: instances/{instance}/databases/{databaseName} or projects/{project}/instances/{instance}/databases/{databaseName} |
| statement | [string](#string) | | The SQL statement to execute. |
| limit | [int32](#int32) | | The maximum number of rows to return. |
| schema | [string](#string) | optional | The default schema to execute the statement. Equals to the current schema in Oracle and search path in Postgres. |
@@ -3078,7 +3078,7 @@ QueryHistoryService manages query history records of SQL Editor queries and expo
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
-| name | [string](#string) | | The name is the resource name to execute the export against. Format: instances/{instance}/databases/{database} Format: instances/{instance} |
+| name | [string](#string) | | The name is the resource name to execute the export against. Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database} |
| statement | [string](#string) | | The SQL statement to execute. |
| limit | [int32](#int32) | | The maximum number of rows to return. |
| format | [ExportFormat](#bytebase-v1-ExportFormat) | | The export format. |
@@ -3154,7 +3154,7 @@ QueryHistoryService manages query history records of SQL Editor queries and expo
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
-| name | [string](#string) | | The name is the instance name to execute the query against. Format: instances/{instance}/databases/{databaseName} |
+| name | [string](#string) | | The name is the database resource name to execute the query against. Format: instances/{instance}/databases/{databaseName} or projects/{project}/instances/{instance}/databases/{databaseName} |
| statement | [string](#string) | | The SQL statement to execute. |
| limit | [int32](#int32) | | The maximum number of rows to return. |
| data_source_id | [string](#string) | | The id of data source. If omitted, Query resolves the data source server-side by using the single read-only data source when exactly one exists, or the admin data source otherwise. It can also be set explicitly to query the admin data source or a specific read-only data source. |
@@ -3646,7 +3646,7 @@ For example: creator == &#34;users/[email protected]&#34; &amp;&amp; create_time &
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
-| target | [string](#string) | | The resource name of the instance on which the database is created. Format: instances/{instance} |
+| target | [string](#string) | | The resource name of the instance on which the database is created. Format: instances/{instance} or projects/{project}/instances/{instance} |
| database | [string](#string) | | The name of the database to create. |
| table | [string](#string) | | table is the name of the table, if it is not empty, Bytebase should create a table after creating the database. For example, in MongoDB, it only creates the database when we first store data in that database. |
| character_set | [string](#string) | | character_set is the character set of the database. |
@@ -3756,7 +3756,7 @@ For example: creator == &#34;users/[email protected]&#34; &amp;&amp; create_time &
| title | [string](#string) | | |
| content | [string](#string) | | |
| code | [int32](#int32) | | |
-| target | [string](#string) | | Target identification for consolidated results. Format: instances/{instance}/databases/{database} |
+| target | [string](#string) | | Target identification for consolidated results. Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database} |
| type | [PlanCheckRun.Result.Type](#bytebase-v1-PlanCheckRun-Result-Type) | | |
| sql_summary_report | [PlanCheckRun.Result.SqlSummaryReport](#bytebase-v1-PlanCheckRun-Result-SqlSummaryReport) | | |
| sql_review_report | [PlanCheckRun.Result.SqlReviewReport](#bytebase-v1-PlanCheckRun-Result-SqlReviewReport) | | |
@@ -8332,9 +8332,9 @@ IndexMetadata is the metadata for indexes.
When paginating, all other parameters provided to `ListDatabases` must match the call that provided the page token. |
| filter | [string](#string) | | Filter is used to filter databases returned in the list. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec
-Supported filter: - environment: the environment full name in &#34;environments/{id}&#34; format, support &#34;==&#34; operator. - name: the database name, support &#34;.contains()&#34; operator. - project: the project full name in &#34;projects/{id}&#34; format, support &#34;==&#34; operator. - instance: the instance full name in &#34;instances/{id}&#34; format, support &#34;==&#34; operator. - engine: the database engine, check Engine enum for values. Support &#34;==&#34;, &#34;in [xx]&#34;, &#34;!(in [xx])&#34; operator. - exclude_unassigned: should be &#34;true&#34; or &#34;false&#34;, will not show unassigned databases if it&#39;s true, support &#34;==&#34; operator. - table: filter by the database table, support &#34;==&#34; and &#34;.contains()&#34; operator. - labels.{key}: the database label, support &#34;==&#34; and &#34;in&#34; operators.
+Supported filter: - environment: the environment full name in &#34;environments/{id}&#34; format, support &#34;==&#34; operator. - name: the database name, support &#34;.contains()&#34; operator. - project: the project full name in &#34;projects/{id}&#34; format, support &#34;==&#34; operator. - instance: the instance full name in &#34;instances/{id}&#34; or &#34;projects/{project}/instances/{id}&#34; format, support &#34;==&#34; operator. - engine: the database engine, check Engine enum for values. Support &#34;==&#34;, &#34;in [xx]&#34;, &#34;!(in [xx])&#34; operator. - exclude_unassigned: should be &#34;true&#34; or &#34;false&#34;, will not show unassigned databases if it&#39;s true, support &#34;==&#34; operator. - table: filter by the database table, support &#34;==&#34; and &#34;.contains()&#34; operator. - labels.{key}: the database label, support &#34;==&#34; and &#34;in&#34; operators.
-For example: environment == &#34;environments/{environment resource id}&#34; environment == &#34;&#34; (find databases which environment is not set) project == &#34;projects/{project resource id}&#34; instance == &#34;instances/{instance resource id}&#34; name.contains(&#34;database name&#34;) engine == &#34;MYSQL&#34; engine in [&#34;MYSQL&#34;, &#34;POSTGRES&#34;] !(engine in [&#34;MYSQL&#34;, &#34;POSTGRES&#34;]) exclude_unassigned == true table == &#34;sample&#34; table.contains(&#34;sam&#34;) labels.environment == &#34;production&#34; labels.region == &#34;asia&#34; labels.region in [&#34;asia&#34;, &#34;europe&#34;]
+For example: environment == &#34;environments/{environment resource id}&#34; environment == &#34;&#34; (find databases which environment is not set) project == &#34;projects/{project resource id}&#34; instance == &#34;instances/{instance resource id}&#34; instance == &#34;projects/{project resource id}/instances/{instance resource id}&#34; name.contains(&#34;database name&#34;) engine == &#34;MYSQL&#34; engine in [&#34;MYSQL&#34;, &#34;POSTGRES&#34;] !(engine in [&#34;MYSQL&#34;, &#34;POSTGRES&#34;]) exclude_unassigned == true table == &#34;sample&#34; table.contains(&#34;sam&#34;) labels.environment == &#34;production&#34; labels.region == &#34;asia&#34; labels.region in [&#34;asia&#34;, &#34;europe&#34;]
You can combine filter conditions like: environment == &#34;environments/prod&#34; &amp;&amp; name.contains(&#34;employee&#34;) |
| show_deleted | [bool](#bool) | | Show deleted database if specified. |
@@ -11496,7 +11496,7 @@ For example: creator == &#34;users/[email protected]&#34; |
| ----- | ---- | ----- | ----------- |
| name | [string](#string) | | Server-generated. Format: projects/{project}/savedQueries/{savedQuery} |
| project | [string](#string) | | Format: projects/{project} |
-| database | [string](#string) | | The connected database, which must belong to the saved query&#39;s own project. Empty when none is connected, or when the database no longer exists. Format: instances/{instance}/databases/{database} |
+| database | [string](#string) | | The connected database, which must belong to the saved query&#39;s own project. Empty when none is connected, or when the database no longer exists. Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database} |
| title | [string](#string) | | The title of the saved query. |
| creator | [string](#string) | | The owner. Ownership does not transfer. Format: users/{email} |
| create_time | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | |
diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.html
index 7caf289fd2..38fe7a7c03 100644
--- a/proto/gen/grpc-doc/v1/index.html
+++ b/proto/gen/grpc-doc/v1/index.html
@@ -3669,7 +3669,7 @@ Format: projects/{project}/issues/{issue} </p></td>
<td><a href="#string">string</a></td>
<td>repeated</td>
<td><p>The target databases for this access grant.
-Format: instances/{instance}/databases/{database} </p></td>
+Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database} </p></td>
</tr>
<tr>
@@ -4398,7 +4398,7 @@ Format: projects/{id} </p></td>
<td><a href="#string">string</a></td>
<td></td>
<td><p>The provisioned sample instance.
-Format: instances/{instance} </p></td>
+Format: instances/{instance} or projects/{project}/instances/{instance} </p></td>
</tr>
<tr>
@@ -5708,7 +5708,7 @@ If the condition evaluates to false, then this binding does not apply to the cur
The syntax and semantics of CEL are documented at https://github.com/google/cel-spec
Support variables:
-resource.database: the database full name in &#34;instances/{instance}/databases/{database}&#34; format, used by any role with SQL Editor read (e.g. &#34;roles/sqlEditorUser&#34;, &#34;roles/sqlEditorReadUser&#34;) or write (bb.sql.ddl / bb.sql.dml) access, support &#34;==&#34; operator.
+resource.database: the canonical database full name in &#34;instances/{instance}/databases/{database}&#34; or &#34;projects/{project}/instances/{instance}/databases/{database}&#34; format, used by any role with SQL Editor read (e.g. &#34;roles/sqlEditorUser&#34;, &#34;roles/sqlEditorReadUser&#34;) or write (bb.sql.ddl / bb.sql.dml) access, support &#34;==&#34; operator.
resource.schema_name: the schema name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support &#34;==&#34; operator.
resource.table_name: the table name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support &#34;==&#34; operator.
resource.environment_id: the environment to allow the DDL/DML operation in the SQL Editor, only works for the role with bb.sql.ddl or bb.sql.dml permissions. Support &#34;in&#34; operator.
@@ -7176,8 +7176,8 @@ Format: environments/{environment} for valid environments, or &#34;environments/
<td>target</td>
<td><a href="#string">string</a></td>
<td></td>
- <td><p>Format: instances/{instance} if the task is DatabaseCreate.
-Format: instances/{instance}/databases/{database} </p></td>
+ <td><p>Format: instances/{instance} or projects/{project}/instances/{instance} if the task is DatabaseCreate.
+Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database} </p></td>
</tr>
<tr>
@@ -7886,7 +7886,7 @@ Example: For &#34;SELECT 你好;&#34; in a UTF-8 sheet, range [0, 13) represents
<td><a href="#string">string</a></td>
<td></td>
<td><p>The database information.
-Format: instances/{instance}/databases/{database} </p></td>
+Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database} </p></td>
</tr>
<tr>
@@ -8873,7 +8873,7 @@ Format: projects/{project}/queryHistories/{id} </p></td>
<td><a href="#string">string</a></td>
<td></td>
<td><p>The database name to execute the query.
-Format: instances/{instance}/databases/{databaseName} </p></td>
+Format: instances/{instance}/databases/{databaseName} or projects/{project}/instances/{instance}/databases/{databaseName} </p></td>
</tr>
<tr>
@@ -9170,7 +9170,8 @@ Permissions required: None (only returns the caller&#39;s own query history)</p>
<td><a href="#string">string</a></td>
<td></td>
<td><p>The name is the instance name to execute the query against.
-Format: instances/{instance}/databases/{databaseName} </p></td>
+Format: instances/{instance}/databases/{databaseName} or
+projects/{project}/instances/{instance}/databases/{databaseName} </p></td>
</tr>
<tr>
@@ -9316,8 +9317,8 @@ TODO: use range instead </p></td>
<td><a href="#string">string</a></td>
<td></td>
<td><p>The name is the resource name to execute the export against.
-Format: instances/{instance}/databases/{database}
-Format: instances/{instance} </p></td>
+Format: instances/{instance}/databases/{database} or
+projects/{project}/instances/{instance}/databases/{database} </p></td>
</tr>
<tr>
@@ -9534,8 +9535,9 @@ Empty when the user was authorized through normal ACL rather than a grant. </p><
<td>name</td>
<td><a href="#string">string</a></td>
<td></td>
- <td><p>The name is the instance name to execute the query against.
-Format: instances/{instance}/databases/{databaseName} </p></td>
+ <td><p>The name is the database resource name to execute the query against.
+Format: instances/{instance}/databases/{databaseName} or
+projects/{project}/instances/{instance}/databases/{databaseName} </p></td>
</tr>
<tr>
@@ -10513,6 +10515,13 @@ Permissions required: bb.databases.get</p></td>
<td>*</td>
</tr>
+ <tr>
+ <td>Query</td>
+ <td>POST</td>
+ <td>/v1/{name=projects/*/instances/*/databases/*}:query</td>
+ <td>*</td>
+ </tr>
+
@@ -10533,6 +10542,13 @@ Permissions required: bb.databases.get</p></td>
<td>*</td>
</tr>
+ <tr>
+ <td>Export</td>
+ <td>POST</td>
+ <td>/v1/{name=projects/*/instances/*/databases/*}:export</td>
+ <td>*</td>
+ </tr>
+
</tbody>
</table>
@@ -10953,7 +10969,7 @@ Format: projects/{project}/releases/{release} </p></td>
<td><a href="#string">string</a></td>
<td></td>
<td><p>The resource name of the instance on which the database is created.
-Format: instances/{instance} </p></td>
+Format: instances/{instance} or projects/{project}/instances/{instance} </p></td>
</tr>
<tr>
@@ -11241,7 +11257,7 @@ Format: projects/{project}/plans/{plan}/rollout/stages/{stage} </p></td>
<td><a href="#string">string</a></td>
<td></td>
<td><p>Target identification for consolidated results.
-Format: instances/{instance}/databases/{database} </p></td>
+Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database} </p></td>
</tr>
<tr>
@@ -23536,7 +23552,7 @@ Supported filter:
- environment: the environment full name in &#34;environments/{id}&#34; format, support &#34;==&#34; operator.
- name: the database name, support &#34;.contains()&#34; operator.
- project: the project full name in &#34;projects/{id}&#34; format, support &#34;==&#34; operator.
-- instance: the instance full name in &#34;instances/{id}&#34; format, support &#34;==&#34; operator.
+- instance: the instance full name in &#34;instances/{id}&#34; or &#34;projects/{project}/instances/{id}&#34; format, support &#34;==&#34; operator.
- engine: the database engine, check Engine enum for values. Support &#34;==&#34;, &#34;in [xx]&#34;, &#34;!(in [xx])&#34; operator.
- exclude_unassigned: should be &#34;true&#34; or &#34;false&#34;, will not show unassigned databases if it&#39;s true, support &#34;==&#34; operator.
- table: filter by the database table, support &#34;==&#34; and &#34;.contains()&#34; operator.
@@ -23547,6 +23563,7 @@ environment == &#34;environments/{environment resource id}&#34;
environment == &#34;&#34; (find databases which environment is not set)
project == &#34;projects/{project resource id}&#34;
instance == &#34;instances/{instance resource id}&#34;
+instance == &#34;projects/{project resource id}/instances/{instance resource id}&#34;
name.contains(&#34;database name&#34;)
engine == &#34;MYSQL&#34;
engine in [&#34;MYSQL&#34;, &#34;POSTGRES&#34;]
@@ -32713,7 +32730,7 @@ Format: projects/{project}/savedQueries/{savedQuery} </p></td>
<td><p>The connected database, which must belong to the saved query&#39;s own
project. Empty when none is connected, or when the database no longer
exists.
-Format: instances/{instance}/databases/{database} </p></td>
+Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database} </p></td>
</tr>
<tr>
@@ -37096,4 +37113,3 @@ Permissions required: bb.workspaces.rotateDirectorySyncToken</p></td>
</table>
</body>
</html>
-
diff --git a/proto/v1/v1/access_grant_service.proto b/proto/v1/v1/access_grant_service.proto
index 51a7334307..edb43201d0 100644
--- a/proto/v1/v1/access_grant_service.proto
+++ b/proto/v1/v1/access_grant_service.proto
@@ -127,7 +127,7 @@ message AccessGrant {
string issue = 5 [(google.api.field_behavior) = OUTPUT_ONLY];
// The target databases for this access grant.
- // Format: instances/{instance}/databases/{database}
+ // Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
repeated string targets = 6 [(google.api.field_behavior) = REQUIRED];
// The query permission granted.
diff --git a/proto/v1/v1/actuator_service.proto b/proto/v1/v1/actuator_service.proto
index 35d804b306..741b7cb0dd 100644
--- a/proto/v1/v1/actuator_service.proto
+++ b/proto/v1/v1/actuator_service.proto
@@ -49,7 +49,7 @@ message SampleInfo {
// Instance describes one provisioned sample instance.
message Instance {
// The provisioned sample instance.
- // Format: instances/{instance}
+ // Format: instances/{instance} or projects/{project}/instances/{instance}
string instance = 1 [
(google.api.field_behavior) = OUTPUT_ONLY,
(google.api.resource_reference) = {type: "bytebase.com/Instance"}
diff --git a/proto/v1/v1/database_service.proto b/proto/v1/v1/database_service.proto
index 0499a7ac78..e241aec177 100644
--- a/proto/v1/v1/database_service.proto
+++ b/proto/v1/v1/database_service.proto
@@ -282,7 +282,7 @@ message ListDatabasesRequest {
// - environment: the environment full name in "environments/{id}" format, support "==" operator.
// - name: the database name, support ".contains()" operator.
// - project: the project full name in "projects/{id}" format, support "==" operator.
- // - instance: the instance full name in "instances/{id}" format, support "==" operator.
+ // - instance: the instance full name in "instances/{id}" or "projects/{project}/instances/{id}" format, support "==" operator.
// - engine: the database engine, check Engine enum for values. Support "==", "in [xx]", "!(in [xx])" operator.
// - exclude_unassigned: should be "true" or "false", will not show unassigned databases if it's true, support "==" operator.
// - table: filter by the database table, support "==" and ".contains()" operator.
@@ -293,6 +293,7 @@ message ListDatabasesRequest {
// environment == "" (find databases which environment is not set)
// project == "projects/{project resource id}"
// instance == "instances/{instance resource id}"
+ // instance == "projects/{project resource id}/instances/{instance resource id}"
// name.contains("database name")
// engine == "MYSQL"
// engine in ["MYSQL", "POSTGRES"]
diff --git a/proto/v1/v1/iam_policy.proto b/proto/v1/v1/iam_policy.proto
index e41b297515..21a9301ed5 100644
--- a/proto/v1/v1/iam_policy.proto
+++ b/proto/v1/v1/iam_policy.proto
@@ -67,7 +67,7 @@ message Binding {
// The syntax and semantics of CEL are documented at https://github.com/google/cel-spec
//
// Support variables:
- // resource.database: the database full name in "instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator.
+ // resource.database: the canonical database full name in "instances/{instance}/databases/{database}" or "projects/{project}/instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator.
// resource.schema_name: the schema name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.
// resource.table_name: the table name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.
// resource.environment_id: the environment to allow the DDL/DML operation in the SQL Editor, only works for the role with bb.sql.ddl or bb.sql.dml permissions. Support "in" operator.
diff --git a/proto/v1/v1/plan_service.proto b/proto/v1/v1/plan_service.proto
index 070f25811e..b9fc630b86 100644
--- a/proto/v1/v1/plan_service.proto
+++ b/proto/v1/v1/plan_service.proto
@@ -268,7 +268,7 @@ message Plan {
message CreateDatabaseConfig {
reserved 8;
// The resource name of the instance on which the database is created.
- // Format: instances/{instance}
+ // Format: instances/{instance} or projects/{project}/instances/{instance}
string target = 1 [(google.api.field_behavior) = REQUIRED];
// The name of the database to create.
string database = 2 [(google.api.field_behavior) = REQUIRED];
@@ -390,7 +390,7 @@ message PlanCheckRun {
int32 code = 4;
// Target identification for consolidated results.
- // Format: instances/{instance}/databases/{database}
+ // Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
string target = 7;
Type type = 8;
diff --git a/proto/v1/v1/query_history_service.proto b/proto/v1/v1/query_history_service.proto
index 850b47cfd5..d27a4f202b 100644
--- a/proto/v1/v1/query_history_service.proto
+++ b/proto/v1/v1/query_history_service.proto
@@ -149,7 +149,7 @@ message QueryHistory {
string name = 1 [(google.api.field_behavior) = OUTPUT_ONLY];
// The database name to execute the query.
- // Format: instances/{instance}/databases/{databaseName}
+ // Format: instances/{instance}/databases/{databaseName} or projects/{project}/instances/{instance}/databases/{databaseName}
string database = 2 [(google.api.field_behavior) = OUTPUT_ONLY];
string creator = 3 [(google.api.field_behavior) = OUTPUT_ONLY];
diff --git a/proto/v1/v1/rollout_service.proto b/proto/v1/v1/rollout_service.proto
index 750e1c2291..c46839fffd 100644
--- a/proto/v1/v1/rollout_service.proto
+++ b/proto/v1/v1/rollout_service.proto
@@ -441,8 +441,8 @@ message Task {
}
Type type = 5;
- // Format: instances/{instance} if the task is DatabaseCreate.
- // Format: instances/{instance}/databases/{database}
+ // Format: instances/{instance} or projects/{project}/instances/{instance} if the task is DatabaseCreate.
+ // Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
string target = 6;
oneof payload {
@@ -691,7 +691,7 @@ message TaskRunLogEntry {
// Table information.
message Table {
// The database information.
- // Format: instances/{instance}/databases/{database}
+ // Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
string database = 1;
// The schema name.
string schema = 2;
diff --git a/proto/v1/v1/saved_query_service.proto b/proto/v1/v1/saved_query_service.proto
index c4513ece16..6d4f790d03 100644
--- a/proto/v1/v1/saved_query_service.proto
+++ b/proto/v1/v1/saved_query_service.proto
@@ -447,7 +447,7 @@ message SavedQuery {
// The connected database, which must belong to the saved query's own
// project. Empty when none is connected, or when the database no longer
// exists.
- // Format: instances/{instance}/databases/{database}
+ // Format: instances/{instance}/databases/{database} or projects/{project}/instances/{instance}/databases/{database}
string database = 3;
// The title of the saved query.
diff --git a/proto/v1/v1/sql_service.proto b/proto/v1/v1/sql_service.proto
index b91b7fb26f..7857cf6b59 100644
--- a/proto/v1/v1/sql_service.proto
+++ b/proto/v1/v1/sql_service.proto
@@ -22,6 +22,10 @@ service SQLService {
option (google.api.http) = {
post: "/v1/{name=instances/*/databases/*}:query"
body: "*"
+ additional_bindings: {
+ post: "/v1/{name=projects/*/instances/*/databases/*}:query"
+ body: "*"
+ }
};
option (bytebase.v1.permission) = "bb.databases.get";
option (bytebase.v1.auth_method) = IAM;
@@ -86,6 +90,10 @@ service SQLService {
option (google.api.http) = {
post: "/v1/{name=instances/*/databases/*}:export"
body: "*"
+ additional_bindings: {
+ post: "/v1/{name=projects/*/instances/*/databases/*}:export"
+ body: "*"
+ }
};
option (bytebase.v1.permission) = "bb.databases.get";
option (bytebase.v1.auth_method) = IAM;
@@ -96,7 +104,8 @@ service SQLService {
message AdminExecuteRequest {
// The name is the instance name to execute the query against.
- // Format: instances/{instance}/databases/{databaseName}
+ // Format: instances/{instance}/databases/{databaseName} or
+ // projects/{project}/instances/{instance}/databases/{databaseName}
string name = 1 [
(google.api.field_behavior) = REQUIRED,
(google.api.resource_reference) = {type: "bytebase.com/Database"}
@@ -123,8 +132,9 @@ message AdminExecuteResponse {
}
message QueryRequest {
- // The name is the instance name to execute the query against.
- // Format: instances/{instance}/databases/{databaseName}
+ // The name is the database resource name to execute the query against.
+ // Format: instances/{instance}/databases/{databaseName} or
+ // projects/{project}/instances/{instance}/databases/{databaseName}
string name = 1 [
(google.api.field_behavior) = REQUIRED,
(google.api.resource_reference) = {type: "bytebase.com/Database"}
@@ -409,8 +419,8 @@ message Advice {
message ExportRequest {
// The name is the resource name to execute the export against.
- // Format: instances/{instance}/databases/{database}
- // Format: instances/{instance}
+ // Format: instances/{instance}/databases/{database} or
+ // projects/{project}/instances/{instance}/databases/{database}
string name = 1 [
(google.api.field_behavior) = REQUIRED,
(google.api.resource_reference) = {type: "bytebase.com/Database"}