Skip to content

Commit 71a1df7

Browse files
committed
Generalization: Allow list of SQL commands in run_sql() command
The run_sql() command now can have either a single SQL statement in the `sql` field or a list of SQL commands. The new `transaction` field can be set to `true` to wrap the SQL commands in BEGIN/COMMIT.
1 parent 46bb159 commit 71a1df7

File tree

1 file changed

+39
-5
lines changed

1 file changed

+39
-5
lines changed

src/gen/osm2pgsql-gen.cpp

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -368,15 +368,49 @@ class genproc_t
368368

369369
std::string const description =
370370
luaX_get_table_string(lua_state(), "description", 1, "Argument #1");
371-
std::string const sql =
372-
luaX_get_table_string(lua_state(), "sql", 1, "Argument #1");
373371

374-
log_debug("Running SQL command: {}.", description);
372+
bool const transaction = luaX_get_table_bool(lua_state(), "transaction",
373+
1, "Argument #1", false);
374+
375+
std::vector<std::string> queries;
376+
if (transaction) {
377+
queries.emplace_back("BEGIN");
378+
}
379+
380+
lua_getfield(lua_state(), 1, "sql");
381+
int const ltype = lua_type(lua_state(), -1);
382+
if (ltype == LUA_TSTRING) {
383+
queries.emplace_back(lua_tostring(lua_state(), -1));
384+
} else if (ltype == LUA_TTABLE) {
385+
if (!luaX_is_array(lua_state())) {
386+
throw std::runtime_error{
387+
"Table in 'sql' field must be an array."};
388+
}
389+
luaX_for_each(lua_state(), [&]() {
390+
if (lua_type(lua_state(), -1) != LUA_TSTRING) {
391+
throw std::runtime_error{
392+
"Table in 'sql' field must only contain strings."};
393+
}
394+
queries.emplace_back(lua_tostring(lua_state(), -1));
395+
});
396+
} else {
397+
throw std::runtime_error{
398+
"Argument #1 must contain a 'sql' string or table field."};
399+
}
400+
401+
if (transaction) {
402+
queries.emplace_back("COMMIT");
403+
}
404+
405+
log_debug("Running SQL commands: {}.", description);
375406

376407
util::timer_t timer_sql;
377408
pg_conn_t const db_connection{m_conninfo};
378-
db_connection.exec(sql);
379-
log_debug("SQL command took {}.",
409+
for (auto const &query : queries) {
410+
log_debug("Running sql: {}", query);
411+
db_connection.exec(query);
412+
}
413+
log_debug("SQL commands took {}.",
380414
util::human_readable_duration(timer_sql.stop()));
381415

382416
return 0;

0 commit comments

Comments
 (0)