i really need your help.
I have an example of a DataBase which table is "t_client (id_cli, name_cli)"
I want to select the id of client(id_cli) from "selectInput" and the result gives me the name of client (name_cli) by reactive function.
This is my code :
req1 = dbGetQuery(DB, "select id_cli, name_cli from t_client;")
selectInput(inputId = "id_cli", label = "Clients", choices = req1$id_cli)
databaseInput <- reactive({
req1$id_cli = input$id_cli
req2 = dbGetQuery(DB, "select *from t_client where id_cli = 'req1$id_cli';")
req2
})
renderTable({
databaseInput()
})
It doesnt work; i dont have the link between the item from selectInput and the real table "t_client"
Related
For my first shiny application, I want to load data from sql and display it in a table. This works fine, when I only use text input in the sidePanel menu. I want to display all available databases in a drop-down at first. Next, I want the all schemas for that db displayed in a second drop-down, once the db is chosen. Finally I want to select tables in a drop-down, displayed according to the utilized schema and db.
However, I already run into an error (Error in : invalid connection option "SQLdb"), when I am trying to just select the db via drop-down.
# lib
library(DBI)
library(RPostgres)
library(shiny)
library(dplyr)
library(shinydashboard)
# preload
cc<- dbConnect(RPostgres::Postgres(),
dbname = "postgres",
host = "localhost",
port = "5432",
user="postgres",
password="xxxx")
db_list <- dbGetQuery(cc, "SELECT datname FROM pg_database WHERE datistemplate = FALSE")
db_list <- db_list %>% dplyr::filter(!grepl("postgres", datname))
#### UI --------------------------------------------------------------------------------------------------
ui <- dashboardPage(
dashboardHeader(title = "test"),
dashboardSidebar(
sidebarMenu(
menuItem("Load Data",
tabName = "load_data",
icon = icon("database")
)
)
),
dashboardBody(
tabItems(
tabItem(tabName = "load_data",
fluidPage(
sidebarLayout(
sidebarPanel(
#textInput("SQLdb", "Database", value="shiny_data"),
selectInput(inputId = "SQLdb",
label = "Select Database",
choices = db_list,
selected = "shiny_data"),
textInput("schema", "Schema", value="m4_monthly"),
textInput("table", "Table", value="m4_samples"),
textInput("host", "Host", value="localhost"),
textInput("port", "Port", value="5432"),
textInput("user", "User", value = "postgres"),
passwordInput("passwd", "Password"),
actionButton("connectDB", "Load DB table"),
),
mainPanel(
textOutput("test"),
uiOutput("tabnames_ui"),
tableOutput("out"),
dataTableOutput("table")
)))))))
#--------------------------------------------------------------------------------------
#### SERVER
server <- function(input, output, session) {
observe ({
updateSelectInput(session,
"SQLdb",
choices = db_list,
selected = "shiny_data"
)
})
# database load
con=reactiveValues(cc=NULL)
observeEvent(input$connectDB{
con$cc<- dbConnect(RPostgres::Postgres(),
dbname = input$SQLdb,
host = input$host,
port = input$port,
user=input$user,
password=input$passwd)
table_id <- DBI::Id(
schema = input$schema,
table = input$table)
data <- dbReadTable(con$cc, name = table_id, value = input$table)
dbDisconnect(con$cc)
data.frame(data)
output$table <- renderDataTable(data)
})
}
runApp(list(ui = ui, server = server))
I am working on a project that uses TypeORM and PostgreSQL, I am trying to use the query builder to join on multiple conditions. Is there an easier/ more programmatic way to do this than having all the conditions within a string? For example, I want to build the following query to get friends for a user. In SQL this query looks like this (Note: inRel is short for incoming relationship and outRel is short for outgoing relationship)
-- SELECT FRIENDS FOR USER
select outRel."relatingToUserId"
from relationships outRel
inner join relationships inRel
on inRel."userId" = outRel."relatingToUserId"
and inRel."relatingToUserId" = outRel."userId"
and inRel."type" = 'FRIEND'
and outRel."type" = 'FRIEND'
where outRel."userId" = 'some_uuid_for_the_user';
In TypeORM I can accomplish the same result doing
const relationships = await this.createQueryBuilder()
.select('outRel.relatingToUserId')
.from(RelationshipEntity, 'outRel')
.innerJoin(
RelationshipEntity,
'inRel',
`
inRel.userId = outRel.relatingToUserId
AND inRel.relatingToUserId = outRel.userId
AND inRel.type = 'FRIEND'
AND inRel.type = outRel.type
`,
)
.where('outRel.userId = :userId', { userId })
.getMany();
However, I would expect that I should be able to do something more like
const relationships = await this.createQueryBuilder()
.select('outRel.relatingToUserId')
.from(RelationshipEntity, 'outRel')
.innerJoin(RelationshipEntity, 'inRel', 'inRel.userId = outRel.relatingToUserId')
.andWhere('inRel.relatingToUserId = outRel.userId')
.andWhere("inRel.type = 'FRIEND'")
.andWhere('inRel.type = outRel.type')
.where('outRel.userId = :userId', { userId })
.getMany();
But this does not return the same result. Is there a way to build this query more programmatically or am I stuck with a query string?
andWhere are used after .where. Try this:
const relationships = await this.createQueryBuilder()
.select('outRel.relatingToUserId')
.from(RelationshipEntity, 'outRel')
.innerJoin(RelationshipEntity, 'inRel', 'inRel.userId = outRel.relatingToUserId and inRel.relatingToUserId = outRel.userId and inRel.type = outRel.type')
.where('outRel.userId = :userId', { userId })
.andWhere('inRel.type = 'FRIEND'')
.getMany();
I would like to build a shiny app which will allow user to choose the table name from database, and their further plotting etc. I stuck at the point of retrieving the table names from database. I cannot use the tableList which i have created using dbListTables(con,schema="K") as a choice for the selectInput widget. I do not get any error or warning, widget just does not appear at all.
My code:
library(ROracle)
library(shiny)
server <- shinyServer(
function(input, output, session) {
con <- dbConnect(dbDriver("Oracle"),"xxx/K",username="user",password="pwd")
tableList <- dbListTables(con,schema="K")
output$out <- renderPrint(tableList)
df <- data.frame()
quer <- paste("select * from K.", input$tabnames)
df <- data.frame(dbGetQuery(con, quer))
output$table <- renderTable({df})
session$onSessionEnded(function() { dbDisconnect(con) })
})
ui_panel <-
tabPanel("Test",
sidebarLayout(
sidebarPanel(
),
mainPanel(
selectInput("tabnames","tabnames", choices=as.list(tableList)),
tableOutput("out"),
tableOutput("table")
)
)
)
ui <- shinyUI(navbarPage("Test",ui_panel))
runApp(list(ui=ui,server=server))
Thanks for any tipps
[SOLVED] the part for the selectizeInput i solved by placing it on the server side:
library(ROracle)
library(shiny)
library(DT)
server <- shinyServer(
function(input, output, session) {
con <- dbConnect(dbDriver("Oracle"),"xx/K",username="user",password="pwd")
tableList <- dbListTables(con,schema="K")
updateSelectizeInput(session, "tabnames", server = TRUE, choices = tableList)
sqlOutput <- reactive({
sqlInput <- paste("select * from K.",input$tabnames)
dbGetQuery(con, sqlInput)
})
output$table <- DT::renderDataTable(sqlOutput(), server=TRUE, rownames=FALSE, filter="top", options=list(pageLength=10))
session$onSessionEnded(function() { dbDisconnect(con) })
})
ui_panel <-
tabPanel("Test",
sidebarLayout(
sidebarPanel(
),
mainPanel(
selectizeInput("tabnames",label = "server side", choices = NULL),
tableOutput("out"),
tableOutput("table")
)
)
)
ui <- shinyUI(navbarPage("Test",ui_panel))
runApp(list(ui=ui,server=server))
I additionally made the reactive SQL query.
Than i choosed the table from selectizeInput to display, [NOT SOLVED] however it shows me an error:
Error in .oci.GetQuery(conn, statement, data = data, prefetch = prefetch, :
ORA-00903: invalid table name
Than smthg has to be wrong with my SQL Query (Thanks for the tipps here!)
How its even possible if i choosed the table name from the dbListTables?
Any ideas?
I have solved my second question! The problem was very small on the side of ui, instead of dataTableOutput, i had tableOutput, so the ui should look like this:
ui_panel <-
tabPanel("Test",
sidebarLayout(
sidebarPanel(
),
mainPanel(
selectizeInput("tabnames",label = "server side", choices = NULL),
tableOutput("out"),
dataTableOutput("table")
)
)
)
Thanks for all the help!
The following function gives all the related data except artist_id, when run I have checked all elements in the database and ok.
If I change the artist_id to an actual 'id' it shows in the result of the function as WHERE artist_id = 4 AND........
Confess I do not understand what is causing this.
Result of the function:
SELECT `image_album_id`, `member_id`, `artist_id`, `albumname`, `ext`, `timestamp`
FROM album_images WHERE artist_id = AND member_id = 1 AND
image_album_id = 160
<?php
function get_data_nxtprv($fields, $where) {
$return = FALSE;
// Template
$template = "SELECT %s "
. "FROM album_images "
. "WHERE artist_id = " . $artist_id. "
AND member_id = ".$_SESSION['member_id']." %s";
// Current record
$sql = sprintf($template, $fields, $where);
$query = mysql_query($sql);
$query_result = mysql_fetch_assoc($query);
//print_r($sql);
// If data has been found
if ($query_result)
{
$return = $query_result;
}
return $return;
?>
I am not entirely sure I understand your question. But I noticed that your function uses three input variables:
$artist_id, $fields, $where
But $artist_id is not getting passed as an argument.
You would need to modify the function call:
function get_data_nxtprv($artist_id, $fields, $where)
There is an error in your SQL
SELECT `image_album_id`, `member_id`, `artist_id`, `albumname`, `ext`, `timestamp`
FROM album_images WHERE artist_id = AND member_id = 1 AND
image_album_id = 160
should it not be
SELECT `image_album_id`, `member_id`, `artist_id`, `albumname`, `ext`, `timestamp`
FROM album_images WHERE member_id = 1 AND
image_album_id = 160
if artist_id is one of the fields you're looking for?
My LINQ query contains the following Group By statement:
Group p By Key = New With { _
.Latitude = p.Address.GeoLocations.FirstOrDefault(Function(g) New String() {"ADDRESS", "POINT"}.Contains(g.Granularity)).Latitude, _
.Longitude = p.Address.GeoLocations.FirstOrDefault(Function(g) New String() {"ADDRESS", "POINT"}.Contains(g.Granularity)).Longitude}
The query works, but here is the SQL that the clause above produces
SELECT [t6].[Latitude]
FROM (
SELECT TOP (1) [t5].[Latitude]
FROM [dbo].[GeoLocations] AS [t5]
WHERE ([t5].[Granularity] IN (#p0, #p1)) AND ([t5].[AddressId] = [t2].[Addr_AddressId])
) AS [t6]
) AS [value], (
SELECT [t8].[Longitude]
FROM (
SELECT TOP (1) [t7].[Longitude]
FROM [dbo].[GeoLocations] AS [t7]
WHERE ([t7].[Granularity] IN (#p2, #p3)) AND ([t7].[AddressId] = [t2].[Addr_AddressId])
) AS [t8]
) AS [value2]
I am not a SQL expert, but it looks to me that this is rather suboptimal translation. This should really be one query that selects Latitide and Longitude from the first record. Perhaps SQL Server Optimizer will take care of this. But is there a way to nudge Linq to generate a leaner SQL statement to begin with?
I tried the following, too..
Group p By Key = p.Address.GeoLocations.Where(Function(g) New String() {"ADDRESS", "POINT"}.Contains(g.Granularity)). _
Select(Function(g) New With {.Latitude = g.Latitude, .Longitude = g.Longitude}).FirstOrDefault
but this produced an error: "A group by expression can only contain non-constant scalars that are comparable by the server."
Sorry to reply in c#...
Here's what you have, translated to c#:
List<string> params = new List<string>()
{ "Address", "Point" };
from p in people
group p by new {
Latitude = p.Address.GeoLocations
.FirstOrDefault(g => params.Contains(g.Granularity)).Latitude,
Longitude = p.Address.GeoLocations
.FirstOrDefault(g => params.Contains(g.Granularity)).Longitude
};
Here's a rewrite, using the let keyword.
from p in people
let loc = p.Address.GeoLocations
.FirstOrDefault(g => params.Contains(g.Granularity))
group p by new
{
Latitude = loc.Latitude,
Longitude = loc.Longitude
};