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