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