I am using iojs and node-mysql. This is my first foray into async server-side programming. It is essentially a batch job: run it all once, exit. I am specifically trying to do this on a table full of revisions:
For each document edited in the past year; for each revision to that document made in the past year; get the prior revision and diff its content with the current revision.
So, I am using the results of one query (for each document) to fire off an arbitrary number of additional queries (for each revision) that must themselves recurse (get the prior revision).
I can't figure out how to close the database connection. Near as I can tell, the recursion is the confounding factor: If I remove that from the code, then I can close the db connection. But I need to recurse.
Here is a minimal example (assume requires and config are OK) that accomplishes the behavior I'm seeing in my program.
var con = mysql.createConnection(db_config);
con.connect();
con.query('SELECT field_2 FROM test_table', function(err, rows) {
if (err) throw err;
rows.forEach(function(row) {
second_query(row.field_2);
});
// using this here works if there is no recursion, even if second_query runs long
// using this here does not work if there is recursion
// removing this allows the program to run to completion, but the event loop never exits
con.end()
});
function second_query(key) {
con.query('SELECT * FROM test_table_2 WHERE field_2 > ?', [key], function(err, rows) {
if (err) throw err;
if (rows.length > 0) {
rows.forEach(function(row) {
console.log(row.field_2);
});
second_query(key + 1);
}
});
}
I have tried very hard to solve the problem by registering database queries in an accumulator and decrementing the accumulator as each query ends, but that hasn't produced predictable success yet and it makes the code painful to work with.