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