Switch to batch inserts

main
Max Ignatenko 2024-04-14 12:45:05 +01:00
parent c204e48de1
commit bc24c23afc
1 changed files with 15 additions and 14 deletions

View File

@ -132,9 +132,10 @@ func (m *Mirror) runOnce(ctx context.Context) error {
return fmt.Errorf("unexpected status code: %d", resp.StatusCode) return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
} }
newEntries := 0 newEntries := []PLCLogEntry{}
decoder := json.NewDecoder(resp.Body) decoder := json.NewDecoder(resp.Body)
oldCursor := cursor oldCursor := cursor
for { for {
var entry plc.OperationLogEntry var entry plc.OperationLogEntry
err := decoder.Decode(&entry) err := decoder.Decode(&entry)
@ -145,25 +146,25 @@ func (m *Mirror) runOnce(ctx context.Context) error {
return fmt.Errorf("parsing log entry: %w", err) return fmt.Errorf("parsing log entry: %w", err)
} }
err = m.db.Clauses(
clause.OnConflict{
Columns: []clause.Column{{Name: "did"}, {Name: "cid"}},
DoNothing: true,
},
).Create(FromOperationLogEntry(entry)).Error
if err != nil {
return fmt.Errorf("inserting log entry into database: %w", err)
}
cursor = entry.CreatedAt cursor = entry.CreatedAt
newEntries++ newEntries = append(newEntries, *FromOperationLogEntry(entry))
} }
if newEntries == 0 || cursor == oldCursor { if len(newEntries) == 0 || cursor == oldCursor {
break break
} }
log.Info().Msgf("Got %d log entries. New cursor: %q", newEntries, cursor) err = m.db.Clauses(
clause.OnConflict{
Columns: []clause.Column{{Name: "did"}, {Name: "cid"}},
DoNothing: true,
},
).Create(newEntries).Error
if err != nil {
return fmt.Errorf("inserting log entry into database: %w", err)
}
log.Info().Msgf("Got %d log entries. New cursor: %q", len(newEntries), cursor)
} }
return nil return nil
} }