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