r9507: rrf updates
[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-2004 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~^,~})" (table file)
42             (mapcar col-func (ucols file)))))
43
44 (defun create-custom-table-cmd (tablename sql-cmd)
45   "Return SQL command to create a custom table"
46   (format nil "CREATE TABLE ~a AS ~a;" tablename sql-cmd))
47
48 (defun insert-col-value (col value)
49   (if (null (parse-fun col)) 
50       value
51       (format nil "~A" (funcall (parse-fun col) value))))
52
53 (defun insert-values-cmd (file values)
54   "Return sql insert command for a row of values"  
55   (let ((insert-func
56          (lambda (col value)
57            (concatenate 'string (quote-str col)
58                         (insert-col-value col value)
59                         (quote-str col)))))
60     (format
61      nil "INSERT INTO ~a (~{~a~^,~}) VALUES (~A)"
62      (table file)
63      (fields file)
64      (concat-separated-strings
65       "," 
66       (mapcar insert-func (remove-custom-cols (ucols file)) values)
67       (custom-col-values (custom-ucols-for-file file) values t)))))
68
69
70 (defun custom-col-value (col values doquote)
71   (let ((custom-value (funcall (custom-value-fun col) values)))
72     (if custom-value
73         (if doquote
74             (concatenate 'string (quote-str col)
75                          (escape-backslashes custom-value)
76                          (quote-str col))
77             (escape-backslashes custom-value))
78         "")))
79
80 (defun custom-col-values (ucols values doquote)
81   "Returns a list of string column values for SQL inserts for custom columns"
82   (loop for col in ucols collect (custom-col-value col values doquote)))
83
84 (defun remove-custom-cols (cols)
85   "Remove custom cols from a list col umls-cols"
86   (remove-if #'custom-value-fun cols))
87
88 (defun find-custom-cols-for-filename (filename)
89   (remove-if-not (lambda (x) (string-equal filename (car x))) +custom-cols+))
90
91 (defun find-custom-col (filename col)
92   (find-if (lambda (x) (and (string-equal filename (car x))
93                             (string-equal col (cadr x)))) +custom-cols+))
94
95 (defun custom-colnames-for-filename (filename)
96   (mapcar #'cadr (find-custom-cols-for-filename filename)))
97
98 (defun custom-ucols-for-file (file)
99   (remove-if-not #'custom-value-fun (ucols file)))
100
101 (defun noneng-lang-index-files ()
102   (remove-if-not
103    (lambda (f) (and (> (length (fil f)) 4)
104                     (string-equal (fil f) "MRXW_" :end1 5) 
105                     (not (string-equal (fil f) "MRXW_ENG.RRF"))
106                     (not (string-equal (fil f) "MRXW_NONENG.RRF"))))
107    *umls-files*))
108
109 ;;; SQL Command Functions
110
111 (defun create-index-cmd (colname tablename length)
112   "Return sql create index command"
113   (format nil "CREATE INDEX ~a ON ~a (~a)"
114           (concatenate 'string tablename "_" colname "_X")
115           tablename 
116           (case *umls-sql-type*
117             (:mysql
118              (concatenate 'string colname
119                           (if (integerp length)
120                               (format nil " (~d)" length)
121                               "")))
122             ((:postgresql :postgresql-socket)
123              ;; FIXME: incorrect syntax
124              (if (integerp length)
125                  (format nil "substr((~A)::text,1,~D)" colname length)
126                  colname))
127             (t
128              colname))))
129
130 (defun create-all-tables-cmdfile ()
131   "Return sql commands to create all tables. Not need for automated SQL import"
132   (mapcar (lambda (f) (format nil "~a~%~%" (create-table-cmd f))) *umls-files*))
133
134 ;; SQL Execution functions
135
136 (defun sql-drop-tables (conn)
137   "SQL Databases: drop all tables"
138   (dolist (file *umls-files*)
139     (ignore-errors 
140       (sql-execute (format nil "DROP TABLE ~a" (table file)) conn))))
141
142 (defun sql-create-tables (conn)
143   "SQL Databases: create all tables" 
144   (dolist (file *umls-files*)
145     (sql-execute (create-table-cmd file) conn)))
146
147 (defun sql-create-custom-tables (conn)
148   "SQL Databases: create all custom tables"
149   (dolist (ct +custom-tables+)
150     (sql-execute (create-custom-table-cmd (car ct) (cadr ct)) conn)))
151   
152 (defun sql-insert-values (conn file)
153   "SQL Databases: inserts all values for a file"  
154   (with-umls-file (line (fil file))
155     (sql-execute (insert-values-cmd file line) conn)))
156
157 (defun sql-insert-all-values (conn)
158   "SQL Databases: inserts all values for all files"  
159   (dolist (file *umls-files*)
160     (sql-insert-values conn file)))
161
162 (defun drop-index-cmd (colname tablename)
163   "Return sql create index command"
164   (case *umls-sql-type*
165     (:mysql
166      (format nil "DROP INDEX ~a ON ~a"
167              (concatenate 'string tablename "_" colname "_X")
168              tablename))
169     (t
170      (format nil "DROP INDEX ~a"
171              (concatenate 'string tablename "_" colname "_X")))))
172
173 (defun sql-create-indexes (conn &optional (indexes +index-cols+))
174   "SQL Databases: create all indexes"
175   (dolist (idx indexes)
176     (ignore-errors (sql-execute (drop-index-cmd (car idx) (cadr idx)) conn))
177     (sql-execute (create-index-cmd (car idx) (cadr idx) (caddr idx)) conn))) 
178
179 (defun make-usrl (conn)
180   (if (eql :mysql *umls-sql-type*)
181       (sql-execute "drop table if exists USRL" conn)
182       (ignore-errors (sql-execute "drop table USRL" conn)))
183   (sql-execute "create table USRL (sab varchar(80), srl integer)" conn)
184   (dolist (tuple (mutex-sql-query
185                   "select distinct SAB,SRL from MRSO order by SAB asc"))
186     (sql-execute (format nil "insert into USRL (sab,srl) values ('~a',~d)" 
187                          (car tuple) (ensure-integer (cadr tuple)))
188                  conn)))
189
190 (defun sql-create-special-tables (conn)
191   (make-usrl conn)
192   (make-ustats))
193
194 (defun create-umls-db-by-insert ()
195   "SQL Databases: initializes entire database via SQL insert commands"
196   (ensure-ucols+ufiles)
197   (ensure-preparse)
198   (with-sql-connection (conn)
199     (sql-drop-tables conn)
200     (sql-create-tables conn)
201     (sql-insert-all-values conn)
202     (sql-create-indexes conn)
203     (sql-create-custom-tables conn)
204     (sql-create-indexes conn +custom-index-cols+)
205     (sql-create-special-tables conn)))
206
207 (defun create-umls-db (&key (extension ".trans") (skip-translation nil))
208   "SQL Databases: initializes entire database via SQL copy commands. 
209 This is much faster that using create-umls-db-insert."
210   (ensure-ucols+ufiles)
211   (ensure-preparse)
212   (unless skip-translation
213     (translate-all-files extension))
214   (let ((copy-cmd
215          (ecase (umls-sql-type)
216            (:mysql #'mysql-copy-cmd)
217            (:postgresql #'pg-copy-cmd))))
218     (with-sql-connection (conn)
219       (clsql:truncate-database :database conn)
220       (sql-drop-tables conn)
221       (sql-create-tables conn)
222       (dolist (file *umls-files*)
223         (sql-execute (funcall copy-cmd file extension) conn))
224       (sql-create-indexes conn)
225       (sql-create-custom-tables conn)
226       (sql-create-indexes conn +custom-index-cols+)
227       (sql-create-special-tables conn))))
228
229 (defun translate-all-files (&optional (extension ".trans"))
230   "Copy translated files and return postgresql copy commands to import"
231   (make-noneng-index-file extension)
232   (dolist (f (remove "MRXW_NONENG.RRF" *umls-files* :test #'string= :key #'fil))
233     (translate-umls-file f extension)))
234
235 (defun translate-umls-file (file extension)
236   "Translate a umls file into a format suitable for sql copy cmd"
237   (translate-files file extension (list file)))
238
239 (defun make-noneng-index-file (extension)
240   "Make non-english index file"
241   (translate-files (find-ufile "MRXW_NONENG.RRF")
242                    extension (noneng-lang-index-files)))
243
244 (defun translate-files (out-ufile extension input-ufiles)
245   "Translate a umls file into a format suitable for sql copy cmd"
246   (let ((output-path (ufile-pathname out-ufile extension)))
247     (if (probe-file output-path)
248         (format t "File ~A already exists: skipping~%" output-path)
249       (with-open-file (ostream output-path :direction :output)
250         (dolist (input-ufile input-ufiles)
251           (with-umls-ufile (line input-ufile)
252             (translate-line out-ufile line ostream)
253             (princ #\newline ostream)))))))
254
255 (defun translate-line (file line strm)
256   "Translate a single line for sql output"
257   (flet ((col-value (col value)
258            (if (eq (datatype col) 'sql-u)
259                (let ((ui (parse-ui value "")))
260                  (if (stringp ui)
261                      ui
262                      (write-to-string ui)))
263                (escape-backslashes value))))
264     (print-separated-strings
265      strm "|" 
266      (mapcar #'col-value (remove-custom-cols (ucols file)) line)
267      (custom-col-values (custom-ucols-for-file file) line nil))))
268
269 (defun pg-copy-cmd (file extension)
270   "Return postgresql copy statement for a file"  
271   (format
272    nil "COPY ~a FROM '~a' using delimiters '|' with null as ''"
273    (table file) (umls-pathname (fil file) extension)))
274
275 (defun mysql-copy-cmd (file extension &key local-file)
276   "Return mysql copy statement for a file"  
277   (format
278    nil
279    "LOAD DATA ~AINFILE \"~a\" INTO TABLE ~a FIELDS TERMINATED BY \"|\""
280    (if local-file "LOCAL " "")
281    (umls-pathname (fil file) extension) (table file)))
282
283    
284 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
285 ;;;
286 ;;; Routines for analyzing cost of fixed size storage
287 ;;;
288 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
289
290 (defun umls-fixed-size-waste ()
291   "Display storage waste if using all fixed size storage"
292   (let ((totalwaste 0)
293         (totalunavoidable 0)
294         (totalavoidable 0)
295         (unavoidable '())
296         (avoidable '()))
297     (dolist (file *umls-files*)
298       (dolist (col (ucols file))
299         (let* ((avwaste (- (cmax col) (av col)))
300                (cwaste (* avwaste (rws file))))
301           (when (plusp cwaste)
302             (if (<= avwaste 6)
303                 (progn
304                   (incf totalunavoidable cwaste)
305                   (push (list (fil file) (col col)
306                               avwaste cwaste)
307                         unavoidable))
308                 (progn
309                   (incf totalavoidable cwaste)
310                   (push (list (fil file) (col col)
311                               avwaste cwaste)
312                         avoidable)))
313             (incf totalwaste cwaste)))))
314     (values totalwaste totalavoidable totalunavoidable
315             (nreverse avoidable) (nreverse unavoidable))))
316
317 (defun display-waste ()
318   (ensure-ucols+ufiles)
319   (multiple-value-bind (tw ta tu al ul) (umls-fixed-size-waste)
320     (format t "Total waste: ~d~%" tw)
321     (format t "Total avoidable: ~d~%" ta)
322     (format t "Total unavoidable: ~d~%" tu)
323     (format t "Avoidable:~%")
324     (dolist (w al)
325       (format t "  (~a,~a): ~a,~a~%" (car w) (cadr w) (caddr w) (cadddr w)))
326     (format t "Unavoidable:~%")
327     (dolist (w ul)
328       (format t "  (~a,~a): ~a,~a~%" (car w) (cadr w) (caddr w) (cadddr w)))
329     ))
330
331 (defun max-umls-field ()
332   "Return length of longest field"
333   (declare (optimize (speed 3) (space 0)))
334   (ensure-ucols+ufiles)
335   (let ((max 0))
336     (declare (fixnum max))
337     (dolist (ucol *umls-cols*)
338       (when (> (cmax ucol) max)
339         (setq max (cmax ucol))))
340     max))
341
342 (defun max-umls-row ()
343   "Return length of longest row"
344   (declare (optimize (speed 3) (space 0)))
345   (ensure-ucols+ufiles)
346   (let ((rowsizes '()))
347     (dolist (file *umls-files*)
348       (let ((row 0))
349         (dolist (ucol (ucols file))
350           (incf row (1+ (cmax ucol))))
351         (push row rowsizes)))
352     (car (sort rowsizes #'>))))