database: connections pane

When i make a connection to a database using the DBI package in the following way:

con <- DBI::dbConnect(odbc::odbc(), dsn=server, uid=uid, pwd=pwd, timeout = 10)

A connection is made and all tables are displayed in the connections tab of rstudio.

However, If i run the same command in a function like this:

test <- function(){
  con <- DBI::dbConnect(odbc::odbc(), dsn=server, uid=uid, pwd=pwd, timeout = 10)

then a connection made to the database but it is not registered in the connection pane. Hence no tables are shown

Why is this?


The Rstudio connection pane reacts to Connection contract that is included in package. In your case, this is the odbc package that has the connection contract. And it is clever enough to know when the dbConnect function is ran from the top level or from inside the function. In the second case, it won't open the connection pane. This is because often when not executed from top level, it is often inside a script and you don't want to have the connection that opens in that case.

The trick is here in source code and is quite complicated.

If you want to create functions and a package that wraps DBI:dbConnect, you can use the extension mechanism for connection pane with the connection contract inside your own package

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.