1

我怎么能SELECT * FROM table不指定记录类型然后迭代结果(没有加载到内存中,我们的表是巨大的)?

我需要的是逐行迭代,同时将每一行转换为JSON.

我基本上想做这样的事情:

var selectRet  = testdb->select("SELECT * FROM some_table", ());
.
.
.
foreach row in tb { io:println(<json> row);}

在研究了 `ballerina.io 文档一周后,如果不首先使用类型行记录 { ..... } 指定确切的 ROW 结构,我仍然无法完成此操作,当您的表有 200 列时,这非常不方便。

谢谢

4

2 回答 2

1

理想情况下,转换为 json 不应将整个表加载到内存中。但是由于这个已知问题,服务器在表到 json 的转换过程中会出现 OOM。该修复程序将很快在即将发布的版本中提供。

您的用例是否迭代表并将每一行转换为 json?如果是这种情况,一旦上述问题得到解决,您应该能够按照以下方式进行操作,而不会填满内存。

import ballerina/io;
import ballerina/mysql;

endpoint mysql:Client testDB {
    host: "localhost",
    port: 3306,
    name: "testdb",
    username: "root",
    password: "123",
    poolOptions: { maximumPoolSize: 5 },
    dbOptions: { useSSL: false }
};


function main(string... args) {
    var selectRet = testDB->select("SELECT * FROM employee", ());

    table dt;
    match selectRet {
        table tableReturned => dt = tableReturned;
        error err => io:println("Select data from the table failed: "
                + err.message);
    }

    var ret = <json>dt;

    json jsonData;
    match ret {
        json j => jsonData = j;
        error e => io:println("Error occurred while converting the table to json" + e.message);
    }

    foreach j in jsonData {
        match j {
            string js => {
                io:println("string value: ", js);
            }
            json jx => {
                io:println("non-string value: ", jx);
            }
        }
    }
}
于 2018-07-24T05:58:59.277 回答
0

您可以将选择查询返回的表转换为 JSON,而无需将表转换为记录数组。看看下面的示例。我尝试使用最新版本的 Ballerina 0.980.1。我在这里使用了示例员工数据库。

// This function returns an optional type 'error?' 
function performSelect() returns error? {
    endpoint mysql:Client testDB {
        host: "localhost",
        port: 3306,
        name: "employees",
        username: "root",
        password: "root12345678",
        poolOptions: { maximumPoolSize: 5 },
        dbOptions: { useSSL: false, allowPublicKeyRetrieval:true, serverTimezone:"UTC" }
    };

    // If the select query results in an error, 
    // then the 'check' operator returns it to the caller of this function 
    table resultTable = check testDB->select("SELECT * FROM employees", ());

    // convert the table to a json object
    json resultJson = check <json>resultTable;
    io:println(resultJson);
    testDB.stop();

    // Return nil since there are no errors occurred
    return ();
}
于 2018-07-23T21:16:00.730 回答