### Final Setup and Commit Source: https://github.com/cgx-group/libspatialite/blob/master/src/srsinit/epsg_update/README.txt Copies generated C files to the parent directory, updates the repository, Makefile.am, and commits the changes. ```bash # rm ../epsg_inlined*.c # cp epsg_inlined*.c .. # be sure to update as required the repository (ADD/DEL) # be sure to update as required Makefile.am # and finally commit into the repository ``` -------------------------------- ### Enumerate Spatial Layers and Get Extents (C) Source: https://context7.com/cgx-group/libspatialite/llms.txt Demonstrates how to list all vector layers in a database, retrieve their metadata, and get the bounding box of a specific layer. Requires inclusion of sqlite3.h, spatialite.h, and spatialite/gaiageo.h. ```c #include #include #include void vector_layers_example(sqlite3 *db) { /* Get list of all vector layers (optimistic = use cached stats) */ gaiaVectorLayersListPtr list = gaiaGetVectorLayersList(db, NULL, NULL, GAIA_VECTORS_LIST_OPTIMISTIC); if (!list) { printf("No layers found\n"); return; } gaiaVectorLayerPtr lyr = list->First; while (lyr) { printf("Layer: %-20s geom_type=%-16s rows=%d\n", lyr->TableName, (lyr->GeometryType == GAIA_VECTOR_POLYGON) ? "POLYGON" : (lyr->GeometryType == GAIA_VECTOR_POINT) ? "POINT" : "OTHER", lyr->RowCount); lyr = lyr->Next; } gaiaFreeVectorLayersList(list); /* Get bounding box of a specific layer */ gaiaGeomCollPtr extent = gaiaGetLayerExtent(db, "airports", "geom", 0 /* optimistic */); if (extent) { double min_x, min_y, max_x, max_y; gaiaGetMbrMinX(extent, &min_x); gaiaGetMbrMinY(extent, &min_y); gaiaGetMbrMaxX(extent, &max_x); gaiaGetMbrMaxY(extent, &max_y); printf("Extent: (%.4f, %.4f) -> (%.4f, %.4f)\n", min_x, min_y, max_x, max_y); gaiaFreeGeomColl(extent); } } ``` -------------------------------- ### Initialize and Shutdown Libspatialite Globally Source: https://context7.com/cgx-group/libspatialite/llms.txt Call `spatialite_initialize` once at program start and `spatialite_shutdown` once at program exit to manage the global SpatiaLite library lifecycle. This example also shows how to retrieve the SpatiaLite version and target CPU. ```c #include #include int main(void) { /* Call once at program start */ spatialite_initialize(); printf("SpatiaLite version: %s\n", spatialite_version()); printf("Target CPU: %s\n", spatialite_target_cpu()); /* ... application work ... */ /* Call once at program exit */ spatialite_shutdown(); return 0; } /* Expected output: SpatiaLite version: 5.1.0 Target CPU: x86_64-pc-linux-gnu */ ``` -------------------------------- ### Network Routing Setup Source: https://context7.com/cgx-group/libspatialite/llms.txt Function to create a VirtualRouting table for network analysis. ```APIDOC ## `gaia_create_routing` ### Description Build a VirtualRouting table from a linestring road network table, enabling shortest-path (Dijkstra / A*) queries via SQL. ### Parameters - `db` (sqlite3 *): Pointer to the SQLite database connection. - `cache` (void *): Pointer to the spatialite cache. - `routing_data_table` (const char *): Name of the routing data table to create. - `virtual_routing_table` (const char *): Name of the virtual routing table to create. - `input_linestring_table` (const char *): Name of the input linestring table (road network). - `node_from_column` (const char *): Name of the column representing the 'from' node. - `node_to_column` (const char *): Name of the column representing the 'to' node. - `geometry_column` (const char *): Name of the geometry column (used for A*). - `cost_column` (const char *): Name of the column representing the cost (e.g., length). - `name_column` (const char *): Name of the column for the road name. - `enable_astar` (int): Flag to enable A* algorithm (1 for true, 0 for false). - `bidirectional_arcs` (int): Flag to enable bidirectional arcs (1 for true, 0 for false). - `oneway_column` (const char *): Name of the column indicating one-way status (NULL if not applicable). - `oneway_value` (const char *): Value in the `oneway_column` that indicates a one-way road (NULL if not applicable). - `overwrite_if_exists` (int): Flag to overwrite existing tables if they exist (1 for true, 0 for false). ### Returns - `int`: 1 on success, 0 on failure. ### Error Handling - `gaia_create_routing_get_last_error(cache)`: Retrieves the last error message if `gaia_create_routing` fails. ### Example Usage ```c #include #include void routing_example(sqlite3 *db, void *cache) { /* Create routing data and virtual routing table from a roads layer. The roads table must have NodeFrom and NodeTo integer columns. */ int ok = gaia_create_routing(db, cache, "roads_routing_data", /* routing data table to create */ "roads_routing", /* virtual routing table */ "roads", /* input linestring table */ "node_from", /* from-node column */ "node_to", /* to-node column */ "geom", /* geometry column (for A*) */ "cost", /* cost column (length) */ "road_name", /* name column */ 1, /* enable A* algorithm */ 1, /* bidirectional arcs */ NULL, NULL, /* no one-way columns */ 1 /* overwrite if exists */ ); if (!ok) { const char *last_err = gaia_create_routing_get_last_error(cache); fprintf(stderr, "Routing setup error: %s\n", last_err); return; } /* Query: shortest path from node 100 to node 500 */ sqlite3_stmt *stmt; sqlite3_prepare_v2(db, "SELECT Algorithm, ArcRowid, Name, Cost, Geometry " "FROM roads_routing " "WHERE NodeFrom = 100 AND NodeTo = 500", -1, &stmt, NULL); double total_cost = 0.0; while (sqlite3_step(stmt) == SQLITE_ROW) { printf("Arc: %-20s cost=%.2f\n", sqlite3_column_text(stmt, 2), sqlite3_column_double(stmt, 3)); total_cost += sqlite3_column_double(stmt, 3); } printf("Total route cost: %.2f\n", total_cost); sqlite3_finalize(stmt); } ``` ``` -------------------------------- ### Create Network Routing Table (C) Source: https://context7.com/cgx-group/libspatialite/llms.txt Builds a virtual routing table from a linestring road network for shortest-path queries using Dijkstra or A*. Requires the input road table to have NodeFrom and NodeTo integer columns. Includes setup and a sample shortest path query. ```c #include #include void routing_example(sqlite3 *db, void *cache) { /* Create routing data and virtual routing table from a roads layer. The roads table must have NodeFrom and NodeTo integer columns. */ int ok = gaia_create_routing(db, cache, "roads_routing_data", /* routing data table to create */ "roads_routing", /* virtual routing table */ "roads", /* input linestring table */ "node_from", /* from-node column */ "node_to", /* to-node column */ "geom", /* geometry column (for A*) */ "cost", /* cost column (length) */ "road_name", /* name column */ 1, /* enable A* algorithm */ 1, /* bidirectional arcs */ NULL, NULL, /* no one-way columns */ 1 /* overwrite if exists */ ); if (!ok) { const char *last_err = gaia_create_routing_get_last_error(cache); fprintf(stderr, "Routing setup error: %s\n", last_err); return; } /* Query: shortest path from node 100 to node 500 */ sqlite3_stmt *stmt; sqlite3_prepare_v2(db, "SELECT Algorithm, ArcRowid, Name, Cost, Geometry " "FROM roads_routing " "WHERE NodeFrom = 100 AND NodeTo = 500", -1, &stmt, NULL); double total_cost = 0.0; while (sqlite3_step(stmt) == SQLITE_ROW) { printf("Arc: %-20s cost=%.2f\n", sqlite3_column_text(stmt, 2), sqlite3_column_double(stmt, 3)); total_cost += sqlite3_column_double(stmt, 3); } printf("Total route cost: %.2f\n", total_cost); sqlite3_finalize(stmt); } ``` -------------------------------- ### Initialize Spatial Metadata with SQL Functions Source: https://context7.com/cgx-group/libspatialite/llms.txt The `InitSpatialMetadata(1)` SQL function initializes required spatial metadata tables and populates the EPSG reference system dataset. This example demonstrates its usage along with `AddGeometryColumn` and `CreateSpatialIndex` to set up a table for spatial data. ```c #include #include static int init_new_db(sqlite3 *db) { char *err_msg = NULL; int rc; /* InitSpatialMetadata(1) — the integer arg requests EPSG population */ rc = sqlite3_exec(db, "SELECT InitSpatialMetadata(1)", NULL, NULL, &err_msg); if (rc != SQLITE_OK) { fprintf(stderr, "InitSpatialMetadata error: %s\n", err_msg); sqlite3_free(err_msg); return 0; } /* Create a plain table */ rc = sqlite3_exec(db, "CREATE TABLE airports (pk INTEGER PRIMARY KEY, name TEXT)", NULL, NULL, &err_msg); if (rc != SQLITE_OK) { sqlite3_free(err_msg); return 0; } /* Add a geometry column (SRID 4326 = WGS84 lon/lat, POINT, 2D) */ rc = sqlite3_exec(db, "SELECT AddGeometryColumn('airports', 'geom', 4326, 'POINT', 2)", NULL, NULL, &err_msg); if (rc != SQLITE_OK) { sqlite3_free(err_msg); return 0; } /* Create an R*Tree spatial index */ rc = sqlite3_exec(db, "SELECT CreateSpatialIndex('airports', 'geom')", NULL, NULL, &err_msg); if (rc != SQLITE_OK) { sqlite3_free(err_msg); return 0; } return 1; /* success */ } ``` -------------------------------- ### TopoGeo_InitTopoLayer (Partial Initialization) Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Initializes a partially defined new TopoLayer starting from a reference plain Table or View. Similar to the full initialization, it handles NULL database prefixes. ```APIDOC ## TopoGeo_InitTopoLayer (Partial Initialization) ### Description Initializes a partially defined new TopoLayer starting from a reference plain Table or View. ### Parameters - **toponame** (Text) - The name of the topology. - **db-prefix** (Text) - Optional. The prefix for the database. If NULL, the reference Table or View is in the "MAIN" database. - **ref-table-name** (Text) - The name of the reference Table or View. - **topolayer-name** (Text) - The name of the TopoLayer to be created. ### Returns - **Integer** - 1 on success, raises an exception on failure. ``` -------------------------------- ### Run Post-Build Test Script Source: https://github.com/cgx-group/libspatialite/blob/master/src/srsinit/epsg_update/README-PROJ6.txt After building and installing the new libspatialite, run the 'check_srid_spatialite.sh' test script to verify the updated SRS data. Carefully review any detected errors. ```bash ./check_srid_spatialite.sh ``` -------------------------------- ### Replace the Start Point of a LineString Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Use SetStartPoint or ST_SetStartPoint to create a new LineString with its starting point replaced. Returns NULL on error. ```SQL SetStartPoint( line _LineString_ , point _Point_ ) : _Linestring_ ``` ```SQL ST_SetStartPoint( line _LineString_ , point _Point_ ) : _Linestring_ ``` -------------------------------- ### Full Round-Trip with Libspatialite in C Source: https://context7.com/cgx-group/libspatialite/llms.txt This C code demonstrates a complete workflow: initializing libspatialite, opening an in-memory database, setting up spatial metadata, creating a table with a geometry column and spatial index, inserting point data using prepared statements and the C geometry API, performing a spatial query using MBR (Minimum Bounding Rectangle) and spatial index, and finally cleaning up resources. Compile with: gcc app.c -o app -lspatialite -lsqlite3. ```c #include #include #include #include #include #include int main(void) { sqlite3 *db; void *cache; char *err_msg = NULL; sqlite3_stmt *stmt; int rc; /* 1. Global init */ spatialite_initialize(); /* 2. Open in-memory database */ sqlite3_open_v2(":memory:", &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL); cache = spatialite_alloc_connection(); spatialite_init_ex(db, cache, 0); /* 3. Bootstrap spatial metadata */ sqlite3_exec(db, "SELECT InitSpatialMetadata(1)", NULL, NULL, &err_msg); if (err_msg) { fprintf(stderr, "%s\n", err_msg); sqlite3_free(err_msg); } /* 4. Create table + geometry column + spatial index */ sqlite3_exec(db, "CREATE TABLE cities (id INTEGER PRIMARY KEY, name TEXT)", NULL, NULL, NULL); sqlite3_exec(db, "SELECT AddGeometryColumn('cities','geom',4326,'POINT',2)", NULL, NULL, NULL); sqlite3_exec(db, "SELECT CreateSpatialIndex('cities','geom')", NULL, NULL, NULL); /* 5. Insert cities using prepared statement inside a transaction */ sqlite3_exec(db, "BEGIN", NULL, NULL, NULL); sqlite3_prepare_v2(db, "INSERT INTO cities(id,name,geom) VALUES(?,?,?)", -1, &stmt, NULL); struct { int id; const char *name; double lon, lat; } data[] = { {1, "Rome", 12.4924, 41.8902}, {2, "Paris", 2.3488, 48.8534}, {3, "Berlin", 13.4036, 52.5200}, {4, "Madrid", -3.7038, 40.4168}, }; for (int i = 0; i < 4; i++) { unsigned char *blob; int blob_size; gaiaGeomCollPtr g = gaiaAllocGeomColl(); g->Srid = 4326; gaiaAddPointToGeomColl(g, data[i].lon, data[i].lat); gaiaToSpatiaLiteBlobWkb(g, &blob, &blob_size); gaiaFreeGeomColl(g); sqlite3_reset(stmt); sqlite3_bind_int(stmt, 1, data[i].id); sqlite3_bind_text(stmt, 2, data[i].name, -1, SQLITE_STATIC); sqlite3_bind_blob(stmt, 3, blob, blob_size, free); sqlite3_step(stmt); } sqlite3_finalize(stmt); sqlite3_exec(db, "COMMIT", NULL, NULL, NULL); /* 6. Spatial query: cities within a bounding box (Europe) */ rc = sqlite3_prepare_v2(db, "SELECT name, AsText(geom) FROM cities " "WHERE MbrWithin(geom, BuildMbr(-10,35,30,60)) " " AND ROWID IN (" " SELECT pkid FROM idx_cities_geom " " WHERE xmin > -10 AND xmax < 30 " " AND ymin > 35 AND ymax < 60" " )" "ORDER BY name", -1, &stmt, NULL); printf("Cities in Europe (lon -10..30, lat 35..60):\n"); while (sqlite3_step(stmt) == SQLITE_ROW) { printf(" %-10s %s\n", sqlite3_column_text(stmt, 0), sqlite3_column_text(stmt, 1)); } /* Expected: Berlin POINT(13.4036 52.52) Madrid POINT(-3.7038 40.4168) Paris POINT(2.3488 48.8534) Rome POINT(12.4924 41.8902) */ sqlite3_finalize(stmt); /* 7. Cleanup */ sqlite3_close(db); spatialite_cleanup_ex(cache); spatialite_shutdown(); return 0; } /* Compile: gcc app.c -o app -lspatialite -lsqlite3 */ ``` -------------------------------- ### Initialize and Run Coverage Tests Source: https://github.com/cgx-group/libspatialite/blob/master/test/WritingSQLTestCase.txt After configuring and building, initialize coverage numbers, build tests, and generate the coverage summary. This process helps identify untested code. ```bash make coverage-init make check make coverage ``` -------------------------------- ### Project Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Projects a new point from a starting point using a given distance and azimuth (bearing). Assumes long/lat for the start point and meters for distance. Returns NULL on failure or invalid arguments. ```APIDOC ## Project ### Description Returns a new Point projected from a start point using a bearing and distance. **start_point** is expected to be a simple long/lat Point. **distance** is expected to be measured in meters; **azimuth** (aka bearing or heading) has the same identical meaning as in **ST_Azimuth()**. NULL is returned on failure or on invalid arguments. ### Syntax ```sql Project( start_point _Geometry_, distance _Double precision_, azimuth _Double precision_ ) : _Geometry_ ST_Project( start_point _Geometry_, distance _Double precision_, azimuth _Double precision_ ) : _Geometry_ ``` ### Module RTTOPO ``` -------------------------------- ### Configure libspatialite for Coverage Testing Source: https://github.com/cgx-group/libspatialite/blob/master/test/WritingSQLTestCase.txt Run configure with the --enable-gcov=yes option to enable coverage testing. Other configuration options can be included as needed. ```bash make distclean ./configure --enable-gcov=yes make check ``` -------------------------------- ### StartPoint Function Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Retrieves the starting point of a Curve geometry. ```APIDOC ## StartPoint ### Description Returns a Point containing the first Point of the input Curve. ### Syntax - `StartPoint(c Curve) : Point` - `ST_StartPoint(c Curve) : Point` ``` -------------------------------- ### SetStartPoint / ST_SetStartPoint Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Creates a new LineString by replacing its starting point. ```APIDOC ## SetStartPoint / ST_SetStartPoint ### Description Returns a new Linestring by replacing its StartPoint. NULL will be returned if any error is encountered. ### Syntax SetStartPoint( line _LineString_ , point _Point_ ) : _Linestring_ ST_SetStartPoint( line _LineString_ , point _Point_ ) : _Linestring_ ``` -------------------------------- ### AutoGPKGStart Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Automatically creates or refreshes VirtualGPKG wrappers for each GeoPackage geometry table in the specified database. ```APIDOC ## AutoGPKGStart ### Description Inspects the database layout and automatically creates or refreshes a `VirtualGPKG` wrapper for each GeoPackage geometry table. An optional `db_prefix` can be provided to target specific attached databases. ### Syntax AutoGPKGStart( void ) : _Integer_ AutoGPKGStart( db_prefix _String_ ) : _Integer_ ### Parameters * **db_prefix** (_String_) - Optional - Specifies the prefix of an attached database to target. If NULL or omitted, the main database is targeted. ### Return Value * **Integer**: The number of `VirtualGPKG` tables created or refreshed. ``` -------------------------------- ### NDims Function Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Function to get the number of dimensions used by a geometry object. ```APIDOC ## NDims ### Description Returns the dimension number used by the geometric object as: **2**, **3** or **4** respectively for **XY**, **XYZ** and **XYZM** (**3** for **XYM**). ### Syntax ```sql ST_NDims( geom _Geometry_ ) : _Integer_ ``` ### Module base ``` -------------------------------- ### InitTopoNet Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Initializes a Topo-Net. This function is an alias for CreateNetwork. ```APIDOC ## InitTopoNet ### Description Initializes a Topo-Net. This SQL function is explicitly required by ISO 13249-3 and is implemented as an alias for `CreateNetwork(netname)`. Returns 1 on success, 0 on failure, and -1 on invalid arguments. ### Syntax `ST_InitTopoNet( netname TEXT ) : INTEGER` ### Module X, RTTOPO ``` -------------------------------- ### Generate Initial EPSG File Source: https://github.com/cgx-group/libspatialite/blob/master/src/srsinit/epsg_update/README-PROJ6.txt Create the initial 'epsg-proj6' file by running the compiled utility and redirecting its output. This file serves as a seed for the next step. ```bash # rm epsg-proj6 # epsg_from_gdal-proj6 >epsg ``` -------------------------------- ### Decimal Precision Settings Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Functions to set and get the decimal precision for coordinate values in ST_AsText(). ```APIDOC ## SetDecimalPrecision ### Description Explicitly sets the number of decimal digits (precision) to be displayed by ST_AsText() for coordinate values. The default is 6 decimal digits. Passing a negative precision will restore the initial default setting. This setting is honored by the spatialite_gui tool for displaying floating point values. ### Syntax SetDecimalPrecision( _integer_ ) : _void_ ``` ```APIDOC ## GetDecimalPrecision ### Description Returns the currently set decimal precision. A negative precision indicates the default setting. ### Syntax GetDecimalPrecision( _void_ ) : _integer_ ``` -------------------------------- ### Vector Layer Management and Extent Source: https://context7.com/cgx-group/libspatialite/llms.txt Functions to get a list of vector layers, their extents, and to free the layer list. ```APIDOC ## `gaiaGetVectorLayersList` / `gaiaGetLayerExtent` / `gaiaFreeVectorLayersList` ### Description Enumerate all spatial layers in a database and retrieve per-layer metadata including extent and attribute field statistics. ### Functions - `gaiaGetVectorLayersList(db, NULL, NULL, GAIA_VECTORS_LIST_OPTIMISTIC)`: Retrieves a list of all vector layers in the database. - `gaiaGetLayerExtent(db, "airports", "geom", 0)`: Retrieves the bounding box (extent) of a specific layer. - `gaiaFreeVectorLayersList(list)`: Frees the memory allocated for the vector layers list. ### Example Usage ```c #include #include #include void vector_layers_example(sqlite3 *db) { /* Get list of all vector layers (optimistic = use cached stats) */ gaiaVectorLayersListPtr list = gaiaGetVectorLayersList(db, NULL, NULL, GAIA_VECTORS_LIST_OPTIMISTIC); if (!list) { printf("No layers found\n"); return; } gaiaVectorLayerPtr lyr = list->First; while (lyr) { printf("Layer: %-20s geom_type=%-16s rows=%d\n", lyr->TableName, (lyr->GeometryType == GAIA_VECTOR_POLYGON) ? "POLYGON" : (lyr->GeometryType == GAIA_VECTOR_POINT) ? "POINT" : "OTHER", lyr->RowCount); lyr = lyr->Next; } gaiaFreeVectorLayersList(list); /* Get bounding box of a specific layer */ gaiaGeomCollPtr extent = gaiaGetLayerExtent(db, "airports", "geom", 0 /* optimistic */); if (extent) { double min_x, min_y, max_x, max_y; gaiaGetMbrMinX(extent, &min_x); gaiaGetMbrMinY(extent, &min_y); gaiaGetMbrMaxX(extent, &max_x); gaiaGetMbrMaxY(extent, &max_y); printf("Extent: (%.4f, %.4f) -> (%.4f, %.4f)\n", min_x, min_y, max_x, max_y); gaiaFreeGeomColl(extent); } } ``` ``` -------------------------------- ### Get Number of Points in a LineString Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Use NumPoints or ST_NumPoints to retrieve the total number of points that define a LineString geometry. ```SQL NumPoints( line _LineString_ ) : _Integer_ ``` ```SQL ST_NumPoints( line _LineString_ ) : _Integer_ ``` -------------------------------- ### ST_LogiNetFromTGeo Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Creates a Logical Topology-Network from an existing Topology-Geometry. The destination TopoNet must exist and be empty. Returns 1 on success. ```APIDOC ## ST_LogiNetFromTGeo ### Description Will create a Logical Topology-Network from an existing Topology-Geometry. The destination TopoNet is expected to exist and to be completely empty. ### Method SQL Function ### Parameters - **netname** (Text) - The name of the network to create. - **toponame** (Text) - The name of the existing Topology-Geometry. ### Returns - **Integer** - Returns 1 on success; an exception will be raised on failure. Calling this function on behalf of some Network of the Spatial type will raise an exception. ``` -------------------------------- ### Pre-release Final Check Source: https://github.com/cgx-group/libspatialite/blob/master/src/srsinit/epsg_update/README.txt Runs the check_srid_spatialite.sh script after building and installing the updated libspatialite to verify the new SRS entries. ```bash # ./check_srid_spatialite.sh ``` -------------------------------- ### ST_InitTopoGeo Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Initializes a Topo-Geometry, aliased to CreateTopology. Returns 1 on success, 0 on failure, or -1 on invalid arguments. ```APIDOC ## ST_InitTopoGeo ### Description This SQL function is explicitly required by ISO 13249-3, anyway it's simply implemented as an alias-name for CreateTopology ( toponame ). ### Syntax ST_InitTopoGeo( toponame _Text_ ) : _Integer_ ### Returns 1 on success, 0 on failure; -1 will be returned on invalid arguments. ``` -------------------------------- ### Create a SQL Test Case File Source: https://github.com/cgx-group/libspatialite/blob/master/test/WritingSQLTestCase.txt Define a test case for the SQL floor function. The file format includes a test name, database to use, the SQL query, expected rows and columns, and the expected result. ```sql floor(3.2) # you can use the SQL if you're not feeling imaginative. :memory: SELECT floor(3.2); 1 # rows 1 # columns floor(3.2) # this is the header row 3.0 # this is really the result ``` -------------------------------- ### Get a Specific Point from a LineString Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Use PointN or ST_PointN to extract a specific point from a LineString. The first point is indexed as 1. ```SQL PointN( line _LineString_ , n _Integer_ ) : _Point_ ``` ```SQL ST_PointN( line _LineString_ , n _Integer_ ) : _Point_ ``` -------------------------------- ### ReCreateIsoMetaRefsTriggers Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Drops and recreates two Triggers that support the ISO_metadata_reference table. An optional 'enable_eval' argument controls the type of validating Triggers installed. ```APIDOC ## ReCreateIsoMetaRefsTriggers ### Description Drops and creates again two Triggers supporting the ISO_metadata_reference table. The optional argument 'enable_eval' chooses which type of validating Triggers will be installed. By default, this argument is FALSE (0). - **enable_eval=FALSE**: Triggers will never check if the referenced row in the target table exists. - **enable_eval=TRUE**: Triggers will fully check if the referenced row exists, but requires calling the eval() function, which only works when SPATIALITE_SECURITY=relaxed is set. Note: CreateIsoMetadataTables() always creates the version of Triggers not using eval(). ### Syntax ```sql ReCreateIsoMetaRefsTriggers() : _Integer_ ReCreateIsoMetaRefsTriggers( enable_eval _Integer_ ) : _Integer_ ``` ### Returns An Integer value: 1 for TRUE (success), 0 for FALSE (failure), -1 for invalid arguments. ``` -------------------------------- ### InitSpatialMetadata (SQL function) Source: https://context7.com/cgx-group/libspatialite/llms.txt Creates all required spatial metadata tables (geometry_columns, spatial_ref_sys, etc.) in a new or existing database, and populates the EPSG reference system dataset. ```APIDOC ## InitSpatialMetadata (SQL function) ### Description Creates all required spatial metadata tables (`geometry_columns`, `spatial_ref_sys`, etc.) in a new or existing database, and populates the EPSG reference system dataset. ### Usage ```c #include #include static int init_new_db(sqlite3 *db) { char *err_msg = NULL; int rc; /* InitSpatialMetadata(1) — the integer arg requests EPSG population */ rc = sqlite3_exec(db, "SELECT InitSpatialMetadata(1)", NULL, NULL, &err_msg); if (rc != SQLITE_OK) { fprintf(stderr, "InitSpatialMetadata error: %s\n", err_msg); sqlite3_free(err_msg); return 0; } /* Create a plain table */ rc = sqlite3_exec(db, "CREATE TABLE airports (pk INTEGER PRIMARY KEY, name TEXT)", NULL, NULL, &err_msg); if (rc != SQLITE_OK) { sqlite3_free(err_msg); return 0; } /* Add a geometry column (SRID 4326 = WGS84 lon/lat, POINT, 2D) */ rc = sqlite3_exec(db, "SELECT AddGeometryColumn('airports', 'geom', 4326, 'POINT', 2)", NULL, NULL, &err_msg); if (rc != SQLITE_OK) { sqlite3_free(err_msg); return 0; } /* Create an R*Tree spatial index */ rc = sqlite3_exec(db, "SELECT CreateSpatialIndex('airports', 'geom')", NULL, NULL, &err_msg); if (rc != SQLITE_OK) { sqlite3_free(err_msg); return 0; } return 1; /* success */ } ``` ``` -------------------------------- ### CreateIsoMetadataTables Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Creates a set of tables to support ISO Metadata. An optional 'relaxed' argument can be provided to install a relaxed version of the validating Triggers. ```APIDOC ## CreateIsoMetadataTables ### Description Creates a set of tables supporting ISO Metadata. If the optional argument 'relaxed' is specified, a relaxed version of the validating Triggers will be installed. ### Syntax ```sql CreateIsoMetadataTables() : _Integer_ CreateIsoMetadataTables( relaxed _Integer_ ) : _Integer_ ``` ### Returns An Integer value: 1 for TRUE (success), 0 for FALSE (failure), -1 for invalid arguments. ``` -------------------------------- ### InitFDOSpatialMetaData Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Creates the geometry_columns and spatial_ref_sys metadata tables with an FDO/OGR layout. Returns 1 for TRUE or 0 for FALSE. ```APIDOC ## InitFDOSpatialMetaData ### Description Creates the **geometry_columns** and **spatial_ref_sys** metadata tables. the return type is Integer, with a return value of 1 for TRUE or 0 for FALSE. Please note: Spatial Metadata created using this function will have the FDO/OGR layout, and not the standard SpatiaLite layout. ### Syntax InitFDOSpatialMetaData( void ) : _Integer_ ``` -------------------------------- ### Line_Substring Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Extracts a portion of a line segment defined by start and end fractions of its total length. Both fractions must be between 0.0 and 1.0. Returns NULL for invalid arguments. ```APIDOC ## Line_Substring ### Description Returns a Linestring being a substring of the input one, starting and ending at the given fractions of total length. Second and third arguments are expected to be in the range between 0.0 and 1.0. NULL is returned for invalid arguments. ### Function Signature `Line_Substring(line _Curve_, start_fraction _Double precision_, end_fraction _Double precision_) : _Curve_` ### Related Function `ST_Line_Substring(line _Curve_, start_fraction _Double precision_, end_fraction _Double precision_) : _Curve_` ### Notes This function is GEOS specific. ``` -------------------------------- ### EnsureClosedRings Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Ensures that all rings within a Geometry are correctly closed, meaning the start and end vertices are coincident. Accepts any Geometry class and returns NULL on invalid arguments. ```APIDOC ## EnsureClosedRings ### Description Returns a new Geometry derived from the input Geometry; all Rings within the output Geometry are ensured to be correctly closed, i.e. will have exactly coincident start and end vertices. This function accepts input Geometries of any class: Point, MultiPoint, Linestring, MultiLinestring, Polygon, MultiPolygon, GeometryCollection and Geometry. Will return NULL on invalid argument. ### Syntax EnsureClosedRings( geom _Geometry_ ) : geom _Geometry_ ### Module base ``` -------------------------------- ### Create a SQL Test Case for Integer Input Source: https://github.com/cgx-group/libspatialite/blob/master/test/WritingSQLTestCase.txt Write a test case to verify the behavior of the SQL floor function with integer input. This helps ensure the function handles different data types correctly. ```sql floor(integer) # integer input - this is just the name remember :memory: SELECT floor(3); # the SQL to run 1 # rows 1 # columns floor(3) # this is the header row 3.0 # this is really the result ``` -------------------------------- ### Build LEMON Parser Executable Source: https://github.com/cgx-group/libspatialite/blob/master/src/gaiageo/lemon/ReadMe.txt Compile the LEMON parser from its source code. Ensure you are in the 'lemon_src' directory before running this command. ```bash cd lemon_src gcc lemon.c -o lemon ``` -------------------------------- ### Adding Geometry Column to Helper Table Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Example SQL statement to add a geometry column of type POINT to the helper table, which will contain the new vertices for replacement. ```SQL SELECT AddGeometryColumn('_helper_table_', '_geom_', _someSRID_, 'POINT', _dimensions_ ); ``` -------------------------------- ### CreateNetwork Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Creates a new Topo-Net with various configuration options. ```APIDOC ## CreateNetwork ### Description Creates all necessary DBMS objects (tables, triggers, indices, etc.) to store a separate Topo-Net. Returns 1 on success, 0 on failure, and -1 on invalid arguments. ### Syntax `CreateNetwork( netname TEXT ) : INTEGER` `CreateNetwork( netname TEXT, spatial BOOLEAN ) : INTEGER` `CreateNetwork( netname TEXT, spatial BOOLEAN, srid INTEGER ) : INTEGER` `CreateNetwork( netname TEXT, spatial BOOLEAN, srid INTEGER, has_z BOOLEAN ) : INTEGER` `CreateNetwork( netname TEXT, spatial BOOLEAN, srid INTEGER, has_z BOOLEAN, allow_coincident BOOLEAN ) : INTEGER` ### Parameters * **netname** (TEXT) - The unique name for this Topo-Net. * **spatial** (BOOLEAN) - If TRUE, creates a Spatial-Network; otherwise, a Logical-Network (FALSE by default). * **srid** (INTEGER) - The Spatial Reference System for this Topo-Net (-1 by default). * **has_z** (BOOLEAN) - If TRUE, supports 3D (XYZ) coordinates (FALSE by default). * **allow_coincident** (BOOLEAN) - If FALSE, Node-on-Node, Link-on-Node, or Node-on-Link conditions will raise an exception (TRUE by default). ### Module RTTOPO ``` -------------------------------- ### CreateMissingSystemTables Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Creates any missing ancillary metadata tables required by libspatialite v.5 and later. It can optionally install a relaxed version of validating triggers and handle the operation within a transaction. ```APIDOC ## CreateMissingSystemTables ### Description Creates any missing ancillary metadata tables required by libspatialite v.5 and subsequent versions. Returns 1 on success; an exception is raised on invalid arguments or failure. ### Syntax - `CreateMissingSystemTables( void ) : _Integer_` - `CreateMissingSystemTables( relaxed _Integer_ ) : _Integer_` - `CreateMissingSystemTables( relaxed _Integer_ , transaction _Integer_ ) : _Integer_` ### Parameters #### Optional Parameters - `relaxed` (Integer): If set to TRUE, a relaxed version of validating triggers is installed (not checking for strict XSD schema validation). - `transaction` (Integer): If set to TRUE, the entire operation is atomically confined within a monolithic SQL transaction. ``` -------------------------------- ### Create a SQL Test Case for Null/Text Input Source: https://github.com/cgx-group/libspatialite/blob/master/test/WritingSQLTestCase.txt Develop a test case to check the SQL floor function's behavior when given non-numeric input, expecting a null output. This addresses edge cases and potential errors. ```sql floor(null) # text input, expecting null output :memory: SELECT floor("some text"); # the SQL to run 1 # rows 1 # columns floor("some text") # this is the header row ``` -------------------------------- ### Get the Index of a Point in a LineString Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Use GetPointIndex or ST_GetPointIndex to find the zero-based index of the vertex nearest to a given point. If check_multiple is TRUE, returns -1 if the point corresponds to multiple vertices. ```SQL GetPointIndex( line _LineString_ , point _Point_ ) : _Integer_ GetPointIndex( line _LineString_ , point _Point_ , check_multiple _Boolean_ ) : _Integer_ ``` ```SQL ST_GetPointIndex line _LineString_ , point _Point_ ) : _Integer_ ST_GetPointIndex line _LineString_ , point _Point_ , check_multiple _Boolean_ ) : _Integer_ ``` -------------------------------- ### CreateTopoTables Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Creates the 'topologies' and 'networks' meta-tables. Returns 1 on success, 0 on failure (e.g., if tables already exist). ```APIDOC ## CreateTopoTables ### Description Will create both topologies and networks meta-tables. ### Syntax CreateTopoTables( ) : _Integer_ ### Returns 1 on success, 0 on failure (including already existing tables). ``` -------------------------------- ### gpkgCreateBaseTables Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Creates the base tables required for an empty GeoPackage. ```APIDOC ## gpkgCreateBaseTables ### Description Creates the essential base tables for an empty GeoPackage. ### Syntax gpkgCreateBaseTables( void ) : _void_ ### Return Value * **void**: Returns nothing on success. Raises an exception on error. ``` -------------------------------- ### Manage Spatial Tables and Geometries Source: https://context7.com/cgx-group/libspatialite/llms.txt Utilize `elementary_geometries_ex2` to expand multi-part geometries, `gaiaRenameTable` and `gaiaRenameColumn` for renaming, and `gaiaDropTable5` for safe table removal. ```c #include #include void table_management_example(sqlite3 *db) { char *err_msg = NULL; /* Expand MULTIPOLYGON rows into individual POLYGON rows */ int rows_inserted = 0; elementary_geometries_ex2(db, "world_borders", /* input table */ "geom", /* geometry column */ "world_simple", /* output table (new) */ "pk_uid", /* primary key column */ "multi_id", /* origin-id column */ &rows_inserted, 1 /* use transaction */); printf("Elementary geometries inserted: %d\n", rows_inserted); /* Rename table (requires SQLite >= 3.25) */ int ok = gaiaRenameTable(db, "main", "world_simple", "world_polygons", &err_msg); if (!ok) { fprintf(stderr, "%s\n", err_msg); sqlite3_free(err_msg); } /* Rename a column */ ok = gaiaRenameColumn(db, "main", "world_polygons", "multi_id", "origin_id", &err_msg); if (!ok) { fprintf(stderr, "%s\n", err_msg); sqlite3_free(err_msg); } /* Drop old table, removing spatial index and metadata entries */ ok = gaiaDropTable5(db, "main", "world_borders", &err_msg); if (!ok) { fprintf(stderr, "%s\n", err_msg); sqlite3_free(err_msg); } else printf("Table dropped successfully\n"); } ``` -------------------------------- ### Copy Generated GML Parser Files Source: https://github.com/cgx-group/libspatialite/blob/master/src/gaiageo/lemon/ReadMe.txt Copy the generated Gml.h and Gml.c files to the -/lemon/include directory. ```bash cp Gml.h .. cp Gml.c .. ``` -------------------------------- ### TopoGeo_InitTopoLayer Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Initializes a new TopoLayer starting from a reference GeoTable. It can handle NULL values for database prefix and reference column name, and accepts various geometry types. An optional boolean argument 'is-view' can be set to TRUE to accept Views or Tables with unregistered Geometry columns. ```APIDOC ## TopoGeo_InitTopoLayer ### Description Initializes a fully defined new TopoLayer starting from a reference GeoTable. ### Parameters - **toponame** (Text) - The name of the topology. - **db-prefix** (Text) - Optional. The prefix for the database. If NULL, the reference GeoTable is in the "MAIN" database. - **ref-table-name** (Text) - The name of the reference GeoTable. - **topolayer-name** (Text) - The name of the TopoLayer to be created. - **is-view** (Boolean) - Optional. If TRUE, accepts Views or Tables with unregistered Geometry columns. Defaults to FALSE. ### Returns - **Integer** - 1 on success, raises an exception on failure. ``` -------------------------------- ### WMS_CreateTables Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Creates all necessary database tables for permanently registering WMS datasources and their configurations. ```APIDOC ## WMS_CreateTables ### Description Creates all DB Tables required for permanently registering WMS datasources and their configurations. ### Syntax WMS_CreateTables() : Integer ### Returns - **1**: on success - **0**: on failure ``` -------------------------------- ### AutoFDOStart Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Inspects Spatial Metadata and automatically creates or refreshes a VirtualFDO wrapper for each FDO/OGR geometry table. The function returns the count of created VirtualFDO tables. An optional db_prefix can specify the target database. ```APIDOC ## AutoFDOStart ### Description This function will inspect the Spatial Metadata, then automatically creating/refreshing a **VirtualFDO** wrapper for each FDO/OGR geometry table. The return type is Integer [how many VirtualFDO tables have been created]. The optional **db_prefix** argument specifies which one of the ATTACHED databases is intended to be targeted; if unspecified or **NULL** then the **MAIN** database will be assumed by default. ### Syntax AutoFDOStart( void ) : _Integer_ AutoFDOStart( db_prefix _String_ ) : _Integer_ ``` -------------------------------- ### AutoGPKGStop Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Automatically destroys any VirtualGPKG wrappers found in the specified database. ```APIDOC ## AutoGPKGStop ### Description Inspects the database layout and automatically destroys any `VirtualGPKG` wrappers found. An optional `db_prefix` can be provided to target specific attached databases. ### Syntax AutoGPKGStop( void ) : _Integer_ AutoGPKGStop( db_prefix _String_ ) : _Integer_ ### Parameters * **db_prefix** (_String_) - Optional - Specifies the prefix of an attached database to target. If NULL or omitted, the main database is targeted. ### Return Value * **Integer**: The number of `VirtualGPKG` tables destroyed. ``` -------------------------------- ### ST_CreateTopoGeo Source: https://github.com/cgx-group/libspatialite/blob/master/spatialite-sql-latest.html Populates a full topology by importing a collection of arbitrary geometries. ```APIDOC ## ST_CreateTopoGeo ### Description Populates a full topology by importing a collection of arbitrary geometries. The destination topology must already exist and be empty. Both SRID and dimensions of input geometries must match SRID and dimensions declared by the topology. ### Parameters - **toponame** (Text) - The name of the topology. - **geometry** (BLOB) - The collection of geometries to import. ### Returns - **NULL** - On success; an exception will be raised on failure. ``` -------------------------------- ### Copy Generated KML Parser Files Source: https://github.com/cgx-group/libspatialite/blob/master/src/gaiageo/lemon/ReadMe.txt Copy the generated Kml.h and Kml.c files to the -/lemon/include directory. ```bash cp Kml.h .. cp Kml.c .. ``` -------------------------------- ### Create SQL Table Source: https://github.com/cgx-group/libspatialite/blob/master/test/sqlproc_error.txt Defines a new table named 'another_test' with an integer primary key, a text field, and a double field. Ensure data types are appropriate for your needs. ```sql -- -- creating a table -- CREATE TABLE another_test ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, value DOUBLE NOT NULL); ``` -------------------------------- ### Generate EWKT Parser Source: https://github.com/cgx-group/libspatialite/blob/master/src/gaiageo/lemon/ReadMe.txt Generate C code and header files for parsing EWKT format using the LEMON parser. The output files are Ewkt.c and Ewkt.h. ```bash lemon_src/lemon -l Ewkt.y ```