Scripts relacionados con el acceso y análisis en bases de datos Access.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

183 lines
7.2 KiB

  1. require(RODBC)
  2. sqlDropLast<-function(conn, tablename, droplast=1){
  3. table<-sqlFetch(conn, tablename)
  4. table<-table[1:(nrow(table)-droplast),]
  5. sqlSave(conn, table, tablename = tablename, safer = F)
  6. }
  7. sqlInitialize<-function(){
  8. library(tidyverse)
  9. library(RODBC)
  10. library(openxlsx)
  11. ## Conexión a la base de datos
  12. source("ruta_database.R", encoding = "UTF-8")
  13. }
  14. sqlBackUp<-function(dbfile=file,bu.dir){
  15. db=strsplit(dbfile, "/")[[1]]%>% tail(n=1)
  16. bu_path<-gsub(db,bu.dir,dbfile)
  17. if (!dir.exists(bu_path)){
  18. dir.create(bu_path)
  19. print(paste0("Back Up directory ", bu_path, " created"))
  20. }
  21. cp_bu<-paste0(bu_path, "/", format(Sys.time(), format="%Y%m%d"),"-",db)
  22. file.copy(dbfile, cp_bu)
  23. }
  24. sqlShowSamples<-function(conn=dta, nhcs=nhc.test, verb=F, dbtype){
  25. if (dbtype == "OV"){
  26. db<-c("dbtables"="SAMPLES", "dbcode"="OVID", "dbsamples"="samples")
  27. query<-paste0("SELECT O.NHC,S.* FROM ",db["dbtables"]," S INNER JOIN ",db["dbcode"]," O ON O.",db["dbcode"],"=S.",db["dbcode"])
  28. }
  29. if (dbtype == "UM"){
  30. db<-c("dbtables"="MUESTRAS", "dbcode"="UMID", "dbsamples"="CODIGO")
  31. query<-paste0("SELECT O.NHC,S.* FROM ",db["dbtables"]," S INNER JOIN ",db["dbcode"]," O ON O.",db["dbcode"],"=S.",db["dbcode"])
  32. }
  33. if (nrow(sqlQuery(conn, query) %>% filter(NHC %in% nhcs)) == 0){
  34. return("No hay muestras de ningún paciente.")
  35. }
  36. if (isFALSE(verb)){
  37. sqlQuery(conn, query) %>% filter(NHC %in% nhcs) %>%
  38. group_by(NHC,UQ(rlang::sym(db["dbcode"]))) %>% summarise(Samples=length(UQ(rlang::sym(db["dbsamples"]))), Names=paste0(UQ(rlang::sym(db["dbsamples"])), collapse = ";")) %>%
  39. merge(data.frame(NHC=nhcs),all=T) %>% mutate(NHC=factor(NHC,levels = nhcs)) %>% arrange(NHC)
  40. }else{
  41. sqlQuery(conn, query) %>% filter(NHC %in% nhcs)
  42. }
  43. }
  44. sqlGenOVID<-function(conn=dta, nhcs=nhc.test, verb=T, sinc=F, dbtype){
  45. if (dbtype == "OV"){
  46. db<-c("dbcode"="OVID")
  47. }
  48. if (dbtype == "UM"){
  49. db<-c("dbcode"="UMID")
  50. }
  51. dbid<-sqlFetch(conn,db["dbcode"])
  52. new.nhc<-nhcs[!nhcs %in% dbid$NHC]
  53. next.num<-gsub(db["dbcode"],"",dbid[,db["dbcode"]]) %>% as.numeric %>% max(na.rm=T)+1
  54. last.num<-next.num+(length(new.nhc)-1)
  55. newtab<-data.frame("NHC"=new.nhc, "ID"=sprintf("%s%04d",db["dbcode"],next.num:last.num)) %>% rename(!!db["dbcode"]:="ID")
  56. if(dbtype=="OV"){
  57. dbid<-rbind(dbid,newtab)
  58. }
  59. if(dbtype=="UM"){
  60. dbid<-merge(dbid, newtab, all=T) %>% select(Id,NHC,UMID) %>% arrange(Id)
  61. dbid$Id<-rownames(dbid)
  62. }
  63. rownames(dbid)<-as.character(1:nrow(dbid))
  64. dbid<-filter(dbid, NHC %in% new.nhc) %>% mutate(NHC=as.character(NHC))
  65. if (sinc){
  66. ### !! Atención, esto cambia la base de datos:
  67. sqlSave(conn, dbid, tablename=db["dbcode"], append = T)
  68. print("La base ha sido actualizada.")
  69. }
  70. if (verb){
  71. return(dbid)
  72. }
  73. }
  74. sqlWriteTemp<-function(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod=T, clinics.mod=T){
  75. upd.ovid<-sqlFetch(conn, "OVID") %>% filter(NHC %in% nhcs)
  76. if (samples.mod){
  77. ## Generar código para las nuevas muestras
  78. samples<-sqlFetch(conn, "SAMPLES")
  79. if(sum(grepl(paste0("OV",Sys.time() %>% format("%y")), samples$samples)) > 0){
  80. next.samp<-gsub(paste0("OV",Sys.time() %>% format("%y")),"", samples$samples) %>% as.numeric %>% max(na.rm=T)+1
  81. }else{
  82. next.samp<-1
  83. }
  84. last.samp<-next.samp+(length(nhcs)-1)
  85. new.samp<-sprintf("OV%s%02d",Sys.time() %>% format("%y"),next.samp:last.samp)
  86. new.samp.df<-merge(sqlFetch(dta,"OVID") %>% merge(data.frame("NHC"=nhcs)), data.frame("NHC"=nhcs, "samples"=new.samp))
  87. samples.exp<-merge(samples %>% slice(0), new.samp.df %>% select(-NHC), all=T) %>% select(colnames(samples)) %>% arrange(samples)
  88. }
  89. if (clinics.mod){
  90. ## Importar los datos clínicos de pacientes existentes y generar nueva entrada par los nuevos
  91. upd.clinics<-sqlFetch(conn, "CLINICS")
  92. ovid.new<-sqlFetch(conn, "OVID") %>% filter(NHC %in% nhcs)
  93. upd.clinics<-merge(ovid.new,upd.clinics, all.x=T, by="OVID")
  94. upd.clinics$NHC<-as.character(upd.clinics$NHC)
  95. for (i in colnames(upd.clinics)[sapply(upd.clinics, lubridate::is.POSIXct)]){upd.clinics[,i]<-as.Date(upd.clinics[,i])}
  96. }
  97. ## Exportar tablas a la plantilla de entrada para su rellenado
  98. wb <- loadWorkbook(file)
  99. writeData(wb, "NHC", upd.ovid)
  100. if (samples.mod){writeData(wb,"samples",samples.exp)}
  101. if (clinics.mod){writeData(wb,"CLINICS",upd.clinics)}
  102. saveWorkbook(wb,file,overwrite = TRUE)
  103. }
  104. sqlSincBD<-function(conn=dta, filetemp="QueryOV.xlsx", sinc.samples=F, sinc.clinics=F){
  105. ## Añadir código de muestra nueva a la base de datos
  106. nsamples<-sqlFetch(conn, "SAMPLES") %>% nrow
  107. upd.samples<-read.xlsx(filetemp, sheet = "samples", detectDates = T)
  108. if (nrow(upd.samples) > 0){rownames(upd.samples)<-(nsamples+1):(nsamples+nrow(upd.samples)) %>% as.character}
  109. if (sinc.samples & nrow(upd.samples) > 0){
  110. upd.samples$IQ_date<-as.Date(upd.samples$IQ_date)
  111. upd.samples$TIL_date<-as.Date(upd.samples$TIL_date)
  112. ### !! Atención, esto cambia la base de datos:
  113. sqlSave(conn, upd.samples, tablename="SAMPLES", append = T, varTypes = c("IQ_date"="date","TIL_date"="date"))
  114. print("Tabla SAMPLES sincronizada.")
  115. }
  116. ## Añadir datos clínicos modificados a la base de datos
  117. upd.clinics<-read.xlsx(filetemp, sheet = "CLINICS",detectDates = T)
  118. ovid.mod<-upd.clinics$OVID[upd.clinics$OVID %in% (sqlFetch(dta, "CLINICS") %>% pull(OVID))]
  119. rnames<-sqlFetch(conn, "CLINICS") %>% filter(OVID %in% ovid.mod) %>% rownames
  120. clinics.mod<-upd.clinics %>% filter(OVID %in% ovid.mod) %>% select(-NHC)
  121. rownames(clinics.mod)<-rnames
  122. ### !! Atención, esto cambia la base de datos:
  123. if (sinc.clinics){
  124. fechas<-colnames(clinics.mod)[grepl("DO|date", colnames(clinics.mod))]
  125. for (i in fechas){
  126. clinics.mod[,i]<-as.Date(clinics.mod[,i])
  127. }
  128. sqlUpdate(conn, clinics.mod,"CLINICS")
  129. print("Tabla CLINICS modificada.")
  130. }
  131. ## Añadir datos clínicos nuevos a la base de datos
  132. nsamples.clin<-sqlFetch(conn, "CLINICS") %>% nrow
  133. ovid.new<-upd.clinics$OVID[!upd.clinics$OVID %in% (sqlFetch(conn, "CLINICS") %>% pull(OVID))]
  134. clinics.new<-upd.clinics %>% filter(OVID %in% ovid.new) %>% select(-NHC)
  135. if (length(ovid.new) > 0){rownames(clinics.new)<-(nsamples.clin+1):(nsamples.clin+nrow(clinics.new)) %>% as.character}
  136. ### !! Atención, esto cambia la base de datos:
  137. if (sinc.clinics){
  138. fechas<-colnames(clinics.new)[grepl("DO|date", colnames(clinics.new))]
  139. varTypes<-rep("Date",length(fechas))
  140. names(varTypes)<-fechas
  141. for (i in fechas){
  142. clinics.new[,i]<-as.Date(clinics.new[,i])
  143. }
  144. sqlSave(conn, clinics.new, tablename="CLINICS", append = T, varTypes = varTypes)
  145. print("Tabla CLINICS sincronizada.")
  146. }
  147. }
  148. sqlMultiSamples<-function(kbl=F, NHC=F){
  149. query<-sqlQuery(dta, "SELECT M.UMID,U.NHC,M.FECHA_RECEPCION,M.CODIGO,C.CODIGO,R.CODIGO
  150. FROM ((MUESTRAS M
  151. LEFT OUTER JOIN CNAG C ON M.CODIGO=C.CODIGO)
  152. LEFT OUTER JOIN RNADNA R ON M.CODIGO=R.CODIGO)
  153. LEFT OUTER JOIN UMID U ON U.UMID=M.UMID") %>% rename("CNAG"="CODIGO.1","RNADNA"="CODIGO.2")
  154. query<-query %>% mutate(
  155. CNAG=case_when(!is.na(CNAG)~"X",TRUE~""),
  156. RNADNA=case_when(!is.na(RNADNA)~"X",TRUE~"")
  157. )
  158. if (kbl==T){
  159. query %>% kableExtra::kbl() %>% kableExtra::kable_styling(full_width = F, bootstrap_options = c("striped"))
  160. }else{
  161. return(query)
  162. }
  163. }