bool SqlDatabaseManager::GetNeighbors(const Model& model, 
                                      const string& distance_function_name, 
                                      const int num_neighbors,
                                      vector<pair<Model*, double> >* neighbors) const {
  if (neighbors == NULL) return false;
  Table results;
  stringstream query_text;                  
  query_text << "SELECT * FROM get_saved_neighbors('" << model.ModelName()
             << "','" << distance_function_name 
             << "'," << num_neighbors << ");";
  if (!database_.Query(query_text.str(), &results)) return false;
  int distance_column;
  if (!results.GetColumnIndex("distance", &distance_column)) return false;
  // Turn each database row into a Model.
  LoadModelFunctor load_model_functor(results, model_root_);
  double distance;
  const int num_rows = results.NumRows();
  neighbors->reserve(num_rows);
  for (int row = 0; row < num_rows; ++row) {
    Model* neighbor_model = model_allocator_->Get();
    if (!load_model_functor(neighbor_model, row) ||
        !results.GetField(distance_column, row, &distance)) return false;
    neighbors->push_back(make_pair(neighbor_model, distance));
  }
  return true;
}
bool SqlDatabaseManager::GetAlignment(const Model& source,
                                      const Model& dest, 
                                      const string& alignment_method_name, 
                                      float alignment[16]) const {
  Table results;
  stringstream query_text;                  
  query_text << "SELECT get_alignment('" << source.ModelName() << "','" 
             << dest.ModelName() << "','" << alignment_method_name << "')";
  if (!database_.Query(query_text.str(), &results)) return false;
  vector<float> alignment_vector;
  alignment_vector.reserve(16);
  if (results.NumColumns() == 0 || results.NumRows() == 0) return false;
  if (!results.GetField(0, 0, &alignment_vector)) return false;
  for (int i = 0; i < 16; ++i) alignment[i] = alignment_vector[i];
  return true;
}
/*! This is a helper to filter out duplicate code from the GetXXXList functions.
    The name_type is assumed to be the name of the table, and the column in the table
    is assumed to be "<name_type>_name".*/
static bool NameList(const string& name_type, 
                     const DatabaseConnection& database,
                     vector<string>* list) {
  if (list == NULL) return false;
  Table results;
  if (!database.Query("SELECT * FROM get_" + name_type + "_names();", 
      &results)) return false;
  const int num_rows = results.NumRows();
  list->reserve(num_rows);
  int name_column;
  if (!results.GetColumnIndex(name_type + "_name", &name_column)) return false;
  string name;
  for (int row = 0; row < num_rows; ++row) {
    if (!results.GetField(name_column, row, &name)) return false;
    list->push_back(name);
  }
  return true;
}
bool SqlDatabaseManager::ModelList(vector<Model*>* model_list, 
								   FilterList::FilterType filter) const {
  if (model_list == NULL) return false;
  Table results;
  if (!database_.Query("SELECT * FROM get_models() " + 
						FilterList::GetWhereClause(filter) + ";", 
						&results)) return false;
  // Turn each database row into a Model.
  LoadModelFunctor load_model_functor(results, model_root_);
  const int num_rows = results.NumRows();
  model_list->reserve(num_rows);
  for (int row = 0; row < num_rows; ++row) {
    Model* model = model_allocator_->Get();
	if (!load_model_functor(model, row)){
		return false;
	}
    model_list->push_back(model);
  }
  return true;
}
bool SqlDatabaseManager::GetGrasps(const Model& model, 
                                   const string& hand_name, 
                                   vector<Grasp*>* grasp_list) const {
  if (grasp_list == NULL) return false;
  Table results;
  PROF_START_TIMER(GET_GRASPS_SQL);
  if (!database_.Query("SELECT * FROM get_grasps('" + model.ModelName() + 
                       "','" + hand_name + "');", &results)) 
    return false;
  PROF_STOP_TIMER(GET_GRASPS_SQL);
  // Get the column indices for the columns we care about.
  int pregrasp_joints_column, grasp_joints_column, 
      pregrasp_position_column, grasp_position_column,
      grasp_id_column, epsilon_quality_column, volume_quality_column,
	  grasp_contacts_column, grasp_source_name_column;
  PROF_START_TIMER(GET_GRASPS_GETCOLUMN);
  if (!results.GetColumnIndex("grasp_pregrasp_joints", &pregrasp_joints_column) ||
      !results.GetColumnIndex("grasp_grasp_joints", &grasp_joints_column) ||
      !results.GetColumnIndex("grasp_pregrasp_position", 
                              &pregrasp_position_column) ||
      !results.GetColumnIndex("grasp_grasp_position", &grasp_position_column) ||
      !results.GetColumnIndex("grasp_id", &grasp_id_column) ||
      !results.GetColumnIndex("grasp_epsilon_quality", &epsilon_quality_column) ||
      !results.GetColumnIndex("grasp_volume_quality", &volume_quality_column) ||
	  !results.GetColumnIndex("grasp_contacts", &grasp_contacts_column) ||
	  !results.GetColumnIndex("grasp_source_name", &grasp_source_name_column))
    return false;
	PROF_STOP_TIMER(GET_GRASPS_GETCOLUMN);
  // Turn each database row into a Grasp.
  vector<double> pregrasp_joints, grasp_joints, 
      pregrasp_position, grasp_position, grasp_contacts;
  int grasp_id;
  string grasp_source_name;
  double epsilon_quality, volume_quality;
  const int num_rows = results.NumRows();
  grasp_list->reserve(num_rows);
  for (int row = 0; row < num_rows; ++row) {
    grasp_list->push_back(grasp_allocator_->Get());
    Grasp& grasp = *(grasp_list->back());

	pregrasp_joints.clear();
	pregrasp_position.clear();
	grasp_joints.clear();
	grasp_position.clear();

	PROF_START_TIMER(GET_GRASPS_GETFIELD);
    if (!results.GetField(pregrasp_joints_column, row, &pregrasp_joints) || 
        !results.GetField(grasp_joints_column, row, &grasp_joints) || 
        !results.GetField(pregrasp_position_column, row, &pregrasp_position) ||
        !results.GetField(grasp_position_column, row, &grasp_position) || 
        !results.GetField(grasp_id_column, row, &grasp_id) ||
        !results.GetField(epsilon_quality_column, row, &epsilon_quality) ||
        !results.GetField(volume_quality_column, row, &volume_quality) ||
		!results.GetField(grasp_contacts_column, row, &grasp_contacts) ||
		!results.GetField(grasp_source_name_column, row, &grasp_source_name))
      return false;
	PROF_STOP_TIMER(GET_GRASPS_GETFIELD);
    grasp.SetSourceModel(model);
    grasp.SetHandName(hand_name);
    grasp.SetEpsilonQuality(epsilon_quality);
    grasp.SetVolumeQuality(volume_quality);
    grasp.SetGraspId(grasp_id);

	pregrasp_joints.erase(pregrasp_joints.begin());
	pregrasp_position.erase(pregrasp_position.begin());
	grasp_joints.erase(grasp_joints.begin());
	grasp_position.erase(grasp_position.begin());
    
	grasp.SetGraspParameters(pregrasp_joints, 
                             pregrasp_position, 
                             grasp_joints, 
                             grasp_position);
	grasp.SetContacts(grasp_contacts);
	grasp.SetPregraspJoints(pregrasp_joints);
	grasp.SetPregraspPosition(pregrasp_position);
	grasp.SetFinalgraspJoints(grasp_joints);
	grasp.SetFinalgraspPosition(grasp_position);
	grasp.SetSource(grasp_source_name);
  }
  return true;
}