在Shiny中隔离数据库查询

时间:2019-04-16 02:02:13

标签: mysql r shiny

我正在尝试实施以下工作流程: *用户选择所需的分类和数字过滤器。 *按下按钮后,基于这些过滤器,将对Presto数据库运行复杂的查询,并将其作为数据帧存储在内存中。 *对过滤器进行的连续更改不应该调用数据库,而应该过滤内存中的数据帧。

如何实现?我尝试以下(可重复的示例)失败:

library(shiny)
library(shinyWidgets)
library(DT)
library(tidyverse)
library(tidytidbits)
library(pool)
library(DBI)


pool <- dbPool(
  drv = RMySQL::MySQL(),
  dbname = "shinydemo",
  host = "shiny-demo.csa7qlmguqrf.us-east-1.rds.amazonaws.com",
  username = "guest",
  password = "guest",
  minSize = 1,
  maxSize = 3,
  idleTimeout = 2 * 60 * 100
)

onStop(function() {
  poolClose(pool)
})


ui <- fluidPage(
  titlePanel("Basic DataTable"),

  # Create a new Row in the UI for selectInputs
  fluidRow(
    column(4,
        selectInput("name",
                    "Name:",
                    c("all", "Kabul", "Amsterdam"))
    ),
    column(4,
        selectInput("nistrict",
                    "District:",
                    c("all", "Kabol", "Noord-Holland"))
    ),
    column(4,
        switchInput("search", label = icon("search"), value = FALSE)
    )
  ),
  # Create a new row for the table.
  DT::dataTableOutput("table")
)


server <- function(input, output) {

  # Filter data based on selections
  observeEvent(search(), {
    output$table <- renderDataTable({
      if (input$search == TRUE) {
        baseTable <- isolate({
          print("querying database")
          pool %>% tbl("City") %>%
            execute_if(input$name != "all", filter(Name == input$name)) %>%
            collect()
        })
        data <- reactive(baseTable %>%
          execute_if(input$name != "all", filter(Name == input$name)))
      }
      else {
        data <- reactive('i want you to fail')
      }
      datatable(data())
    })
  })
}

shinyApp(ui, server)

0 个答案:

没有答案