% Execute the query built on the query panel
%
% M Hewitson
%
% $Id: cb_executeQuery.m,v 1.3 2011/04/08 08:56:36 hewitson Exp $
%
function cb_executeQuery(varargin)
  
  
  % Get connection
  mainfig  = varargin{end};
  conn     = mainfig.connection;
  if isempty(conn)
    error('### Please connect to a database first.');
  end
  
  % Get Selected fields
  fieldList = findobj(mainfig.handle, 'Tag', 'fieldsList');
  fieldsStr = get(fieldList, 'String');
  vals      = get(fieldList, 'Value');
  fields    = fieldsStr(vals)';
  
  
  % Get query
  h = findobj(mainfig.handle, 'Tag', 'queryDisplayTxt');
  q = get(h, 'String');
  
  try
    curs = exec(conn, q);
    curs = fetch(curs);
    results = curs.Data;
    close(curs);
  catch
    warning('!!! Unable to execute query %s', q)
    warning('!!! Server returned: %s', curs.Message);
    results = {};
  end
  
  if ~isempty(results)
    if strcmp(results{1}, 'No Data')
      errordlg('Query returned no results.', 'Query Empty');
      return
    else
      whos('results')
      whos('fields')
      repogui2.sqlResultsGUI(results, fields, q);
    end
  else
    error('### Unable to execute query');
  end
  
end
