下面是一个 R 函数,它读取多行 SQL 查询(来自文本文件)并将其转换为单行字符串。该功能删除格式和整行注释。
要使用它,请运行代码来定义函数,您的单行字符串将是运行 ONELINEQ("querytextfile.sql","~/path/to/thefile") 的结果。
它是如何工作的:内联注释详细说明了这一点;它读取查询的每一行并删除(替换为空)写出查询的单行版本(如问题中所要求的)不需要的任何内容。结果是一个行列表,其中一些是空白的并被过滤掉;最后一步是将这个(未列出的)列表粘贴在一起并返回单行。
#
# This set of functions allows us to read in formatted, commented SQL queries
# Comments must be entire-line comments, not on same line as SQL code, and begun with "--"
# The parsing function, to be applied to each line:
LINECLEAN <- function(x) {
x = gsub("\t+", "", x, perl=TRUE); # remove all tabs
x = gsub("^\\s+", "", x, perl=TRUE); # remove leading whitespace
x = gsub("\\s+$", "", x, perl=TRUE); # remove trailing whitespace
x = gsub("[ ]+", " ", x, perl=TRUE); # collapse multiple spaces to a single space
x = gsub("^[--]+.*$", "", x, perl=TRUE); # destroy any comments
return(x)
}
# PRETTYQUERY is the filename of your formatted query in quotes, eg "myquery.sql"
# DIRPATH is the path to that file, eg "~/Documents/queries"
ONELINEQ <- function(PRETTYQUERY,DIRPATH) {
A <- readLines(paste0(DIRPATH,"/",PRETTYQUERY)) # read in the query to a list of lines
B <- lapply(A,LINECLEAN) # process each line
C <- Filter(function(x) x != "",B) # remove blank and/or comment lines
D <- paste(unlist(C),collapse=" ") # paste lines together into one-line string, spaces between.
return(D)
}
# TODO: add eof newline automatically to remove warning
#############################################################################################