-
Notifications
You must be signed in to change notification settings - Fork 8
rsql: Add manyInserter and InsertMany API #25
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
NeilLuno
wants to merge
3
commits into
main
Choose a base branch
from
neil-insert-many
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -45,34 +45,82 @@ func (t eventType) ReflexType() int { | |
|
|
||
| // makeDefaultInserter returns the default sql inserter configured via WithEventsXField options. | ||
| func makeDefaultInserter(schema eTableSchema) inserter { | ||
| return func(ctx context.Context, tx *sql.Tx, | ||
| foreignID string, typ reflex.EventType, metadata []byte, | ||
| ins := makeDefaultManyInserter(schema) | ||
| return func( | ||
| ctx context.Context, | ||
| tx *sql.Tx, | ||
| foreignID string, | ||
| typ reflex.EventType, | ||
| metadata []byte, | ||
| ) error { | ||
| q := "insert into " + schema.name + | ||
| " set " + schema.foreignIDField + "=?, " + schema.timeField + "=now(6), " + schema.typeField + "=?" | ||
| args := []interface{}{foreignID, typ.ReflexType()} | ||
| return ins(ctx, tx, EventToInsert{ | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nice I like that the singular is using the multiple inserter with just 1 event. |
||
| ForeignID: foreignID, | ||
| Type: typ, | ||
| Metadata: metadata, | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| if schema.metadataField != "" { | ||
| q += ", " + schema.metadataField + "=?" | ||
| args = append(args, metadata) | ||
| } else if metadata != nil { | ||
| return errors.New("metadata not enabled") | ||
| // makeDefaultManyInserter returns the default sql manyInserter configured via WithEventsXField options. | ||
| func makeDefaultManyInserter(schema eTableSchema) manyInserter { | ||
| return func(ctx context.Context, tx *sql.Tx, events ...EventToInsert) error { | ||
| if len(events) == 0 { | ||
| return nil | ||
| } | ||
| q, args, err := makeInsertManyQuery(ctx, schema, events) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| _, err = tx.ExecContext(ctx, q, args...) | ||
| return errors.Wrap(err, "insert error") | ||
| } | ||
| } | ||
|
|
||
| func makeInsertManyQuery( | ||
| ctx context.Context, | ||
| schema eTableSchema, | ||
| events []EventToInsert, | ||
| ) (query string, args []any, err error) { | ||
| spanCtx, hasTrace := tracing.Extract(ctx) | ||
| var traceData []byte | ||
| if schema.traceField != "" && hasTrace { | ||
| d, err := tracing.Marshal(spanCtx) | ||
| if err != nil { | ||
| return "", nil, err | ||
| } | ||
| traceData = d | ||
| } | ||
|
|
||
| spanCtx, hasTrace := tracing.Extract(ctx) | ||
| if schema.traceField != "" && hasTrace { | ||
| traceData, err := tracing.Marshal(spanCtx) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| cols := schema.foreignIDField + ", " + schema.typeField + ", " + schema.timeField | ||
| if schema.metadataField != "" { | ||
| cols += ", " + schema.metadataField | ||
| } | ||
| if traceData != nil { | ||
| cols += ", " + schema.traceField | ||
| } | ||
|
|
||
| q += ", " + schema.traceField + "=?" | ||
| q := "insert into " + schema.name + " (" + cols + ") values" | ||
|
|
||
| for i, e := range events { | ||
| vals := "?, ?, now(6)" | ||
| args = append(args, e.ForeignID, e.Type.ReflexType()) | ||
| if schema.metadataField != "" { | ||
| vals += ", ?" | ||
| args = append(args, e.Metadata) | ||
| } else if e.Metadata != nil { | ||
| return "", nil, errors.New("metadata not enabled") | ||
| } | ||
| if traceData != nil { | ||
| vals += ", ?" | ||
| args = append(args, traceData) | ||
| } | ||
|
|
||
| _, err := tx.ExecContext(ctx, q, args...) | ||
| return errors.Wrap(err, "insert error") | ||
| if i > 0 { | ||
| q += "," | ||
| } | ||
| q += " (" + vals + ")" | ||
| } | ||
|
|
||
| return q, args, nil | ||
| } | ||
|
|
||
| type row interface { | ||
|
|
@@ -158,7 +206,14 @@ func getNextEvents(ctx context.Context, dbc *sql.DB, schema eTableSchema, | |
| } | ||
|
|
||
| // GetNextEventsForTesting fetches a bunch of events from the event table | ||
| func GetNextEventsForTesting(ctx context.Context, _ *testing.T, dbc *sql.DB, table *EventsTable, after int64, lag time.Duration) ([]*reflex.Event, error) { | ||
| func GetNextEventsForTesting( | ||
| ctx context.Context, | ||
| _ *testing.T, | ||
| dbc *sql.DB, | ||
| table *EventsTable, | ||
| after int64, | ||
| lag time.Duration, | ||
| ) ([]*reflex.Event, error) { | ||
| return getNextEvents(ctx, dbc, table.schema, after, lag) | ||
| } | ||
|
|
||
|
|
@@ -287,7 +342,16 @@ func makeDefaultErrorInserter(schema errTableSchema) ErrorInserter { | |
| // NB: See the documentation is the following link on the behaviour of "on last_insert_id(<expr>)" https://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_last-insert-id | ||
| q := fmt.Sprintf( | ||
| "insert into %s set %s=?, %s=?, %s=?, %s=now(6), %s=now(6), %s=? on duplicate key update %s=last_insert_id(%s)", | ||
| schema.name, schema.eventConsumerField, schema.eventIDField, schema.errorMsgField, schema.errorCreatedAtField, schema.errorUpdatedAtField, schema.errorStatusField, schema.idField, schema.idField) | ||
| schema.name, | ||
| schema.eventConsumerField, | ||
| schema.eventIDField, | ||
| schema.errorMsgField, | ||
| schema.errorCreatedAtField, | ||
| schema.errorUpdatedAtField, | ||
| schema.errorStatusField, | ||
| schema.idField, | ||
| schema.idField, | ||
| ) | ||
| return func(ctx context.Context, tx *sql.Tx, consumer string, eventID string, errMsg string, errStatus reflex.ErrorStatus) (string, error) { | ||
| r, err := tx.ExecContext(ctx, q, consumer, eventID, errMsg, errStatus) | ||
| // If the error has already been written then we can ignore the error | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,117 @@ | ||
| package rsql | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "fmt" | ||
| "testing" | ||
|
|
||
| "github.com/luno/jettison/jtest" | ||
| "github.com/sebdah/goldie/v2" | ||
| "github.com/stretchr/testify/require" | ||
| "go.opentelemetry.io/otel/trace" | ||
|
|
||
| "github.com/luno/reflex/internal/tracing" | ||
| ) | ||
|
|
||
| //go:generate go test . -run Test_makeInsertManyQuery -update -clean | ||
|
|
||
| func Test_makeInsertManyQuery(t *testing.T) { | ||
| ctx := context.Background() | ||
|
|
||
| defaultSchema := eTableSchema{ | ||
| name: "events", | ||
| idField: "id", | ||
| timeField: "timestamp", | ||
| typeField: "type", | ||
| foreignIDField: "foreign_id", | ||
| } | ||
|
|
||
| assert := func(t *testing.T, q string, args []any) { | ||
| buf := new(bytes.Buffer) | ||
| buf.WriteString(q) | ||
| buf.WriteString("\n") | ||
| for _, arg := range args { | ||
| buf.WriteString("\n") | ||
| buf.WriteString(fmt.Sprint(arg)) | ||
| } | ||
| goldie.New(t).Assert(t, t.Name(), buf.Bytes()) | ||
| } | ||
|
|
||
| t.Run("empty", func(t *testing.T) { | ||
| q, args, err := makeInsertManyQuery(ctx, defaultSchema, nil) | ||
| jtest.RequireNil(t, err) | ||
| assert(t, q, args) | ||
| }) | ||
|
|
||
| t.Run("one", func(t *testing.T) { | ||
| q, args, err := makeInsertManyQuery(ctx, defaultSchema, []EventToInsert{ | ||
| {"fid", testEventType(1), nil}, | ||
| }) | ||
| jtest.RequireNil(t, err) | ||
| assert(t, q, args) | ||
| }) | ||
|
|
||
| t.Run("two", func(t *testing.T) { | ||
| q, args, err := makeInsertManyQuery(ctx, defaultSchema, []EventToInsert{ | ||
| {"fid1", testEventType(1), nil}, | ||
| {"fid2", testEventType(2), nil}, | ||
| }) | ||
| jtest.RequireNil(t, err) | ||
| assert(t, q, args) | ||
| }) | ||
|
|
||
| t.Run("more", func(t *testing.T) { | ||
| var events []EventToInsert | ||
| for i := range 5 { | ||
| events = append(events, EventToInsert{ | ||
| ForeignID: fmt.Sprintf("fid%d", i+1), | ||
| Type: testEventType(i), | ||
| }) | ||
| } | ||
| q, args, err := makeInsertManyQuery(ctx, defaultSchema, events) | ||
| jtest.RequireNil(t, err) | ||
| assert(t, q, args) | ||
| }) | ||
|
|
||
| t.Run("metadata_error", func(t *testing.T) { | ||
| _, _, err := makeInsertManyQuery(ctx, defaultSchema, []EventToInsert{ | ||
| {"fid", testEventType(1), []byte("metadata")}, | ||
| }) | ||
| require.ErrorContains(t, err, "metadata not enabled") | ||
| }) | ||
|
|
||
| t.Run("with_metadata", func(t *testing.T) { | ||
| schemaWithMetadata := defaultSchema | ||
| schemaWithMetadata.metadataField = "metadata" | ||
| q, args, err := makeInsertManyQuery(ctx, schemaWithMetadata, []EventToInsert{ | ||
| {"fid", testEventType(1), []byte("metadata")}, | ||
| }) | ||
| jtest.RequireNil(t, err) | ||
| assert(t, q, args) | ||
| }) | ||
|
|
||
| t.Run("with_trace", func(t *testing.T) { | ||
| schemaWithTrace := defaultSchema | ||
| schemaWithTrace.traceField = "trace" | ||
| traceID, err := trace.TraceIDFromHex("00000000000000000000000000000009") | ||
| jtest.RequireNil(t, err) | ||
| spanID, err := trace.SpanIDFromHex("0000000000000002") | ||
| jtest.RequireNil(t, err) | ||
| data, err := tracing.Marshal(trace.NewSpanContext(trace.SpanContextConfig{ | ||
| TraceID: traceID, | ||
| SpanID: spanID, | ||
| })) | ||
| jtest.RequireNil(t, err) | ||
| ctx := tracing.Inject(ctx, data) | ||
| q, args, err := makeInsertManyQuery(ctx, schemaWithTrace, []EventToInsert{ | ||
| {"fid", testEventType(1), nil}, | ||
| }) | ||
| jtest.RequireNil(t, err) | ||
| assert(t, q, args) | ||
| }) | ||
| } | ||
|
|
||
| type testEventType int | ||
|
|
||
| func (t testEventType) ReflexType() int { return int(t) } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
To support
for i := range N.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Any reason why we can't go for 1.23? If people are still using 1.22, they'd just have to use the version before this update
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No reason, just that I didn't need it.