<commit_before>var _ = require('lodash');
var bluebird = require('bluebird');
var util = require('./util');

module.exports = function resolveQueryObjects(config, knexInst) {
  var pendingQueries = [];

  _.forIn(config, function(entries, table) {
    entries = config[table] = util.asArray(entries);

    entries.forEach(function(entry, index) {
      _.forIn(entry, function(colValue, colName, record) {
        if (isQueryObject(colValue)) {
          var constraints = colValue;
          pendingQueries.push(
            knexInst(constraints.from)
              .where(constraints.where)
              .then(function(result) {
                if (result.length > 1) {
                  var where = JSON.stringify(constraints);
                  throw new Error(where + ' matches >1 possible FK!');
                } else {
                  record[colName] = result[0].id;
                }
              })
          );
        }
      });
    });
  });
  return pendingQueries;
};

function isQueryObject(value) {<commit_msg>Refactor executeFkQueries<commit_after>var _ = require('lodash');
var bluebird = require('bluebird');
var util = require('./util');
var knex;

module.exports = function resolveQueryObjects(config, knexInst) {
  var pendingQueries = [];
  knex = knexInst;

  _.forEach(config, function handleTable(entries) {
    util.asArray(entries).forEach(function (entry) {
      var promises = _.map(entry, resolveSingleValue);
      pendingQueries = pendingQueries.concat(promises);
    });
  });
  return pendingQueries;
};

function resolveSingleValue(colValue, colName, entry) {
  if (isQueryObject(colValue)) {
    return knex(colValue.from)
      .where(colValue.where)
      .then(function(result) {
        if (result.length > 1) {
          var where = JSON.stringify(colValue);
          throw new Error(where + ' matches >1 possible FK!');
        } else {
          entry[colName] = result[0].id;
        }
      });
  }
}

function isQueryObject(value) {
{'fraction_non_alphanumeric': 0.1303472571716155, 'fraction_numerical': 0.003019627579265224, 'mean_word_length': 2.5436720142602494, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5077447', 'n_tokens_mistral': 588, 'n_tokens_neox': 572, 'n_words': 115}