在DolphinDB插件函数向表写入数据时,如何获取实际插入的行数?

编程语言 2026-07-11

我正在开发DolphinDB插件,需要将数据写入内存表或分布式表。在插件中,我调用内置函数 append! 来执行写入,并且想获取实际插入的行数。下面给出简化版本的代码:

static FunctionDefSP appendFunc = heap->currentSession()->getFunctionDef("append!");
vector<ConstantSP> appendArgs = {destTable, batchTable};
int insertedRows = 0;
ConstantSP ret = appendFunc->call(heap, appendArgs);
insertedRows = ret->getInt();   // This fails with an error

然而,在执行这段代码时,出现错误:

向DolphinDB追加失败:对象不能被转换为整型标量。

经过调试,我发现 ret 实际上是一个字典(当目标表是分布式表时),所以 getInt() 不能直接使用。随后我尝试用如下方式从字典中提取行数:

ConstantSP keys = ret->getKeys();
ConstantSP firstCol = ret->getMember(keys->get(0));
insertedRows = ((VectorSP)firstCol)->size();   // Not correct

但这返回的是源表的行数(batchTable),而不是实际插入的行数。此外,返回的值似乎与写入是否成功无关,总是保持不变。

我还尝试按照文档所述,使用内置函数 matchedRowCount,据说 matchedRowCount 会返回当前会话中最近一个 INSERT INTODELETEUPDATE 语句影响的行数。我的代码是这样的:

static FunctionDefSP matchedRowCountFunc = heap->currentSession()->getFunctionDef("matchedRowCount");

appendFunc->call(heap, appendArgs);   // Execute tableInsert first
vector<ConstantSP> emptyArgs;
ConstantSP ret = matchedRowCountFunc->call(heap, emptyArgs);
insertedRows = ret->getInt();   // Always returns 0

然而,insertedRows 即使在写入成功时也总是为0。

如何在目标为分布式表(返回值为字典)的情况下,正确获取实际由 append! 插入的行数?

环境:

  • DolphinDB版本:3.0.0.4
  • 插件使用C++
  • 目标表可以是内存表或分布式表(DFS表)

任何指导都将不胜感激。

解决方案

感谢 @Ted Lyngmo的提示。切换到 tableInsert 而不是 append! 之后,我终于能够获取实际插入的行数:

static FunctionDefSP appendFunc = heap->currentSession()->getFunctionDef("tableInsert");
vector<ConstantSP> appendArgs = {destTable, batchTable};
int insertedRows = 0;
ConstantSP ret = appendFunc->call(heap, appendArgs);
insertedRows = ret->getInt(); 
cout << "Append result: " << insertedRows << " rows" << endl;

例如,在下面的测试用例中:

@testing:case="test_load_mismatched_schema"
conn = duckdb::connect(":memory:")
duckdb::execute(conn, "create table t(i int)")
duckdb::execute(conn, "insert into t values (1), (2), (5)")
t = duckdb::query(conn, "select * from t")  // retrieve correct schema
dest = table(1:0, [`s], [STRING])
duckdb::load(conn, "t", dest, batchSize=1)
assert 1, dest.size() == 3 
assert 2, eqObj(string(t.i), dest.s)
duckdb::close(conn)

控制台按预期输出:

Append result: 3 rows

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章