Skip to content

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

feat: enhance query history (#20554)

ecmadao01491aecb25a
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yaml
index bcba1dec17..87c4c62fe4 100644
--- a/backend/api/mcp/gen/openapi.yaml
+++ b/backend/api/mcp/gen/openapi.yaml
@@ -5565,6 +5565,44 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/bytebase.v1.ExportResponse'
+ /bytebase.v1.SQLService/GetQueryHistory:
+ post:
+ tags:
+ - bytebase.v1.SQLService
+ summary: GetQueryHistory
+ description: |-
+ GetQueryHistory gets a single query history for the caller.
+ Permissions required: None (only returns the caller's own query history)
+ operationId: bytebase.v1.SQLService.GetQueryHistory
+ parameters:
+ - name: Connect-Protocol-Version
+ in: header
+ required: true
+ schema:
+ $ref: '#/components/schemas/connect-protocol-version'
+ - name: Connect-Timeout-Ms
+ in: header
+ schema:
+ $ref: '#/components/schemas/connect-timeout-header'
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/bytebase.v1.GetQueryHistoryRequest'
+ required: true
+ responses:
+ default:
+ description: Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/connect.error'
+ "200":
+ description: Success
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/bytebase.v1.QueryHistory'
/bytebase.v1.SQLService/Query:
post:
tags:
@@ -11855,6 +11893,17 @@ components:
Format: projects/{project}
title: GetProjectRequest
additionalProperties: false
+ bytebase.v1.GetQueryHistoryRequest:
+ type: object
+ properties:
+ name:
+ type: string
+ title: name
+ description: |-
+ The name of the query history to retrieve.
+ Format: projects/{project}/queryHistories/{id}
+ title: GetQueryHistoryRequest
+ additionalProperties: false
bytebase.v1.GetReleaseRequest:
type: object
properties:
diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.go
index 3719bab367..7ad34a9ce2 100644
--- a/backend/api/v1/sql_service.go
+++ b/backend/api/v1/sql_service.go
@@ -1440,6 +1440,36 @@ func (s *SQLService) SearchQueryHistories(ctx context.Context, req *connect.Requ
return connect.NewResponse(resp), nil
}
+// GetQueryHistory gets a single query history. Query histories are private to
+// their creator, so only the creator may retrieve one.
+func (s *SQLService) GetQueryHistory(ctx context.Context, req *connect.Request[v1pb.GetQueryHistoryRequest]) (*connect.Response[v1pb.QueryHistory], error) {
+ user, ok := GetUserFromContext(ctx)
+ if !ok {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("user not found"))
+ }
+
+ projectID, historyID, err := common.GetProjectIDQueryHistoryID(req.Msg.Name)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, err)
+ }
+
+ history, err := s.store.GetQueryHistory(ctx, historyID)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get query history: %v", err.Error()))
+ }
+ // Hide existence from non-creators and project mismatches by returning the
+ // same not-found error for all three cases.
+ if history == nil || history.Project != projectID || history.Creator != user.Email {
+ return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("query history %q not found", req.Msg.Name))
+ }
+
+ queryHistory, err := s.convertToV1QueryHistory(ctx, history)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to convert query history"))
+ }
+ return connect.NewResponse(queryHistory), nil
+}
+
// The Build*Func parser-context helpers moved to
// `backend/component/parsercontext` so the runner layer can use them
// without an import cycle. See parsercontext.BuildGetDatabaseMetadataFunc,
diff --git a/backend/common/resource_name.go b/backend/common/resource_name.go
index 35a904b34d..116a8bab89 100644
--- a/backend/common/resource_name.go
+++ b/backend/common/resource_name.go
@@ -52,6 +52,7 @@ const (
FileNamePrefix = "files/"
RevisionNamePrefix = "revisions/"
AccessGrantNamePrefix = "accessGrants/"
+ QueryHistoryNamePrefix = "queryHistories/"
ServiceAccountNamePrefix = "serviceAccounts/"
WorkloadIdentityNamePrefix = "workloadIdentities/"
@@ -103,6 +104,15 @@ func GetProjectIDAccessGrantID(name string) (string, string, error) {
return tokens[0], tokens[1], nil
}
+// GetProjectIDQueryHistoryID returns the project ID and query history ID from a resource name.
+func GetProjectIDQueryHistoryID(name string) (string, string, error) {
+ tokens, err := GetNameParentTokens(name, ProjectNamePrefix, QueryHistoryNamePrefix)
+ if err != nil {
+ return "", "", err
+ }
+ return tokens[0], tokens[1], nil
+}
+
// FormatAccessGrant returns the resource name for an access grant.
func FormatAccessGrant(projectID string, id string) string {
return fmt.Sprintf("%s/%s%s", FormatProject(projectID), AccessGrantNamePrefix, id)
diff --git a/backend/common/resource_name_test.go b/backend/common/resource_name_test.go
index 845145ed40..92f2399ef2 100644
--- a/backend/common/resource_name_test.go
+++ b/backend/common/resource_name_test.go
@@ -15,3 +15,16 @@ func TestGetInstanceDatabaseID(t *testing.T) {
_, err = GetInstanceID("instances/i2/databases/d3")
require.Error(t, err)
}
+
+func TestGetProjectIDQueryHistoryID(t *testing.T) {
+ projectID, historyID, err := GetProjectIDQueryHistoryID("projects/p1/queryHistories/550e8400-e29b-41d4-a716-446655440000")
+ require.NoError(t, err)
+ require.Equal(t, "p1", projectID)
+ require.Equal(t, "550e8400-e29b-41d4-a716-446655440000", historyID)
+
+ _, _, err = GetProjectIDQueryHistoryID("projects/p1/queryHistories")
+ require.Error(t, err)
+
+ _, _, err = GetProjectIDQueryHistoryID("queryHistories/h1")
+ require.Error(t, err)
+}
diff --git a/backend/generated-go/v1/sql_service.pb.go b/backend/generated-go/v1/sql_service.pb.go
index 4e995a4623..4547dc9587 100644
--- a/backend/generated-go/v1/sql_service.pb.go
+++ b/backend/generated-go/v1/sql_service.pb.go
@@ -410,7 +410,7 @@ func (x QueryHistory_Type) Number() protoreflect.EnumNumber {
// Deprecated: Use QueryHistory_Type.Descriptor instead.
func (QueryHistory_Type) EnumDescriptor() ([]byte, []int) {
- return file_v1_sql_service_proto_rawDescGZIP(), []int{16, 0}
+ return file_v1_sql_service_proto_rawDescGZIP(), []int{17, 0}
}
type AdminExecuteRequest struct {
@@ -1834,6 +1834,52 @@ func (x *SearchQueryHistoriesRequest) GetFilter() string {
return ""
}
+type GetQueryHistoryRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The name of the query history to retrieve.
+ // Format: projects/{project}/queryHistories/{id}
+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *GetQueryHistoryRequest) Reset() {
+ *x = GetQueryHistoryRequest{}
+ mi := &file_v1_sql_service_proto_msgTypes[15]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *GetQueryHistoryRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*GetQueryHistoryRequest) ProtoMessage() {}
+
+func (x *GetQueryHistoryRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_v1_sql_service_proto_msgTypes[15]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use GetQueryHistoryRequest.ProtoReflect.Descriptor instead.
+func (*GetQueryHistoryRequest) Descriptor() ([]byte, []int) {
+ return file_v1_sql_service_proto_rawDescGZIP(), []int{15}
+}
+
+func (x *GetQueryHistoryRequest) GetName() string {
+ if x != nil {
+ return x.Name
+ }
+ return ""
+}
+
type SearchQueryHistoriesResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
// The list of history.
@@ -1848,7 +1894,7 @@ type SearchQueryHistoriesResponse struct {
func (x *SearchQueryHistoriesResponse) Reset() {
*x = SearchQueryHistoriesResponse{}
- mi := &file_v1_sql_service_proto_msgTypes[15]
+ mi := &file_v1_sql_service_proto_msgTypes[16]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1860,7 +1906,7 @@ func (x *SearchQueryHistoriesResponse) String() string {
func (*SearchQueryHistoriesResponse) ProtoMessage() {}
func (x *SearchQueryHistoriesResponse) ProtoReflect() protoreflect.Message {
- mi := &file_v1_sql_service_proto_msgTypes[15]
+ mi := &file_v1_sql_service_proto_msgTypes[16]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1873,7 +1919,7 @@ func (x *SearchQueryHistoriesResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use SearchQueryHistoriesResponse.ProtoReflect.Descriptor instead.
func (*SearchQueryHistoriesResponse) Descriptor() ([]byte, []int) {
- return file_v1_sql_service_proto_rawDescGZIP(), []int{15}
+ return file_v1_sql_service_proto_rawDescGZIP(), []int{16}
}
func (x *SearchQueryHistoriesResponse) GetQueryHistories() []*QueryHistory {
@@ -1910,7 +1956,7 @@ type QueryHistory struct {
func (x *QueryHistory) Reset() {
*x = QueryHistory{}
- mi := &file_v1_sql_service_proto_msgTypes[16]
+ mi := &file_v1_sql_service_proto_msgTypes[17]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1922,7 +1968,7 @@ func (x *QueryHistory) String() string {
func (*QueryHistory) ProtoMessage() {}
func (x *QueryHistory) ProtoReflect() protoreflect.Message {
- mi := &file_v1_sql_service_proto_msgTypes[16]
+ mi := &file_v1_sql_service_proto_msgTypes[17]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1935,7 +1981,7 @@ func (x *QueryHistory) ProtoReflect() protoreflect.Message {
// Deprecated: Use QueryHistory.ProtoReflect.Descriptor instead.
func (*QueryHistory) Descriptor() ([]byte, []int) {
- return file_v1_sql_service_proto_rawDescGZIP(), []int{16}
+ return file_v1_sql_service_proto_rawDescGZIP(), []int{17}
}
func (x *QueryHistory) GetName() string {
@@ -2003,7 +2049,7 @@ type AICompletionRequest struct {
func (x *AICompletionRequest) Reset() {
*x = AICompletionRequest{}
- mi := &file_v1_sql_service_proto_msgTypes[17]
+ mi := &file_v1_sql_service_proto_msgTypes[18]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2015,7 +2061,7 @@ func (x *AICompletionRequest) String() string {
func (*AICompletionRequest) ProtoMessage() {}
func (x *AICompletionRequest) ProtoReflect() protoreflect.Message {
- mi := &file_v1_sql_service_proto_msgTypes[17]
+ mi := &file_v1_sql_service_proto_msgTypes[18]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2028,7 +2074,7 @@ func (x *AICompletionRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use AICompletionRequest.ProtoReflect.Descriptor instead.
func (*AICompletionRequest) Descriptor() ([]byte, []int) {
- return file_v1_sql_service_proto_rawDescGZIP(), []int{17}
+ return file_v1_sql_service_proto_rawDescGZIP(), []int{18}
}
func (x *AICompletionRequest) GetMessages() []*AICompletionRequest_Message {
@@ -2049,7 +2095,7 @@ type AICompletionResponse struct {
func (x *AICompletionResponse) Reset() {
*x = AICompletionResponse{}
- mi := &file_v1_sql_service_proto_msgTypes[18]
+ mi := &file_v1_sql_service_proto_msgTypes[19]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2061,7 +2107,7 @@ func (x *AICompletionResponse) String() string {
func (*AICompletionResponse) ProtoMessage() {}
func (x *AICompletionResponse) ProtoReflect() protoreflect.Message {
- mi := &file_v1_sql_service_proto_msgTypes[18]
+ mi := &file_v1_sql_service_proto_msgTypes[19]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2074,7 +2120,7 @@ func (x *AICompletionResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use AICompletionResponse.ProtoReflect.Descriptor instead.
func (*AICompletionResponse) Descriptor() ([]byte, []int) {
- return file_v1_sql_service_proto_rawDescGZIP(), []int{18}
+ return file_v1_sql_service_proto_rawDescGZIP(), []int{19}
}
func (x *AICompletionResponse) GetCandidates() []*AICompletionResponse_Candidate {
@@ -2111,7 +2157,7 @@ type QueryResult_PostgresError struct {
func (x *QueryResult_PostgresError) Reset() {
*x = QueryResult_PostgresError{}
- mi := &file_v1_sql_service_proto_msgTypes[19]
+ mi := &file_v1_sql_service_proto_msgTypes[20]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2123,7 +2169,7 @@ func (x *QueryResult_PostgresError) String() string {
func (*QueryResult_PostgresError) ProtoMessage() {}
func (x *QueryResult_PostgresError) ProtoReflect() protoreflect.Message {
- mi := &file_v1_sql_service_proto_msgTypes[19]
+ mi := &file_v1_sql_service_proto_msgTypes[20]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2269,7 +2315,7 @@ type QueryResult_SyntaxError struct {
func (x *QueryResult_SyntaxError) Reset() {
*x = QueryResult_SyntaxError{}
- mi := &file_v1_sql_service_proto_msgTypes[20]
+ mi := &file_v1_sql_service_proto_msgTypes[21]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2281,7 +2327,7 @@ func (x *QueryResult_SyntaxError) String() string {
func (*QueryResult_SyntaxError) ProtoMessage() {}
func (x *QueryResult_SyntaxError) ProtoReflect() protoreflect.Message {
- mi := &file_v1_sql_service_proto_msgTypes[20]
+ mi := &file_v1_sql_service_proto_msgTypes[21]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2316,7 +2362,7 @@ type QueryResult_CommandError struct {
func (x *QueryResult_CommandError) Reset() {
*x = QueryResult_CommandError{}
- mi := &file_v1_sql_service_proto_msgTypes[21]
+ mi := &file_v1_sql_service_proto_msgTypes[22]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2328,7 +2374,7 @@ func (x *QueryResult_CommandError) String() string {
func (*QueryResult_CommandError) ProtoMessage() {}
func (x *QueryResult_CommandError) ProtoReflect() protoreflect.Message {
- mi := &file_v1_sql_service_proto_msgTypes[21]
+ mi := &file_v1_sql_service_proto_msgTypes[22]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2361,7 +2407,7 @@ type QueryResult_Message struct {
func (x *QueryResult_Message) Reset() {
*x = QueryResult_Message{}
- mi := &file_v1_sql_service_proto_msgTypes[22]
+ mi := &file_v1_sql_service_proto_msgTypes[23]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2373,7 +2419,7 @@ func (x *QueryResult_Message) String() string {
func (*QueryResult_Message) ProtoMessage() {}
func (x *QueryResult_Message) ProtoReflect() protoreflect.Message {
- mi := &file_v1_sql_service_proto_msgTypes[22]
+ mi := &file_v1_sql_service_proto_msgTypes[23]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2414,7 +2460,7 @@ type RowValue_Timestamp struct {
func (x *RowValue_Timestamp) Reset() {
*x = RowValue_Timestamp{}
- mi := &file_v1_sql_service_proto_msgTypes[23]
+ mi := &file_v1_sql_service_proto_msgTypes[24]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2426,7 +2472,7 @@ func (x *RowValue_Timestamp) String() string {
func (*RowValue_Timestamp) ProtoMessage() {}
func (x *RowValue_Timestamp) ProtoReflect() protoreflect.Message {
- mi := &file_v1_sql_service_proto_msgTypes[23]
+ mi := &file_v1_sql_service_proto_msgTypes[24]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2475,7 +2521,7 @@ type RowValue_TimestampTZ struct {
func (x *RowValue_TimestampTZ) Reset() {
*x = RowValue_TimestampTZ{}
- mi := &file_v1_sql_service_proto_msgTypes[24]
+ mi := &file_v1_sql_service_proto_msgTypes[25]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2487,7 +2533,7 @@ func (x *RowValue_TimestampTZ) String() string {
func (*RowValue_TimestampTZ) ProtoMessage() {}
func (x *RowValue_TimestampTZ) ProtoReflect() protoreflect.Message {
- mi := &file_v1_sql_service_proto_msgTypes[24]
+ mi := &file_v1_sql_service_proto_msgTypes[25]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2541,7 +2587,7 @@ type AICompletionRequest_Message struct {
func (x *AICompletionRequest_Message) Reset() {
*x = AICompletionRequest_Message{}
- mi := &file_v1_sql_service_proto_msgTypes[25]
+ mi := &file_v1_sql_service_proto_msgTypes[26]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2553,7 +2599,7 @@ func (x *AICompletionRequest_Message) String() string {
func (*AICompletionRequest_Message) ProtoMessage() {}
func (x *AICompletionRequest_Message) ProtoReflect() protoreflect.Message {
- mi := &file_v1_sql_service_proto_msgTypes[25]
+ mi := &file_v1_sql_service_proto_msgTypes[26]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2566,7 +2612,7 @@ func (x *AICompletionRequest_Message) ProtoReflect() protoreflect.Message {
// Deprecated: Use AICompletionRequest_Message.ProtoReflect.Descriptor instead.
func (*AICompletionRequest_Message) Descriptor() ([]byte, []int) {
- return file_v1_sql_service_proto_rawDescGZIP(), []int{17, 0}
+ return file_v1_sql_service_proto_rawDescGZIP(), []int{18, 0}
}
func (x *AICompletionRequest_Message) GetRole() string {
@@ -2592,7 +2638,7 @@ type AICompletionResponse_Candidate struct {
func (x *AICompletionResponse_Candidate) Reset() {
*x = AICompletionResponse_Candidate{}
- mi := &file_v1_sql_service_proto_msgTypes[26]
+ mi := &file_v1_sql_service_proto_msgTypes[27]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2604,7 +2650,7 @@ func (x *AICompletionResponse_Candidate) String() string {
func (*AICompletionResponse_Candidate) ProtoMessage() {}
func (x *AICompletionResponse_Candidate) ProtoReflect() protoreflect.Message {
- mi := &file_v1_sql_service_proto_msgTypes[26]
+ mi := &file_v1_sql_service_proto_msgTypes[27]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2617,7 +2663,7 @@ func (x *AICompletionResponse_Candidate) ProtoReflect() protoreflect.Message {
// Deprecated: Use AICompletionResponse_Candidate.ProtoReflect.Descriptor instead.
func (*AICompletionResponse_Candidate) Descriptor() ([]byte, []int) {
- return file_v1_sql_service_proto_rawDescGZIP(), []int{18, 0}
+ return file_v1_sql_service_proto_rawDescGZIP(), []int{19, 0}
}
func (x *AICompletionResponse_Candidate) GetContent() *AICompletionResponse_Candidate_Content {
@@ -2637,7 +2683,7 @@ type AICompletionResponse_Candidate_Content struct {
func (x *AICompletionResponse_Candidate_Content) Reset() {
*x = AICompletionResponse_Candidate_Content{}
- mi := &file_v1_sql_service_proto_msgTypes[27]
+ mi := &file_v1_sql_service_proto_msgTypes[28]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2649,7 +2695,7 @@ func (x *AICompletionResponse_Candidate_Content) String() string {
func (*AICompletionResponse_Candidate_Content) ProtoMessage() {}
func (x *AICompletionResponse_Candidate_Content) ProtoReflect() protoreflect.Message {
- mi := &file_v1_sql_service_proto_msgTypes[27]
+ mi := &file_v1_sql_service_proto_msgTypes[28]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2662,7 +2708,7 @@ func (x *AICompletionResponse_Candidate_Content) ProtoReflect() protoreflect.Mes
// Deprecated: Use AICompletionResponse_Candidate_Content.ProtoReflect.Descriptor instead.
func (*AICompletionResponse_Candidate_Content) Descriptor() ([]byte, []int) {
- return file_v1_sql_service_proto_rawDescGZIP(), []int{18, 0, 0}
+ return file_v1_sql_service_proto_rawDescGZIP(), []int{19, 0, 0}
}
func (x *AICompletionResponse_Candidate_Content) GetParts() []*AICompletionResponse_Candidate_Content_Part {
@@ -2681,7 +2727,7 @@ type AICompletionResponse_Candidate_Content_Part struct {
func (x *AICompletionResponse_Candidate_Content_Part) Reset() {
*x = AICompletionResponse_Candidate_Content_Part{}
- mi := &file_v1_sql_service_proto_msgTypes[28]
+ mi := &file_v1_sql_service_proto_msgTypes[29]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2693,7 +2739,7 @@ func (x *AICompletionResponse_Candidate_Content_Part) String() string {
func (*AICompletionResponse_Candidate_Content_Part) ProtoMessage() {}
func (x *AICompletionResponse_Candidate_Content_Part) ProtoReflect() protoreflect.Message {
- mi := &file_v1_sql_service_proto_msgTypes[28]
+ mi := &file_v1_sql_service_proto_msgTypes[29]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2706,7 +2752,7 @@ func (x *AICompletionResponse_Candidate_Content_Part) ProtoReflect() protoreflec
// Deprecated: Use AICompletionResponse_Candidate_Content_Part.ProtoReflect.Descriptor instead.
func (*AICompletionResponse_Candidate_Content_Part) Descriptor() ([]byte, []int) {
- return file_v1_sql_service_proto_rawDescGZIP(), []int{18, 0, 0, 0}
+ return file_v1_sql_service_proto_rawDescGZIP(), []int{19, 0, 0, 0}
}
func (x *AICompletionResponse_Candidate_Content_Part) GetText() string {
@@ -2903,7 +2949,9 @@ const file_v1_sql_service_proto_rawDesc = "" +
"\tpage_size\x18\x01 \x01(\x05R\bpageSize\x12\x1d\n" +
"\n" +
"page_token\x18\x02 \x01(\tR\tpageToken\x12\x16\n" +
- "\x06filter\x18\x03 \x01(\tR\x06filter\"\x8f\x01\n" +
+ "\x06filter\x18\x03 \x01(\tR\x06filter\"1\n" +
+ "\x16GetQueryHistoryRequest\x12\x17\n" +
+ "\x04name\x18\x01 \x01(\tB\x03\xe0A\x02R\x04name\"\x8f\x01\n" +
"\x1cSearchQueryHistoriesResponse\x12G\n" +
"\x0fquery_histories\x18\x01 \x03(\v2\x19.bytebase.v1.QueryHistoryB\x03\xe0A\x03R\x0equeryHistories\x12&\n" +
"\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"\x9b\x03\n" +
@@ -2937,12 +2985,13 @@ const file_v1_sql_service_proto_rawDesc = "" +
"\aContent\x12N\n" +
"\x05parts\x18\x01 \x03(\v28.bytebase.v1.AICompletionResponse.Candidate.Content.PartR\x05parts\x1a\x1a\n" +
"\x04Part\x12\x12\n" +
- "\x04text\x18\x01 \x01(\tR\x04text2\xc7\a\n" +
+ "\x04text\x18\x01 \x01(\tR\x04text2\xcf\b\n" +
"\n" +
"SQLService\x12\x8f\x01\n" +
"\x05Query\x12\x19.bytebase.v1.QueryRequest\x1a\x1a.bytebase.v1.QueryResponse\"O\x8a\xea0\x10bb.databases.get\x90\xea0\x01\x98\xea0\x01\x82\xd3\xe4\x93\x02-:\x01*\"(/v1/{name=instances/*/databases/*}:query\x12\x89\x01\n" +
"\fAdminExecute\x12 .bytebase.v1.AdminExecuteRequest\x1a!.bytebase.v1.AdminExecuteResponse\"0\x8a\xea0\fbb.sql.admin\x90\xea0\x01\x98\xea0\x01\x82\xd3\xe4\x93\x02\x12\x12\x10/v1:adminExecute(\x010\x01\x12\x95\x01\n" +
- "\x14SearchQueryHistories\x12(.bytebase.v1.SearchQueryHistoriesRequest\x1a).bytebase.v1.SearchQueryHistoriesResponse\"(\x90\xea0\x02\x82\xd3\xe4\x93\x02\x1e:\x01*\"\x19/v1/queryHistories:search\x12\x84\x02\n" +
+ "\x14SearchQueryHistories\x12(.bytebase.v1.SearchQueryHistoriesRequest\x1a).bytebase.v1.SearchQueryHistoriesResponse\"(\x90\xea0\x02\x82\xd3\xe4\x93\x02\x1e:\x01*\"\x19/v1/queryHistories:search\x12\x85\x01\n" +
+ "\x0fGetQueryHistory\x12#.bytebase.v1.GetQueryHistoryRequest\x1a\x19.bytebase.v1.QueryHistory\"2\x90\xea0\x02\x82\xd3\xe4\x93\x02(\x12&/v1/{name=projects/*/queryHistories/*}\x12\x84\x02\n" +
"\x06Export\x12\x1a.bytebase.v1.ExportRequest\x1a\x1b.bytebase.v1.ExportResponse\"\xc0\x01\x8a\xea0\x10bb.databases.get\x90\xea0\x01\x98\xea0\x01\x82\xd3\xe4\x93\x02\x9d\x01:\x01*Z1:\x01*\",/v1/{name=projects/*/plans/*/rollout}:exportZ::\x01*\"5/v1/{name=projects/*/plans/*/rollout/stages/*}:export\")/v1/{name=instances/*/databases/*}:export\x12\x81\x01\n" +
"\fDiffMetadata\x12 .bytebase.v1.DiffMetadataRequest\x1a!.bytebase.v1.DiffMetadataResponse\",\x80\xea0\x01\x82\xd3\xe4\x93\x02\":\x01*\"\x1d/v1/schemaDesign:diffMetadata\x12x\n" +
"\fAICompletion\x12 .bytebase.v1.AICompletionRequest\x1a!.bytebase.v1.AICompletionResponse\"#\x90\xea0\x02\x82\xd3\xe4\x93\x02\x19:\x01*\"\x14/v1/sql/aiCompletionB\xa5\x01\n" +
@@ -2961,7 +3010,7 @@ func file_v1_sql_service_proto_rawDescGZIP() []byte {
}
var file_v1_sql_service_proto_enumTypes = make([]protoimpl.EnumInfo, 7)
-var file_v1_sql_service_proto_msgTypes = make([]protoimpl.MessageInfo, 29)
+var file_v1_sql_service_proto_msgTypes = make([]protoimpl.MessageInfo, 30)
var file_v1_sql_service_proto_goTypes = []any{
(QueryOption_RedisRunCommandsOn)(0), // 0: bytebase.v1.QueryOption.RedisRunCommandsOn
(QueryOption_MSSQLExplainFormat)(0), // 1: bytebase.v1.QueryOption.MSSQLExplainFormat
@@ -2985,29 +3034,30 @@ var file_v1_sql_service_proto_goTypes = []any{
(*DiffMetadataRequest)(nil), // 19: bytebase.v1.DiffMetadataRequest
(*DiffMetadataResponse)(nil), // 20: bytebase.v1.DiffMetadataResponse
(*SearchQueryHistoriesRequest)(nil), // 21: bytebase.v1.SearchQueryHistoriesRequest
- (*SearchQueryHistoriesResponse)(nil), // 22: bytebase.v1.SearchQueryHistoriesResponse
- (*QueryHistory)(nil), // 23: bytebase.v1.QueryHistory
- (*AICompletionRequest)(nil), // 24: bytebase.v1.AICompletionRequest
- (*AICompletionResponse)(nil), // 25: bytebase.v1.AICompletionResponse
- (*QueryResult_PostgresError)(nil), // 26: bytebase.v1.QueryResult.PostgresError
- (*QueryResult_SyntaxError)(nil), // 27: bytebase.v1.QueryResult.SyntaxError
- (*QueryResult_CommandError)(nil), // 28: bytebase.v1.QueryResult.CommandError
- (*QueryResult_Message)(nil), // 29: bytebase.v1.QueryResult.Message
- (*RowValue_Timestamp)(nil), // 30: bytebase.v1.RowValue.Timestamp
- (*RowValue_TimestampTZ)(nil), // 31: bytebase.v1.RowValue.TimestampTZ
- (*AICompletionRequest_Message)(nil), // 32: bytebase.v1.AICompletionRequest.Message
- (*AICompletionResponse_Candidate)(nil), // 33: bytebase.v1.AICompletionResponse.Candidate
- (*AICompletionResponse_Candidate_Content)(nil), // 34: bytebase.v1.AICompletionResponse.Candidate.Content
- (*AICompletionResponse_Candidate_Content_Part)(nil), // 35: bytebase.v1.AICompletionResponse.Candidate.Content.Part
- (*durationpb.Duration)(nil), // 36: google.protobuf.Duration
- (*PermissionDeniedDetail)(nil), // 37: bytebase.v1.PermissionDeniedDetail
- (structpb.NullValue)(0), // 38: google.protobuf.NullValue
- (*structpb.Value)(nil), // 39: google.protobuf.Value
- (*Position)(nil), // 40: bytebase.v1.Position
- (ExportFormat)(0), // 41: bytebase.v1.ExportFormat
- (*DatabaseMetadata)(nil), // 42: bytebase.v1.DatabaseMetadata
- (Engine)(0), // 43: bytebase.v1.Engine
- (*timestamppb.Timestamp)(nil), // 44: google.protobuf.Timestamp
+ (*GetQueryHistoryRequest)(nil), // 22: bytebase.v1.GetQueryHistoryRequest
+ (*SearchQueryHistoriesResponse)(nil), // 23: bytebase.v1.SearchQueryHistoriesResponse
+ (*QueryHistory)(nil), // 24: bytebase.v1.QueryHistory
+ (*AICompletionRequest)(nil), // 25: bytebase.v1.AICompletionRequest
+ (*AICompletionResponse)(nil), // 26: bytebase.v1.AICompletionResponse
+ (*QueryResult_PostgresError)(nil), // 27: bytebase.v1.QueryResult.PostgresError
+ (*QueryResult_SyntaxError)(nil), // 28: bytebase.v1.QueryResult.SyntaxError
+ (*QueryResult_CommandError)(nil), // 29: bytebase.v1.QueryResult.CommandError
+ (*QueryResult_Message)(nil), // 30: bytebase.v1.QueryResult.Message
+ (*RowValue_Timestamp)(nil), // 31: bytebase.v1.RowValue.Timestamp
+ (*RowValue_TimestampTZ)(nil), // 32: bytebase.v1.RowValue.TimestampTZ
+ (*AICompletionRequest_Message)(nil), // 33: bytebase.v1.AICompletionRequest.Message
+ (*AICompletionResponse_Candidate)(nil), // 34: bytebase.v1.AICompletionResponse.Candidate
+ (*AICompletionResponse_Candidate_Content)(nil), // 35: bytebase.v1.AICompletionResponse.Candidate.Content
+ (*AICompletionResponse_Candidate_Content_Part)(nil), // 36: bytebase.v1.AICompletionResponse.Candidate.Content.Part
+ (*durationpb.Duration)(nil), // 37: google.protobuf.Duration
+ (*PermissionDeniedDetail)(nil), // 38: bytebase.v1.PermissionDeniedDetail
+ (structpb.NullValue)(0), // 39: google.protobuf.NullValue
+ (*structpb.Value)(nil), // 40: google.protobuf.Value
+ (*Position)(nil), // 41: bytebase.v1.Position
+ (ExportFormat)(0), // 42: bytebase.v1.ExportFormat
+ (*DatabaseMetadata)(nil), // 43: bytebase.v1.DatabaseMetadata
+ (Engine)(0), // 44: bytebase.v1.Engine
+ (*timestamppb.Timestamp)(nil), // 45: google.protobuf.Timestamp
}
var file_v1_sql_service_proto_depIdxs = []int32{
12, // 0: bytebase.v1.AdminExecuteResponse.results:type_name -> bytebase.v1.QueryResult
@@ -3016,53 +3066,55 @@ var file_v1_sql_service_proto_depIdxs = []int32{
0, // 3: bytebase.v1.QueryOption.redis_run_commands_on:type_name -> bytebase.v1.QueryOption.RedisRunCommandsOn
1, // 4: bytebase.v1.QueryOption.mssql_explain_format:type_name -> bytebase.v1.QueryOption.MSSQLExplainFormat
14, // 5: bytebase.v1.QueryResult.rows:type_name -> bytebase.v1.QueryRow
- 36, // 6: bytebase.v1.QueryResult.latency:type_name -> google.protobuf.Duration
- 26, // 7: bytebase.v1.QueryResult.postgres_error:type_name -> bytebase.v1.QueryResult.PostgresError
- 27, // 8: bytebase.v1.QueryResult.syntax_error:type_name -> bytebase.v1.QueryResult.SyntaxError
- 37, // 9: bytebase.v1.QueryResult.permission_denied:type_name -> bytebase.v1.PermissionDeniedDetail
- 28, // 10: bytebase.v1.QueryResult.command_error:type_name -> bytebase.v1.QueryResult.CommandError
- 29, // 11: bytebase.v1.QueryResult.messages:type_name -> bytebase.v1.QueryResult.Message
+ 37, // 6: bytebase.v1.QueryResult.latency:type_name -> google.protobuf.Duration
+ 27, // 7: bytebase.v1.QueryResult.postgres_error:type_name -> bytebase.v1.QueryResult.PostgresError
+ 28, // 8: bytebase.v1.QueryResult.syntax_error:type_name -> bytebase.v1.QueryResult.SyntaxError
+ 38, // 9: bytebase.v1.QueryResult.permission_denied:type_name -> bytebase.v1.PermissionDeniedDetail
+ 29, // 10: bytebase.v1.QueryResult.command_error:type_name -> bytebase.v1.QueryResult.CommandError
+ 30, // 11: bytebase.v1.QueryResult.messages:type_name -> bytebase.v1.QueryResult.Message
13, // 12: bytebase.v1.QueryResult.masked:type_name -> bytebase.v1.MaskingReason
15, // 13: bytebase.v1.QueryRow.values:type_name -> bytebase.v1.RowValue
- 38, // 14: bytebase.v1.RowValue.null_value:type_name -> google.protobuf.NullValue
- 39, // 15: bytebase.v1.RowValue.value_value:type_name -> google.protobuf.Value
- 30, // 16: bytebase.v1.RowValue.timestamp_value:type_name -> bytebase.v1.RowValue.Timestamp
- 31, // 17: bytebase.v1.RowValue.timestamp_tz_value:type_name -> bytebase.v1.RowValue.TimestampTZ
+ 39, // 14: bytebase.v1.RowValue.null_value:type_name -> google.protobuf.NullValue
+ 40, // 15: bytebase.v1.RowValue.value_value:type_name -> google.protobuf.Value
+ 31, // 16: bytebase.v1.RowValue.timestamp_value:type_name -> bytebase.v1.RowValue.Timestamp
+ 32, // 17: bytebase.v1.RowValue.timestamp_tz_value:type_name -> bytebase.v1.RowValue.TimestampTZ
4, // 18: bytebase.v1.Advice.status:type_name -> bytebase.v1.Advice.Level
- 40, // 19: bytebase.v1.Advice.start_position:type_name -> bytebase.v1.Position
- 40, // 20: bytebase.v1.Advice.end_position:type_name -> bytebase.v1.Position
+ 41, // 19: bytebase.v1.Advice.start_position:type_name -> bytebase.v1.Position
+ 41, // 20: bytebase.v1.Advice.end_position:type_name -> bytebase.v1.Position
5, // 21: bytebase.v1.Advice.rule_type:type_name -> bytebase.v1.Advice.RuleType
- 41, // 22: bytebase.v1.ExportRequest.format:type_name -> bytebase.v1.ExportFormat
- 42, // 23: bytebase.v1.DiffMetadataRequest.source_metadata:type_name -> bytebase.v1.DatabaseMetadata
- 42, // 24: bytebase.v1.DiffMetadataRequest.target_metadata:type_name -> bytebase.v1.DatabaseMetadata
- 43, // 25: bytebase.v1.DiffMetadataRequest.engine:type_name -> bytebase.v1.Engine
- 23, // 26: bytebase.v1.SearchQueryHistoriesResponse.query_histories:type_name -> bytebase.v1.QueryHistory
- 44, // 27: bytebase.v1.QueryHistory.create_time:type_name -> google.protobuf.Timestamp
- 36, // 28: bytebase.v1.QueryHistory.duration:type_name -> google.protobuf.Duration
+ 42, // 22: bytebase.v1.ExportRequest.format:type_name -> bytebase.v1.ExportFormat
+ 43, // 23: bytebase.v1.DiffMetadataRequest.source_metadata:type_name -> bytebase.v1.DatabaseMetadata
+ 43, // 24: bytebase.v1.DiffMetadataRequest.target_metadata:type_name -> bytebase.v1.DatabaseMetadata
+ 44, // 25: bytebase.v1.DiffMetadataRequest.engine:type_name -> bytebase.v1.Engine
+ 24, // 26: bytebase.v1.SearchQueryHistoriesResponse.query_histories:type_name -> bytebase.v1.QueryHistory
+ 45, // 27: bytebase.v1.QueryHistory.create_time:type_name -> google.protobuf.Timestamp
+ 37, // 28: bytebase.v1.QueryHistory.duration:type_name -> google.protobuf.Duration
6, // 29: bytebase.v1.QueryHistory.type:type_name -> bytebase.v1.QueryHistory.Type
- 32, // 30: bytebase.v1.AICompletionRequest.messages:type_name -> bytebase.v1.AICompletionRequest.Message
- 33, // 31: bytebase.v1.AICompletionResponse.candidates:type_name -> bytebase.v1.AICompletionResponse.Candidate
- 40, // 32: bytebase.v1.QueryResult.SyntaxError.start_position:type_name -> bytebase.v1.Position
+ 33, // 30: bytebase.v1.AICompletionRequest.messages:type_name -> bytebase.v1.AICompletionRequest.Message
+ 34, // 31: bytebase.v1.AICompletionResponse.candidates:type_name -> bytebase.v1.AICompletionResponse.Candidate
+ 41, // 32: bytebase.v1.QueryResult.SyntaxError.start_position:type_name -> bytebase.v1.Position
2, // 33: bytebase.v1.QueryResult.CommandError.command_type:type_name -> bytebase.v1.QueryResult.CommandError.Type
3, // 34: bytebase.v1.QueryResult.Message.level:type_name -> bytebase.v1.QueryResult.Message.Level
- 44, // 35: bytebase.v1.RowValue.Timestamp.google_timestamp:type_name -> google.protobuf.Timestamp
- 44, // 36: bytebase.v1.RowValue.TimestampTZ.google_timestamp:type_name -> google.protobuf.Timestamp
- 34, // 37: bytebase.v1.AICompletionResponse.Candidate.content:type_name -> bytebase.v1.AICompletionResponse.Candidate.Content
- 35, // 38: bytebase.v1.AICompletionResponse.Candidate.Content.parts:type_name -> bytebase.v1.AICompletionResponse.Candidate.Content.Part
+ 45, // 35: bytebase.v1.RowValue.Timestamp.google_timestamp:type_name -> google.protobuf.Timestamp
+ 45, // 36: bytebase.v1.RowValue.TimestampTZ.google_timestamp:type_name -> google.protobuf.Timestamp
+ 35, // 37: bytebase.v1.AICompletionResponse.Candidate.content:type_name -> bytebase.v1.AICompletionResponse.Candidate.Content
+ 36, // 38: bytebase.v1.AICompletionResponse.Candidate.Content.parts:type_name -> bytebase.v1.AICompletionResponse.Candidate.Content.Part
9, // 39: bytebase.v1.SQLService.Query:input_type -> bytebase.v1.QueryRequest
7, // 40: bytebase.v1.SQLService.AdminExecute:input_type -> bytebase.v1.AdminExecuteRequest
21, // 41: bytebase.v1.SQLService.SearchQueryHistories:input_type -> bytebase.v1.SearchQueryHistoriesRequest
- 17, // 42: bytebase.v1.SQLService.Export:input_type -> bytebase.v1.ExportRequest
- 19, // 43: bytebase.v1.SQLService.DiffMetadata:input_type -> bytebase.v1.DiffMetadataRequest
- 24, // 44: bytebase.v1.SQLService.AICompletion:input_type -> bytebase.v1.AICompletionRequest
- 10, // 45: bytebase.v1.SQLService.Query:output_type -> bytebase.v1.QueryResponse
- 8, // 46: bytebase.v1.SQLService.AdminExecute:output_type -> bytebase.v1.AdminExecuteResponse
- 22, // 47: bytebase.v1.SQLService.SearchQueryHistories:output_type -> bytebase.v1.SearchQueryHistoriesResponse
- 18, // 48: bytebase.v1.SQLService.Export:output_type -> bytebase.v1.ExportResponse
- 20, // 49: bytebase.v1.SQLService.DiffMetadata:output_type -> bytebase.v1.DiffMetadataResponse
- 25, // 50: bytebase.v1.SQLService.AICompletion:output_type -> bytebase.v1.AICompletionResponse
- 45, // [45:51] is the sub-list for method output_type
- 39, // [39:45] is the sub-list for method input_type
+ 22, // 42: bytebase.v1.SQLService.GetQueryHistory:input_type -> bytebase.v1.GetQueryHistoryRequest
+ 17, // 43: bytebase.v1.SQLService.Export:input_type -> bytebase.v1.ExportRequest
+ 19, // 44: bytebase.v1.SQLService.DiffMetadata:input_type -> bytebase.v1.DiffMetadataRequest
+ 25, // 45: bytebase.v1.SQLService.AICompletion:input_type -> bytebase.v1.AICompletionRequest
+ 10, // 46: bytebase.v1.SQLService.Query:output_type -> bytebase.v1.QueryResponse
+ 8, // 47: bytebase.v1.SQLService.AdminExecute:output_type -> bytebase.v1.AdminExecuteResponse
+ 23, // 48: bytebase.v1.SQLService.SearchQueryHistories:output_type -> bytebase.v1.SearchQueryHistoriesResponse
+ 24, // 49: bytebase.v1.SQLService.GetQueryHistory:output_type -> bytebase.v1.QueryHistory
+ 18, // 50: bytebase.v1.SQLService.Export:output_type -> bytebase.v1.ExportResponse
+ 20, // 51: bytebase.v1.SQLService.DiffMetadata:output_type -> bytebase.v1.DiffMetadataResponse
+ 26, // 52: bytebase.v1.SQLService.AICompletion:output_type -> bytebase.v1.AICompletionResponse
+ 46, // [46:53] is the sub-list for method output_type
+ 39, // [39:46] is the sub-list for method input_type
39, // [39:39] is the sub-list for extension type_name
39, // [39:39] is the sub-list for extension extendee
0, // [0:39] is the sub-list for field type_name
@@ -3100,14 +3152,14 @@ func file_v1_sql_service_proto_init() {
(*RowValue_TimestampTzValue)(nil),
}
file_v1_sql_service_proto_msgTypes[10].OneofWrappers = []any{}
- file_v1_sql_service_proto_msgTypes[16].OneofWrappers = []any{}
+ file_v1_sql_service_proto_msgTypes[17].OneofWrappers = []any{}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_v1_sql_service_proto_rawDesc), len(file_v1_sql_service_proto_rawDesc)),
NumEnums: 7,
- NumMessages: 29,
+ NumMessages: 30,
NumExtensions: 0,
NumServices: 1,
},
diff --git a/backend/generated-go/v1/sql_service.pb.gw.go b/backend/generated-go/v1/sql_service.pb.gw.go
index 62b220b2db..e49918efd2 100644
--- a/backend/generated-go/v1/sql_service.pb.gw.go
+++ b/backend/generated-go/v1/sql_service.pb.gw.go
@@ -150,6 +150,45 @@ func local_request_SQLService_SearchQueryHistories_0(ctx context.Context, marsha
return msg, metadata, err
}
+func request_SQLService_GetQueryHistory_0(ctx context.Context, marshaler runtime.Marshaler, client SQLServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq GetQueryHistoryRequest
+ metadata runtime.ServerMetadata
+ err error
+ )
+ if req.Body != nil {
+ _, _ = io.Copy(io.Discard, req.Body)
+ }
+ 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 := client.GetQueryHistory(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
+ return msg, metadata, err
+}
+
+func local_request_SQLService_GetQueryHistory_0(ctx context.Context, marshaler runtime.Marshaler, server SQLServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq GetQueryHistoryRequest
+ metadata runtime.ServerMetadata
+ err error
+ )
+ 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.GetQueryHistory(ctx, &protoReq)
+ return msg, metadata, err
+}
+
func request_SQLService_Export_0(ctx context.Context, marshaler runtime.Marshaler, client SQLServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var (
protoReq ExportRequest
@@ -392,6 +431,26 @@ func RegisterSQLServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux,
}
forward_SQLService_SearchQueryHistories_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
+ mux.Handle(http.MethodGet, pattern_SQLService_GetQueryHistory_0, 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/GetQueryHistory", runtime.WithHTTPPathPattern("/v1/{name=projects/*/queryHistories/*}"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := local_request_SQLService_GetQueryHistory_0(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_GetQueryHistory_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
mux.Handle(http.MethodPost, pattern_SQLService_Export_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
@@ -583,6 +642,23 @@ func RegisterSQLServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux,
}
forward_SQLService_SearchQueryHistories_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
+ mux.Handle(http.MethodGet, pattern_SQLService_GetQueryHistory_0, 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/GetQueryHistory", runtime.WithHTTPPathPattern("/v1/{name=projects/*/queryHistories/*}"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := request_SQLService_GetQueryHistory_0(annotatedContext, inboundMarshaler, client, req, pathParams)
+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
+ if err != nil {
+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ forward_SQLService_GetQueryHistory_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
mux.Handle(http.MethodPost, pattern_SQLService_Export_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
@@ -675,6 +751,7 @@ 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_AdminExecute_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0}, []string{"v1"}, "adminExecute"))
pattern_SQLService_SearchQueryHistories_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "queryHistories"}, "search"))
+ pattern_SQLService_GetQueryHistory_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 2, 2, 1, 0, 4, 4, 5, 3}, []string{"v1", "projects", "queryHistories", "name"}, ""))
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, 4, 5, 5, 4}, []string{"v1", "projects", "plans", "rollout", "name"}, "export"))
pattern_SQLService_Export_2 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 2, 2, 1, 0, 2, 3, 2, 4, 1, 0, 4, 7, 5, 5}, []string{"v1", "projects", "plans", "rollout", "stages", "name"}, "export"))
@@ -686,6 +763,7 @@ var (
forward_SQLService_Query_0 = runtime.ForwardResponseMessage
forward_SQLService_AdminExecute_0 = runtime.ForwardResponseStream
forward_SQLService_SearchQueryHistories_0 = runtime.ForwardResponseMessage
+ forward_SQLService_GetQueryHistory_0 = runtime.ForwardResponseMessage
forward_SQLService_Export_0 = runtime.ForwardResponseMessage
forward_SQLService_Export_1 = runtime.ForwardResponseMessage
forward_SQLService_Export_2 = runtime.ForwardResponseMessage
diff --git a/backend/generated-go/v1/sql_service_equal.pb.go b/backend/generated-go/v1/sql_service_equal.pb.go
index 029bd3d6ba..4a53755700 100644
--- a/backend/generated-go/v1/sql_service_equal.pb.go
+++ b/backend/generated-go/v1/sql_service_equal.pb.go
@@ -570,6 +570,19 @@ func (x *SearchQueryHistoriesRequest) Equal(y *SearchQueryHistoriesRequest) bool
return true
}
+func (x *GetQueryHistoryRequest) Equal(y *GetQueryHistoryRequest) bool {
+ if x == y {
+ return true
+ }
+ if x == nil || y == nil {
+ return x == nil && y == nil
+ }
+ if x.Name != y.Name {
+ return false
+ }
+ return true
+}
+
func (x *SearchQueryHistoriesResponse) Equal(y *SearchQueryHistoriesResponse) bool {
if x == y {
return true
diff --git a/backend/generated-go/v1/sql_service_grpc.pb.go b/backend/generated-go/v1/sql_service_grpc.pb.go
index 85d64dbe07..d738628b62 100644
--- a/backend/generated-go/v1/sql_service_grpc.pb.go
+++ b/backend/generated-go/v1/sql_service_grpc.pb.go
@@ -22,6 +22,7 @@ const (
SQLService_Query_FullMethodName = "/bytebase.v1.SQLService/Query"
SQLService_AdminExecute_FullMethodName = "/bytebase.v1.SQLService/AdminExecute"
SQLService_SearchQueryHistories_FullMethodName = "/bytebase.v1.SQLService/SearchQueryHistories"
+ SQLService_GetQueryHistory_FullMethodName = "/bytebase.v1.SQLService/GetQueryHistory"
SQLService_Export_FullMethodName = "/bytebase.v1.SQLService/Export"
SQLService_DiffMetadata_FullMethodName = "/bytebase.v1.SQLService/DiffMetadata"
SQLService_AICompletion_FullMethodName = "/bytebase.v1.SQLService/AICompletion"
@@ -42,6 +43,9 @@ type SQLServiceClient interface {
// SearchQueryHistories searches query histories for the caller.
// Permissions required: None (only returns caller's own query histories)
SearchQueryHistories(ctx context.Context, in *SearchQueryHistoriesRequest, opts ...grpc.CallOption) (*SearchQueryHistoriesResponse, error)
+ // GetQueryHistory gets a single query history for the caller.
+ // Permissions required: None (only returns the caller's own query history)
+ GetQueryHistory(ctx context.Context, in *GetQueryHistoryRequest, opts ...grpc.CallOption) (*QueryHistory, error)
// Exports query results to a file format.
// Permissions required: bb.databases.get
Export(ctx context.Context, in *ExportRequest, opts ...grpc.CallOption) (*ExportResponse, error)
@@ -94,6 +98,16 @@ func (c *sQLServiceClient) SearchQueryHistories(ctx context.Context, in *SearchQ
return out, nil
}
+func (c *sQLServiceClient) GetQueryHistory(ctx context.Context, in *GetQueryHistoryRequest, opts ...grpc.CallOption) (*QueryHistory, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(QueryHistory)
+ err := c.cc.Invoke(ctx, SQLService_GetQueryHistory_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
func (c *sQLServiceClient) Export(ctx context.Context, in *ExportRequest, opts ...grpc.CallOption) (*ExportResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ExportResponse)
@@ -139,6 +153,9 @@ type SQLServiceServer interface {
// SearchQueryHistories searches query histories for the caller.
// Permissions required: None (only returns caller's own query histories)
SearchQueryHistories(context.Context, *SearchQueryHistoriesRequest) (*SearchQueryHistoriesResponse, error)
+ // GetQueryHistory gets a single query history for the caller.
+ // Permissions required: None (only returns the caller's own query history)
+ GetQueryHistory(context.Context, *GetQueryHistoryRequest) (*QueryHistory, error)
// Exports query results to a file format.
// Permissions required: bb.databases.get
Export(context.Context, *ExportRequest) (*ExportResponse, error)
@@ -167,6 +184,9 @@ func (UnimplementedSQLServiceServer) AdminExecute(grpc.BidiStreamingServer[Admin
func (UnimplementedSQLServiceServer) SearchQueryHistories(context.Context, *SearchQueryHistoriesRequest) (*SearchQueryHistoriesResponse, error) {
return nil, status.Error(codes.Unimplemented, "method SearchQueryHistories not implemented")
}
+func (UnimplementedSQLServiceServer) GetQueryHistory(context.Context, *GetQueryHistoryRequest) (*QueryHistory, error) {
+ return nil, status.Error(codes.Unimplemented, "method GetQueryHistory not implemented")
+}
func (UnimplementedSQLServiceServer) Export(context.Context, *ExportRequest) (*ExportResponse, error) {
return nil, status.Error(codes.Unimplemented, "method Export not implemented")
}
@@ -240,6 +260,24 @@ func _SQLService_SearchQueryHistories_Handler(srv interface{}, ctx context.Conte
return interceptor(ctx, in, info, handler)
}
+func _SQLService_GetQueryHistory_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(GetQueryHistoryRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SQLServiceServer).GetQueryHistory(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SQLService_GetQueryHistory_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SQLServiceServer).GetQueryHistory(ctx, req.(*GetQueryHistoryRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
func _SQLService_Export_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ExportRequest)
if err := dec(in); err != nil {
@@ -309,6 +347,10 @@ var SQLService_ServiceDesc = grpc.ServiceDesc{
MethodName: "SearchQueryHistories",
Handler: _SQLService_SearchQueryHistories_Handler,
},
+ {
+ MethodName: "GetQueryHistory",
+ Handler: _SQLService_GetQueryHistory_Handler,
+ },
{
MethodName: "Export",
Handler: _SQLService_Export_Handler,
diff --git a/backend/generated-go/v1/v1connect/sql_service.connect.go b/backend/generated-go/v1/v1connect/sql_service.connect.go
index bc87b14e2d..505ef6cddf 100644
--- a/backend/generated-go/v1/v1connect/sql_service.connect.go
+++ b/backend/generated-go/v1/v1connect/sql_service.connect.go
@@ -40,6 +40,9 @@ const (
// SQLServiceSearchQueryHistoriesProcedure is the fully-qualified name of the SQLService's
// SearchQueryHistories RPC.
SQLServiceSearchQueryHistoriesProcedure = "/bytebase.v1.SQLService/SearchQueryHistories"
+ // SQLServiceGetQueryHistoryProcedure is the fully-qualified name of the SQLService's
+ // GetQueryHistory RPC.
+ SQLServiceGetQueryHistoryProcedure = "/bytebase.v1.SQLService/GetQueryHistory"
// SQLServiceExportProcedure is the fully-qualified name of the SQLService's Export RPC.
SQLServiceExportProcedure = "/bytebase.v1.SQLService/Export"
// SQLServiceDiffMetadataProcedure is the fully-qualified name of the SQLService's DiffMetadata RPC.
@@ -59,6 +62,9 @@ type SQLServiceClient interface {
// SearchQueryHistories searches query histories for the caller.
// Permissions required: None (only returns caller's own query histories)
SearchQueryHistories(context.Context, *connect.Request[v1.SearchQueryHistoriesRequest]) (*connect.Response[v1.SearchQueryHistoriesResponse], error)
+ // GetQueryHistory gets a single query history for the caller.
+ // Permissions required: None (only returns the caller's own query history)
+ GetQueryHistory(context.Context, *connect.Request[v1.GetQueryHistoryRequest]) (*connect.Response[v1.QueryHistory], error)
// Exports query results to a file format.
// Permissions required: bb.databases.get
Export(context.Context, *connect.Request[v1.ExportRequest]) (*connect.Response[v1.ExportResponse], error)
@@ -99,6 +105,12 @@ func NewSQLServiceClient(httpClient connect.HTTPClient, baseURL string, opts ...
connect.WithSchema(sQLServiceMethods.ByName("SearchQueryHistories")),
connect.WithClientOptions(opts...),
),
+ getQueryHistory: connect.NewClient[v1.GetQueryHistoryRequest, v1.QueryHistory](
+ httpClient,
+ baseURL+SQLServiceGetQueryHistoryProcedure,
+ connect.WithSchema(sQLServiceMethods.ByName("GetQueryHistory")),
+ connect.WithClientOptions(opts...),
+ ),
export: connect.NewClient[v1.ExportRequest, v1.ExportResponse](
httpClient,
baseURL+SQLServiceExportProcedure,
@@ -125,6 +137,7 @@ type sQLServiceClient struct {
query *connect.Client[v1.QueryRequest, v1.QueryResponse]
adminExecute *connect.Client[v1.AdminExecuteRequest, v1.AdminExecuteResponse]
searchQueryHistories *connect.Client[v1.SearchQueryHistoriesRequest, v1.SearchQueryHistoriesResponse]
+ getQueryHistory *connect.Client[v1.GetQueryHistoryRequest, v1.QueryHistory]
export *connect.Client[v1.ExportRequest, v1.ExportResponse]
diffMetadata *connect.Client[v1.DiffMetadataRequest, v1.DiffMetadataResponse]
aICompletion *connect.Client[v1.AICompletionRequest, v1.AICompletionResponse]
@@ -145,6 +158,11 @@ func (c *sQLServiceClient) SearchQueryHistories(ctx context.Context, req *connec
return c.searchQueryHistories.CallUnary(ctx, req)
}
+// GetQueryHistory calls bytebase.v1.SQLService.GetQueryHistory.
+func (c *sQLServiceClient) GetQueryHistory(ctx context.Context, req *connect.Request[v1.GetQueryHistoryRequest]) (*connect.Response[v1.QueryHistory], error) {
+ return c.getQueryHistory.CallUnary(ctx, req)
+}
+
// Export calls bytebase.v1.SQLService.Export.
func (c *sQLServiceClient) Export(ctx context.Context, req *connect.Request[v1.ExportRequest]) (*connect.Response[v1.ExportResponse], error) {
return c.export.CallUnary(ctx, req)
@@ -171,6 +189,9 @@ type SQLServiceHandler interface {
// SearchQueryHistories searches query histories for the caller.
// Permissions required: None (only returns caller's own query histories)
SearchQueryHistories(context.Context, *connect.Request[v1.SearchQueryHistoriesRequest]) (*connect.Response[v1.SearchQueryHistoriesResponse], error)
+ // GetQueryHistory gets a single query history for the caller.
+ // Permissions required: None (only returns the caller's own query history)
+ GetQueryHistory(context.Context, *connect.Request[v1.GetQueryHistoryRequest]) (*connect.Response[v1.QueryHistory], error)
// Exports query results to a file format.
// Permissions required: bb.databases.get
Export(context.Context, *connect.Request[v1.ExportRequest]) (*connect.Response[v1.ExportResponse], error)
@@ -207,6 +228,12 @@ func NewSQLServiceHandler(svc SQLServiceHandler, opts ...connect.HandlerOption)
connect.WithSchema(sQLServiceMethods.ByName("SearchQueryHistories")),
connect.WithHandlerOptions(opts...),
)
+ sQLServiceGetQueryHistoryHandler := connect.NewUnaryHandler(
+ SQLServiceGetQueryHistoryProcedure,
+ svc.GetQueryHistory,
+ connect.WithSchema(sQLServiceMethods.ByName("GetQueryHistory")),
+ connect.WithHandlerOptions(opts...),
+ )
sQLServiceExportHandler := connect.NewUnaryHandler(
SQLServiceExportProcedure,
svc.Export,
@@ -233,6 +260,8 @@ func NewSQLServiceHandler(svc SQLServiceHandler, opts ...connect.HandlerOption)
sQLServiceAdminExecuteHandler.ServeHTTP(w, r)
case SQLServiceSearchQueryHistoriesProcedure:
sQLServiceSearchQueryHistoriesHandler.ServeHTTP(w, r)
+ case SQLServiceGetQueryHistoryProcedure:
+ sQLServiceGetQueryHistoryHandler.ServeHTTP(w, r)
case SQLServiceExportProcedure:
sQLServiceExportHandler.ServeHTTP(w, r)
case SQLServiceDiffMetadataProcedure:
@@ -260,6 +289,10 @@ func (UnimplementedSQLServiceHandler) SearchQueryHistories(context.Context, *con
return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.SQLService.SearchQueryHistories is not implemented"))
}
+func (UnimplementedSQLServiceHandler) GetQueryHistory(context.Context, *connect.Request[v1.GetQueryHistoryRequest]) (*connect.Response[v1.QueryHistory], error) {
+ return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.SQLService.GetQueryHistory is not implemented"))
+}
+
func (UnimplementedSQLServiceHandler) Export(context.Context, *connect.Request[v1.ExportRequest]) (*connect.Response[v1.ExportResponse], error) {
return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.SQLService.Export is not implemented"))
}
diff --git a/backend/store/query_history.go b/backend/store/query_history.go
index d60b5eb342..f9c940eb09 100644
--- a/backend/store/query_history.go
+++ b/backend/store/query_history.go
@@ -2,6 +2,7 @@ package store
import (
"context"
+ "strings"
"time"
"github.com/google/cel-go/cel"
@@ -46,8 +47,9 @@ type QueryHistoryMessage struct {
// FindQueryHistoryMessage is the API message for finding query histories.
type FindQueryHistoryMessage struct {
- Creator *string
- Project *string
+ ResourceID *string
+ Creator *string
+ Project *string
// Instance is the instance resource name like instances/{instance}.
Instance *string
// Database is database resource name like instances/{instance}/databases/{database}.
@@ -122,6 +124,9 @@ func (s *Store) ListQueryHistories(ctx context.Context, find *FindQueryHistoryMe
if filterQ := find.FilterQ; filterQ != nil {
q.And("?", filterQ)
}
+ if v := find.ResourceID; v != nil {
+ q.And("query_history.resource_id = ?", *v)
+ }
if v := find.Creator; v != nil {
q.And("query_history.creator = ?", *v)
}
@@ -188,6 +193,23 @@ func (s *Store) ListQueryHistories(ctx context.Context, find *FindQueryHistoryMe
return queryHistories, nil
}
+// GetQueryHistory gets a single query history by its resource id. Returns nil
+// when no matching record exists.
+func (s *Store) GetQueryHistory(ctx context.Context, resourceID string) (*QueryHistoryMessage, error) {
+ limit := 1
+ histories, err := s.ListQueryHistories(ctx, &FindQueryHistoryMessage{
+ ResourceID: &resourceID,
+ Limit: &limit,
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(histories) == 0 {
+ return nil, nil
+ }
+ return histories[0], nil
+}
+
func GetListQueryHistoryFilter(filter string) (*qb.Query, error) {
if filter == "" {
return nil, nil
@@ -267,7 +289,13 @@ func GetListQueryHistoryFilter(filter string) (*qb.Query, error) {
if !ok {
return nil, errors.Errorf("expect string, got %T, hint: filter literals should be string", value)
}
- return parseToSQL("statement", "%"+strValue+"%")
+ // Normalize whitespace on both sides so a single-line search
+ // like "SELECT * FROM t" matches a stored multi-line statement
+ // "SELECT\n *\nFROM t", and match case-insensitively. Mirrors
+ // the access-grant `query.contains` search in
+ // GetListAccessGrantFilter.
+ normalizedValue := strings.Join(strings.Fields(strValue), " ")
+ return qb.Q().Space("regexp_replace(query_history.statement, '\\s+', ' ', 'g') ILIKE ?", "%"+normalizedValue+"%"), nil
default:
return nil, errors.Errorf("unexpected function %v", functionName)
}
diff --git a/backend/store/query_history_filter_test.go b/backend/store/query_history_filter_test.go
index f6704ef79b..a82c016026 100644
--- a/backend/store/query_history_filter_test.go
+++ b/backend/store/query_history_filter_test.go
@@ -60,7 +60,7 @@ func TestGetListQueryHistoryFilter(t *testing.T) {
{
name: "statement contains operator",
filter: `statement.contains("SELECT")`,
- wantSQL: "(query_history.statement LIKE $1)",
+ wantSQL: "(regexp_replace(query_history.statement, '\\s+', ' ', 'g') ILIKE $1)",
wantArgs: []any{"%SELECT%"},
wantErr: false,
},
@@ -102,7 +102,7 @@ func TestGetListQueryHistoryFilter(t *testing.T) {
{
name: "complex nested with statement contains",
filter: `project == "projects/test" && statement.contains("SELECT") && type == "QUERY"`,
- wantSQL: "(((query_history.project = $1 AND query_history.statement LIKE $2) AND query_history.type = $3))",
+ wantSQL: "(((query_history.project = $1 AND regexp_replace(query_history.statement, '\\s+', ' ', 'g') ILIKE $2) AND query_history.type = $3))",
wantArgs: []any{"test", "%SELECT%", QueryHistoryType("QUERY")},
wantErr: false,
},
@@ -195,7 +195,7 @@ func TestGetListQueryHistoryFilter_EdgeCases(t *testing.T) {
name: "statement contains punctuation literally",
filter: `statement.contains("SELECT.*FROM")`,
description: "contains should treat punctuation as plain substring content",
- wantSQL: "(query_history.statement LIKE $1)",
+ wantSQL: "(regexp_replace(query_history.statement, '\\s+', ' ', 'g') ILIKE $1)",
wantArgs: []any{"%SELECT.*FROM%"},
wantErr: false,
},
@@ -227,7 +227,7 @@ func TestGetListQueryHistoryFilter_EdgeCases(t *testing.T) {
name: "complex filter with all supported fields",
filter: `project == "projects/test" && database == "instances/i1/databases/db1" && type == "EXPORT" && statement.contains("INSERT")`,
description: "combination of all supported filter types",
- wantSQL: "(((query_history.project = $1 AND query_history.database = $2) AND (query_history.type = $3 AND query_history.statement LIKE $4)))",
+ wantSQL: "(((query_history.project = $1 AND query_history.database = $2) AND (query_history.type = $3 AND regexp_replace(query_history.statement, '\\s+', ' ', 'g') ILIKE $4)))",
wantArgs: []any{"test", "instances/i1/databases/db1", QueryHistoryType("EXPORT"), "%INSERT%"},
wantErr: false,
},
@@ -282,7 +282,7 @@ func TestGetListQueryHistoryFilter_CompareWithOriginal(t *testing.T) {
{
name: "statement contains",
filter: `statement.contains("SELECT")`,
- expectedConditions: []string{"query_history.statement LIKE $1"},
+ expectedConditions: []string{"regexp_replace(query_history.statement, '\\s+', ' ', 'g') ILIKE $1"},
},
{
name: "OR condition",
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 43f6436f5c..8bb6b47eb6 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -2694,6 +2694,7 @@
"copy-all-column-names": "Copy all column names",
"copy-all-rows-as-csv": "Copy all rows as CSV",
"copy-all-rows-as-sql": "Copy all rows as SQL",
+ "copy-history-link": "Copy history link",
"copy-name": "Copy name",
"copy-selected-results": "Copy selected data by <action></action> or <button></button>",
"copy-selected-rows-as-csv": "Copy selected rows as CSV",
@@ -2747,6 +2748,7 @@
"notify-empty-statement": "Please input your SQL statements in the editor",
"only-select-allowed": "Only read-only statements are allowed to execute.",
"open-in-new-tab": "Open in new tab",
+ "opened-from-link": "Opened from link",
"pending-query": "Pending query",
"preview-table-data": "Preview table data",
"previous-row": "Previous Row",
@@ -2759,8 +2761,10 @@
"query-context": {
"admin-data-source-is-disallowed-to-query": "Admin data source is disallowed to query."
},
+ "query-history-not-found": "Query history not found or no longer accessible",
"query-time": "Query time",
"re-request": "Re-request",
+ "recent": "Recent",
"redis-command": {
"all-nodes": "All nodes",
"only-for-cluster": "Only available for cluster connection",
@@ -2817,6 +2821,7 @@
"table-empty-placeholder": "Click Run to execute the query.",
"table-view": "Table view",
"text-format": "Text format",
+ "unable-to-connect-database": "Unable to connect to database {{name}}",
"upload-file": "Upload file",
"url-copied-to-clipboard": "The URL is copied to your clipboard",
"vertical-display": "Vertical display",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 0c58777da7..831134aafa 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -2694,6 +2694,7 @@
"copy-all-column-names": "Copiar todos los nombres de las columnas",
"copy-all-rows-as-csv": "Copiar todas las filas como CSV",
"copy-all-rows-as-sql": "Copiar todas las filas como SQL",
+ "copy-history-link": "Copiar enlace del historial",
"copy-name": "Copiar nombre",
"copy-selected-results": "Copiar datos seleccionados por <action></action> o <button></button>",
"copy-selected-rows-as-csv": "Copiar las filas seleccionadas como CSV",
@@ -2747,6 +2748,7 @@
"notify-empty-statement": "Ingrese sus declaraciones SQL en el editor",
"only-select-allowed": "Solo se permiten ejecutar declaraciones de solo lectura.",
"open-in-new-tab": "Abrir en nueva pestaña",
+ "opened-from-link": "Abierto desde enlace",
"pending-query": "Consulta pendiente",
"preview-table-data": "Vista previa de datos de la tabla",
"previous-row": "Fila anterior",
@@ -2759,8 +2761,10 @@
"query-context": {
"admin-data-source-is-disallowed-to-query": "No se permite realizar consultas a la fuente de datos del administrador."
},
+ "query-history-not-found": "Historial de consultas no encontrado o ya no accesible",
"query-time": "Tiempo de consulta",
"re-request": "Volver a solicitar",
+ "recent": "Reciente",
"redis-command": {
"all-nodes": "Todos los nodos",
"only-for-cluster": "Sólo disponible para conexión de clúster",
@@ -2817,6 +2821,7 @@
"table-empty-placeholder": "Haga clic en Ejecutar para ejecutar la consulta.",
"table-view": "Vista de tabla",
"text-format": "Formato de texto",
+ "unable-to-connect-database": "No se puede conectar a la base de datos {{name}}",
"upload-file": "Subir archivo",
"url-copied-to-clipboard": "La URL se copia al portapapeles.",
"vertical-display": "Pantalla vertical",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 3385e3133c..1ca9118248 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -2694,6 +2694,7 @@
"copy-all-column-names": "すべての列名をコピーします",
"copy-all-rows-as-csv": "すべての行を CSV としてコピー",
"copy-all-rows-as-sql": "すべての行を SQL としてコピー",
+ "copy-history-link": "履歴リンクをコピー",
"copy-name": "名前をコピーする",
"copy-selected-results": "選択したデータを<action></action>または<button></button>でコピーします",
"copy-selected-rows-as-csv": "選択した行を CSV としてコピー",
@@ -2747,6 +2748,7 @@
"notify-empty-statement": "エディターに SQL ステートメントを入力してください",
"only-select-allowed": "読み取り専用ステートメントのみが実行を許可されます",
"open-in-new-tab": "新しいタブで開く",
+ "opened-from-link": "リンクから開く",
"pending-query": "保留中のクエリ",
"preview-table-data": "テーブルデータのプレビュー",
"previous-row": "前の行",
@@ -2759,8 +2761,10 @@
"query-context": {
"admin-data-source-is-disallowed-to-query": "管理者データ ソースはクエリできません。"
},
+ "query-history-not-found": "クエリ履歴が見つからないか、アクセスできなくなりました",
"query-time": "クエリ時間",
"re-request": "再申請",
+ "recent": "最近",
"redis-command": {
"all-nodes": "すべてのノード",
"only-for-cluster": "クラスタ接続のみ使用可能",
@@ -2817,6 +2821,7 @@
"table-empty-placeholder": "「実行」をクリックしてクエリを実行します。",
"table-view": "テーブルビュー",
"text-format": "テキスト形式",
+ "unable-to-connect-database": "データベース {{name}} に接続できません",
"upload-file": "ファイルをアップロードする",
"url-copied-to-clipboard": "URLがクリップボードにコピーされました",
"vertical-display": "縦型表示",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 5809086b30..5d4bc10744 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -2694,6 +2694,7 @@
"copy-all-column-names": "Sao chép tất cả tên cột",
"copy-all-rows-as-csv": "Sao chép tất cả các hàng dưới dạng CSV",
"copy-all-rows-as-sql": "Sao chép tất cả các hàng dưới dạng SQL",
+ "copy-history-link": "Sao chép liên kết lịch sử",
"copy-name": "Sao chép tên",
"copy-selected-results": "Sao chép dữ liệu đã chọn bằng <action></action> hoặc <button></button>",
"copy-selected-rows-as-csv": "Sao chép các hàng đã chọn dưới dạng CSV",
@@ -2747,6 +2748,7 @@
"notify-empty-statement": "Vui lòng nhập câu lệnh SQL của bạn vào trình soạn thảo",
"only-select-allowed": "Chỉ cho phép thực thi câu lệnh chỉ đọc.",
"open-in-new-tab": "Mở trong tab mới",
+ "opened-from-link": "Mở từ liên kết",
"pending-query": "Đang chờ truy vấn",
"preview-table-data": "Xem trước dữ liệu bảng",
"previous-row": "Dòng trước",
@@ -2759,8 +2761,10 @@
"query-context": {
"admin-data-source-is-disallowed-to-query": "Nguồn dữ liệu quản trị không được phép truy vấn."
},
+ "query-history-not-found": "Không tìm thấy lịch sử truy vấn hoặc không còn truy cập được",
"query-time": "Thời gian truy vấn",
"re-request": "Yêu cầu lại",
+ "recent": "Gần đây",
"redis-command": {
"all-nodes": "Tất cả các nút",
"only-for-cluster": "Chỉ khả dụng cho kết nối cụm",
@@ -2817,6 +2821,7 @@
"table-empty-placeholder": "Nhấp vào Chạy để thực hiện truy vấn.",
"table-view": "Chế độ xem bảng",
"text-format": "Định dạng văn bản",
+ "unable-to-connect-database": "Không thể kết nối đến cơ sở dữ liệu {{name}}",
"upload-file": "Tải lên tệp",
"url-copied-to-clipboard": "URL đã được sao chép vào bảng nhớ tạm của bạn",
"vertical-display": "Hiển thị dọc",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index b2d83b333c..f861da75cf 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -2694,6 +2694,7 @@
"copy-all-column-names": "复制所有列名",
"copy-all-rows-as-csv": "将所有行复制为 CSV",
"copy-all-rows-as-sql": "将所有行复制为 SQL",
+ "copy-history-link": "复制历史记录链接",
"copy-name": "复制名称",
"copy-selected-results": "通过 <action></action> 或 <button></button> 来快速复制选定的数据",
"copy-selected-rows-as-csv": "将选定行复制为 CSV",
@@ -2747,6 +2748,7 @@
"notify-empty-statement": "请在编辑器中输入 SQL 语句",
"only-select-allowed": "只允许执行只读语句",
"open-in-new-tab": "在新选项卡中打开",
+ "opened-from-link": "从链接打开",
"pending-query": "待处理查询",
"preview-table-data": "预览表数据",
"previous-row": "上一行",
@@ -2759,8 +2761,10 @@
"query-context": {
"admin-data-source-is-disallowed-to-query": "禁止查询主数据源。"
},
+ "query-history-not-found": "查询历史记录不存在或已无法访问",
"query-time": "查询时间",
"re-request": "重新申请",
+ "recent": "最近",
"redis-command": {
"all-nodes": "所有节点",
"only-for-cluster": "仅适用于集群连接",
@@ -2817,6 +2821,7 @@
"table-empty-placeholder": "点击 \"运行\" 执行查询",
"table-view": "表格视图",
"text-format": "文本格式",
+ "unable-to-connect-database": "无法连接到数据库 {{name}}",
"upload-file": "上传文件",
"url-copied-to-clipboard": "URL 已复制到剪贴板",
"vertical-display": "竖向展示",
diff --git a/frontend/src/react/components/sql-editor/HistoryPane.test.tsx b/frontend/src/react/components/sql-editor/HistoryPane.test.tsx
index 5df40f2b31..3f62c897ed 100644
--- a/frontend/src/react/components/sql-editor/HistoryPane.test.tsx
+++ b/frontend/src/react/components/sql-editor/HistoryPane.test.tsx
@@ -26,21 +26,49 @@ const mocks = vi.hoisted(() => ({
resetPageToken: vi.fn(),
pushNotification: vi.fn(),
sqlEditorEventsEmit: vi.fn().mockResolvedValue(undefined),
+ externalUrl: "https://example.com" as string | undefined,
+ linkedQueryHistory: undefined as
+ | { name: string; statement: string; createTime: unknown }
+ | undefined,
+ linkedQueryHistoryTabId: "tab1" as string | undefined,
+ setLinkedQueryHistory: vi.fn(),
}));
vi.mock("react-i18next", () => ({
useTranslation: mocks.useTranslation,
}));
-vi.mock("@/react/stores/app", () => ({
- // Route `useAppStore.getState().notify(...)` through the same vi.fn the
- // tests asserted against under the legacy `pushNotification` API so the
- // assertion bodies stay readable.
- useAppStore: {
- getState: () => ({ notify: mocks.pushNotification }),
+vi.mock("@/react/stores/app", () => {
+ // `useAppStore` is used both as a selector hook (for
+ // `serverInfo.externalUrl`) and via `.getState().notify(...)`. Route
+ // `notify` through the same vi.fn the tests asserted against under the
+ // legacy `pushNotification` API so the assertion bodies stay readable.
+ const state = () => ({
+ notify: mocks.pushNotification,
+ serverInfo: { externalUrl: mocks.externalUrl },
+ });
+ const useAppStore = (selector?: (s: ReturnType<typeof state>) => unknown) =>
+ selector ? selector(state()) : state();
+ useAppStore.getState = state;
+ return { useAppStore };
+});
+
+vi.mock("@/react/router", () => ({
+ router: {
+ resolve: ({
+ params,
+ }: {
+ params: { project: string; queryHistory: string };
+ }) => ({
+ href: `/sql-editor/projects/${params.project}/queryHistories/${params.queryHistory}`,
+ }),
},
}));
+vi.mock("@/react/router/handles", () => ({
+ SQL_EDITOR_QUERY_HISTORY_MODULE: "sql-editor.query-history",
+}));
+
// Zustand tab store — selector hook + imperative getter.
vi.mock("@/react/stores/sqlEditor/tab", () => ({
useSQLEditorTabState: (
@@ -74,11 +102,17 @@ vi.mock("@/react/stores/sqlEditor", () => ({
selector: (s: {
fetchQueryHistoryList: typeof mocks.fetchQueryHistoryList;
resetPageToken: typeof mocks.resetPageToken;
+ linkedQueryHistory: typeof mocks.linkedQueryHistory;
+ linkedQueryHistoryTabId: typeof mocks.linkedQueryHistoryTabId;
+ setLinkedQueryHistory: typeof mocks.setLinkedQueryHistory;
}) => unknown
) =>
selector({
fetchQueryHistoryList: mocks.fetchQueryHistoryList,
resetPageToken: mocks.resetPageToken,
+ linkedQueryHistory: mocks.linkedQueryHistory,
+ linkedQueryHistoryTabId: mocks.linkedQueryHistoryTabId,
+ setLinkedQueryHistory: mocks.setLinkedQueryHistory,
}),
}));
@@ -117,9 +151,22 @@ vi.mock("@/types", () => ({
}));
vi.mock("@/utils", () => ({
- getHighlightHTMLByKeyWords: vi.fn((s: string, _k: string) =>
- s.replace(/</g, "&lt;").replace(/>/g, "&gt;")
- ),
+ extractProjectResourceName: (name: string) =>
+ name.match(/(?:^|\/)projects\/([^/]+)(?:$|\/)/)?.[1] ?? "",
+ extractQueryHistoryUID: (name: string) =>
+ name.match(/(?:^|\/)queryHistories\/([^/]+)(?:$|\/)/)?.[1] ?? "-1",
+}));
+
+// The real HighlightLabelText pulls in `@/utils/util` (DOMPurify + i18n init);
+// stub it to render the text so textContent assertions still hold.
+vi.mock("@/react/components/HighlightLabelText", () => ({
+ HighlightLabelText: ({
+ text,
+ className,
+ }: {
+ text: string;
+ className?: string;
+ }) => <span className={className}>{text}</span>,
}));
vi.mock("dayjs", () => {
@@ -171,6 +218,9 @@ beforeEach(async () => {
mocks.currentTabDatabase = "db/test";
mocks.project = "projects/proj1";
+ mocks.externalUrl = "https://example.com";
+ mocks.linkedQueryHistory = undefined;
+ mocks.linkedQueryHistoryTabId = "tab1";
mocks.historyEntry = { queryHistories: [], nextPageToken: "" };
mocks.fetchQueryHistoryList.mockResolvedValue({ queryHistories: [] });
@@ -296,4 +346,147 @@ describe("HistoryPane", () => {
expect(mocks.pushNotification).toHaveBeenCalledTimes(1);
unmount();
});
+
+ test("click copy-link button → clipboard writes the external deep link", async () => {
+ mocks.historyEntry = {
+ queryHistories: [
+ makeHistory("projects/proj1/queryHistories/h1", "SELECT * FROM users"),
+ ],
+ nextPageToken: "",
+ };
+
+ const { container, render, unmount } = renderIntoContainer(<HistoryPane />);
+ render();
+
+ const copyLinkBtn = container.querySelector(
+ "[data-copy-link-btn]"
+ ) as HTMLButtonElement;
+ expect(copyLinkBtn).not.toBeNull();
+
+ await act(async () => {
+ copyLinkBtn.click();
+ });
+
+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
+ "https://example.com/sql-editor/projects/proj1/queryHistories/h1"
+ );
+ expect(mocks.pushNotification).toHaveBeenCalledTimes(1);
+ unmount();
+ });
+
+ test("copy-link button falls back to window origin when externalUrl unset", async () => {
+ mocks.externalUrl = undefined;
+ mocks.historyEntry = {
+ queryHistories: [
+ makeHistory("projects/proj1/queryHistories/h1", "SELECT * FROM users"),
+ ],
+ nextPageToken: "",
+ };
+
+ const { container, render, unmount } = renderIntoContainer(<HistoryPane />);
+ render();
+
+ const copyLinkBtn = container.querySelector(
+ "[data-copy-link-btn]"
+ ) as HTMLButtonElement;
+
+ await act(async () => {
+ copyLinkBtn.click();
+ });
+
+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
+ `${window.location.origin}/sql-editor/projects/proj1/queryHistories/h1`
+ );
+ unmount();
+ });
+
+ test("opened-from-link section renders the linked history and recent header", () => {
+ mocks.linkedQueryHistory = makeHistory(
+ "projects/proj1/queryHistories/h1",
+ "SELECT * FROM salary"
+ );
+ mocks.historyEntry = {
+ queryHistories: [makeHistory("histories/h2", "SELECT * FROM employee")],
+ nextPageToken: "",
+ };
+
+ const { container, render, unmount } = renderIntoContainer(<HistoryPane />);
+ render();
+
+ const linkedSection = container.querySelector("[data-linked-history]");
+ expect(linkedSection).not.toBeNull();
+ expect(container.textContent).toContain("sql-editor.opened-from-link");
+ expect(container.textContent).toContain("SELECT * FROM salary");
+ // Recent header appears because there is a non-linked recent entry.
+ expect(container.textContent).toContain("sql-editor.recent");
+ expect(container.textContent).toContain("SELECT * FROM employee");
+ unmount();
+ });
+
+ test("linked history is not duplicated in the recent list", () => {
+ mocks.linkedQueryHistory = makeHistory(
+ "projects/proj1/queryHistories/h1",
+ "SELECT * FROM salary"
+ );
+ // The recent list also contains the linked entry (same name) plus another.
+ mocks.historyEntry = {
+ queryHistories: [
+ makeHistory("projects/proj1/queryHistories/h1", "SELECT * FROM salary"),
+ makeHistory("histories/h2", "SELECT * FROM employee"),
+ ],
+ nextPageToken: "",
+ };
+
+ const { container, render, unmount } = renderIntoContainer(<HistoryPane />);
+ render();
+
+ // One linked row + one recent row (the duplicate is filtered out).
+ expect(container.querySelectorAll("[data-history-row]").length).toBe(2);
+ unmount();
+ });
+
+ test("opened-from-link section is hidden when another tab is active", () => {
+ mocks.linkedQueryHistory = makeHistory(
+ "projects/proj1/queryHistories/h1",
+ "SELECT * FROM salary"
+ );
+ // Linked draft tab is not the active tab (active is "tab1").
+ mocks.linkedQueryHistoryTabId = "other-tab";
+ mocks.historyEntry = {
+ queryHistories: [makeHistory("histories/h2", "SELECT * FROM employee")],
+ nextPageToken: "",
+ };
+
+ const { container, render, unmount } = renderIntoContainer(<HistoryPane />);
+ render();
+
+ expect(container.querySelector("[data-linked-history]")).toBeNull();
+ expect(container.textContent).not.toContain("sql-editor.opened-from-link");
+ // Recent header is also hidden — it only pairs with the linked section.
+ expect(container.textContent).not.toContain("sql-editor.recent");
+ expect(container.textContent).toContain("SELECT * FROM employee");
+ unmount();
+ });
+
+ test("dismiss button clears the linked history", async () => {
+ mocks.linkedQueryHistory = makeHistory(
+ "projects/proj1/queryHistories/h1",
+ "SELECT * FROM salary"
+ );
+
+ const { container, render, unmount } = renderIntoContainer(<HistoryPane />);
+ render();
+
+ const dismissBtn = container.querySelector(
+ "[data-dismiss-linked-history]"
+ ) as HTMLButtonElement;
+ expect(dismissBtn).not.toBeNull();
+
+ await act(async () => {
+ dismissBtn.click();
+ });
+
+ expect(mocks.setLinkedQueryHistory).toHaveBeenCalledWith(undefined);
+ unmount();
+ });
});
diff --git a/frontend/src/react/components/sql-editor/HistoryPane.tsx b/frontend/src/react/components/sql-editor/HistoryPane.tsx
index c155a0bb4f..b26cc4f5f6 100644
--- a/frontend/src/react/components/sql-editor/HistoryPane.tsx
+++ b/frontend/src/react/components/sql-editor/HistoryPane.tsx
@@ -1,5 +1,5 @@
import dayjs from "dayjs";
-import { Copy, Loader2 } from "lucide-react";
+import { Copy, Link2, Loader2, X } from "lucide-react";
import {
useCallback,
useEffect,
@@ -9,8 +9,12 @@ import {
useState,
} from "react";
import { useTranslation } from "react-i18next";
+import { HighlightLabelText } from "@/react/components/HighlightLabelText";
import { Button } from "@/react/components/ui/button";
import { SearchInput } from "@/react/components/ui/search-input";
+import { cn } from "@/react/lib/utils";
+import { router } from "@/react/router";
+import { SQL_EDITOR_QUERY_HISTORY_MODULE } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
import type { QueryHistoryFilter } from "@/react/stores/sqlEditor";
import {
@@ -24,7 +28,7 @@ import {
} from "@/react/stores/sqlEditor/tab";
import { DEBOUNCE_SEARCH_DELAY, getDateForPbTimestampProtoEs } from "@/types";
import type { QueryHistory } from "@/types/proto-es/v1/sql_service_pb";
-import { getHighlightHTMLByKeyWords } from "@/utils";
+import { extractProjectResourceName, extractQueryHistoryUID } from "@/utils";
import { sqlEditorEvents } from "@/views/sql-editor/events";
/**
@@ -38,6 +42,15 @@ export function HistoryPane() {
(s) => s.fetchQueryHistoryList
);
const resetPageToken = useSQLEditorStore((s) => s.resetPageToken);
+ const workspaceExternalURL = useAppStore((s) => s.serverInfo?.externalUrl);
+ const linkedQueryHistory = useSQLEditorStore((s) => s.linkedQueryHistory);
+ const linkedQueryHistoryTabId = useSQLEditorStore(
+ (s) => s.linkedQueryHistoryTabId
+ );
+ const setLinkedQueryHistory = useSQLEditorStore(
+ (s) => s.setLinkedQueryHistory
+ );
+ const currentTabId = useSQLEditorTabState((s) => s.currentTabId);
const [searchText, setSearchText] = useState("");
const [loading, setLoading] = useState(false);
@@ -141,6 +154,108 @@ export function HistoryPane() {
}
};
+ // Builds a shareable deep link to a query history. Opening it loads the
+ // statement into a new draft tab — see `SQLEditorRouteShell`.
+ const buildHistoryLink = (history: QueryHistory) => {
+ const route = router.resolve({
+ name: SQL_EDITOR_QUERY_HISTORY_MODULE,
+ params: {
+ project: extractProjectResourceName(history.name),
+ queryHistory: extractQueryHistoryUID(history.name),
+ },
+ });
+ return new URL(
+ route.href,
+ workspaceExternalURL || globalThis.location.origin
+ ).href;
+ };
+
+ const handleCopyLink = async (history: QueryHistory) => {
+ try {
+ await navigator.clipboard.writeText(buildHistoryLink(history));
+ useAppStore.getState().notify({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("sql-editor.url-copied-to-clipboard"),
+ });
+ } catch {
+ // clipboard not available
+ }
+ };
+
+ // Only surface the "Opened from link" section while its own draft tab is
+ // active — switching to another tab hides it (it reappears on switching back).
+ const showLinkedHistory =
+ !!linkedQueryHistory && currentTabId === linkedQueryHistoryTabId;
+
+ // When shown, the linked history must not also repeat in the recent list.
+ const recentHistories = historyData.queryHistories.filter(
+ (h) => !(showLinkedHistory && h.name === linkedQueryHistory?.name)
+ );
+
+ // Highlight each whitespace-separated search term independently, so matches
+ // show even when the stored statement differs in whitespace/case from the
+ // query — mirroring the server's normalized, case-insensitive search.
+ const searchKeywords = useMemo(
+ () => searchText.trim().split(/\s+/).filter(Boolean),
+ [searchText]
+ );
+
+ const renderHistoryRow = (history: QueryHistory, highlighted = false) => (
+ <div
+ key={history.name}
+ data-history-row
+ className={cn(
+ "w-full p-2 gap-y-1 flex flex-col justify-start items-start cursor-pointer",
+ highlighted ? "bg-accent/10" : "border-b hover:bg-control-bg"
+ )}
+ onClick={() => {
+ void handleHistoryClick(history);
+ }}
+ >
+ <div className="w-full flex flex-row justify-between items-center">
+ <div className="flex items-start gap-x-1">
+ <span className="text-xs text-control-placeholder">
+ {titleOfQueryHistory(history)}
+ </span>
+ </div>
+ <div className="flex items-center gap-x-1">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-6 w-6 p-0 hover:bg-control-bg-hover"
+ data-copy-link-btn
+ onClick={(e) => {
+ e.stopPropagation();
+ void handleCopyLink(history);
+ }}
+ aria-label={t("sql-editor.copy-history-link")}
+ >
+ <Link2 className="size-3.5" />
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-6 w-6 p-0 hover:bg-control-bg-hover"
+ data-copy-btn
+ onClick={(e) => {
+ e.stopPropagation();
+ void handleCopy(history.statement);
+ }}
+ aria-label={t("common.copy")}
+ >
+ <Copy className="size-3.5" />
+ </Button>
+ </div>
+ </div>
+ <HighlightLabelText
+ text={history.statement}
+ keyword={searchKeywords}
+ className="max-w-full text-xs wrap-break-word font-mono line-clamp-3"
+ />
+ </div>
+ );
+
return (
<div className="relative w-full h-full flex flex-col justify-start items-start">
<div className="w-full px-1">
@@ -153,46 +268,39 @@ export function HistoryPane() {
</div>
<div className="w-full flex flex-col justify-start items-start overflow-y-auto">
- {historyData.queryHistories.map((history) => (
- <div
- key={history.name}
- data-history-row
- className="w-full p-2 gap-y-1 border-b flex flex-col justify-start items-start cursor-pointer hover:bg-control-bg"
- onClick={() => {
- void handleHistoryClick(history);
- }}
- >
- <div className="w-full flex flex-row justify-between items-center">
- <div className="flex items-start gap-x-1">
- <span className="text-xs text-control-placeholder">
- {titleOfQueryHistory(history)}
+ {showLinkedHistory && linkedQueryHistory && (
+ <section className="w-full" data-linked-history>
+ <div className="w-full flex items-center justify-between px-2 py-1.5 bg-accent/20">
+ <div className="flex items-center gap-x-1.5 text-accent">
+ <Link2 className="size-3.5" />
+ <span className="text-xs font-semibold uppercase tracking-wide">
+ {t("sql-editor.opened-from-link")}
</span>
</div>
<Button
variant="ghost"
size="sm"
- className="h-6 w-6 p-0"
- data-copy-btn
- onClick={(e) => {
- e.stopPropagation();
- void handleCopy(history.statement);
- }}
- aria-label={t("common.copy")}
+ className="h-5 w-5 p-0 text-accent hover:bg-accent/10 hover:text-accent"
+ data-dismiss-linked-history
+ onClick={() => setLinkedQueryHistory(undefined)}
+ aria-label={t("common.close")}
>
- <Copy className="size-3.5" />
+ <X className="size-3.5" />
</Button>
</div>
- <p
- className="max-w-full text-xs wrap-break-word font-mono line-clamp-3"
- dangerouslySetInnerHTML={{
- __html: getHighlightHTMLByKeyWords(
- history.statement,
- searchText
- ),
- }}
- />
+ {renderHistoryRow(linkedQueryHistory, /* highlighted */ true)}
+ </section>
+ )}
+
+ {showLinkedHistory && recentHistories.length > 0 && (
+ <div className="w-full flex items-center px-2 py-1.5 bg-control-bg">
+ <span className="text-xs font-semibold uppercase tracking-wide text-control-placeholder">
+ {t("sql-editor.recent")}
+ </span>
</div>
- ))}
+ )}
+
+ {recentHistories.map((history) => renderHistoryRow(history))}
{historyData.nextPageToken && (
<div className="w-full flex flex-col items-center my-2">
@@ -209,7 +317,8 @@ export function HistoryPane() {
)}
</div>
- {historyData.queryHistories.length === 0 &&
+ {recentHistories.length === 0 &&
+ !showLinkedHistory &&
(loading ? (
<div className="absolute inset-0 flex items-center justify-center bg-background/75">
<Loader2 className="size-6 animate-spin text-accent" />
diff --git a/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx b/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx
index e0f6749f99..8fcb2f4ece 100644
--- a/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx
+++ b/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx
@@ -1,3 +1,4 @@
+import dayjs from "dayjs";
import { debounce, head, omit } from "lodash-es";
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
@@ -15,6 +16,7 @@ import {
SQL_EDITOR_HOME_MODULE,
SQL_EDITOR_INSTANCE_MODULE,
SQL_EDITOR_PROJECT_MODULE,
+ SQL_EDITOR_QUERY_HISTORY_MODULE,
SQL_EDITOR_WORKSHEET_MODULE,
} from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
@@ -31,6 +33,7 @@ import {
import { migrateLegacyCache } from "@/store/modules/sqlEditor/legacy/migration";
import {
DEFAULT_SQL_EDITOR_TAB_MODE,
+ getDateForPbTimestampProtoEs,
isValidDatabaseName,
isValidInstanceName,
isValidProjectName,
@@ -60,8 +63,22 @@ const SQL_EDITOR_MODULES = new Set<string>([
SQL_EDITOR_INSTANCE_MODULE,
SQL_EDITOR_DATABASE_MODULE,
SQL_EDITOR_WORKSHEET_MODULE,
+ SQL_EDITOR_QUERY_HISTORY_MODULE,
]);
+// Fingerprint of a query-history draft tab's seeded statement + connection
+// target. The "Opened from link" banner is dropped once this changes (edit,
+// connection switch, or tab close).
+const linkedDraftFingerprint = (tab: {
+ statement: string;
+ connection: { instance: string; database: string };
+}) =>
+ JSON.stringify([
+ tab.statement,
+ tab.connection.instance,
+ tab.connection.database,
+ ]);
+
const ASIDE_PANEL_TABS: readonly AsidePanelTab[] = [
"SCHEMA",
"WORKSHEET",
@@ -253,7 +270,90 @@ export function SQLEditorRouteShell() {
return true;
};
+ // Hydrates a query-history deep link
+ // (`/sql-editor/projects/:project/queryHistories/:queryHistory`): fetches the
+ // history and opens its statement in a new draft tab, seeding the connection
+ // from the history's database when it is still accessible in the project. The
+ // queryHistory URL is a one-shot entry point — once the draft tab is seeded,
+ // the reactive `syncURL` effect rewrites the URL to the resulting
+ // database/project route.
+ const prepareQueryHistory = async () => {
+ if (route.name !== SQL_EDITOR_QUERY_HISTORY_MODULE) return false;
+ const projectId = route.params.project;
+ const queryHistoryId = route.params.queryHistory;
+ if (typeof projectId !== "string" || !projectId) return false;
+ if (typeof queryHistoryId !== "string" || !queryHistoryId) return false;
+
+ const projectName = `projects/${projectId}`;
+ await maybeSwitchProject(projectName);
+
+ const historyName = `${projectName}/queryHistories/${queryHistoryId}`;
+ const history = await useSQLEditorStore
+ .getState()
+ .fetchQueryHistory(historyName)
+ .catch(() => undefined);
+ if (!history) {
+ useAppStore.getState().notify({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("sql-editor.query-history-not-found"),
+ });
+ return false;
+ }
+
+ // Resolve the connection from the history's database. Leave it empty (a
+ // statement-only draft) and warn when the database is gone or no longer
+ // belongs to this project.
+ let connection: { instance: string; database: string } | undefined;
+ if (isValidDatabaseName(history.database)) {
+ const database = await useAppStore
+ .getState()
+ .getOrFetchDatabaseByName(history.database);
+ if (
+ isValidDatabaseName(database.name) &&
+ database.project === projectName
+ ) {
+ const { instance } = extractDatabaseResourceName(database.name);
+ connection = { instance, database: database.name };
+ } else {
+ useAppStore.getState().notify({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("sql-editor.unable-to-connect-database", {
+ name: history.database,
+ }),
+ });
+ }
+ }
+
+ const title = `Query history at ${dayjs(
+ getDateForPbTimestampProtoEs(history.createTime)
+ ).format("YYYY-MM-DD HH:mm:ss")}`;
+ const tab = getSQLEditorTabsState().addTab(
+ {
+ title,
+ statement: history.statement,
+ ...(connection ? { connection } : {}),
+ },
+ /* beside */ true
+ );
+
+ // Surface the history in the sidebar: remember it (and its draft tab's
+ // baseline) for the "Opened from link" section and force the HISTORY panel
+ // open. `setAsidePanelTab` here wins over the localStorage restore that the
+ // `project-context-ready` event schedules (`restoreLastVisitedSidebarTab`
+ // also prefers HISTORY while a linked history is set, covering either
+ // ordering).
+ useSQLEditorStore.getState().setLinkedQueryHistory(history, {
+ tabId: tab.id,
+ baseline: linkedDraftFingerprint(tab),
+ });
+ setAsidePanelTab("HISTORY");
+ return true;
+ };
+
const initializeConnectionFromQuery = async () => {
+ if (await prepareQueryHistory()) return;
if (await prepareSheet()) return;
if (await prepareConnectionParams()) return;
};
@@ -401,6 +501,44 @@ export function SQLEditorRouteShell() {
await navigate.replace({ name: SQL_EDITOR_HOME_MODULE });
};
+ // ---- dismiss "Opened from link" when its draft tab diverges -----------
+
+ const linkedQueryHistory = useSQLEditorStore((s) => s.linkedQueryHistory);
+ const linkedQueryHistoryTabId = useSQLEditorStore(
+ (s) => s.linkedQueryHistoryTabId
+ );
+ const linkedQueryHistoryBaseline = useSQLEditorStore(
+ (s) => s.linkedQueryHistoryBaseline
+ );
+ const linkedTabFingerprint = useSQLEditorTabState((s) => {
+ if (!linkedQueryHistoryTabId) return undefined;
+ const tab = s.tabsById.get(linkedQueryHistoryTabId);
+ return tab ? linkedDraftFingerprint(tab) : undefined;
+ });
+ useEffect(() => {
+ if (!linkedQueryHistory || !linkedQueryHistoryBaseline) return;
+ // Drop the banner once the seeded draft diverges from its baseline — the
+ // user edited the statement, switched the connection, or closed the tab
+ // (fingerprint becomes undefined). It matches at seed time, so this won't
+ // fire on load.
+ if (linkedTabFingerprint !== linkedQueryHistoryBaseline) {
+ useSQLEditorStore.getState().setLinkedQueryHistory(undefined);
+ }
+ }, [linkedQueryHistory, linkedQueryHistoryBaseline, linkedTabFingerprint]);
+
+ // Running a query consumes the deep-link context — drop the "Opened from
+ // link" banner on the first execution (worksheet or terminal).
+ useEffect(() => {
+ const off = sqlEditorEvents.on("query-executed", () => {
+ if (useSQLEditorStore.getState().linkedQueryHistory) {
+ useSQLEditorStore.getState().setLinkedQueryHistory(undefined);
+ }
+ });
+ return () => {
+ off();
+ };
+ }, []);
+
// ---- sidebar tab restore (after project context ready) ----------------
useEffect(() => {
@@ -415,6 +553,14 @@ export function SQLEditorRouteShell() {
const sidebarRestoredRef = useRef(false);
const restoreLastVisitedSidebarTab = () => {
+ // A query-history deep link forces the HISTORY panel open, ahead of the
+ // `?panel=` override and the localStorage default.
+ if (useSQLEditorStore.getState().linkedQueryHistory) {
+ setAsidePanelTab("HISTORY");
+ sidebarRestoredRef.current = true;
+ return;
+ }
+
let stored: AsidePanelTab = "WORKSHEET";
try {
const raw = window.localStorage.getItem(
diff --git a/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx b/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx
index 89b5f3a579..eb2d13ff71 100644
--- a/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx
+++ b/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx
@@ -33,6 +33,7 @@ import { languageOfEngineV1 } from "@/types/sqlEditor/editor";
import { instanceV1AllowsExplain, nextAnimationFrame } from "@/utils";
import { sqlEditorEvents } from "@/views/sql-editor/events";
import { useAIActions } from "../Panels/common/useAIActions";
+import { computeAppendedSelection } from "./appendSelection";
import { activeSQLEditorRef, activeStatementRef } from "./state";
import { UploadFileButton } from "./UploadFileButton";
@@ -390,11 +391,12 @@ export function SQLEditor({ onExecute }: SQLEditorProps) {
.join("\n\n");
editor.setValue(newStatement);
if (select) {
+ const range = computeAppendedSelection(oldStatement, appended);
const selection = new monaco.Selection(
- oldStatement.split("\n").length + 1,
- 0,
- newStatement.split("\n").length + 1,
- 0
+ range.startLineNumber,
+ range.startColumn,
+ range.endLineNumber,
+ range.endColumn
);
requestAnimationFrame(() => {
void sqlEditorEvents.emit("set-editor-selection", selection);
diff --git a/frontend/src/react/components/sql-editor/StandardPanel/appendSelection.test.ts b/frontend/src/react/components/sql-editor/StandardPanel/appendSelection.test.ts
new file mode 100644
index 0000000000..2428d5475b
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/StandardPanel/appendSelection.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, test } from "vitest";
+import { computeAppendedSelection } from "./appendSelection";
+
+describe("computeAppendedSelection", () => {
+ test("empty tab — selects the appended block from line 1", () => {
+ // Regression for PR #20554: the first line must be included.
+ const appended = 'SELECT\n *\nFROM "public".db\nLIMIT\n1;';
+ expect(computeAppendedSelection("", appended)).toEqual({
+ startLineNumber: 1,
+ startColumn: 1,
+ endLineNumber: 5,
+ endColumn: 3, // "1;".length + 1
+ });
+ });
+
+ test("single-line append into empty tab", () => {
+ expect(computeAppendedSelection("", "SELECT 1;")).toEqual({
+ startLineNumber: 1,
+ startColumn: 1,
+ endLineNumber: 1,
+ endColumn: 10, // "SELECT 1;".length + 1
+ });
+ });
+
+ test("append after an existing single-line statement", () => {
+ // newStatement = "SELECT 1;\n\nSELECT 2;" → appended starts at line 3.
+ expect(computeAppendedSelection("SELECT 1;", "SELECT 2;")).toEqual({
+ startLineNumber: 3,
+ startColumn: 1,
+ endLineNumber: 3,
+ endColumn: 10,
+ });
+ });
+
+ test("append after a multi-line statement", () => {
+ // old = 2 lines → blank separator on line 3 → appended starts line 4.
+ const appended = "SELECT\n2;";
+ expect(computeAppendedSelection("SELECT\n1;", appended)).toEqual({
+ startLineNumber: 4,
+ startColumn: 1,
+ endLineNumber: 5,
+ endColumn: 3,
+ });
+ });
+});
diff --git a/frontend/src/react/components/sql-editor/StandardPanel/appendSelection.ts b/frontend/src/react/components/sql-editor/StandardPanel/appendSelection.ts
new file mode 100644
index 0000000000..f50dec85c8
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/StandardPanel/appendSelection.ts
@@ -0,0 +1,28 @@
+/**
+ * Computes the Monaco selection range (1-based) covering the `appended` block
+ * after it is joined to `oldStatement` via `appendStatement` semantics:
+ *
+ * - empty old statement → `newStatement === appended`, starting at line 1
+ * - otherwise → `oldStatement + "\n\n" + appended`, so the appended block
+ * starts after the old statement plus the blank separator line.
+ *
+ * Returns the four args for `monaco.Selection`, selecting exactly the appended
+ * block (including its first line — see PR #20554).
+ */
+export const computeAppendedSelection = (
+ oldStatement: string,
+ appended: string
+): {
+ startLineNumber: number;
+ startColumn: number;
+ endLineNumber: number;
+ endColumn: number;
+} => {
+ const appendedLines = appended.split("\n");
+ const startLineNumber = oldStatement
+ ? oldStatement.split("\n").length + 2
+ : 1;
+ const endLineNumber = startLineNumber + appendedLines.length - 1;
+ const endColumn = appendedLines[appendedLines.length - 1].length + 1;
+ return { startLineNumber, startColumn: 1, endLineNumber, endColumn };
+};
diff --git a/frontend/src/react/router/handles.ts b/frontend/src/react/router/handles.ts
index 7b952f9086..fc1264ea9e 100644
--- a/frontend/src/react/router/handles.ts
+++ b/frontend/src/react/router/handles.ts
@@ -60,6 +60,7 @@ export const SQL_EDITOR_PROJECT_MODULE = "sql-editor.project";
export const SQL_EDITOR_INSTANCE_MODULE = "sql-editor.instance";
export const SQL_EDITOR_DATABASE_MODULE = "sql-editor.database";
export const SQL_EDITOR_WORKSHEET_MODULE = "sql-editor.worksheet";
+export const SQL_EDITOR_QUERY_HISTORY_MODULE = "sql-editor.query-history";
// --- dashboard/workspaceSetting.ts ---
export const SETTING_ROUTE = "setting";
diff --git a/frontend/src/react/router/routes/sqlEditor.tsx b/frontend/src/react/router/routes/sqlEditor.tsx
index f2587eda91..549bd8de3f 100644
--- a/frontend/src/react/router/routes/sqlEditor.tsx
+++ b/frontend/src/react/router/routes/sqlEditor.tsx
@@ -5,6 +5,7 @@ import {
SQL_EDITOR_HOME_MODULE,
SQL_EDITOR_INSTANCE_MODULE,
SQL_EDITOR_PROJECT_MODULE,
+ SQL_EDITOR_QUERY_HISTORY_MODULE,
SQL_EDITOR_WORKSHEET_MODULE,
} from "@/react/router/handles";
import type { Permission } from "@/types";
@@ -70,6 +71,10 @@ export const sqlEditorRoutes: RouteObject[] = [
path: "projects/:project/sheets/:sheet",
handle: { name: SQL_EDITOR_WORKSHEET_MODULE },
},
+ {
+ path: "projects/:project/queryHistories/:queryHistory",
+ handle: { name: SQL_EDITOR_QUERY_HISTORY_MODULE },
+ },
],
},
];
diff --git a/frontend/src/react/stores/sqlEditor/queryHistory.test.ts b/frontend/src/react/stores/sqlEditor/queryHistory.test.ts
index b65fd3cdd3..3dabb44456 100644
--- a/frontend/src/react/stores/sqlEditor/queryHistory.test.ts
+++ b/frontend/src/react/stores/sqlEditor/queryHistory.test.ts
@@ -36,7 +36,11 @@ const stubUIStateSlice = (): UIStateSlice => ({
highlightAccessGrantName: undefined,
isShowingCode: false,
aiPanelSize: 0.3,
+ linkedQueryHistory: undefined,
+ linkedQueryHistoryTabId: undefined,
+ linkedQueryHistoryBaseline: undefined,
setAsidePanelTab: vi.fn(),
+ setLinkedQueryHistory: vi.fn(),
setShowConnectionPanel: vi.fn(),
setShowAIPanel: vi.fn(),
setPendingInsertAtCaret: vi.fn(),
diff --git a/frontend/src/react/stores/sqlEditor/queryHistory.ts b/frontend/src/react/stores/sqlEditor/queryHistory.ts
index 7865bf993c..b16fb4ead4 100644
--- a/frontend/src/react/stores/sqlEditor/queryHistory.ts
+++ b/frontend/src/react/stores/sqlEditor/queryHistory.ts
@@ -1,9 +1,13 @@
import { create } from "@bufbuild/protobuf";
import { sqlServiceClientConnect } from "@/connect";
import type { QueryHistory } from "@/types/proto-es/v1/sql_service_pb";
-import { SearchQueryHistoriesRequestSchema } from "@/types/proto-es/v1/sql_service_pb";
+import {
+ GetQueryHistoryRequestSchema,
+ SearchQueryHistoriesRequestSchema,
+} from "@/types/proto-es/v1/sql_service_pb";
import { isValidDatabaseName } from "@/types/v1/database";
import { isValidProjectName } from "@/types/v1/project";
+import { escapeCELStringLiteral } from "@/utils/v1/cel";
import type {
QueryHistoryEntry,
QueryHistoryFilter,
@@ -23,7 +27,9 @@ const getListQueryHistoryFilter = (filter: QueryHistoryFilter) => {
params.push(`database == "${filter.database}"`);
}
if (filter.statement) {
- params.push(`statement.contains("${filter.statement}")`);
+ params.push(
+ `statement.contains("${escapeCELStringLiteral(filter.statement)}")`
+ );
}
return params.join(" && ");
};
@@ -130,6 +136,12 @@ export const createQueryHistorySlice: SQLEditorSliceCreator<
});
return resp;
},
+
+ fetchQueryHistory: async (name) => {
+ return await sqlServiceClientConnect.getQueryHistory(
+ create(GetQueryHistoryRequestSchema, { name })
+ );
+ },
});
/**
diff --git a/frontend/src/react/stores/sqlEditor/types.ts b/frontend/src/react/stores/sqlEditor/types.ts
index 9ddc4f4888..f8e9e8924a 100644
--- a/frontend/src/react/stores/sqlEditor/types.ts
+++ b/frontend/src/react/stores/sqlEditor/types.ts
@@ -27,8 +27,21 @@ export interface UIStateSlice {
// Persisted fraction of the editor width given to the AI side pane when it
// is shown. Stored in localStorage and re-read on store creation.
aiPanelSize: number;
+ // The query history opened from a deep link this session. Surfaced as the
+ // "Opened from link" section atop the history pane until dismissed or until
+ // its draft tab is edited.
+ linkedQueryHistory: QueryHistory | undefined;
+ // The id of the draft tab seeded from `linkedQueryHistory`, and a fingerprint
+ // of its seeded statement + connection. Used to dismiss the "Opened from
+ // link" section once the draft diverges (edit, connection change, or close).
+ linkedQueryHistoryTabId: string | undefined;
+ linkedQueryHistoryBaseline: string | undefined;
setAsidePanelTab: (tab: AsidePanelTab) => void;
+ setLinkedQueryHistory: (
+ value: QueryHistory | undefined,
+ meta?: { tabId: string; baseline: string }
+ ) => void;
setShowConnectionPanel: (value: boolean) => void;
setShowAIPanel: (value: boolean) => void;
setPendingInsertAtCaret: (value: string | undefined) => void;
@@ -57,6 +70,9 @@ export interface QueryHistorySlice {
mergeLatest: (
filter: QueryHistoryFilter
) => Promise<SearchQueryHistoriesResponse>;
+ // Fetches a single query history by its resource name
+ // (`projects/{project}/queryHistories/{id}`). Used to hydrate a deep link.
+ fetchQueryHistory: (name: string) => Promise<QueryHistory>;
}
export interface TreeSlice {
diff --git a/frontend/src/react/stores/sqlEditor/uiState.test.ts b/frontend/src/react/stores/sqlEditor/uiState.test.ts
index 0439d6c8ff..ebc76ca7d7 100644
--- a/frontend/src/react/stores/sqlEditor/uiState.test.ts
+++ b/frontend/src/react/stores/sqlEditor/uiState.test.ts
@@ -38,6 +38,7 @@ const stubQueryHistorySlice = (): QueryHistorySlice => ({
fetchQueryHistoryList: vi.fn().mockResolvedValue(undefined),
resetPageToken: vi.fn(),
mergeLatest: vi.fn().mockResolvedValue(undefined),
+ fetchQueryHistory: vi.fn().mockResolvedValue(undefined),
});
const stubTreeSlice = (): TreeSlice => ({
diff --git a/frontend/src/react/stores/sqlEditor/uiState.ts b/frontend/src/react/stores/sqlEditor/uiState.ts
index ce78c8142e..48809bc820 100644
--- a/frontend/src/react/stores/sqlEditor/uiState.ts
+++ b/frontend/src/react/stores/sqlEditor/uiState.ts
@@ -38,8 +38,17 @@ export const createUIStateSlice: SQLEditorSliceCreator<UIStateSlice> = (
highlightAccessGrantName: undefined,
isShowingCode: false,
aiPanelSize: readAIPanelSize(),
+ linkedQueryHistory: undefined,
+ linkedQueryHistoryTabId: undefined,
+ linkedQueryHistoryBaseline: undefined,
setAsidePanelTab: (tab) => set({ asidePanelTab: tab }),
+ setLinkedQueryHistory: (value, meta) =>
+ set({
+ linkedQueryHistory: value,
+ linkedQueryHistoryTabId: value ? meta?.tabId : undefined,
+ linkedQueryHistoryBaseline: value ? meta?.baseline : undefined,
+ }),
setShowConnectionPanel: (v) => set({ showConnectionPanel: v }),
setShowAIPanel: (v) => set({ showAIPanel: v }),
setPendingInsertAtCaret: (v) => set({ pendingInsertAtCaret: v }),
diff --git a/frontend/src/react/stores/sqlEditor/worksheet.test.ts b/frontend/src/react/stores/sqlEditor/worksheet.test.ts
index 02bb36c900..903c3927a6 100644
--- a/frontend/src/react/stores/sqlEditor/worksheet.test.ts
+++ b/frontend/src/react/stores/sqlEditor/worksheet.test.ts
@@ -21,7 +21,11 @@ const stubUIStateSlice = (): UIStateSlice => ({
highlightAccessGrantName: undefined,
isShowingCode: false,
aiPanelSize: 0.3,
+ linkedQueryHistory: undefined,
+ linkedQueryHistoryTabId: undefined,
+ linkedQueryHistoryBaseline: undefined,
setAsidePanelTab: vi.fn(),
+ setLinkedQueryHistory: vi.fn(),
setShowConnectionPanel: vi.fn(),
setShowAIPanel: vi.fn(),
setPendingInsertAtCaret: vi.fn(),
@@ -35,6 +39,7 @@ const stubQueryHistorySlice = (): QueryHistorySlice => ({
fetchQueryHistoryList: vi.fn(async () => undefined as never),
resetPageToken: vi.fn(),
mergeLatest: vi.fn(async () => undefined as never),
+ fetchQueryHistory: vi.fn(async () => undefined as never),
});
const stubTreeSlice = (): TreeSlice => ({
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 80790a8cf7..e125d5bf38 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
@@ -1201,6 +1201,25 @@ export declare type SearchQueryHistoriesRequest = Message<"bytebase.v1.SearchQue
*/
export declare const SearchQueryHistoriesRequestSchema: GenMessage<SearchQueryHistoriesRequest>;
+/**
+ * @generated from message bytebase.v1.GetQueryHistoryRequest
+ */
+export declare type GetQueryHistoryRequest = Message<"bytebase.v1.GetQueryHistoryRequest"> & {
+ /**
+ * The name of the query history to retrieve.
+ * Format: projects/{project}/queryHistories/{id}
+ *
+ * @generated from field: string name = 1;
+ */
+ name: string;
+};
+
+/**
+ * Describes the message bytebase.v1.GetQueryHistoryRequest.
+ * Use `create(GetQueryHistoryRequestSchema)` to create a new message.
+ */
+export declare const GetQueryHistoryRequestSchema: GenMessage<GetQueryHistoryRequest>;
+
/**
* @generated from message bytebase.v1.SearchQueryHistoriesResponse
*/
@@ -1461,6 +1480,17 @@ export declare const SQLService: GenService<{
input: typeof SearchQueryHistoriesRequestSchema;
output: typeof SearchQueryHistoriesResponseSchema;
},
+ /**
+ * GetQueryHistory gets a single query history for the caller.
+ * Permissions required: None (only returns the caller's own query history)
+ *
+ * @generated from rpc bytebase.v1.SQLService.GetQueryHistory
+ */
+ getQueryHistory: {
+ methodKind: "unary";
+ input: typeof GetQueryHistoryRequestSchema;
+ output: typeof QueryHistorySchema;
+ },
/**
* Exports query results to a file format.
* Permissions required: bb.databases.get
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 26a8c721f0..28e5ef8547 100644
--- a/frontend/src/types/proto-es/v1/sql_service_pb.js
+++ b/frontend/src/types/proto-es/v1/sql_service_pb.js
@@ -15,7 +15,7 @@ import { file_v1_database_service } from "./database_service_pb";
* Describes the file v1/sql_service.proto.
*/
export const file_v1_sql_service = /*@__PURE__*/
- fileDesc("ChR2MS9zcWxfc2VydmljZS5wcm90bxILYnl0ZWJhc2UudjEiqgEKE0FkbWluRXhlY3V0ZVJlcXVlc3QSKwoEbmFtZRgBIAEoCUId4EEC+kEXChVieXRlYmFzZS5jb20vRGF0YWJhc2USEQoJc3RhdGVtZW50GAIgASgJEg0KBWxpbWl0GAMgASgFEhMKBnNjaGVtYRgEIAEoCUgAiAEBEhYKCWNvbnRhaW5lchgFIAEoCUgBiAEBQgkKB19zY2hlbWFCDAoKX2NvbnRhaW5lciJBChRBZG1pbkV4ZWN1dGVSZXNwb25zZRIpCgdyZXN1bHRzGAEgAygLMhguYnl0ZWJhc2UudjEuUXVlcnlSZXN1bHQi/AEKDFF1ZXJ5UmVxdWVzdBIrCgRuYW1lGAEgASgJQh3gQQL6QRcKFWJ5dGViYXNlLmNvbS9EYXRhYmFzZRIRCglzdGF0ZW1lbnQYAiABKAkSDQoFbGltaXQYAyABKAUSFgoOZGF0YV9zb3VyY2VfaWQYBCABKAkSDwoHZXhwbGFpb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c3BvbnNlIiOQ6jACgtPkkwIZOgEqIhQvdjEvc3FsL2FpQ29tcGxldGlvbkKlAQoPY29tLmJ5dGViYXNlLnYxQg9TcWxTZXJ2aWNlUHJvdG9QAVo0Z2l0aHViLmNvbS9ieXRlYmFzZS9ieXRlYmFzZS9iYWNrZW5kL2dlbmVyYXRlZC1nby92MaICA0JYWKoCC0J5dGViYXNlLlYxygILQnl0ZWJhc2VcVjHiAhdCeXRlYmFzZVxWMVxHUEJNZXRhZGF0YeoCDEJ5dGViYXNlOjpWMWIGcHJvdG8z", [file_google_api_annotations, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_duration, file_google_protobuf_struct, file_google_protobuf_timestamp, file_v1_annotation, file_v1_common, file_v1_database_service]);
+ fileDesc("ChR2MS9zcWxfc2VydmljZS5wcm90bxILYnl0ZWJhc2UudjEiqgEKE0FkbWluRXhlY3V0ZVJlcXVlc3QSKwoEbmFtZRgBIAEoCUId4EEC+kEXChVieXRlYmFzZS5jb20vRGF0YWJhc2USEQoJc3RhdGVtZW50GAIgASgJEg0KBWxpbWl0GAMgASgFEhMKBnNjaGVtYRgEIAEoCUgAiAEBEhYKCWNvbnRhaW5lchgFIAEoCUgBiAEBQgkKB19zY2hlbWFCDAoKX2NvbnRhaW5lciJBChRBZG1pbkV4ZWN1dGVSZXNwb25zZRIpCgdyZXN1bHRzGAEgAygLMhguYnl0ZWJhc2UudjEuUXVlcnlSZXN1bHQi/AEKDFF1ZXJ5UmVxdWVzdBIrCgRuYW1lGAEgASgJQh3gQQL6QRcKFWJ5dGViYXNlLmNvbS9EYXRhYmFzZRIRCglzdGF0ZW1lbnQYAiABKAkSDQoFbGltaXQYAyABKAUSFgoOZGF0YV9zb3VyY2VfaWQYBCABKAkSDwoHZXhwbGFpbhgFIAEoCBITCgZzY2hlbWEYBiABKAlIAIgBARIuCgxxdWVyeV9vcHRpb24YByABKAsyGC5ieXRlYmFzZS52MS5RdWVyeU9wdGlvbhIWCgljb250YWluZXIYCCABK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FEZXNpZ246ZGlmZk1ldGFkYXRhEngKDEFJQ29tcGxldGlvbhIgLmJ5dGViYXNlLnYxLkFJQ29tcGxldGlvblJlcXVlc3QaIS5ieXRlYmFzZS52MS5BSUNvbXBsZXRpb25SZXNwb25zZSIjkOowAoLT5JMCGToBKiIUL3YxL3NxbC9haUNvbXBsZXRpb25CpQEKD2NvbS5ieXRlYmFzZS52MUIPU3FsU2VydmljZVByb3RvUAFaNGdpdGh1Yi5jb20vYnl0ZWJhc2UvYnl0ZWJhc2UvYmFja2VuZC9nZW5lcmF0ZWQtZ28vdjGiAgNCWFiqAgtCeXRlYmFzZS5WMcoCC0J5dGViYXNlXFYx4gIXQnl0ZWJhc2VcVjFcR1BCTWV0YWRhdGHqAgxCeXRlYmFzZTo6VjFiBnByb3RvMw", [file_google_api_annotations, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_duration, file_google_protobuf_struct, file_google_protobuf_timestamp, file_v1_annotation, file_v1_common, file_v1_database_service]);
/**
* Describes the message bytebase.v1.AdminExecuteRequest.
@@ -240,25 +240,32 @@ export const DiffMetadataResponseSchema = /*@__PURE__*/
export const SearchQueryHistoriesRequestSchema = /*@__PURE__*/
messageDesc(file_v1_sql_service, 14);
+/**
+ * Describes the message bytebase.v1.GetQueryHistoryRequest.
+ * Use `create(GetQueryHistoryRequestSchema)` to create a new message.
+ */
+export const GetQueryHistoryRequestSchema = /*@__PURE__*/
+ messageDesc(file_v1_sql_service, 15);
+
/**
* Describes the message bytebase.v1.SearchQueryHistoriesResponse.
* Use `create(SearchQueryHistoriesResponseSchema)` to create a new message.
*/
export const SearchQueryHistoriesResponseSchema = /*@__PURE__*/
- messageDesc(file_v1_sql_service, 15);
+ messageDesc(file_v1_sql_service, 16);
/**
* Describes the message bytebase.v1.QueryHistory.
* Use `create(QueryHistorySchema)` to create a new message.
*/
export const QueryHistorySchema = /*@__PURE__*/
- messageDesc(file_v1_sql_service, 16);
+ messageDesc(file_v1_sql_service, 17);
/**
* Describes the enum bytebase.v1.QueryHistory.Type.
*/
export const QueryHistory_TypeSchema = /*@__PURE__*/
- enumDesc(file_v1_sql_service, 16, 0);
+ enumDesc(file_v1_sql_service, 17, 0);
/**
* @generated from enum bytebase.v1.QueryHistory.Type
@@ -271,42 +278,42 @@ export const QueryHistory_Type = /*@__PURE__*/
* Use `create(AICompletionRequestSchema)` to create a new message.
*/
export const AICompletionRequestSchema = /*@__PURE__*/
- messageDesc(file_v1_sql_service, 17);
+ messageDesc(file_v1_sql_service, 18);
/**
* Describes the message bytebase.v1.AICompletionRequest.Message.
* Use `create(AICompletionRequest_MessageSchema)` to create a new message.
*/
export const AICompletionRequest_MessageSchema = /*@__PURE__*/
- messageDesc(file_v1_sql_service, 17, 0);
+ messageDesc(file_v1_sql_service, 18, 0);
/**
* Describes the message bytebase.v1.AICompletionResponse.
* Use `create(AICompletionResponseSchema)` to create a new message.
*/
export const AICompletionResponseSchema = /*@__PURE__*/
- messageDesc(file_v1_sql_service, 18);
+ messageDesc(file_v1_sql_service, 19);
/**
* Describes the message bytebase.v1.AICompletionResponse.Candidate.
* Use `create(AICompletionResponse_CandidateSchema)` to create a new message.
*/
export const AICompletionResponse_CandidateSchema = /*@__PURE__*/
- messageDesc(file_v1_sql_service, 18, 0);
+ messageDesc(file_v1_sql_service, 19, 0);
/**
* Describes the message bytebase.v1.AICompletionResponse.Candidate.Content.
* Use `create(AICompletionResponse_Candidate_ContentSchema)` to create a new message.
*/
export const AICompletionResponse_Candidate_ContentSchema = /*@__PURE__*/
- messageDesc(file_v1_sql_service, 18, 0, 0);
+ messageDesc(file_v1_sql_service, 19, 0, 0);
/**
* Describes the message bytebase.v1.AICompletionResponse.Candidate.Content.Part.
* Use `create(AICompletionResponse_Candidate_Content_PartSchema)` to create a new message.
*/
export const AICompletionResponse_Candidate_Content_PartSchema = /*@__PURE__*/
- messageDesc(file_v1_sql_service, 18, 0, 0, 0);
+ messageDesc(file_v1_sql_service, 19, 0, 0, 0);
/**
* SQLService executes SQL queries and manages query operations.
diff --git a/frontend/src/utils/v1/cel.test.ts b/frontend/src/utils/v1/cel.test.ts
new file mode 100644
index 0000000000..60d469f004
--- /dev/null
+++ b/frontend/src/utils/v1/cel.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, test } from "vitest";
+import { escapeCELStringLiteral } from "./cel";
+
+describe("escapeCELStringLiteral", () => {
+ test("escapes double quotes — regression for SQL identifiers", () => {
+ // `statement.contains("...")` must stay valid CEL when the statement
+ // contains double quotes (e.g. a quoted identifier).
+ expect(escapeCELStringLiteral('SELECT * FROM "public".db LIMIT 1;')).toBe(
+ 'SELECT * FROM \\"public\\".db LIMIT 1;'
+ );
+ });
+
+ test("escapes backslashes before quotes", () => {
+ expect(escapeCELStringLiteral('a\\b"c')).toBe('a\\\\b\\"c');
+ });
+
+ test("escapes newlines, carriage returns, and tabs", () => {
+ expect(escapeCELStringLiteral("a\nb\rc\td")).toBe("a\\nb\\rc\\td");
+ });
+
+ test("leaves plain text unchanged", () => {
+ expect(escapeCELStringLiteral("select 1")).toBe("select 1");
+ });
+});
diff --git a/frontend/src/utils/v1/cel.ts b/frontend/src/utils/v1/cel.ts
index be6564c7eb..68aff65d3c 100644
--- a/frontend/src/utils/v1/cel.ts
+++ b/frontend/src/utils/v1/cel.ts
@@ -9,6 +9,18 @@ import {
BatchParseRequestSchema,
} from "@/types/proto-es/v1/cel_service_pb";
+// Escapes a value for embedding inside a double-quoted CEL string literal,
+// e.g. `statement.contains("<escaped>")`. Without this, free text containing a
+// double quote (such as a SQL identifier like `"public"`) breaks the filter
+// the backend parses. Backslash must be escaped first.
+export const escapeCELStringLiteral = (value: string): string =>
+ value
+ .replace(/\\/g, "\\\\")
+ .replace(/"/g, '\\"')
+ .replace(/\n/g, "\\n")
+ .replace(/\r/g, "\\r")
+ .replace(/\t/g, "\\t");
+
export const batchConvertCELStringToParsedExpr = async (
celList: string[]
): Promise<Expr[]> => {
diff --git a/frontend/src/utils/v1/index.ts b/frontend/src/utils/v1/index.ts
index fa3433a7f8..c68bf8a4ac 100644
--- a/frontend/src/utils/v1/index.ts
+++ b/frontend/src/utils/v1/index.ts
@@ -10,6 +10,7 @@ export * from "./instance";
export * from "./sql";
export * from "./sheet";
export * from "./worksheet";
+export * from "./queryHistory";
export * from "./issue";
export * from "./changelog";
export * from "./revision";
diff --git a/frontend/src/utils/v1/queryHistory.test.ts b/frontend/src/utils/v1/queryHistory.test.ts
new file mode 100644
index 0000000000..36e20e8b4c
--- /dev/null
+++ b/frontend/src/utils/v1/queryHistory.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, test } from "vitest";
+import { extractQueryHistoryUID } from "./queryHistory";
+
+describe("extractQueryHistoryUID", () => {
+ test("extracts the uid from a full resource name", () => {
+ expect(
+ extractQueryHistoryUID(
+ "projects/proj1/queryHistories/550e8400-e29b-41d4-a716-446655440000"
+ )
+ ).toBe("550e8400-e29b-41d4-a716-446655440000");
+ });
+
+ test("returns the unknown id sentinel when no match", () => {
+ expect(extractQueryHistoryUID("projects/proj1")).toBe("-1");
+ });
+});
diff --git a/frontend/src/utils/v1/queryHistory.ts b/frontend/src/utils/v1/queryHistory.ts
new file mode 100644
index 0000000000..cf0a5229c9
--- /dev/null
+++ b/frontend/src/utils/v1/queryHistory.ts
@@ -0,0 +1,9 @@
+import { UNKNOWN_ID } from "@/types";
+
+// Extracts the query history UID from a resource name like
+// `projects/{project}/queryHistories/{id}`.
+export const extractQueryHistoryUID = (name: string) => {
+ const pattern = /(?:^|\/)queryHistories\/([^/]+)(?:$|\/)/;
+ const matches = pattern.exec(name);
+ return matches?.[1] ?? `${UNKNOWN_ID}`;
+};
diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yaml
index 208bb27280..acf0a635d7 100644
--- a/proto/gen/grpc-doc/openapi.yaml
+++ b/proto/gen/grpc-doc/openapi.yaml
@@ -10652,6 +10652,35 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/bytebase.v1.Policy'
+ /v1/projects/{project}/queryHistories/{queryHistory}:
+ get:
+ tags:
+ - SQLService
+ summary: GetQueryHistory
+ description: |-
+ GetQueryHistory gets a single query history for the caller.
+ Permissions required: None (only returns the caller's own query history)
+ operationId: SQLService_GetQueryHistory
+ parameters:
+ - name: project
+ in: path
+ description: The project id.
+ required: true
+ schema:
+ type: string
+ - name: queryHistory
+ in: path
+ description: The queryHistory id.
+ required: true
+ schema:
+ type: string
+ responses:
+ "200":
+ description: Success
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/bytebase.v1.QueryHistory'
/v1/projects/{project}/releases:
get:
tags:
@@ -21029,6 +21058,19 @@ components:
required:
- name
additionalProperties: false
+ bytebase.v1.GetQueryHistoryRequest:
+ type: object
+ properties:
+ name:
+ type: string
+ title: name
+ description: |-
+ The name of the query history to retrieve.
+ Format: projects/{project}/queryHistories/{id}
+ title: GetQueryHistoryRequest
+ required:
+ - name
+ additionalProperties: false
bytebase.v1.GetReleaseRequest:
type: object
properties:
diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.md
index 1781fa8b41..00bf3bac63 100644
--- a/proto/gen/grpc-doc/v1/README.md
+++ b/proto/gen/grpc-doc/v1/README.md
@@ -232,6 +232,7 @@
- [DiffMetadataResponse](#bytebase-v1-DiffMetadataResponse)
- [ExportRequest](#bytebase-v1-ExportRequest)
- [ExportResponse](#bytebase-v1-ExportResponse)
+ - [GetQueryHistoryRequest](#bytebase-v1-GetQueryHistoryRequest)
- [MaskingReason](#bytebase-v1-MaskingReason)
- [QueryHistory](#bytebase-v1-QueryHistory)
- [QueryOption](#bytebase-v1-QueryOption)
@@ -4495,6 +4496,21 @@ DatabaseService manages databases and their schemas.
+<a name="bytebase-v1-GetQueryHistoryRequest"></a>
+
+### GetQueryHistoryRequest
+
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| name | [string](#string) | | The name of the query history to retrieve. Format: projects/{project}/queryHistories/{id} |
+
+
+
+
+
+
<a name="bytebase-v1-MaskingReason"></a>
### MaskingReason
@@ -4924,6 +4940,7 @@ SQLService executes SQL queries and manages query operations.
| Query | [QueryRequest](#bytebase-v1-QueryRequest) | [QueryResponse](#bytebase-v1-QueryResponse) | Executes a read-only SQL query against a database. Permissions required: bb.databases.get |
| AdminExecute | [AdminExecuteRequest](#bytebase-v1-AdminExecuteRequest) stream | [AdminExecuteResponse](#bytebase-v1-AdminExecuteResponse) stream | Executes SQL with admin privileges via streaming connection. Permissions required: bb.sql.admin |
| SearchQueryHistories | [SearchQueryHistoriesRequest](#bytebase-v1-SearchQueryHistoriesRequest) | [SearchQueryHistoriesResponse](#bytebase-v1-SearchQueryHistoriesResponse) | SearchQueryHistories searches query histories for the caller. Permissions required: None (only returns caller&#39;s own query histories) |
+| GetQueryHistory | [GetQueryHistoryRequest](#bytebase-v1-GetQueryHistoryRequest) | [QueryHistory](#bytebase-v1-QueryHistory) | GetQueryHistory gets a single query history for the caller. Permissions required: None (only returns the caller&#39;s own query history) |
| Export | [ExportRequest](#bytebase-v1-ExportRequest) | [ExportResponse](#bytebase-v1-ExportResponse) | Exports query results to a file format. Permissions required: bb.databases.get |
| DiffMetadata | [DiffMetadataRequest](#bytebase-v1-DiffMetadataRequest) | [DiffMetadataResponse](#bytebase-v1-DiffMetadataResponse) | Computes schema differences between two database metadata. Permissions required: None |
| AICompletion | [AICompletionRequest](#bytebase-v1-AICompletionRequest) | [AICompletionResponse](#bytebase-v1-AICompletionResponse) | Provides AI-powered SQL completion and generation. Permissions required: None (authenticated users only, requires AI to be enabled) |
diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.html
index 6b8ac9d5e3..a9f0767520 100644
--- a/proto/gen/grpc-doc/v1/index.html
+++ b/proto/gen/grpc-doc/v1/index.html
@@ -1067,6 +1067,10 @@
<a href="#bytebase.v1.ExportResponse"><span class="badge">M</span>ExportResponse</a>
</li>
+ <li>
+ <a href="#bytebase.v1.GetQueryHistoryRequest"><span class="badge">M</span>GetQueryHistoryRequest</a>
+ </li>
+
<li>
<a href="#bytebase.v1.MaskingReason"><span class="badge">M</span>MaskingReason</a>
</li>
@@ -13604,6 +13608,31 @@ Empty when the user was authorized through normal ACL rather than a grant. </p><
+ <h3 id="bytebase.v1.GetQueryHistoryRequest">GetQueryHistoryRequest</h3>
+ <p></p>
+
+
+ <table class="field-table">
+ <thead>
+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>
+ </thead>
+ <tbody>
+
+ <tr>
+ <td>name</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>The name of the query history to retrieve.
+Format: projects/{project}/queryHistories/{id} </p></td>
+ </tr>
+
+ </tbody>
+ </table>
+
+
+
+
+
<h3 id="bytebase.v1.MaskingReason">MaskingReason</h3>
<p></p>
@@ -14802,6 +14831,14 @@ Permissions required: bb.sql.admin</p></td>
Permissions required: None (only returns caller&#39;s own query histories)</p></td>
</tr>
+ <tr>
+ <td>GetQueryHistory</td>
+ <td><a href="#bytebase.v1.GetQueryHistoryRequest">GetQueryHistoryRequest</a></td>
+ <td><a href="#bytebase.v1.QueryHistory">QueryHistory</a></td>
+ <td><p>GetQueryHistory gets a single query history for the caller.
+Permissions required: None (only returns the caller&#39;s own query history)</p></td>
+ </tr>
+
<tr>
<td>Export</td>
<td><a href="#bytebase.v1.ExportRequest">ExportRequest</a></td>
@@ -14876,6 +14913,16 @@ Permissions required: None (authenticated users only, requires AI to be enabled)
+ <tr>
+ <td>GetQueryHistory</td>
+ <td>GET</td>
+ <td>/v1/{name=projects/*/queryHistories/*}</td>
+ <td></td>
+ </tr>
+
+
+
+
<tr>
<td>Export</td>
<td>POST</td>
diff --git a/proto/v1/v1/sql_service.proto b/proto/v1/v1/sql_service.proto
index 429aed53ab..2a416dc7cd 100644
--- a/proto/v1/v1/sql_service.proto
+++ b/proto/v1/v1/sql_service.proto
@@ -48,6 +48,13 @@ service SQLService {
option (bytebase.v1.auth_method) = CUSTOM;
}
+ // GetQueryHistory gets a single query history for the caller.
+ // Permissions required: None (only returns the caller's own query history)
+ rpc GetQueryHistory(GetQueryHistoryRequest) returns (QueryHistory) {
+ option (google.api.http) = {get: "/v1/{name=projects/*/queryHistories/*}"};
+ option (bytebase.v1.auth_method) = CUSTOM;
+ }
+
// Exports query results to a file format.
// Permissions required: bb.databases.get
rpc Export(ExportRequest) returns (ExportResponse) {
@@ -501,6 +508,12 @@ message SearchQueryHistoriesRequest {
string filter = 3;
}
+message GetQueryHistoryRequest {
+ // The name of the query history to retrieve.
+ // Format: projects/{project}/queryHistories/{id}
+ string name = 1 [(google.api.field_behavior) = REQUIRED];
+}
+
message SearchQueryHistoriesResponse {
// The list of history.
repeated QueryHistory query_histories = 1 [(google.api.field_behavior) = OUTPUT_ONLY];