# Topology

The PostGIS Topology types and functions are used to manage topological objects such as faces, edges and nodes.

Sandro Santilli's presentation at PostGIS Day Paris 2011 conference gives a good synopsis of PostGIS Topology and where it is headed Topology with PostGIS 2.0 slide deck.

Vincent Picavet provides a good synopsis and overview of what is Topology, how is it used, and various FOSS4G tools that support it in PostGIS Topology PGConf EU 2012.

An example of a topologically based GIS database is the US Census Topologically Integrated Geographic Encoding and Referencing System (TIGER) database. If you want to experiment with PostGIS topology and need some data, check out Topology_Load_Tiger.

The PostGIS topology module has existed in prior versions of PostGIS but was never part of the Official PostGIS documentation. In PostGIS 2.0.0 major cleanup is going on to remove use of all deprecated functions in it, fix known usability issues, better document the features and functions, add new functions, and enhance to closer conform to SQL-MM standards.

Details of this project can be found at PostGIS Topology Wiki

All functions and tables associated with this module are installed in a schema called `topology`.

Functions that are defined in SQL/MM standard are prefixed with ST_ and functions specific to PostGIS are not prefixed.

Topology support is build by default starting with PostGIS 2.0, and can be disabled specifying --without-topology configure option at build time as described in postgis_installation

## Topology Types

getfaceedges_returntype

A composite type that consists of a sequence number and an edge number.

#### Description

A composite type that consists of a sequence number and an edge number. This is the return type for `ST_GetFaceEdges` and `GetNodeEdges` functions.

1. `sequence` is an integer: Refers to a topology defined in the topology.topology table which defines the topology schema and srid.

2. `edge` is an integer: The identifier of an edge.

TopoGeometry

A composite type representing a topologically defined geometry.

#### Description

A composite type that refers to a topology geometry in a specific topology layer, having a specific type and a specific id. The elements of a TopoGeometry are the properties: topology_id, layer_id, id integer, type integer.

1. `topology_id` is an integer: Refers to a topology defined in the topology.topology table which defines the topology schema and srid.

2. `layer_id` is an integer: The layer_id in the layers table that the TopoGeometry belongs to. The combination of topology_id, layer_id provides a unique reference in the topology.layers table.

3. `id` is an integer: The id is the autogenerated sequence number that uniquely defines the topogeometry in the respective topology layer.

4. `type` integer between 1 - 4 that defines the geometry type: 1:[multi]point, 2:[multi]line, 3:[multi]poly, 4:collection

#### Casting Behavior

This section lists the automatic as well as explicit casts allowed for this data type

Cast To | Behavior
geometry | automatic

#### See Also

CreateTopoGeom

validatetopology_returntype

A composite type that consists of an error message and id1 and id2 to denote location of error. This is the return type for `ValidateTopology`.

#### Description

A composite type that consists of an error message and two integers. The ValidateTopology function returns a set of these to denote validation errors and the id1 and id2 to denote the ids of the topology objects involved in the error.

1. `error` is varchar: Denotes type of error.

   Current error descriptors are: coincident nodes, edge crosses node, edge not simple, edge end node geometry mismatch, edge start node geometry mismatch, face overlaps face,face within face,

2. `id1` is an integer: Denotes identifier of edge / face / nodes in error.

3. `id2` is an integer: For errors that involve 2 objects denotes the secondary edge / or node

#### See Also

ValidateTopology

## Topology Domains

TopoElement

An array of 2 integers generally used to identify a TopoGeometry component.

#### Description

An array of 2 integers used to represent one component of a simple or hierarchical topogeometry.

In the case of a simple TopoGeometry the first element of the array represents the identifier of a topological primitive and the second element represents its type (1:node, 2:edge, 3:face). In the case of a hierarchical TopoGeometry the first element of the array represents the identifier of a child TopoGeometry and the second element represents its layer identifier.

For any given hierarchical TopoGeometry all child TopoGeometry elements will come from the same child layer, as specified in the topology.layer record for the layer of the TopoGeometry being defined.

#### Examples

    SELECT te[1] AS id, te[2] AS type FROM
    ( SELECT ARRAY[1,2]::topology.topoelement AS te ) f;
     id | type
    ----+------
      1 |    2

    SELECT ARRAY[1,2]::topology.topoelement;
      te
    -------
     {1,2}

    --Example of what happens when you try to case a 3 element array to topoelement
    -- NOTE: topoement has to be a 2 element array so fails dimension check
    SELECT ARRAY[1,2,3]::topology.topoelement;
    ERROR:  value for domain topology.topoelement violates check constraint "dimensions"

#### See Also

GetTopoGeomElements, topoelementarray, topogeometry, TopoGeom_addElement, TopoGeom_remElement

TopoElementArray

An array of TopoElement objects.

#### Description

An array of 1 or more TopoElement objects, generally used to pass around components of TopoGeometry objects.

#### Examples

    SELECT '{{1,2},{4,3}}'::topology.topoelementarray As tea;
      tea
    -------
    {{1,2},{4,3}}

    -- more verbose equivalent --
    SELECT ARRAY[ARRAY[1,2], ARRAY[4,3]]::topology.topoelementarray As tea;

      tea
    -------
    {{1,2},{4,3}}

    --using the array agg function packaged with topology --
    SELECT topology.TopoElementArray_Agg(ARRAY[e,t]) As tea
      FROM generate_series(1,4) As e CROSS JOIN generate_series(1,3) As t;
      tea
    --------------------------------------------------------------------------
    {{1,1},{1,2},{1,3},{2,1},{2,2},{2,3},{3,1},{3,2},{3,3},{4,1},{4,2},{4,3}}

    SELECT '{{1,2,4},{3,4,5}}'::topology.topoelementarray As tea;
    ERROR:  value for domain topology.topoelementarray violates check constraint "dimensions"

#### See Also

topoelement, GetTopoGeomElementArray, TopoElementArray_Agg

## Topology and TopoGeometry Management

AddTopoGeometryColumn

Adds a topogeometry column to an existing table, registers this new column as a layer in topology.layer and returns the new layer_id.

                            integer AddTopoGeometryColumn
                            varchar
                            topology_name

                            varchar
                            schema_name

                            varchar
                            table_name

                            varchar
                            column_name

                            varchar
                            feature_type

                            integer AddTopoGeometryColumn

                            varchar
                            topology_name

                            varchar
                            schema_name

                            varchar
                            table_name

                            varchar
                            column_name

                            varchar
                            feature_type

                            integer
                            child_layer

#### Description

Each TopoGeometry object belongs to a specific Layer of a specific Topology. Before creating a TopoGeometry object you need to create its TopologyLayer. A Topology Layer is an association of a feature-table with the topology. It also contain type and hierarchy information. We create a layer using the AddTopoGeometryColumn() function:

This function will both add the requested column to the table and add a record to the topology.layer table with all the given info.

If you don't specify [child_layer] (or set it to NULL) this layer would contain Basic TopoGeometries (composed by primitive topology elements). Otherwise this layer will contain hierarchical TopoGeometries (composed by TopoGeometries from the child_layer).

Once the layer is created (its id is returned by the AddTopoGeometryColumn function) you're ready to construct TopoGeometry objects in it

Valid `feature_type`s are: POINT, MULTIPOINT, LINE, MULTILINE, POLYGON, MULTIPOLYGON, COLLECTION

Availability: 1.1

#### Examples

    -- Note for this example we created our new table in the ma_topo schema
    -- though we could have created it in a different schema -- in which case topology_name and schema_name would be different
    CREATE SCHEMA ma;
    CREATE TABLE ma.parcels(gid serial, parcel_id varchar(20) PRIMARY KEY, address text);
    SELECT topology.AddTopoGeometryColumn('ma_topo', 'ma', 'parcels', 'topo', 'POLYGON');

    CREATE SCHEMA ri;
    CREATE TABLE ri.roads(gid serial PRIMARY KEY, road_name text);
    SELECT topology.AddTopoGeometryColumn('ri_topo', 'ri', 'roads', 'topo', 'LINE');

#### See Also

DropTopoGeometryColumn, toTopoGeom, CreateTopology, CreateTopoGeom

RenameTopoGeometryColumn

Renames a topogeometry column

                            topology.layer RenameTopoGeometryColumn
                            regclass
                            layer_table
                            name
                            feature_column
                            name
                            new_name

#### Description

This function changes the name of an existing TopoGeometry column ensuring metadata information about it is updated accordingly.

Availability: 3.4.0

#### Examples

    SELECT topology.RenameTopoGeometryColumn('public.parcels', 'topogeom', 'tgeom');

#### See Also

AddTopoGeometryColumn, RenameTopology

DropTopology

Use with caution: Drops a topology schema and deletes its reference from topology.topology table and references to tables in that schema from the geometry_columns table.

    					integer DropTopology
    					varchar  topology_schema_name

#### Description

Drops a topology schema and deletes its reference from topology.topology table and references to tables in that schema from the geometry_columns table. This function should be USED WITH CAUTION, as it could destroy data you care about. If the schema does not exist, it just removes reference entries the named schema.

Availability: 1.1

#### Examples

Cascade drops the ma_topo schema and removes all references to it in topology.topology and geometry_columns.

    SELECT topology.DropTopology('ma_topo');

#### See Also

DropTopoGeometryColumn

RenameTopology

Renames a topology

    						varchar RenameTopology
    						varchar  old_name
    						varchar  new_name

#### Description

Renames a topology schema, updating its metadata record in the `topology.topology` table.

Availability: 3.4.0

#### Examples

Rename a topology from `topo_stage` to `topo_prod`.

    SELECT topology.RenameTopology('topo_stage', 'topo_prod');

#### See Also

CopyTopology, RenameTopoGeometryColumn

DropTopoGeometryColumn

Drops the topogeometry column from the table named `table_name` in schema `schema_name` and unregisters the columns from topology.layer table.

    					text DropTopoGeometryColumn
    					varchar  schema_name
    					varchar  table_name
    					varchar  column_name

#### Description

Drops the topogeometry column from the table named `table_name` in schema `schema_name` and unregisters the columns from topology.layer table. Returns summary of drop status. NOTE: it first sets all values to NULL before dropping to bypass referential integrity checks.

Availability: 1.1

#### Examples

    SELECT topology.DropTopoGeometryColumn('ma_topo', 'parcel_topo', 'topo');

#### See Also

AddTopoGeometryColumn

Populate_Topology_Layer

Adds missing entries to topology.layer table by reading metadata from topo tables.

    					setof record Populate_Topology_Layer

#### Description

Adds missing entries to the `topology.layer` table by inspecting topology constraints on tables. This function is useful for fixing up entries in topology catalog after restores of schemas with topo data.

It returns the list of entries created. Returned columns are `schema_name`, `table_name`, `feature_column`.

Availability: 2.3.0

#### Examples

    SELECT CreateTopology('strk_topo');
    CREATE SCHEMA strk;
    CREATE TABLE strk.parcels(gid serial, parcel_id varchar(20) PRIMARY KEY, address text);
    SELECT topology.AddTopoGeometryColumn('strk_topo', 'strk', 'parcels', 'topo', 'POLYGON');
    -- this will return no records because this feature is already registered
    SELECT *
      FROM topology.Populate_Topology_Layer();

    -- let's rebuild
    TRUNCATE TABLE topology.layer;

    SELECT *
      FROM topology.Populate_Topology_Layer();

    SELECT topology_id,layer_id, schema_name As sn, table_name As tn, feature_column As fc
    FROM topology.layer;

     schema_name | table_name | feature_column
    -------------+------------+----------------
     strk        | parcels    | topo
    (1 row)

     topology_id | layer_id |  sn  |   tn    |  fc
    -------------+----------+------+---------+------
               2 |        2 | strk | parcels | topo
    (1 row)

#### See Also

AddTopoGeometryColumn

TopologySummary

Takes a topology name and provides summary totals of types of objects in topology.

    					text TopologySummary
    					varchar  topology_schema_name

#### Description

Takes a topology name and provides summary totals of types of objects in topology.

Availability: 2.0.0

#### Examples

    SELECT topology.topologysummary('city_data');
                        topologysummary
    --------------------------------------------------------
     Topology city_data (329), SRID 4326, precision: 0
     22 nodes, 24 edges, 10 faces, 29 topogeoms in 5 layers
     Layer 1, type Polygonal (3), 9 topogeoms
      Deploy: features.land_parcels.feature
     Layer 2, type Puntal (1), 8 topogeoms
      Deploy: features.traffic_signs.feature
     Layer 3, type Lineal (2), 8 topogeoms
      Deploy: features.city_streets.feature
     Layer 4, type Polygonal (3), 3 topogeoms
      Hierarchy level 1, child layer 1
      Deploy: features.big_parcels.feature
     Layer 5, type Puntal (1), 1 topogeoms
      Hierarchy level 1, child layer 2
      Deploy: features.big_signs.feature

#### See Also

Topology_Load_Tiger

ValidateTopology

Returns a set of validatetopology_returntype objects detailing issues with topology.

    					setof validatetopology_returntype ValidateTopology
    					varchar  toponame
    					geometry bbox

#### Description

Returns a set of validatetopology_returntype objects detailing issues with topology, optionally limiting the check to the area specified by the `bbox` parameter.

List of possible errors, what they mean and what the returned ids represent are displayed below:

Error | id1 | id2 | Meaning
coincident nodes | Identifier of first node. | Identifier of second node. | Two nodes have the same geometry.
edge crosses node | Identifier of the edge. | Identifier of the node. | An edge has a node in its interior. See ST_Relate.
invalid edge | Identifier of the edge. |  | An edge geometry is invalid. See ST_IsValid.
edge not simple | Identifier of the edge. |  | An edge geometry has self-intersections. See ST_IsSimple.
edge crosses edge | Identifier of first edge. | Identifier of second edge. | Two edges have an interior intersection. See ST_Relate.
edge start node geometry mismatch | Identifier of the edge. | Identifier of the indicated start node. | The geometry of the node indicated as the starting node for an edge does not match the first point of the edge geometry. See ST_StartPoint.
edge end node geometry mismatch | Identifier of the edge. | Identifier of the indicated end node. | The geometry of the node indicated as the ending node for an edge does not match the last point of the edge geometry. See ST_EndPoint.
face without edges | Identifier of the orphaned face. |  | No edge reports an existing face on either of its sides (left_face, right_face).
face has no rings | Identifier of the partially-defined face. |  | Edges reporting a face on their sides do not form a ring.
face has wrong mbr | Identifier of the face with wrong mbr cache. |  | Minimum bounding rectangle of a face does not match minimum bounding box of the collection of edges reporting the face on their sides.
hole not in advertised face | Signed identifier of an edge, identifying the ring. See GetRingEdges. |  | A ring of edges reporting a face on its exterior is contained in different face.
not-isolated node has not- containing_face | Identifier of the ill-defined node. |  | A node which is reported as being on the boundary of one or more edges is indicating a containing face.
isolated node has containing_face | Identifier of the ill-defined node. |  | A node which is not reported as being on the boundary of any edges is lacking the indication of a containing face.
isolated node has wrong containing_face | Identifier of the misrepresented node. |  | A node which is not reported as being on the boundary of any edges indicates a containing face which is not the actual face containing it. See GetFaceContainingPoint.
invalid next_right_edge | Identifier of the misrepresented edge. | Signed id of the edge which should be indicated as the next right edge. | The edge indicated as the next edge encountered walking on the right side of an edge is wrong.
invalid next_left_edge | Identifier of the misrepresented edge. | Signed id of the edge which should be indicated as the next left edge. | The edge indicated as the next edge encountered walking on the left side of an edge is wrong.
mixed face labeling in ring | Signed identifier of an edge, identifying the ring. See GetRingEdges. |  | Edges in a ring indicate conflicting faces on the walking side. This is also known as a "Side Location Conflict".
non-closed ring | Signed identifier of an edge, identifying the ring. See GetRingEdges. |  | A ring of edges formed by following next_left_edge/next_right_edge attributes starts and ends on different nodes.
face has multiple shells | Identifier of the contended face. | Signed identifier of an edge, identifying the ring. See GetRingEdges. | More than a one ring of edges indicate the same face on its interior.

Availability: 1.0.0

Enhanced: 2.0.0 more efficient edge crossing detection and fixes for false positives that were existent in prior versions.

Changed: 2.2.0 values for id1 and id2 were swapped for 'edge crosses node' to be consistent with error description.

Changed: 3.2.0 added optional bbox parameter, perform face labeling and edge linking checks.

#### Examples

    SELECT * FROM  topology.ValidateTopology('ma_topo');
          error        | id1 | id2
    -------------------+-----+-----
    face without edges |   1 |

#### See Also

validatetopology_returntype, Topology_Load_Tiger

ValidateTopologyRelation

Returns info about invalid topology relation records

    					setof record ValidateTopologyRelation
    					varchar  toponame

#### Description

Returns a set records giving information about invalidities in the relation table of the topology.

Availability: 3.2.0

#### See Also

ValidateTopology

FindTopology

Returns a topology record by different means.

                            topology FindTopology
                            TopoGeometry topogeom

                            topology FindTopology
                            regclass layerTable
                            name layerColumn

                            topology FindTopology
                            name layerSchema
                            name layerTable
                            name layerColumn

                            topology FindTopology
                            text topoName

                            topology FindTopology
                            int id

#### Description

Takes a topology identifier or the identifier of a topology-related object and returns a topology.topology record.

Availability: 3.2.0

#### Examples

    SELECT name(findTopology('features.land_parcels', 'feature'));
       name
    -----------
     city_data
    (1 row)

#### See Also

FindLayer

FindLayer

Returns a topology.layer record by different means.

                            topology.layer FindLayer
                            TopoGeometry tg

                            topology.layer FindLayer
                            regclass layer_table
                            name feature_column

                            topology.layer FindLayer
                            name schema_name
                            name table_name
                            name feature_column

                            topology.layer FindLayer
                            integer topology_id
                            integer layer_id

#### Description

Takes a layer identifier or the identifier of a topology-related object and returns a topology.layer record.

Availability: 3.2.0

#### Examples

    SELECT layer_id(findLayer('features.land_parcels', 'feature'));
     layer_id
    ----------
            1
    (1 row)

#### See Also

FindTopology

## Topology Statistics Management

Adding elements to a topology triggers many database queries for finding existing edges that will be split, adding nodes and updating edges that will node with the new linework. For this reason it is useful that statistics about the data in the topology tables are up-to-date.

PostGIS Topology population and editing functions do not automatically update the statistics because a updating stats after each and every change in a topology would be overkill, so it is the caller's duty to take care of that.

That the statistics updated by autovacuum will NOT be visible to transactions which started before autovacuum process completed, so long-running transactions will need to run ANALYZE themselves, to use updated statistics.

## Topology Constructors

CreateTopology

Creates a new topology schema and registers it in the topology.topology table.

    						integer CreateTopology
    						varchar  topology_schema_name

    						integer CreateTopology
    						varchar  topology_schema_name
    						integer  srid

    						integer CreateTopology
    						varchar  topology_schema_name
    						integer  srid
    						double precision  prec

    						integer CreateTopology
    						varchar  topology_schema_name
    						integer  srid
    						double precision  prec
    						boolean  hasz

#### Description

Creates a new topology schema with name `topology_name` and registers it in the `topology.topology` table. Topologies must be uniquely named. The topology tables (`edge_data`, `face`, `node`,and `relation` are created in the schema. It returns the id of the topology.

The `srid` is the spatial reference system SRID for the topology.

The tolerance `prec` is measured in the units of the spatial reference system. The tolerance defaults to 0.

`hasz` defaults to false if not specified.

This is similar to the SQL/MM ST_InitTopoGeo but has more functionality.

Availability: 1.1

Enhanced: 2.0 added the signature accepting hasZ

#### Examples

Create a topology schema called `ma_topo` that stores edges and nodes in Massachusetts State Plane-meters (SRID = 26986). The tolerance represents 0.5 meters since the spatial reference system is meter-based.

    SELECT topology.CreateTopology('ma_topo', 26986, 0.5);

Create a topology for Rhode Island called `ri_topo` in spatial reference system State Plane-feet (SRID = 3438)

    SELECT topology.CreateTopology('ri_topo', 3438) AS topoid;
    topoid
    ------
    2

#### See Also

spatial_ref_sys, ST_InitTopoGeo, Topology_Load_Tiger

CopyTopology

Makes a copy of a topology (nodes, edges, faces, layers and TopoGeometries) into a new schema

    						integer CopyTopology
    						varchar  existing_topology_name
    						varchar  new_name

#### Description

Creates a new topology with name `new_name`, with SRID and precision copied from `existing_topology_name` The nodes, edges and faces in `existing_topology_name` are copied into the new topology, as well as Layers and their associated TopoGeometries.

The new rows in the `topology.layer` table contain synthetic values for schema_name, table_name and feature_column. This is because the TopoGeometry objects exist only as a definition and are not yet available in a user-defined table.

Availability: 2.0.0

#### Examples

Make a backup of a topology called `ma_topo`.

    SELECT topology.CopyTopology('ma_topo', 'ma_topo_backup');

#### See Also

spatial_ref_sys, CreateTopology, RenameTopology

ST_InitTopoGeo

Creates a new topology schema and registers it in the topology.topology table.

    						text ST_InitTopoGeo
    						varchar  topology_schema_name

#### Description

This is the SQL-MM equivalent of CreateTopology. It lacks options for spatial reference system and tolerance. it returns a text description of the topology creation, instead of the topology id.

Availability: 1.1

&sqlmm_compliant; SQL-MM 3 Topo-Geo and Topo-Net 3: Routine Details: X.3.17

#### Examples

    SELECT topology.ST_InitTopoGeo('topo_schema_to_create') AS topocreation;
                          astopocreation
    ------------------------------------------------------------
     Topology-Geometry 'topo_schema_to_create' (id:7) created.

#### See Also

CreateTopology

ST_CreateTopoGeo

Adds a collection of geometries to a given empty topology and returns a message detailing success.

    					text ST_CreateTopoGeo
    					varchar  atopology
    					geometry  acollection

#### Description

Adds a collection of geometries to a given empty topology and returns a message detailing success.

Useful for populating an empty topology.

Availability: 2.0

&sqlmm_compliant; SQL-MM: Topo-Geo and Topo-Net 3: Routine Details -- X.3.18

#### Examples

    -- Populate topology --
    SELECT topology.ST_CreateTopoGeo('ri_topo',
     ST_GeomFromText('MULTILINESTRING((384744 236928,384750 236923,384769 236911,384799 236895,384811 236890,384833 236884,
      384844 236882,384866 236881,384879 236883,384954 236898,385087 236932,385117 236938,
      385167 236938,385203 236941,385224 236946,385233 236950,385241 236956,385254 236971,
      385260 236979,385268 236999,385273 237018,385273 237037,385271 237047,385267 237057,
      385225 237125,385210 237144,385192 237161,385167 237192,385162 237202,385159 237214,
      385159 237227,385162 237241,385166 237256,385196 237324,385209 237345,385234 237375,
      385237 237383,385238 237399,385236 237407,385227 237419,385213 237430,385193 237439,
      385174 237451,385170 237455,385169 237460,385171 237475,385181 237503,385190 237521,
      385200 237533,385206 237538,385213 237541,385221 237542,385235 237540,385242 237541,
      385249 237544,385260 237555,385270 237570,385289 237584,385292 237589,385291 237596,385284 237630))',3438)
      );

          st_createtopogeo
    ----------------------------
     Topology ri_topo populated

    -- create tables and topo geometries --
    CREATE TABLE ri.roads(gid serial PRIMARY KEY, road_name text);

    SELECT topology.AddTopoGeometryColumn('ri_topo', 'ri', 'roads', 'topo', 'LINE');

#### See Also

TopoGeo_LoadGeometry, AddTopoGeometryColumn, CreateTopology, DropTopology

TopoGeo_AddPoint

Adds a point to an existing topology using a tolerance and possibly splitting an existing edge.

    						integer TopoGeo_AddPoint
    						varchar  atopology
    						geometry  apoint
    						float8  tolerance

#### Description

Adds a point to an existing topology and returns its identifier. The given point will snap to existing nodes or edges within given tolerance. An existing edge may be split by the snapped point.

Availability: 2.0.0

#### See Also

TopoGeo_AddLineString, TopoGeo_AddPolygon, TopoGeo_LoadGeometry, AddNode, CreateTopology

TopoGeo_AddLineString

Adds a linestring to an existing topology using a tolerance and possibly splitting existing edges/faces.

    						SETOF integer TopoGeo_AddLineString
    						varchar  atopology
    						geometry  aline
    						float8  tolerance

#### Description

Adds a linestring to an existing topology and returns a set of signed edge identifiers forming it up (negative identifies mean the edge goes in the opposite direction of the input linestring). The given line will snap to existing nodes or edges within given tolerance. Existing edges and faces may be split by the line. New nodes and faces may be added.

Updating statistics about topologies being loaded via this function is up to caller, see Topology_StatsManagement.

Availability: 2.0.0

Enhanced: 3.2.0 added support for returning signed identifier.

#### See Also

TopoGeo_AddPoint, TopoGeo_AddPolygon, TopoGeo_LoadGeometry, AddEdge, CreateTopology

TopoGeo_AddPolygon

Adds a polygon to an existing topology using a tolerance and possibly splitting existing edges/faces. Returns face identifiers.

    						SETOF integer TopoGeo_AddPolygon
    						varchar  atopology
    						geometry  apoly
    						float8  tolerance

#### Description

Adds a polygon to an existing topology and returns a set of face identifiers forming it up. The boundary of the given polygon will snap to existing nodes or edges within given tolerance. Existing edges and faces may be split by the boundary of the new polygon.

Updating statistics about topologies being loaded via this function is up to caller, see Topology_StatsManagement.

Availability: 2.0.0

#### See Also

TopoGeo_AddPoint, TopoGeo_AddLineString, TopoGeo_LoadGeometry, AddFace, CreateTopology

TopoGeo_LoadGeometry

Load a geometry into an existing topology, snapping and splitting as needed.

    						void TopoGeo_LoadGeometry
    						varchar  atopology
    						geometry  ageom
    						float8  tolerance

#### Description

Loads a geometry into an existing topology. The given geometry will snap to existing nodes or edges within given tolerance. Existing edges and faces may be split as a consequence of the load.

Updating statistics about topologies being loaded via this function is up to caller, see Topology_StatsManagement.

Availability: 3.5.0

#### See Also

TopoGeo_AddPoint, TopoGeo_AddLineString, TopoGeo_AddPolygon, CreateTopology

## Topology Editors

ST_AddIsoNode

Adds an isolated node to a face in a topology and returns the nodeid of the new node. If face is null, the node is still created.

    					integer ST_AddIsoNode
    					varchar  atopology
    					integer  aface
    					geometry  apoint

#### Description

Adds an isolated node with point location `apoint` to an existing face with faceid `aface` to a topology `atopology` and returns the nodeid of the new node.

If the spatial reference system (srid) of the point geometry is not the same as the topology, the `apoint` is not a point geometry, the point is null, or the point intersects an existing edge (even at the boundaries) then an exception is thrown. If the point already exists as a node, an exception is thrown.

If `aface` is not null and the `apoint` is not within the face, then an exception is thrown.

Availability: 1.1

&sqlmm_compliant; SQL-MM: Topo-Net Routines: X+1.3.1

#### Examples

#### See Also

AddNode, CreateTopology, DropTopology, ST_Intersects

ST_AddIsoEdge

Adds an isolated edge defined by geometry `alinestring` to a topology connecting two existing isolated nodes `anode` and `anothernode` and returns the edge id of the new edge.

    					integer ST_AddIsoEdge
    					varchar  atopology
    					integer  anode
    					integer  anothernode
    					geometry  alinestring

#### Description

Adds an isolated edge defined by geometry `alinestring` to a topology connecting two existing isolated nodes `anode` and `anothernode` and returns the edge id of the new edge.

If the spatial reference system (srid) of the `alinestring` geometry is not the same as the topology, any of the input arguments are null, or the nodes are contained in more than one face, or the nodes are start or end nodes of an existing edge, then an exception is thrown.

If the `alinestring` is not within the face of the face the `anode` and `anothernode` belong to, then an exception is thrown.

If the `anode` and `anothernode` are not the start and end points of the `alinestring` then an exception is thrown.

Availability: 1.1

&sqlmm_compliant; SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.4

#### Examples

#### See Also

ST_AddIsoNode, ST_IsSimple, ST_Within

ST_AddEdgeNewFaces

Add a new edge and, if in doing so it splits a face, delete the original face and replace it with two new faces.

    					integer ST_AddEdgeNewFaces
    					varchar  atopology
    					integer  anode
    					integer  anothernode
    					geometry  acurve

#### Description

Add a new edge and, if in doing so it splits a face, delete the original face and replace it with two new faces. Returns the id of the newly added edge.

Updates all existing joined edges and relationships accordingly.

If any arguments are null, the given nodes are unknown (must already exist in the `node` table of the topology schema) , the `acurve` is not a `LINESTRING`, the `anode` and `anothernode` are not the start and endpoints of `acurve` then an error is thrown.

If the spatial reference system (srid) of the `acurve` geometry is not the same as the topology an exception is thrown.

Availability: 2.0

&sqlmm_compliant; SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.12

#### Examples

#### See Also

ST_RemEdgeNewFace

ST_AddEdgeModFace

ST_AddEdgeModFace

Add a new edge and, if in doing so it splits a face, modify the original face and add a new face.

    					integer ST_AddEdgeModFace
    					varchar  atopology
    					integer  anode
    					integer  anothernode
    					geometry  acurve

#### Description

Add a new edge and, if doing so splits a face, modify the original face and add a new one.

If possible, the new face will be created on left side of the new edge. This will not be possible if the face on the left side will need to be the Universe face (unbounded).

Returns the id of the newly added edge.

Updates all existing joined edges and relationships accordingly.

If any arguments are null, the given nodes are unknown (must already exist in the `node` table of the topology schema) , the `acurve` is not a `LINESTRING`, the `anode` and `anothernode` are not the start and endpoints of `acurve` then an error is thrown.

If the spatial reference system (srid) of the `acurve` geometry is not the same as the topology an exception is thrown.

Availability: 2.0

&sqlmm_compliant; SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.13

#### Examples

#### See Also

ST_RemEdgeModFace

ST_AddEdgeNewFaces

ST_RemEdgeNewFace

Removes an edge and, if the removed edge separated two faces, delete the original faces and replace them with a new face.

    					integer ST_RemEdgeNewFace
    					varchar  atopology
    					integer  anedge

#### Description

Removes an edge and, if the removed edge separated two faces, delete the original faces and replace them with a new face.

Returns the id of a newly created face or NULL, if no new face is created. No new face is created when the removed edge is dangling or isolated or confined with the universe face (possibly making the universe flood into the face on the other side).

Updates all existing joined edges and relationships accordingly.

Refuses to remove an edge participating in the definition of an existing TopoGeometry. Refuses to heal two faces if any TopoGeometry is defined by only one of them (and not the other).

If any arguments are null, the given edge is unknown (must already exist in the `edge` table of the topology schema), the topology name is invalid then an error is thrown.

Availability: 2.0

&sqlmm_compliant; SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.14

#### Examples

#### See Also

ST_RemEdgeModFace

ST_AddEdgeNewFaces

ST_RemEdgeModFace

Removes an edge, and if the edge separates two faces deletes one face and modifies the other face to cover the space of both.

    					integer ST_RemEdgeModFace
    					varchar  atopology
    					integer  anedge

#### Description

Removes an edge, and if the removed edge separates two faces deletes one face and modifies the other face to cover the space of both. Preferentially keeps the face on the right, to be consistent with ST_AddEdgeModFace. Returns the id of the face which is preserved.

Updates all existing joined edges and relationships accordingly.

Refuses to remove an edge participating in the definition of an existing TopoGeometry. Refuses to heal two faces if any TopoGeometry is defined by only one of them (and not the other).

If any arguments are null, the given edge is unknown (must already exist in the `edge` table of the topology schema), the topology name is invalid then an error is thrown.

Availability: 2.0

&sqlmm_compliant; SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.15

#### Examples

#### See Also

ST_AddEdgeModFace

ST_RemEdgeNewFace

ST_ChangeEdgeGeom

Changes the shape of an edge without affecting the topology structure.

    					integer ST_ChangeEdgeGeom
    					varchar  atopology
    					integer  anedge
    					geometry  acurve

#### Description

Changes the shape of an edge without affecting the topology structure.

If any arguments are null, the given edge does not exist in the `edge` table of the topology schema, the `acurve` is not a `LINESTRING`, or the modification would change the underlying topology then an error is thrown.

If the spatial reference system (srid) of the `acurve` geometry is not the same as the topology an exception is thrown.

If the new `acurve` is not simple, then an error is thrown.

If moving the edge from old to new position would hit an obstacle then an error is thrown.

Availability: 1.1.0

Enhanced: 2.0.0 adds topological consistency enforcement

&sqlmm_compliant; SQL-MM: Topo-Geo and Topo-Net 3: Routine Details X.3.6

#### Examples

    SELECT topology.ST_ChangeEdgeGeom('ma_topo', 1,
    		ST_GeomFromText('LINESTRING(227591.9 893900.4,227622.6 893844.3,227641.6 893816.6, 227704.5 893778.5)', 26986) );
     ----
     Edge 1 changed

#### See Also

ST_AddEdgeModFace

ST_RemEdgeModFace

ST_ModEdgeSplit

ST_ModEdgeSplit

Split an edge by creating a new node along an existing edge, modifying the original edge and adding a new edge.

    					integer ST_ModEdgeSplit
    					varchar  atopology
    					integer  anedge
    					geometry  apoint

#### Description

Split an edge by creating a new node along an existing edge, modifying the original edge and adding a new edge. Updates all existing joined edges and relationships accordingly. Returns the identifier of the newly added node.

Availability: 1.1

Changed: 2.0 - In prior versions, this was misnamed ST_ModEdgesSplit

&sqlmm_compliant; SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.9

#### Examples

    -- Add an edge --
     SELECT topology.AddEdge('ma_topo', ST_GeomFromText('LINESTRING(227592 893910, 227600 893910)', 26986) ) As edgeid;

    -- edgeid-
    3

    -- Split the edge  --
    SELECT topology.ST_ModEdgeSplit('ma_topo',  3, ST_SetSRID(ST_Point(227594,893910),26986)  ) As node_id;
            node_id
    -------------------------
    7

#### See Also

ST_NewEdgesSplit, ST_ModEdgeHeal, ST_NewEdgeHeal, AddEdge

ST_ModEdgeHeal

Heals two edges by deleting the node connecting them, modifying the first edge and deleting the second edge. Returns the id of the deleted node.

    					int ST_ModEdgeHeal
    					varchar  atopology
    					integer  anedge
    					integer  anotheredge

#### Description

Heals two edges by deleting the node connecting them, modifying the first edge and deleting the second edge. Returns the id of the deleted node. Updates all existing joined edges and relationships accordingly.

Availability: 2.0

&sqlmm_compliant; SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.9

#### See Also

ST_ModEdgeSplit ST_NewEdgesSplit

ST_NewEdgeHeal

Heals two edges by deleting the node connecting them, deleting both edges, and replacing them with an edge whose direction is the same as the first edge provided.

    					int ST_NewEdgeHeal
    					varchar  atopology
    					integer  anedge
    					integer  anotheredge

#### Description

Heals two edges by deleting the node connecting them, deleting both edges, and replacing them with an edge whose direction is the same as the first edge provided. Returns the id of the new edge replacing the healed ones. Updates all existing joined edges and relationships accordingly.

Availability: 2.0

&sqlmm_compliant; SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.9

#### See Also

ST_ModEdgeHeal ST_ModEdgeSplit ST_NewEdgesSplit

ST_MoveIsoNode

Moves an isolated node in a topology from one point to another. If new `apoint` geometry exists as a node an error is thrown. Returns description of move.

    					text ST_MoveIsoNode
    					varchar  atopology
    					integer  anode
    					geometry  apoint

#### Description

Moves an isolated node in a topology from one point to another. If new `apoint` geometry exists as a node an error is thrown.

If any arguments are null, the `apoint` is not a point, the existing node is not isolated (is a start or end point of an existing edge), new node location intersects an existing edge (even at the end points) or the new location is in a different face (since 3.2.0) then an exception is thrown.

If the spatial reference system (srid) of the point geometry is not the same as the topology an exception is thrown.

Availability: 2.0.0

Enhanced: 3.2.0 ensures the nod cannot be moved in a different face

&sqlmm_compliant; SQL-MM: Topo-Net Routines: X.3.2

#### Examples

    -- Add an isolated node with no face  --
    SELECT topology.ST_AddIsoNode('ma_topo',  NULL, ST_GeomFromText('POINT(227579 893916)', 26986) ) As nodeid;
     nodeid
    --------
          7
    -- Move the new node --
    SELECT topology.ST_MoveIsoNode('ma_topo', 7,  ST_GeomFromText('POINT(227579.5 893916.5)', 26986) ) As descrip;
                          descrip
    ----------------------------------------------------
    Isolated Node 7 moved to location 227579.5,893916.5

#### See Also

ST_AddIsoNode

ST_NewEdgesSplit

Split an edge by creating a new node along an existing edge, deleting the original edge and replacing it with two new edges. Returns the id of the new node created that joins the new edges.

    					integer ST_NewEdgesSplit
    					varchar  atopology
    					integer  anedge
    					geometry  apoint

#### Description

Split an edge with edge id `anedge` by creating a new node with point location `apoint` along current edge, deleting the original edge and replacing it with two new edges. Returns the id of the new node created that joins the new edges. Updates all existing joined edges and relationships accordingly.

If the spatial reference system (srid) of the point geometry is not the same as the topology, the `apoint` is not a point geometry, the point is null, the point already exists as a node, the edge does not correspond to an existing edge or the point is not within the edge then an exception is thrown.

Availability: 1.1

&sqlmm_compliant; SQL-MM: Topo-Net Routines: X.3.8

#### Examples

    -- Add an edge  --
    SELECT topology.AddEdge('ma_topo', ST_GeomFromText('LINESTRING(227575 893917,227592 893900)', 26986) ) As edgeid;
    -- result-
    edgeid
    ------
    	2
    -- Split the new edge --
    SELECT topology.ST_NewEdgesSplit('ma_topo', 2,  ST_GeomFromText('POINT(227578.5 893913.5)', 26986) ) As newnodeid;
     newnodeid
    ---------
           6

#### See Also

ST_ModEdgeSplit ST_ModEdgeHeal ST_NewEdgeHeal AddEdge

ST_RemoveIsoNode

Removes an isolated node and returns description of action. If the node is not isolated (is start or end of an edge), then an exception is thrown.

    					text ST_RemoveIsoNode
    					varchar  atopology
    					integer  anode

#### Description

Removes an isolated node and returns description of action. If the node is not isolated (is start or end of an edge), then an exception is thrown.

Availability: 1.1

&sqlmm_compliant; SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X+1.3.3

#### Examples

    -- Remove an isolated node with no face  --
    SELECT topology.ST_RemoveIsoNode('ma_topo',  7 ) As result;
             result
    -------------------------
     Isolated node 7 removed

#### See Also

ST_AddIsoNode

ST_RemoveIsoEdge

Removes an isolated edge and returns description of action. If the edge is not isolated, then an exception is thrown.

    					text ST_RemoveIsoEdge
    					varchar  atopology
    					integer  anedge

#### Description

Removes an isolated edge and returns description of action. If the edge is not isolated, then an exception is thrown.

Availability: 1.1

&sqlmm_compliant; SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X+1.3.3

#### Examples

    -- Remove an isolated node with no face  --
    SELECT topology.ST_RemoveIsoNode('ma_topo',  7 ) As result;
             result
    -------------------------
     Isolated node 7 removed

#### See Also

ST_AddIsoNode

## Topology Accessors

GetEdgeByPoint

Finds the edge-id of an edge that intersects a given point.

                    integer GetEdgeByPoint
                    varchar  atopology
                    geometry  apoint
                    float8  tol1

#### Description

Retrieves the id of an edge that intersects a Point.

The function returns an integer (id-edge) given a topology, a POINT and a tolerance. If tolerance = 0 then the point has to intersect the edge.

If `apoint` doesn't intersect an edge, returns 0 (zero).

If use tolerance > 0 and there is more than one edge near the point then an exception is thrown.

If tolerance = 0, the function uses ST_Intersects otherwise uses ST_DWithin.

Performed by the GEOS module.

Availability: 2.0.0

#### Examples

These examples use edges we created in AddEdge

    SELECT topology.GetEdgeByPoint('ma_topo',geom, 1) As with1mtol, topology.GetEdgeByPoint('ma_topo',geom,0) As withnotol
    FROM ST_GeomFromEWKT('SRID=26986;POINT(227622.6 893843)') As geom;
     with1mtol | withnotol
    -----------+-----------
             2 |         0

    SELECT topology.GetEdgeByPoint('ma_topo',geom, 1) As nearnode
    FROM ST_GeomFromEWKT('SRID=26986;POINT(227591.9 893900.4)') As geom;

    -- get error --
    ERROR:  Two or more edges found

#### See Also

AddEdge, GetNodeByPoint, GetFaceByPoint

GetFaceByPoint

Finds face intersecting a given point.

    					integer GetFaceByPoint
    					varchar  atopology
    					geometry  apoint
    					float8  tol1

#### Description

Finds a face referenced by a Point, with given tolerance.

The function will effectively look for a face intersecting a circle having the point as center and the tolerance as radius.

If no face intersects the given query location, 0 is returned (universal face).

If more than one face intersect the query location an exception is thrown.

Availability: 2.0.0

Enhanced: 3.2.0 more efficient implementation and clearer contract, stops working with invalid topologies.

#### Examples

    SELECT topology.GetFaceByPoint('ma_topo',geom, 10) As with1mtol, topology.GetFaceByPoint('ma_topo',geom,0) As withnotol
    	FROM ST_GeomFromEWKT('POINT(234604.6 899382.0)') As geom;

    	 with1mtol | withnotol
    	-----------+-----------
    			 1 |         0

    SELECT topology.GetFaceByPoint('ma_topo',geom, 1) As nearnode
    	FROM ST_GeomFromEWKT('POINT(227591.9 893900.4)') As geom;

    -- get error --
    ERROR:  Two or more faces found

#### See Also

GetFaceContainingPoint, AddFace, GetNodeByPoint, GetEdgeByPoint

GetFaceContainingPoint

Finds the face containing a point.

    					integer GetFaceContainingPoint
    					text  atopology
    					geometry  apoint

#### Description

Returns the id of the face containing a point.

An exception is thrown if the point falls on a face boundary.

The function relies on a valid topology, using edge linking and face labeling.

Availability: 3.2.0

#### See Also

ST_GetFaceGeometry

GetNodeByPoint

Finds the node-id of a node at a point location.

                    integer GetNodeByPoint
                    varchar  atopology
                    geometry  apoint
                    float8  tol1

#### Description

Retrieves the id of a node at a point location.

The function returns an integer (id-node) given a topology, a POINT and a tolerance. If tolerance = 0 means exact intersection, otherwise retrieves the node from an interval.

If `apoint` doesn't intersect a node, returns 0 (zero).

If use tolerance > 0 and there is more than one node near the point then an exception is thrown.

If tolerance = 0, the function uses ST_Intersects otherwise uses ST_DWithin.

Performed by the GEOS module.

Availability: 2.0.0

#### Examples

These examples use edges we created in AddEdge

    SELECT topology.GetNodeByPoint('ma_topo',geom, 1) As nearnode
     FROM ST_GeomFromEWKT('SRID=26986;POINT(227591.9 893900.4)') As geom;
      nearnode
    ----------
            2

    SELECT topology.GetNodeByPoint('ma_topo',geom, 1000) As too_much_tolerance
     FROM ST_GeomFromEWKT('SRID=26986;POINT(227591.9 893900.4)') As geom;

     ----get error--
     ERROR:  Two or more nodes found

#### See Also

AddEdge, GetEdgeByPoint, GetFaceByPoint

GetTopologyID

Returns the id of a topology in the topology.topology table given the name of the topology.

    					integer GetTopologyID
    					varchar toponame

#### Description

Returns the id of a topology in the topology.topology table given the name of the topology.

Availability: 1.1

#### Examples

    SELECT topology.GetTopologyID('ma_topo') As topo_id;
     topo_id
    ---------
           1

#### See Also

CreateTopology, DropTopology, GetTopologyName, GetTopologySRID

GetTopologySRID

Returns the SRID of a topology in the topology.topology table given the name of the topology.

    					integer GetTopologyID
    					varchar toponame

#### Description

Returns the spatial reference id of a topology in the topology.topology table given the name of the topology.

Availability: 2.0.0

#### Examples

    SELECT topology.GetTopologySRID('ma_topo') As SRID;
     SRID
    -------
      4326

#### See Also

CreateTopology, DropTopology, GetTopologyName, GetTopologyID

GetTopologyName

Returns the name of a topology (schema) given the id of the topology.

    					varchar GetTopologyName
    					integer topology_id

#### Description

Returns the topology name (schema) of a topology from the topology.topology table given the topology id of the topology.

Availability: 1.1

#### Examples

    SELECT topology.GetTopologyName(1) As topo_name;
     topo_name
    -----------
     ma_topo

#### See Also

CreateTopology, DropTopology, GetTopologyID, GetTopologySRID

ST_GetFaceEdges

Returns a set of ordered edges that bound `aface`.

    					getfaceedges_returntype ST_GetFaceEdges
    					varchar  atopology
    					integer  aface

#### Description

Returns a set of ordered edges that bound `aface`. Each output consists of a sequence and edgeid. Sequence numbers start with value 1.

Enumeration of each ring edges start from the edge with smallest identifier. Order of edges follows a left-hand-rule (bound face is on the left of each directed edge).

Availability: 2.0

&sqlmm_compliant; SQL-MM 3 Topo-Geo and Topo-Net 3: Routine Details: X.3.5

#### Examples

    -- Returns the edges bounding face 1
    SELECT (topology.ST_GetFaceEdges('tt', 1)).*;
    -- result --
     sequence | edge
    ----------+------
            1 |   -4
            2 |    5
            3 |    7
            4 |   -6
            5 |    1
            6 |    2
            7 |    3
    (7 rows)

    -- Returns the sequence, edge id
    -- and geometry of the edges that bound face 1
    -- If you just need geom and seq, can use ST_GetFaceGeometry
    SELECT t.seq, t.edge, geom
    FROM topology.ST_GetFaceEdges('tt',1) As t(seq,edge)
    	INNER JOIN tt.edge AS e ON abs(t.edge) = e.edge_id;

#### See Also

GetRingEdges, AddFace, ST_GetFaceGeometry

ST_GetFaceGeometry

Returns the polygon in the given topology with the specified face id.

    					geometry ST_GetFaceGeometry
    					varchar  atopology
    					integer  aface

#### Description

Returns the polygon in the given topology with the specified face id. Builds the polygon from the edges making up the face.

Availability: 1.1

&sqlmm_compliant; SQL-MM 3 Topo-Geo and Topo-Net 3: Routine Details: X.3.16

#### Examples

    -- Returns the wkt of the polygon added with AddFace
    SELECT ST_AsText(topology.ST_GetFaceGeometry('ma_topo', 1)) As facegeomwkt;
    -- result --
                   facegeomwkt

    --------------------------------------------------------------------------------
     POLYGON((234776.9 899563.7,234896.5 899456.7,234914 899436.4,234946.6 899356.9,
    234872.5 899328.7,234891 899285.4,234992.5 899145,234890.6 899069,
    234755.2 899255.4,234612.7 899379.4,234776.9 899563.7))

#### See Also

AddFace

GetRingEdges

Returns the ordered set of signed edge identifiers met by walking on an a given edge side.

    					getfaceedges_returntype GetRingEdges
    					varchar  atopology
    					integer  aring
    					integer  max_edges=null

#### Description

Returns the ordered set of signed edge identifiers met by walking on an a given edge side. Each output consists of a sequence and a signed edge id. Sequence numbers start with value 1.

If you pass a positive edge id, the walk starts on the left side of the corresponding edge and follows the edge direction. If you pass a negative edge id, the walk starts on the right side of it and goes backward.

If `max_edges` is not null no more than those records are returned by that function. This is meant to be a safety parameter when dealing with possibly invalid topologies.

This function uses edge ring linking metadata.

Availability: 2.0.0

#### See Also

ST_GetFaceEdges, GetNodeEdges

GetNodeEdges

Returns an ordered set of edges incident to the given node.

    					getfaceedges_returntype GetNodeEdges
    					varchar  atopology
    					integer  anode

#### Description

Returns an ordered set of edges incident to the given node. Each output consists of a sequence and a signed edge id. Sequence numbers start with value 1. A positive edge starts at the given node. A negative edge ends into the given node. Closed edges will appear twice (with both signs). Order is clockwise starting from northbound.

This function computes ordering rather than deriving from metadata and is thus usable to build edge ring linking.

Availability: 2.0

#### See Also

getfaceedges_returntype, GetRingEdges, ST_Azimuth

## Topology Processing

Polygonize

Finds and registers all faces defined by topology edges.

    					text Polygonize
    					varchar  toponame

#### Description

Registers all faces that can be built out a topology edge primitives.

The target topology is assumed to contain no self-intersecting edges.

Already known faces are recognized, so it is safe to call Polygonize multiple times on the same topology.

This function does not use nor set the next_left_edge and next_right_edge fields of the edge table.

Availability: 2.0.0

#### See Also

AddFace, ST_Polygonize

AddNode

Adds a point node to the node table in the specified topology schema and returns the nodeid of new node. If point already exists as node, the existing nodeid is returned.

    						integer AddNode
    						varchar  toponame
    						geometry  apoint
    						boolean  allowEdgeSplitting=false
    						boolean  computeContainingFace=false

#### Description

Adds a point node to the node table in the specified topology schema. The AddEdge function automatically adds start and end points of an edge when called so not necessary to explicitly add nodes of an edge.

If any edge crossing the node is found either an exception is raised or the edge is split, depending on the `allowEdgeSplitting` parameter value.

If `computeContainingFace` is true a newly added node would get the correct containing face computed.

If the `apoint` geometry already exists as a node, the node is not added but the existing nodeid is returned.

Availability: 2.0.0

#### Examples

    SELECT topology.AddNode('ma_topo', ST_GeomFromText('POINT(227641.6 893816.5)', 26986) ) As nodeid;
    -- result --
    nodeid
    --------
     4

#### See Also

AddEdge, CreateTopology

AddEdge

Adds a linestring edge to the edge table and associated start and end points to the point nodes table of the specified topology schema using the specified linestring geometry and returns the edgeid of the new (or existing) edge.

    					integer AddEdge
    					varchar  toponame
    					geometry  aline

#### Description

Adds an edge to the edge table and associated nodes to the nodes table of the specified `toponame` schema using the specified linestring geometry and returns the edgeid of the new or existing record. The newly added edge has "universe" face on both sides and links to itself.

If the `aline` geometry crosses, overlaps, contains or is contained by an existing linestring edge, then an error is thrown and the edge is not added.

The geometry of `aline` must have the same `srid` as defined for the topology otherwise an invalid spatial reference sys error will be thrown.

Performed by the GEOS module.

AddEdge is deprecated as of 3.5.0. Use TopoGeo_AddLineString instead.

Availability: 2.0.0

#### Examples

    SELECT topology.AddEdge('ma_topo', ST_GeomFromText('LINESTRING(227575.8 893917.2,227591.9 893900.4)', 26986) ) As edgeid;
    -- result-
    edgeid
    --------
     1

    SELECT topology.AddEdge('ma_topo', ST_GeomFromText('LINESTRING(227591.9 893900.4,227622.6 893844.2,227641.6 893816.5,
     227704.5 893778.5)', 26986) ) As edgeid;
    -- result --
    edgeid
    --------
     2

     SELECT topology.AddEdge('ma_topo', ST_GeomFromText('LINESTRING(227591.2 893900, 227591.9 893900.4,
      227704.5 893778.5)', 26986) ) As edgeid;
     -- gives error --
     ERROR:  Edge intersects (not on endpoints) with existing edge 1

#### See Also

TopoGeo_AddLineString, CreateTopology, spatial_ref_sys

AddFace

Registers a face primitive to a topology and gets its identifier.

    					integer AddFace
    					varchar  toponame
    					geometry  apolygon
    					boolean  force_new=false

#### Description

Registers a face primitive to a topology and gets its identifier.

For a newly added face, the edges forming its boundaries and the ones contained in the face will be updated to have correct values in the left_face and right_face fields. Isolated nodes contained in the face will also be updated to have a correct containing_face field value.

This function does not use nor set the next_left_edge and next_right_edge fields of the edge table.

The target topology is assumed to be valid (containing no self-intersecting edges). An exception is raised if: The polygon boundary is not fully defined by existing edges or the polygon overlaps an existing face.

If the `apolygon` geometry already exists as a face, then: if `force_new` is false (the default) the face id of the existing face is returned; if `force_new` is true a new id will be assigned to the newly registered face.

When a new registration of an existing face is performed (force_new=true), no action will be taken to resolve dangling references to the existing face in the edge, node an relation tables, nor will the MBR field of the existing face record be updated. It is up to the caller to deal with that.

The `apolygon` geometry must have the same `srid` as defined for the topology otherwise an invalid spatial reference sys error will be thrown.

Availability: 2.0.0

#### Examples

    -- first add the edges we use generate_series as an iterator (the below
    -- will only work for polygons with < 10000 points because of our max in gs)
    SELECT topology.AddEdge('ma_topo', ST_MakeLine(ST_PointN(geom,i), ST_PointN(geom, i + 1) )) As edgeid
        FROM (SELECT  ST_NPoints(geom) AS npt, geom
                FROM
                    (SELECT ST_Boundary(ST_GeomFromText('POLYGON((234896.5 899456.7,234914 899436.4,234946.6 899356.9,234872.5 899328.7,
                    234891 899285.4,234992.5 899145, 234890.6 899069,234755.2 899255.4,
                    234612.7 899379.4,234776.9 899563.7,234896.5 899456.7))', 26986) )  As geom
                )  As geoms) As facen CROSS JOIN generate_series(1,10000) As i
             WHERE i < npt;
    -- result --
     edgeid
    --------
          3
          4
          5
          6
          7
          8
          9
         10
         11
         12
    (10 rows)
    -- then add the face -

    SELECT topology.AddFace('ma_topo',
        ST_GeomFromText('POLYGON((234896.5 899456.7,234914 899436.4,234946.6 899356.9,234872.5 899328.7,
        234891 899285.4,234992.5 899145, 234890.6 899069,234755.2 899255.4,
        234612.7 899379.4,234776.9 899563.7,234896.5 899456.7))', 26986) ) As faceid;
    -- result --
    faceid
    --------
     1

#### See Also

AddEdge, CreateTopology, spatial_ref_sys

ST_Simplify

Returns a "simplified" geometry version of the given TopoGeometry using the Douglas-Peucker algorithm.

    			geometry ST_Simplify
    			TopoGeometry tg
    			float8 tolerance

#### Description

Returns a "simplified" geometry version of the given TopoGeometry using the Douglas-Peucker algorithm on each component edge.

The returned geometry may be non-simple or non-valid.

Splitting component edges may help retaining simplicity/validity.

Performed by the GEOS module.

Availability: 2.1.0

#### See Also

Geometry ST_Simplify, ST_IsSimple, ST_IsValid, ST_ModEdgeSplit

RemoveUnusedPrimitives

Removes topology primitives which not needed to define existing TopoGeometry objects.

    			int RemoveUnusedPrimitives
    			text topology_name
    			geometry bbox

#### Description

Finds all primitives (nodes, edges, faces) that are not strictly needed to represent existing TopoGeometry objects and removes them, maintaining topology validity (edge linking, face labeling) and TopoGeometry space occupation.

No new primitive identifiers are created, but rather existing primitives are expanded to include merged faces (upon removing edges) or healed edges (upon removing nodes).

Availability: 3.3.0

#### See Also

ST_ModEdgeHeal, ST_RemEdgeModFace

## TopoGeometry Constructors

CreateTopoGeom

Creates a new topo geometry object from topo element array - tg_type: 1:[multi]point, 2:[multi]line, 3:[multi]poly, 4:collection

    					topogeometry CreateTopoGeom
    					varchar  toponame
    					integer  tg_type
    					integer layer_id
    					topoelementarray tg_objs

    					topogeometry CreateTopoGeom
    					varchar  toponame
    					integer  tg_type
    					integer layer_id

#### Description

Creates a topogeometry object for layer denoted by `layer_id` and registers it in the relations table in the `toponame` schema.

`tg_type` is an integer: 1:[multi]point (punctal), 2:[multi]line (lineal), 3:[multi]poly (areal), 4:collection. `layer_id` is the layer id in the topology.layer table.

punctal layers are formed from set of nodes, lineal layers are formed from a set of edges, areal layers are formed from a set of faces, and collections can be formed from a mixture of nodes, edges, and faces.

Omitting the array of components generates an empty TopoGeometry object.

Availability: 1.1

#### Examples: Form from existing edges

Create a topogeom in ri_topo schema for layer 2 (our ri_roads), of type (2) LINE, for the first edge (we loaded in `ST_CreateTopoGeo`).

    INSERT INTO ri.ri_roads(road_name, topo) VALUES('Unknown', topology.CreateTopoGeom('ri_topo',2,2,'{{1,2}}'::topology.topoelementarray);

#### Examples: Convert an areal geometry to best guess topogeometry

Lets say we have geometries that should be formed from a collection of faces. We have for example blockgroups table and want to know the topo geometry of each block group. If our data was perfectly aligned, we could do this:

    -- create our topo geometry column --
    SELECT topology.AddTopoGeometryColumn(
    	'topo_boston',
    	'boston', 'blockgroups', 'topo', 'POLYGON');

    -- addtopgeometrycolumn --
    1

    -- update our column assuming
    -- everything is perfectly aligned with our edges
    UPDATE boston.blockgroups AS bg
    	SET topo = topology.CreateTopoGeom('topo_boston'
            ,3,1
            , foo.bfaces)
    FROM (SELECT b.gid,  topology.TopoElementArray_Agg(ARRAY[f.face_id,3]) As bfaces
    	FROM boston.blockgroups As b
                INNER JOIN topo_boston.face As f ON b.geom && f.mbr
            WHERE ST_Covers(b.geom, topology.ST_GetFaceGeometry('topo_boston', f.face_id))
                GROUP BY b.gid) As foo
    WHERE foo.gid = bg.gid;

    --the world is rarely perfect allow for some error
    --count the face if 50% of it falls
    -- within what we think is our blockgroup boundary
    UPDATE boston.blockgroups AS bg
    	SET topo = topology.CreateTopoGeom('topo_boston'
            ,3,1
            , foo.bfaces)
    FROM (SELECT b.gid,  topology.TopoElementArray_Agg(ARRAY[f.face_id,3]) As bfaces
    	FROM boston.blockgroups As b
                INNER JOIN topo_boston.face As f ON b.geom && f.mbr
            WHERE ST_Covers(b.geom, topology.ST_GetFaceGeometry('topo_boston', f.face_id))
    	OR
     (  ST_Intersects(b.geom, topology.ST_GetFaceGeometry('topo_boston', f.face_id))
                AND ST_Area(ST_Intersection(b.geom, topology.ST_GetFaceGeometry('topo_boston', f.face_id) ) ) >
                    ST_Area(topology.ST_GetFaceGeometry('topo_boston', f.face_id))*0.5
                    )
                GROUP BY b.gid) As foo
    WHERE foo.gid = bg.gid;

    -- and if we wanted to convert our topogeometry back
    -- to a denormalized geometry aligned with our faces and edges
    -- cast the topo to a geometry
    -- The really cool thing is my new geometries
    -- are now aligned with my tiger street centerlines
    UPDATE boston.blockgroups SET new_geom = topo::geometry;

#### See Also

AddTopoGeometryColumn, toTopoGeom ST_CreateTopoGeo, ST_GetFaceGeometry, topoelementarray, TopoElementArray_Agg

toTopoGeom

Converts a simple Geometry into a topo geometry.

    					topogeometry toTopoGeom
    					geometry  geom
    					varchar  toponame
    					integer layer_id
    					float8 tolerance

    					topogeometry toTopoGeom
    					geometry  geom
    					topogeometry  topogeom
    					float8 tolerance

#### Description

Converts a simple Geometry into a topogeometry.

Topological primitives required to represent the input geometry will be added to the underlying topology, possibly splitting existing ones, and they will be associated with the output TopoGeometry in the `relation` table.

Existing TopoGeometry objects (with the possible exception of `topogeom`, if given) will retain their shapes.

When `tolerance` is given it will be used to snap the input geometry to existing primitives.

In the first form a new TopoGeometry will be created for the given layer (`layer_id`) of the given topology (`toponame`).

In the second form the primitives resulting from the conversion will be added to the pre-existing TopoGeometry (`topogeom`), possibly adding space to its final shape. To have the new shape completely replace the old one see clearTopoGeom.

Availability: 2.0

Enhanced: 2.1.0 adds the version taking an existing TopoGeometry.

#### Examples

This is a full self-contained workflow

     -- do this if you don't have a topology setup already
    -- creates topology not allowing any tolerance
    SELECT topology.CreateTopology('topo_boston_test', 2249);
    -- create a new table
    CREATE TABLE nei_topo(gid serial primary key, nei varchar(30));
    --add a topogeometry column to it
    SELECT topology.AddTopoGeometryColumn('topo_boston_test', 'public', 'nei_topo', 'topo', 'MULTIPOLYGON') As new_layer_id;
    new_layer_id
    -----------
    1

    --use new layer id in populating the new topogeometry column
    -- we add the topogeoms to the new layer with 0 tolerance
    INSERT INTO nei_topo(nei, topo)
    SELECT nei,  topology.toTopoGeom(geom, 'topo_boston_test', 1)
    FROM neighborhoods
    WHERE gid BETWEEN 1 and 15;

    --use to verify what has happened --
    SELECT * FROM
        topology.TopologySummary('topo_boston_test');

    -- summary--
    Topology topo_boston_test (5), SRID 2249, precision 0
    61 nodes, 87 edges, 35 faces, 15 topogeoms in 1 layers
    Layer 1, type Polygonal (3), 15 topogeoms
     Deploy: public.nei_topo.topo

    -- Shrink all TopoGeometry polygons by 10 meters
    UPDATE nei_topo SET topo = ST_Buffer(clearTopoGeom(topo), -10);

    -- Get the no-one-lands left by the above operation
    -- I think GRASS calls this "polygon0 layer"
    SELECT ST_GetFaceGeometry('topo_boston_test', f.face_id)
      FROM topo_boston_test.face f
      WHERE f.face_id > 0 -- don't consider the universe face
      AND NOT EXISTS ( -- check that no TopoGeometry references the face
        SELECT * FROM topo_boston_test.relation
        WHERE layer_id = 1 AND element_id = f.face_id
      );

#### See Also

CreateTopology, AddTopoGeometryColumn, CreateTopoGeom, TopologySummary, clearTopoGeom

TopoElementArray_Agg

Returns a `topoelementarray` for a set of element_id, type arrays (topoelements).

                    topoelementarray TopoElementArray_Agg
                    topoelement set tefield

#### Description

Used to create a topoelementarray from a set of topoelement.

Availability: 2.0.0

#### Examples

    SELECT topology.TopoElementArray_Agg(ARRAY[e,t]) As tea
      FROM generate_series(1,3) As e CROSS JOIN generate_series(1,4) As t;
      tea
    --------------------------------------------------------------------------
    {{1,1},{1,2},{1,3},{1,4},{2,1},{2,2},{2,3},{2,4},{3,1},{3,2},{3,3},{3,4}}

#### See Also

topoelement, topoelementarray

TopoElement

Converts a topogeometry to a topoelement.

    					topoelement TopoElement
    					topogeometry  topo

#### Description

Converts a topogeometry to a topoelement.

Availability: 3.4.0

#### Examples

This is a full self-contained workflow

    -- do this if you don't have a topology setup already
    -- Creates topology not allowing any tolerance
    SELECT TopoElement(topo)
    FROM neighborhoods;

    -- using as cast
    SELECT topology.TopoElementArray_Agg(topo::topoelement)
    FROM neighborhoods
    GROUP BY city;

#### See Also

TopoElementArray_Agg, topogeometry, topoelement

## TopoGeometry Editors

clearTopoGeom

Clears the content of a topo geometry.

    					topogeometry clearTopoGeom
    					topogeometry  topogeom

#### Description

Clears the content a topogeometry turning it into an empty one. Mostly useful in conjunction with toTopoGeom to replace the shape of existing objects and any dependent object in higher hierarchical levels.

Availability: 2.1

#### Examples

    -- Shrink all TopoGeometry polygons by 10 meters
    UPDATE nei_topo SET topo = ST_Buffer(clearTopoGeom(topo), -10);

#### See Also

toTopoGeom

TopoGeom_addElement

Adds an element to the definition of a TopoGeometry.

    					topogeometry TopoGeom_addElement
    					topogeometry  tg
              topoelement  el

#### Description

Adds a topoelement to the definition of a TopoGeometry object. Does not error out if the element is already part of the definition.

Availability: 2.3

#### Examples

    -- Add edge 5 to TopoGeometry tg
    UPDATE mylayer SET tg = TopoGeom_addElement(tg, '{5,2}');

#### See Also

TopoGeom_remElement, CreateTopoGeom

TopoGeom_remElement

Removes an element from the definition of a TopoGeometry.

    					topogeometry TopoGeom_remElement
    					topogeometry  tg
              topoelement  el

#### Description

Removes a topoelement from the definition of a TopoGeometry object.

Availability: 2.3

#### Examples

    -- Remove face 43 from TopoGeometry tg
    UPDATE mylayer SET tg = TopoGeom_remElement(tg, '{43,3}');

#### See Also

TopoGeom_addElement, CreateTopoGeom

TopoGeom_addTopoGeom

Adds element of a TopoGeometry to the definition of another TopoGeometry.

    					topogeometry TopoGeom_addTopoGeom
    					topogeometry  tgt
                        topogeometry  src

#### Description

Adds the elements of a topogeometry to the definition of another TopoGeometry, possibly changing its cached type (type attribute) to a collection, if needed to hold all elements in the source object.

The two TopoGeometry objects need be defined against the *same* topology and, if hierarchically defined, need be composed by elements of the same child layer.

Availability: 3.2

#### Examples

    -- Set an "overall" TopoGeometry value to be composed by all
    -- elements of specific TopoGeometry values
    UPDATE mylayer SET tg_overall = TopoGeom_addTopogeom(
        TopoGeom_addTopoGeom(
            clearTopoGeom(tg_overall),
            tg_specific1
        ),
        tg_specific2
    );

#### See Also

TopoGeom_addElement, clearTopoGeom, CreateTopoGeom

toTopoGeom

Adds a geometry shape to an existing topo geometry.

#### Description

Refer to toTopoGeom.

## TopoGeometry Accessors

GetTopoGeomElementArray

Returns a `topoelementarray` (an array of topoelements) containing the topological elements and type of the given TopoGeometry (primitive elements).

    					topoelementarray GetTopoGeomElementArray
    					varchar  toponame
    					integer  layer_id
    					integer tg_id

    					topoelementarray GetTopoGeomElementArray
    					topogeometry  tg

#### Description

Returns a topoelementarray containing the topological elements and type of the given TopoGeometry (primitive elements). This is similar to GetTopoGeomElements except it returns the elements as an array rather than as a dataset.

tg_id is the topogeometry id of the topogeometry object in the topology in the layer denoted by `layer_id` in the topology.layer table.

Availability: 1.1

#### Examples

#### See Also

GetTopoGeomElements, topoelementarray

GetTopoGeomElements

Returns a set of `topoelement` objects containing the topological element_id,element_type of the given TopoGeometry (primitive elements).

    					setof topoelement GetTopoGeomElements
    					varchar  toponame
    					integer  layer_id
    					integer tg_id

    					setof topoelement GetTopoGeomElements
    					topogeometry  tg

#### Description

Returns a set of element_id,element_type (topoelements) corresponding to primitive topology elements topoelement (1: nodes, 2: edges, 3: faces) that a given topogeometry object in `toponame` schema is composed of.

tg_id is the topogeometry id of the topogeometry object in the topology in the layer denoted by `layer_id` in the topology.layer table.

Availability: 2.0.0

#### Examples

#### See Also

GetTopoGeomElementArray, topoelement, TopoGeom_addElement, TopoGeom_remElement

ST_SRID

Returns the spatial reference identifier for a topogeometry.

    			integer ST_SRID
    			topogeometry  tg

#### Description

Returns the spatial reference identifier for the ST_Geometry as defined in spatial_ref_sys table. spatial_ref_sys

spatial_ref_sys table is a table that catalogs all spatial reference systems known to PostGIS and is used for transformations from one spatial reference system to another. So verifying you have the right spatial reference system identifier is important if you plan to ever transform your geometries.

Availability: 3.2.0

&sqlmm_compliant; SQL-MM 3: 14.1.5

#### Examples

    SELECT ST_SRID(ST_GeomFromText('POINT(-71.1043 42.315)',4326));
    		--result
    		4326

#### See Also

spatial_ref_sys, ST_SetSRID, ST_Transform, ST_SRID

## TopoGeometry Outputs

AsGML

Returns the GML representation of a topogeometry.

                            text AsGML
                            topogeometry  tg

                            text AsGML
                            topogeometry  tg
                            text  nsprefix_in

                            text AsGML
                            topogeometry  tg
                            regclass  visitedTable

                            text AsGML
                            topogeometry  tg
                            regclass  visitedTable
                            text  nsprefix

                            text AsGML
                            topogeometry  tg
                            text  nsprefix_in
                            integer  precision
                            integer  options

                            text AsGML
                            topogeometry  tg
                            text  nsprefix_in
                            integer  precision
                            integer  options
                            regclass  visitedTable

                            text AsGML
                            topogeometry  tg
                            text  nsprefix_in
                            integer  precision
                            integer  options
                            regclass  visitedTable
                            text  idprefix

                            text AsGML
                            topogeometry  tg
                            text  nsprefix_in
                            integer  precision
                            integer  options
                            regclass  visitedTable
                            text  idprefix
                            int  gmlversion

#### Description

Returns the GML representation of a topogeometry in version GML3 format. If no `nsprefix_in` is specified then `gml` is used. Pass in an empty string for nsprefix to get a non-qualified name space. The precision (default: 15) and options (default 1) parameters, if given, are passed untouched to the underlying call to ST_AsGML.

The `visitedTable` parameter, if given, is used for keeping track of the visited Node and Edge elements so to use cross-references (xlink:xref) rather than duplicating definitions. The table is expected to have (at least) two integer fields: 'element_type' and 'element_id'. The calling user must have both read and write privileges on the given table. For best performance, an index should be defined on `element_type` and `element_id`, in that order. Such index would be created automatically by adding a unique constraint to the fields. Example:

    CREATE TABLE visited (
      element_type integer, element_id integer,
      unique(element_type, element_id)
    );

The `idprefix` parameter, if given, will be prepended to Edge and Node tag identifiers.

The `gmlver` parameter, if given, will be passed to the underlying ST_AsGML. Defaults to 3.

Availability: 2.0.0

#### Examples

This uses the topo geometry we created in CreateTopoGeom

    SELECT topology.AsGML(topo) As rdgml
      FROM ri.roads
      WHERE road_name = 'Unknown';

    -- rdgml--
    <gml:TopoCurve>
        <gml:directedEdge>
            <gml:Edge gml:id="E1">
                <gml:directedNode orientation="-">
                    <gml:Node gml:id="N1"/>
                </gml:directedNode>
                <gml:directedNode></gml:directedNode>
                <gml:curveProperty>
                    <gml:Curve srsName="urn:ogc:def:crs:EPSG::3438">
                        <gml:segments>
                            <gml:LineStringSegment>
                                <gml:posList srsDimension="2">384744 236928 384750 236923 384769 236911 384799 236895 384811 236890
                                384833 236884 384844 236882 384866 236881 384879 236883 384954 236898 385087 236932 385117 236938
                                385167 236938 385203 236941 385224 236946 385233 236950 385241 236956 385254 236971
                                385260 236979 385268 236999 385273 237018 385273 237037 385271 237047 385267 237057 385225 237125
                                385210 237144 385192 237161 385167 237192 385162 237202 385159 237214 385159 237227 385162 237241
                                385166 237256 385196 237324 385209 237345 385234 237375 385237 237383 385238 237399 385236 237407
                                385227 237419 385213 237430 385193 237439 385174 237451 385170 237455 385169 237460 385171 237475
                                385181 237503 385190 237521 385200 237533 385206 237538 385213 237541 385221 237542 385235 237540 385242 237541
                                385249 237544 385260 237555 385270 237570 385289 237584 385292 237589 385291 237596 385284 237630</gml:posList>
                            </gml:LineStringSegment>
                        </gml:segments>
                    </gml:Curve>
                </gml:curveProperty>
            </gml:Edge>
        </gml:directedEdge>
    </gml:TopoCurve>

Same exercise as previous without namespace

    SELECT topology.AsGML(topo,'') As rdgml
      FROM ri.roads
      WHERE road_name = 'Unknown';

    -- rdgml--
    <TopoCurve>
        <directedEdge>
            <Edge id="E1">
                <directedNode orientation="-">
                    <Node id="N1"/>
                </directedNode>
                <directedNode></directedNode>
                <curveProperty>
                    <Curve srsName="urn:ogc:def:crs:EPSG::3438">
                        <segments>
                            <LineStringSegment>
                                <posList srsDimension="2">384744 236928 384750 236923 384769 236911 384799 236895 384811 236890
                                384833 236884 384844 236882 384866 236881 384879 236883 384954 236898 385087 236932 385117 236938
                                385167 236938 385203 236941 385224 236946 385233 236950 385241 236956 385254 236971
                                385260 236979 385268 236999 385273 237018 385273 237037 385271 237047 385267 237057 385225 237125
                                385210 237144 385192 237161 385167 237192 385162 237202 385159 237214 385159 237227 385162 237241
                                385166 237256 385196 237324 385209 237345 385234 237375 385237 237383 385238 237399 385236 237407
                                385227 237419 385213 237430 385193 237439 385174 237451 385170 237455 385169 237460 385171 237475
                                385181 237503 385190 237521 385200 237533 385206 237538 385213 237541 385221 237542 385235 237540 385242 237541
                                385249 237544 385260 237555 385270 237570 385289 237584 385292 237589 385291 237596 385284 237630</posList>
                             </LineStringSegment>
                        </segments>
                    </Curve>
                </curveProperty>
            </Edge>
        </directedEdge>
    </TopoCurve>

#### See Also

CreateTopoGeom, ST_CreateTopoGeo

AsTopoJSON

Returns the TopoJSON representation of a topogeometry.

                            text AsTopoJSON
                            topogeometry  tg
                            regclass  edgeMapTable

#### Description

Returns the TopoJSON representation of a topogeometry. If `edgeMapTable` is not null, it will be used as a lookup/storage mapping of edge identifiers to arc indices. This is to be able to allow for a compact "arcs" array in the final document.

The table, if given, is expected to have an "arc_id" field of type "serial" and an "edge_id" of type integer; the code will query the table for "edge_id" so it is recommended to add an index on that field.

Arc indices in the TopoJSON output are 0-based but they are 1-based in the "edgeMapTable" table.

A full TopoJSON document will be need to contain, in addition to the snippets returned by this function, the actual arcs plus some headers. See the TopoJSON specification.

Availability: 2.1.0

Enhanced: 2.2.1 added support for puntal inputs

#### See Also

ST_AsGeoJSON

#### Examples

    CREATE TEMP TABLE edgemap(arc_id serial, edge_id int unique);

    -- header
    SELECT '{ "type": "Topology", "transform": { "scale": [1,1], "translate": [0,0] }, "objects": {'

    -- objects
    UNION ALL SELECT '"' || feature_name || '": ' || AsTopoJSON(feature, 'edgemap')
    FROM features.big_parcels WHERE feature_name = 'P3P4';

    -- arcs
    WITH edges AS (
      SELECT m.arc_id, e.geom FROM edgemap m, city_data.edge e
      WHERE e.edge_id = m.edge_id
    ), points AS (
      SELECT arc_id, (st_dumppoints(geom)).* FROM edges
    ), compare AS (
      SELECT p2.arc_id,
             CASE WHEN p1.path IS NULL THEN p2.geom
                  ELSE ST_Translate(p2.geom, -ST_X(p1.geom), -ST_Y(p1.geom))
             END AS geom
      FROM points p2 LEFT OUTER JOIN points p1
      ON ( p1.arc_id = p2.arc_id AND p2.path[1] = p1.path[1]+1 )
      ORDER BY arc_id, p2.path
    ), arcsdump AS (
      SELECT arc_id, (regexp_matches( ST_AsGeoJSON(geom), '\[.*\]'))[1] as t
      FROM compare
    ), arcs AS (
      SELECT arc_id, '[' || array_to_string(array_agg(t), ',') || ']' as a FROM arcsdump
      GROUP BY arc_id
      ORDER BY arc_id
    )
    SELECT '}, "arcs": [' UNION ALL
    SELECT array_to_string(array_agg(a), E',\n') from arcs

    -- footer
    UNION ALL SELECT ']}'::text as t;

    -- Result:
    { "type": "Topology", "transform": { "scale": [1,1], "translate": [0,0] }, "objects": {
    "P3P4": { "type": "MultiPolygon", "arcs": [[[-1]],[[6,5,-5,-4,-3,1]]]}
    }, "arcs": [
     [[25,30],[6,0],[0,10],[-14,0],[0,-10],[8,0]],
     [[35,6],[0,8]],
     [[35,6],[12,0]],
     [[47,6],[0,8]],
     [[47,14],[0,8]],
     [[35,22],[12,0]],
     [[35,14],[0,8]]
     ]}

## Topology Spatial Relationships

Equals

Returns true if two topogeometries are composed of the same topology primitives.

                  boolean Equals
                  topogeometry  tg1
                  topogeometry  tg2

#### Description

Returns true if two topogeometries are composed of the same topology primitives: faces, edges, nodes.

This function not supported for topogeometries that are geometry collections. It also can not compare topogeometries from different topologies.

Availability: 1.1.0

&Z_support;

#### Examples

#### See Also

GetTopoGeomElements, ST_Equals

Intersects

Returns true if any pair of primitives from the two topogeometries intersect.

                  boolean Intersects
                  topogeometry  tg1
                  topogeometry  tg2

#### Description

Returns true if any pair of primitives from the two topogeometries intersect.

This function not supported for topogeometries that are geometry collections. It also can not compare topogeometries from different topologies. Also not currently supported for hierarchical topogeometries (topogeometries composed of other topogeometries).

Availability: 1.1.0

&Z_support;

#### Examples

#### See Also

ST_Intersects

## Importing and exporting Topologies

Once you have created topologies, and maybe associated topological layers, you might want to export them into a file-based format for backup or transfer into another database.

Using the standard dump/restore tools of PostgreSQL is problematic because topologies are composed by a set of tables (4 for primitives, an arbitrary number for layers) and records in metadata tables (topology.topology and topology.layer). Additionally, topology identifiers are not univoque across databases so that parameter of your topology will need to be changes upon restoring it.

In order to simplify export/restore of topologies a pair of executables are provided: `pgtopo_export` and `pgtopo_import`. Example usage:

    pgtopo_export dev_db topo1 | pgtopo_import topo1 | psql staging_db

### Using the Topology exporter

The `pgtopo_export` script takes the name of a database and a topology and outputs a dump file which can be used to import the topology (and associated layers) into a new database.

By default `pgtopo_export` writes the dump file to the standard output so that it can be piped to `pgtopo_import` or redirected to a file (refusing to write to terminal). You can optionally specify an output filename with the `-f` commandline switch.

By default `pgtopo_export` includes a dump of all layers defined against the given topology. This may be more data than you need, or may be non-working (in case your layer tables have complex dependencies) in which case you can request skipping the layers with the `--skip-layers` switch and deal with those separately.

Invoking `pgtopo_export` with the `--help` (or `-h` for short) switch will always print short usage string.

The dump file format is a compressed tar archive of a `pgtopo_export` directory containing at least a `pgtopo_dump_version` file with format version info. As of version `1` the directory contains tab-delimited CSV files with data of the topology primitive tables (node, edge_data, face, relation), the topology and layer records associated with it and (unless `--skip-layers` is given) a custom-format PostgreSQL dump of tables reported as being layers of the given topology.

### Using the Topology importer

The `pgtopo_import` script takes a `pgtopo_export` format topology dump and a name to give to the topology to be created and outputs an SQL script reconstructing the topology and associated layers.

The generated SQL file will contain statements that create a topology with the given name, load primitive data in it, restores and registers all topology layers by properly linking all TopoGeometry values to their correct topology.

By default `pgtopo_import` reads the dump from the standard input so that it can be used in conjunction with `pgtopo_export` in a pipeline. You can optionally specify an input filename with the `-f` commandline switch.

By default `pgtopo_import` includes in the output SQL file the code to restore all layers found in the dump.

This may be unwanted or non-working in case your target database already have tables with the same name as the ones in the dump. In that case you can request skipping the layers with the `--skip-layers` switch and deal with those separately (or later).

SQL to only load and link layers to a named topology can be generated using the `--only-layers` switch. This can be useful to load layers AFTER resolving the naming conflicts or to link layers to a different topology (say a spatially-simplified version of the starting topology).