]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/sql/Pg/012.schema.vandelay.sql
Vandelay-based record matching and import for Acquisitions
[Evergreen.git] / Open-ILS / src / sql / Pg / 012.schema.vandelay.sql
1 DROP SCHEMA IF EXISTS vandelay CASCADE;
2
3 BEGIN;
4
5 CREATE SCHEMA vandelay;
6
7 CREATE TABLE vandelay.match_set (
8     id      SERIAL  PRIMARY KEY,
9     name    TEXT        NOT NULL,
10     owner   INT     NOT NULL REFERENCES actor.org_unit (id) ON DELETE CASCADE,
11     mtype   TEXT        NOT NULL DEFAULT 'biblio', -- 'biblio','authority','mfhd'?, others?
12     CONSTRAINT name_once_per_owner_mtype UNIQUE (name, owner, mtype)
13 );
14
15 -- Table to define match points, either FF via SVF or tag+subfield
16 CREATE TABLE vandelay.match_set_point (
17     id          SERIAL  PRIMARY KEY,
18     match_set   INT     REFERENCES vandelay.match_set (id) ON DELETE CASCADE,
19     parent      INT     REFERENCES vandelay.match_set_point (id),
20     bool_op     TEXT    CHECK (bool_op IS NULL OR (bool_op IN ('AND','OR','NOT'))),
21     svf         TEXT    REFERENCES config.record_attr_definition (name),
22     tag         TEXT,
23     subfield    TEXT,
24     negate      BOOL    DEFAULT FALSE,
25     quality     INT     NOT NULL DEFAULT 1, -- higher is better
26     CONSTRAINT vmsp_need_a_subfield_with_a_tag CHECK ((tag IS NOT NULL AND subfield IS NOT NULL) OR tag IS NULL),
27     CONSTRAINT vmsp_need_a_tag_or_a_ff_or_a_bo CHECK (
28         (tag IS NOT NULL AND svf IS NULL AND bool_op IS NULL) OR
29         (tag IS NULL AND svf IS NOT NULL AND bool_op IS NULL) OR
30         (tag IS NULL AND svf IS NULL AND bool_op IS NOT NULL)
31     )
32 );
33
34 CREATE TABLE vandelay.match_set_quality (
35     id          SERIAL  PRIMARY KEY,
36     match_set   INT     NOT NULL REFERENCES vandelay.match_set (id) ON DELETE CASCADE,
37     svf         TEXT    REFERENCES config.record_attr_definition,
38     tag         TEXT,
39     subfield    TEXT,
40     value       TEXT    NOT NULL,
41     quality     INT     NOT NULL DEFAULT 1, -- higher is better
42     CONSTRAINT vmsq_need_a_subfield_with_a_tag CHECK ((tag IS NOT NULL AND subfield IS NOT NULL) OR tag IS NULL),
43     CONSTRAINT vmsq_need_a_tag_or_a_ff CHECK ((tag IS NOT NULL AND svf IS NULL) OR (tag IS NULL AND svf IS NOT NULL))
44 );
45 CREATE UNIQUE INDEX vmsq_def_once_per_set ON vandelay.match_set_quality (match_set, COALESCE(tag,''), COALESCE(subfield,''), COALESCE(svf,''), value);
46
47
48 CREATE TABLE vandelay.queue (
49         id                              BIGSERIAL       PRIMARY KEY,
50         owner                   INT                     NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
51         name                    TEXT            NOT NULL,
52         complete                BOOL            NOT NULL DEFAULT FALSE,
53     match_set       INT         REFERENCES vandelay.match_set (id) ON UPDATE CASCADE ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED
54 );
55
56 CREATE TABLE vandelay.queued_record (
57     id                  BIGSERIAL                   PRIMARY KEY,
58     create_time TIMESTAMP WITH TIME ZONE    NOT NULL DEFAULT NOW(),
59     import_time TIMESTAMP WITH TIME ZONE,
60         purpose         TEXT                                            NOT NULL DEFAULT 'import' CHECK (purpose IN ('import','overlay')),
61     marc                TEXT                        NOT NULL,
62     quality     INT                         NOT NULL DEFAULT 0
63 );
64
65
66
67 /* Bib stuff at the top */
68 ----------------------------------------------------
69
70 CREATE TABLE vandelay.bib_attr_definition (
71         id                      SERIAL  PRIMARY KEY,
72         code            TEXT    UNIQUE NOT NULL,
73         description     TEXT,
74         xpath           TEXT    NOT NULL,
75         remove          TEXT    NOT NULL DEFAULT ''
76 );
77
78 -- Each TEXT field (other than 'name') should hold an XPath predicate for pulling the data needed
79 -- DROP TABLE vandelay.import_item_attr_definition CASCADE;
80 CREATE TABLE vandelay.import_item_attr_definition (
81     id              BIGSERIAL   PRIMARY KEY,
82     owner           INT         NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
83     name            TEXT        NOT NULL,
84     tag             TEXT        NOT NULL,
85     keep            BOOL        NOT NULL DEFAULT FALSE,
86     owning_lib      TEXT,
87     circ_lib        TEXT,
88     call_number     TEXT,
89     copy_number     TEXT,
90     status          TEXT,
91     location        TEXT,
92     circulate       TEXT,
93     deposit         TEXT,
94     deposit_amount  TEXT,
95     ref             TEXT,
96     holdable        TEXT,
97     price           TEXT,
98     barcode         TEXT,
99     circ_modifier   TEXT,
100     circ_as_type    TEXT,
101     alert_message   TEXT,
102     opac_visible    TEXT,
103     pub_note_title  TEXT,
104     pub_note        TEXT,
105     priv_note_title TEXT,
106     priv_note       TEXT,
107         CONSTRAINT vand_import_item_attr_def_idx UNIQUE (owner,name)
108 );
109
110 CREATE TABLE vandelay.import_error (
111     code        TEXT    PRIMARY KEY,
112     description TEXT    NOT NULL -- i18n
113 );
114
115 CREATE TYPE vandelay.bib_queue_queue_type AS ENUM ('bib', 'acq');
116
117 CREATE TABLE vandelay.bib_queue (
118         queue_type          vandelay.bib_queue_queue_type       NOT NULL DEFAULT 'bib',
119         item_attr_def   BIGINT REFERENCES vandelay.import_item_attr_definition (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
120         CONSTRAINT vand_bib_queue_name_once_per_owner_const UNIQUE (owner,name,queue_type)
121 ) INHERITS (vandelay.queue);
122 ALTER TABLE vandelay.bib_queue ADD PRIMARY KEY (id);
123
124 CREATE TABLE vandelay.queued_bib_record (
125         queue               INT         NOT NULL REFERENCES vandelay.bib_queue (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
126         bib_source          INT         REFERENCES config.bib_source (id) DEFERRABLE INITIALLY DEFERRED,
127         imported_as     BIGINT  REFERENCES biblio.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
128         import_error    TEXT    REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
129         error_detail    TEXT
130 ) INHERITS (vandelay.queued_record);
131 ALTER TABLE vandelay.queued_bib_record ADD PRIMARY KEY (id);
132 CREATE INDEX queued_bib_record_queue_idx ON vandelay.queued_bib_record (queue);
133
134 CREATE TABLE vandelay.queued_bib_record_attr (
135         id                      BIGSERIAL       PRIMARY KEY,
136         record          BIGINT          NOT NULL REFERENCES vandelay.queued_bib_record (id) DEFERRABLE INITIALLY DEFERRED,
137         field           INT                     NOT NULL REFERENCES vandelay.bib_attr_definition (id) DEFERRABLE INITIALLY DEFERRED,
138         attr_value      TEXT            NOT NULL
139 );
140 CREATE INDEX queued_bib_record_attr_record_idx ON vandelay.queued_bib_record_attr (record);
141
142 CREATE TABLE vandelay.bib_match (
143         id                              BIGSERIAL       PRIMARY KEY,
144         queued_record   BIGINT          REFERENCES vandelay.queued_bib_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
145         eg_record               BIGINT          REFERENCES biblio.record_entry (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
146     quality         INT         NOT NULL DEFAULT 1,
147     match_score     INT         NOT NULL DEFAULT 0
148 );
149
150 CREATE TABLE vandelay.import_item (
151     id              BIGSERIAL   PRIMARY KEY,
152     record          BIGINT      NOT NULL REFERENCES vandelay.queued_bib_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
153     definition      BIGINT      NOT NULL REFERENCES vandelay.import_item_attr_definition (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
154         import_error    TEXT        REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
155         error_detail    TEXT,
156     imported_as     BIGINT,
157     import_time     TIMESTAMP WITH TIME ZONE,
158     owning_lib      INT,
159     circ_lib        INT,
160     call_number     TEXT,
161     copy_number     INT,
162     status          INT,
163     location        INT,
164     circulate       BOOL,
165     deposit         BOOL,
166     deposit_amount  NUMERIC(8,2),
167     ref             BOOL,
168     holdable        BOOL,
169     price           NUMERIC(8,2),
170     barcode         TEXT,
171     circ_modifier   TEXT,
172     circ_as_type    TEXT,
173     alert_message   TEXT,
174     pub_note        TEXT,
175     priv_note       TEXT,
176     opac_visible    BOOL
177 );
178  
179 CREATE TABLE vandelay.import_bib_trash_fields (
180     id              BIGSERIAL   PRIMARY KEY,
181     owner           INT         NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
182     field           TEXT        NOT NULL,
183         CONSTRAINT vand_import_bib_trash_fields_idx UNIQUE (owner,field)
184 );
185
186 CREATE TABLE vandelay.merge_profile (
187     id              BIGSERIAL   PRIMARY KEY,
188     owner           INT         NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
189     name            TEXT        NOT NULL,
190     add_spec        TEXT,
191     replace_spec    TEXT,
192     strip_spec      TEXT,
193     preserve_spec   TEXT,
194     lwm_ratio       NUMERIC,
195         CONSTRAINT vand_merge_prof_owner_name_idx UNIQUE (owner,name),
196         CONSTRAINT add_replace_strip_or_preserve CHECK ((preserve_spec IS NOT NULL OR replace_spec IS NOT NULL) OR (preserve_spec IS NULL AND replace_spec IS NULL))
197 );
198
199 CREATE OR REPLACE FUNCTION vandelay.marc21_record_type( marc TEXT ) RETURNS config.marc21_rec_type_map AS $func$
200 DECLARE
201     ldr         TEXT;
202     tval        TEXT;
203     tval_rec    RECORD;
204     bval        TEXT;
205     bval_rec    RECORD;
206     retval      config.marc21_rec_type_map%ROWTYPE;
207 BEGIN
208     ldr := oils_xpath_string( '//*[local-name()="leader"]', marc );
209
210     IF ldr IS NULL OR ldr = '' THEN
211         SELECT * INTO retval FROM config.marc21_rec_type_map WHERE code = 'BKS';
212         RETURN retval;
213     END IF;
214
215     SELECT * INTO tval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'Type' LIMIT 1; -- They're all the same
216     SELECT * INTO bval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'BLvl' LIMIT 1; -- They're all the same
217
218
219     tval := SUBSTRING( ldr, tval_rec.start_pos + 1, tval_rec.length );
220     bval := SUBSTRING( ldr, bval_rec.start_pos + 1, bval_rec.length );
221
222     -- RAISE NOTICE 'type %, blvl %, ldr %', tval, bval, ldr;
223
224     SELECT * INTO retval FROM config.marc21_rec_type_map WHERE type_val LIKE '%' || tval || '%' AND blvl_val LIKE '%' || bval || '%';
225
226
227     IF retval.code IS NULL THEN
228         SELECT * INTO retval FROM config.marc21_rec_type_map WHERE code = 'BKS';
229     END IF;
230
231     RETURN retval;
232 END;
233 $func$ LANGUAGE PLPGSQL;
234
235 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_fixed_field( marc TEXT, ff TEXT ) RETURNS TEXT AS $func$
236 DECLARE
237     rtype       TEXT;
238     ff_pos      RECORD;
239     tag_data    RECORD;
240     val         TEXT;
241 BEGIN
242     rtype := (vandelay.marc21_record_type( marc )).code;
243     FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE fixed_field = ff AND rec_type = rtype ORDER BY tag DESC LOOP
244         FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(ff_pos.tag) || '"]/text()', marc ) ) x(value) LOOP
245             val := SUBSTRING( tag_data.value, ff_pos.start_pos + 1, ff_pos.length );
246             RETURN val;
247         END LOOP;
248         val := REPEAT( ff_pos.default_val, ff_pos.length );
249         RETURN val;
250     END LOOP;
251
252     RETURN NULL;
253 END;
254 $func$ LANGUAGE PLPGSQL;
255
256 CREATE TYPE biblio.record_ff_map AS (record BIGINT, ff_name TEXT, ff_value TEXT);
257 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_all_fixed_fields( marc TEXT ) RETURNS SETOF biblio.record_ff_map AS $func$
258 DECLARE
259     tag_data    TEXT;
260     rtype       TEXT;
261     ff_pos      RECORD;
262     output      biblio.record_ff_map%ROWTYPE;
263 BEGIN
264     rtype := (vandelay.marc21_record_type( marc )).code;
265
266     FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE rec_type = rtype ORDER BY tag DESC LOOP
267         output.ff_name  := ff_pos.fixed_field;
268         output.ff_value := NULL;
269
270         FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(tag) || '"]/text()', marc ) ) x(value) LOOP
271             output.ff_value := SUBSTRING( tag_data.value, ff_pos.start_pos + 1, ff_pos.length );
272             IF output.ff_value IS NULL THEN output.ff_value := REPEAT( ff_pos.default_val, ff_pos.length ); END IF;
273             RETURN NEXT output;
274             output.ff_value := NULL;
275         END LOOP;
276
277     END LOOP;
278
279     RETURN;
280 END;
281 $func$ LANGUAGE PLPGSQL;
282
283 CREATE TYPE biblio.marc21_physical_characteristics AS ( id INT, record BIGINT, ptype TEXT, subfield INT, value INT );
284 CREATE OR REPLACE FUNCTION vandelay.marc21_physical_characteristics( marc TEXT) RETURNS SETOF biblio.marc21_physical_characteristics AS $func$
285 DECLARE
286     rowid   INT := 0;
287     _007    TEXT;
288     ptype   config.marc21_physical_characteristic_type_map%ROWTYPE;
289     psf     config.marc21_physical_characteristic_subfield_map%ROWTYPE;
290     pval    config.marc21_physical_characteristic_value_map%ROWTYPE;
291     retval  biblio.marc21_physical_characteristics%ROWTYPE;
292 BEGIN
293
294     _007 := oils_xpath_string( '//*[@tag="007"]', marc );
295
296     IF _007 IS NOT NULL AND _007 <> '' THEN
297         SELECT * INTO ptype FROM config.marc21_physical_characteristic_type_map WHERE ptype_key = SUBSTRING( _007, 1, 1 );
298
299         IF ptype.ptype_key IS NOT NULL THEN
300             FOR psf IN SELECT * FROM config.marc21_physical_characteristic_subfield_map WHERE ptype_key = ptype.ptype_key LOOP
301                 SELECT * INTO pval FROM config.marc21_physical_characteristic_value_map WHERE ptype_subfield = psf.id AND value = SUBSTRING( _007, psf.start_pos + 1, psf.length );
302
303                 IF pval.id IS NOT NULL THEN
304                     rowid := rowid + 1;
305                     retval.id := rowid;
306                     retval.ptype := ptype.ptype_key;
307                     retval.subfield := psf.id;
308                     retval.value := pval.id;
309                     RETURN NEXT retval;
310                 END IF;
311
312             END LOOP;
313         END IF;
314     END IF;
315
316     RETURN;
317 END;
318 $func$ LANGUAGE PLPGSQL;
319
320 CREATE TYPE vandelay.flat_marc AS ( tag CHAR(3), ind1 TEXT, ind2 TEXT, subfield TEXT, value TEXT );
321 CREATE OR REPLACE FUNCTION vandelay.flay_marc ( TEXT ) RETURNS SETOF vandelay.flat_marc AS $func$
322
323 use MARC::Record;
324 use MARC::File::XML (BinaryEncoding => 'UTF-8');
325 use MARC::Charset;
326 use strict;
327
328 MARC::Charset->assume_unicode(1);
329
330 my $xml = shift;
331 my $r = MARC::Record->new_from_xml( $xml );
332
333 return_next( { tag => 'LDR', value => $r->leader } );
334
335 for my $f ( $r->fields ) {
336     if ($f->is_control_field) {
337         return_next({ tag => $f->tag, value => $f->data });
338     } else {
339         for my $s ($f->subfields) {
340             return_next({
341                 tag      => $f->tag,
342                 ind1     => $f->indicator(1),
343                 ind2     => $f->indicator(2),
344                 subfield => $s->[0],
345                 value    => $s->[1]
346             });
347
348             if ( $f->tag eq '245' and $s->[0] eq 'a' ) {
349                 my $trim = $f->indicator(2) || 0;
350                 return_next({
351                     tag      => 'tnf',
352                     ind1     => $f->indicator(1),
353                     ind2     => $f->indicator(2),
354                     subfield => 'a',
355                     value    => substr( $s->[1], $trim )
356                 });
357             }
358         }
359     }
360 }
361
362 return undef;
363
364 $func$ LANGUAGE PLPERLU;
365
366 CREATE OR REPLACE FUNCTION vandelay.flatten_marc ( marc TEXT ) RETURNS SETOF vandelay.flat_marc AS $func$
367 DECLARE
368     output  vandelay.flat_marc%ROWTYPE;
369     field   RECORD;
370 BEGIN
371     FOR field IN SELECT * FROM vandelay.flay_marc( marc ) LOOP
372         output.ind1 := field.ind1;
373         output.ind2 := field.ind2;
374         output.tag := field.tag;
375         output.subfield := field.subfield;
376         IF field.subfield IS NOT NULL AND field.tag NOT IN ('020','022','024') THEN -- exclude standard numbers and control fields
377             output.value := naco_normalize(field.value, field.subfield);
378         ELSE
379             output.value := field.value;
380         END IF;
381
382         CONTINUE WHEN output.value IS NULL;
383
384         RETURN NEXT output;
385     END LOOP;
386 END;
387 $func$ LANGUAGE PLPGSQL;
388
389 CREATE OR REPLACE FUNCTION vandelay.extract_rec_attrs ( xml TEXT, attr_defs TEXT[]) RETURNS hstore AS $_$
390 DECLARE
391     transformed_xml TEXT;
392     prev_xfrm       TEXT;
393     normalizer      RECORD;
394     xfrm            config.xml_transform%ROWTYPE;
395     attr_value      TEXT;
396     new_attrs       HSTORE := ''::HSTORE;
397     attr_def        config.record_attr_definition%ROWTYPE;
398 BEGIN
399
400     FOR attr_def IN SELECT * FROM config.record_attr_definition WHERE name IN (SELECT * FROM UNNEST(attr_defs)) ORDER BY format LOOP
401
402         IF attr_def.tag IS NOT NULL THEN -- tag (and optional subfield list) selection
403             SELECT  ARRAY_TO_STRING(ARRAY_ACCUM(x.value), COALESCE(attr_def.joiner,' ')) INTO attr_value
404               FROM  vandelay.flatten_marc(xml) AS x
405               WHERE x.tag LIKE attr_def.tag
406                     AND CASE
407                         WHEN attr_def.sf_list IS NOT NULL
408                             THEN POSITION(x.subfield IN attr_def.sf_list) > 0
409                         ELSE TRUE
410                         END
411               GROUP BY x.tag
412               ORDER BY x.tag
413               LIMIT 1;
414
415         ELSIF attr_def.fixed_field IS NOT NULL THEN -- a named fixed field, see config.marc21_ff_pos_map.fixed_field
416             attr_value := vandelay.marc21_extract_fixed_field(xml, attr_def.fixed_field);
417
418         ELSIF attr_def.xpath IS NOT NULL THEN -- and xpath expression
419
420             SELECT INTO xfrm * FROM config.xml_transform WHERE name = attr_def.format;
421
422             -- See if we can skip the XSLT ... it's expensive
423             IF prev_xfrm IS NULL OR prev_xfrm <> xfrm.name THEN
424                 -- Can't skip the transform
425                 IF xfrm.xslt <> '---' THEN
426                     transformed_xml := oils_xslt_process(xml,xfrm.xslt);
427                 ELSE
428                     transformed_xml := xml;
429                 END IF;
430
431                 prev_xfrm := xfrm.name;
432             END IF;
433
434             IF xfrm.name IS NULL THEN
435                 -- just grab the marcxml (empty) transform
436                 SELECT INTO xfrm * FROM config.xml_transform WHERE xslt = '---' LIMIT 1;
437                 prev_xfrm := xfrm.name;
438             END IF;
439
440             attr_value := oils_xpath_string(attr_def.xpath, transformed_xml, COALESCE(attr_def.joiner,' '), ARRAY[ARRAY[xfrm.prefix, xfrm.namespace_uri]]);
441
442         ELSIF attr_def.phys_char_sf IS NOT NULL THEN -- a named Physical Characteristic, see config.marc21_physical_characteristic_*_map
443             SELECT  m.value::TEXT INTO attr_value
444               FROM  vandelay.marc21_physical_characteristics(xml) v
445                     JOIN config.marc21_physical_characteristic_value_map m ON (m.id = v.value)
446               WHERE v.subfield = attr_def.phys_char_sf
447               LIMIT 1; -- Just in case ...
448
449         END IF;
450
451         -- apply index normalizers to attr_value
452         FOR normalizer IN
453             SELECT  n.func AS func,
454                     n.param_count AS param_count,
455                     m.params AS params
456               FROM  config.index_normalizer n
457                     JOIN config.record_attr_index_norm_map m ON (m.norm = n.id)
458               WHERE attr = attr_def.name
459               ORDER BY m.pos LOOP
460                 EXECUTE 'SELECT ' || normalizer.func || '(' ||
461                     quote_literal( attr_value ) ||
462                     CASE
463                         WHEN normalizer.param_count > 0
464                             THEN ',' || REPLACE(REPLACE(BTRIM(normalizer.params,'[]'),E'\'',E'\\\''),E'"',E'\'')
465                             ELSE ''
466                         END ||
467                     ')' INTO attr_value;
468
469         END LOOP;
470
471         -- Add the new value to the hstore
472         new_attrs := new_attrs || hstore( attr_def.name, attr_value );
473
474     END LOOP;
475
476     RETURN new_attrs;
477 END;
478 $_$ LANGUAGE PLPGSQL;
479
480 CREATE OR REPLACE FUNCTION vandelay.extract_rec_attrs ( xml TEXT ) RETURNS hstore AS $_$
481     SELECT vandelay.extract_rec_attrs( $1, (SELECT ARRAY_ACCUM(name) FROM config.record_attr_definition));
482 $_$ LANGUAGE SQL;
483
484 -- Everything between this comment and the beginning of the definition of
485 -- vandelay.match_bib_record() is strictly in service of that function.
486 CREATE TYPE vandelay.match_set_test_result AS (record BIGINT, quality INTEGER);
487
488 CREATE OR REPLACE FUNCTION vandelay.match_set_test_marcxml(
489     match_set_id INTEGER, record_xml TEXT
490 ) RETURNS SETOF vandelay.match_set_test_result AS $$
491 DECLARE
492     tags_rstore HSTORE;
493     svf_rstore  HSTORE;
494     coal        TEXT;
495     joins       TEXT;
496     query_      TEXT;
497     wq          TEXT;
498     qvalue      INTEGER;
499     rec         RECORD;
500 BEGIN
501     tags_rstore := vandelay.flatten_marc_hstore(record_xml);
502     svf_rstore := vandelay.extract_rec_attrs(record_xml);
503
504     CREATE TEMPORARY TABLE _vandelay_tmp_qrows (q INTEGER);
505     CREATE TEMPORARY TABLE _vandelay_tmp_jrows (j TEXT);
506
507     -- generate the where clause and return that directly (into wq), and as
508     -- a side-effect, populate the _vandelay_tmp_[qj]rows tables.
509     wq := vandelay.get_expr_from_match_set(match_set_id);
510
511     query_ := 'SELECT DISTINCT(bre.id) AS record, ';
512
513     -- qrows table is for the quality bits we add to the SELECT clause
514     SELECT ARRAY_TO_STRING(
515         ARRAY_ACCUM('COALESCE(n' || q::TEXT || '.quality, 0)'), ' + '
516     ) INTO coal FROM _vandelay_tmp_qrows;
517
518     -- our query string so far is the SELECT clause and the inital FROM.
519     -- no JOINs yet nor the WHERE clause
520     query_ := query_ || coal || ' AS quality ' || E'\n' ||
521         'FROM biblio.record_entry bre ';
522
523     -- jrows table is for the joins we must make (and the real text conditions)
524     SELECT ARRAY_TO_STRING(ARRAY_ACCUM(j), E'\n') INTO joins
525         FROM _vandelay_tmp_jrows;
526
527     -- add those joins and the where clause to our query.
528     query_ := query_ || joins || E'\n' || 'WHERE ' || wq || ' AND not bre.deleted';
529
530     -- this will return rows of record,quality
531     FOR rec IN EXECUTE query_ USING tags_rstore, svf_rstore LOOP
532         RETURN NEXT rec;
533     END LOOP;
534
535     DROP TABLE _vandelay_tmp_qrows;
536     DROP TABLE _vandelay_tmp_jrows;
537     RETURN;
538 END;
539
540 $$ LANGUAGE PLPGSQL;
541
542 CREATE OR REPLACE FUNCTION vandelay.flatten_marc_hstore(
543     record_xml TEXT
544 ) RETURNS HSTORE AS $func$
545 BEGIN
546     RETURN (SELECT
547         HSTORE(
548             ARRAY_ACCUM(tag || (COALESCE(subfield, ''))),
549             ARRAY_ACCUM(value)
550         )
551         FROM (
552             SELECT  tag, subfield, ARRAY_ACCUM(value)::TEXT AS value
553               FROM  (SELECT tag,
554                             subfield,
555                             CASE WHEN tag = '020' THEN -- caseless -- isbn
556                                 LOWER((REGEXP_MATCHES(value,$$^(\S{10,17})$$))[1] || '%')
557                             WHEN tag = '022' THEN -- caseless -- issn
558                                 LOWER((REGEXP_MATCHES(value,$$^(\S{4}[- ]?\S{4})$$))[1] || '%')
559                             WHEN tag = '024' THEN -- caseless -- upc (other)
560                                 LOWER(value || '%')
561                             ELSE
562                                 value
563                             END AS value
564                       FROM  vandelay.flatten_marc(record_xml)) x
565                 GROUP BY tag, subfield ORDER BY tag, subfield
566         ) subquery
567     );
568 END;
569 $func$ LANGUAGE PLPGSQL;
570
571 CREATE OR REPLACE FUNCTION vandelay.get_expr_from_match_set(
572     match_set_id INTEGER
573 ) RETURNS TEXT AS $$
574 DECLARE
575     root    vandelay.match_set_point;
576 BEGIN
577     SELECT * INTO root FROM vandelay.match_set_point
578         WHERE parent IS NULL AND match_set = match_set_id;
579
580     RETURN vandelay.get_expr_from_match_set_point(root);
581 END;
582 $$  LANGUAGE PLPGSQL;
583
584 CREATE OR REPLACE FUNCTION vandelay.get_expr_from_match_set_point(
585     node vandelay.match_set_point
586 ) RETURNS TEXT AS $$
587 DECLARE
588     q           TEXT;
589     i           INTEGER;
590     this_op     TEXT;
591     children    INTEGER[];
592     child       vandelay.match_set_point;
593 BEGIN
594     SELECT ARRAY_ACCUM(id) INTO children FROM vandelay.match_set_point
595         WHERE parent = node.id;
596
597     IF ARRAY_LENGTH(children, 1) > 0 THEN
598         this_op := vandelay._get_expr_render_one(node);
599         q := '(';
600         i := 1;
601         WHILE children[i] IS NOT NULL LOOP
602             SELECT * INTO child FROM vandelay.match_set_point
603                 WHERE id = children[i];
604             IF i > 1 THEN
605                 q := q || ' ' || this_op || ' ';
606             END IF;
607             i := i + 1;
608             q := q || vandelay.get_expr_from_match_set_point(child);
609         END LOOP;
610         q := q || ')';
611         RETURN q;
612     ELSIF node.bool_op IS NULL THEN
613         PERFORM vandelay._get_expr_push_qrow(node);
614         PERFORM vandelay._get_expr_push_jrow(node);
615         RETURN vandelay._get_expr_render_one(node);
616     ELSE
617         RETURN '';
618     END IF;
619 END;
620 $$  LANGUAGE PLPGSQL;
621
622 CREATE OR REPLACE FUNCTION vandelay._get_expr_push_qrow(
623     node vandelay.match_set_point
624 ) RETURNS VOID AS $$
625 DECLARE
626 BEGIN
627     INSERT INTO _vandelay_tmp_qrows (q) VALUES (node.id);
628 END;
629 $$ LANGUAGE PLPGSQL;
630
631 CREATE OR REPLACE FUNCTION vandelay._get_expr_push_jrow(
632     node vandelay.match_set_point
633 ) RETURNS VOID AS $$
634 DECLARE
635     jrow        TEXT;
636     my_alias    TEXT;
637     op          TEXT;
638     tagkey      TEXT;
639     caseless    BOOL;
640 BEGIN
641     -- remember $1 is tags_rstore, and $2 is svf_rstore
642
643     caseless := FALSE;
644
645     IF node.tag IS NOT NULL THEN
646         caseless := (node.tag IN ('020', '022', '024'));
647         tagkey := node.tag;
648         IF node.subfield IS NOT NULL THEN
649             tagkey := tagkey || node.subfield;
650         END IF;
651     END IF;
652
653     IF node.negate THEN
654         IF caseless THEN
655             op := 'NOT LIKE';
656         ELSE
657             op := '<>';
658         END IF;
659     ELSE
660         IF caseless THEN
661             op := 'LIKE';
662         ELSE
663             op := '=';
664         END IF;
665     END IF;
666
667     my_alias := 'n' || node.id::TEXT;
668
669     jrow := 'LEFT JOIN (SELECT *, ' || node.quality ||
670         ' AS quality FROM metabib.';
671     IF node.tag IS NOT NULL THEN
672         jrow := jrow || 'full_rec) ' || my_alias || ' ON (' ||
673             my_alias || '.record = bre.id AND ' || my_alias || '.tag = ''' ||
674             node.tag || '''';
675         IF node.subfield IS NOT NULL THEN
676             jrow := jrow || ' AND ' || my_alias || '.subfield = ''' ||
677                 node.subfield || '''';
678         END IF;
679         jrow := jrow || ' AND (';
680
681         IF caseless THEN
682             jrow := jrow || 'LOWER(' || my_alias || '.value) ' || op;
683         ELSE
684             jrow := jrow || my_alias || '.value ' || op;
685         END IF;
686
687         jrow := jrow || ' ANY(($1->''' || tagkey || ''')::TEXT[])))';
688     ELSE    -- svf
689         jrow := jrow || 'record_attr) ' || my_alias || ' ON (' ||
690             my_alias || '.id = bre.id AND (' ||
691             my_alias || '.attrs->''' || node.svf ||
692             ''' ' || op || ' $2->''' || node.svf || '''))';
693     END IF;
694     INSERT INTO _vandelay_tmp_jrows (j) VALUES (jrow);
695 END;
696 $$ LANGUAGE PLPGSQL;
697
698 CREATE OR REPLACE FUNCTION vandelay._get_expr_render_one(
699     node vandelay.match_set_point
700 ) RETURNS TEXT AS $$
701 DECLARE
702     s           TEXT;
703 BEGIN
704     IF node.bool_op IS NOT NULL THEN
705         RETURN node.bool_op;
706     ELSE
707         RETURN '(n' || node.id::TEXT || '.id IS NOT NULL)';
708     END IF;
709 END;
710 $$ LANGUAGE PLPGSQL;
711
712 CREATE OR REPLACE FUNCTION vandelay.match_bib_record() RETURNS TRIGGER AS $func$
713 DECLARE
714     incoming_existing_id    TEXT;
715     test_result             vandelay.match_set_test_result%ROWTYPE;
716     tmp_rec                 BIGINT;
717     match_set               INT;
718 BEGIN
719     IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
720         RETURN NEW;
721     END IF;
722
723     DELETE FROM vandelay.bib_match WHERE queued_record = NEW.id;
724
725     SELECT q.match_set INTO match_set FROM vandelay.bib_queue q WHERE q.id = NEW.queue;
726
727     IF match_set IS NOT NULL THEN
728         NEW.quality := vandelay.measure_record_quality( NEW.marc, match_set );
729     END IF;
730
731     -- Perfect matches on 901$c exit early with a match with high quality.
732     incoming_existing_id :=
733         oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]', NEW.marc);
734
735     IF incoming_existing_id IS NOT NULL AND incoming_existing_id != '' THEN
736         SELECT id INTO tmp_rec FROM biblio.record_entry WHERE id = incoming_existing_id::bigint;
737         IF tmp_rec IS NOT NULL THEN
738             INSERT INTO vandelay.bib_match (queued_record, eg_record, match_score, quality) 
739                 SELECT
740                     NEW.id, 
741                     b.id,
742                     9999,
743                     -- note: no match_set means quality==0
744                     vandelay.measure_record_quality( b.marc, match_set )
745                 FROM biblio.record_entry b
746                 WHERE id = incoming_existing_id::bigint;
747         END IF;
748     END IF;
749
750     IF match_set IS NULL THEN
751         RETURN NEW;
752     END IF;
753
754     FOR test_result IN SELECT * FROM
755         vandelay.match_set_test_marcxml(match_set, NEW.marc) LOOP
756
757         INSERT INTO vandelay.bib_match ( queued_record, eg_record, match_score, quality )
758             SELECT  
759                 NEW.id,
760                 test_result.record,
761                 test_result.quality,
762                 vandelay.measure_record_quality( b.marc, match_set )
763                 FROM  biblio.record_entry b
764                 WHERE id = test_result.record;
765
766     END LOOP;
767
768     RETURN NEW;
769 END;
770 $func$ LANGUAGE PLPGSQL;
771
772 CREATE OR REPLACE FUNCTION vandelay.measure_record_quality ( xml TEXT, match_set_id INT ) RETURNS INT AS $_$
773 DECLARE
774     out_q   INT := 0;
775     rvalue  TEXT;
776     test    vandelay.match_set_quality%ROWTYPE;
777 BEGIN
778
779     FOR test IN SELECT * FROM vandelay.match_set_quality WHERE match_set = match_set_id LOOP
780         IF test.tag IS NOT NULL THEN
781             FOR rvalue IN SELECT value FROM vandelay.flatten_marc( xml ) WHERE tag = test.tag AND subfield = test.subfield LOOP
782                 IF test.value = rvalue THEN
783                     out_q := out_q + test.quality;
784                 END IF;
785             END LOOP;
786         ELSE
787             IF test.value = vandelay.extract_rec_attrs(xml, ARRAY[test.svf]) -> test.svf THEN
788                 out_q := out_q + test.quality;
789             END IF;
790         END IF;
791     END LOOP;
792
793     RETURN out_q;
794 END;
795 $_$ LANGUAGE PLPGSQL;
796
797 CREATE TYPE vandelay.tcn_data AS (tcn TEXT, tcn_source TEXT, used BOOL);
798 CREATE OR REPLACE FUNCTION vandelay.find_bib_tcn_data ( xml TEXT ) RETURNS SETOF vandelay.tcn_data AS $_$
799 DECLARE
800     eg_tcn          TEXT;
801     eg_tcn_source   TEXT;
802     output          vandelay.tcn_data%ROWTYPE;
803 BEGIN
804
805     -- 001/003
806     eg_tcn := BTRIM((oils_xpath('//*[@tag="001"]/text()',xml))[1]);
807     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
808
809         eg_tcn_source := BTRIM((oils_xpath('//*[@tag="003"]/text()',xml))[1]);
810         IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
811             eg_tcn_source := 'System Local';
812         END IF;
813
814         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
815
816         IF NOT FOUND THEN
817             output.used := FALSE;
818         ELSE
819             output.used := TRUE;
820         END IF;
821
822         output.tcn := eg_tcn;
823         output.tcn_source := eg_tcn_source;
824         RETURN NEXT output;
825
826     END IF;
827
828     -- 901 ab
829     eg_tcn := BTRIM((oils_xpath('//*[@tag="901"]/*[@code="a"]/text()',xml))[1]);
830     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
831
832         eg_tcn_source := BTRIM((oils_xpath('//*[@tag="901"]/*[@code="b"]/text()',xml))[1]);
833         IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
834             eg_tcn_source := 'System Local';
835         END IF;
836
837         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
838
839         IF NOT FOUND THEN
840             output.used := FALSE;
841         ELSE
842             output.used := TRUE;
843         END IF;
844
845         output.tcn := eg_tcn;
846         output.tcn_source := eg_tcn_source;
847         RETURN NEXT output;
848
849     END IF;
850
851     -- 039 ab
852     eg_tcn := BTRIM((oils_xpath('//*[@tag="039"]/*[@code="a"]/text()',xml))[1]);
853     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
854
855         eg_tcn_source := BTRIM((oils_xpath('//*[@tag="039"]/*[@code="b"]/text()',xml))[1]);
856         IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
857             eg_tcn_source := 'System Local';
858         END IF;
859
860         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
861
862         IF NOT FOUND THEN
863             output.used := FALSE;
864         ELSE
865             output.used := TRUE;
866         END IF;
867
868         output.tcn := eg_tcn;
869         output.tcn_source := eg_tcn_source;
870         RETURN NEXT output;
871
872     END IF;
873
874     -- 020 a
875     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="020"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
876     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
877
878         eg_tcn_source := 'ISBN';
879
880         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
881
882         IF NOT FOUND THEN
883             output.used := FALSE;
884         ELSE
885             output.used := TRUE;
886         END IF;
887
888         output.tcn := eg_tcn;
889         output.tcn_source := eg_tcn_source;
890         RETURN NEXT output;
891
892     END IF;
893
894     -- 022 a
895     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="022"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
896     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
897
898         eg_tcn_source := 'ISSN';
899
900         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
901
902         IF NOT FOUND THEN
903             output.used := FALSE;
904         ELSE
905             output.used := TRUE;
906         END IF;
907
908         output.tcn := eg_tcn;
909         output.tcn_source := eg_tcn_source;
910         RETURN NEXT output;
911
912     END IF;
913
914     -- 010 a
915     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="010"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
916     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
917
918         eg_tcn_source := 'LCCN';
919
920         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
921
922         IF NOT FOUND THEN
923             output.used := FALSE;
924         ELSE
925             output.used := TRUE;
926         END IF;
927
928         output.tcn := eg_tcn;
929         output.tcn_source := eg_tcn_source;
930         RETURN NEXT output;
931
932     END IF;
933
934     -- 035 a
935     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="035"]/*[@code="a"]/text()',xml))[1], $re$^.*?(\w+)$$re$, $re$\1$re$);
936     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
937
938         eg_tcn_source := 'System Legacy';
939
940         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
941
942         IF NOT FOUND THEN
943             output.used := FALSE;
944         ELSE
945             output.used := TRUE;
946         END IF;
947
948         output.tcn := eg_tcn;
949         output.tcn_source := eg_tcn_source;
950         RETURN NEXT output;
951
952     END IF;
953
954     RETURN;
955 END;
956 $_$ LANGUAGE PLPGSQL;
957
958 CREATE OR REPLACE FUNCTION vandelay.add_field ( target_xml TEXT, source_xml TEXT, field TEXT, force_add INT ) RETURNS TEXT AS $_$
959
960     use MARC::Record;
961     use MARC::File::XML (BinaryEncoding => 'UTF-8');
962     use MARC::Charset;
963     use strict;
964
965     MARC::Charset->assume_unicode(1);
966
967     my $target_xml = shift;
968     my $source_xml = shift;
969     my $field_spec = shift;
970     my $force_add = shift || 0;
971
972     my $target_r = MARC::Record->new_from_xml( $target_xml );
973     my $source_r = MARC::Record->new_from_xml( $source_xml );
974
975     return $target_xml unless ($target_r && $source_r);
976
977     my @field_list = split(',', $field_spec);
978
979     my %fields;
980     for my $f (@field_list) {
981         $f =~ s/^\s*//; $f =~ s/\s*$//;
982         if ($f =~ /^(.{3})(\w*)(?:\[([^]]*)\])?$/) {
983             my $field = $1;
984             $field =~ s/\s+//;
985             my $sf = $2;
986             $sf =~ s/\s+//;
987             my $match = $3;
988             $match =~ s/^\s*//; $match =~ s/\s*$//;
989             $fields{$field} = { sf => [ split('', $sf) ] };
990             if ($match) {
991                 my ($msf,$mre) = split('~', $match);
992                 if (length($msf) > 0 and length($mre) > 0) {
993                     $msf =~ s/^\s*//; $msf =~ s/\s*$//;
994                     $mre =~ s/^\s*//; $mre =~ s/\s*$//;
995                     $fields{$field}{match} = { sf => $msf, re => qr/$mre/ };
996                 }
997             }
998         }
999     }
1000
1001     for my $f ( keys %fields) {
1002         if ( @{$fields{$f}{sf}} ) {
1003             for my $from_field ($source_r->field( $f )) {
1004                 my @tos = $target_r->field( $f );
1005                 if (!@tos) {
1006                     next if (exists($fields{$f}{match}) and !$force_add);
1007                     my @new_fields = map { $_->clone } $source_r->field( $f );
1008                     $target_r->insert_fields_ordered( @new_fields );
1009                 } else {
1010                     for my $to_field (@tos) {
1011                         if (exists($fields{$f}{match})) {
1012                             next unless (grep { $_ =~ $fields{$f}{match}{re} } $to_field->subfield($fields{$f}{match}{sf}));
1013                         }
1014                         my @new_sf = map { ($_ => $from_field->subfield($_)) } grep { defined($from_field->subfield($_)) } @{$fields{$f}{sf}};
1015                         $to_field->add_subfields( @new_sf );
1016                     }
1017                 }
1018             }
1019         } else {
1020             my @new_fields = map { $_->clone } $source_r->field( $f );
1021             $target_r->insert_fields_ordered( @new_fields );
1022         }
1023     }
1024
1025     $target_xml = $target_r->as_xml_record;
1026     $target_xml =~ s/^<\?.+?\?>$//mo;
1027     $target_xml =~ s/\n//sgo;
1028     $target_xml =~ s/>\s+</></sgo;
1029
1030     return $target_xml;
1031
1032 $_$ LANGUAGE PLPERLU;
1033
1034 CREATE OR REPLACE FUNCTION vandelay.add_field ( target_xml TEXT, source_xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1035     SELECT vandelay.add_field( $1, $2, $3, 0 );
1036 $_$ LANGUAGE SQL;
1037
1038 CREATE OR REPLACE FUNCTION vandelay.strip_field ( xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1039
1040     use MARC::Record;
1041     use MARC::File::XML (BinaryEncoding => 'UTF-8');
1042     use MARC::Charset;
1043     use strict;
1044
1045     MARC::Charset->assume_unicode(1);
1046
1047     my $xml = shift;
1048     my $r = MARC::Record->new_from_xml( $xml );
1049
1050     return $xml unless ($r);
1051
1052     my $field_spec = shift;
1053     my @field_list = split(',', $field_spec);
1054
1055     my %fields;
1056     for my $f (@field_list) {
1057         $f =~ s/^\s*//; $f =~ s/\s*$//;
1058         if ($f =~ /^(.{3})(\w*)(?:\[([^]]*)\])?$/) {
1059             my $field = $1;
1060             $field =~ s/\s+//;
1061             my $sf = $2;
1062             $sf =~ s/\s+//;
1063             my $match = $3;
1064             $match =~ s/^\s*//; $match =~ s/\s*$//;
1065             $fields{$field} = { sf => [ split('', $sf) ] };
1066             if ($match) {
1067                 my ($msf,$mre) = split('~', $match);
1068                 if (length($msf) > 0 and length($mre) > 0) {
1069                     $msf =~ s/^\s*//; $msf =~ s/\s*$//;
1070                     $mre =~ s/^\s*//; $mre =~ s/\s*$//;
1071                     $fields{$field}{match} = { sf => $msf, re => qr/$mre/ };
1072                 }
1073             }
1074         }
1075     }
1076
1077     for my $f ( keys %fields) {
1078         for my $to_field ($r->field( $f )) {
1079             if (exists($fields{$f}{match})) {
1080                 next unless (grep { $_ =~ $fields{$f}{match}{re} } $to_field->subfield($fields{$f}{match}{sf}));
1081             }
1082
1083             if ( @{$fields{$f}{sf}} ) {
1084                 $to_field->delete_subfield(code => $fields{$f}{sf});
1085             } else {
1086                 $r->delete_field( $to_field );
1087             }
1088         }
1089     }
1090
1091     $xml = $r->as_xml_record;
1092     $xml =~ s/^<\?.+?\?>$//mo;
1093     $xml =~ s/\n//sgo;
1094     $xml =~ s/>\s+</></sgo;
1095
1096     return $xml;
1097
1098 $_$ LANGUAGE PLPERLU;
1099
1100 CREATE OR REPLACE FUNCTION vandelay.replace_field ( target_xml TEXT, source_xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1101 DECLARE
1102     xml_output TEXT;
1103     parsed_target TEXT;
1104     curr_field TEXT;
1105 BEGIN
1106
1107     parsed_target := vandelay.strip_field( target_xml, ''); -- this dance normalizes the format of the xml for the IF below
1108     xml_output := parsed_target; -- if there are no replace rules, just return the input
1109
1110     FOR curr_field IN SELECT UNNEST( STRING_TO_ARRAY(field, ',') ) LOOP -- naive split, but it's the same we use in the perl
1111
1112         xml_output := vandelay.strip_field( parsed_target, curr_field);
1113
1114         IF xml_output <> parsed_target  AND curr_field ~ E'~' THEN
1115             -- we removed something, and there was a regexp restriction in the curr_field definition, so proceed
1116             xml_output := vandelay.add_field( xml_output, source_xml, curr_field, 1 );
1117         ELSIF curr_field !~ E'~' THEN
1118             -- No regexp restriction, add the curr_field
1119             xml_output := vandelay.add_field( xml_output, source_xml, curr_field, 0 );
1120         END IF;
1121
1122         parsed_target := xml_output; -- in prep for any following loop iterations
1123
1124     END LOOP;
1125
1126     RETURN xml_output;
1127 END;
1128 $_$ LANGUAGE PLPGSQL;
1129
1130 CREATE OR REPLACE FUNCTION vandelay.merge_record_xml ( target_xml TEXT, source_xml TEXT, add_rule TEXT, replace_preserve_rule TEXT, strip_rule TEXT ) RETURNS TEXT AS $_$
1131     SELECT vandelay.replace_field( vandelay.add_field( vandelay.strip_field( $1, $5) , $2, $3 ), $2, $4);
1132 $_$ LANGUAGE SQL;
1133
1134 CREATE TYPE vandelay.compile_profile AS (add_rule TEXT, replace_rule TEXT, preserve_rule TEXT, strip_rule TEXT);
1135 CREATE OR REPLACE FUNCTION vandelay.compile_profile ( incoming_xml TEXT ) RETURNS vandelay.compile_profile AS $_$
1136 DECLARE
1137     output              vandelay.compile_profile%ROWTYPE;
1138     profile             vandelay.merge_profile%ROWTYPE;
1139     profile_tmpl        TEXT;
1140     profile_tmpl_owner  TEXT;
1141     add_rule            TEXT := '';
1142     strip_rule          TEXT := '';
1143     replace_rule        TEXT := '';
1144     preserve_rule       TEXT := '';
1145
1146 BEGIN
1147
1148     profile_tmpl := (oils_xpath('//*[@tag="905"]/*[@code="t"]/text()',incoming_xml))[1];
1149     profile_tmpl_owner := (oils_xpath('//*[@tag="905"]/*[@code="o"]/text()',incoming_xml))[1];
1150
1151     IF profile_tmpl IS NOT NULL AND profile_tmpl <> '' AND profile_tmpl_owner IS NOT NULL AND profile_tmpl_owner <> '' THEN
1152         SELECT  p.* INTO profile
1153           FROM  vandelay.merge_profile p
1154                 JOIN actor.org_unit u ON (u.id = p.owner)
1155           WHERE p.name = profile_tmpl
1156                 AND u.shortname = profile_tmpl_owner;
1157
1158         IF profile.id IS NOT NULL THEN
1159             add_rule := COALESCE(profile.add_spec,'');
1160             strip_rule := COALESCE(profile.strip_spec,'');
1161             replace_rule := COALESCE(profile.replace_spec,'');
1162             preserve_rule := COALESCE(profile.preserve_spec,'');
1163         END IF;
1164     END IF;
1165
1166     add_rule := add_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="a"]/text()',incoming_xml),','),'');
1167     strip_rule := strip_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="d"]/text()',incoming_xml),','),'');
1168     replace_rule := replace_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="r"]/text()',incoming_xml),','),'');
1169     preserve_rule := preserve_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="p"]/text()',incoming_xml),','),'');
1170
1171     output.add_rule := BTRIM(add_rule,',');
1172     output.replace_rule := BTRIM(replace_rule,',');
1173     output.strip_rule := BTRIM(strip_rule,',');
1174     output.preserve_rule := BTRIM(preserve_rule,',');
1175
1176     RETURN output;
1177 END;
1178 $_$ LANGUAGE PLPGSQL;
1179
1180 CREATE OR REPLACE FUNCTION vandelay.template_overlay_bib_record ( v_marc TEXT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1181 DECLARE
1182     merge_profile   vandelay.merge_profile%ROWTYPE;
1183     dyn_profile     vandelay.compile_profile%ROWTYPE;
1184     editor_string   TEXT;
1185     editor_id       INT;
1186     source_marc     TEXT;
1187     target_marc     TEXT;
1188     eg_marc         TEXT;
1189     replace_rule    TEXT;
1190     match_count     INT;
1191 BEGIN
1192
1193     SELECT  b.marc INTO eg_marc
1194       FROM  biblio.record_entry b
1195       WHERE b.id = eg_id
1196       LIMIT 1;
1197
1198     IF eg_marc IS NULL OR v_marc IS NULL THEN
1199         -- RAISE NOTICE 'no marc for template or bib record';
1200         RETURN FALSE;
1201     END IF;
1202
1203     dyn_profile := vandelay.compile_profile( v_marc );
1204
1205     IF merge_profile_id IS NOT NULL THEN
1206         SELECT * INTO merge_profile FROM vandelay.merge_profile WHERE id = merge_profile_id;
1207         IF FOUND THEN
1208             dyn_profile.add_rule := BTRIM( dyn_profile.add_rule || ',' || COALESCE(merge_profile.add_spec,''), ',');
1209             dyn_profile.strip_rule := BTRIM( dyn_profile.strip_rule || ',' || COALESCE(merge_profile.strip_spec,''), ',');
1210             dyn_profile.replace_rule := BTRIM( dyn_profile.replace_rule || ',' || COALESCE(merge_profile.replace_spec,''), ',');
1211             dyn_profile.preserve_rule := BTRIM( dyn_profile.preserve_rule || ',' || COALESCE(merge_profile.preserve_spec,''), ',');
1212         END IF;
1213     END IF;
1214
1215     IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1216         -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1217         RETURN FALSE;
1218     END IF;
1219
1220     IF dyn_profile.replace_rule <> '' THEN
1221         source_marc = v_marc;
1222         target_marc = eg_marc;
1223         replace_rule = dyn_profile.replace_rule;
1224     ELSE
1225         source_marc = eg_marc;
1226         target_marc = v_marc;
1227         replace_rule = dyn_profile.preserve_rule;
1228     END IF;
1229
1230     UPDATE  biblio.record_entry
1231       SET   marc = vandelay.merge_record_xml( target_marc, source_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule )
1232       WHERE id = eg_id;
1233
1234     IF NOT FOUND THEN
1235         -- RAISE NOTICE 'update of biblio.record_entry failed';
1236         RETURN FALSE;
1237     END IF;
1238
1239     RETURN TRUE;
1240
1241 END;
1242 $$ LANGUAGE PLPGSQL;
1243
1244 CREATE OR REPLACE FUNCTION vandelay.merge_record_xml ( target_marc TEXT, template_marc TEXT ) RETURNS TEXT AS $$
1245 DECLARE
1246     dyn_profile     vandelay.compile_profile%ROWTYPE;
1247     replace_rule    TEXT;
1248     tmp_marc        TEXT;
1249     trgt_marc        TEXT;
1250     tmpl_marc        TEXT;
1251     match_count     INT;
1252 BEGIN
1253
1254     IF target_marc IS NULL OR template_marc IS NULL THEN
1255         -- RAISE NOTICE 'no marc for target or template record';
1256         RETURN NULL;
1257     END IF;
1258
1259     dyn_profile := vandelay.compile_profile( template_marc );
1260
1261     IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1262         -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1263         RETURN NULL;
1264     END IF;
1265
1266     IF dyn_profile.replace_rule <> '' THEN
1267         trgt_marc = target_marc;
1268         tmpl_marc = template_marc;
1269         replace_rule = dyn_profile.replace_rule;
1270     ELSE
1271         tmp_marc = target_marc;
1272         trgt_marc = template_marc;
1273         tmpl_marc = tmp_marc;
1274         replace_rule = dyn_profile.preserve_rule;
1275     END IF;
1276
1277     RETURN vandelay.merge_record_xml( trgt_marc, tmpl_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule );
1278
1279 END;
1280 $$ LANGUAGE PLPGSQL;
1281
1282 CREATE OR REPLACE FUNCTION vandelay.template_overlay_bib_record ( v_marc TEXT, eg_id BIGINT) RETURNS BOOL AS $$
1283     SELECT vandelay.template_overlay_bib_record( $1, $2, NULL);
1284 $$ LANGUAGE SQL;
1285
1286 CREATE OR REPLACE FUNCTION vandelay.overlay_bib_record ( import_id BIGINT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1287 DECLARE
1288     merge_profile   vandelay.merge_profile%ROWTYPE;
1289     dyn_profile     vandelay.compile_profile%ROWTYPE;
1290     editor_string   TEXT;
1291     editor_id       INT;
1292     source_marc     TEXT;
1293     target_marc     TEXT;
1294     eg_marc         TEXT;
1295     v_marc          TEXT;
1296     replace_rule    TEXT;
1297 BEGIN
1298
1299     SELECT  q.marc INTO v_marc
1300       FROM  vandelay.queued_record q
1301             JOIN vandelay.bib_match m ON (m.queued_record = q.id AND q.id = import_id)
1302       LIMIT 1;
1303
1304     IF v_marc IS NULL THEN
1305         -- RAISE NOTICE 'no marc for vandelay or bib record';
1306         RETURN FALSE;
1307     END IF;
1308
1309     IF vandelay.template_overlay_bib_record( v_marc, eg_id, merge_profile_id) THEN
1310         UPDATE  vandelay.queued_bib_record
1311           SET   imported_as = eg_id,
1312                 import_time = NOW()
1313           WHERE id = import_id;
1314
1315         editor_string := (oils_xpath('//*[@tag="905"]/*[@code="u"]/text()',v_marc))[1];
1316
1317         IF editor_string IS NOT NULL AND editor_string <> '' THEN
1318             SELECT usr INTO editor_id FROM actor.card WHERE barcode = editor_string;
1319
1320             IF editor_id IS NULL THEN
1321                 SELECT id INTO editor_id FROM actor.usr WHERE usrname = editor_string;
1322             END IF;
1323
1324             IF editor_id IS NOT NULL THEN
1325                 UPDATE biblio.record_entry SET editor = editor_id WHERE id = eg_id;
1326             END IF;
1327         END IF;
1328
1329         RETURN TRUE;
1330     END IF;
1331
1332     -- RAISE NOTICE 'update of biblio.record_entry failed';
1333
1334     RETURN FALSE;
1335
1336 END;
1337 $$ LANGUAGE PLPGSQL;
1338
1339 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record_with_best ( import_id BIGINT, merge_profile_id INT, lwm_ratio_value_p NUMERIC ) RETURNS BOOL AS $$
1340 DECLARE
1341     eg_id           BIGINT;
1342     lwm_ratio_value NUMERIC;
1343 BEGIN
1344
1345     lwm_ratio_value := COALESCE(lwm_ratio_value_p, 0.0);
1346
1347     PERFORM * FROM vandelay.queued_bib_record WHERE import_time IS NOT NULL AND id = import_id;
1348
1349     IF FOUND THEN
1350         -- RAISE NOTICE 'already imported, cannot auto-overlay'
1351         RETURN FALSE;
1352     END IF;
1353
1354     SELECT  m.eg_record INTO eg_id
1355       FROM  vandelay.bib_match m
1356             JOIN vandelay.queued_bib_record qr ON (m.queued_record = qr.id)
1357             JOIN vandelay.bib_queue q ON (qr.queue = q.id)
1358             JOIN biblio.record_entry r ON (r.id = m.eg_record)
1359       WHERE m.queued_record = import_id
1360             AND qr.quality::NUMERIC / COALESCE(NULLIF(m.quality,0),1)::NUMERIC >= lwm_ratio_value
1361       ORDER BY  m.match_score DESC, -- required match score
1362                 qr.quality::NUMERIC / COALESCE(NULLIF(m.quality,0),1)::NUMERIC DESC, -- quality tie breaker
1363                 m.id -- when in doubt, use the first match
1364       LIMIT 1;
1365
1366     IF eg_id IS NULL THEN
1367         -- RAISE NOTICE 'incoming record is not of high enough quality';
1368         RETURN FALSE;
1369     END IF;
1370
1371     RETURN vandelay.overlay_bib_record( import_id, eg_id, merge_profile_id );
1372 END;
1373 $$ LANGUAGE PLPGSQL;
1374
1375 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record_with_best ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1376     SELECT vandelay.auto_overlay_bib_record_with_best( $1, $2, p.lwm_ratio ) FROM vandelay.merge_profile p WHERE id = $2;
1377 $$ LANGUAGE SQL;
1378
1379 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1380 DECLARE
1381     eg_id           BIGINT;
1382     match_count     INT;
1383 BEGIN
1384
1385     PERFORM * FROM vandelay.queued_bib_record WHERE import_time IS NOT NULL AND id = import_id;
1386
1387     IF FOUND THEN
1388         -- RAISE NOTICE 'already imported, cannot auto-overlay'
1389         RETURN FALSE;
1390     END IF;
1391
1392     SELECT COUNT(*) INTO match_count FROM vandelay.bib_match WHERE queued_record = import_id;
1393
1394     IF match_count <> 1 THEN
1395         -- RAISE NOTICE 'not an exact match';
1396         RETURN FALSE;
1397     END IF;
1398
1399     -- Check that the one match is on the first 901c
1400     SELECT  m.eg_record INTO eg_id
1401       FROM  vandelay.queued_bib_record q
1402             JOIN vandelay.bib_match m ON (m.queued_record = q.id)
1403       WHERE q.id = import_id
1404             AND m.eg_record = oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]',marc)::BIGINT;
1405
1406     IF NOT FOUND THEN
1407         -- RAISE NOTICE 'not a 901c match';
1408         RETURN FALSE;
1409     END IF;
1410
1411     RETURN vandelay.overlay_bib_record( import_id, eg_id, merge_profile_id );
1412 END;
1413 $$ LANGUAGE PLPGSQL;
1414
1415 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue ( queue_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1416 DECLARE
1417     queued_record   vandelay.queued_bib_record%ROWTYPE;
1418 BEGIN
1419
1420     FOR queued_record IN SELECT * FROM vandelay.queued_bib_record WHERE queue = queue_id AND import_time IS NULL LOOP
1421
1422         IF vandelay.auto_overlay_bib_record( queued_record.id, merge_profile_id ) THEN
1423             RETURN NEXT queued_record.id;
1424         END IF;
1425
1426     END LOOP;
1427
1428     RETURN;
1429     
1430 END;
1431 $$ LANGUAGE PLPGSQL;
1432
1433 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue_with_best ( queue_id BIGINT, merge_profile_id INT, lwm_ratio_value NUMERIC ) RETURNS SETOF BIGINT AS $$
1434 DECLARE
1435     queued_record   vandelay.queued_bib_record%ROWTYPE;
1436 BEGIN
1437
1438     FOR queued_record IN SELECT * FROM vandelay.queued_bib_record WHERE queue = queue_id AND import_time IS NULL LOOP
1439
1440         IF vandelay.auto_overlay_bib_record_with_best( queued_record.id, merge_profile_id, lwm_ratio_value ) THEN
1441             RETURN NEXT queued_record.id;
1442         END IF;
1443
1444     END LOOP;
1445
1446     RETURN;
1447     
1448 END;
1449 $$ LANGUAGE PLPGSQL;
1450
1451 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue_with_best ( import_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1452     SELECT vandelay.auto_overlay_bib_queue_with_best( $1, $2, p.lwm_ratio ) FROM vandelay.merge_profile p WHERE id = $2;
1453 $$ LANGUAGE SQL;
1454
1455 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue ( queue_id BIGINT ) RETURNS SETOF BIGINT AS $$
1456     SELECT * FROM vandelay.auto_overlay_bib_queue( $1, NULL );
1457 $$ LANGUAGE SQL;
1458
1459 CREATE OR REPLACE FUNCTION vandelay.ingest_bib_marc ( ) RETURNS TRIGGER AS $$
1460 DECLARE
1461     value   TEXT;
1462     atype   TEXT;
1463     adef    RECORD;
1464 BEGIN
1465     IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1466         RETURN NEW;
1467     END IF;
1468
1469     FOR adef IN SELECT * FROM vandelay.bib_attr_definition LOOP
1470
1471         SELECT extract_marc_field('vandelay.queued_bib_record', id, adef.xpath, adef.remove) INTO value FROM vandelay.queued_bib_record WHERE id = NEW.id;
1472         IF (value IS NOT NULL AND value <> '') THEN
1473             INSERT INTO vandelay.queued_bib_record_attr (record, field, attr_value) VALUES (NEW.id, adef.id, value);
1474         END IF;
1475
1476     END LOOP;
1477
1478     RETURN NULL;
1479 END;
1480 $$ LANGUAGE PLPGSQL;
1481
1482 CREATE OR REPLACE FUNCTION vandelay.cleanup_bib_marc ( ) RETURNS TRIGGER AS $$
1483 BEGIN
1484     IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1485         RETURN NEW;
1486     END IF;
1487
1488     DELETE FROM vandelay.queued_bib_record_attr WHERE record = OLD.id;
1489     DELETE FROM vandelay.import_item WHERE record = OLD.id;
1490
1491     IF TG_OP = 'UPDATE' THEN
1492         RETURN NEW;
1493     END IF;
1494     RETURN OLD;
1495 END;
1496 $$ LANGUAGE PLPGSQL;
1497
1498 CREATE TRIGGER cleanup_bib_trigger
1499     BEFORE UPDATE OR DELETE ON vandelay.queued_bib_record
1500     FOR EACH ROW EXECUTE PROCEDURE vandelay.cleanup_bib_marc();
1501
1502 CREATE TRIGGER ingest_bib_trigger
1503     AFTER INSERT OR UPDATE ON vandelay.queued_bib_record
1504     FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_bib_marc();
1505
1506 CREATE TRIGGER zz_match_bibs_trigger
1507     BEFORE INSERT OR UPDATE ON vandelay.queued_bib_record
1508     FOR EACH ROW EXECUTE PROCEDURE vandelay.match_bib_record();
1509
1510
1511 /* Authority stuff down here */
1512 ---------------------------------------
1513 CREATE TABLE vandelay.authority_attr_definition (
1514         id                      SERIAL  PRIMARY KEY,
1515         code            TEXT    UNIQUE NOT NULL,
1516         description     TEXT,
1517         xpath           TEXT    NOT NULL,
1518         remove          TEXT    NOT NULL DEFAULT ''
1519 );
1520
1521 CREATE TYPE vandelay.authority_queue_queue_type AS ENUM ('authority');
1522 CREATE TABLE vandelay.authority_queue (
1523         queue_type      vandelay.authority_queue_queue_type NOT NULL DEFAULT 'authority',
1524         CONSTRAINT vand_authority_queue_name_once_per_owner_const UNIQUE (owner,name,queue_type)
1525 ) INHERITS (vandelay.queue);
1526 ALTER TABLE vandelay.authority_queue ADD PRIMARY KEY (id);
1527
1528 CREATE TABLE vandelay.queued_authority_record (
1529         queue           INT     NOT NULL REFERENCES vandelay.authority_queue (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
1530         imported_as     INT     REFERENCES authority.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
1531         import_error    TEXT    REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
1532         error_detail    TEXT
1533 ) INHERITS (vandelay.queued_record);
1534 ALTER TABLE vandelay.queued_authority_record ADD PRIMARY KEY (id);
1535 CREATE INDEX queued_authority_record_queue_idx ON vandelay.queued_authority_record (queue);
1536
1537 CREATE TABLE vandelay.queued_authority_record_attr (
1538         id                      BIGSERIAL       PRIMARY KEY,
1539         record          BIGINT          NOT NULL REFERENCES vandelay.queued_authority_record (id) DEFERRABLE INITIALLY DEFERRED,
1540         field           INT                     NOT NULL REFERENCES vandelay.authority_attr_definition (id) DEFERRABLE INITIALLY DEFERRED,
1541         attr_value      TEXT            NOT NULL
1542 );
1543 CREATE INDEX queued_authority_record_attr_record_idx ON vandelay.queued_authority_record_attr (record);
1544
1545 CREATE TABLE vandelay.authority_match (
1546         id                              BIGSERIAL       PRIMARY KEY,
1547         queued_record   BIGINT          REFERENCES vandelay.queued_authority_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
1548         eg_record               BIGINT          REFERENCES authority.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
1549     quality         INT         NOT NULL DEFAULT 0
1550 );
1551
1552 CREATE OR REPLACE FUNCTION vandelay.ingest_authority_marc ( ) RETURNS TRIGGER AS $$
1553 DECLARE
1554     value   TEXT;
1555     atype   TEXT;
1556     adef    RECORD;
1557 BEGIN
1558     IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1559         RETURN NEW;
1560     END IF;
1561
1562     FOR adef IN SELECT * FROM vandelay.authority_attr_definition LOOP
1563
1564         SELECT extract_marc_field('vandelay.queued_authority_record', id, adef.xpath, adef.remove) INTO value FROM vandelay.queued_authority_record WHERE id = NEW.id;
1565         IF (value IS NOT NULL AND value <> '') THEN
1566             INSERT INTO vandelay.queued_authority_record_attr (record, field, attr_value) VALUES (NEW.id, adef.id, value);
1567         END IF;
1568
1569     END LOOP;
1570
1571     RETURN NULL;
1572 END;
1573 $$ LANGUAGE PLPGSQL;
1574
1575 CREATE OR REPLACE FUNCTION vandelay.cleanup_authority_marc ( ) RETURNS TRIGGER AS $$
1576 BEGIN
1577     IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1578         RETURN NEW;
1579     END IF;
1580
1581     DELETE FROM vandelay.queued_authority_record_attr WHERE record = OLD.id;
1582     IF TG_OP = 'UPDATE' THEN
1583         RETURN NEW;
1584     END IF;
1585     RETURN OLD;
1586 END;
1587 $$ LANGUAGE PLPGSQL;
1588
1589 CREATE TRIGGER cleanup_authority_trigger
1590     BEFORE UPDATE OR DELETE ON vandelay.queued_authority_record
1591     FOR EACH ROW EXECUTE PROCEDURE vandelay.cleanup_authority_marc();
1592
1593 CREATE TRIGGER ingest_authority_trigger
1594     AFTER INSERT OR UPDATE ON vandelay.queued_authority_record
1595     FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_authority_marc();
1596
1597 CREATE OR REPLACE FUNCTION vandelay.overlay_authority_record ( import_id BIGINT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1598 DECLARE
1599     merge_profile   vandelay.merge_profile%ROWTYPE;
1600     dyn_profile     vandelay.compile_profile%ROWTYPE;
1601     source_marc     TEXT;
1602     target_marc     TEXT;
1603     eg_marc         TEXT;
1604     v_marc          TEXT;
1605     replace_rule    TEXT;
1606     match_count     INT;
1607 BEGIN
1608
1609     SELECT  b.marc INTO eg_marc
1610       FROM  authority.record_entry b
1611             JOIN vandelay.authority_match m ON (m.eg_record = b.id AND m.queued_record = import_id)
1612       LIMIT 1;
1613
1614     SELECT  q.marc INTO v_marc
1615       FROM  vandelay.queued_record q
1616             JOIN vandelay.authority_match m ON (m.queued_record = q.id AND q.id = import_id)
1617       LIMIT 1;
1618
1619     IF eg_marc IS NULL OR v_marc IS NULL THEN
1620         -- RAISE NOTICE 'no marc for vandelay or authority record';
1621         RETURN FALSE;
1622     END IF;
1623
1624     dyn_profile := vandelay.compile_profile( v_marc );
1625
1626     IF merge_profile_id IS NOT NULL THEN
1627         SELECT * INTO merge_profile FROM vandelay.merge_profile WHERE id = merge_profile_id;
1628         IF FOUND THEN
1629             dyn_profile.add_rule := BTRIM( dyn_profile.add_rule || ',' || COALESCE(merge_profile.add_spec,''), ',');
1630             dyn_profile.strip_rule := BTRIM( dyn_profile.strip_rule || ',' || COALESCE(merge_profile.strip_spec,''), ',');
1631             dyn_profile.replace_rule := BTRIM( dyn_profile.replace_rule || ',' || COALESCE(merge_profile.replace_spec,''), ',');
1632             dyn_profile.preserve_rule := BTRIM( dyn_profile.preserve_rule || ',' || COALESCE(merge_profile.preserve_spec,''), ',');
1633         END IF;
1634     END IF;
1635
1636     IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1637         -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1638         RETURN FALSE;
1639     END IF;
1640
1641     IF dyn_profile.replace_rule <> '' THEN
1642         source_marc = v_marc;
1643         target_marc = eg_marc;
1644         replace_rule = dyn_profile.replace_rule;
1645     ELSE
1646         source_marc = eg_marc;
1647         target_marc = v_marc;
1648         replace_rule = dyn_profile.preserve_rule;
1649     END IF;
1650
1651     UPDATE  authority.record_entry
1652       SET   marc = vandelay.merge_record_xml( target_marc, source_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule )
1653       WHERE id = eg_id;
1654
1655     IF FOUND THEN
1656         UPDATE  vandelay.queued_authority_record
1657           SET   imported_as = eg_id,
1658                 import_time = NOW()
1659           WHERE id = import_id;
1660         RETURN TRUE;
1661     END IF;
1662
1663     -- RAISE NOTICE 'update of authority.record_entry failed';
1664
1665     RETURN FALSE;
1666
1667 END;
1668 $$ LANGUAGE PLPGSQL;
1669
1670 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_record ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1671 DECLARE
1672     eg_id           BIGINT;
1673     match_count     INT;
1674 BEGIN
1675     SELECT COUNT(*) INTO match_count FROM vandelay.authority_match WHERE queued_record = import_id;
1676
1677     IF match_count <> 1 THEN
1678         -- RAISE NOTICE 'not an exact match';
1679         RETURN FALSE;
1680     END IF;
1681
1682     SELECT  m.eg_record INTO eg_id
1683       FROM  vandelay.authority_match m
1684       WHERE m.queued_record = import_id
1685       LIMIT 1;
1686
1687     IF eg_id IS NULL THEN
1688         RETURN FALSE;
1689     END IF;
1690
1691     RETURN vandelay.overlay_authority_record( import_id, eg_id, merge_profile_id );
1692 END;
1693 $$ LANGUAGE PLPGSQL;
1694
1695 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_queue ( queue_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1696 DECLARE
1697     queued_record   vandelay.queued_authority_record%ROWTYPE;
1698 BEGIN
1699
1700     FOR queued_record IN SELECT * FROM vandelay.queued_authority_record WHERE queue = queue_id AND import_time IS NULL LOOP
1701
1702         IF vandelay.auto_overlay_authority_record( queued_record.id, merge_profile_id ) THEN
1703             RETURN NEXT queued_record.id;
1704         END IF;
1705
1706     END LOOP;
1707
1708     RETURN;
1709     
1710 END;
1711 $$ LANGUAGE PLPGSQL;
1712
1713 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_queue ( queue_id BIGINT ) RETURNS SETOF BIGINT AS $$
1714     SELECT * FROM vandelay.auto_overlay_authority_queue( $1, NULL );
1715 $$ LANGUAGE SQL;
1716
1717
1718 -- Vandelay (for importing and exporting records) 012.schema.vandelay.sql 
1719 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath ) VALUES (1, 'title', oils_i18n_gettext(1, 'vqbrad', 'Title of work', 'description'),'//*[@tag="245"]/*[contains("abcmnopr",@code)]');
1720 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath ) VALUES (2, 'author', oils_i18n_gettext(1, 'vqbrad', 'Author of work', 'description'),'//*[@tag="100" or @tag="110" or @tag="113"]/*[contains("ad",@code)]');
1721 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath ) VALUES (3, 'language', oils_i18n_gettext(3, 'vqbrad', 'Language of work', 'description'),'//*[@tag="240"]/*[@code="l"][1]');
1722 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath ) VALUES (4, 'pagination', oils_i18n_gettext(4, 'vqbrad', 'Pagination', 'description'),'//*[@tag="300"]/*[@code="a"][1]');
1723 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath, ident, remove ) VALUES (5, 'isbn',oils_i18n_gettext(5, 'vqbrad', 'ISBN', 'description'),'//*[@tag="020"]/*[@code="a"]', TRUE, $r$(?:-|\s.+$)$r$);
1724 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath, ident, remove ) VALUES (6, 'issn',oils_i18n_gettext(6, 'vqbrad', 'ISSN', 'description'),'//*[@tag="022"]/*[@code="a"]', TRUE, $r$(?:-|\s.+$)$r$);
1725 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath ) VALUES (7, 'price',oils_i18n_gettext(7, 'vqbrad', 'Price', 'description'),'//*[@tag="020" or @tag="022"]/*[@code="c"][1]');
1726 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath, ident ) VALUES (8, 'rec_identifier',oils_i18n_gettext(8, 'vqbrad', 'Accession Number', 'description'),'//*[@tag="001"]', TRUE);
1727 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath, ident ) VALUES (9, 'eg_tcn',oils_i18n_gettext(9, 'vqbrad', 'TCN Value', 'description'),'//*[@tag="901"]/*[@code="a"]', TRUE);
1728 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath, ident ) VALUES (10, 'eg_tcn_source',oils_i18n_gettext(10, 'vqbrad', 'TCN Source', 'description'),'//*[@tag="901"]/*[@code="b"]', TRUE);
1729 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath, ident ) VALUES (11, 'eg_identifier',oils_i18n_gettext(11, 'vqbrad', 'Internal ID', 'description'),'//*[@tag="901"]/*[@code="c"]', TRUE);
1730 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath ) VALUES (12, 'publisher',oils_i18n_gettext(12, 'vqbrad', 'Publisher', 'description'),'//*[@tag="260"]/*[@code="b"][1]');
1731 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath, remove ) VALUES (13, 'pubdate',oils_i18n_gettext(13, 'vqbrad', 'Publication Date', 'description'),'//*[@tag="260"]/*[@code="c"][1]',$r$\D$r$);
1732 --INSERT INTO vandelay.bib_attr_definition ( id, code, description, xpath ) VALUES (14, 'edition',oils_i18n_gettext(14, 'vqbrad', 'Edition', 'description'),'//*[@tag="250"]/*[@code="a"][1]');
1733 --
1734 --INSERT INTO vandelay.import_item_attr_definition (
1735 --    owner, name, tag, owning_lib, circ_lib, location,
1736 --    call_number, circ_modifier, barcode, price, copy_number,
1737 --    circulate, ref, holdable, opac_visible, status
1738 --) VALUES (
1739 --    1,
1740 --    'Evergreen 852 export format',
1741 --    '852',
1742 --    '[@code = "b"][1]',
1743 --    '[@code = "b"][2]',
1744 --    'c',
1745 --    'j',
1746 --    'g',
1747 --    'p',
1748 --    'y',
1749 --    't',
1750 --    '[@code = "x" and text() = "circulating"]',
1751 --    '[@code = "x" and text() = "reference"]',
1752 --    '[@code = "x" and text() = "holdable"]',
1753 --    '[@code = "x" and text() = "visible"]',
1754 --    'z'
1755 --);
1756 --
1757 --INSERT INTO vandelay.import_item_attr_definition (
1758 --    owner,
1759 --    name,
1760 --    tag,
1761 --    owning_lib,
1762 --    location,
1763 --    call_number,
1764 --    circ_modifier,
1765 --    barcode,
1766 --    price,
1767 --    status
1768 --) VALUES (
1769 --    1,
1770 --    'Unicorn Import format -- 999',
1771 --    '999',
1772 --    'm',
1773 --    'l',
1774 --    'a',
1775 --    't',
1776 --    'i',
1777 --    'p',
1778 --    'k'
1779 --);
1780 --
1781 --INSERT INTO vandelay.authority_attr_definition ( code, description, xpath, ident ) VALUES ('rec_identifier','Identifier','//*[@tag="001"]', TRUE);
1782
1783 COMMIT;
1784