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