I'm trying to create a trivial package which wraps around the odbc
package, basically omitting the connection argument. For now, the package will have a single function:
library(odbc)
getQuery <- function(sql) {
con <- dbConnect(odbc(),
Driver = "SQL Server",
Server = "Foo",
UID = "user",
PWD = "password")
return(dbGetQuery(con, sql))
}
I created the package with usethis
:
create_package('pkg')
use_R('sql_con')
use_package('odbc')
I then modified my code to use the proper namespace and omit the library
call:
# sql_con.R
getQuery <- function(sql) {
con <- odbc::dbConnect(odbc::odbc(),
Driver = "SQL Server",
Server = "Foo",
UID = "user",
PWD = "password")
return(odbc::dbGetQuery(con, sql))
}
I also modified the NAMESPACE and DESCRIPTION files:
# NAMESPACE
exportPattern("^[[:alpha:]]+")
importMethodsFrom(odbc, dbGetQuery, dbConnect)
# DESCRIPTION
Package: pkg
Type: Package
Title: What the Package Does (Title Case)
Version: 0.1.0
Author: Who wrote it
Maintainer: The package maintainer <yourself@somewhere.net>
Description: More about what it does (maybe more than one line)
Use four spaces when indenting paragraphs within the Description.
License: What license is it under?
Encoding: UTF-8
LazyData: true
Depends:
odbc
Building the package works fine, no errors. Running a check also finds no errors (but complains about the lack of man
pages and license information in DESCRIPTION
).
However, if I try to use my package, I get an error:
library(pkg)
getQuery(" SELECT * FROM FooDB")
# Error in (function (classes, fdef, mtable) :
# unable to find an inherited method for function ‘dbGetQuery’ for signature ‘"Microsoft SQL Server", "character"’
If I instead just source()
the package code, it works fine.
I don't know if this is relevant, but exploring with showMethods("dbGetQuery")
indicates that the inherited method is only created when needed. That is, loading odbc
does not create the method with the "Microsoft SQL Server" signature. It's only created once dbGetQuery
is actually called with the relevant signature:
library(odbc)
showMethods("dbGetQuery")
# Function: dbGetQuery (package DBI)
# conn="DBIConnection", statement="character"
# conn="OdbcConnection", statement="character"
con <- odbc::dbConnect(odbc::odbc(),
Driver = "SQL Server",
Server = "Foo",
UID = "user",
PWD = "password")
showMethods("dbGetQuery")
# Function: dbGetQuery (package DBI)
# conn="DBIConnection", statement="character"
# conn="OdbcConnection", statement="character"
dbGetQuery(con, "SELECT * FROM Foo")
showMethods("dbGetQuery")
# Function: dbGetQuery (package DBI)
# conn="DBIConnection", statement="character"
# conn="Microsoft SQL Server", statement="character"
# (inherited from: conn="OdbcConnection", statement="character")
# conn="OdbcConnection", statement="character"
Am I missing anything? I don't know how else to tell R I really need everything odbc
can offer me.