biommap/utils/geojson2sql.py
2021-09-13 16:38:41 +02:00

61 lines
2.2 KiB
Python

import geojson
def convert_coordinates_to_geom(coordinates, geometry_type):
""" Returns a string with a valid PostGIS command for creating a geometry from an array of coordinates """
if geometry_type == 'POINT':
res = f'ST_GeomFromText(\'POINT({coordinates[0]} {coordinates[1]})\'),'
return res
def import_geosjon_as_sql(filename, sql_filename, schema_name, table_name, column_list, values_list):
""" Import a geojson """
with open(filename) as f:
g = geojson.load(f)
sql_f = open(sql_filename,'w')
for f in g['features']:
#print(f)
sql = f'INSERT INTO "{schema_name}"."{table_name}" ('
col_name = ''
col_value = ''
for i,c in enumerate(column_list):
if values_list[i] == 'UUID':
col_name += f'"{c}",'
col_value += 'uuid_generate_v4(),'
elif values_list[i] == 'NOW':
col_name += f'"{c}",'
col_value += 'now()::timestamptz,'
elif c == 'geom':
col_name += f'"{c}",'
col_value += convert_coordinates_to_geom(f.geometry.coordinates, values_list[i])
elif values_list[i].startswith('properties.'):
col_name += f'"{c}",'
prop = values_list[i].split('.')[1]
col_value += f'\'{f.properties[prop]}\','
else:
col_name += f'"{c}",'
col_value += f'\'{values_list[i]}\','
sql += f'{col_name[:-1]}) VALUES ({col_value[:-1]});\n'
sql_f.write(sql)
sql_f.close()
if __name__ == '__main__':
filename = './gis/arbres.geojson'
sql_filename = 'arbres.sql'
schema_name= 'gnc_sites'
table_name = 't_sites'
column_list = ['uuid_sinp', 'id_program', 'name', 'geom', 'timestamp_create', 'id_type', 'obs_txt']
values_list = ['UUID', '2', 'import arbres remarquables', 'POINT', 'NOW', '1', 'import' ]
import_geosjon_as_sql(filename, sql_filename, schema_name, table_name, column_list, values_list)
# add CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; ??