-
Notifications
You must be signed in to change notification settings - Fork 64
/
glue_sql.Rd
219 lines (184 loc) · 7.54 KB
/
glue_sql.Rd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/sql.R
\name{glue_sql}
\alias{glue_sql}
\alias{glue_data_sql}
\title{Interpolate strings with SQL escaping}
\usage{
glue_sql(
...,
.con,
.sep = "",
.envir = parent.frame(),
.open = "{",
.close = "}",
.na = DBI::SQL("NULL"),
.null = character(),
.comment = "#",
.literal = FALSE,
.trim = TRUE
)
glue_data_sql(
.x,
...,
.con,
.sep = "",
.envir = parent.frame(),
.open = "{",
.close = "}",
.na = DBI::SQL("NULL"),
.null = character(),
.comment = "#",
.literal = FALSE,
.trim = TRUE
)
}
\arguments{
\item{...}{[\code{expressions}]\cr Unnamed arguments are taken to be expression
string(s) to format. Multiple inputs are concatenated together before formatting.
Named arguments are taken to be temporary variables available for substitution.
\if{html}{\out{<div class="sourceCode">}}\preformatted{For `glue_data()`, elements in `...` override the values in `.x`.
}\if{html}{\out{</div>}}}
\item{.con}{[\code{DBIConnection}]: A DBI connection object obtained from
\code{\link[DBI:dbConnect]{DBI::dbConnect()}}.}
\item{.sep}{[\code{character(1)}: \sQuote{""}]\cr Separator used to separate elements.}
\item{.envir}{[\code{environment}: \code{parent.frame()}]\cr Environment to evaluate each expression in. Expressions are
evaluated from left to right. If \code{.x} is an environment, the expressions are
evaluated in that environment and \code{.envir} is ignored. If \code{NULL} is passed, it is equivalent to \code{\link[=emptyenv]{emptyenv()}}.}
\item{.open}{[\code{character(1)}: \sQuote{\\\{}]\cr The opening delimiter. Doubling the
full delimiter escapes it.}
\item{.close}{[\code{character(1)}: \sQuote{\\\}}]\cr The closing delimiter. Doubling the
full delimiter escapes it.}
\item{.na}{[\code{character(1)}: \code{DBI::SQL("NULL")}]\cr Value to replace
\code{NA} values with. If \code{NULL} missing values are propagated, that is an \code{NA}
result will cause \code{NA} output. Otherwise the value is replaced by the
value of \code{.na}.}
\item{.null}{[\code{character(1)}: \sQuote{character()}]\cr Value to replace
NULL values with. If \code{character()} whole output is \code{character()}. If
\code{NULL} all NULL values are dropped (as in \code{paste0()}). Otherwise the
value is replaced by the value of \code{.null}.}
\item{.comment}{[\code{character(1)}: \sQuote{#}]\cr Value to use as the comment
character.}
\item{.literal}{[\code{boolean(1)}: \sQuote{FALSE}]\cr Whether to treat single or
double quotes, backticks, and comments as regular characters (vs. as
syntactic elements), when parsing the expression string. Setting \code{.literal = TRUE} probably only makes sense in combination with a custom
\code{.transformer}, as is the case with \code{glue_col()}. Regard this argument
(especially, its name) as experimental.}
\item{.trim}{[\code{logical(1)}: \sQuote{TRUE}]\cr Whether to trim the input
template with \code{\link[=trim]{trim()}} or not.}
\item{.x}{[\code{listish}]\cr An environment, list, or data frame used to lookup values.}
}
\value{
A \code{\link[DBI:SQL]{DBI::SQL()}} object with the given query.
}
\description{
SQL databases often have custom quotation syntax for identifiers and strings
which make writing SQL queries error prone and cumbersome to do. \code{glue_sql()} and
\code{glue_data_sql()} are analogs to \code{\link[=glue]{glue()}} and \code{\link[=glue_data]{glue_data()}} which handle the
SQL quoting. \code{glue_sql_collapse()} can be used to collapse \code{\link[DBI:SQL]{DBI::SQL()}} objects.
They automatically quote character results, quote identifiers if the glue
expression is surrounded by backticks '\verb{`}' and do not quote
non-characters such as numbers. If numeric data is stored in a character
column (which should be quoted) pass the data to \code{glue_sql()} as a
character.
Returning the result with \code{\link[DBI:SQL]{DBI::SQL()}} will suppress quoting if desired for
a given value.
Note \href{https://solutions.posit.co/connections/db/best-practices/run-queries-safely/#parameterized-queries}{parameterized queries}
are generally the safest and most efficient way to pass user defined
values in a query, however not every database driver supports them.
If you place a \code{*} at the end of a glue expression the values will be
collapsed with commas, or if there are no values, produce \code{NULL}.
This is useful for (e.g.) the
\href{https://www.w3schools.com/sql/sql_in.asp}{SQL IN Operator}.
}
\examples{
\dontshow{if (requireNamespace("DBI", quietly = TRUE) && requireNamespace("RSQLite", quietly = TRUE)) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf}
con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
iris2 <- iris
colnames(iris2) <- gsub("[.]", "_", tolower(colnames(iris)))
DBI::dbWriteTable(con, "iris", iris2)
var <- "sepal_width"
tbl <- "iris"
num <- 2
val <- "setosa"
glue_sql("
SELECT {`var`}
FROM {`tbl`}
WHERE {`tbl`}.sepal_length > {num}
AND {`tbl`}.species = {val}
", .con = con)
# If sepal_length is store on the database as a character explicitly convert
# the data to character to quote appropriately.
glue_sql("
SELECT {`var`}
FROM {`tbl`}
WHERE {`tbl`}.sepal_length > {as.character(num)}
AND {`tbl`}.species = {val}
", .con = con)
# `glue_sql()` can be used in conjuction with parameterized queries using
# `DBI::dbBind()` to provide protection for SQL Injection attacks
sql <- glue_sql("
SELECT {`var`}
FROM {`tbl`}
WHERE {`tbl`}.sepal_length > ?
", .con = con)
query <- DBI::dbSendQuery(con, sql)
DBI::dbBind(query, list(num))
DBI::dbFetch(query, n = 4)
DBI::dbClearResult(query)
# `glue_sql()` can be used to build up more complex queries with
# interchangeable sub queries. It returns `DBI::SQL()` objects which are
# properly protected from quoting.
sub_query <- glue_sql("
SELECT *
FROM {`tbl`}
", .con = con)
glue_sql("
SELECT s.{`var`}
FROM ({sub_query}) AS s
", .con = con)
# If you want to input multiple values for use in SQL IN statements put `*`
# at the end of the value and the values will be collapsed and quoted appropriately.
glue_sql("SELECT * FROM {`tbl`} WHERE sepal_length IN ({vals*})",
vals = 1, .con = con)
glue_sql("SELECT * FROM {`tbl`} WHERE sepal_length IN ({vals*})",
vals = 1:5, .con = con)
glue_sql("SELECT * FROM {`tbl`} WHERE species IN ({vals*})",
vals = "setosa", .con = con)
glue_sql("SELECT * FROM {`tbl`} WHERE species IN ({vals*})",
vals = c("setosa", "versicolor"), .con = con)
# If you need to reference variables from multiple tables use `DBI::Id()`.
# Here we create a new table of nicknames, join the two tables together and
# select columns from both tables. Using `DBI::Id()` and the special
# `glue_sql()` syntax ensures all the table and column identifiers are quoted
# appropriately.
iris_db <- "iris"
nicknames_db <- "nicknames"
nicknames <- data.frame(
species = c("setosa", "versicolor", "virginica"),
nickname = c("Beachhead Iris", "Harlequin Blueflag", "Virginia Iris"),
stringsAsFactors = FALSE
)
DBI::dbWriteTable(con, nicknames_db, nicknames)
cols <- list(
DBI::Id(iris_db, "sepal_length"),
DBI::Id(iris_db, "sepal_width"),
DBI::Id(nicknames_db, "nickname")
)
iris_species <- DBI::Id(iris_db, "species")
nicknames_species <- DBI::Id(nicknames_db, "species")
query <- glue_sql("
SELECT {`cols`*}
FROM {`iris_db`}
JOIN {`nicknames_db`}
ON {`iris_species`}={`nicknames_species`}",
.con = con
)
query
DBI::dbGetQuery(con, query, n = 5)
DBI::dbDisconnect(con)
\dontshow{\}) # examplesIf}
}
\seealso{
\code{\link[=glue_sql_collapse]{glue_sql_collapse()}} to collapse \code{\link[DBI:SQL]{DBI::SQL()}} objects.
}