function varargout = resultsToCell(resultSet)
% RESULTSTOCELL  Converts a java.sql.ResultSet to a cell array
%
% DEPRECATED! Use utils.mysql.execute instead!
%
% CALL:
%
%   [results, colnames] = utils.jmysql.resultsToCell(rs);
%
% INPUTS:
%
%   rs       - a java.sql.ResultSet like that returned from utils.jmysql.query
%
% OUTPUTS:
%
%   results  - a cell array of results
%   colnames - a cell array of column names
%
% VERSION: $Id: resultsToCell.m,v 1.1 2009/07/27 19:46:21 hewitson Exp $
%

  warning('!!! deprecated. use utils.mysql.execute instead');
  
  if ~isa(resultSet, 'java.sql.ResultSet')
    error('### first argument should be a java.sql.ResultSet');
  end

  % get results into a cell array
  md = rs.getMetaData();
  nc = md.getColumnCount();
  row = 1;
  while rs.next()
    for kk = 1:nc
      % convert to matlab objects
      rows{row, kk} = java2matlab(rs.getObject(kk));
    end
    row = row + 1;
  end
      
  % get column names
  names = cell(1, nc);
  for kk = 1:nc
    names{kk} = char(md.getColumnName(kk));
  end
      
  % assign output
  switch nargout
    case 0
      varargout{1} = rows;
    case 1
      varargout{1} = rows;
    case 2
      varargout{1} = names;
      varargout{2} = rows;
    otherwise
      error('### too many output arguments');
  end      
end


function val = java2matlab(val)
  % matlab converts all base types. just add a conversion for datetime columns
  switch class(val)
    case 'java.sql.Timestamp'
      val = time(plist('time', char(val), 'timezone', 'UTC'));
  end
end
