diff --git a/pkg/database/source.go b/pkg/database/source.go index 6e31fc0..2a44bbe 100644 --- a/pkg/database/source.go +++ b/pkg/database/source.go @@ -245,3 +245,37 @@ func DeleteSource(ctx context.Context, id models.SourceID) error { utils.HandleEvent(span, localLogger, "Source deleted successfully") return nil } + +func CreateKnownSources(ctx context.Context) ([]models.Source, error) { + ctx, span, localLogger := utils.SetupTracing(ctx, tracer, "CreateKnownSources") + defer span.End() + + if client == nil { + return nil, utils.HandleError(ctx, span, localLogger, &otterError.Database{Reason: otterError.DatabaseIsNotConnected}) + } + + sources := []models.Source{ + { + DisplayName: "e621", + Domain: "e621.net", + Icon: "https://e621.net/safari-pinned-tab.svg", + }, + { + DisplayName: "Fur Affinity", + Domain: "furaffinity.net", + Icon: "https://www.furaffinity.net/themes/beta/img/banners/fa_logo.png", + }, + } + + result := client.WithContext(ctx).Model(models.Source{}).CreateInBatches(sources, len(sources)) + if result.Error != nil { + if errors.Is(result.Error, gorm.ErrDuplicatedKey) { + return nil, utils.HandleError(ctx, span, localLogger, &otterError.Database{Reason: otterError.DuplicateKey}) + } + return nil, utils.HandleError(ctx, span, localLogger, result.Error) + } + + utils.HandleEvent(span, localLogger, "Batch posts created successfully") + + return sources, nil +} diff --git a/pkg/database/source_test.go b/pkg/database/source_test.go index 9e23757..04fda94 100644 --- a/pkg/database/source_test.go +++ b/pkg/database/source_test.go @@ -537,6 +537,34 @@ func TestDeleteSource(t *testing.T) { } } +func TestCreateKnownSources(t *testing.T) { + // Setup trow away container + ctx := context.Background() + container, gormDB, err := test.StartPostgresContainer(ctx) + if err != nil { + logger.Fatalf("Could not start PostgreSQL container: %v", err) + } + + client = gormDB + + // Setup open telemetry + tracer = otel.Tracer(tracingName) + + hook := otellogrus.NewHook(tracingName) + logger.AddHook(hook) + + defer container.Terminate(ctx) + + // -- -- Tests + + t.Run("CreateKnownSources", func(t *testing.T) { + err, _ := CreateKnownSources(ctx) + if err != nil { + t.Errorf("DeleteSource() error = %v", err) + } + }) +} + func checkSourceID(got models.Source, want models.Source) bool { if got.ID != want.ID { return false