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.

144 lines
5.7 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="BU_OVARIO"){
  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){
  25. if (isFALSE(verb)){
  26. sqlQuery(conn, "SELECT O.NHC,S.*
  27. FROM SAMPLES S
  28. INNER JOIN OVID O
  29. ON O.OVID=S.OVID") %>% filter(NHC %in% nhcs) %>%
  30. group_by(NHC,OVID) %>% summarise(Samples=length(samples), Names=paste0(samples, collapse = ";")) %>% merge(data.frame(NHC=nhcs),all=T)
  31. }else{
  32. sqlQuery(conn, "SELECT O.NHC,S.*
  33. FROM SAMPLES S
  34. INNER JOIN OVID O
  35. ON O.OVID=S.OVID") %>% filter(NHC %in% nhcs)
  36. }
  37. }
  38. sqlGenOVID<-function(conn=dta, nhcs=nhc.test, verb=T, sinc=F){
  39. ovid<-sqlFetch(conn,"OVID")
  40. new.nhc<-nhcs[!nhcs %in% ovid$NHC]
  41. next.num<-gsub("OVID","",ovid$OVID) %>% as.numeric %>% max(na.rm=T)+1
  42. last.num<-next.num+(length(new.nhc)-1)
  43. upd.ovid<-rbind(ovid,data.frame("NHC"=new.nhc, "OVID"=sprintf("OVID%04d",next.num:last.num)))
  44. rownames(upd.ovid)<-as.character(1:nrow(upd.ovid))
  45. upd.ovid<-filter(upd.ovid, NHC %in% new.nhc) %>% mutate(NHC=as.character(NHC))
  46. if (sinc){
  47. ### !! Atención, esto cambia la base de datos:
  48. sqlSave(conn, upd.ovid, tablename="OVID", append = T)
  49. print("La base ha sido actualizada.")
  50. }
  51. if (verb){
  52. return(upd.ovid)
  53. }
  54. }
  55. sqlWriteTemp<-function(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod=T, clinics.mod=T){
  56. upd.ovid<-sqlFetch(conn, "OVID") %>% filter(NHC %in% nhcs)
  57. if (samples.mod){
  58. ## Generar código para las nuevas muestras
  59. samples<-sqlFetch(conn, "SAMPLES")
  60. if(sum(grepl(paste0("OV",Sys.time() %>% format("%y")), samples$samples)) > 0){
  61. next.samp<-gsub(paste0("OV",Sys.time() %>% format("%y")),"", samples$samples) %>% as.numeric %>% max(na.rm=T)+1
  62. }else{
  63. next.samp<-1
  64. }
  65. last.samp<-next.samp+(length(nhcs)-1)
  66. new.samp<-sprintf("OV%s%02d",Sys.time() %>% format("%y"),next.samp:last.samp)
  67. new.samp.df<-merge(sqlFetch(dta,"OVID") %>% merge(data.frame("NHC"=nhcs)), data.frame("NHC"=nhcs, "samples"=new.samp))
  68. samples.exp<-merge(samples %>% slice(0), new.samp.df %>% select(-NHC), all=T) %>% select(colnames(samples)) %>% arrange(samples)
  69. }
  70. if (clinics.mod){
  71. ## Importar los datos clínicos de pacientes existentes y generar nueva entrada par los nuevos
  72. upd.clinics<-sqlFetch(conn, "CLINICS")
  73. ovid.new<-sqlFetch(conn, "OVID") %>% filter(NHC %in% nhcs)
  74. upd.clinics<-merge(ovid.new,upd.clinics, all.x=T, by="OVID")
  75. upd.clinics$NHC<-as.character(upd.clinics$NHC)
  76. for (i in colnames(upd.clinics)[sapply(upd.clinics, lubridate::is.POSIXct)]){upd.clinics[,i]<-as.Date(upd.clinics[,i])}
  77. }
  78. ## Exportar tablas a la plantilla de entrada para su rellenado
  79. wb <- loadWorkbook(file)
  80. writeData(wb, "NHC", upd.ovid)
  81. if (samples.mod){writeData(wb,"samples",samples.exp)}
  82. if (clinics.mod){writeData(wb,"CLINICS",upd.clinics)}
  83. saveWorkbook(wb,file,overwrite = TRUE)
  84. }
  85. sqlSincBD<-function(conn=dta, filetemp="QueryOV.xlsx", sinc.samples=F, sinc.clinics=F){
  86. ## Añadir código de muestra nueva a la base de datos
  87. nsamples<-sqlFetch(conn, "SAMPLES") %>% nrow
  88. upd.samples<-read.xlsx(filetemp, sheet = "samples", detectDates = T)
  89. if (nrow(upd.samples) > 0){rownames(upd.samples)<-(nsamples+1):(nsamples+nrow(upd.samples)) %>% as.character}
  90. if (sinc.samples & nrow(upd.samples) > 0){
  91. upd.samples$IQ_date<-as.Date(upd.samples$IQ_date)
  92. ### !! Atención, esto cambia la base de datos:
  93. sqlSave(conn, upd.samples, tablename="SAMPLES", append = T, varTypes = c("IQ_date"="date"))
  94. print("Tabla SAMPLES sincronizada.")
  95. }
  96. ## Añadir datos clínicos modificados a la base de datos
  97. upd.clinics<-read.xlsx(filetemp, sheet = "CLINICS",detectDates = T)
  98. ovid.mod<-upd.clinics$OVID[upd.clinics$OVID %in% (sqlFetch(dta, "CLINICS") %>% pull(OVID))]
  99. rnames<-sqlFetch(conn, "CLINICS") %>% filter(OVID %in% ovid.mod) %>% rownames
  100. clinics.mod<-upd.clinics %>% filter(OVID %in% ovid.mod) %>% select(-NHC)
  101. rownames(clinics.mod)<-rnames
  102. ### !! Atención, esto cambia la base de datos:
  103. if (sinc.clinics){
  104. fechas<-colnames(clinics.mod)[grepl("DO|date", colnames(clinics.mod))]
  105. for (i in fechas){
  106. clinics.mod[,i]<-as.Date(clinics.mod[,i])
  107. }
  108. sqlUpdate(conn, clinics.mod,"CLINICS")
  109. print("Tabla CLINICS modificada.")
  110. }
  111. ## Añadir datos clínicos nuevos a la base de datos
  112. nsamples.clin<-sqlFetch(conn, "CLINICS") %>% nrow
  113. ovid.new<-upd.clinics$OVID[!upd.clinics$OVID %in% (sqlFetch(conn, "CLINICS") %>% pull(OVID))]
  114. clinics.new<-upd.clinics %>% filter(OVID %in% ovid.new) %>% select(-NHC)
  115. if (length(ovid.new) > 0){rownames(clinics.new)<-(nsamples.clin+1):(nsamples.clin+nrow(clinics.new)) %>% as.character}
  116. ### !! Atención, esto cambia la base de datos:
  117. if (sinc.clinics){
  118. fechas<-colnames(clinics.new)[grepl("DO|date", colnames(clinics.new))]
  119. varTypes<-rep("Date",length(fechas))
  120. names(varTypes)<-fechas
  121. for (i in fechas){
  122. clinics.new[,i]<-as.Date(clinics.new[,i])
  123. }
  124. sqlSave(conn, clinics.new, tablename="CLINICS", append = T, varTypes = varTypes)
  125. print("Tabla CLINICS sincronizada.")
  126. }
  127. }