1

I am currently building a (large) survey and need to send the responses people provide to a database. I have set up my database connection using the pool and RMariaDB packages, and I have written the following function to construct the SQL queries and submit my data (the data is secured with SSL certificates and all this information is passed through the list db_config).

save_db <- function (db_pool, x, db_name, db_config, replace_val) {
  # Construct the DB query to be sent to the database
  if (!replace_val) {
    query <- sprintf(
      "INSERT INTO %s (%s) VALUES ('%s')",
      db_name,
      paste(names(x), collapse = ", "),
      paste(x, collapse = "', '")
    )
  } else {
    query <- sprintf(
      "UPDATE %s SET %s WHERE %s;",
      db_name,
      paste(paste0(names(x)[-1], " = \'", x[-1], "\'"), collapse = ", "),
      paste0(names(x)[1], " = \'", x[1], "\'")
    )
  }

  # Submit the insert query to the database via the opened connection
  RMariaDB::dbExecute(db_pool, query)
}

db_poolis the pool object handling my database connections; x is a named vector with the data that I am sending to the database, where the names corresponds to the column names of my MariaDB and the values are stored as data blobs; db_name is the name of my database; replace_val a boolean.

The data blobs are essentially different output objects from the survey, e.g. vectors or matrices of responses, turned into character strings using the toJSON() from the jsonlite package.

So far, so good. I am able to send data to the database, download it and reconstruct the responses using the fromJSON() command. All is good. However, I do have one security concern. In my survey, I do have a few open-ended questions where people can write what they want. While unlikely, I am concerned that someone might use a SQL injection attack. Worst case scenario, I lose all my data.

I know of the sqlInterpolate() function from the DBI package. From my understanding, the function escapes any quotation marks, meaning that any value submitted will be turned into a safe string.

What I have not been able to do is modify my function above to work with sqlInterpolate. In my case x is a named vector of length seven where each vector element is a JSON string. Essentially, I need to use sqlInterpolate() on each of the JSON strings. I was wondering if there is an "easy" way of doing this, or if my best course of action would be to completely rewrite my function to send seven individual deposits to the DB, i.e. one for each vector element.

A rather simplified example would be something like this:

library(jsonlite)

# Create some data to test the string on
y <- 1:3
z <- matrix(runif(4), 2, 2)
q <- c("one", "don't")
x <- c(toJSON(y), toJSON(z), toJSON(q))
names(x) <- c("var_1", "var_2", "var_3")
db_name <- "my_db"

# Current sprintf() statement
sprintf(
  "INSERT INTO %s (%s) VALUES ('%s')",
  db_name,
  paste(names(x), collapse = ", "),
  paste(x, collapse = "', '")
)

And what I would need to interpolate is the values captured by ('%s') in the sprintf() statement (and similarly for the update query). Because I am fairly certain that just turning everything into a JSON string would sanitize my DB input?

Any help would be much appreciated.

1 Answer 1

1

Having spent several hours trying and failing at this today, I believe I managed to find a work around. I have done some testing and it appears to be working. I am posting an answer to my own question in case someone has a similar problem at a different time.

My updated function now looks like this:

save_db <- function (db_pool, x, db_name, db_config, replace_val) {
  # Interpolate the elements of x
  x <- do.call(c, lapply(x, function(y) {
    sql <- "?value"
    sqlInterpolate(db_pool, sql, value = y)
  }))

  # Construct the DB query to be sent to the database
  if (!replace_val) {
    query <- sprintf(
      "INSERT INTO %s (%s) VALUES (%s)",
      db_name,
      paste(names(x), collapse = ", "),
      paste(x, collapse = ", ")
    )

  } else {
    query <- sprintf(
      "UPDATE %s SET %s WHERE %s;",
      db_name,
      paste(paste0(names(x)[-1], " = ", x[-1]), collapse = ", "),
      paste0(names(x)[1], " = ", x[1])
    )
  }

  # Submit the insert query to the database via the opened connection
  RMariaDB::dbExecute(db_pool, query)
}

It appears that the key was to only use the interpolation on the actual JSON string itself, like so:

  x <- do.call(c, lapply(x, function(y) {
    sql <- "?value"
    sqlInterpolate(db_pool, sql, value = y)
  }))

And the rest of the function can be used as is. To see this, let's use the example I provided in my original question:

y <- 1:3
z <- matrix(runif(4), 2, 2)
q <- c("one", "don't")
x <- c(toJSON(y), toJSON(z), toJSON(q))
names(x) <- c("var_1", "var_2", "var_3")
db_name <- "my_db"

# Current sprintf() statement
sprintf(
  "INSERT INTO %s (%s) VALUES ('%s')",
  db_name,
  paste(names(x), collapse = ", "),
  paste(x, collapse = "', '")
)

Which yields the output:

"INSERT INTO my_db (var_1, var_2, var_3) VALUES ('[1,2,3]', '[[0.6573,0.1726],[0.3291,0.9903]]', '[\"one\",\"don't\"]')" 

If I now transform my x as above and use the updated sprintf() call (Note that the extra single quotation marks are removed):

x <- do.call(c, lapply(x, function(y) {
  sql <- "?value"
  sqlInterpolate(ANSI(), sql, value = y)
}))

sprintf(
  "INSERT INTO %s (%s) VALUES (%s)",
  db_name,
  paste(names(x), collapse = ", "),
  paste(x, collapse = ", ")
)

I will get:

"INSERT INTO my_db (var_1, var_2, var_3) VALUES ('[1,2,3]', '[[0.6573,0.1726],[0.3291,0.9903]]', '[\"one\",\"don''t\"]')"

And we see that the single quotation mark in don't is correctly quoted out. If I have missed something crucial in my own solution, please feel free to comment on it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.