|
| 1 | +/* |
| 2 | + * Copyright (c) 2025. protobox |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package outboxsql |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "fmt" |
| 22 | + "strings" |
| 23 | + |
| 24 | + sq "github.com/Masterminds/squirrel" |
| 25 | + "github.com/samber/lo" |
| 26 | + |
| 27 | + "github.com/notjustmoney/protobox/outbox" |
| 28 | +) |
| 29 | + |
| 30 | +type MarkerFunc func(ctx context.Context, messages []outbox.PublishedMessage) (int, error) |
| 31 | + |
| 32 | +func (f MarkerFunc) Mark(ctx context.Context, messages []outbox.PublishedMessage) (int, error) { |
| 33 | + return f(ctx, messages) |
| 34 | +} |
| 35 | + |
| 36 | +func Marker( |
| 37 | + dbCtx *dbCtx, |
| 38 | + cfg Config, |
| 39 | +) MarkerFunc { |
| 40 | + return func(ctx context.Context, messages []outbox.PublishedMessage) (int, error) { |
| 41 | + args := make([]interface{}, 0, len(messages)*3) |
| 42 | + for i := 0; i < len(messages); i++ { |
| 43 | + args = append(args, messages[i].ID) |
| 44 | + args = append(args, messages[i].ProcessedAt.UTC()) |
| 45 | + args = append(args, messages[i].Error) |
| 46 | + } |
| 47 | + |
| 48 | + if _, err := sq. |
| 49 | + Update(cfg.TableName). |
| 50 | + Set("processed_at", sq.Expr("v.processed_at")). |
| 51 | + Set("error", sq.Expr("v.error")). |
| 52 | + Suffix("FROM"). |
| 53 | + SuffixExpr( |
| 54 | + sq.Alias( |
| 55 | + sq.Expr(fmt.Sprintf("VALUES %s", strings.Join(lo.Map(messages, func(_ outbox.PublishedMessage, index int) string { |
| 56 | + return fmt.Sprintf("($%d, $%d::timestamp with time zone, $%d)", index*3+1, index*3+2, index*3+3) |
| 57 | + }), ",")), args...), |
| 58 | + "v(id, processed_at, error)", |
| 59 | + ), |
| 60 | + ). |
| 61 | + Suffix("WHERE " + cfg.TableName + ".id = v.id::uuid"). |
| 62 | + PlaceholderFormat(sq.Dollar). |
| 63 | + RunWith(dbCtx.executor(ctx)). |
| 64 | + ExecContext(ctx); err != nil { |
| 65 | + return 0, err |
| 66 | + } |
| 67 | + |
| 68 | + return len(messages), nil |
| 69 | + } |
| 70 | +} |
0 commit comments