实例联合列表支持按流程定义key过滤,同key多版本实例一并命中

This commit is contained in:
rulego-team committed 2026-10-09 19:18:54 +08:00
1 parent 3c2b9daf31
commit 512afa0baf
5 files changed
+230 -17

No files matched your search

+18 -8
View File
@@ -569,7 +569,7 @@ type instanceUnionQuery struct {
// buildInstanceUnionQuery 构建实例合并查询的 WHERE 条件(运行时/历史两分支共用同一段条件)。
// statuses 为空时排除软删除行:deleted 对用户不可见,任何列表不应带出。
func buildInstanceUnionQuery(tenantID, processID, startUserID string, statuses []string, keyword string, startTimeFrom, startTimeTo *time.Time, instanceID, businessKey, endReasonPrefix string, endReasonNotPrefixes ...string) instanceUnionQuery {
func buildInstanceUnionQuery(tenantID string, processIDs []string, startUserID string, statuses []string, keyword string, startTimeFrom, startTimeTo *time.Time, instanceID, businessKey, endReasonPrefix string, endReasonNotPrefixes ...string) instanceUnionQuery {
uq := instanceUnionQuery{
runSQL: "SELECT * FROM wf_instance WHERE 1=1",
histSQL: "SELECT * FROM wf_hi_instance WHERE 1=1",
@@ -579,9 +579,18 @@ func buildInstanceUnionQuery(tenantID, processID, startUserID string, statuses [
uq.conditions += " AND tenant_id = ?"
uq.args = append(uq.args, tenantID)
}
if processID != "" {
uq.conditions += " AND process_id = ?"
uq.args = append(uq.args, processID)
if len(processIDs) > 0 {
placeholders := make([]string, 0, len(processIDs))
for _, id := range processIDs {
if id == "" {
continue
}
placeholders = append(placeholders, "?")
uq.args = append(uq.args, id)
}
if len(placeholders) > 0 {
uq.conditions += " AND process_id IN (" + strings.Join(placeholders, ",") + ")"
}
}
if instanceID != "" {
uq.conditions += " AND id = ?"
@@ -640,12 +649,13 @@ func buildInstanceUnionQuery(tenantID, processID, startUserID string, statuses [
return uq
}
// GetInstancesUnionPagination 分页获取流程实例列表(合并运行时和历史表,支持多租户)
func (d *InstanceDAO) GetInstancesUnionPagination(ctx context.Context, tenantID, ProcessID, startUserID string, statuses []string, keyword string, startTimeFrom, startTimeTo *time.Time, limit, offset int, instanceID, businessKey, endReasonPrefix string, endReasonNotPrefixes ...string) ([]*model.WfInstance, int64, error) {
// GetInstancesUnionPagination 分页获取流程实例列表(合并运行时和历史表,支持多租户)。
// processIDs 按流程定义 ID 集合过滤(IN 语义)。
func (d *InstanceDAO) GetInstancesUnionPagination(ctx context.Context, tenantID string, processIDs []string, startUserID string, statuses []string, keyword string, startTimeFrom, startTimeTo *time.Time, limit, offset int, instanceID, businessKey, endReasonPrefix string, endReasonNotPrefixes ...string) ([]*model.WfInstance, int64, error) {
if tenantID == "" {
return nil, 0, errors.New("tenantID required")
}
uq := buildInstanceUnionQuery(tenantID, ProcessID, startUserID, statuses, keyword, startTimeFrom, startTimeTo, instanceID, businessKey, endReasonPrefix, endReasonNotPrefixes...)
uq := buildInstanceUnionQuery(tenantID, processIDs, startUserID, statuses, keyword, startTimeFrom, startTimeTo, instanceID, businessKey, endReasonPrefix, endReasonNotPrefixes...)
// Count SQL:归档在单事务内完成(建历史行+删活行同 tx),两表不会有同 ID 双行,
// 故用 UNION ALL 免去 UNION 去重的全列比较排序开销。
@@ -776,7 +786,7 @@ func (d *InstanceDAO) CountInstancesUnionByBuckets(ctx context.Context, tenantID
if tenantID == "" {
return nil, errors.New("tenantID required")
}
uq := buildInstanceUnionQuery(tenantID, processID, startUserID, nil, keyword, startTimeFrom, startTimeTo, "", "", "")
uq := buildInstanceUnionQuery(tenantID, []string{processID}, startUserID, nil, keyword, startTimeFrom, startTimeTo, "", "", "")
// 参数顺序须与 SQL 文本一致:先外层 SELECT 的桶参数,再两个分支各一份条件参数
selects := []string{"COUNT(*) AS total"}
+59 -5
View File
@@ -310,7 +310,7 @@ func TestInstanceDAO_UnionPagination_ExcludesDeletedByDefault(t *testing.T) {
}
// 未指定状态:两表的 deleted 行都排除
list, total, err := d.GetInstancesUnionPagination(ctx, "t1", "", "u1", nil, "", nil, nil, 10, 0, "", "", "")
list, total, err := d.GetInstancesUnionPagination(ctx, "t1", nil, "u1", nil, "", nil, nil, 10, 0, "", "", "")
if err != nil {
t.Fatalf("union query: %v", err)
}
@@ -324,7 +324,7 @@ func TestInstanceDAO_UnionPagination_ExcludesDeletedByDefault(t *testing.T) {
}
// 显式传 deleted:按传入过滤,两表各一条均命中
list, total, err = d.GetInstancesUnionPagination(ctx, "t1", "", "u1", []string{"deleted"}, "", nil, nil, 10, 0, "", "", "")
list, total, err = d.GetInstancesUnionPagination(ctx, "t1", nil, "u1", []string{"deleted"}, "", nil, nil, 10, 0, "", "", "")
if err != nil {
t.Fatalf("union query by status: %v", err)
}
@@ -340,6 +340,60 @@ func TestInstanceDAO_UnionPagination_ExcludesDeletedByDefault(t *testing.T) {
}
}
// 联合查询按流程定义 ID 集合过滤(IN 语义,活表与历史表同时命中)。
func TestInstanceDAO_UnionPagination_ProcessIDs(t *testing.T) {
q := newTestQuery(t, ddlWfInstance, ddlWfHiInstance)
d := NewInstanceDAOWithQuery(q)
ctx := context.Background()
now := time.Now()
seed := []*model.WfInstance{
{ID: "i-v1", ProcessID: "p1", Name: "on v1", Status: "active", TenantID: "t1", StartUserID: "u1", CreatedAt: now},
{ID: "i-v2", ProcessID: "p2", Name: "on v2", Status: "active", TenantID: "t1", StartUserID: "u1", CreatedAt: now},
{ID: "i-other", ProcessID: "p9", Name: "other def", Status: "active", TenantID: "t1", StartUserID: "u1", CreatedAt: now},
}
for _, in := range seed {
if err := d.Create(ctx, in); err != nil {
t.Fatalf("seed instance %s: %v", in.ID, err)
}
}
if err := d.Query.WfHiInstance.WithContext(ctx).Create(&model.WfHiInstance{
ID: "hi-v1", ProcessID: "p1", Name: "archived on v1", Status: "terminated", TenantID: "t1", StartUserID: "u1", CreatedAt: now,
}); err != nil {
t.Fatalf("seed hi instance: %v", err)
}
// 多版本 ID 集合:两版本各一条 + 老版本的历史归档行
list, total, err := d.GetInstancesUnionPagination(ctx, "t1", []string{"p1", "p2"}, "u1", nil, "", nil, nil, 10, 0, "", "", "")
if err != nil {
t.Fatalf("union query by process IDs: %v", err)
}
if total != 3 || len(list) != 3 {
t.Errorf("process IDs filter: total=%d len=%d, want 3/3", total, len(list))
}
got := map[string]bool{}
for _, in := range list {
got[in.ID] = true
}
for _, want := range []string{"i-v1", "i-v2", "hi-v1"} {
if !got[want] {
t.Errorf("process IDs filter: %s missing, got %v", want, got)
}
}
if got["i-other"] {
t.Errorf("process IDs filter: i-other (p9) 不应命中")
}
// 含空串元素的集合跳过空值,等价于不按流程定义过滤(4 条全量)
list, total, err = d.GetInstancesUnionPagination(ctx, "t1", []string{""}, "u1", nil, "", nil, nil, 10, 0, "", "", "")
if err != nil {
t.Fatalf("union query with blank IDs: %v", err)
}
if total != 4 || len(list) != 4 {
t.Errorf("blank process IDs should mean no filter: total=%d, want 4", total)
}
}
// 联合查询按 end_reason 前缀过滤。
func TestInstanceDAO_UnionPagination_EndReasonPrefix(t *testing.T) {
q := newTestQuery(t, ddlWfInstance, ddlWfHiInstance)
@@ -360,7 +414,7 @@ func TestInstanceDAO_UnionPagination_EndReasonPrefix(t *testing.T) {
}
}
list, total, err := d.GetInstancesUnionPagination(ctx, "t1", "", "u1", []string{"terminated"}, "", nil, nil, 10, 0, "", "", "审批拒绝")
list, total, err := d.GetInstancesUnionPagination(ctx, "t1", nil, "u1", []string{"terminated"}, "", nil, nil, 10, 0, "", "", "审批拒绝")
if err != nil {
t.Fatalf("union query by end_reason prefix: %v", err)
}
@@ -701,7 +755,7 @@ func TestInstanceDAO_NullEndReasonCountedInTerminated(t *testing.T) {
}
// 2) 联合查询列表(buildInstanceUnionQuery 的 NOT LIKE)
list, total, err := d.GetInstancesUnionPagination(ctx, "t1", "", "u1", []string{"terminated"}, "", nil, nil, 10, 0, "", "", "", "审批拒绝", "申请人撤回")
list, total, err := d.GetInstancesUnionPagination(ctx, "t1", nil, "u1", []string{"terminated"}, "", nil, nil, 10, 0, "", "", "", "审批拒绝", "申请人撤回")
if err != nil {
t.Fatalf("union by not-prefix: %v", err)
}
@@ -744,7 +798,7 @@ func TestInstanceDAO_NullEndReasonCountedInTerminated(t *testing.T) {
// 而 IS NULL OR 在所有方言行为严格一致。
func TestEndReasonNotLike_UsesIsNullOR(t *testing.T) {
tq := buildTaskInstanceQuery(&dto.TaskQuery{EndReasonNotPrefixes: []string{"审批拒绝", "申请人撤回"}})
uq := buildInstanceUnionQuery("t1", "", "u1", []string{"terminated"}, "", nil, nil, "", "", "", "审批拒绝", "申请人撤回")
uq := buildInstanceUnionQuery("t1", nil, "u1", []string{"terminated"}, "", nil, nil, "", "", "", "审批拒绝", "申请人撤回")
bcond, _ := bucketWhere(InstanceStatusBucket{Statuses: []string{"terminated"}, EndReasonNotPrefixes: []string{"审批拒绝", "申请人撤回"}})
for _, tc := range []struct{ name, sql string }{
+44 -3
View File
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"sync"
"time"
@@ -1932,9 +1933,17 @@ func (s *RuntimeServiceImpl) GetProcessInstanceUnionList(ctx context.Context, ac
return nil, 0, err
}
request.TenantID = actor.TenantID
// 实例(含归档历史行)挂在发起时的版本 ID 上,按 key 过滤须取该 key 全部版本 ID
processIDs, noMatch, err := resolveProcessIDFilter(ctx, s.processDAO, actor.TenantID, request.ProcessKey, request.ProcessID)
if err != nil {
return nil, 0, err
}
if noMatch {
return []*model.WfInstance{}, 0, nil
}
size := request.GetPageSize()
offset := (request.GetPage() - 1) * size
instances, total, err := s.instanceDAO.GetInstancesUnionPagination(ctx, request.TenantID, request.ProcessID, "", request.Status, request.Keyword, nil, nil, size, offset, request.InstanceID, request.BusinessKey, "")
instances, total, err := s.instanceDAO.GetInstancesUnionPagination(ctx, request.TenantID, processIDs, "", request.Status, request.Keyword, nil, nil, size, offset, request.InstanceID, request.BusinessKey, "")
if err != nil {
return nil, 0, err
}
@@ -1942,6 +1951,38 @@ func (s *RuntimeServiceImpl) GetProcessInstanceUnionList(ctx context.Context, ac
return instances, total, nil
}
// resolveProcessIDFilter 把实例查询条件里的 processKey/processID 归一为
// processID 集合(IN 语义)。key 非空时取该 key 全部版本 ID;key 与 ID 同时
// 传入按 AND 处理——ID 不在该 key 的版本集内时 noMatch 为 true,调用方直接
// 返回空列表。两者都为空时返回 nil,表示查询不按流程定义过滤。
func resolveProcessIDFilter(ctx context.Context, store ProcessStore, tenantID, processKey, processID string) (ids []string, noMatch bool, err error) {
if processKey == "" {
if processID == "" {
return nil, false, nil
}
return []string{processID}, false, nil
}
defs, _, err := store.List(ctx, &dto.ProcessQueryRequest{
PageRequest: dto.PageRequest{Page: 1, PageSize: dto.MaxPageSize, TenantID: tenantID},
ProcessKey: processKey,
AllVersion: true,
})
if err != nil {
return nil, false, fmt.Errorf("failed to resolve process key '%s': %w", processKey, err)
}
if len(defs) == 0 {
return nil, true, nil
}
ids = make([]string, 0, len(defs))
for _, def := range defs {
ids = append(ids, def.ID)
}
if processID != "" && !slices.Contains(ids, processID) {
return nil, true, nil
}
return ids, false, nil
}
// UpdateInstanceCurrentActivity 更新 active 实例的当前节点。
// 只在节点创建任务时由组件回调;失败仅记日志不阻塞主流程(监控字段,非关键路径)。
func (s *RuntimeServiceImpl) UpdateInstanceCurrentActivity(ctx context.Context, processInstanceID, activityKey string) error {
@@ -2177,7 +2218,7 @@ func (s *RuntimeServiceImpl) GetMyApplicationsProcessInstanceList(ctx context.Co
}
// 运行时+历史表合并查询(DAO 支持 tenantID/startUserID 条件)
statuses, endReasonPrefix, endReasonNotPrefixes := instanceStatusScope(instanceStatus)
instances, total, err := s.instanceDAO.GetInstancesUnionPagination(ctx, tenantID, "", userID, statuses, keyword, nil, nil, pageSize, (page-1)*pageSize, "", "", endReasonPrefix, endReasonNotPrefixes...)
instances, total, err := s.instanceDAO.GetInstancesUnionPagination(ctx, tenantID, nil, userID, statuses, keyword, nil, nil, pageSize, (page-1)*pageSize, "", "", endReasonPrefix, endReasonNotPrefixes...)
if err != nil {
return nil, 0, err
}
@@ -2196,7 +2237,7 @@ func (s *RuntimeServiceImpl) CountMyApplications(ctx context.Context, actor Acto
if err := requireNonEmptyTenantForRealUser(&actor); err != nil {
return 0, err
}
_, total, err := s.instanceDAO.GetInstancesUnionPagination(ctx, tenantID, "", userID, nil, "", from, to, 1, 0, "", "", "")
_, total, err := s.instanceDAO.GetInstancesUnionPagination(ctx, tenantID, nil, userID, nil, "", from, to, 1, 0, "", "", "")
if err != nil {
return 0, fmt.Errorf("failed to count my applications: %w", err)
}
+108
View File
@@ -0,0 +1,108 @@
package service
import (
"context"
"errors"
"testing"
"github.com/rulego/gflow-engine/model"
"github.com/rulego/gflow-engine/query"
"github.com/rulego/gflow-engine/types/dto"
)
// resolveProcessIDFilter 的 key→全版本 ID 解析与 AND 交集语义。
type fakeProcessStore struct {
defs []model.WfProcess
err error
}
func (f *fakeProcessStore) Underlying() *query.Query { return nil }
func (f *fakeProcessStore) List(ctx context.Context, request *dto.ProcessQueryRequest) ([]*model.WfProcess, int64, error) {
if f.err != nil {
return nil, 0, f.err
}
var out []*model.WfProcess
for i := range f.defs {
d := &f.defs[i]
if request.ProcessKey != "" && d.ProcessKey != request.ProcessKey {
continue
}
if request.TenantID != "" && d.TenantID != request.TenantID {
continue
}
out = append(out, d)
}
return out, int64(len(out)), nil
}
func (f *fakeProcessStore) Get(ctx context.Context, id string) (*model.WfProcess, error) {
return nil, errors.New("not implemented")
}
func (f *fakeProcessStore) GetByIDs(ctx context.Context, ids []string) ([]*model.WfProcess, error) {
return nil, errors.New("not implemented")
}
func (f *fakeProcessStore) GetByKeyAndVersion(ctx context.Context, tenantID, processKey string, version int32) (*model.WfProcess, error) {
return nil, errors.New("not implemented")
}
func (f *fakeProcessStore) GetLatestByKey(ctx context.Context, tenantID, processKey string) (*model.WfProcess, error) {
return nil, errors.New("not implemented")
}
func (f *fakeProcessStore) Update(ctx context.Context, entity *model.WfProcess) error {
return errors.New("not implemented")
}
func (f *fakeProcessStore) Delete(ctx context.Context, tenantID, id string) error {
return errors.New("not implemented")
}
func (f *fakeProcessStore) CountActiveReferencingForm(ctx context.Context, tenantID, formKey string) (int64, error) {
return 0, errors.New("not implemented")
}
func TestResolveProcessIDFilter(t *testing.T) {
store := &fakeProcessStore{defs: []model.WfProcess{
{ID: "p1", ProcessKey: "k", Version: 1, TenantID: "t1"},
{ID: "p2", ProcessKey: "k", Version: 2, TenantID: "t1"},
{ID: "q1", ProcessKey: "other", Version: 1, TenantID: "t1"},
}}
ctx := context.Background()
// key 与 ID 都为空:不按流程定义过滤
ids, noMatch, err := resolveProcessIDFilter(ctx, store, "t1", "", "")
if err != nil || noMatch || ids != nil {
t.Errorf("empty filter: ids=%v noMatch=%v err=%v, want nil/false/nil", ids, noMatch, err)
}
// 仅 ID:单元素集合
ids, noMatch, err = resolveProcessIDFilter(ctx, store, "t1", "", "p9")
if err != nil || noMatch || len(ids) != 1 || ids[0] != "p9" {
t.Errorf("id only: ids=%v noMatch=%v err=%v", ids, noMatch, err)
}
// 仅 key:该 key 全部版本 ID
ids, noMatch, err = resolveProcessIDFilter(ctx, store, "t1", "k", "")
if err != nil || noMatch || len(ids) != 2 {
t.Errorf("key only: ids=%v noMatch=%v err=%v, want 2 version IDs", ids, noMatch, err)
}
// key + 属于该 key 的 ID:AND 命中,返回全集
ids, noMatch, err = resolveProcessIDFilter(ctx, store, "t1", "k", "p1")
if err != nil || noMatch || len(ids) != 2 {
t.Errorf("key+member id: ids=%v noMatch=%v err=%v, want full set", ids, noMatch, err)
}
// key + 不属于该 key 的 ID:交集为空
ids, noMatch, err = resolveProcessIDFilter(ctx, store, "t1", "k", "q1")
if err != nil || !noMatch {
t.Errorf("key+foreign id: noMatch=%v err=%v, want noMatch=true", noMatch, err)
}
// key 无任何版本:空结果
ids, noMatch, err = resolveProcessIDFilter(ctx, store, "t1", "ghost", "")
if err != nil || !noMatch {
t.Errorf("unknown key: noMatch=%v err=%v, want noMatch=true", noMatch, err)
}
// 存储查询失败:错误冒泡
store.err = errors.New("db down")
if _, _, err = resolveProcessIDFilter(ctx, store, "t1", "k", ""); err == nil {
t.Errorf("store failure: want error bubble-up")
}
}
+1 -1
View File
@@ -51,7 +51,7 @@ type InstanceStore interface {
HasActiveByParentID(ctx context.Context, parentID string) (bool, error)
SetCurrentActivity(ctx context.Context, id, activityKey string) error
ListByTaskConditions(ctx context.Context, req *dto.TaskQuery) ([]*model.WfInstance, int64, error)
GetInstancesUnionPagination(ctx context.Context, tenantID, ProcessID, startUserID string, statuses []string, keyword string, startTimeFrom, startTimeTo *time.Time, limit, offset int, instanceID, businessKey, endReasonPrefix string, endReasonNotPrefixes ...string) ([]*model.WfInstance, int64, error)
GetInstancesUnionPagination(ctx context.Context, tenantID string, processIDs []string, startUserID string, statuses []string, keyword string, startTimeFrom, startTimeTo *time.Time, limit, offset int, instanceID, businessKey, endReasonPrefix string, endReasonNotPrefixes ...string) ([]*model.WfInstance, int64, error)
CountInstancesUnionByBuckets(ctx context.Context, tenantID, processID, startUserID, keyword string, startTimeFrom, startTimeTo *time.Time, buckets []dao.InstanceStatusBucket) (map[string]int64, error)
CountTaskInstancesByBuckets(ctx context.Context, req *dto.TaskQuery, buckets []dao.InstanceStatusBucket) (map[string]int64, error)
}