Created
November 10, 2022 15:20
-
-
Save nbenn/023d177f223a112ec561ea69ea12e385 to your computer and use it in GitHub Desktop.
Auto increment for Postgres (for use within a package)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' @importFrom methods setOldClass setMethod | |
#' @importMethodsFrom DBI dbDataType | |
#' @importClassesFrom RPostgres PqConnection | |
#' Generate SQL for custom data types | |
#' | |
#' SQL for data types as described in [auto_increment()] can be generated | |
#' using [DBI::dbDataType()]. | |
#' | |
#' @param dbObj Object for determining SQL dialect (e.g. connection) | |
#' @param obj Object for determining SQL type | |
#' @param ... Generic consistency | |
#' | |
#' @name dbDataType | |
#' @aliases dbDataType,PqConnection,data.frame-method | |
#' @rdname custom-dbDataType | |
#' @export | |
setMethod( | |
"dbDataType", | |
signature("PqConnection", "data.frame"), | |
function(dbObj, obj, ...) { | |
res <- Map( | |
function(x, i) { | |
dbDataType(dbObj, x, col = DBI::dbQuoteIdentifier(dbObj, i)) | |
}, | |
obj, | |
names(obj) | |
) | |
stopifnot(all(lgl_ply(res, is_string))) | |
unlist(res) | |
} | |
) | |
setOldClass("auto_increment") | |
#' Auto increment type | |
#' | |
#' Class constructor for support of an auto increment type. | |
#' | |
#' @param size Integer size | |
#' | |
#' @export | |
auto_increment <- function(size = c(NA, "small", "big")) { | |
structure(integer(), size = match.arg(size), class = "auto_increment") | |
} | |
#' @name dbDataType | |
#' @aliases dbDataType,PqConnection,auto_increment-method | |
#' @rdname custom-dbDataType | |
#' @export | |
setMethod( | |
"dbDataType", | |
signature("PqConnection", "auto_increment"), | |
function(dbObj, obj, ...) { | |
size <- attr(obj, "size") | |
if (is.na(size)) size <- "" | |
paste0(size, "serial") | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment