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