view pkg/imports/bn.go @ 3302:ec6163c6687d

'Historicise' gauges on import Gauge data sets will be updated or a new version will be inserted depending on temporal validity and a timestamp marking the last update in the RIS-Index of a data set. The trigger on date_info is removed because the value is actually an attribut coming from the RIS-Index. Gauge measurements and predictions are associated to the version with matching temporal validity. Bottlenecks are always associated to the actual version of the gauge, although this might change as soon as bottlenecks are 'historicised', too.
author Tom Gottfried <tom@intevation.de>
date Thu, 16 May 2019 18:41:43 +0200
parents bfde4f8dd323
children 6592396f5061
line wrap: on
line source

// This is Free Software under GNU Affero General Public License v >= 3.0
// without warranty, see README.md and license for details.
//
// SPDX-License-Identifier: AGPL-3.0-or-later
// License-Filename: LICENSES/AGPL-3.0.txt
//
// Copyright (C) 2018, 2019 by via donau
//   – Österreichische Wasserstraßen-Gesellschaft mbH
// Software engineering by Intevation GmbH
//
// Author(s):
//  * Sascha L. Teichmann <sascha.teichmann@intevation.de>
//  * Tom Gottfried <tom.gottfried@intevation.de>

package imports

import (
	"context"
	"database/sql"
	"errors"
	"regexp"
	"strconv"
	"time"

	"gemma.intevation.de/gemma/pkg/soap/ifbn"
)

// Bottleneck is an import job to import
// bottlenecks from an IFBN SOAP service.
type Bottleneck struct {
	// URL is the URL of the SOAP service.
	URL string `json:"url"`
	// Tolerance used for axis snapping
	Tolerance float64 `json:"tolerance"`
	// Insecure indicates if HTTPS traffic
	// should validate certificates or not.
	Insecure bool `json:"insecure"`
}

// BNJobKind is the import queue type identifier.
const BNJobKind JobKind = "bn"

const (
	hasBottleneckSQL = `
SELECT true FROM waterway.bottlenecks WHERE bottleneck_id = $1`

	insertBottleneckSQL = `
INSERT INTO waterway.bottlenecks (
  bottleneck_id,
  gauge_location,
  gauge_validity,
  objnam,
  nobjnm,
  stretch,
  area,
  rb,
  lb,
  responsible_country,
  revisiting_time,
  limiting,
  date_info,
  source_organization
) VALUES (
  $1,
  isrs_fromText($2),
  (SELECT validity FROM waterway.gauges
     WHERE location = isrs_fromText($2) AND NOT erased),
  $3,
  $4,
  isrsrange(least(isrs_fromText($5), isrs_fromText($6)),
            greatest(isrs_fromText($5), isrs_fromText($6))),
  ISRSrange_area(
    ISRSrange_axis(isrsrange(least(isrs_fromText($5), isrs_fromText($6)),
                             greatest(isrs_fromText($5), isrs_fromText($6))),
                   $14),
    (SELECT ST_Collect(CAST(area AS geometry))
        FROM waterway.waterway_area)),
  $7,
  $8,
  $9,
  $10,
  $11,
  $12,
  $13
)
RETURNING id`

	insertBottleneckMaterialSQL = `
INSERT INTO waterway.bottlenecks_riverbed_materials (
   bottleneck_id,
   riverbed
) VALUES (
   $1,
   $2
)`
)

type bnJobCreator struct{}

func init() {
	RegisterJobCreator(BNJobKind, bnJobCreator{})
}

func (bnJobCreator) Description() string { return "bottlenecks" }

func (bnJobCreator) AutoAccept() bool { return false }

func (bnJobCreator) Create() Job { return new(Bottleneck) }

func (bnJobCreator) Depends() [2][]string {
	return [2][]string{
		{"bottlenecks", "bottlenecks_riverbed_materials"},
		{"gauges", "distance_marks_virtual", "waterway_axis", "waterway_area"},
	}
}

const (
	bnStageDoneSQL = `
UPDATE waterway.bottlenecks SET staging_done = true
WHERE id IN (
  SELECT key from import.track_imports
  WHERE import_id = $1 AND
        relation = 'waterway.bottlenecks'::regclass)`
)

// StageDone moves the imported bottleneck out of the staging area.
func (bnJobCreator) StageDone(
	ctx context.Context,
	tx *sql.Tx,
	id int64,
) error {
	_, err := tx.ExecContext(ctx, bnStageDoneSQL, id)
	return err
}

// CleanUp of a bottleneck import is a NOP.
func (*Bottleneck) CleanUp() error { return nil }

var rblbRe = regexp.MustCompile(`(..)_(..)`)

func splitRBLB(s string) (*string, *string) {
	m := rblbRe.FindStringSubmatch(s)
	if len(m) == 0 {
		return nil, nil
	}
	return &m[1], &m[2]
}

func revisitingTime(s string) int {
	v, err := strconv.Atoi(s)
	if err != nil {
		v = 0
	}
	return v
}

// Do executes the actual bottleneck import.
func (bn *Bottleneck) Do(
	ctx context.Context,
	importID int64,
	conn *sql.Conn,
	feedback Feedback,
) (interface{}, error) {

	fetch := func() ([]*ifbn.BottleNeckType, error) {
		client := ifbn.NewIBottleneckService(bn.URL, bn.Insecure, nil)

		req := &ifbn.Export_bn_by_isrs{}

		resp, err := client.Export_bn_by_isrs(req)
		if err != nil {
			return nil, err
		}

		if resp.Export_bn_by_isrsResult == nil {
			return nil, errors.New("no Bottlenecks found")
		}

		return resp.Export_bn_by_isrsResult.BottleNeckType, nil
	}

	return storeBottlenecks(ctx, fetch, importID, conn, feedback, bn.Tolerance)
}

func storeBottlenecks(
	ctx context.Context,
	fetch func() ([]*ifbn.BottleNeckType, error),
	importID int64,
	conn *sql.Conn,
	feedback Feedback,
	tolerance float64,
) (interface{}, error) {
	start := time.Now()

	bns, err := fetch()
	if err != nil {
		return nil, err
	}

	feedback.Info("Found %d bottlenecks for import", len(bns))

	var hasStmt, insertStmt, insertMaterialStmt, trackStmt *sql.Stmt

	for _, x := range []struct {
		sql  string
		stmt **sql.Stmt
	}{
		{hasBottleneckSQL, &hasStmt},
		{insertBottleneckSQL, &insertStmt},
		{insertBottleneckMaterialSQL, &insertMaterialStmt},
		{trackImportSQL, &trackStmt},
	} {
		var err error
		if *x.stmt, err = conn.PrepareContext(ctx, x.sql); err != nil {
			return nil, err
		}
		defer (*x.stmt).Close()
	}

	var nids []string

	feedback.Info("Tolerance used to snap waterway axis: %g", tolerance)

	for _, bn := range bns {
		if err := storeBottleneck(
			ctx, importID, conn, feedback, bn, &nids, tolerance,
			hasStmt, insertStmt, insertMaterialStmt, trackStmt); err != nil {
			return nil, err
		}
	}
	if len(nids) == 0 {
		return nil, UnchangedError("No new bottlenecks inserted")
	}

	feedback.Info("Storing %d bottlenecks took %s", len(nids), time.Since(start))
	feedback.Info("Import of bottlenecks was successful")
	summary := struct {
		Bottlenecks []string `json:"bottlenecks"`
	}{
		Bottlenecks: nids,
	}
	return &summary, nil
}

func storeBottleneck(
	ctx context.Context,
	importID int64,
	conn *sql.Conn,
	feedback Feedback,
	bn *ifbn.BottleNeckType,
	nids *[]string,
	tolerance float64,
	hasStmt, insertStmt, insertMaterialStmt, trackStmt *sql.Stmt,
) error {

	tx, err := conn.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback()

	var found bool
	err = tx.StmtContext(ctx, hasStmt).QueryRowContext(ctx,
		bn.Bottleneck_id).Scan(&found)
	switch {
	case err == sql.ErrNoRows:
		// This is good.
	case err != nil:
		return err
	case found:
		feedback.Info("'%s' already in database. Skip", bn.OBJNAM)
		// TODO: Deep comparison database vs. SOAP.
		return nil
	}

	rb, lb := splitRBLB(bn.Rb_lb)

	var limiting, country string

	if bn.Limiting_factor != nil {
		limiting = string(*bn.Limiting_factor)
	}

	if bn.Responsible_country != nil {
		country = string(*bn.Responsible_country)
	}

	var nid int64

	err = tx.StmtContext(ctx, insertStmt).QueryRowContext(
		ctx,
		bn.Bottleneck_id,
		bn.Fk_g_fid,
		bn.OBJNAM,
		bn.NOBJNM,
		bn.From_ISRS, bn.To_ISRS,
		rb,
		lb,
		country,
		revisitingTime(bn.Revisiting_time),
		limiting,
		bn.Date_Info,
		bn.Source,
		tolerance,
	).Scan(&nid)
	if err != nil {
		feedback.Warn("Failed to insert '%s' into database", bn.OBJNAM)
		feedback.Warn(handleError(err).Error())
		return nil
	}

	if bn.Riverbed != nil {
		for _, material := range bn.Riverbed.Material {
			if material != nil {
				mat := string(*material)
				if _, err := tx.StmtContext(ctx,
					insertMaterialStmt).ExecContext(
					ctx, nid, material); err != nil {
					feedback.Warn(
						"Failed to insert riverbed material '%s' for bottleneck '%s'.",
						mat, bn.OBJNAM)
					feedback.Warn(handleError(err).Error())
				}
			}
		}
	}

	if _, err := tx.StmtContext(ctx, trackStmt).ExecContext(
		ctx, importID, "waterway.bottlenecks", nid,
	); err != nil {
		return err
	}
	if err = tx.Commit(); err != nil {
		return err
	}
	feedback.Info("Inserted '%s' into database", bn.OBJNAM)
	*nids = append(*nids, bn.Bottleneck_id)
	return nil
}