1 ;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10; Package: umlisp -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
6 ;;;; Purpose: Create SQL database for UMLisp
7 ;;;; Author: Kevin M. Rosenberg
12 ;;;; This file, part of UMLisp, is
13 ;;;; Copyright (c) 2000-2006 by Kevin M. Rosenberg, M.D.
15 ;;;; UMLisp users are granted the rights to distribute and use this software
16 ;;;; as governed by the terms of the GNU General Public License.
17 ;;;; *************************************************************************
21 (defun create-table-cmd (file)
22 "Return sql command to create a table"
25 (let ((sqltype (sqltype c)))
29 ((string-equal sqltype "VARCHAR")
30 (setq sqltype "VARCHAR2"))
31 ((string-equal sqltype "BIGINT")
32 (setq sqltype "VARCHAR2(20)")))))
37 (if (or (string-equal sqltype "VARCHAR")
38 (string-equal sqltype "CHAR"))
39 (format nil "~a (~a)" sqltype (cmax c))
41 (format nil "CREATE TABLE ~a (~{~a~^,~})~A~A"
43 (mapcar col-func (ucols file))
44 (if (and (eq *umls-sql-type* :mysql)
45 (string-equal (table file) "MRCXT"))
48 (if (eq *umls-sql-type* :mysql)
49 " TYPE=MYISAM CHARACTER SET utf8"
52 (defun create-custom-table-cmd (tablename sql-cmd)
53 "Return SQL command to create a custom table"
54 (format nil "CREATE TABLE ~a AS ~a;" tablename sql-cmd))
56 (defun insert-col-value (col value)
57 (if (null (parse-fun col))
59 (format nil "~A" (funcall (parse-fun col) value))))
61 (defun insert-values-cmd (file values)
62 "Return sql insert command for a row of values"
65 (concatenate 'string (quote-str col)
66 (insert-col-value col value)
69 nil "INSERT INTO ~a (~{~a~^,~}) VALUES (~A)"
72 (concat-separated-strings
74 (mapcar insert-func (remove-custom-cols (ucols file)) values)
75 (custom-col-values (custom-ucols-for-file file) values t)))))
78 (defun custom-col-value (col values doquote)
79 (let ((custom-value (funcall (custom-value-fun col) values)))
82 (concatenate 'string (quote-str col)
83 (escape-backslashes custom-value)
85 (escape-backslashes custom-value))
88 (defun custom-col-values (ucols values doquote)
89 "Returns a list of string column values for SQL inserts for custom columns"
90 (loop for col in ucols collect (custom-col-value col values doquote)))
92 (defun remove-custom-cols (cols)
93 "Remove custom cols from a list col umls-cols"
94 (remove-if #'custom-value-fun cols))
96 (defun find-custom-cols-for-filename (filename)
97 (remove-if-not (lambda (x) (string-equal filename (car x))) +custom-cols+))
99 (defun find-custom-col (filename col)
100 (find-if (lambda (x) (and (string-equal filename (car x))
101 (string-equal col (cadr x)))) +custom-cols+))
103 (defun custom-colnames-for-filename (filename)
104 (mapcar #'cadr (find-custom-cols-for-filename filename)))
106 (defun custom-ucols-for-file (file)
107 (remove-if-not #'custom-value-fun (ucols file)))
109 (defun noneng-lang-index-files ()
111 (lambda (f) (and (> (length (fil f)) 4)
112 (string-equal (fil f) "MRXW_" :end1 5)
113 (not (string-equal (fil f) "MRXW_ENG.RRF"))
114 (not (string-equal (fil f) "MRXW_NONENG.RRF"))))
117 ;;; SQL Command Functions
119 (defun create-index-cmd (colname tablename length)
120 "Return sql create index command"
121 (format nil "CREATE INDEX ~a ON ~a (~a)"
122 (concatenate 'string tablename "_" colname "_X")
124 (case *umls-sql-type*
126 (concatenate 'string colname
127 (if (integerp length)
128 (format nil " (~d)" length)
130 ((:postgresql :postgresql-socket)
131 ;; FIXME: incorrect syntax for postgresql?
132 (if (integerp length)
133 (format nil "substr((~A)::text,1,~D)" colname length)
138 (defun create-all-tables-cmdfile ()
139 "Return sql commands to create all tables. Not need for automated SQL import"
140 (mapcar (lambda (f) (format nil "~a~%~%" (create-table-cmd f))) *umls-files*))
142 ;; SQL Execution functions
144 (defun sql-drop-tables (conn)
145 "SQL Databases: drop all tables"
146 (dolist (file *umls-files*)
148 (sql-execute (format nil "DROP TABLE ~a" (table file)) conn))))
150 (defun sql-create-tables (conn)
151 "SQL Databases: create all tables"
152 (dolist (file *umls-files*)
153 (sql-execute (create-table-cmd file) conn)))
156 (defun sql-create-kcon-table (conn)
157 "Create concept table, one row per concept."
158 (ignore-errors (execute-command "DROP TABLE KCON" :database conn))
160 (format nil "CREATE TABLE KCON (CUI INTEGER, STR ~A, LRL ~A)"
161 (case *umls-sql-type*
163 (format nil "VARCHAR2(~D)"
164 (slot-value (find-ucol "STR" "MRCONSO.RRF") 'max)))
166 (case *umls-sql-type*
168 ((:postgresql :postgresql-socket) "INT2")
169 (:oracle "NUMBER(2,0)")
172 ;; KCON deprecated by KPFENG field in MRCONSO
174 (dolist (tuple (query "select distinct cui from MRCONSO order by cui"
176 (let ((cui (car tuple)))
178 (format nil "INSERT into KCON VALUES (~D,'~A',~D)"
180 (add-sql-quotes (pfstr-hash cui) )
184 (defun sql-create-custom-tables (conn)
185 "SQL Databases: create all custom tables"
186 ;;(sql-create-kcon-table conn)
187 (dolist (ct +custom-tables+)
188 (sql-execute (create-custom-table-cmd (car ct) (cadr ct)) conn)))
190 (defun sql-insert-values (conn file)
191 "SQL Databases: inserts all values for a file"
192 (with-umls-file (line (fil file))
193 (sql-execute (insert-values-cmd file line) conn)))
195 (defun sql-insert-all-values (conn)
196 "SQL Databases: inserts all values for all files"
197 (dolist (file *umls-files*)
198 (sql-insert-values conn file)))
200 (defun drop-index-cmd (colname tablename)
201 "Return sql create index command"
202 (case *umls-sql-type*
204 (format nil "DROP INDEX ~a ON ~a"
205 (concatenate 'string tablename "_" colname "_X")
208 (format nil "DROP INDEX ~a"
209 (concatenate 'string tablename "_" colname "_X")))))
211 (defun sql-create-indexes (conn &key (indexes +index-cols+) verbose)
212 "SQL Databases: create all indexes"
213 (dolist (idx indexes)
214 (when verbose (format t "UMLS Import: Creating index for column ~A on table ~A.~%"
215 (first idx) (second idx)))
216 (ignore-errors (sql-execute (drop-index-cmd (car idx) (cadr idx)) conn))
217 (sql-execute (create-index-cmd (car idx) (cadr idx) (caddr idx)) conn)))
219 (defun make-usrl (conn)
220 (if (eql :mysql *umls-sql-type*)
221 (sql-execute "drop table if exists USRL" conn)
222 (ignore-errors (sql-execute "drop table USRL" conn)))
223 (sql-execute "create table USRL (sab varchar(80), srl integer)" conn)
224 (dolist (tuple (mutex-sql-query
225 "select distinct SAB,SRL from MRCONSO order by SAB asc"))
226 (sql-execute (format nil "insert into USRL (sab,srl) values ('~a',~d)"
227 (car tuple) (ensure-integer (cadr tuple)))
230 (defun sql-create-special-tables (conn)
234 (defun create-umls-db-by-insert (&key verbose)
235 "SQL Databases: initializes entire database via SQL insert commands"
236 (ensure-ucols+ufiles)
238 (with-sql-connection (conn)
239 (sql-drop-tables conn)
240 (sql-create-tables conn)
241 (sql-insert-all-values conn)
242 (sql-create-indexes conn)
243 (sql-create-custom-tables conn)
244 (sql-create-indexes conn :indexes +custom-index-cols+ :verbose verbose)
245 (sql-create-special-tables conn)))
247 (defun create-umls-db (&key (extension "-trans") (force-translation nil) (verbose nil))
248 "SQL Databases: initializes entire database via SQL copy commands.
249 This is much faster that using create-umls-db-insert."
250 (when verbose (format t "UMLS Import: Starting.~%"))
251 (ensure-ucols+ufiles)
252 (when verbose (format t "UMLS Import: Preparsing files.~%"))
254 (when verbose (format t "UMLS Import: Converting text UMLS files to optimized format.~%"))
255 (translate-all-files :extension extension :verbose verbose :force force-translation)
257 (ecase (umls-sql-type)
258 (:mysql #'mysql-copy-cmd)
259 (:postgresql #'pg-copy-cmd))))
260 (with-sql-connection (conn)
261 (clsql:truncate-database :database conn)
262 (sql-drop-tables conn)
263 (sql-create-tables conn)
264 (dolist (file *umls-files*)
265 (when verbose (format t "UMLS Import: Importing file ~A to SQL.~%" (fil file)))
266 (sql-execute (funcall copy-cmd file extension) conn))
267 (When verbose (format t "UMLS Import: Creating SQL indices.~%"))
268 (sql-create-indexes conn :verbose verbose)
269 (When verbose (format t "UMLS Import: Creating custom tables.~%"))
270 (sql-create-custom-tables conn)
271 (When verbose (format t "UMLS Import: Creating custom indices.~%"))
272 (sql-create-indexes conn :indexes +custom-index-cols+ :verbose verbose)
273 (When verbose (format t "UMLS Import: Creating special tables.~%"))
274 (sql-create-special-tables conn)))
275 (When verbose (format t "UMLS Import: Completed.~%"))
278 (defun translate-all-files (&key (extension "-trans") verbose force)
279 "Translate all *umls-files* to optimized import format."
280 (when verbose (format t "UMLS Import: Translating file ~A.~%" (fil (find-ufile "MRXW_NONENG.RRF"))))
281 (make-noneng-index-file extension :force force)
282 (dolist (f (remove "MRXW_NONENG.RRF" *umls-files* :test #'string= :key #'fil))
283 (when verbose (format t "UMLS Import: Translating file ~A.~%" (fil f)))
284 (translate-umls-file f extension :force force)))
286 (defun translate-umls-file (file extension &key force)
287 "Translate a umls file into a format suitable for sql copy cmd"
288 (translate-files file extension (list file) :force force))
290 (defun make-noneng-index-file (extension &key force)
291 "Make non-english index file"
292 (translate-files (find-ufile "MRXW_NONENG.RRF")
293 extension (noneng-lang-index-files) :force force))
295 (defun verify-translation-file (output-path input-ufiles)
296 "Returns t if translation file exists and is correct size. Warns and deletes incomplete translation file."
297 (when (probe-file output-path)
298 (let ((translated-lines 0)
300 (eof (cons nil nil)))
301 (catch 'done-counting
302 (with-open-file (ts output-path :direction :input
303 #+(and clisp unicode) :external-format
304 #+(and clisp unicode) charset:utf-8)
306 ((eq (read-line ts nil eof) eof))
307 (incf translated-lines)))
308 (dolist (input-ufile input-ufiles)
309 (with-umls-ufile (line input-ufile)
311 (when (> input-lines translated-lines)
312 (throw 'done-counting 'incomplete)))))
314 ((< input-lines translated-lines)
315 (format t "Translated file ~A incomplete, deleting...~%" output-path)
316 (delete-file output-path)
318 ((eql input-lines translated-lines)
319 (format t "Translated file ~A already exists: skipping...~%" output-path)
322 (warn "The number of input lines is 0 for output file ~A." output-path)
324 ((> translated-lines input-lines)
325 (error "Shouldn't happen. Translated lines of ~A is ~D, greater than input lines ~D"
326 output-path translated-lines input-lines)
327 (delete-file output-path)
330 (defun translate-files (out-ufile extension input-ufiles &key force)
331 "Translate a umls file into a format suitable for sql copy cmd"
332 (let ((output-path (ufile-pathname out-ufile extension)))
333 (when (and (not force) (verify-translation-file output-path input-ufiles))
334 (return-from translate-files output-path))
335 (with-open-file (ostream output-path :direction :output
336 :if-exists :overwrite
337 :if-does-not-exist :create
338 #+(and clisp unicode) :external-format
339 #+(and clisp unicode) charset:utf-8)
340 (dolist (input-ufile input-ufiles)
341 (with-umls-ufile (line input-ufile)
342 (translate-line out-ufile line ostream)
343 (princ #\newline ostream))))))
345 (defun translate-line (file line strm)
346 "Translate a single line for sql output"
347 (flet ((col-value (col value)
348 (if (eq (datatype col) 'sql-u)
349 (let ((ui (parse-ui value "")))
352 (write-to-string ui)))
353 (escape-backslashes value))))
354 (print-separated-strings
356 (mapcar #'col-value (remove-custom-cols (ucols file)) line)
357 (custom-col-values (custom-ucols-for-file file) line nil))))
359 (defun pg-copy-cmd (file extension)
360 "Return postgresql copy statement for a file"
362 nil "COPY ~a FROM '~a' using delimiters '|' with null as ''"
363 (table file) (ufile-pathname file extension)))
365 (defun mysql-copy-cmd (file extension &key (local-file t))
366 "Return mysql copy statement for a file"
369 "LOAD DATA ~AINFILE \"~a\" INTO TABLE ~a FIELDS TERMINATED BY \"|\""
370 (if local-file "LOCAL " "")
371 (namestring (ufile-pathname file extension)) (table file)))
374 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
376 ;;; Routines for analyzing cost of fixed size storage
378 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
380 (defun umls-fixed-size-waste ()
381 "Display storage waste if using all fixed size storage"
387 (dolist (file *umls-files*)
388 (dolist (col (ucols file))
389 (let* ((avwaste (- (cmax col) (av col)))
390 (cwaste (* avwaste (rws file))))
394 (incf totalunavoidable cwaste)
395 (push (list (fil file) (col col)
399 (incf totalavoidable cwaste)
400 (push (list (fil file) (col col)
403 (incf totalwaste cwaste)))))
404 (values totalwaste totalavoidable totalunavoidable
405 (nreverse avoidable) (nreverse unavoidable))))
407 (defun display-waste ()
408 (ensure-ucols+ufiles)
409 (multiple-value-bind (tw ta tu al ul) (umls-fixed-size-waste)
410 (format t "Total waste: ~d~%" tw)
411 (format t "Total avoidable: ~d~%" ta)
412 (format t "Total unavoidable: ~d~%" tu)
413 (format t "Avoidable:~%")
415 (format t " (~a,~a): ~a,~a~%" (car w) (cadr w) (caddr w) (cadddr w)))
416 (format t "Unavoidable:~%")
418 (format t " (~a,~a): ~a,~a~%" (car w) (cadr w) (caddr w) (cadddr w)))
421 (defun max-umls-field ()
422 "Return length of longest field"
423 (declare (optimize (speed 3) (space 0)))
424 (ensure-ucols+ufiles)
426 (declare (type (integer 0 1000000) max))
427 (dolist (ucol *umls-cols*)
428 (when (> (the (integer 0 1000000) (cmax ucol)) max)
429 (setq max (cmax ucol))))
432 (defun max-umls-row ()
433 "Return length of longest row"
434 (declare (optimize (speed 3) (space 0)))
435 (ensure-ucols+ufiles)
436 (let ((rowsizes '()))
437 (dolist (file *umls-files*)
439 (declare (type (integer 0 1000000) row))
440 (dolist (ucol (ucols file))
441 (let* ((col-max (cmax ucol))
442 (max-with-delim (1+ col-max)))
443 (declare (type (integer 0 1000000) col-max max-with-delim))
444 (incf row max-with-delim)))
445 (push row rowsizes)))
446 (car (sort rowsizes #'>))))