From 23695b4513328ad8f39cfe3f9709939d30cd94e9 Mon Sep 17 00:00:00 2001 From: markus Date: Mon, 14 Dec 2020 20:16:35 +0100 Subject: [PATCH] fix: update rows when already exist during an import When rows in the table devices, sensors, humidities, pressures and temperatures already exist, they will only be updated. --- pkg/repository/repository.go | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/pkg/repository/repository.go b/pkg/repository/repository.go index 3227050..68395b3 100644 --- a/pkg/repository/repository.go +++ b/pkg/repository/repository.go @@ -271,18 +271,21 @@ func Import(sourceDSNURL *url.URL, destDNSURL *url.URL, flogger logger.Logger, o } } + // Initialize source repository sourceRepo, err := New(sourceDSNURL, flogger) if err != nil { return fmt.Errorf("Failed to open the source repo: %w", err) } defer sourceRepo.Close() + // Initialize destination repository destRepo, err := New(destDNSURL, flogger) if err != nil { return fmt.Errorf("Failed to open the destination repo: %w", err) } defer destRepo.Close() + // AddOrUpdate: Devices ctx := context.Background() devices, err := sourceRepo.database.SelectDevices(ctx) if err != nil { @@ -292,12 +295,13 @@ func Import(sourceDSNURL *url.URL, destDNSURL *url.URL, flogger logger.Logger, o flogger.Debug("Found %v devices", len(devices)) for i := range devices { - err := destRepo.AddDevices(devices[i]) + err := destRepo.AddOrUpdateDevices(devices[i]) if err != nil { - return fmt.Errorf("Failed to add device %v into dest repo: %w", devices[i].Name, err) + return fmt.Errorf("Failed to add or update device %v into dest repo: %w", devices[i].Name, err) } } + // AddOrUpdate: Sensors if optImport.Sensors { sensors, err := sourceRepo.database.SelectSensors(ctx) if err != nil { @@ -307,9 +311,9 @@ func Import(sourceDSNURL *url.URL, destDNSURL *url.URL, flogger logger.Logger, o flogger.Debug("Found %v sensors", len(sensors)) for i := range sensors { - err := destRepo.AddSensors(sensors[i]) + err := destRepo.AddOrUpdateSensors(sensors[i]) if err != nil { - return fmt.Errorf("Failed to add sensor %v into dest repo: %w", sensors[i].Name, err) + return fmt.Errorf("Failed to add or update sensor %v into dest repo: %w", sensors[i].Name, err) } } } @@ -327,9 +331,9 @@ func Import(sourceDSNURL *url.URL, destDNSURL *url.URL, flogger logger.Logger, o flogger.Debug("Found %v %v values", len(measuredValues), key) - err = destRepo.AddMeasuredValues(measuredValues...) + err = destRepo.AddOrUpdateMeasuredValues(measuredValues...) if err != nil { - return fmt.Errorf("Failed to add %v into dest repo: %w", key, err) + return fmt.Errorf("Failed to add or update %v into dest repo: %w", key, err) } } }