spatialite.py 1.6 KB

12345678910111213141516171819202122232425262728293031
  1. import sqlite3
  2. # Path to your SpatiaLite database
  3. db_path = "D:\\temp\\output.sqlite"
  4. # Connect to the SQLite database
  5. conn = sqlite3.connect(db_path)
  6. # Enable loading of extensions
  7. conn.enable_load_extension(True)
  8. # Load the SpatiaLite extension
  9. try:
  10. conn.execute("SELECT load_extension('mod_spatialite');")
  11. print("SpatiaLite extension loaded successfully!")
  12. except sqlite3.OperationalError as e:
  13. print(f"Error loading SpatiaLite extension: {e}")
  14. # Create a cursor to execute queries
  15. cursor = conn.cursor()
  16. # Example: Check SpatiaLite version
  17. cursor.execute("drop table if exists topology_table_temp;")
  18. cursor.execute("create table topology_table_temp(PIEID INTEGER PRIMARY KEY not null,PIEUUID VARCHAR(128),PIEVALIDED BOOLEAN,sid,idx,rulecode,geometry MULTILINESTRING);")
  19. cursor.execute("with t as( select 0 sid, 0 did, numgeometries(linesfromrings(gunion(geometry))) cnt, linesfromrings(gunion(geometry)) geometry from topology_table ), cte(idx, sid, did, cnt, geometry, subgeom) AS ( SELECT 1 idx, sid, did, cnt, geometry, geometryN(geometry, 1) subgeom from t UNION ALL SELECT idx + 1 idx, sid, did, cnt, geometry, geometryN(geometry, idx + 1) subgeom FROM cte WHERE idx < cnt ) insert into topology_table_temp SELECT null,createuuid(),isvalid(casttomulti(subgeom)), sid, idx, 'A03' rulecode, casttomulti(subgeom) geometry FROM cte; ")
  20. cursor.execute("select recovergeometrycolumn('topology_table_temp', 'geometry', (select srid from geometry_columns where f_table_name = 'topology_table'), 'MULTILINESTRING', 'XY');")
  21. # version = cursor.fetchone()
  22. # print(f"SpatiaLite version: {version[0]}")
  23. # Close the connection when done
  24. conn.close()