示例#1
0
 def canExecute(self):
     if FireDb is None:
         return (
             False,
             "Dette plugin er afhængigt af API'et til Fikspunktregistret. Se venligst https://github.com/Septima/fire-qgis#installation",
         )
     fire_connection_string = self.settings.value("fire_connection_string")
     if fire_connection_string is None:
         conf_message = "Kan ikke finde konfigurationsfil. Se venligst https://github.com/Kortforsyningen/fire-cli#konfigurationsfil for format og placering af konfigurationsfil"
         return False, conf_message
     else:
         try:
             fireDb = FireDb(fire_connection_string)
             fireDb.hent_observationstyper()
             return True, "OK"
         except Exception as ex:
             str_ex = str(ex)
             fire_connection_file_path = self.settings.value(
                 "fire_connection_file_path")
             return (
                 False,
                 "Fejl i forbindelse til Fikspunktregistret. Se venligst https://github.com/Kortforsyningen/fire-cli#konfigurationsfil for format og indhold af konfigurationsfil.          Exception:["
                 + str_ex + "]  Konfigurationsfil:[" +
                 fire_connection_file_path + "]",
             )
示例#2
0
def _set_database(ctx, param, value):
    """
    Vælg en specifik databaseforbindelse.
    """
    if value is not None:
        new_firedb = FireDb(db=str(value).lower())
        override_firedb(new_firedb)
示例#3
0
    def processAlgorithm(self, parameters, context,
                         feedback: QgsProcessingFeedback):
        # Input / Output
        source = self.parameterAsSource(parameters, self.INPUT, context)
        (sink, dest_id) = self.create_output_sink(parameters, context,
                                                  source.sourceCrs())

        # Filter parameters
        observation_type_indices = self.parameterAsEnums(
            parameters, self.OBSERVATION_TYPE, context)
        observation_types = list(
            map(lambda i: self.OBSERVATION_TYPES[i][0],
                observation_type_indices))

        from_date = None
        from_date_string = self.parameterAsString(parameters, self.FROM_DATE,
                                                  context)
        if from_date_string:
            from_date = datetime.fromisoformat(from_date_string)

        to_date = None
        to_date_string = self.parameterAsString(parameters, self.TO_DATE,
                                                context)
        if to_date_string:
            to_date = datetime.fromisoformat(to_date_string)

        fire_connection_string = self.settings.value("fire_connection_string")
        fireDb = FireDb(fire_connection_string, debug=True)

        features = list(source.getFeatures())
        total_num_features = len(features)
        total_num_features_processed = 0
        # for current, feature in enumerate(features):
        for feature in features:
            if feedback.isCanceled():
                return {}
            wkt = feature.geometry().asWkt().upper()
            geometry = Geometry(wkt)
            observations = fireDb.hent_observationer_naer_geometri(
                geometri=geometry, afstand=0, tidfra=from_date, tidtil=to_date)

            pid_list = self.get_pids_from_observations(observations)
            geometriobjekter = self.get_geometriobjekter_from_pids(
                fireDb, pid_list)
            idents = self.get_idents_from_pids(fireDb, pid_list)

            feedback.setProgressText(
                "Fandt {antal} observationer".format(antal=len(observations)))
            feedback.setProgressText("Fandt {antal} geometriobjekter".format(
                antal=len(geometriobjekter)))
            feedback.setProgressText(
                "Fandt {antal} idents".format(antal=len(idents)))
            for current, observation in enumerate(observations):
                observation_type_id = observation.observationstypeid
                if observation_type_id in observation_types:
                    feature = self.create_feature_from_observation(
                        observation, geometriobjekter, idents, feedback)
                    if feature:
                        sink.addFeature(feature, QgsFeatureSink.FastInsert)
            total_num_features_processed = total_num_features_processed + 1
            feedback.setProgress(total_num_features_processed /
                                 total_num_features)
            if feedback.isCanceled():
                return {}

        apply_theme = self.parameterAsBool(parameters, self.APPLY_THEME,
                                           context)
        if apply_theme:
            style_file = os.path.join(os.path.dirname(__file__), "..",
                                      "styles", "observation.qml")
            alg_params = {"INPUT": dest_id, "STYLE": style_file}
            processing.run(
                "qgis:setstyleforvectorlayer",
                alg_params,
                context=context,
                feedback=feedback,
                is_child_algorithm=True,
            )

        return {self.OUTPUT: dest_id}
示例#4
0
        "--monokrom",
        is_flag=True,
        callback=_set_monochrome,
        help="Vis ikke farver i terminalen",
    ),
    click.help_option(help="Vis denne hjælp tekst"),
]


def default_options():
    def _add_options(func):
        for option in reversed(_default_options):
            func = option(func)
        return func

    return _add_options


def print(*args, **kwargs):
    """
    Custom print function based on click.secho.

    Overrides color when 'monokrom' parameter is set applied in command
    line calls.
    """
    kwargs["color"] = _show_colors
    click.secho(*args, **kwargs)


firedb = FireDb()
示例#5
0
)


class DummyFireDb(FireDb):
    """
    FireDb klasse der bruges i tests hvor databaseudtræk med
    API-funktioner mockes.
    """
    def __init__(self, connectionstring=None, debug=False):
        self._cache = {
            "punkt": {},
            "punktinfotype": {},
        }


persistent_firedb = FireDb(db="ci", debug=False)
fire.cli.override_firedb(persistent_firedb)


@pytest.fixture
def firedb():
    return persistent_firedb


@pytest.fixture
def dummydb():
    return DummyFireDb()


@pytest.fixture()
def sag(firedb):
示例#6
0
"""
Indlæs herred- og sognegrænser i Oracledatabasen.

Dette kunne være en ogr2ogr one-liner, men da Oracle-driveren ikke
tilbydes som en del af gdal/ogr-pakken i conda-forge populeres databasen
istedet med dette script.
"""
from pathlib import Path

from sqlalchemy.sql import text
import fiona

from fire.api import FireDb
from fire.api.model import Geometry

firedb = FireDb(db="ci")

with fiona.open(Path(__file__).parent /
                "../data/herredsogn.shp") as herredsogn:
    for feature in herredsogn:
        g = Geometry(feature["geometry"])
        kode = feature["properties"]["kode"]

        # Fjollet hack for at omgå begrænsninger i Oracle.
        # Tilsyneladende må strenge ikke være længere end 4000 tegn, så her omgår vi begrænsningen
        # ved at splitte wkt-strengen i to dele og sammensætte den med ||-operatoren i SQL udtrykket.
        # Idioti, men det virker.
        wkt1, wkt2 = g.wkt[:len(g.wkt) // 2], g.wkt[len(g.wkt) // 2:]
        statement = text(f"""INSERT INTO herredsogn (kode, geometri)
                VALUES ('{kode}', SDO_GEOMETRY(TO_CLOB('{wkt1}') || TO_CLOB('{wkt2}'), 4326)
            )""")