关于postgresql:使用PostgREST插入/更新PostGIS几何列

Insert/update PostGIS geometry column with PostgREST

我将PostgreSQL 12.1,PostGIS 3.0.0和PostgREST 7.0.1结合使用,对此设置我感到非常满意。有一个开放的增强功能,可以在PostgREST中更广泛地支持PostGIS,我很期待它。

我有一个带有几何列的表:

1
2
3
4
CREATE TABLE places (
  id serial PRIMARY KEY,
  geometry geometry(GEOMETRY,4326)
);

使用SQL,我可以像这样插入纬度57.20和经度17.45的点:

1
INSERT INTO places(geometry) VALUES (ST_GeomFromText('POINT(17.45 57.20)', 4326));

使用PostgREST查询时,它表示为GeoJSON:

1
2
3
4
5
6
7
8
GET /places?id=eq.6317&SELECT=geometry

[{
 "geometry": {
   "type":"Point",
   "coordinates": [17.45,57.2]
  }
}]

但是,我该如何表示几何图形才能使用PostgREST插入/更新?

使用GeoJSON会导致500内部服务器错误:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
POST /places

{
   "geometry": {
       "type":"Point",
       "coordinates": [17.45,57.2]
    }
}

500 Internal Server Error

{
   "hint":"\"{\
\" <-- parse error at position 2 within geometry"
,
   "details": NULL,
   "code":"XX000",
   "message":"parse error - invalid geometry"
}

与使用ST_GeomFromText函数相同:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
POST /places

{
   "geometry":"ST_GeomFromText('POINT(17.45 57.20)', 4326)"
}

500 Internal Server Error

{
   "hint":"\"ST\" <-- parse error at position 2 within geometry",
   "details": NULL,
   "code":"XX000",
   "message":"parse error - invalid geometry"
}

起作用的是使用内部PostGIS字符串表示形式,但是我的API客户端手头只有17.45 57.20的值:

1
2
3
4
5
6
7
POST /places

{
   "geometry":"0101000020E610000033333333337331409A99999999994C40"
}

201 Created

是否还有其他可用的文本表示形式?是否有可能将ST_GeomFromText之类的函数传递给PostgREST?任何提示都非常感谢!


直接的方法是使用geometry文字表示形式:

1
2
3
4
5
POST /places

{
 "geometry":"SRID=4326;POINT(17.45 57.2)"
}

(您可以省略SRID)

这行得通,因为这也行得通:

1
2
SELECT 'SRID=4326;POINT(54.729142 25.268204)'::geometry
-- result: 0101000020E6100000ED116A86545D4B4009A87004A9443940

另一种方法是在插入触发器之前处理json数组。