Compare commits

...

73 Commits

Author SHA1 Message Date
marcelcosta 560540cf1a Commit in cytometry. 2023-10-10 12:35:43 +02:00
marcelcosta bd52e8c452 Corrección nombre de fecha de extracción. Solución de bug. 2023-02-02 16:54:09 +01:00
marcelcosta 43b807cc63 Corrección de la función de backup. 2022-07-04 11:09:20 +02:00
marcelcosta cb38ea347d Añadir notificación de sincronización y backup de nitrógeno. 2022-07-04 11:08:45 +02:00
marcelcosta 6671939939 Cambiar sistema de pedir contraseña. 2022-07-04 10:58:27 +02:00
marcelcosta a6f0c97d47 Añadir la opción de pasar la ruta de citometría en texto. 2022-04-20 15:34:54 +02:00
marcelcosta 56484a5903 Volver a meter unas línias borradas por error. 2022-04-20 12:13:27 +02:00
marcelcosta b5323436ec Boleanas en la app. 2022-04-20 09:49:37 +02:00
marcelcosta a57fb3aac8 Gates booleanas se hacen en R y no en Flowjo (que enlentece mucho el análisis). 2022-04-06 16:54:51 +02:00
marcelcosta dbb8e1ed0d Merge branch 'dev' 2022-04-06 12:42:53 +02:00
marcelcosta e6c2a32ddb Corregir exportar png IC 2022-04-06 12:42:31 +02:00
marcelcosta 51acdd0ece Merge branch 'dev' 2022-04-06 12:35:16 +02:00
marcelcosta dcbf4f8b9d Canvi en l'ordre de les dependències. 2022-04-06 12:32:41 +02:00
marcelcosta 001f64cc76 Merge branch 'dev' 2022-04-06 11:18:24 +02:00
marcelcosta e95caafe28 Cambio a pie chart para Visor IC. 2022-04-05 16:57:26 +02:00
marcelcosta f45ebfd106 Merge branch 'dev' 2022-04-05 10:09:30 +02:00
marcelcosta cb6c739d14 Para actualizar la tabla Poblaciones de citometría, permitir que falten poblaciones (de cara a agrupar diferentes paneles). 2022-04-05 10:08:26 +02:00
marcelcosta 20bf1d2c20 He añadido al visor de muestras el plot de IC. 2022-04-04 17:30:55 +02:00
marcelcosta a5581182c2 Añadir al visor de muestras el plot de poblaciones. 2022-04-04 17:15:12 +02:00
marcelcosta ab1684651e Completado procesado de datos de Checkpoint Inhibitors. 2022-04-04 17:14:42 +02:00
marcelcosta 67ba4921ca Añadir sección de citometría para tinciones de Poblaciones. 2022-04-04 15:40:54 +02:00
marcelcosta db6c07595c Cambiar etiquetas. 2022-04-04 11:37:56 +02:00
marcelcosta 35e4d31495 Iniciar sección citometría. Botón para el directorio. 2022-04-04 11:35:23 +02:00
marcelcosta 38aa06c4ee Añadir etiquetas para el código. 2022-04-04 11:34:43 +02:00
marcelcosta 38e902cef0 Merge branch 'dev' 2022-04-04 10:53:51 +02:00
marcelcosta 3492b7f7ef Corregir año en la fecha de tabla clinics 2022-04-01 12:26:42 +02:00
marcelcosta 44901be490 Corregir año en la fecha de tabla clinics 2022-04-01 12:26:04 +02:00
marcelcosta 3c8a69b21c Merge branch 'main' into dev 2022-04-01 12:21:02 +02:00
Costa 9b8f24ddd8 Corregir formato en las fechas de la plantilla CLINICS. 2022-03-31 14:18:46 +02:00
Costa ea45d8c845 merge with nitro 2022-03-31 13:40:47 +02:00
Costa 134133498b Corregir carga librerías para merge 2022-03-29 12:24:11 +02:00
Costa c9d09c44a2 Cambio de "Sincronizar" a "Actualizar" nitrógeno. 2022-03-28 14:52:42 +02:00
Costa b12ae3fd5f Introducción de un botón para actualizar nitrógeno. 2022-03-28 14:52:04 +02:00
Costa 2909f49eec Añadido plot para expresión de genes. 2022-03-28 12:49:29 +02:00
Costa b14fddf8fe Visor scRNAseq. 2022-03-22 16:29:04 +01:00
Costa 5bbd25c64d Empezar visor scRNAseq. 2022-03-22 14:26:33 +01:00
Costa 5ea3b493f4 Añadir la sincronización de tablas para CC. 2022-03-22 14:25:17 +01:00
Costa ffdf64d736 Añadir cancer de cólon. 2022-03-17 17:15:54 +01:00
Costa af5eee3a33 Relleno del visor - fase I 2022-03-17 16:21:24 +01:00
Costa 6cdde0282a Creación de una división por paneles. 2022-03-15 11:38:41 +01:00
Costa f4c6fae34a Cambio en el formato de definir las rutas. 2022-03-04 17:46:56 +01:00
Costa a8ca15592e Corrección de la función de importar NHC de excel. 2022-03-04 17:46:37 +01:00
Costa 022a222ddf Soporte para base de datos OVID. 2022-03-04 14:56:19 +01:00
Costa 5762efa5e4 Consistencia en sqlGenOVID. 2022-03-03 19:09:29 +01:00
Costa df0e5d4985 Añadir espacio 2022-03-02 14:10:39 +01:00
Costa b968de1fb1 Añadir aplicación shiny 2022-03-02 14:01:05 +01:00
Costa 52f5ad865d Poder cambiar la ruta de la función sqlInitialize. 2022-03-02 14:00:12 +01:00
Costa 72f89330e6 Machacar plantilla. 2022-03-01 14:43:47 +01:00
Costa 109acff436 Generar tabla vacía cuando no haya CNAG y RNA. 2022-03-01 14:43:25 +01:00
Costa 76fa2fc0b1 No machacar la columna Samples de la pestaña NHC de la plantilla. 2022-03-01 14:35:34 +01:00
Costa f4f4e6a350 Añadir soporte para asignar CNAG y RNADNA. También para incluir automaticamente la fecha. 2022-03-01 14:26:15 +01:00
del Carpio Huerta e948b086ed Quitar un Id. 2022-03-01 13:03:42 +01:00
del Carpio Huerta ea01f18d16 Solucionar problemas en la modificación y entrada de nuevos elementos de la tabla CLINICOS. 2022-02-28 16:06:49 +01:00
del Carpio Huerta 1be48b44fb Mejorar el escriturado de la pestaña nhc de la plantilla. 2022-02-28 16:06:22 +01:00
del Carpio Huerta 766fe1f4d4 Error en la función de llenar la plantilla. 2022-02-28 16:05:48 +01:00
del Carpio Huerta 34b54230cb Solucionar otro problema de duplicado. 2022-02-28 16:05:06 +01:00
del Carpio Huerta 2e4f3416e6 Solucionar error cuando el NHC está duplicado. 2022-02-28 16:04:36 +01:00
Costa 1613207bf6 Corregir función sqlBackup. 2022-01-27 15:04:13 +01:00
Costa 4ba729e6c6 Correction of conflicts for merging UM to main.
Merge branch 'UM'

# Conflicts:
#	workflow.R
2022-01-24 15:24:59 +01:00
Costa f2f8f12855 Correct workflow to merge.
Merge branch 'main' of https://git.ratg.cat/marcelcosta/BDAccess

# Conflicts:
#	workflow.R
2022-01-24 15:20:56 +01:00
Costa 3b8a4c0657 Correcting some workflow positions. Changing sqlDropLast to sqlLastDrop to avoid errors with sqlDrop. 2022-01-24 14:58:07 +01:00
Costa 8c8065fe9d Corregido el error en el que no había pacientes nuevos en la función sqlGenOVID. 2021-12-20 16:17:37 +01:00
Costa 944b5df181 Updating documentation. 2021-12-20 16:08:10 +01:00
Costa a87460b6bb Completar compatibilidad con MU. 2021-12-20 15:20:11 +01:00
Marin Jimenez d9e8117b83 Cambio de orden en funciones inciales 2021-11-17 16:04:43 +01:00
Costa 39c9f9bcc4 He puesto el sqlInitizalize antes del sqlBackup. 2021-11-17 15:21:48 +01:00
Costa d863315655 He creado la función sqlMultiSamples. También he adaptado la función sqlGenOVID para que sea usable para UM. 2021-11-17 15:20:44 +01:00
Costa 126b8c4ee2 Optimización de sqlShowSamples. 2021-11-16 12:37:40 +01:00
Costa e185a1e44d Adding dbtype to sqlShowSamples function. 2021-11-16 11:10:11 +01:00
Costa ec3a8328e7 Adding dbtype in functions. 2021-11-15 17:42:40 +01:00
Costa 3f927a5364 Start changes to both OV and UM. 2021-11-15 17:40:00 +01:00
Marin Jimenez 80dc3ec3d7 Merge branch 'main' of https://git.ratg.cat/marcelcosta/BDAccess 2021-11-15 14:19:51 +01:00
Marin Jimenez 24cd858bcd Añadir lectura de NHCs. Solución error en sincronización de SAMPLES por la fecha de columna nueva. 2021-11-15 14:19:17 +01:00
7 changed files with 2938 additions and 423 deletions
+1431
View File
File diff suppressed because it is too large Load Diff
+233 -36
View File
@@ -8,6 +8,7 @@
<li><a href="#sqlgenovid">sqlGenOVID</a></li>
<li><a href="#sqlwritetemp">sqlWriteTemp</a></li>
<li><a href="#sqlsincbd">sqlSincBD</a></li>
<li><a href="#sqlmultisamples">sqlMultiSamples</a></li>
</ul>
</div>
@@ -19,7 +20,7 @@
Removes from Database the last (or the amount specified) entry.
### Usage
sqlDropLast(conn, tablename, droplast=1)
sqlDropLast(conn, tablename, droplast=1, dbtype=NULL)
### Arguments
Argument|Description
@@ -27,6 +28,7 @@ Argument|Description
conn|connection handle returned by odbcConnect.
tablename|character: a database table name accessible from the connected DSN.
droplast|the amount of lines to be removed from the table strating from tail. By default, it removes only 1 line.
dbtype|used to manually specify the database type. It defaults to NULL and the type is deduced.
### Details
Removes from Database the last (or the amount specified) entry.
@@ -42,10 +44,17 @@ sqlDropLast(dta, "TableTest")
### Function
```r
sqlDropLast<-function(conn, tablename, droplast=1){
sqlDropLast<-function(conn, tablename, droplast=1,dbtype=NULL){
if(sqlTables(conn) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
if(sqlTables(conn) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
table<-sqlFetch(conn, tablename)
table<-table[1:(nrow(table)-droplast),]
sqlSave(conn, table, tablename = tablename, safer = F)
if (dbtype == "OV"){sqlSave(conn, table, tablename = tablename, safer = F)}
if (dbtype == "UM"){
sqlDrop(conn, tablename)
sqlSave(conn, table, tablename = tablename, safer = F)}
}
```
@@ -94,13 +103,14 @@ sqlInitialize<-function(){
Creates a Back Up copy of the database.
### Usage
sqlBackUp(dbfile=file,bu.dir="BU_OVARIO")
sqlBackUp(dbfile=file,conn=dta,bu.dir=NULL)
### Arguments
Argument|Description
---|---
dbfile| Database File location.
bu.dir| Directory under the DB file where the back up will be placed.
conn|connection handle returned by odbcConnect.
bu.dir|Directory under the DB file where the back up will be placed. It defaults to NULL and is deduced from conn database.
### Details
Creates a Back Up copy of the database. It adds the date in front of the back up file.
@@ -116,7 +126,10 @@ sqlBackUp()
### Function
```r
sqlBackUp<-function(dbfile=file,bu.dir="BU_OVARIO"){
sqlBackUp<-function(dbfile=file,conn=dta,bu.dir=NULL){
if(sqlTables(conn) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){bu.dir<-"BU_UM"}
if(sqlTables(conn) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){bu.dir<-"BU_OVARIO"}
db=strsplit(dbfile, "/")[[1]]%>% tail(n=1)
bu_path<-gsub(db,bu.dir,dbfile)
if (!dir.exists(bu_path)){
@@ -136,7 +149,7 @@ sqlBackUp<-function(dbfile=file,bu.dir="BU_OVARIO"){
Shows if there are already samples from the specified NHCs.
### Usage
sqlShowSamples(conn=dta, nhcs=nhc.test, verb=F)
sqlShowSamples(conn=dta, nhcs=nhc.test, verb=F, dbtype=NULL)
### Arguments
Argument|Description
@@ -144,6 +157,7 @@ Argument|Description
conn|connection handle returned by odbcConnect.
nhcs|Character vector with the NHCs to test.
verb|Verbose: if TRUE, all the columns from "SAMPLES" table are printed.
dbtype|used to manually specify the database type. It defaults to NULL and the type is deduced.
### Details
Takes the NHCs listed in the nhcs vector and checks if there are already samples from those patients.
@@ -160,18 +174,27 @@ sqlShowSamples()
### Function
```r
sqlShowSamples<-function(conn=dta, nhcs=nhc.test, verb=F){
sqlShowSamples<-function(conn=dta, nhcs=nhc.test, verb=F, dbtype=NULL){
if(sqlTables(dta) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
if(sqlTables(dta) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
if (dbtype == "OV"){
db<-c("dbtables"="SAMPLES", "dbcode"="OVID", "dbsamples"="samples")
query<-paste0("SELECT O.NHC,S.* FROM ",db["dbtables"]," S INNER JOIN ",db["dbcode"]," O ON O.",db["dbcode"],"=S.",db["dbcode"])
}
if (dbtype == "UM"){
db<-c("dbtables"="MUESTRAS", "dbcode"="UMID", "dbsamples"="CODIGO")
query<-paste0("SELECT O.NHC,S.* FROM ",db["dbtables"]," S INNER JOIN ",db["dbcode"]," O ON O.",db["dbcode"],"=S.",db["dbcode"])
}
if (nrow(sqlQuery(conn, query) %>% filter(NHC %in% nhcs)) == 0){
return("No hay muestras de ningún paciente.")
}
if (isFALSE(verb)){
sqlQuery(conn, "SELECT O.NHC,S.*
FROM SAMPLES S
INNER JOIN OVID O
ON O.OVID=S.OVID") %>% filter(NHC %in% nhcs) %>%
group_by(NHC,OVID) %>% summarise(Samples=length(samples), Names=paste0(samples, collapse = ";")) %>% merge(data.frame(NHC=nhcs),all=T)
sqlQuery(conn, query) %>% filter(NHC %in% nhcs) %>%
group_by(NHC,UQ(rlang::sym(db["dbcode"]))) %>% summarise(Samples=length(UQ(rlang::sym(db["dbsamples"]))), Names=paste0(UQ(rlang::sym(db["dbsamples"])), collapse = ";")) %>%
merge(data.frame(NHC=nhcs),all=T) %>% mutate(NHC=factor(NHC,levels = nhcs)) %>% arrange(NHC)
}else{
sqlQuery(conn, "SELECT O.NHC,S.*
FROM SAMPLES S
INNER JOIN OVID O
ON O.OVID=S.OVID") %>% filter(NHC %in% nhcs)
sqlQuery(conn, query) %>% filter(NHC %in% nhcs)
}
}
```
@@ -181,10 +204,10 @@ sqlShowSamples<-function(conn=dta, nhcs=nhc.test, verb=F){
## sqlGenOVID
### Description
Generates new consecutive OVID code for the patients that are not found in the DB.
Generates new consecutive OVID or UMID code for the patients that are not found in the DB.
### Usage
sqlGenOVID(conn=dta, nhcs=nhc.test, verb=T, sinc=F)
sqlGenOVID(conn=dta, nhcs=nhc.test, verb=T, sinc=F, dbtype=NULL)
### Arguments
Argument|Description
@@ -193,9 +216,10 @@ conn|connection handle returned by odbcConnect.
nhcs|Character vector with the NHCs to test.
verb|Verbose: if TRUE (default), it prints the data.frame with the generated OVID codes.
sinc|If TRUE (default is FALSE for security), it adds the new entries to the "OVID" table in the DB.
dbtype|used to manually specify the database type. It defaults to NULL and the type is deduced.
### Details
Generates new consecutive OVID code for the patients that are not found in the DB.
Generates new consecutive OVID or UMID code for the patients that are not found in the DB.
### Value
If verb is TRUE, it returns a data.frame.
@@ -209,23 +233,41 @@ sqlGenOVID(sinc=T)
### Function
```r
sqlGenOVID<-function(conn=dta, nhcs=nhc.test, verb=T, sinc=F){
ovid<-sqlFetch(conn,"OVID")
sqlGenOVID<-function(conn=dta, nhcs=nhc.test, verb=T, sinc=F, dbtype=NULL){
if(sqlTables(dta) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
if(sqlTables(dta) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
new.nhc<-nhcs[!nhcs %in% ovid$NHC]
next.num<-gsub("OVID","",ovid$OVID) %>% as.numeric %>% max(na.rm=T)+1
if (dbtype == "OV"){
db<-c("dbcode"="OVID")
}
if (dbtype == "UM"){
db<-c("dbcode"="UMID")
}
dbid<-sqlFetch(conn,db["dbcode"])
new.nhc<-nhcs[!nhcs %in% dbid$NHC]
next.num<-gsub(db["dbcode"],"",dbid[,db["dbcode"]]) %>% as.numeric %>% max(na.rm=T)+1
last.num<-next.num+(length(new.nhc)-1)
upd.ovid<-rbind(ovid,data.frame("NHC"=new.nhc, "OVID"=sprintf("OVID%04d",next.num:last.num)))
rownames(upd.ovid)<-as.character(1:nrow(upd.ovid))
upd.ovid<-filter(upd.ovid, NHC %in% new.nhc) %>% mutate(NHC=as.character(NHC))
newtab<-data.frame("NHC"=new.nhc, "ID"=sprintf("%s%04d",db["dbcode"],next.num:last.num)) %>% rename(!!db["dbcode"]:="ID")
if(dbtype=="OV"){
dbid<-rbind(dbid,newtab)
}
if(dbtype=="UM"){
dbid<-merge(dbid, newtab, all=T) %>% select(Id,NHC,UMID) %>% arrange(Id)
dbid$Id<-as.numeric(rownames(dbid))
dbid$NHC<-as.numeric(dbid$NHC)
}
rownames(dbid)<-as.character(1:nrow(dbid))
dbid<-filter(dbid, NHC %in% new.nhc) %>% mutate(NHC=as.character(NHC))
if (sinc){
### !! Atención, esto cambia la base de datos:
sqlSave(conn, upd.ovid, tablename="OVID", append = T)
sqlSave(conn, dbid, tablename=db["dbcode"], append = T)
print("La base ha sido actualizada.")
}
if (verb){
return(upd.ovid)
return(dbid)
}
}
```
@@ -235,10 +277,10 @@ sqlGenOVID<-function(conn=dta, nhcs=nhc.test, verb=T, sinc=F){
## sqlWriteTemp
### Description
Fills the Query Template file with the OVID and OV newly generated codes.
Fills the Query Template file with the OVID or UMID and OV or UM newly generated codes.
### Usage
sqlWriteTemp(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod=T, clinics.mod=T)
sqlWriteTemp(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod=T, clinics.mod=T, dbtype=NULL)
### Arguments
Argument|Description
@@ -248,9 +290,10 @@ nhcs|Character vector with the NHCs to test.
file|Template file that will be used to interact with the DB.
samples.mod|If TRUE (default), it fills the "samples" template sheet.
clinics.mod|If TRUE (default), it fills the "CLINICS" template sheet.
dbtype|used to manually specify the database type. It defaults to NULL and the type is deduced.
### Details
Fills the Query Template file with the OVID and OV newly generated codes. It is required that the DB has been updated with the sqlGenOVID function. It replaces previous content in the template file sheets that are filled. In the case of "CLINICS" table, if there were already an entry in the DB for that OVID code, the template file is filled with that information.
Fills the Query Template file with the OVID and OV or UMID and UM newly generated codes. It is required that the DB has been updated with the sqlGenOVID function. It replaces previous content in the template file sheets that are filled. In the case of "CLINICS" table, if there were already an entry in the DB for that OVID/UMID code, the template file is filled with that information.
### Value
Invisibly for success (and failures cause errors).
@@ -265,7 +308,11 @@ sqlWriteTemp()
### Function
```r
sqlWriteTemp<-function(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod=T, clinics.mod=T){
sqlWriteTemp<-function(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod=T, clinics.mod=T, dbtype=NULL){
if(sqlTables(dta) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
if(sqlTables(dta) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
if (dbtype=="OV"){
upd.ovid<-sqlFetch(conn, "OVID") %>% filter(NHC %in% nhcs)
if (samples.mod){
## Generar código para las nuevas muestras
@@ -297,6 +344,39 @@ sqlWriteTemp<-function(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod
if (clinics.mod){writeData(wb,"CLINICS",upd.clinics)}
saveWorkbook(wb,file,overwrite = TRUE)
}
if (dbtype=="UM"){
upd.umid<-sqlFetch(conn, "UMID") %>% filter(NHC %in% nhcs)
if (samples.mod){
## Generar código para las nuevas muestras
samples<-sqlFetch(conn, "MUESTRAS")
if(sum(grepl(paste0("UM",Sys.time() %>% format("%y")), samples$CODIGO)) > 0){
next.samp<-gsub(paste0("UM",Sys.time() %>% format("%y")),"", samples$CODIGO) %>% as.numeric %>% max(na.rm=T)+1
}else{
next.samp<-1
}
last.samp<-next.samp+(length(nhcs)-1)
new.samp<-sprintf("UM%s%02d",Sys.time() %>% format("%y"),next.samp:last.samp)
new.samp.df<-merge(sqlFetch(dta,"UMID") %>% merge(data.frame("NHC"=nhcs)), data.frame("NHC"=nhcs, "CODIGO"=new.samp))
samples.exp<-merge(samples %>% slice(0), new.samp.df %>% select(-NHC), all=T) %>% select(colnames(samples)) %>% arrange(CODIGO)
}
if (clinics.mod){
## Importar los datos clínicos de pacientes existentes y generar nueva entrada par los nuevos
upd.clinics<-sqlFetch(conn, "CLINICOS")
umid.new<-sqlFetch(conn, "UMID") %>% filter(NHC %in% nhcs)
upd.clinics<-merge(umid.new,upd.clinics %>% select(-Id), all.x=T, by="UMID")
upd.clinics$NHC<-as.character(upd.clinics$NHC)
for (i in colnames(upd.clinics)[sapply(upd.clinics, lubridate::is.POSIXct)]){upd.clinics[,i]<-as.Date(upd.clinics[,i])}
}
## Exportar tablas a la plantilla de entrada para su rellenado
wb <- loadWorkbook(file)
writeData(wb, "NHC", upd.umid)
if (samples.mod){writeData(wb,"samples",samples.exp)}
if (clinics.mod){writeData(wb,"CLINICS",upd.clinics)}
saveWorkbook(wb,file,overwrite = TRUE)
}
}
```
---
@@ -307,7 +387,7 @@ sqlWriteTemp<-function(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod
Updates the DB with the information filled in the template file.
### Usage
sqlSincBD(conn=dta, filetemp="QueryOV.xlsx", sinc.samples=F, sinc.clinics=F)
sqlSincBD(conn=dta, filetemp="queryOV.xlsx", sinc.samples=F, sinc.clinics=F, dbtype=NULL)
### Arguments
Argument|Description
@@ -316,6 +396,7 @@ conn|connection handle returned by odbcConnect.
filetemp|Template file that will be used to interact with the DB.
sinc.samples|If TRUE (default is FALSE for security), it updates the SAMPLES table in the DB with the information in the "samples" template sheet.
clinics.mod|If TRUE (default is FALSE for security), it updates the CLINICS table in the DB with the information in the "CLINICS" template sheet.
dbtype|used to manually specify the database type. It defaults to NULL and the type is deduced.
### Details
Updates the DB with the information filled in the template file. All the "samples" entries are added as new rows (as all samples are new even if the patient was already in the DB). The new patients included in the "CLINICS" sheet are introduced in the DB as new rows and the ones that were already there are modified in its previous row location.
@@ -334,20 +415,43 @@ sqlSincBD(sinc.samples=T, sinc.clinics=T)
### Function
```r
sqlSincBD<-function(conn=dta, filetemp="QueryOV.xlsx", sinc.samples=F, sinc.clinics=F){
sqlSincBD<-function(conn=dta, filetemp="queryOV.xlsx", sinc.samples=F, sinc.clinics=F, dbtype=NULL){
if(sqlTables(dta) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
if(sqlTables(dta) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
## Añadir código de muestra nueva a la base de datos
if (dbtype == "OV"){
print("DB OV detectada")
nsamples<-sqlFetch(conn, "SAMPLES") %>% nrow
upd.samples<-read.xlsx(filetemp, sheet = "samples", detectDates = T)
if (nrow(upd.samples) > 0){rownames(upd.samples)<-(nsamples+1):(nsamples+nrow(upd.samples)) %>% as.character}
if (sinc.samples & nrow(upd.samples) > 0){
upd.samples$IQ_date<-as.Date(upd.samples$IQ_date)
upd.samples$TIL_date<-as.Date(upd.samples$TIL_date)
### !! Atención, esto cambia la base de datos:
sqlSave(conn, upd.samples, tablename="SAMPLES", append = T, varTypes = c("IQ_date"="date"))
sqlSave(conn, upd.samples, tablename="SAMPLES", append = T, varTypes = c("IQ_date"="date","TIL_date"="date"))
print("Tabla SAMPLES sincronizada.")
}
}
if (dbtype == "UM"){
print("DB UM detectada")
nsamples<-sqlFetch(conn, "MUESTRAS") %>% nrow
upd.samples<-read.xlsx(filetemp, sheet = "samples", detectDates = T)
if (nrow(upd.samples) > 0){rownames(upd.samples)<-(nsamples+1):(nsamples+nrow(upd.samples)) %>% as.character}
if (sinc.samples & nrow(upd.samples) > 0){
upd.samples$FECHA_RECEPCION<-as.Date(upd.samples$FECHA_RECEPCION)
upd.samples$TIPO<-as.character(upd.samples$TIPO)
upd.samples$OBS<-as.character(upd.samples$OBS)
### !! Atención, esto cambia la base de datos:
sqlSave(conn, upd.samples, tablename="MUESTRAS", append = T, varTypes = c("FECHA_RECEPCION"="Date"), rownames = F)
print("Tabla MUESTRAS sincronizada.")
}
}
## Añadir datos clínicos modificados a la base de datos
if (dbtype == "OV"){
upd.clinics<-read.xlsx(filetemp, sheet = "CLINICS",detectDates = T)
ovid.mod<-upd.clinics$OVID[upd.clinics$OVID %in% (sqlFetch(dta, "CLINICS") %>% pull(OVID))]
rnames<-sqlFetch(conn, "CLINICS") %>% filter(OVID %in% ovid.mod) %>% rownames
@@ -363,8 +467,27 @@ sqlSincBD<-function(conn=dta, filetemp="QueryOV.xlsx", sinc.samples=F, sinc.clin
sqlUpdate(conn, clinics.mod,"CLINICS")
print("Tabla CLINICS modificada.")
}
}
if (dbtype == "UM"){
upd.clinics<-read.xlsx(filetemp, sheet = "CLINICS",detectDates = T)
umid.mod<-upd.clinics$UMID[upd.clinics$UMID %in% (sqlFetch(dta, "CLINICOS") %>% pull(UMID))]
rnames<-sqlFetch(conn, "CLINICOS") %>% filter(UMID %in% umid.mod) %>% rownames
clinics.mod<-upd.clinics %>% filter(UMID %in% umid.mod) %>% select(-NHC)
rownames(clinics.mod)<-rnames
### !! Atención, esto cambia la base de datos:
if (sinc.clinics){
fechas<-colnames(clinics.mod)[grepl("date|MET_DX|DoB", colnames(clinics.mod), ignore.case = T)]
for (i in fechas){
clinics.mod[,i]<-as.Date(clinics.mod[,i])
}
sqlUpdate(conn, clinics.mod,"CLINICOS")
print("Tabla CLINICOS modificada.")
}
}
## Añadir datos clínicos nuevos a la base de datos
if (dbtype == "OV"){
nsamples.clin<-sqlFetch(conn, "CLINICS") %>% nrow
ovid.new<-upd.clinics$OVID[!upd.clinics$OVID %in% (sqlFetch(conn, "CLINICS") %>% pull(OVID))]
clinics.new<-upd.clinics %>% filter(OVID %in% ovid.new) %>% select(-NHC)
@@ -382,4 +505,78 @@ sqlSincBD<-function(conn=dta, filetemp="QueryOV.xlsx", sinc.samples=F, sinc.clin
print("Tabla CLINICS sincronizada.")
}
}
if (dbtype == "UM"){
nsamples.clin<-sqlFetch(conn, "CLINICOS") %>% nrow
umid.new<-upd.clinics$UMID[!upd.clinics$UMID %in% (sqlFetch(conn, "CLINICOS") %>% pull(UMID))]
clinics.new<-upd.clinics %>% filter(UMID %in% umid.new) %>% select(-NHC)
if (length(umid.new) > 0){rownames(clinics.new)<-(nsamples.clin+1):(nsamples.clin+nrow(clinics.new)) %>% as.character}
### !! Atención, esto cambia la base de datos:
if (sinc.clinics){
fechas<-colnames(clinics.new)[grepl("date|MET_DX|DoB", colnames(clinics.new), ignore.case = T)]
varTypes<-rep("Date",length(fechas))
names(varTypes)<-fechas
for (i in fechas){
clinics.new[,i]<-as.Date(clinics.new[,i])
}
sqlSave(conn, clinics.new, tablename="CLINICOS", append = T, varTypes = varTypes)
print("Tabla CLINICOS sincronizada.")
}
}
}
```
---
## sqlMultiSamples
### Description
Prints a table compiling information about laboratory samples, scRNAseq samples and RNA/DNA samples.
### Usage
sqlMultiSamples(kbl=F, NHC=F, full=F)
### Arguments
Argument|Description
---|---
kbl|formats the output table with the kableEstra style. Defaults to F.
NHC|adds the NHC to the table in addition to the UMID. Defaults to F.
full|prints also the patients that doesn't appear in the MUESTRAS table. Defaults to F.
### Details
Prints a table compiling information about laboratory samples, scRNAseq samples and RNA/DNA samples.
### Value
A data.frame or a kableExtra table.
### Examples
```r
dta<-odbcConnect("test")
sqlMultiSamples()
```
### Function
```r
sqlMultiSamples<-function(kbl=F, NHC=F, full=F){
query<-sqlQuery(dta, "SELECT U.UMID,U.NHC,M.FECHA_RECEPCION,M.TIPO,M.CODIGO,C.CODIGO,R.CODIGO,R.ESTADO
FROM ((UMID U
LEFT OUTER JOIN MUESTRAS M ON U.UMID=M.UMID)
LEFT OUTER JOIN CNAG C ON M.CODIGO=C.CODIGO)
LEFT OUTER JOIN RNADNA R ON M.CODIGO=R.CODIGO") %>% rename("CNAG"="CODIGO.1","RNADNA"="CODIGO.2")
if (full==F){query<- query %>% filter(!is.na(CODIGO))}
if (NHC==F){query<- query %>% select(-NHC)}
query<-query %>% mutate(
CNAG=case_when(!is.na(CNAG)~"X",TRUE~""),
RNADNA=case_when((!is.na(RNADNA) & (ESTADO=="ENV"))~"X",
(!is.na(RNADNA) & (is.na(ESTADO)))~".",
TRUE~"")
) %>% select(-ESTADO)
if (kbl==T){
query %>% kableExtra::kbl() %>% kableExtra::kable_styling(full_width = F, bootstrap_options = c("striped"))
}else{
return(query)
}
}
```
+233 -37
View File
@@ -18,7 +18,7 @@ knitr::opts_chunk$set(echo = TRUE)
Removes from Database the last (or the amount specified) entry.
### Usage
sqlDropLast(conn, tablename, droplast=1)
sqlLastDrop(conn, tablename, droplast=1, dbtype=NULL)
### Arguments
Argument|Description
@@ -26,6 +26,7 @@ Argument|Description
conn|connection handle returned by odbcConnect.
tablename|character: a database table name accessible from the connected DSN.
droplast|the amount of lines to be removed from the table strating from tail. By default, it removes only 1 line.
dbtype|used to manually specify the database type. It defaults to NULL and the type is deduced.
### Details
Removes from Database the last (or the amount specified) entry.
@@ -36,15 +37,22 @@ Invisibly for success (and failures cause errors).
### Examples
```r
dta<-odbcConnect("test")
sqlDropLast(dta, "TableTest")
sqlLastDrop(dta, "TableTest")
```
### Function
```r
sqlDropLast<-function(conn, tablename, droplast=1){
sqlLastDrop<-function(conn, tablename, droplast=1,dbtype=NULL){
if(sqlTables(conn) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
if(sqlTables(conn) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
table<-sqlFetch(conn, tablename)
table<-table[1:(nrow(table)-droplast),]
sqlSave(conn, table, tablename = tablename, safer = F)
if (dbtype == "OV"){sqlSave(conn, table, tablename = tablename, safer = F)}
if (dbtype == "UM"){
sqlDrop(conn, tablename)
sqlSave(conn, table, tablename = tablename, safer = F)}
}
```
@@ -93,13 +101,14 @@ sqlInitialize<-function(){
Creates a Back Up copy of the database.
### Usage
sqlBackUp(dbfile=file,bu.dir="BU_OVARIO")
sqlBackUp(dbfile=file,conn=dta,bu.dir=NULL)
### Arguments
Argument|Description
---|---
dbfile| Database File location.
bu.dir| Directory under the DB file where the back up will be placed.
conn|connection handle returned by odbcConnect.
bu.dir|Directory under the DB file where the back up will be placed. It defaults to NULL and is deduced from conn database.
### Details
Creates a Back Up copy of the database. It adds the date in front of the back up file.
@@ -115,7 +124,10 @@ sqlBackUp()
### Function
```r
sqlBackUp<-function(dbfile=file,bu.dir="BU_OVARIO"){
sqlBackUp<-function(dbfile=file,conn=dta,bu.dir=NULL){
if(sqlTables(conn) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){bu.dir<-"BU_UM"}
if(sqlTables(conn) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){bu.dir<-"BU_OVARIO"}
db=strsplit(dbfile, "/")[[1]]%>% tail(n=1)
bu_path<-gsub(db,bu.dir,dbfile)
if (!dir.exists(bu_path)){
@@ -135,7 +147,7 @@ sqlBackUp<-function(dbfile=file,bu.dir="BU_OVARIO"){
Shows if there are already samples from the specified NHCs.
### Usage
sqlShowSamples(conn=dta, nhcs=nhc.test, verb=F)
sqlShowSamples(conn=dta, nhcs=nhc.test, verb=F, dbtype=NULL)
### Arguments
Argument|Description
@@ -143,6 +155,7 @@ Argument|Description
conn|connection handle returned by odbcConnect.
nhcs|Character vector with the NHCs to test.
verb|Verbose: if TRUE, all the columns from "SAMPLES" table are printed.
dbtype|used to manually specify the database type. It defaults to NULL and the type is deduced.
### Details
Takes the NHCs listed in the nhcs vector and checks if there are already samples from those patients.
@@ -159,18 +172,27 @@ sqlShowSamples()
### Function
```r
sqlShowSamples<-function(conn=dta, nhcs=nhc.test, verb=F){
sqlShowSamples<-function(conn=dta, nhcs=nhc.test, verb=F, dbtype=NULL){
if(sqlTables(dta) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
if(sqlTables(dta) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
if (dbtype == "OV"){
db<-c("dbtables"="SAMPLES", "dbcode"="OVID", "dbsamples"="samples")
query<-paste0("SELECT O.NHC,S.* FROM ",db["dbtables"]," S INNER JOIN ",db["dbcode"]," O ON O.",db["dbcode"],"=S.",db["dbcode"])
}
if (dbtype == "UM"){
db<-c("dbtables"="MUESTRAS", "dbcode"="UMID", "dbsamples"="CODIGO")
query<-paste0("SELECT O.NHC,S.* FROM ",db["dbtables"]," S INNER JOIN ",db["dbcode"]," O ON O.",db["dbcode"],"=S.",db["dbcode"])
}
if (nrow(sqlQuery(conn, query) %>% filter(NHC %in% nhcs)) == 0){
return("No hay muestras de ningún paciente.")
}
if (isFALSE(verb)){
sqlQuery(conn, "SELECT O.NHC,S.*
FROM SAMPLES S
INNER JOIN OVID O
ON O.OVID=S.OVID") %>% filter(NHC %in% nhcs) %>%
group_by(NHC,OVID) %>% summarise(Samples=length(samples), Names=paste0(samples, collapse = ";")) %>% merge(data.frame(NHC=nhcs),all=T)
sqlQuery(conn, query) %>% filter(NHC %in% nhcs) %>%
group_by(NHC,UQ(rlang::sym(db["dbcode"]))) %>% summarise(Samples=length(UQ(rlang::sym(db["dbsamples"]))), Names=paste0(UQ(rlang::sym(db["dbsamples"])), collapse = ";")) %>%
merge(data.frame(NHC=nhcs),all=T) %>% mutate(NHC=factor(NHC,levels = nhcs)) %>% arrange(NHC)
}else{
sqlQuery(conn, "SELECT O.NHC,S.*
FROM SAMPLES S
INNER JOIN OVID O
ON O.OVID=S.OVID") %>% filter(NHC %in% nhcs)
sqlQuery(conn, query) %>% filter(NHC %in% nhcs)
}
}
```
@@ -180,10 +202,10 @@ sqlShowSamples<-function(conn=dta, nhcs=nhc.test, verb=F){
## sqlGenOVID
### Description
Generates new consecutive OVID code for the patients that are not found in the DB.
Generates new consecutive OVID or UMID code for the patients that are not found in the DB.
### Usage
sqlGenOVID(conn=dta, nhcs=nhc.test, verb=T, sinc=F)
sqlGenOVID(conn=dta, nhcs=nhc.test, verb=T, sinc=F, dbtype=NULL)
### Arguments
Argument|Description
@@ -192,9 +214,10 @@ conn|connection handle returned by odbcConnect.
nhcs|Character vector with the NHCs to test.
verb|Verbose: if TRUE (default), it prints the data.frame with the generated OVID codes.
sinc|If TRUE (default is FALSE for security), it adds the new entries to the "OVID" table in the DB.
dbtype|used to manually specify the database type. It defaults to NULL and the type is deduced.
### Details
Generates new consecutive OVID code for the patients that are not found in the DB.
Generates new consecutive OVID or UMID code for the patients that are not found in the DB.
### Value
If verb is TRUE, it returns a data.frame.
@@ -208,23 +231,41 @@ sqlGenOVID(sinc=T)
### Function
```r
sqlGenOVID<-function(conn=dta, nhcs=nhc.test, verb=T, sinc=F){
ovid<-sqlFetch(conn,"OVID")
sqlGenOVID<-function(conn=dta, nhcs=nhc.test, verb=T, sinc=F, dbtype=NULL){
if(sqlTables(dta) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
if(sqlTables(dta) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
new.nhc<-nhcs[!nhcs %in% ovid$NHC]
next.num<-gsub("OVID","",ovid$OVID) %>% as.numeric %>% max(na.rm=T)+1
if (dbtype == "OV"){
db<-c("dbcode"="OVID")
}
if (dbtype == "UM"){
db<-c("dbcode"="UMID")
}
dbid<-sqlFetch(conn,db["dbcode"])
new.nhc<-nhcs[!nhcs %in% dbid$NHC]
next.num<-gsub(db["dbcode"],"",dbid[,db["dbcode"]]) %>% as.numeric %>% max(na.rm=T)+1
last.num<-next.num+(length(new.nhc)-1)
upd.ovid<-rbind(ovid,data.frame("NHC"=new.nhc, "OVID"=sprintf("OVID%04d",next.num:last.num)))
rownames(upd.ovid)<-as.character(1:nrow(upd.ovid))
upd.ovid<-filter(upd.ovid, NHC %in% new.nhc) %>% mutate(NHC=as.character(NHC))
newtab<-data.frame("NHC"=new.nhc, "ID"=sprintf("%s%04d",db["dbcode"],next.num:last.num)) %>% rename(!!db["dbcode"]:="ID")
if(dbtype=="OV"){
dbid<-rbind(dbid,newtab)
}
if(dbtype=="UM"){
dbid<-merge(dbid, newtab, all=T) %>% select(Id,NHC,UMID) %>% arrange(Id)
dbid$Id<-as.numeric(rownames(dbid))
dbid$NHC<-as.numeric(dbid$NHC)
}
rownames(dbid)<-as.character(1:nrow(dbid))
dbid<-filter(dbid, NHC %in% new.nhc) %>% mutate(NHC=as.character(NHC))
if (sinc){
### !! Atención, esto cambia la base de datos:
sqlSave(conn, upd.ovid, tablename="OVID", append = T)
sqlSave(conn, dbid, tablename=db["dbcode"], append = T)
print("La base ha sido actualizada.")
}
if (verb){
return(upd.ovid)
return(dbid)
}
}
```
@@ -234,10 +275,10 @@ sqlGenOVID<-function(conn=dta, nhcs=nhc.test, verb=T, sinc=F){
## sqlWriteTemp
### Description
Fills the Query Template file with the OVID and OV newly generated codes.
Fills the Query Template file with the OVID or UMID and OV or UM newly generated codes.
### Usage
sqlWriteTemp(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod=T, clinics.mod=T)
sqlWriteTemp(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod=T, clinics.mod=T, dbtype=NULL)
### Arguments
Argument|Description
@@ -247,9 +288,10 @@ nhcs|Character vector with the NHCs to test.
file|Template file that will be used to interact with the DB.
samples.mod|If TRUE (default), it fills the "samples" template sheet.
clinics.mod|If TRUE (default), it fills the "CLINICS" template sheet.
dbtype|used to manually specify the database type. It defaults to NULL and the type is deduced.
### Details
Fills the Query Template file with the OVID and OV newly generated codes. It is required that the DB has been updated with the sqlGenOVID function. It replaces previous content in the template file sheets that are filled. In the case of "CLINICS" table, if there were already an entry in the DB for that OVID code, the template file is filled with that information.
Fills the Query Template file with the OVID and OV or UMID and UM newly generated codes. It is required that the DB has been updated with the sqlGenOVID function. It replaces previous content in the template file sheets that are filled. In the case of "CLINICS" table, if there were already an entry in the DB for that OVID/UMID code, the template file is filled with that information.
### Value
Invisibly for success (and failures cause errors).
@@ -264,7 +306,11 @@ sqlWriteTemp()
### Function
```r
sqlWriteTemp<-function(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod=T, clinics.mod=T){
sqlWriteTemp<-function(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod=T, clinics.mod=T, dbtype=NULL){
if(sqlTables(dta) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
if(sqlTables(dta) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
if (dbtype=="OV"){
upd.ovid<-sqlFetch(conn, "OVID") %>% filter(NHC %in% nhcs)
if (samples.mod){
## Generar código para las nuevas muestras
@@ -296,6 +342,39 @@ sqlWriteTemp<-function(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod
if (clinics.mod){writeData(wb,"CLINICS",upd.clinics)}
saveWorkbook(wb,file,overwrite = TRUE)
}
if (dbtype=="UM"){
upd.umid<-sqlFetch(conn, "UMID") %>% filter(NHC %in% nhcs)
if (samples.mod){
## Generar código para las nuevas muestras
samples<-sqlFetch(conn, "MUESTRAS")
if(sum(grepl(paste0("UM",Sys.time() %>% format("%y")), samples$CODIGO)) > 0){
next.samp<-gsub(paste0("UM",Sys.time() %>% format("%y")),"", samples$CODIGO) %>% as.numeric %>% max(na.rm=T)+1
}else{
next.samp<-1
}
last.samp<-next.samp+(length(nhcs)-1)
new.samp<-sprintf("UM%s%02d",Sys.time() %>% format("%y"),next.samp:last.samp)
new.samp.df<-merge(sqlFetch(dta,"UMID") %>% merge(data.frame("NHC"=nhcs)), data.frame("NHC"=nhcs, "CODIGO"=new.samp))
samples.exp<-merge(samples %>% slice(0), new.samp.df %>% select(-NHC), all=T) %>% select(colnames(samples)) %>% arrange(CODIGO)
}
if (clinics.mod){
## Importar los datos clínicos de pacientes existentes y generar nueva entrada par los nuevos
upd.clinics<-sqlFetch(conn, "CLINICOS")
umid.new<-sqlFetch(conn, "UMID") %>% filter(NHC %in% nhcs)
upd.clinics<-merge(umid.new,upd.clinics %>% select(-Id), all.x=T, by="UMID")
upd.clinics$NHC<-as.character(upd.clinics$NHC)
for (i in colnames(upd.clinics)[sapply(upd.clinics, lubridate::is.POSIXct)]){upd.clinics[,i]<-as.Date(upd.clinics[,i])}
}
## Exportar tablas a la plantilla de entrada para su rellenado
wb <- loadWorkbook(file)
writeData(wb, "NHC", upd.umid)
if (samples.mod){writeData(wb,"samples",samples.exp)}
if (clinics.mod){writeData(wb,"CLINICS",upd.clinics)}
saveWorkbook(wb,file,overwrite = TRUE)
}
}
```
---
@@ -306,7 +385,7 @@ sqlWriteTemp<-function(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod
Updates the DB with the information filled in the template file.
### Usage
sqlSincBD(conn=dta, filetemp="QueryOV.xlsx", sinc.samples=F, sinc.clinics=F)
sqlSincBD(conn=dta, filetemp="queryOV.xlsx", sinc.samples=F, sinc.clinics=F, dbtype=NULL)
### Arguments
Argument|Description
@@ -315,6 +394,7 @@ conn|connection handle returned by odbcConnect.
filetemp|Template file that will be used to interact with the DB.
sinc.samples|If TRUE (default is FALSE for security), it updates the SAMPLES table in the DB with the information in the "samples" template sheet.
clinics.mod|If TRUE (default is FALSE for security), it updates the CLINICS table in the DB with the information in the "CLINICS" template sheet.
dbtype|used to manually specify the database type. It defaults to NULL and the type is deduced.
### Details
Updates the DB with the information filled in the template file. All the "samples" entries are added as new rows (as all samples are new even if the patient was already in the DB). The new patients included in the "CLINICS" sheet are introduced in the DB as new rows and the ones that were already there are modified in its previous row location.
@@ -333,20 +413,43 @@ sqlSincBD(sinc.samples=T, sinc.clinics=T)
### Function
```r
sqlSincBD<-function(conn=dta, filetemp="QueryOV.xlsx", sinc.samples=F, sinc.clinics=F){
sqlSincBD<-function(conn=dta, filetemp="queryOV.xlsx", sinc.samples=F, sinc.clinics=F, dbtype=NULL){
if(sqlTables(dta) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
if(sqlTables(dta) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
## Añadir código de muestra nueva a la base de datos
if (dbtype == "OV"){
print("DB OV detectada")
nsamples<-sqlFetch(conn, "SAMPLES") %>% nrow
upd.samples<-read.xlsx(filetemp, sheet = "samples", detectDates = T)
if (nrow(upd.samples) > 0){rownames(upd.samples)<-(nsamples+1):(nsamples+nrow(upd.samples)) %>% as.character}
if (sinc.samples & nrow(upd.samples) > 0){
upd.samples$IQ_date<-as.Date(upd.samples$IQ_date)
upd.samples$TIL_date<-as.Date(upd.samples$TIL_date)
### !! Atención, esto cambia la base de datos:
sqlSave(conn, upd.samples, tablename="SAMPLES", append = T, varTypes = c("IQ_date"="date"))
sqlSave(conn, upd.samples, tablename="SAMPLES", append = T, varTypes = c("IQ_date"="date","TIL_date"="date"))
print("Tabla SAMPLES sincronizada.")
}
}
if (dbtype == "UM"){
print("DB UM detectada")
nsamples<-sqlFetch(conn, "MUESTRAS") %>% nrow
upd.samples<-read.xlsx(filetemp, sheet = "samples", detectDates = T)
if (nrow(upd.samples) > 0){rownames(upd.samples)<-(nsamples+1):(nsamples+nrow(upd.samples)) %>% as.character}
if (sinc.samples & nrow(upd.samples) > 0){
upd.samples$FECHA_RECEPCION<-as.Date(upd.samples$FECHA_RECEPCION)
upd.samples$TIPO<-as.character(upd.samples$TIPO)
upd.samples$OBS<-as.character(upd.samples$OBS)
### !! Atención, esto cambia la base de datos:
sqlSave(conn, upd.samples, tablename="MUESTRAS", append = T, varTypes = c("FECHA_RECEPCION"="Date"), rownames = F)
print("Tabla MUESTRAS sincronizada.")
}
}
## Añadir datos clínicos modificados a la base de datos
if (dbtype == "OV"){
upd.clinics<-read.xlsx(filetemp, sheet = "CLINICS",detectDates = T)
ovid.mod<-upd.clinics$OVID[upd.clinics$OVID %in% (sqlFetch(dta, "CLINICS") %>% pull(OVID))]
rnames<-sqlFetch(conn, "CLINICS") %>% filter(OVID %in% ovid.mod) %>% rownames
@@ -362,8 +465,27 @@ sqlSincBD<-function(conn=dta, filetemp="QueryOV.xlsx", sinc.samples=F, sinc.clin
sqlUpdate(conn, clinics.mod,"CLINICS")
print("Tabla CLINICS modificada.")
}
}
if (dbtype == "UM"){
upd.clinics<-read.xlsx(filetemp, sheet = "CLINICS",detectDates = T)
umid.mod<-upd.clinics$UMID[upd.clinics$UMID %in% (sqlFetch(dta, "CLINICOS") %>% pull(UMID))]
rnames<-sqlFetch(conn, "CLINICOS") %>% filter(UMID %in% umid.mod) %>% rownames
clinics.mod<-upd.clinics %>% filter(UMID %in% umid.mod) %>% select(-NHC)
rownames(clinics.mod)<-rnames
### !! Atención, esto cambia la base de datos:
if (sinc.clinics){
fechas<-colnames(clinics.mod)[grepl("date|MET_DX|DoB", colnames(clinics.mod), ignore.case = T)]
for (i in fechas){
clinics.mod[,i]<-as.Date(clinics.mod[,i])
}
sqlUpdate(conn, clinics.mod,"CLINICOS")
print("Tabla CLINICOS modificada.")
}
}
## Añadir datos clínicos nuevos a la base de datos
if (dbtype == "OV"){
nsamples.clin<-sqlFetch(conn, "CLINICS") %>% nrow
ovid.new<-upd.clinics$OVID[!upd.clinics$OVID %in% (sqlFetch(conn, "CLINICS") %>% pull(OVID))]
clinics.new<-upd.clinics %>% filter(OVID %in% ovid.new) %>% select(-NHC)
@@ -381,4 +503,78 @@ sqlSincBD<-function(conn=dta, filetemp="QueryOV.xlsx", sinc.samples=F, sinc.clin
print("Tabla CLINICS sincronizada.")
}
}
if (dbtype == "UM"){
nsamples.clin<-sqlFetch(conn, "CLINICOS") %>% nrow
umid.new<-upd.clinics$UMID[!upd.clinics$UMID %in% (sqlFetch(conn, "CLINICOS") %>% pull(UMID))]
clinics.new<-upd.clinics %>% filter(UMID %in% umid.new) %>% select(-NHC)
if (length(umid.new) > 0){rownames(clinics.new)<-(nsamples.clin+1):(nsamples.clin+nrow(clinics.new)) %>% as.character}
### !! Atención, esto cambia la base de datos:
if (sinc.clinics){
fechas<-colnames(clinics.new)[grepl("date|MET_DX|DoB", colnames(clinics.new), ignore.case = T)]
varTypes<-rep("Date",length(fechas))
names(varTypes)<-fechas
for (i in fechas){
clinics.new[,i]<-as.Date(clinics.new[,i])
}
sqlSave(conn, clinics.new, tablename="CLINICOS", append = T, varTypes = varTypes)
print("Tabla CLINICOS sincronizada.")
}
}
}
```
---
## sqlMultiSamples
### Description
Prints a table compiling information about laboratory samples, scRNAseq samples and RNA/DNA samples.
### Usage
sqlMultiSamples(kbl=F, NHC=F, full=F)
### Arguments
Argument|Description
---|---
kbl|formats the output table with the kableEstra style. Defaults to F.
NHC|adds the NHC to the table in addition to the UMID. Defaults to F.
full|prints also the patients that doesn't appear in the MUESTRAS table. Defaults to F.
### Details
Prints a table compiling information about laboratory samples, scRNAseq samples and RNA/DNA samples.
### Value
A data.frame or a kableExtra table.
### Examples
```r
dta<-odbcConnect("test")
sqlMultiSamples()
```
### Function
```r
sqlMultiSamples<-function(kbl=F, NHC=F, full=F){
query<-sqlQuery(dta, "SELECT U.UMID,U.NHC,M.FECHA_RECEPCION,M.TIPO,M.CODIGO,C.CODIGO,R.CODIGO,R.ESTADO
FROM ((UMID U
LEFT OUTER JOIN MUESTRAS M ON U.UMID=M.UMID)
LEFT OUTER JOIN CNAG C ON M.CODIGO=C.CODIGO)
LEFT OUTER JOIN RNADNA R ON M.CODIGO=R.CODIGO") %>% rename("CNAG"="CODIGO.1","RNADNA"="CODIGO.2")
if (full==F){query<- query %>% filter(!is.na(CODIGO))}
if (NHC==F){query<- query %>% select(-NHC)}
query<-query %>% mutate(
CNAG=case_when(!is.na(CNAG)~"X",TRUE~""),
RNADNA=case_when((!is.na(RNADNA) & (ESTADO=="ENV"))~"X",
(!is.na(RNADNA) & (is.na(ESTADO)))~".",
TRUE~"")
) %>% select(-ESTADO)
if (kbl==T){
query %>% kableExtra::kbl() %>% kableExtra::kable_styling(full_width = F, bootstrap_options = c("striped"))
}else{
return(query)
}
}
```
File diff suppressed because one or more lines are too long
+4 -1
View File
@@ -1 +1,4 @@
file<-"C:/Users/47926492N/OneDrive - IDIBELL - Institut d'Investigació Biomèdica de Bellvitge/RATG-PIULATS/OVARIO.accdb"
# file<-"C:/Users/47926492N/OneDrive - IDIBELL - Institut d'Investigació Biomèdica de Bellvitge/RATG-PIULATS/MELANOMA UVEAL CIT.accdb"
# file<-"C:/Users/47926492N/OneDrive - IDIBELL - Institut d'Investigació Biomèdica de Bellvitge/RATG-PIULATS/OVARIO.accdb"
UMfile<-file<-"C:/Users/47926492N/Documents/Test/MELANOMA UVEAL CIT.accdb"
OVfile<-file<-"C:/Users/47926492N/Documents/Test/OVARIO.accdb"
+227 -27
View File
@@ -1,21 +1,32 @@
require(RODBC)
sqlDropLast<-function(conn, tablename, droplast=1){
sqlLastDrop<-function(conn, tablename, droplast=1,dbtype=NULL){
if(sqlTables(conn) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
if(sqlTables(conn) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
table<-sqlFetch(conn, tablename)
table<-table[1:(nrow(table)-droplast),]
sqlSave(conn, table, tablename = tablename, safer = F)
if (dbtype == "OV"){sqlSave(conn, table, tablename = tablename, safer = F)}
if (dbtype == "UM"){
sqlDrop(conn, tablename)
sqlSave(conn, table, tablename = tablename, safer = F)}
}
sqlInitialize<-function(){
sqlInitialize<-function(ruta="ruta_database.R"){
library(tidyverse)
library(RODBC)
library(openxlsx)
## Conexión a la base de datos
source("ruta_database.R", encoding = "UTF-8")
source(ruta, encoding = "UTF-8")
}
sqlBackUp<-function(dbfile=file,bu.dir="BU_OVARIO"){
sqlBackUp<-function(dbfile=file,conn=dta,bu.dir=NULL){
if(sqlTables(conn) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){bu.dir<-"BU_UM"}
if(sqlTables(conn) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){bu.dir<-"BU_OVARIO"}
db=strsplit(dbfile, "/")[[1]]%>% tail(n=1)
bu_path<-gsub(db,bu.dir,dbfile)
if (!dir.exists(bu_path)){
@@ -26,42 +37,87 @@ sqlBackUp<-function(dbfile=file,bu.dir="BU_OVARIO"){
file.copy(dbfile, cp_bu)
}
sqlShowSamples<-function(conn=dta, nhcs=nhc.test, verb=F){
sqlShowSamples<-function(conn=dta, nhcs=nhc.test, verb=F, dbtype=NULL){
if(sqlTables(dta) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
if(sqlTables(dta) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
if (dbtype == "OV"){
db<-c("dbtables"="SAMPLES", "dbcode"="OVID", "dbsamples"="samples")
query<-paste0("SELECT O.NHC,S.* FROM ",db["dbtables"]," S INNER JOIN ",db["dbcode"]," O ON O.",db["dbcode"],"=S.",db["dbcode"])
}
if (dbtype == "UM"){
db<-c("dbtables"="MUESTRAS", "dbcode"="UMID", "dbsamples"="CODIGO")
query<-paste0("SELECT O.NHC,S.* FROM ",db["dbtables"]," S INNER JOIN ",db["dbcode"]," O ON O.",db["dbcode"],"=S.",db["dbcode"])
}
if (nrow(sqlQuery(conn, query) %>% filter(NHC %in% nhcs)) == 0){
return("No hay muestras de ningún paciente.")
}
if (isFALSE(verb)){
sqlQuery(conn, "SELECT O.NHC,S.*
FROM SAMPLES S
INNER JOIN OVID O
ON O.OVID=S.OVID") %>% filter(NHC %in% nhcs) %>%
group_by(NHC,OVID) %>% summarise(Samples=length(samples), Names=paste0(samples, collapse = ";")) %>% merge(data.frame(NHC=nhcs),all=T)
sqlQuery(conn, query) %>% filter(NHC %in% nhcs) %>%
group_by(NHC,UQ(rlang::sym(db["dbcode"]))) %>% summarise(Samples=length(UQ(rlang::sym(db["dbsamples"]))), Names=paste0(UQ(rlang::sym(db["dbsamples"])), collapse = ";")) %>%
merge(data.frame(NHC=nhcs),all=T) %>% mutate(NHC=factor(NHC,levels = unique(nhcs))) %>% arrange(NHC)
}else{
sqlQuery(conn, "SELECT O.NHC,S.*
FROM SAMPLES S
INNER JOIN OVID O
ON O.OVID=S.OVID") %>% filter(NHC %in% nhcs)
sqlQuery(conn, query) %>% filter(NHC %in% nhcs)
}
}
sqlGenOVID<-function(conn=dta, nhcs=nhc.test, verb=T, sinc=F){
ovid<-sqlFetch(conn,"OVID")
sqlGenOVID<-function(conn=dta, nhcs=nhc.test, verb=T, sinc=F, dbtype=NULL){
if(sqlTables(conn) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
if(sqlTables(conn) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
new.nhc<-nhcs[!nhcs %in% ovid$NHC]
next.num<-gsub("OVID","",ovid$OVID) %>% as.numeric %>% max(na.rm=T)+1
if (dbtype == "OV"){
db<-c("dbcode"="OVID", "dbpref"="OVID")
}
if (dbtype == "UM"){
db<-c("dbcode"="UMID","dbpref"="UMID")
}
if (dbtype == "CC"){
db<-c("dbcode"="PATID", "dbpref"="CCID")
}
dbid<-sqlFetch(conn,db["dbcode"])
new.nhc<-nhcs[!nhcs %in% dbid$NHC] %>% unique()
if(length(new.nhc) > 0){
if (nrow(dbid) == 0){next.num<-1}else{
next.num<-gsub(db["dbcode"],"",dbid[,db["dbcode"]]) %>% as.numeric %>% max(na.rm=T)+1
}
print(next.num)
last.num<-next.num+(length(new.nhc)-1)
upd.ovid<-rbind(ovid,data.frame("NHC"=new.nhc, "OVID"=sprintf("OVID%04d",next.num:last.num)))
rownames(upd.ovid)<-as.character(1:nrow(upd.ovid))
upd.ovid<-filter(upd.ovid, NHC %in% new.nhc) %>% mutate(NHC=as.character(NHC))
newtab<-data.frame("NHC"=new.nhc, "ID"=sprintf("%s%04d",db["dbpref"],next.num:last.num)) %>% rename(!!db["dbcode"]:="ID")
if(dbtype=="OV"){
dbid<-rbind(dbid,newtab)
}
if(dbtype=="UM"){
dbid<-merge(dbid, newtab, all=T) %>% select(NHC,UMID) %>% arrange(UMID)
# dbid$Id<-as.numeric(rownames(dbid))
dbid$NHC<-as.numeric(dbid$NHC)
}
if (dbtype=="CC"){
dbid<-merge(dbid, newtab, all=T) %>% select(NHC,PATID) %>% arrange(PATID)
dbid$NHC<-as.numeric(dbid$NHC)
}
rownames(dbid)<-as.character(1:nrow(dbid))
dbid<-filter(dbid, NHC %in% new.nhc) %>% mutate(NHC=as.character(NHC))
if (sinc){
### !! Atención, esto cambia la base de datos:
sqlSave(conn, upd.ovid, tablename="OVID", append = T)
sqlSave(conn, dbid, tablename=db["dbcode"], append = T, rownames = F)
print("La base ha sido actualizada.")
}
if (verb){
return(upd.ovid)
return(dbid)
}
}else{
print("No hay pacientes nuevos.")
}
}
sqlWriteTemp<-function(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod=T, clinics.mod=T){
sqlWriteTemp<-function(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod=T, clinics.mod=T, dbtype=NULL, today=F){
if(sqlTables(dta) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
if(sqlTables(dta) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
if (dbtype=="OV"){
upd.ovid<-sqlFetch(conn, "OVID") %>% filter(NHC %in% nhcs)
if (samples.mod){
## Generar código para las nuevas muestras
@@ -93,21 +149,104 @@ sqlWriteTemp<-function(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod
if (clinics.mod){writeData(wb,"CLINICS",upd.clinics)}
saveWorkbook(wb,file,overwrite = TRUE)
}
if (dbtype=="UM"){
upd.umid<-sqlFetch(conn, "UMID") %>% filter(NHC %in% nhcs)
if (samples.mod){
## Generar código para las nuevas muestras
samples<-sqlFetch(conn, "MUESTRAS")
if(sum(grepl(paste0("UM",Sys.time() %>% format("%y")), samples$CODIGO)) > 0){
next.samp<-gsub(paste0("UM",Sys.time() %>% format("%y")),"", samples$CODIGO) %>% as.numeric %>% max(na.rm=T)+1
}else{
next.samp<-1
}
last.samp<-next.samp+(length(nhcs)-1)
new.samp<-sprintf("UM%s%02d",Sys.time() %>% format("%y"),next.samp:last.samp)
new.samp.df<-data.frame("NHC"=nhcs, "CODIGO"=new.samp) %>% merge(sqlFetch(dta,"UMID"), all.x=T) %>% arrange(CODIGO)
samples.exp<-merge(samples %>% slice(0), new.samp.df %>% select(-NHC), all=T) %>% select(colnames(samples)) %>% arrange(CODIGO)
if (today==TRUE){
samples.exp$FECHA_RECEPCION<-format(Sys.Date(), "%d/%m/%y")
}
}
nhc.table<-read.xlsx(file, sheet = "NHC")
if (any(sapply(nhc.table$Samples, function(x) "cnag" %in% strsplit(x,",")[[1]]) == T)){
nhcs.cnag<-nhc.table[sapply(nhc.table$Samples, function(x) "cnag" %in% strsplit(x,",")[[1]]),"NHC"]
umid.cnag<-sqlFetch(conn, "UMID") %>% filter(NHC %in% nhcs.cnag) %>% pull(UMID)
sample.cnag<-samples.exp %>% filter(UMID %in% umid.cnag) %>% pull(CODIGO)
cnag.exp<-merge(data.frame("UMID"=umid.cnag, "CODIGO"=sample.cnag), sqlFetch(dta, "CNAG") %>% slice(0), all=T)
if (today==TRUE){
cnag.exp$FECHA_ENVIO<-format(Sys.Date(), "%d/%m/%y")
}
}else{cnag.exp<-sqlFetch(dta, "CNAG") %>% slice(0)}
if (any(sapply(nhc.table$Samples, function(x) "rna" %in% strsplit(x,",")[[1]]) == T)){
nhcs.rna<-nhc.table[sapply(nhc.table$Samples, function(x) "rna" %in% strsplit(x,",")[[1]]),"NHC"]
umid.rna<-sqlFetch(conn, "UMID") %>% filter(NHC %in% nhcs.rna) %>% pull(UMID)
sample.rna<-samples.exp %>% filter(UMID %in% umid.rna) %>% pull(CODIGO)
rna.exp<-merge(data.frame("UMID"=umid.rna, "CODIGO"=sample.rna), sqlFetch(dta, "RNADNA") %>% slice(0), all=T)
}else{rna.exp<- sqlFetch(dta, "RNADNA") %>% slice(0)}
if (clinics.mod){
## Importar los datos clínicos de pacientes existentes y generar nueva entrada par los nuevos
upd.clinics<-sqlFetch(conn, "CLINICOS")
umid.new<-sqlFetch(conn, "UMID") %>% filter(NHC %in% nhcs)
upd.clinics<-merge(umid.new,upd.clinics, all.x=T, by="UMID")
upd.clinics$NHC<-as.character(upd.clinics$NHC)
for (i in colnames(upd.clinics)[sapply(upd.clinics, lubridate::is.POSIXct)]){upd.clinics[,i]<-as.Date(upd.clinics[,i])}
}
## Exportar tablas a la plantilla de entrada para su rellenado
wb <- createWorkbook(file)
addWorksheet(wb, "NHC")
addWorksheet(wb, "samples")
addWorksheet(wb, "CLINICS")
addWorksheet(wb, "CNAG")
addWorksheet(wb, "RNADNA")
writeData(wb, "NHC", merge(nhc.table, upd.umid, sort = F))
if (samples.mod){writeData(wb,"samples",samples.exp)}
if (clinics.mod){writeData(wb,"CLINICS",upd.clinics)}
writeData(wb,"CNAG",cnag.exp)
writeData(wb,"RNADNA",rna.exp)
saveWorkbook(wb,file,overwrite = TRUE)
}
}
sqlSincBD<-function(conn=dta, filetemp="queryOV.xlsx", sinc.samples=F, sinc.clinics=F, dbtype=NULL){
if(sqlTables(dta) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
if(sqlTables(dta) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
sqlSincBD<-function(conn=dta, filetemp="QueryOV.xlsx", sinc.samples=F, sinc.clinics=F){
## Añadir código de muestra nueva a la base de datos
if (dbtype == "OV"){
print("DB OV detectada")
nsamples<-sqlFetch(conn, "SAMPLES") %>% nrow
upd.samples<-read.xlsx(filetemp, sheet = "samples", detectDates = T)
if (nrow(upd.samples) > 0){rownames(upd.samples)<-(nsamples+1):(nsamples+nrow(upd.samples)) %>% as.character}
if (sinc.samples & nrow(upd.samples) > 0){
upd.samples$IQ_date<-as.Date(upd.samples$IQ_date)
upd.samples$TIL_date<-as.Date(upd.samples$TIL_date)
### !! Atención, esto cambia la base de datos:
sqlSave(conn, upd.samples, tablename="SAMPLES", append = T, varTypes = c("IQ_date"="date"))
sqlSave(conn, upd.samples, tablename="SAMPLES", append = T, varTypes = c("IQ_date"="date","TIL_date"="date"))
print("Tabla SAMPLES sincronizada.")
}
}
if (dbtype == "UM"){
print("DB UM detectada")
nsamples<-sqlFetch(conn, "MUESTRAS") %>% nrow
upd.samples<-read.xlsx(filetemp, sheet = "samples", detectDates = T)
if (nrow(upd.samples) > 0){rownames(upd.samples)<-(nsamples+1):(nsamples+nrow(upd.samples)) %>% as.character}
if (sinc.samples & nrow(upd.samples) > 0){
upd.samples$FECHA_RECEPCION<-as.Date(upd.samples$FECHA_RECEPCION)
upd.samples$TIPO<-as.character(upd.samples$TIPO)
upd.samples$OBS<-as.character(upd.samples$OBS)
### !! Atención, esto cambia la base de datos:
sqlSave(conn, upd.samples, tablename="MUESTRAS", append = T, varTypes = c("FECHA_RECEPCION"="Date"), rownames = F)
print("Tabla MUESTRAS sincronizada.")
}
}
## Añadir datos clínicos modificados a la base de datos
if (dbtype == "OV"){
upd.clinics<-read.xlsx(filetemp, sheet = "CLINICS",detectDates = T)
ovid.mod<-upd.clinics$OVID[upd.clinics$OVID %in% (sqlFetch(dta, "CLINICS") %>% pull(OVID))]
rnames<-sqlFetch(conn, "CLINICS") %>% filter(OVID %in% ovid.mod) %>% rownames
@@ -123,8 +262,27 @@ sqlSincBD<-function(conn=dta, filetemp="QueryOV.xlsx", sinc.samples=F, sinc.clin
sqlUpdate(conn, clinics.mod,"CLINICS")
print("Tabla CLINICS modificada.")
}
}
if (dbtype == "UM"){
upd.clinics<-read.xlsx(filetemp, sheet = "CLINICS",detectDates = T)
umid.mod<-upd.clinics$UMID[upd.clinics$UMID %in% (sqlFetch(dta, "CLINICOS") %>% pull(UMID))]
rnames<-sqlFetch(conn, "CLINICOS") %>% filter(UMID %in% umid.mod) %>% rownames
clinics.mod<-upd.clinics %>% filter(UMID %in% umid.mod) %>% select(-NHC)
rownames(clinics.mod)<-rnames
### !! Atención, esto cambia la base de datos:
if (sinc.clinics){
fechas<-colnames(clinics.mod)[grepl("date|MET_DX|DoB", colnames(clinics.mod), ignore.case = T)]
for (i in fechas){
clinics.mod[,i]<-as.Date(clinics.mod[,i])
}
sqlUpdate(conn, clinics.mod,"CLINICOS", index="UMID")
print("Tabla CLINICOS modificada.")
}
}
## Añadir datos clínicos nuevos a la base de datos
if (dbtype == "OV"){
nsamples.clin<-sqlFetch(conn, "CLINICS") %>% nrow
ovid.new<-upd.clinics$OVID[!upd.clinics$OVID %in% (sqlFetch(conn, "CLINICS") %>% pull(OVID))]
clinics.new<-upd.clinics %>% filter(OVID %in% ovid.new) %>% select(-NHC)
@@ -142,3 +300,45 @@ sqlSincBD<-function(conn=dta, filetemp="QueryOV.xlsx", sinc.samples=F, sinc.clin
print("Tabla CLINICS sincronizada.")
}
}
if (dbtype == "UM"){
nsamples.clin<-sqlFetch(conn, "CLINICOS") %>% nrow
umid.new<-upd.clinics$UMID[!upd.clinics$UMID %in% (sqlFetch(conn, "CLINICOS") %>% pull(UMID))]
clinics.new<-upd.clinics %>% filter(UMID %in% umid.new) %>% select(-NHC)
if (length(umid.new) > 0){rownames(clinics.new)<-(nsamples.clin+1):(nsamples.clin+nrow(clinics.new)) %>% as.character}
### !! Atención, esto cambia la base de datos:
if (sinc.clinics){
fechas<-colnames(clinics.new)[grepl("date|MET_DX|DoB", colnames(clinics.new), ignore.case = T)]
varTypes<-rep("Date",length(fechas))
names(varTypes)<-fechas
for (i in fechas){
clinics.new[,i]<-as.Date(clinics.new[,i])
}
sqlSave(conn, clinics.new, tablename="CLINICOS", append = T, varTypes = varTypes, rownames = F)
print("Tabla CLINICOS sincronizada.")
}
}
}
sqlMultiSamples<-function(kbl=F, NHC=F, full=F){
query<-sqlQuery(dta, "SELECT U.UMID,U.NHC,M.FECHA_RECEPCION,M.TIPO,M.CODIGO,C.CODIGO,R.CODIGO,R.ESTADO
FROM ((UMID U
LEFT OUTER JOIN MUESTRAS M ON U.UMID=M.UMID)
LEFT OUTER JOIN CNAG C ON M.CODIGO=C.CODIGO)
LEFT OUTER JOIN RNADNA R ON M.CODIGO=R.CODIGO") %>% rename("CNAG"="CODIGO.1","RNADNA"="CODIGO.2")
if (full==F){query<- query %>% filter(!is.na(CODIGO))}
if (NHC==F){query<- query %>% select(-NHC)}
query<-query %>% mutate(
CNAG=case_when(!is.na(CNAG)~"X",TRUE~""),
RNADNA=case_when((!is.na(RNADNA) & (ESTADO=="ENV"))~"X",
(!is.na(RNADNA) & (is.na(ESTADO)))~".",
TRUE~"")
) %>% select(-ESTADO)
if (kbl==T){
query %>% kableExtra::kbl() %>% kableExtra::kable_styling(full_width = F, bootstrap_options = c("striped"))
}else{
return(query)
}
}
+10 -4
View File
@@ -1,15 +1,21 @@
source("sqlFunctions.R")
# Crear copia de seguridad
sqlBackUp()
source("sqlFunctions.R", encoding = "UTF-8")
# Cargar dependencias
sqlInitialize()
## Asegurarse de que la variable file sea la que nos corresponde:
file
# Inicializar conexión
dta<-odbcConnectAccess2007(access.file = file,
pwd = .rs.askForPassword("Enter password:"))
# Crear copia de seguridad
sqlBackUp()
## Importamos los NHC de las muestras nuevas
nhc.test<-read.xlsx("queryOV.xlsx", sheet = "NHC") %>% pull(NHC)
# Ver si ya hay muestras de los pacientes (opcional, para uno mismo)
sqlShowSamples()