Bug: SQL INSERT Statement with multi rows does not work as expected
I came across the bug when trying to insert multiple rows into a table with a INSERT Statement(the code below). The execution of the statement did not return any error. But when querying the table, only the first row had been inserted into the table. The bug exists both in sql_client and Python SDK of OpenMLDB, i haven't test it in Java SDK.
127.0.0.1:6527/> CREATE DATABASE db_test;
Create database success
127.0.0.1:6527/> USE db_test;
Database changed
127.0.0.1:6527/db_test> CREATE TABLE user(userId string, createAt timestamp, index(key=userId, ts=createAt));
I0907 13:11:27.337503 163 zk_client.cc:56] node watcher with event type 3, state 3
127.0.0.1:6527/db_test> INSERT INTO user VALUES('user_0', 1628689181169), ('user_1', 1628689181169), ('user_2', 1628689181169);
127.0.0.1:6527/db_test> SELECT * FROM user;
-------- ---------------
userId createAt
-------- ---------------
user_0 1628689181169
-------- ---------------
Expected Behavior
After success execution of the INSERT statement with multiple rows, the result of the querying should contains all the rows in the INSERT statement.
Current Behavior
After success execution of the INSERT statement with multiple rows, the current result of the querying only contains the first row in the INSERT statement.
Possible Solution
There are two possible solution for the bug.
- First One: Given an Explicitly error or warn when user trying to insert multiple rows in a
INSERTstatement. - Second One: Support Insert multiple rows in a
INSERTstatement
I prefer to the second solution to support multiple rows inserting.
Steps to Reproduce
CREATE DATABASE db_test;
USE db_test;
CREATE TABLE user(userId string, createAt timestamp, index(key=userId, ts=createAt));
INSERT INTO user VALUES('user_0', 1628689181169), ('user_1', 1628689181169), ('user_2', 1628689181169);
SELECT * FROM user;
Context (Environment)
- Image: ghcr.io/4paradigm/openmldb:0.2.1
Detailed Description
After a further investigation, i find that the SQL Parser already support parsing multiple rows(as code shown below).
// hybridse/src/planv2/ast_node_converter.cc
base::Status ConvertInsertStatement(const zetasql::ASTInsertStatement* root, node::NodeManager* node_manager,
...
node::ExprListNode* rows = node_manager->MakeExprList();
for (auto row : root->rows()->rows()) {
CHECK_TRUE(nullptr != row, common::kSqlError, "Un-support insert statement with null row")
node::ExprListNode* row_values;
CHECK_STATUS(ConvertExprNodeList(row->values(), node_manager, &row_values))
for (auto expr : row_values->children_) {
CHECK_TRUE(nullptr != expr &&
(node::kExprPrimary == expr->GetExprType() || node::kExprParameter == expr->GetExprType()),
common::kSqlError, "Un-support insert statement with un-const value")
}
rows->AddChild(row_values);
}
...
However, the SQLClusterRouter only take the first row put build a default_map.
// src/sdk/sql_cluster_router.cc
SQLClusterRouter::GetInsertInfo(const std::string& db, const std::string& sql, ::hybridse::sdk::Status* status,
...
*default_map = GetDefaultMap(*table_info, column_map,
dynamic_cast<::hybridse::node::ExprListNode*>(insert_stmt->values_[0]), str_length);
if (!(*default_map)) {
status->msg = "get default value map of " + sql + " failed";
LOG(WARNING) << status->msg;
return false;
}
...
I am not family with C++, so i am not sure if the bug related to the code i find above.
Possible Implementation
I think it is not hard to fix SQLClusterRouter::GetInsertInfo, however when coming to error handling, the behavior after a row failed to be inserted should be discussed before fix the bug.
@jingchen2222
@Shouren @imotai It's true. Execute Insert statement with multi-rows has been supported. We at least should give an Explicitly message to inform users or support this feature. We will fix this issue in a later version.
@Shouren Thanks for your nice advice.
The GetInsertRow function you've mentioned above, is used by single-row insertion with placeholders. For example, we can insert multi-row via using JDBC Statement.
PreparedStatement impl4 = router.getInsertPreparedStmt(dbname,""insert into tsql1010 values(?, ?, ?, 'zhenzhou', 5);");
impl4.close();
Assert.assertTrue(impl4.isClosed());
PreparedStatement impl5 = router.getInsertPreparedStmt(dbname, insert);
impl5.setLong(1, 1004);
impl5.setDate(2, d5);
impl5.setString(3, "henan");
Similarly, we have GetInsertRows function in sql_cluster_router.cc for multi-rows insertion with placeholders(parameters)
std::shared_ptr<SQLInsertRows> SQLClusterRouter::GetInsertRows(const std::string& db, const std::string& sql,
::hybridse::sdk::Status* status) {
//...
}
And also, we support multi-rows insertion with placeholders via JDBC Statement. For example,
String insertPlaceholder = "insert into tsql1010 values(?, 2, 'taiyuan', 2.0);";
PreparedStatement impl = router.getInsertPreparedStmt(dbname, (String) batchData[i][0]);
Object[][] datas1 = (Object[][]) batchData[i][1];
for (int j = 0; j < datas1.length; j++) {
// code ignore ...
impl.addBatch();
}
// code ignore ...
impl.executeBatch();
However, we still fail to support the normal multi-rows insert statement like
INSERT INTO user VALUES('user_0', 1628689181169), ('user_1', 1628689181169), ('user_2', 1628689181169);
This might require us to modify the logic as below:
bool SQLClusterRouter::ExecuteInsert(const std::string& db, const std::string& sql, ::hybridse::sdk::Status* status) {
// code ignore ...
std::shared_ptr<SQLInsertRow> row = std::make_shared<SQLInsertRow>(
table_info, ::openmldb::sdk::ConvertToSchema(table_info), default_map, str_length);
if (!row) {
status->msg = "fail to parse row from sql " + sql;
LOG(WARNING) << status->msg;
return false;
}
if (!row->Init(0)) {
status->msg = "fail to encode row for table " + table_info->name();
LOG(WARNING) << status->msg;
return false;
}
if (!row->IsComplete()) {
status->msg = "insert value isn't complete";
LOG(WARNING) << status->msg;
return false;
}
// ignore ...
return PutRow(table_info->tid(), row, tablets, status);
}
however when coming to error handling, the behaviour after a row failed to be inserted should be discussed before fix the bug.
It's really a problem in OpenMLDB since it does not support transaction yet. Thanks again.
Multi-rows insertion SQL will be parsed into a set of rows. Any error, which comes before the PutRow stage, can halt the insertion immediately. For instance, the execution stops when SQL parse errors and no rows will be put into storage.
While, when the error comes to the PutRow stage, we can't revert the whole execution. In that case, there might have an unexpected number of rows in storage.
This issue will be closed once #398 closed.
Similarly, we have
GetInsertRowsfunction insql_cluster_router.ccfor multi-rows insertion with placeholders(parameters)std::shared_ptr<SQLInsertRows> SQLClusterRouter::GetInsertRows(const std::string& db, const std::string& sql, ::hybridse::sdk::Status* status) { //... }
I discover this function when trying to fix a duplicate call to hybridse::plan::PlanAPI::CreatePlanTreeFromScript (An issue may be created later to discuss). Nice to see there is a function to support multi-row insertion.
however when coming to error handling, the behaviour after a row failed to be inserted should be discussed before fix the bug.
It's really a problem in OpenMLDB since it does not support
transactionyet. Thanks again. Multi-rows insertion SQL will be parsed into a set of rows. Any error, which comes before thePutRowstage, can halt the insertion immediately. For instance, the execution stops when SQL parse errors and no rows will be put into storage.
I think transaction it not a problem as long as people do not have an expectation of transaction when a INSERT statement with multi-rows is being executed.
While, when the error comes to the
PutRowstage, we can't revert the whole execution. In that case, there might have an unexpected number of rows in storage.
I think it is an acceptable result with a error message contain the number of success and failure.
I think it is an acceptable result with a error message contain the number of success and failure.
Agree.
@Shouren On top of the above discussions, we had better redesign the error system including ERROR_CODE, ERROR_MSG_PATTERN, TRACE_MSG for the sake of readability.
Many users might feel confused by the error message.
https://github.com/4paradigm/OpenMLDB/issues/406 will follow the problem.