# Copyright (c) Microsoft Corporation.  All rights reserved.
#
# FUNCTIONS
#    Unit tests for RxOdbcData and tests for RxTerdata constructor
#
############################################################################################

".rxSqliteConnectionStringFromFile" <- function()
{
    if (exists("rxSqliteConnectionStringFromFile", globalenv()))
        get("rxSqliteConnectionStringFromFile", globalenv())
    else
        RevoScaleR:::rxSqliteConnectionStringFromFile
}

test.RxOdbcData.invalid.arg.table <- function()
{
    checkException(RxOdbcData(table = NA_character_), silent = TRUE)
    checkException(RxOdbcData(table = ""), silent = TRUE)
    checkException(RxOdbcData(table = letters), silent = TRUE)
    checkException(RxOdbcData(table = 1), silent = TRUE)
}

test.RxOdbcData.valid.arg.table <- function()
{
    checkTrue(validObject(RxOdbcData(table = "mytable")))
}

test.RxOdbcData.invalid.arg.sqlQuery <- function()
{
    checkException(RxOdbcData(sqlQuery = NA_character_), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = ""), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = letters), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = 1), silent = TRUE)
}

test.RxOdbcData.valid.arg.sqlQuery <- function()
{
    checkTrue(validObject(RxOdbcData(sqlQuery = "SELECT * FROM mytable")))
}

test.RxOdbcData.invalid.arg.server <- function()
{
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              server = NA_character_), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              server = ""), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              server = letters), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              server = 1), silent = TRUE)
}

test.RxOdbcData.valid.arg.server <- function()
{
    checkTrue(validObject(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                                     server = "myserver")))
}

test.RxOdbcData.invalid.arg.dsn <- function()
{
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              dsn = NA_character_), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              dsn = ""), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              dsn = letters), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              dsn = 1), silent = TRUE)
}

test.RxOdbcData.valid.arg.dsn <- function()
{
    checkTrue(validObject(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                                     dsn = "mydsn")))
}

test.RxOdbcData.invalid.arg.user <- function()
{
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              user = NA_character_), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              user = ""), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              user = letters), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              user = 1), silent = TRUE)
}

test.RxOdbcData.valid.arg.user <- function()
{
    checkTrue(validObject(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                                     user = "me")))
}

test.RxOdbcData.invalid.arg.password <- function()
{
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              password = NA_character_), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              password = ""), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              password = letters), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              password = 1), silent = TRUE)
}

test.RxOdbcData.valid.arg.password <- function()
{
    checkTrue(validObject(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                                     password = "opensesame")))
}

test.RxOdbcData.invalid.arg.connectionString <- function()
{
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              connectionString = NA_character_), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              connectionString = ""), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              connectionString = letters), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              connectionString = 1), silent = TRUE)
}

test.RxOdbcData.valid.arg.connectionString <- function()
{
    checkTrue(validObject(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                                     connectionString = "CONNECTION STRING")))
}

test.RxOdbcData.invalid.arg.returnDataFrame <- function()
{
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              returnDataFrame = NULL), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              returnDataFrame = NA), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              returnDataFrame = 1), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              returnDataFrame = c(TRUE, FALSE)), silent = TRUE)
}

test.RxOdbcData.valid.arg.returnDataFrame <- function()
{
    checkTrue(validObject(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                                     returnDataFrame = TRUE)))
    checkTrue(validObject(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                                     returnDataFrame = FALSE)))
}

test.RxOdbcData.invalid.arg.stringsAsFactors <- function()
{
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              stringsAsFactors = NULL), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              stringsAsFactors = NA), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              stringsAsFactors = 1), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              stringsAsFactors = c(TRUE, FALSE)), silent = TRUE)
}

test.RxOdbcData.valid.arg.stringsAsFactors <- function()
{
    checkTrue(validObject(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                                     stringsAsFactors = TRUE)))
    checkTrue(validObject(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                                     stringsAsFactors = FALSE)))
}

test.RxOdbcData.invalid.arg.rowsPerRead <- function()
{
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              rowsPerRead = NULL), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              rowsPerRead = NA_integer_), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              rowsPerRead = "a"), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              rowsPerRead = 0), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              rowsPerRead = Inf), silent = TRUE)
    checkException(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                              rowsPerRead = 1:2), silent = TRUE)
}

test.RxOdbcData.valid.arg.rowsPerRead <- function()
{
    for (i in c(1L, 10L, 100L))
    {
        checkTrue(validObject(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                                         rowsPerRead = i), test = TRUE))
    }
    for (i in c(1, 10, 100))
    {
        checkTrue(validObject(RxOdbcData(sqlQuery = "SELECT * FROM mytable",
                                         rowsPerRead = i), test = TRUE))
    }
}

"test.RxOdbcData.args.returnDataFrame" <- function()
{
	 rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()

    conString <-
      try(rxSqliteConnectionStringFromFile(file.path(rxGetOption("sampleDataDir"),
                                                    "claims.sqlite")),
          silent = TRUE)

    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])
        
	claimsQuery <- "SELECT * FROM claims"
    odbcDS1 <-
      RxOdbcData(sqlQuery = claimsQuery,
                 connectionString = conString,
				 returnDataFrame = TRUE)
			
	rxOpen(odbcDS1) 
	myData1 <- rxReadNext(odbcDS1) 
	rxClose(odbcDS1)						
			
	checkEquals(class(myData1), "data.frame")
	
    odbcDS2 <-
      RxOdbcData(sqlQuery = claimsQuery,
                 connectionString = conString,
				 returnDataFrame = FALSE)
    claimsList <- rxDataStep(odbcDS1)
	
	rxOpen(odbcDS2) 
	myData2 <- rxReadNext(odbcDS2) 
	rxClose(odbcDS2)		
	checkEquals(class(myData2), "list")
	
	checkEquals(myData1$number, myData2$number)
}

"test.RxOdbcData.args.sqlQuery.select.all" <- function()
{
    rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()
    claimsTextFile <- file.path(rxGetOption("sampleDataDir"), "claims.txt")
    expect <-
      read.csv(claimsTextFile, header = TRUE,
               colClasses =
               c("integer", "character", "character", "character", "numeric",
                 "numeric"),
               col.names =
               c("RowNum", "age", "car_age", "type", "cost", "number"))
    conString <-
      try(rxSqliteConnectionStringFromFile(file.path(rxGetOption("sampleDataDir"),
                                                    "claims.sqlite")),
          silent = TRUE)

    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])
        
    odbcDS <-
      RxOdbcData(sqlQuery = "SELECT * FROM claims",
                 connectionString = conString)
    xdfFileName <- tempfile( pattern = ".rxOdbc1", fileext = ".xdf")
    xdfDS <- RxXdfData(xdfFileName)
    rxImport(odbcDS, xdfDS, overwrite = TRUE, reportProgress = 0)
    received <- rxReadXdf(xdfFileName, reportProgress = 0)
    checkIdentical(received, expect)
    file.remove(xdfFileName)
}

"test.RxOdbcData.args.sqlQuery.select" <- function()
{
    #DEACTIVATED("Defect 6030657:rxLinMod(data=RxOdbcData) does not work if the order of the selected fields is different from those in the database.")
    
    databaseName <- file.path(rxGetOption("sampleDataDir"), "claims.sqlite")
    rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()
    conString <- try(rxSqliteConnectionStringFromFile(databaseName), silent = TRUE)
    if (inherits(conString, "try-error")) DEACTIVATED(strsplit(conString, "\n")[[1]][2])
    
    ## modeling with different data specification
    odbcDS <- RxOdbcData(connectionString = conString, colClasses = c(number = "factor"), 
        table = "claims")                                                   #results correct
    linModObj1 <- rxLinMod(cost ~ number, data = odbcDS)
    
    odbcDS <- RxOdbcData(connectionString = conString, colClasses = c(number = "factor"), 
        sqlQuery = "select * from claims")                                  #results correct
    linModObj2 <- rxLinMod(cost ~ number, data = odbcDS)
    
    odbcDS <- RxOdbcData(connectionString = conString, colClasses = c(number = "factor"),
        sqlQuery = "SELECT cost, number FROM claims")                       #results correct
    linModObj3 <- rxLinMod(cost ~ number, data = odbcDS)
    
    odbcDS <- RxOdbcData(connectionString = conString, colClasses = c(number = "factor"),
        sqlQuery = "SELECT tbl.cost, tbl.number AS number FROM claims tbl") #results correct
    linModObj4 <- rxLinMod(cost ~ number, data = odbcDS)
    
    odbcDS <- RxOdbcData(connectionString = conString, colClasses = c(number = "factor"),
        sqlQuery = "SELECT number, cost FROM claims")                       #results wrong
    linModObj5 <- rxLinMod(cost ~ number, data = odbcDS)
    
    ## check results
    dontmatch <- c("params")
    domatch <- setdiff(names(linModObj1), dontmatch)
    
    sapply(domatch, function(nm) checkIdentical(linModObj1[[nm]], linModObj2[[nm]]))
    sapply(domatch, function(nm) checkIdentical(linModObj1[[nm]], linModObj3[[nm]]))
    sapply(domatch, function(nm) checkIdentical(linModObj1[[nm]], linModObj4[[nm]]))
    sapply(domatch, function(nm) checkIdentical(linModObj1[[nm]], linModObj5[[nm]]))
}

test.RxOdbcData.args.colClasses <- function()
{
    rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()
    claimsTextFile <- file.path(rxGetOption("sampleDataDir"), "claims.txt")
    expect <-
      read.csv(claimsTextFile, header = TRUE,
               colClasses =
               c("integer", "character", "character", "character", "numeric",
                 "numeric"),
               col.names =
               c("RowNum", "age", "car_age", "type", "cost", "number"))
    for (col in c("cost", "number"))
        expect[[col]] <- as.integer(expect[[col]])
    conString <-
      try(rxSqliteConnectionStringFromFile(file.path(rxGetOption("sampleDataDir"),
                                                    "claims.sqlite")),
          silent = TRUE)
    
    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])
        
    odbcDS <-
      RxOdbcData(sqlQuery = "SELECT * FROM claims",
                 connectionString = conString,
                 colClasses =
                 c("RowNum" = "integer", "age" = "character",
                   "car_age" = "character", "type" = "character",
                   "cost" = "integer", "number" = "integer"))
    xdfFileName <- tempfile( pattern = ".rxOdbc2", fileext = ".xdf")
    xdfDS <- RxXdfData(xdfFileName)
    rxImport(odbcDS, xdfDS, overwrite = TRUE, reportProgress = 0)
    received <- rxReadXdf(xdfFileName, reportProgress = 0)
    checkIdentical(received, expect)
    file.remove(xdfFileName)
}

test.RxOdbcData.args.colInfo <- function()
{
    rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()
    claimsTextFile <- file.path(rxGetOption("sampleDataDir"), "claims.txt")
    expect <-
      read.csv(claimsTextFile, header = TRUE,
               colClasses =
               c("integer", "factor", "factor", "factor", "numeric",
                 "numeric"),
               col.names =
               c("RowNum", "age", "car_age", "type", "cost", "number"))
    for (col in c("cost", "number"))
        expect[[col]] <- as.integer(expect[[col]])
        
    attr(expect$age, ".rxDescription") <- "Age of car"
    levels(expect$type) = c("Alpha", "Beta", "Gamma", "Delta")
    conString <-
      try(rxSqliteConnectionStringFromFile(file.path(rxGetOption("sampleDataDir"),
                                                    "claims.sqlite")),
          silent = TRUE)
    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])
        
    odbcDS <-
      RxOdbcData(sqlQuery = "SELECT * FROM claims",
                 connectionString = conString,
                 colInfo =
                 list("RowNum" = list(type = "integer"),
                      "age" =
                        list(type = "factor", description = "Age of car",
                            levels = levels(expect[["age"]])),
                      "car_age" =
                      list(type = "factor", levels = levels(expect[["car_age"]])),
                      "type" =
                        list(type = "factor",
                            levels = c("A", "B", "C", "D"), 
                            newLevels = levels(expect[["type"]])),
                      "cost" = list(type = "integer"),
                      "number" = list(type = "integer")))
    xdfFileName <- tempfile( pattern = ".rxOdbc3", fileext = ".xdf")
    xdfDS <- RxXdfData(xdfFileName)
    rxImport(odbcDS, xdfDS, overwrite = TRUE, reportProgress = 0)
    received <- rxReadXdf(xdfFileName, reportProgress = 0)
    checkIdentical(received, expect)
    file.remove(xdfFileName)
}


######## Import with Direct ODBC datasource	

"test.RxOdbcData.args.fastODBC.stringToFactor" <- function()
{			
    # fix for bug RA-4631
    
    rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()
	conString <- try(
					rxSqliteConnectionStringFromFile(file.path(rxGetOption("unitTestDataDir"), "mortDefaultTiny.sqlite"),
                    useFastRead = FALSE),
					silent = TRUE)
    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])
		
	dsODBC1 <- RxOdbcData(
				sqlQuery = "SELECT * FROM mortDef",
                connectionString = conString,
				useFastRead = FALSE,
				colInfo = list(  isDefault = list(type = "factor", levels = c("No","Yes")))
				)	
							
	dsODBC2 <- RxOdbcData(
				sqlQuery = "SELECT * FROM mortDef",
                connectionString = conString,
				useFastRead = TRUE,
				colInfo = list(  isDefault = list(type = "factor", levels = c("No","Yes")))
				)					
	
	frame1 <- rxImport(dsODBC1, reportProgress = 0)

	frame2 <- rxImport(dsODBC2, reportProgress = 0)
	
    checkEquals(frame1, frame2)
}

"test.RxOdbcData.method.head" <- function()
{
	rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()
    claimsTextFile <- file.path(rxGetOption("sampleDataDir"), "claims.txt")

    conString <-
      try(rxSqliteConnectionStringFromFile(file.path(rxGetOption("sampleDataDir"),
                                                    "claims.sqlite")),
          silent = TRUE)

    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])
        
    odbcDS <-
      RxOdbcData(sqlQuery = "SELECT * FROM claims",
                 connectionString = conString)

	textDS <- RxTextData(claimsTextFile)
	
	odbcHead <- head(odbcDS)
	textHead <- head(textDS)

	# text file has car.age, odbc file has car_age for var name
	checkEquals( odbcHead, textHead, checkNames = FALSE)
}

"test.RxOdbcData.method.names" <- function()
{
	
	rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()

    conString <-
      try(rxSqliteConnectionStringFromFile(file.path(rxGetOption("sampleDataDir"),
                                                    "claims.sqlite")),
          silent = TRUE)

    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])
		
    odbcDS <-
      RxOdbcData(sqlQuery = "SELECT * FROM claims",
                 connectionString = conString)				

	importNames <- names(rxImport(odbcDS, numRows = 3))
	methodNames <- names(odbcDS)
	checkEquals(importNames, methodNames)
	
    conString <-
      try(rxSqliteConnectionStringFromFile(file.path(rxGetOption("sampleDataDir"), "claims.sqlite"), 
		  useFastRead = FALSE),
          silent = TRUE)
    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])
		
    odbcDSslow <-
      RxOdbcData(sqlQuery = "SELECT * FROM claims",
                 connectionString = conString, useFastRead = FALSE)				
	methodNamesSlow <- names(odbcDSslow)
	checkEquals(methodNamesSlow, methodNames)		
}

"test.RxTeradata.args.basic" <- function()
{
    
    # Create a Teradata data source
    TeradataConnString <- "DRIVER=Teradata;DBCNAME=hostname;DATABASE=RevoTestDB;UID=DBUser;PWD=Password;"

    rxTeradataDS <- RxTeradata(sqlQuery = "SELECT * FROM RevoTestDB.claims",
                               connectionString = TeradataConnString)
    
    rxTeradataDS2 <- RxTeradata(sqlQuery = "SELECT * FROM RevoTestDB.claims",
                               connectionString = TeradataConnString, stringsAsFactors = TRUE)
    checkEquals(rxTeradataDS@sqlQuery, rxTeradataDS2@sqlQuery)
    checkEquals(rxTeradataDS@stringsAsFactors, FALSE)
    checkEquals(rxTeradataDS2@stringsAsFactors, TRUE)
    
    # Check hidden argument
    rxTeradataDS3 <- RxTeradata(sqlQuery = "SELECT * FROM RevoTestDB.claims",
                               connectionString = TeradataConnString, inTeradata = TRUE)
    checkEquals(rxTeradataDS3@inTeradata, TRUE)                        
}

"test.RxOdbcData.write" <- function()
{
    
    rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()

    databaseName <- file.path(tempdir(), "tempTest1.sqlite")
    conString <-
      try(rxSqliteConnectionStringFromFile(databaseName),
          silent = TRUE)

    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])

	##Create data source
	# Note: car.age is not a valid column name for SQL
	inDataSource1 <- RxTextData(file = file.path(rxGetOption("sampleDataDir"), "claims.txt"), 
		stringsAsFactors = FALSE, 
		useFastRead = TRUE)
	
	#grepl( "^[a-zA-Z_][a-zA-Z0-9_]*$", rxGetVarNames(inDataSource1))
	
    inDataSource1 <- RxTextData(file = file.path(rxGetOption("sampleDataDir"), "claims.txt"), 
		stringsAsFactors = FALSE, 
		colInfo = list(car.age = list(newName = "carAge")),
		useFastRead = TRUE)

    ##Create data destination
    outDataSource1 <- RxOdbcData(table = "claims", connectionString = conString,
 		useFastRead = TRUE)
	
	rxDataStep(inData = inDataSource1, outFile = outDataSource1, overwrite = TRUE)
	
	varInfoSql <- rxGetVarInfo(outDataSource1)
	varInfoTxt <- rxGetVarInfo(inDataSource1)
	txtNames <- names(varInfoTxt)
	txtNames <- ifelse( txtNames == "car.age", "carAge", txtNames)
	
	checkEquals(names(varInfoSql), txtNames)
	
	outDataSource2 <- RxOdbcData(table = "kyphosis", connectionString = conString, useFastRead = TRUE)
	inData2 <- file.path( rxGetOption("sampleDataDir"), "Kyphosis.xdf")
	rxDataStep(inData = inData2 , outFile = outDataSource2, overwrite = TRUE)
	varInfoSql <- rxGetVarInfo(outDataSource2)
	varInfoXdf <- rxGetVarInfo(inData2)
	checkEquals(names(varInfoSql), names(varInfoXdf))
	
	# Clean-up
	file.remove(databaseName)
	
    
}

#"test.RxOdbcData.write.fixed" <- function()
#{
    # Functionality not fully implemented
    ### prepare the connection string for the outDataSource
    #databaseName <- tempfile(pattern = "odbc.write.", fileext = ".sqlite")
    #on.exit(file.remove(databaseName), add = TRUE)
    #
    #rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()
    #conString <- try(rxSqliteConnectionStringFromFile(databaseName), silent = TRUE)
    #if (inherits(conString, "try-error")) DEACTIVATED(strsplit(conString, "\n")[[1]][2])
    #
    ### create in and out data sources
	##inDataSource <- file.path( rxGetOption("sampleDataDir"), "kyphosis.xdf")   #seems OK
    ##outDataSource <- RxOdbcData(table = "kyphosis", connectionString = conString, useFastRead = TRUE)    
    #inDataSource <- RxTextData(file = file.path(rxGetOption("sampleDataDir"), "claims.txt"),
	    #stringsAsFactors = FALSE, colInfo = list(car.age = list(newName = "carAge")),
			 #useFastRead = TRUE)
    #outDataSource <- RxOdbcData(table = "claims", connectionString = conString,
			#colInfo = list(type = list(type = "fixed", width = 1)), useFastRead = TRUE)
	#
	#rxDataStep(inData = inDataSource, outFile = outDataSource, overwrite = TRUE)
	#outInfo <- rxGetVarInfo(outDataSource)
    #checkEquals(outInfo$type$storage, "fixed")
	#checkEquals(outInfo$type$colWidth, 1)
	#newDF1 <- rxDataStep(RxOdbcData(table = "claims", connectionString = conString))
	#newDF2 <- rxDataStep(inDataSource)
	#checkEquals(newDF1$type, newDF2$type)
#}


"test.RxOdbcData.write.numRows" <- function()
{
     
    ## prepare the connection string for the outDataSource
    databaseName <- tempfile(pattern = "odbc.write.", fileext = ".sqlite")
    on.exit(file.remove(databaseName), add = TRUE)
    
    rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()
    conString <- try(rxSqliteConnectionStringFromFile(databaseName), silent = TRUE)
    if (inherits(conString, "try-error")) DEACTIVATED(strsplit(conString, "\n")[[1]][2])
    
    ## create in and out data sources
	#inDataSource <- file.path( rxGetOption("sampleDataDir"), "kyphosis.xdf")   #seems OK
    #outDataSource <- RxOdbcData(table = "kyphosis", connectionString = conString, useFastRead = TRUE)    
    inDataSource <- RxTextData(file = file.path(rxGetOption("sampleDataDir"), "claims.txt"),
	    stringsAsFactors = FALSE, colInfo = list(car.age = list(newName = "carAge")), useFastRead = TRUE)
    outDataSource <- RxOdbcData(table = "claims", connectionString = conString,	useFastRead = TRUE)
    
    ## write to table with specified numRows
    numRows <- 1
    #rxImport(inData = inDataSource, outFile = "foo.xdf", numRows = numRows, overwrite = TRUE)
    #rxDataStep(inData = inDataSource, numRows = numRows, overwrite = TRUE) # read more rows than nessary
	rxDataStep(inData = inDataSource, outFile = outDataSource, numRows = numRows, overwrite = TRUE)
    outData <- rxDataStep(outDataSource)
	checkEquals(nrow(outData), numRows)
}

"test.RxOdbcData.write.overwrite" <- function()
{
    
    ## prepare the connection string for the outDataSource
    databaseName <- tempfile(pattern = "odbc.write.", fileext = ".sqlite")
    on.exit(file.remove(databaseName), add = TRUE)
    
    rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()
    conString <- try(rxSqliteConnectionStringFromFile(databaseName), silent = TRUE)
    if (inherits(conString, "try-error")) DEACTIVATED(strsplit(conString, "\n")[[1]][2])
    
    ## create in and out data sources
    inDataSource1 <- RxTextData(file = file.path(rxGetOption("sampleDataDir"), "claims.txt"),
		stringsAsFactors = FALSE, colInfo = list(car.age = list(newName = "carAge")), useFastRead = TRUE)
	inDataSource2 <- file.path(rxGetOption("sampleDataDir"), "Kyphosis.xdf")
    
    outDataSource <- RxOdbcData(table = "claimsORkyphosis", connectionString = conString, useFastRead = TRUE)    
    
    ## write to table with the same schema    
	rxDataStep(inData = inDataSource1, outFile = outDataSource, overwrite = TRUE)
	checkException(rxDataStep(inData = inDataSource1, outFile = outDataSource, overwrite = FALSE))
	rxDataStep(inData = inDataSource1, outFile = outDataSource, overwrite = TRUE)   #write again
    
    outData <- rxDataStep(outDataSource)
    inData1 <- rxDataStep(inDataSource1)
    checkIdentical(outData, inData1)
	
	## Now append rows
	rxDataStep(inData = inDataSource1, outFile = outDataSource, append = "rows")
	outData1 <- rxDataStep(outDataSource)
	checkIdentical(outData1, rbind(inData1, inData1))
	
    ###################################
    ## write to table with different schema
	checkException(rxDataStep(inData = inDataSource2, outFile = outDataSource, overwrite = FALSE))
	rxDataStep(inData = inDataSource2, outFile = outDataSource, overwrite = TRUE)   #write again
    
	# Specify the factor levels to match the xdf file
	outDataSource2 <- RxDataSource(dataSource = outDataSource, colInfo = list(Kyphosis = list(type = "factor",
		levels = c("absent", "present"))))
    outData2 <- rxDataStep(outDataSource2)
    inData2 <- rxDataStep(inDataSource2)
    checkIdentical(outData2, inData2)
}

"test.RxOdbcData.rxPredict.outFile.overwrite" <- function()
{
    ## prepare the connection string for the outDataSource
    databaseName <- tempfile(pattern = "odbc.write.", fileext = ".sqlite")
    on.exit(file.remove(databaseName), add = TRUE)
    if (file.exists(databaseName)) file.remove(databaseName)
	
    rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()
    conString <- try(rxSqliteConnectionStringFromFile(databaseName), silent = TRUE)
    if (inherits(conString, "try-error")) DEACTIVATED(strsplit(conString, "\n")[[1]][2])
    
    ## create in and out data sources
	inDataSource <- file.path(rxGetOption("sampleDataDir"), "claims.xdf")
    outDataSource <- RxOdbcData(table = "claims", connectionString = conString, useFastRead = TRUE)    

    ## perform modeling and prediction
	linModObj = rxLinMod(cost~number, data = inDataSource)
    rxPredict(modelObject = linModObj, data = inDataSource, outData = outDataSource, 
        writeModelVars = TRUE, overwrite = TRUE)
    outData <- rxDataStep(outDataSource)
    dim.outData <- dim(outData)

    ## try to write again with same schema and overwrite = FALSE
    checkException(rxPredict(modelObject = linModObj, data = inDataSource, outData = outDataSource, 
        writeModelVars = TRUE, overwrite = FALSE))
    
    ## try to write again with same schema and overwrite = TRUE
    rxPredict(modelObject = linModObj, data = inDataSource, outData = outDataSource, 
        writeModelVars = TRUE, overwrite = TRUE)
    dim.outData2 <- dim(rxDataStep(outDataSource))
    checkEquals(dim.outData2, dim.outData)
    
    ## try to write again with different schema and overwrite = TRUE
    rxPredict(modelObject = linModObj, data = inDataSource, outData = outDataSource, 
        writeModelVars = FALSE, overwrite = TRUE)
    dim.outData3 <- dim(rxDataStep(outDataSource))
    checkEquals(dim.outData3[1], dim.outData[1])
    checkTrue(dim.outData3[2] != dim.outData[2])

    ## try to write again with the same schema but append = "rows"
    rxPredict(modelObject = linModObj, data = inDataSource, outData = outDataSource, 
        writeModelVars = FALSE, append = "rows")
    dim.outData4 <- dim(rxDataStep(outDataSource))
    checkEquals(dim.outData4[1], dim.outData[1] * 2)
    checkTrue(dim.outData4[2] == dim.outData3[2])
}

"test.RxOdbcData.rxPredict.outData.extraVarsToWrite" <- function()
{
    #DEACTIVATED("Defect 6030618:rxPredict.rxLinMod(extraVarsToWrite) does not work if outData is an ODBC data source.")
    
    ## prepare the connection strings
    databaseName <- file.path(rxGetOption("sampleDataDir"), "claims.sqlite")
    rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()
    conString <- try(rxSqliteConnectionStringFromFile(databaseName), silent = TRUE)
    if (inherits(conString, "try-error")) DEACTIVATED(strsplit(conString, "\n")[[1]][2])
    
    databaseNameOut <- tempfile(pattern = "odbc.write.", fileext = ".sqlite")
    on.exit(file.remove(databaseNameOut), add = TRUE)
    if (file.exists(databaseNameOut)) file.remove(databaseNameOut)
    conStringOut <- try(rxSqliteConnectionStringFromFile(databaseNameOut), silent = TRUE)
    
    #conString <- conStringOut <- "Driver=SQL Server;Server=.;Database=RevoTestDB;Uid=RevoTester;Pwd=RevoTester"
    
    ## create in and out data sources
    colInfo <- list(
        RowNum =list(type = "integer"),
        age = list( type = "factor",
            levels = c("17-20", "21-24", "25-29", "30-34", "35-39", "40-49", "50-59", "60+")),
        car_age = list(type = "factor",
            levels = c("0-3", "4-7", "8-9", "10+")),
        type = list(type = "factor",
            levels = c("A", "B", "C", "D")))
    
    inDataSource <- dataParameter <- RxOdbcData(connectionString = conString, 
        sqlQuery = "select * from claims", colInfo = colInfo)
    outDataSource <- RxOdbcData(table = "claimsOut", connectionString = conStringOut)
    
    ## perform modeling and prediction
    #form <- cost ~ type + car.age + number    #regression
    form <- ageLogical ~ type + car_age + cost + number
    linModObj = rxLinMod(form, data = inDataSource,
        transforms = expression(list(ageLogical = (age == "30-34")))
    )
    extraVarsToWrite <- "RowNum"
    rxPredict(modelObject = linModObj, data = inDataSource, outData = outDataSource, 
        writeModelVars = TRUE, extraVarsToWrite = extraVarsToWrite, overwrite = TRUE)
    
    ## check result
    outData <- rxDataStep(outDataSource)
    inData <- rxDataStep(inDataSource)
    checkEquals(outData[[extraVarsToWrite]], inData[[extraVarsToWrite]])
}

"test.RxOdbcData.rxPredict.outFile" <- function()
{

    rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()

    databaseName <- file.path(rxGetOption("sampleDataDir"), "claims.sqlite")
    conString <-
      try(rxSqliteConnectionStringFromFile(databaseName),
          silent = TRUE)
     
    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])
               
    databaseNameOut <- file.path(tempdir(), "tempTest1.sqlite")
    conStringOut <-
      try(rxSqliteConnectionStringFromFile(databaseNameOut),
          silent = TRUE)

    if (inherits(conStringOut, "try-error"))
        DEACTIVATED(strsplit(conStringOut, "\n")[[1]][2])
    
    odbcDS <- RxOdbcData(
				sqlQuery = "SELECT * FROM claims",
                connectionString = conString,
                useFastRead = TRUE,
                colClasses = c("RowNum" = "integer", "age" = "character",
							   "carAge" = "character", "type" = "character",
							   "cost" = "integer", "number" = "integer"))
	linModObj = rxLinMod(cost~number, data=odbcDS)

    ##Create data destination
    odbcOutDS <- RxOdbcData(table = "claimsPred", connectionString = conStringOut,
 		useFastRead = TRUE)
	
    rxPredict(modelObject = linModObj, data = odbcDS, 
        outData = odbcOutDS, 
        writeModelVars = TRUE,
        overwrite = TRUE)

	varInfoOut <- rxGetVarInfo(odbcOutDS)
		
    checkEquals(names(varInfoOut), c("cost_Pred", "cost", "number"))
    dfFromOdbc <- rxDataStep(odbcOutDS)
    checkEquals(nrow(dfFromOdbc), 128)
    
    dfIn <- rxDataStep(odbcDS)
    dfPredict <- rxPredict(modelObject = linModObj, data = dfIn, writeModelVars = TRUE)
    
    checkEquals(dfFromOdbc$cost_Pred, dfPredict$cost_Pred)
    checkEquals(dfFromOdbc$cost, dfPredict$cost)
    
	# Clean-up
	file.remove(databaseNameOut)
		
}

"test.RxOdbcData.rxKmeans.outFile" <- function()
{ 
    rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()

    databaseName <- file.path(rxGetOption("sampleDataDir"), "claims.sqlite")
    conString <-
      try(rxSqliteConnectionStringFromFile(databaseName),
          silent = TRUE)
     
    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])
               
    databaseNameOut <- file.path(tempdir(), "tempTest2.sqlite")
	if (file.exists(databaseNameOut)) file.remove( databaseNameOut)
    conStringOut <-
      try(rxSqliteConnectionStringFromFile(databaseNameOut),
          silent = TRUE)

    if (inherits(conStringOut, "try-error"))
        DEACTIVATED(strsplit(conStringOut, "\n")[[1]][2])
    
    odbcDS <- RxOdbcData(
				sqlQuery = "SELECT * FROM claims",
                connectionString = conString,
                useFastRead = TRUE,
				rowsPerRead = 100,
                colClasses = c("RowNum" = "integer", "age" = "character",
							   "carAge" = "character", "type" = "character",
							   "cost" = "integer", "number" = "integer"))

    ##Create data destination
    odbcOutDS <- RxOdbcData(table = "claimsKmeansOut", connectionString = conStringOut,
 		useFastRead = TRUE)    
    
    centers <- matrix(c(220, 700), ncol = 1)

    kmeansOutOdbc <- rxKmeans(~cost, data = odbcDS, #numClusters = 2, numStarts = 4L, seed = 4,
        centers = centers,
        outFile = odbcOutDS, writeModelVars = TRUE)
    
    
    xdfFile <- file.path(rxGetOption("sampleDataDir"),"claims.xdf")
    outFile1 <- tempfile(pattern = "rxKmeans1",  fileext = ".xdf")   
    
    kmeansOutXdf <- rxKmeans(~cost, data = xdfFile, #numClusters = 2, numStarts = 4L, seed = 4,
        centers = centers,
		outColName = "X_rxCluster",
        outFile = outFile1, writeModelVars = TRUE)     
    
    kmeansOutOdbc <- rxDataStep(odbcOutDS)
    kmeansOutXdf <- rxDataStep(outFile1)
    
    checkEquals(kmeansOutOdbc$X_rxCluster, kmeansOutXdf$X_rxCluster)
    
    df1 <- rxDataStep(outFile1)
    df2 <- rxDataStep(odbcOutDS)
    checkEquals(df1$cost, df2$cost)
    checkEquals(df1$X_rxCluster , df2$X_rxCluster)
	
	kmeansOutOdbc2 <- rxKmeans(~cost, data = odbcDS, #numClusters = 2, numStarts = 4L, seed = 4,
        centers = centers,
        outFile = odbcOutDS, writeModelVars = TRUE, overwrite = TRUE)
	
    df3 <- rxDataStep(odbcOutDS)
    checkEquals(df1$cost, df3$cost)
    checkEquals(df1$X_rxCluster , df3$X_rxCluster)	
      
    file.remove(outFile1)
    file.remove( databaseNameOut)
    
}

"test.RxOdbcData.rxDTree.outFile" <- function()
{
	#DEACTIVATED("Pending support for rxDTree outFile for RxOdbcData")
    ## make local data
	rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()
	conString <- try(
					rxSqliteConnectionStringFromFile(file.path(rxGetOption("sampleDataDir"), "claims.sqlite"),
                        useFastRead = TRUE),
					silent = TRUE)
    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])
        
    databaseNameOut <- file.path(tempdir(), "tempTest3.sqlite")
    conStringOut <-
      try(rxSqliteConnectionStringFromFile(databaseNameOut),
          silent = TRUE)        
	##Create data destinations
    odbcOutDS <- RxOdbcData(table = "claimsDtreeOut", connectionString = conStringOut,
 		useFastRead = TRUE)  
	xdfOutFile <- tempfile(pattern = "rxDTree2",  fileext = ".xdf")   
      
	# Temporary conString
    #conString <- paste("Driver=SQLite3 ODBC Driver;Database=", file.path(rxGetOption("sampleDataDir"), "claims.sqlite"), sep = "")
    claimsColInfo <- list( "type" =
                        list(type = "factor",
                            levels = c("A", "B", "C", "D")),	
						  "age" =
						list(type = "factor",
							levels = c("17-20", "21-24", "25-29", "30-34", "35-39", "40-49", "50-59", "60+"))
						)		
					
	claimsOdbc <- RxOdbcData(
				sqlQuery = "SELECT * FROM claims",
                useFastRead = TRUE,
                connectionString = conString,
                colInfo = claimsColInfo,
                rowsPerRead = 32)
														
    claimsDF    <- rxReadXdf(file.path(rxGetOption("sampleDataDir"), "claims.xdf"))
	claimsOdbcDF <- rxImport(claimsOdbc)
	res <- try(checkEquals(nrow(claimsOdbcDF), 128))
	if (inherits(res, "try-error"))
	{
		message("Incorrect number of rows returned. Verify that you have a compatible SQLite ODBC driver (!=.92).")
	}
    ## set up arguments
    form        <- age ~ cost + number
	require(rpart)
    control     <- rpart.control(
                    minsplit = 5, minbucket = 2, cp = 0.01, maxdepth = 4, maxcompete = 4,
                    maxsurrogate = 5, usesurrogate = 2, surrogatestyle = 0, xval = 0)
    
    ## build the models
    fitDtreeXdfOut <- rxDTree(
        formula = form, data = claimsOdbc, control = control, maxNumBins = 100, outFile = xdfOutFile,
        writeModelVars = TRUE, outColName = "X_rxNode",
        maxRowsInMemory = if(exists(".maxRowsInMemory")) .maxRowsInMemory else -1
        )
    
    fitDtreeOdbcOut <- rxDTree(
        formula = form, data = claimsOdbc, control = control, maxNumBins = 100, outFile = odbcOutDS,
        writeModelVars = TRUE,
        maxRowsInMemory = if(exists(".maxRowsInMemory")) .maxRowsInMemory else -1
        )        
    
    ## check results
    
	dataOutXdf <- rxDataStep(xdfOutFile)
	dataOutOdbc <- rxDataStep(odbcOutDS)
	checkEquals(names(dataOutXdf), names(dataOutOdbc))
	checkEquals(dataOutXdf$X_rxNode, dataOutOdbc$X_rxNode)
	
    # Clean-up
    file.remove(xdfOutFile)
    file.remove(databaseNameOut)
}

"test.RxOdbcData.write.Integer" <- function()
{
    rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()

    sqliteFilePath <- file.path(tempdir(), "tempTest1.sqlite")
    conString <-
      try(rxSqliteConnectionStringFromFile(sqliteFilePath),
          silent = TRUE)

    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])		
			
    outOdbcDS <- RxOdbcData(table = "MyIntegers", connectionString = conString, useFastRead = TRUE)
	myData1 <- data.frame(	SmallintV = as.integer(881:890),
							BigintV = as.integer(80000001:80000010),
							stringsAsFactors = FALSE)	
	rxDataStep(inData = myData1, outFile = outOdbcDS, overwrite = TRUE)
		
	sumDF <- rxSummary(~., data=myData1) 
	sumDB <- rxSummary(~., data=outOdbcDS) 
	checkEquals(sumDF$sDataFrame, sumDB$sDataFrame)
	
	# Clean-up
	file.remove(sqliteFilePath)
}

"test.RxOdbcData.write.Logical" <- function()
{
    rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()

    sqliteFilePath <- file.path(tempdir(), "tempTest2.sqlite")
    conString <-
      try(rxSqliteConnectionStringFromFile(sqliteFilePath),
          silent = TRUE)

    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])		
			
    outOdbcDS2 <- RxOdbcData(table = "MyLogic", connectionString = conString, useFastRead = TRUE)
							
	myData2 <- data.frame(	RowNum = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
					BoolV = c(FALSE,  TRUE, FALSE, FALSE, FALSE, FALSE,  TRUE, TRUE, FALSE, TRUE)
					)	 
	rxDataStep(inData = myData2, outFile = outOdbcDS2, overwrite = TRUE)		
	
	varInfoDF <- rxGetVarInfo(myData2)
	varInfoDB <- rxGetVarInfo(outOdbcDS2)
	checkEquals(names(varInfoDF), names(varInfoDB))
	
	# Check missing value writing
	missings <- data.frame(
	    log = c(TRUE, FALSE, NA),
	    logi = c(TRUE, FALSE, NA),
	    logu = c(TRUE, FALSE, NA),
	    logf = c(TRUE, FALSE, NA),
	    logs = c(TRUE, FALSE, NA),
	    int = c(1L, 2L, NA),
	    i16 = c(1L, 2L, NA),
	    u16 = c(1L, 2L, NA),
	    u16f = c(1L, 2L, NA),
	    dbl = c(1, 2, NA), 
	    chr = c("a", "b", NA),
	    stringsAsFactors = FALSE
	)
	
	colClassesOut <- c(log = "logical", logi = "int16", logu = "uint16", logf = "float32", logs = "character", i16 = "int16", u16 = "uint16", u16f = "float32")
	colClassesIn <- c(log = "logical", logi = "logical", logu = "logical", logf = "logical", logs = "logical", i16 = "integer", u16 = "integer", u16f = "integer")
	
	dsMissings <- RxOdbcData(table = "Missings", connectionString = conString, colClasses = colClassesOut)
	rxDataStep(missings, dsMissings, overwrite = TRUE )
	
	missingsOut <- rxDataStep(dsMissings, colClasses = colClassesIn)
	checkIdentical(missings, missingsOut)
	
	# Clean-up
	file.remove(sqliteFilePath)
}


"test.RxOdbcData.write.String" <- function()
{
    rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()

    sqliteFilePath <- file.path(tempdir(), "tempTest3.sqlite")
    conString <-
      try(rxSqliteConnectionStringFromFile(sqliteFilePath),
          silent = TRUE)

    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])		
			
    outOdbcDS3 <- RxOdbcData(table = "MyStrings", connectionString = conString, useFastRead = TRUE)
							
	myData3 <- data.frame(	RowNum = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
					xfixed2 = c("aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh", "ii", "jj"),
					xfixed3 = c("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj"),
					StrV = c("abcdefghij", "abcdefghi", "abcdefgh", "abcdefg", "abcdef", "abcde", "abcd", "abc", "ab", "a"),
					VaribleRaw = c("aaa0000000000", "bbb1", "ccc22", "ddd333", "eee4444", "fff55555", "ggg666666", "hhh7777777", "iii88888888", "jjj999999999"),							  			   
					stringsAsFactors = FALSE
					)	 
	rxDataStep(inData = myData3, outFile = outOdbcDS3, overwrite = TRUE)		
	
	varInfoDF <- rxGetVarInfo(myData3)
	varInfoDB <- rxGetVarInfo(outOdbcDS3)
	checkEquals(names(varInfoDF), names(varInfoDB))
	
	readDS <- RxOdbcData(sqlQuery = "SELECT * FROM MyStrings", connectionString = conString, stringsAsFactors = FALSE)
	rxOpen(readDS) 
	myData <- rxReadNext(readDS) # Cannot change string to factors	
	rxClose(readDS)					
	checkEquals(myData3, myData)
	
	# Clean-up
	file.remove(sqliteFilePath)
}

# tests our ability to read and write UTF-16 from wide character column types using ODBC
# in R and RevoScaleR, of course, the unicode characters are stored as UTF-8
"test.RxOdbcData.Utf16" <- function()
{
	if ( toupper(Sys.info()[["sysname"]]) != "WINDOWS" ) 
	{
		DEACTIVATED("This test currently supported only on Windows.")
	}
	
	# prepare the connection string for sqlite database file
	rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()
	connectionString <- try(rxSqliteConnectionStringFromFile(file.path(rxGetOption("sampleDataDir"), "Utf16leDb.sqlite")), silent = TRUE)	
    if (inherits(connectionString, "try-error")) DEACTIVATED(strsplit(connectionString, "\n")[[1]][2])
	
	# create the data source
	characterData <- RxOdbcData(connectionString = connectionString, table = "characterData")
	
	# read UTF-16 from DB into a data frame (which will contain UTF-8)
	unicodeDf <- rxImport(characterData, colClasses = c(NCHAR="character", NVARCHAR="factor"))
	
	# check unicode data frame 
	asianMoonChar <- "\u6708" # unicode moon character (UTF-8 encoding)
	checkEquals(c('NCHAR', 'NVARCHAR', asianMoonChar), names(unicodeDf))
	checkEquals("UTF-8", Encoding(names(unicodeDf)[3]))
	checkEquals(data.frame(NCHAR=c('BLEARG', asianMoonChar, 'one'), stringsAsFactors=FALSE), unicodeDf[1])
	checkEquals("UTF-8", Encoding(levels(unicodeDf[2,2])[2]))
	checkEquals(data.frame(NVARCHAR=factor(c('BLEARG', asianMoonChar, 'two'), levels=c('BLEARG', asianMoonChar, 'two'))), unicodeDf[2])
	checkEquals("UTF-8", Encoding(names(unicodeDf)[3]))
	dfCol3 <- data.frame(1:3)
	names(dfCol3) <- c(asianMoonChar)
	checkEquals(dfCol3, unicodeDf[3])

	
	# read from 'characterData' write to 'outCharacterData' tables in DB
    databaseName <- tempfile(pattern = "Utf16leDb.", fileext = ".sqlite")
    on.exit(file.remove(databaseName), add = TRUE)	
	connectionString <- rxSqliteConnectionStringFromFile(databaseName)
	outCharData <- RxOdbcData(connectionString = connectionString, table = "outCharacterData")	
	rxDataStep(inData = characterData, outFile = outCharData, overwrite = TRUE)	
	
	outUnicodeDf <- rxImport(outCharData, colClasses = c(NCHAR="character", NVARCHAR="factor"))
	
	# check outUnicodeDf
	checkEquals(unicodeDf, outUnicodeDf)
}

"test.RxOdbcData.args.colInfo.factorIndex" <- function()
{
    rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()

    sqliteFilePath <- file.path(tempdir(), "tempTest1.sqlite")
    conString <-
      try(rxSqliteConnectionStringFromFile(sqliteFilePath),
          silent = TRUE)

    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])		
	tableName <- "factorIndexTest"		
    outOdbcDS <- RxOdbcData(table = tableName, connectionString = conString, useFastRead = TRUE)
	set.seed(10)
	xint1 <- as.integer(runif(50, 1, 5))
	myData1 <- data.frame(	xfac1 = as.character(xint1),
							xint1= xint1,
                            xint2 = xint1,
                            xnum = rnorm(50),
							stringsAsFactors = FALSE)	
	rxDataStep(inData = myData1, outFile = outOdbcDS, overwrite = TRUE)
			
	odbcDS1 <- RxOdbcData(table = tableName, connectionString = conString, 
		useFastRead = TRUE, rowsPerRead = 40, 
        colInfo =
		list(
            xint1 = list(type = "factorIndex", minLevel = 1, levels = as.character(1:4)),
            xfac1 = list(type = "factorIndex", maxLevel = 4, levels = as.character(0:4)),
            xint2 = list(type = "factorIndex", minLevel = 1, levels = letters[1:4])
            ))
    outDataFrame <- rxImport(odbcDS1)
    checkEquals(levels(outDataFrame$xfac1), as.character(0:4))
    checkEquals(levels(outDataFrame$xint1), c("NA", as.character(1:4)))
    
    # Make sure variables are treated as factors in analysis
    sumOut <- rxSummary(~xint1 + xint2, data = odbcDS1)
    sumOutDF <- rxSummary(~xint1 + xint2, data = outDataFrame)
    checkEquals(sumOut$categorical[[1]]$Counts, sumOutDF$categorical[[1]]$Counts)
    
    linModOut <- rxLinMod(xnum~xint2, data = odbcDS1)
    linModOutDF <- rxLinMod(xnum~xint2, data = outDataFrame)
    checkEquals(coef(linModOut), coef(linModOutDF))
    
    # When predicting, mocel vars should written as integers
	predTableName <- "factorPredOut"		
    odbcPredDS <- RxOdbcData(table = predTableName, connectionString = conString, useFastRead = TRUE)	    
    rxPredict(linModOut, data = odbcDS1, outData = odbcPredDS, writeModelVars = TRUE, overwrite = TRUE)
    
    checkDF1 <- rxDataStep(odbcPredDS)
    checkDF2 <- rxDataStep(outOdbcDS)
    checkEquals(checkDF1$xint2, checkDF2$xint2)
    checkEquals(checkDF1$xint2, myData1$xint2)
    checkTrue(is.integer(checkDF1$xint2))
    
    # When being written out, they should be written as integers
	outTableName <- "factorIndexOut"		
    odbcDS2 <- RxOdbcData(table = outTableName, connectionString = conString, useFastRead = TRUE)	
    rxDataStep(inData = odbcDS1, outFile = odbcDS2, overwrite = TRUE)
    outDataFrame2 <- rxImport(odbcDS2)
    
	odbcDS3 <- RxOdbcData(table = tableName, connectionString = conString, 
		useFastRead = TRUE, rowsPerRead = 40)	
    outDataFrame3 <- rxImport(odbcDS3)
    checkEquals(outDataFrame2$xint1, outDataFrame3$xint1)

    
    # Write from xdf to odbc with factorIndexes
	rxDataStep(inData = myData1, outFile = outOdbcDS, overwrite = TRUE)
			
    myIris <- iris
    newNames <- names(iris)
    newNames <- gsub(pattern = "\\.", replacement= "", x= newNames)
    names(myIris) <- newNames
    
    outXdf <- tempfile(pattern = "tempFactor", fileext = ".xdf")
    rxImport(myIris, outFile = outXdf, rowsPerRead = 40, overwrite = TRUE) 
    
    irisColInfo <- rxCreateColInfo(outXdf)
    irisColInfo$Species$type <- "factorIndex"
    irisTable <- "iris"
    odbcIris <- RxOdbcData(table = irisTable, connectionString = conString, 
        useFastRead = TRUE,
        writeFactorsAsIndexes = TRUE
        )
           
    rxDataStep(inData = outXdf, outFile = odbcIris, overwrite = TRUE)   
    
    irisDF <- rxDataStep(inData = RxOdbcData(table = irisTable, connectionString = conString))
    checkTrue(is.integer(irisDF$Species))
    checkEquals(irisDF$Species + 1, as.integer(iris$Species))
    
    # Write from csv directly to xdf
    txtFileName <- tempfile( pattern = ".irisTxt", fileext = ".csv")
    txtFileName <- "irisTxt.csv"
    txtDS <- RxTextData(file = txtFileName, colClasses = c(Species = "factor"))
    rxDataStep(inData = myIris, outFile = txtDS, overwrite = TRUE)
    
    # Compute the factor info from the text data source
    irisColInfo <- rxCreateColInfo(data = txtDS, factorsOnly = TRUE)
    txtDS <- RxTextData(file = txtFileName, colInfo = irisColInfo)
    
    # Write from csv to odbc
    rxDataStep(inData = txtDS, outFile = odbcIris, overwrite = TRUE)
    
    irisDF2 <- rxDataStep(inData = RxOdbcData(table = irisTable, connectionString = conString))
    checkTrue(is.integer(irisDF2$Species))
    checkEquals(irisDF2$Species + 1, as.integer(iris$Species))
    
    odbcIris <- RxDataSource(dataSource = odbcIris, colInfo = list(Species = list(type = "factorIndex", levels = irisColInfo$Species$levels)))
    
    
    linModOut1 <- rxLinMod(SepalLength~Species, data = myIris)
    linModOut2 <- rxLinMod(SepalLength~Species, data = odbcIris)
	checkEquals(coef(linModOut1), coef(linModOut2))
    
	# Clean-up
	file.remove(sqliteFilePath)	
    file.remove(outXdf)
    file.remove(txtFileName)
}

internal.random.strings <- function(nn, min, max) {
    # Generate some random, big strings
    upperAlphas <- toupper(letters)
    lowerAlphas <- tolower(letters)
    digits <- c("0","1", "2", "3", "4", "5", "6", "7", "8", "9")
    
    set <- c(upperAlphas, lowerAlphas, digits)
    
    lens <- trunc(runif(nn, min, max))
    
    strings <- unlist(lapply(lens, function(nn, ss) paste(sample(ss, nn, replace=T), collapse=""), ss=set))
    
    strings
}

"test.RxOdbcData.keyvalue" <- function()
{
    rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()
    
    sqliteFilePath <- normalizePath(file.path(tempdir(), "tempTestKeyValue.sqlite"))
    try(unlink(sqliteFilePath), silent = TRUE)
    on.exit(unlink(sqliteFilePath))
    conString <-
        try(rxSqliteConnectionStringFromFile(sqliteFilePath),
            silent = TRUE)
    
    if (inherits(conString, "try-error")) {
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])
    }
    
    out.table = "rdata"
    ds <- RxOdbcData(table=out.table, connectionString=conString)

    # Create the table (no version column)
    rxOpen(ds, "w")
    checkTrue(rxExecuteSQLDDL(ds, paste("create table ", out.table, " (id varchar(200) not null, value varbinary(100000))", sep="")))
    checkTrue(rxExecuteSQLDDL(ds, paste("create unique index id_index on ", out.table, " (id)", sep="")))
    rxClose(ds)

    ll <- list(a = 1:11, b = "test")
    rxWriteObject(ds, 'test.list', ll)
    mm <- rxReadObject(ds, 'test.list')
    checkIdentical(ll, mm)

    checkException(rxWriteObject(ds, 'test.list', ll))
    checkTrue(rxWriteObject(ds, 'test.list', ll, overwrite=TRUE))

    rxDeleteObject(ds, 'test.list')
    mm <- rxReadObject(ds, 'test.list')
    checkEquals(mm, NULL)

    checkException(rxWriteObject(ds, 'test.string', 'test', serialize = F))
    rr1 <- charToRaw("test")
    checkTrue(rxWriteObject(ds, 'test.string', rr1, serialize=F))
    checkException(rxReadObject(ds, 'test.string'))
    rr2 <- rxReadObject(ds, 'test.string', deserialize = F)
    checkIdentical(rr1, rr2)

    checkEquals(NROW(rxListKeys(ds)), 1)
    rxDeleteObject(ds, all=T)
    checkEquals(NROW(rxListKeys(ds)), 0)

    ll$string <- internal.random.strings(1, 10000, 100000)
    ll$binary <- charToRaw(internal.random.strings(1, 10000, 100000))

    rxWriteObject(ds, 'test.big.list', ll)
    mm <- rxReadObject(ds, 'test.big.list')
    checkIdentical(ll, mm)

    rxWriteObject(ds, 'another.big.list', ll)
    checkEquals(NROW(rxListKeys(ds)), 2)

    rxDeleteObject(ds, all = TRUE)
    checkEquals(NROW(rxListKeys(ds)), 0)

    rxOpen(ds, "w")
    checkTrue(rxExecuteSQLDDL(ds, paste("drop table ", out.table, sep="")))
    checkTrue(rxExecuteSQLDDL(ds, paste("create table ", out.table, " (id varchar(200) not null, version varchar(200), value varbinary(100000))", sep="")))
    checkTrue(rxExecuteSQLDDL(ds, paste("create index id_index on ", out.table, " (id)", sep="")))
    rxClose(ds)

    checkTrue(rxWriteObject(ds, 'important.list', ll, "v1.0.0", overwrite = TRUE))
    checkTrue(rxWriteObject(ds, 'important.list', ll, "v1.1.0", overwrite = TRUE))
    checkTrue(rxWriteObject(ds, 'important.list', ll, "v1.3.0", overwrite = TRUE))
    checkTrue(rxWriteObject(ds, 'another.list', ll, "v1.0.0", overwrite = TRUE))
    checkTrue(rxWriteObject(ds, 'another.list', ll, "v1.0.0", overwrite = TRUE))

    checkIdentical(rxListKeys(ds), data.frame(id = c("another.list", "important.list"), stringsAsFactors = F))
    checkIdentical(rxListKeys(ds, key = "important.list"), data.frame(version = c("v1.0.0", "v1.1.0", "v1.3.0"), stringsAsFactors = F))
    checkIdentical(rxListKeys(ds, key = "important.list", version = "v1.3.0"), data.frame(version = c("v1.3.0"), stringsAsFactors = F))
    checkEquals(NROW(rxListKeys(ds, key = "important.list", version = "none")), 0)

    checkTrue(rxWriteObject(ds, 'important.list', ll, "v2.0.0"))
    checkTrue(rxWriteObject(ds, 'important.list', ll, "v2.1.0"))
    checkTrue(rxWriteObject(ds, 'important.list', ll, "v2.3.0"))
    checkIdentical(rxListKeys(ds), data.frame(id = c("another.list", "important.list"), stringsAsFactors = F))
    checkIdentical(rxListKeys(ds, key = "important.list"), data.frame(version = c("v1.0.0", "v1.1.0", "v1.3.0", "v2.0.0", "v2.1.0", "v2.3.0"), stringsAsFactors = F))
    checkIdentical(rxListKeys(ds, key = "another.list"), data.frame(version = c("v1.0.0"), stringsAsFactors = F))

    # Repeat the first test with a few additional, but null-able columns
    rxOpen(ds, "w")
    checkTrue(rxExecuteSQLDDL(ds, paste("drop table ", out.table, sep = "")))
    checkTrue(rxExecuteSQLDDL(ds, paste("create table ", out.table, " (first_extra real, value varbinary(100000), second_extra real, id varchar(200) not null, third_extra real, version varchar(200), fourth_extra real)", sep = "")))
    checkTrue(rxExecuteSQLDDL(ds, paste("create unique index id_index on ", out.table, " (id)", sep = "")))
    rxClose(ds)

    ll <- list(a = 1:11, b = "test")
    rxWriteObject(ds, 'test.list', ll)
    mm <- rxReadObject(ds, 'test.list')
    checkIdentical(ll, mm)

    checkException(rxWriteObject(ds, 'test.list', ll))
    checkTrue(rxWriteObject(ds, 'test.list', ll, overwrite = TRUE))

    rxDeleteObject(ds, 'test.list')
    mm <- rxReadObject(ds, 'test.list')
    checkEquals(mm, NULL)

    checkException(rxWriteObject(ds, 'test.string', 'test', serialize = F))
    rr1 <- charToRaw("test")
    checkTrue(rxWriteObject(ds, 'test.string', rr1, serialize = F))
    checkException(rxReadObject(ds, 'test.string'))
    rr2 <- rxReadObject(ds, 'test.string', deserialize = F)
    checkIdentical(rr1, rr2)

    checkEquals(NROW(rxListKeys(ds)), 1)
    rxDeleteObject(ds, all = T)
    checkEquals(NROW(rxListKeys(ds)), 0)

    ll$string <- internal.random.strings(1, 10000, 100000)
    ll$binary <- charToRaw(internal.random.strings(1, 10000, 100000))

    rxWriteObject(ds, 'test.big.list', ll)
    mm <- rxReadObject(ds, 'test.big.list')
    checkIdentical(ll, mm)

    rxWriteObject(ds, 'another.big.list', ll)
    checkEquals(NROW(rxListKeys(ds)), 2)

    rxDeleteObject(ds, all = TRUE)
    checkEquals(NROW(rxListKeys(ds)), 0)

    rxWriteObject(ds, 'test.big.list', ll)
    l1 <- rxReadObject(ds, 'test.big.list')
    l2 <- rxReadObject(rxReadObject(ds, 'test.big.list', deserialize = F))
    checkIdentical(l1, l2)
}

"test.RxOdbcData.widedata" <- function()
{
    rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()
    
    sqliteFilePath <- normalizePath(file.path(tempdir(), "tempTestWideData.sqlite"))
    try(unlink(sqliteFilePath), silent = TRUE)
    on.exit(unlink(sqliteFilePath))
    conString <-
        try(rxSqliteConnectionStringFromFile(sqliteFilePath),
            silent = TRUE)
    
    if (inherits(conString, "try-error")) {
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])
    }
    
    strings <- internal.random.strings(11, 65000, 1000000)
    strings[4] <- NA
    df1 <- data.frame(id = 1:NROW(strings), strings = strings, floats = round(rnorm(NROW(strings)),4), stringsAsFactors = F)
    
    table.name <- "widestrings"
    
    ds <- RxOdbcData(table=table.name, connectionString=conString, stringsAsFactors=F)
    rxDataStep(df1, ds)
    
    df2 <- rxDataStep(ds)
    df2 <- df2[order(df2[,1]),]
    
    checkEqualsNumeric(NROW(df2), NROW(df1))
    checkIdentical(df1, df2)
    
    # Investigate why blobs are not working    
    #     bb = lapply(strings, charToRaw)
    #     df3 = data.frame(id=1:NROW(bb), binary=I(bb), floats = round(rnorm(NROW(bb)),4), stringsAsFactors = F)
    #     
    #     table.name <- "widebinaries"
    #     
    #     ds <- RxOdbcData(table=table.name, connectionString=conString, stringsAsFactors=F)
    #     rxDataStep(df3, ds)
    #     
    #     df4 <- rxDataStep(ds)
    #     df4 <- df4[order(df4[,1]),]
    #     
    #     checkEqualsNumeric(NROW(df3), NROW(df4))
    #     checkIdentical(df3, df4)
}