Changes needed for 2009AB version of UMLS
[umlisp.git] / create-sql.lisp
1 ;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10; Package: umlisp -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:     sql-create
6 ;;;; Purpose:  Create SQL database for UMLisp
7 ;;;; Author:   Kevin M. Rosenberg
8 ;;;; Created:  Apr 2000
9 ;;;;
10 ;;;; This file, part of UMLisp, is
11 ;;;;    Copyright (c) 2000-2010 by Kevin M. Rosenberg, M.D.
12 ;;;;
13 ;;;; UMLisp users are granted the rights to distribute and use this software
14 ;;;; as governed by the terms of the GNU General Public License.
15 ;;;; *************************************************************************
16
17 (in-package #:umlisp)
18
19 (defun create-table-cmd (file)
20   "Return sql command to create a table"
21   (let ((col-func
22          (lambda (c)
23            (let ((sqltype (sqltype c)))
24              (case *umls-sql-type*
25                (:oracle
26                 (cond
27                  ((string-equal sqltype "VARCHAR")
28                   (setq sqltype "VARCHAR2"))
29                  ((string-equal sqltype "BIGINT")
30                   (setq sqltype "VARCHAR2(20)")))))
31
32              (concatenate 'string
33                (col c)
34                " "
35                (if (or (string-equal sqltype "VARCHAR")
36                        (string-equal sqltype "CHAR"))
37                    (format nil "~a (~a)" sqltype (cmax c))
38                  sqltype))))))
39     (format nil "CREATE TABLE ~a (~{~a~^,~})~A~A"
40             (table file)
41             (mapcar col-func (ucols file))
42             (if (and (eq *umls-sql-type* :mysql)
43                      (string-equal (table file) "MRCXT"))
44                 " MAX_ROWS=200000000"
45               "")
46             (if (eq *umls-sql-type* :mysql)
47                 " TYPE=MYISAM CHARACTER SET utf8"
48                 ""))))
49
50 (defun create-custom-table-cmd (tablename sql-cmd)
51   "Return SQL command to create a custom table"
52   (format nil "CREATE TABLE ~a AS ~a;" tablename sql-cmd))
53
54 (defun insert-col-value (col value)
55   (if (null (parse-fun col))
56       value
57       (format nil "~A" (funcall (parse-fun col) value))))
58
59 (defun insert-values-cmd (file values)
60   "Return sql insert command for a row of values"
61   (let ((insert-func
62          (lambda (col value)
63            (concatenate 'string (quote-str col)
64                         (insert-col-value col value)
65                         (quote-str col)))))
66     (format
67      nil "INSERT INTO ~a (~{~a~^,~}) VALUES (~A)"
68      (table file)
69      (fields file)
70      (concat-separated-strings
71       ","
72       (mapcar insert-func (remove-custom-cols (ucols file)) values)
73       (custom-col-values (custom-ucols-for-file file) values t)))))
74
75
76 (defun custom-col-value (col values doquote)
77   (let ((custom-value (funcall (custom-value-fun col) values)))
78     (if custom-value
79         (if doquote
80             (concatenate 'string (quote-str col)
81                          (escape-backslashes custom-value)
82                          (quote-str col))
83             (escape-backslashes custom-value))
84         "")))
85
86 (defun custom-col-values (ucols values doquote)
87   "Returns a list of string column values for SQL inserts for custom columns"
88   (loop for col in ucols collect (custom-col-value col values doquote)))
89
90 (defun remove-custom-cols (cols)
91   "Remove custom cols from a list col umls-cols"
92   (remove-if #'custom-value-fun cols))
93
94 (defun find-custom-cols-for-filename (filename)
95   (remove-if-not (lambda (x) (string-equal filename (car x))) +custom-cols+))
96
97 (defun find-custom-col (filename col)
98   (find-if (lambda (x) (and (string-equal filename (car x))
99                             (string-equal col (cadr x)))) +custom-cols+))
100
101 (defun custom-colnames-for-filename (filename)
102   (mapcar #'cadr (find-custom-cols-for-filename filename)))
103
104 (defun custom-ucols-for-file (file)
105   (remove-if-not #'custom-value-fun (ucols file)))
106
107 (defun noneng-lang-index-files ()
108   (remove-if-not
109    (lambda (f) (and (> (length (fil f)) 4)
110                     (string-equal (fil f) "MRXW_" :end1 5)
111                     (not (string-equal (fil f) "MRXW_ENG.RRF"))
112                     (not (string-equal (fil f) "MRXW_NONENG.RRF"))))
113    *umls-files*))
114
115 ;;; SQL Command Functions
116
117 (defun create-index-cmd (colname tablename length)
118   "Return sql create index command"
119   (format nil "CREATE INDEX ~a ON ~a (~a)"
120           (concatenate 'string tablename "_" colname "_X")
121           tablename
122           (case *umls-sql-type*
123             (:mysql
124              (concatenate 'string colname
125                           (if (integerp length)
126                               (format nil " (~d)" length)
127                               "")))
128             ((:postgresql :postgresql-socket)
129              ;; FIXME: incorrect syntax for postgresql?
130              (if (integerp length)
131                  (format nil "substr((~A)::text,1,~D)" colname length)
132                  colname))
133             (t
134              colname))))
135
136 (defun create-all-tables-cmdfile ()
137   "Return sql commands to create all tables. Not need for automated SQL import"
138   (mapcar (lambda (f) (format nil "~a~%~%" (create-table-cmd f))) *umls-files*))
139
140 ;; SQL Execution functions
141
142 (defun sql-drop-tables (conn)
143   "SQL Databases: drop all tables"
144   (dolist (file *umls-files*)
145     (ignore-errors
146       (sql-execute (format nil "DROP TABLE ~a" (table file)) conn))))
147
148 (defun sql-create-tables (conn)
149   "SQL Databases: create all tables"
150   (dolist (file *umls-files*)
151     (sql-execute (create-table-cmd file) conn)))
152
153 #+ignore
154 (defun sql-create-kcon-table (conn)
155   "Create concept table, one row per concept."
156   (ignore-errors (execute-command "DROP TABLE KCON" :database conn))
157   (execute-command
158    (format nil "CREATE TABLE KCON (CUI INTEGER, STR ~A, LRL ~A)"
159            (case *umls-sql-type*
160              (:oracle
161               (format nil "VARCHAR2(~D)"
162                       (slot-value (find-ucol "STR" "MRCONSO.RRF") 'max)))
163              (t "TEXT"))
164            (case *umls-sql-type*
165              (:mysql "TINYINT")
166              ((:postgresql :postgresql-socket) "INT2")
167              (:oracle "NUMBER(2,0)")
168              (t "INTEGER")))
169    :database conn)
170   ;; KCON deprecated by KPFENG field in MRCONSO
171   #+nil
172   (dolist (tuple (query "select distinct cui from MRCONSO order by cui"
173                         :database conn))
174     (let ((cui (car tuple)))
175       (execute-command
176        (format nil "INSERT into KCON VALUES (~D,'~A',~D)"
177                cui
178                (add-sql-quotes (pfstr-hash cui) )
179                (cui-lrl cui))
180        :database conn))))
181
182 (defun sql-create-custom-tables (conn)
183   "SQL Databases: create all custom tables"
184   ;;(sql-create-kcon-table conn)
185   (dolist (ct +custom-tables+)
186     (sql-execute (create-custom-table-cmd (car ct) (cadr ct)) conn)))
187
188 (defun sql-insert-values (conn file)
189   "SQL Databases: inserts all values for a file"
190   (with-umls-file (line (fil file))
191     (sql-execute (insert-values-cmd file line) conn)))
192
193 (defun sql-insert-all-values (conn)
194   "SQL Databases: inserts all values for all files"
195   (dolist (file *umls-files*)
196     (sql-insert-values conn file)))
197
198 (defun drop-index-cmd (colname tablename)
199   "Return sql create index command"
200   (case *umls-sql-type*
201     (:mysql
202      (format nil "DROP INDEX ~a ON ~a"
203              (concatenate 'string tablename "_" colname "_X")
204              tablename))
205     (t
206      (format nil "DROP INDEX ~a"
207              (concatenate 'string tablename "_" colname "_X")))))
208
209 (defun sql-create-indexes (conn &key (indexes +index-cols+) verbose)
210   "SQL Databases: create all indexes"
211   (dolist (idx indexes)
212     (when verbose (format t "UMLS Import: Creating index for column ~A on table ~A.~%"
213                           (first idx) (second idx)))
214     (ignore-errors (sql-execute (drop-index-cmd (car idx) (cadr idx)) conn))
215     (sql-execute (create-index-cmd (car idx) (cadr idx) (caddr idx)) conn)))
216
217 (defun make-usrl (conn)
218   (if (eql :mysql *umls-sql-type*)
219       (sql-execute "drop table if exists USRL" conn)
220       (ignore-errors (sql-execute "drop table USRL" conn)))
221   (sql-execute "create table USRL (sab varchar(80), srl integer)" conn)
222   (dolist (tuple (mutex-sql-query
223                   "select distinct SAB,SRL from MRCONSO order by SAB asc"))
224     (sql-execute (format nil "insert into USRL (sab,srl) values ('~a',~d)"
225                          (car tuple) (ensure-integer (cadr tuple)))
226                  conn)))
227
228 (defun sql-create-special-tables (conn)
229   (make-usrl conn)
230   (make-ustats))
231
232 (defun create-umls-db-by-insert (&key verbose)
233   "SQL Databases: initializes entire database via SQL insert commands"
234   (ensure-ucols+ufiles)
235   (ensure-preparse)
236   (with-sql-connection (conn)
237     (sql-drop-tables conn)
238     (sql-create-tables conn)
239     (sql-insert-all-values conn)
240     (sql-create-indexes conn)
241     (sql-create-custom-tables conn)
242     (sql-create-indexes conn :indexes +custom-index-cols+ :verbose verbose)
243     (sql-create-special-tables conn)))
244
245 (defun create-umls-db (&key (extension "-trans") (force-translation nil) (verbose nil))
246   "SQL Databases: initializes entire database via SQL copy commands.
247 This is much faster that using create-umls-db-insert."
248   (when verbose (format t "UMLS Import: Starting.~%"))
249   (ensure-ucols+ufiles)
250   (when verbose (format t "UMLS Import: Preparsing files.~%"))
251   (ensure-preparse)
252   (when verbose (format t "UMLS Import: Converting text UMLS files to optimized format.~%"))
253   (translate-all-files :extension extension :verbose verbose :force force-translation)
254   (let ((copy-cmd
255          (ecase (umls-sql-type)
256            (:mysql #'mysql-copy-cmd)
257            (:postgresql #'pg-copy-cmd))))
258     (with-sql-connection (conn)
259       (clsql:truncate-database :database conn)
260       (sql-drop-tables conn)
261       (sql-create-tables conn)
262       (dolist (file *umls-files*)
263         (when verbose (format t "UMLS Import: Importing file ~A to SQL.~%" (fil file)))
264         (sql-execute (funcall copy-cmd file extension) conn))
265       (when verbose (format t "UMLS Import: Creating SQL indices.~%"))
266       (sql-create-indexes conn :verbose verbose)
267       (when verbose (format t "UMLS Import: Creating custom tables.~%"))
268       (sql-create-custom-tables conn)
269       (when verbose (format t "UMLS Import: Creating custom indices.~%"))
270       (sql-create-indexes conn :indexes +custom-index-cols+ :verbose verbose)
271       (when verbose (format t "UMLS Import: Creating special tables.~%"))
272       (sql-create-special-tables conn)))
273   (when verbose (format t "UMLS Import: Completed.~%"))
274   t)
275
276 (defun translate-all-files (&key (extension "-trans") verbose force)
277   "Translate all *umls-files* to optimized import format."
278   (when verbose (format t "UMLS Import: Translating file ~A.~%" (fil (find-ufile "MRXW_NONENG.RRF"))))
279   (make-noneng-index-file extension :force force)
280   (dolist (f (remove "MRXW_NONENG.RRF" *umls-files* :test #'string= :key #'fil))
281     (when verbose (format t "UMLS Import: Translating file ~A.~%" (fil f)))
282     (translate-umls-file f extension :force force)))
283
284 (defun translate-umls-file (file extension &key force)
285   "Translate a umls file into a format suitable for sql copy cmd"
286   (translate-files file extension (list file) :force force))
287
288 (defun make-noneng-index-file (extension &key force)
289   "Make non-english index file"
290   (translate-files (find-ufile "MRXW_NONENG.RRF")
291                    extension (noneng-lang-index-files) :force force))
292
293 (defun verify-translation-file (output-path input-ufiles)
294   "Returns t if translation file exists and is correct size. Warns and deletes incomplete translation file."
295   (when (probe-file output-path)
296     (let ((translated-lines 0)
297           (input-lines 0)
298           (eof (cons nil nil)))
299       (catch 'done-counting
300         (with-open-file (ts output-path :direction :input
301                             #+(and sbcl sb-unicode) :external-format
302                             #+(and sbcl sb-unicode) :UTF-8
303                             #+(and allegro ics) :external-format
304                             #+(and allegro ics) :UTF-8
305                             #+lispworks :external-format
306                             #+lispworks :UTF-8
307                             #+(and clisp unicode) :external-format
308                             #+(and clisp unicode) charset:utf-8)
309           (do ()
310               ((eq (read-line ts nil eof) eof))
311             (incf translated-lines)))
312         (dolist (input-ufile input-ufiles)
313           (with-umls-ufile (line input-ufile)
314                            (incf input-lines)
315                            (when (> input-lines translated-lines)
316                              (throw 'done-counting 'incomplete)))))
317       (cond
318         ((< input-lines translated-lines)
319           (format t "Translated file ~A incomplete, deleting...~%" output-path)
320           (delete-file output-path)
321           nil)
322         ((eql input-lines translated-lines)
323           (format t "Translated file ~A already exists: skipping...~%" output-path)
324           t)
325         ((eql input-lines 0)
326           (warn "The number of input lines is 0 for output file ~A." output-path)
327           nil)
328         ((> translated-lines input-lines)
329           (error "Shouldn't happen. Translated lines of ~A is ~D, greater than input lines ~D"
330                  output-path translated-lines input-lines)
331           (delete-file output-path)
332           nil)))))
333
334 (defun translate-files (out-ufile extension input-ufiles &key force)
335   "Translate a umls file into a format suitable for sql copy cmd"
336   (let ((output-path (ufile-pathname out-ufile extension)))
337     (when (and (not force) (verify-translation-file output-path input-ufiles))
338       (return-from translate-files output-path))
339     (with-open-file (ostream output-path :direction :output
340                              :if-exists :overwrite
341                              :if-does-not-exist :create
342                              #+(and sbcl sb-unicode) :external-format
343                              #+(and sbcl sb-unicode) :UTF-8
344                              #+(and allegro ics) :external-format
345                              #+(and allegro ics) :UTF-8
346                              #+lispworks :external-format
347                              #+lispworks :UTF-8
348                              #+(and clisp unicode) :external-format
349                              #+(and clisp unicode) charset:utf-8)
350       (dolist (input-ufile input-ufiles)
351         (with-umls-ufile (line input-ufile)
352           (translate-line out-ufile line ostream)
353           (princ #\newline ostream))))))
354
355 (defun translate-line (file line strm)
356   "Translate a single line for sql output"
357   (flet ((col-value (col value)
358            (if (eq (datatype col) 'sql-u)
359                (let ((ui (parse-ui value "")))
360                  (if (stringp ui)
361                      ui
362                      (write-to-string ui)))
363                (escape-backslashes value))))
364     (print-separated-strings
365      strm "|"
366      (mapcar #'col-value (remove-custom-cols (ucols file)) line)
367      (custom-col-values (custom-ucols-for-file file) line nil))))
368
369 (defun pg-copy-cmd (file extension)
370   "Return postgresql copy statement for a file"
371   (format
372    nil "COPY ~a FROM '~a' using delimiters '|' with null as ''"
373    (table file) (ufile-pathname file extension)))
374
375 (defun mysql-copy-cmd (file extension &key (local-file t))
376   "Return mysql copy statement for a file"
377   (format
378    nil
379    "LOAD DATA ~AINFILE '~a' INTO TABLE ~a FIELDS TERMINATED BY '|'"
380    (if local-file "LOCAL " "")
381    (namestring (ufile-pathname file extension)) (table file)))
382
383
384 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
385 ;;;
386 ;;; Routines for analyzing cost of fixed size storage
387 ;;;
388 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
389
390 (defun umls-fixed-size-waste ()
391   "Display storage waste if using all fixed size storage"
392   (let ((totalwaste 0)
393         (totalunavoidable 0)
394         (totalavoidable 0)
395         (unavoidable '())
396         (avoidable '()))
397     (dolist (file *umls-files*)
398       (dolist (col (ucols file))
399         (let* ((avwaste (- (cmax col) (av col)))
400                (cwaste (* avwaste (rws file))))
401           (when (plusp cwaste)
402             (if (<= avwaste 6)
403                 (progn
404                   (incf totalunavoidable cwaste)
405                   (push (list (fil file) (col col)
406                               avwaste cwaste)
407                         unavoidable))
408                 (progn
409                   (incf totalavoidable cwaste)
410                   (push (list (fil file) (col col)
411                               avwaste cwaste)
412                         avoidable)))
413             (incf totalwaste cwaste)))))
414     (values totalwaste totalavoidable totalunavoidable
415             (nreverse avoidable) (nreverse unavoidable))))
416
417 (defun display-waste ()
418   (ensure-ucols+ufiles)
419   (multiple-value-bind (tw ta tu al ul) (umls-fixed-size-waste)
420     (format t "Total waste: ~d~%" tw)
421     (format t "Total avoidable: ~d~%" ta)
422     (format t "Total unavoidable: ~d~%" tu)
423     (format t "Avoidable:~%")
424     (dolist (w al)
425       (format t "  (~a,~a): ~a,~a~%" (car w) (cadr w) (caddr w) (cadddr w)))
426     (format t "Unavoidable:~%")
427     (dolist (w ul)
428       (format t "  (~a,~a): ~a,~a~%" (car w) (cadr w) (caddr w) (cadddr w)))
429     ))
430
431 (defun max-umls-field ()
432   "Return length of longest field"
433   (declare (optimize (speed 3) (space 0)))
434   (ensure-ucols+ufiles)
435   (let ((max 0))
436     (declare (type (integer 0 1000000) max))
437     (dolist (ucol *umls-cols*)
438       (when (> (the (integer 0 1000000) (cmax ucol)) max)
439         (setq max (cmax ucol))))
440     max))
441
442 (defun max-umls-row ()
443   "Return length of longest row"
444   (declare (optimize (speed 3) (space 0)))
445   (ensure-ucols+ufiles)
446   (let ((rowsizes '()))
447     (dolist (file *umls-files*)
448       (let ((row 0))
449         (declare (type (integer 0 1000000) row))
450         (dolist (ucol (ucols file))
451           (let* ((col-max (cmax ucol))
452                  (max-with-delim (1+ col-max)))
453             (declare (type (integer 0 1000000) col-max max-with-delim))
454             (incf row max-with-delim)))
455         (push row rowsizes)))
456     (car (sort rowsizes #'>))))