Given a results specification and ConnectionHandler instance - this class allow queries to be namespaced within any tables specified within a list of pre-determined tables. This allows the encapsulation of queries, using specific table names in a consistent manner that is striaghtforward to maintain over time.
tablePrefix
tablePrefix to use
new()
initialize class
QueryNamespace$new(
connectionHandler = NULL,
tableSpecification = NULL,
tablePrefix = "",
...
)
connectionHandler
ConnectionHandler instance @seealsoConnectionHandler
tableSpecification
tableSpecification data.frame
tablePrefix
constant string to prefix all tables with
...
additional replacement variables e.g. database_schema, vocabulary_schema etc Set Connection Handler
addReplacementVariable()
add a variable to automatically be replaced in query strings (e.g. @database_schema.@table_name becomes 'database_schema.table_1')
addTableSpecification()
add a variable to automatically be replaced in query strings (e.g. @database_schema.@table_name becomes 'database_schema.table_1')
QueryNamespace$addTableSpecification(
tableSpecification,
useTablePrefix = TRUE,
tablePrefix = self$tablePrefix,
replace = TRUE
)
tableSpecification
table specification data.frame conforming to column names tableName, columnName, dataType and primaryKey
useTablePrefix
prefix the results with the tablePrefix (TRUE)
tablePrefix
prefix string - defaults to class variable set during initialization
replace
replace existing variables of the same name Render
executeSql()
Call to execute sql within namespaced queries
library(ResultModelManager)
# Create some junk test data
connectionDetails <-
DatabaseConnector::createConnectionDetails(
server = "test_db.sqlite",
dbms = "sqlite"
)
conn <- DatabaseConnector::connect(connectionDetails)
#> Connecting using SQLite driver
DatabaseConnector::insertTable(
connection = conn,
tableName = "cd_cohort",
data = data.frame(
cohort_id = c(1, 2, 3),
cohort_name = c("cohort one", "cohort two", "cohort three"),
json = "{}",
sql = "SELECT 1"
)
)
#> Inserting data took 0.0108 secs
DatabaseConnector::disconnect(conn)
connectionHandler <- ConnectionHandler$new(connectionDetails = connectionDetails)
#> Connecting using SQLite driver
tableSpecification <- data.frame(
tableName = "cohort",
columnName = c(
"cohort_id",
"cohort_name",
"json",
"sql"
),
primaryKey = c(TRUE, FALSE, FALSE, FALSE),
dataType = c("int", "varchar", "varchar", "varchar")
)
cohortNamespace <- QueryNamespace$new(
connectionHandler = connectionHandler,
tableSpecification = tableSpecification,
result_schema = "main",
tablePrefix = "cd_"
)
sql <- "SELECT * FROM @result_schema.@cohort WHERE cohort_id = @cohort_id"
# Returns : "SELECT * FROM main.cd_cohort WHERE cohort_id = @cohort_id"
print(cohortNamespace$render(sql))
#> [1] "SELECT * FROM main.cd_cohort WHERE cohort_id = cd_cohort_id"
# Returns query result
result <- cohortNamespace$queryDb(sql, cohort_id = 1)
# cleanup test data
unlink("test_db.sqlite")