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