Change default SQL server host
[umlisp.git] / parse-common.lisp
1 ;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10; Package: umlisp -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:     parse-common.lisp
6 ;;;; Purpose:  Common, stable parsing routines 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 ensure-ucols+ufiles (&optional (alwaysclear nil))
20   "Initialize all UMLS file and column structures if not already initialized"
21   (handler-case
22       (when (or alwaysclear (null *umls-files*))
23         (setf *umls-cols* nil *umls-files* nil)
24         (gen-ufiles)
25         (gen-ucols)
26         (set-ucols-for-ufiles *umls-files*)
27         (ensure-field-lengths))
28     (error (e)
29       (warn "Error reading ucols+ufiles: ~A." e)
30       (setf *umls-cols* nil *umls-files* nil)
31       nil))
32   t)
33
34
35 (defun add-ucols (ucols)
36   "Adds a ucol or list of ucols to *umls-cols*. Returns input value."
37   (setq *umls-cols* (append (mklist ucols) *umls-cols*))
38   ucols)
39
40 (defun add-ufiles (ufiles)
41   "Adds a ufile or list of ufiles to *umls-filess*. Returns input value."
42   (setq *umls-files* (append (mklist ufiles) *umls-files*))
43   ufiles)
44
45 (defun ufile-pathname (ufile &optional (extension ""))
46   "Return pathname for a umls filename with an optional extension"
47   (assert (typep ufile 'ufile))
48   (let* ((dirs (nconc (list (dir ufile))
49                       (awhen (subdir ufile) (list it))))
50          (name-list (delimited-string-to-list (fil ufile) #\.))
51          (name (if (second name-list)
52                    (first name-list)
53                    (concatenate 'string (first name-list) (or extension ""))))
54          (type (when (second name-list)
55                  (concatenate 'string (second name-list) (or extension "")))))
56      (merge-pathnames
57       (make-pathname :name name :type type
58                      :directory (cons :relative dirs))
59       *umls-path*)))
60
61 (defun umls-pathname (filename &optional (extension ""))
62 "Return pathname for a umls filename with an optional extension"
63   (etypecase filename
64     (string
65      (let* ((name-list (delimited-string-to-list filename #\.))
66             (name (if (second name-list)
67                       (first name-list)
68                       (concatenate 'string (first name-list) (or extension ""))))
69             (type (when (second name-list)
70                     (concatenate 'string (second name-list) (or extension "")))))
71      (merge-pathnames
72       (make-pathname :name name :type type)
73       (case (schar filename 0)
74         ((#\M #\m)
75          *meta-path*)
76         ((#\L #\l)
77          *lex-path*)
78         ((#\S #\s)
79          *net-path*)
80         (t
81          *umls-path*)))))
82     (pathname
83      filename)))
84
85
86 ;;; Find field lengths for LEX and NET files
87
88 (defun ensure-field-lengths ()
89   "Initial colstruct field lengths for files that don't have a measurement.
90 Currently, these are the LEX and NET files."
91   (dolist (length-list (ufiles-field-lengths (ufiles-to-measure)))
92     (destructuring-bind (filename fields-max fields-av count-lines) length-list
93       (let ((file (find-ufile filename)))
94         (unless file
95           (error "Can't find ~A filename in ufiles" filename))
96         (if (zerop count-lines)
97             (warn "File ~A is empty." filename)
98             (progn
99               (unless (= (length fields-max) (length (fields file)))
100                 (error
101                  "Number of file fields ~A not equal to field count in ufile ~S"
102                  fields-max file))
103             (dotimes (i (length (fields file)))
104               (declare (fixnum i))
105               (let* ((field (nth i (fields file)))
106                      (col (find-ucol field filename)))
107                 (unless col
108                   (error "can't find column ~A" field))
109                 (setf (cmax col) (aref fields-max i))
110                 (setf (av col) (aref fields-av i))
111                 (ensure-ucol-datatype col (datatype-for-colname (col col)))))))))))
112
113 (defun ufiles-to-measure ()
114   "Returns a list of ufiles to measure"
115   (loop for ufile in *umls-files*
116         unless (or (char= #\M (schar (fil ufile) 0))
117                    (char= #\m (schar (fil ufile) 0)))
118       collect ufile))
119
120
121 (defun ufiles-field-lengths (ufiles)
122   "Returns a list of lists of containing (FILE MAX AV)"
123   (loop for ufile in ufiles collect (file-field-lengths ufile)))
124
125 (defun file-field-lengths (ufile)
126   "Returns a list of FILENAME MAX AV"
127   (declare (optimize (speed 3) (safety 0)))
128   (let (fields-max fields-av num-fields (count-lines 0))
129     (declare (fixnum count-lines))
130     (with-umls-ufile (line ufile)
131       (unless num-fields
132         (setq num-fields (length line))
133         (setq fields-max (make-array num-fields :element-type 'fixnum
134                                      :initial-element 0))
135         (setq fields-av (make-array num-fields :element-type '(or integer float)
136                                     :initial-element 0)))
137       (dotimes (i (or num-fields 0))
138         (declare (fixnum i))
139         (let* ((str (nth i line))
140                (len (length #-(and clisp unicode) str
141                             #+(and clisp unicode)
142                             (if *octet-sql-storage*
143                                 (ext:convert-string-to-bytes str charset:utf-8)
144                               str))))
145           #-(and clisp unicode) (declare (string str))
146           (declare (type (integer 0 100000000) len))
147           (incf (aref fields-av i) len)
148           (when (> len (aref fields-max i))
149             (setf (aref fields-max i) len))))
150       (incf count-lines))
151     (dotimes (i (or num-fields 0))
152       (setf (aref fields-av i)
153             (if (plusp count-lines)
154                 (float (/ (aref fields-av i) count-lines))
155                 0)))
156     (list (fil ufile) fields-max fields-av count-lines)))
157
158 ;;; UMLS column/file functions
159
160 (defun find-ucol-of-colname (colname filename ucols)
161 "Returns list of umls-col structure for a column name and a filename"
162   (dolist (ucol ucols nil)
163     (when (and (string-equal filename (fil ucol))
164                (string-equal colname (col ucol)))
165       (return-from find-ucol-of-colname ucol))))
166
167 (defun ensure-col-in-columns (colname filename ucols)
168   (aif (find-ucol-of-colname colname filename ucols)
169        it
170        (add-ucols (make-ucol-for-column colname filename ucols))))
171
172 (defun make-ucol-for-column (colname filename ucols)
173   ;; try to find column name without a terminal digit
174   (let* ((len (length colname))
175          (last-digit? (digit-char-p (schar colname (1- len))))
176          (base-colname (if last-digit?
177                            (subseq colname 0 (1- len))
178                            colname))
179          (ucol (when last-digit?
180                  (find-ucol-of-colname base-colname filename ucols))))
181     (when (and last-digit? (null ucol))
182       (error "Couldn't find a base column for col ~A in file ~A"
183              colname filename))
184     (copy-or-new-ucol colname filename ucol)))
185
186 (defun copy-or-new-ucol (colname filename ucol)
187   (if ucol
188       (make-instance
189        'ucol
190        :col (copy-seq colname) :des (copy-seq (des ucol)) :ref (copy-seq (ref ucol))
191        :min (cmin ucol) :max (cmax ucol) :fil (copy-seq (fil ucol))
192        :sqltype (copy-seq (sqltype ucol)) :dty (copy-seq (dty ucol))
193        :parse-fun (parse-fun ucol) :quote-str (copy-seq (quote-str ucol))
194        :datatype (datatype ucol) :custom-value-fun (custom-value-fun ucol))
195       (make-empty-ucol colname filename)))
196
197 (defun ensure-compiled-fun (fun)
198   "Ensure that a function is compiled"
199   (etypecase fun
200     (null
201      nil)
202     (function
203      (if (compiled-function-p fun)
204          fun
205          (compile nil fun)))
206     (list
207      (compile nil fun))))
208
209 (defun make-ucol (col des ref min av max fil dty
210                   &key (sqltype "VARCHAR") (parse-fun #'add-sql-quotes)
211                   (quote-str "'") (custom-value-fun))
212   (let ((ucol (make-instance
213                'ucol
214                :col col :des des :ref ref :min min :av av
215                :max (if (eql max 0) 1 max) ;; ensure at least one char wide
216                :fil fil
217                :dty dty
218                :sqltype sqltype
219                :quote-str quote-str
220                :parse-fun (ensure-compiled-fun parse-fun)
221                :custom-value-fun (ensure-compiled-fun custom-value-fun))))
222     (ensure-ucol-datatype ucol (datatype-for-colname col))
223     ucol))
224
225 (defun make-empty-ucol (colname filename)
226   ;;(format "call in make-empty-ucol: ~A/~A" colname filename)
227   (make-ucol (copy-seq colname) "Unknown" "" nil nil nil filename nil))
228
229 (defun find-ucol (colname filename)
230   "Returns list of umls-col structure for a column name and a filename"
231   (ensure-col-in-columns colname filename *umls-cols*))
232
233 (defun find-ufile (filename)
234   "Returns umls-file structure for a filename"
235   (find-if #'(lambda (f) (string= filename (fil f))) *umls-files*))
236
237 (defun position-field-file (filename fieldname)
238   "Returns the position of a field in a file"
239   (let ((ufile (find-ufile filename)))
240     (unless ufile
241       (warn "Unable to find ufile for filename ~A." filename)
242       (return-from position-field-file nil))
243     (let ((pos (position fieldname (fields ufile) :test #'string=)))
244       (unless pos
245         (warn "Unable to find field ~A in ufile ~S." fieldname ufile)
246         (return-from position-field-file nil))
247       pos)))
248
249 (defun find-ucols-for-ufile (ufile)
250   "Returns list of umls-cols for a file structure"
251   (loop for colname in (fields ufile)
252       collect (find-ucol colname
253                          (if (subdir ufile)
254                              (concatenate 'string (subdir ufile) "/" (fil ufile))
255                            (fil ufile)))))
256
257 (defun umls-field-string-to-list (fmt)
258   "Converts a comma delimited list of fields into a list of field names. Will
259 append a unique number (starting at 2) onto a column name that is repeated in the list"
260   (let ((col-counts (make-hash-table :test 'equal)))
261     (loop for colname in (delimited-string-to-list (escape-column-name fmt) #\,)
262           collect
263           (multiple-value-bind (value found) (gethash colname col-counts)
264             (cond
265               (found
266                 (incf (gethash colname col-counts))
267                 (concatenate 'string colname (write-to-string (1+ value))))
268               (t
269                (setf (gethash colname col-counts) 1)
270                colname))))))
271
272 (defun decompose-fil (fil)
273   (if fil
274       (let ((pos (position #\/ fil)))
275         (if pos
276             (values (subseq fil (1+ pos)) (subseq fil 0 pos))
277           (values fil nil)))
278     (values nil nil)))
279
280 (defun filename-to-tablename (file)
281   (let ((pos (search ".RRF" file)))
282     (when pos
283       (setf file (subseq file 0 pos))))
284   (substitute #\_ #\. file))
285
286 (defun make-ufile (dir fil des cls rws bts fields)
287   (multiple-value-bind (file subdir) (decompose-fil fil)
288     (let ((ufile (make-instance 'ufile :dir dir :fil file :subdir subdir
289                                 :des des :cls cls
290                                 :rws rws :bts bts :fields fields
291                                 :table (filename-to-tablename file))))
292       ufile)))
293
294 (defun set-ucols-for-ufiles (ufiles)
295   (dolist (ufile ufiles)
296     (setf (ucols ufile) (find-ucols-for-ufile ufile))))
297
298 (defun datatype-for-colname (colname)
299 "Return datatype for column name"
300   (second (find colname +col-datatypes+ :key #'car :test #'string-equal)))
301
302 (defun canonicalize-column-type (type)
303   (cond
304    ((string-equal type "TINYINT")
305     (case *umls-sql-type*
306       (:mysql "TINYINT")
307       ((:postgresql :postgresql-socket) "INT1")
308       (:oracle "NUMBER(3,0)")
309       (t "INTEGER")))
310    ((string-equal type "SMALLINT")
311     (case *umls-sql-type*
312       (:mysql "SMALLINT")
313       ((:postgresql :postgresql-socket) "INT2")
314       (:oracle "NUMBER(5,0)")
315       (t "INTEGER")))
316    ((string-equal type "INTEGER")
317     (case *umls-sql-type*
318       (:mysql "INTEGER")
319       ((:postgresql :postgresql-socket) "INT4")
320       (:oracle "NUMBER(9,0)")
321       (t "INTEGER")))
322    ((string-equal type "BIGINT")
323     (case *umls-sql-type*
324       (:mysql "BIGINT")
325       ((:postgresql :postgresql-socket) "INT8")
326       (:oracle "NUMBER(38,0)")
327       (t "INTEGER")))
328    ((string-equal type "TEXT")
329     (case *umls-sql-type*
330       (:mysql "TEXT")
331       ((:postgresql :postgresql-socket) "TEXT")
332       (:oracle "VARCHAR2(3000)")
333       (t "VARCHAR(3000)")))
334    ((string-equal type "VARCHAR")
335     (case *umls-sql-type*
336       (:mysql "VARCHAR")
337       ((:postgresql :postgresql-socket) "VARCHAR")
338       (:oracle "VARCHAR2")
339       (t "VARCHAR")))
340    ((string-equal type "NUMERIC")
341     (case *umls-sql-type*
342       (:mysql "NUMERIC")
343       ((:postgresql :postgresql-socket) "NUMERIC")
344       (:oracle "NUMBER")
345       (t "NUMERIC")))
346    (t
347     type)))
348
349 (defun ensure-ucol-datatype (col datatype)
350   "Add data type information to column"
351   (setf (datatype col) datatype)
352   (case datatype
353     (sql-u (setf (sqltype col) (canonicalize-column-type "INTEGER")
354                  (parse-fun col) #'parse-ui
355                  (quote-str col) ""))
356     (sql-s (setf (sqltype col) (canonicalize-column-type "SMALLINT")
357                  (parse-fun col) #'parse-integer
358                  (quote-str col) ""))
359     (sql-l (setf (sqltype col)  (canonicalize-column-type "BIGINT")
360                  (parse-fun col) #'parse-integer
361                  (quote-str col) ""))
362     (sql-i (setf (sqltype col)  (canonicalize-column-type "INTEGER")
363                  (parse-fun col) #'parse-integer
364                  (quote-str col) ""))
365     (sql-t (setf (sqltype col)  (canonicalize-column-type "TINYINT")
366                  (parse-fun col) #'parse-integer
367                  (quote-str col) ""))
368     (sql-f (setf (sqltype col)  (canonicalize-column-type "NUMERIC")
369                  (parse-fun col) #'read-from-string
370                  (quote-str col) ""))
371     (t                                  ; Default column type, optimized text storage
372      (setf (parse-fun col) #'add-sql-quotes
373            (quote-str col) "'")
374      (when (and (cmax col) (av col))
375        (if (> (cmax col) 255)
376            (setf (sqltype col) (canonicalize-column-type "TEXT"))
377          (setf (sqltype col) (canonicalize-column-type "VARCHAR")))))))
378
379 (defun escape-column-name (name)
380   (substitute #\_ #\/ name))
381
382 ;; SQLNAME is required for collision of SQL reserved words (MYSQL 8: RANK)
383 ;; and column names in UMLS (RANK in MRRANK)
384 (defvar *sql-reserved-names* '("RANK"))
385 (defmethod sqlname ((c ucol))
386   (sqlname (col c)))
387 (defmethod sqlname ((name string))
388   (if (find name *sql-reserved-names* :test #'string-equal)
389       (concatenate 'string "_" name)
390     name))
391 (defmethod sqlname ((l list))
392   (mapcar #'sqlname l))
393 (defmethod sqlname ((s symbol))
394   (sqlname (symbol-name s)))