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.

384 lines
11 KiB

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