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