r11704: can not use keywords in :subobject functions
[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 (defun position-field-file (filename fieldname)
234   "Returns the position of a field in a file"
235   (let ((ufile (find-ufile filename)))
236     (unless ufile
237       (warn "Unable to find ufile for filename ~A." filename)
238       (return-from position-field-file nil))
239     (let ((pos (position fieldname (fields ufile) :test #'string=)))
240       (unless pos
241         (warn "Unable to find field ~A in ufile ~S." fieldname ufile)
242         (return-from position-field-file nil))
243       pos)))
244
245 (defun find-ucols-for-ufile (ufile)
246   "Returns list of umls-cols for a file structure"
247   (loop for colname in (fields ufile)
248       collect (find-ucol colname
249                          (if (subdir ufile)
250                              (concatenate 'string (subdir ufile) "/" (fil ufile))
251                            (fil ufile)))))
252
253 (defun umls-field-string-to-list (fmt)
254   "Converts a comma delimited list of fields into a list of field names. Will
255 append a unique number (starting at 2) onto a column name that is repeated in the list"
256   (let ((col-counts (make-hash-table :test 'equal)))
257     (loop for colname in (delimited-string-to-list (escape-column-name fmt) #\,)
258           collect
259           (multiple-value-bind (value found) (gethash colname col-counts)
260             (cond
261               (found
262                 (incf (gethash colname col-counts))
263                 (concatenate 'string colname (write-to-string (1+ value))))
264               (t
265                (setf (gethash colname col-counts) 1)
266                colname))))))
267
268 (defun decompose-fil (fil)
269   (if fil
270       (let ((pos (position #\/ fil)))
271         (if pos
272             (values (subseq fil (1+ pos)) (subseq fil 0 pos))
273           (values fil nil)))
274     (values nil nil)))
275
276 (defun filename-to-tablename (file)
277   (let ((pos (search ".RRF" file)))
278     (when pos
279       (setf file (subseq file 0 pos))))
280   (substitute #\_ #\. file))
281
282 (defun make-ufile (dir fil des cls rws bts fields)
283   (multiple-value-bind (file subdir) (decompose-fil fil)
284     (let ((ufile (make-instance 'ufile :dir dir :fil file :subdir subdir
285                                 :des des :cls cls
286                                 :rws rws :bts bts :fields fields
287                                 :table (filename-to-tablename file))))
288       ufile)))
289
290 (defun set-ucols-for-ufiles (ufiles)
291   (dolist (ufile ufiles)
292     (setf (ucols ufile) (find-ucols-for-ufile ufile))))
293
294 (defun datatype-for-colname (colname)
295 "Return datatype for column name"
296   (second (find colname +col-datatypes+ :key #'car :test #'string-equal)))
297
298 (defun canonicalize-column-type (type)
299   (cond
300    ((string-equal type "TINYINT")
301     (case *umls-sql-type*
302       (:mysql "TINYINT")
303       ((:postgresql :postgresql-socket) "INT1")
304       (:oracle "NUMBER(3,0)")
305       (t "INTEGER")))
306    ((string-equal type "SMALLINT")
307     (case *umls-sql-type*
308       (:mysql "SMALLINT")
309       ((:postgresql :postgresql-socket) "INT2")
310       (:oracle "NUMBER(5,0)")
311       (t "INTEGER")))
312    ((string-equal type "INTEGER")
313     (case *umls-sql-type*
314       (:mysql "INTEGER")
315       ((:postgresql :postgresql-socket) "INT4")
316       (:oracle "NUMBER(9,0)")
317       (t "INTEGER")))
318    ((string-equal type "BIGINT")
319     (case *umls-sql-type*
320       (:mysql "BIGINT")
321       ((:postgresql :postgresql-socket) "INT8")
322       (:oracle "NUMBER(38,0)")
323       (t "INTEGER")))
324    ((string-equal type "TEXT")
325     (case *umls-sql-type*
326       (:mysql "TEXT")
327       ((:postgresql :postgresql-socket) "TEXT")
328       (:oracle "VARCHAR2(3000)")
329       (t "VARCHAR(3000)")))
330    ((string-equal type "VARCHAR")
331     (case *umls-sql-type*
332       (:mysql "VARCHAR")
333       ((:postgresql :postgresql-socket) "VARCHAR")
334       (:oracle "VARCHAR2")
335       (t "VARCHAR")))
336    ((string-equal type "NUMERIC")
337     (case *umls-sql-type*
338       (:mysql "NUMERIC")
339       ((:postgresql :postgresql-socket) "NUMERIC")
340       (:oracle "NUMBER")
341       (t "NUMERIC")))
342    (t
343     type)))
344
345 (defun ensure-ucol-datatype (col datatype)
346   "Add data type information to column"
347   (setf (datatype col) datatype)
348   (case datatype
349     (sql-u (setf (sqltype col) (canonicalize-column-type "INTEGER")
350                  (parse-fun col) #'parse-ui
351                  (quote-str col) ""))
352     (sql-s (setf (sqltype col) (canonicalize-column-type "SMALLINT")
353                  (parse-fun col) #'parse-integer
354                  (quote-str col) ""))
355     (sql-l (setf (sqltype col)  (canonicalize-column-type "BIGINT")
356                  (parse-fun col) #'parse-integer
357                  (quote-str col) ""))
358     (sql-i (setf (sqltype col)  (canonicalize-column-type "INTEGER")
359                  (parse-fun col) #'parse-integer
360                  (quote-str col) ""))
361     (sql-t (setf (sqltype col)  (canonicalize-column-type "TINYINT")
362                  (parse-fun col) #'parse-integer
363                  (quote-str col) ""))
364     (sql-f (setf (sqltype col)  (canonicalize-column-type "NUMERIC")
365                  (parse-fun col) #'read-from-string
366                  (quote-str col) ""))
367     (t                                  ; Default column type, optimized text storage
368      (setf (parse-fun col) #'add-sql-quotes
369            (quote-str col) "'")
370      (when (and (cmax col) (av col))
371        (if (> (cmax col) 255)
372            (setf (sqltype col) (canonicalize-column-type "TEXT"))
373          (setf (sqltype col) (canonicalize-column-type "VARCHAR")))))))
374
375 (defun escape-column-name (name)
376   (substitute #\_ #\/ name))