PostGIS - Como faço para verificar o tipo de geometria antes de fazer uma inserção

StackOverflow https://stackoverflow.com/questions/2023821

  •  19-09-2019
  •  | 
  •  

Pergunta

Eu tenho um banco de dados do PostGres com milhões de linhas que possui uma coluna chamada Geom, que contém o limite de uma propriedade.

Usando um script python, estou extraindo as informações desta tabela e a inserir novamente em uma nova tabela.

Quando eu insiro na nova tabela, o script se bate com o seguinte:

Traceback (most recent call last):
  File "build_parcels.py", line 258, in <module>
    main()
  File "build_parcels.py", line 166, in main
    update_cursor.executemany("insert into parcels (par_id, street_add, title_no, proprietors, au_name, ua_name, geom) VALUES (%s, %s, %s, %s, %s, %s, %s)", inserts)
psycopg2.IntegrityError: new row for relation "parcels" violates check constraint "enforce_geotype_geom"

A nova tabela possui uma restrição de verificação enforce_geotype_geom = ((geometrytype (geom) = 'polygon' :: text) ou (geom é nulo)) enquanto a tabela antiga não, então estou supondo ?) Na tabela antiga. Quero manter os novos dados como polígono, então não quero inserir mais nada.

Inicialmente, tentei encerrar a consulta com o manuseio de erros do Python padrão com a esperança de que as linhas geoms fracassassem, mas o script continuaria em execução, mas o script foi gravado para se comprometer no final e não cada linha, para que não funcione.

Eu acho que o que preciso fazer é iterar através das linhas geom de mesa antiga e verificar que tipo de geometria elas são para que eu possa estabelecer se quero ou não mantê -lo ou jogá -lo fora antes de inserir na nova tabela

Qual é a melhor maneira de fazer isso?

Foi útil?

Solução

Esse pedaço surpreendentemente útil do PostGIS SQL deve ajudá -lo a descobrir ... Existem muitos testes do tipo geometria aqui:

-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-- 
-- $Id: cleanGeometry.sql 2008-04-24 10:30Z Dr. Horst Duester $
--
-- cleanGeometry - remove self- and ring-selfintersections from 
--                 input Polygon geometries 
-- http://www.sogis.ch
-- Copyright 2008 SO!GIS Koordination, Kanton Solothurn, Switzerland
-- Version 1.0
-- contact: horst dot duester at bd dot so dot ch
--
-- This is free software; you can redistribute and/or modify it under
-- the terms of the GNU General Public Licence. See the COPYING file.
-- This software is without any warrenty and you use it at your own risk
--  
-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


CREATE OR REPLACE FUNCTION cleanGeometry(geometry)
  RETURNS geometry AS
$BODY$DECLARE
  inGeom ALIAS for $1;
  outGeom geometry;
  tmpLinestring geometry;

Begin

  outGeom := NULL;

-- Clean Process for Polygon 
  IF (GeometryType(inGeom) = 'POLYGON' OR GeometryType(inGeom) = 'MULTIPOLYGON') THEN

-- Only process if geometry is not valid, 
-- otherwise put out without change
    if not isValid(inGeom) THEN

-- create nodes at all self-intersecting lines by union the polygon boundaries
-- with the startingpoint of the boundary.  
      tmpLinestring := st_union(st_multi(st_boundary(inGeom)),st_pointn(boundary(inGeom),1));
      outGeom = buildarea(tmpLinestring);      
      IF (GeometryType(inGeom) = 'MULTIPOLYGON') THEN      
        RETURN st_multi(outGeom);
      ELSE
        RETURN outGeom;
      END IF;
    else    
      RETURN inGeom;
    END IF;


------------------------------------------------------------------------------
-- Clean Process for LINESTRINGS, self-intersecting parts of linestrings 
-- will be divided into multiparts of the mentioned linestring 
------------------------------------------------------------------------------
  ELSIF (GeometryType(inGeom) = 'LINESTRING') THEN

-- create nodes at all self-intersecting lines by union the linestrings
-- with the startingpoint of the linestring.  
    outGeom := st_union(st_multi(inGeom),st_pointn(inGeom,1));
    RETURN outGeom;
  ELSIF (GeometryType(inGeom) = 'MULTILINESTRING') THEN 
    outGeom := multi(st_union(st_multi(inGeom),st_pointn(inGeom,1)));
    RETURN outGeom;
  ELSIF (GeometryType(inGeom) = '<NULL>' OR GeometryType(inGeom) = 'GEOMETRYCOLLECTION') THEN 
    RETURN NULL;
  ELSE 
    RAISE NOTICE 'The input type % is not supported %',GeometryType(inGeom),st_summary(inGeom);
    RETURN inGeom;
  END IF;     
End;$BODY$
  LANGUAGE 'plpgsql' VOLATILE;

Outras dicas

A opção 1 é criar um ponto de salvamento antes de cada inserção e reverter para esse ponto de segurança se um INSERT falha.

A opção 2 é anexar a expressão de restrição de verificação como um WHERE Condição da consulta original que produziu os dados para evitar selecioná -los.

A melhor resposta depende do tamanho das tabelas, do número relativo de linhas defeituosas e quão rápido e muitas vezes isso deve ser executado.

Eu acho que você pode usarSt_collectionExtract - Dada uma (geometria multi), retorna uma (multi) geometria que consiste apenas de elementos do tipo especificado.

Eu o uso ao inserir os resultados de uma ST_INTERSECTION, o ST_DUMP quebra qualquer multi-polígono, coleções em geometria individual. Então ST_CollectionExtract (theGeom, 3) descarta qualquer coisa, menos polígonos:

ST_CollectionExtract((st_dump(ST_Intersection(data.polygon, grid.polygon))).geom, )::geometry(polygon, 4326)

O segundo parâmetro acima 3 pode ser: 1 == POINT, 2 == LINESTRING, 3 == POLYGON

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top