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.

383 lines
11 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. ## sqlBackUp
  69. ### Description
  70. Creates a Back Up copy of the database.
  71. ### Usage
  72. sqlBackUp(dbfile=file,bu.dir="BU_OVARIO")
  73. ### Arguments
  74. Argument|Description
  75. ---|---
  76. dbfile| Database File location.
  77. bu.dir| Directory under the DB file where the back up will be placed.
  78. ### Details
  79. Creates a Back Up copy of the database. It adds the date in front of the back up file.
  80. ### Value
  81. Invisibly for success (and failures cause errors).
  82. ### Examples
  83. ```r
  84. sqlInitialize()
  85. sqlBackUp()
  86. ```
  87. ### Function
  88. ```r
  89. sqlBackUp<-function(dbfile=file,bu.dir="BU_OVARIO"){
  90. db=strsplit(dbfile, "/")[[1]]%>% tail(n=1)
  91. bu_path<-gsub(db,bu.dir,dbfile)
  92. if (!dir.exists(bu_path)){
  93. dir.create(bu_path)
  94. print(paste0("Back Up directory ", bu_path, " created"))
  95. }
  96. cp_bu<-paste0(bu_path, "/", format(Sys.time(), format="%Y%m%d"),"-",db)
  97. file.copy(dbfile, cp_bu)
  98. }
  99. ```
  100. ---
  101. ## sqlShowSamples
  102. ### Description
  103. Shows if there are already samples from the specified NHCs.
  104. ### Usage
  105. sqlShowSamples(conn=dta, nhcs=nhc.test, verb=F)
  106. ### Arguments
  107. Argument|Description
  108. ---|---
  109. conn|connection handle returned by odbcConnect.
  110. nhcs|Character vector with the NHCs to test.
  111. verb|Verbose: if TRUE, all the columns from "SAMPLES" table are printed.
  112. ### Details
  113. Takes the NHCs listed in the nhcs vector and checks if there are already samples from those patients.
  114. ### Value
  115. A data.frame with information about the patients.
  116. ### Examples
  117. ```r
  118. dta<-odbcConnect("test")
  119. nhc.test<-c("XXXXXXXX","XXXXXXX")
  120. sqlShowSamples()
  121. ```
  122. ### Function
  123. ```r
  124. sqlShowSamples<-function(conn=dta, nhcs=nhc.test, verb=F){
  125. if (isFALSE(verb)){
  126. sqlQuery(conn, "SELECT O.NHC,S.*
  127. FROM SAMPLES S
  128. INNER JOIN OVID O
  129. ON O.OVID=S.OVID") %>% filter(NHC %in% nhcs) %>%
  130. group_by(NHC,OVID) %>% summarise(Samples=length(samples), Names=paste0(samples, collapse = ";")) %>% merge(data.frame(NHC=nhcs),all=T)
  131. }else{
  132. sqlQuery(conn, "SELECT O.NHC,S.*
  133. FROM SAMPLES S
  134. INNER JOIN OVID O
  135. ON O.OVID=S.OVID") %>% filter(NHC %in% nhcs)
  136. }
  137. }
  138. ```
  139. ---
  140. ## sqlGenOVID
  141. ### Description
  142. Generates new consecutive OVID code for the patients that are not found in the DB.
  143. ### Usage
  144. sqlGenOVID(conn=dta, nhcs=nhc.test, verb=T, sinc=F)
  145. ### Arguments
  146. Argument|Description
  147. ---|---
  148. conn|connection handle returned by odbcConnect.
  149. nhcs|Character vector with the NHCs to test.
  150. verb|Verbose: if TRUE (default), it prints the data.frame with the generated OVID codes.
  151. sinc|If TRUE (default is FALSE for security), it adds the new entries to the "OVID" table in the DB.
  152. ### Details
  153. Generates new consecutive OVID code for the patients that are not found in the DB.
  154. ### Value
  155. If verb is TRUE, it returns a data.frame.
  156. ### Examples
  157. ```r
  158. dta<-odbcConnect("test")
  159. nhc.test<-c("XXXXXXXX","XXXXXXX")
  160. sqlGenOVID(sinc=T)
  161. ```
  162. ### Function
  163. ```r
  164. sqlGenOVID<-function(conn=dta, nhcs=nhc.test, verb=T, sinc=F){
  165. ovid<-sqlFetch(conn,"OVID")
  166. new.nhc<-nhcs[!nhcs %in% ovid$NHC]
  167. next.num<-gsub("OVID","",ovid$OVID) %>% as.numeric %>% max(na.rm=T)+1
  168. last.num<-next.num+(length(new.nhc)-1)
  169. upd.ovid<-rbind(ovid,data.frame("NHC"=new.nhc, "OVID"=sprintf("OVID%04d",next.num:last.num)))
  170. rownames(upd.ovid)<-as.character(1:nrow(upd.ovid))
  171. upd.ovid<-filter(upd.ovid, NHC %in% new.nhc) %>% mutate(NHC=as.character(NHC))
  172. if (sinc){
  173. ### !! Atención, esto cambia la base de datos:
  174. sqlSave(conn, upd.ovid, tablename="OVID", append = T)
  175. print("La base ha sido actualizada.")
  176. }
  177. if (verb){
  178. return(upd.ovid)
  179. }
  180. }
  181. ```
  182. ---
  183. ## sqlWriteTemp
  184. ### Description
  185. Fills the Query Template file with the OVID and OV newly generated codes.
  186. ### Usage
  187. sqlWriteTemp(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod=T, clinics.mod=T)
  188. ### Arguments
  189. Argument|Description
  190. ---|---
  191. conn|connection handle returned by odbcConnect.
  192. nhcs|Character vector with the NHCs to test.
  193. file|Template file that will be used to interact with the DB.
  194. samples.mod|If TRUE (default), it fills the "samples" template sheet.
  195. clinics.mod|If TRUE (default), it fills the "CLINICS" template sheet.
  196. ### Details
  197. 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.
  198. ### Value
  199. Invisibly for success (and failures cause errors).
  200. ### Examples
  201. ```r
  202. dta<-odbcConnect("test")
  203. nhc.test<-c("XXXXXXXX","XXXXXXX")
  204. sqlGenOVID(sinc=T)
  205. sqlWriteTemp()
  206. ```
  207. ### Function
  208. ```r
  209. sqlWriteTemp<-function(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod=T, clinics.mod=T){
  210. upd.ovid<-sqlFetch(conn, "OVID") %>% filter(NHC %in% nhcs)
  211. if (samples.mod){
  212. ## Generar código para las nuevas muestras
  213. samples<-sqlFetch(conn, "SAMPLES")
  214. if(sum(grepl(paste0("OV",Sys.time() %>% format("%y")), samples$samples)) > 0){
  215. next.samp<-gsub(paste0("OV",Sys.time() %>% format("%y")),"", samples$samples) %>% as.numeric %>% max(na.rm=T)+1
  216. }else{
  217. next.samp<-1
  218. }
  219. last.samp<-next.samp+(length(nhcs)-1)
  220. new.samp<-sprintf("OV%s%02d",Sys.time() %>% format("%y"),next.samp:last.samp)
  221. new.samp.df<-merge(sqlFetch(dta,"OVID") %>% merge(data.frame("NHC"=nhcs)), data.frame("NHC"=nhcs, "samples"=new.samp))
  222. samples.exp<-merge(samples %>% slice(0), new.samp.df %>% select(-NHC), all=T) %>% select(colnames(samples)) %>% arrange(samples)
  223. }
  224. if (clinics.mod){
  225. ## Importar los datos clínicos de pacientes existentes y generar nueva entrada par los nuevos
  226. upd.clinics<-sqlFetch(conn, "CLINICS")
  227. ovid.new<-sqlFetch(conn, "OVID") %>% filter(NHC %in% nhcs)
  228. upd.clinics<-merge(ovid.new,upd.clinics, all.x=T, by="OVID")
  229. upd.clinics$NHC<-as.character(upd.clinics$NHC)
  230. for (i in colnames(upd.clinics)[sapply(upd.clinics, lubridate::is.POSIXct)]){upd.clinics[,i]<-as.Date(upd.clinics[,i])}
  231. }
  232. ## Exportar tablas a la plantilla de entrada para su rellenado
  233. wb <- loadWorkbook(file)
  234. writeData(wb, "NHC", upd.ovid)
  235. if (samples.mod){writeData(wb,"samples",samples.exp)}
  236. if (clinics.mod){writeData(wb,"CLINICS",upd.clinics)}
  237. saveWorkbook(wb,file,overwrite = TRUE)
  238. }
  239. ```
  240. ---
  241. ## sqlSincBD
  242. ### Description
  243. Updates the DB with the information filled in the template file.
  244. ### Usage
  245. sqlSincBD(conn=dta, filetemp="QueryOV.xlsx", sinc.samples=F, sinc.clinics=F)
  246. ### Arguments
  247. Argument|Description
  248. ---|---
  249. conn|connection handle returned by odbcConnect.
  250. filetemp|Template file that will be used to interact with the DB.
  251. 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.
  252. 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.
  253. ### Details
  254. 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.
  255. ### Value
  256. Invisibly for success (and failures cause errors).
  257. ### Examples
  258. ```r
  259. dta<-odbcConnect("test")
  260. nhc.test<-c("XXXXXXXX","XXXXXXX")
  261. sqlGenOVID(sinc=T)
  262. sqlWriteTemp()
  263. sqlSincBD(sinc.samples=T, sinc.clinics=T)
  264. ```
  265. ### Function
  266. ```r
  267. sqlSincBD<-function(conn=dta, filetemp="QueryOV.xlsx", sinc.samples=F, sinc.clinics=F){
  268. ## Añadir código de muestra nueva a la base de datos
  269. nsamples<-sqlFetch(conn, "SAMPLES") %>% nrow
  270. upd.samples<-read.xlsx(filetemp, sheet = "samples", detectDates = T)
  271. if (nrow(upd.samples) > 0){rownames(upd.samples)<-(nsamples+1):(nsamples+nrow(upd.samples)) %>% as.character}
  272. if (sinc.samples & nrow(upd.samples) > 0){
  273. upd.samples$IQ_date<-as.Date(upd.samples$IQ_date)
  274. ### !! Atención, esto cambia la base de datos:
  275. sqlSave(conn, upd.samples, tablename="SAMPLES", append = T, varTypes = c("IQ_date"="date"))
  276. print("Tabla SAMPLES sincronizada.")
  277. }
  278. ## Añadir datos clínicos modificados a la base de datos
  279. upd.clinics<-read.xlsx(filetemp, sheet = "CLINICS",detectDates = T)
  280. ovid.mod<-upd.clinics$OVID[upd.clinics$OVID %in% (sqlFetch(dta, "CLINICS") %>% pull(OVID))]
  281. rnames<-sqlFetch(conn, "CLINICS") %>% filter(OVID %in% ovid.mod) %>% rownames
  282. clinics.mod<-upd.clinics %>% filter(OVID %in% ovid.mod) %>% select(-NHC)
  283. rownames(clinics.mod)<-rnames
  284. ### !! Atención, esto cambia la base de datos:
  285. if (sinc.clinics){
  286. fechas<-colnames(clinics.mod)[grepl("DO|date", colnames(clinics.mod))]
  287. for (i in fechas){
  288. clinics.mod[,i]<-as.Date(clinics.mod[,i])
  289. }
  290. sqlUpdate(conn, clinics.mod,"CLINICS")
  291. print("Tabla CLINICS modificada.")
  292. }
  293. ## Añadir datos clínicos nuevos a la base de datos
  294. nsamples.clin<-sqlFetch(conn, "CLINICS") %>% nrow
  295. ovid.new<-upd.clinics$OVID[!upd.clinics$OVID %in% (sqlFetch(conn, "CLINICS") %>% pull(OVID))]
  296. clinics.new<-upd.clinics %>% filter(OVID %in% ovid.new) %>% select(-NHC)
  297. if (length(ovid.new) > 0){rownames(clinics.new)<-(nsamples.clin+1):(nsamples.clin+nrow(clinics.new)) %>% as.character}
  298. ### !! Atención, esto cambia la base de datos:
  299. if (sinc.clinics){
  300. fechas<-colnames(clinics.new)[grepl("DO|date", colnames(clinics.new))]
  301. varTypes<-rep("Date",length(fechas))
  302. names(varTypes)<-fechas
  303. for (i in fechas){
  304. clinics.new[,i]<-as.Date(clinics.new[,i])
  305. }
  306. sqlSave(conn, clinics.new, tablename="CLINICS", append = T, varTypes = varTypes)
  307. print("Tabla CLINICS sincronizada.")
  308. }
  309. }
  310. ```