function ensureConnectionCallback(runner) {
  runner.client.emit('start', runner.builder);
  runner.builder.emit('start', runner.builder);
  const sql = runner.builder.toSQL();

  if (runner.builder._debug) {
    runner.client.logger.debug(sql);
  }

  if (Array.isArray(sql)) {
    return runner.queryArray(sql);
  }
  return runner.query(sql);
}

function ensureConnectionStreamCallback(runner, params) {
  try {
    const sql = runner.builder.toSQL();

    if (Array.isArray(sql) && params.hasHandler) {
      throw new Error(
        'The stream may only be used with a single query statement.'
      );
    }

    return runner.client.stream(
      runner.connection,
      sql,
      params.stream,
      params.options
    );
  } catch (e) {
    params.stream.emit('error', e);
    throw e;
  }
}

module.exports = {
  ensureConnectionCallback,
  ensureConnectionStreamCallback,
};
