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.

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