You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node/TypeScript调用PostGIS函数时遇参数数据类型无法确定错误

问题分析与解决:PostgreSQL无法推断参数$4的数据类型

问题根源

你在sql模板字符串中错误地用单引号包裹了参数占位符:'${JSON.stringify(excludeGeojson)}'。这种写法会导致postgres.js将带引号的内容作为参数传递,但PostgreSQL无法自动推断该参数的数据类型,从而抛出could not determine data type of parameter $4错误。

而直接执行SQL时,你传递的是单引号包裹的字符串字面量,PostgreSQL可以根据query_cityjson_excludetest函数的参数定义(预期为json/jsonb类型)自动完成类型转换,因此能正常运行。


解决方法

方法1:直接传递JSON对象(推荐)

postgres.js的sql模板支持直接传入JavaScript对象,它会自动将对象序列化为JSON并绑定为正确的参数类型:

const excludeGeojson = {
  "coordinates": [
    [
      [13.052800998359942, 52.40228431090625],
      [13.048063265289755, 52.397217941608375],
      [13.060780338266397, 52.398328636914954],
      [13.052800998359942, 52.40228431090625]
    ]
  ],
  "type": "Polygon"
};

const query = sql`SELECT query_cityjson_excludetest(${z}, ${x}, ${y}, ${excludeGeojson})`.execute();

方法2:显式标记JSON类型

如果需要传递字符串形式的JSON,可使用sql.json()方法明确指定参数类型:

const jsonStr = JSON.stringify(excludeGeojson);
const query = sql`SELECT query_cityjson_excludetest(${z}, ${x}, ${y}, ${sql.json(jsonStr)})`.execute();

方法3:SQL中显式转换类型

在SQL语句中通过类型转换告知PostgreSQL参数的目标类型:

const jsonStr = JSON.stringify(excludeGeojson);
const query = sql`SELECT query_cityjson_excludetest(${z}, ${x}, ${y}, ${jsonStr}::json)`.execute();

内容的提问来源于stack exchange,提问作者pcace

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 11:30:19