r11101: clisp ext form
[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 ;;;; $Id$
11 ;;;;
12 ;;;; This file, part of UMLisp, is
13 ;;;;    Copyright (c) 2000-2006 by Kevin M. Rosenberg, M.D.
14 ;;;;
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 ;;;; *************************************************************************
18
19 (in-package #:umlisp)
20
21 (defun create-table-cmd (file)
22   "Return sql command to create a table"
23   (let ((col-func
24          (lambda (c)
25            (let ((sqltype (sqltype c)))
26              (case *umls-sql-type*
27                (:oracle
28                 (cond
29                  ((string-equal sqltype "VARCHAR")
30                   (setq sqltype "VARCHAR2"))
31                  ((string-equal sqltype "BIGINT")
32                   (setq sqltype "VARCHAR2(20)")))))
33
34              (concatenate 'string
35                (col c)
36                " "
37                (if (or (string-equal sqltype "VARCHAR")
38                        (string-equal sqltype "CHAR"))
39                    (format nil "~a (~a)" sqltype (cmax c))
40                  sqltype))))))
41     (format nil "CREATE TABLE ~a (~{~a~^,~})~A~A"
42             (table file)
43             (mapcar col-func (ucols file))
44             (if (and (eq *umls-sql-type* :mysql)
45                      (string-equal (table file) "MRCXT"))
46                 " MAX_ROWS=200000000"
47               "")
48             (if (eq *umls-sql-type* :mysql)
49                 " TYPE=MYISAM DEFAULT CHARACTER latin1"
50                 ""))))
51
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))
55
56 (defun insert-col-value (col value)
57   (if (null (parse-fun col))
58       value
59       (format nil "~A" (funcall (parse-fun col) value))))
60
61 (defun insert-values-cmd (file values)
62   "Return sql insert command for a row of values"
63   (let ((insert-func
64          (lambda (col value)
65            (concatenate 'string (quote-str col)
66                         (insert-col-value col value)
67                         (quote-str col)))))
68     (format
69      nil "INSERT INTO ~a (~{~a~^,~}) VALUES (~A)"
70      (table file)
71      (fields file)
72      (concat-separated-strings
73       ","
74       (mapcar insert-func (remove-custom-cols (ucols file)) values)
75       (custom-col-values (custom-ucols-for-file file) values t)))))
76
77
78 (defun custom-col-value (col values doquote)
79   (let ((custom-value (funcall (custom-value-fun col) values)))
80     (if custom-value
81         (if doquote
82             (concatenate 'string (quote-str col)
83                          (escape-backslashes custom-value)
84                          (quote-str col))
85             (escape-backslashes custom-value))
86         "")))
87
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)))
91
92 (defun remove-custom-cols (cols)
93   "Remove custom cols from a list col umls-cols"
94   (remove-if #'custom-value-fun cols))
95
96 (defun find-custom-cols-for-filename (filename)
97   (remove-if-not (lambda (x) (string-equal filename (car x))) +custom-cols+))
98
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+))
102
103 (defun custom-colnames-for-filename (filename)
104   (mapcar #'cadr (find-custom-cols-for-filename filename)))
105
106 (defun custom-ucols-for-file (file)
107   (remove-if-not #'custom-value-fun (ucols file)))
108
109 (defun noneng-lang-index-files ()
110   (remove-if-not
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"))))
115    *umls-files*))
116
117 ;;; SQL Command Functions
118
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")
123           tablename
124           (case *umls-sql-type*
125             (:mysql
126              (concatenate 'string colname
127                           (if (integerp length)
128                               (format nil " (~d)" length)
129                               "")))
130             ((:postgresql :postgresql-socket)
131              ;; FIXME: incorrect syntax
132              (if (integerp length)
133                  (format nil "substr((~A)::text,1,~D)" colname length)
134                  colname))
135             (t
136              colname))))
137
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*))
141
142 ;; SQL Execution functions
143
144 (defun sql-drop-tables (conn)
145   "SQL Databases: drop all tables"
146   (dolist (file *umls-files*)
147     (ignore-errors
148       (sql-execute (format nil "DROP TABLE ~a" (table file)) conn))))
149
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)))
154
155 #+ignore
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))
159   (execute-command
160    (format nil "CREATE TABLE KCON (CUI INTEGER, STR ~A, LRL ~A)"
161            (case *umls-sql-type*
162              (:oracle
163               (format nil "VARCHAR2(~D)"
164                       (slot-value (find-ucol "STR" "MRCONSO.RRF") 'max)))
165              (t "TEXT"))
166            (case *umls-sql-type*
167              (:mysql "TINYINT")
168              ((:postgresql :postgresql-socket) "INT2")
169              (:oracle "NUMBER(2,0)")
170              (t "INTEGER")))
171    :database conn)
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 &optional (indexes +index-cols+))
210   "SQL Databases: create all indexes"
211   (dolist (idx indexes)
212     (ignore-errors (sql-execute (drop-index-cmd (car idx) (cadr idx)) conn))
213     (sql-execute (create-index-cmd (car idx) (cadr idx) (caddr idx)) conn)))
214
215 (defun make-usrl (conn)
216   (if (eql :mysql *umls-sql-type*)
217       (sql-execute "drop table if exists USRL" conn)
218       (ignore-errors (sql-execute "drop table USRL" conn)))
219   (sql-execute "create table USRL (sab varchar(80), srl integer)" conn)
220   (dolist (tuple (mutex-sql-query
221                   "select distinct SAB,SRL from MRCONSO order by SAB asc"))
222     (sql-execute (format nil "insert into USRL (sab,srl) values ('~a',~d)"
223                          (car tuple) (ensure-integer (cadr tuple)))
224                  conn)))
225
226 (defun sql-create-special-tables (conn)
227   (make-usrl conn)
228   (make-ustats))
229
230 (defun create-umls-db-by-insert ()
231   "SQL Databases: initializes entire database via SQL insert commands"
232   (ensure-ucols+ufiles)
233   (ensure-preparse)
234   (with-sql-connection (conn)
235     (sql-drop-tables conn)
236     (sql-create-tables conn)
237     (sql-insert-all-values conn)
238     (sql-create-indexes conn)
239     (sql-create-custom-tables conn)
240     (sql-create-indexes conn +custom-index-cols+)
241     (sql-create-special-tables conn)))
242
243 (defun create-umls-db (&key (extension ".trans") (skip-translation nil))
244   "SQL Databases: initializes entire database via SQL copy commands.
245 This is much faster that using create-umls-db-insert."
246   (ensure-ucols+ufiles)
247   (ensure-preparse)
248   (unless skip-translation
249     (translate-all-files extension))
250   (let ((copy-cmd
251          (ecase (umls-sql-type)
252            (:mysql #'mysql-copy-cmd)
253            (:postgresql #'pg-copy-cmd))))
254     (with-sql-connection (conn)
255       (clsql:truncate-database :database conn)
256       (sql-drop-tables conn)
257       (sql-create-tables conn)
258       (dolist (file *umls-files*)
259         (sql-execute (funcall copy-cmd file extension) conn))
260       (sql-create-indexes conn)
261       (sql-create-custom-tables conn)
262       (sql-create-indexes conn +custom-index-cols+)
263       (sql-create-special-tables conn))))
264
265 (defun translate-all-files (&optional (extension ".trans"))
266   "Copy translated files and return postgresql copy commands to import"
267   (make-noneng-index-file extension)
268   (dolist (f (remove "MRXW_NONENG.RRF" *umls-files* :test #'string= :key #'fil))
269     (translate-umls-file f extension)))
270
271 (defun translate-umls-file (file extension)
272   "Translate a umls file into a format suitable for sql copy cmd"
273   (translate-files file extension (list file)))
274
275 (defun make-noneng-index-file (extension)
276   "Make non-english index file"
277   (translate-files (find-ufile "MRXW_NONENG.RRF")
278                    extension (noneng-lang-index-files)))
279
280 (defun translate-files (out-ufile extension input-ufiles)
281   "Translate a umls file into a format suitable for sql copy cmd"
282   (let ((output-path (ufile-pathname out-ufile extension)))
283     (if (probe-file output-path)
284         (format t "File ~A already exists: skipping~%" output-path)
285       (with-open-file (ostream output-path :direction :output
286                                #+(and clisp unicode) :external-format
287                                #+(and clisp unicode) charset:utf-8)
288         (dolist (input-ufile input-ufiles)
289           (with-umls-ufile (line input-ufile)
290             (translate-line out-ufile line ostream)
291             (princ #\newline ostream)))))))
292
293 (defun translate-line (file line strm)
294   "Translate a single line for sql output"
295   (flet ((col-value (col value)
296            (if (eq (datatype col) 'sql-u)
297                (let ((ui (parse-ui value "")))
298                  (if (stringp ui)
299                      ui
300                      (write-to-string ui)))
301                (escape-backslashes value))))
302     (print-separated-strings
303      strm "|"
304      (mapcar #'col-value (remove-custom-cols (ucols file)) line)
305      (custom-col-values (custom-ucols-for-file file) line nil))))
306
307 (defun pg-copy-cmd (file extension)
308   "Return postgresql copy statement for a file"
309   (format
310    nil "COPY ~a FROM '~a' using delimiters '|' with null as ''"
311    (table file) (ufile-pathname file extension)))
312
313 (defun mysql-copy-cmd (file extension &key local-file)
314   "Return mysql copy statement for a file"
315   (format
316    nil
317    "LOAD DATA ~AINFILE \"~a\" INTO TABLE ~a FIELDS TERMINATED BY \"|\""
318    (if local-file "LOCAL " "")
319    (ufile-pathname file extension) (table file)))
320
321
322 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
323 ;;;
324 ;;; Routines for analyzing cost of fixed size storage
325 ;;;
326 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
327
328 (defun umls-fixed-size-waste ()
329   "Display storage waste if using all fixed size storage"
330   (let ((totalwaste 0)
331         (totalunavoidable 0)
332         (totalavoidable 0)
333         (unavoidable '())
334         (avoidable '()))
335     (dolist (file *umls-files*)
336       (dolist (col (ucols file))
337         (let* ((avwaste (- (cmax col) (av col)))
338                (cwaste (* avwaste (rws file))))
339           (when (plusp cwaste)
340             (if (<= avwaste 6)
341                 (progn
342                   (incf totalunavoidable cwaste)
343                   (push (list (fil file) (col col)
344                               avwaste cwaste)
345                         unavoidable))
346                 (progn
347                   (incf totalavoidable cwaste)
348                   (push (list (fil file) (col col)
349                               avwaste cwaste)
350                         avoidable)))
351             (incf totalwaste cwaste)))))
352     (values totalwaste totalavoidable totalunavoidable
353             (nreverse avoidable) (nreverse unavoidable))))
354
355 (defun display-waste ()
356   (ensure-ucols+ufiles)
357   (multiple-value-bind (tw ta tu al ul) (umls-fixed-size-waste)
358     (format t "Total waste: ~d~%" tw)
359     (format t "Total avoidable: ~d~%" ta)
360     (format t "Total unavoidable: ~d~%" tu)
361     (format t "Avoidable:~%")
362     (dolist (w al)
363       (format t "  (~a,~a): ~a,~a~%" (car w) (cadr w) (caddr w) (cadddr w)))
364     (format t "Unavoidable:~%")
365     (dolist (w ul)
366       (format t "  (~a,~a): ~a,~a~%" (car w) (cadr w) (caddr w) (cadddr w)))
367     ))
368
369 (defun max-umls-field ()
370   "Return length of longest field"
371   (declare (optimize (speed 3) (space 0)))
372   (ensure-ucols+ufiles)
373   (let ((max 0))
374     (declare (fixnum max))
375     (dolist (ucol *umls-cols*)
376       (when (> (cmax ucol) max)
377         (setq max (cmax ucol))))
378     max))
379
380 (defun max-umls-row ()
381   "Return length of longest row"
382   (declare (optimize (speed 3) (space 0)))
383   (ensure-ucols+ufiles)
384   (let ((rowsizes '()))
385     (dolist (file *umls-files*)
386       (let ((row 0))
387         (dolist (ucol (ucols file))
388           (incf row (1+ (cmax ucol))))
389         (push row rowsizes)))
390     (car (sort rowsizes #'>))))