ankane / dbx

A fast, easy-to-use database library for R
Other
187 stars 15 forks source link

Overload +-Operator for Character vectors Marked as SQL? #7

Closed petermeissner closed 6 years ago

petermeissner commented 6 years ago

(I moved this over from https://github.com/r-dbi/DBI/issues/260 ... since @krlmlr tries to keep features of the DBI package in reign this package appears to be the right place)

The Problem

Writing SQL is a lot of pasting-together strings. The SQL() function provides a nice entry point to mark character vectors as SQL (which will result in nicer printing).

If we have a way to mark text as SQL would it not be nice to be able to do something 'simply' put together parts of an SQL-statement in an easy manner?


The Solution

SQL() in combination with overloading the plus operator might bring a lot of productivity gain here.

#' +-Operator for SQL
#' 
#' Pastes together two character vectors marked as SQL (via \code{SQL()}). 
#' 
#' @param a first part of SQL statement
#' @param b second part of SQL statement
#'
#' @export
#' @examples
#' 
#' ## SQL("SELECT * FROM mytable ") + "WHERE id ='"  + 1:10 + "'"
#' ## <SQL> SELECT * FROM mytable WHERE id ='1'
#' ## <SQL> SELECT * FROM mytable WHERE id ='2'
#' ## <SQL> SELECT * FROM mytable WHERE id ='3'
#' ## <SQL> SELECT * FROM mytable WHERE id ='4'
#' ## <SQL> SELECT * FROM mytable WHERE id ='5'
#' ## <SQL> SELECT * FROM mytable WHERE id ='6'
#' ## <SQL> SELECT * FROM mytable WHERE id ='7'
#' ## <SQL> SELECT * FROM mytable WHERE id ='8'
#' ## <SQL> SELECT * FROM mytable WHERE id ='9'
#' ## <SQL> SELECT * FROM mytable WHERE id ='10'
#' 
"+.SQL" <- function(a,b) {SQL(paste0(a,b))}
petermeissner commented 6 years ago

@krlmlr suggested making this a S4 method. If you like the idea of the operator per se I can write up the S4 code (and make a pull request?).

petermeissner commented 6 years ago

As discussed in https://github.com/ankane/dbx/issues/5 this is out of scope of the package (for now) - hence I close the issue.