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

使用postgresql:JsonValue类型创建Ballerina记录时出现编译错误

问题分析与解决

问题原因

Ballerina 的 postgresql:Client->queryRow() 方法要求返回的记录类型必须是 anydata 的子类型。json 本身属于 anydata 体系,所以用它定义记录字段时能自动完成映射;但 postgresql:JsonValue 不属于 anydata 子类型,导致类型检查不通过,触发编译错误。

解决方案

你需要手动处理查询结果的类型转换,以下两种方式都能解决问题:

方式一:通过临时记录中转转换

先以包含 json 类型的临时记录接收查询结果,再将 json 转换为 postgresql:JsonValue:

import ballerina/io;
import ballerina/sql;
import ballerinax/postgresql;

type TestData record {|
    string authId;
    string userId;
    postgresql:JsonValue? data;
|};

public function testFunction(postgresql:Client cl) returns TestData|error {
    // 定义临时记录接收结果
    type TempRow record {|
        string authId;
        string userId;
        json? data;
    |};
    TempRow tempRow = check cl->queryRow(`SELECT * FROM test_table WHERE auth_id = 'authId'`);
    
    // 转换json为postgresql:JsonValue
    postgresql:JsonValue? pgData = match tempRow.data {
        json j => postgresql:fromJson(j),
        () => ()
    };
    
    // 构造目标记录返回
    return {
        authId: tempRow.authId,
        userId: tempRow.userId,
        data: pgData
    };
}

方式二:通过 sql:Row 手动提取字段

直接用 sql:Row 获取原始结果,逐个字段提取并转换为目标类型:

import ballerina/io;
import ballerina/sql;
import ballerinax/postgresql;

type TestData record {|
    string authId;
    string userId;
    postgresql:JsonValue? data;
|};

public function testFunction(postgresql:Client cl) returns TestData|error {
    sql:Row row = check cl->queryRow(`SELECT auth_id, user_id, data FROM test_table WHERE auth_id = 'authId'`);
    
    string authId = check row.getString(0);
    string userId = check row.getString(1);
    postgresql:JsonValue? data = check row.getJsonValue(2);
    
    return {authId, userId, data};
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 04:15:05