/* contrib/srm_funct/srm_funct--unpackaged--1.0.sql */

-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "CREATE EXTENSION srm_funct FROM unpackaged" to load this file. \quit

/* contrib/srm_funct/srm_funct--1.0.sql */

SET search_path TO public, topology, tiger, tiger_data;

CREATE OR REPLACE FUNCTION funciones."10_tablas_union_mv"(
	num_tablas text,
	esch text,
	contenido text,
	nameview text,
	nametable1 text,
	nametable2 text,
	nametable3 text,
	nametable4 text,
	nametable5 text,
	nametable6 text,
	nametable7 text,
	nametable8 text,
	nametable9 text,
	nametable10 text)
    RETURNS text
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ declare tab text; BEGIN 
--el numero de tablas marca el número de uniones, funcion que une hasta 10 tablas
CASE
  WHEN num_tablas = '2' THEN

EXECUTE 'create materialized view "'|| esch ||'"."'|| nameview ||'" as 
	select '|| contenido ||' FROM "'|| esch ||'"."'|| nametable1||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable2||'"';
ELSE tab := '2';
  END CASE;
  CASE
  WHEN num_tablas = '3' THEN
--las geometrias no validas
EXECUTE 'create materialized view "'|| esch ||'"."'|| nameview ||'" as 
	select '|| contenido ||' FROM "'|| esch ||'"."'|| nametable1||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable2||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable3||'"';
ELSE tab := '3';
  END CASE;
  
   CASE
  WHEN num_tablas = '4' THEN
--las geometrias no validas
EXECUTE 'create materialized view "'|| esch ||'"."'|| nameview ||'" as 
	select '|| contenido ||' FROM "'|| esch ||'"."'|| nametable1||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable2||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable3||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable4||'"';
ELSE tab := '4';
  END CASE;
  
     CASE
  WHEN num_tablas = '5' THEN
--las geometrias no validas
EXECUTE 'create materialized view "'|| esch ||'"."'|| nameview ||'" as 
	select '|| contenido ||' FROM "'|| esch ||'"."'|| nametable1||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable2||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable3||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable4||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable5||'"';

ELSE tab := '5';
END CASE;
     CASE
  WHEN num_tablas = '6' THEN
--las geometrias no validas
EXECUTE 'create materialized view "'|| esch ||'"."'|| nameview ||'" as 
	select '|| contenido ||' FROM "'|| esch ||'"."'|| nametable1||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable2||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable3||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable4||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable5||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable6||'"';

ELSE tab := '6';
  END CASE;
       CASE
  WHEN num_tablas = '7' THEN
--las geometrias no validas
EXECUTE 'create materialized view "'|| esch ||'"."'|| nameview ||'" as 
	select '|| contenido ||' FROM "'|| esch ||'"."'|| nametable1||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable2||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable3||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable4||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable5||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable6||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable7||'"';
ELSE tab := '7';
  END CASE;
  
       CASE
  WHEN num_tablas = '8' THEN
--las geometrias no validas
EXECUTE 'create materialized view "'|| esch ||'"."'|| nameview ||'" as 
	select '|| contenido ||' FROM "'|| esch ||'"."'|| nametable1||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable2||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable3||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable4||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable5||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable6||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable7||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable8||'"';
ELSE tab := '8';
  END CASE;

          CASE
  WHEN num_tablas = '9' THEN
--las geometrias no validas
EXECUTE 'create materialized view "'|| esch ||'"."'|| nameview ||'" as 
	select '|| contenido ||' FROM "'|| esch ||'"."'|| nametable1||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable2||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable3||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable4||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable5||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable6||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable7||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable8||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable9||'"';
ELSE tab := '9';
  END CASE;
           CASE
  WHEN num_tablas = '10' THEN
--las geometrias no validas
EXECUTE 'create materialized view "'|| esch ||'"."'|| nameview ||'" as 
	select '|| contenido ||' FROM "'|| esch ||'"."'|| nametable1||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable2||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable3||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable4||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable5||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable6||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable7||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable8||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable9||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable10||'"';
ELSE tab := '10';
  END CASE;
  Return tab;
  END; $BODY$;
  
  
CREATE OR REPLACE FUNCTION funciones."10_tablas_union_vw"(
	num_tablas text,
	esch text,
	contenido text,
	nameview text,
	nametable1 text,
	nametable2 text,
	nametable3 text,
	nametable4 text,
	nametable5 text,
	nametable6 text,
	nametable7 text,
	nametable8 text,
	nametable9 text,
	nametable10 text)
    RETURNS text
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ declare tab text; BEGIN --el numero de tablas marca el número de uniones, funcion que une hasta 10 tablas
CASE
  WHEN num_tablas = '2' THEN

EXECUTE 'create  view "'|| esch ||'"."'|| nameview ||'" as 
	select '|| contenido ||' FROM "'|| esch ||'"."'|| nametable1||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable2||'"';
ELSE tab := '2';
  END CASE;
  CASE
  WHEN num_tablas = '3' THEN
--las geometrias no validas
EXECUTE 'create  view "'|| esch ||'"."'|| nameview ||'" as 
	select '|| contenido ||' FROM "'|| esch ||'"."'|| nametable1||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable2||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable3||'"';
ELSE tab := '3';
  END CASE;
  
   CASE
  WHEN num_tablas = '4' THEN
--las geometrias no validas
EXECUTE 'create  view "'|| esch ||'"."'|| nameview ||'" as 
	select '|| contenido ||' FROM "'|| esch ||'"."'|| nametable1||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable2||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable3||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable4||'"';
ELSE tab := '4';
  END CASE;
  
     CASE
  WHEN num_tablas = '5' THEN
--las geometrias no validas
EXECUTE 'create  view "'|| esch ||'"."'|| nameview ||'" as 
	select '|| contenido ||' FROM "'|| esch ||'"."'|| nametable1||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable2||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable3||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable4||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable5||'"';

ELSE tab := '5';
END CASE;
     CASE
  WHEN num_tablas = '6' THEN
--las geometrias no validas
EXECUTE 'create  view "'|| esch ||'"."'|| nameview ||'" as 
	select '|| contenido ||' FROM "'|| esch ||'"."'|| nametable1||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable2||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable3||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable4||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable5||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable6||'"';

ELSE tab := '6';
  END CASE;
       CASE
  WHEN num_tablas = '7' THEN
--las geometrias no validas
EXECUTE 'create  view "'|| esch ||'"."'|| nameview ||'" as 
	select '|| contenido ||' FROM "'|| esch ||'"."'|| nametable1||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable2||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable3||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable4||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable5||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable6||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable7||'"';
ELSE tab := '7';
  END CASE;
  
       CASE
  WHEN num_tablas = '8' THEN
--las geometrias no validas
EXECUTE 'create  view "'|| esch ||'"."'|| nameview ||'" as 
	select '|| contenido ||' FROM "'|| esch ||'"."'|| nametable1||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable2||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable3||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable4||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable5||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable6||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable7||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable8||'"';
ELSE tab := '8';
  END CASE;

          CASE
  WHEN num_tablas = '9' THEN
--las geometrias no validas
EXECUTE 'create  view "'|| esch ||'"."'|| nameview ||'" as 
	select '|| contenido ||' FROM "'|| esch ||'"."'|| nametable1||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable2||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable3||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable4||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable5||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable6||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable7||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable8||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable9||'"';
ELSE tab := '9';
  END CASE;
           CASE
  WHEN num_tablas = '10' THEN
--las geometrias no validas
EXECUTE 'create  view "'|| esch ||'"."'|| nameview ||'" as 
	select '|| contenido ||' FROM "'|| esch ||'"."'|| nametable1||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable2||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable3||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable4||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable5||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable6||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable7||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable8||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable9||'"
UNION ALL
select  '|| contenido ||' FROM "'|| esch ||'"."'|| nametable10||'"';
ELSE tab := '10';
  END CASE;
  Return tab;
  END; $BODY$;
  
  


CREATE OR REPLACE FUNCTION funciones.__alter_column_name_mv(
	esch text,
	name_tables text,
	column_name text,
	new_column_name text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*Descripcion: sirve para renombrar una columna de una vista materializada, column_name (viejo nombre de la columna), new_column_name (nuevo nombre de la columna) */
	EXECUTE 'ALTER MATERIALIZED VIEW "'|| esch ||'"."'|| name_tables ||'" RENAME COLUMN "'|| column_name ||'" TO "'|| new_column_name||'"';
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__alter_table_name(
	esch text,
	name_tables character varying,
	new_name character varying)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*Descripcion: sirve para renombrar una tabla foranea, name_tables (viejo nombre de la tabla), new_name (nuevo nombre de la tabla) */
		EXECUTE 'ALTER FOREIGN TABLE "'|| esch ||'".'|| name_tables ||' RENAME TO "'|| new_name||'"';
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__change_epsg(
	esch text,
	name_table character varying,
	epsg numeric,
	geometria text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$

BEGIN
		/*Descripcion: sirve para cambiar el epsg */
		EXECUTE 'ALTER TABLE "'|| esch ||'"."'||name_table||'" ALTER COLUMN geom TYPE Geometry('||geometria||',' || epsg||')';
		
END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.__contour_lines(
	geomin geometry[],
	colin numeric[],
	breaks numeric[])
    RETURNS TABLE(geom geometry, break numeric) 
    LANGUAGE 'plpgsql'

    COST 100
    IMMUTABLE 
    ROWS 1000
AS $BODY$ 
/*Extrae la interpolación de puntos de dispersión, convirtiendolas en lineas de contorno, colin: numeric values array
breaks: numeric breaks array*/
DECLARE
	bucketin integer[];
	gs geometry[];
	g geometry;
	vertex geometry[];
	vv numeric[];
	bu integer[];
	inter numeric[];
	interp12 geometry[];
	interp23 geometry[];
	interp31 geometry[];
	segment geometry[];
	running_merge geometry[];
	i integer;
BEGIN
	WITH
	a AS(
		SELECT
			width_bucket(t.x, breaks) AS bin
		FROM unnest(colin) AS t(x)
	)
	SELECT array_agg(bin) INTO bucketin FROM a;

	WITH
	a AS (SELECT unnest(geomin) AS e),
	b AS (SELECT ST_DelaunayTriangles(ST_Collect(a.e)) AS t FROM a),
	c AS (SELECT (ST_Dump(t)).geom AS v FROM b)
	SELECT array_agg(v) INTO gs FROM c;

	i:= 0;

	FOREACH g IN ARRAY gs
	LOOP

		SELECT
			array_agg(a.v),
			array_agg(b.c), 
			array_agg(b.bk)
		INTO vertex, vv, bu
		FROM
		(
			SELECT (ST_DumpPoints(g)).geom AS v limit 3
		) as a
		CROSS JOIN 
		LATERAL(
			SELECT
				t.*
			FROM
				unnest(geomin, colin, bucketin) AS t(geo, c, bk)
			WHERE ST_Equals(geo, a.v)
			LIMIT 1
		) AS b;

		CONTINUE WHEN bu[1] = bu[2] and bu[1] = bu[3];

		interp12 := _get_cell_intersects(vertex, vv, bu, breaks,1,2);
		interp23 := _get_cell_intersects(vertex, vv, bu, breaks,2,3);
		interp31 := _get_cell_intersects(vertex, vv, bu, breaks,3,1);

		WITH
		a AS(
            SELECT
                t.*
            FROM
            unnest(breaks, interp12, interp23, interp31) AS t(br, p12 , p23, p31)
		),
		b AS(
		SELECT
            CASE
            WHEN
            (p12 IS NOT NULL AND p23 IS NOT NULL AND ST_equals(p12, p23)=false) OR
            (p23 IS NOT NULL AND p31 IS NOT NULL AND ST_equals(p23, p31)=false) OR
            (p31 IS NOT NULL AND p12 IS NOT NULL AND ST_equals(p31, p12)=false)
            THEN ST_MakeLine(ARRAY[p12, p23, p31]::geometry[])
            ELSE null::geometry END AS segm,
            br
		FROM a
		)
		SELECT
		    array_agg(b.segm) into segment
		FROM unnest(breaks) AS c(x) 
        LEFT JOIN b ON b.br = c.x;

		IF i = 0 THEN
            running_merge = segment;
            i := 1;
		ELSE
            WITH
            a AS(
                SELECT
                    ST_CollectionExtract(x, 2) AS x,
                    y
                FROM unnest(running_merge,segment) AS t(x,y)
            ),
            b AS(
                SELECT
                ST_collect(x,y) AS element
                FROM a
            )
            SELECT
                array_agg(element) INTO running_merge
            FROM b;
		END IF;

	END LOOP;

	RETURN QUERY
	WITH a AS(
            SELECT
                br,
                ST_CollectionExtract(geo, 2) AS geo
            FROM unnest(running_merge, breaks) AS t(geo, br)
        ),
        b AS(
            SELECT
                ST_LineMerge(geo) AS geo,
                br
            FROM a
        )
    SELECT
        geo AS geom,
        br AS break
	FROM b;

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__crear_tesela(
	geom geometry,
	x_side double precision,
	y_side double precision,
	OUT geometry)
    RETURNS SETOF geometry 
    LANGUAGE 'plpgsql'

    COST 100
    IMMUTABLE STRICT 
    ROWS 1000
AS $BODY$ 
/*crea una geometría de salida con la teselación de una geometría de entrada que ha de ser un polígono. geom:campo geometría, x_side:tamaño de la tesela en X,
y_side:tamaño de la tesela en Y*/
DECLARE
x_max DECIMAL;
y_max DECIMAL;
x_min DECIMAL;
y_min DECIMAL;
srid INTEGER := 4326;
input_srid INTEGER;
x_series DECIMAL;
y_series DECIMAL;
geom_cell geometry := ST_GeomFromText(FORMAT('POLYGON((0 0, 0 %s, %s %s, %s 0,0 0))',
											$3, $2, $3, $2), srid);
BEGIN
	CASE ST_SRID (geom) WHEN 0 THEN
		geom := ST_SetSRID (geom, srid);
		RAISE NOTICE'SRID Not Found.';
	ELSE
		RAISE NOTICE'SRID Found.';
	END CASE;
	input_srid := ST_srid ( geom );
	geom := ST_Transform ( geom, srid );
	x_max := ST_XMax ( geom );
	y_max := ST_YMax ( geom );
	x_min := ST_XMin ( geom );
	y_min := ST_YMin ( geom );
	x_series := CEIL ( @( x_max - x_min ) / x_side );
	y_series := CEIL ( @( y_max - y_min ) / y_side );

	RETURN QUERY With foo AS (
		SELECT
		ST_Translate( geom_cell, j * $2 + x_min, i * $3 + y_min ) AS cell
		FROM
			generate_series ( 0, x_series ) AS j,
			generate_series ( 0, y_series ) AS i
		) SELECT ST_CollectionExtract(ST_Collect(ST_Transform ( ST_Intersection(cell, geom), input_srid)), 3)
		FROM foo where ST_intersects (cell, geom);
END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.__crear_teselas_en_poligono_mv(
	esch text,
	namein text,
	nameout text,
	x text,
	y text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geoma text;
srid1 text;

BEGIN
/*se lanza la función __crear_tesela y de las teselas que extrae las separa añadiendolas un identificador */
SELECT f_geometry_column into geoma 
FROM geometry_columns 
WHERE f_table_schema = esch 
AND f_table_name = namein; 

EXECUTE 'select ST_SRID('||geoma||') from  "'|| esch ||'"."'|| namein ||'" group by ST_SRID;' into srid1;

EXECUTE 'create materialized view  "'|| esch ||'"."'|| nameout ||'"
as select row_number ()over() as id_tess,st_transform(st_setsrid(geom,'|| srid1 ||'),4326)::geometry(Geometry, 4326) as geom from 
(select (st_dump (geom)).geom from (select funciones.__crear_tesela(
	'|| geoma ||',
	'|| x ||',
	'|| y ||') as geom from  "'|| esch ||'"."'|| namein ||'")t order by geom desc)t;';

END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.__crear_teselas_en_poligono_vw(
	esch text,
	namein text,
	nameout text,
	x text,
	y text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geoma text;
srid1 text;

BEGIN
/*se lanza la función __crear_tesela y de las teselas que extrae las separa añadiendolas un identificador */
SELECT f_geometry_column into geoma 
FROM geometry_columns 
WHERE f_table_schema = esch 
AND f_table_name = namein; 

EXECUTE 'select ST_SRID('||geoma||') from  "'|| esch ||'"."'|| namein ||'" group by ST_SRID;' into srid1;

EXECUTE 'create view  "'|| esch ||'"."'|| nameout ||'"
as select row_number ()over() as id_tess,st_transform(st_setsrid(geom,'|| srid1 ||'),4326)::geometry(Geometry, 4326) as geom from 
(select (st_dump (geom)).geom from (select funciones.__crear_tesela(
	'|| geoma ||',
	'|| x ||',
	'|| y ||') as geom from  "'|| esch ||'"."'|| namein ||'")t order by geom desc)t;';

END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.__create_innerjoin_id_mv(
	esch text,
	namemv text,
	nametablegeom text,
	nametablegeom_id text,
	tematic text,
	tematic_id text,
	contenido text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: crea una vista materializada desde un innerjoin, nametablegeom_id (nombre de la columna de la tabla geométrica), tematic_id (nombre de la columna de la tabla temática) */
	EXECUTE 'CREATE MATERIALIZED VIEW  "'|| esch ||'"."'|| namemv ||'" AS SELECT '|| contenido||' 
	From "'|| esch ||'"."'|| nametablegeom ||'" INNER JOIN "'|| esch ||'"."'|| tematic ||'" 
	ON concat( "'|| nametablegeom ||'"."'|| nametablegeom_id ||'" )= concat( "'|| tematic ||'"."'|| tematic_id ||'" )';
	
	EXECUTE 'create unique index on "'|| esch ||'"."'|| namemv ||'" (id_srm)';
exception when others then 
EXECUTE 'CREATE MATERIALIZED VIEW  "'|| esch ||'"."'|| namemv ||'" AS select row_number ()over() as id_srm,* from (SELECT '|| contenido||' 
	From "'|| esch ||'"."'|| nametablegeom ||'" INNER JOIN "'|| esch ||'"."'|| tematic ||'" 
	ON concat( "'|| nametablegeom ||'"."'|| nametablegeom_id ||'" )= concat( "'|| tematic ||'"."'|| tematic_id ||'" ))t';
	
	EXECUTE 'create unique index on "'|| esch ||'"."'|| namemv ||'" (id_srm)';
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__create_innerjoin_id_vw(
	esch text,
	namemv text,
	nametablegeom text,
	nametablegeom_id text,
	tematic text,
	tematic_id text,
	contenido text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: crea una vista desde un innerjoin, nametablegeom_id (nombre de la columna de la tabla geométrica), tematic_id (nombre de la columna de la tabla temática) */
	EXECUTE 'CREATE VIEW  "'|| esch ||'"."'|| namemv ||'" AS SELECT '|| contenido||' From "'|| esch ||'"."'|| nametablegeom ||'" INNER JOIN "'|| esch ||'"."'|| tematic ||'" ON concat( "'|| nametablegeom ||'"."'|| nametablegeom_id ||'" )= concat( "'|| tematic ||'"."'|| tematic_id ||'" )';
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__create_innerjoin_mv(
	esch text,
	namemv text,
	nametablegeom text,
	nametablegeom_id text,
	tematic text,
	tematic_id text,
	contenido text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: crea una vista materializada desde un innerjoin, nametablegeom_id (nombre de la columna de la tabla geométrica), tematic_id (nombre de la columna de la tabla temática) */
		EXECUTE 'CREATE MATERIALIZED VIEW  "'|| esch ||'"."'|| namemv ||'" AS select a.*
FRom "'|| esch ||'"."'|| nametablegeom ||'"  as B
     INNER JOIN (SELECT '|| contenido||',similarity ("'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text,"'|| tematic ||'"."'|| tematic_id ||'"::text)as similarity_index 
	From "'|| esch ||'"."'|| nametablegeom ||'"  INNER JOIN "'|| esch ||'"."'|| tematic ||'" 
	ON  "'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text % "'|| tematic ||'"."'|| tematic_id ||'"::text)A
     ON A."'|| nametablegeom_id ||'" = B."'|| nametablegeom_id ||'"
    INNER JOIN ( 
          select A."'|| nametablegeom_id ||'",MAX(A.similarity)as expertrank
          from (SELECT '|| contenido||',similarity ("'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text,"'|| tematic ||'"."'|| tematic_id ||'"::text) 
	From "'|| esch ||'"."'|| nametablegeom ||'"  INNER JOIN "'|| esch ||'"."'|| tematic ||'" 
	ON  "'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text % "'|| tematic ||'"."'|| tematic_id ||'"::text)A 
          group by A."'|| nametablegeom_id ||'"
     ) as NewA 
    ON a."'|| nametablegeom_id ||'" = NewA."'|| nametablegeom_id ||'" 
       AND a.similarity_index = NewA.expertrank;';
	   EXECUTE 'create unique index on "'|| esch ||'"."'|| namemv ||'" (id_srm)';
exception when others then 
EXECUTE 'CREATE MATERIALIZED VIEW  "'|| esch ||'"."'|| namemv ||'" AS select row_number ()over() as id_srm,* from (select a.*
FRom "'|| esch ||'"."'|| nametablegeom ||'"  as B
     INNER JOIN (SELECT '|| contenido||',similarity ("'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text,"'|| tematic ||'"."'|| tematic_id ||'"::text)as similarity_index 
	From "'|| esch ||'"."'|| nametablegeom ||'"  INNER JOIN "'|| esch ||'"."'|| tematic ||'" 
	ON  "'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text % "'|| tematic ||'"."'|| tematic_id ||'"::text)A
     ON A."'|| nametablegeom_id ||'" = B."'|| nametablegeom_id ||'"
    INNER JOIN ( 
          select A."'|| nametablegeom_id ||'",MAX(A.similarity)as expertrank
          from (SELECT '|| contenido||',similarity ("'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text,"'|| tematic ||'"."'|| tematic_id ||'"::text) 
	From "'|| esch ||'"."'|| nametablegeom ||'"  INNER JOIN "'|| esch ||'"."'|| tematic ||'" 
	ON  "'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text % "'|| tematic ||'"."'|| tematic_id ||'"::text)A 
          group by A."'|| nametablegeom_id ||'"
     ) as NewA 
    ON a."'|| nametablegeom_id ||'" = NewA."'|| nametablegeom_id ||'" 
       AND a.similarity_index = NewA.expertrank)t;';
	   EXECUTE 'create unique index on "'|| esch ||'"."'|| namemv ||'" (id_srm)';
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__create_innerjoin_vw(
	esch text,
	namemv text,
	nametablegeom text,
	nametablegeom_id text,
	tematic text,
	tematic_id text,
	contenido text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: crea una vista  desde un innerjoin, nametablegeom_id (nombre de la columna de la tabla geométrica), tematic_id (nombre de la columna de la tabla temática) */
	EXECUTE 'CREATE VIEW  "'|| esch ||'"."'|| namemv ||'" AS select a.*
FRom "'|| esch ||'"."'|| nametablegeom ||'"  as B
     INNER JOIN (SELECT '|| contenido||',similarity ("'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text,"'|| tematic ||'"."'|| tematic_id ||'"::text)as similarity_index 
	From "'|| esch ||'"."'|| nametablegeom ||'"  INNER JOIN "'|| esch ||'"."'|| tematic ||'" 
	ON  "'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text % "'|| tematic ||'"."'|| tematic_id ||'"::text)A
     ON A."'|| nametablegeom_id ||'" = B."'|| nametablegeom_id ||'"
    INNER JOIN ( 
          select A."'|| nametablegeom_id ||'",MAX(A.similarity)as expertrank
          from (SELECT '|| contenido||',similarity ("'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text,"'|| tematic ||'"."'|| tematic_id ||'"::text) 
	From "'|| esch ||'"."'|| nametablegeom ||'"  INNER JOIN "'|| esch ||'"."'|| tematic ||'" 
	ON  "'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text % "'|| tematic ||'"."'|| tematic_id ||'"::text)A 
          group by A."'|| nametablegeom_id ||'"
     ) as NewA 
    ON a."'|| nametablegeom_id ||'" = NewA."'|| nametablegeom_id ||'" 
       AND a.similarity_index = NewA.expertrank;';
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__create_leftjoin__id_vw(
	esch text,
	namemv text,
	nametablegeom text,
	nametablegeom_id text,
	tematic text,
	tematic_id text,
	contenido text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: crea una vista desde un leftjoin, nametablegeom_id (nombre de la columna de la tabla geométrica), tematic_id (nombre de la columna de la tabla temática) */
	EXECUTE 'CREATE VIEW  "'|| esch ||'"."'|| namemv ||'" AS SELECT '|| contenido||' From "'|| esch ||'"."'|| nametablegeom ||'" LEFT JOIN "'|| esch ||'"."'|| tematic ||'" ON concat( "'|| nametablegeom ||'"."'|| nametablegeom_id ||'" )= concat( "'|| tematic ||'"."'|| tematic_id ||'" )';
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__create_leftjoin_id_mv(
	esch text,
	namemv text,
	nametablegeom text,
	nametablegeom_id text,
	tematic text,
	tematic_id text,
	contenido text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: crea una vista materializada desde un innerjoin, nametablegeom_id (nombre de la columna de la tabla geométrica), tematic_id (nombre de la columna de la tabla temática) */
	EXECUTE 'CREATE MATERIALIZED VIEW  "'|| esch ||'"."'|| namemv ||'" AS SELECT '|| contenido||' From "'|| esch ||'"."'|| nametablegeom ||'" LEFT JOIN "'|| esch ||'"."'|| tematic ||'" ON concat( "'|| nametablegeom ||'"."'|| nametablegeom_id ||'" )= concat( "'|| tematic ||'"."'|| tematic_id ||'" )';
	
	EXECUTE 'create unique index on "'|| esch ||'"."'|| namemv ||'" (id_srm)';
exception when others then 
EXECUTE 'CREATE MATERIALIZED VIEW  "'|| esch ||'"."'|| namemv ||'" AS select  row_number ()over() as id_srm, * from (SELECT '|| contenido||' From "'|| esch ||'"."'|| nametablegeom ||'" LEFT JOIN "'|| esch ||'"."'|| tematic ||'" ON concat( "'|| nametablegeom ||'"."'|| nametablegeom_id ||'" )= concat( "'|| tematic ||'"."'|| tematic_id ||'" ))t';
		
	EXECUTE 'create unique index on "'|| esch ||'"."'|| namemv ||'" (id_srm)';
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__create_leftjoin_mv(
	esch text,
	namemv text,
	nametablegeom text,
	nametablegeom_id text,
	tematic text,
	tematic_id text,
	contenido text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: crea una vista materializada desde un innerjoin, nametablegeom_id (nombre de la columna de la tabla geométrica), tematic_id (nombre de la columna de la tabla temática) */
		EXECUTE 'CREATE MATERIALIZED VIEW  "'|| esch ||'"."'|| namemv ||'" AS select a.*
FRom "'|| esch ||'"."'|| nametablegeom ||'"  as B
     INNER JOIN (SELECT '|| contenido||',COALESCE(similarity ("'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text,"'|| tematic ||'"."'|| tematic_id ||'"::text),0)as similarity_index 
	From "'|| esch ||'"."'|| nametablegeom ||'"  LEFT JOIN "'|| esch ||'"."'|| tematic ||'" 
	ON  "'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text % "'|| tematic ||'"."'|| tematic_id ||'"::text)A
     ON A."'|| nametablegeom_id ||'" = B."'|| nametablegeom_id ||'"
    INNER JOIN ( 
          select A."'|| nametablegeom_id ||'",MAX(A.similarity)as expertrank
          from (SELECT '|| contenido||',COALESCE(similarity ("'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text,"'|| tematic ||'"."'|| tematic_id ||'"::text),0) as similarity 
	From "'|| esch ||'"."'|| nametablegeom ||'"  LEFT JOIN "'|| esch ||'"."'|| tematic ||'" 
	ON  "'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text % "'|| tematic ||'"."'|| tematic_id ||'"::text)A 
          group by A."'|| nametablegeom_id ||'"
     ) as NewA 
    ON a."'|| nametablegeom_id ||'" = NewA."'|| nametablegeom_id ||'" 
       AND a.similarity_index = NewA.expertrank;';
	   EXECUTE 'create unique index on "'|| esch ||'"."'|| namemv ||'" (id_srm)';
exception when others then 
EXECUTE 'CREATE MATERIALIZED VIEW  "'|| esch ||'"."'|| namemv ||'" AS select row_number ()over() as id_srm,* from (select a.*
FRom "'|| esch ||'"."'|| nametablegeom ||'"  as B
     INNER JOIN (SELECT '|| contenido||',COALESCE(similarity ("'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text,"'|| tematic ||'"."'|| tematic_id ||'"::text),0)as similarity_index 
	From "'|| esch ||'"."'|| nametablegeom ||'"  LEFT JOIN "'|| esch ||'"."'|| tematic ||'" 
	ON  "'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text % "'|| tematic ||'"."'|| tematic_id ||'"::text)A
     ON A."'|| nametablegeom_id ||'" = B."'|| nametablegeom_id ||'"
    INNER JOIN ( 
          select A."'|| nametablegeom_id ||'",MAX(A.similarity)as expertrank
          from (SELECT '|| contenido||',COALESCE(similarity ("'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text,"'|| tematic ||'"."'|| tematic_id ||'"::text),0) as similarity 
	From "'|| esch ||'"."'|| nametablegeom ||'"  LEFT JOIN "'|| esch ||'"."'|| tematic ||'" 
	ON  "'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text % "'|| tematic ||'"."'|| tematic_id ||'"::text)A 
          group by A."'|| nametablegeom_id ||'"
     ) as NewA 
    ON a."'|| nametablegeom_id ||'" = NewA."'|| nametablegeom_id ||'" 
       AND a.similarity_index = NewA.expertrank)t;';
	   EXECUTE 'create unique index on "'|| esch ||'"."'|| namemv ||'" (id_srm)';
END;
$BODY$;

	


CREATE OR REPLACE FUNCTION funciones.__create_leftjoin_vw(
	esch text,
	namemv text,
	nametablegeom text,
	nametablegeom_id text,
	tematic text,
	tematic_id text,
	contenido text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: crea una vista desde un leftjoin, nametablegeom_id (nombre de la columna de la tabla geométrica), tematic_id (nombre de la columna de la tabla temática) */
	EXECUTE 'CREATE VIEW  "'|| esch ||'"."'|| namemv ||'" AS select a.*
FRom "'|| esch ||'"."'|| nametablegeom ||'"  as B
     INNER JOIN (SELECT '|| contenido||',COALESCE(similarity ("'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text,"'|| tematic ||'"."'|| tematic_id ||'"::text),0)as similarity_index 
	From "'|| esch ||'"."'|| nametablegeom ||'"  LEFT JOIN "'|| esch ||'"."'|| tematic ||'" 
	ON  "'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text % "'|| tematic ||'"."'|| tematic_id ||'"::text)A
     ON A."'|| nametablegeom_id ||'" = B."'|| nametablegeom_id ||'"
    INNER JOIN ( 
          select A."'|| nametablegeom_id ||'",MAX(A.similarity)as expertrank
          from (SELECT '|| contenido||',COALESCE(similarity ("'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text,"'|| tematic ||'"."'|| tematic_id ||'"::text),0) as similarity 
	From "'|| esch ||'"."'|| nametablegeom ||'"  LEFT JOIN "'|| esch ||'"."'|| tematic ||'" 
	ON  "'|| nametablegeom ||'"."'|| nametablegeom_id ||'"::text % "'|| tematic ||'"."'|| tematic_id ||'"::text)A 
          group by A."'|| nametablegeom_id ||'"
     ) as NewA 
    ON a."'|| nametablegeom_id ||'" = NewA."'|| nametablegeom_id ||'" 
       AND a.similarity_index = NewA.expertrank;';
	   END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__create_mv(
	esch text,
	nameview text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: crea una vista materializada */
	EXECUTE 'CREATE materialized VIEW "'|| esch ||'"."'|| nameview ||'" AS SELECT * FROM "'|| esch ||'"."'|| nametable||'"';
	EXECUTE 'create unique index on "'|| esch ||'"."'|| nameview ||'" (fid)';
END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.__create_view(
	esch text,
	nameview text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: crea una vista */
	EXECUTE 'CREATE  VIEW "'|| esch ||'"."'|| nameview ||'" AS SELECT * FROM "'|| esch ||'"."'|| nametable||'"';
END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.__create_mv_contain(
	esch text,
	nameview text,
	nametable text,
	contenido text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: crea una vista materializada, contenido: la selección en bruto de los nombres de las columnas que se quieren llevar a la vista */
	EXECUTE 'CREATE materialized VIEW "'|| esch ||'"."'|| nameview ||'" AS SELECT "'|| contenido||'" FROM "'|| esch ||'"."'|| nametable||'"';
	EXECUTE 'create unique index on "'|| esch ||'"."'|| nameview ||'" (fid)';
END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.__create_view_contain(
	esch text,
	nameview text,
	nametable text,
	contenido text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: crea una vista, contenido: la selección en bruto de los nombres de las columnas que se quieren llevar a la vista */
	EXECUTE 'CREATE VIEW "'|| esch ||'"."'|| nameview ||'" AS SELECT "'|| contenido||'" FROM "'|| esch ||'"."'|| nametable||'"';
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__create_schema(
	nombre_usuario character varying)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: crea un esquema, nombre_usuario (nombre del esquema) */
	EXECUTE 'CREATE SCHEMA "'|| nombre_usuario ||'"';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__create_user(
	nombre_usuario character varying,
	pw character varying)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: crea un usuario pw: [REDACTED] */
	EXECUTE 'CREATE SCHEMA "'|| nombre_usuario ||'"';
	EXECUTE 'CREATE user "'|| nombre_usuario ||'" LOGIN
  NOSUPERUSER
  INHERIT
  NOCREATEDB
  NOCREATEROLE
  NOREPLICATION
  CONNECTION LIMIT -1
  PASSWORD ''' || pw ||'''';
  EXECUTE 'GRANT ALL ON SCHEMA "'|| nombre_usuario ||'" TO postgres';
  EXECUTE 'GRANT ALL ON SCHEMA "'|| nombre_usuario ||'" TO "'|| nombre_usuario ||'"';
  EXECUTE 'ALTER USER "'|| nombre_usuario ||'" SET search_path TO "' || nombre_usuario ||'"';
  EXECUTE 'ALTER ROLE "'|| nombre_usuario ||'" IN DATABASE '||current_database()||' SET search_path TO "'|| nombre_usuario ||'"';
  EXECUTE 'GRANT SELECT ON ALL TABLES IN SCHEMA public TO "' || nombre_usuario ||'"';
  EXECUTE 'GRANT all privileges ON ALL TABLES IN SCHEMA "'|| nombre_usuario ||'" TO "'|| nombre_usuario ||'"';
  
END;
$BODY$;








CREATE OR REPLACE FUNCTION funciones.__create_wrapper_csv(
	ser text,
	exc text,
	esch text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
       /*Descripcion: wrapper local a archivos csv sin limite, exc:direccion del archivo*/
		EXECUTE 'CREATE SERVER aserpost FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''' || exc || ''', format ''CSV'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all FROM SERVER "'|| ser ||'" INTO "'|| esch||'"' ;
		EXECUTE 'ALTER SERVER aserpost RENAME TO "'|| ser ||'"';
		
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__create_wrapper_csv(
	ser text,
	exc text,
	name_tables character varying,
	esch text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*Descripcion: wrapper local a archivos csv con limite de tablas, exc:direccion del archivo, name_tables: el nombre de los archivos a limitar*/
		EXECUTE 'CREATE SERVER aserpost FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''' || exc || ''', format ''CSV'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all limit to ("'|| name_tables ||'") FROM SERVER ' || ser || ' INTO "' || esch||'"';
		EXECUTE 'ALTER SERVER aserpost RENAME TO "'|| ser ||'"';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__create_wrapper_excel(
	ser text,
	exc text,
	names_tables character varying,
	tipo text,
	esch text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*Descripcion: wrapper local a archivos excel con limite de tablas, exc:direccion del archivo con el .xls o .xlsx, 
		name_tables: el nombre de los archivos a limitar en el caso del excell el nombre de las hojas, tipo: XLS o XLSX*/
		EXECUTE 'CREATE SERVER aserpost FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''' || exc || ''', format ''' || tipo || ''', config_options ''OGR_XLSX_HEADERS=FORCE'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all LIMIT TO ("'|| names_tables ||'")FROM SERVER '|| ser ||' INTO "'|| esch||'"' ;
		EXECUTE 'ALTER SERVER aserpost RENAME TO "'|| ser ||'"';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__create_wrapper_excel(
	ser text,
	exc text,
	tipo text,
	esch text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*Descripcion: wrapper local a archivos excel sin limite de tablas, exc:direccion del archivo con el .xls o .xlsx, tipo: XLS o XLSX*/
		EXECUTE 'CREATE SERVER aserpost FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''' || exc || ''', format ''' || tipo || ''', config_options ''OGR_XLSX_HEADERS=FORCE'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all FROM SERVER ' || ser || ' INTO "'|| esch||'"';
		EXECUTE 'ALTER SERVER aserpost RENAME TO "'|| ser ||'"';		
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__create_wrapper_geopackage(
	ser text,
	exc text,
	esch text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
       /*Descripcion: wrapper local a archivos geopackage sin limite, exc:direccion del archivo acabado con nombre archivo y .gpkg*/
		EXECUTE 'CREATE SERVER aserpost FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''' || exc || ''', format ''GPKG'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all FROM SERVER ' || ser || ' INTO "'|| esch ||'"';
		EXECUTE 'ALTER SERVER aserpost RENAME TO "'|| ser ||'"';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__create_wrapper_host(
	ser text,
	host text,
	puerto integer,
	dbase text,
	usr text,
	pass character varying,
	esch1 text,
	esch2 text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		   /*Descripcion: wrapper a otro postgres, usr: usuario del otro postgres, pass: password del otro postgres, 
		   esch1:el esquema que se quiere importar, esch2: el esquema propio*/ 
			
		EXECUTE 'CREATE SERVER aserpost FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host ''' || host || ''', port ''' || puerto || ''', dbname ''' || dbase || ''')';
		EXECUTE 'CREATE USER MAPPING FOR "'|| dbase ||'" SERVER '|| ser ||' OPTIONS ("user" ''' || usr || ''', password ''' || pass || ''')';
		EXECUTE 'IMPORT FOREIGN SCHEMA "'|| esch1 ||'" FROM SERVER '|| ser ||' INTO "'|| esch2||'"' ;
		EXECUTE 'ALTER SERVER aserpost RENAME TO "'|| ser ||'"';
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__create_wrapper_host(
	ser text,
	host text,
	puerto integer,
	dbase text,
	usr text,
	pass character varying,
	esch1 text,
	esch2 text,
	name_tables character varying)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		   /*Descripcion: wrapper a otro postgres con limitacion de tablas , usr: usuario del otro postgres, pass: password del otro postgres, 
		   esch1:el esquema que se quiere importar, esch2: el esquema propio
		   name_tables: el nombre de los archivos a limitar*/ 
		EXECUTE 'CREATE SERVER aserpost FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host ''' || host || ''', port ''' || puerto || ''', dbname ''' || dbase || ''')';
		EXECUTE 'CREATE USER MAPPING FOR "'|| dbase ||'" SERVER ' || ser || ' OPTIONS ("user" ''' || usr || ''', password ''' || pass || ''')';
		EXECUTE 'IMPORT FOREIGN SCHEMA "'|| esch1 ||'" LIMIT TO ("'|| name_tables ||'") FROM SERVER '|| ser ||' INTO "'|| esch2||'"';
		EXECUTE 'ALTER SERVER aserpost RENAME TO "'|| ser ||'"';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__create_wrapper_kml(
	ser text,
	exc text,
	esch text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*Descripcion: wrapper local a archivos kml sin limite de tablas, exc:direccion del archivo*/
		EXECUTE 'CREATE SERVER aserpost FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''' || exc || ''', format ''KML'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all FROM SERVER '|| ser ||' INTO "'|| esch||'"';
		EXECUTE 'ALTER SERVER aserpost RENAME TO "'|| ser ||'"';
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__create_wrapper_mdb(
	ser text,
	exc text,
	esch text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*Descripcion: wrapper local a archivos MDB sin limite de tablas, exc:direccion del archivo*/
		EXECUTE 'CREATE SERVER aserpost FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''' || exc || ''', format ''Geomedia'', config_options ''OGR_SKIP=ODBC GEOMEDIA_DRIVER_TEMPLATE="DRIVER=Microsoft Access Driver (*.mdb, *.accdb);DBQ=%s"'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all FROM SERVER ' || ser || ' INTO "'|| esch ||'"';
		EXECUTE 'ALTER SERVER aserpost RENAME TO "'|| ser ||'"';
	
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__create_wrapper_mdb(
	ser text,
	exc text,
	names_tables character varying,
	esch text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*Descripcion: wrapper local a archivos MDB con limite de tablas, exc:direccion del archivo, name_tables: el nombre de los archivos a limitar*/
		EXECUTE 'CREATE SERVER aserpost FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''' || exc || ''', format ''Geomedia'', config_options ''OGR_SKIP=ODBC GEOMEDIA_DRIVER_TEMPLATE="DRIVER=Microsoft Access Driver (*.mdb, *.accdb);DBQ=%s"'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all LIMIT TO ("'|| names_tables ||'")FROM SERVER ' || ser || ' INTO "'|| esch ||'"';
		EXECUTE 'ALTER SERVER aserpost RENAME TO "'|| ser ||'"';
	
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__create_wrapper_shp(
	ser text,
	exc text,
	esch text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*Descripcion: wrapper local a archivos shp sin limite de tablas, exc:direccion del archivo*/
		EXECUTE 'CREATE SERVER aserpost FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''' || exc || ''', format ''ESRI Shapefile'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all FROM SERVER ' || ser || ' INTO "'|| esch ||'"';
		EXECUTE 'ALTER SERVER aserpost RENAME TO "'|| ser ||'"';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__create_wrapper_shp(
	ser text,
	exc text,
	name_tables character varying,
	esch text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*Descripcion: wrapper local a archivos shp con limite de tablas, exc:direccion del archivo, name_tables: el nombre de los archivos a limitar*/
		EXECUTE 'CREATE SERVER aserpost FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''' || exc || ''', format ''ESRI Shapefile'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all limit to ("'|| name_tables ||'") FROM SERVER ' || ser || ' INTO "'|| esch ||'"';
		EXECUTE 'ALTER SERVER aserpost RENAME TO "'|| ser ||'"';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__drop_mv(
	esch text,
	name_tables text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: eliminar vista materializada en cascada*/
	EXECUTE 'DROP materialized VIEW if exists "'|| esch ||'"."'|| name_tables ||'" cascade';
END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.__drop_vw(
	esch text,
	name_tables text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: eliminar vista materializada en cascada*/
	EXECUTE 'DROP VIEW if exists "'|| esch ||'"."'|| name_tables ||'" cascade';
END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.__drop_esch(
	esch text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: eliminar vista materializada en cascada*/
	EXECUTE 'DROP schema if exists "'|| esch ||'" cascade';
END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.__drop_server(
	ser text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: eliminar servidor en cascada*/
	EXECUTE 'DROP SERVER if exists "'|| ser ||'" cascade';
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__drop_user(
	nombre_usuario character varying)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: eliminar usuario*/
  EXECUTE 'drop schema "'|| nombre_usuario ||'" cascade';
  EXECUTE 'REVOKE  GRANT OPTION FOR ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM "'|| nombre_usuario ||'" CASCADE';
  EXECUTE 'REVOKE GRANT OPTION FOR  ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM "'|| nombre_usuario ||'" CASCADE';
  EXECUTE 'REVOKE select ON all tables in schema public FROM "'|| nombre_usuario ||'"';
  EXECUTE 'drop role "'|| nombre_usuario ||'"';
  
END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.__external_wrapper_csv(
	ser text,
	exc text,
	esch text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*Descripcion: wrapper extertno a archivos csv sin limite de tablas, exc:direccion del archivo*/
		EXECUTE 'CREATE SERVER ageojson FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''' || exc || ''', format ''CSV'', config_options ''GDAL_HTTP_UNSAFESSL=YES'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all FROM SERVER ageojson INTO "'|| esch ||'"';
		EXECUTE 'ALTER SERVER ageojson RENAME TO "'|| ser ||'"';

END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.__external_wrapper_csv_limit(
	ser text,
	exc text,
	esch text,
	name_tables character varying,
	new_name character varying)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
       /*Descripcion: wrapper extertno a archivos csv con limite de tablas, exc:direccion del archivo, name_tables: el nombre de los archivos a limitar, new_name:nuevo nombre de la tabla*/
		EXECUTE 'CREATE SERVER acsv FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''/vsicurl_streaming/' || exc || ''', format ''CSV'',config_options ''GDAL_HTTP_UNSAFESSL=YES'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all limit to ('|| name_tables ||')  FROM SERVER acsv INTO "'|| esch ||'"';
		EXECUTE 'ALTER FOREIGN TABLE "'|| esch ||'".'|| name_tables ||' RENAME TO "'|| new_name ||'"';
		EXECUTE 'ALTER SERVER acsv RENAME TO "'|| ser ||'"';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__external_wrapper_excel(
	ser text,
	exc text,
	esch text,
	tipo text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*Descripcion: wrapper externo a archivos excel sin limite de tablas, exc:direccion del archivo con el .xls o .xlsx, tipo: XLS o XLSX*/
		EXECUTE 'CREATE SERVER axcl FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''/vsicurl_streaming/' || exc || ''', format ''' || tipo || ''',open_options ''OGR_XLSX_HEADERS=FORCE'', config_options ''GDAL_HTTP_UNSAFESSL=YES'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all FROM SERVER axcl INTO "'|| esch ||'"';
		EXECUTE 'ALTER SERVER axcl RENAME TO "'|| ser ||'"';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__external_wrapper_excel_limit(
	ser text,
	exc text,
	esch text,
	tipo text,
	name_tables character varying,
	new_name character varying)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*Descripcion: wrapper externo a archivos excel con limite de tablas, exc:direccion del archivo con el .xls o .xlsx, tipo: XLS o XLSX
		name_tables: el nombre de los archivos a limitar, new_name:nuevo nombre de la tabla*/
		EXECUTE 'CREATE SERVER axcl FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''/vsicurl_streaming/' || exc || ''', format ''' || tipo || ''',open_options ''OGR_XLSX_HEADERS=FORCE'', config_options ''GDAL_HTTP_UNSAFESSL=YES'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all limit to ('|| name_tables ||')  FROM SERVER axcl INTO "'|| esch ||'"';
		EXECUTE 'ALTER FOREIGN TABLE "'|| esch ||'".'|| name_tables ||' RENAME TO "'|| new_name ||'"';
		EXECUTE 'ALTER SERVER axcl RENAME TO "'|| ser ||'"';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__external_wrapper_geojson(
	ser text,
	exc text,
	esch text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*Descripcion: wrapper extertno a archivos geojson sin limite de tablas, exc:direccion del archivo*/
		EXECUTE 'CREATE SERVER ageojson FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''' || exc || ''', format ''GeoJSON'', config_options ''GDAL_HTTP_UNSAFESSL=YES'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all FROM SERVER ageojson INTO "'|| esch ||'"';
		EXECUTE 'ALTER SERVER ageojson RENAME TO "'|| ser ||'"';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__external_wrapper_geojson_limit(
	ser text,
	exc text,
	esch text,
	name_tables character varying,
	new_name character varying)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*Descripcion: wrapper extertno a archivos geojson con limite de tablas, exc:direccion del archivo, name_tables: el nombre de los archivos a limitar, new_name:nuevo nombre de la tabla*/
		EXECUTE 'CREATE SERVER ageojson FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''' || exc || ''', format ''GeoJSON'', config_options ''GDAL_HTTP_UNSAFESSL=YES'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all limit to ('|| name_tables ||')  FROM SERVER ageojson INTO "'|| esch ||'"';
		EXECUTE 'ALTER FOREIGN TABLE "'|| esch ||'".'|| name_tables ||' RENAME TO "'|| new_name ||'"';
		EXECUTE 'ALTER SERVER ageojson RENAME TO "'|| ser ||'"';
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__external_wrapper_geopackage(
	ser text,
	exc text,
	esch text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*Descripcion: wrapper extertno a archivos geopackage sin limite de tablas, exc:direccion del archivo con nombre archivo y .gpkg*/
		EXECUTE 'CREATE SERVER ageopackage FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''/vsicurl_streaming/' || exc || ''', format ''GPKG'',config_options ''GDAL_HTTP_UNSAFESSL=YES'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all  FROM SERVER ageopackage INTO "'|| esch ||'"';
		EXECUTE 'ALTER SERVER ageopackage RENAME TO "'|| ser ||'"';
		
END;
$BODY$;



CREATE OR REPLACE FUNCTION funciones.__external_wrapper_geopackage_limit(
	ser text,
	exc text,
	esch text,
	name_tables character varying,
	new_name character varying)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
    
AS $BODY$
BEGIN
		/*Descripcion: wrapper extertno a archivos geopackage con limite de tablas, exc:direccion del archivo con nombre archivo y .gpkg, name_tables: el nombre de los archivos a limitar, new_name:nuevo nombre de la tabla*/
		EXECUTE 'CREATE SERVER ageopackage FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''/vsicurl_streaming/' || exc || ''', format ''GPKG'',config_options ''GDAL_HTTP_UNSAFESSL=YES'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all limit to ("'|| name_tables ||'")  FROM SERVER ageopackage INTO "'|| esch ||'"';
		EXECUTE 'ALTER FOREIGN TABLE "'|| esch ||'"."'|| name_tables ||'" RENAME TO "'|| new_name ||'"';
		EXECUTE 'ALTER SERVER ageopackage RENAME TO "'|| ser ||'"';
		
END;
$BODY$;



CREATE OR REPLACE FUNCTION funciones.__external_wrapper_gml_limit(
	ser text,
	exc text,
	esch text,
	name_tables character varying,
	new_name character varying)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
    
AS $BODY$
BEGIN
		/*Descripcion: wrapper extertno a archivos geopackage con limite de tablas, exc:direccion del archivo con nombre archivo y .gml, name_tables: el nombre de los archivos a limitar, new_name:nuevo nombre de la tabla*/
		EXECUTE 'CREATE SERVER agml FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''/vsicurl_streaming/' || exc || ''', format ''GML'',config_options ''GDAL_HTTP_UNSAFESSL=YES'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all limit to ("'|| name_tables ||'")  FROM SERVER agml INTO "'|| esch ||'"';
		EXECUTE 'ALTER FOREIGN TABLE "'|| esch ||'"."'|| name_tables ||'" RENAME TO "'|| new_name ||'"';
		EXECUTE 'ALTER SERVER agml RENAME TO "'|| ser ||'"';
		
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__external_wrapper_kml(
	ser text,
	exc text,
	esch text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*Descripcion: wrapper extertno a archivos kml sin limite de tablas, exc:direccion del archivo*/
		EXECUTE 'CREATE SERVER akml FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''/vsicurl_streaming/' || exc || ''', format ''KML'',config_options ''GDAL_HTTP_UNSAFESSL=YES'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all  FROM SERVER akml INTO "'|| esch ||'"';
		EXECUTE 'ALTER SERVER akml RENAME TO "'|| ser ||'"';
		
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__external_wrapper_kml(
	ser text,
	exc text,
	esch text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*Descripcion: wrapper extertno a archivos kml sin limite de tablas, exc:direccion del archivo*/
		EXECUTE 'CREATE SERVER akml FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''/vsicurl_streaming/' || exc || ''', format ''KML'',config_options ''GDAL_HTTP_UNSAFESSL=YES'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all  FROM SERVER akml INTO "'|| esch ||'"';
		EXECUTE 'ALTER SERVER akml RENAME TO "'|| ser ||'"';
		
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__external_wrapper_kml_limit(
	ser text,
	exc text,
	esch text,
	name_tables character varying,
	new_name character varying)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*Descripcion: wrapper extertno a archivos kml con limite de tablas, exc:direccion del archivo, name_tables: el nombre de los archivos a limitar, new_name:nuevo nombre de la tabla*/
		EXECUTE 'CREATE SERVER akml FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''/vsicurl_streaming/' || exc || ''', format ''KML'',config_options ''GDAL_HTTP_UNSAFESSL=YES'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all limit to ('|| name_tables ||')  FROM SERVER akml INTO "'|| esch ||'"';
		EXECUTE 'ALTER FOREIGN TABLE "'|| esch ||'".'|| name_tables ||' RENAME TO "'|| new_name ||'"';
		EXECUTE 'ALTER SERVER akml RENAME TO "'|| ser ||'"';
		
END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.__external_wrapper_postgresql(
	ser text,
	host text,
	puerto integer,
	dbase_user text,
	usr_server text,
	usr_user text,
	pass_user text,
	esch_user text,
	esch_server text,
	name_tables character varying,
	new_name character varying)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*Descripcion: wrapper a otro postgres con limitacion de tablas , usr_user: usuario del otro postgres, pass_user: password del otro postgres, 
		   esch_user:el esquema que se quiere importar, esch_server: el esquema propio
		   name_tables: el nombre de los archivos a limitar*/ 
		EXECUTE 'CREATE SERVER a'|| ser ||' FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host ''' || host || ''', port ''' || puerto || ''', dbname ''' || dbase_user || ''')';
		EXECUTE 'CREATE USER MAPPING FOR "'|| usr_server ||'" SERVER a'|| ser ||' OPTIONS ("user" ''' || usr_user || ''', password ''' || pass_user || ''')';
		EXECUTE 'IMPORT FOREIGN SCHEMA "'|| esch_user || '" LIMIT TO ("'|| name_tables ||'") FROM SERVER a'|| ser ||' INTO "'|| esch_server ||'"';
		EXECUTE 'ALTER FOREIGN TABLE "'|| esch_server ||'"."'|| name_tables ||'" RENAME TO "'|| new_name ||'"';
		EXECUTE 'ALTER SERVER a'|| ser ||' RENAME TO "'|| ser ||'"';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__external_wrapper_postgresql_no_limit(
	ser text,
	host text,
	puerto integer,
	dbase_user text,
	usr_server text,
	usr_user text,
	pass_user text,
	esch_user text,
	esch_server text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ BEGIN
		/*Descripcion: wrapper a otro postgres sin limitacion de tablas , usr_user: usuario del otro postgres, pass_user: password del otro postgres, 
		   esch_user:el esquema que se quiere importar, esch_server: el esquema propio*/ 
		EXECUTE 'CREATE SERVER a'|| ser ||' FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host ''' || host || ''', port ''' || puerto || ''', dbname ''' || dbase_user || ''')';
		EXECUTE 'CREATE USER MAPPING FOR "'|| usr_server ||'" SERVER a'|| ser ||' OPTIONS ("user" ''' || usr_user || ''', password ''' || pass_user || ''')';
		EXECUTE 'IMPORT FOREIGN SCHEMA "'|| esch_user || '" FROM SERVER a'|| ser ||' INTO "'|| esch_server ||'"';
		EXECUTE 'ALTER SERVER a'|| ser ||' RENAME TO "'|| ser ||'"';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__external_wrapper_shp_limit(
	ser text,
	exc text,
	esch text,
	name_tables character varying,
	new_name character varying)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*Descripcion: wrapper extertno a archivos shp con limite de tablas, exc:direccion del archivo, name_tables: el nombre de los archivos a limitar, new_name:nuevo nombre de la tabla*/
		EXECUTE 'CREATE SERVER ashp FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''/vsicurl/'|| exc ||''', format ''ESRI Shapefile'',config_options ''GDAL_HTTP_UNSAFESSL=YES'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all limit to ('|| name_tables ||')  FROM SERVER ashp INTO "'|| esch ||'"';
		EXECUTE 'ALTER FOREIGN TABLE "'|| esch ||'".'|| name_tables ||' RENAME TO "'|| new_name ||'"';
		EXECUTE 'ALTER SERVER ashp RENAME TO "'|| ser ||'"';

END;
$BODY$;



CREATE OR REPLACE FUNCTION funciones.__external_wrapper_shp(
	ser text,
	exc text,
	esch text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*Descripcion: wrapper extertno a archivos shp sin limite de tablas, exc:direccion del archivo*/
		EXECUTE 'CREATE SERVER ashp FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''/vsicurl/' || exc || ''', format ''ESRI Shapefile'',config_options ''GDAL_HTTP_UNSAFESSL=YES'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all FROM SERVER ashp INTO "'|| esch ||'"';
		EXECUTE 'ALTER SERVER ashp RENAME TO "'|| ser ||'"';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__external_wrapper_zip(
	ser text,
	exc text,
	esch text,
	new_name character varying)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$	declare coordx character varying
	;
 BEGIN
		/*Descripcion: wrapper extertno a archivos zip que tienen un archivo, exc:direccion del archivo, new_name:nuevo nombre de la tabla, coordx:extrae el nombre de la tabla por si no coincide con el zip*/
		EXECUTE 'CREATE SERVER zip FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''/vsizip//vsicurl_streaming/'|| exc ||''', config_options ''GDAL_HTTP_UNSAFESSL=YES'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all FROM SERVER zip INTO "'|| esch ||'"';
		select foreign_table_name into coordx FROM information_schema.foreign_tables where foreign_server_name = 'zip';
		EXECUTE 'ALTER FOREIGN TABLE "'|| esch ||'"."'|| coordx ||'" RENAME TO "'|| new_name ||'"';
		EXECUTE 'ALTER SERVER zip RENAME TO "'|| ser ||'"';
		

END;  
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__external_wrapper_zip_varios(
	ser text,
	exc text,
	esch text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$	declare coordx character varying
	;
 BEGIN
		/*Descripcion: wrapper extertno a archivos zip que tienen muchas archivos, exc:direccion del archivo*/
		EXECUTE 'CREATE SERVER zip FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''/vsizip//vsicurl/'|| exc ||''', config_options ''GDAL_HTTP_UNSAFESSL=YES'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all FROM SERVER zip INTO "'|| esch ||'"';
		EXECUTE 'ALTER SERVER zip RENAME TO "'|| ser ||'"';
		
		

END;  
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__ftp_wrapper_csv(
	ser text,
	exc text,
	esch text,
	name_tables character varying,
	new_name character varying)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*sin uso; Descripcion: wrapper extertno a archivos shp con limite de tablas, exc:direccion del archivo, name_tables: el nombre de los archivos a limitar, new_name:nuevo nombre de la tabla*/
		EXECUTE 'CREATE SERVER acsv FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''/vsicurl_streaming/' || exc || ''', format ''CSV'',config_options ''GDAL_HTTP_UNSAFESSL=YES'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all limit to ("'|| name_tables ||'")  FROM SERVER acsv INTO "'|| esch ||'"';
		EXECUTE 'ALTER FOREIGN TABLE "'|| esch ||'"."'|| name_tables ||'" RENAME TO "'|| new_name ||'"';
		EXECUTE 'ALTER SERVER acsv RENAME TO "'|| ser ||'"';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__ftp_wrapper_excel(
	ser text,
	exc text,
	esch text,
	tipo text,
	name_tables character varying,
	new_name character varying)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*sin uso; Descripcion: wrapper externo a archivos excel con limite de tablas, exc:direccion del archivo con el .xls o .xlsx, tipo: XLS o XLSX
		name_tables: el nombre de los archivos a limitar, new_name:nuevo nombre de la tabla*/
		EXECUTE 'CREATE SERVER axcl FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''/vsicurl_streaming/' || exc || ''', format ''' || tipo || ''',open_options ''OGR_XLSX_HEADERS=FORCE'', config_options ''GDAL_HTTP_UNSAFESSL=YES'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all limit to ('|| name_tables ||')  FROM SERVER axcl INTO "'|| esch ||'"';
		EXECUTE 'ALTER FOREIGN TABLE "'|| esch ||'".'|| name_tables ||' RENAME TO "'|| new_name ||'"';
		EXECUTE 'ALTER SERVER axcl RENAME TO "'|| ser ||'"';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__ftp_wrapper_kml_limit(
	ser text,
	exc text,
	esch text,
	name_tables character varying,
	new_name character varying)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*sin uso; Descripcion: wrapper extertno a archivos kml con limite de tablas, exc:direccion del archivo, name_tables: el nombre de los archivos a limitar, new_name:nuevo nombre de la tabla*/
		EXECUTE 'CREATE SERVER akml FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''/vsicurl_streaming/' || exc || ''', format ''KML'',config_options ''GDAL_HTTP_UNSAFESSL=YES'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all limit to ('|| name_tables ||')  FROM SERVER akml INTO "'|| esch ||'"';
		EXECUTE 'ALTER FOREIGN TABLE "'|| esch ||'".'|| name_tables ||' RENAME TO "'|| new_name ||'"';
		EXECUTE 'ALTER SERVER akml RENAME TO "'|| ser ||'"';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__ftp_wrapper_shp(
	ser text,
	exc text,
	esch text,
	name_tables character varying,
	new_name character varying)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
		/*sin uso; Descripcion: wrapper extertno a archivos shp con limite de tablas, exc:direccion del archivo, name_tables: el nombre de los archivos a limitar, new_name:nuevo nombre de la tabla*/
		EXECUTE 'CREATE SERVER ashp FOREIGN DATA WRAPPER ogr_fdw OPTIONS (datasource ''/vsicurl_streaming/' || exc || ''', format ''ESRI Shapefile'',config_options ''GDAL_HTTP_UNSAFESSL=YES'')';
		EXECUTE 'IMPORT FOREIGN SCHEMA ogr_all limit to ("'|| name_tables ||'")  FROM SERVER ashp INTO "'|| esch ||'"';
		EXECUTE 'ALTER FOREIGN TABLE "'|| esch ||'"."'|| name_tables ||'" RENAME TO "'|| new_name ||'"';
		EXECUTE 'ALTER SERVER ashp RENAME TO "'|| ser ||'"';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.__list_schemas(
	)
    RETURNS TABLE(schema_name_0 character varying) 
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
    ROWS 1000
AS $BODY$ BEGIN

	RETURN QUERY 

select schema_name::character varying
from information_schema.schemata where not schema_name  like 'pg%';
END;
$BODY$;



CREATE OR REPLACE FUNCTION funciones.__list_tbl_view_matview(
	_schema text)
    RETURNS TABLE(nombre character varying, tipo character varying) 
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
    ROWS 1000
AS $BODY$ BEGIN

	RETURN query 

select * from (SELECT
            table_name::character varying as nombre,table_type as tipo
        FROM
            information_schema.tables
        WHERE
            table_schema = _schema
union all 
select matviewname::character varying as nombre, 'MATVIEW' as tipo 
from pg_matviews
where schemaname = _schema)t;
END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.alter_name_hidro2_vw(
	esch text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
BEGIN
	/*Descripcion:cambia el nombre de una vista pensado para las de la union */
	EXECUTE 'ALTER VIEW "'|| esch ||'"."paraunionhidro_'|| nametable ||'"
    RENAME TO "zvw_'|| nametable ||'";';

END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.alter_name_rail2_vw(
	esch text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ BEGIN
	/*Descripcion:cambia el nombre de una vista pensado para las de la union */
	EXECUTE 'ALTER VIEW "'|| esch ||'"."paraunionrail_'|| nametable ||'"
    RENAME TO "zvw_'|| nametable ||'";';

END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.alter_name_vw(
	esch text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ BEGIN
	/*Descripcion:cambia el nombre de una vista pensado para las de la union */
	EXECUTE 'ALTER VIEW "'|| esch ||'"."paraunion_'|| nametable ||'"
    RENAME TO "zvw_'|| nametable ||'";';

END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.calles_desde_edificios(
	esch text,
	tbl_entrada text,
	tbl_salida text,
	distancia_nucleo_urbano double precision,
	longitud_calles double precision,
	precison double precision)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
BEGIN

--concav zonificando los edificios
EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_valid";';
EXECUTE 'create table "'|| esch ||'"."'|| tbl_salida ||'_valid" as select st_collectionextract(st_makevalid(geom),3) as geom from "'|| esch ||'"."'|| tbl_entrada ||'";';
EXECUTE 'create index "'|| esch ||'_'|| tbl_salida ||'_valid" ON "'|| esch ||'"."'|| tbl_salida ||'_valid" USING GIST (geom);';

EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_edi_union";';
EXECUTE 'create table "'|| esch ||'"."'|| tbl_salida ||'_edi_union" as select  st_union(geom) as geom  from "'|| esch ||'"."'|| tbl_salida ||'_valid";';
EXECUTE 'create index "'|| esch ||'_'|| tbl_salida ||'_edi_union" ON "'|| esch ||'"."'|| tbl_salida ||'_edi_union" USING GIST (geom);';

EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_buff_valid";';
EXECUTE 'create table "'|| esch ||'"."'|| tbl_salida ||'_buff_valid" as select st_buffer(geom,'|| distancia_nucleo_urbano ||') as geom from "'|| esch ||'"."'|| tbl_salida ||'_valid";';
EXECUTE 'create index "'|| esch ||'_'|| tbl_salida ||'_buff_valid" ON "'|| esch ||'"."'|| tbl_salida ||'_buff_valid" USING GIST (geom);';

EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_buff_union";';
EXECUTE 'create table "'|| esch ||'"."'|| tbl_salida ||'_buff_union" as select  st_union(geom) as geom  from "'|| esch ||'"."'|| tbl_salida ||'_buff_valid";';
EXECUTE 'create index "'|| esch ||'_'|| tbl_salida ||'_buff_union" ON "'|| esch ||'"."'|| tbl_salida ||'_buff_union" USING GIST (geom);';

EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_edi_buff_dump";';
EXECUTE 'create table "'|| esch ||'"."'|| tbl_salida ||'_edi_buff_dump" as select row_number ()over() as id_zona,* from (select  (st_dump(geom)).geom from "'|| esch ||'"."'|| tbl_salida ||'_buff_union")t;';
EXECUTE 'create index "'|| esch ||'_'|| tbl_salida ||'_edi_buff_dump" ON "'|| esch ||'"."'|| tbl_salida ||'_edi_buff_dump" USING GIST (geom);';

EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_edi_zona";';
EXECUTE 'create table "'|| esch ||'"."'|| tbl_salida ||'_edi_zona" as select b.id_zona,a.* from "'|| esch ||'"."'|| tbl_salida ||'_valid" a , "'|| esch ||'"."'|| tbl_salida ||'_edi_buff_dump" b
where st_intersects(a.geom,b.geom);';
EXECUTE 'create index "'|| esch ||'_'|| tbl_salida ||'_edi_zona" ON "'|| esch ||'"."'|| tbl_salida ||'_edi_zona" USING GIST (geom);';

EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_edi_zona_uni";';
EXECUTE 'create table "'|| esch ||'"."'|| tbl_salida ||'_edi_zona_uni" as select st_union(geom) as geom ,id_zona from "'|| esch ||'"."'|| tbl_salida ||'_edi_zona" group by id_zona;';
EXECUTE 'create index "'|| esch ||'_'|| tbl_salida ||'_edi_zona_uni" ON "'|| esch ||'"."'|| tbl_salida ||'_edi_zona_uni" USING GIST (geom);';

EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_edi_zona_uni_concav";';
EXECUTE 'create table "'|| esch ||'"."'|| tbl_salida ||'_edi_zona_uni_concav" as select  ST_ConcaveHull(geom,0.4) as geom  from "'|| esch ||'"."'|| tbl_salida ||'_edi_zona_uni";';
EXECUTE 'create index "'|| esch ||'_'|| tbl_salida ||'_edi_zona_uni_concav" ON "'|| esch ||'"."'|| tbl_salida ||'_edi_zona_uni_concav" USING GIST (geom);';

EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_edi_zona_uni_concav_menos";';
EXECUTE 'create table "'|| esch ||'"."'|| tbl_salida ||'_edi_zona_uni_concav_menos" as select st_union (st_buffer(geom,-0.00004)) as geom from "'|| esch ||'"."'|| tbl_salida ||'_edi_zona_uni_concav";';
EXECUTE 'create index "'|| esch ||'_'|| tbl_salida ||'_edi_zona_uni_concav_menos" ON "'|| esch ||'"."'|| tbl_salida ||'_edi_zona_uni_concav_menos" USING GIST (geom);';

-- diferencia desde el concav zonas
EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_diferencia_zonas";';
EXECUTE 'create table "'|| esch ||'"."'|| tbl_salida ||'_diferencia_zonas" (like "'|| esch ||'"."'|| tbl_salida ||'_edi_zona_uni_concav_menos");';
EXECUTE 'alter table "'|| esch ||'"."'|| tbl_salida ||'_diferencia_zonas" add column geom_dif geometry (Geometry);';
EXECUTE 'create index '|| esch ||'_'|| tbl_salida ||'_diferencia_zonas_geom_dif_gidx on "'|| esch ||'"."'|| tbl_salida ||'_diferencia_zonas" using gist(geom_dif);';		

EXECUTE 'insert into "'|| esch ||'"."'|| tbl_salida ||'_diferencia_zonas"  
select a.*,(st_dump(st_difference(a.geom,b.geom))).geom
from "'|| esch ||'"."'|| tbl_salida ||'_edi_zona_uni_concav_menos" a, "'|| esch ||'"."'|| tbl_salida ||'_edi_union" b  
where st_intersects(a.geom,b.geom);';

EXECUTE 'insert into "'|| esch ||'"."'|| tbl_salida ||'_diferencia_zonas" 
select a.*,null from "'|| esch ||'"."'|| tbl_salida ||'_edi_zona_uni_concav_menos" a left join "'|| esch ||'"."'|| tbl_salida ||'_edi_union" b on st_intersects(a.geom,b.geom) where b.geom is null;';
					
EXECUTE 'update "'|| esch ||'"."'|| tbl_salida ||'_diferencia_zonas" set geom_dif = geom where geom_dif is null;';
EXECUTE 'update "'|| esch ||'"."'|| tbl_salida ||'_diferencia_zonas" set geom = geom_dif;';

EXECUTE 'alter table "'|| esch ||'"."'|| tbl_salida ||'_diferencia_zonas" drop column geom_dif;';

EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_segmentado";';
EXECUTE 'create table  "'|| esch ||'"."'|| tbl_salida ||'_segmentado" as select ST_Segmentize(geom,'|| precison ||') as geom 
from "'|| esch ||'"."'|| tbl_salida ||'_diferencia_zonas";';
EXECUTE 'create index "'|| esch ||'_'|| tbl_salida ||'_segmentado" ON "'|| esch ||'"."'|| tbl_salida ||'_segmentado" USING GIST (geom);';
EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_voronoy_lines";';
EXECUTE 'create table "'|| esch ||'"."'|| tbl_salida ||'_voronoy_lines"
as select row_number ()over() as id_zona,* from (select (st_dump(ST_VoronoiLines (geom))).geom as geom from "'|| esch ||'"."'|| tbl_salida ||'_segmentado")t;';
EXECUTE 'create index "'|| esch ||'_'|| tbl_salida ||'_voronoy_lines" ON "'|| esch ||'"."'|| tbl_salida ||'_voronoy_lines" USING GIST (geom);';

EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_voronoy_cortado";';
EXECUTE 'create table "'|| esch ||'"."'|| tbl_salida ||'_voronoy_cortado" as select id_zona,geom from (select b.*,id from (select a.*,a.id_zona as id from "'|| esch ||'"."'|| tbl_salida ||'_voronoy_lines" a,
(select (st_dump(geom)).geom from "'|| esch ||'"."'|| tbl_salida ||'_edi_zona_uni_concav_menos") b where st_intersects (a.geom,st_exteriorring(b.geom)))t
right join
(select * from "'|| esch ||'"."'|| tbl_salida ||'_voronoy_lines")b on ST_Equals (t.geom,b.geom))t where id is null;';
EXECUTE 'create index "'|| esch ||'_'|| tbl_salida ||'_voronoy_cortado" ON "'|| esch ||'"."'|| tbl_salida ||'_voronoy_cortado" USING GIST (geom);';

EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_caminos";';
EXECUTE 'create table "'|| esch ||'"."'|| tbl_salida ||'_caminos" as select * from (select st_length(geom) as distance,* from (select b.*,t.id from (select a.geom, a.id_zona as id from "'|| esch ||'"."'|| tbl_salida ||'_voronoy_cortado" a join
"'|| esch ||'"."'|| tbl_salida ||'_valid" b on st_intersects (a.geom,st_buffer(b.geom,0.000012576)))t right join
(select * from "'|| esch ||'"."'|| tbl_salida ||'_voronoy_cortado")b on ST_Equals (t.geom,b.geom))t where id is null)t where distance < '|| longitud_calles ||';';
EXECUTE 'create index "'|| esch ||'_'|| tbl_salida ||'_caminos" ON "'|| esch ||'"."'|| tbl_salida ||'_caminos" USING GIST (geom);';

EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'";';
EXECUTE 'create table "'|| esch ||'"."'|| tbl_salida ||'" as select a.* from "'|| esch ||'"."'|| tbl_salida ||'_caminos" a,
"'|| esch ||'"."'|| tbl_salida ||'_edi_zona_uni_concav_menos" b where st_intersects (a.geom,b.geom);';
EXECUTE 'create index "'|| esch ||'_'|| tbl_salida ||'" ON "'|| esch ||'"."'|| tbl_salida ||'" USING GIST (geom);';

EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_caminos_sueltos";';
EXECUTE 'create table "'|| esch ||'"."'|| tbl_salida ||'_caminos_sueltos" as select id1 as id,''Points without union'' as errores, point as geom from(select r1.geom as point, r1.id_zona as id1, r2.id_zona as id2
from (select (st_dumppoints(geom)).geom, id_zona from "'|| esch ||'"."'|| tbl_salida ||'") r1 
	  left join "'|| esch ||'"."'|| tbl_salida ||'" r2 
on r1.id_zona<>r2.id_zona and st_expand (r1.geom,1000) && r2.geom and st_distance (r1.geom,r2.geom) = 0)
as tabla where id2 is null;';
EXECUTE 'create index "'|| esch ||'_'|| tbl_salida ||'_caminos_sueltos" ON "'|| esch ||'"."'|| tbl_salida ||'_caminos_sueltos" USING GIST (geom);';

EXECUTE 'delete from "'|| esch ||'"."'|| tbl_salida ||'" 
USING "'|| esch ||'"."'|| tbl_salida ||'_caminos_sueltos" b
where id_zona = b.id;';
														 
EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_valid";';
EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_edi_union";';
EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_buff_valid";';
EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_buff_union";';
EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_edi_buff_dump";';
EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_edi_zona";';
EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_edi_zona_uni";';
EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_edi_zona_uni_concav";';
EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_edi_zona_uni_concav_menos";';
EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_diferencia_zonas";';
EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_segmentado";';
EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_voronoy_lines";';
EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_voronoy_cortado";';
EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_caminos";';
EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_salida ||'_caminos_sueltos";';

END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.cambiar_esquema_multiples_tablas(
	_schema_salida text,
	schema_entrada text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
    row     record;
BEGIN
    FOR row IN 
        SELECT
            table_schema,
            table_name
        FROM
            information_schema.tables
        WHERE
            table_schema = ''||schema_entrada ||''
     
    LOOP
        EXECUTE 'alter TABLE "'||schema_entrada ||'"."'||row.table_name||'" set schema "'||_schema_salida ||'"';
    END LOOP;
END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.cambiarusermapping()
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
    row     record;
BEGIN
    FOR row IN 
       select split_part(split_part(umoptions::Text, ',',1),'=','2') as pga,
replace(split_part(split_part(umoptions::Text, ',',2),'=','2'),'}',' ') as usr,
srvname from pg_user_mappings
     
    LOOP
        EXECUTE 'DROP USER MAPPING IF EXISTS FOR postgres
SERVER "'||row.srvname||'";

CREATE USER MAPPING if not exists FOR srm_postgres_1 
SERVER "'||row.srvname||'"
   OPTIONS (password '''||row.pga||''', "user" '''||row.usr||''')';
    END LOOP;
END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.chequear_geometrias_mv(
	validar boolean,
	esch text,
	nameview text,
	nametable text)
    RETURNS text
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ declare tab text; BEGIN --cuando validar es 0 extrae la vista de todas las geometrías, cuando es 1 solo las falsas
CASE
  WHEN validar = '0' THEN
--todas geometrías sean validas o no
 EXECUTE 'CREATE MATERIALIZED VIEW "'|| esch ||'"."'|| nameview ||'" AS SELECT row_number() OVER () AS id'|| nametable||', (case when st_isvalid (st_force2d (geom)) is null then ''f'' else st_isvalid (st_force2d (geom)) end) AS valido,* FROM "'|| esch ||'"."'|| nametable||'"';
EXECUTE 'create unique index on "'|| esch ||'"."'|| nameview ||'" (id'|| nametable||')';

ELSE tab := 'falsa';
  END CASE;
  CASE
  WHEN validar = '1' THEN
--las geometrias no validas
 EXECUTE 'CREATE MATERIALIZED VIEW "'|| esch ||'"."'|| nameview ||'" AS SELECT row_number() OVER () AS id'|| nametable||', (case when st_isvalid (st_force2d (geom)) is null then ''f'' else st_isvalid (st_force2d (geom)) end) AS valido,* FROM "'|| esch ||'"."'|| nametable||'"where st_isvalid (geom)= ''false'' or st_isvalid (geom) is null';  
EXECUTE 'create unique index on "'|| esch ||'"."'|| nameview ||'" (id'|| nametable||')';

ELSE tab := 'todas';
  END CASE;
  Return tab;
  END; $BODY$;

  


CREATE OR REPLACE FUNCTION funciones.chequear_geometrias_vw(
	validar boolean,
	esch text,
	nameview text,
	nametable text)
    RETURNS text
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ declare tab text; BEGIN --cuando validar es 0 extrae la vista de todas las geometrías, cuando es 1 solo las falsas
CASE
  WHEN validar = '0' THEN
--todas geometrías sean validas o no
 EXECUTE 'CREATE VIEW "'|| esch ||'"."'|| nameview ||'" AS SELECT row_number() OVER () AS id'|| nametable||', (case when st_isvalid (st_force2d (geom)) is null then ''f'' else st_isvalid (st_force2d (geom)) end) AS valido,* FROM "'|| esch ||'"."'|| nametable||'"';

ELSE tab := 'falsa';
  END CASE;
  CASE
  WHEN validar = '1' THEN
--las geometrias no validas
 EXECUTE 'CREATE VIEW "'|| esch ||'"."'|| nameview ||'" AS SELECT row_number() OVER () AS id'|| nametable||', (case when st_isvalid (st_force2d (geom)) is null then ''f'' else st_isvalid (st_force2d (geom)) end) AS valido,* FROM "'|| esch ||'"."'|| nametable||'"where st_isvalid (geom)= ''false'' or st_isvalid (geom) is null';  

ELSE tab := 'todas';
  END CASE;
  Return tab;
  END; $BODY$;




CREATE OR REPLACE FUNCTION funciones.chequear_topologia_mv(
	esch text,
	nameview text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ BEGIN
	/*Descripcion: Saca errores topológicos */

Execute 'create materialized view "'|| esch ||'"."'|| nameview ||'" as select row_number() OVER () AS id'|| nametable||', id, error from( 
select gid1 as id,concat(''geometries with union points'','':'','' id '',gid1,'' y '',gid2) as "error", seudogeom as geom from 
(select c1.id as gid1, max (c2.id) as gid2, c1.geom as seudogeom,
count (*) as num from  (select (st_dumppoints(geom)).geom, id from "'|| esch ||'"."'|| nametable ||'") c1, 
 (select (st_dumppoints(geom)).geom as geoml, geom, id from "'|| esch ||'"."'|| nametable ||'") c2 where c1.id<>c2.id
and c1.geom && c2.geom and (st_distance (c1.geom,c2.geoml))=0 
group by c1.id,c1.geom)as tabla where num = 1
								  

union all

select id1 as id,''Junctions without union'' as errores, geom from (select r1.id as id1, r2.id as id2, r1.geom from (select a.id,(st_dumppoints(st_intersection(st_buffer(a.geom,0),st_buffer(b.geom,0)))).geom as geom
from "'|| esch ||'"."'|| nametable ||'" a, "'|| esch ||'"."'|| nametable ||'" b 
where a.geom && b.geom and st_relate (st_buffer(a.geom,0),st_buffer(b.geom,0), ''T********'') and a.id>b.id) r1
left join (select (st_dumppoints(geom)).geom, id from "'|| esch ||'"."'|| nametable ||'") r2
on st_distance (r1.geom,r2.geom) = 0) as tabla where id2 is null 

union all

select id1 as id,''Points without union'' as errores, point as geom from(select r1.geom as point, r1.id as id1, r2.id as id2
from (select (st_dumppoints(geom)).geom, id from "'|| esch ||'"."'|| nametable ||'") r1 
	  left join "'|| esch ||'"."'|| nametable ||'" r2 
on r1.id<>r2.id and st_expand (r1.geom,1000) && r2.geom and st_distance (r1.geom,r2.geom) = 0)
as tabla where id2 is null

union all

select distinct on (ra.geom)  ra.id, 
  ''Hollow space'' as errores,st_centroid (ra.geom) as geom from 
(select  re.geom, re.contiene, ST_touches (ST_Buffer(st_force2d(st_makevalid(a.geom)),0),re.geom), ST_Buffer(st_force2d(st_makevalid(a.geom)),0),id 
 FROM "'|| esch ||'"."'|| nametable ||'" a, (SELECT  st_contains (((st_dump (ST_Boundary(st_union(ST_Multi(ST_Buffer(st_force2d(geom),0)))))).geom),
		ST_ExteriorRing((st_dump(st_union(ST_Multi(ST_Buffer(st_force2d(geom),0))))).geom)) as contiene, 
		((st_dump (ST_Boundary(st_union(ST_Multi(ST_Buffer(st_force2d(geom),0)))))).geom)  AS geom
	   FROM "'|| esch ||'"."'|| nametable ||'") re) ra
 where ra.contiene is null and ra.st_touches = ''true''

union all

select gida as id,''Isolated geometry'' as "error",ST_PointOnSurface(st_makepolygon((st_dump(ST_CollectionExtract(contorno,2))).geom)) from (select t1.id as gida, st_multi (st_boundary(t1.geom)) as contorno, t2.id as gidb
from "'|| esch ||'"."'|| nametable ||'" t1 left join "'|| esch ||'"."'|| nametable ||'" t2
on t1.id<>t2.id and st_intersects (t1.geom,t2.geom)) as tabla where gidb is null

union all

select id,''Repeated vertex'' as "error", ST_PointOnSurface(geomp) as geom 
from (select *, (st_dumppoints (geom)).geom as geomp from "'|| esch ||'"."'|| nametable ||'" 
where not st_asewkb(st_removerepeatedpoints (geom)) = st_asewkb (geom))r
GROUP BY id,geomp
     HAVING COUNT(*)>1
	 
union all

select a.id,concat(''
duplicate geometry'','':'','' id original '',b.id) as "error", ST_PointOnSurface(a.geom) as geom
from "'|| esch ||'"."'|| nametable ||'" a, "'|| esch ||'"."'|| nametable ||'" b 
where a.id>b.id and ST_Equals(ST_SnapToGrid(a.geom, 0.005), ST_SnapToGrid(b.geom, 0.005))

union all

select a.id,concat(''overlapping geometries'','':'','' id '',a.id,'' y '',b.id) as "error",ST_PointOnSurface(st_intersection(st_buffer(a.geom,0),st_buffer(b.geom,0))) as geom
from "'|| esch ||'"."'|| nametable ||'" a, "'|| esch ||'"."'|| nametable ||'" b 
where a.geom && b.geom and st_relate (st_buffer(a.geom,0),st_buffer(b.geom,0), ''T********'') and a.id>b.id)re';
EXECUTE 'create unique index on "'|| esch ||'"."'|| nameview ||'" (id'|| nametable||')';
END;
$BODY$;



CREATE OR REPLACE FUNCTION funciones.chequear_topologia_mv(
	esch text,
	nameview text,
	nametable text,
	pk text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ BEGIN
	/*Descripcion: Saca errores topológicos */

Execute 'create materialized view "'|| esch ||'"."'|| nameview ||'" as select row_number() OVER () AS id'|| nametable||', '||pk||', error from( 
select gid1 as '||pk||',concat(''geometries with union points'','':'','' pk '',gid1,'' y '',gid2) as "error", seudogeom as geom from 
(select c1.'||pk||' as gid1, max (c2.'||pk||') as gid2, c1.geom as seudogeom,
count (*) as num from  (select (st_dumppoints(geom)).geom, '||pk||' from "'|| esch ||'"."'|| nametable ||'") c1, 
 (select (st_dumppoints(geom)).geom as geoml, geom, '||pk||' from "'|| esch ||'"."'|| nametable ||'") c2 where c1.'||pk||'<>c2.'||pk||'
and c1.geom && c2.geom and (st_distance (c1.geom,c2.geoml))=0 
group by c1.'||pk||',c1.geom)as tabla where num = 1
								  

union all

select '||pk||'1 as '||pk||',''Junctions without union'' as errores, geom from (select r1.'||pk||' as '||pk||'1, r2.'||pk||' as '||pk||'2, r1.geom from (select a.'||pk||',(st_dumppoints(st_intersection(st_buffer(a.geom,0),st_buffer(b.geom,0)))).geom as geom
from "'|| esch ||'"."'|| nametable ||'" a, "'|| esch ||'"."'|| nametable ||'" b 
where a.geom && b.geom and st_relate (st_buffer(a.geom,0),st_buffer(b.geom,0), ''T********'') and a.'||pk||'>b.'||pk||') r1
left join (select (st_dumppoints(geom)).geom, '||pk||' from "'|| esch ||'"."'|| nametable ||'") r2
on st_distance (r1.geom,r2.geom) = 0) as tabla where '||pk||'2 is null 

union all

select '||pk||'1 as '||pk||',''Points without union'' as errores, point as geom from(select r1.geom as point, r1.'||pk||' as '||pk||'1, r2.'||pk||' as '||pk||'2
from (select (st_dumppoints(geom)).geom, '||pk||' from "'|| esch ||'"."'|| nametable ||'") r1 
	  left join "'|| esch ||'"."'|| nametable ||'" r2 
on r1.'||pk||'<>r2.'||pk||' and st_expand (r1.geom,1000) && r2.geom and st_distance (r1.geom,r2.geom) = 0)
as tabla where '||pk||'2 is null

union all

select distinct on (ra.geom)  ra.'||pk||', 
  ''Hollow space'' as errores,st_centroid (ra.geom) as geom from 
(select  re.geom, re.contiene, ST_touches (ST_Buffer(st_force2d(st_makevalid(a.geom)),0),re.geom), ST_Buffer(st_force2d(st_makevalid(a.geom)),0),'||pk||' 
 FROM "'|| esch ||'"."'|| nametable ||'" a, (SELECT  st_contains (((st_dump (ST_Boundary(st_union(ST_Multi(ST_Buffer(st_force2d(geom),0)))))).geom),
		ST_ExteriorRing((st_dump(st_union(ST_Multi(ST_Buffer(st_force2d(geom),0))))).geom)) as contiene, 
		((st_dump (ST_Boundary(st_union(ST_Multi(ST_Buffer(st_force2d(geom),0)))))).geom)  AS geom
	   FROM "'|| esch ||'"."'|| nametable ||'") re) ra
 where ra.contiene is null and ra.st_touches = ''true''

union all

select gida as '||pk||',''Isolated geometry'' as "error",ST_PointOnSurface(st_makepolygon((st_dump(ST_CollectionExtract(contorno,2))).geom)) from (select t1.'||pk||' as gida, st_multi (st_boundary(t1.geom)) as contorno, t2.'||pk||' as gidb
from "'|| esch ||'"."'|| nametable ||'" t1 left join "'|| esch ||'"."'|| nametable ||'" t2
on t1.'||pk||'<>t2.'||pk||' and st_intersects (t1.geom,t2.geom)) as tabla where gidb is null

union all

select '||pk||',''Repeated vertex'' as "error", ST_PointOnSurface(geomp) as geom 
from (select *, (st_dumppoints (geom)).geom as geomp from "'|| esch ||'"."'|| nametable ||'" 
where not st_asewkb(st_removerepeatedpoints (geom)) = st_asewkb (geom))r
GROUP BY '||pk||',geomp
     HAVING COUNT(*)>1
	 
union all

select a.'||pk||',concat(''
duplicate geometry'','':'','' '||pk||' original '',b.'||pk||') as "error", ST_PointOnSurface(a.geom) as geom
from "'|| esch ||'"."'|| nametable ||'" a, "'|| esch ||'"."'|| nametable ||'" b 
where a.'||pk||'>b.'||pk||' and ST_Equals(ST_SnapToGrid(a.geom, 0.005), ST_SnapToGrid(b.geom, 0.005))

union all

select a.'||pk||',concat(''overlapping geometries'','':'','' pk '',a.'||pk||','' y '',b.'||pk||') as "error",ST_PointOnSurface(st_intersection(st_buffer(a.geom,0),st_buffer(b.geom,0))) as geom
from "'|| esch ||'"."'|| nametable ||'" a, "'|| esch ||'"."'|| nametable ||'" b 
where a.geom && b.geom and st_relate (st_buffer(a.geom,0),st_buffer(b.geom,0), ''T********'') and a.'||pk||'>b.'||pk||')re';
EXECUTE 'create unique index on "'|| esch ||'"."'|| nameview ||'" (id'|| nametable||')';
END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.chequear_topologia_vw(
	esch text,
	nameview text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ BEGIN
	/*Descripcion: Saca errores topológicos */

Execute 'create view "'|| esch ||'"."'|| nameview ||'" as select row_number() OVER () AS id'|| nametable||', id, error from( 
select gid1 as id,concat(''geometries with union points'','':'','' id '',gid1,'' y '',gid2) as "error", seudogeom as geom from 
(select c1.id as gid1, max (c2.id) as gid2, c1.geom as seudogeom,
count (*) as num from  (select (st_dumppoints(geom)).geom, id from "'|| esch ||'"."'|| nametable ||'") c1, 
 (select (st_dumppoints(geom)).geom as geoml, geom, id from "'|| esch ||'"."'|| nametable ||'") c2 where c1.id<>c2.id
and c1.geom && c2.geom and (st_distance (c1.geom,c2.geoml))=0 
group by c1.id,c1.geom)as tabla where num = 1
								  

union all

select id1 as id,''Junctions without union'' as errores, geom from (select r1.id as id1, r2.id as id2, r1.geom from (select a.id,(st_dumppoints(st_intersection(st_buffer(a.geom,0),st_buffer(b.geom,0)))).geom as geom
from "'|| esch ||'"."'|| nametable ||'" a, "'|| esch ||'"."'|| nametable ||'" b 
where a.geom && b.geom and st_relate (st_buffer(a.geom,0),st_buffer(b.geom,0), ''T********'') and a.id>b.id) r1
left join (select (st_dumppoints(geom)).geom, id from "'|| esch ||'"."'|| nametable ||'") r2
on st_distance (r1.geom,r2.geom) = 0) as tabla where id2 is null 

union all

select id1 as id,''Points without union'' as errores, point as geom from(select r1.geom as point, r1.id as id1, r2.id as id2
from (select (st_dumppoints(geom)).geom, id from "'|| esch ||'"."'|| nametable ||'") r1 
	  left join "'|| esch ||'"."'|| nametable ||'" r2 
on r1.id<>r2.id and st_expand (r1.geom,1000) && r2.geom and st_distance (r1.geom,r2.geom) = 0)
as tabla where id2 is null

union all

select distinct on (ra.geom)  ra.id, 
  ''Hollow space'' as errores,st_centroid (ra.geom) as geom from 
(select  re.geom, re.contiene, ST_touches (ST_Buffer(st_force2d(st_makevalid(a.geom)),0),re.geom), ST_Buffer(st_force2d(st_makevalid(a.geom)),0),id 
 FROM "'|| esch ||'"."'|| nametable ||'" a, (SELECT  st_contains (((st_dump (ST_Boundary(st_union(ST_Multi(ST_Buffer(st_force2d(geom),0)))))).geom),
		ST_ExteriorRing((st_dump(st_union(ST_Multi(ST_Buffer(st_force2d(geom),0))))).geom)) as contiene, 
		((st_dump (ST_Boundary(st_union(ST_Multi(ST_Buffer(st_force2d(geom),0)))))).geom)  AS geom
	   FROM "'|| esch ||'"."'|| nametable ||'") re) ra
 where ra.contiene is null and ra.st_touches = ''true''

union all

select gida as id,''Isolated geometry'' as "error",ST_PointOnSurface(st_makepolygon((st_dump(ST_CollectionExtract(contorno,2))).geom)) from (select t1.id as gida, st_multi (st_boundary(t1.geom)) as contorno, t2.id as gidb
from "'|| esch ||'"."'|| nametable ||'" t1 left join "'|| esch ||'"."'|| nametable ||'" t2
on t1.id<>t2.id and st_intersects (t1.geom,t2.geom)) as tabla where gidb is null

union all

select id,''Repeated vertex'' as "error", ST_PointOnSurface(geomp) as geom 
from (select *, (st_dumppoints (geom)).geom as geomp from "'|| esch ||'"."'|| nametable ||'" 
where not st_asewkb(st_removerepeatedpoints (geom)) = st_asewkb (geom))r
GROUP BY id,geomp
     HAVING COUNT(*)>1
	 
union all

select a.id,concat(''
duplicate geometry'','':'','' id original '',b.id) as "error", ST_PointOnSurface(a.geom) as geom
from "'|| esch ||'"."'|| nametable ||'" a, "'|| esch ||'"."'|| nametable ||'" b 
where a.id>b.id and ST_Equals(ST_SnapToGrid(a.geom, 0.005), ST_SnapToGrid(b.geom, 0.005))

union all

select a.id,concat(''overlapping geometries'','':'','' id '',a.id,'' y '',b.id) as "error",ST_PointOnSurface(st_intersection(st_buffer(a.geom,0),st_buffer(b.geom,0))) as geom
from "'|| esch ||'"."'|| nametable ||'" a, "'|| esch ||'"."'|| nametable ||'" b 
where a.geom && b.geom and st_relate (st_buffer(a.geom,0),st_buffer(b.geom,0), ''T********'') and a.id>b.id)re';
END;
$BODY$;



CREATE OR REPLACE FUNCTION funciones.chequear_topologia_vw(
	esch text,
	nameview text,
	nametable text,
	pk text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ BEGIN
	/*Descripcion: Saca errores topológicos */

Execute 'create view "'|| esch ||'"."'|| nameview ||'" as select row_number() OVER () AS id'|| nametable||', '||pk||', error from( 
select gid1 as '||pk||',concat(''geometries with union points'','':'','' pk '',gid1,'' y '',gid2) as "error", seudogeom as geom from 
(select c1.'||pk||' as gid1, max (c2.'||pk||') as gid2, c1.geom as seudogeom,
count (*) as num from  (select (st_dumppoints(geom)).geom, '||pk||' from "'|| esch ||'"."'|| nametable ||'") c1, 
 (select (st_dumppoints(geom)).geom as geoml, geom, '||pk||' from "'|| esch ||'"."'|| nametable ||'") c2 where c1.'||pk||'<>c2.'||pk||'
and c1.geom && c2.geom and (st_distance (c1.geom,c2.geoml))=0 
group by c1.'||pk||',c1.geom)as tabla where num = 1
								  

union all

select '||pk||'1 as '||pk||',''Junctions without union'' as errores, geom from (select r1.'||pk||' as '||pk||'1, r2.'||pk||' as '||pk||'2, r1.geom from (select a.'||pk||',(st_dumppoints(st_intersection(st_buffer(a.geom,0),st_buffer(b.geom,0)))).geom as geom
from "'|| esch ||'"."'|| nametable ||'" a, "'|| esch ||'"."'|| nametable ||'" b 
where a.geom && b.geom and st_relate (st_buffer(a.geom,0),st_buffer(b.geom,0), ''T********'') and a.'||pk||'>b.'||pk||') r1
left join (select (st_dumppoints(geom)).geom, '||pk||' from "'|| esch ||'"."'|| nametable ||'") r2
on st_distance (r1.geom,r2.geom) = 0) as tabla where '||pk||'2 is null 

union all

select '||pk||'1 as '||pk||',''Points without union'' as errores, point as geom from(select r1.geom as point, r1.'||pk||' as '||pk||'1, r2.'||pk||' as '||pk||'2
from (select (st_dumppoints(geom)).geom, '||pk||' from "'|| esch ||'"."'|| nametable ||'") r1 
	  left join "'|| esch ||'"."'|| nametable ||'" r2 
on r1.'||pk||'<>r2.'||pk||' and st_expand (r1.geom,1000) && r2.geom and st_distance (r1.geom,r2.geom) = 0)
as tabla where '||pk||'2 is null

union all

select distinct on (ra.geom)  ra.'||pk||', 
  ''Hollow space'' as errores,st_centroid (ra.geom) as geom from 
(select  re.geom, re.contiene, ST_touches (ST_Buffer(st_force2d(st_makevalid(a.geom)),0),re.geom), ST_Buffer(st_force2d(st_makevalid(a.geom)),0),'||pk||' 
 FROM "'|| esch ||'"."'|| nametable ||'" a, (SELECT  st_contains (((st_dump (ST_Boundary(st_union(ST_Multi(ST_Buffer(st_force2d(geom),0)))))).geom),
		ST_ExteriorRing((st_dump(st_union(ST_Multi(ST_Buffer(st_force2d(geom),0))))).geom)) as contiene, 
		((st_dump (ST_Boundary(st_union(ST_Multi(ST_Buffer(st_force2d(geom),0)))))).geom)  AS geom
	   FROM "'|| esch ||'"."'|| nametable ||'") re) ra
 where ra.contiene is null and ra.st_touches = ''true''

union all

select gida as '||pk||',''Isolated geometry'' as "error",ST_PointOnSurface(st_makepolygon((st_dump(ST_CollectionExtract(contorno,2))).geom)) from (select t1.'||pk||' as gida, st_multi (st_boundary(t1.geom)) as contorno, t2.'||pk||' as gidb
from "'|| esch ||'"."'|| nametable ||'" t1 left join "'|| esch ||'"."'|| nametable ||'" t2
on t1.'||pk||'<>t2.'||pk||' and st_intersects (t1.geom,t2.geom)) as tabla where gidb is null

union all

select '||pk||',''Repeated vertex'' as "error", ST_PointOnSurface(geomp) as geom 
from (select *, (st_dumppoints (geom)).geom as geomp from "'|| esch ||'"."'|| nametable ||'" 
where not st_asewkb(st_removerepeatedpoints (geom)) = st_asewkb (geom))r
GROUP BY '||pk||',geomp
     HAVING COUNT(*)>1
	 
union all

select a.'||pk||',concat(''
duplicate geometry'','':'','' '||pk||' original '',b.'||pk||') as "error", ST_PointOnSurface(a.geom) as geom
from "'|| esch ||'"."'|| nametable ||'" a, "'|| esch ||'"."'|| nametable ||'" b 
where a.'||pk||'>b.'||pk||' and ST_Equals(ST_SnapToGrid(a.geom, 0.005), ST_SnapToGrid(b.geom, 0.005))

union all

select a.'||pk||',concat(''overlapping geometries'','':'','' pk '',a.'||pk||','' y '',b.'||pk||') as "error",ST_PointOnSurface(st_intersection(st_buffer(a.geom,0),st_buffer(b.geom,0))) as geom
from "'|| esch ||'"."'|| nametable ||'" a, "'|| esch ||'"."'|| nametable ||'" b 
where a.geom && b.geom and st_relate (st_buffer(a.geom,0),st_buffer(b.geom,0), ''T********'') and a.'||pk||'>b.'||pk||')re';
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.comprobacion_cambios_mv(
	esch text,
	nameview text,
	nametableia text,
	nametableori text,
	percent_detection double precision,
	percent_nochange double precision)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ declare 
geome1 text;
geome2 text;
srid1 text;
srid2 text;

BEGIN

/*percent_detection limite por el cual la interseccion no sera valida, percent_nochange limite por el cual no habra cambio*/

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| nametableia ||'"';
EXECUTE 'create table __cespaci2 as select * from "'|| esch ||'"."'|| nametableori ||'"';

SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
SELECT f_geometry_column into geome2 FROM geometry_columns  WHERE  f_table_name = '__cespaci2';

EXECUTE 'drop table __cespaci1';
EXECUTE 'drop table __cespaci2';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| nametableia ||'" group by ST_SRID;' into srid1;
EXECUTE 'select ST_SRID("'||geome2||'") from  "'|| esch ||'"."'|| nametableori ||'" group by ST_SRID;' into srid2;


EXECUTE 'create materialized view "'|| esch ||'"."'|| nameview ||'" as 
SELECT re."IA/I", re."ORI/I", re.cambio, re.geom::geometry(Geometry, 4326) AS geom FROM (select ra.* from 
(SELECT te.geom as geombien, te.cambio FROM (select 

fil.* from (select te."IA/I", te."ORI/I", ''No hay cambio'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geom as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I">'''|| percent_nochange ||''' and te."ORI/I">'''|| percent_nochange ||'''
UNION ALL
select te."IA/I", te."ORI/I", ''Nuevo'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geom as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I"<'''|| percent_nochange ||''' and te."ORI/I"<'''|| percent_nochange ||'''
UNION ALL
select te."IA/I", te."ORI/I", ''Cambio nuevo'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geomia as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I"<'''|| percent_nochange ||''' and te."ORI/I">'''|| percent_nochange ||'''
UNION ALL
select te."IA/I", te."ORI/I", ''Cambio derruido'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geomia as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I">'''|| percent_nochange ||''' and te."ORI/I"<'''|| percent_nochange ||'''
)fil

UNION ALL

select null as "IA/I", null as "ORI/I", cambio, re.geom from (select null as porcentaje_cambio, ''No existe IA''as cambio, ta.geom as geom from (select re.tocan, re.fid ,re.geom from 
(select st_intersects(pol3.inter, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) ) as tocan, pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326))) pol3, 
"'|| esch ||'"."'|| nametableori||'" pol6)re group by re.tocan, re.fid, re.geom)ta 
group by ta.fid, ta.geom HAVING COUNT(ta.fid) =1)re
UNION ALL
select null as "IA/I", null as "ORI/I", ''No existe IA'' as cambio, geom as geom from (select re.inter,(st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I",
''No existe IA'' as cambio, re.geom,re.geomia
from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" < '''|| percent_detection ||''' or ta."ORI/I" < '''|| percent_detection ||'''
UNION ALL

select null as "IA/I", null as "ORI/I", cambio, re.geom from (select null as porcentaje_cambio, ''No existe original''as cambio, ta.geom as geom from (select re.tocan, re.fid ,re.geom from 
(select st_intersects(pol3.inter, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) ) as tocan, pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6			
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326))) pol3, 
"'|| esch ||'"."'|| nametableia||'" pol6)re group by re.tocan, re.fid, re.geom)ta 
group by ta.fid, ta.geom HAVING COUNT(ta.fid) =1)re
UNION ALL
select null as "IA/I", null as "ORI/I", ''No existe original'' as cambio, geomia as geom from (select re.inter, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I",
''No existe original'' as cambio, re.geom,re.geomia
from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" < '''|| percent_detection ||''' or ta."ORI/I" < '|| percent_detection ||')te 
 where cambio not like ''No existe %'')re,
(SELECT ter."IA/I", ter."ORI/I", ter.cambio, ter.geom FROM (select 

fil.* from (select te."IA/I", te."ORI/I", ''No hay cambio'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geom as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I">'''|| percent_nochange ||''' and te."ORI/I">'''|| percent_nochange ||'''
UNION ALL
select te."IA/I", te."ORI/I", ''Nuevo'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geom as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I"<'''|| percent_nochange ||''' and te."ORI/I"<'''|| percent_nochange ||'''
UNION ALL
select te."IA/I", te."ORI/I", ''Cambio nuevo'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geomia as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I"<'''|| percent_nochange ||''' and te."ORI/I">'''|| percent_nochange ||'''
UNION ALL
select te."IA/I", te."ORI/I", ''Cambio derruido'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geomia as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I">'''|| percent_nochange ||''' and te."ORI/I"<'''|| percent_nochange ||'''
)fil

UNION ALL

select null as "IA/I", null as "ORI/I", cambio, re.geom from (select null as porcentaje_cambio, ''No existe IA''as cambio, ta.geom as geom from (select re.tocan, re.fid ,re.geom from 
(select st_intersects(pol3.inter, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) ) as tocan, pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326))) pol3, 
"'|| esch ||'"."'|| nametableori||'" pol6)re group by re.tocan, re.fid, re.geom)ta 
group by ta.fid, ta.geom HAVING COUNT(ta.fid) =1)re
UNION ALL
select null as "IA/I", null as "ORI/I", ''No existe IA'' as cambio, geom as geom from (select re.inter,(st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I",
''No existe IA'' as cambio, re.geom,re.geomia
from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" < '''|| percent_detection ||''' or ta."ORI/I" < '''|| percent_detection ||'''
UNION ALL

select null as "IA/I", null as "ORI/I", cambio, re.geom from (select null as porcentaje_cambio, ''No existe original''as cambio, ta.geom as geom from (select re.tocan, re.fid ,re.geom from 
(select st_intersects(pol3.inter, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) ) as tocan, pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6			
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326))) pol3, 
"'|| esch ||'"."'|| nametableia||'" pol6)re group by re.tocan, re.fid, re.geom)ta 
group by ta.fid, ta.geom HAVING COUNT(ta.fid) =1)re
UNION ALL
select null as "IA/I", null as "ORI/I", ''No existe original'' as cambio, geomia as geom from (select re.inter, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I",
''No existe original'' as cambio, re.geom,re.geomia
from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" < '''|| percent_detection ||''' or ta."ORI/I" < '|| percent_detection ||')ter
where cambio like ''%IA'')ra
where st_intersects(re.geombien,ra.geom) = ''true'' 
union all 
SELECT ta.* FROM (select 

fil.* from (select te."IA/I", te."ORI/I", ''No hay cambio'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geom as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I">'''|| percent_nochange ||''' and te."ORI/I">'''|| percent_nochange ||'''
UNION ALL
select te."IA/I", te."ORI/I", ''Nuevo'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geom as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I"<'''|| percent_nochange ||''' and te."ORI/I"<'''|| percent_nochange ||'''
UNION ALL
select te."IA/I", te."ORI/I", ''Cambio nuevo'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geomia as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I"<'''|| percent_nochange ||''' and te."ORI/I">'''|| percent_nochange ||'''
UNION ALL
select te."IA/I", te."ORI/I", ''Cambio derruido'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geomia as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I">'''|| percent_nochange ||''' and te."ORI/I"<'''|| percent_nochange ||'''
)fil

UNION ALL

select null as "IA/I", null as "ORI/I", cambio, re.geom from (select null as porcentaje_cambio, ''No existe IA''as cambio, ta.geom as geom from (select re.tocan, re.fid ,re.geom from 
(select st_intersects(pol3.inter, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) ) as tocan, pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326))) pol3, 
"'|| esch ||'"."'|| nametableori||'" pol6)re group by re.tocan, re.fid, re.geom)ta 
group by ta.fid, ta.geom HAVING COUNT(ta.fid) =1)re
UNION ALL
select null as "IA/I", null as "ORI/I", ''No existe IA'' as cambio, geom as geom from (select re.inter,(st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I",
''No existe IA'' as cambio, re.geom,re.geomia
from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" < '''|| percent_detection ||''' or ta."ORI/I" < '''|| percent_detection ||'''
UNION ALL

select null as "IA/I", null as "ORI/I", cambio, re.geom from (select null as porcentaje_cambio, ''No existe original''as cambio, ta.geom as geom from (select re.tocan, re.fid ,re.geom from 
(select st_intersects(pol3.inter, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) ) as tocan, pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6			
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326))) pol3, 
"'|| esch ||'"."'|| nametableia||'" pol6)re group by re.tocan, re.fid, re.geom)ta 
group by ta.fid, ta.geom HAVING COUNT(ta.fid) =1)re
UNION ALL
select null as "IA/I", null as "ORI/I", ''No existe original'' as cambio, geomia as geom from (select re.inter, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I",
''No existe original'' as cambio, re.geom,re.geomia
from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" < '''|| percent_detection ||''' or ta."ORI/I" < '|| percent_detection ||')ta)re
     GROUP BY re."IA/I", re."ORI/I", re.cambio, re.geom
     HAVING COUNT(*)=1';
	   
	END;
$BODY$;



CREATE OR REPLACE FUNCTION funciones.comprobacion_cambios_vw(
	esch text,
	nameview text,
	nametableia text,
	nametableori text,
	percent_detection double precision,
	percent_nochange double precision)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ declare 
geome1 text;
geome2 text;
srid1 text;
srid2 text;

BEGIN

/*percent_detection limite por el cual la interseccion no sera valida, percent_nochange limite por el cual no habra cambio*/

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| nametableia ||'"';
EXECUTE 'create table __cespaci2 as select * from "'|| esch ||'"."'|| nametableori ||'"';

SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
SELECT f_geometry_column into geome2 FROM geometry_columns  WHERE  f_table_name = '__cespaci2';

EXECUTE 'drop table __cespaci1';
EXECUTE 'drop table __cespaci2';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| nametableia ||'" group by ST_SRID;' into srid1;
EXECUTE 'select ST_SRID("'||geome2||'") from  "'|| esch ||'"."'|| nametableori ||'" group by ST_SRID;' into srid2;


EXECUTE 'create view "'|| esch ||'"."'|| nameview ||'" as 
SELECT re."IA/I", re."ORI/I", re.cambio, re.geom::geometry(Geometry, 4326) AS geom FROM (select ra.* from 
(SELECT te.geom as geombien, te.cambio FROM (select 

fil.* from (select te."IA/I", te."ORI/I", ''No hay cambio'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geom as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I">'''|| percent_nochange ||''' and te."ORI/I">'''|| percent_nochange ||'''
UNION ALL
select te."IA/I", te."ORI/I", ''Nuevo'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geom as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I"<'''|| percent_nochange ||''' and te."ORI/I"<'''|| percent_nochange ||'''
UNION ALL
select te."IA/I", te."ORI/I", ''Cambio nuevo'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geomia as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I"<'''|| percent_nochange ||''' and te."ORI/I">'''|| percent_nochange ||'''
UNION ALL
select te."IA/I", te."ORI/I", ''Cambio derruido'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geomia as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I">'''|| percent_nochange ||''' and te."ORI/I"<'''|| percent_nochange ||'''
)fil

UNION ALL

select null as "IA/I", null as "ORI/I", cambio, re.geom from (select null as porcentaje_cambio, ''No existe IA''as cambio, ta.geom as geom from (select re.tocan, re.fid ,re.geom from 
(select st_intersects(pol3.inter, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) ) as tocan, pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326))) pol3, 
"'|| esch ||'"."'|| nametableori||'" pol6)re group by re.tocan, re.fid, re.geom)ta 
group by ta.fid, ta.geom HAVING COUNT(ta.fid) =1)re
UNION ALL
select null as "IA/I", null as "ORI/I", ''No existe IA'' as cambio, geom as geom from (select re.inter,(st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I",
''No existe IA'' as cambio, re.geom,re.geomia
from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" < '''|| percent_detection ||''' or ta."ORI/I" < '''|| percent_detection ||'''
UNION ALL

select null as "IA/I", null as "ORI/I", cambio, re.geom from (select null as porcentaje_cambio, ''No existe original''as cambio, ta.geom as geom from (select re.tocan, re.fid ,re.geom from 
(select st_intersects(pol3.inter, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) ) as tocan, pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6			
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326))) pol3, 
"'|| esch ||'"."'|| nametableia||'" pol6)re group by re.tocan, re.fid, re.geom)ta 
group by ta.fid, ta.geom HAVING COUNT(ta.fid) =1)re
UNION ALL
select null as "IA/I", null as "ORI/I", ''No existe original'' as cambio, geomia as geom from (select re.inter, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I",
''No existe original'' as cambio, re.geom,re.geomia
from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" < '''|| percent_detection ||''' or ta."ORI/I" < '|| percent_detection ||')te 
 where cambio not like ''No existe %'')re,
(SELECT ter."IA/I", ter."ORI/I", ter.cambio, ter.geom FROM (select 

fil.* from (select te."IA/I", te."ORI/I", ''No hay cambio'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geom as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I">'''|| percent_nochange ||''' and te."ORI/I">'''|| percent_nochange ||'''
UNION ALL
select te."IA/I", te."ORI/I", ''Nuevo'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geom as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I"<'''|| percent_nochange ||''' and te."ORI/I"<'''|| percent_nochange ||'''
UNION ALL
select te."IA/I", te."ORI/I", ''Cambio nuevo'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geomia as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I"<'''|| percent_nochange ||''' and te."ORI/I">'''|| percent_nochange ||'''
UNION ALL
select te."IA/I", te."ORI/I", ''Cambio derruido'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geomia as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I">'''|| percent_nochange ||''' and te."ORI/I"<'''|| percent_nochange ||'''
)fil

UNION ALL

select null as "IA/I", null as "ORI/I", cambio, re.geom from (select null as porcentaje_cambio, ''No existe IA''as cambio, ta.geom as geom from (select re.tocan, re.fid ,re.geom from 
(select st_intersects(pol3.inter, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) ) as tocan, pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326))) pol3, 
"'|| esch ||'"."'|| nametableori||'" pol6)re group by re.tocan, re.fid, re.geom)ta 
group by ta.fid, ta.geom HAVING COUNT(ta.fid) =1)re
UNION ALL
select null as "IA/I", null as "ORI/I", ''No existe IA'' as cambio, geom as geom from (select re.inter,(st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I",
''No existe IA'' as cambio, re.geom,re.geomia
from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" < '''|| percent_detection ||''' or ta."ORI/I" < '''|| percent_detection ||'''
UNION ALL

select null as "IA/I", null as "ORI/I", cambio, re.geom from (select null as porcentaje_cambio, ''No existe original''as cambio, ta.geom as geom from (select re.tocan, re.fid ,re.geom from 
(select st_intersects(pol3.inter, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) ) as tocan, pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6			
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326))) pol3, 
"'|| esch ||'"."'|| nametableia||'" pol6)re group by re.tocan, re.fid, re.geom)ta 
group by ta.fid, ta.geom HAVING COUNT(ta.fid) =1)re
UNION ALL
select null as "IA/I", null as "ORI/I", ''No existe original'' as cambio, geomia as geom from (select re.inter, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I",
''No existe original'' as cambio, re.geom,re.geomia
from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" < '''|| percent_detection ||''' or ta."ORI/I" < '|| percent_detection ||')ter
where cambio like ''%IA'')ra
where st_intersects(re.geombien,ra.geom) = ''true'' 
union all 
SELECT ta.* FROM (select 

fil.* from (select te."IA/I", te."ORI/I", ''No hay cambio'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geom as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I">'''|| percent_nochange ||''' and te."ORI/I">'''|| percent_nochange ||'''
UNION ALL
select te."IA/I", te."ORI/I", ''Nuevo'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geom as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I"<'''|| percent_nochange ||''' and te."ORI/I"<'''|| percent_nochange ||'''
UNION ALL
select te."IA/I", te."ORI/I", ''Cambio nuevo'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geomia as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I"<'''|| percent_nochange ||''' and te."ORI/I">'''|| percent_nochange ||'''
UNION ALL
select te."IA/I", te."ORI/I", ''Cambio derruido'' as cambio, te.geom from(select ta."IA/I", ta."ORI/I", ta.geomia as geom from (select re.inter,re.geom,re.geomia, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I"

from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" > '''|| percent_detection ||''' and ta."ORI/I" > '''|| percent_detection ||''')te where te."IA/I">'''|| percent_nochange ||''' and te."ORI/I"<'''|| percent_nochange ||'''
)fil

UNION ALL

select null as "IA/I", null as "ORI/I", cambio, re.geom from (select null as porcentaje_cambio, ''No existe IA''as cambio, ta.geom as geom from (select re.tocan, re.fid ,re.geom from 
(select st_intersects(pol3.inter, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) ) as tocan, pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326))) pol3, 
"'|| esch ||'"."'|| nametableori||'" pol6)re group by re.tocan, re.fid, re.geom)ta 
group by ta.fid, ta.geom HAVING COUNT(ta.fid) =1)re
UNION ALL
select null as "IA/I", null as "ORI/I", ''No existe IA'' as cambio, geom as geom from (select re.inter,(st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I",
''No existe IA'' as cambio, re.geom,re.geomia
from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" < '''|| percent_detection ||''' or ta."ORI/I" < '''|| percent_detection ||'''
UNION ALL

select null as "IA/I", null as "ORI/I", cambio, re.geom from (select null as porcentaje_cambio, ''No existe original''as cambio, ta.geom as geom from (select re.tocan, re.fid ,re.geom from 
(select st_intersects(pol3.inter, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) ) as tocan, pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6			
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326))) pol3, 
"'|| esch ||'"."'|| nametableia||'" pol6)re group by re.tocan, re.fid, re.geom)ta 
group by ta.fid, ta.geom HAVING COUNT(ta.fid) =1)re
UNION ALL
select null as "IA/I", null as "ORI/I", ''No existe original'' as cambio, geomia as geom from (select re.inter, (st_area(re.inter) / st_area(re.geomia)) * 100 as "IA/I", (st_area(re.inter) / st_area(re.geom)) * 100 as "ORI/I",
''No existe original'' as cambio, re.geom,re.geomia
from (SELECT ST_INTERSECTION(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)) as inter,pol6.fid, st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326) as geom,
 st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326) as geomia
from "'|| esch ||'"."'|| nametableia||'" pol3 , 
		 "'|| esch ||'"."'|| nametableori||'" pol6				
WHERE ST_INTERSECTS(st_transform(st_setsrid(pol3."'||geome1||'",'||srid1||'),4326),st_transform(st_setsrid(pol6."'||geome2||'",'||srid2||'),4326)))re)ta where ta."IA/I" < '''|| percent_detection ||''' or ta."ORI/I" < '|| percent_detection ||')ta)re
     GROUP BY re."IA/I", re."ORI/I", re.cambio, re.geom
     HAVING COUNT(*)=1';
	   
	END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.comprobacion_de_datos_mv(
	esch text,
	nameview text,
	nametable text,
	contenido character varying)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ declare namecolumn character varying; BEGIN /*Retorna una vista con una columna en la cual informa si el contenido buscado existe o no.
contenido:que se quiere buscar*/
SELECT COLUMN_NAME into namecolumn FROM information_schema.COLUMNS WHERE TABLE_NAME = ''|| nametable ||'' limit 1;
EXECUTE 'create materialized view "'|| esch ||'"."'|| nameview ||'" as select *, ''true'' as exists 
	from "'|| esch ||'"."'|| nametable||'" where '|| contenido ||'
union
select *, ''false'' as exists from "'|| esch ||'"."'|| nametable||'" where '||namecolumn||'
not in (select '||namecolumn||' from "'|| esch ||'"."'|| nametable||'" where '|| contenido ||')';
	END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.comprobacion_de_datos_vw(
	esch text,
	nameview text,
	nametable text,
	contenido character varying)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ declare namecolumn character varying; BEGIN /*Retorna una vista con una columna en la cual informa si el contenido buscado existe o no.
contenido:que se quiere buscar*/
SELECT COLUMN_NAME into namecolumn FROM information_schema.COLUMNS WHERE TABLE_NAME = ''|| nametable ||'' limit 1;
EXECUTE 'create  view "'|| esch ||'"."'|| nameview ||'" as select *, ''true'' as exists 
	from "'|| esch ||'"."'|| nametable||'" where '|| contenido ||'
union
select *, ''false'' as exists from "'|| esch ||'"."'|| nametable||'" where '||namecolumn||'
not in (select '||namecolumn||' from "'|| esch ||'"."'|| nametable||'" where '|| contenido ||')';
	END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.crear_geometrias_validas_mv(
	esch text,
	nameview text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$declare 
geome1 text;
srid1 text;

BEGIN

/*percent_detection limite por el cual la interseccion no sera valida, percent_nochange limite por el cual no habra cambio*/

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| nametable ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| nametable ||'" group by ST_SRID;' into srid1;


/*Descripcion: crea una vista materializada con una columna de geometrías validas */
EXECUTE 'CREATE  MATERIALIZED VIEW "'|| esch ||'"."'|| nameview ||'" 
AS SELECT row_number() OVER () AS id'|| nameview ||', 
st_transform(st_setsrid(st_makevalid,'|| srid1 ||'),4326)::geometry(Geometry, 4326) as geom
from (select st_makevalid ('|| geome1 ||'),* FROM "'|| esch ||'"."'|| nametable||'")a';
EXECUTE 'create unique index on "'|| esch ||'"."'|| nameview ||'" (id'|| nameview ||')';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.crear_geometrias_validas_vw(
	esch text,
	nameview text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$declare 
geome1 text;
srid1 text;

BEGIN

/*percent_detection limite por el cual la interseccion no sera valida, percent_nochange limite por el cual no habra cambio*/

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| nametable ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| nametable ||'" group by ST_SRID;' into srid1;


/*Descripcion: crea una vista materializada con una columna de geometrías validas */
EXECUTE 'CREATE  VIEW "'|| esch ||'"."'|| nameview ||'" 
AS SELECT row_number() OVER () AS id'|| nameview ||', 
st_transform(st_setsrid(st_makevalid,'|| srid1 ||'),4326)::geometry(Geometry, 4326) as geom
from (select st_makevalid ('|| geome1 ||'),* FROM "'|| esch ||'"."'|| nametable||'")a';
EXECUTE 'create unique index on "'|| esch ||'"."'|| nameview ||'" (id'|| nameview ||')';

END;
$BODY$;



CREATE OR REPLACE FUNCTION funciones.create_for_union_rail2_vw(
	esch text,
	nameview text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ BEGIN
	/*Descripcion:crea una vista para hacer una union posterior */
	EXECUTE 'create view "'|| esch ||'"."paraunionrail_'|| nameview ||'" as 
	select ra.* from 
	(select * FROM "'|| esch ||'"."'|| nametable||'") ra';

END;
$BODY$;



CREATE OR REPLACE FUNCTION funciones.create_for_union_vw(
	esch text,
	nameview text,
	nametable text,
	value text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ BEGIN
	/*Descripcion:crea una vista para hacer una union posterior */
	EXECUTE 'create view "'|| esch ||'"."paraunion_'|| nameview ||'" as 
	select ra.geom, ra.layer_ori from 
	(select geom, '''|| value||''' as layer_ori FROM "'|| esch ||'"."'|| nametable||'") ra';

END;
$BODY$;



CREATE OR REPLACE FUNCTION funciones.cubierta_sin_solapes(
	esch text,
	cubierta text,
	cubiertasalida text,
	redtransporte text,
	hidrografia text,
	epsg numeric)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: une los atributos iniciales a las capas generalizadas */
	EXECUTE 'drop table if exists "'||esch||'"."'||cubierta||'_valid";
	create table "'||esch||'"."'||cubierta||'_valid" as select *, st_makevalid(geom) as geom2 from "'||esch||'"."'||cubierta||'";
alter table "'||esch||'"."'||cubierta||'_valid" drop column geom; 
alter table "'||esch||'"."'||cubierta||'_valid" rename column geom2 to geom;
create index z_red_'||cubierta||'_valid_geom_dif_gidx on "'||esch||'"."'||cubierta||'_valid" using gist(geom);
drop table if exists "'||esch||'"."'||cubiertasalida||'";
create table "'||esch||'"."'||cubiertasalida||'" (like "'||esch||'"."'||cubierta||'_valid");
alter table "'||esch||'"."'||cubiertasalida||'"
add column geom_dif geometry (Geometry,'||epsg||');
create index z_'||cubierta||'_diferencia_geom_dif_gidx
on "'||esch||'"."'||cubiertasalida||'" 
using gist(geom_dif); 
drop table if exists "'||esch||'"."'||redtransporte||'_union";
create table "'||esch||'"."'||redtransporte||'_union" as select st_makevalid(st_union(st_makevalid(geom))) as geom from "'||esch||'"."'||redtransporte||'";

create index z_red_clean_union_geom_dif_gidx
on "'||esch||'"."'||redtransporte||'_union" 
using gist(geom);
insert into "'||esch||'"."'||cubiertasalida||'"  
select a.*,(st_dump(st_difference(a.geom,b.geom))).geom
from "'||esch||'"."'||cubierta||'_valid" a, 
"'||esch||'"."'||redtransporte||'_union" b  
where st_intersects(a.geom,b.geom);
insert into "'||esch||'"."'||cubiertasalida||'" 
select a.*,null from  "'||esch||'"."'||cubierta||'_valid" a 
left join "'||esch||'"."'||redtransporte||'_union" b on st_intersects(a.geom,b.geom) where b.geom is null;
update "'||esch||'"."'||cubiertasalida||'"  set geom_dif = geom where geom_dif is null;
update "'||esch||'"."'||cubiertasalida||'"  set geom = geom_dif;			

drop table if exists "'||esch||'"."'||cubierta||'_diferencia2";
create table "'||esch||'"."'||cubierta||'_diferencia2"(like "'||esch||'"."'||cubiertasalida||'");
alter table "'||esch||'"."'||cubierta||'_diferencia2"
add column geom_dif2 geometry (Geometry,'||epsg||');
create index z_'||cubierta||'_diferencia2_geom_dif_gidx
on "'||esch||'"."'||cubierta||'_diferencia2" 
using gist(geom_dif2);
create table "'||esch||'"."'||hidrografia||'_union" as select st_makevalid(st_union(st_makevalid(geom))) as geom from "'||esch||'"."'||hidrografia||'";
create index z_hidro_general_generaliced_union_geom_dif_gidx
on "'||esch||'"."'||hidrografia||'_union" 
using gist(geom);
insert into "'||esch||'"."'||cubierta||'_diferencia2"  
select a.*,(st_dump(st_difference(a.geom,b.geom))).geom
from "'||esch||'"."'||cubiertasalida||'" a, 
"'||esch||'"."'||hidrografia||'_union" b  
where st_intersects(a.geom,b.geom);
insert into "'||esch||'"."'||cubierta||'_diferencia2" 
select a.*,null from  "'||esch||'"."'||cubiertasalida||'" a 
left join "'||esch||'"."'||hidrografia||'_union" b on st_intersects(a.geom,b.geom) where b.geom is null;
update "'||esch||'"."'||cubierta||'_diferencia2"  set geom_dif2 = geom where geom_dif2 is null;
update "'||esch||'"."'||cubierta||'_diferencia2"  set geom = geom_dif2;	
alter table "'||esch||'"."'||cubierta||'_diferencia2" drop column geom_dif2;
alter table "'||esch||'"."'||cubierta||'_diferencia2" drop column geom_dif;
drop table "'||esch||'"."'||cubiertasalida||'";
drop table "'||esch||'"."'||redtransporte||'_union";
drop table "'||esch||'"."'||hidrografia||'_union";
alter table "'||esch||'"."'||cubierta||'_diferencia2" rename to "'||cubiertasalida||'";';

END;
$BODY$;



CREATE OR REPLACE FUNCTION funciones.dividir_por_tipo_mv(
	esch text,
	nameview text,
	nametable text,
	campo text,
	valor text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: divide la tabla por el topo que se quiera tipo */
	EXECUTE 'create materialized view "'|| esch ||'"."'|| nameview ||'"
as select * from "'|| esch ||'"."'|| nametable||'" where "'|| campo ||'" = '''|| valor ||'''';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.dividir_por_tipo_vw(
	esch text,
	nameview text,
	nametable text,
	campo text,
	valor text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: divide la tabla por el topo que se quiera tipo */
	EXECUTE 'create view "'|| esch ||'"."'|| nameview ||'"
as select * from "'|| esch ||'"."'|| nametable||'" where "'|| campo ||'" = '''|| valor ||'''';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.extraer_centroides_mv(
	esch text,
	nameview text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ declare 
geome1 text;
srid1 text;
camposc text;

BEGIN

/*percent_detection limite por el cual la interseccion no sera valida, percent_nochange limite por el cual no habra cambio*/

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| nametable ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| nametable ||'" group by ST_SRID;' into srid1;
EXECUTE 'select concat(''"''||STRING_AGG(column_name,''", "'')||''"'') from (SELECT a.attname as column_name,
pg_catalog.format_type(a.atttypid, a.atttypmod) FROM pg_attribute a JOIN pg_class t on a.attrelid = t.oid 
JOIN pg_namespace s on t.relnamespace = s.oid WHERE a.attnum > 0 AND NOT a.attisdropped AND t.relname = '''|| nametable ||'''
AND s.nspname = '''|| esch ||''' ORDER BY a.attnum)a where format_type  not like ''%geometry%'';'into camposc;

/*Descripcion: extrae puntos que siempre estan dentro de la geometria */
EXECUTE 'CREATE  MATERIALIZED VIEW "'|| esch ||'"."'|| nameview ||'" AS 
select '||camposc||', st_transform(st_setsrid(centroid,'||srid1||'),4326)::geometry(Geometry, 4326) AS geom, row_number() OVER () as fidid 
from(SELECT *, ST_PointOnSurface ("'||geome1||'") as centroid FROM "'|| esch ||'"."'|| nametable||'")te';
EXECUTE 'create unique index on "'|| esch ||'"."'|| nameview ||'" (fidid)';

END;
$BODY$;



CREATE OR REPLACE FUNCTION funciones.extraer_centroides_vw(
	esch text,
	nameview text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ declare 
geome1 text;
srid1 text;
camposc text;

BEGIN

/*percent_detection limite por el cual la interseccion no sera valida, percent_nochange limite por el cual no habra cambio*/

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| nametable ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| nametable ||'" group by ST_SRID;' into srid1;
EXECUTE 'select concat(''"''||STRING_AGG(column_name,''", "'')||''"'') from (SELECT a.attname as column_name,
pg_catalog.format_type(a.atttypid, a.atttypmod) FROM pg_attribute a JOIN pg_class t on a.attrelid = t.oid 
JOIN pg_namespace s on t.relnamespace = s.oid WHERE a.attnum > 0 AND NOT a.attisdropped AND t.relname = '''|| nametable ||'''
AND s.nspname = '''|| esch ||''' ORDER BY a.attnum)a where format_type  not like ''%geometry%'';'into camposc;

/*Descripcion: extrae puntos que siempre estan dentro de la geometria */
EXECUTE 'CREATE VIEW "'|| esch ||'"."'|| nameview ||'" AS 
select '||camposc||', st_transform(st_setsrid(centroid,'||srid1||'),4326)::geometry(Geometry, 4326) AS geom
from (SELECT *, ST_PointOnSurface ("'||geome1||'") as centroid FROM "'|| esch ||'"."'|| nametable||'")te';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.extraer_lineas_exteriores_mv(
	esch text,
	nameview text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ declare 
geome1 text;
srid1 text;
camposc text;
BEGIN

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| nametable ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| nametable ||'" group by ST_SRID;' into srid1;
EXECUTE 'select concat(''"''||STRING_AGG(column_name,''", "'')||''"'') from (SELECT a.attname as column_name,
pg_catalog.format_type(a.atttypid, a.atttypmod) FROM pg_attribute a JOIN pg_class t on a.attrelid = t.oid 
JOIN pg_namespace s on t.relnamespace = s.oid WHERE a.attnum > 0 AND NOT a.attisdropped AND t.relname = '''|| nametable ||'''
AND s.nspname = '''|| esch ||''' ORDER BY a.attnum)a where format_type  not like ''%geometry%'';'into camposc;

 EXECUTE 'create  materialized view "'|| esch ||'"."'|| nameview||'" as 
select '||camposc||',  st_transform(st_setsrid(bounda,'||srid1||'),4326)::geometry(Geometry, 4326) AS geom, row_number() OVER () as fidid 
from (select *, ST_boundary(st_force2d(geom)) as bounda
 from "'|| esch ||'"."'||nametable||'")a';
EXECUTE 'create unique index on "'|| esch ||'"."'|| nameview ||'" (fidid)';
	 
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.extraer_lineas_exteriores_vw(
	esch text,
	nameview text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ declare 
geome1 text;
srid1 text;
camposc text;
BEGIN

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| nametable ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| nametable ||'" group by ST_SRID;' into srid1;
EXECUTE 'select concat(''"''||STRING_AGG(column_name,''", "'')||''"'') from (SELECT a.attname as column_name,
pg_catalog.format_type(a.atttypid, a.atttypmod) FROM pg_attribute a JOIN pg_class t on a.attrelid = t.oid 
JOIN pg_namespace s on t.relnamespace = s.oid WHERE a.attnum > 0 AND NOT a.attisdropped AND t.relname = '''|| nametable ||'''
AND s.nspname = '''|| esch ||''' ORDER BY a.attnum)a where format_type  not like ''%geometry%'';'into camposc;

 EXECUTE 'create view "'|| esch ||'"."'|| nameview||'" as 
select '||camposc||',  st_transform(st_setsrid(bounda,'||srid1||'),4326)::geometry(Geometry, 4326) AS geom, row_number() OVER () as fidid 
from (select *, ST_boundary(st_force2d(geom)) as bounda
 from "'|| esch ||'"."'||nametable||'")a';
	 
END;
$BODY$;



CREATE OR REPLACE FUNCTION funciones.generalizar_areas(
	esch text,
	nametable text,
	tbl_salida text,
	tolerance double precision,
	simply double precision,
	pk_field character varying,
	min_area double precision,
	area_peri double precision,
	epsg integer)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: une los atributos iniciales a las capas generalizadas */
	EXECUTE 'create table "'|| esch ||'"."'|| nametable||'_tipo"

as select "'|| pk_field ||'", st_union (geom) as geom from "'|| esch ||'"."'|| nametable||'" group by "'|| pk_field ||'";

create table "'|| esch ||'"."'|| nametable||'_dissolve" as select "'|| pk_field ||'", (st_dump (geom)).geom as geom from "'|| esch ||'"."'|| nametable||'_tipo";
	
CREATE table "'|| esch ||'"."'|| nametable||'_dissolve_simplify"
	AS  
	SELECT "'|| pk_field ||'",
	st_simplifypreservetopology(geom, '|| simply ||')as geom
	
	FROM "'|| esch ||'"."'|| nametable||'_dissolve";
	CREATE TABLE "'|| esch ||'"."'|| nametable||'_dissolve_simplify2"
	as
	select fid, "'|| pk_field ||'",geom,st_area (geom) as area from (SELECT row_number() OVER () AS fid,
	 "'|| pk_field ||'",
	    ST_GeomFromText(ST_AsText( (ST_Dump(geom)).geom )) as geom
	    
	from "'|| esch ||'"."'|| nametable||'_dissolve_simplify")t;
	
CREATE TABLE "'|| esch ||'"."'|| nametable||'_dissolve_simplify_anillos"

AS
 SELECT "'|| nametable||'_dissolve_simplify2".fid,"'|| pk_field ||'",
    (st_dumprings(st_force2d("'|| nametable||'_dissolve_simplify2".geom))).geom AS geom,
    st_area((st_dumprings(st_force2d("'|| nametable||'_dissolve_simplify2".geom))).geom) AS area
   FROM "'|| esch ||'"."'|| nametable||'_dissolve_simplify2";
	

create table   "'|| esch ||'"."'|| nametable||'_union_simply_anillos" as SELECT fid ,
"'|| pk_field ||'",
   st_force2d(geom) as geom,
   area
FROM
  "'|| esch ||'"."'|| nametable||'_dissolve_simplify2"
UNION
SELECT fid ,
"'|| pk_field ||'",
   ST_Buffer(geom,'|| tolerance||'),
   area
FROM
  "'|| esch ||'"."'|| nametable||'_dissolve_simplify_anillos";
  
  UPDATE "'|| esch ||'"."'|| nametable||'_union_simply_anillos" SET geom=ST_makevalid(geom) WHERE NOT ST_isValid(geom);
    create table "'|| esch ||'"."'|| nametable||'_union_simply_anillos_unidos" as select st_union(geom) as geom, "'|| pk_field ||'" from  "'|| esch ||'"."'|| nametable||'_union_simply_anillos" group by "'|| pk_field ||'" 
	 ; create table "'|| esch ||'"."'|| nametable||'_union_simply_anillos_unidos_dump2" as select (st_dump(geom)).geom as geom, "'|| pk_field ||'" from  "'|| esch ||'"."'|| nametable||'_union_simply_anillos_unidos"  
;
create table "'|| esch ||'"."'|| nametable||'_union_simply_anillos_unidos_dump" as SELECT row_number() OVER () AS fid,geom, "'|| pk_field ||'" from "'|| esch ||'"."'|| nametable||'_union_simply_anillos_unidos_dump2"
;create table "'|| esch ||'"."'|| nametable||'_union" as select fid, ST_CollectionExtract(st_union(geom),3) as geom, 
"'|| pk_field ||'",
st_area(ST_CollectionExtract(st_union(geom),3)),
((st_area(ST_CollectionExtract(st_union(geom),3)))/(((ST_Perimeter(ST_CollectionExtract(st_union(geom),3))))^2)) as relation
from "'|| esch ||'"."'|| nametable||'_union_simply_anillos_unidos_dump"  group by fid,"'|| pk_field ||'";

create table "'|| esch ||'"."'|| nametable||'_union_area" as SELECT * FROM "'|| esch ||'"."'|| nametable||'_union";

CREATE INDEX z_'|| nametable||'_union_area_geom_gidx
    ON "'|| esch ||'"."'|| nametable||'_union_area" USING gist
    (geom);
	
	
	create table "'|| esch ||'"."'||tbl_salida||'" as select a.*, b.geom as geom2 
	from "'|| esch ||'"."'|| nametable||'" a join
	"'|| esch ||'"."'|| nametable||'_union_area" b on a."'|| pk_field ||'" = b."'|| pk_field ||'" and st_intersects (st_setsrid(b.geom,'|| epsg||'),a.geom);
		alter table "'|| esch ||'"."'||tbl_salida||'"  drop geom;
	alter table "'|| esch ||'"."'||tbl_salida||'"  rename geom2 to geom;
	alter table "'|| esch ||'"."'||tbl_salida||'"  add column ida serial;

DELETE FROM  "'|| esch ||'"."'||tbl_salida||'"
WHERE ida IN
    (SELECT ida
    FROM 
        (SELECT ida,
         ROW_NUMBER() OVER( PARTITION BY geom
        ORDER BY  ida ) AS row_num
        FROM "'|| esch ||'"."'||tbl_salida||'") t
        WHERE t.row_num > 1 );
		CREATE INDEX z_'||tbl_salida||'_generaliced_geom_gidx
    ON "'|| esch ||'"."'||tbl_salida||'" USING gist
    (geom);
		
drop table "'|| esch ||'"."'|| nametable||'_union_area";
drop table "'|| esch ||'"."'|| nametable||'_tipo";
drop table "'|| esch ||'"."'|| nametable||'_dissolve";
drop table "'|| esch ||'"."'|| nametable||'_dissolve_simplify";
drop table "'|| esch ||'"."'|| nametable||'_dissolve_simplify2";
drop table "'|| esch ||'"."'|| nametable||'_dissolve_simplify_anillos";
drop table "'|| esch ||'"."'|| nametable||'_union_simply_anillos";
drop table "'|| esch ||'"."'|| nametable||'_union_simply_anillos_unidos";
drop table "'|| esch ||'"."'|| nametable||'_union_simply_anillos_unidos_dump2";	
drop table "'|| esch ||'"."'|| nametable||'_union_simply_anillos_unidos_dump";
drop table "'|| esch ||'"."'|| nametable||'_union";

ALTER TABLE "'|| esch ||'"."'||tbl_salida||'" ALTER COLUMN geom TYPE geometry(Geometry,'|| epsg ||') USING ST_SetSRID(geom,'|| epsg||');  
alter table "'|| esch ||'"."'||tbl_salida||'"  add column area double precision;
alter table "'|| esch ||'"."'||tbl_salida||'"  add column relation double precision;
update "'|| esch ||'"."'||tbl_salida||'" set area = st_area(geom);
update "'|| esch ||'"."'||tbl_salida||'" set relation = ((st_area(geom))/((ST_Perimeter(geom))^2))/0.079577471546  ;
create table "'|| esch ||'"."'||tbl_salida||'2" as select * from "'|| esch ||'"."'||tbl_salida||'" 
where area>'''|| min_area ||''' and relation > ('|| area_peri ||')^2;
drop table "'|| esch ||'"."'||tbl_salida||'";';

EXECUTE 'create table "'|| esch ||'"."'|| tbl_salida||'" as select  row_number ()over() as id_todo,* from "'|| esch ||'"."'||tbl_salida||'2";';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| tbl_salida ||'_geom_gidx
    ON "'|| esch ||'"."'|| tbl_salida||'" USING gist
    (geom);';
EXECUTE 'create table "'|| esch ||'".tmp'|| nametable ||'_union as select st_union (geom) from "'|| esch ||'"."'|| tbl_salida||'";';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nametable ||'_union_geom_gidx
    ON "'|| esch ||'".tmp'|| nametable ||'_union USING gist
    (st_union);';
EXECUTE 'create table "'|| esch ||'".tmp'|| nametable ||'_union_dump as select (st_dump (st_union)).geom from "'|| esch ||'".tmp'|| nametable ||'_union;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nametable ||'_union_dump_geom_gidx
    ON "'|| esch ||'".tmp'|| nametable ||'_union_dump USING gist
    (geom);';
EXECUTE 'create table "'|| esch ||'".tmp'|| nametable ||'_union_dump_boundary as select st_boundary(geom) as boundary from "'|| esch ||'".tmp'|| nametable ||'_union_dump;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nametable ||'_union_dump_boundary_geom_gidx
    ON "'|| esch ||'".tmp'|| nametable ||'_union_dump_boundary USING gist
    (boundary);';
EXECUTE 'create table "'|| esch ||'".tmp'|| nametable ||'_union_dump_exterior as select st_exteriorring(geom) as geom from "'|| esch ||'".tmp'|| nametable ||'_union_dump;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nametable ||'_union_dump_exterior_geom_gidx
    ON "'|| esch ||'".tmp'|| nametable ||'_union_dump_exterior USING gist
    (geom);';
EXECUTE 'create table  "'|| esch ||'".tmp'|| nametable ||'_union_dump_exterior_poligon as select ST_MakePolygon(geom) as geom from  "'|| esch ||'".tmp'|| nametable ||'_union_dump_exterior;';
EXECUTE 'create table  "'|| esch ||'".tmp'|| nametable ||'_union_dump_boundary_dump as select (ST_dump(boundary)).geom as geom from  "'|| esch ||'".tmp'|| nametable ||'_union_dump_boundary;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nametable ||'__union_dump_exterior_poligon_geom_gidx
    ON "'|| esch ||'".tmp'|| nametable ||'_union_dump_exterior_poligon USING gist
    (geom);';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nametable ||'_union_ddump_boundary_dump_geom_gidx
    ON "'|| esch ||'".tmp'|| nametable ||'_union_dump_boundary_dump USING gist
    (geom);';

	
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nametable ||'_union_dump_contains;';
EXECUTE 'create table "'|| esch ||'".tmp'|| nametable ||'_union_dump_contains as 
select a.geom as geom from  "'|| esch ||'".tmp'|| nametable ||'_union_dump_boundary_dump a,"'|| esch ||'".tmp'|| nametable ||'_union_dump_exterior_poligon b where ST_ContainsProperly (b.geom,a.geom);';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nametable ||'_union_dddump_contains_geom_gidx
    ON "'|| esch ||'".tmp'|| nametable ||'_union_dump_contains USING gist
    (geom);';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nametable ||'_union_huecos;';
EXECUTE 'create table "'|| esch ||'".tmp'|| nametable ||'_union_huecos
as select st_makepolygon(geom) as geom from "'|| esch ||'".tmp'|| nametable ||'_union_dump_contains;';
EXECUTE 'create table "'|| esch ||'".tmp'|| nametable ||'_huecos_id as select row_number ()over() as id_hueco,* from  "'|| esch ||'".tmp'|| nametable ||'_union_huecos;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nametable ||'_huecos_id_geom_gidx
    ON "'|| esch ||'".tmp'|| nametable ||'_huecos_id USING gist
    (geom);';
EXECUTE 'drop table if exists  "'|| esch ||'".tmp'|| nametable ||'_huecos_buffer_id;';
EXECUTE 'create table "'|| esch ||'".tmp'|| nametable ||'_huecos_buffer_id
as select id_hueco,st_buffer (geom,0.05) as geom from "'|| esch ||'".tmp'|| nametable ||'_huecos_id;';

EXECUTE 'create INDEX '|| esch ||'_tmp'|| nametable ||'_huecos_buffer_id_geom_gidx
    ON "'|| esch ||'".tmp'|| nametable ||'_huecos_buffer_id USING gist
    (geom);';

	EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nametable ||'_huecos_intersection;';
EXECUTE 'create table "'|| esch ||'".tmp'|| nametable ||'_huecos_intersection
 as select id_todo,id_hueco,st_area(st_intersection (a.geom,b.geom)) as area,a.geom from 
 (select * from "'|| esch ||'"."'|| tbl_salida||'") a, 
 "'|| esch ||'".tmp'|| nametable ||'_huecos_buffer_id b
 where st_intersects (a.geom,b.geom);';
 EXECUTE 'create INDEX '|| esch ||'_tmp'|| nametable ||'_dhuecos_intersection_geom_gidx
    ON "'|| esch ||'".tmp'|| nametable ||'_huecos_intersection USING gist
    (geom);';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nametable ||'_huecos_intersection_max;';
EXECUTE 'create table  "'|| esch ||'".tmp'|| nametable ||'_huecos_intersection_max as select id_hueco,max(area) 
from  "'|| esch ||'".tmp'|| nametable ||'_huecos_intersection group by id_hueco;';

EXECUTE 'create table "'|| esch ||'".tmp'|| nametable ||'_ori_huecos_id as select a.* from "'|| esch ||'".tmp'|| nametable ||'_huecos_intersection a,
"'|| esch ||'".tmp'|| nametable ||'_huecos_intersection_max b where a.area =b.max and a.id_hueco = b.id_hueco;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nametable ||'_ori_huecos_id_gidx
    ON "'|| esch ||'".tmp'|| nametable ||'_ori_huecos_id USING gist
    (geom);';
	
EXECUTE 'create table "'|| esch ||'".tmp'|| nametable ||'_id_hueco_id_todo as select  b.*,y.id_todo
from  "'|| esch ||'".tmp'|| nametable ||'_ori_huecos_id y
join "'|| esch ||'".tmp'|| nametable ||'_huecos_id b
on y.id_hueco = b.id_hueco;';

 EXECUTE 'create INDEX '|| esch ||'_tmp'|| nametable ||'_id_hueco_id_todo_gidx
    ON "'|| esch ||'".tmp'|| nametable ||'_id_hueco_id_todo USING gist
    (geom);';
	
EXECUTE 'create table "'|| esch ||'".tmp'|| nametable ||'_geom_hueco_geom_ori as 
select geom,id_todo from "'|| esch ||'"."'|| tbl_salida||'" 
union all select geom,id_todo
from  "'|| esch ||'".tmp'|| nametable ||'_id_hueco_id_todo;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nametable ||'_geom_hueco_geom_ori_gidx
    ON "'|| esch ||'".tmp'|| nametable ||'_geom_hueco_geom_ori USING gist
    (geom);';
	
EXECUTE 'create table "'|| esch ||'".tmp'|| nametable ||'_geom_hueco_geom_ori_unidas as select 
st_union(geom),id_todo from "'|| esch ||'".tmp'|| nametable ||'_geom_hueco_geom_ori group by id_todo;';

EXECUTE 'update "'|| esch ||'"."'|| tbl_salida||'" a set geom = b.st_union from 
"'|| esch ||'".tmp'|| nametable ||'_geom_hueco_geom_ori_unidas b
where a.id_todo = b.id_todo;';

EXECUTE 'drop table if exists "'|| esch ||'"."'||tbl_salida||'2";';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nametable ||';';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nametable ||'_union;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nametable ||'_union_dump;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nametable ||'_union_dump_boundary;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nametable ||'_union_dump_exterior;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nametable ||'_union_dump_exterior_poligon;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nametable ||'_union_dump_boundary_dump;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nametable ||'_union_dump_contains;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nametable ||'_union_huecos;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nametable ||'_huecos_id;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nametable ||'_huecos_buffer_id;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nametable ||'_huecos_intersection;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nametable ||'_huecos_intersection_max;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nametable ||'_ori_huecos_id;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nametable ||'_id_hueco_id_todo;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nametable ||'_geom_hueco_geom_ori;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nametable ||'_geom_hueco_geom_ori_unidas;';

END;
$BODY$;



CREATE OR REPLACE FUNCTION funciones.generalizar_areas(
	esch text,
	nametable text,
	tbl_salida text,
	tolerance double precision,
	simply double precision,
	pk_field character varying,
	min_area double precision,
	epsg integer)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: une los atributos iniciales a las capas generalizadas */
	EXECUTE 'create table "'|| esch ||'"."'|| nametable||'_tipo"

as select "'|| pk_field ||'", st_union (geom) as geom from "'|| esch ||'"."'|| nametable||'" group by "'|| pk_field ||'";

create table "'|| esch ||'"."'|| nametable||'_dissolve" as select "'|| pk_field ||'", (st_dump (geom)).geom as geom from "'|| esch ||'"."'|| nametable||'_tipo";
	
CREATE table "'|| esch ||'"."'|| nametable||'_dissolve_simplify"
	AS  
	SELECT "'|| pk_field ||'",
	st_simplifypreservetopology(geom, '|| simply ||')as geom
	
	FROM "'|| esch ||'"."'|| nametable||'_dissolve";
	CREATE TABLE "'|| esch ||'"."'|| nametable||'_dissolve_simplify2"
	as
	select fid, "'|| pk_field ||'",geom,st_area (geom) as area from (SELECT row_number() OVER () AS fid,
	 "'|| pk_field ||'",
	    ST_GeomFromText(ST_AsText( (ST_Dump(geom)).geom )) as geom
	    
	from "'|| esch ||'"."'|| nametable||'_dissolve_simplify")t;
	
CREATE TABLE "'|| esch ||'"."'|| nametable||'_dissolve_simplify_anillos"

AS
 SELECT "'|| nametable||'_dissolve_simplify2".fid,"'|| pk_field ||'",
    (st_dumprings(st_force2d("'|| nametable||'_dissolve_simplify2".geom))).geom AS geom,
    st_area((st_dumprings(st_force2d("'|| nametable||'_dissolve_simplify2".geom))).geom) AS area
   FROM "'|| esch ||'"."'|| nametable||'_dissolve_simplify2";
	

create table   "'|| esch ||'"."'|| nametable||'_union_simply_anillos" as SELECT fid ,
"'|| pk_field ||'",
   st_force2d(geom) as geom,
   area
FROM
  "'|| esch ||'"."'|| nametable||'_dissolve_simplify2"
UNION
SELECT fid ,
"'|| pk_field ||'",
   ST_Buffer(geom,'|| tolerance||'),
   area
FROM
  "'|| esch ||'"."'|| nametable||'_dissolve_simplify_anillos";
  
  UPDATE "'|| esch ||'"."'|| nametable||'_union_simply_anillos" SET geom=ST_makevalid(geom) WHERE NOT ST_isValid(geom);
    create table "'|| esch ||'"."'|| nametable||'_union_simply_anillos_unidos" as select st_union(geom) as geom, "'|| pk_field ||'" from  "'|| esch ||'"."'|| nametable||'_union_simply_anillos" group by "'|| pk_field ||'" 
	 ; create table "'|| esch ||'"."'|| nametable||'_union_simply_anillos_unidos_dump2" as select (st_dump(geom)).geom as geom, "'|| pk_field ||'" from  "'|| esch ||'"."'|| nametable||'_union_simply_anillos_unidos"  
;
create table "'|| esch ||'"."'|| nametable||'_union_simply_anillos_unidos_dump" as SELECT row_number() OVER () AS fid,geom, "'|| pk_field ||'" from "'|| esch ||'"."'|| nametable||'_union_simply_anillos_unidos_dump2"
;create table "'|| esch ||'"."'|| nametable||'_union" as select fid, ST_CollectionExtract(st_union(geom),3) as geom, 
"'|| pk_field ||'",
st_area(ST_CollectionExtract(st_union(geom),3)) 
from "'|| esch ||'"."'|| nametable||'_union_simply_anillos_unidos_dump"  group by fid,"'|| pk_field ||'";

create table "'|| esch ||'"."'|| nametable||'_union_area" as SELECT * FROM "'|| esch ||'"."'|| nametable||'_union"
where st_area>'''|| min_area ||''';

CREATE INDEX z_'|| nametable||'_union_area_geom_gidx
    ON "'|| esch ||'"."'|| nametable||'_union_area" USING gist
    (geom);
	
	
	create table "'|| esch ||'"."'||tbl_salida||'" as select a.*, b.geom as geom2 
	from "'|| esch ||'"."'|| nametable||'" a join
	"'|| esch ||'"."'|| nametable||'_union_area" b on a."'|| pk_field ||'" = b."'|| pk_field ||'" and st_intersects (st_setsrid(b.geom,'|| epsg||'),a.geom);
		alter table "'|| esch ||'"."'||tbl_salida||'"  drop geom;
	alter table "'|| esch ||'"."'||tbl_salida||'"  rename geom2 to geom;
	alter table "'|| esch ||'"."'||tbl_salida||'"  add column ida serial;

DELETE FROM  "'|| esch ||'"."'||tbl_salida||'"
WHERE ida IN
    (SELECT ida
    FROM 
        (SELECT ida,
         ROW_NUMBER() OVER( PARTITION BY geom
        ORDER BY  ida ) AS row_num
        FROM "'|| esch ||'"."'||tbl_salida||'") t
        WHERE t.row_num > 1 );
		CREATE INDEX z_'||tbl_salida||'_generaliced_geom_gidx
    ON "'|| esch ||'"."'||tbl_salida||'" USING gist
    (geom);
	
drop table "'|| esch ||'"."'|| nametable||'_union_area";
drop table "'|| esch ||'"."'|| nametable||'_tipo";
drop table "'|| esch ||'"."'|| nametable||'_dissolve";
drop table "'|| esch ||'"."'|| nametable||'_dissolve_simplify";
drop table "'|| esch ||'"."'|| nametable||'_dissolve_simplify2";
drop table "'|| esch ||'"."'|| nametable||'_dissolve_simplify_anillos";
drop table "'|| esch ||'"."'|| nametable||'_union_simply_anillos";
drop table "'|| esch ||'"."'|| nametable||'_union_simply_anillos_unidos";
drop table "'|| esch ||'"."'|| nametable||'_union_simply_anillos_unidos_dump2";	
drop table "'|| esch ||'"."'|| nametable||'_union_simply_anillos_unidos_dump";
drop table "'|| esch ||'"."'|| nametable||'_union";

ALTER TABLE "'|| esch ||'"."'||tbl_salida||'" ALTER COLUMN geom TYPE geometry(Geometry,'|| epsg ||') USING ST_SetSRID(geom,'|| epsg||');  ';
END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.geocoding_inverse_geopy (direccion text) RETURNS text 
AS $$

DECLARE
	sLongitud text;
	sLatitud text;
	sSql text;
BEGIN
		sSql:= '
		WITH 
			entjsonGeoloc AS
			(SELECT json_array_elements(content::json) as content
			from 
				 http
					(
						(
						''POST'',
						''http://192.168.1.43:30015/MG/externalRestAPI_call/geocoding_Inverse_geopy'',
						NULL,
						''application/json'',
						''{"user":"","input":"'||direccion||'"}''
						)::http_request
					)
			)
			SELECT 
				(content::json#>>''{lon}'')::numeric AS longitude,
				(content::json#>>''{lat}'')::numeric AS latitude

			FROM entjsonGeoloc
			LIMIT 1';
	EXECUTE sSql INTO sLongitud,sLatitud;
	--RAISE NOTICE '%, %',sLongitud,sLatitud;
	RETURN sLongitud||','||sLatitud;
END;
$$ language 'plpgsql' STRICT IMMUTABLE;


CREATE OR REPLACE FUNCTION funciones.nineintersection_matrix_mv(
	validar boolean,
	esch text,
	nameview text,
	name_table1 text,
	name_table2 text,
	matriz text)
    RETURNS text
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ 
declare geome1 character varying;
declare	geome2 character varying;
declare tab text;
declare srid1 character varying;
declare	srid2 character varying;

BEGIN

/*Descripcion: crea una vista o vista materializada que comprueba la matriz 9d y extrae si es cierto su intersección si no hay correspondencia retorna vista vacia*/
	
EXECUTE 'create table __nmtab1 as select * from "'|| esch ||'"."'|| name_table1 ||'"';
EXECUTE 'create table __nmtab2 as select * from "'|| esch ||'"."'|| name_table2 ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__nmtab1';
SELECT f_geometry_column into geome2 FROM geometry_columns  WHERE  f_table_name = '__nmtab2';
EXECUTE 'drop table __nmtab1';
EXECUTE 'drop table __nmtab2';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| name_table1 ||'" group by ST_SRID;' into srid1;
EXECUTE 'select ST_SRID("'||geome2||'") from  "'|| esch ||'"."'|| name_table2 ||'" group by ST_SRID;' into srid2;

CASE
  WHEN validar = '0' THEN
EXECUTE 'create materialized view "'|| esch ||'"."'|| nameview ||'" as 
select  ROW_NUMBER() OVER () as  fid_'|| name_table1 ||',st_setsrid(geom,4326)::geometry(Geometry, 4326) AS geom from 
(SELECT st_intersection(st_transform(st_setsrid(a.'|| geome1 ||','|| srid1 ||'),4326),st_transform(st_setsrid(b.'|| geome2 ||','|| srid2 ||'),4326)) as geom
from "'|| esch ||'"."'|| name_table1 ||'" a, "'|| esch ||'"."'|| name_table2 ||'" b
where ST_Relate(st_transform(st_setsrid(a.'|| geome1 ||','|| srid1 ||'),4326),st_transform(st_setsrid(b.'|| geome2 ||','|| srid2 ||'),4326), '''|| matriz ||''') = true)re';
EXECUTE 'create unique index on "'|| esch ||'"."'|| nameview ||'" ( fid_'|| name_table1 ||')';
ELSE tab := 'geom1';
  END CASE;
  CASE
  WHEN validar = '1' THEN
  EXECUTE 'create materialized view "'|| esch ||'"."'|| nameview ||'" as 
select  ROW_NUMBER() OVER () as fid_'|| name_table1 ||',* from (SELECT a.'|| geome1 ||',count(a.fid)as numgeomtouch
from "'|| esch ||'"."'|| name_table1 ||'" a, "'|| esch ||'"."'|| name_table2 ||'" b
where ST_Relate(st_transform(st_setsrid(a.'|| geome1 ||','|| srid1 ||'),4326),st_transform(st_setsrid(b.'|| geome2 ||','|| srid2 ||'),4326), '''|| matriz ||''') = true group by a.geom,a.fid)re';
EXECUTE 'create unique index on "'|| esch ||'"."'|| nameview ||'" ( fid_'|| name_table1 ||')';
ELSE tab := 'intersectiongeom';
END CASE;
Return tab;
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.nineintersection_matrix_vw(
	validar boolean,
	esch text,
	nameview text,
	name_table1 text,
	name_table2 text,
	matriz text)
    RETURNS text
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ 
declare geome1 character varying;
declare	geome2 character varying;
declare tab text;
declare srid1 character varying;
declare	srid2 character varying;

BEGIN

/*Descripcion: crea una vista o vista materializada que comprueba la matriz 9d y extrae si es cierto su intersección si no hay correspondencia retorna vista vacia*/
	
EXECUTE 'create table __nmtab1 as select * from "'|| esch ||'"."'|| name_table1 ||'"';
EXECUTE 'create table __nmtab2 as select * from "'|| esch ||'"."'|| name_table2 ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__nmtab1';
SELECT f_geometry_column into geome2 FROM geometry_columns  WHERE  f_table_name = '__nmtab2';
EXECUTE 'drop table __nmtab1';
EXECUTE 'drop table __nmtab2';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| name_table1 ||'" group by ST_SRID;' into srid1;
EXECUTE 'select ST_SRID("'||geome2||'") from  "'|| esch ||'"."'|| name_table2 ||'" group by ST_SRID;' into srid2;

CASE
  WHEN validar = '0' THEN
EXECUTE 'create view "'|| esch ||'"."'|| nameview ||'" as 
select  ROW_NUMBER() OVER () as  fid_'|| name_table1 ||',st_setsrid(geom,4326)::geometry(Geometry, 4326) AS geom from 
(SELECT st_intersection(st_transform(st_setsrid(a.'|| geome1 ||','|| srid1 ||'),4326),st_transform(st_setsrid(b.'|| geome2 ||','|| srid2 ||'),4326)) as geom
from "'|| esch ||'"."'|| name_table1 ||'" a, "'|| esch ||'"."'|| name_table2 ||'" b
where ST_Relate(st_transform(st_setsrid(a.'|| geome1 ||','|| srid1 ||'),4326),st_transform(st_setsrid(b.'|| geome2 ||','|| srid2 ||'),4326), '''|| matriz ||''') = true)re';
EXECUTE 'create unique index on "'|| esch ||'"."'|| nameview ||'" ( fid_'|| name_table1 ||')';
ELSE tab := 'geom1';
  END CASE;
  CASE
  WHEN validar = '1' THEN
  EXECUTE 'create view "'|| esch ||'"."'|| nameview ||'" as 
select  ROW_NUMBER() OVER () as fid_'|| name_table1 ||',* from (SELECT a.'|| geome1 ||',count(a.fid)as numgeomtouch
from "'|| esch ||'"."'|| name_table1 ||'" a, "'|| esch ||'"."'|| name_table2 ||'" b
where ST_Relate(st_transform(st_setsrid(a.'|| geome1 ||','|| srid1 ||'),4326),st_transform(st_setsrid(b.'|| geome2 ||','|| srid2 ||'),4326), '''|| matriz ||''') = true group by a.geom,a.fid)re';
ELSE tab := 'intersectiongeom';
END CASE;
Return tab;
END;
$BODY$;





CREATE OR REPLACE FUNCTION funciones.rellenar_huecos_mv(
	esch text,
	nametable text,
	nameview text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
   EXECUTE 'CREATE MATERIALIZED VIEW "'|| esch ||'"."'||nameview||'"
 AS
 SELECT st_union(st_makevalid(pol3.geom)) AS geom,
    pol3.layer_ori
   FROM ( SELECT re.fid,
            re.geom,
            re.layer_ori
           FROM ( SELECT pol3_1.bgeom,
                    pol3_1.id AS fid,
                    pol6.layer_ori,
                    pol6.area,
                    pol6.geom
                   FROM ( SELECT ra.bgeom,
                            max(ra.area) AS area,
                            ra.id
                           FROM ( SELECT re_1.bgeom,
                                    re_1.layer_ori,
                                    re_1.id,
                                    re_1.area,
                                    re_1.geom
                                   FROM ( SELECT st_area(st_intersection(pol3_2.bgeom, st_makevalid(pol6_1.geom))) AS area,
    pol6_1.layer_ori,
    pol3_2.id,
    pol3_2.bgeom,
    pol3_2.geom
   FROM ( SELECT DISTINCT ON ((st_makepolygon(ra_1.geom))) row_number() OVER () AS id,
      st_buffer(ra_1.geom, 0.00005::double precision, ''endcap=flat join=round''::text) AS bgeom,
      st_makepolygon(ra_1.geom) AS geom,
      ra_1.layer_ori
     FROM ( SELECT re_2.geom,
        re_2.contiene,
        st_touches(st_buffer(st_force2d(st_makevalid(a.geom)), 0::double precision), re_2.geom) AS st_touches,
        st_buffer(st_force2d(st_makevalid(a.geom)), 0::double precision) AS st_buffer,
        a.layer_ori
       FROM "'|| esch ||'"."'|| nametable||'" a,
        ( SELECT st_contains((st_dump(st_boundary(st_union(st_multi(st_buffer(st_force2d("'|| nametable||'".geom), 0::double precision)))))).geom, st_exteriorring(st_union(st_multi(st_buffer(st_force2d("'|| nametable||'".geom), 0::double precision))))) AS contiene,
          (st_dump(st_boundary(st_union(st_multi(st_buffer(st_force2d("'|| nametable||'".geom), 0::double precision)))))).geom AS geom
         FROM "'|| esch ||'"."'|| nametable||'") re_2) ra_1
    WHERE ra_1.contiene = ''false'' AND ra_1.st_touches = ''true'') pol3_2,
    "'|| esch ||'"."'|| nametable||'" pol6_1
  WHERE st_intersects(pol3_2.bgeom, st_makevalid(pol6_1.geom))) re_1) ra
                          GROUP BY ra.id, ra.bgeom) pol3_1
                     LEFT JOIN ( SELECT re_1.bgeom,
                            re_1.layer_ori,
                            re_1.id,
                            re_1.area,
                            re_1.geom
                           FROM ( SELECT st_area(st_intersection(pol3_2.bgeom, st_makevalid(pol6_1.geom))) AS area,
                                    pol6_1.layer_ori,
                                    pol3_2.id,
                                    pol3_2.bgeom,
                                    pol3_2.geom
                                   FROM ( SELECT DISTINCT ON ((st_makepolygon(ra.geom))) row_number() OVER () AS id,
    st_buffer(ra.geom, 0.00005::double precision, ''endcap=flat join=round''::text) AS bgeom,
    st_makepolygon(ra.geom) AS geom,
    ra.layer_ori
   FROM ( SELECT re_2.geom,
      re_2.contiene,
      st_touches(st_buffer(st_force2d(st_makevalid(a.geom)), 0::double precision), re_2.geom) AS st_touches,
      st_buffer(st_force2d(st_makevalid(a.geom)), 0::double precision) AS st_buffer,
      a.layer_ori
     FROM "'|| esch ||'"."'|| nametable||'" a,
      ( SELECT st_contains((st_dump(st_boundary(st_union(st_multi(st_buffer(st_force2d("'|| nametable||'".geom), 0::double precision)))))).geom, st_exteriorring(st_union(st_multi(st_buffer(st_force2d("'|| nametable||'".geom), 0::double precision))))) AS contiene,
        (st_dump(st_boundary(st_union(st_multi(st_buffer(st_force2d("'|| nametable||'".geom), 0::double precision)))))).geom AS geom
       FROM "'|| esch ||'"."'|| nametable||'") re_2) ra
  WHERE ra.contiene = ''false'' AND ra.st_touches = ''true'') pol3_2,
                                    "'|| esch ||'"."'|| nametable||'" pol6_1
                                  WHERE st_intersects(pol3_2.bgeom, st_makevalid(pol6_1.geom))) re_1) pol6 ON pol3_1.area = pol6.area) re
        UNION ALL
         SELECT "'|| nametable||'".fid,
            "'|| nametable||'".geom,
            "'|| nametable||'".layer_ori
           FROM "'|| esch ||'"."'|| nametable||'") pol3
  GROUP BY pol3.layer_ori;';
  END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.rellenar_huecos_tbl2(
	esch text,
	nameview text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN

EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||';';
EXECUTE 'create table  "'|| esch ||'".tmp'|| nameview ||' as select st_makevalid (geom) as geom, layer_ori from "'|| esch ||'"."'|| nameview ||'";';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||' USING gist
    (geom);';
EXECUTE 'drop table if exists "'|| esch ||'"."'|| nametable||'";';
EXECUTE 'create table "'|| esch ||'"."'|| nametable||'" as select  row_number ()over() as id_todo,* from "'|| esch ||'".tmp'|| nameview ||';';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nametable ||'_geom_gidx
    ON "'|| esch ||'"."'|| nametable||'" USING gist
    (geom);';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_union as select st_union (geom) from "'|| esch ||'".tmp'|| nameview ||';';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_union_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_union USING gist
    (st_union);';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_union_dump as select (st_dump (st_union)).geom from "'|| esch ||'".tmp'|| nameview ||'_union;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_union_dump_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_union_dump USING gist
    (geom);';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary as select st_boundary(geom) as boundary from "'|| esch ||'".tmp'|| nameview ||'_union_dump;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_union_dump_boundary_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary USING gist
    (boundary);';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior as select st_exteriorring(geom) as geom from "'|| esch ||'".tmp'|| nameview ||'_union_dump;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_union_dump_exterior_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior USING gist
    (geom);';
EXECUTE 'create table  "'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior_poligon as select ST_MakePolygon(geom) as geom from  "'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior;';
EXECUTE 'create table  "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary_dump as select (ST_dump(boundary)).geom as geom from  "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'__union_dump_exterior_poligon_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior_poligon USING gist
    (geom);';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_union_dump_boundary_dump_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary_dump USING gist
    (geom);';

	
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_dump_contains;';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_union_dump_contains as 
select a.geom as geom from  "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary_dump a,"'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior_poligon b where ST_ContainsProperly (b.geom,a.geom);';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_union_dump_contains_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_union_dump_contains USING gist
    (geom);';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_huecos;';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_union_huecos
as select st_makepolygon(geom) as geom from "'|| esch ||'".tmp'|| nameview ||'_union_dump_contains;';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_huecos_id as select row_number ()over() as id_hueco,* from  "'|| esch ||'".tmp'|| nameview ||'_union_huecos;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_huecos_id_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_huecos_id USING gist
    (geom);';
EXECUTE 'drop table if exists  "'|| esch ||'".tmp'|| nameview ||'_huecos_buffer_id;';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_huecos_buffer_id
as select id_hueco,st_buffer (geom,0.05) as geom from "'|| esch ||'".tmp'|| nameview ||'_huecos_id;';

EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_huecos_buffer_id_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_huecos_buffer_id USING gist
    (geom);';

	EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection;';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection
 as select id_todo,id_hueco,st_area(st_intersection (a.geom,b.geom)) as area,a.geom, layer_ori from "'|| esch ||'"."'|| nametable||'" a, 
 "'|| esch ||'".tmp'|| nameview ||'_huecos_buffer_id b
 where st_intersects (a.geom,b.geom);';
 EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_huecos_intersection_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection USING gist
    (geom);';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection_max;';
EXECUTE 'create table  "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection_max as select id_hueco,max(area) 
from  "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection group by id_hueco;';

EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_ori_huecos_id as select a.* from "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection a,
"'|| esch ||'".tmp'|| nameview ||'_huecos_intersection_max b where a.area =b.max and a.id_hueco = b.id_hueco;';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_ohuecos_ori_geom as select id_hueco,geom from  "'|| esch ||'".tmp'|| nameview ||'_ori_huecos_id
union all select id_hueco,geom from "'|| esch ||'".tmp'|| nameview ||'_huecos_id;';
 EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_ohuecos_ori_geom_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_ohuecos_ori_geom USING gist
    (geom);';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection_centroid as select  id_todo,id_hueco, st_pointonsurface(geom) as geom from "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection;';	
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_huecos_ori as select id_hueco,st_union(geom) as geom from "'|| esch ||'".tmp'|| nameview ||'_ohuecos_ori_geom group by id_hueco;';
 EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_huecos_intersection_centroid_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection_centroid USING gist
    (geom);';
	 EXECUTE 'create INDEX '|| esch ||'tmp'|| nameview ||'_huecos_ori_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_huecos_ori USING gist
    (geom);';
		
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_huecos_id_ori as  select a.geom,b.id_todo from "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection_centroid b, 
"'|| esch ||'".tmp'|| nameview ||'_huecos_ori a where st_intersects (a.geom,b.geom) and a.id_hueco = b.id_hueco;';
EXECUTE 'create INDEX '|| esch ||'tmp'|| nameview ||'_huecos_id_ori_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_huecos_id_ori USING gist
    (geom);';
EXECUTE 'create table  "'|| esch ||'".tmp'|| nameview ||'_huecos_id_ori_union as select 
st_union (geom),id_todo from "'|| esch ||'".tmp'|| nameview ||'_huecos_id_ori group by id_todo;';
		
EXECUTE 'update "'|| esch ||'"."'|| nametable||'" a set geom = b.st_union from 
"'|| esch ||'".tmp'|| nameview ||'_huecos_id_ori_union b
where a.id_todo = b.id_todo;';

EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||';';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_dump;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior_poligon;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary_dump;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_dump_contains;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_huecos;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_huecos_id;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_huecos_buffer_id;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection_max;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_ori_huecos_id;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_ohuecos_ori_geom;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection_centroid;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_huecos_ori;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_huecos_id_ori;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_huecos_id_ori_union;';

END;
$BODY$;



CREATE OR REPLACE FUNCTION funciones.rellenar_huecos_tbl(
	esch text,
	nameview text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN

EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||';';
EXECUTE 'create table  "'|| esch ||'".tmp'|| nameview ||' as select st_makevalid (geom) as geom, layer_ori from "'|| esch ||'"."'|| nameview ||'";';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||' USING gist
    (geom);';
EXECUTE 'drop table if exists "'|| esch ||'"."'|| nametable||'";';
EXECUTE 'create table "'|| esch ||'"."'|| nametable||'" as select  row_number ()over() as id_todo,* from "'|| esch ||'".tmp'|| nameview ||';';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nametable ||'_geom_gidx
    ON "'|| esch ||'"."'|| nametable||'" USING gist
    (geom);';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_union as select st_union (geom) from "'|| esch ||'".tmp'|| nameview ||';';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_union_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_union USING gist
    (st_union);';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_union_dump as select (st_dump (st_union)).geom from "'|| esch ||'".tmp'|| nameview ||'_union;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_union_dump_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_union_dump USING gist
    (geom);';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary as select st_boundary(geom) as boundary from "'|| esch ||'".tmp'|| nameview ||'_union_dump;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_union_dump_boundary_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary USING gist
    (boundary);';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior as select st_exteriorring(geom) as geom from "'|| esch ||'".tmp'|| nameview ||'_union_dump;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_union_dump_exterior_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior USING gist
    (geom);';
EXECUTE 'create table  "'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior_poligon as select ST_MakePolygon(geom) as geom from  "'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior;';
EXECUTE 'create table  "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary_dump as select (ST_dump(boundary)).geom as geom from  "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'__union_dump_exterior_poligon_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior_poligon USING gist
    (geom);';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_union_dump_boundary_dump_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary_dump USING gist
    (geom);';

	
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_dump_contains;';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_union_dump_contains as 
select a.geom as geom from  "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary_dump a,"'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior_poligon b where ST_ContainsProperly (b.geom,a.geom);';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_union_dump_contains_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_union_dump_contains USING gist
    (geom);';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_huecos;';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_union_huecos
as select st_makepolygon(geom) as geom from "'|| esch ||'".tmp'|| nameview ||'_union_dump_contains;';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_huecos_id as select row_number ()over() as id_hueco,* from  "'|| esch ||'".tmp'|| nameview ||'_union_huecos;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_huecos_id_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_huecos_id USING gist
    (geom);';
EXECUTE 'drop table if exists  "'|| esch ||'".tmp'|| nameview ||'_huecos_buffer_id;';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_huecos_buffer_id
as select id_hueco,st_buffer (geom,0.05) as geom from "'|| esch ||'".tmp'|| nameview ||'_huecos_id;';

EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_huecos_buffer_id_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_huecos_buffer_id USING gist
    (geom);';

	EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection;';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection
 as select id_todo,id_hueco,st_area(st_intersection (a.geom,b.geom)) as area,a.geom, layer_ori from 
 (select * from "'|| esch ||'"."'|| nametable||'" where layer_ori = ''cub'') a, 
 "'|| esch ||'".tmp'|| nameview ||'_huecos_buffer_id b
 where st_intersects (a.geom,b.geom);';
 EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_huecos_intersection_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection USING gist
    (geom);';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection_max;';
EXECUTE 'create table  "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection_max as select id_hueco,max(area) 
from  "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection group by id_hueco;';

EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_ori_huecos_id as select a.* from "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection a,
"'|| esch ||'".tmp'|| nameview ||'_huecos_intersection_max b where a.area =b.max and a.id_hueco = b.id_hueco;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_ori_huecos_id_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_ori_huecos_id USING gist
    (geom);';
	
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_id_hueco_id_todo as select  b.*,y.id_todo
from  "'|| esch ||'".tmp'|| nameview ||'_ori_huecos_id y
join "'|| esch ||'".tmp'|| nameview ||'_huecos_id b
on y.id_hueco = b.id_hueco;';

 EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_id_hueco_id_todo_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_id_hueco_id_todo USING gist
    (geom);';
	
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_geom_hueco_geom_ori as 
select geom,id_todo from "'|| esch ||'"."'|| nametable||'" 
union all select geom,id_todo
from  "'|| esch ||'".tmp'|| nameview ||'_id_hueco_id_todo;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_geom_hueco_geom_ori_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_geom_hueco_geom_ori USING gist
    (geom);';
	
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_geom_hueco_geom_ori_unidas as select 
st_union(geom),id_todo from "'|| esch ||'".tmp'|| nameview ||'_geom_hueco_geom_ori group by id_todo;';

EXECUTE 'update "'|| esch ||'"."'|| nametable||'" a set geom = b.st_union from 
"'|| esch ||'".tmp'|| nameview ||'_geom_hueco_geom_ori_unidas b
where a.id_todo = b.id_todo;';

EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||';';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_dump;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior_poligon;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary_dump;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_dump_contains;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_huecos;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_huecos_id;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_huecos_buffer_id;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection_max;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_ori_huecos_id;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_id_hueco_id_todo;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_geom_hueco_geom_ori;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_geom_hueco_geom_ori_unidas;';

END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.rellenar_huecos_tbl_todo(
	esch text,
	nameview text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN

EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||';';
EXECUTE 'create table  "'|| esch ||'".tmp'|| nameview ||' as select st_makevalid (geom) as geom, layer_ori from "'|| esch ||'"."'|| nameview ||'";';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||' USING gist
    (geom);';
EXECUTE 'drop table if exists "'|| esch ||'"."'|| nametable||'";';
EXECUTE 'create table "'|| esch ||'"."'|| nametable||'" as select  row_number ()over() as id_todo,* from "'|| esch ||'".tmp'|| nameview ||';';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nametable ||'_geom_gidx
    ON "'|| esch ||'"."'|| nametable||'" USING gist
    (geom);';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_union as select st_union (geom) from "'|| esch ||'".tmp'|| nameview ||';';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_union_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_union USING gist
    (st_union);';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_union_dump as select (st_dump (st_union)).geom from "'|| esch ||'".tmp'|| nameview ||'_union;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_union_dump_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_union_dump USING gist
    (geom);';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary as select st_boundary(geom) as boundary from "'|| esch ||'".tmp'|| nameview ||'_union_dump;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_union_dump_boundary_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary USING gist
    (boundary);';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior as select st_exteriorring(geom) as geom from "'|| esch ||'".tmp'|| nameview ||'_union_dump;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_union_dump_exterior_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior USING gist
    (geom);';
EXECUTE 'create table  "'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior_poligon as select ST_MakePolygon(geom) as geom from  "'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior;';
EXECUTE 'create table  "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary_dump as select (ST_dump(boundary)).geom as geom from  "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'__union_dump_exterior_poligon_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior_poligon USING gist
    (geom);';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_union_dump_boundary_dump_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary_dump USING gist
    (geom);';

	
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_dump_contains;';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_union_dump_contains as 
select a.geom as geom from  "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary_dump a,"'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior_poligon b where ST_ContainsProperly (b.geom,a.geom);';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_union_dump_contains_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_union_dump_contains USING gist
    (geom);';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_huecos;';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_union_huecos
as select st_makepolygon(geom) as geom from "'|| esch ||'".tmp'|| nameview ||'_union_dump_contains;';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_huecos_id as select row_number ()over() as id_hueco,* from  "'|| esch ||'".tmp'|| nameview ||'_union_huecos;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_huecos_id_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_huecos_id USING gist
    (geom);';
EXECUTE 'drop table if exists  "'|| esch ||'".tmp'|| nameview ||'_huecos_buffer_id;';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_huecos_buffer_id
as select id_hueco,st_buffer (geom,0.05) as geom from "'|| esch ||'".tmp'|| nameview ||'_huecos_id;';

EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_huecos_buffer_id_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_huecos_buffer_id USING gist
    (geom);';

	EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection;';
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection
 as select id_todo,id_hueco,st_area(st_intersection (a.geom,b.geom)) as area,a.geom, layer_ori from "'|| esch ||'"."'|| nametable||'" a, 
 "'|| esch ||'".tmp'|| nameview ||'_huecos_buffer_id b
 where st_intersects (a.geom,b.geom);';
 EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_huecos_intersection_geom_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection USING gist
    (geom);';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection_max;';
EXECUTE 'create table  "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection_max as select id_hueco,max(area) 
from  "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection group by id_hueco;';

EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_ori_huecos_id as select a.* from "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection a,
"'|| esch ||'".tmp'|| nameview ||'_huecos_intersection_max b where a.area =b.max and a.id_hueco = b.id_hueco;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_ori_huecos_id_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_ori_huecos_id USING gist
    (geom);';
	
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_id_hueco_id_todo as select  b.*,y.id_todo
from  "'|| esch ||'".tmp'|| nameview ||'_ori_huecos_id y
join "'|| esch ||'".tmp'|| nameview ||'_huecos_id b
on y.id_hueco = b.id_hueco;';

 EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_id_hueco_id_todo_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_id_hueco_id_todo USING gist
    (geom);';
	
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_geom_hueco_geom_ori as 
select geom,id_todo from "'|| esch ||'"."'|| nametable||'" 
union all select geom,id_todo
from  "'|| esch ||'".tmp'|| nameview ||'_id_hueco_id_todo;';
EXECUTE 'create INDEX '|| esch ||'_tmp'|| nameview ||'_geom_hueco_geom_ori_gidx
    ON "'|| esch ||'".tmp'|| nameview ||'_geom_hueco_geom_ori USING gist
    (geom);';
	
EXECUTE 'create table "'|| esch ||'".tmp'|| nameview ||'_geom_hueco_geom_ori_unidas as select 
st_union(geom),id_todo from "'|| esch ||'".tmp'|| nameview ||'_geom_hueco_geom_ori group by id_todo;';

EXECUTE 'update "'|| esch ||'"."'|| nametable||'" a set geom = b.st_union from 
"'|| esch ||'".tmp'|| nameview ||'_geom_hueco_geom_ori_unidas b
where a.id_todo = b.id_todo;';

EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||';';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_dump;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_dump_exterior_poligon;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_dump_boundary_dump;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_dump_contains;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_union_huecos;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_huecos_id;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_huecos_buffer_id;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_huecos_intersection_max;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_ori_huecos_id;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_id_hueco_id_todo;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_geom_hueco_geom_ori;';
EXECUTE 'drop table if exists "'|| esch ||'".tmp'|| nameview ||'_geom_hueco_geom_ori_unidas;';

END;
$BODY$;



CREATE OR REPLACE FUNCTION funciones.rellenar_huecos_vw(
	esch text,
	nametable text,
	nameview text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
   EXECUTE 'CREATE OR REPLACE VIEW "'|| esch ||'"."'||nameview||'"
 AS
 SELECT st_union(st_makevalid(pol3.geom)) AS geom,
    pol3.layer_ori
   FROM ( SELECT re.fid,
            re.geom,
            re.layer_ori
           FROM ( SELECT pol3_1.bgeom,
                    pol3_1.id AS fid,
                    pol6.layer_ori,
                    pol6.area,
                    pol6.geom
                   FROM ( SELECT ra.bgeom,
                            max(ra.area) AS area,
                            ra.id
                           FROM ( SELECT re_1.bgeom,
                                    re_1.layer_ori,
                                    re_1.id,
                                    re_1.area,
                                    re_1.geom
                                   FROM ( SELECT st_area(st_intersection(pol3_2.bgeom, st_makevalid(pol6_1.geom))) AS area,
    pol6_1.layer_ori,
    pol3_2.id,
    pol3_2.bgeom,
    pol3_2.geom
   FROM ( SELECT DISTINCT ON ((st_makepolygon(ra_1.geom))) row_number() OVER () AS id,
      st_buffer(ra_1.geom, 0.00005::double precision, ''endcap=flat join=round''::text) AS bgeom,
      st_makepolygon(ra_1.geom) AS geom,
      ra_1.layer_ori
     FROM ( SELECT re_2.geom,
        re_2.contiene,
        st_touches(st_buffer(st_force2d(st_makevalid(a.geom)), 0::double precision), re_2.geom) AS st_touches,
        st_buffer(st_force2d(st_makevalid(a.geom)), 0::double precision) AS st_buffer,
        a.layer_ori
       FROM "'|| esch ||'"."'|| nametable||'" a,
        ( SELECT st_contains((st_dump(st_boundary(st_union(st_multi(st_buffer(st_force2d("'|| nametable||'".geom), 0::double precision)))))).geom, st_exteriorring(st_union(st_multi(st_buffer(st_force2d("'|| nametable||'".geom), 0::double precision))))) AS contiene,
          (st_dump(st_boundary(st_union(st_multi(st_buffer(st_force2d("'|| nametable||'".geom), 0::double precision)))))).geom AS geom
         FROM "'|| esch ||'"."'|| nametable||'") re_2) ra_1
    WHERE ra_1.contiene = ''false'' AND ra_1.st_touches = ''true'') pol3_2,
    "'|| esch ||'"."'|| nametable||'" pol6_1
  WHERE st_intersects(pol3_2.bgeom, st_makevalid(pol6_1.geom))) re_1) ra
                          GROUP BY ra.id, ra.bgeom) pol3_1
                     LEFT JOIN ( SELECT re_1.bgeom,
                            re_1.layer_ori,
                            re_1.id,
                            re_1.area,
                            re_1.geom
                           FROM ( SELECT st_area(st_intersection(pol3_2.bgeom, st_makevalid(pol6_1.geom))) AS area,
                                    pol6_1.layer_ori,
                                    pol3_2.id,
                                    pol3_2.bgeom,
                                    pol3_2.geom
                                   FROM ( SELECT DISTINCT ON ((st_makepolygon(ra.geom))) row_number() OVER () AS id,
    st_buffer(ra.geom, 0.00005::double precision, ''endcap=flat join=round''::text) AS bgeom,
    st_makepolygon(ra.geom) AS geom,
    ra.layer_ori
   FROM ( SELECT re_2.geom,
      re_2.contiene,
      st_touches(st_buffer(st_force2d(st_makevalid(a.geom)), 0::double precision), re_2.geom) AS st_touches,
      st_buffer(st_force2d(st_makevalid(a.geom)), 0::double precision) AS st_buffer,
      a.layer_ori
     FROM "'|| esch ||'"."'|| nametable||'" a,
      ( SELECT st_contains((st_dump(st_boundary(st_union(st_multi(st_buffer(st_force2d("'|| nametable||'".geom), 0::double precision)))))).geom, st_exteriorring(st_union(st_multi(st_buffer(st_force2d("'|| nametable||'".geom), 0::double precision))))) AS contiene,
        (st_dump(st_boundary(st_union(st_multi(st_buffer(st_force2d("'|| nametable||'".geom), 0::double precision)))))).geom AS geom
       FROM "'|| esch ||'"."'|| nametable||'") re_2) ra
  WHERE ra.contiene = ''false'' AND ra.st_touches = ''true'') pol3_2,
                                    "'|| esch ||'"."'|| nametable||'" pol6_1
                                  WHERE st_intersects(pol3_2.bgeom, st_makevalid(pol6_1.geom))) re_1) pol6 ON pol3_1.area = pol6.area) re
        UNION ALL
         SELECT "'|| nametable||'".fid,
            "'|| nametable||'".geom,
            "'|| nametable||'".layer_ori
           FROM "'|| esch ||'"."'|| nametable||'") pol3
  GROUP BY pol3.layer_ori;';
  END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.renombrar_multiples_tablas(
	_schema text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
    row record;
BEGIN
    FOR row IN 
        SELECT
            table_name,
			table_schema
        FROM
             information_schema.tables 
        where
            table_schema = ''||_schema || ''
    LOOP
        EXECUTE 'Alter TABLE "'||row.table_schema||'"."'||row.table_name||'" rename to "'||row.table_name||'_ft"';
        EXECUTE 'create table TABLE "'||row.table_schema||'"."'||row.table_name||'" as select * from    "'||row.table_schema||'"."'||row.table_name||'_ft"';
    END LOOP;
END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.sacar_puntos_erroneos_mv2(
	esch text,
	nameview text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ BEGIN
EXECUTE 'create materialized view "'|| esch ||'"."'|| nameview ||'" as (select distinct on (ra.geom)  st_pointonsurface (ra.geom) as geom,  ra.fid, 
  ''hollow space'' as errores from 
(select  re.geom, re.contiene, ST_touches (ST_Buffer(st_force2d(st_makevalid(a.geom)),0),re.geom), ST_Buffer(st_force2d(st_makevalid(a.geom)),0),fid 
 FROM "'|| esch ||'"."'|| nametable||'" a, (SELECT  st_contains (((st_dump (ST_Boundary(st_union(ST_Multi(ST_Buffer(st_force2d(geom),0)))))).geom),
		ST_ExteriorRing(st_union(ST_Multi(ST_Buffer(st_force2d(geom),0))))) as contiene, 
		((st_dump (ST_Boundary(st_union(ST_Multi(ST_Buffer(st_force2d(geom),0)))))).geom)  AS geom
	   FROM "'|| esch ||'"."'|| nametable||'") re) ra
 where ra.contiene = ''false'' and ra.st_touches = ''true'')
UNION ALL
(SELECT re.re as geom, re.fid, ra.ra as errores
   FROM (SELECT ST_SetSRID(ST_MakePoint (a[2]::double precision,  a[4]::double precision),4326) as re, fid 
		 from  
		(select regexp_split_to_array( to_tsvector(ST_IsValidReason(st_force2d(geom)))::text,''''''''), fid FROM "'|| esch ||'"."'|| nametable||'" WHERE NOT ST_IsValid(geom))as dt(a)) re, 
		(select ST_IsValidReason(geom) as ra, fid  fROM "'|| esch ||'"."'|| nametable||'" WHERE NOT ST_IsValid(geom)) ra where ra.fid = re.fid)';
   
	END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.sacar_puntos_erroneos_mv(
	esch text,
	nameview text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ declare 
geome1 text;
srid1 text;
camposc text;
BEGIN
/*Descripcion: Saca errores topológicos */

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| nametable ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| nametable ||'" group by ST_SRID;' into srid1;

Execute 'create materialized view "'|| esch ||'"."'|| nameview ||'" as select row_number() OVER () AS id'|| nametable||', id, error,
st_transform(St_setsrid(Geom,'||srid1||'),4326)::geometry(Geometry, 4326) as geom from( 
select gid1 as id,concat(''geometries with union points'','':'','' id '',gid1,'' y '',gid2) as "error", seudogeom as geom from 
(select c1.id as gid1, max (c2.id) as gid2, c1.geom as seudogeom,
count (*) as num from  (select (st_dumppoints("'||geome1||'")).geom, id from "'|| esch ||'"."'|| nametable ||'") c1, 
 (select (st_dumppoints("'||geome1||'")).geom as geoml, "'||geome1||'", id from "'|| esch ||'"."'|| nametable ||'") c2 where c1.id<>c2.id
and c1.geom && c2.geom and (st_distance (c1.geom,c2.geoml))=0 
group by c1.id,c1.geom)as tabla where num = 1
								  

union all

select id1 as id,''Junctions without union'' as errores, geom from (select r1.id as id1, r2.id as id2, r1.geom from 
(select a.id,(st_dumppoints(st_intersection(st_buffer(a."'||geome1||'",0),st_buffer(b."'||geome1||'",0)))).geom as geom
from "'|| esch ||'"."'|| nametable ||'" a, "'|| esch ||'"."'|| nametable ||'" b 
where a."'||geome1||'" && b."'||geome1||'" and st_relate (st_buffer(a."'||geome1||'",0),st_buffer(b."'||geome1||'",0), ''T********'') and a.id>b.id) r1
left join (select (st_dumppoints("'||geome1||'")).geom, id from "'|| esch ||'"."'|| nametable ||'") r2
on st_distance (r1.geom,r2.geom) = 0) as tabla where id2 is null 

union all

select id1 as id,''Points without union'' as errores, point as geom from(select r1.geom as point, r1.id as id1, r2.id as id2
from (select (st_dumppoints("'||geome1||'")).geom, id from "'|| esch ||'"."'|| nametable ||'") r1 
	  left join "'|| esch ||'"."'|| nametable ||'" r2 
on r1.id<>r2.id and st_expand (r1.geom,1000) && r2."'||geome1||'" and st_distance (r1.geom,r2."'||geome1||'") = 0)
as tabla where id2 is null

union all

select distinct on (ra.geom)  ra.id, 
  ''Hollow space'' as errores,st_centroid (ra.geom) as geom from 
(select  re.geom, re.contiene, ST_touches (ST_Buffer(st_force2d(st_makevalid(a."'||geome1||'")),0),re.geom), ST_Buffer(st_force2d(st_makevalid(a."'||geome1||'")),0),id 
 FROM "'|| esch ||'"."'|| nametable ||'" a, (SELECT  st_contains (((st_dump (ST_Boundary(st_union(ST_Multi(ST_Buffer(st_force2d("'||geome1||'"),0)))))).geom),
		ST_ExteriorRing((st_dump(st_union(ST_Multi(ST_Buffer(st_force2d("'||geome1||'"),0))))).geom)) as contiene, 
		((st_dump (ST_Boundary(st_union(ST_Multi(ST_Buffer(st_force2d("'||geome1||'"),0)))))).geom)  AS geom
	   FROM "'|| esch ||'"."'|| nametable ||'") re) ra
 where ra.contiene is null and ra.st_touches = ''true''

union all

select gida as id,''Isolated geometry'' as "error",ST_PointOnSurface(st_makepolygon((st_dump(ST_CollectionExtract(contorno,2))).geom)) 
from (select t1.id as gida, st_multi (st_boundary(t1."'||geome1||'")) as contorno, t2.id as gidb
from "'|| esch ||'"."'|| nametable ||'" t1 left join "'|| esch ||'"."'|| nametable ||'" t2
on t1.id<>t2.id and st_intersects (t1."'||geome1||'",t2."'||geome1||'")) as tabla where gidb is null

union all

select id,''Repeated vertex'' as "error", ST_PointOnSurface(geomp) as geom 
from (select *, (st_dumppoints ("'||geome1||'")).geom as geomp from "'|| esch ||'"."'|| nametable ||'" 
where not st_asewkb(st_removerepeatedpoints ("'||geome1||'")) = st_asewkb ("'||geome1||'"))r
GROUP BY id,geomp
     HAVING COUNT(*)>1
	 
union all

select a.id,concat(''
duplicate geometry'','':'','' id original '',b.id) as "error", ST_PointOnSurface(a."'||geome1||'") as geom
from "'|| esch ||'"."'|| nametable ||'" a, "'|| esch ||'"."'|| nametable ||'" b 
where a.id>b.id and ST_Equals(ST_SnapToGrid(a."'||geome1||'", 0.005), ST_SnapToGrid(b."'||geome1||'", 0.005))

union all

select a.id,concat(''overlapping geometries'','':'','' id '',a.id,'' y '',b.id) as "error",ST_PointOnSurface(st_intersection(st_buffer(a."'||geome1||'",0),st_buffer(b."'||geome1||'",0))) as geom
from "'|| esch ||'"."'|| nametable ||'" a, "'|| esch ||'"."'|| nametable ||'" b 
where a."'||geome1||'" && b."'||geome1||'" and st_relate (st_buffer(a."'||geome1||'",0),st_buffer(b."'||geome1||'",0), ''T********'') and a.id>b.id)re';
EXECUTE 'create unique index on "'|| esch ||'"."'|| nameview ||'" (id'|| nametable||')';
END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.sacar_puntos_erroneos_vw2(
	esch text,
	nameview text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ BEGIN
EXECUTE 'create view "'|| esch ||'"."'|| nameview ||'" as (select distinct on (ra.geom)  st_pointonsurface (ra.geom) as geom,  ra.fid, 
  ''hollow space'' as errores from 
(select  re.geom, re.contiene, ST_touches (ST_Buffer(st_force2d(st_makevalid(a.geom)),0),re.geom), ST_Buffer(st_force2d(st_makevalid(a.geom)),0),fid 
 FROM "'|| esch ||'"."'|| nametable||'" a, (SELECT  st_contains (((st_dump (ST_Boundary(st_union(ST_Multi(ST_Buffer(st_force2d(geom),0)))))).geom),
		ST_ExteriorRing(st_union(ST_Multi(ST_Buffer(st_force2d(geom),0))))) as contiene, 
		((st_dump (ST_Boundary(st_union(ST_Multi(ST_Buffer(st_force2d(geom),0)))))).geom)  AS geom
	   FROM "'|| esch ||'"."'|| nametable||'") re) ra
 where ra.contiene = ''false'' and ra.st_touches = ''true'')
UNION ALL
(SELECT re.re as geom, re.fid, ra.ra as errores
   FROM (SELECT ST_SetSRID(ST_MakePoint (a[2]::double precision,  a[4]::double precision),4326) as re, fid 
		 from  
		(select regexp_split_to_array( to_tsvector(ST_IsValidReason(st_force2d(geom)))::text,''''''''), fid FROM "'|| esch ||'"."'|| nametable||'" WHERE NOT ST_IsValid(geom))as dt(a)) re, 
		(select ST_IsValidReason(geom) as ra, fid  fROM "'|| esch ||'"."'|| nametable||'" WHERE NOT ST_IsValid(geom)) ra where ra.fid = re.fid)';
   
	END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.sacar_puntos_erroneos_vw(
	esch text,
	nameview text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ declare 
geome1 text;
srid1 text;
camposc text;
BEGIN
/*Descripcion: Saca errores topológicos */

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| nametable ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| nametable ||'" group by ST_SRID;' into srid1;

Execute 'create view "'|| esch ||'"."'|| nameview ||'" as select row_number() OVER () AS id'|| nametable||', id, error,
st_transform(St_setsrid(Geom,'||srid1||'),4326)::geometry(Geometry, 4326) as geom from( 
select gid1 as id,concat(''geometries with union points'','':'','' id '',gid1,'' y '',gid2) as "error", seudogeom as geom from 
(select c1.id as gid1, max (c2.id) as gid2, c1.geom as seudogeom,
count (*) as num from  (select (st_dumppoints("'||geome1||'")).geom, id from "'|| esch ||'"."'|| nametable ||'") c1, 
 (select (st_dumppoints("'||geome1||'")).geom as geoml, "'||geome1||'", id from "'|| esch ||'"."'|| nametable ||'") c2 where c1.id<>c2.id
and c1.geom && c2.geom and (st_distance (c1.geom,c2.geoml))=0 
group by c1.id,c1.geom)as tabla where num = 1
								  

union all

select id1 as id,''Junctions without union'' as errores, geom from (select r1.id as id1, r2.id as id2, r1.geom from 
(select a.id,(st_dumppoints(st_intersection(st_buffer(a."'||geome1||'",0),st_buffer(b."'||geome1||'",0)))).geom as geom
from "'|| esch ||'"."'|| nametable ||'" a, "'|| esch ||'"."'|| nametable ||'" b 
where a."'||geome1||'" && b."'||geome1||'" and st_relate (st_buffer(a."'||geome1||'",0),st_buffer(b."'||geome1||'",0), ''T********'') and a.id>b.id) r1
left join (select (st_dumppoints("'||geome1||'")).geom, id from "'|| esch ||'"."'|| nametable ||'") r2
on st_distance (r1.geom,r2.geom) = 0) as tabla where id2 is null 

union all

select id1 as id,''Points without union'' as errores, point as geom from(select r1.geom as point, r1.id as id1, r2.id as id2
from (select (st_dumppoints("'||geome1||'")).geom, id from "'|| esch ||'"."'|| nametable ||'") r1 
	  left join "'|| esch ||'"."'|| nametable ||'" r2 
on r1.id<>r2.id and st_expand (r1.geom,1000) && r2."'||geome1||'" and st_distance (r1.geom,r2."'||geome1||'") = 0)
as tabla where id2 is null

union all

select distinct on (ra.geom)  ra.id, 
  ''Hollow space'' as errores,st_centroid (ra.geom) as geom from 
(select  re.geom, re.contiene, ST_touches (ST_Buffer(st_force2d(st_makevalid(a."'||geome1||'")),0),re.geom), ST_Buffer(st_force2d(st_makevalid(a."'||geome1||'")),0),id 
 FROM "'|| esch ||'"."'|| nametable ||'" a, (SELECT  st_contains (((st_dump (ST_Boundary(st_union(ST_Multi(ST_Buffer(st_force2d("'||geome1||'"),0)))))).geom),
		ST_ExteriorRing((st_dump(st_union(ST_Multi(ST_Buffer(st_force2d("'||geome1||'"),0))))).geom)) as contiene, 
		((st_dump (ST_Boundary(st_union(ST_Multi(ST_Buffer(st_force2d("'||geome1||'"),0)))))).geom)  AS geom
	   FROM "'|| esch ||'"."'|| nametable ||'") re) ra
 where ra.contiene is null and ra.st_touches = ''true''

union all

select gida as id,''Isolated geometry'' as "error",ST_PointOnSurface(st_makepolygon((st_dump(ST_CollectionExtract(contorno,2))).geom)) 
from (select t1.id as gida, st_multi (st_boundary(t1."'||geome1||'")) as contorno, t2.id as gidb
from "'|| esch ||'"."'|| nametable ||'" t1 left join "'|| esch ||'"."'|| nametable ||'" t2
on t1.id<>t2.id and st_intersects (t1."'||geome1||'",t2."'||geome1||'")) as tabla where gidb is null

union all

select id,''Repeated vertex'' as "error", ST_PointOnSurface(geomp) as geom 
from (select *, (st_dumppoints ("'||geome1||'")).geom as geomp from "'|| esch ||'"."'|| nametable ||'" 
where not st_asewkb(st_removerepeatedpoints ("'||geome1||'")) = st_asewkb ("'||geome1||'"))r
GROUP BY id,geomp
     HAVING COUNT(*)>1
	 
union all

select a.id,concat(''
duplicate geometry'','':'','' id original '',b.id) as "error", ST_PointOnSurface(a."'||geome1||'") as geom
from "'|| esch ||'"."'|| nametable ||'" a, "'|| esch ||'"."'|| nametable ||'" b 
where a.id>b.id and ST_Equals(ST_SnapToGrid(a."'||geome1||'", 0.005), ST_SnapToGrid(b."'||geome1||'", 0.005))

union all

select a.id,concat(''overlapping geometries'','':'','' id '',a.id,'' y '',b.id) as "error",ST_PointOnSurface(st_intersection(st_buffer(a."'||geome1||'",0),st_buffer(b."'||geome1||'",0))) as geom
from "'|| esch ||'"."'|| nametable ||'" a, "'|| esch ||'"."'|| nametable ||'" b 
where a."'||geome1||'" && b."'||geome1||'" and st_relate (st_buffer(a."'||geome1||'",0),st_buffer(b."'||geome1||'",0), ''T********'') and a.id>b.id)re';
EXECUTE 'create unique index on "'|| esch ||'"."'|| nameview ||'" (id'|| nametable||')';
END;
$BODY$;





CREATE OR REPLACE FUNCTION funciones.seleccion_total_vw(
	esch text,
	nameview text,
	nametable text,
	contenido text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: hace una busqueda por el contenido que se añada en el where */
	EXECUTE 'create view "'|| esch ||'"."'|| nameview ||'"
as select * from "'|| esch ||'"."'|| nametable||'" where  '|| contenido ||'';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.seleccion_total_mv(
	esch text,
	nameview text,
	nametable text,
	contenido text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: hace una busqueda por el contenido que se añada en el where */
	EXECUTE 'create materialized view "'|| esch ||'"."'|| nameview ||'"
as select * from "'|| esch ||'"."'|| nametable||'" where  '|| contenido ||'';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.topotoleranceloop(
	esquema_dest text,
	destino text,
	anedge integer,
	maxtolerance double precision)
    RETURNS double precision
    LANGUAGE 'plpgsql'

    COST 100
    STABLE STRICT 
AS $BODY$DECLARE
  tol float8;
  sql varchar;
BEGIN
  tol := maxtolerance;
  LOOP
        sql := 'select topology.toTopoGeom(geom,''topo_'||destino||''', 1,' || tol || ')
		from "'||esquema_dest||'"."'||destino||'_topo"';
        BEGIN
          RAISE DEBUG 'Running %', sql;
          EXECUTE sql;
          RETURN tol;
        EXCEPTION
         WHEN OTHERS THEN
          RAISE WARNING 'Simplification of edge % with tolerance % failed: %', anedge, tol, SQLERRM;
          tol := round( (tol/1.25) * 1e8 ) / 1e8; -- round to get to zero quicker
          IF tol = 0 THEN RAISE EXCEPTION '%', SQLERRM; END IF;
        END;
  END LOOP;
END
$BODY$;




CREATE OR REPLACE FUNCTION funciones.union_de_atributos_por_centrodies_mv(
	esch text,
	nameview text,
	nametable_geom text,
	tabla_centroides text,
	contenido text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ declare colum character varying;
BEGIN
	/*Descripcion: une los atributos iniciales a las capas generalizadas */
	EXECUTE 'create materialized view  "'|| esch ||'"."'|| nameview ||'" as SELECT 
	'|| contenido ||',a.geom 
 FROM (SELECT '|| contenido ||',
          b.geom,
          st_contains(b.geom, a.centroid) AS st_contains
         FROM "'|| esch ||'"."'|| nametable_geom||'" b,
          "'|| esch ||'"."'||tabla_centroides||'" a ) a WHERE a.st_contains = ''true''';

END; $BODY$;



CREATE OR REPLACE FUNCTION funciones.union_de_atributos_por_centrodies_tbl(
	esch text,
	nameview text,
	nametable_geom text,
	tabla_centroides text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ declare colum character varying;
BEGIN

EXECUTE 'drop table if exists  "'|| esch ||'".centroides;';
EXECUTE 'create table  "'|| esch ||'".centroides as SELECT * FROM  "'|| esch ||'"."'||tabla_centroides||'";';
EXECUTE 'alter table  "'|| esch ||'".centroides drop column geom;';
EXECUTE 'alter table  "'|| esch ||'".centroides rename centroid to geom;';
EXECUTE 'create INDEX ZxasCabW7iWwiBeL8_centroides_geom_gidx
    ON  "'|| esch ||'".centroides USING gist
    (geom);';
	
EXECUTE 'drop table if exists  "'|| esch ||'".cubierta;';
EXECUTE 'create table   "'|| esch ||'".cubierta as select  geom ,layer_ori,row_number ()over() as id_srm from  "'|| esch ||'"."'|| nametable_geom||'"
group by layer_ori, geom;';
EXECUTE 'drop table if exists  "'|| esch ||'".cubierta_centroides;';
EXECUTE 'create table  "'|| esch ||'".cubierta_centroides
as select layer_ori,st_pointonsurface(geom) as geom, id_srm from  "'|| esch ||'".cubierta;';

EXECUTE 'create INDEX ZxasCabW7iWwiBeL8_cubierta_centroides_geom_gidx
    ON  "'|| esch ||'".cubierta_centroides USING gist
    (geom);';

EXECUTE 'drop table if exists  "'|| esch ||'".cubierta_centroides_valores;';
EXECUTE 'create table   "'|| esch ||'".cubierta_centroides_valores as
SELECT DISTINCT ON (h.geom) s.*, h.id_srm,
			h.geom as geom_cubier
		   FROM  "'|| esch ||'".centroides s
			 LEFT JOIN  "'|| esch ||'".cubierta_centroides h 
			 ON st_dwithin(h.geom, s.geom, 200::double precision)
		  ORDER BY h.geom, (st_distance(h.geom, s.geom));';

EXECUTE 'alter table  "'|| esch ||'".cubierta_centroides_valores drop column geom;';
EXECUTE 'alter table  "'|| esch ||'".cubierta_centroides_valores rename geom_cubier to geom;';

EXECUTE 'drop table if exists  "'|| esch ||'"."'|| nameview ||'";';
EXECUTE 'create table  "'|| esch ||'"."'|| nameview ||'" 
as select a.*,b.geom as geom2 from  "'|| esch ||'".cubierta b,
 "'|| esch ||'".cubierta_centroides_valores a where a.id_srm = b.id_srm;';
EXECUTE 'alter table  "'|| esch ||'"."'|| nameview ||'" drop column geom;';
EXECUTE 'alter table  "'|| esch ||'"."'|| nameview ||'" rename geom2 to geom;';
EXECUTE 'alter table  "'|| esch ||'"."'|| nameview ||'" drop column if exists ogc_fid;';
EXECUTE 'alter table  "'|| esch ||'"."'|| nameview ||'" drop column if exists id_srm;';
EXECUTE 'update  "'|| esch ||'"."'|| nameview ||'" set shape_leng = ST_Perimeter(geom);';
EXECUTE 'update  "'|| esch ||'"."'|| nameview ||'" set shape_area = ST_area(geom);';

EXECUTE 'drop table if exists  "'|| esch ||'".centroides;';
EXECUTE 'drop table if exists  "'|| esch ||'".cubierta;';
EXECUTE 'drop table if exists  "'|| esch ||'".cubierta_centroides;';
EXECUTE 'drop table if exists  "'|| esch ||'".cubierta_centroides_valores;';

END; $BODY$;


CREATE OR REPLACE FUNCTION funciones.union_de_atributos_por_centrodies_vw(
	esch text,
	nameview text,
	nametable_geom text,
	tabla_centroides text,
	contenido text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$ declare colum character varying;
BEGIN
	/*Descripcion: une los atributos iniciales a las capas generalizadas */
	EXECUTE 'create view  "'|| esch ||'"."'|| nameview ||'" as SELECT 
	'|| contenido ||',a.geom 
 FROM (SELECT '|| contenido ||',
          b.geom,
          st_contains(b.geom, a.centroid) AS st_contains
         FROM "'|| esch ||'"."'|| nametable_geom||'" b,
          "'|| esch ||'"."'||tabla_centroides||'" a ) a WHERE a.st_contains = ''true''';

END; $BODY$;




CREATE OR REPLACE FUNCTION funciones.union_multiple_mw(
	_schema text,
	_nameview text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
   _safe_target text := quote_ident(_schema) || '.' || quote_ident(_nameview);
BEGIN
 
   EXECUTE (
      SELECT 'CREATE materialized view ' || _safe_target || ' AS TABLE '
          || string_agg(quote_ident(table_schema) || '.'
                     || quote_ident(table_name), ' UNION ALL TABLE ')
      FROM   information_schema.views
      WHERE  table_schema = _schema
      AND    table_name LIKE ('paraunion%')
   );
END
$BODY$;

CREATE OR REPLACE FUNCTION funciones.union_multiple_rail2_mw(
	_schema text,
	_nameview text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
   _safe_target text := quote_ident(_schema) || '.' || quote_ident(_nameview);
BEGIN
 
   EXECUTE (
      SELECT 'CREATE materialized view ' || _safe_target || ' AS TABLE '
          || string_agg(quote_ident(table_schema) || '.'
                     || quote_ident(table_name), ' UNION ALL TABLE ')
      FROM   information_schema.views
      WHERE  table_schema = _schema
      AND    table_name LIKE ('paraunionrail%')
   );
END
$BODY$;


CREATE OR REPLACE FUNCTION funciones.union_multiple_rail2_vw(
	_schema text,
	_nameview text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
   _safe_target text := quote_ident(_schema) || '.' || quote_ident(_nameview);
BEGIN
 
   EXECUTE (
      SELECT 'CREATE view ' || _safe_target || ' AS TABLE '
          || string_agg(quote_ident(table_schema) || '.'
                     || quote_ident(table_name), ' UNION ALL TABLE ')
      FROM   information_schema.views
      WHERE  table_schema = _schema
      AND    table_name LIKE ('paraunionrail%')
   );
END
$BODY$;




CREATE OR REPLACE FUNCTION funciones.union_multiple_vw(
	_schema text,
	_nameview text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
   _safe_target text := quote_ident(_schema) || '.' || quote_ident(_nameview);
BEGIN
 
   EXECUTE (
      SELECT 'CREATE view ' || _safe_target || ' AS TABLE '
          || string_agg(quote_ident(table_schema) || '.'
                     || quote_ident(table_name), ' UNION ALL TABLE ')
      FROM   information_schema.views
      WHERE  table_schema = _schema
      AND    table_name LIKE ('paraunion%')
   );
END
$BODY$;




CREATE OR REPLACE FUNCTION funciones.verficar_datos_mv(
	campo text,
	valor text,
	esch text,
	nameview text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: verifica datos */
	EXECUTE 'CREATE  MATERIALIZED VIEW "'|| esch ||'"."'|| nameview ||'" AS SELECT * FROM "'|| esch ||'"."'|| nametable||'"  
	where "'|| campo ||'" = '''|| valor ||'''';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.verficar_datos_vw(
	campo text,
	valor text,
	esch text,
	nameview text,
	nametable text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$BEGIN
	/*Descripcion: verifica datos */
	EXECUTE 'CREATE  VIEW "'|| esch ||'"."'|| nameview ||'" AS SELECT * FROM "'|| esch ||'"."'|| nametable||'"  
	where "'|| campo ||'" = '''|| valor ||'''';

END;
$BODY$;



CREATE OR REPLACE FUNCTION funciones.zzloop(
	)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE 
   r geometry;
BEGIN
FOR r IN 
   SELECT geom
   FROM   "ZxasCabW7iWwiBeL8".edipbpruebaarea
LOOP
   BEGIN -- may be unnecessary
      UPDATE "ZxasCabW7iWwiBeL8".llenar
      SET    geom = st_union (geom,r);
   EXCEPTION when others
      THEN UPDATE "ZxasCabW7iWwiBeL8".llenar
      SET    geom = st_union (geom,r);
   END;
END LOOP;
END
$BODY$;




CREATE OR REPLACE FUNCTION funciones.concavehull_mv(
	esch text,
	tbl_entrada text,
	vw_salida text,
	contenido text,
	porcentaje text,
	holes text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geome1 text;
srid1 text;
BEGIN

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tbl_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| tbl_entrada ||'" group by ST_SRID;' into srid1;

EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'" as 
select '|| contenido ||' 
st_transform(st_setsrid(ST_ConcaveHull(st_force2d("'||geome1||'"),'||porcentaje||','||holes||'), '||srid1||'),4326)::geometry(Geometry, 4326) AS geom
from "'||esch||'"."'||tbl_entrada||'";';

END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.concavehull_union_mv(
	esch text,
	tbl_entrada text,
	vw_salida text,
	porcentaje text,
	holes text,
	simplify text,
	buff text,
	area_min text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geome1 text;
srid1 text;
BEGIN
/*ejemplo se saca un casco urbano,
simplify simplificación previa de las geometrías para mejorar la velocidad
buff distancia a la que se genera un buffer para unir geometrías colindantes
area_min area a la cual no aparecerán los geometrías*/

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tbl_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| tbl_entrada ||'" group by ST_SRID;' into srid1;

EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'" as select
row_number() OVER () AS id_srm, st_transform(st_setsrid(geom,'||srid1||'),4326)::geometry(Geometry, 4326) AS geom from  (select (st_dump(st_union(geom))).geom from (select ST_ConcaveHull
(st_buffer
((st_dump(st_union(st_buffer(st_simplify('||geome1||','||simplify||'),'||buff||',''endcap=flat'')))).geom
,-'||buff||',''endcap=flat''),'||porcentaje||','||holes||') as geom
from "'||esch||'"."'||tbl_entrada||'")a)a
where st_area (geom) > '||area_min||';';

END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.concavehull_union_vw(
	esch text,
	tbl_entrada text,
	vw_salida text,
	porcentaje text,
	holes text,
	simplify text,
	buff text,
	area_min text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geome1 text;
srid1 text;
BEGIN

/*ejemplo se saca un casco urbano,
simplify simplificación previa de las geometrías para mejorar la velocidad
buff distancia a la que se genera un buffer para unir geometrías colindantes
area_min area a la cual no aparecerán los geometrías*/

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tbl_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| tbl_entrada ||'" group by ST_SRID;' into srid1;

EXECUTE 'create view "'||esch||'"."'||vw_salida||'" as select
row_number() OVER () AS id_srm, st_transform(st_setsrid(geom,'||srid1||'),4326)::geometry(Geometry, 4326) AS geom from  (select (st_dump(st_union(geom))).geom from (select ST_ConcaveHull
(st_buffer
((st_dump(st_union(st_buffer(st_simplify('||geome1||','||simplify||'),'||buff||',''endcap=flat'')))).geom
,-'||buff||',''endcap=flat''),'||porcentaje||','||holes||') as geom
from "'||esch||'"."'||tbl_entrada||'")a)a
where st_area (geom) > '||area_min||';';

END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.concavehull_vw(
	esch text,
	tbl_entrada text,
	vw_salida text,
	contenido text,
	porcentaje text,
	holes text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geome1 text;
srid1 text;
BEGIN

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tbl_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| tbl_entrada ||'" group by ST_SRID;' into srid1;

EXECUTE 'create view "'||esch||'"."'||vw_salida||'" as 
select '|| contenido ||' 
st_transform(st_setsrid(ST_ConcaveHull(st_force2d("'||geome1||'"),'||porcentaje||','||holes||'), '||srid1||'),4326)::geometry(Geometry, 4326) AS geom
from "'||esch||'"."'||tbl_entrada||'";';

END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.convexhull_mv(
	esch text,
	tbl_entrada text,
	vw_salida text,
	contenido text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geome1 text;
srid1 text;
BEGIN

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tbl_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| tbl_entrada ||'" group by ST_SRID;' into srid1;

EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'" as 
select '|| contenido ||' st_transform(st_setsrid(ST_ConvexHull('||geome1||'), '||srid1||'),4326)::geometry(Geometry, 4326) AS geom 
from "'||esch||'"."'||tbl_entrada||'";';

END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.convexhull_union_mv(
	esch text,
	tbl_entrada text,
	vw_salida text,
	simplify text,
	buff text,
	area_min text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geome1 text;
srid1 text;
BEGIN
--ejemplo se saca un casco urbano

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tbl_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| tbl_entrada ||'" group by ST_SRID;' into srid1;

EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'" as select
row_number() OVER () AS id_srm, st_transform(st_setsrid(geom, '||srid1||'),4326)::geometry(Geometry, 4326) AS geom from (select (st_dump(st_union(geom))).geom from 
(select ST_ConvexHull (st_buffer((st_dump(st_union(st_buffer
(st_simplify(st_force2d('||geome1||'),'||simplify||'),'||buff||',''endcap=flat''))))
.geom,-'||buff||',''endcap=flat'')) as geom
from "'||esch||'"."'||tbl_entrada||'")a)a
where st_area (geom) > '||area_min||';';
END;
$BODY$;



CREATE OR REPLACE FUNCTION funciones.convexhull_union_vw(
	esch text,
	tbl_entrada text,
	vw_salida text,
	simplify text,
	buff text,
	area_min text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geome1 text;
srid1 text;
BEGIN
--ejemplo se saca un casco urbano

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tbl_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| tbl_entrada ||'" group by ST_SRID;' into srid1;

EXECUTE 'create view "'||esch||'"."'||vw_salida||'" as select
row_number() OVER () AS id_srm, st_transform(st_setsrid(geom, '||srid1||'),4326)::geometry(Geometry, 4326) AS geom from (select (st_dump(st_union(geom))).geom from 
(select ST_ConvexHull (st_buffer((st_dump(st_union(st_buffer
(st_simplify(st_force2d('||geome1||'),'||simplify||'),'||buff||',''endcap=flat''))))
.geom,-'||buff||',''endcap=flat'')) as geom
from "'||esch||'"."'||tbl_entrada||'")a)a
where st_area (geom) > '||area_min||';';
END;
$BODY$;



CREATE OR REPLACE FUNCTION funciones.convexhull_vw(
	esch text,
	tbl_entrada text,
	vw_salida text,
	contenido text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geome1 text;
srid1 text;
BEGIN

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tbl_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| tbl_entrada ||'" group by ST_SRID;' into srid1;

EXECUTE 'create view "'||esch||'"."'||vw_salida||'" as 
select '|| contenido ||' st_transform(st_setsrid(ST_ConvexHull('||geome1||'), '||srid1||'),4326)::geometry(Geometry, 4326) AS geom 
from "'||esch||'"."'||tbl_entrada||'";';

END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.crear_tabla_desde_foreign(
	schema_entrada text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
    row     record;
BEGIN
    FOR row IN 
        SELECT
            table_schema,
            table_name
        FROM
            information_schema.tables
        WHERE
            table_schema = ''||schema_entrada ||''
     
    LOOP
		execute 'create table "'||schema_entrada ||'"."'||row.table_name||'2" as select 
* from "'||schema_entrada ||'"."'||row.table_name||'";

CREATE INDEX "'||schema_entrada ||'_'||row.table_name||'_geom_gist"
    ON "'||schema_entrada ||'"."'||row.table_name||'2" USING gist
    (geom);
	
drop foreign table "'||schema_entrada ||'"."'||row.table_name||'";

alter table "'||schema_entrada ||'"."'||row.table_name||'2" rename to "'||row.table_name||'"';
    END LOOP;
END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.difference_dump_mv(
	esch text,
	tbl_entrada_a_cortar text,
	tbl_corta text,
	vw_salida text,
	contenido text,
	srid1_a_cortar text,
	srid2_corta text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geome1 text;
geome2 text;
BEGIN
--el resultado de la diferencia se corta para crear poligonos independientes
EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tbl_entrada_a_cortar ||'"';
EXECUTE 'create table __cespaci2 as select * from "'|| esch ||'"."'|| tbl_corta ||'"';

SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
SELECT f_geometry_column into geome2 FROM geometry_columns  WHERE  f_table_name = '__cespaci2';

EXECUTE 'drop table __cespaci1';
EXECUTE 'drop table __cespaci2';

EXECUTE 'create  materialized view "'||esch||'"."'||vw_salida||'" as  
SELECT '||contenido||' b.geom::geometry(Geometry, 4326) AS geom  FROM 
(select '||contenido||' (st_dump(b.geom)).geom AS geom from
(select '||contenido||' ST_difference(a.transform_srid ,b.geom) as geom
from (select * ,ST_Transform(st_setsrid('||geome1||','||srid1_a_cortar||'),4326) as transform_srid 
from "'||esch||'"."'||tbl_entrada_a_cortar||'") a,
(select st_union(st_makevalid(ST_Transform(st_setsrid('||geome2||','||srid2_corta||'),4326))) as geom 
from "'||esch||'"."'||tbl_corta||'") b)b)b;';

END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.difference_dump_vw(
	esch text,
	tbl_entrada_a_cortar text,
	tbl_corta text,
	vw_salida text,
	contenido text,
	srid1_a_cortar text,
	srid2_corta text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geome1 text;
geome2 text;
BEGIN
--el resultado de la diferencia se corta para crear poligonos independientes
EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tbl_entrada_a_cortar ||'"';
EXECUTE 'create table __cespaci2 as select * from "'|| esch ||'"."'|| tbl_corta ||'"';

SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
SELECT f_geometry_column into geome2 FROM geometry_columns  WHERE  f_table_name = '__cespaci2';

EXECUTE 'drop table __cespaci1';
EXECUTE 'drop table __cespaci2';

EXECUTE 'create  view "'||esch||'"."'||vw_salida||'" as  
SELECT '||contenido||' b.geom::geometry(Geometry, 4326) AS geom  FROM 
(select '||contenido||' (st_dump(b.geom)).geom AS geom from
(select '||contenido||' ST_difference(a.transform_srid ,b.geom) as geom
from (select * ,ST_Transform(st_setsrid('||geome1||','||srid1_a_cortar||'),4326) as transform_srid 
from "'||esch||'"."'||tbl_entrada_a_cortar||'") a,
(select st_union(st_makevalid(ST_Transform(st_setsrid('||geome2||','||srid2_corta||'),4326))) as geom 
from "'||esch||'"."'||tbl_corta||'") b)b)b;';

END;
$BODY$;




CREATE OR REPLACE FUNCTION funciones.difference_mv(
	esch text,
	tbl_entrada_a_cortar text,
	tbl_corta text,
	vw_salida text,
	contenido text,
	srid1_a_cortar text,
	srid2_corta text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geome1 text;
geome2 text;
BEGIN
EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tbl_entrada_a_cortar ||'"';
EXECUTE 'create table __cespaci2 as select * from "'|| esch ||'"."'|| tbl_corta ||'"';

SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
SELECT f_geometry_column into geome2 FROM geometry_columns  WHERE  f_table_name = '__cespaci2';

EXECUTE 'drop table __cespaci1';
EXECUTE 'drop table __cespaci2';

EXECUTE 'create materialized  view "'||esch||'"."'||vw_salida||'" as 
select '|| contenido ||' ST_difference(a.transform_srid ,b.geom)::geometry(Geometry, 4326) as geom 
from (select * ,ST_Transform(st_setsrid('||geome1||','||srid1_a_cortar||'),4326) as transform_srid 
from "'||esch||'"."'||tbl_entrada_a_cortar||'") a,
(select st_union(st_makevalid(ST_Transform(st_setsrid('||geome2||','||srid2_corta||'),4326))) as geom 
from "'||esch||'"."'||tbl_corta||'") b;';

END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.difference_vw(
	esch text,
	tbl_entrada_a_cortar text,
	tbl_corta text,
	vw_salida text,
	contenido text,
	srid1_a_cortar text,
	srid2_corta text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geome1 text;
geome2 text;
BEGIN
EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tbl_entrada_a_cortar ||'"';
EXECUTE 'create table __cespaci2 as select * from "'|| esch ||'"."'|| tbl_corta ||'"';

SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
SELECT f_geometry_column into geome2 FROM geometry_columns  WHERE  f_table_name = '__cespaci2';

EXECUTE 'drop table __cespaci1';
EXECUTE 'drop table __cespaci2';

EXECUTE 'create   view "'||esch||'"."'||vw_salida||'" as 
select '|| contenido ||' ST_difference(a.transform_srid ,b.geom)::geometry(Geometry, 4326) as geom 
from (select * ,ST_Transform(st_setsrid('||geome1||','||srid1_a_cortar||'),4326) as transform_srid 
from "'||esch||'"."'||tbl_entrada_a_cortar||'") a,
(select st_union(st_makevalid(ST_Transform(st_setsrid('||geome2||','||srid2_corta||'),4326))) as geom 
from "'||esch||'"."'||tbl_corta||'") b;';

END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.h3_loop(
	tipo text,
	col text)
    RETURNS TABLE(ar text) 
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
    ROWS 1000
AS $BODY$
DECLARE
 pa   record; 
BEGIN

execute 'create table borrar_table (column_name text,column_valor text);';
Execute 'insert into  borrar_table (column_name) values '||col||';';
Execute 'insert into  borrar_table (column_valor) values '||tipo||';';
FOR pa IN 
       select column_name,column_valor from (select column_name from borrar_table where column_name is not null)b,
(select column_valor from borrar_table where column_valor is not null)a 
group by column_name,column_valor

	  LOOP
   ar:= 'ROUND('||pa.column_valor||'(b."'||pa.column_name||'"::integer),3) as "'||pa.column_valor||'_'||pa.column_name||'",';  RETURN NEXT;	END LOOP;
	execute 'drop table if exists borrar_table';
	execute 'drop table if exists borrar_valor';
	raise notice 'Value: %', pa;

END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.h3_mixto_vw(
	esch text,
	vw_salida text,
	tabla_entrada text,
	h3_zoom text,
	contenido_campos text,
	campos_no_agrupacion text,
	contenido_where text,
	srid1 text,
 	valor_escala text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
	geome1 character varying;
	astring character varying;
	bstring character varying;
	cstring character varying;

	begin 
	
/*valor escala según nivel:
15--0.000008,14--0.00002,13--0.000055,12--0.00014,11--0.00038,10--0.00085,
9--0.002,8--0.0048,7--0.0015,6--0.0049,5--0.12,4--0.35,3--0.82,2--2.5,1--9*/

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tabla_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';


select STRING_AGG(string,', ') into astring from(select string from
(select split_part(split_part(regexp_split_to_table(''|| contenido_campos ||'', ','),'(', 2),')','1') as string)a
group by string)a;

if campos_no_agrupacion <> '' then 
select concat(STRING_AGG(concat ('split_part(STRING_AGG(',de,'::text, '',''),'','',1)', ' as ',de),', '),' , ') into bstring
from (select regexp_split_to_table(''||campos_no_agrupacion||'',',') as de)a where de  <>'';
select concat (campos_no_agrupacion,',') into cstring;
else 
bstring:=campos_no_agrupacion;
cstring:=campos_no_agrupacion;
end if;

execute 'drop  view if exists "'||esch||'"."'||vw_salida||'"';
EXECUTE 'create  view "'||esch||'"."'||vw_salida||'" as 
select '||bstring||''|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| cstring ||'  '|| astring ||',h3_geo_to_h3index(st_centroid (geom),'||h3_zoom||') as h3_index from  
(select id_pol,'|| cstring ||'  '|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| cstring ||' '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	'''||valor_escala||''',
	'''||valor_escala||''') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| cstring ||' '|| astring ||',id_pol)a group by h3_index;' ;
	end;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.h3_mixto_index_vw(
	esch text,
	vw_salida text,
	tabla_entrada text,
	h3_zoom text,
	contenido_campos text,
	campos_no_agrupacion text,
	contenido_where text,
	srid1 text,
 	valor_escala text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
	geome1 character varying;
	astring character varying;
	bstring character varying;
	cstring character varying;

	begin 
	
/*valor escala según nivel:
15--0.000008,14--0.00002,13--0.000055,12--0.00014,11--0.00038,10--0.00085,
9--0.002,8--0.0048,7--0.0015,6--0.0049,5--0.12,4--0.35,3--0.82,2--2.5,1--9*/

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tabla_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';


select STRING_AGG(string,', ') into astring from(select string from
(select split_part(split_part(regexp_split_to_table(''|| contenido_campos ||'', ','),'(', 2),')','1') as string)a
group by string)a;

if campos_no_agrupacion <> '' then 
select concat(STRING_AGG(concat ('split_part(STRING_AGG(',de,'::text, '',''),'','',1)', ' as ',de),', '),' , ') into bstring
from (select regexp_split_to_table(''||campos_no_agrupacion||'',',') as de)a where de  <>'';
select concat (campos_no_agrupacion,',') into cstring;
else 
bstring:=campos_no_agrupacion;
cstring:=campos_no_agrupacion;
end if;

execute 'drop  view if exists "'||esch||'"."'||vw_salida||'"';
EXECUTE 'create  view "'||esch||'"."'||vw_salida||'" as 
select '||bstring||''|| contenido_campos ||',
h3_index
from 
(select * from	  
(select id_pol,'|| cstring ||'  '|| astring ||',h3_geo_to_h3index(st_centroid (geom),'||h3_zoom||') as h3_index from  
(select id_pol,'|| cstring ||'  '|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| cstring ||' '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	'''||valor_escala||''',
	'''||valor_escala||''') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| cstring ||' '|| astring ||',id_pol)a group by h3_index;' ;
	end;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.h3_mixto_mv(
	esch text,
	vw_salida text,
	tabla_entrada text,
	h3_zoom text,
	contenido_campos text,
	campos_no_agrupacion text,
	contenido_where text,
	srid1 text,
 	valor_escala text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
	geome1 character varying;
	astring character varying;
	bstring character varying;
	cstring character varying;

	begin 
	
/*valor escala según nivel:
15--0.000008,14--0.00002,13--0.000055,12--0.00014,11--0.00038,10--0.00085,
9--0.002,8--0.0048,7--0.0015,6--0.0049,5--0.12,4--0.35,3--0.82,2--2.5,1--9*/

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tabla_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';


select STRING_AGG(string,', ') into astring from(select string from
(select split_part(split_part(regexp_split_to_table(''|| contenido_campos ||'', ','),'(', 2),')','1') as string)a
group by string)a;

if campos_no_agrupacion <> '' then 
select concat(STRING_AGG(concat ('split_part(STRING_AGG(',de,'::text, '',''),'','',1)', ' as ',de),', '),' , ') into bstring
from (select regexp_split_to_table(''||campos_no_agrupacion||'',',') as de)a where de  <>'';
select concat (campos_no_agrupacion,',') into cstring;
else 
bstring:=campos_no_agrupacion;
cstring:=campos_no_agrupacion;
end if;

execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'"';
EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'" as 
select '||bstring||''|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| cstring ||'  '|| astring ||',h3_geo_to_h3index(st_centroid (geom),'||h3_zoom||') as h3_index from  
(select id_pol,'|| cstring ||'  '|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| cstring ||' '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	'''||valor_escala||''',
	'''||valor_escala||''') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| cstring ||' '|| astring ||',id_pol)a group by h3_index;' ;
	end;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.h3_mixto_index_mv(
	esch text,
	vw_salida text,
	tabla_entrada text,
	h3_zoom text,
	contenido_campos text,
	campos_no_agrupacion text,
	contenido_where text,
	srid1 text,
 	valor_escala text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
	geome1 character varying;
	astring character varying;
	bstring character varying;
	cstring character varying;

	begin 
	
/*valor escala según nivel:
15--0.000008,14--0.00002,13--0.000055,12--0.00014,11--0.00038,10--0.00085,
9--0.002,8--0.0048,7--0.0015,6--0.0049,5--0.12,4--0.35,3--0.82,2--2.5,1--9*/

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tabla_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';


select STRING_AGG(string,', ') into astring from(select string from
(select split_part(split_part(regexp_split_to_table(''|| contenido_campos ||'', ','),'(', 2),')','1') as string)a
group by string)a;

if campos_no_agrupacion <> '' then 
select concat(STRING_AGG(concat ('split_part(STRING_AGG(',de,'::text, '',''),'','',1)', ' as ',de),', '),' , ') into bstring
from (select regexp_split_to_table(''||campos_no_agrupacion||'',',') as de)a where de  <>'';
select concat (campos_no_agrupacion,',') into cstring;
else 
bstring:=campos_no_agrupacion;
cstring:=campos_no_agrupacion;
end if;

execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'"';
EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'" as 
select '||bstring||''|| contenido_campos ||',
h3_index
from 
(select * from	  
(select id_pol,'|| cstring ||'  '|| astring ||',h3_geo_to_h3index(st_centroid (geom),'||h3_zoom||') as h3_index from  
(select id_pol,'|| cstring ||'  '|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| cstring ||' '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	'''||valor_escala||''',
	'''||valor_escala||''') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| cstring ||' '|| astring ||',id_pol)a group by h3_index;' ;
	end;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.h3_punto_mixto_mv(
	esch text,
	vw_salida text,
	tabla_entrada text,
	h3_zoom text,
	contenido_campos text,
	contenido_where text,
	srid1 text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
	geome1 character varying;
	astring character varying;
	begin 
	
EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tabla_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';

select STRING_AGG(string,', ') into astring from(select string from
(select split_part(split_part(regexp_split_to_table(''|| contenido_campos ||'', ','),'(', 2),')','1') as string)a
group by string)a;

 execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'"';
	execute 'CREATE materialized VIEW "'||esch||'"."'||vw_salida||'"
 AS
SELECT '|| contenido_campos ||', h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) as geom
   FROM (SELECT '|| astring ||',h3_geo_to_h3index(ST_Transform(st_setsrid('||geome1||','||srid1||'),4326), '||h3_zoom||') AS h3_index
                   FROM "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')a
				   group by h3_index;' ;
	end;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.h3_punto_mixto_index_mv(
	esch text,
	vw_salida text,
	tabla_entrada text,
	h3_zoom text,
	contenido_campos text,
	contenido_where text,
	srid1 text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
	geome1 character varying;
	astring character varying;
	begin 
	
EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tabla_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';

select STRING_AGG(string,', ') into astring from(select string from
(select split_part(split_part(regexp_split_to_table(''|| contenido_campos ||'', ','),'(', 2),')','1') as string)a
group by string)a;

 execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'"';
	execute 'CREATE materialized VIEW "'||esch||'"."'||vw_salida||'"
 AS
SELECT '|| contenido_campos ||', h3_index
   FROM (SELECT '|| astring ||',h3_geo_to_h3index(ST_Transform(st_setsrid('||geome1||','||srid1||'),4326), '||h3_zoom||') AS h3_index
                   FROM "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')a
				   group by h3_index;' ;
	end;
$BODY$;
  

CREATE OR REPLACE FUNCTION funciones.h3_punto_mixto_vw(
	esch text,
	vw_salida text,
	tabla_entrada text,
	h3_zoom text,
	contenido_campos text,
	contenido_where text,
	srid1 text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
	geome1 character varying;
	astring character varying;
	begin 

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tabla_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';

select STRING_AGG(string,', ') into astring from(select string from
(select split_part(split_part(regexp_split_to_table(''|| contenido_campos ||'', ','),'(', 2),')','1') as string)a
group by string)a;

 execute 'drop view if exists "'||esch||'"."'||vw_salida||'"';
	execute 'CREATE VIEW "'||esch||'"."'||vw_salida||'"
 AS
SELECT '|| contenido_campos ||', h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) as geom
   FROM (SELECT '|| astring ||',h3_geo_to_h3index(ST_Transform(st_setsrid('||geome1||','||srid1||'),4326), '||h3_zoom||') AS h3_index
                   FROM "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')a
				   group by h3_index;' ;
	end;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.h3_punto_mixto_index_vw(
	esch text,
	vw_salida text,
	tabla_entrada text,
	h3_zoom text,
	contenido_campos text,
	contenido_where text,
	srid1 text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
	geome1 character varying;
	astring character varying;
	begin 

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tabla_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';

select STRING_AGG(string,', ') into astring from(select string from
(select split_part(split_part(regexp_split_to_table(''|| contenido_campos ||'', ','),'(', 2),')','1') as string)a
group by string)a;

 execute 'drop  view if exists "'||esch||'"."'||vw_salida||'"';
	execute 'CREATE  VIEW "'||esch||'"."'||vw_salida||'"
 AS
SELECT '|| contenido_campos ||', h3_index
   FROM (SELECT '|| astring ||',h3_geo_to_h3index(ST_Transform(st_setsrid('||geome1||','||srid1||'),4326), '||h3_zoom||') AS h3_index
                   FROM "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')a
				   group by h3_index;' ;
	end;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.h3_valores_mv(
	esch text,
	vw_salida text,
	tabla_entrada text,
	h3_zoom text,
	tipo text,
	col text,
	contenido_where text,
	srid1 text,
 	valor_escala text)
    RETURNS TABLE(te text) 
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
    ROWS 1000
AS $BODY$
DECLARE
	te text; 
	geome1 character varying;
	begin 
	-- descarte del mixto se deja por si acaso
 select STRING_AGG(ar,' ') from (select funciones.h3_loop(tipo,col) as ar) a into te;

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tabla_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';

 execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'"';
EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'" as select  
'||te||' h3_index,a.geom from (select
st_setsrid(h3_h3index_to_geoboundary( h3_geo_to_h3index),4326) as geom,h3_geo_to_h3index as h3_index from 
(select * from (select ( h3_geo_to_h3index
((st_dump(st_generatepoints(ST_Transform(st_setsrid('||geome1||','||srid1||'),4326),
((round(st_area(ST_Transform(st_setsrid('||geome1||','||srid1||'),4326)::Geography)))*'||valor_escala||')::integer))).geom,'|| h3_zoom ||'))
from "'||esch||'"."'||tabla_entrada||'")a group by h3_geo_to_h3index)a)a,
(select * from "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||') b
where st_intersects (a.geom,ST_Transform(st_setsrid(b.'||geome1||','||srid1||'),4326))
group by a.geom,a.h3_index' ;
	end;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.h3_valores_vw(
	esch text,
	vw_salida text,
	tabla_entrada text,
	h3_zoom text,
	tipo text,
	col text,
	contenido_where text,
	srid1 text,
 	valor_escala text)
    RETURNS TABLE(te text) 
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
    ROWS 1000
AS $BODY$
DECLARE
	te text; 
	geome1 character varying;
	begin 
	-- descarte del mixto se deja por si acaso
 select STRING_AGG(ar,' ') from (select funciones.h3_loop(tipo,col) as ar) a into te;

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tabla_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';

 execute 'drop  view if exists "'||esch||'"."'||vw_salida||'"';
EXECUTE 'create  view "'||esch||'"."'||vw_salida||'" as select  
'||te||' h3_index,a.geom from (select
st_setsrid(h3_h3index_to_geoboundary( h3_geo_to_h3index),4326) as geom,h3_geo_to_h3index as h3_index from 
(select * from (select ( h3_geo_to_h3index
((st_dump(st_generatepoints(ST_Transform(st_setsrid('||geome1||','||srid1||'),4326),
((round(st_area(ST_Transform(st_setsrid('||geome1||','||srid1||'),4326)::Geography)))*'||valor_escala||')::integer))).geom,'|| h3_zoom ||'))
from "'||esch||'"."'||tabla_entrada||'")a group by h3_geo_to_h3index)a)a,
(select * from "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||') b
where st_intersects (a.geom,ST_Transform(st_setsrid(b.'||geome1||','||srid1||'),4326))
group by a.geom,a.h3_index' ;
	end;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.h3_conteo_vw(
	esch text,
	vw_salida text,
	tabla_entrada text,
	h3_zoom text,
	contenido_where text,
	srid1 text,
 	valor_escala text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
	geome1 character varying;

	begin 
	
/*valor escala según nivel:
15--0.000008,14--0.00002,13--0.000055,12--0.00014,11--0.00038,10--0.00085,
9--0.002,8--0.0048,7--0.015,6--0.049,5--0.12,4--0.35,3--0.82,2--2.5,1--9*/

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tabla_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';


 execute 'drop view if exists "'||esch||'"."'||vw_salida||'"';
EXECUTE 'create view "'||esch||'"."'||vw_salida||'" as 
select count(*),
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,h3_geo_to_h3index(st_centroid (geom),'||h3_zoom||') as h3_index from  
(select id_pol,(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	'''||valor_escala||''',
	'''||valor_escala||''') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,id_pol)a group by h3_index;' ;
	end;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.h3_conteo_index_vw(
	esch text,
	vw_salida text,
	tabla_entrada text,
	h3_zoom text,
	contenido_where text,
	srid1 text,
 	valor_escala text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
	geome1 character varying;

	begin 
	
/*valor escala según nivel:
15--0.000008,14--0.00002,13--0.000055,12--0.00014,11--0.00038,10--0.00085,
9--0.002,8--0.0048,7--0.0015,6--0.0049,5--0.12,4--0.35,3--0.82,2--2.5,1--9*/

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tabla_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';


 execute 'drop view if exists "'||esch||'"."'||vw_salida||'"';
EXECUTE 'create view "'||esch||'"."'||vw_salida||'" as 
select count(*),h3_index
from 
(select * from	  
(select id_pol,h3_geo_to_h3index(st_centroid (geom),'||h3_zoom||') as h3_index from  
(select id_pol,(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	'''||valor_escala||''',
	'''||valor_escala||''') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,id_pol)a group by h3_index;' ;
	end;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.h3_conteo_mv(
	esch text,
	vw_salida text,
	tabla_entrada text,
	h3_zoom text,
	contenido_where text,
	srid1 text,
 	valor_escala text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
	geome1 character varying;

	begin 
	
/*valor escala según nivel:
15--0.000008,14--0.00002,13--0.000055,12--0.00014,11--0.00038,10--0.00085,
9--0.002,8--0.0048,7--0.0015,6--0.0049,5--0.12,4--0.35,3--0.82,2--2.5,1--9*/

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tabla_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';


 execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'"';
EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'" as 
select count(*),
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,h3_geo_to_h3index(st_centroid (geom),'||h3_zoom||') as h3_index from  
(select id_pol,(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	'''||valor_escala||''',
	'''||valor_escala||''') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,id_pol)a group by h3_index;' ;
	end;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.h3_conteo_index_mv(
	esch text,
	vw_salida text,
	tabla_entrada text,
	h3_zoom text,
	contenido_where text,
	srid1 text,
 	valor_escala text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
	geome1 character varying;

	begin 
	
/*valor escala según nivel:
15--0.000008,14--0.00002,13--0.000055,12--0.00014,11--0.00038,10--0.00085,
9--0.002,8--0.0048,7--0.0015,6--0.0049,5--0.12,4--0.35,3--0.82,2--2.5,1--9*/

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tabla_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';


 execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'"';
EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'" as 
select count(*),h3_index
from 
(select * from	  
(select id_pol,h3_geo_to_h3index(st_centroid (geom),'||h3_zoom||') as h3_index from  
(select id_pol,(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	'''||valor_escala||''',
	'''||valor_escala||''') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,id_pol)a group by h3_index;' ;
	end;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.h3_punto_conteo_vw(
	esch text,
	vw_salida text,
	tabla_entrada text,
	h3_zoom text,
	contenido_where text,
	srid1 text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
	geome1 character varying;
	begin 

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tabla_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';

 execute 'drop  view if exists "'||esch||'"."'||vw_salida||'"';
	execute 'CREATE  VIEW "'||esch||'"."'||vw_salida||'"
 AS
SELECT  "num_'||vw_salida||'", h3_index, st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) as geom
   FROM (SELECT count(*) AS "num_'||vw_salida||'", h3_index
           FROM (SELECT h3_geo_to_h3index(ST_Transform(st_setsrid('||geome1||','||srid1||'),4326), '||h3_zoom||') AS h3_index
                   FROM "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')a
				   group by h3_index )a
 order by "num_'||vw_salida||'" desc;' ;
	end;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.h3_punto_conteo_index_vw(
	esch text,
	vw_salida text,
	tabla_entrada text,
	h3_zoom text,
	contenido_where text,
	srid1 text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
	geome1 character varying;
	begin 

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tabla_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';

 execute 'drop  view if exists "'||esch||'"."'||vw_salida||'"';
	execute 'CREATE  VIEW "'||esch||'"."'||vw_salida||'"
 AS
SELECT  "num_'||vw_salida||'", h3_index
   FROM (SELECT count(*) AS "num_'||vw_salida||'", h3_index
           FROM (SELECT h3_geo_to_h3index(ST_Transform(st_setsrid('||geome1||','||srid1||'),4326), '||h3_zoom||') AS h3_index
                   FROM "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')a
				   group by h3_index )a
 order by "num_'||vw_salida||'" desc;' ;
	end;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.h3_punto_conteo_mv(
	esch text,
	vw_salida text,
	tabla_entrada text,
	h3_zoom text,
	contenido_where text,
	srid1 text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
	geome1 character varying;
	begin 

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tabla_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';

 execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'"';
	execute 'CREATE materialized VIEW "'||esch||'"."'||vw_salida||'"
 AS
SELECT  "num_'||vw_salida||'", h3_index, st_setsrid(h3_h3index_to_geoboundary(h3_index),4326::geometry(Geometry, 4326) as geom
   FROM (SELECT count(*) AS "num_'||vw_salida||'", h3_index
           FROM (SELECT h3_geo_to_h3index(ST_Transform(st_setsrid('||geome1||','||srid1||'),4326), '||h3_zoom||') AS h3_index
                   FROM "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')a
				   group by h3_index )a
 order by "num_'||vw_salida||'" desc;' ;
	end;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.h3_punto_conteo_index_mv(
	esch text,
	vw_salida text,
	tabla_entrada text,
	h3_zoom text,
	contenido_where text,
	srid1 text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
	geome1 character varying;
	begin 

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tabla_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';

 execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'"';
	execute 'CREATE materialized VIEW "'||esch||'"."'||vw_salida||'"
 AS
SELECT  "num_'||vw_salida||'", h3_index
   FROM (SELECT count(*) AS "num_'||vw_salida||'", h3_index
           FROM (SELECT h3_geo_to_h3index(ST_Transform(st_setsrid('||geome1||','||srid1||'),4326), '||h3_zoom||') AS h3_index
                   FROM "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')a
				   group by h3_index )a
 order by "num_'||vw_salida||'" desc;' ;
	end;
$BODY$;

 CREATE OR REPLACE FUNCTION funciones.h3_padre_hijo_vw(
	esch text,
	vw_salida text,
	tabla_entrada text,
	contenido_campos text,
	contenido_where text,
	srid1 text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
	geome1 character varying;
	astring character varying;
	
	begin 
	
EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tabla_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';

select STRING_AGG(string,', ') into astring from(select string from
(select split_part(split_part(regexp_split_to_table(''|| contenido_campos ||'', ','),'(', 2),')','1') as string)a
group by string)a;

execute 'drop view if exists "'||esch||'"."'||vw_salida||'_h1"';
EXECUTE 'create view "'||esch||'"."'||vw_salida||'_h1" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),1) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''9'',
	''9'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop view if exists "'||esch||'"."'||vw_salida||'_h2"';
EXECUTE 'create view "'||esch||'"."'||vw_salida||'_h2" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),2) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''2.5'',
	''2.5'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop view if exists "'||esch||'"."'||vw_salida||'_h3"';
EXECUTE 'create view "'||esch||'"."'||vw_salida||'_h3" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),3) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.82'',
	''0.82'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop view if exists "'||esch||'"."'||vw_salida||'_h4"';
EXECUTE 'create view "'||esch||'"."'||vw_salida||'_h4" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),4) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.35'',
	''0.35'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop view if exists "'||esch||'"."'||vw_salida||'_h5"';
EXECUTE 'create view "'||esch||'"."'||vw_salida||'_h5" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),5) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.12'',
	''0.12'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop view if exists "'||esch||'"."'||vw_salida||'_h6"';
EXECUTE 'create view "'||esch||'"."'||vw_salida||'_h6" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),6) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.049'',
	''0.049'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop view if exists "'||esch||'"."'||vw_salida||'_h7"';
EXECUTE 'create view "'||esch||'"."'||vw_salida||'_h7" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),7) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.015'',
	''0.015'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop view if exists "'||esch||'"."'||vw_salida||'_h8"';
EXECUTE 'create view "'||esch||'"."'||vw_salida||'_h8" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),8) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.0048'',
	''0.0048'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop view if exists "'||esch||'"."'||vw_salida||'_h9"';
EXECUTE 'create view "'||esch||'"."'||vw_salida||'_h9" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),9) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.002'',
	''0.002'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop view if exists "'||esch||'"."'||vw_salida||'_h10"';
EXECUTE 'create view "'||esch||'"."'||vw_salida||'_h10" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),10) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.00085'',
	''0.00085'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_indexx;' ;

 execute 'drop view if exists "'||esch||'"."'||vw_salida||'_h11"';
EXECUTE 'create view "'||esch||'"."'||vw_salida||'_h11" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),11) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.00038'',
	''0.00038'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop view if exists "'||esch||'"."'||vw_salida||'_h12"';
EXECUTE 'create view "'||esch||'"."'||vw_salida||'_h12" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),12) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.00014'',
	''0.00014'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop view if exists "'||esch||'"."'||vw_salida||'_h13"';
EXECUTE 'create view "'||esch||'"."'||vw_salida||'_h13" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),13) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.000055'',
	''0.000055'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop view if exists "'||esch||'"."'||vw_salida||'_h14"';
EXECUTE 'create view "'||esch||'"."'||vw_salida||'_h14" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),14) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.00002'',
	''0.00002'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop view if exists "'||esch||'"."'||vw_salida||'_h15"';
EXECUTE 'create view "'||esch||'"."'||vw_salida||'_h15" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),15) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.000008'',
	''0.000008'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

	end;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.h3_padre_hijo_mv(
	esch text,
	vw_salida text,
	tabla_entrada text,
	contenido_campos text,
	contenido_where text,
	srid1 text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
	geome1 character varying;
	astring character varying;
	
	begin 
	
EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tabla_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';

select STRING_AGG(string,', ') into astring from(select string from
(select split_part(split_part(regexp_split_to_table(''|| contenido_campos ||'', ','),'(', 2),')','1') as string)a
group by string)a;

execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'_h1"';
EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'_h1" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),1) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''9'',
	''9'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'_h2"';
EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'_h2" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),2) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''2.5'',
	''2.5'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'_h3"';
EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'_h3" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),3) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.82'',
	''0.82'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'_h4"';
EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'_h4" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),4) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.35'',
	''0.35'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'_h5"';
EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'_h5" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),5) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.12'',
	''0.12'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'_h6"';
EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'_h6" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),6) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.049'',
	''0.049'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'_h7"';
EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'_h7" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),7) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.015'',
	''0.015'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'_h8"';
EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'_h8" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),8) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.0048'',
	''0.0048'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'_h9"';
EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'_h9" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),9) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.002'',
	''0.002'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'_h10"';
EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'_h10" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),10) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.00085'',
	''0.00085'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_indexx;' ;

 execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'_h11"';
EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'_h11" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),11) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.00038'',
	''0.00038'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'_h12"';
EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'_h12" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),12) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.00014'',
	''0.00014'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'_h13"';
EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'_h13" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),13) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.000055'',
	''0.000055'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'_h14"';
EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'_h14" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),14) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.00002'',
	''0.00002'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

 execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'_h15"';
EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'_h15" as select '|| contenido_campos ||',
h3_index,st_setsrid(h3_h3index_to_geoboundary(h3_index),4326)::geometry(Geometry, 4326) AS geom 
from 
(select * from	  
(select id_pol,'|| astring ||',h3_geo_to_h3index(st_centroid (geom),15) as h3_index from  
(select id_pol,'|| astring ||',(st_dump (st_transform(st_setsrid(geom,'||srid1||'),4326))).geom from  
(select row_number() OVER () AS id_pol,* from (select '|| astring ||',funciones.__crear_tesela(
	st_makevalid('||geome1||'),
	''0.000008'',
	''0.000008'') as geom
	from  "'||esch||'"."'||tabla_entrada||'" '|| contenido_where ||')t )a ) a )a 
	group by  h3_index,'|| astring ||',id_pol)a group by h3_index;' ;

	end;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.linea_central_poligono_tbl(
	esch text,
	tbl_entrada text,
	tbl_salida text,
	num_limp integer)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geome1 text;

BEGIN

EXECUTE 'create table __espaci1 as select * from "'|| esch ||'"."'|| tbl_entrada ||'"';

SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__espaci1';

EXECUTE 'drop table __espaci1';

/*el num_limp es la cantidad de veces que se eliminan los extremos*/
EXECUTE 'drop table if exists "'||esch||'"."'||tbl_entrada||'_cdz";';
EXECUTE 'create table "'||esch||'"."'||tbl_entrada||'_cdz" as select 
st_simplify((st_dump
(st_union(st_buffer ('||geome1||',(0.0005/1.1132*0.00001),''endcap=square join=bevel'')))).geom,(1/1.1132*0.00001)) as geom
from "'||esch||'"."'||tbl_entrada||'";';
EXECUTE 'create index "'||esch||'_'||tbl_entrada||'_cdz" 
ON "'||esch||'"."'||tbl_entrada||'_cdz" USING GIST (geom);';
EXECUTE 'drop table if exists "'||esch||'"."'||tbl_entrada||'_cdzb";';
EXECUTE 'create table "'||esch||'"."'||tbl_entrada||'_cdzb" as select st_boundary (geom) as geom
from "'||esch||'"."'||tbl_entrada||'_cdz";';

EXECUTE 'drop table if exists "'||esch||'"."'||tbl_entrada||'_cs";';
EXECUTE 'create table  "'||esch||'"."'||tbl_entrada||'_cs" as select ST_Segmentize(geom,(1/1.1132*0.00001)) as geom 
from "'||esch||'"."'||tbl_entrada||'_cdz";';
EXECUTE 'create index "'||esch||'_'||tbl_entrada||'_cs" ON "'||esch||'"."'||tbl_entrada||'_cs" USING GIST (geom);';
EXECUTE 'drop table if exists "'||esch||'"."'||tbl_entrada||'_cvl";';
EXECUTE 'create table "'||esch||'"."'||tbl_entrada||'_cvl"
as select row_number ()over() as id_zona,* from (select (st_dump(ST_VoronoiLines (geom))).geom as geom from "'||esch||'"."'||tbl_entrada||'_cs")t;';
EXECUTE 'create index "'||esch||'_'||tbl_entrada||'_cvl" ON "'||esch||'"."'||tbl_entrada||'_cvl" USING GIST (geom);';
EXECUTE 'drop table if exists "'||esch||'"."'||tbl_entrada||'_cvc";';
EXECUTE 'create table "'||esch||'"."'||tbl_entrada||'_cvc" as select id_zona,geom from (select b.*,id from (select a.*,a.id_zona as id from "'||esch||'"."'||tbl_entrada||'_cvl" a,
(select (st_dump(geom)).geom from "'||esch||'"."'||tbl_entrada||'_cdz") b 
where st_intersects (a.geom,st_exteriorring(b.geom)))t
right join
(select * from "'||esch||'"."'||tbl_entrada||'_cvl")b on ST_Equals (t.geom,b.geom))t 
where id is null;';
EXECUTE 'create index "'||esch||'_'||tbl_entrada||'_cvc" ON "'||esch||'"."'||tbl_entrada||'_cvc" USING GIST (geom);';

EXECUTE 'drop table if exists "'||esch||'"."'||tbl_entrada||'_cc";';
EXECUTE 'create table "'||esch||'"."'||tbl_entrada||'_cc" as select a.geom, a.id_zona as id from "'||esch||'"."'||tbl_entrada||'_cvc" a join
"'||esch||'"."'||tbl_entrada||'_cdz" b on st_intersects (a.geom,b.geom);';
EXECUTE 'create index "'||esch||'_'||tbl_entrada||'_cc" ON "'||esch||'"."'||tbl_entrada||'_cc" USING GIST (geom);';

EXECUTE 'drop table if exists "'||esch||'"."'||tbl_salida||'";';
EXECUTE 'create table "'||esch||'"."'||tbl_salida||'" as select * from (select st_length(geom) as distancia, * from (select a.geom, a.id as id from 
"'||esch||'"."'||tbl_entrada||'_cc" a join
"'||esch||'"."'||tbl_entrada||'_cdz" b
on ST_ContainsProperly (b.geom,a.geom))a)a;';

EXECUTE 'create index "'||esch||'_'||tbl_salida||'" 
ON "'||esch||'"."'||tbl_salida||'" USING GIST (geom);';

for counter in 0..num_limp loop

EXECUTE 'drop table if exists "'||esch||'"."'||tbl_entrada||'_ccs";';
EXECUTE 'create table "'||esch||'"."'||tbl_entrada||'_ccs" as select id1 as id,''Points without union'' as errores, point as geom from(select r1.geom as point, r1.id_zona as id1, r2.id as id2
from (select (st_dumppoints(geom)).geom, id as id_zona from "'||esch||'"."'||tbl_salida||'") r1 
	  left join "'||esch||'"."'||tbl_salida||'" r2 
on r1.id_zona<>r2.id and st_expand (r1.geom,1000) && r2.geom and st_distance (r1.geom,r2.geom) = 0)
as tabla where id2 is null;';
EXECUTE 'create index "'||esch||'_'||tbl_entrada||'_ccs" ON "'||esch||'"."'||tbl_entrada||'_ccs" USING GIST (geom);';
EXECUTE 'delete from "'||esch||'"."'||tbl_salida||'" a 
USING "'||esch||'"."'||tbl_entrada||'_ccs" b
where a.id = b.id;';

RAISE NOTICE 'counter: %', counter;
end loop;

EXECUTE 'drop table if exists "'||esch||'"."'||tbl_entrada||'_cdz";';
EXECUTE 'drop table if exists "'||esch||'"."'||tbl_entrada||'_cdzb";';
EXECUTE 'drop table if exists "'||esch||'"."'||tbl_entrada||'_cs";';
EXECUTE 'drop table if exists "'||esch||'"."'||tbl_entrada||'_cvl";';
EXECUTE 'drop table if exists "'||esch||'"."'||tbl_entrada||'_cc";';
EXECUTE 'drop table if exists "'||esch||'"."'||tbl_entrada||'_ccs";';
EXECUTE 'drop table if exists "'||esch||'"."'||tbl_entrada||'_cvc";';

END;
$BODY$;

/*Medial axis con limpieza a la que se añade la unión de los ejes entre cruces.
También se añade el campo "materialized" para determinar si se crea una vista o una vista materializada, en lugar de crear dos funciones iguales.
Si se crea una vista materializada se crea un índice en el campo geom*/

CREATE OR REPLACE FUNCTION funciones.medialaxis_con_limpieza_unidos_mv(
	esch text,
	tbl_entrada text,
	vw_salida text,
	contenido text,
	metros_buff text,
	simpli text,
	materialized boolean default false)
    RETURNS void
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
AS $BODY$
declare 
geome1 text;
vwType varchar;
sSql varchar;
BEGIN
/*medial axis con una limpieza previa por si hubiera geometrias no validas o agujeros o 
cortes que solucionan los problemas de un medial axis básico. Une los tramos de vial entre cruces.
 metros_buff para la limpieza de pequeños huecos dentro de la geometría que da errores al medial*/
 
--EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tbl_entrada ||'"';

SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_schema = esch AND f_table_name = tbl_entrada;

IF materialized = true THEN 
		vwType:='materialized view';
	ELSE 
		vwType:='view';
	END IF;

--EXECUTE 'drop table __cespaci1';
EXECUTE 'DROP '||vwType||' IF EXISTS "'||esch||'"."'||vw_salida||'"';
sSql:=
'create materialized view "'||esch||'"."'||vw_salida||'" as 

WITH
	ejes as 
		(
		select '||contenido||',
		ST_ApproximateMedialAxis('||geome1||') as geom from  
			(
			select '||contenido||', (ST_SimplifyPreserveTopology ((st_dump(st_makevalid(st_buffer('||geome1||','||metros_buff||')))).geom,'||simpli||')) as geom
			from "'||esch||'"."'||tbl_entrada||'"
			) as g
		)
	SELECT 
		'||contenido||',
		t2.geom
	FROM 
		(
		SELECT '||contenido||',(st_dump(st_linemerge(st_collect((t.dump).geom)))).geom as geom
		FROM 
			(
			SELECT '||contenido||', st_dump(geom) as dump from ejes
			) as t
		GROUP BY '||contenido||'
		) as t2';
-- DEBBUG
	--RAISE NOTICE 'sql: %',sSql;
	
EXECUTE sSql;
IF materialized = true THEN 
	EXECUTE 'CREATE INDEX '||esch||'_'||vw_salida||'_geom_idx ON "'||esch||'"."'||vw_salida||'" USING GIST(geom)';
END IF;
END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.medialaxis_con_limpieza_mv(
	esch text,
	tbl_entrada text,
	vw_salida text,
	contenido text,
	metros_buff text,
	simpli text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geome1 text;
srid1 text;
BEGIN
/*medial axis con una limpieza previa por si hubiera geometrias no validas o agujeros o 
cortes que solucionan los problemas de un medial axis básico.
- metros_buff para la limpieza de pequeños huecos dentro de la geometría que da errores al medial*/

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tbl_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| tbl_entrada ||'" group by ST_SRID;' into srid1;

EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'" as 
select '||contenido||' 
st_transform(st_setsrid(ST_ApproximateMedialAxis(geom), '||srid1||'),4326)::geometry(Geometry, 4326) as geom from  
(select '||contenido||' ST_SimplifyPreserveTopology(st_buffer('||geome1||','||metros_buff||'),'||simpli||') as geom
from "'||esch||'"."'||tbl_entrada||'")a;';

END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.medialaxis_con_limpieza_vw(
	esch text,
	tbl_entrada text,
	vw_salida text,
	contenido text,
	metros_buff text,
	simpli text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geome1 text;
srid1 text;
BEGIN
/*medial axis con una limpieza previa por si hubiera geometrias no validas o agujeros o 
cortes que solucionan los problemas de un medial axis básico.
- metros_buff para la limpieza de pequeños huecos dentro de la geometría que da errores al medial*/

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tbl_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| tbl_entrada ||'" group by ST_SRID;' into srid1;

EXECUTE 'create  view "'||esch||'"."'||vw_salida||'" as 
select '||contenido||' 
st_transform(st_setsrid(ST_ApproximateMedialAxis(geom), '||srid1||'),4326)::geometry(Geometry, 4326) as geom from  
(select '||contenido||' ST_SimplifyPreserveTopology(st_buffer('||geome1||','||metros_buff||'),'||simpli||') as geom
from "'||esch||'"."'||tbl_entrada||'")a;';

END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.medialaxis_mv(
	esch text,
	tbl_entrada text,
	vw_salida text,
	contenido text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geome1 text;
srid1 text;
BEGIN

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tbl_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| tbl_entrada ||'" group by ST_SRID;' into srid1;

EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'" as 
select '|| contenido ||'
st_transform(st_setsrid(ST_ApproximateMedialAxis(st_makevalid('||geome1||')), '||srid1||'),4326)::geometry(Geometry, 4326) as geom 
from "'||esch||'"."'||tbl_entrada||'";';

END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.medialaxis_vw(
	esch text,
	tbl_entrada text,
	vw_salida text,
	contenido text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geome1 text;
srid1 text;
BEGIN

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tbl_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| tbl_entrada ||'" group by ST_SRID;' into srid1;

EXECUTE 'create view "'||esch||'"."'||vw_salida||'" as 
select '|| contenido ||'
st_transform(st_setsrid(ST_ApproximateMedialAxis(st_makevalid('||geome1||')), '||srid1||'),4326)::geometry(Geometry, 4326) as geom 
from "'||esch||'"."'||tbl_entrada||'";';

END;
$BODY$;


/*Genera las tablas de área unidas y simplificadas para un valor score superior a un umbral, así como la tabla de ejes de esas áreas.

Si la tabla de entrada tiene coordenadas geocéntrias y la distancia de buffer se quiere dar en metros, introducir el parámetro sridAux con un srid proyectado en metros.
En caso contrario, introducir el buffer en grados y notación decimal
StraightSkeleton puede dar error con el sistema 4326, o cualquier otro geocéntrico: ERROR:  CGAL failed to create straightSkeleton. Si se introduce el sridAux, se proyectará antes de ejecutar la función

Si se especifica sridAux = null, no se hace la transformación. 
El resultado siempre se da en las coordenadas del campo de origen
*/
--DROP FUNCTION funciones.areas_ejes_viales_ia;

CREATE OR REPLACE FUNCTION funciones.areas_ejes_viales_ia(
	esch text,
	tbl_entrada text,
	salidaareas text,
	salidaejes text,
    umbralscore numeric,
	dist_buff numeric,
	simpli numeric,
	sridAux integer
)
    RETURNS void
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
AS $BODY$
declare 
	geome1 text;
	iSrid integer;
	vwType varchar;
	sSql varchar;
	sSqlMedialAxis varchar;
	sSqlArea varchar;
BEGIN
	/*medial axis con una limpieza previa por si hubiera geometrias no validas o agujeros o 
	cortes que solucionan los problemas de un medial axis básico. Une los tramos de vial entre cruces.
	 dist_buff para la limpieza de pequeños huecos dentro de la geometría que da errores al medial*/

	--EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tbl_entrada ||'"';

	SELECT f_geometry_column,srid into geome1,iSrid FROM geometry_columns  WHERE  f_table_schema = esch AND f_table_name = tbl_entrada;
	IF iSrid=0 THEN iSrid:=4326;
	END IF;

	IF sridAux IS NOT NULL AND sridAux<>iSrid THEN  
		--sSqlArea:='st_transform(st_buffer(st_transform('||geome1||','||sridAux||'),'||dist_buff||'),'||iSrid||')';
		sSqlArea:='(st_dump(st_union(st_makevalid(st_transform(ST_SimplifyPreserveTopology (st_buffer(st_transform('||geome1||','||sridAux||'),'||dist_buff||'),'||simpli||'),'||iSrid||'))))).geom';
		sSqlMedialAxis:='st_transform(ST_ApproximateMedialAxis(st_transform(geom,'||sridAux||')),'||iSrid||')';
		
		ELSE
		--sSqlArea:='st_buffer('||geome1||','||dist_buff||')';
		sSqlArea:='(st_dump(st_union(st_makevalid(ST_SimplifyPreserveTopology (st_buffer('||geome1||','||dist_buff||'),'||simpli||'))))).geom';
		sSqlMedialAxis:='ST_ApproximateMedialAxis(geom)';
		
	END IF;
	--sSqlMedialAxis:='ST_ApproximateMedialAxis(geom)';
	--EXECUTE 'drop table __cespaci1';
	EXECUTE 'DROP TABLE IF EXISTS "'||esch||'"."'||salidaareas||'" CASCADE';
	--DEBUG
	--RAISE NOTICE 'esch, vw_salida, contenido, geome1,dist_buff, simpli, tbl_entrada: %,%,%,%,%,%,%',esch, vw_salida, contenido, geome1,dist_buff, simpli, tbl_entrada;

	sSql:= 'CREATE TABLE "'||esch||'"."'||salidaareas||'" AS 
		WITH 
		simples AS 
			(
				SELECT 
					'||sSqlArea||' as geom
				FROM "'||esch||'"."'||tbl_entrada||'" 
				WHERE score>='||umbralscore||'
			)
		SELECT 
			(row_number() over ())::integer as gid,
			geom:: geometry(polygon,'||iSrid||')  as geom
			FROM simples';
	--DEBBUG
		RAISE NOTICE 'sql: %',sSql;
	EXECUTE sSql;
	EXECUTE 'ALTER TABLE "'||esch||'"."'||salidaareas||'" ADD PRIMARY KEY (gid)';
	EXECUTE 'CREATE INDEX '||esch||'_'||salidaareas||'_geom_idx ON "'||esch||'"."'||salidaareas||'" USING GIST(geom)';
	-- Creamos la tabla de ejes a partir de la de áreas

	/* StraightSkeleton puede dar error con el sistema 4326 (seguramente con cualquier sistema no proyectado)
	Si da error, añadir como parámetro de entrada el srid aux.
	*/

	

	EXECUTE 'DROP TABLE IF EXISTS "'||esch||'"."'||salidaejes||'"';
	sSql:=
	'CREATE TABLE "'||esch||'"."'||salidaejes||'" as 

	WITH
		ejes as 
			(
			select 
				gid as gidarea,
				(st_dump('||sSqlMedialAxis||')).geom as geom 
				from "'||esch||'"."'||salidaareas||'"
			WHERE st_isvalid(geom)=true

			),
		unidos as 
			(
				SELECT 
					gidarea,
					(st_dump(st_linemerge(st_collect((geom))))).geom::geometry(linestring,'||iSrid||') as geom
				FROM 
					ejes
				GROUP BY gidarea
			)
		SELECT 
			row_number() over () as gid,
			geom
		FROM 
			unidos'
		;

	--DEBBUG
		--RAISE NOTICE 'sql: %',sSql;

	EXECUTE sSql;
	EXECUTE 'CREATE INDEX '||esch||'_'||salidaejes||'_geom_idx ON "'||esch||'"."'||salidaejes||'" USING GIST(geom)';
	EXCEPTION WHEN OTHERS THEN 
		RAISE WARNING E'ERROR: % /n DESCRIPCION: %',SQLSTATE,SQLERRM;
END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.padre_hijo_limites_administrativos_mv(
	esch text,
	table_a_contar text,
	vw_salida text,
	tipo text,
	col text,
	srid1 text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
--si se cambia el nombre de num_features cambiar también en la función padre_hijo_loop2
declare 
geome1 text;
te text;
ta text;
tu text;
BEGIN

select STRING_AGG(ar,' ') from (select funciones.padre_hijo_loop1(tipo,col) as ar) a into te;
select STRING_AGG(ar,' ') from (select funciones.padre_hijo_loop2(tipo) as ar) a into ta;
select STRING_AGG(ar,' ') from (select funciones.padre_hijo_loop3(tipo,col) as ar) a into tu;

EXECUTE 'create table __espaci1 as select * from "'|| esch ||'"."'|| table_a_contar ||'"';

SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__espaci1';

EXECUTE 'drop table __espaci1';

execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'";';

execute 'CREATE materialized VIEW "'||esch||'"."'||vw_salida||'_apoyo"
 AS
select count(b.geom) as num_features,'||te||'
    a.municipio,a.natcode_municipio,
    a.natcode_provincia,
    a.natcode_ccaa,
    a.gid_0,a.name
   FROM "'||esch||'"."'||table_a_contar||'" b
      JOIN multinivel.municipios a ON st_intersects(ST_Transform(st_setsrid(b.'||geome1||','||srid1||'),4326), a.geom)
  GROUP BY a.natcode_provincia, a.natcode_municipio,a.natcode_ccaa, a.gid_0, a.municipio,a.name
  ORDER BY (count(b.geom)) DESC';
  
execute 'create materialized view "'||esch||'"."'||vw_salida||'_z_4" as 
select '||tu||''||ta||'
a.municipio,a.provincia,a.geom::geometry(Geometry, 4326) AS geom
from "'||esch||'"."'||vw_salida||'_apoyo" b RIGHT JOIN multinivel.municipios a
on a.natcode_municipio::text=b.natcode_municipio::text 
group by a.municipio,a.provincia,a.geom';

execute 'create materialized view "'||esch||'"."'||vw_salida||'_z_3" as 
select '||tu||''||ta||'
a.provincia,a.ccaa,a.geom::geometry(Geometry, 4326) AS geom 
from "'||esch||'"."'||vw_salida||'_apoyo" b RIGHT JOIN multinivel.provincias a
on a.natcode_provincia::text=b.natcode_provincia::text 
group by a.ccaa,a.provincia,a.geom';

execute 'create materialized view "'||esch||'"."'||vw_salida||'_z_2" as 
select '||tu||''||ta||'
a.ccaa,a.name_0,a.geom::geometry(Geometry, 4326) AS geom 
from "'||esch||'"."'||vw_salida||'_apoyo" b RIGHT JOIN multinivel.comunidades_mundo a
on a.natcode_ccaa::text=b.natcode_ccaa::text 
group by a.ccaa,a.name_0,a.geom';

execute 'create materialized view "'||esch||'"."'||vw_salida||'_z_1" as 
select '||tu||''||ta||' a.name_0,a.name,a.geom::geometry(Geometry, 4326) AS geom 
from "'||esch||'"."'||vw_salida||'_apoyo" b right join multinivel.paises a 
on b.gid_0::text=a.gid_0::text group by a.name_0,a.geom,a.name';

execute 'create materialized view "'||esch||'"."'||vw_salida||'_z_0" as 
select '||tu||''||ta||' a.name,a.geom::geometry(Geometry, 4326) AS geom 
from "'||esch||'"."'||vw_salida||'_apoyo" b right join multinivel.continentes a 
on b.name::text=a.name::text  group by a.name,a.geom ';

 END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.padre_hijo_limites_administrativos_vw(
	esch text,
	table_a_contar text,
	vw_salida text,
	tipo text,
	col text,
	srid1 text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
--si se cambia el nombre de num_features cambiar también en la función padre_hijo_loop2
declare 
geome1 text;
te text;
ta text;
tu text;
BEGIN

select STRING_AGG(ar,' ') from (select funciones.padre_hijo_loop1(tipo,col) as ar) a into te;
select STRING_AGG(ar,' ') from (select funciones.padre_hijo_loop2(tipo) as ar) a into ta;
select STRING_AGG(ar,' ') from (select funciones.padre_hijo_loop3(tipo,col) as ar) a into tu;

EXECUTE 'create table __espaci1 as select * from "'|| esch ||'"."'|| table_a_contar ||'"';

SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__espaci1';

EXECUTE 'drop table __espaci1';

execute 'drop  view if exists "'||esch||'"."'||vw_salida||'";';

execute 'CREATE  VIEW "'||esch||'"."'||vw_salida||'_apoyo"
 AS
select count(b.geom) as num_features,'||te||'
    a.municipio,a.natcode_municipio,
    a.natcode_provincia,
    a.natcode_ccaa,
    a.gid_0,a.name
   FROM "'||esch||'"."'||table_a_contar||'" b
      JOIN multinivel.municipios a ON st_intersects(ST_Transform(st_setsrid(b.'||geome1||','||srid1||'),4326), a.geom)
  GROUP BY a.natcode_provincia, a.natcode_municipio,a.natcode_ccaa, a.gid_0, a.municipio,a.name
  ORDER BY (count(b.geom)) DESC';
  
execute 'create view "'||esch||'"."'||vw_salida||'_z_4" as 
select '||tu||''||ta||'
a.municipio,a.provincia,a.geom::geometry(Geometry, 4326) AS geom 
from "'||esch||'"."'||vw_salida||'_apoyo" b RIGHT JOIN multinivel.municipios a
on a.natcode_municipio::text=b.natcode_municipio::text 
group by a.municipio,a.provincia,a.geom';

execute 'create view "'||esch||'"."'||vw_salida||'_z_3" as 
select '||tu||''||ta||'
a.provincia,a.ccaa,a.geom::geometry(Geometry, 4326) AS geom 
from "'||esch||'"."'||vw_salida||'_apoyo" b RIGHT JOIN multinivel.provincias a
on a.natcode_provincia::text=b.natcode_provincia::text 
group by a.ccaa,a.provincia,a.geom';

execute 'create view "'||esch||'"."'||vw_salida||'_z_2" as 
select '||tu||''||ta||'
a.ccaa,a.name_0,a.geom::geometry(Geometry, 4326) AS geom
from "'||esch||'"."'||vw_salida||'_apoyo" b RIGHT JOIN multinivel.comunidades_mundo a
on a.natcode_ccaa::text=b.natcode_ccaa::text 
group by a.ccaa,a.name_0,a.geom';

execute 'create view "'||esch||'"."'||vw_salida||'_z_1" as 
select '||tu||''||ta||' a.name_0,a.name,a.geom::geometry(Geometry, 4326) AS geom 
from "'||esch||'"."'||vw_salida||'_apoyo" b right join multinivel.paises a 
on b.gid_0::text=a.gid_0::text group by a.name_0,a.geom,a.name';

execute 'create view "'||esch||'"."'||vw_salida||'_z_0" as 
select '||tu||''||ta||' a.name,a.geom::geometry(Geometry, 4326) AS geom 
from "'||esch||'"."'||vw_salida||'_apoyo" b right join multinivel.continentes a 
on b.name::text=a.name::text  group by a.name,a.geom ';

 END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.padre_hijo_loop1(
	tipo text,
	col text)
    RETURNS TABLE(ar text) 
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
    ROWS 1000
AS $BODY$
DECLARE
 pa   record; 
BEGIN

execute 'create table borrar_table (column_name text,column_valor text);';
Execute 'insert into  borrar_table (column_name) values '||col||';';
Execute 'insert into  borrar_table (column_valor) values '||tipo||';';
FOR pa IN 
       select column_name,column_valor from (select column_name from borrar_table where column_name is not null)b,
(select column_valor from borrar_table where column_valor is not null)a 
group by column_name,column_valor

	  LOOP
   ar:= 'ROUND('||pa.column_valor||'(b."'||pa.column_name||'"::integer),3) as "'||pa.column_valor||'_'||pa.column_name||'",';  RETURN NEXT;	END LOOP;
	execute 'drop table if exists borrar_table';
	execute 'drop table if exists borrar_valor';
	raise notice 'Value: %', pa;

END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.padre_hijo_loop2(
	tipo text)
    RETURNS TABLE(ar text) 
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
    ROWS 1000
AS $BODY$
--num_x es el nombre de la columna de la vista de apoyo donde cuenta la geometría
DECLARE
 pa   record; 
BEGIN

execute 'create table borrar_table (column_name text,column_valor text);';
Execute 'insert into  borrar_table (column_name) values (''num_features'');';
Execute 'insert into  borrar_table (column_valor) values '||tipo||';';
FOR pa IN 
       select column_name,column_valor from (select column_name from borrar_table where column_name is not null)b,
(select column_valor from borrar_table where column_valor is not null)a 
group by column_name,column_valor

	  LOOP
   ar:= 'ROUND('||pa.column_valor||'(b."'||pa.column_name||'"::integer),3) as "'||pa.column_valor||'_'||pa.column_name||'",';  RETURN NEXT;	END LOOP;
	execute 'drop table if exists borrar_table';
	execute 'drop table if exists borrar_valor';
	raise notice 'Value: %', pa;

END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.padre_hijo_loop3(
	tipo text,
	col text)
    RETURNS TABLE(ar text) 
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
    ROWS 1000
AS $BODY$
DECLARE
 pa   record; 
BEGIN

execute 'create table borrar_table (column_name text,column_valor text);';
Execute 'insert into  borrar_table (column_name) values '||col||';';
Execute 'insert into  borrar_table (column_valor) values '||tipo||';';
FOR pa IN 
       select column_name,column_valor from (select column_name from borrar_table where column_name is not null)b,
(select column_valor from borrar_table where column_valor is not null)a 
group by column_name,column_valor

	  LOOP
   ar:= 'ROUND('||pa.column_valor||'(b."'||pa.column_valor||'_'||pa.column_name||'"::integer),3) as "'||pa.column_valor||'_'||pa.column_name||'",';  RETURN NEXT;	END LOOP;
	execute 'drop table if exists borrar_table';
	execute 'drop table if exists borrar_valor';
	raise notice 'Value: %', pa;

END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.generica_mv(
	esch text,
	vw_salida text,
	contenido_sql text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
BEGIN
/*función para introducir código sql que crea vista o vista materializada*/

EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'" as '||contenido_sql||';';

END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.generica_vw(
	esch text,
	vw_salida text,
	contenido_sql text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
BEGIN
/*función para introducir código sql que crea vista o vista materializada*/

EXECUTE 'create view "'||esch||'"."'||vw_salida||'" as '||contenido_sql||';';

END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.agrupacion_espacial_mixto_mv(
	esch text,
	vw_salida text,
	tabla_entrada_geom text,
	tabla_entrada_campos text,
	contenido_campos text,
	contenido_where text,
	srid1_a_cortar text,
	srid2_a_campos text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
	geome1 character varying;
    geome2 character varying;

	begin 
EXECUTE 'create table __nmtabe1 as select * from "'|| esch ||'"."'|| tabla_entrada_geom ||'"';
EXECUTE 'create table __nmtabe2 as select * from "'|| esch ||'"."'|| tabla_entrada_campos ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__nmtabe1';
SELECT f_geometry_column into geome2 FROM geometry_columns  WHERE  f_table_name = '__nmtabe2';
EXECUTE 'drop table __nmtabe1';
EXECUTE 'drop table __nmtabe2';

execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'"';
EXECUTE 'create materialized  view "'||esch||'"."'||vw_salida||'" as select  
'|| contenido_campos ||',ST_Transform(st_setsrid(a.'||geome1||','||srid1_a_cortar||'),4326)::geometry(Geometry, 4326) as geom from
(SELECT * from "'|| esch ||'"."'|| tabla_entrada_geom ||'") a,
(select * from "'|| esch ||'"."'|| tabla_entrada_campos ||'"  '|| contenido_where ||') b 
 where st_intersects (ST_Transform(st_setsrid(a.'||geome1||','||srid1_a_cortar||'),4326),ST_Transform(st_setsrid(b.'||geome2||','||srid2_a_campos||'),4326)) group by a.geom;';
	end;
$BODY$;



CREATE OR REPLACE FUNCTION funciones.agrupacion_espacial_mixto_vw(
	esch text,
	vw_salida text,
	tabla_entrada_geom text,
	tabla_entrada_campos text,
	contenido_campos text,
	contenido_where text,
	srid1_a_cortar text,
	srid2_a_campos text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
 DECLARE
	geome1 character varying;
    geome2 character varying;

	begin 
EXECUTE 'create table __nmtabe1 as select * from "'|| esch ||'"."'|| tabla_entrada_geom ||'"';
EXECUTE 'create table __nmtabe2 as select * from "'|| esch ||'"."'|| tabla_entrada_campos ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__nmtabe1';
SELECT f_geometry_column into geome2 FROM geometry_columns  WHERE  f_table_name = '__nmtabe2';
EXECUTE 'drop table __nmtabe1';
EXECUTE 'drop table __nmtabe2';



execute 'drop view if exists "'||esch||'"."'||vw_salida||'"';
EXECUTE 'create  view"'||esch||'"."'||vw_salida||'" as select  
'|| contenido_campos ||',ST_Transform(st_setsrid(a.'||geome1||','||srid1_a_cortar||'),4326)::geometry(Geometry, 4326) as geom from
(SELECT * from "'|| esch ||'"."'|| tabla_entrada_geom ||'") a,
(select * from "'|| esch ||'"."'|| tabla_entrada_campos ||'"  '|| contenido_where ||') b 
 where st_intersects (ST_Transform(st_setsrid(a.'||geome1||','||srid1_a_cortar||'),4326),ST_Transform(st_setsrid(b.'||geome2||','||srid2_a_campos||'),4326)) group by a.geom;';
	end;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.generica_mv(
	esch text,
	vw_salida text,
	contenido_sql text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
BEGIN
/*función para introducir código sql que crea vista o vista materializada*/

EXECUTE 'create materialized view "'||esch||'"."'||vw_salida||'" as '||contenido_sql||';';

END;
$BODY$;



CREATE OR REPLACE FUNCTION funciones.generica_vw(
	esch text,
	vw_salida text,
	contenido_sql text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
BEGIN
/*función para introducir código sql que crea vista o vista materializada*/

EXECUTE 'create view "'||esch||'"."'||vw_salida||'" as '||contenido_sql||';';

END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.padre_hijo_limites_administrativos_mixto_mv(
	esch text,
	table_a_contar text,
	vw_salida text,
	contenido text,
	contenido_where text,
	srid1 text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geome1 text;
tali text;

BEGIN

select string_agg(concat(operacion,'(',alias,')',' as ',alias),',')
from (select row_number() OVER () AS id_srm, unnest as alias from (select * from (select * from (select * from (select * from 
(select * from (select * from (select * from (select * from 
(select * from (select * from (select * from (select unnest(string_to_array
(unnest(string_to_array(contenido, ' as ')),',')))a
where unnest not like  ('%sum(%'))a where unnest not like  ('%count(%'))a
where unnest not like  ('%avg(%'))a where unnest not like  ('%stddev(%'))a where unnest not like  ('%max(%'))a
where unnest not like  ('%min(%'))a where unnest not like  ('%bool_and(%'))a where unnest not like  ('%bit_and(%'))a
where unnest not like  ('%bit_or(%'))a where unnest not like  ('%bool_or(%'))a where unnest not like  ('%every(%'))a
)a,
(select row_number() OVER () AS id_srm, replace as operacion from (select replace(unnest(string_to_array( unnest(string_to_array
(unnest(string_to_array(contenido, ' as ')),',')),'(')),' ',''))a
where replace in ('sum','count','avg','stddev','max','min','bool_and','bit_and','bit_or','bool_or','every'))b
where a.id_Srm=b.id_srm into tali;

EXECUTE 'create table __espaci1 as select * from "'|| esch ||'"."'|| table_a_contar ||'"';

SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__espaci1';

EXECUTE 'drop table __espaci1';

execute 'drop materialized view if exists "'||esch||'"."'||vw_salida||'_apoyo" cascade;';

execute 'CREATE materialized VIEW "'||esch||'"."'||vw_salida||'_apoyo"
 AS
select count(b.geom) as num_x,'||contenido||',
    a.municipio,a.natcode_municipio,
    a.natcode_provincia,
    a.natcode_ccaa,
    a.gid_0,a.name
   FROM (select * from "'||esch||'"."'||table_a_contar||'" '||contenido_where||' ) b
      JOIN multinivel.municipios a ON st_intersects(ST_Transform(st_setsrid(b.'||geome1||','||srid1||'),4326), a.geom)
  GROUP BY a.natcode_provincia, a.natcode_municipio,a.natcode_ccaa, a.gid_0, a.municipio,a.name
  ORDER BY (count(b.geom)) DESC';
  
execute 'create materialized view "'||esch||'"."'||vw_salida||'_z_4" as 
select '||tali||',
a.municipio,a.provincia,a.geom::geometry(Geometry, 4326) as geom 
from "'||esch||'"."'||vw_salida||'_apoyo" b RIGHT JOIN multinivel.municipios a
on a.natcode_municipio::text=b.natcode_municipio::text 
group by a.municipio,a.provincia,a.geom';

execute 'create materialized view "'||esch||'"."'||vw_salida||'_z_3" as 
select '||tali||',
a.provincia,a.ccaa,a.geom::geometry(Geometry, 4326) as geom 
from "'||esch||'"."'||vw_salida||'_apoyo" b RIGHT JOIN multinivel.provincias a
on a.natcode_provincia::text=b.natcode_provincia::text 
group by a.ccaa,a.provincia,a.geom';

execute 'create materialized view "'||esch||'"."'||vw_salida||'_z_2" as 
select '||tali||',
a.ccaa,a.name_0,a.geom::geometry(Geometry, 4326) as geom  
from "'||esch||'"."'||vw_salida||'_apoyo" b RIGHT JOIN multinivel.comunidades_mundo a
on a.natcode_ccaa::text=b.natcode_ccaa::text 
group by a.ccaa,a.name_0,a.geom';

execute 'create materialized view "'||esch||'"."'||vw_salida||'_z_1" as 
select '||tali||', a.name_0,a.name,a.geom::geometry(Geometry, 4326) as geom  
from "'||esch||'"."'||vw_salida||'_apoyo" b right join multinivel.paises a 
on b.gid_0::text=a.gid_0::text group by a.name_0,a.geom,a.name';

execute 'create materialized view "'||esch||'"."'||vw_salida||'_z_0" as 
select '||tali||', a.name,a.geom::geometry(Geometry, 4326) as geom  
from "'||esch||'"."'||vw_salida||'_apoyo" b right join multinivel.continentes a 
on b.name::text=a.name::text  group by a.name,a.geom ';

 END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.padre_hijo_limites_administrativos_mixto_vw(
	esch text,
	table_a_contar text,
	vw_salida text,
	contenido text,
	contenido_where text,
	srid1 text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geome1 text;
tali text;

BEGIN

select string_agg(concat(operacion,'(',alias,')',' as ',alias),',')
from (select row_number() OVER () AS id_srm, unnest as alias from (select * from (select * from (select * from (select * from 
(select * from (select * from (select * from (select * from 
(select * from (select * from (select * from (select unnest(string_to_array
(unnest(string_to_array(contenido, ' as ')),',')))a
where unnest not like  ('%sum(%'))a where unnest not like  ('%count(%'))a
where unnest not like  ('%avg(%'))a where unnest not like  ('%stddev(%'))a where unnest not like  ('%max(%'))a
where unnest not like  ('%min(%'))a where unnest not like  ('%bool_and(%'))a where unnest not like  ('%bit_and(%'))a
where unnest not like  ('%bit_or(%'))a where unnest not like  ('%bool_or(%'))a where unnest not like  ('%every(%'))a
)a,
(select row_number() OVER () AS id_srm, replace as operacion from (select replace(unnest(string_to_array( unnest(string_to_array
(unnest(string_to_array(contenido, ' as ')),',')),'(')),' ',''))a
where replace in ('sum','count','avg','stddev','max','min','bool_and','bit_and','bit_or','bool_or','every'))b
where a.id_Srm=b.id_srm into tali;

EXECUTE 'create table __espaci1 as select * from "'|| esch ||'"."'|| table_a_contar ||'"';

SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__espaci1';

EXECUTE 'drop table __espaci1';

execute 'drop  view if exists "'||esch||'"."'||vw_salida||'_apoyo" cascade;';

execute 'CREATE  VIEW "'||esch||'"."'||vw_salida||'_apoyo"
 AS
select count(b.geom) as num_x,'||contenido||',
    a.municipio,a.natcode_municipio,
    a.natcode_provincia,
    a.natcode_ccaa,
    a.gid_0,a.name
   FROM (select * from "'||esch||'"."'||table_a_contar||'" '||contenido_where||' ) b
      JOIN multinivel.municipios a ON st_intersects(ST_Transform(st_setsrid(b.'||geome1||','||srid1||'),4326), a.geom)
  GROUP BY a.natcode_provincia, a.natcode_municipio,a.natcode_ccaa, a.gid_0, a.municipio,a.name
  ORDER BY (count(b.geom)) DESC';
  
execute 'create  view "'||esch||'"."'||vw_salida||'_z_4" as 
select '||tali||',
a.municipio,a.provincia,a.geom::geometry(Geometry, 4326) as geom  
from "'||esch||'"."'||vw_salida||'_apoyo" b RIGHT JOIN multinivel.municipios a
on a.natcode_municipio::text=b.natcode_municipio::text 
group by a.municipio,a.provincia,a.geom';

execute 'create materialized view "'||esch||'"."'||vw_salida||'_z_3" as 
select '||tali||',
a.provincia,a.ccaa,a.geom::geometry(Geometry, 4326) as geom  
from "'||esch||'"."'||vw_salida||'_apoyo" b RIGHT JOIN multinivel.provincias a
on a.natcode_provincia::text=b.natcode_provincia::text 
group by a.ccaa,a.provincia,a.geom';

execute 'create  view "'||esch||'"."'||vw_salida||'_z_2" as 
select '||tali||',
a.ccaa,a.name_0,a.geom::geometry(Geometry, 4326) as geom  
from "'||esch||'"."'||vw_salida||'_apoyo" b RIGHT JOIN multinivel.comunidades_mundo a
on a.natcode_ccaa::text=b.natcode_ccaa::text 
group by a.ccaa,a.name_0,a.geom';

execute 'create  view "'||esch||'"."'||vw_salida||'_z_1" as 
select '||tali||', a.name_0,a.name,a.geom::geometry(Geometry, 4326) as geom  
from "'||esch||'"."'||vw_salida||'_apoyo" b right join multinivel.paises a 
on b.gid_0::text=a.gid_0::text group by a.name_0,a.geom,a.name';

execute 'create  view "'||esch||'"."'||vw_salida||'_z_0" as 
select '||tali||', a.name,a.geom::geometry(Geometry, 4326) as geom  
from "'||esch||'"."'||vw_salida||'_apoyo" b right join multinivel.continentes a 
on b.name::text=a.name::text  group by a.name,a.geom ';

 END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.get_http_text(
	contain text)
    RETURNS TABLE(ar text) 
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
    ROWS 1000
AS $BODY$
DECLARE
 pa   record; 
 am text;
BEGIN
select content FROM http_get
(contain) into am;
execute 'create table borrar_geo as select json_object_keys(properties)  as column_name  
from (select gid,geom,properties from  
(WITH data AS (select '''||am||'''::json AS fc)
SELECT
  row_number() OVER () AS gid,
  ST_GeomFromGeoJSON(feat->>''geometry'') AS geom,
  feat->''properties'' AS properties
FROM (
  SELECT json_array_elements(fc->''features'') AS feat
  FROM data
) AS f)a)a';

FOR pa IN 
        SELECT column_name
  FROM borrar_geo
 
	  LOOP
   ar:= 'properties ->> '''||pa.column_name||''' as '||pa.column_name||',';  RETURN NEXT;	END LOOP;
	execute 'drop table if exists borrar_geo';
	raise notice 'Value: % %', pa,contain;

END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.get_http_vw(
	esch text,
	vw text,
	contain text)
    RETURNS TABLE(te text) 
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
    ROWS 1000
AS $BODY$
DECLARE
	te text;
	am text;
	begin 
 select STRING_AGG(ar,' ') from (select funciones.get_http_text (contain) as ar) a into te;
 select content FROM http_get
(contain) into am;
 execute 'drop view if exists "'||esch||'"."'||vw||'"';
	execute 'create view "'||esch||'"."'||vw||'" as select '||te||' geom from 
(select gid,geom,properties from  
(WITH data AS (select (select content FROM http_get
('''||contain||'''))::json AS fc)
SELECT
  row_number() OVER () AS gid,
  ST_GeomFromGeoJSON(feat->>''geometry'') AS geom,
  feat->''properties'' AS properties
FROM (
  SELECT json_array_elements(fc->''features'') AS feat
  FROM data
) AS f)a)a' ;
	end;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.get_http_mv(
	esch text,
	vw text,
	contain text)
    RETURNS TABLE(te text) 
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
    ROWS 1000
AS $BODY$
DECLARE
	te text;
	am text;
	begin 
 select STRING_AGG(ar,' ') from (select funciones.get_http_text (contain) as ar) a into te;
 select content FROM http_get
(contain) into am;
 execute 'drop materialized view if exists "'||esch||'"."'||vw||'"';
	execute 'create materialized view "'||esch||'"."'||vw||'" as select '||te||' geom from 
(select gid,geom,properties from  
(WITH data AS (select (select content FROM http_get
('''||contain||'''))::json AS fc)
SELECT
  row_number() OVER () AS gid,
  ST_GeomFromGeoJSON(feat->>''geometry'') AS geom,
  feat->''properties'' AS properties
FROM (
  SELECT json_array_elements(fc->''features'') AS feat
  FROM data
) AS f)a)a' ;
	end;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.get_owm_text(
	ciudad text)
    RETURNS TABLE(ar text) 
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
    ROWS 1000
AS $BODY$
DECLARE
 pa   record; 
 --am text;
BEGIN
--select content FROM http_get
--(contain) into am;
execute 'create table borrar_geo_owm as select json_object_keys(content::json) as column_name
from http_get 
(''https://api.openweathermap.org/data/2.5/weather?units=metric&q='||ciudad||'&lang=en&appid=b7186bcc4eb7869e0fd3f2565e54a458'')
';

FOR pa IN 
        SELECT column_name
  FROM borrar_geo_owm
 
	  LOOP
   ar:= 'properties ->> '''||pa.column_name||''' as '||pa.column_name||',';  RETURN NEXT;	END LOOP;
	execute 'drop table if exists borrar_geo_owm';
	raise notice 'Value: % %', pa,ciudad;

END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.get_owm_mv(
	esch text,
	vw text,
	ciudad text)
    RETURNS TABLE(te text) 
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
    ROWS 1000
AS $BODY$
DECLARE
	te text;
	begin 
 select STRING_AGG(ar,' ') from (select funciones.get_owm_text (ciudad) as ar) a into te;

 execute 'drop materialized view if exists "'||esch||'"."'||vw||'"';
	execute 'create materialized view "'||esch||'"."'||vw||'" as select '||te||' current_time as time  from 
(select (content::json) as properties
from http_get 
(''https://api.openweathermap.org/data/2.5/weather?units=metric&q='||ciudad||'&lang=en&appid=b7186bcc4eb7869e0fd3f2565e54a458'')
)a' ;
	end;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.get_owm_vw(
	esch text,
	vw text,
	ciudad text)
    RETURNS TABLE(te text) 
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
    ROWS 1000
AS $BODY$
DECLARE
	te text;
	begin 
 select STRING_AGG(ar,' ') from (select funciones.get_owm_text (ciudad) as ar) a into te;

 execute 'drop  view if exists "'||esch||'"."'||vw||'"';
	execute 'create  view "'||esch||'"."'||vw||'" as select '||te||' current_time as time  from 
(select (content::json) as properties
from http_get 
(''https://api.openweathermap.org/data/2.5/weather?units=metric&q='||ciudad||'&lang=en&appid=b7186bcc4eb7869e0fd3f2565e54a458'')
)a' ;
	end;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.owm_centroid_masciudades_vw(
	esch text,
	vw text,
	lat text,
	lon text,
	num_city text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
	begin 
--num_city es el numero de ciudades maximo 50
 execute 'drop view if exists "'||esch||'"."'||vw||'"';
	execute 'create view "'||esch||'"."'||vw||'" as select 
''<style>table {  border: 3px solid #1FBAEB;    border-collapse: separate;       font-family: arial, sans-serif;width:100%; border-spacing: 2px;h1 {text-align: center;}p {text-align: center;}div {text-align: center;}th  {text-align: center;}</style><table>  <tr>    <td  style="text-align: left;"><a target=_blank><img src="https://i.imgur.com/WNKhNmc.png" style="width:20%;"></a></td> <td  style="text-align: right;"><a target=_blank><img src="https://openweathermap.org/themes/openweathermap/assets/img/logo_white_cropped.png" style="width:20%;"></a> </tr> 

<tr>  <th colspan="2" style="text-align: center;">TEMPERATURA</th> </tr> <tr>    <td  style="text-align: center;">Actual: ''||temp||'' ºC</td> <td  style="text-align: center;">Sensación térmica: ''||feels_like||'' ºC</td></tr> <tr>    <td  style="text-align: center;">MIN: ''||temp_min||'' ºC</td> <td  style="text-align: center;">MAX: ''||temp_max||'' ºC</td></tr>  <tr><td><br></br></td> <td></td> </tr>

<tr>  <th colspan="2" style="text-align: center;">CLIMA</th> </tr> <tr>    <td  style="text-align: center;">Presión: ''||pressure||'' hpa</td> <td  style="text-align: center;">Humedad: ''||humidity||'' %</td> </tr> <tr>    <td  style="text-align: center;">Nubes: ''||clouds||'' %</td> <td  style="text-align: center;">Descripcion: ''||description||''</td></tr>

 <tr><td><br></br></td> <td></td> </tr>

<tr>  <th colspan="2" style="text-align: center;">VIENTO</th> </tr> <tr>    <td  style="text-align: center;">Velocidad: ''||speed||'' m/s</td> <td  style="text-align: center;">Dirección: ''||deg||'' º</td> </tr>

<tr><td><br></br></td> <td></td> </tr>

<tr>  <th colspan="2" style="text-align: center;">LOCALIDAD</th> </tr> <tr>    <td  style="text-align: center;">País: ''||country||'' </td> <td  style="text-align: center;">Localidad: ''||name||'' </td> </tr>  <tr>    <td colspan="2" style="text-align: center;">Hora actual: ''||time||'' </td> </tr>
<tr><td><br></br></td> <td></td> </tr>'' as info

,st_setsrid(ST_MakePoint(lon::float,lat::float),4326) as geom from (select 
a.properties -> ''coord''  ->> ''lon''  AS lon,
a.properties -> ''coord''  ->> ''lat''  AS lat, 	
replace(replace(a.properties::text,''['','''')::text,'']'','''')::json -> ''weather''  ->> ''id''  AS id,
replace(replace(a.properties::text,''['','''')::text,'']'','''')::json -> ''weather''  ->> ''main''  AS main,
replace(replace(a.properties::text,''['','''')::text,'']'','''')::json -> ''weather''  ->> ''description''  AS description,
replace(replace(a.properties::text,''['','''')::text,'']'','''')::json -> ''weather''  ->> ''icon'' AS icon,
    a.properties ->> ''base''::text AS base,
	a.properties -> ''main''  ->> ''temp''  AS temp,
	a.properties -> ''main''  ->> ''feels_like''  AS feels_like,
	a.properties -> ''main''  ->> ''temp_min''  AS temp_min,
	a.properties -> ''main''  ->> ''temp_max''  AS temp_max,
	a.properties -> ''main''  ->> ''pressure''  AS pressure,
	a.properties -> ''main''  ->> ''humidity''  AS humidity,
    a.properties ->> ''visibility''::text AS visibility,
	a.properties -> ''wind''  ->> ''speed''  AS speed,
	a.properties -> ''wind''  ->> ''deg''  AS deg,
		a.properties -> ''rain''  ->> ''1h''  AS "1h",

    a.properties -> ''clouds'' ->> ''all'' AS clouds,
    a.properties ->> ''dt''::text AS dt,
    a.properties -> ''sys'' ->> ''type'' AS type,
	a.properties -> ''sys'' ->> ''country'' AS country,
	 split_part(split_part(to_timestamp((a.properties -> ''sys'' ->> ''sunrise'')::integer)::text,'' '',2),''+'',1) as sunrise,
	split_part(split_part(to_timestamp((a.properties -> ''sys'' ->> ''sunset'')::integer)::text,'' '',2),''+'',1) as sunset,
	
    a.properties ->> ''timezone''::text AS timezone,
    a.properties ->> ''id''::text AS id,
    a.properties ->> ''name''::text AS name,
    a.properties ->> ''cod''::text AS cod, split_part(current_time::text,''.'',1) as time from 
(select unnest(string_to_array(replace (list::text,''},{'',''}},{{''),''},{''))::json as properties from
(SELECT  substr(a.properties ->> ''list''::text, 2, length(a.properties ->> ''list''::text) - 2)  AS list
     from
(select (content::json) as properties from http_get 
(''http://api.openweathermap.org/data/2.5/find?lat='||lat||'&lon='||lon||'&cnt='||num_city||'&appid=b7186bcc4eb7869e0fd3f2565e54a458''
))a)a)a)a' ;
	end;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.owm_vw(
	esch text,
	vw text,
	ciudad text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
DECLARE
	begin 

 execute 'drop view if exists "'||esch||'"."'||vw||'"';
	execute 'create view "'||esch||'"."'||vw||'" as select 
''<style>table {  border: 3px solid #1FBAEB;    border-collapse: separate;       font-family: arial, sans-serif;width:100%; border-spacing: 2px;h1 {text-align: center;}p {text-align: center;}div {text-align: center;}th  {text-align: center;}</style><table>  <tr>    <td  style="text-align: left;"><a target=_blank><img src="https://i.imgur.com/WNKhNmc.png" style="width:20%;"></a></td> <td  style="text-align: right;"><a target=_blank><img src="https://openweathermap.org/themes/openweathermap/assets/img/logo_white_cropped.png" style="width:20%;"></a> </tr> 

<tr>  <th colspan="2" style="text-align: center;">TEMPERATURA</th> </tr> <tr>    <td  style="text-align: center;">Actual: ''||temp||'' ºC</td> <td  style="text-align: center;">Sensación térmica: ''||feels_like||'' ºC</td></tr> <tr>    <td  style="text-align: center;">MIN: ''||temp_min||'' ºC</td> <td  style="text-align: center;">MAX: ''||temp_max||'' ºC</td></tr>  <tr><td><br></br></td> <td></td> </tr>

<tr>  <th colspan="2" style="text-align: center;">CLIMA</th> </tr> <tr>    <td  style="text-align: center;">Presión: ''||pressure||'' hpa</td> <td  style="text-align: center;">Humedad: ''||humidity||'' %</td> </tr> <tr>    <td  style="text-align: center;">Nubes: ''||clouds||'' %</td> <td  style="text-align: center;">Descripcion: ''||description||''</td></tr>

 <tr><td><br></br></td> <td></td> </tr>

<tr>  <th colspan="2" style="text-align: center;">VIENTO</th> </tr> <tr>    <td  style="text-align: center;">Velocidad: ''||speed||'' m/s</td> <td  style="text-align: center;">Dirección: ''||deg||'' º</td> </tr>

<tr><td><br></br></td> <td></td> </tr>

<tr>  <th colspan="2" style="text-align: center;">CIUDAD</th> </tr> <tr>    <td  style="text-align: center;">País: ''||country||'' </td> <td  style="text-align: center;">Ciudad: ''||name||'' </td> </tr> <tr>    <td  style="text-align: center;">Amanecer: ''||sunrise||'' </td> <td  style="text-align: center;">Anochecer: ''||sunset||''</td></tr> <tr>    <td colspan="2" style="text-align: center;">Hora actual: ''||time||'' </td> </tr>
<tr><td><br></br></td> <td></td> </tr>'' as info

,st_setsrid(ST_MakePoint(lon::float,lat::float),4326) as geom from (select 
a.properties -> ''coord''  ->> ''lon''  AS lon,
a.properties -> ''coord''  ->> ''lat''  AS lat, 	
replace(replace(a.properties::text,''['','''')::text,'']'','''')::json -> ''weather''  ->> ''id''  AS id,
replace(replace(a.properties::text,''['','''')::text,'']'','''')::json -> ''weather''  ->> ''main''  AS main,
replace(replace(a.properties::text,''['','''')::text,'']'','''')::json -> ''weather''  ->> ''description''  AS description,
replace(replace(a.properties::text,''['','''')::text,'']'','''')::json -> ''weather''  ->> ''icon'' AS icon,
    a.properties ->> ''base''::text AS base,
	a.properties -> ''main''  ->> ''temp''  AS temp,
	a.properties -> ''main''  ->> ''feels_like''  AS feels_like,
	a.properties -> ''main''  ->> ''temp_min''  AS temp_min,
	a.properties -> ''main''  ->> ''temp_max''  AS temp_max,
	a.properties -> ''main''  ->> ''pressure''  AS pressure,
	a.properties -> ''main''  ->> ''humidity''  AS humidity,
    a.properties ->> ''visibility''::text AS visibility,
	a.properties -> ''wind''  ->> ''speed''  AS speed,
	a.properties -> ''wind''  ->> ''deg''  AS deg,
		a.properties -> ''rain''  ->> ''1h''  AS "1h",

    a.properties -> ''clouds'' ->> ''all'' AS clouds,
    a.properties ->> ''dt''::text AS dt,
    a.properties -> ''sys'' ->> ''type'' AS type,
	a.properties -> ''sys'' ->> ''country'' AS country,
	 split_part(split_part(to_timestamp((a.properties -> ''sys'' ->> ''sunrise'')::integer)::text,'' '',2),''+'',1) as sunrise,
	split_part(split_part(to_timestamp((a.properties -> ''sys'' ->> ''sunset'')::integer)::text,'' '',2),''+'',1) as sunset,
	
    a.properties ->> ''timezone''::text AS timezone,
    a.properties ->> ''id''::text AS id,
    a.properties ->> ''name''::text AS name,
    a.properties ->> ''cod''::text AS cod, split_part(current_time::text,''.'',1) as time from 
(select (content::json) as properties
from http_get 
(''https://api.openweathermap.org/data/2.5/weather?units=metric&q='||ciudad||'&lang=en&appid=b7186bcc4eb7869e0fd3f2565e54a458'')
)a)a' ;
	end;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.post_http_text(
	url text,
	contain text)
    RETURNS TABLE(ar text) 
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
    ROWS 1000
AS $BODY$
DECLARE
 pa   record; 
 am text;
BEGIN
select content FROM http_post
(url,contain,'application/x-www-form-urlencoded') into am;
execute 'create table borrar_geo as select column_name from (select json_object_keys(properties)  as column_name  
from (select gid,geom,properties from  
(WITH data AS (select '''||am||'''::json AS fc)
SELECT
  row_number() OVER () AS gid,
  ST_GeomFromGeoJSON(feat->>''geometry'') AS geom,
  feat->''properties'' AS properties
FROM (
  SELECT json_array_elements(fc->''features'') AS feat
  FROM data
) AS f)a)a)a group by column_name';

FOR pa IN 
        SELECT column_name
  FROM borrar_geo
 
	  LOOP
   ar:= 'properties ->> '''||pa.column_name||''' as '||pa.column_name||',';  RETURN NEXT;	END LOOP;
	execute 'drop table if exists borrar_geo';
	raise notice 'Value: % %', pa,contain;

END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.post_http_vw(
	esch text,
	vw text,
	url text,
	contain text)
    RETURNS TABLE(te text) 
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
    ROWS 1000
AS $BODY$
DECLARE
	te text;
	am text;
	begin 
 select STRING_AGG(ar,' ') from (select funciones.post_http_text (url,contain) as ar) a into te;
 select content FROM http_post
(url,contain,'application/x-www-form-urlencoded') into am;
 execute 'drop view if exists "'||esch||'"."'||vw||'"';
	execute 'create view "'||esch||'"."'||vw||'" as select '||te||' geom from 
(select gid,geom,properties from  
(WITH data AS (select (select content FROM http_post
('''||url||''','''||contain||''',''application/x-www-form-urlencoded''))::json AS fc)
SELECT
  row_number() OVER () AS gid,
  ST_GeomFromGeoJSON(feat->>''geometry'') AS geom,
  feat->''properties'' AS properties
FROM (
  SELECT json_array_elements(fc->''features'') AS feat
  FROM data
) AS f)a)a' ;
	end;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.text_geo(
	contain text)
    RETURNS TABLE(ar text) 
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
    ROWS 1000
AS $BODY$
DECLARE
 pa   record; 
 am text;
BEGIN
select content FROM http_get
(contain) into am;
execute 'create table borrar_geo as select json_object_keys(properties)  as column_name  
from (select gid,geom,properties from  
(WITH data AS (select '''||am||'''::json AS fc)
SELECT
  row_number() OVER () AS gid,
  ST_GeomFromGeoJSON(feat->>''geometry'') AS geom,
  feat->''properties'' AS properties
FROM (
  SELECT json_array_elements(fc->''features'') AS feat
  FROM data
) AS f)a)a';

FOR pa IN 
        SELECT column_name
  FROM borrar_geo
 
	  LOOP
   ar:= 'properties ->> '''||pa.column_name||''' as '||pa.column_name||',';  RETURN NEXT;	END LOOP;
	execute 'drop table if exists borrar_geo';
	raise notice 'Value: % %', pa,contain;

END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.ia_limpieza(
	esch text,
	vw_salida text,
	tabla_entrada text,
	area_min text,
	pk text)
    RETURNS void
    LANGUAGE 'plpgsql' 

   COST 100
    VOLATILE 
AS $BODY$
DECLARE
	geome1 character varying;
	begin 
	
EXECUTE 'create table __nmtab1 as select * from "'|| esch ||'"."'|| tabla_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__nmtabe1';
EXECUTE 'drop table __nmtabe1';

EXECUTE 'drop table if exists "'|| esch ||'".areas_grandes;';
EXECUTE 'create table "'|| esch ||'".areas_grandes
as select * from (select "'|| pk ||'" as id,ROUND(st_area ('|| geome1 ||'::Geography)::numeric,3),entity_index,score,'|| geome1 ||' from "'|| esch ||'"."'|| tabla_entrada||'")a
where ROUND::numeric > '''|| area_min ||''';';
EXECUTE 'CREATE INDEX " '|| esch ||'_areas_grandes_geom"
ON  "'|| esch ||'".areas_grandes  USING GIST (geom);';
EXECUTE 'drop table if exists "'|| esch ||'".areas_peque;';
EXECUTE 'create table "'|| esch ||'".areas_peque
as select * from (select "'|| pk ||'" as id,ROUND(st_area (geom::Geography)::numeric,3),entity_index,score,st_centroid(geom) as geoma,geom from "'|| esch ||'"."'|| tabla_entrada||'")a
where ROUND::numeric <= '''|| area_min ||''';';
EXECUTE 'CREATE INDEX  "'|| esch ||'_areas_peque_geom"
ON  "'|| esch ||'".areas_peque  USING GIST (geom);';

EXECUTE 'drop table if exists "'|| esch ||'".areas_peque_id;';
EXECUTE 'create table "'|| esch ||'".areas_peque_id as 
select a.id,b.geom from "'|| esch ||'".areas_grandes a,  "'|| esch ||'".areas_peque b
where st_contains (a.geom,b.geoma);';
EXECUTE 'CREATE INDEX  "'|| esch ||'_areas_peque_id_geom"
ON  "'|| esch ||'".areas_peque_id  USING GIST (geom);';

EXECUTE 'drop table if exists "'|| esch ||'".areas_peque_no;';
EXECUTE 'create table "'|| esch ||'".areas_peque_no as 
select a.geom from (select a.geom,b.id from "'|| esch ||'".areas_peque a left join "'|| esch ||'".areas_peque_id b
on st_intersects (a.geoma,b.geom))a
where id is null;';
EXECUTE 'CREATE INDEX  "'|| esch ||'_areas_peque_no_geom"
ON  "'|| esch ||'".areas_peque_no  USING GIST (geom);';

EXECUTE 'drop table if exists "'|| esch ||'".areas_peque_no_id;';
EXECUTE 'create table "'|| esch ||'".areas_peque_no_id as 
select a.id,b.geom from "'|| esch ||'".areas_grandes a,  "'|| esch ||'".areas_peque_no b
where st_touches (a.geom,b.geom);';
EXECUTE 'CREATE INDEX  "'|| esch ||'_areas_peque_no_id_geom"
ON  "'|| esch ||'".areas_peque_no_id  USING GIST (geom);';

EXECUTE 'drop table  if exists "'|| esch ||'".ia_fin1;';
EXECUTE 'create table "'|| esch ||'".ia_fin1 as
select id ,st_union(geom) as geom from 
(select id,geom from "'|| esch ||'".areas_peque_id 
union all select id,geom from "'|| esch ||'".areas_grandes
union all select id,geom from "'|| esch ||'".areas_peque_no_id)a
group by id;';
EXECUTE 'CREATE INDEX  "'|| esch ||'_aia_fin1_geom"
ON  "'|| esch ||'".ia_fin1  USING GIST (geom);';

EXECUTE 'drop table if exists "'|| esch ||'".ia_agujeros_peque;
create table "'|| esch ||'".ia_agujeros_peque as 
select  id,geom from (select ROUND(st_area (geom::Geography)::numeric,3),geom,id from 
(select (ST_DumpRings((st_dump(geom)).geom)).geom,id from "'|| esch ||'".ia_fin1
)a )a where round < '''|| area_min ||'''';

EXECUTE 'CREATE INDEX  "'|| esch ||'_ia_agujeros_peque_geom"
ON  "'|| esch ||'".ia_agujeros_peque  USING GIST (geom);';

EXECUTE 'drop table  if exists "'|| esch ||'".ia_fin2;';
EXECUTE 'create table "'|| esch ||'".ia_fin2 as
select id ,st_union(geom) as geom from 
(select id,geom from "'|| esch ||'".ia_fin1 
union all select id,geom from "'|| esch ||'".ia_agujeros_peque)a
group by id;';
EXECUTE 'CREATE INDEX  "'|| esch ||'_aia_fin2_geom"
ON  "'|| esch ||'".ia_fin2  USING GIST (geom);';
-----
EXECUTE 'drop table if exists "'|| esch ||'".ia_agujeros_peque;
create table "'|| esch ||'".ia_agujeros_peque as 
select  id,geom from (select ROUND(st_area (geom::Geography)::numeric,3),geom,id from 
(select (ST_DumpRings((st_dump(st_makevalid(geom))).geom)).geom,id from "'|| esch ||'".ia_fin2
)a )a where round < '''|| area_min ||'''';

EXECUTE 'CREATE INDEX  "'|| esch ||'_ia_agujeros_peque_geom"
ON  "'|| esch ||'".ia_agujeros_peque  USING GIST (geom);';

EXECUTE 'drop table  if exists "'|| esch ||'".ia_fin3;';
EXECUTE 'create table "'|| esch ||'".ia_fin3 as
select id ,st_union(geom) as geom from 
(select id,geom from "'|| esch ||'".ia_fin2 
union all select id,geom from "'|| esch ||'".ia_agujeros_peque)a
group by id;';
EXECUTE 'CREATE INDEX  "'|| esch ||'_ia_fin3_geom"
ON  "'|| esch ||'".ia_fin3  USING GIST (geom);';
------
EXECUTE 'drop table if exists "'|| esch ||'".ia_fin3_union;';
EXECUTE 'create table "'|| esch ||'".ia_fin3_union as select (st_dump(st_union (geom))).geom 
from "'|| esch ||'".ia_fin3;';
EXECUTE 'CREATE INDEX  "'|| esch ||'_ia_fin3_union_geom"
ON  "'|| esch ||'".ia_fin3_union  USING GIST (geom);';

EXECUTE 'drop table if exists "'|| esch ||'".ia_fin3_union_huecos;';
EXECUTE 'create table "'|| esch ||'".ia_fin3_union_huecos as 
select  ROUND(st_area (geom::Geography)::numeric,3) ,geom from (
	select ROUND(st_area (geom::Geography)::numeric,3),geom from 
(select (ST_DumpRings((st_dump(st_makevalid(geom))).geom)).geom from "'|| esch ||'".ia_fin3_union
)a )a where round < '''|| area_min ||'''';
EXECUTE 'CREATE INDEX  "'|| esch ||'_ia_fin3_union_huecos_geom"
ON  "'|| esch ||'".ia_fin3_union_huecos  USING GIST (geom);';

EXECUTE 'drop table if exists "'|| esch ||'".ia_fin3_sin_huecos';
EXECUTE 'create table "'|| esch ||'".ia_fin3_sin_huecos as select a.id,st_union(a.geom,b.geom) as geom
from "'|| esch ||'".ia_fin3 a  join
"'|| esch ||'".ia_fin3_union_huecos b on st_intersects(a.geom,b.geom)';
EXECUTE 'CREATE INDEX  "'|| esch ||'_ia_fin3_sin_huecos_geom"
ON  "'|| esch ||'".ia_fin3_sin_huecos  USING GIST (geom);';

EXECUTE 'drop table if exists "'|| esch ||'".ia_fin';
EXECUTE 'create table "'|| esch ||'".ia_fin as select a.id,st_union(a.geom) as geom from
(select id,geom from "'|| esch ||'".ia_fin3_sin_huecos union all
select id,geom from "'|| esch ||'".ia_fin3)a
group by id';
------
EXECUTE 'drop table if exists "'|| esch ||'"."'||vw_salida||'";';
EXECUTE 'create table "'|| esch ||'"."'||vw_salida||'" as
select a.*,b.geom as geoma from "'|| esch ||'".ia_fin b,
"'|| esch ||'"."'|| tabla_entrada||'" a
where a."'|| pk ||'" =b.id;';
EXECUTE 'alter table "'|| esch ||'"."'||vw_salida||'" drop column '|| geome1 ||';';
EXECUTE 'alter table "'|| esch ||'"."'||vw_salida||'" rename geoma to geom;';
EXECUTE 'CREATE INDEX  "'|| esch ||'_'||vw_salida||'_geom"
ON  "'|| esch ||'"."'||vw_salida||'"  USING GIST (geom);';

---borramos tablas intermedias
EXECUTE 'drop table  if exists "'|| esch ||'".ia_fin;';
EXECUTE 'drop table  if exists "'|| esch ||'".ia_fin1;';
EXECUTE 'drop table  if exists "'|| esch ||'".ia_fin2;';
EXECUTE 'drop table  if exists "'|| esch ||'".ia_fin3;';
EXECUTE 'drop table if exists "'|| esch ||'".areas_grandes;';
EXECUTE 'drop table if exists "'|| esch ||'".areas_peque_no;';
EXECUTE 'drop table if exists "'|| esch ||'".areas_peque_id;';
EXECUTE 'drop table if exists "'|| esch ||'".areas_peque;';
EXECUTE 'drop table if exists "'|| esch ||'".areas_peque_no_id;';
EXECUTE 'drop table if exists "'|| esch ||'".ia_agujeros_peque;';
EXECUTE 'drop table if exists "'|| esch ||'".ia_fin3_sin_huecos';
EXECUTE 'drop table if exists "'|| esch ||'".ia_fin3_union_huecos;';
EXECUTE 'drop table if exists "'|| esch ||'".ia_fin3_union;';


end; $BODY$;



CREATE OR REPLACE FUNCTION funciones.delaunytriangles_mv(
	esch text,
	tbl_entrada text,
	tbl_salida text,
	tolerancia text,
	inti text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geome1 text;
srid1 text;
BEGIN

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tbl_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| tbl_entrada ||'" group by ST_SRID;' into srid1;

EXECUTE 'create materialized view "'||esch||'"."'||tbl_salida||'" as 
select row_number() OVER () AS id'|| tbl_salida ||',st_transform(st_setsrid(geom, '||srid1||'),4326)::geometry(Geometry, 4326) as geom
from ( select (st_dump(ST_DelaunayTriangles(ST_Collect("'||geome1||'"),'||tolerancia||','||inti||' ))).geom as geom
from "'||esch||'"."'||tbl_entrada||'")a;';

END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.delaunytriangles_vw(
	esch text,
	tbl_entrada text,
	tbl_salida text,
	tolerancia text,
	inti text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geome1 text;
srid1 text;
BEGIN

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tbl_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| tbl_entrada ||'" group by ST_SRID;' into srid1;

EXECUTE 'create view "'||esch||'"."'||tbl_salida||'" as 
select row_number() OVER () AS id'|| tbl_salida ||',st_transform(st_setsrid(geom, '||srid1||'),4326)::geometry(Geometry, 4326) as geom
from ( select (st_dump(ST_DelaunayTriangles(ST_Collect("'||geome1||'"),'||tolerancia||','||inti||' ))).geom as geom
from "'||esch||'"."'||tbl_entrada||'")a;';

END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.delaunytriangles_tbl(
	esch text,
	tbl_entrada text,
	tbl_salida text,
	tolerancia text,
	inti text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geome1 text;
srid1 text;
BEGIN

EXECUTE 'create table __cespaci1 as select * from "'|| esch ||'"."'|| tbl_entrada ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__cespaci1';
EXECUTE 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| tbl_entrada ||'" group by ST_SRID;' into srid1;

EXECUTE 'create table "'||esch||'"."'||tbl_salida||'" as 
select row_number() OVER () AS id'|| tbl_salida ||',st_transform(st_setsrid(geom, '||srid1||'),4326)::geometry(Geometry, 4326) as geom
from ( select (st_dump(ST_DelaunayTriangles(ST_Collect("'||geome1||'"),'||tolerancia||','||inti||' ))).geom as geom
from "'||esch||'"."'||tbl_entrada||'")a;';

END;
$BODY$;

CREATE OR REPLACE FUNCTION funciones.palos_sueltos(
	esch text,
	tbl_entrada text,
	tbl_puntos_entrada text,
	distancia double precision,
	tbl_salida text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare filasd integer;
begin
/*función que puede servir de base para hacer algo similar a lineas telefónicas no esta en uso*/
EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos";';
EXECUTE 'create table "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos" as  select row_number() OVER () AS palo_final,*
from (select st_endpoint(geom) as geom,tramo from "'|| esch ||'"."'|| tbl_entrada ||'"
union all
select st_startpoint(geom) as geom,tramo from "'|| esch ||'"."'|| tbl_entrada ||'")a;';
EXECUTE 'CREATE INDEX "'|| esch ||''|| tbl_entrada ||'_puntos_sueltos_geom_gidx"
    ON "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos" USING gist
    (geom);';
	
EXECUTE 'CREATE TABLE "tmppuntos_linea_tension_ac_sueltos" as select * from "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos";';
select count(*) into filasd FROM tmppuntos_linea_tension_ac_sueltos;
EXECUTE 'drop TABLE "tmppuntos_linea_tension_ac_sueltos";';

EXECUTE 'drop table if exists  "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos_ordenados";';
EXECUTE 'create table "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos_ordenados" (id_palo serial primary key, id_prueba integer, geom geometry(Point,4326),
	palo_suelto integer,tramo integer,nuevo_tramo integer,grados double precision );';
EXECUTE 'CREATE INDEX "'|| esch ||''|| tbl_entrada ||'_puntos_sueltos_ordenados_geom_gidx"
    ON "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos_ordenados" USING gist
    (geom);';		

-- primer punto

EXECUTE 'insert into "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos_ordenados" (geom,palo_suelto,tramo, nuevo_tramo) select geom, palo_final, tramo, 1 as nuevo_tramo from 
(select distinct on (st_distance (a.geom,b.geom)) b.geom,palo_final,tramo
from 
(select geom, palo_final,tramo from "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos")b
left join
(select st_exteriorring(st_envelope(st_union(geom))) as geom from "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos")a 
 on ST_DWithin(a.geom,b.geom,(100/1.1132)*0.00001)
order by st_distance (a.geom,b.geom),b.palo_final limit 1)a;';

EXECUTE 'insert into "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos_ordenados" (geom,palo_suelto,nuevo_tramo,tramo) select geom,palo, 1 as nuevo_tramo,tramo from
(select a.* from (select/* distinct on (st_distance (a.geom,b.geom))*/ b.geom, a.tramo,st_distance (a.geom,b.geom),b.palo
from 
(select * from "'|| esch ||'"."'|| tbl_puntos_entrada ||'")b
left join
(select id_palo,geom,tramo from(select id_palo, geom,tramo from "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos_ordenados" 
 group by id_palo)a,(select max(id_palo) from "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos_ordenados")b where id_palo =max)a 
 on ST_DWithin(a.geom,b.geom,'|| distancia ||'))a left join
 "'|| esch ||'"."'|| tbl_puntos_entrada ||'" b on a.palo =b.palo where b.tramo<>a.tramo 
 and st_distance is not null order by st_distance limit 1)a;';

-- siguientes puntos sueltos
for i in 2..100 loop
EXECUTE 'insert into "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos_ordenados" (geom,palo_suelto,tramo, nuevo_tramo) select a.geom, palo_final, a.tramo,'||i||' as nuevo_tramo from 
(select * from (select b.geom,palo_final,st_distance (a.geom,b.geom),tramo
from 
(select geom, palo_final,tramo from "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos")b
left join
(select st_exteriorring(st_envelope(st_union(geom))) as geom from (select a.* from (select * from "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos")a left join
 (select * from "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos_ordenados")b on a.palo_final =b.palo_suelto where b.id_palo is null)a)a 
 on ST_DWithin(a.geom,b.geom,'|| distancia ||'))a where st_distance = 0)a left join 
 (select * from "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos_ordenados")b on a.palo_final =b.palo_suelto where b.id_palo is null
 limit 1;';

EXECUTE 'insert into "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos_ordenados" (geom,palo_suelto,nuevo_tramo,tramo) select geom,palo, '||i||' as nuevo_tramo,tramo from
(select a.* from (select/* distinct on (st_distance (a.geom,b.geom))*/ b.geom, a.tramo,st_distance (a.geom,b.geom),b.palo
from 
(select * from "'|| esch ||'"."'|| tbl_puntos_entrada ||'")b
left join
(select id_palo,geom,tramo from(select id_palo, geom,tramo from "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos_ordenados" 
 group by id_palo)a,(select max(id_palo) from "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos_ordenados")b where id_palo =max)a 
 on ST_DWithin(a.geom,b.geom,'|| distancia ||'))a left join
 "'|| esch ||'"."'|| tbl_puntos_entrada ||'" b on a.palo =b.palo where b.tramo<>a.tramo 
 and st_distance is not null order by st_distance limit 1)a;';
end loop;

--crear lineas
EXECUTE 'drop table if exists  "'|| esch ||'"."'|| tbl_entrada ||'_perdidas";';
EXECUTE 'create table "'|| esch ||'"."'|| tbl_entrada ||'_perdidas" as select st_makeline (geom) as geom, nuevo_tramo 
from   "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos_ordenados" group by nuevo_tramo order by nuevo_tramo;';

EXECUTE 'drop table if exists  "'|| esch ||'"."'|| tbl_salida ||'";';
EXECUTE 'create table "'|| esch ||'"."'|| tbl_salida ||'" as 
select row_number() OVER () AS tramo,* from (select (st_dump(st_union(geom))).geom as geom from (select * from "'|| esch ||'"."'|| tbl_entrada ||'_perdidas"
union all 
select * from "'|| esch ||'"."'|| tbl_entrada ||'")a)a;';
EXECUTE 'drop table if exists "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos";';
EXECUTE 'drop table if exists  "'|| esch ||'"."'|| tbl_entrada ||'_puntos_sueltos_ordenados";';
EXECUTE 'drop table if exists  "'|| esch ||'"."'|| tbl_entrada ||'_perdidas";';

end;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.spatial_join_vw(
	esch text,
	name_table1 text,
	name_table2 text,
	view_salida text,
	tipo_de_interseccion text,
	contenido text,
	tipo_join text)
    RETURNS text
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare geome1 character varying;
declare	geome2 character varying;
declare tab text;
declare srid1 text;
declare srid2 text;

BEGIN

/*Descripcion: crea una vista o vista materializada que comprueba la matriz 9d y extrae si es cierto su intersección si no hay correspondencia retorna vista vacia*/

EXECUTE 'create table __nmtab1 as select * from "'|| esch ||'"."'|| name_table1 ||'"';
EXECUTE 'create table __nmtab2 as select * from "'|| esch ||'"."'|| name_table2 ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__nmtab1';
SELECT f_geometry_column into geome2 FROM geometry_columns  WHERE  f_table_name = '__nmtab2';
EXECUTE 'drop table __nmtab1';
EXECUTE 'drop table __nmtab2';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| name_table1 ||'" group by ST_SRID;' into srid1;
EXECUTE 'select ST_SRID("'||geome2||'") from  "'|| esch ||'"."'|| name_table2 ||'" group by ST_SRID;' into srid2;

CASE
  ---- los cualquier interaccion entre las dos geometrias canta
  WHEN tipo_de_interseccion = 'interseccion' and tipo_join = 'left' THEN
EXECUTE 'create  view "'|| esch ||'"."'|| view_salida ||'" as 
select  ROW_NUMBER() OVER () as  fid_'|| name_table1 ||','|| contenido||' from 
"'|| esch ||'"."'|| name_table1 ||'"  left join
"'|| esch ||'"."'|| name_table2 ||'"  
on ST_intersects (st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome1 ||'",'||srid1||'),4326),st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome2 ||'",'||srid2||'),4326)) ;';
ELSE tab := 'no interseccion dentro';
  END CASE;
  CASE
  ---- los puntos entre a y be se tocan solo en su superficie
      WHEN tipo_de_interseccion = 'tocan' and tipo_join = 'left' THEN
EXECUTE 'create  view "'|| esch ||'"."'|| view_salida ||'" as 
select  ROW_NUMBER() OVER () as  fid_'|| name_table1 ||','|| contenido||' from 
"'|| esch ||'"."'|| name_table1 ||'"  left join
"'|| esch ||'"."'|| name_table2 ||'"  
on ST_touches (st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome1 ||'",'||srid1||'),4326),st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome2 ||'",'||srid2||'),4326)) ;';
ELSE tab := 'no touch';
END CASE;
  CASE
  --- a contiene a b
      WHEN tipo_de_interseccion = 'contiene' and tipo_join = 'left' THEN
EXECUTE 'create  view "'|| esch ||'"."'|| view_salida ||'" as 
select  ROW_NUMBER() OVER () as  fid_'|| name_table1 ||','|| contenido||' from 
"'|| esch ||'"."'|| name_table1 ||'"  left join
"'|| esch ||'"."'|| name_table2 ||'"  
on ST_Contains (st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome1 ||'",'||srid1||'),4326),st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome2 ||'",'||srid2||'),4326)) ;';
ELSE tab := 'no contiene';
END CASE;
  CASE
  --no todos los puntos esan en el interior del otro
      WHEN tipo_de_interseccion = 'cruzan' and tipo_join = 'left'  THEN
EXECUTE 'create  view "'|| esch ||'"."'|| view_salida ||'" as 
select  ROW_NUMBER() OVER () as  fid_'|| name_table1 ||','|| contenido||' from 
"'|| esch ||'"."'|| name_table1 ||'"  left join
"'|| esch ||'"."'|| name_table2 ||'"  
on ST_Crosses (st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome1 ||'",'||srid1||'),4326),st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome2 ||'",'||srid2||'),4326)) ;';
ELSE tab := 'no interseccion dentro';
END CASE;
CASE
  ---- los cualquier interaccion entre las dos geometrias canta
  WHEN tipo_de_interseccion = 'interseccion' and tipo_join = 'inner' THEN
EXECUTE 'create  view "'|| esch ||'"."'|| view_salida ||'" as 
select  ROW_NUMBER() OVER () as  fid_'|| name_table1 ||','|| contenido||' from 
"'|| esch ||'"."'|| name_table1 ||'"  inner join
"'|| esch ||'"."'|| name_table2 ||'"  
on ST_intersects (st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome1 ||'",'||srid1||'),4326),st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome2 ||'",'||srid2||'),4326)) ;';
ELSE tab := 'no interseccion dentro';
  END CASE;
  CASE
  ---- los puntos entre a y be se tocan solo en su superficie
      WHEN tipo_de_interseccion = 'tocan' and tipo_join = 'inner' THEN
EXECUTE 'create  view "'|| esch ||'"."'|| view_salida ||'" as 
select  ROW_NUMBER() OVER () as  fid_'|| name_table1 ||','|| contenido||' from 
"'|| esch ||'"."'|| name_table1 ||'"  inner join
"'|| esch ||'"."'|| name_table2 ||'"  
on ST_touches (st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome1 ||'",'||srid1||'),4326),st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome2 ||'",'||srid2||'),4326)) ;';
ELSE tab := 'no touch';
END CASE;
  CASE
  --- a contiene a b
      WHEN tipo_de_interseccion = 'contiene' and tipo_join = 'inner' THEN
EXECUTE 'create  view "'|| esch ||'"."'|| view_salida ||'" as 
select  ROW_NUMBER() OVER () as  fid_'|| name_table1 ||','|| contenido||' from 
"'|| esch ||'"."'|| name_table1 ||'"  inner join
"'|| esch ||'"."'|| name_table2 ||'"  
on ST_Contains (st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome1 ||'",'||srid1||'),4326),st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome2 ||'",'||srid2||'),4326)) ;';
ELSE tab := 'no contiene';
END CASE;
  CASE
  --no todos los puntos esan en el interior del otro
      WHEN tipo_de_interseccion = 'cruzan' and tipo_join = 'inner'  THEN
EXECUTE 'create  view "'|| esch ||'"."'|| view_salida ||'" as 
select  ROW_NUMBER() OVER () as  fid_'|| name_table1 ||','|| contenido||' from 
"'|| esch ||'"."'|| name_table1 ||'"   inner join
"'|| esch ||'"."'|| name_table2 ||'"  
on ST_Crosses (st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome1 ||'",'||srid1||'),4326),st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome2 ||'",'||srid2||'),4326)) ;';
ELSE tab := 'no interseccion dentro';
END CASE;
Return tab;
END;
$BODY$;
	
	
CREATE OR REPLACE FUNCTION funciones.spatial_join_mv(
	esch text,
	name_table1 text,
	name_table2 text,
	view_salida text,
	tipo_de_interseccion text,
	contenido text,
	tipo_join text)
    RETURNS text
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare geome1 character varying;
declare	geome2 character varying;
declare tab text;
declare srid1 text;
declare srid2 text;

BEGIN

/*Descripcion: crea una vista o vista materializada que comprueba la matriz 9d y extrae si es cierto su intersección si no hay correspondencia retorna vista vacia*/

EXECUTE 'create table __nmtab1 as select * from "'|| esch ||'"."'|| name_table1 ||'"';
EXECUTE 'create table __nmtab2 as select * from "'|| esch ||'"."'|| name_table2 ||'"';
SELECT f_geometry_column into geome1 FROM geometry_columns  WHERE  f_table_name = '__nmtab1';
SELECT f_geometry_column into geome2 FROM geometry_columns  WHERE  f_table_name = '__nmtab2';
EXECUTE 'drop table __nmtab1';
EXECUTE 'drop table __nmtab2';
EXECUTE 'select ST_SRID("'||geome1||'") from  "'|| esch ||'"."'|| name_table1 ||'" group by ST_SRID;' into srid1;
EXECUTE 'select ST_SRID("'||geome2||'") from  "'|| esch ||'"."'|| name_table2 ||'" group by ST_SRID;' into srid2;

CASE
  ---- los cualquier interaccion entre las dos geometrias canta
  WHEN tipo_de_interseccion = 'interseccion' and tipo_join = 'left' THEN
EXECUTE 'create  materialized view "'|| esch ||'"."'|| view_salida ||'" as 
select  ROW_NUMBER() OVER () as  fid_'|| name_table1 ||','|| contenido||' from 
"'|| esch ||'"."'|| name_table1 ||'"  left join
"'|| esch ||'"."'|| name_table2 ||'"  
on ST_intersects (st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome1 ||'",'||srid1||'),4326),st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome2 ||'",'||srid2||'),4326)) ;';
ELSE tab := 'no interseccion dentro';
  END CASE;
  CASE
  ---- los puntos entre a y be se tocan solo en su superficie
      WHEN tipo_de_interseccion = 'tocan' and tipo_join = 'left' THEN
EXECUTE 'create  materialized view "'|| esch ||'"."'|| view_salida ||'" as 
select  ROW_NUMBER() OVER () as  fid_'|| name_table1 ||','|| contenido||' from 
"'|| esch ||'"."'|| name_table1 ||'"  left join
"'|| esch ||'"."'|| name_table2 ||'"  
on ST_touches (st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome1 ||'",'||srid1||'),4326),st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome2 ||'",'||srid2||'),4326)) ;';
ELSE tab := 'no touch';
END CASE;
  CASE
  --- a contiene a b
      WHEN tipo_de_interseccion = 'contiene' and tipo_join = 'left' THEN
EXECUTE 'create  materialized view "'|| esch ||'"."'|| view_salida ||'" as 
select  ROW_NUMBER() OVER () as  fid_'|| name_table1 ||','|| contenido||' from 
"'|| esch ||'"."'|| name_table1 ||'"  left join
"'|| esch ||'"."'|| name_table2 ||'"  
on ST_Contains (st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome1 ||'",'||srid1||'),4326),st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome2 ||'",'||srid2||'),4326)) ;';
ELSE tab := 'no contiene';
END CASE;
  CASE
  --no todos los puntos esan en el interior del otro
      WHEN tipo_de_interseccion = 'cruzan' and tipo_join = 'left'  THEN
EXECUTE 'create  materialized view "'|| esch ||'"."'|| view_salida ||'" as 
select  ROW_NUMBER() OVER () as  fid_'|| name_table1 ||','|| contenido||' from 
"'|| esch ||'"."'|| name_table1 ||'"  left join
"'|| esch ||'"."'|| name_table2 ||'"  
on ST_Crosses (st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome1 ||'",'||srid1||'),4326),st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome2 ||'",'||srid2||'),4326)) ;';
ELSE tab := 'no interseccion dentro';
END CASE;
CASE
  ---- los cualquier interaccion entre las dos geometrias canta
  WHEN tipo_de_interseccion = 'interseccion' and tipo_join = 'inner' THEN
EXECUTE 'create  materialized view "'|| esch ||'"."'|| view_salida ||'" as 
select  ROW_NUMBER() OVER () as  fid_'|| name_table1 ||','|| contenido||' from 
"'|| esch ||'"."'|| name_table1 ||'"  inner join
"'|| esch ||'"."'|| name_table2 ||'"  
on ST_intersects (st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome1 ||'",'||srid1||'),4326),st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome2 ||'",'||srid2||'),4326)) ;';
ELSE tab := 'no interseccion dentro';
  END CASE;
  CASE
  ---- los puntos entre a y be se tocan solo en su superficie
      WHEN tipo_de_interseccion = 'tocan' and tipo_join = 'inner' THEN
EXECUTE 'create  materialized view "'|| esch ||'"."'|| view_salida ||'" as 
select  ROW_NUMBER() OVER () as  fid_'|| name_table1 ||','|| contenido||' from 
"'|| esch ||'"."'|| name_table1 ||'"  inner join
"'|| esch ||'"."'|| name_table2 ||'"  
on ST_touches (st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome1 ||'",'||srid1||'),4326),st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome2 ||'",'||srid2||'),4326)) ;';
ELSE tab := 'no touch';
END CASE;
  CASE
  --- a contiene a b
      WHEN tipo_de_interseccion = 'contiene' and tipo_join = 'inner' THEN
EXECUTE 'create  materialized view "'|| esch ||'"."'|| view_salida ||'" as 
select  ROW_NUMBER() OVER () as  fid_'|| name_table1 ||','|| contenido||' from 
"'|| esch ||'"."'|| name_table1 ||'"  inner join
"'|| esch ||'"."'|| name_table2 ||'"  
on ST_Contains (st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome1 ||'",'||srid1||'),4326),st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome2 ||'",'||srid2||'),4326)) ;';
ELSE tab := 'no contiene';
END CASE;
  CASE
  --no todos los puntos esan en el interior del otro
      WHEN tipo_de_interseccion = 'cruzan' and tipo_join = 'inner'  THEN
EXECUTE 'create  materialized view "'|| esch ||'"."'|| view_salida ||'" as 
select  ROW_NUMBER() OVER () as  fid_'|| name_table1 ||','|| contenido||' from 
"'|| esch ||'"."'|| name_table1 ||'"   inner join
"'|| esch ||'"."'|| name_table2 ||'"  
on ST_Crosses (st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome1 ||'",'||srid1||'),4326),st_transform(st_setsrid("'|| name_table1 ||'"."'|| geome2 ||'",'||srid2||'),4326)) ;';
ELSE tab := 'no interseccion dentro';
END CASE;
Return tab;
END;
$BODY$;



CREATE OR REPLACE FUNCTION funciones.log_ddl()

  RETURNS event_trigger AS $$

DECLARE

  audit_query TEXT;

  r RECORD;
  row record;
  tabla text;
  conteo_nuevo bigint;
  conteo_antiguo bigint;
  nombre text;
  nuevo_nombre text;


BEGIN
/* función que tiene como base una tabla semilla y una tabla copia que se comunican entre sí para saber que sucede en la semilla 
y poder replicarlo a las demás, se recomiendan hacer las variaciones en la tabla semilla en momentos donde la base d edatos no sufra cambios*/

/* lanzar en la base de datos de catalogo_usuarios
CREATE EVENT TRIGGER log_ddl_info ON ddl_command_end EXECUTE PROCEDURE funciones.log_ddl();*/


 r := pg_event_trigger_ddl_commands();

select SPLIT_PART(r.object_identity,'.',2) into tabla;


select count (*) as num_nuevo from (SELECT a.attname as column_name
FROM pg_attribute a
 JOIN pg_class t on a.attrelid = t.oid  JOIN pg_namespace s on t.relnamespace = s.oid
WHERE a.attnum > 0 AND NOT a.attisdropped AND t.relname = 'layerserversemilla' 
  AND s.nspname = 'semilla'  ORDER BY a.attnum)a into conteo_nuevo;

select count (*)  as num_antiguo from (SELECT a.attname as column_name
FROM pg_attribute a
 JOIN pg_class t on a.attrelid = t.oid  JOIN pg_namespace s on t.relnamespace = s.oid
WHERE a.attnum > 0 AND NOT a.attisdropped AND t.relname = 'layerserversemilla2' 
  AND s.nspname = 'semilla'  ORDER BY a.attnum)a into conteo_antiguo;
  
  IF tg_tag = 'ALTER TABLE' and conteo_nuevo > conteo_antiguo and tabla = 'layerserversemilla'

  THEN
 
select  concat('"',new_column,'"',' ', data_type) as nueva_column into nombre from (select a.column_name as old_column,b.column_name as new_column,b.data_type from 
( select column_name, data_type from information_schema.columns 
  where table_schema = 'semilla' and table_name = 'layerserversemilla2')a right join
 ( select column_name, data_type from information_schema.columns 
  where table_schema = 'semilla' and table_name = 'layerserversemilla')b on a.column_name = b.column_name)a where old_column is null
  group by new_column,data_type;
  

execute 'alter table semilla.layerserversemilla2 add column '||nombre||';';

FOR row IN 
        SELECT
            table_schema,
            table_name
        FROM
            information_schema.tables  
        WHERE
            table_schema <> 'public' and table_schema <> 'pg_catalog'  and table_schema <> 'tiger'  and table_schema <> 'information_schema'
     and table_schema <> 'topology'  and table_schema <> 'semilla'
    LOOP
        EXECUTE 'alter TABLE "'||row.table_schema ||'"."'||row.table_name||'" add column '||nombre||';';
    END LOOP;

  END IF;
  
  IF tg_tag = 'ALTER TABLE' and conteo_nuevo < conteo_antiguo and tabla = 'layerserversemilla'

  THEN

select  old_column into nombre from (select a.column_name as old_column,b.column_name as new_column,b.data_type from 
( select column_name, data_type from information_schema.columns 
  where table_schema = 'semilla' and table_name = 'layerserversemilla2')a left join
 ( select column_name, data_type from information_schema.columns 
  where table_schema = 'semilla' and table_name = 'layerserversemilla')b on a.column_name = b.column_name)a where new_column is null;
  

execute 'alter table semilla.layerserversemilla2 drop column "'||nombre||'";';

FOR row IN 
        SELECT
            table_schema,
            table_name
        FROM
            information_schema.tables  
        WHERE
            table_schema <> 'public' and table_schema <> 'pg_catalog'  and table_schema <> 'tiger'  and table_schema <> 'information_schema'
     and table_schema <> 'topology'  and table_schema <> 'semilla'
    LOOP
        EXECUTE 'alter TABLE "'||row.table_schema ||'"."'||row.table_name||'" drop column "'||nombre||'";';
    END LOOP;
	
  END IF;
  
	IF tg_tag = 'ALTER TABLE' and conteo_nuevo = conteo_antiguo and tabla = 'layerserversemilla'

  THEN
  
 select  new_column into nuevo_nombre from (select a.column_name as old_column,b.column_name as new_column,b.data_type from 
( select column_name, data_type from information_schema.columns 
  where table_schema = 'semilla' and table_name = 'layerserversemilla2')a right join
 ( select column_name, data_type from information_schema.columns 
  where table_schema = 'semilla' and table_name = 'layerserversemilla')b on a.column_name = b.column_name)a where old_column is null;
  
select  old_column into nombre from (select a.column_name as old_column,b.column_name as new_column,b.data_type from 
( select column_name, data_type from information_schema.columns 
  where table_schema = 'semilla' and table_name = 'layerserversemilla2')a left join
 ( select column_name, data_type from information_schema.columns 
  where table_schema = 'semilla' and table_name = 'layerserversemilla')b on a.column_name = b.column_name)a where new_column is null;
  

execute 'alter table semilla.layerserversemilla2 rename column "'||nombre||'" to "'||nuevo_nombre||'";';

FOR row IN 
        SELECT
            table_schema,
            table_name
        FROM
            information_schema.tables  
        WHERE
            table_schema <> 'public' and table_schema <> 'pg_catalog'  and table_schema <> 'tiger'  and table_schema <> 'information_schema'
     and table_schema <> 'topology'  and table_schema <> 'semilla'
    LOOP
        EXECUTE 'alter TABLE "'||row.table_schema ||'"."'||row.table_name||'" rename column "'||nombre||'" to "'||nuevo_nombre||'";';
    END LOOP;
  END IF;

END;

$$ LANGUAGE plpgsql;




CREATE OR REPLACE FUNCTION funciones.h3_agrupacion(
	sch text,
	tbl text,
	tbl_salida text,
	h3_zoom text)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
declare 
geoma text;
srid1 text;

BEGIN
---función por terminar queda darle una vuelta al tema de ifs

Execute 'create table __cespaci1 as select * from "'|| sch ||'"."'|| tbl ||'"'; 

SELECT f_geometry_column into geoma FROM geometry_columns  WHERE  f_table_name = '__cespaci1'; 

Execute 'drop table __cespaci1';
EXECUTE 'select ST_SRID("'||geoma||'") from  "'|| sch ||'"."'|| tbl ||'" group by ST_SRID' into srid1; 

Execute 'drop table if exists "'||sch||'"."'||tbl||'_apoyo" ;';
Execute 'create table "'||sch||'"."'||tbl||'_apoyo" as select * from "'||sch||'"."'||tbl||'";';
Execute 'create index '||sch||'_'||tbl||'_apoyo_geom_idx ON "'||sch||'"."'||tbl||'_apoyo" USING GIST (geom);';

Execute 'drop table if exists "'||sch||'".hex01 ;';

if h3_zoom = '1'  
then 
Execute 'create table "'||sch||'".hex01 as select count,h3_index,h3_index as h3_to_parent,''1'' as ide,a.geom from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                    h3_geo_to_h3index(st_centroid(a_2.geom), 1) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''9''::double precision, ''9''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a;';
  END IF;
  IF  h3_zoom > '1' then
Execute 'create table "'||sch||'".hex01 as select count,h3_index,h3_index as h3_to_parent,''1'' as ide,a.geom from
( SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                    h3_geo_to_h3index(st_centroid(a_2.geom), 1) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''9''::double precision, ''9''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a, "'||sch||'"."'||tbl||'_apoyo" b
  where st_contains(st_transform(st_setsrid(b."'||geoma||'", '||srid1||'), 4326),a.geom);';
end if;

Execute 'create index '||sch||'_hex01_geom_idx ON "'||sch||'".hex01 USING GIST (geom);';

Execute 'drop table if exists "'||sch||'".hex02;';

if h3_zoom = '2'  
then
Execute 'create table "'||sch||'".hex02 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,1),''2'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 2) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''2.5''::double precision, ''2.5''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a)r left join
  "'||sch||'".hex01 b
  on b.h3_index=r.h3_to_parent) t where ides is null;
  create index '||sch||'_hex02_geom_idx ON "'||sch||'".hex02 USING GIST (geom);';
   END IF;
  IF  h3_zoom < '2' then execute 'create table "'||sch||'".hex02 as select null as count, null as h3_index,null as h3_to_parent,null as ide, null as geom from  "'||sch||'"."'||tbl||'_apoyo"';
 END IF;
  IF h3_zoom > '2' THEN

Execute 'create table "'||sch||'".hex02 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,1),''2'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 2) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''2.5''::double precision, ''2.5''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a, "'||sch||'"."'||tbl||'_apoyo" b
  where st_contains(st_transform(st_setsrid(b."'||geoma||'", '||srid1||'), 4326),a.geom))r left join
  "'||sch||'".hex01 b
  on b.h3_index=r.h3_to_parent) t where ides is null;
  create index '||sch||'_hex02_geom_idx ON "'||sch||'".hex02 USING GIST (geom);';
  END IF;
  
  Execute 'drop table if exists "'||sch||'".hex03;';

if h3_zoom = '3'  
then
Execute 'create table "'||sch||'".hex03 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,2),''3'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 3) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.82''::double precision, ''0.82''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a)r left join
  "'||sch||'".hex02 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex03_geom_idx ON "'||sch||'".hex03 USING GIST (geom);';
  
   END IF;
  IF   h3_zoom < '3' then execute 'create table "'||sch||'".hex03 as select null as count, null as h3_index,null as h3_to_parent,null as ide, null as geom from  "'||sch||'"."'||tbl||'_apoyo"';
END IF;
  IF h3_zoom > '3' then 

Execute 'create table "'||sch||'".hex03 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,2),''3'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 3) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.82''::double precision, ''0.82''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a, "'||sch||'"."'||tbl||'_apoyo" b
  where st_contains(st_transform(st_setsrid(b."'||geoma||'", '||srid1||'), 4326),a.geom))r left join
  "'||sch||'".hex02 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex03_geom_idx ON "'||sch||'".hex03 USING GIST (geom);';
 
   end if;

Execute 'drop table if exists "'||sch||'".hex04;';

if h3_zoom = '4'  
then
Execute 'create table "'||sch||'".hex04 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,3),''4'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 4) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.35''::double precision, ''0.35''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a)r left join
  "'||sch||'".hex03 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex04_geom_idx ON "'||sch||'".hex04 USING GIST (geom);';
  
   END IF;
  IF  h3_zoom < '4' then execute 'create table "'||sch||'".hex04 as select null as count, null as h3_index,null as h3_to_parent,null as ide, null as geom from  "'||sch||'"."'||tbl||'_apoyo"';
END IF;
  IF  h3_zoom > '4' then

Execute 'create table "'||sch||'".hex04 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,3),''4'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 4) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.35''::double precision, ''0.35''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a, "'||sch||'"."'||tbl||'_apoyo" b
  where st_contains(st_transform(st_setsrid(b."'||geoma||'", '||srid1||'), 4326),a.geom))r left join
  "'||sch||'".hex03 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex04_geom_idx ON "'||sch||'".hex04 USING GIST (geom);';
   end if; 
   
Execute 'drop table if exists "'||sch||'".hex05;';

if h3_zoom = '5'  
then
Execute 'create table "'||sch||'".hex05 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,3) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,4),''5'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 5) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.12''::double precision, ''0.12''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a)r left join
  "'||sch||'".hex04 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex03 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex05_geom_idx ON "'||sch||'".hex05 USING GIST (geom);';
  
   END IF;
  IF  h3_zoom < '5' then execute 'create table "'||sch||'".hex05 as select null as count, null as h3_index,null as h3_to_parent,null as ide, null as geom from  "'||sch||'"."'||tbl||'_apoyo"';
END IF;
  IF  h3_zoom > '5' then

Execute 'create table "'||sch||'".hex05 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,3) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,4),''5'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 5) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.12''::double precision, ''0.12''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a, "'||sch||'"."'||tbl||'_apoyo" b
  where st_contains(st_transform(st_setsrid(b."'||geoma||'", '||srid1||'), 4326),a.geom))r left join
  "'||sch||'".hex04 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex03 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex05_geom_idx ON "'||sch||'".hex05 USING GIST (geom);';
   end if;
   
 Execute 'drop table if exists "'||sch||'".hex06;';
 
if h3_zoom = '6'  
then 
Execute 'create table "'||sch||'".hex06 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,3) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,4) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,5),''6'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 6) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.049''::double precision, ''0.049''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a)r left join
  "'||sch||'".hex05 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex04 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex03 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex06_geom_idx ON "'||sch||'".hex06 USING GIST (geom);';
  
   END IF;
  IF   h3_zoom < '6' then execute 'create table "'||sch||'".hex06 as select null as count, null as h3_index,null as h3_to_parent,null as ide, null as geom from  "'||sch||'"."'||tbl||'_apoyo"';
END IF;
  IF  h3_zoom > '6' then

Execute 'create table "'||sch||'".hex06 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,3) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,4) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,5),''6'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 6) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.049''::double precision, ''0.049''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a, "'||sch||'"."'||tbl||'_apoyo" b
  where st_contains(st_transform(st_setsrid(b."'||geoma||'", '||srid1||'), 4326),a.geom))r left join
  "'||sch||'".hex05 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex04 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex03 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex06_geom_idx ON "'||sch||'".hex06 USING GIST (geom);';
  
     end if;
 Execute 'drop table if exists "'||sch||'".hex07;';
 
 if h3_zoom = '7'  
then 
Execute 'create table "'||sch||'".hex07 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,3) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,4) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,5) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,6),''7'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 7) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.015''::double precision, ''0.015''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a)r left join
  "'||sch||'".hex06 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex05 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex04 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex03 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex07_geom_idx ON "'||sch||'".hex07 USING GIST (geom);';
  
   END IF;
  IF   h3_zoom < '7' then execute 'create table "'||sch||'".hex07 as select null as count, null as h3_index,null as h3_to_parent,null as ide, null as geom from  "'||sch||'"."'||tbl||'_apoyo"';
END IF;
  IF  h3_zoom > '7' then

Execute 'create table "'||sch||'".hex07 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,3) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,4) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,5) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,6),''7'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 7) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.015''::double precision, ''0.015''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a, "'||sch||'"."'||tbl||'_apoyo" b
  where st_contains(st_transform(st_setsrid(b."'||geoma||'", '||srid1||'), 4326),a.geom))r left join
  "'||sch||'".hex06 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex05 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex04 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex03 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex07_geom_idx ON "'||sch||'".hex07 USING GIST (geom);';
  
    end if;
 Execute 'drop table if exists "'||sch||'".hex08;';
 
 if h3_zoom = '8'  
then  
Execute 'create table "'||sch||'".hex08 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,3) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,4) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,5) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,6) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,7),''8'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 8) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.0048''::double precision, ''0.0048''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a)r left join
  "'||sch||'".hex07 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex06 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex05 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex04 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex03 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex08_geom_idx ON "'||sch||'".hex08 USING GIST (geom);';
  
  END IF;
  IF   h3_zoom < '8' then execute 'create table "'||sch||'".hex08 as select null as count, null as h3_index,null as h3_to_parent,null as ide, null as geom from  "'||sch||'"."'||tbl||'_apoyo"';
END IF;
  IF  h3_zoom > '8' then

Execute 'create table "'||sch||'".hex08 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,3) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,4) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,5) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,6) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,7),''8'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 8) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.0048''::double precision, ''0.0048''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a, "'||sch||'"."'||tbl||'_apoyo" b
  where st_contains(st_transform(st_setsrid(b."'||geoma||'", '||srid1||'), 4326),a.geom))r left join
  "'||sch||'".hex07 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex06 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex05 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex04 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex03 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex08_geom_idx ON "'||sch||'".hex08 USING GIST (geom);';
   end if;
   
Execute 'drop table if exists "'||sch||'".hex09;';

 if h3_zoom = '9'  
then 
Execute 'create table "'||sch||'".hex09 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,3) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,4) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,5) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,6) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,7) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,8),''9'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 9) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.002''::double precision, ''0.002''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a)r left join
  "'||sch||'".hex08 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex07 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex06 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex05 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex04 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex03 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex09_geom_idx ON "'||sch||'".hex09 USING GIST (geom);';
  
  END IF;
  IF  h3_zoom < '9' then execute 'create table "'||sch||'".hex09 as select null as count, null as h3_index,null as h3_to_parent,null as ide, null as geom from  "'||sch||'"."'||tbl||'_apoyo"';
END IF;
  IF h3_zoom > '9' then

Execute 'create table "'||sch||'".hex09 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,3) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,4) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,5) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,6) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,7) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,8),''9'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 9) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.002''::double precision, ''0.002''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a, "'||sch||'"."'||tbl||'_apoyo" b
  where st_contains(st_transform(st_setsrid(b."'||geoma||'", '||srid1||'), 4326),a.geom))r left join
  "'||sch||'".hex08 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex07 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex06 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex05 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex04 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex03 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex09_geom_idx ON "'||sch||'".hex09 USING GIST (geom);';
  end if;
  
Execute 'drop table if exists "'||sch||'".hex10;';

 if h3_zoom = '10'  
then 
Execute 'create table "'||sch||'".hex10 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,3) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,4) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,5) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,6) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,7) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,8) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,9),''10'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 10) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.00085''::double precision, ''0.00085''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a)r left join
  "'||sch||'".hex09 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex08 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex07 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex06 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex05 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex04 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex03 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex10_geom_idx ON "'||sch||'".hex10 USING GIST (geom);';
  
  END IF;
  IF   h3_zoom < '10' then execute 'create table "'||sch||'".hex10 as select null as count, null as h3_index,null as h3_to_parent,null as ide, null as geom from  "'||sch||'"."'||tbl||'_apoyo"';
END IF;
  IF  h3_zoom > '10' then

Execute 'create table "'||sch||'".hex10 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,3) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,4) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,5) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,6) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,7) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,8) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,9),''10'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 10) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.00085''::double precision, ''0.00085''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a, "'||sch||'"."'||tbl||'_apoyo" b
  where st_contains(st_transform(st_setsrid(b."'||geoma||'", '||srid1||'), 4326),a.geom))r left join
  "'||sch||'".hex09 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex08 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex07 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex06 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex05 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex04 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex03 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex10_geom_idx ON "'||sch||'".hex10 USING GIST (geom);';
   end if;
   
   Execute 'drop table if exists "'||sch||'".hex11;';

 if h3_zoom = '11'  
then
Execute 'create table "'||sch||'".hex11 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,3) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,4) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,5) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,6) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,7) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,8) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,9) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,10),''11'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 11) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.00038''::double precision, ''0.00038''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a)r left join
  "'||sch||'".hex10 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex09 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex08 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex07 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex06 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex05 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex04 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex03 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex11_geom_idx ON "'||sch||'".hex11 USING GIST (geom);';
  
  END IF;
  IF   h3_zoom < '11' then execute 'create table "'||sch||'".hex11 as select null as count, null as h3_index,null as h3_to_parent,null as ide, null as geom from  "'||sch||'"."'||tbl||'_apoyo"';
END IF;
  IF  h3_zoom > '11' then

Execute 'create table "'||sch||'".hex11 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,3) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,4) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,5) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,6) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,7) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,8) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,9) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,10),''11'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 11) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.00038''::double precision, ''0.00038''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a, "'||sch||'"."'||tbl||'_apoyo" b
  where st_contains(st_transform(st_setsrid(b."'||geoma||'", '||srid1||'), 4326),a.geom))r left join
  "'||sch||'".hex10 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex09 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex08 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex07 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex06 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex05 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex04 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex03 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex11_geom_idx ON "'||sch||'".hex11 USING GIST (geom);';
     end if;

  Execute 'drop table if exists "'||sch||'".hex12;';
 
  if h3_zoom = '12'  
then

Execute 'create table "'||sch||'".hex12 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,3) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,4) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,5) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,6) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,7) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,8) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,9) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,10) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,11),''12'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 12) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.00014''::double precision, ''0.00014''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a)r left join
  "'||sch||'".hex11 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex10 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex09 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex08 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex07 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex06 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex05 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex04 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex03 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex12_geom_idx ON "'||sch||'".hex12 USING GIST (geom);';
  
  END IF;
  IF  h3_zoom < '12' then execute 'create table "'||sch||'".hex12 as select null as count, null as h3_index,null as h3_to_parent,null as ide, null as geom from  "'||sch||'"."'||tbl||'_apoyo"';
END IF;
  IF h3_zoom > '12' then

Execute 'create table "'||sch||'".hex12 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,3) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,4) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,5) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,6) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,7) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,8) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,9) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,10) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,11),''12'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 12) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.00014''::double precision, ''0.00014''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a, "'||sch||'"."'||tbl||'_apoyo" b
  where st_contains(st_transform(st_setsrid(b."'||geoma||'", '||srid1||'), 4326),a.geom))r left join
  "'||sch||'".hex11 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex10 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex09 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex08 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex07 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex06 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex05 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex04 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex03 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex12_geom_idx ON "'||sch||'".hex12 USING GIST (geom);';
  end if;
  
  Execute 'drop table if exists "'||sch||'".hex13;';
  
   if h3_zoom = '13'  
then
Execute 'create table "'||sch||'".hex13 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,3) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,4) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,5) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,6) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,7) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,8) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,9) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,10) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,11) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,12),''13'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 13) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.000055''::double precision, ''0.000055''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a)r left join
  "'||sch||'".hex12 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex11 b 
  on b.h3_index=r.abuelo) t where ides is null)r  left join "'||sch||'".hex10 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex09 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex08 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex07 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex06 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex05 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex04 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex03 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex13_geom_idx ON "'||sch||'".hex13 USING GIST (geom);';
  
  END IF;
  IF  h3_zoom < '13' then execute 'create table "'||sch||'".hex13 as select null as count, null as h3_index,null as h3_to_parent,null as ide, null as geom from  "'||sch||'"."'||tbl||'_apoyo"';
END IF;
  IF h3_zoom > '13' then

Execute 'create table "'||sch||'".hex13 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,3) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,4) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,5) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,6) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,7) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,8) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,9) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,10) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,11) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,12),''13'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 13) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.000055''::double precision, ''0.000055''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a, "'||sch||'"."'||tbl||'_apoyo" b
  where st_contains(st_transform(st_setsrid(b."'||geoma||'", '||srid1||'), 4326),a.geom))r left join
  "'||sch||'".hex12 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex11 b 
  on b.h3_index=r.abuelo) t where ides is null)r  left join "'||sch||'".hex10 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex09 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex08 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex07 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex06 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex05 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex04 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex03 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex13_geom_idx ON "'||sch||'".hex13 USING GIST (geom);';
    end if;

  Execute 'drop table if exists "'||sch||'".hex14;';
  
  
    if h3_zoom = '14'  
then 

Execute 'create table "'||sch||'".hex14 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,3) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,4) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,5) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,6) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,7) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,8) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,9) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,10) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,11) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,12) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,13),''14'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 14) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.00002''::double precision, ''0.00002''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a)r left join
  "'||sch||'".hex13 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex12 b 
  on b.h3_index=r.abuelo) t where ides is null)r  left join "'||sch||'".hex11 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex10 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex09 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex08 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex07 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex06 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex05 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex04 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex03 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex14_geom_idx ON "'||sch||'".hex14 USING GIST (geom);';
  
  END IF;
  IF  h3_zoom < '14' then execute 'create table "'||sch||'".hex14 as select null as count, null as h3_index,null as h3_to_parent,null as ide, null as geom from  "'||sch||'"."'||tbl||'_apoyo"';
END IF;
  IF h3_zoom > '14' then

Execute 'create table "'||sch||'".hex14 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,3) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,4) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,5) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,6) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,7) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,8) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,9) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,10) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,11) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,12) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,13),''14'' as ide from
(SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                   h3_geo_to_h3index(st_centroid(a_2.geom), 14) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.00002''::double precision, ''0.00002''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a, "'||sch||'"."'||tbl||'_apoyo" b
  where st_contains(st_transform(st_setsrid(b."'||geoma||'", '||srid1||'), 4326),a.geom))r left join
  "'||sch||'".hex13 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex12 b 
  on b.h3_index=r.abuelo) t where ides is null)r  left join "'||sch||'".hex11 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex10 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex09 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex08 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex07 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex06 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex05 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex04 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex03 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex14_geom_idx ON "'||sch||'".hex14 USING GIST (geom);';
    end if;
  
Execute 'drop table if exists "'||sch||'".hex15;';

    if h3_zoom = '15'  
then 

Execute 'create table "'||sch||'".hex15 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,3) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,4) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,5) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,6) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,7) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,8) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,9) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,10) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,11) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,12) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,13) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,14),''15'' as ide from
( SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                    h3_geo_to_h3index(st_centroid(a_2.geom), 15) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.000008''::double precision, ''0.000008''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a)r left join
  "'||sch||'".hex14 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex13 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex12 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex11 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex10 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex09 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex08 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex07 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex06 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex05 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex04 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex03 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex15_geom_idx ON "'||sch||'".hex15 USING GIST (geom);';
  
END IF;
  IF   h3_zoom < '15' then execute 'create table "'||sch||'".hex15 as select null as count, null as h3_index,null as h3_to_parent,null as ide, null as geom from  "'||sch||'"."'||tbl||'_apoyo"';
END IF;
  IF   h3_zoom > '15' then

Execute 'create table "'||sch||'".hex15 as 
select count,h3_index,h3_to_parent,ide,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,1) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,2) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,3) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,4) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,5) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,6) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,7) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,8) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,9) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,10) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,11) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,12) as abuelo,geom from (select r.*,b.ide as ides from 
(select count,h3_index,h3_to_parent,ide,h3_to_parent(h3_index,13) as abuelo,geom from (select r.*,b.ide as ides from 
		(select a.*,h3_to_parent(h3_index,14),''15'' as ide from
( SELECT count(*) AS count,
    a.h3_index,
    st_setsrid(h3_h3index_to_geoboundary(a.h3_index), 4326)::geometry(Geometry,4326) AS geom
   FROM ( SELECT a_1.id_pol,
            a_1.h3_index
           FROM ( SELECT a_2.id_pol,
                    h3_geo_to_h3index(st_centroid(a_2.geom), 15) AS h3_index
                   FROM ( SELECT a_3.id_pol,
                            (st_dump(st_transform(st_setsrid(a_3.geom, '||srid1||'), 4326))).geom AS geom
                           FROM ( SELECT row_number() OVER () AS id_pol,
                                    t.geom
                                   FROM 
( SELECT funciones.__crear_tesela(st_makevalid("'||tbl||'_apoyo"."'||geoma||'"), ''0.000008''::double precision, ''0.000008''::double precision) AS geom
   FROM "'||sch||'"."'||tbl||'_apoyo") t) a_3) a_2) a_1
          GROUP BY a_1.h3_index, a_1.id_pol) a
  GROUP BY a.h3_index) a)r left join
  "'||sch||'".hex14 b
  on b.h3_index=r.h3_to_parent) t where ides is null)r left join "'||sch||'".hex13 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex12 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex11 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex10 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex09 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex08 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex07 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex06 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex05 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex04 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex03 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex02 b 
  on b.h3_index=r.abuelo) t where ides is null)r left join "'||sch||'".hex01 b 
  on b.h3_index=r.abuelo) t where ides is null;
  create index '||sch||'_hex15_geom_idx ON "'||sch||'".hex15 USING GIST (geom);';
    end if;

/*Execute 'drop table if exists"'||sch||'"."'||tbl_salida||'";';
Execute 'create table "'||sch||'"."'||tbl_salida||'" as select * from  "'||sch||'".hex15
union all  select * from "'||sch||'".hex14 union all   select * from "'||sch||'".hex13 union all  
select * from "'||sch||'".hex12
union all  select * from "'||sch||'".hex11 union all   select * from "'||sch||'".hex10 union all  
select * from "'||sch||'".hex09
union all  select * from "'||sch||'".hex08 union all   select * from "'||sch||'".hex07 union all 
select * from "'||sch||'".hex06
union all  select * from "'||sch||'".hex05 union all   select * from "'||sch||'".hex04 union all  
select * from "'||sch||'".hex03
union all  select * from "'||sch||'".hex02 union all   select * from "'||sch||'".hex01;';*/

/*Execute 'drop table if exists"'||sch||'".hex15;';Execute 'drop table if exists"'||sch||'".hex14;';Execute 'drop table if exists"'||sch||'".hex13;';
Execute 'drop table if exists"'||sch||'".hex12;';Execute 'drop table if exists"'||sch||'".hex11;';Execute 'drop table if exists"'||sch||'".hex10;';
Execute 'drop table if exists"'||sch||'".hex09;';Execute 'drop table if exists"'||sch||'".hex08;';Execute 'drop table if exists"'||sch||'".hex07;';
Execute 'drop table if exists"'||sch||'".hex06;';Execute 'drop table if exists"'||sch||'".hex05;';Execute 'drop table if exists"'||sch||'".hex04;';
Execute 'drop table if exists"'||sch||'".hex03;';Execute 'drop table if exists"'||sch||'".hex02;';Execute 'drop table if exists"'||sch||'".hex01;';
Execute 'drop table if exists"'||sch||'"."'||tbl||'_apoyo";';*/
  	END;
$BODY$;


CREATE OR REPLACE FUNCTION funciones.apagar_clientes_geoserver()
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$

BEGIN
-- función por terminar cuando se cree el servicio de reinicio de geoserver en python solo habría que elegir el get y post y mandar la url
SELECT 
    pg_terminate_backend(pid) 
FROM pg_stat_activity 
WHERE pid <> pg_backend_pid()    AND application_name = 'PostgreSQL JDBC Driver';

select http_get
('url');
select content FROM http_post
(url,contain,'application/x-www-form-urlencoded');

END;  
$BODY$;

/*Función que devuelve el tipo de dato de postgres correspondiente al tipo de dato de json introducido como parámetro.*/
CREATE OR REPLACE FUNCTION funciones.tipo_json_pg(tipojson text) RETURNS text 
AS $$
DECLARE
	sTipoPg text;
BEGIN
	CASE tipojson 
		
		WHEN 'DateTime' THEN 
			sTipoPg:='timestamp';
		WHEN 'Float' THEN
			sTipoPg:='double precision';
		WHEN 'Integer' THEN
			sTipoPg:='integer';
		WHEN 'Number' THEN 
			sTipoPg:='numeric';
		WHEN 'Text' THEN 
			sTipoPg:='text';
		WHEN 'String' THEN 
			sTipoPg:='text';
		WHEN 'geo:json' THEN
			sTipoPg:='json';
		WHEN 'boolean' THEN 
			sTipoPg:='boolean';
	ELSE 
		sTipoPg:='';
	END CASE;
	RETURN sTipoPg;
END;
$$ language 'plpgsql' STRICT IMMUTABLE;

--Función para obtener el token del servicio fiware

CREATE OR REPLACE FUNCTION funciones.fiware_token 
(
	version_token char(2),
	url_token text,
	application_id text,
	application_secret text,
	fiware_user text,
	fiware_password text,
	service text,
	subservice text
	
) RETURNS text 
AS $$ 

	DECLARE
		application text;
		urlTokenIp varchar;
		encoded_auth_token varchar;
		sHeadersToken varchar;
		sContentTypeToken varchar;
		sDataToken varchar;
		jContentToken json;
		sHeadersTokenResult text[];
		access_token text;
		sSql text;
	BEGIN 
	/* PASO 1. Obtención del token para el servicio KeyRock. Con el application_id y application_secret se tiene que obtener un token codificado en base 64.
	*/
		IF version_token='V1' THEN
			application:=application_id||':'||application_secret;
			EXECUTE 'SELECT encode('||quote_literal(application)||', '||quote_literal('base64')||')::text'
			INTO encoded_auth_token;
			--DEBBUG
			--RAISE NOTICE 'encoded_auth_token: %',encoded_auth_token;
		END IF;
	--Se realiza la petición HTTP de tipo POST
	--Obtenemos la dirección ip de la url de petición del token
		urlTokenIp:= split_part(url_token,'/',3);
		--DEBUGG
		--RAISE NOTICE 'urlTokenIp %',urlTokenIp;
		--RETURN;
		IF version_token='V1' THEN
			sHeadersToken:= 
				'ARRAY 
					[
						http_header(''HOST'', '''||urlTokenIp||'''),
						http_header(''Authorization'',''Basic OTMyZDU2MTctNmNlZS00YTEyLWEyMDMtNjc5MGI1NjQyNTM4OjdhZGUzMjc4LWJhZjYtNDQ2Ni1iNDYyLTY4M2E2NmRhOGJlOQ=='')
					]';
			sContentTypeToken:= 'application/x-www-form-urlencoded';
			sDataToken:= 'grant_type=password&username='||fiware_user||'&password='||fiware_password;
			sSql:= '
				SELECT content::json->>''access_token''
				FROM
					http (
							(
								''POST'',
								'''||url_token||''','
								||sHeadersToken||',
								'''||sContentTypeToken||''',
								'''||sDataToken||'''
							)::http_request
					)';
		ELSE 
			sHeadersToken:= 'NULL';
			sContentTypeToken:='application/json';
			sDataToken:='{"auth": {
					"identity": {
						"methods": [
							"password"
						],
						"password": {
							"user": {
								"domain": {
									"name": "'||service||'"
								},
								"name": "'||fiware_user||'",
								"password": "'||fiware_password||'"
							}
						}
					},
					"scope": {
						"project": {
							"domain": {
								"name": "'||service||'"
							},
							"name": "'||subservice||'"
						}
					}
				}
			   }';
			sSql:= '
				WITH 
					headers as 
						(SELECT (unnest(headers)).*
						FROM
							http (
									(
										''POST'',
										'''||url_token||''','
										||sHeadersToken||',
										'''||sContentTypeToken||''',
										'''||sDataToken||'''
									)::http_request
								)
						)
						SELECT value FROM headers WHERE field=''X-Subject-Token''';
		END IF;
			

		--DEBUG 
		--RAISE NOTICE 'sSql token: %',sSql;
		PERFORM http_set_curlopt('CURLOPT_SSL_VERIFYHOST', url_token);
		EXECUTE sSql INTO access_token;
		RETURN access_token;
	END;
$$ language 'plpgsql' VOLATILE;

CREATE OR REPLACE FUNCTION funciones.fiware_json 
(
	version_token char(2),
	url_token text,
	url_cb text,
	application_id text,
	application_secret text,
	fiware_user text,
	fiware_password text,
	service text,
	subservice text,
	entity_name text
) RETURNS json
AS $$

	DECLARE
		sParamType text;
		access_token text;
		sContentType text ='';
		sSql text;
		jJson text;
	BEGIN
		access_token:= funciones.fiware_token
		(
			version_token,
			url_token,
			application_id,
			application_secret,
			fiware_user,
			fiware_password,
			service,
			subservice 
		);
		sParamType:='?type='||entity_name;
		--sSql:= 'SELECT json_array_elements(content::json) as content
		sSql:= 'SELECT content as content
				FROM http 
						(
							(
								''GET'',
								'''||url_cb||sParamType||''',
								ARRAY 
									[
										http_header(''Fiware-Service'','''||service||'''),
										http_header(''Fiware-ServicePath'','''||subservice||'''),
										http_header(''X-Auth-Token'','''||access_token||''')'
										||sContentType||'
									],
								NULL,
								NULL
							)::http_request
						)';
		EXECUTE sSql INTO jJson;
		RETURN jJson;
	END;
$$ language 'plpgsql' VOLATILE;

/* Función que crea una vista o vista materializada a partir de un servicio fiware*/
--DROP FUNCTION funciones.__wrapper_fiware;
CREATE OR REPLACE FUNCTION funciones.__wrapper_fiware 
(
	esch text,
	vw_salida text,
	version_token char(2),
	url_token text,
	url_cb text,
	application_id text,
	application_secret text,
	fiware_user text,
	fiware_password text,
	service text,
	subservice text,
	entity_name text,
	georref_type text,
	georref_attr text,
	materialized boolean
	
) RETURNS void
AS $$
DECLARE	
	application text;
	sSql text;
	urlTokenIp varchar;
	encoded_auth_token varchar;
	sHeadersToken varchar;
	sContentTypeToken varchar;
	sDataToken varchar;
	jContentToken json;
	sHeadersTokenResult text[];
	access_token text;
	sContentType text ='';
	jsonObjeto json;
	sParamType text;
	aKeys text[];
	sKey text;
	jValue json;
	sKeyTipo text;
	sKeyTipoPg text;
	aSelect text[];
	sSelect text;
	sCampoGeom text;
	sTipoGeom text;
	sCampoLon text;
	sCampoLat text;
	nLongitud numeric;
	nLatitud numeric;
	sAddressType text;
	sAddress text;
	vwType text;
	
BEGIN

/*Chequeo de los parámetros introducidos*/
-- georref_type dentro de los valores permitidos
	IF georref_type NOT IN('location','LonLat','address') THEN
		RAISE EXCEPTION 'Tipo de georreferenciación no válido: %', georref_type;
	END IF;
	
-- Si los parámetros application_id y application_secret vienen nulos, se les da el valor de texto NULL, para que entren así en la consulta final
	IF application_id IS NULL THEN 
		application_id:='NULL';
	END IF;
	IF application_secret IS NULL THEN 
		application_secret:='NULL';
	END IF;
	

/* PASO 1. Obtención del token para el servicio KeyRock. Con el application_id y application_secret se tiene que obtener un token codificado en base 64.
*/
	
	access_token:= funciones.fiware_token
		(
			version_token,
			url_token,
			application_id,
			application_secret,
			fiware_user,
			fiware_password,
			service,
			subservice 
		);
	--DEBUG
	--RAISE NOTICE 'access_token: %',access_token;


/*Paso 2. Obtención de las entidades*/

	sParamType:='?type='||entity_name;
	jsonObjeto:= funciones.fiware_json (
		version_token,
		url_token,
		url_cb,
		application_id,
		application_secret,
		fiware_user,
		fiware_password,
		service,
		subservice,
		entity_name
	);
	
	--DEBUG 
	--RAISE NOTICE 'jsonObjeto: %',jsonObjeto;
	
	FOR sKey,jValue IN SELECT * from json_each(jsonObjeto->0) LOOP
		--DEBUG	
		--RAISE NOTICE 'sKey %', sKey;
		--RAISE NOTICE 'sValue %', jValue;
		IF sKey = 'type' THEN 
			CONTINUE;
		END IF;
		
		IF sKey = 'id' THEN 
			sKeyTipo:='text';
			aSelect:= array_append(aSelect,'content#>>''{id}'' AS id');
		ELSEIF 
			
			sKeyTipo <> 'array' THEN
			sKeyTipo:= jValue#>>'{type}';
			--RAISE NOTICE 'sKeyTipo: %',sKeyTipo;
			
			sKeyTipoPg:=funciones.tipo_json_pg(sKeyTipo);
			IF sKeyTipoPg='' THEN 
				sKeyTipoPg:='text';
			END IF;
			aSelect:= array_append(aSelect,'(content#>>''{'||sKey||',value}'')::'||sKeyTipoPg||' AS "'||sKey||'"');
		ELSE 
			aSelect:= array_append(aSelect,'content#>''{'||sKey||',value}'' AS "'||sKey||'"');
		END IF;
		
		--DEBUG
		--RAISE NOTICE '%', array_to_string(aSelect,',');
	END LOOP;
	
	CASE georref_type 
			WHEN 'LonLat' THEN 
				
				sCampoLon:= trim(split_part(georref_attr,',',1));
				sCampoLat:= trim(split_part(georref_attr,',',2));
				
				sCampoGeom:= 'st_setsrid
								(st_makepoint
									(
										(content#>>''{'||sCampoLon||',value}'')::numeric,
										(content#>>''{'||sCampoLat||',value}'')::numeric
									),4326
								)::geometry (point,4326) AS geom';
				aSelect:=aSelect || sCampoGeom;
			WHEN 'location' THEN 
				sTipoGeom:= (jsonObjeto->0)#>>'{location,value,type}'; 
				sCampoGeom:= 'st_setsrid
								(
									st_geomfromgeojson 
										(
											(content#>>''{'||georref_attr||',value}'')
										),
									4326
								)::geometry ('||sTipoGeom||',4326) AS geom';
								--)::geometry (point,4326) AS geom';
				aSelect:=aSelect || sCampoGeom;
			ELSE 

				sAddressType:= (jsonObjeto->0)#>>'{address,type}';
				sAddress:= (jsonObjeto->0)#>>'{address,value}';
				--DEBUG
				--RAISE NOTICE 'sAddressType, sAddress: %, %',sAddressType,sAddress;
				CASE sAddressType 
					WHEN 'Text' THEN 
						sAddress:='replace(content#>>''{address,value}'','','','' '')';
					WHEN 'PostalAddress' THEN 
						sAddress:= '(content#>>''{address,value,addressLocality}'')||'' ''||
								(content#>>''{address,value,streetAddress}'')';
					ELSE
						RAISE EXCEPTION 'Formato de dirección (address) no reconocido';
				END CASE;
				sCampoGeom:= 'st_setsrid(
								st_makepoint(
										split_part(funciones.geocoding_inverse_geopy('||sAddress||'),'','',1)::numeric,
										split_part(funciones.geocoding_inverse_geopy('||sAddress||'),'','',2)::numeric
										),
								4326)::geometry (point,4326)'
								;
					
				aSelect:=aSelect || sCampoGeom;
		END CASE;
	
	IF materialized = true THEN 
		vwType:='materialized view';
	ELSE 
		vwType:='view';
	END IF;
	EXECUTE 'DROP '||vwType||' IF EXISTS "'||esch||'"."'||vw_salida||'"';
	sSql:= 
		'CREATE  '||vwType||' "'||esch||'"."'||vw_salida||'" AS
			WITH entjson AS
			(
				SELECT json_array_elements(funciones.fiware_json 
					(
						'''||version_token||''',
						'''||url_token||''',
						'''||url_cb||''',
						'''||application_id||''',
						'''||application_secret||''',
						'''||fiware_user||''',
						'''||fiware_password||''',
						'''||service||''',
						'''||subservice||''',
						'''||entity_name||'''
					)) AS content
			)
			SELECT '||array_to_string(aSelect,',')||'
			FROM entjson
		';
		--DEBUG
		RAISE NOTICE 'sSql crear vista: %',sSql;
		EXECUTE sSql;
	RETURN;
END;
$$ language 'plpgsql' VOLATILE;
