Skip to content

Commit 30af427

Browse files
committed
Generalization: Allow setting condition for running SQL commands
If a condition is set with "if_has_rows", the SQL command in "if_has_rows" will be run and only if that returns any rows, the main sql command is run. This check happens only in "append" mode, in "create" mode the command is always run. To be used with something like "SELECT 1 FROM some_table LIMIT 1" to check whether the table has any rows (for instance an expire table).
1 parent a969ab0 commit 30af427

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

src/gen/osm2pgsql-gen.cpp

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,9 @@ class genproc_t
373373
bool const transaction = luaX_get_table_bool(lua_state(), "transaction",
374374
1, "Argument #1", false);
375375

376+
std::string const if_has_rows = luaX_get_table_string(
377+
lua_state(), "if_has_rows", 1, "Argument #1", "");
378+
376379
std::vector<std::string> queries;
377380
if (transaction) {
378381
queries.emplace_back("BEGIN");
@@ -403,10 +406,21 @@ class genproc_t
403406
queries.emplace_back("COMMIT");
404407
}
405408

409+
pg_conn_t const db_connection{m_conninfo};
410+
411+
if (m_append && !if_has_rows.empty()) {
412+
auto const result = db_connection.exec(if_has_rows);
413+
if (result.num_tuples() == 0) {
414+
log_info("Not running SQL command: {} (no rows in "
415+
"condition result).",
416+
description);
417+
return 0;
418+
}
419+
}
420+
406421
log_info("Running SQL commands: {}.", description);
407422

408423
util::timer_t timer_sql;
409-
pg_conn_t const db_connection{m_conninfo};
410424
for (auto const &query : queries) {
411425
log_debug("Running sql: {}", query);
412426
db_connection.exec(query);

0 commit comments

Comments
 (0)