--/
create or replace python scalar script ST_GeomFromGeoJSON(g varchar(2000000)) returns varchar(2000000) as
## https://tools.ietf.org/html/rfc7946
import json
def point(coordinates):
 return str(coordinates[0])+" "+str(coordinates[1])   
 
def linestring(coordinates):
 return "("+ (",".join(map(point,coordinates)))  +")" 
 
def polygon(coordinates):
 return "("+ ",".join(map(linestring,coordinates))+")"
 
def geometry(geo):
 if geo["type"] == "Point":
  return "POINT ("+point(geo["coordinates"])+")"
 if geo["type"] == "MultiPoint":
  return "MULTIPOINT(" + ",".join(map(point,geo["coordinates"]))+")"
 if geo["type"] == "LineString":
  return "LINESTRING" + linestring(geo["coordinates"])
 if geo["type"] == "MultiLineString":
  return "MULTILINESTRING("+ ",".join(map(linestring,geo["coordinates"]))+")"
 if geo["type"] == "Polygon":
  return "POLYGON" + polygon(geo["coordinates"])
 if geo["type"] == "MultiPolygon":
  return "MULTIPOLYGON("+ ",".join(map(polygon,geo["coordinates"]))+")"
 if geo["type"] == "GeometryCollection":
  return "GEOMETRYCOLLECTION(" + ",".join(map(geometry, geo["geometries"])) + ")"
 
 
def run(ctx):
 geo = json.loads(ctx.g)
 return geometry(geo)
/

create table geo(geo geometry);
insert into geo
select ST_GeomFromGeoJSON('{ "type": "Point",  "coordinates": [30, 10.5] }')
union
select ST_GeomFromGeoJSON('{ "type": "MultiPoint", "coordinates": [ [100.0, 0.0], [101.0, 1.0] ] }')
union
select ST_GeomFromGeoJSON('{ "type": "LineString", "coordinates": [ [100.0, 0.0], [101.0, 1.0] ] }')
union
select ST_GeomFromGeoJSON('{ "type": "MultiLineString", "coordinates": [ [ [100.0, 0.0], [101.0, 1.0] ], [ [102.0, 2.0], [103.0, 3.0] ] ] }')
union
select ST_GeomFromGeoJSON('{ "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ],
             [ [100.8, 0.8], [100.8, 0.2], [100.2, 0.2], [100.2, 0.8], [100.8, 0.8] ] ] }')
union             
select ST_GeomFromGeoJSON('{ "type": "MultiPolygon", "coordinates": [ [ [ [102.0, 2.0], [103.0,2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0] ] ], 
                           [ [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ], 
                           [ [100.2, 0.2], [100.2, 0.8], [100.8, 0.8], [100.8, 0.2], [100.2, 0.2] ] ] ] }')     
union
select ST_GeomFromGeoJSON('{ "type": "GeometryCollection", "geometries": [{ "type": "Point", "coordinates": [100.0, 0.0] }, 
                                                                          { "type": "LineString", "coordinates": [[101.0, 0.0], [102.0, 1.0] ] }] }');     
select * from geo;