## The new query is in sf_utils.r
## This is the *OLD* query  kept for archiving purposes.   get rid soon
# ---------------------------------------------------- 

###
if (FALSE)
sfQry_OLD_as_of_20150721 <- function(qry
                , connex=sfGetCon()
                , wh=warehouse
                # , warehouse=getOption("snowflake_currentwh", getOption("snowflake_defaultwh"))
                , warehouse=getSnowflakeWH()
                , to.dt=exists("as.data.table")
                , refresh_con_if_expired = TRUE
                , fail_on_query_error = TRUE
                , update_last_ran = grepl("SELECT|UPDATE|INSERT", qry, ignore.case=TRUE)
                , check_warehouse=FALSE

                , verbose.max.width=getOption("width", 80) * 0.8
                , verbose.max.lines=22L
                , verbose.add.dots=nchar(qry) < 5000
                , verbose.shortCircuit=TRUE
                , verbose.indentAnd=grepl("\\bOR\\b", qry)
                , verbose.indentOr=FALSE
                , verbose=TRUE
                , verbose.key=verbose
                , verbose.firstOfMonth=TRUE

                ## Used only for details updating
                , size=NULL
                , type=NULL

                , ...
) {

  ## Make sure package is loaded
  require(RODBC)

  if (length(qry) != 1)
    stop ("qry has length ", length(qry), ". It should have length 1.  Use sapply or similar")


  if (!inherits(connex, "RODBC"))
    stop ("connex is not of type 'RODBC'")

  ## Cleanup warehouse argument
  missing_wh <- missing(wh) && missing(warehouse)
  wh %<>% .sf_clean_name

  if (!missing_wh && !is.null(wh)) {
    if (!identical(toupper(wh), getSnowflakeWH(refresh=FALSE)))
      setSnowflake(wh=wh)
  }

  ## TODO - wh - check, turn on, etc. 
  ## ...... wh ...... ?? 
  if (check_warehouse) {
      s.t({
        current_wh <- getSnowflakeWH(connex=connex, refresh=TRUE, verbose=FALSE)
        if (!is.null(wh) && isTRUE(wh != current_wh)) {
          message (" %% reminder to RICK -- something about current_wh in sfQry()  %%  ")
          setSnowflake(wh=wh, connex=connex)
          current_wh <- getSnowflakeWH(connex=connex, refresh=TRUE, verbose=FALSE)
          if (current_wh != wh)
            stop ("warehouse did not take.\nCurrent is '", current_wh, "'\nExpected is '", wh, "'\n")
        }
      }, title = "Checking Warehouse")
  } else {
    current_wh <- getSnowflakeWH(refresh=FALSE, verbose=FALSE)
  }

  if (verbose) {
     hr <- paste0(pasteR(verbose.max.width+3), "\n")
     cat("\n\n\t    Running query on snowflake using warehouse '", ifelseNULL(wh, current_wh, wh), "'. [Began at ", timeStamp(frmt="%R %p") ,"] \n   ", hr
        , verboseQry(qry, max.lines=verbose.max.lines, max.width=verbose.max.width, shortCircuit.ifendl.detected=verbose.shortCircuit, indentAnd=verbose.indentAnd, indentOr=verbose.indentOr, add.dots=verbose.add.dots)
        , "\n   ", hr, sep="")
  }

  ## DEBUGGING
  browser(expr=inDebugMode("sfQry"), text="in sfQry() before executing query")

  ## SCRATCH CODE.
  ## TODO 2015-05-18 Attempt to ship query without waiting for response, so we can increase WH size automagically
          if (FALSE) {
            sfShowTables()
            rr <- odbcQuery(connex, qry)
            rt <- sqlGetResults(connex)
          }


  ## EXECUTE QUERY -- OR TRY TO, AT LEAST
  ret <- try(sqlQuery(connex, qry, stringsAsFactors=FALSE))
  last_ran <- now()  ## force last_ran to evaluate
  force(last_ran)

  ## Update the last_ran timestamp
  if (update_last_ran)
    sfUpdateWH_QryLastRan(name=current_wh, size=size, type=type, last_ran=last_ran)

  ## IF con IS EXPIRED, REFRESH AND TRY AGAIN
  pat.expired <- c("first argument is not an open RODBC channel", "Authentication token has expired") %>% regOr
  if (refresh_con_if_expired) {
    if (isErr(ret) || (is.character(ret) && any(grepl(pat.expired, ret)))) {
      message("connex was expired, refreshing then trying the query again")
      connex <- sfGetCon(refresh=TRUE)
      ret <- sqlQuery(connex, qry, stringsAsFactors=FALSE)
    }
  }

  ## CHECK FOR ERROR
  if (is.character(ret) && length(ret) < 5 && any(grepl("error", ret, ignore.case=TRUE)))
    return(sfErrorParse(qres=ret, qry=qry, fail_on_query_error=fail_on_query_error))
  ## ELSE, NO ERROR, continue. 

  ## Convert to data.table; wrap in try() so as to not fail after having waited for the query to run
  try (ret <- as.data.table(ret))
  try (setnamestolower(ret))
  
  return(ret)
}
