R/StmtSelectFields.R

#' SELECT fields statement.
#'
#' This class represents a SQL SELECT statement with specific fields. It
#' requires a list of `ExprField` instances representing the fields to select,
#' with optional `distinct` keyword to remove duplicate results.
#'
#' @examples
#' # Create a SELECT statement with specific fields:
#' field1 <- ExprField$new("title", "books")
#' field2 <- ExprField$new("name", "authors")
#' select_fields <- StmtSelectFields$new(fields = list(field1, field2))
#'
#' # Use the created SELECT statement inside a SELECT query:
#' query <- QuerySelect$new(select = select_fields,
#'                          from = StmtFrom$new("books"))
#'
#' @import R6
#' @include StmtSelect.R
#' @export
StmtSelectFields <- R6::R6Class("StmtSelectFields",
  inherit = StmtSelect,
  public = list(

    #' @description
    #' Initializer
    #' @param fields A list of ExprField instances.
    #' @param distinct Set to TRUE enable `distinct` keyword and remove
    #'                 duplicate results.
    #' @return Nothing.
    initialize = function(fields, distinct = FALSE) {
      chk::chk_all(fields, chk::chk_is, "ExprField")
      private$fields <- fields
      super$initialize(distinct = distinct)
      return(invisible(NULL))
    },

    #' @description
    #' Generates the list of tokens representing this statement.
    #' @return A list of Token objects.
    getTokens = function() {
      tokens <- list(.select, .spc)
      if (private$distinct) {
        tokens <- c(tokens, .distinct, .spc)
      }
      i <- 0L
      for (field in private$fields) {
        if (i > 0L) {
          tokens <- c(tokens, .coma, optspace())
        }
        tokens <- c(tokens, field$getTokens())
        i <- i + 1L
      }
      return(tokens)
    }
  ),
  private = list(
    fields = NULL
  )
)

Try the sqlq package in your browser

Any scripts or data that you put into this service are public.

sqlq documentation built on Sept. 16, 2025, 9:10 a.m.