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.

344 lines
15 KiB

2 years ago
2 years ago
  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(ruta="ruta_database.R"){
  13. library(tidyverse)
  14. library(RODBC)
  15. library(openxlsx)
  16. ## Conexión a la base de datos
  17. source(ruta, 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(conn) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
  55. if(sqlTables(conn) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
  56. if (dbtype == "OV"){
  57. db<-c("dbcode"="OVID", "dbpref"="OVID")
  58. }
  59. if (dbtype == "UM"){
  60. db<-c("dbcode"="UMID","dbpref"="UMID")
  61. }
  62. if (dbtype == "CC"){
  63. db<-c("dbcode"="PATID", "dbpref"="CCID")
  64. }
  65. dbid<-sqlFetch(conn,db["dbcode"])
  66. new.nhc<-nhcs[!nhcs %in% dbid$NHC] %>% unique()
  67. if(length(new.nhc) > 0){
  68. if (nrow(dbid) == 0){next.num<-1}else{
  69. next.num<-gsub(db["dbcode"],"",dbid[,db["dbcode"]]) %>% as.numeric %>% max(na.rm=T)+1
  70. }
  71. print(next.num)
  72. last.num<-next.num+(length(new.nhc)-1)
  73. newtab<-data.frame("NHC"=new.nhc, "ID"=sprintf("%s%04d",db["dbpref"],next.num:last.num)) %>% rename(!!db["dbcode"]:="ID")
  74. if(dbtype=="OV"){
  75. dbid<-rbind(dbid,newtab)
  76. }
  77. if(dbtype=="UM"){
  78. dbid<-merge(dbid, newtab, all=T) %>% select(NHC,UMID) %>% arrange(UMID)
  79. # dbid$Id<-as.numeric(rownames(dbid))
  80. dbid$NHC<-as.numeric(dbid$NHC)
  81. }
  82. if (dbtype=="CC"){
  83. dbid<-merge(dbid, newtab, all=T) %>% select(NHC,PATID) %>% arrange(PATID)
  84. dbid$NHC<-as.numeric(dbid$NHC)
  85. }
  86. rownames(dbid)<-as.character(1:nrow(dbid))
  87. dbid<-filter(dbid, NHC %in% new.nhc) %>% mutate(NHC=as.character(NHC))
  88. if (sinc){
  89. ### !! Atención, esto cambia la base de datos:
  90. sqlSave(conn, dbid, tablename=db["dbcode"], append = T, rownames = F)
  91. print("La base ha sido actualizada.")
  92. }
  93. if (verb){
  94. return(dbid)
  95. }
  96. }else{
  97. print("No hay pacientes nuevos.")
  98. }
  99. }
  100. sqlWriteTemp<-function(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod=T, clinics.mod=T, dbtype=NULL, today=F){
  101. if(sqlTables(dta) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
  102. if(sqlTables(dta) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
  103. if (dbtype=="OV"){
  104. upd.ovid<-sqlFetch(conn, "OVID") %>% filter(NHC %in% nhcs)
  105. if (samples.mod){
  106. ## Generar código para las nuevas muestras
  107. samples<-sqlFetch(conn, "SAMPLES")
  108. if(sum(grepl(paste0("OV",Sys.time() %>% format("%y")), samples$samples)) > 0){
  109. next.samp<-gsub(paste0("OV",Sys.time() %>% format("%y")),"", samples$samples) %>% as.numeric %>% max(na.rm=T)+1
  110. }else{
  111. next.samp<-1
  112. }
  113. last.samp<-next.samp+(length(nhcs)-1)
  114. new.samp<-sprintf("OV%s%02d",Sys.time() %>% format("%y"),next.samp:last.samp)
  115. new.samp.df<-merge(sqlFetch(dta,"OVID") %>% merge(data.frame("NHC"=nhcs)), data.frame("NHC"=nhcs, "samples"=new.samp))
  116. samples.exp<-merge(samples %>% slice(0), new.samp.df %>% select(-NHC), all=T) %>% select(colnames(samples)) %>% arrange(samples)
  117. }
  118. if (clinics.mod){
  119. ## Importar los datos clínicos de pacientes existentes y generar nueva entrada par los nuevos
  120. upd.clinics<-sqlFetch(conn, "CLINICS")
  121. ovid.new<-sqlFetch(conn, "OVID") %>% filter(NHC %in% nhcs)
  122. upd.clinics<-merge(ovid.new,upd.clinics, all.x=T, by="OVID")
  123. upd.clinics$NHC<-as.character(upd.clinics$NHC)
  124. for (i in colnames(upd.clinics)[sapply(upd.clinics, lubridate::is.POSIXct)]){upd.clinics[,i]<-as.Date(upd.clinics[,i])}
  125. }
  126. ## Exportar tablas a la plantilla de entrada para su rellenado
  127. wb <- loadWorkbook(file)
  128. writeData(wb, "NHC", upd.ovid)
  129. if (samples.mod){writeData(wb,"samples",samples.exp)}
  130. if (clinics.mod){writeData(wb,"CLINICS",upd.clinics)}
  131. saveWorkbook(wb,file,overwrite = TRUE)
  132. }
  133. if (dbtype=="UM"){
  134. upd.umid<-sqlFetch(conn, "UMID") %>% filter(NHC %in% nhcs)
  135. if (samples.mod){
  136. ## Generar código para las nuevas muestras
  137. samples<-sqlFetch(conn, "MUESTRAS")
  138. if(sum(grepl(paste0("UM",Sys.time() %>% format("%y")), samples$CODIGO)) > 0){
  139. next.samp<-gsub(paste0("UM",Sys.time() %>% format("%y")),"", samples$CODIGO) %>% as.numeric %>% max(na.rm=T)+1
  140. }else{
  141. next.samp<-1
  142. }
  143. last.samp<-next.samp+(length(nhcs)-1)
  144. new.samp<-sprintf("UM%s%02d",Sys.time() %>% format("%y"),next.samp:last.samp)
  145. new.samp.df<-data.frame("NHC"=nhcs, "CODIGO"=new.samp) %>% merge(sqlFetch(dta,"UMID"), all.x=T) %>% arrange(CODIGO)
  146. samples.exp<-merge(samples %>% slice(0), new.samp.df %>% select(-NHC), all=T) %>% select(colnames(samples)) %>% arrange(CODIGO)
  147. if (today==TRUE){
  148. samples.exp$FECHA_RECEPCION<-format(Sys.Date(), "%d/%m/%y")
  149. }
  150. }
  151. nhc.table<-read.xlsx(file, sheet = "NHC")
  152. if (any(sapply(nhc.table$Samples, function(x) "cnag" %in% strsplit(x,",")[[1]]) == T)){
  153. nhcs.cnag<-nhc.table[sapply(nhc.table$Samples, function(x) "cnag" %in% strsplit(x,",")[[1]]),"NHC"]
  154. umid.cnag<-sqlFetch(conn, "UMID") %>% filter(NHC %in% nhcs.cnag) %>% pull(UMID)
  155. sample.cnag<-samples.exp %>% filter(UMID %in% umid.cnag) %>% pull(CODIGO)
  156. cnag.exp<-merge(data.frame("UMID"=umid.cnag, "CODIGO"=sample.cnag), sqlFetch(dta, "CNAG") %>% slice(0), all=T)
  157. if (today==TRUE){
  158. cnag.exp$FECHA_ENVIO<-format(Sys.Date(), "%d/%m/%y")
  159. }
  160. }else{cnag.exp<-sqlFetch(dta, "CNAG") %>% slice(0)}
  161. if (any(sapply(nhc.table$Samples, function(x) "rna" %in% strsplit(x,",")[[1]]) == T)){
  162. nhcs.rna<-nhc.table[sapply(nhc.table$Samples, function(x) "rna" %in% strsplit(x,",")[[1]]),"NHC"]
  163. umid.rna<-sqlFetch(conn, "UMID") %>% filter(NHC %in% nhcs.rna) %>% pull(UMID)
  164. sample.rna<-samples.exp %>% filter(UMID %in% umid.rna) %>% pull(CODIGO)
  165. rna.exp<-merge(data.frame("UMID"=umid.rna, "CODIGO"=sample.rna), sqlFetch(dta, "RNADNA") %>% slice(0), all=T)
  166. }else{rna.exp<- sqlFetch(dta, "RNADNA") %>% slice(0)}
  167. if (clinics.mod){
  168. ## Importar los datos clínicos de pacientes existentes y generar nueva entrada par los nuevos
  169. upd.clinics<-sqlFetch(conn, "CLINICOS")
  170. umid.new<-sqlFetch(conn, "UMID") %>% filter(NHC %in% nhcs)
  171. upd.clinics<-merge(umid.new,upd.clinics, all.x=T, by="UMID")
  172. upd.clinics$NHC<-as.character(upd.clinics$NHC)
  173. for (i in colnames(upd.clinics)[sapply(upd.clinics, lubridate::is.POSIXct)]){upd.clinics[,i]<-as.Date(upd.clinics[,i])}
  174. }
  175. ## Exportar tablas a la plantilla de entrada para su rellenado
  176. wb <- createWorkbook(file)
  177. addWorksheet(wb, "NHC")
  178. addWorksheet(wb, "samples")
  179. addWorksheet(wb, "CLINICS")
  180. addWorksheet(wb, "CNAG")
  181. addWorksheet(wb, "RNADNA")
  182. writeData(wb, "NHC", merge(nhc.table, upd.umid, sort = F))
  183. if (samples.mod){writeData(wb,"samples",samples.exp)}
  184. if (clinics.mod){writeData(wb,"CLINICS",upd.clinics)}
  185. writeData(wb,"CNAG",cnag.exp)
  186. writeData(wb,"RNADNA",rna.exp)
  187. saveWorkbook(wb,file,overwrite = TRUE)
  188. }
  189. }
  190. sqlSincBD<-function(conn=dta, filetemp="queryOV.xlsx", sinc.samples=F, sinc.clinics=F, dbtype=NULL){
  191. if(sqlTables(dta) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
  192. if(sqlTables(dta) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
  193. ## Añadir código de muestra nueva a la base de datos
  194. if (dbtype == "OV"){
  195. print("DB OV detectada")
  196. nsamples<-sqlFetch(conn, "SAMPLES") %>% nrow
  197. upd.samples<-read.xlsx(filetemp, sheet = "samples", detectDates = T)
  198. if (nrow(upd.samples) > 0){rownames(upd.samples)<-(nsamples+1):(nsamples+nrow(upd.samples)) %>% as.character}
  199. if (sinc.samples & nrow(upd.samples) > 0){
  200. upd.samples$IQ_date<-as.Date(upd.samples$IQ_date)
  201. upd.samples$TIL_date<-as.Date(upd.samples$TIL_date)
  202. ### !! Atención, esto cambia la base de datos:
  203. sqlSave(conn, upd.samples, tablename="SAMPLES", append = T, varTypes = c("IQ_date"="date","TIL_date"="date"))
  204. print("Tabla SAMPLES sincronizada.")
  205. }
  206. }
  207. if (dbtype == "UM"){
  208. print("DB UM detectada")
  209. nsamples<-sqlFetch(conn, "MUESTRAS") %>% nrow
  210. upd.samples<-read.xlsx(filetemp, sheet = "samples", detectDates = T)
  211. if (nrow(upd.samples) > 0){rownames(upd.samples)<-(nsamples+1):(nsamples+nrow(upd.samples)) %>% as.character}
  212. if (sinc.samples & nrow(upd.samples) > 0){
  213. upd.samples$FECHA_RECEPCION<-as.Date(upd.samples$FECHA_RECEPCION)
  214. upd.samples$TIPO<-as.character(upd.samples$TIPO)
  215. upd.samples$OBS<-as.character(upd.samples$OBS)
  216. ### !! Atención, esto cambia la base de datos:
  217. sqlSave(conn, upd.samples, tablename="MUESTRAS", append = T, varTypes = c("FECHA_RECEPCION"="Date"), rownames = F)
  218. print("Tabla MUESTRAS sincronizada.")
  219. }
  220. }
  221. ## Añadir datos clínicos modificados a la base de datos
  222. if (dbtype == "OV"){
  223. upd.clinics<-read.xlsx(filetemp, sheet = "CLINICS",detectDates = T)
  224. ovid.mod<-upd.clinics$OVID[upd.clinics$OVID %in% (sqlFetch(dta, "CLINICS") %>% pull(OVID))]
  225. rnames<-sqlFetch(conn, "CLINICS") %>% filter(OVID %in% ovid.mod) %>% rownames
  226. clinics.mod<-upd.clinics %>% filter(OVID %in% ovid.mod) %>% select(-NHC)
  227. rownames(clinics.mod)<-rnames
  228. ### !! Atención, esto cambia la base de datos:
  229. if (sinc.clinics){
  230. fechas<-colnames(clinics.mod)[grepl("DO|date", colnames(clinics.mod))]
  231. for (i in fechas){
  232. clinics.mod[,i]<-as.Date(clinics.mod[,i])
  233. }
  234. sqlUpdate(conn, clinics.mod,"CLINICS")
  235. print("Tabla CLINICS modificada.")
  236. }
  237. }
  238. if (dbtype == "UM"){
  239. upd.clinics<-read.xlsx(filetemp, sheet = "CLINICS",detectDates = T)
  240. umid.mod<-upd.clinics$UMID[upd.clinics$UMID %in% (sqlFetch(dta, "CLINICOS") %>% pull(UMID))]
  241. rnames<-sqlFetch(conn, "CLINICOS") %>% filter(UMID %in% umid.mod) %>% rownames
  242. clinics.mod<-upd.clinics %>% filter(UMID %in% umid.mod) %>% select(-NHC)
  243. rownames(clinics.mod)<-rnames
  244. ### !! Atención, esto cambia la base de datos:
  245. if (sinc.clinics){
  246. fechas<-colnames(clinics.mod)[grepl("date|MET_DX|DoB", colnames(clinics.mod), ignore.case = T)]
  247. for (i in fechas){
  248. clinics.mod[,i]<-as.Date(clinics.mod[,i])
  249. }
  250. sqlUpdate(conn, clinics.mod,"CLINICOS", index="UMID")
  251. print("Tabla CLINICOS modificada.")
  252. }
  253. }
  254. ## Añadir datos clínicos nuevos a la base de datos
  255. if (dbtype == "OV"){
  256. nsamples.clin<-sqlFetch(conn, "CLINICS") %>% nrow
  257. ovid.new<-upd.clinics$OVID[!upd.clinics$OVID %in% (sqlFetch(conn, "CLINICS") %>% pull(OVID))]
  258. clinics.new<-upd.clinics %>% filter(OVID %in% ovid.new) %>% select(-NHC)
  259. if (length(ovid.new) > 0){rownames(clinics.new)<-(nsamples.clin+1):(nsamples.clin+nrow(clinics.new)) %>% as.character}
  260. ### !! Atención, esto cambia la base de datos:
  261. if (sinc.clinics){
  262. fechas<-colnames(clinics.new)[grepl("DO|date", colnames(clinics.new))]
  263. varTypes<-rep("Date",length(fechas))
  264. names(varTypes)<-fechas
  265. for (i in fechas){
  266. clinics.new[,i]<-as.Date(clinics.new[,i])
  267. }
  268. sqlSave(conn, clinics.new, tablename="CLINICS", append = T, varTypes = varTypes)
  269. print("Tabla CLINICS sincronizada.")
  270. }
  271. }
  272. if (dbtype == "UM"){
  273. nsamples.clin<-sqlFetch(conn, "CLINICOS") %>% nrow
  274. umid.new<-upd.clinics$UMID[!upd.clinics$UMID %in% (sqlFetch(conn, "CLINICOS") %>% pull(UMID))]
  275. clinics.new<-upd.clinics %>% filter(UMID %in% umid.new) %>% select(-NHC)
  276. if (length(umid.new) > 0){rownames(clinics.new)<-(nsamples.clin+1):(nsamples.clin+nrow(clinics.new)) %>% as.character}
  277. ### !! Atención, esto cambia la base de datos:
  278. if (sinc.clinics){
  279. fechas<-colnames(clinics.new)[grepl("date|MET_DX|DoB", colnames(clinics.new), ignore.case = T)]
  280. varTypes<-rep("Date",length(fechas))
  281. names(varTypes)<-fechas
  282. for (i in fechas){
  283. clinics.new[,i]<-as.Date(clinics.new[,i])
  284. }
  285. sqlSave(conn, clinics.new, tablename="CLINICOS", append = T, varTypes = varTypes, rownames = F)
  286. print("Tabla CLINICOS sincronizada.")
  287. }
  288. }
  289. }
  290. sqlMultiSamples<-function(kbl=F, NHC=F, full=F){
  291. query<-sqlQuery(dta, "SELECT U.UMID,U.NHC,M.FECHA_RECEPCION,M.TIPO,M.CODIGO,C.CODIGO,R.CODIGO,R.ESTADO
  292. FROM ((UMID U
  293. LEFT OUTER JOIN MUESTRAS M ON U.UMID=M.UMID)
  294. LEFT OUTER JOIN CNAG C ON M.CODIGO=C.CODIGO)
  295. LEFT OUTER JOIN RNADNA R ON M.CODIGO=R.CODIGO") %>% rename("CNAG"="CODIGO.1","RNADNA"="CODIGO.2")
  296. if (full==F){query<- query %>% filter(!is.na(CODIGO))}
  297. if (NHC==F){query<- query %>% select(-NHC)}
  298. query<-query %>% mutate(
  299. CNAG=case_when(!is.na(CNAG)~"X",TRUE~""),
  300. RNADNA=case_when((!is.na(RNADNA) & (ESTADO=="ENV"))~"X",
  301. (!is.na(RNADNA) & (is.na(ESTADO)))~".",
  302. TRUE~"")
  303. ) %>% select(-ESTADO)
  304. if (kbl==T){
  305. query %>% kableExtra::kbl() %>% kableExtra::kable_styling(full_width = F, bootstrap_options = c("striped"))
  306. }else{
  307. return(query)
  308. }
  309. }