73605a9f285c7db454aece139825fb72272bf0d2
[umlisp.git] / sql-create.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 ;;;; Programmer:    Kevin M. Rosenberg
8 ;;;; Date Started:  Apr 2000
9 ;;;;
10 ;;;; $Id: sql-create.lisp,v 1.1 2002/10/18 03:57:39 kevin Exp $
11 ;;;;
12 ;;;; This file, part of UMLisp, is
13 ;;;;    Copyright (c) 2000-2002 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 (declaim (optimize (speed 3) (safety 1) (compilation-speed 0) (debug 3)))
21
22
23 (defun create-table-cmd (file)
24 "Return sql command to create a table"
25   (let ((col-func 
26          (lambda (c) 
27            (let ((sqltype (umls-col-sqltype c)))
28              (concatenate 'string (umls-col-col c)
29                 " "
30                 (if (or (string-equal sqltype "VARCHAR")
31                         (string-equal sqltype "CHAR"))
32                      (format nil "~a (~a)" sqltype (umls-col-max c))
33                   sqltype)
34                 ",")))))
35     (format nil "CREATE TABLE ~a (~a)" (umls-file-table file)
36             (string-trim-last-character
37              (mapcar-append-string col-func (umls-cols-for-umls-file file))))))
38
39 (defun create-custom-table-cmd (tablename sql-cmd)
40 "Return SQL command to create a custom table"
41   (format nil "CREATE TABLE ~a AS ~a;" tablename sql-cmd))
42
43 (defun insert-values-cmd (file values)
44 "Return sql insert command for a row of values"  
45   (let ((insert-func
46          (lambda (col value)
47            (concatenate
48             'string
49             (umls-col-quotechar col)
50             (if (null (umls-col-parsefunc col)) 
51                 value
52               (format nil "~A" (funcall (umls-col-parsefunc col) value)))
53             (umls-col-quotechar col)
54             ","))))
55     (format
56      nil "INSERT INTO ~a (~a) VALUES (~a)"
57      (umls-file-table file)
58      (string-trim-last-character
59       (mapcar-append-string (lambda (c) (concatenate 'string c ","))
60                             (umls-file-fields file)))
61      (string-trim-last-character
62       (concatenate 'string
63         (mapcar2-append-string insert-func
64                                (remove-custom-cols (umls-file-colstructs file)) 
65                                values)
66         (custom-col-values (custom-colstructs-for-file file) values "," t)))
67      )))
68
69 (defun custom-col-values (colstructs values delim doquote)
70   "Returns string of column values for SQL inserts for custom columns"
71   (let ((result ""))
72     (dolist (col colstructs)
73       (let* ((func (umls-col-custom-value-func col))
74              (custom-value (funcall func values)))
75         (string-append result 
76                        (if doquote (umls-col-quotechar col))
77                        (escape-backslashes custom-value)
78                        (if doquote (umls-col-quotechar col))
79                        delim)))
80     result))
81
82 (defun remove-custom-cols (cols)
83   "Remove custom cols from a list col umls-cols"
84   (remove-if #'umls-col-custom-value-func cols))
85
86 (defun find-custom-cols-for-filename (filename)
87   (remove-if-not (lambda (x) (string-equal filename (car x))) +custom-cols+))
88
89 (defun find-custom-col (filename col)
90   (find-if (lambda (x) (and (string-equal filename (car x))
91                             (string-equal col (cadr x)))) +custom-cols+))
92
93
94 (defun custom-colnames-for-filename (filename)
95   (mapcar #'cadr (find-custom-cols-for-filename filename)))
96
97 (defun custom-colstructs-for-file (file)
98   (remove-if-not #'umls-col-custom-value-func (umls-file-colstructs file)))
99
100 (defun noneng-lang-index-files ()
101   (remove-if-not (lambda (f) (and (> (length (umls-file-fil f)) 4)
102                               (string-equal (umls-file-fil f) "MRXW." :end1 5) 
103                               (not (string-equal (umls-file-fil f) "MRXW.ENG"))
104                               (not (string-equal (umls-file-fil f) "MRXW.NONENG"))))
105                  *umls-files*))
106
107 ;;; SQL Command Functions
108
109 (defun create-index-cmd (colname tablename length)
110 "Return sql create index command"
111   (format nil "CREATE INDEX ~a ON ~a (~a ~a)"
112     (concatenate 'string tablename "_" colname "_X") tablename colname
113     (if (integerp length)
114         (format nil "(~d)" length)
115       "")))
116
117 (defun create-all-tables-cmdfile ()
118 "Return sql commands to create all tables. Not need for automated SQL import"
119   (mapcar (lambda (f) (format nil "~a~%~%" (create-table-cmd f))) *umls-files*))
120
121
122 ;; SQL Execution functions
123
124 (defun sql-drop-tables (conn)
125 "SQL Databases: drop all tables"
126   (mapcar
127    (lambda (file)
128      (ignore-errors 
129       (sql-execute (format nil "DROP TABLE ~a" (umls-file-table file)) conn)))
130    *umls-files*))
131
132 (defun sql-create-tables (conn)
133 "SQL Databases: create all tables" 
134   (mapcar (lambda (file) (sql-execute (create-table-cmd file) conn)) *umls-files*))
135
136 (defun sql-create-custom-tables (conn)
137 "SQL Databases: create all custom tables"
138   (mapcar (lambda (ct)
139      (sql-execute (create-custom-table-cmd (car ct) (cadr ct)) conn))
140    +custom-tables+))
141   
142 (defun sql-insert-values (conn file)
143 "SQL Databases: inserts all values for a file"  
144   (with-umls-file (line (umls-file-fil file))
145                   (sql-execute (insert-values-cmd file line) conn)))
146
147 (defun sql-insert-all-values (conn)
148 "SQL Databases: inserts all values for all files"  
149   (mapcar (lambda (file) (sql-insert-values conn file)) *umls-files*))
150
151 (defun sql-create-indexes (conn &optional (indexes +index-cols+))
152 "SQL Databases: create all indexes"
153 (mapcar 
154  (lambda (idx) 
155    (sql-execute (create-index-cmd (car idx) (cadr idx) (caddr idx)) conn)) 
156  indexes))
157
158 (defun make-usrl (conn)
159   (sql-execute "drop table if exists USRL" conn)
160   (sql-execute "create table USRL (sab varchar(80), srl integer)" conn)
161   (dolist (tuple (mutex-sql-query "select distinct SAB,SRL from MRSO order by SAB asc"))
162     (sql-execute (format nil "insert into USRL (sab,srl) values ('~a',~d)" 
163                          (car tuple) (ensure-integer (cadr tuple)))
164                  conn)))
165
166 (defun sql-create-special-tables (conn)
167   (make-usrl conn))
168
169 (defun create-umls-db-by-insert ()
170 "SQL Databases: initializes entire database via SQL insert commands"
171   (init-umls)
172   (init-hash-table)
173   (with-sql-connection (conn)
174 ;;   (sql-drop-tables conn)
175 ;;   (sql-create-tables conn)
176 ;;   (sql-insert-all-values conn)
177    (sql-create-indexes conn)
178    (sql-create-custom-tables conn)
179    (sql-create-indexes conn +custom-index-cols+)
180    (sql-create-special-tables)))
181
182 (defun create-umls-db (&optional (extension ".trans") 
183                                  (copy-cmd #'mysql-copy-cmd))
184   "SQL Databases: initializes entire database via SQL copy commands. 
185 This is much faster that using create-umls-db-insert."
186   (init-umls)
187   (init-hash-table)
188   (translate-all-files extension)
189   (with-sql-connection (conn)
190     (sql-drop-tables conn)
191     (sql-create-tables conn)
192     (mapcar 
193      #'(lambda (file) (sql-execute (funcall copy-cmd file extension) conn)) 
194      *umls-files*)
195     (sql-create-indexes conn)
196     (sql-create-custom-tables conn)
197     (sql-create-indexes conn +custom-index-cols+)
198     (sql-create-special-tables conn)))
199
200 (defun translate-all-files (&optional (extension ".trans"))
201 "Copy translated files and return postgresql copy commands to import"
202   (make-noneng-index-file extension)
203   (mapcar (lambda (f) (translate-file f extension)) *umls-files*))
204
205 (defun translate-file (file extension)
206   "Translate a umls file into a format suitable for sql copy cmd"
207   (let ((path (umls-pathname (umls-file-fil file) extension)))
208     (if (probe-file path)
209         (progn
210           (format t "File ~A already exists: skipping~%" path)
211           nil)
212       (with-open-file (ostream path :direction :output)
213         (with-umls-file (line (umls-file-fil file))
214           (princ (umls-translate file line) ostream)
215           (princ #\newline ostream))
216         t))))
217
218 (defun make-noneng-index-file (extension)
219   "Make non-english index file"
220   (let* ((outfile (find-umls-file "MRXW.NONENG"))
221          (path (umls-pathname (umls-file-fil outfile) extension)))
222         
223     (if (probe-file path)
224         (progn
225           (format t "File ~A already exists: skipping~%" path)
226           nil)
227       (progn
228         (with-open-file (ostream path :direction :output)
229           (dolist (inputfile (noneng-lang-index-files))
230             (with-umls-file (line (umls-file-fil inputfile))
231               (princ (umls-translate outfile line) ostream) ;; use outfile for custom cols
232               (princ #\newline ostream))))
233         t))))
234
235 (defun pg-copy-cmd (file extension)
236 "Return postgresql copy statement for a file"  
237   (format nil "COPY ~a FROM '~a' using delimiters '|' with null as ''"
238           (umls-file-table file) (umls-pathname (umls-file-fil file) extension)))
239
240 (defun mysql-copy-cmd (file extension)
241 "Return mysql copy statement for a file"  
242   (format nil "LOAD DATA LOCAL INFILE \"~a\" INTO TABLE ~a FIELDS TERMINATED BY \"|\""
243     (umls-pathname (umls-file-fil file) extension) (umls-file-table file)))
244
245 (defun umls-translate (file line)
246 "Translate a single line for sql output"
247 (string-trim-last-character
248  (concatenate 'string
249    (mapcar2-append-string 
250     (lambda (col value)
251       (concatenate
252           'string
253         (if (eq (umls-col-datatype col) 'sql-u)
254             (format nil "~d" (parse-ui value ""))
255           (escape-backslashes value))
256         "|"))
257     (remove-custom-cols (umls-file-colstructs file)) 
258     line)
259    (custom-col-values (custom-colstructs-for-file file) line "|" nil))))
260    
261
262 (defun umls-fixed-size-waste ()
263   "Display storage waste if using all fixed size storage"
264   (let ((totalwaste 0)
265         (totalunavoidable 0)
266         (totalavoidable 0)
267         (unavoidable '())
268         (avoidable '()))
269     (dolist (file *umls-files*)
270       (dolist (col (umls-file-colstructs file))
271         (let* ((avwaste (- (umls-col-max col) (umls-col-av col)))
272                (cwaste (* avwaste (umls-file-rws file))))
273           (unless (zerop cwaste)
274             (if (<= avwaste 6)
275                 (progn
276                   (incf totalunavoidable cwaste)
277                   (setq unavoidable (append unavoidable (list (list (umls-file-fil file) (umls-col-col col) avwaste cwaste)))))
278               (progn
279                   (incf totalavoidable cwaste)
280                   (setq avoidable (append avoidable (list (list (umls-file-fil file) (umls-col-col col) avwaste cwaste))))))
281             (incf totalwaste cwaste)))))
282     (values totalwaste totalavoidable totalunavoidable avoidable unavoidable)))
283
284 (defun display-waste ()
285   (unless *umls-files*
286     (init-umls))
287   (multiple-value-bind (tw ta tu al ul) (umls-fixed-size-waste)
288     (format t "Total waste: ~d~%" tw)
289     (format t "Total avoidable: ~d~%" ta)
290     (format t "Total unavoidable: ~d~%" tu)
291     (format t "Avoidable:~%")
292     (dolist (w al)
293       (format t "  (~a,~a): ~a,~a~%" (car w) (cadr w) (caddr w) (cadddr w)))
294     (format t "Unavoidable:~%")
295     (dolist (w ul)
296       (format t "  (~a,~a): ~a,~a~%" (car w) (cadr w) (caddr w) (cadddr w)))
297   ))
298
299 (defun max-umls-field ()
300   "Return length of longest field"
301   (unless *umls-files*
302     (init-umls))
303   (let ((max 0))
304     (declare (fixnum max))
305     (dolist (col *umls-cols*)
306       (when (> (umls-col-max col) max)
307         (setq max (umls-col-max col))))
308     max))
309
310 (defun max-umls-row ()
311   "Return length of longest row"
312   (if t
313       6000  ;;; hack to use on systems without MRCOLS/MRFILES -- ok for UMLS2001
314     (progn
315       (unless *umls-files*
316         (init-umls))
317       (let ((rowsizes '()))
318         (dolist (file *umls-files*)
319           (let ((row 0)
320                 (fields (umls-file-colstructs file)))
321             (dolist (field fields)
322               (incf row (1+ (umls-col-max field))))
323             (push row rowsizes)))
324         (car (sort rowsizes #'>))))))