Skip to content

Support capturing parameterized queries #159

@seasick

Description

@seasick

Brief description of the problem

Currently parameters of e.g. dbSendQuery are not considered when storing the statement and its return value.

When capturing two identical queries with different parameters only the result of the last query persists because the second capturing will overwrite the captured result of the first.

# Simplified code ahead ---v
capture_db_requests({
  dbSendQuery(con, "SELECT * FROM airlines WHERE carrier = $1 LIMIT 1", list("9E"))
  # capturing this overwrites the result of the previous capture, because only the statement is hashed
  dbSendQuery(con, "SELECT * FROM airlines WHERE carrier = $1 LIMIT 1", list("AA")) 
})

with_mock_db({
  # Both queries will get "AA" airlines
  dbSendQuery(con, "SELECT * FROM airlines WHERE carrier = $1 LIMIT 1", list("9E"))
  dbSendQuery(con, "SELECT * FROM airlines WHERE carrier = $1 LIMIT 1", list("AA"))
})
I've build a small test case - click me
# tests/testthat/test-parameterized-query.R
with_mock_path(path = file.path(temp_dir, "parameteterized-query"), {
    capture_db_requests({
        suppressMessages(con <- nycflights13_create_sqlite(verbose = FALSE))

        result <- dbSendQuery(con, "SELECT * FROM airlines WHERE carrier = $1 LIMIT 1", list("9E"))
        dbClearResult(result)

        result <- dbSendQuery(con, "SELECT * FROM airlines WHERE carrier = $1 LIMIT 1", list("AA"))
        dbClearResult(result)

        dbDisconnect(con)
    })

    with_mock_db({
        test_that("fetching queries with parameters", {
            suppressMessages(con <- nycflights13_create_sqlite(verbose = FALSE))

            # make a query
            result <- dbSendQuery(con, "SELECT * FROM airlines WHERE carrier = $1 LIMIT 1", list("9E"))
            rows <- DBI::dbFetch(result)
            dbClearResult(result)

            expect_equal(rows$carrier, "9E")

            # make a different one
            result <- dbSendQuery(con, "SELECT * FROM airlines WHERE carrier = $1 LIMIT 1", list("AA"))
            rows <- DBI::dbFetch(result)
            dbClearResult(result)

            expect_equal(rows$carrier, "AA")

            dbDisconnect(con)
        })
    })
})

Is there currently a way to have identical queries with different parameters and different captures?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions