topology.sql.in 58.3 KB
Newer Older
1
-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2
--
3 4
--
-- PostGIS - Spatial Types for PostgreSQL
5
-- http://postgis.net
6
--
Sandro Santilli's avatar
Sandro Santilli committed
7
-- Copyright (C) 2010, 2011 Sandro Santilli <strk@kbt.io>
8
-- Copyright (C) 2005 Refractions Research Inc.
9 10 11 12
--
-- This is free software; you can redistribute and/or modify it under
-- the terms of the GNU General Public Licence. See the COPYING file.
--
Sandro Santilli's avatar
Sandro Santilli committed
13
-- Author: Sandro Santilli <strk@kbt.io>
14
--
15 16 17 18
-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
--
-- STATUS:
--
Sandro Santilli's avatar
Sandro Santilli committed
19
--  All objects are created in the 'topology' schema.
20
--
Sandro Santilli's avatar
Sandro Santilli committed
21 22 23
--  We have PostGIS-specific objects and SQL/MM objects.
--  PostGIS-specific objects have no prefix, SQL/MM ones
--  have the ``ST_' prefix.
24
--
25 26
-- [PostGIS-specific]
--
Sandro Santilli's avatar
Sandro Santilli committed
27 28
-- TABLE topology
--  Table storing topology info (name, srid, precision)
29
--
Sandro Santilli's avatar
Sandro Santilli committed
30 31 32
-- TYPE TopoGeometry
--  Complex type storing topology_id, layer_id, geometry type
--  and topogeometry id.
33
--
Sandro Santilli's avatar
Sandro Santilli committed
34 35 36
-- DOMAIN TopoElement
--  An array of two elements: element_id and element_type.
--  In fact, an array of integers.
37
--
Sandro Santilli's avatar
Sandro Santilli committed
38 39 40 41
-- DOMAIN TopoElementArray
--  An array of element_id,element_type values.
--  In fact, a bidimensional array of integers:
--  '{{id,type}, {id,type}, ...}'
42
--
Sandro Santilli's avatar
Sandro Santilli committed
43 44 45 46 47 48
-- FUNCTION CreateTopology(name, [srid], [precision])
--  Initialize a new topology (creating schema with
--  edge,face,node,relation) and add a record into
--  the topology.topology table.
--  TODO: add triggers (or rules, or whatever) enforcing
--        precision to the edge and node tables.
49
--
Sandro Santilli's avatar
Sandro Santilli committed
50 51 52 53 54
-- FUNCTION DropTopology(name)
--    Delete a topology removing reference from the
--    topology.topology table
--
-- FUNCTION GetTopologyId(name)
55
-- FUNCTION GetTopologySRID(name)
Sandro Santilli's avatar
Sandro Santilli committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
-- FUNCTION GetTopologyName(id)
--    Return info about a Topology
--
-- FUNCTION AddTopoGeometryColumn(toponame, schema, table, column, geomtype)
--    Add a TopoGeometry column to a table, making it a topology layer.
--    Returns created layer id.
--
-- FUNCTION DropTopoGeometryColumn(schema, table, column)
--    Drop a TopoGeometry column, unregister the associated layer,
--    cleanup the relation table.
--
-- FUNCTION CreateTopoGeom(toponame, geomtype, layer_id, topo_objects)
--    Create a TopoGeometry object from existing Topology elements.
--    The "topo_objects" parameter is of TopoElementArray type.
--
-- FUNCTION GetTopoGeomElementArray(toponame, layer_id, topogeom_id)
-- FUNCTION GetTopoGeomElementArray(TopoGeometry)
--    Returns a TopoElementArray object containing the topological
--    elements of the given TopoGeometry.
--
-- FUNCTION GetTopoGeomElements(toponame, layer_id, topogeom_id)
-- FUNCTION GetTopoGeomElements(TopoGeometry)
--    Returns a set of TopoElement objects containing the
--    topological elements of the given TopoGeometry (primitive
--    elements)
--
-- FUNCTION ValidateTopology(toponame)
--    Run validity checks on the topology, returning, for each
--    detected error, a 3-columns row containing error string
--    and references to involved topo elements: error, id1, id2
86 87 88
--
-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
--
Sandro Santilli's avatar
Sandro Santilli committed
89
-- Overloaded functions for TopoGeometry inputs
90
--
Sandro Santilli's avatar
Sandro Santilli committed
91 92
-- FUNCTION intersects(TopoGeometry, TopoGeometry)
-- FUNCTION equals(TopoGeometry, TopoGeometry)
93 94 95
--
-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
--
Sandro Santilli's avatar
Sandro Santilli committed
96 97 98 99
-- FUNCTION TopoGeo_AddPoint(toponame, point)
--    Add a Point geometry to the topology
--    TODO: accept a topology/layer id
--          rework to use existing node if existent
100
--
Sandro Santilli's avatar
Sandro Santilli committed
101 102 103 104 105
-- FUNCTION TopoGeo_AddLinestring(toponame, line)
--    Add a LineString geometry to the topology
--    TODO: accept a topology/layer id
--          rework to use existing nodes/edges
--          splitting them if required
106
--
Sandro Santilli's avatar
Sandro Santilli committed
107 108 109
-- FUNCTION TopoGeo_AddPolygon(toponame, polygon)
--    Add a Polygon geometry to the topology
--    TODO: implement
110
--
Sandro Santilli's avatar
Sandro Santilli committed
111 112
-- TYPE GetFaceEdges_ReturnType
--    Complex type used to return tuples from ST_GetFaceEdges
113 114 115 116 117 118
--
-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
--
-- [SQL/MM]
--
--   ST_InitTopoGeo
Sandro Santilli's avatar
Sandro Santilli committed
119 120 121
--    Done, can be modified to include explicit sequences or
--    more constraints. Very noisy due to implicit index creations
--    for primary keys and sequences for serial fields...
122
--
123
--   ST_CreateTopoGeo
Sandro Santilli's avatar
Sandro Santilli committed
124
--    Complete
125
--
126
--   ST_AddIsoNode
Sandro Santilli's avatar
Sandro Santilli committed
127
--    Complete
128
--
129
--   ST_RemoveIsoNode
Sandro Santilli's avatar
Sandro Santilli committed
130
--    Complete
131
--
132
--   ST_MoveIsoNode
Sandro Santilli's avatar
Sandro Santilli committed
133
--    Complete
134
--
135
--   ST_AddIsoEdge
Sandro Santilli's avatar
Sandro Santilli committed
136
--    Complete
137 138
--
--   ST_RemoveIsoEdge
139
--    Complete, exceptions untested
140
--
141
--   ST_ChangeEdgeGeom
Sandro Santilli's avatar
Sandro Santilli committed
142
--    Complete
143 144
--
--   ST_NewEdgesSplit
145 146
--    Complete
--    Also updates the Relation table
147
--
148
--   ST_ModEdgeSplit
149 150
--    Complete
--    Also updates the Relation table
151 152
--
--   ST_AddEdgeNewFaces
153
--    Complete
154 155 156
--    Also updates the Relation table
--
--   ST_AddEdgeModFace
157 158
--    Complete
--    Also updates the Relation table
159
--
160
--   ST_GetFaceEdges
Sandro Santilli's avatar
Sandro Santilli committed
161
--    Complete
162 163
--
--   ST_ModEdgeHeal
Sandro Santilli's avatar
Sandro Santilli committed
164
--    Complete
165 166 167
--    Also updates the Relation table
--
--   ST_NewEdgeHeal
Sandro Santilli's avatar
Sandro Santilli committed
168
--    Complete
169
--    Also updates the Relation table
170
--
171
--   ST_GetFaceGeometry
Sandro Santilli's avatar
Sandro Santilli committed
172
--    Implemented using ST_BuildArea()
173
--
174
--   ST_RemEdgeNewFace
175
--    Complete
176
--    Also updates the Relation table
177
--
178
--   ST_RemEdgeModFace
Sandro Santilli's avatar
Sandro Santilli committed
179
--    Complete
180
--    Also updates the Relation table
181
--
182 183
--   ST_ValidateTopoGeo
--    Unimplemented (probably a wrapper around ValidateTopology)
184 185
--
--
186

187 188 189
-- Uninstalling previous installation isn't really a good habit ...
-- Let people decide about that
-- DROP SCHEMA topology CASCADE;
190

191 192
#include "../postgis/sqldefines.h"

193
CREATE SCHEMA topology;
194
COMMENT ON SCHEMA topology IS 'PostGIS Topology schema';
195

196 197
-- Doing everything outside of a transaction helps
-- upgrading in the best case.
198
BEGIN;
199 200 201 202 203 204 205 206 207 208 209 210 211

--={ ----------------------------------------------------------------
--  POSTGIS-SPECIFIC block
--
--  This part contains function NOT in the SQL/MM specification
--
---------------------------------------------------------------------

--
-- Topology table.
-- Stores id,name,precision and SRID of topologies.
--
CREATE TABLE topology.topology (
Sandro Santilli's avatar
Sandro Santilli committed
212 213 214 215 216
  id SERIAL NOT NULL PRIMARY KEY,
  name VARCHAR NOT NULL UNIQUE,
  SRID INTEGER NOT NULL,
  precision FLOAT8 NOT NULL,
  hasz BOOLEAN NOT NULL DEFAULT false
217 218 219 220 221 222
);

--{ LayerTrigger()
--
-- Layer integrity trigger
--
223
CREATE OR REPLACE FUNCTION topology.LayerTrigger()
Sandro Santilli's avatar
Sandro Santilli committed
224
  RETURNS trigger
225
AS
226
$$
227
DECLARE
Sandro Santilli's avatar
Sandro Santilli committed
228 229 230 231
  rec RECORD;
  ok BOOL;
  toponame varchar;
  query TEXT;
232 233
BEGIN

Sandro Santilli's avatar
Sandro Santilli committed
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
  --RAISE NOTICE 'LayerTrigger called % % at % level', TG_WHEN, TG_OP, TG_LEVEL;

  IF TG_OP = 'INSERT' THEN
    RAISE EXCEPTION 'LayerTrigger not meant to be called on INSERT';
  ELSIF TG_OP = 'UPDATE' THEN
    RAISE EXCEPTION 'The topology.layer table cannot be updated';
  END IF;

  -- Check for existance of any feature column referencing
  -- this layer
  FOR rec IN SELECT * FROM pg_namespace n, pg_class c, pg_attribute a
    WHERE text(n.nspname) = OLD.schema_name
    AND c.relnamespace = n.oid
    AND text(c.relname) = OLD.table_name
    AND a.attrelid = c.oid
    AND text(a.attname) = OLD.feature_column
  LOOP
    query = 'SELECT * '
252
         ' FROM ' || quote_ident(OLD.schema_name)
Sandro Santilli's avatar
Sandro Santilli committed
253 254 255
      || '.' || quote_ident(OLD.table_name)
      || ' WHERE layer_id('
      || quote_ident(OLD.feature_column)||') '
256
         '=' || OLD.layer_id
Sandro Santilli's avatar
Sandro Santilli committed
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
      || ' LIMIT 1';
    --RAISE NOTICE '%', query;
    FOR rec IN EXECUTE query
    LOOP
      RAISE NOTICE 'A feature referencing layer % of topology % still exists in %.%.%', OLD.layer_id, OLD.topology_id, OLD.schema_name, OLD.table_name, OLD.feature_column;
      RETURN NULL;
    END LOOP;
  END LOOP;

  -- Get topology name
  SELECT name FROM topology.topology INTO toponame
    WHERE id = OLD.topology_id;

  IF toponame IS NULL THEN
    RAISE NOTICE 'Could not find name of topology with id %',
      OLD.layer_id;
  END IF;

  -- Check if any record in the relation table references this layer
276 277 278
  FOR rec IN SELECT c.oid FROM pg_namespace n, pg_class c
    WHERE text(n.nspname) = toponame AND c.relnamespace = n.oid
          AND c.relname = 'relation'
Sandro Santilli's avatar
Sandro Santilli committed
279 280
  LOOP
    query = 'SELECT * '
281
         ' FROM ' || quote_ident(toponame)
Sandro Santilli's avatar
Sandro Santilli committed
282
      || '.relation '
283
         ' WHERE layer_id = '|| OLD.layer_id
Sandro Santilli's avatar
Sandro Santilli committed
284 285 286 287 288 289 290 291 292 293
      || ' LIMIT 1';
    --RAISE NOTICE '%', query;
    FOR rec IN EXECUTE query
    LOOP
      RAISE NOTICE 'A record in %.relation still references layer %', toponame, OLD.layer_id;
      RETURN NULL;
    END LOOP;
  END LOOP;

  RETURN OLD;
294
END;
295
$$
296
LANGUAGE 'plpgsql' VOLATILE STRICT;
297 298 299 300 301 302 303
--} LayerTrigger()

--{
-- Layer table.
-- Stores topology layer informations
--
CREATE TABLE topology.layer (
Sandro Santilli's avatar
Sandro Santilli committed
304 305 306 307 308 309 310 311 312 313 314
  topology_id INTEGER NOT NULL
    REFERENCES topology.topology(id),
  layer_id integer NOT NULL,
  schema_name VARCHAR NOT NULL,
  table_name VARCHAR NOT NULL,
  feature_column VARCHAR NOT NULL,
  feature_type integer NOT NULL,
  level INTEGER NOT NULL DEFAULT 0,
  child_id INTEGER DEFAULT NULL,
  UNIQUE(schema_name, table_name, feature_column),
  PRIMARY KEY(topology_id, layer_id)
315 316 317 318 319 320 321 322
);

CREATE TRIGGER layer_integrity_checks BEFORE UPDATE OR DELETE
ON topology.layer FOR EACH ROW EXECUTE PROCEDURE topology.LayerTrigger();

--} Layer table.

--
323
-- Type returned by ValidateTopology
324 325
--
CREATE TYPE topology.ValidateTopology_ReturnType AS (
Sandro Santilli's avatar
Sandro Santilli committed
326 327 328
  error varchar,
  id1 integer,
  id2 integer
329 330 331 332 333 334
);

--
-- TopoGeometry type
--
CREATE TYPE topology.TopoGeometry AS (
Sandro Santilli's avatar
Sandro Santilli committed
335 336 337 338 339
  topology_id integer,
  layer_id integer,
  id integer,
  type integer -- 1: [multi]point, 2: [multi]line,
               -- 3: [multi]polygon, 4: collection
340 341 342 343
);

--
-- TopoElement domain
344
--
345 346 347 348 349 350 351 352 353 354 355 356
-- This is an array of two elements: element_id and element_type.
--
-- When used to define _simple_ TopoGeometries,
-- element_type can be:
--  0: a node
--  1: an edge
--  2: a face
-- and element_id will be the node, edge or face identifier
--
-- When used to define _hierarchical_ TopoGeometries,
-- element_type will be the child layer identifier and
-- element_id will be composing TopoGoemetry identifier
357 358
--
CREATE DOMAIN topology.TopoElement AS integer[]
Sandro Santilli's avatar
Sandro Santilli committed
359 360 361 362
  CONSTRAINT DIMENSIONS CHECK (
    array_upper(VALUE, 2) IS NULL
    AND array_upper(VALUE, 1) = 2
  );
363 364
ALTER DOMAIN topology.TopoElement ADD
        CONSTRAINT lower_dimension CHECK (
Sandro Santilli's avatar
Sandro Santilli committed
365 366
    array_lower(VALUE, 1) = 1
  );
367
ALTER DOMAIN topology.TopoElement DROP CONSTRAINT
368 369 370 371
#if POSTGIS_PGSQL_VERSION >= 92
  IF EXISTS
#endif
  type_range;
372 373
ALTER DOMAIN topology.TopoElement ADD
        CONSTRAINT type_range CHECK (
374
    VALUE[2] > 0
Sandro Santilli's avatar
Sandro Santilli committed
375
  );
376

377 378 379 380
--
-- TopoElementArray domain
--
CREATE DOMAIN topology.TopoElementArray AS integer[][]
Sandro Santilli's avatar
Sandro Santilli committed
381 382 383 384 385
  CONSTRAINT DIMENSIONS CHECK (
    array_upper(VALUE, 2) IS NOT NULL
    AND array_upper(VALUE, 2) = 2
    AND array_upper(VALUE, 3) IS NULL
  );
386 387 388 389 390

--{ RelationTrigger()
--
-- Relation integrity trigger
--
391
CREATE OR REPLACE FUNCTION topology.RelationTrigger()
Sandro Santilli's avatar
Sandro Santilli committed
392
  RETURNS trigger
393
AS
394
$$
395
DECLARE
Sandro Santilli's avatar
Sandro Santilli committed
396 397 398 399 400
  toponame varchar;
  topoid integer;
  plyr RECORD; -- parent layer
  rec RECORD;
  ok BOOL;
401 402

BEGIN
Sandro Santilli's avatar
Sandro Santilli committed
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
  IF TG_NARGS != 2 THEN
    RAISE EXCEPTION 'RelationTrigger called with wrong number of arguments';
  END IF;

  topoid = TG_ARGV[0];
  toponame = TG_ARGV[1];

  --RAISE NOTICE 'RelationTrigger called % % on %.relation for a %', TG_WHEN, TG_OP, toponame, TG_LEVEL;

  IF TG_OP = 'DELETE' THEN
    RAISE EXCEPTION 'RelationTrigger not meant to be called on DELETE';
  END IF;

  -- Get layer info (and verify it exists)
  ok = false;
  FOR plyr IN EXECUTE 'SELECT * FROM topology.layer '
419 420
       'WHERE '
       ' topology_id = ' || topoid
Sandro Santilli's avatar
Sandro Santilli committed
421
    || ' AND'
422
       ' layer_id = ' || NEW.layer_id
Sandro Santilli's avatar
Sandro Santilli committed
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
  LOOP
    ok = true;
    EXIT;
  END LOOP;
  IF NOT ok THEN
    RAISE EXCEPTION 'Layer % does not exist in topology %',
      NEW.layer_id, topoid;
    RETURN NULL;
  END IF;

  IF plyr.level > 0 THEN -- this is hierarchical layer

    -- ElementType must be the layer child id
    IF NEW.element_type != plyr.child_id THEN
      RAISE EXCEPTION 'Type of elements in layer % must be set to its child layer id %', plyr.layer_id, plyr.child_id;
      RETURN NULL;
    END IF;

    -- ElementId must be an existent TopoGeometry in child layer
    ok = false;
    FOR rec IN EXECUTE 'SELECT topogeo_id FROM '
      || quote_ident(toponame) || '.relation '
445
         ' WHERE layer_id = ' || plyr.child_id
Sandro Santilli's avatar
Sandro Santilli committed
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
      || ' AND topogeo_id = ' || NEW.element_id
    LOOP
      ok = true;
      EXIT;
    END LOOP;
    IF NOT ok THEN
      RAISE EXCEPTION 'TopoGeometry % does not exist in the child layer %', NEW.element_id, plyr.child_id;
      RETURN NULL;
    END IF;

  ELSE -- this is a basic layer

    -- ElementType must be compatible with layer type
    IF plyr.feature_type != 4
      AND plyr.feature_type != NEW.element_type
    THEN
      RAISE EXCEPTION 'Element of type % is not compatible with layer of type %', NEW.element_type, plyr.feature_type;
      RETURN NULL;
    END IF;

    --
    -- Now lets see if the element is consistent, which
    -- is it exists in the topology tables.
    --

    --
    -- Element is a Node
    --
474
    IF NEW.element_type = 1
Sandro Santilli's avatar
Sandro Santilli committed
475 476 477 478
    THEN
      ok = false;
      FOR rec IN EXECUTE 'SELECT node_id FROM '
        || quote_ident(toponame) || '.node '
479
           ' WHERE node_id = ' || NEW.element_id
Sandro Santilli's avatar
Sandro Santilli committed
480 481 482 483 484 485 486 487 488 489 490 491
      LOOP
        ok = true;
        EXIT;
      END LOOP;
      IF NOT ok THEN
        RAISE EXCEPTION 'Node % does not exist in topology %', NEW.element_id, toponame;
        RETURN NULL;
      END IF;

    --
    -- Element is an Edge
    --
492
    ELSIF NEW.element_type = 2
Sandro Santilli's avatar
Sandro Santilli committed
493 494 495 496
    THEN
      ok = false;
      FOR rec IN EXECUTE 'SELECT edge_id FROM '
        || quote_ident(toponame) || '.edge_data '
497
           ' WHERE edge_id = ' || abs(NEW.element_id)
Sandro Santilli's avatar
Sandro Santilli committed
498 499 500 501 502 503 504 505 506 507 508 509
      LOOP
        ok = true;
        EXIT;
      END LOOP;
      IF NOT ok THEN
        RAISE EXCEPTION 'Edge % does not exist in topology %', NEW.element_id, toponame;
        RETURN NULL;
      END IF;

    --
    -- Element is a Face
    --
510
    ELSIF NEW.element_type = 3
Sandro Santilli's avatar
Sandro Santilli committed
511 512 513 514 515 516 517 518
    THEN
      IF NEW.element_id = 0 THEN
        RAISE EXCEPTION 'Face % cannot be associated with any feature', NEW.element_id;
        RETURN NULL;
      END IF;
      ok = false;
      FOR rec IN EXECUTE 'SELECT face_id FROM '
        || quote_ident(toponame) || '.face '
519
           ' WHERE face_id = ' || NEW.element_id
Sandro Santilli's avatar
Sandro Santilli committed
520 521 522 523 524 525 526 527 528 529 530
      LOOP
        ok = true;
        EXIT;
      END LOOP;
      IF NOT ok THEN
        RAISE EXCEPTION 'Face % does not exist in topology %', NEW.element_id, toponame;
        RETURN NULL;
      END IF;
    END IF;

  END IF;
531

Sandro Santilli's avatar
Sandro Santilli committed
532
  RETURN NEW;
533
END;
534
$$
535
LANGUAGE 'plpgsql' VOLATILE STRICT;
536 537 538 539 540 541 542 543 544
--} RelationTrigger()

--{
--  AddTopoGeometryColumn(toponame, schema, table, colum, type, [child])
--
--  Add a TopoGeometry column to a table, making it a topology layer.
--  Returns created layer id.
--
--
545
CREATE OR REPLACE FUNCTION topology.AddTopoGeometryColumn(toponame varchar, schema varchar, tbl varchar, col varchar, ltype varchar, child integer)
Sandro Santilli's avatar
Sandro Santilli committed
546
  RETURNS integer
547 548
AS
$$
549
DECLARE
Sandro Santilli's avatar
Sandro Santilli committed
550 551 552 553 554 555
  intltype integer;
  newlevel integer;
  topoid integer;
  rec RECORD;
  newlayer_id integer;
  query text;
556 557
BEGIN

558 559 560
  -- Get topology id
  SELECT id INTO topoid
    FROM topology.topology WHERE name = toponame;
561

562 563
  IF NOT FOUND THEN
    RAISE EXCEPTION 'Topology % does not exist', quote_literal(toponame);
Sandro Santilli's avatar
Sandro Santilli committed
564 565
  END IF;

566
  IF ltype ILIKE '%POINT%' OR ltype ILIKE 'PUNTAL' THEN
Sandro Santilli's avatar
Sandro Santilli committed
567
    intltype = 1;
568
  ELSIF ltype ILIKE '%LINE%' OR ltype ILIKE 'LINEAL' THEN
Sandro Santilli's avatar
Sandro Santilli committed
569
    intltype = 2;
570
  ELSIF ltype ILIKE '%POLYGON%' OR ltype ILIKE 'AREAL' THEN
Sandro Santilli's avatar
Sandro Santilli committed
571
    intltype = 3;
572
  ELSIF ltype ILIKE '%COLLECTION%' OR ltype ILIKE 'GEOMETRY' THEN
Sandro Santilli's avatar
Sandro Santilli committed
573 574 575 576 577 578 579 580 581
    intltype = 4;
  ELSE
    RAISE EXCEPTION 'Layer type must be one of POINT,LINE,POLYGON,COLLECTION';
  END IF;

  --
  -- Add new TopoGeometry column in schema.table
  --
  EXECUTE 'ALTER TABLE ' || quote_ident(schema)
582
    || '.' || quote_ident(tbl)
Sandro Santilli's avatar
Sandro Santilli committed
583 584 585 586 587 588 589 590 591
    || ' ADD COLUMN ' || quote_ident(col)
    || ' topology.TopoGeometry;';

  --
  -- See if child id exists and extract its level
  --
  IF child IS NOT NULL THEN
    SELECT level + 1 FROM topology.layer
      WHERE layer_id = child
592
        AND topology_id = topoid
Sandro Santilli's avatar
Sandro Santilli committed
593 594 595 596 597 598 599 600 601 602 603 604 605 606
      INTO newlevel;
    IF newlevel IS NULL THEN
      RAISE EXCEPTION 'Child layer % does not exist in topology "%"', child, toponame;
    END IF;
  END IF;

  --
  -- Get new layer id from sequence
  --
  EXECUTE 'SELECT nextval(' ||
    quote_literal(
      quote_ident(toponame) || '.layer_id_seq'
    ) || ')' INTO STRICT newlayer_id;

607
  EXECUTE 'INSERT INTO '
608 609 610 611
       'topology.layer(topology_id, '
       'layer_id, level, child_id, schema_name, '
       'table_name, feature_column, feature_type) '
       'VALUES ('
Sandro Santilli's avatar
Sandro Santilli committed
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
    || topoid || ','
    || newlayer_id || ',' || COALESCE(newlevel, 0) || ','
    || COALESCE(child::text, 'NULL') || ','
    || quote_literal(schema) || ','
    || quote_literal(tbl) || ','
    || quote_literal(col) || ','
    || intltype || ');';

  --
  -- Create a sequence for TopoGeometries in this new layer
  --
  EXECUTE 'CREATE SEQUENCE ' || quote_ident(toponame)
    || '.topogeo_s_' || newlayer_id;

  --
  -- Add constraints on TopoGeom column
  --
  EXECUTE 'ALTER TABLE ' || quote_ident(schema)
630
    || '.' || quote_ident(tbl)
Sandro Santilli's avatar
Sandro Santilli committed
631
    || ' ADD CONSTRAINT "check_topogeom_' || col || '" CHECK ('
632
       'topology_id(' || quote_ident(col) || ') = ' || topoid
Sandro Santilli's avatar
Sandro Santilli committed
633
    || ' AND '
634
       'layer_id(' || quote_ident(col) || ') = ' || newlayer_id
Sandro Santilli's avatar
Sandro Santilli committed
635
    || ' AND '
636
       'type(' || quote_ident(col) || ') = ' || intltype
Sandro Santilli's avatar
Sandro Santilli committed
637 638 639 640 641 642
    || ');';

  --
  -- Add dependency of the feature column on the topology schema
  --
  query = 'INSERT INTO pg_catalog.pg_depend SELECT '
643 644 645 646 647 648 649
       'fcat.oid, fobj.oid, fsub.attnum, tcat.oid, '
       'tobj.oid, 0, ''n'' '
       'FROM pg_class fcat, pg_namespace fnsp, '
       ' pg_class fobj, pg_attribute fsub, '
       ' pg_class tcat, pg_namespace tobj '
       ' WHERE fcat.relname = ''pg_class'' '
       ' AND fnsp.nspname = ' || quote_literal(schema)
Sandro Santilli's avatar
Sandro Santilli committed
650
    || ' AND fobj.relnamespace = fnsp.oid '
651
       ' AND fobj.relname = ' || quote_literal(tbl)
Sandro Santilli's avatar
Sandro Santilli committed
652
    || ' AND fsub.attrelid = fobj.oid '
653
       ' AND fsub.attname = ' || quote_literal(col)
Sandro Santilli's avatar
Sandro Santilli committed
654
    || ' AND tcat.relname = ''pg_namespace'' '
655
       ' AND tobj.nspname = ' || quote_literal(toponame);
656 657 658 659 660 661 662 663

--
-- The only reason to add this dependency is to avoid
-- simple drop of a feature column. Still, drop cascade
-- will remove both the feature column and the sequence
-- corrupting the topology anyway ...
--
#if 0
Sandro Santilli's avatar
Sandro Santilli committed
664
  --
665
  -- Add dependency of the topogeom sequence on the feature column
Sandro Santilli's avatar
Sandro Santilli committed
666 667 668
  -- This is a dirty hack ...
  --
  query = 'INSERT INTO pg_catalog.pg_depend SELECT '
669 670 671 672 673 674 675 676
       'scat.oid, sobj.oid, 0, fcat.oid, '
       'fobj.oid, fsub.attnum, ''n'' '
       'FROM pg_class fcat, pg_namespace fnsp, '
       ' pg_class fobj, pg_attribute fsub, '
       ' pg_class scat, pg_class sobj, '
       ' pg_namespace snsp '
       ' WHERE fcat.relname = ''pg_class'' '
       ' AND fnsp.nspname = ' || quote_literal(schema)
Sandro Santilli's avatar
Sandro Santilli committed
677
    || ' AND fobj.relnamespace = fnsp.oid '
678
       ' AND fobj.relname = ' || quote_literal(tbl)
Sandro Santilli's avatar
Sandro Santilli committed
679
    || ' AND fsub.attrelid = fobj.oid '
680
       ' AND fsub.attname = ' || quote_literal(col)
Sandro Santilli's avatar
Sandro Santilli committed
681
    || ' AND scat.relname = ''pg_class'' '
682
       ' AND snsp.nspname = ' || quote_literal(toponame)
683
    || ' AND sobj.relnamespace = snsp.oid '
684 685
       ' AND sobj.relname = '
       ' ''topogeo_s_' || newlayer_id || ''' ';
Sandro Santilli's avatar
Sandro Santilli committed
686 687 688

  RAISE NOTICE '%', query;
  EXECUTE query;
689 690
#endif

Sandro Santilli's avatar
Sandro Santilli committed
691
  RETURN newlayer_id;
692
END;
693
$$
694
LANGUAGE 'plpgsql' VOLATILE;
695
--}{ AddTopoGeometryColumn
696

697
CREATE OR REPLACE FUNCTION topology.AddTopoGeometryColumn(varchar, varchar, varchar, varchar, varchar)
Sandro Santilli's avatar
Sandro Santilli committed
698
  RETURNS integer
699 700
AS
$$
Sandro Santilli's avatar
Sandro Santilli committed
701
  SELECT topology.AddTopoGeometryColumn($1, $2, $3, $4, $5, NULL);
702
$$
703
LANGUAGE 'sql' VOLATILE;
704 705 706 707 708 709 710 711 712 713 714

--
--} AddTopoGeometryColumn

--{
--  DropTopoGeometryColumn(schema, table, colum)
--
--  Drop a TopoGeometry column, unregister the associated layer,
--  cleanup the relation table.
--
--
715
CREATE OR REPLACE FUNCTION topology.DropTopoGeometryColumn(schema varchar, tbl varchar, col varchar)
Sandro Santilli's avatar
Sandro Santilli committed
716
  RETURNS text
717 718
AS
$$
719
DECLARE
Sandro Santilli's avatar
Sandro Santilli committed
720 721 722 723
  rec RECORD;
  lyrinfo RECORD;
  ok BOOL;
  result text;
724 725 726
BEGIN

        -- Get layer and topology info
Sandro Santilli's avatar
Sandro Santilli committed
727 728
  ok = false;
  FOR rec IN EXECUTE 'SELECT t.name as toponame, l.* FROM '
729 730 731
       'topology.topology t, topology.layer l '
       ' WHERE l.topology_id = t.id'
       ' AND l.schema_name = ' || quote_literal(schema)
Sandro Santilli's avatar
Sandro Santilli committed
732 733 734 735 736 737 738 739 740 741 742 743
    || ' AND l.table_name = ' || quote_literal(tbl)
    || ' AND l.feature_column = ' || quote_literal(col)
  LOOP
    ok = true;
    lyrinfo = rec;
  END LOOP;

  -- Layer not found
  IF NOT ok THEN
    RAISE EXCEPTION 'No layer registered on %.%.%',
      schema,tbl,col;
  END IF;
744

Sandro Santilli's avatar
Sandro Santilli committed
745
  -- Clean up the topology schema
746
  BEGIN
Sandro Santilli's avatar
Sandro Santilli committed
747 748 749
    -- Cleanup the relation table
    EXECUTE 'DELETE FROM ' || quote_ident(lyrinfo.toponame)
      || '.relation '
750 751
         ' WHERE '
         'layer_id = ' || lyrinfo.layer_id;
Sandro Santilli's avatar
Sandro Santilli committed
752 753 754 755

    -- Drop the sequence for topogeoms in this layer
    EXECUTE 'DROP SEQUENCE ' || quote_ident(lyrinfo.toponame)
      || '.topogeo_s_' || lyrinfo.layer_id;
756 757 758 759 760 761
  EXCEPTION
    WHEN UNDEFINED_TABLE THEN
      RAISE NOTICE '%', SQLERRM;
    WHEN OTHERS THEN
      RAISE EXCEPTION 'Got % (%)', SQLERRM, SQLSTATE;
  END;
Sandro Santilli's avatar
Sandro Santilli committed
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785

  ok = false;
  FOR rec IN SELECT * FROM pg_namespace n, pg_class c, pg_attribute a
    WHERE text(n.nspname) = schema
    AND c.relnamespace = n.oid
    AND text(c.relname) = tbl
    AND a.attrelid = c.oid
    AND text(a.attname) = col
  LOOP
    ok = true;
    EXIT;
  END LOOP;

  IF ok THEN
    -- Set feature column to NULL to bypass referential integrity
    -- checks
    EXECUTE 'UPDATE ' || quote_ident(schema) || '.'
      || quote_ident(tbl)
      || ' SET ' || quote_ident(col)
      || ' = NULL';
  END IF;

  -- Delete the layer record
  EXECUTE 'DELETE FROM topology.layer '
786
       ' WHERE topology_id = ' || lyrinfo.topology_id
Sandro Santilli's avatar
Sandro Santilli committed
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
    || ' AND layer_id = ' || lyrinfo.layer_id;

  IF ok THEN
    -- Drop the layer column
    EXECUTE 'ALTER TABLE ' || quote_ident(schema) || '.'
      || quote_ident(tbl)
      || ' DROP ' || quote_ident(col)
      || ' cascade';
  END IF;

  result = 'Layer ' || lyrinfo.layer_id || ' ('
    || schema || '.' || tbl || '.' || col
    || ') dropped';

  RETURN result;
802
END;
803
$$
804
LANGUAGE 'plpgsql' VOLATILE;
805 806 807
--
--} DropTopoGeometryColumn

808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
-- {
--
-- populate_topology_layer
--
-- Register missing layers into topology.topology, looking at
-- their constraints.
--
-- The function doesn't attempt to determine if a layer is
-- hierarchical or primitive, but always assumes primitive.
--
-- }{
DROP FUNCTION IF EXISTS topology.populate_topology_layer();
CREATE OR REPLACE FUNCTION topology.populate_topology_layer()
	RETURNS TABLE(schema_name text, table_name text, feature_column text)
AS
$$
  INSERT INTO topology.layer
  WITH checks AS (
  SELECT
    n.nspname sch, r.relname tab,
    replace(c.conname, 'check_topogeom_', '') col,
    --c.consrc src,
    regexp_matches(c.consrc,
      '\.topology_id = (\d+).*\.layer_id = (\d+).*\.type = (\d+)') inf
832 833
  FROM (SELECT conname, connamespace, conrelid, conkey, pg_get_constraintdef(oid) As consrc
		    FROM pg_constraint) AS c, pg_class r, pg_namespace n
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
  WHERE c.conname LIKE 'check_topogeom_%'
    AND r.oid = c.conrelid
    AND n.oid = r.relnamespace
  ), newrows AS (
    SELECT inf[1]::int as topology_id,
           inf[2]::int as layer_id,
          sch, tab, col, inf[3]::int as feature_type --, src
    FROM checks c
    WHERE NOT EXISTS (
      SELECT * FROM topology.layer l
      WHERE l.schema_name = c.sch
        AND l.table_name = c.tab
        AND l.feature_column = c.col
    )
  )
  SELECT topology_id, layer_id, sch,
         tab, col, feature_type,
         0, NULL
  FROM newrows RETURNING schema_name,table_name,feature_column;
$$
LANGUAGE 'sql' VOLATILE;

856 857 858 859
--{
-- CreateTopoGeom(topology_name, topogeom_type, layer_id, elements)
--
-- Create a TopoGeometry object from Topology elements.
860
-- The elements parameter is a two-dimensional array.
861 862 863 864 865
-- Every element of the array is either a Topology element represented by
-- (id, type) or a TopoGeometry element represented by (id, layer).
-- The actual semantic depends on the TopoGeometry layer, either at
-- level 0 (elements are topological primitives) or higer (elements
-- are TopoGeoms from child layer).
866
--
867 868 869 870 871 872 873 874 875 876 877
-- @param toponame Topology name
--
-- @param tg_type Spatial type of geometry
--          1:[multi]point (puntal)
--          2:[multi]line  (lineal)
--          3:[multi]poly  (areal)
--          4:collection   (mixed)
--
-- @param layer_id Layer identifier
--
-- @param tg_objs Array of components
878
--
879 880
-- Return a topology.TopoGeometry object.
--
881
CREATE OR REPLACE FUNCTION topology.CreateTopoGeom(toponame varchar, tg_type integer, layer_id integer, tg_objs topology.TopoElementArray)
Sandro Santilli's avatar
Sandro Santilli committed
882
  RETURNS topology.TopoGeometry
883 884
AS
$$
885
DECLARE
Sandro Santilli's avatar
Sandro Santilli committed
886 887 888 889 890 891 892 893 894 895 896
  i integer;
  dims varchar;
  outerdims varchar;
  innerdims varchar;
  obj_type integer;
  obj_id integer;
  ret topology.TopoGeometry;
  rec RECORD;
  layertype integer;
  layerlevel integer;
  layerchild integer;
897 898
BEGIN

Sandro Santilli's avatar
Sandro Santilli committed
899 900 901 902 903
  IF tg_type < 1 OR tg_type > 4 THEN
    RAISE EXCEPTION 'Invalid TopoGeometry type % (must be in the range 1..4)', tg_type;
  END IF;

  -- Get topology id into return TopoGeometry
904 905 906 907 908 909
  SELECT id INTO ret.topology_id
    FROM topology.topology WHERE name = toponame;

  IF NOT FOUND THEN
    RAISE EXCEPTION 'Topology % does not exist', quote_literal(toponame);
  END IF;
Sandro Santilli's avatar
Sandro Santilli committed
910 911 912 913 914 915

  --
  -- Get layer info
  --
  layertype := NULL;
  FOR rec IN EXECUTE 'SELECT * FROM topology.layer'
916
       ' WHERE topology_id = ' || ret.topology_id
Sandro Santilli's avatar
Sandro Santilli committed
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
    || ' AND layer_id = ' || layer_id
  LOOP
    layertype = rec.feature_type;
    layerlevel = rec.level;
    layerchild = rec.child_id;
  END LOOP;

  -- Check for existence of given layer id
  IF layertype IS NULL THEN
    RAISE EXCEPTION 'No layer with id % is registered with topology %', layer_id, toponame;
  END IF;

  -- Verify compatibility between layer geometry type and
  -- TopoGeom requested geometry type
  IF layertype != 4 and layertype != tg_type THEN
    RAISE EXCEPTION 'A Layer of type % cannot contain a TopoGeometry of type %', layertype, tg_type;
  END IF;

  -- Set layer id and type in return object
  ret.layer_id = layer_id;
  ret.type = tg_type;

  --
  -- Get new TopoGeo id from sequence
  --
  FOR rec IN EXECUTE 'SELECT nextval(' ||
    quote_literal(
      quote_ident(toponame) || '.topogeo_s_' || layer_id
    ) || ')'
  LOOP
    ret.id = rec.nextval;
  END LOOP;

  -- Loop over outer dimension
  i = array_lower(tg_objs, 1);
  LOOP
    obj_id = tg_objs[i][1];
    obj_type = tg_objs[i][2];

    -- Elements of type 0 represent emptiness, just skip them
    IF obj_type = 0 THEN
      IF obj_id != 0 THEN
        RAISE EXCEPTION 'Malformed empty topo element {0,%} -- id must be 0 as well', obj_id;
      END IF;
    ELSE
      IF layerlevel = 0 THEN -- array specifies lower-level objects
        IF tg_type != 4 and tg_type != obj_type THEN
          RAISE EXCEPTION 'A TopoGeometry of type % cannot contain topology elements of type %', tg_type, obj_type;
        END IF;
      ELSE -- array specifies lower-level topogeometries
        IF obj_type != layerchild THEN
          RAISE EXCEPTION 'TopoGeom element layer do not match TopoGeom child layer';
        END IF;
        -- TODO: verify that the referred TopoGeometry really
        -- exists in the relation table ?
      END IF;

      --RAISE NOTICE 'obj:% type:% id:%', i, obj_type, obj_id;

      --
      -- Insert record into the Relation table
      --
      EXECUTE 'INSERT INTO '||quote_ident(toponame)
        || '.relation(topogeo_id, layer_id, '
981 982
           'element_id,element_type) '
           ' VALUES ('||ret.id
Sandro Santilli's avatar
Sandro Santilli committed
983 984 985 986 987 988 989 990 991 992 993
        ||','||ret.layer_id
        || ',' || obj_id || ',' || obj_type || ');';
    END IF;

    i = i+1;
    IF i > array_upper(tg_objs, 1) THEN
      EXIT;
    END IF;
  END LOOP;

  RETURN ret;
994 995

END
996
$$
997
LANGUAGE 'plpgsql' VOLATILE STRICT;
998 999 1000 1001 1002
--} CreateTopoGeom(toponame,topogeom_type, layer_id, TopoElementArray)

--{
-- CreateTopoGeom(topology_name, topogeom_type, layer_id) - creates the empty topogeom
CREATE OR REPLACE FUNCTION topology.CreateTopoGeom(toponame varchar, tg_type integer, layer_id integer)
Sandro Santilli's avatar
Sandro Santilli committed
1003
  RETURNS topology.TopoGeometry
1004 1005 1006 1007 1008
AS
$$
  SELECT topology.CreateTopoGeom($1,$2,$3,'{{0,0}}');
$$ LANGUAGE 'sql' VOLATILE STRICT;
--} CreateTopoGeom(toponame, topogeom_type, layer_id)
1009 1010 1011 1012

--{
-- GetTopologyName(topology_id)
--
1013 1014
-- TODO: rewrite in SQL ?
--
1015
CREATE OR REPLACE FUNCTION topology.GetTopologyName(topoid integer)
Sandro Santilli's avatar
Sandro Santilli committed
1016
  RETURNS varchar
1017
AS
1018
$$
1019
DECLARE
Sandro Santilli's avatar
Sandro Santilli committed
1020
  ret varchar;
1021 1022 1023
BEGIN
        SELECT name FROM topology.topology into ret
                WHERE id = topoid;
Sandro Santilli's avatar
Sandro Santilli committed
1024
  RETURN ret;
1025
END
1026
$$
1027
LANGUAGE 'plpgsql' STABLE STRICT;
1028 1029 1030 1031 1032
--} GetTopologyName(topoid)

--{
-- GetTopologyId(toponame)
--
1033 1034
-- TODO: rewrite in SQL ?
--
1035
CREATE OR REPLACE FUNCTION topology.GetTopologyId(toponame varchar)
Sandro Santilli's avatar
Sandro Santilli committed
1036
  RETURNS integer
1037
AS
1038
$$
1039
DECLARE
Sandro Santilli's avatar
Sandro Santilli committed
1040
  ret integer;
1041
BEGIN
1042 1043 1044 1045 1046 1047 1048
  SELECT id INTO ret
    FROM topology.topology WHERE name = toponame;

  IF NOT FOUND THEN
    RAISE EXCEPTION 'Topology % does not exist', quote_literal(toponame);
  END IF;

Sandro Santilli's avatar
Sandro Santilli committed
1049
  RETURN ret;
1050
END
1051
$$
1052
LANGUAGE 'plpgsql' STABLE STRICT;
1053
--} GetTopologyId(toponame)
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063

--{
-- GetTopologySRID(toponame)
--
CREATE OR REPLACE FUNCTION topology.GetTopologySRID(toponame varchar)
  RETURNS integer
AS $$
  SELECT SRID FROM topology.topology WHERE name = $1;
$$ LANGUAGE 'sql' STABLE STRICT;
--} GetTopologySRID(toponame)
1064 1065 1066 1067 1068 1069 1070

--{
-- GetTopoGeomElementArray(toponame, layer_id, topogeom_id)
-- GetTopoGeomElementArray(TopoGeometry)
--
-- Returns a set of element_id,element_type
--
1071
CREATE OR REPLACE FUNCTION topology.GetTopoGeomElementArray(toponame varchar, layer_id integer, tgid integer)
Sandro Santilli's avatar
Sandro Santilli committed
1072
  RETURNS topology.TopoElementArray
1073
AS
1074
$$
1075
DECLARE
Sandro Santilli's avatar
Sandro Santilli committed
1076 1077 1078 1079
  rec RECORD;
  tg_objs varchar := '{';
  i integer;
  query text;
1080 1081
BEGIN

Sandro Santilli's avatar
Sandro Santilli committed
1082 1083
  query = 'SELECT * FROM topology.GetTopoGeomElements('
    || quote_literal(toponame) || ','
1084
    || quote_literal(layer_id) || ','
Sandro Santilli's avatar
Sandro Santilli committed
1085 1086 1087
    || quote_literal(tgid)
    || ') as obj ORDER BY obj';

1088 1089 1090 1091 1092
#ifdef POSTGIS_TOPOLOGY_DEBUG
  RAISE DEBUG 'Query: %', query;
#endif

  -- TODO: why not using array_agg here ?
Sandro Santilli's avatar
Sandro Santilli committed
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108

  i = 1;
  FOR rec IN EXECUTE query
  LOOP
    IF i > 1 THEN
      tg_objs = tg_objs || ',';
    END IF;
    tg_objs = tg_objs || '{'
      || rec.obj[1] || ',' || rec.obj[2]
      || '}';
    i = i+1;
  END LOOP;

  tg_objs = tg_objs || '}';

  RETURN tg_objs;
1109
END;
1110
$$
1111
LANGUAGE 'plpgsql' STABLE STRICT;
1112

1113
CREATE OR REPLACE FUNCTION topology.GetTopoGeomElementArray(tg topology.TopoGeometry)
Sandro Santilli's avatar
Sandro Santilli committed
1114
  RETURNS topology.TopoElementArray
1115
AS
1116
$$
1117
DECLARE
Sandro Santilli's avatar
Sandro Santilli committed
1118
  toponame varchar;
1119
BEGIN
Sandro Santilli's avatar
Sandro Santilli committed
1120
  toponame = topology.GetTopologyName(tg.topology_id);
1121
  RETURN topology.GetTopoGeomElementArray(toponame, tg.layer_id, tg.id);
1122
END;
1123
$$
1124
LANGUAGE 'plpgsql' STABLE STRICT;
1125 1126 1127 1128 1129 1130 1131 1132 1133

--} GetTopoGeomElementArray()

--{
-- GetTopoGeomElements(toponame, layer_id, topogeom_id)
-- GetTopoGeomElements(TopoGeometry)
--
-- Returns a set of element_id,element_type
--
1134
CREATE OR REPLACE FUNCTION topology.GetTopoGeomElements(toponame varchar, layerid integer, tgid integer)
Sandro Santilli's avatar
Sandro Santilli committed
1135
  RETURNS SETOF topology.TopoElement
1136
AS
1137
$$
1138
DECLARE
Sandro Santilli's avatar
Sandro Santilli committed
1139 1140 1141 1142 1143 1144 1145
  ret topology.TopoElement;
  rec RECORD;
  rec2 RECORD;
  query text;
  query2 text;
  lyr RECORD;
  ok bool;
1146
  topoid INTEGER;
1147 1148
BEGIN

1149 1150 1151 1152 1153 1154 1155
  -- Get topology id
  SELECT id INTO topoid
    FROM topology.topology WHERE name = toponame;
  IF NOT FOUND THEN
    RAISE EXCEPTION 'Topology % does not exist', quote_literal(toponame);
  END IF;

Sandro Santilli's avatar
Sandro Santilli committed
1156 1157
  -- Get layer info
  ok = false;
1158 1159 1160
  FOR rec IN EXECUTE 'SELECT * FROM topology.layer '
       ' WHERE layer_id = $1 AND topology_id = $2'
       USING layerid, topoid
Sandro Santilli's avatar
Sandro Santilli committed
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
  LOOP
    lyr = rec;
    ok = true;
  END LOOP;

  IF NOT ok THEN
    RAISE EXCEPTION 'Layer % does not exist', layerid;
  END IF;

  query = 'SELECT abs(element_id) as element_id, element_type FROM '
    || quote_ident(toponame) || '.relation WHERE '
1172
       ' layer_id = ' || layerid
Sandro Santilli's avatar
Sandro Santilli committed
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
    || ' AND topogeo_id = ' || quote_literal(tgid)
    || ' ORDER BY element_type, element_id';

  --RAISE NOTICE 'Query: %', query;

  FOR rec IN EXECUTE query
  LOOP
    IF lyr.level > 0 THEN
      query2 = 'SELECT * from topology.GetTopoGeomElements('
        || quote_literal(toponame) || ','
        || rec.element_type
        || ','
        || rec.element_id
        || ') as ret;';
      --RAISE NOTICE 'Query2: %', query2;
      FOR rec2 IN EXECUTE query2
      LOOP
        RETURN NEXT rec2.ret;
      END LOOP;
    ELSE
      ret = '{' || rec.element_id || ',' || rec.element_type || '}';
      RETURN NEXT ret;
    END IF;
1196

Sandro Santilli's avatar
Sandro Santilli committed
1197 1198 1199
  END LOOP;

  RETURN;
1200
END;
1201
$$
1202
LANGUAGE 'plpgsql' STABLE STRICT;
1203

1204
CREATE OR REPLACE FUNCTION topology.GetTopoGeomElements(tg topology.TopoGeometry)
Sandro Santilli's avatar
Sandro Santilli committed
1205
  RETURNS SETOF topology.TopoElement
1206
AS
1207
$$
1208
DECLARE
Sandro Santilli's avatar
Sandro Santilli committed
1209 1210
  toponame varchar;
  rec RECORD;
1211
BEGIN
Sandro Santilli's avatar
Sandro Santilli committed
1212 1213 1214 1215 1216 1217 1218
  toponame = topology.GetTopologyName(tg.topology_id);
  FOR rec IN SELECT * FROM topology.GetTopoGeomElements(toponame,
    tg.layer_id,tg.id) as ret
  LOOP
    RETURN NEXT rec.ret;
  END LOOP;
  RETURN;
1219
END;
1220
$$
1221
LANGUAGE 'plpgsql' STABLE STRICT;
1222 1223 1224 1225 1226 1227 1228

--} GetTopoGeomElements()

--{
-- Geometry(TopoGeometry)
--
-- Construct a Geometry from a TopoGeometry.
1229
--
1230
-- }{
1231
CREATE OR REPLACE FUNCTION topology.Geometry(topogeom topology.TopoGeometry)
Sandro Santilli's avatar
Sandro Santilli committed
1232
  RETURNS Geometry
1233
AS $$
1234
DECLARE
1235 1236 1237 1238 1239 1240
  toponame varchar;
  geom geometry;
  rec RECORD;
  plyr RECORD;
  clyr RECORD;
  sql TEXT;
1241 1242
BEGIN

1243 1244
  -- Get topology name
  SELECT name FROM topology.topology
Sandro Santilli's avatar
Sandro Santilli committed
1245
  WHERE id = topogeom.topology_id
1246 1247 1248 1249
  INTO toponame;
  IF toponame IS NULL THEN
    RAISE EXCEPTION 'Invalid TopoGeometry (unexistent topology id %)', topogeom.topology_id;
  END IF;
1250

1251 1252 1253 1254 1255 1256 1257 1258
  -- Get layer info
  SELECT * FROM topology.layer
    WHERE topology_id = topogeom.topology_id
    AND layer_id = topogeom.layer_id
    INTO plyr;
  IF plyr IS NULL THEN
    RAISE EXCEPTION 'Could not find TopoGeometry layer % in topology %', topogeom.layer_id, topogeom.topology_id;
  END IF;
1259

1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
  --
  -- If this feature layer is on any level > 0 we will
  -- compute the topological union of all child features
  -- in fact recursing.
  --
  IF plyr.level > 0 THEN -- {

    -- Get child layer info
    SELECT * FROM topology.layer WHERE layer_id = plyr.child_id
      AND topology_id = topogeom.topology_id
      INTO clyr;
    IF clyr IS NULL THEN
      RAISE EXCEPTION 'Invalid layer % in topology % (unexistent child layer %)', topogeom.layer_id, topogeom.topology_id, plyr.child_id;
    END IF;
1274

1275 1276 1277 1278 1279 1280
    sql := 'SELECT st_multi(st_union(topology.Geometry('
      || quote_ident(clyr.feature_column)
      || '))) as geom FROM '
      || quote_ident(clyr.schema_name) || '.'
      || quote_ident(clyr.table_name)
      || ', ' || quote_ident(toponame) || '.relation pr'
1281 1282
         ' WHERE '
         ' pr.topogeo_id = ' || topogeom.id
1283
      || ' AND '
1284
         ' pr.layer_id = ' || topogeom.layer_id
1285
      || ' AND '
1286
         ' id('||quote_ident(clyr.feature_column)
1287
      || ') = pr.element_id '
1288 1289
         ' AND '
         'layer_id('||quote_ident(clyr.feature_column)
1290 1291 1292
      || ') = pr.element_type ';
    --RAISE DEBUG '%', query;
    EXECUTE sql INTO geom;
1293

1294
  ELSIF topogeom.type = 3 THEN -- [multi]polygon -- }{
1295

1296
    sql := 'SELECT st_multi(st_union('
1297
         'topology.ST_GetFaceGeometry('
1298
      || quote_literal(toponame) || ','
1299
      || 'element_id))) as g FROM '
1300 1301 1302 1303 1304 1305 1306 1307
      || quote_ident(toponame)
      || '.relation WHERE topogeo_id = '
      || topogeom.id || ' AND layer_id = '
      || topogeom.layer_id || ' AND element_type = 3 ';
    EXECUTE sql INTO geom;

  ELSIF topogeom.type = 2 THEN -- [multi]line -- }{

1308
    sql :=
1309 1310 1311
      'SELECT st_multi(ST_LineMerge(ST_Collect(e.geom))) as g FROM '
      || quote_ident(toponame) || '.edge e, '
      || quote_ident(toponame) || '.relation r '
1312
         ' WHERE r.topogeo_id = ' || topogeom.id
1313 1314
      || ' AND r.layer_id = ' || topogeom.layer_id
      || ' AND r.element_type = 2 '
1315
         ' AND abs(r.element_id) = e.edge_id';
1316
    EXECUTE sql INTO geom;
1317

1318 1319 1320 1321 1322 1323
  ELSIF topogeom.type = 1 THEN -- [multi]point -- }{

    sql :=
      'SELECT st_multi(st_union(n.geom)) as g FROM '
      || quote_ident(toponame) || '.node n, '
      || quote_ident(toponame) || '.relation r '
1324
         ' WHERE r.topogeo_id = ' || topogeom.id
1325 1326
      || ' AND r.layer_id = ' || topogeom.layer_id
      || ' AND r.element_type = 1 '
1327
         ' AND r.element_id = n.node_id';
1328 1329 1330
    EXECUTE sql INTO geom;

  ELSIF topogeom.type = 4 THEN -- mixed collection -- }{
1331

1332
    sql := 'WITH areas AS ( SELECT ST_Union('
1333
         'topology.ST_GetFaceGeometry('
1334
      || quote_literal(toponame) || ','
1335
      || 'element_id)) as g FROM '
1336 1337 1338 1339
      || quote_ident(toponame)
      || '.relation WHERE topogeo_id = '
      || topogeom.id || ' AND layer_id = '
      || topogeom.layer_id || ' AND element_type = 3), '
1340
         'lines AS ( SELECT ST_LineMerge(ST_Collect(e.geom)) as g FROM '
1341 1342
      || quote_ident(toponame) || '.edge e, '
      || quote_ident(toponame) || '.relation r '
1343
         ' WHERE r.topogeo_id = ' || topogeom.id
1344 1345
      || ' AND r.layer_id = ' || topogeom.layer_id
      || ' AND r.element_type = 2 '
1346 1347
         ' AND abs(r.element_id) = e.edge_id ), '
         ' points as ( SELECT st_union(n.geom) as g FROM '
1348 1349
      || quote_ident(toponame) || '.node n, '
      || quote_ident(toponame) || '.relation r '
1350
         ' WHERE r.topogeo_id = ' || topogeom.id
1351 1352
      || ' AND r.layer_id = ' || topogeom.layer_id
      || ' AND r.element_type = 1 '
1353 1354 1355 1356
         ' AND r.element_id = n.node_id ), '
         ' un as ( SELECT g FROM areas UNION ALL SELECT g FROM lines '
         '          UNION ALL SELECT g FROM points ) '
         'SELECT ST_Multi(ST_Collect(g)) FROM un';
1357
    EXECUTE sql INTO geom;
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372

  ELSE -- }{

    RAISE EXCEPTION 'Invalid TopoGeometries (unknown type %)', topogeom.type;

  END IF; -- }

  IF geom IS NULL THEN
    IF topogeom.type = 3 THEN -- [multi]polygon
      geom := 'MULTIPOLYGON EMPTY';
    ELSIF topogeom.type = 2 THEN -- [multi]line
      geom := 'MULTILINESTRING EMPTY';
    ELSIF topogeom.type = 1 THEN -- [multi]point
      geom := 'MULTIPOINT EMPTY';
    ELSE
1373 1374 1375
      geom := 'GEOMETRYCOLLECTION EMPTY';
    END IF;
  END IF;
1376

1377
  RETURN geom;
1378
END
1379
$$
1380 1381 1382
LANGUAGE 'plpgsql' VOLATILE STRICT;
--} Geometry(TopoGeometry)

1383
-- 7.3+ explicit cast
1384 1385
CREATE CAST (topology.TopoGeometry AS Geometry) WITH FUNCTION topology.Geometry(topology.TopoGeometry) AS IMPLICIT;

1386 1387 1388 1389 1390 1391
--{
--  ValidateTopology(toponame)
--
--  Return a Set of ValidateTopology_ReturnType containing
--  informations on all topology inconsistencies
--
1392
CREATE OR REPLACE FUNCTION topology.ValidateTopology(toponame varchar)
Sandro Santilli's avatar
Sandro Santilli committed
1393
  RETURNS setof topology.ValidateTopology_ReturnType
1394
AS
1395
$$
1396
DECLARE
Sandro Santilli's avatar
Sandro Santilli committed
1397 1398 1399 1400 1401 1402 1403
  retrec topology.ValidateTopology_ReturnType;
  rec RECORD;
  rec2 RECORD;
  i integer;
  invalid_edges integer[];
  invalid_faces integer[];
  sql text;
1404 1405
BEGIN

Sandro Santilli's avatar
Sandro Santilli committed
1406 1407 1408 1409
  -- Check for coincident nodes
  FOR rec IN EXECUTE 'SELECT a.node_id as id1, b.node_id as id2 FROM '
    || quote_ident(toponame) || '.node a, '
    || quote_ident(toponame) || '.node b '
1410 1411
       'WHERE a.node_id < b.node_id '
       ' AND ST_DWithin(a.geom, b.geom, 0)' -- NOTE: see #1625 and #1789
Sandro Santilli's avatar
Sandro Santilli committed
1412 1413 1414 1415 1416 1417 1418 1419 1420
  LOOP
    retrec.error = 'coincident nodes';
    retrec.id1 = rec.id1;
    retrec.id2 = rec.id2;
    RETURN NEXT retrec;
  END LOOP;

  -- Check for edge crossed nodes
  -- TODO: do this in the single edge loop
1421
  FOR rec IN EXECUTE 'SELECT n.node_id as nid, e.edge_id as eid FROM '
Sandro Santilli's avatar
Sandro Santilli committed
1422 1423
    || quote_ident(toponame) || '.node n, '
    || quote_ident(toponame) || '.edge e '
1424 1425 1426
       'WHERE e.start_node != n.node_id '
       'AND e.end_node != n.node_id '
       'AND ST_Within(n.geom, e.geom)'
Sandro Santilli's avatar
Sandro Santilli committed
1427 1428
  LOOP
    retrec.error = 'edge crosses node';
1429 1430
    retrec.id1 = rec.eid; -- edge_id
    retrec.id2 = rec.nid; -- node_id
Sandro Santilli's avatar
Sandro Santilli committed
1431 1432 1433
    RETURN NEXT retrec;
  END LOOP;

1434
  -- Scan all edges
Sandro Santilli's avatar
Sandro Santilli committed
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
  FOR rec IN EXECUTE 'SELECT e.geom, e.edge_id as id1, e.left_face, e.right_face FROM '
    || quote_ident(toponame) || '.edge e ORDER BY edge_id'
  LOOP

    -- Any invalid edge becomes a cancer for higher level complexes
    IF NOT ST_IsValid(rec.geom) THEN

      retrec.error = 'invalid edge';
      retrec.id1 = rec.id1;
      retrec.id2 = NULL;
      RETURN NEXT retrec;
      invalid_edges := array_append(invalid_edges, rec.id1);
1447 1448

      IF invalid_faces IS NULL OR NOT rec.left_face = ANY ( invalid_faces )
Sandro Santilli's avatar
Sandro Santilli committed
1449 1450 1451
      THEN
        invalid_faces := array_append(invalid_faces, rec.left_face);
      END IF;
1452 1453

      IF rec.right_face != rec.left_face AND ( invalid_faces IS NULL OR
Sandro Santilli's avatar
Sandro Santilli committed
1454 1455 1456 1457
            NOT rec.right_face = ANY ( invalid_faces ) )
      THEN
        invalid_faces := array_append(invalid_faces, rec.right_face);
      END IF;
1458 1459 1460

      CONTINUE;

Sandro Santilli's avatar
Sandro Santilli committed
1461
    END IF;
1462

Sandro Santilli's avatar
Sandro Santilli committed
1463 1464 1465 1466 1467
    IF NOT ST_IsSimple(rec.geom) THEN
      retrec.error = 'edge not simple';
      retrec.id1 = rec.id1;
      retrec.id2 = NULL;
      RETURN NEXT retrec;
1468 1469
    END IF;

Sandro Santilli's avatar
Sandro Santilli committed
1470 1471 1472 1473
  END LOOP;

  -- Check for edge crossing
  sql := 'SELECT e1.edge_id as id1, e2.edge_id as id2, '
1474 1475
       ' e1.geom as g1, e2.geom as g2, '
       'ST_Relate(e1.geom, e2.geom) as im FROM '
Sandro Santilli's avatar
Sandro Santilli committed
1476 1477
    || quote_ident(toponame) || '.edge e1, '
    || quote_ident(toponame) || '.edge e2 '
1478 1479
       'WHERE e1.edge_id < e2.edge_id '
       ' AND e1.geom && e2.geom ';
Sandro Santilli's avatar
Sandro Santilli committed
1480 1481 1482 1483 1484 1485 1486 1487 1488
  IF invalid_edges IS NOT NULL THEN
    sql := sql || ' AND NOT e1.edge_id = ANY ('
               || quote_literal(invalid_edges) || ')'
               || ' AND NOT e2.edge_id = ANY ('
               || quote_literal(invalid_edges) || ')';
  END IF;

  FOR rec IN EXECUTE sql
  LOOP
1489

Sandro Santilli's avatar
Sandro Santilli committed
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
    IF ST_RelateMatch(rec.im, 'FF1F**1*2') THEN
      CONTINUE; -- no interior intersection

    --
    -- Closed lines have no boundary, so endpoint
    -- intersection would be considered interior
    -- See http://trac.osgeo.org/postgis/ticket/770
    -- See also full explanation in topology.AddEdge
    --

1500
    ELSIF ST_RelateMatch(rec.im, 'FF10F01F2') THEN
Sandro Santilli's avatar
Sandro Santilli committed
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
      -- first line (g1) is open, second (g2) is closed
      -- first boundary has puntual intersection with second interior
      --
      -- compute intersection, check it equals second endpoint
      IF ST_Equals(ST_Intersection(rec.g2, rec.g1),
                   ST_StartPoint(rec.g2))
      THEN
        CONTINUE;
      END IF;

1511
    ELSIF ST_RelateMatch(rec.im, 'F01FFF102') THEN
Sandro Santilli's avatar
Sandro Santilli committed
1512 1513
      -- second line (g2) is open, first (g1) is closed
      -- second boundary has puntual intersection with first interior
1514
      --
Sandro Santilli's avatar
Sandro Santilli committed
1515 1516 1517 1518 1519 1520 1521
      -- compute intersection, check it equals first endpoint
      IF ST_Equals(ST_Intersection(rec.g2, rec.g1),
                   ST_StartPoint(rec.g1))
      THEN
        CONTINUE;
      END IF;

1522
    ELSIF ST_RelateMatch(rec.im, '0F1FFF1F2') THEN
Sandro Santilli's avatar
Sandro Santilli committed
1523 1524
      -- both lines are closed (boundary intersects nothing)
      -- they have puntual intersection between interiors
1525
      --
Sandro Santilli's avatar
Sandro Santilli committed
1526 1527 1528 1529 1530 1531 1532 1533
      -- compute intersection, check it's a single point
      -- and equals first StartPoint _and_ second StartPoint
      IF ST_Equals(ST_Intersection(rec.g1, rec.g2),
                   ST_StartPoint(rec.g1)) AND
         ST_Equals(ST_StartPoint(rec.g1), ST_StartPoint(rec.g2))
      THEN
        CONTINUE;
      END IF;
1534

Sandro Santilli's avatar
Sandro Santilli committed
1535 1536 1537 1538 1539 1540 1541 1542 1543
    END IF;

    retrec.error = 'edge crosses edge';
    retrec.id1 = rec.id1;
    retrec.id2 = rec.id2;
    RETURN NEXT retrec;
  END LOOP;

  -- Check for edge start_node geometry mis-match
1544
  -- TODO: move this in the first edge table scan
Sandro Santilli's avatar
Sandro Santilli committed
1545 1546 1547
  FOR rec IN EXECUTE 'SELECT e.edge_id as id1, n.node_id as id2 FROM '
    || quote_ident(toponame) || '.edge e, '
    || quote_ident(toponame) || '.node n '
1548 1549
       'WHERE e.start_node = n.node_id '
       'AND NOT ST_Equals(ST_StartPoint(e.geom), n.geom)'
Sandro Santilli's avatar
Sandro Santilli committed
1550 1551 1552 1553 1554 1555 1556 1557
  LOOP
    retrec.error = 'edge start node geometry mis-match';
    retrec.id1 = rec.id1;
    retrec.id2 = rec.id2;
    RETURN NEXT retrec;
  END LOOP;

  -- Check for edge end_node geometry mis-match
1558
  -- TODO: move this in the first edge table scan
Sandro Santilli's avatar
Sandro Santilli committed
1559 1560 1561
  FOR rec IN EXECUTE 'SELECT e.edge_id as id1, n.node_id as id2 FROM '
    || quote_ident(toponame) || '.edge e, '
    || quote_ident(toponame) || '.node n '
1562 1563
       'WHERE e.end_node = n.node_id '
       'AND NOT ST_Equals(ST_EndPoint(e.geom), n.geom)'
Sandro Santilli's avatar
Sandro Santilli committed
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
  LOOP
    retrec.error = 'edge end node geometry mis-match';
    retrec.id1 = rec.id1;
    retrec.id2 = rec.id2;
    RETURN NEXT retrec;
  END LOOP;

  -- Check for faces w/out edges
  FOR rec IN EXECUTE 'SELECT face_id as id1 FROM '
    || quote_ident(toponame) || '.face '
1574
    || 'WHERE face_id > 0 EXCEPT ( SELECT left_face FROM '
Sandro Santilli's avatar
Sandro Santilli committed
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
    || quote_ident(toponame) || '.edge '
    || ' UNION SELECT right_face FROM '
    || quote_ident(toponame) || '.edge '
    || ')'
  LOOP
    retrec.error = 'face without edges';
    retrec.id1 = rec.id1;
    retrec.id2 = NULL;
    RETURN NEXT retrec;
  END LOOP;

  -- Now create a temporary table to construct all face geometries
  -- for checking their consistency

  sql := 'CREATE TEMP TABLE face_check ON COMMIT DROP AS '
1590
       'SELECT face_id, topology.ST_GetFaceGeometry('
Sandro Santilli's avatar
Sandro Santilli committed
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
    || quote_literal(toponame) || ', face_id) as geom, mbr FROM '
    || quote_ident(toponame) || '.face WHERE face_id > 0';
  IF invalid_faces IS NOT NULL THEN
    sql := sql || ' AND NOT face_id = ANY ('
               || quote_literal(invalid_faces) || ')';
  END IF;
  EXECUTE sql;

  -- Build a gist index on geom
  EXECUTE 'CREATE INDEX "face_check_gist" ON '
1601
       'face_check USING gist (geom);';
Sandro Santilli's avatar
Sandro Santilli committed
1602 1603

  -- Build a btree index on id
1604
  EXECUTE 'CREATE INDEX "face_check_bt" ON '
1605
       'face_check (face_id);';
Sandro Santilli's avatar
Sandro Santilli committed
1606 1607 1608 1609

  -- Scan the table looking for NULL geometries
  FOR rec IN EXECUTE
    'SELECT f1.face_id FROM '
1610
       'face_check f1 WHERE f1.geom IS NULL OR ST_IsEmpty(f1.geom)'
Sandro Santilli's avatar
Sandro Santilli committed
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
  LOOP
    -- Face missing !
    retrec.error := 'face has no rings';
    retrec.id1 := rec.face_id;
    retrec.id2 := NULL;
    RETURN NEXT retrec;
  END LOOP;

  -- Scan the table looking for overlap or containment
  -- TODO: also check for MBR consistency
  FOR rec IN EXECUTE
    'SELECT f1.geom, f1.face_id as id1, f2.face_id as id2, '
1623 1624 1625 1626 1627 1628
       ' ST_Relate(f1.geom, f2.geom) as im'
       ' FROM '
       'face_check f1, '
       'face_check f2 '
       'WHERE f1.face_id < f2.face_id'
       ' AND f1.geom && f2.geom'
Sandro Santilli's avatar
Sandro Santilli committed
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
  LOOP

    -- Face overlap
    IF ST_RelateMatch(rec.im, 'T*T***T**') THEN
    retrec.error = 'face overlaps face';
    retrec.id1 = rec.id1;
    retrec.id2 = rec.id2;
    RETURN NEXT retrec;
    END IF;

1639
    -- Face 1 is within face 2
Sandro Santilli's avatar
Sandro Santilli committed
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
    IF ST_RelateMatch(rec.im, 'T*F**F***') THEN
    retrec.error = 'face within face';
    retrec.id1 = rec.id1;
    retrec.id2 = rec.id2;
    RETURN NEXT retrec;
    END IF;

    -- Face 1 contains face 2
    IF ST_RelateMatch(rec.im, 'T*****FF*') THEN
    retrec.error = 'face within face';
    retrec.id1 = rec.id2;
    retrec.id2 = rec.id1;
    RETURN NEXT retrec;
    END IF;

  END LOOP;
1656 1657

#if 0
Sandro Santilli's avatar
Sandro Santilli committed
1658 1659 1660 1661
  -- Check SRID consistency
  FOR rec in EXECUTE
    'SELECT count(*) FROM ( getSRID(geom) FROM '
    || quote_ident(toponame) || '.edge '
1662
       ' UNION '
Sandro Santilli's avatar
Sandro Santilli committed
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
    'SELECT getSRID(geom) FROM '
    || quote_ident(toponame) || '.node )'
  LOOP
    IF rec.count > 1 THEN
      retrec.error = 'mixed SRIDs';
      retrec.id1 = NULL;
      retrec.id2 = NULL;
      RETURN NEXT retrec;
    END IF;
  END LOOP;
1673 1674
#endif

1675 1676
  DROP TABLE face_check;

Sandro Santilli's avatar
Sandro Santilli committed
1677
  RETURN;
1678
END
1679
$$
1680
LANGUAGE 'plpgsql' VOLATILE STRICT;
1681 1682 1683
-- } ValidateTopology(toponame)

--{
1684
--  CreateTopology(name, SRID, precision, hasZ)
1685 1686 1687
--
-- Create a topology schema, add a topology info record
-- in the topology.topology relation, return it's numeric
1688
-- id.