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.

371 lines
11 KiB

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