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.

341 lines
10 KiB

  1. ---
  2. title: "sqlFunctions-Doc"
  3. output:
  4. html_document:
  5. toc: true
  6. toc_depth: 2
  7. ---
  8. ```{r setup, include=FALSE}
  9. knitr::opts_chunk$set(echo = TRUE)
  10. ```
  11. ---
  12. ## sqlDropLast
  13. ### Description
  14. Removes from Database the last (or the amount specified) entry.
  15. ### Usage
  16. sqlDropLast(conn, tablename, droplast=1)
  17. ### Arguments
  18. Argument|Description
  19. ---|---
  20. conn|connection handle returned by odbcConnect.
  21. tablename|character: a database table name accessible from the connected DSN.
  22. droplast|the amount of lines to be removed from the table strating from tail. By default, it removes only 1 line.
  23. ### Details
  24. Removes from Database the last (or the amount specified) entry.
  25. ### Value
  26. Invisibly for success (and failures cause errors).
  27. ### Examples
  28. ```r
  29. dta<-odbcConnect("test")
  30. sqlDropLast(dta, "TableTest")
  31. ```
  32. ### Function
  33. ```r
  34. sqlDropLast<-function(conn, tablename, droplast=1){
  35. table<-sqlFetch(conn, tablename)
  36. table<-table[1:(nrow(table)-droplast),]
  37. sqlSave(conn, table, tablename = tablename, safer = F)
  38. }
  39. ```
  40. ---
  41. ## sqlInitizalize
  42. ### Description
  43. Loads required libraries and gets the db location.
  44. ### Usage
  45. sqlInitialize()
  46. ### Arguments
  47. Argument|Description
  48. ---|---
  49. ### Details
  50. Loads required libraries and gets the db location from "ruta_database.R" file.
  51. ### Value
  52. Invisibly for success (and failures cause errors).
  53. ### Examples
  54. ```r
  55. sqlInitialize()
  56. ```
  57. ### Function
  58. ```r
  59. sqlInitialize<-function(){
  60. library(tidyverse)
  61. library(RODBC)
  62. library(openxlsx)
  63. ## Conexión a la base de datos
  64. source("ruta_database.R", encoding = "UTF-8")
  65. }
  66. ```
  67. ---
  68. ## sqlShowSamples
  69. ### Description
  70. Shows if there are already samples from the specified NHCs.
  71. ### Usage
  72. sqlShowSamples(conn=dta, nhcs=nhc.test, verb=F)
  73. ### Arguments
  74. Argument|Description
  75. ---|---
  76. conn|connection handle returned by odbcConnect.
  77. nhcs|Character vector with the NHCs to test.
  78. verb|Verbose: if TRUE, all the columns from "SAMPLES" table are printed.
  79. ### Details
  80. Takes the NHCs listed in the nhcs vector and checks if there are already samples from those patients.
  81. ### Value
  82. A data.frame with information about the patients.
  83. ### Examples
  84. ```r
  85. dta<-odbcConnect("test")
  86. nhc.test<-c("XXXXXXXX","XXXXXXX")
  87. sqlShowSamples()
  88. ```
  89. ### Function
  90. ```r
  91. sqlShowSamples<-function(conn=dta, nhcs=nhc.test, verb=F){
  92. if (isFALSE(verb)){
  93. sqlQuery(conn, "SELECT O.NHC,S.*
  94. FROM SAMPLES S
  95. INNER JOIN OVID O
  96. ON O.OVID=S.OVID") %>% filter(NHC %in% nhcs) %>%
  97. group_by(NHC,OVID) %>% summarise(Samples=length(samples), Names=paste0(samples, collapse = ";")) %>% merge(data.frame(NHC=nhcs),all=T)
  98. }else{
  99. sqlQuery(conn, "SELECT O.NHC,S.*
  100. FROM SAMPLES S
  101. INNER JOIN OVID O
  102. ON O.OVID=S.OVID") %>% filter(NHC %in% nhcs)
  103. }
  104. }
  105. ```
  106. ---
  107. ## sqlGenOVID
  108. ### Description
  109. Generates new consecutive OVID code for the patients that are not found in the DB.
  110. ### Usage
  111. sqlGenOVID(conn=dta, nhcs=nhc.test, verb=T, sinc=F)
  112. ### Arguments
  113. Argument|Description
  114. ---|---
  115. conn|connection handle returned by odbcConnect.
  116. nhcs|Character vector with the NHCs to test.
  117. verb|Verbose: if TRUE (default), it prints the data.frame with the generated OVID codes.
  118. sinc|If TRUE (default is FALSE for security), it adds the new entries to the "OVID" table in the DB.
  119. ### Details
  120. Generates new consecutive OVID code for the patients that are not found in the DB.
  121. ### Value
  122. If verb is TRUE, it returns a data.frame.
  123. ### Examples
  124. ```r
  125. dta<-odbcConnect("test")
  126. nhc.test<-c("XXXXXXXX","XXXXXXX")
  127. sqlGenOVID(sinc=T)
  128. ```
  129. ### Function
  130. ```r
  131. sqlGenOVID<-function(conn=dta, nhcs=nhc.test, verb=T, sinc=F){
  132. ovid<-sqlFetch(conn,"OVID")
  133. new.nhc<-nhcs[!nhcs %in% ovid$NHC]
  134. next.num<-gsub("OVID","",ovid$OVID) %>% as.numeric %>% max(na.rm=T)+1
  135. last.num<-next.num+(length(new.nhc)-1)
  136. upd.ovid<-rbind(ovid,data.frame("NHC"=new.nhc, "OVID"=sprintf("OVID%04d",next.num:last.num)))
  137. rownames(upd.ovid)<-as.character(1:nrow(upd.ovid))
  138. upd.ovid<-filter(upd.ovid, NHC %in% new.nhc) %>% mutate(NHC=as.character(NHC))
  139. if (sinc){
  140. ### !! Atención, esto cambia la base de datos:
  141. sqlSave(conn, upd.ovid, tablename="OVID", append = T)
  142. print("La base ha sido actualizada.")
  143. }
  144. if (verb){
  145. return(upd.ovid)
  146. }
  147. }
  148. ```
  149. ---
  150. ## sqlWriteTemp
  151. ### Description
  152. Fills the Query Template file with the OVID and OV newly generated codes.
  153. ### Usage
  154. sqlWriteTemp(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod=T, clinics.mod=T)
  155. ### Arguments
  156. Argument|Description
  157. ---|---
  158. conn|connection handle returned by odbcConnect.
  159. nhcs|Character vector with the NHCs to test.
  160. file|Template file that will be used to interact with the DB.
  161. samples.mod|If TRUE (default), it fills the "samples" template sheet.
  162. clinics.mod|If TRUE (default), it fills the "CLINICS" template sheet.
  163. ### Details
  164. Fills the Query Template file with the OVID and OV newly generated codes. It is required that the DB has been updated with the sqlGenOVID function. It replaces previous content in the template file sheets that are filled. In the case of "CLINICS" table, if there were already an entry in the DB for that OVID code, the template file is filled with that information.
  165. ### Value
  166. Invisibly for success (and failures cause errors).
  167. ### Examples
  168. ```r
  169. dta<-odbcConnect("test")
  170. nhc.test<-c("XXXXXXXX","XXXXXXX")
  171. sqlGenOVID(sinc=T)
  172. sqlWriteTemp()
  173. ```
  174. ### Function
  175. ```r
  176. sqlWriteTemp<-function(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod=T, clinics.mod=T){
  177. upd.ovid<-sqlFetch(conn, "OVID") %>% filter(NHC %in% nhcs)
  178. if (samples.mod){
  179. ## Generar código para las nuevas muestras
  180. samples<-sqlFetch(conn, "SAMPLES")
  181. if(sum(grepl(paste0("OV",Sys.time() %>% format("%y")), samples$samples)) > 0){
  182. next.samp<-gsub(paste0("OV",Sys.time() %>% format("%y")),"", samples$samples) %>% as.numeric %>% max(na.rm=T)+1
  183. }else{
  184. next.samp<-1
  185. }
  186. last.samp<-next.samp+(length(nhcs)-1)
  187. new.samp<-sprintf("OV%s%02d",Sys.time() %>% format("%y"),next.samp:last.samp)
  188. new.samp.df<-merge(sqlFetch(dta,"OVID") %>% merge(data.frame("NHC"=nhcs)), data.frame("NHC"=nhcs, "samples"=new.samp))
  189. samples.exp<-merge(samples %>% slice(0), new.samp.df %>% select(-NHC), all=T) %>% select(colnames(samples)) %>% arrange(samples)
  190. }
  191. if (clinics.mod){
  192. ## Importar los datos clínicos de pacientes existentes y generar nueva entrada par los nuevos
  193. upd.clinics<-sqlFetch(conn, "CLINICS")
  194. ovid.new<-sqlFetch(conn, "OVID") %>% filter(NHC %in% nhcs)
  195. upd.clinics<-merge(ovid.new,upd.clinics, all.x=T, by="OVID")
  196. upd.clinics$NHC<-as.character(upd.clinics$NHC)
  197. for (i in colnames(upd.clinics)[sapply(upd.clinics, lubridate::is.POSIXct)]){upd.clinics[,i]<-as.Date(upd.clinics[,i])}
  198. }
  199. ## Exportar tablas a la plantilla de entrada para su rellenado
  200. wb <- loadWorkbook(file)
  201. writeData(wb, "NHC", upd.ovid)
  202. if (samples.mod){writeData(wb,"samples",samples.exp)}
  203. if (clinics.mod){writeData(wb,"CLINICS",upd.clinics)}
  204. saveWorkbook(wb,file,overwrite = TRUE)
  205. }
  206. ```
  207. ---
  208. ## sqlSincBD
  209. ### Description
  210. Updates the DB with the information filled in the template file.
  211. ### Usage
  212. sqlSincBD(conn=dta, filetemp="QueryOV.xlsx", sinc.samples=F, sinc.clinics=F)
  213. ### Arguments
  214. Argument|Description
  215. ---|---
  216. conn|connection handle returned by odbcConnect.
  217. filetemp|Template file that will be used to interact with the DB.
  218. sinc.samples|If TRUE (default is FALSE for security), it updates the SAMPLES table in the DB with the information in the "samples" template sheet.
  219. clinics.mod|If TRUE (default is FALSE for security), it updates the CLINICS table in the DB with the information in the "CLINICS" template sheet.
  220. ### Details
  221. Updates the DB with the information filled in the template file. All the "samples" entries are added as new rows (as all samples are new even if the patient was already in the DB). The new patients included in the "CLINICS" sheet are introduced in the DB as new rows and the ones that were already there are modified in its previous row location.
  222. ### Value
  223. Invisibly for success (and failures cause errors).
  224. ### Examples
  225. ```r
  226. dta<-odbcConnect("test")
  227. nhc.test<-c("XXXXXXXX","XXXXXXX")
  228. sqlGenOVID(sinc=T)
  229. sqlWriteTemp()
  230. sqlSincBD(sinc.samples=T, sinc.clinics=T)
  231. ```
  232. ### Function
  233. ```r
  234. sqlSincBD<-function(conn=dta, filetemp="QueryOV.xlsx", sinc.samples=F, sinc.clinics=F){
  235. ## Añadir código de muestra nueva a la base de datos
  236. nsamples<-sqlFetch(conn, "SAMPLES") %>% nrow
  237. upd.samples<-read.xlsx(filetemp, sheet = "samples", detectDates = T)
  238. if (nrow(upd.samples) > 0){rownames(upd.samples)<-(nsamples+1):(nsamples+nrow(upd.samples)) %>% as.character}
  239. if (sinc.samples & nrow(upd.samples) > 0){
  240. upd.samples$IQ_date<-as.Date(upd.samples$IQ_date)
  241. ### !! Atención, esto cambia la base de datos:
  242. sqlSave(conn, upd.samples, tablename="SAMPLES", append = T, varTypes = c("IQ_date"="date"))
  243. print("Tabla SAMPLES sincronizada.")
  244. }
  245. ## Añadir datos clínicos modificados a la base de datos
  246. upd.clinics<-read.xlsx(filetemp, sheet = "CLINICS",detectDates = T)
  247. ovid.mod<-upd.clinics$OVID[upd.clinics$OVID %in% (sqlFetch(dta, "CLINICS") %>% pull(OVID))]
  248. rnames<-sqlFetch(conn, "CLINICS") %>% filter(OVID %in% ovid.mod) %>% rownames
  249. clinics.mod<-upd.clinics %>% filter(OVID %in% ovid.mod) %>% select(-NHC)
  250. rownames(clinics.mod)<-rnames
  251. ### !! Atención, esto cambia la base de datos:
  252. if (sinc.clinics){
  253. fechas<-colnames(clinics.mod)[grepl("DO|date", colnames(clinics.mod))]
  254. for (i in fechas){
  255. clinics.mod[,i]<-as.Date(clinics.mod[,i])
  256. }
  257. sqlUpdate(conn, clinics.mod,"CLINICS")
  258. print("Tabla CLINICS modificada.")
  259. }
  260. ## Añadir datos clínicos nuevos a la base de datos
  261. nsamples.clin<-sqlFetch(conn, "CLINICS") %>% nrow
  262. ovid.new<-upd.clinics$OVID[!upd.clinics$OVID %in% (sqlFetch(conn, "CLINICS") %>% pull(OVID))]
  263. clinics.new<-upd.clinics %>% filter(OVID %in% ovid.new) %>% select(-NHC)
  264. if (length(ovid.new) > 0){rownames(clinics.new)<-(nsamples.clin+1):(nsamples.clin+nrow(clinics.new)) %>% as.character}
  265. ### !! Atención, esto cambia la base de datos:
  266. if (sinc.clinics){
  267. fechas<-colnames(clinics.new)[grepl("DO|date", colnames(clinics.new))]
  268. varTypes<-rep("Date",length(fechas))
  269. names(varTypes)<-fechas
  270. for (i in fechas){
  271. clinics.new[,i]<-as.Date(clinics.new[,i])
  272. }
  273. sqlSave(conn, clinics.new, tablename="CLINICS", append = T, varTypes = varTypes)
  274. print("Tabla CLINICS sincronizada.")
  275. }
  276. }
  277. ```