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.

306 lines
13 KiB

  1. require(RODBC)
  2. sqlLastDrop<-function(conn, tablename, droplast=1,dbtype=NULL){
  3. if(sqlTables(conn) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
  4. if(sqlTables(conn) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
  5. table<-sqlFetch(conn, tablename)
  6. table<-table[1:(nrow(table)-droplast),]
  7. if (dbtype == "OV"){sqlSave(conn, table, tablename = tablename, safer = F)}
  8. if (dbtype == "UM"){
  9. sqlDrop(conn, tablename)
  10. sqlSave(conn, table, tablename = tablename, safer = F)}
  11. }
  12. sqlInitialize<-function(){
  13. library(tidyverse)
  14. library(RODBC)
  15. library(openxlsx)
  16. ## Conexión a la base de datos
  17. source("ruta_database.R", encoding = "UTF-8")
  18. }
  19. sqlBackUp<-function(dbfile=file,conn=dta,bu.dir=NULL){
  20. if(sqlTables(conn) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){bu.dir<-"BU_UM"}
  21. if(sqlTables(conn) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){bu.dir<-"BU_OVARIO"}
  22. db=strsplit(dbfile, "/")[[1]]%>% tail(n=1)
  23. bu_path<-gsub(db,bu.dir,dbfile)
  24. if (!dir.exists(bu_path)){
  25. dir.create(bu_path)
  26. print(paste0("Back Up directory ", bu_path, " created"))
  27. }
  28. cp_bu<-paste0(bu_path, "/", format(Sys.time(), format="%Y%m%d"),"-",db)
  29. file.copy(dbfile, cp_bu)
  30. }
  31. sqlShowSamples<-function(conn=dta, nhcs=nhc.test, verb=F, dbtype=NULL){
  32. if(sqlTables(dta) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
  33. if(sqlTables(dta) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
  34. if (dbtype == "OV"){
  35. db<-c("dbtables"="SAMPLES", "dbcode"="OVID", "dbsamples"="samples")
  36. query<-paste0("SELECT O.NHC,S.* FROM ",db["dbtables"]," S INNER JOIN ",db["dbcode"]," O ON O.",db["dbcode"],"=S.",db["dbcode"])
  37. }
  38. if (dbtype == "UM"){
  39. db<-c("dbtables"="MUESTRAS", "dbcode"="UMID", "dbsamples"="CODIGO")
  40. query<-paste0("SELECT O.NHC,S.* FROM ",db["dbtables"]," S INNER JOIN ",db["dbcode"]," O ON O.",db["dbcode"],"=S.",db["dbcode"])
  41. }
  42. if (nrow(sqlQuery(conn, query) %>% filter(NHC %in% nhcs)) == 0){
  43. return("No hay muestras de ningún paciente.")
  44. }
  45. if (isFALSE(verb)){
  46. sqlQuery(conn, query) %>% filter(NHC %in% nhcs) %>%
  47. group_by(NHC,UQ(rlang::sym(db["dbcode"]))) %>% summarise(Samples=length(UQ(rlang::sym(db["dbsamples"]))), Names=paste0(UQ(rlang::sym(db["dbsamples"])), collapse = ";")) %>%
  48. merge(data.frame(NHC=nhcs),all=T) %>% mutate(NHC=factor(NHC,levels = unique(nhcs))) %>% arrange(NHC)
  49. }else{
  50. sqlQuery(conn, query) %>% filter(NHC %in% nhcs)
  51. }
  52. }
  53. sqlGenOVID<-function(conn=dta, nhcs=nhc.test, verb=T, sinc=F, dbtype=NULL){
  54. if(sqlTables(dta) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
  55. if(sqlTables(dta) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
  56. if (dbtype == "OV"){
  57. db<-c("dbcode"="OVID")
  58. }
  59. if (dbtype == "UM"){
  60. db<-c("dbcode"="UMID")
  61. }
  62. dbid<-sqlFetch(conn,db["dbcode"])
  63. new.nhc<-nhcs[!nhcs %in% dbid$NHC] %>% unique()
  64. if(length(new.nhc) > 0){
  65. next.num<-gsub(db["dbcode"],"",dbid[,db["dbcode"]]) %>% as.numeric %>% max(na.rm=T)+1
  66. last.num<-next.num+(length(new.nhc)-1)
  67. newtab<-data.frame("NHC"=new.nhc, "ID"=sprintf("%s%04d",db["dbcode"],next.num:last.num)) %>% rename(!!db["dbcode"]:="ID")
  68. if(dbtype=="OV"){
  69. dbid<-rbind(dbid,newtab)
  70. }
  71. if(dbtype=="UM"){
  72. dbid<-merge(dbid, newtab, all=T) %>% select(NHC,UMID) %>% arrange(UMID)
  73. # dbid$Id<-as.numeric(rownames(dbid))
  74. dbid$NHC<-as.numeric(dbid$NHC)
  75. }
  76. rownames(dbid)<-as.character(1:nrow(dbid))
  77. dbid<-filter(dbid, NHC %in% new.nhc) %>% mutate(NHC=as.character(NHC))
  78. if (sinc){
  79. ### !! Atención, esto cambia la base de datos:
  80. sqlSave(conn, dbid, tablename=db["dbcode"], append = T, rownames = F)
  81. print("La base ha sido actualizada.")
  82. }
  83. if (verb){
  84. return(dbid)
  85. }
  86. }else{
  87. print("No hay pacientes nuevos.")
  88. }
  89. }
  90. sqlWriteTemp<-function(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod=T, clinics.mod=T, dbtype=NULL){
  91. if(sqlTables(dta) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
  92. if(sqlTables(dta) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
  93. if (dbtype=="OV"){
  94. upd.ovid<-sqlFetch(conn, "OVID") %>% filter(NHC %in% nhcs)
  95. if (samples.mod){
  96. ## Generar código para las nuevas muestras
  97. samples<-sqlFetch(conn, "SAMPLES")
  98. if(sum(grepl(paste0("OV",Sys.time() %>% format("%y")), samples$samples)) > 0){
  99. next.samp<-gsub(paste0("OV",Sys.time() %>% format("%y")),"", samples$samples) %>% as.numeric %>% max(na.rm=T)+1
  100. }else{
  101. next.samp<-1
  102. }
  103. last.samp<-next.samp+(length(nhcs)-1)
  104. new.samp<-sprintf("OV%s%02d",Sys.time() %>% format("%y"),next.samp:last.samp)
  105. new.samp.df<-merge(sqlFetch(dta,"OVID") %>% merge(data.frame("NHC"=nhcs)), data.frame("NHC"=nhcs, "samples"=new.samp))
  106. samples.exp<-merge(samples %>% slice(0), new.samp.df %>% select(-NHC), all=T) %>% select(colnames(samples)) %>% arrange(samples)
  107. }
  108. if (clinics.mod){
  109. ## Importar los datos clínicos de pacientes existentes y generar nueva entrada par los nuevos
  110. upd.clinics<-sqlFetch(conn, "CLINICS")
  111. ovid.new<-sqlFetch(conn, "OVID") %>% filter(NHC %in% nhcs)
  112. upd.clinics<-merge(ovid.new,upd.clinics, all.x=T, by="OVID")
  113. upd.clinics$NHC<-as.character(upd.clinics$NHC)
  114. for (i in colnames(upd.clinics)[sapply(upd.clinics, lubridate::is.POSIXct)]){upd.clinics[,i]<-as.Date(upd.clinics[,i])}
  115. }
  116. ## Exportar tablas a la plantilla de entrada para su rellenado
  117. wb <- loadWorkbook(file)
  118. writeData(wb, "NHC", upd.ovid)
  119. if (samples.mod){writeData(wb,"samples",samples.exp)}
  120. if (clinics.mod){writeData(wb,"CLINICS",upd.clinics)}
  121. saveWorkbook(wb,file,overwrite = TRUE)
  122. }
  123. if (dbtype=="UM"){
  124. upd.umid<-sqlFetch(conn, "UMID") %>% filter(NHC %in% nhcs)
  125. if (samples.mod){
  126. ## Generar código para las nuevas muestras
  127. samples<-sqlFetch(conn, "MUESTRAS")
  128. if(sum(grepl(paste0("UM",Sys.time() %>% format("%y")), samples$CODIGO)) > 0){
  129. next.samp<-gsub(paste0("UM",Sys.time() %>% format("%y")),"", samples$CODIGO) %>% as.numeric %>% max(na.rm=T)+1
  130. }else{
  131. next.samp<-1
  132. }
  133. last.samp<-next.samp+(length(nhcs)-1)
  134. new.samp<-sprintf("UM%s%02d",Sys.time() %>% format("%y"),next.samp:last.samp)
  135. new.samp.df<-data.frame("NHC"=nhcs, "CODIGO"=new.samp) %>% merge(sqlFetch(dta,"UMID")) %>% arrange(CODIGO)
  136. samples.exp<-merge(samples %>% slice(0), new.samp.df %>% select(-NHC), all=T) %>% select(colnames(samples)) %>% arrange(CODIGO)
  137. }
  138. if (clinics.mod){
  139. ## Importar los datos clínicos de pacientes existentes y generar nueva entrada par los nuevos
  140. upd.clinics<-sqlFetch(conn, "CLINICOS")
  141. umid.new<-sqlFetch(conn, "UMID") %>% filter(NHC %in% nhcs)
  142. upd.clinics<-merge(umid.new,upd.clinics %>% select(-Id), all.x=T, by="UMID")
  143. upd.clinics$NHC<-as.character(upd.clinics$NHC)
  144. for (i in colnames(upd.clinics)[sapply(upd.clinics, lubridate::is.POSIXct)]){upd.clinics[,i]<-as.Date(upd.clinics[,i])}
  145. }
  146. ## Exportar tablas a la plantilla de entrada para su rellenado
  147. wb <- loadWorkbook(file)
  148. writeData(wb, "NHC", merge(data.frame("NHC"=nhcs), upd.umid, sort = F))
  149. if (samples.mod){writeData(wb,"samples",samples.exp)}
  150. if (clinics.mod){writeData(wb,"CLINICS",upd.clinics)}
  151. saveWorkbook(wb,file,overwrite = TRUE)
  152. }
  153. }
  154. sqlSincBD<-function(conn=dta, filetemp="queryOV.xlsx", sinc.samples=F, sinc.clinics=F, dbtype=NULL){
  155. if(sqlTables(dta) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
  156. if(sqlTables(dta) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
  157. ## Añadir código de muestra nueva a la base de datos
  158. if (dbtype == "OV"){
  159. print("DB OV detectada")
  160. nsamples<-sqlFetch(conn, "SAMPLES") %>% nrow
  161. upd.samples<-read.xlsx(filetemp, sheet = "samples", detectDates = T)
  162. if (nrow(upd.samples) > 0){rownames(upd.samples)<-(nsamples+1):(nsamples+nrow(upd.samples)) %>% as.character}
  163. if (sinc.samples & nrow(upd.samples) > 0){
  164. upd.samples$IQ_date<-as.Date(upd.samples$IQ_date)
  165. upd.samples$TIL_date<-as.Date(upd.samples$TIL_date)
  166. ### !! Atención, esto cambia la base de datos:
  167. sqlSave(conn, upd.samples, tablename="SAMPLES", append = T, varTypes = c("IQ_date"="date","TIL_date"="date"))
  168. print("Tabla SAMPLES sincronizada.")
  169. }
  170. }
  171. if (dbtype == "UM"){
  172. print("DB UM detectada")
  173. nsamples<-sqlFetch(conn, "MUESTRAS") %>% nrow
  174. upd.samples<-read.xlsx(filetemp, sheet = "samples", detectDates = T)
  175. if (nrow(upd.samples) > 0){rownames(upd.samples)<-(nsamples+1):(nsamples+nrow(upd.samples)) %>% as.character}
  176. if (sinc.samples & nrow(upd.samples) > 0){
  177. upd.samples$FECHA_RECEPCION<-as.Date(upd.samples$FECHA_RECEPCION)
  178. upd.samples$TIPO<-as.character(upd.samples$TIPO)
  179. upd.samples$OBS<-as.character(upd.samples$OBS)
  180. ### !! Atención, esto cambia la base de datos:
  181. sqlSave(conn, upd.samples, tablename="MUESTRAS", append = T, varTypes = c("FECHA_RECEPCION"="Date"), rownames = F)
  182. print("Tabla MUESTRAS sincronizada.")
  183. }
  184. }
  185. ## Añadir datos clínicos modificados a la base de datos
  186. if (dbtype == "OV"){
  187. upd.clinics<-read.xlsx(filetemp, sheet = "CLINICS",detectDates = T)
  188. ovid.mod<-upd.clinics$OVID[upd.clinics$OVID %in% (sqlFetch(dta, "CLINICS") %>% pull(OVID))]
  189. rnames<-sqlFetch(conn, "CLINICS") %>% filter(OVID %in% ovid.mod) %>% rownames
  190. clinics.mod<-upd.clinics %>% filter(OVID %in% ovid.mod) %>% select(-NHC)
  191. rownames(clinics.mod)<-rnames
  192. ### !! Atención, esto cambia la base de datos:
  193. if (sinc.clinics){
  194. fechas<-colnames(clinics.mod)[grepl("DO|date", colnames(clinics.mod))]
  195. for (i in fechas){
  196. clinics.mod[,i]<-as.Date(clinics.mod[,i])
  197. }
  198. sqlUpdate(conn, clinics.mod,"CLINICS")
  199. print("Tabla CLINICS modificada.")
  200. }
  201. }
  202. if (dbtype == "UM"){
  203. upd.clinics<-read.xlsx(filetemp, sheet = "CLINICS",detectDates = T)
  204. umid.mod<-upd.clinics$UMID[upd.clinics$UMID %in% (sqlFetch(dta, "CLINICOS") %>% pull(UMID))]
  205. rnames<-sqlFetch(conn, "CLINICOS") %>% filter(UMID %in% umid.mod) %>% rownames
  206. clinics.mod<-upd.clinics %>% filter(UMID %in% umid.mod) %>% select(-NHC)
  207. rownames(clinics.mod)<-rnames
  208. ### !! Atención, esto cambia la base de datos:
  209. if (sinc.clinics){
  210. fechas<-colnames(clinics.mod)[grepl("date|MET_DX|DoB", colnames(clinics.mod), ignore.case = T)]
  211. for (i in fechas){
  212. clinics.mod[,i]<-as.Date(clinics.mod[,i])
  213. }
  214. sqlUpdate(conn, clinics.mod,"CLINICOS")
  215. print("Tabla CLINICOS modificada.")
  216. }
  217. }
  218. ## Añadir datos clínicos nuevos a la base de datos
  219. if (dbtype == "OV"){
  220. nsamples.clin<-sqlFetch(conn, "CLINICS") %>% nrow
  221. ovid.new<-upd.clinics$OVID[!upd.clinics$OVID %in% (sqlFetch(conn, "CLINICS") %>% pull(OVID))]
  222. clinics.new<-upd.clinics %>% filter(OVID %in% ovid.new) %>% select(-NHC)
  223. if (length(ovid.new) > 0){rownames(clinics.new)<-(nsamples.clin+1):(nsamples.clin+nrow(clinics.new)) %>% as.character}
  224. ### !! Atención, esto cambia la base de datos:
  225. if (sinc.clinics){
  226. fechas<-colnames(clinics.new)[grepl("DO|date", colnames(clinics.new))]
  227. varTypes<-rep("Date",length(fechas))
  228. names(varTypes)<-fechas
  229. for (i in fechas){
  230. clinics.new[,i]<-as.Date(clinics.new[,i])
  231. }
  232. sqlSave(conn, clinics.new, tablename="CLINICS", append = T, varTypes = varTypes)
  233. print("Tabla CLINICS sincronizada.")
  234. }
  235. }
  236. if (dbtype == "UM"){
  237. nsamples.clin<-sqlFetch(conn, "CLINICOS") %>% nrow
  238. umid.new<-upd.clinics$UMID[!upd.clinics$UMID %in% (sqlFetch(conn, "CLINICOS") %>% pull(UMID))]
  239. clinics.new<-upd.clinics %>% filter(UMID %in% umid.new) %>% select(-NHC)
  240. if (length(umid.new) > 0){rownames(clinics.new)<-(nsamples.clin+1):(nsamples.clin+nrow(clinics.new)) %>% as.character}
  241. ### !! Atención, esto cambia la base de datos:
  242. if (sinc.clinics){
  243. fechas<-colnames(clinics.new)[grepl("date|MET_DX|DoB", colnames(clinics.new), ignore.case = T)]
  244. varTypes<-rep("Date",length(fechas))
  245. names(varTypes)<-fechas
  246. for (i in fechas){
  247. clinics.new[,i]<-as.Date(clinics.new[,i])
  248. }
  249. sqlSave(conn, clinics.new, tablename="CLINICOS", append = T, varTypes = varTypes)
  250. print("Tabla CLINICOS sincronizada.")
  251. }
  252. }
  253. }
  254. sqlMultiSamples<-function(kbl=F, NHC=F, full=F){
  255. query<-sqlQuery(dta, "SELECT U.UMID,U.NHC,M.FECHA_RECEPCION,M.TIPO,M.CODIGO,C.CODIGO,R.CODIGO,R.ESTADO
  256. FROM ((UMID U
  257. LEFT OUTER JOIN MUESTRAS M ON U.UMID=M.UMID)
  258. LEFT OUTER JOIN CNAG C ON M.CODIGO=C.CODIGO)
  259. LEFT OUTER JOIN RNADNA R ON M.CODIGO=R.CODIGO") %>% rename("CNAG"="CODIGO.1","RNADNA"="CODIGO.2")
  260. if (full==F){query<- query %>% filter(!is.na(CODIGO))}
  261. if (NHC==F){query<- query %>% select(-NHC)}
  262. query<-query %>% mutate(
  263. CNAG=case_when(!is.na(CNAG)~"X",TRUE~""),
  264. RNADNA=case_when((!is.na(RNADNA) & (ESTADO=="ENV"))~"X",
  265. (!is.na(RNADNA) & (is.na(ESTADO)))~".",
  266. TRUE~"")
  267. ) %>% select(-ESTADO)
  268. if (kbl==T){
  269. query %>% kableExtra::kbl() %>% kableExtra::kable_styling(full_width = F, bootstrap_options = c("striped"))
  270. }else{
  271. return(query)
  272. }
  273. }