R/StmtCreate.R

#' CREATE TABLE statement.
#'
#' @examples
#' # To generate a simple CREATE TABLE statement:
#' fields_def <- list(ExprFieldDef$new('id', 'integer', primary=TRUE),
#'                    ExprFieldDef$new('title', 'varchar(200)', nullable=FALSE),
#'                    ExprFieldDef$new('author', 'varchar(80)', nullable=FALSE))
#' StmtCreate$new(tabl = 'books', fields_def = fields_def)
#'
#' @import R6
#' @include Statement.R
#' @export
StmtCreate <- R6::R6Class("StmtCreate",
  inherit = Statement,
  public = list(

    #' @description
    #' Initializer.
    #' @param tabl A table name.
    #' @param fields_def An instance of ExprListFields
    #' @return Nothing.
    initialize = function(tabl, fields_def) {
      chk::chk_all(fields_def, chk::chk_is, "ExprFieldDef")
      chk::chk_string(tabl)
      private$fields_def <- fields_def
      private$table <- tabl
    },

    #' @description
    #' Generates the list of tokens representing this statement.
    #' @return A list of Token objects.
    getTokens = function() {

      tokens <- list(.create, .spc, .table, .spc,
                     TokenIdentifier$new(private$table), .spc, .lparen)

      # Add field definitions
      i <- 0L
      for (def in private$fields_def) {
        if (i > 0L) {
          tokens <- c(tokens, .coma, optspace())
        }
        tokens <- c(tokens, def$getTokens())
        i <- i + 1L
      }

      # Close parenthesis
      tokens <- c(tokens, .rparen)

      return(tokens)
    }
  ),
  private = list(
    table = NULL,
    fields_def = 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.