]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/sql/Pg/012.schema.vandelay.sql
LP1928258 Vandelay separate bib edit update option
[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     heading     BOOLEAN NOT NULL DEFAULT FALSE, -- match on authority heading
27     CONSTRAINT vmsp_need_a_subfield_with_a_tag CHECK ((tag IS NOT NULL AND subfield IS NOT NULL) OR tag IS NULL),
28     CONSTRAINT vmsp_need_a_tag_or_a_ff_or_a_bo CHECK (
29         (tag IS NOT NULL AND svf IS NULL AND heading IS FALSE AND bool_op IS NULL) OR 
30         (tag IS NULL AND svf IS NOT NULL AND heading IS FALSE AND bool_op IS NULL) OR 
31         (tag IS NULL AND svf IS NULL AND heading IS TRUE AND bool_op IS NULL) OR 
32         (tag IS NULL AND svf IS NULL AND heading IS FALSE AND bool_op IS NOT NULL)
33     )
34 );
35
36 CREATE TABLE vandelay.match_set_quality (
37     id          SERIAL  PRIMARY KEY,
38     match_set   INT     NOT NULL REFERENCES vandelay.match_set (id) ON DELETE CASCADE,
39     svf         TEXT    REFERENCES config.record_attr_definition,
40     tag         TEXT,
41     subfield    TEXT,
42     value       TEXT    NOT NULL,
43     quality     INT     NOT NULL DEFAULT 1, -- higher is better
44     CONSTRAINT vmsq_need_a_subfield_with_a_tag CHECK ((tag IS NOT NULL AND subfield IS NOT NULL) OR tag IS NULL),
45     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))
46 );
47 CREATE UNIQUE INDEX vmsq_def_once_per_set ON vandelay.match_set_quality (match_set, COALESCE(tag,''), COALESCE(subfield,''), COALESCE(svf,''), value);
48
49
50 CREATE TABLE vandelay.queue (
51         id                              BIGSERIAL       PRIMARY KEY,
52         owner                   INT                     NOT NULL REFERENCES actor.usr (id) DEFERRABLE INITIALLY DEFERRED,
53         name                    TEXT            NOT NULL,
54         complete                BOOL            NOT NULL DEFAULT FALSE,
55     match_set       INT         REFERENCES vandelay.match_set (id) ON UPDATE CASCADE ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED
56 );
57
58 CREATE TABLE vandelay.queued_record (
59     id                  BIGSERIAL                   PRIMARY KEY,
60     create_time TIMESTAMP WITH TIME ZONE    NOT NULL DEFAULT NOW(),
61     import_time TIMESTAMP WITH TIME ZONE,
62         purpose         TEXT                                            NOT NULL DEFAULT 'import' CHECK (purpose IN ('import','overlay')),
63     marc                TEXT                        NOT NULL,
64     quality     INT                         NOT NULL DEFAULT 0
65 );
66
67
68
69 /* Bib stuff at the top */
70 ----------------------------------------------------
71
72 CREATE TABLE vandelay.bib_attr_definition (
73         id                      SERIAL  PRIMARY KEY,
74         code            TEXT    UNIQUE NOT NULL,
75         description     TEXT,
76         xpath           TEXT    NOT NULL,
77         remove          TEXT    NOT NULL DEFAULT ''
78 );
79
80 -- Each TEXT field (other than 'name') should hold an XPath predicate for pulling the data needed
81 -- DROP TABLE vandelay.import_item_attr_definition CASCADE;
82 CREATE TABLE vandelay.import_item_attr_definition (
83     id              BIGSERIAL   PRIMARY KEY,
84     owner           INT         NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
85     name            TEXT        NOT NULL,
86     tag             TEXT        NOT NULL,
87     keep            BOOL        NOT NULL DEFAULT FALSE,
88     owning_lib      TEXT,
89     circ_lib        TEXT,
90     call_number     TEXT,
91     copy_number     TEXT,
92     status          TEXT,
93     location        TEXT,
94     circulate       TEXT,
95     deposit         TEXT,
96     deposit_amount  TEXT,
97     ref             TEXT,
98     holdable        TEXT,
99     price           TEXT,
100     barcode         TEXT,
101     circ_modifier   TEXT,
102     circ_as_type    TEXT,
103     alert_message   TEXT,
104     opac_visible    TEXT,
105     pub_note_title  TEXT,
106     pub_note        TEXT,
107     priv_note_title TEXT,
108     priv_note       TEXT,
109     internal_id     TEXT,
110     stat_cat_data   TEXT,
111     parts_data      TEXT,
112         CONSTRAINT vand_import_item_attr_def_idx UNIQUE (owner,name)
113 );
114
115 CREATE TABLE vandelay.import_error (
116     code        TEXT    PRIMARY KEY,
117     description TEXT    NOT NULL -- i18n
118 );
119
120 CREATE TYPE vandelay.bib_queue_queue_type AS ENUM ('bib', 'acq');
121
122 CREATE TABLE vandelay.bib_queue (
123         queue_type          vandelay.bib_queue_queue_type       NOT NULL DEFAULT 'bib',
124         item_attr_def   BIGINT REFERENCES vandelay.import_item_attr_definition (id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,
125     match_bucket    INTEGER, -- REFERENCES container.biblio_record_entry_bucket(id);
126         CONSTRAINT vand_bib_queue_name_once_per_owner_const UNIQUE (owner,name,queue_type)
127 ) INHERITS (vandelay.queue);
128 ALTER TABLE vandelay.bib_queue ADD PRIMARY KEY (id);
129
130 CREATE TABLE vandelay.queued_bib_record (
131         queue               INT         NOT NULL REFERENCES vandelay.bib_queue (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
132         bib_source          INT         REFERENCES config.bib_source (id) DEFERRABLE INITIALLY DEFERRED,
133         imported_as     BIGINT  REFERENCES biblio.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
134         import_error    TEXT    REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
135         error_detail    TEXT
136 ) INHERITS (vandelay.queued_record);
137 ALTER TABLE vandelay.queued_bib_record ADD PRIMARY KEY (id);
138 CREATE INDEX queued_bib_record_queue_idx ON vandelay.queued_bib_record (queue);
139
140 CREATE TABLE vandelay.queued_bib_record_attr (
141         id                      BIGSERIAL       PRIMARY KEY,
142         record          BIGINT          NOT NULL REFERENCES vandelay.queued_bib_record (id) DEFERRABLE INITIALLY DEFERRED,
143         field           INT                     NOT NULL REFERENCES vandelay.bib_attr_definition (id) DEFERRABLE INITIALLY DEFERRED,
144         attr_value      TEXT            NOT NULL
145 );
146 CREATE INDEX queued_bib_record_attr_record_idx ON vandelay.queued_bib_record_attr (record);
147
148 CREATE TABLE vandelay.bib_match (
149         id                              BIGSERIAL       PRIMARY KEY,
150         queued_record   BIGINT          REFERENCES vandelay.queued_bib_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
151         eg_record               BIGINT          REFERENCES biblio.record_entry (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
152     quality         INT         NOT NULL DEFAULT 1,
153     match_score     INT         NOT NULL DEFAULT 0
154 );
155 CREATE INDEX bib_match_queued_record_idx ON vandelay.bib_match (queued_record);
156
157 CREATE TABLE vandelay.import_item (
158     id              BIGSERIAL   PRIMARY KEY,
159     record          BIGINT      NOT NULL REFERENCES vandelay.queued_bib_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
160     definition      BIGINT      NOT NULL REFERENCES vandelay.import_item_attr_definition (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
161         import_error    TEXT        REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
162         error_detail    TEXT,
163     imported_as     BIGINT,
164     import_time     TIMESTAMP WITH TIME ZONE,
165     owning_lib      INT,
166     circ_lib        INT,
167     call_number     TEXT,
168     copy_number     INT,
169     status          INT,
170     location        INT,
171     circulate       BOOL,
172     deposit         BOOL,
173     deposit_amount  NUMERIC(8,2),
174     ref             BOOL,
175     holdable        BOOL,
176     price           NUMERIC(8,2),
177     barcode         TEXT,
178     circ_modifier   TEXT,
179     circ_as_type    TEXT,
180     alert_message   TEXT,
181     pub_note        TEXT,
182     priv_note       TEXT,
183     stat_cat_data   TEXT,
184     parts_data      TEXT,
185     opac_visible    BOOL,
186     internal_id     BIGINT -- queue_type == 'acq' ? acq.lineitem_detail.id : asset.copy.id
187 );
188 CREATE INDEX import_item_record_idx ON vandelay.import_item (record);
189
190 CREATE TABLE vandelay.import_bib_trash_group(
191     id           SERIAL  PRIMARY KEY,
192     owner        INTEGER NOT NULL REFERENCES actor.org_unit(id),
193     label        TEXT    NOT NULL, --i18n
194     always_apply BOOLEAN NOT NULL DEFAULT FALSE,
195         CONSTRAINT vand_import_bib_trash_grp_owner_label UNIQUE (owner, label)
196 );
197  
198 CREATE TABLE vandelay.import_bib_trash_fields (
199     id         BIGSERIAL PRIMARY KEY,
200     grp        INTEGER   NOT NULL REFERENCES vandelay.import_bib_trash_group,
201     field      TEXT      NOT NULL,
202     CONSTRAINT vand_import_bib_trash_fields_once_per UNIQUE (grp, field)
203 );
204
205 CREATE TABLE vandelay.merge_profile (
206     id              BIGSERIAL   PRIMARY KEY,
207     owner           INT         NOT NULL REFERENCES actor.org_unit (id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
208     name            TEXT        NOT NULL,
209     add_spec        TEXT,
210     replace_spec    TEXT,
211     strip_spec      TEXT,
212     preserve_spec   TEXT,
213     update_bib_source BOOLEAN   NOT NULL DEFAULT FALSE,
214     update_bib_editor BOOLEAN   NOT NULL DEFAULT FALSE,
215     lwm_ratio       NUMERIC,
216         CONSTRAINT vand_merge_prof_owner_name_idx UNIQUE (owner,name),
217         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))
218 );
219
220 CREATE OR REPLACE FUNCTION vandelay.marc21_record_type( marc TEXT ) RETURNS config.marc21_rec_type_map AS $func$
221 DECLARE
222         ldr         TEXT;
223         tval        TEXT;
224         tval_rec    RECORD;
225         bval        TEXT;
226         bval_rec    RECORD;
227     retval      config.marc21_rec_type_map%ROWTYPE;
228 BEGIN
229     ldr := oils_xpath_string( '//*[local-name()="leader"]', marc );
230
231     IF ldr IS NULL OR ldr = '' THEN
232         SELECT * INTO retval FROM config.marc21_rec_type_map WHERE code = 'BKS';
233         RETURN retval;
234     END IF;
235
236     SELECT * INTO tval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'Type' LIMIT 1; -- They're all the same
237     SELECT * INTO bval_rec FROM config.marc21_ff_pos_map WHERE fixed_field = 'BLvl' LIMIT 1; -- They're all the same
238
239
240     tval := SUBSTRING( ldr, tval_rec.start_pos + 1, tval_rec.length );
241     bval := SUBSTRING( ldr, bval_rec.start_pos + 1, bval_rec.length );
242
243     -- RAISE NOTICE 'type %, blvl %, ldr %', tval, bval, ldr;
244
245     SELECT * INTO retval FROM config.marc21_rec_type_map WHERE type_val LIKE '%' || tval || '%' AND blvl_val LIKE '%' || bval || '%';
246
247
248     IF retval.code IS NULL THEN
249         SELECT * INTO retval FROM config.marc21_rec_type_map WHERE code = 'BKS';
250     END IF;
251
252     RETURN retval;
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, use_default BOOL DEFAULT FALSE ) 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         IF ff_pos.tag = 'ldr' THEN
271             output.ff_value := oils_xpath_string('//*[local-name()="leader"]', marc);
272             IF output.ff_value IS NOT NULL THEN
273                 output.ff_value := SUBSTRING( output.ff_value, ff_pos.start_pos + 1, ff_pos.length );
274                 RETURN NEXT output;
275                 output.ff_value := NULL;
276             END IF;
277         ELSE
278             FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(ff_pos.tag) || '"]/text()', marc ) ) x(value) LOOP
279                 output.ff_value := SUBSTRING( tag_data, ff_pos.start_pos + 1, ff_pos.length );
280                 CONTINUE WHEN output.ff_value IS NULL AND NOT use_default;
281                 IF output.ff_value IS NULL THEN output.ff_value := REPEAT( ff_pos.default_val, ff_pos.length ); END IF;
282                 RETURN NEXT output;
283                 output.ff_value := NULL;
284             END LOOP;
285         END IF;
286
287     END LOOP;
288
289     RETURN;
290 END;
291 $func$ LANGUAGE PLPGSQL;
292
293 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_fixed_field_list( marc TEXT, ff TEXT, use_default BOOL DEFAULT FALSE ) RETURNS TEXT[] AS $func$
294 DECLARE
295     rtype       TEXT;
296     ff_pos      RECORD;
297     tag_data    RECORD;
298     val         TEXT;
299     collection  TEXT[] := '{}'::TEXT[];
300 BEGIN
301     rtype := (vandelay.marc21_record_type( marc )).code;
302     FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE fixed_field = ff AND rec_type = rtype ORDER BY tag DESC LOOP
303         IF ff_pos.tag = 'ldr' THEN
304             val := oils_xpath_string('//*[local-name()="leader"]', marc);
305             IF val IS NOT NULL THEN
306                 val := SUBSTRING( val, ff_pos.start_pos + 1, ff_pos.length );
307                 collection := collection || val;
308             END IF;
309         ELSE
310             FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(ff_pos.tag) || '"]/text()', marc ) ) x(value) LOOP
311                 val := SUBSTRING( tag_data.value, ff_pos.start_pos + 1, ff_pos.length );
312                 collection := collection || val;
313             END LOOP;
314         END IF;
315         CONTINUE WHEN NOT use_default;
316         CONTINUE WHEN ARRAY_UPPER(collection, 1) > 0;
317         val := REPEAT( ff_pos.default_val, ff_pos.length );
318         collection := collection || val;
319     END LOOP;
320
321     RETURN collection;
322 END;
323 $func$ LANGUAGE PLPGSQL;
324
325 CREATE OR REPLACE FUNCTION vandelay.marc21_extract_fixed_field( marc TEXT, ff TEXT, use_default BOOL DEFAULT FALSE ) RETURNS TEXT AS $func$
326 DECLARE
327     rtype       TEXT;
328     ff_pos      RECORD;
329     tag_data    RECORD;
330     val         TEXT;
331 BEGIN
332     rtype := (vandelay.marc21_record_type( marc )).code;
333     FOR ff_pos IN SELECT * FROM config.marc21_ff_pos_map WHERE fixed_field = ff AND rec_type = rtype ORDER BY tag DESC LOOP
334         IF ff_pos.tag = 'ldr' THEN
335             val := oils_xpath_string('//*[local-name()="leader"]', marc);
336             IF val IS NOT NULL THEN
337                 val := SUBSTRING( val, ff_pos.start_pos + 1, ff_pos.length );
338                 RETURN val;
339             END IF;
340         ELSE
341             FOR tag_data IN SELECT value FROM UNNEST( oils_xpath( '//*[@tag="' || UPPER(ff_pos.tag) || '"]/text()', marc ) ) x(value) LOOP
342                 val := SUBSTRING( tag_data.value, ff_pos.start_pos + 1, ff_pos.length );
343                 RETURN val;
344             END LOOP;
345         END IF;
346         CONTINUE WHEN NOT use_default;
347         val := REPEAT( ff_pos.default_val, ff_pos.length );
348         RETURN val;
349     END LOOP;
350
351     RETURN NULL;
352 END;
353 $func$ LANGUAGE PLPGSQL;
354
355 CREATE TYPE biblio.marc21_physical_characteristics AS ( id INT, record BIGINT, ptype TEXT, subfield INT, value INT );
356 CREATE OR REPLACE FUNCTION vandelay.marc21_physical_characteristics( marc TEXT) RETURNS SETOF biblio.marc21_physical_characteristics AS $func$
357 DECLARE
358     rowid   INT := 0;
359     _007    TEXT;
360     ptype   config.marc21_physical_characteristic_type_map%ROWTYPE;
361     psf     config.marc21_physical_characteristic_subfield_map%ROWTYPE;
362     pval    config.marc21_physical_characteristic_value_map%ROWTYPE;
363     retval  biblio.marc21_physical_characteristics%ROWTYPE;
364 BEGIN
365
366     FOR _007 IN SELECT oils_xpath_string('//*', value) FROM UNNEST(oils_xpath('//*[@tag="007"]', marc)) x(value) LOOP
367         IF _007 IS NOT NULL AND _007 <> '' THEN
368             SELECT * INTO ptype FROM config.marc21_physical_characteristic_type_map WHERE ptype_key = SUBSTRING( _007, 1, 1 );
369
370             IF ptype.ptype_key IS NOT NULL THEN
371                 FOR psf IN SELECT * FROM config.marc21_physical_characteristic_subfield_map WHERE ptype_key = ptype.ptype_key LOOP
372                     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 );
373
374                     IF pval.id IS NOT NULL THEN
375                         rowid := rowid + 1;
376                         retval.id := rowid;
377                         retval.ptype := ptype.ptype_key;
378                         retval.subfield := psf.id;
379                         retval.value := pval.id;
380                         RETURN NEXT retval;
381                     END IF;
382
383                 END LOOP;
384             END IF;
385         END IF;
386     END LOOP;
387
388     RETURN;
389 END;
390 $func$ LANGUAGE PLPGSQL;
391
392 CREATE TYPE vandelay.flat_marc AS ( tag CHAR(3), ind1 TEXT, ind2 TEXT, subfield TEXT, value TEXT );
393 CREATE OR REPLACE FUNCTION vandelay.flay_marc ( TEXT ) RETURNS SETOF vandelay.flat_marc AS $func$
394
395 use MARC::Record;
396 use MARC::File::XML (BinaryEncoding => 'UTF-8');
397 use MARC::Charset;
398 use strict;
399
400 MARC::Charset->assume_unicode(1);
401
402 my $xml = shift;
403 my $r = MARC::Record->new_from_xml( $xml );
404
405 return_next( { tag => 'LDR', value => $r->leader } );
406
407 for my $f ( $r->fields ) {
408     if ($f->is_control_field) {
409         return_next({ tag => $f->tag, value => $f->data });
410     } else {
411         for my $s ($f->subfields) {
412             return_next({
413                 tag      => $f->tag,
414                 ind1     => $f->indicator(1),
415                 ind2     => $f->indicator(2),
416                 subfield => $s->[0],
417                 value    => $s->[1]
418             });
419
420             if ( $f->tag eq '245' and $s->[0] eq 'a' ) {
421                 my $trim = $f->indicator(2) || 0;
422                 return_next({
423                     tag      => 'tnf',
424                     ind1     => $f->indicator(1),
425                     ind2     => $f->indicator(2),
426                     subfield => 'a',
427                     value    => substr( $s->[1], $trim )
428                 });
429             }
430         }
431     }
432 }
433
434 return undef;
435
436 $func$ LANGUAGE PLPERLU;
437
438 CREATE OR REPLACE FUNCTION vandelay.flatten_marc ( marc TEXT ) RETURNS SETOF vandelay.flat_marc AS $func$
439 DECLARE
440     output  vandelay.flat_marc%ROWTYPE;
441     field   RECORD;
442 BEGIN
443     FOR field IN SELECT * FROM vandelay.flay_marc( marc ) LOOP
444         output.ind1 := field.ind1;
445         output.ind2 := field.ind2;
446         output.tag := field.tag;
447         output.subfield := field.subfield;
448         IF field.subfield IS NOT NULL AND field.tag NOT IN ('020','022','024') THEN -- exclude standard numbers and control fields
449             output.value := naco_normalize(field.value, field.subfield);
450         ELSE
451             output.value := field.value;
452         END IF;
453
454         CONTINUE WHEN output.value IS NULL;
455
456         RETURN NEXT output;
457     END LOOP;
458 END;
459 $func$ LANGUAGE PLPGSQL;
460
461 CREATE OR REPLACE FUNCTION vandelay.extract_rec_attrs ( xml TEXT, attr_defs TEXT[]) RETURNS hstore AS $_$
462 DECLARE
463     transformed_xml TEXT;
464     prev_xfrm       TEXT;
465     normalizer      RECORD;
466     xfrm            config.xml_transform%ROWTYPE;
467     attr_value      TEXT;
468     new_attrs       HSTORE := ''::HSTORE;
469     attr_def        config.record_attr_definition%ROWTYPE;
470 BEGIN
471
472     FOR attr_def IN SELECT * FROM config.record_attr_definition WHERE name IN (SELECT * FROM UNNEST(attr_defs)) ORDER BY format LOOP
473
474         IF attr_def.tag IS NOT NULL THEN -- tag (and optional subfield list) selection
475             SELECT  STRING_AGG(x.value, COALESCE(attr_def.joiner,' ')) INTO attr_value
476               FROM  vandelay.flatten_marc(xml) AS x
477               WHERE x.tag LIKE attr_def.tag
478                     AND CASE
479                         WHEN attr_def.sf_list IS NOT NULL
480                             THEN POSITION(x.subfield IN attr_def.sf_list) > 0
481                         ELSE TRUE
482                         END
483               GROUP BY x.tag
484               ORDER BY x.tag
485               LIMIT 1;
486
487         ELSIF attr_def.fixed_field IS NOT NULL THEN -- a named fixed field, see config.marc21_ff_pos_map.fixed_field
488             attr_value := vandelay.marc21_extract_fixed_field(xml, attr_def.fixed_field);
489
490         ELSIF attr_def.xpath IS NOT NULL THEN -- and xpath expression
491
492             SELECT INTO xfrm * FROM config.xml_transform WHERE name = attr_def.format;
493
494             -- See if we can skip the XSLT ... it's expensive
495             IF prev_xfrm IS NULL OR prev_xfrm <> xfrm.name THEN
496                 -- Can't skip the transform
497                 IF xfrm.xslt <> '---' THEN
498                     transformed_xml := oils_xslt_process(xml,xfrm.xslt);
499                 ELSE
500                     transformed_xml := xml;
501                 END IF;
502
503                 prev_xfrm := xfrm.name;
504             END IF;
505
506             IF xfrm.name IS NULL THEN
507                 -- just grab the marcxml (empty) transform
508                 SELECT INTO xfrm * FROM config.xml_transform WHERE xslt = '---' LIMIT 1;
509                 prev_xfrm := xfrm.name;
510             END IF;
511
512             attr_value := oils_xpath_string(attr_def.xpath, transformed_xml, COALESCE(attr_def.joiner,' '), ARRAY[ARRAY[xfrm.prefix, xfrm.namespace_uri]]);
513
514         ELSIF attr_def.phys_char_sf IS NOT NULL THEN -- a named Physical Characteristic, see config.marc21_physical_characteristic_*_map
515             SELECT  m.value::TEXT INTO attr_value
516               FROM  vandelay.marc21_physical_characteristics(xml) v
517                     JOIN config.marc21_physical_characteristic_value_map m ON (m.id = v.value)
518               WHERE v.subfield = attr_def.phys_char_sf
519               LIMIT 1; -- Just in case ...
520
521         END IF;
522
523         -- apply index normalizers to attr_value
524         FOR normalizer IN
525             SELECT  n.func AS func,
526                     n.param_count AS param_count,
527                     m.params AS params
528               FROM  config.index_normalizer n
529                     JOIN config.record_attr_index_norm_map m ON (m.norm = n.id)
530               WHERE attr = attr_def.name
531               ORDER BY m.pos LOOP
532                 EXECUTE 'SELECT ' || normalizer.func || '(' ||
533                     quote_nullable( attr_value ) ||
534                     CASE
535                         WHEN normalizer.param_count > 0
536                             THEN ',' || REPLACE(REPLACE(BTRIM(normalizer.params,'[]'),E'\'',E'\\\''),E'"',E'\'')
537                             ELSE ''
538                         END ||
539                     ')' INTO attr_value;
540
541         END LOOP;
542
543         -- Add the new value to the hstore
544         new_attrs := new_attrs || hstore( attr_def.name, attr_value );
545
546     END LOOP;
547
548     RETURN new_attrs;
549 END;
550 $_$ LANGUAGE PLPGSQL;
551
552 CREATE OR REPLACE FUNCTION vandelay.extract_rec_attrs ( xml TEXT ) RETURNS hstore AS $_$
553     SELECT vandelay.extract_rec_attrs( $1, (SELECT ARRAY_AGG(name) FROM config.record_attr_definition));
554 $_$ LANGUAGE SQL;
555
556 -- Everything between this comment and the beginning of the definition of
557 -- vandelay.match_bib_record() is strictly in service of that function.
558 CREATE TYPE vandelay.match_set_test_result AS (record BIGINT, quality INTEGER);
559
560 CREATE OR REPLACE FUNCTION vandelay.match_set_test_marcxml(
561     match_set_id INTEGER, record_xml TEXT, bucket_id INTEGER 
562 ) RETURNS SETOF vandelay.match_set_test_result AS $$
563 DECLARE
564     tags_rstore HSTORE;
565     svf_rstore  HSTORE;
566     coal        TEXT;
567     joins       TEXT;
568     query_      TEXT;
569     wq          TEXT;
570     qvalue      INTEGER;
571     rec         RECORD;
572 BEGIN
573     tags_rstore := vandelay.flatten_marc_hstore(record_xml);
574     svf_rstore := vandelay.extract_rec_attrs(record_xml);
575
576     CREATE TEMPORARY TABLE _vandelay_tmp_qrows (q INTEGER);
577     CREATE TEMPORARY TABLE _vandelay_tmp_jrows (j TEXT);
578
579     -- generate the where clause and return that directly (into wq), and as
580     -- a side-effect, populate the _vandelay_tmp_[qj]rows tables.
581     wq := vandelay.get_expr_from_match_set(match_set_id, tags_rstore);
582
583     query_ := 'SELECT DISTINCT(record), ';
584
585     -- qrows table is for the quality bits we add to the SELECT clause
586     SELECT STRING_AGG(
587         'COALESCE(n' || q::TEXT || '.quality, 0)', ' + '
588     ) INTO coal FROM _vandelay_tmp_qrows;
589
590     -- our query string so far is the SELECT clause and the inital FROM.
591     -- no JOINs yet nor the WHERE clause
592     query_ := query_ || coal || ' AS quality ' || E'\n';
593
594     -- jrows table is for the joins we must make (and the real text conditions)
595     SELECT STRING_AGG(j, E'\n') INTO joins
596         FROM _vandelay_tmp_jrows;
597
598     -- add those joins and the where clause to our query.
599     query_ := query_ || joins || E'\n';
600
601     -- join the record bucket
602     IF bucket_id IS NOT NULL THEN
603         query_ := query_ || 'JOIN container.biblio_record_entry_bucket_item ' ||
604             'brebi ON (brebi.target_biblio_record_entry = record ' ||
605             'AND brebi.bucket = ' || bucket_id || E')\n';
606     END IF;
607
608     query_ := query_ || 'JOIN biblio.record_entry bre ON (bre.id = record) ' || 'WHERE ' || wq || ' AND not bre.deleted';
609
610     -- this will return rows of record,quality
611     FOR rec IN EXECUTE query_ USING tags_rstore, svf_rstore LOOP
612         RETURN NEXT rec;
613     END LOOP;
614
615     DROP TABLE _vandelay_tmp_qrows;
616     DROP TABLE _vandelay_tmp_jrows;
617     RETURN;
618 END;
619 $$ LANGUAGE PLPGSQL;
620
621
622 CREATE OR REPLACE FUNCTION vandelay.flatten_marc_hstore(
623     record_xml TEXT
624 ) RETURNS HSTORE AS $func$
625 BEGIN
626     RETURN (SELECT
627         HSTORE(
628             ARRAY_AGG(tag || (COALESCE(subfield, ''))),
629             ARRAY_AGG(value)
630         )
631         FROM (
632             SELECT  tag, subfield, ARRAY_AGG(value)::TEXT AS value
633               FROM  (SELECT tag,
634                             subfield,
635                             CASE WHEN tag = '020' THEN -- caseless -- isbn
636                                 LOWER((SELECT REGEXP_MATCHES(value,$$^(\S{10,17})$$))[1] || '%')
637                             WHEN tag = '022' THEN -- caseless -- issn
638                                 LOWER((SELECT REGEXP_MATCHES(value,$$^(\S{4}[- ]?\S{4})$$))[1] || '%')
639                             WHEN tag = '024' THEN -- caseless -- upc (other)
640                                 LOWER(value || '%')
641                             ELSE
642                                 value
643                             END AS value
644                       FROM  vandelay.flatten_marc(record_xml)) x
645                 GROUP BY tag, subfield ORDER BY tag, subfield
646         ) subquery
647     );
648 END;
649 $func$ LANGUAGE PLPGSQL;
650
651 -- backwards compat version so we don't have 
652 -- to modify vandelay.match_set_test_marcxml()
653 CREATE OR REPLACE FUNCTION vandelay.get_expr_from_match_set(
654     match_set_id INTEGER,
655     tags_rstore HSTORE
656 ) RETURNS TEXT AS $$
657 BEGIN
658     RETURN vandelay.get_expr_from_match_set(
659         match_set_id, tags_rstore, NULL);
660 END;
661 $$  LANGUAGE PLPGSQL;
662
663 CREATE OR REPLACE FUNCTION vandelay.get_expr_from_match_set(
664     match_set_id INTEGER,
665     tags_rstore HSTORE,
666     auth_heading TEXT
667 ) RETURNS TEXT AS $$
668 DECLARE
669     root vandelay.match_set_point;
670 BEGIN
671     SELECT * INTO root FROM vandelay.match_set_point
672         WHERE parent IS NULL AND match_set = match_set_id;
673
674     RETURN vandelay.get_expr_from_match_set_point(
675         root, tags_rstore, auth_heading);
676 END;
677 $$  LANGUAGE PLPGSQL;
678
679 CREATE OR REPLACE FUNCTION vandelay.get_expr_from_match_set_point(
680     node vandelay.match_set_point,
681     tags_rstore HSTORE,
682     auth_heading TEXT
683 ) RETURNS TEXT AS $$
684 DECLARE
685     q           TEXT;
686     i           INTEGER;
687     this_op     TEXT;
688     children    INTEGER[];
689     child       vandelay.match_set_point;
690 BEGIN
691     SELECT ARRAY_AGG(id) INTO children FROM vandelay.match_set_point
692         WHERE parent = node.id;
693
694     IF ARRAY_LENGTH(children, 1) > 0 THEN
695         this_op := vandelay._get_expr_render_one(node);
696         q := '(';
697         i := 1;
698         WHILE children[i] IS NOT NULL LOOP
699             SELECT * INTO child FROM vandelay.match_set_point
700                 WHERE id = children[i];
701             IF i > 1 THEN
702                 q := q || ' ' || this_op || ' ';
703             END IF;
704             i := i + 1;
705             q := q || vandelay.get_expr_from_match_set_point(
706                 child, tags_rstore, auth_heading);
707         END LOOP;
708         q := q || ')';
709         RETURN q;
710     ELSIF node.bool_op IS NULL THEN
711         PERFORM vandelay._get_expr_push_qrow(node);
712         PERFORM vandelay._get_expr_push_jrow(node, tags_rstore, auth_heading);
713         RETURN vandelay._get_expr_render_one(node);
714     ELSE
715         RETURN '';
716     END IF;
717 END;
718 $$  LANGUAGE PLPGSQL;
719
720 CREATE OR REPLACE FUNCTION vandelay._get_expr_push_qrow(
721     node vandelay.match_set_point
722 ) RETURNS VOID AS $$
723 DECLARE
724 BEGIN
725     INSERT INTO _vandelay_tmp_qrows (q) VALUES (node.id);
726 END;
727 $$ LANGUAGE PLPGSQL;
728
729 CREATE OR REPLACE FUNCTION vandelay._get_expr_push_jrow(
730     node vandelay.match_set_point,
731     tags_rstore HSTORE,
732     auth_heading TEXT
733 ) RETURNS VOID AS $$
734 DECLARE
735     jrow        TEXT;
736     my_alias    TEXT;
737     op          TEXT;
738     tagkey      TEXT;
739     caseless    BOOL;
740     jrow_count  INT;
741     my_using    TEXT;
742     my_join     TEXT;
743     rec_table   TEXT;
744 BEGIN
745     -- remember $1 is tags_rstore, and $2 is svf_rstore
746     -- a non-NULL auth_heading means we're matching authority records
747
748     IF auth_heading IS NOT NULL THEN
749         rec_table := 'authority.full_rec';
750     ELSE
751         rec_table := 'metabib.full_rec';
752     END IF;
753
754     caseless := FALSE;
755     SELECT COUNT(*) INTO jrow_count FROM _vandelay_tmp_jrows;
756     IF jrow_count > 0 THEN
757         my_using := ' USING (record)';
758         my_join := 'FULL OUTER JOIN';
759     ELSE
760         my_using := '';
761         my_join := 'FROM';
762     END IF;
763
764     IF node.tag IS NOT NULL THEN
765         caseless := (node.tag IN ('020', '022', '024'));
766         tagkey := node.tag;
767         IF node.subfield IS NOT NULL THEN
768             tagkey := tagkey || node.subfield;
769         END IF;
770     END IF;
771
772     IF node.negate THEN
773         IF caseless THEN
774             op := 'NOT LIKE';
775         ELSE
776             op := '<>';
777         END IF;
778     ELSE
779         IF caseless THEN
780             op := 'LIKE';
781         ELSE
782             op := '=';
783         END IF;
784     END IF;
785
786     my_alias := 'n' || node.id::TEXT;
787
788     jrow := my_join || ' (SELECT *, ';
789     IF node.tag IS NOT NULL THEN
790         jrow := jrow  || node.quality ||
791             ' AS quality FROM ' || rec_table || ' mfr WHERE mfr.tag = ''' ||
792             node.tag || '''';
793         IF node.subfield IS NOT NULL THEN
794             jrow := jrow || ' AND mfr.subfield = ''' ||
795                 node.subfield || '''';
796         END IF;
797         jrow := jrow || ' AND (';
798         jrow := jrow || vandelay._node_tag_comparisons(caseless, op, tags_rstore, tagkey);
799         jrow := jrow || ')) ' || my_alias || my_using || E'\n';
800     ELSE    -- svf
801         IF auth_heading IS NOT NULL THEN -- authority record
802             IF node.heading AND auth_heading <> '' THEN
803                 jrow := jrow || 'id AS record, ' || node.quality ||
804                 ' AS quality FROM authority.record_entry are ' ||
805                 ' WHERE are.heading = ''' || auth_heading || '''';
806                 jrow := jrow || ') ' || my_alias || my_using || E'\n';
807             END IF;
808         ELSE -- bib record
809             jrow := jrow || 'id AS record, ' || node.quality ||
810                 ' AS quality FROM metabib.record_attr_flat mraf WHERE mraf.attr = ''' ||
811                 node.svf || ''' AND mraf.value ' || op || ' $2->''' || node.svf || ''') ' ||
812                 my_alias || my_using || E'\n';
813         END IF;
814     END IF;
815     INSERT INTO _vandelay_tmp_jrows (j) VALUES (jrow);
816 END;
817 $$ LANGUAGE PLPGSQL;
818
819 CREATE OR REPLACE FUNCTION vandelay._node_tag_comparisons(
820     caseless BOOLEAN,
821     op TEXT,
822     tags_rstore HSTORE,
823     tagkey TEXT
824 ) RETURNS TEXT AS $$
825 DECLARE
826     result  TEXT;
827     i       INT;
828     vals    TEXT[];
829 BEGIN
830     i := 1;
831     vals := tags_rstore->tagkey;
832     result := '';
833
834     WHILE TRUE LOOP
835         IF i > 1 THEN
836             IF vals[i] IS NULL THEN
837                 EXIT;
838             ELSE
839                 result := result || ' OR ';
840             END IF;
841         END IF;
842
843         IF caseless THEN
844             result := result || 'LOWER(mfr.value) ' || op;
845         ELSE
846             result := result || 'mfr.value ' || op;
847         END IF;
848
849         result := result || ' ' || COALESCE('''' || vals[i] || '''', 'NULL');
850
851         IF vals[i] IS NULL THEN
852             EXIT;
853         END IF;
854         i := i + 1;
855     END LOOP;
856
857     RETURN result;
858
859 END;
860 $$ LANGUAGE PLPGSQL;
861
862 CREATE OR REPLACE FUNCTION vandelay._get_expr_render_one(
863     node vandelay.match_set_point
864 ) RETURNS TEXT AS $$
865 DECLARE
866     s           TEXT;
867 BEGIN
868     IF node.bool_op IS NOT NULL THEN
869         RETURN node.bool_op;
870     ELSE
871         RETURN '(n' || node.id::TEXT || '.id IS NOT NULL)';
872     END IF;
873 END;
874 $$ LANGUAGE PLPGSQL;
875
876 CREATE OR REPLACE FUNCTION vandelay.match_bib_record() RETURNS TRIGGER AS $func$
877 DECLARE
878     incoming_existing_id    TEXT;
879     test_result             vandelay.match_set_test_result%ROWTYPE;
880     tmp_rec                 BIGINT;
881     match_set               INT;
882     match_bucket            INT;
883 BEGIN
884     IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
885         RETURN NEW;
886     END IF;
887
888     DELETE FROM vandelay.bib_match WHERE queued_record = NEW.id;
889
890     SELECT q.match_set INTO match_set FROM vandelay.bib_queue q WHERE q.id = NEW.queue;
891
892     IF match_set IS NOT NULL THEN
893         NEW.quality := vandelay.measure_record_quality( NEW.marc, match_set );
894     END IF;
895
896     -- Perfect matches on 901$c exit early with a match with high quality.
897     incoming_existing_id :=
898         oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]', NEW.marc);
899
900     IF incoming_existing_id IS NOT NULL AND incoming_existing_id != '' THEN
901         SELECT id INTO tmp_rec FROM biblio.record_entry WHERE id = incoming_existing_id::bigint;
902         IF tmp_rec IS NOT NULL THEN
903             INSERT INTO vandelay.bib_match (queued_record, eg_record, match_score, quality) 
904                 SELECT
905                     NEW.id, 
906                     b.id,
907                     9999,
908                     -- note: no match_set means quality==0
909                     vandelay.measure_record_quality( b.marc, match_set )
910                 FROM biblio.record_entry b
911                 WHERE id = incoming_existing_id::bigint;
912         END IF;
913     END IF;
914
915     IF match_set IS NULL THEN
916         RETURN NEW;
917     END IF;
918
919     SELECT q.match_bucket INTO match_bucket FROM vandelay.bib_queue q WHERE q.id = NEW.queue;
920
921     FOR test_result IN SELECT * FROM
922         vandelay.match_set_test_marcxml(match_set, NEW.marc, match_bucket) LOOP
923
924         INSERT INTO vandelay.bib_match ( queued_record, eg_record, match_score, quality )
925             SELECT  
926                 NEW.id,
927                 test_result.record,
928                 test_result.quality,
929                 vandelay.measure_record_quality( b.marc, match_set )
930                 FROM  biblio.record_entry b
931                 WHERE id = test_result.record;
932
933     END LOOP;
934
935     RETURN NEW;
936 END;
937 $func$ LANGUAGE PLPGSQL;
938
939 CREATE OR REPLACE FUNCTION vandelay.measure_record_quality ( xml TEXT, match_set_id INT ) RETURNS INT AS $_$
940 DECLARE
941     out_q   INT := 0;
942     rvalue  TEXT;
943     test    vandelay.match_set_quality%ROWTYPE;
944 BEGIN
945
946     FOR test IN SELECT * FROM vandelay.match_set_quality WHERE match_set = match_set_id LOOP
947         IF test.tag IS NOT NULL THEN
948             FOR rvalue IN SELECT value FROM vandelay.flatten_marc( xml ) WHERE tag = test.tag AND subfield = test.subfield LOOP
949                 IF test.value = rvalue THEN
950                     out_q := out_q + test.quality;
951                 END IF;
952             END LOOP;
953         ELSE
954             IF test.value = vandelay.extract_rec_attrs(xml, ARRAY[test.svf]) -> test.svf THEN
955                 out_q := out_q + test.quality;
956             END IF;
957         END IF;
958     END LOOP;
959
960     RETURN out_q;
961 END;
962 $_$ LANGUAGE PLPGSQL;
963
964 CREATE TYPE vandelay.tcn_data AS (tcn TEXT, tcn_source TEXT, used BOOL);
965 CREATE OR REPLACE FUNCTION vandelay.find_bib_tcn_data ( xml TEXT ) RETURNS SETOF vandelay.tcn_data AS $_$
966 DECLARE
967     eg_tcn          TEXT;
968     eg_tcn_source   TEXT;
969     output          vandelay.tcn_data%ROWTYPE;
970 BEGIN
971
972     -- 001/003
973     eg_tcn := BTRIM((oils_xpath('//*[@tag="001"]/text()',xml))[1]);
974     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
975
976         eg_tcn_source := BTRIM((oils_xpath('//*[@tag="003"]/text()',xml))[1]);
977         IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
978             eg_tcn_source := 'System Local';
979         END IF;
980
981         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
982
983         IF NOT FOUND THEN
984             output.used := FALSE;
985         ELSE
986             output.used := TRUE;
987         END IF;
988
989         output.tcn := eg_tcn;
990         output.tcn_source := eg_tcn_source;
991         RETURN NEXT output;
992
993     END IF;
994
995     -- 901 ab
996     eg_tcn := BTRIM((oils_xpath('//*[@tag="901"]/*[@code="a"]/text()',xml))[1]);
997     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
998
999         eg_tcn_source := BTRIM((oils_xpath('//*[@tag="901"]/*[@code="b"]/text()',xml))[1]);
1000         IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
1001             eg_tcn_source := 'System Local';
1002         END IF;
1003
1004         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
1005
1006         IF NOT FOUND THEN
1007             output.used := FALSE;
1008         ELSE
1009             output.used := TRUE;
1010         END IF;
1011
1012         output.tcn := eg_tcn;
1013         output.tcn_source := eg_tcn_source;
1014         RETURN NEXT output;
1015
1016     END IF;
1017
1018     -- 039 ab
1019     eg_tcn := BTRIM((oils_xpath('//*[@tag="039"]/*[@code="a"]/text()',xml))[1]);
1020     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1021
1022         eg_tcn_source := BTRIM((oils_xpath('//*[@tag="039"]/*[@code="b"]/text()',xml))[1]);
1023         IF eg_tcn_source IS NULL OR eg_tcn_source = '' THEN
1024             eg_tcn_source := 'System Local';
1025         END IF;
1026
1027         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
1028
1029         IF NOT FOUND THEN
1030             output.used := FALSE;
1031         ELSE
1032             output.used := TRUE;
1033         END IF;
1034
1035         output.tcn := eg_tcn;
1036         output.tcn_source := eg_tcn_source;
1037         RETURN NEXT output;
1038
1039     END IF;
1040
1041     -- 020 a
1042     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="020"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
1043     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1044
1045         eg_tcn_source := 'ISBN';
1046
1047         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
1048
1049         IF NOT FOUND THEN
1050             output.used := FALSE;
1051         ELSE
1052             output.used := TRUE;
1053         END IF;
1054
1055         output.tcn := eg_tcn;
1056         output.tcn_source := eg_tcn_source;
1057         RETURN NEXT output;
1058
1059     END IF;
1060
1061     -- 022 a
1062     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="022"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
1063     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1064
1065         eg_tcn_source := 'ISSN';
1066
1067         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
1068
1069         IF NOT FOUND THEN
1070             output.used := FALSE;
1071         ELSE
1072             output.used := TRUE;
1073         END IF;
1074
1075         output.tcn := eg_tcn;
1076         output.tcn_source := eg_tcn_source;
1077         RETURN NEXT output;
1078
1079     END IF;
1080
1081     -- 010 a
1082     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="010"]/*[@code="a"]/text()',xml))[1], $re$^(\w+).*?$$re$, $re$\1$re$);
1083     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1084
1085         eg_tcn_source := 'LCCN';
1086
1087         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
1088
1089         IF NOT FOUND THEN
1090             output.used := FALSE;
1091         ELSE
1092             output.used := TRUE;
1093         END IF;
1094
1095         output.tcn := eg_tcn;
1096         output.tcn_source := eg_tcn_source;
1097         RETURN NEXT output;
1098
1099     END IF;
1100
1101     -- 035 a
1102     eg_tcn := REGEXP_REPLACE((oils_xpath('//*[@tag="035"]/*[@code="a"]/text()',xml))[1], $re$^.*?(\w+)$$re$, $re$\1$re$);
1103     IF eg_tcn IS NOT NULL AND eg_tcn <> '' THEN
1104
1105         eg_tcn_source := 'System Legacy';
1106
1107         PERFORM id FROM biblio.record_entry WHERE tcn_value = eg_tcn  AND NOT deleted;
1108
1109         IF NOT FOUND THEN
1110             output.used := FALSE;
1111         ELSE
1112             output.used := TRUE;
1113         END IF;
1114
1115         output.tcn := eg_tcn;
1116         output.tcn_source := eg_tcn_source;
1117         RETURN NEXT output;
1118
1119     END IF;
1120
1121     RETURN;
1122 END;
1123 $_$ LANGUAGE PLPGSQL;
1124
1125 CREATE OR REPLACE FUNCTION vandelay.add_field ( target_xml TEXT, source_xml TEXT, field TEXT, force_add INT ) RETURNS TEXT AS $_$
1126
1127     use MARC::Record;
1128     use MARC::File::XML (BinaryEncoding => 'UTF-8');
1129     use MARC::Charset;
1130     use strict;
1131
1132     MARC::Charset->assume_unicode(1);
1133
1134     my $target_xml = shift;
1135     my $source_xml = shift;
1136     my $field_spec = shift;
1137     my $force_add = shift || 0;
1138
1139     my $target_r = MARC::Record->new_from_xml( $target_xml );
1140     my $source_r = MARC::Record->new_from_xml( $source_xml );
1141
1142     return $target_xml unless ($target_r && $source_r);
1143
1144     my @field_list = split(',', $field_spec);
1145
1146     my %fields;
1147     for my $f (@field_list) {
1148         $f =~ s/^\s*//; $f =~ s/\s*$//;
1149         if ($f =~ /^(.{3})(\w*)(?:\[([^]]*)\])?$/) {
1150             my $field = $1;
1151             $field =~ s/\s+//;
1152             my $sf = $2;
1153             $sf =~ s/\s+//;
1154             my $match = $3;
1155             $match =~ s/^\s*//; $match =~ s/\s*$//;
1156             $fields{$field} = { sf => [ split('', $sf) ] };
1157             if ($match) {
1158                 my ($msf,$mre) = split('~', $match);
1159                 if (length($msf) > 0 and length($mre) > 0) {
1160                     $msf =~ s/^\s*//; $msf =~ s/\s*$//;
1161                     $mre =~ s/^\s*//; $mre =~ s/\s*$//;
1162                     $fields{$field}{match} = { sf => $msf, re => qr/$mre/ };
1163                 }
1164             }
1165         }
1166     }
1167
1168     for my $f ( keys %fields) {
1169         if ( @{$fields{$f}{sf}} ) {
1170             for my $from_field ($source_r->field( $f )) {
1171                 my @tos = $target_r->field( $f );
1172                 if (!@tos) {
1173                     next if (exists($fields{$f}{match}) and !$force_add);
1174                     my @new_fields = map { $_->clone } $source_r->field( $f );
1175                     $target_r->insert_fields_ordered( @new_fields );
1176                 } else {
1177                     for my $to_field (@tos) {
1178                         if (exists($fields{$f}{match})) {
1179                             next unless (grep { $_ =~ $fields{$f}{match}{re} } $to_field->subfield($fields{$f}{match}{sf}));
1180                         }
1181                         for my $old_sf ($from_field->subfields) {
1182                             $to_field->add_subfields( @$old_sf ) if grep(/$$old_sf[0]/,@{$fields{$f}{sf}});
1183                         }
1184                     }
1185                 }
1186             }
1187         } else {
1188             my @new_fields = map { $_->clone } $source_r->field( $f );
1189             $target_r->insert_fields_ordered( @new_fields );
1190         }
1191     }
1192
1193     $target_xml = $target_r->as_xml_record;
1194     $target_xml =~ s/^<\?.+?\?>$//mo;
1195     $target_xml =~ s/\n//sgo;
1196     $target_xml =~ s/>\s+</></sgo;
1197
1198     return $target_xml;
1199
1200 $_$ LANGUAGE PLPERLU;
1201
1202 CREATE OR REPLACE FUNCTION vandelay.add_field ( target_xml TEXT, source_xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1203     SELECT vandelay.add_field( $1, $2, $3, 0 );
1204 $_$ LANGUAGE SQL;
1205
1206 CREATE OR REPLACE FUNCTION vandelay.strip_field ( xml TEXT, field TEXT ) RETURNS TEXT AS $_$
1207
1208     use MARC::Record;
1209     use MARC::File::XML (BinaryEncoding => 'UTF-8');
1210     use MARC::Charset;
1211     use strict;
1212
1213     MARC::Charset->assume_unicode(1);
1214
1215     my $xml = shift;
1216     my $r = MARC::Record->new_from_xml( $xml );
1217
1218     return $xml unless ($r);
1219
1220     my $field_spec = shift;
1221     my @field_list = split(',', $field_spec);
1222
1223     my %fields;
1224     for my $f (@field_list) {
1225         $f =~ s/^\s*//; $f =~ s/\s*$//;
1226         if ($f =~ /^(.{3})(\w*)(?:\[([^]]*)\])?$/) {
1227             my $field = $1;
1228             $field =~ s/\s+//;
1229             my $sf = $2;
1230             $sf =~ s/\s+//;
1231             my $match = $3;
1232             $match =~ s/^\s*//; $match =~ s/\s*$//;
1233             $fields{$field} = { sf => [ split('', $sf) ] };
1234             if ($match) {
1235                 my ($msf,$mre) = split('~', $match);
1236                 if (length($msf) > 0 and length($mre) > 0) {
1237                     $msf =~ s/^\s*//; $msf =~ s/\s*$//;
1238                     $mre =~ s/^\s*//; $mre =~ s/\s*$//;
1239                     $fields{$field}{match} = { sf => $msf, re => qr/$mre/ };
1240                 }
1241             }
1242         }
1243     }
1244
1245     for my $f ( keys %fields) {
1246         for my $to_field ($r->field( $f )) {
1247             if (exists($fields{$f}{match})) {
1248                 next unless (grep { $_ =~ $fields{$f}{match}{re} } $to_field->subfield($fields{$f}{match}{sf}));
1249             }
1250
1251             if ( @{$fields{$f}{sf}} ) {
1252                 $to_field->delete_subfield(code => $fields{$f}{sf});
1253             } else {
1254                 $r->delete_field( $to_field );
1255             }
1256         }
1257     }
1258
1259     $xml = $r->as_xml_record;
1260     $xml =~ s/^<\?.+?\?>$//mo;
1261     $xml =~ s/\n//sgo;
1262     $xml =~ s/>\s+</></sgo;
1263
1264     return $xml;
1265
1266 $_$ LANGUAGE PLPERLU;
1267
1268 CREATE OR REPLACE FUNCTION vandelay.replace_field 
1269     (target_xml TEXT, source_xml TEXT, field TEXT) RETURNS TEXT AS $_$
1270
1271     use strict;
1272     use MARC::Record;
1273     use MARC::Field;
1274     use MARC::File::XML (BinaryEncoding => 'UTF-8');
1275     use MARC::Charset;
1276
1277     MARC::Charset->assume_unicode(1);
1278
1279     my $target_xml = shift;
1280     my $source_xml = shift;
1281     my $field_spec = shift;
1282
1283     my $target_r = MARC::Record->new_from_xml($target_xml);
1284     my $source_r = MARC::Record->new_from_xml($source_xml);
1285
1286     return $target_xml unless $target_r && $source_r;
1287
1288     # Extract the field_spec components into MARC tags, subfields, 
1289     # and regex matches.  Copied wholesale from vandelay.strip_field()
1290
1291     my @field_list = split(',', $field_spec);
1292     my %fields;
1293     for my $f (@field_list) {
1294         $f =~ s/^\s*//; $f =~ s/\s*$//;
1295         if ($f =~ /^(.{3})(\w*)(?:\[([^]]*)\])?$/) {
1296             my $field = $1;
1297             $field =~ s/\s+//;
1298             my $sf = $2;
1299             $sf =~ s/\s+//;
1300             my $match = $3;
1301             $match =~ s/^\s*//; $match =~ s/\s*$//;
1302             $fields{$field} = { sf => [ split('', $sf) ] };
1303             if ($match) {
1304                 my ($msf,$mre) = split('~', $match);
1305                 if (length($msf) > 0 and length($mre) > 0) {
1306                     $msf =~ s/^\s*//; $msf =~ s/\s*$//;
1307                     $mre =~ s/^\s*//; $mre =~ s/\s*$//;
1308                     $fields{$field}{match} = { sf => $msf, re => qr/$mre/ };
1309                 }
1310             }
1311         }
1312     }
1313
1314     # Returns a flat list of subfield (code, value, code, value, ...)
1315     # suitable for adding to a MARC::Field.
1316     sub generate_replacement_subfields {
1317         my ($source_field, $target_field, @controlled_subfields) = @_;
1318
1319         # Performing a wholesale field replacment.  
1320         # Use the entire source field as-is.
1321         return map {$_->[0], $_->[1]} $source_field->subfields
1322             unless @controlled_subfields;
1323
1324         my @new_subfields;
1325
1326         # Iterate over all target field subfields:
1327         # 1. Keep uncontrolled subfields as is.
1328         # 2. Replace values for controlled subfields when a
1329         #    replacement value exists on the source record.
1330         # 3. Delete values for controlled subfields when no 
1331         #    replacement value exists on the source record.
1332
1333         for my $target_sf ($target_field->subfields) {
1334             my $subfield = $target_sf->[0];
1335             my $target_val = $target_sf->[1];
1336
1337             if (grep {$_ eq $subfield} @controlled_subfields) {
1338                 if (my $source_val = $source_field->subfield($subfield)) {
1339                     # We have a replacement value
1340                     push(@new_subfields, $subfield, $source_val);
1341                 } else {
1342                     # no replacement value for controlled subfield, drop it.
1343                 }
1344             } else {
1345                 # Field is not controlled.  Copy it over as-is.
1346                 push(@new_subfields, $subfield, $target_val);
1347             }
1348         }
1349
1350         # Iterate over all subfields in the source field and back-fill
1351         # any values that exist only in the source field.  Insert these
1352         # subfields in the same relative position they exist in the
1353         # source field.
1354                 
1355         my @seen_subfields;
1356         for my $source_sf ($source_field->subfields) {
1357             my $subfield = $source_sf->[0];
1358             my $source_val = $source_sf->[1];
1359             push(@seen_subfields, $subfield);
1360
1361             # target field already contains this subfield, 
1362             # so it would have been addressed above.
1363             next if $target_field->subfield($subfield);
1364
1365             # Ignore uncontrolled subfields.
1366             next unless grep {$_ eq $subfield} @controlled_subfields;
1367
1368             # Adding a new subfield.  Find its relative position and add
1369             # it to the list under construction.  Work backwards from
1370             # the list of already seen subfields to find the best slot.
1371
1372             my $done = 0;
1373             for my $seen_sf (reverse(@seen_subfields)) {
1374                 my $idx = @new_subfields;
1375                 for my $new_sf (reverse(@new_subfields)) {
1376                     $idx--;
1377                     next if $idx % 2 == 1; # sf codes are in the even slots
1378
1379                     if ($new_subfields[$idx] eq $seen_sf) {
1380                         splice(@new_subfields, $idx + 2, 0, $subfield, $source_val);
1381                         $done = 1;
1382                         last;
1383                     }
1384                 }
1385                 last if $done;
1386             }
1387
1388             # if no slot was found, add to the end of the list.
1389             push(@new_subfields, $subfield, $source_val) unless $done;
1390         }
1391
1392         return @new_subfields;
1393     }
1394
1395     # MARC tag loop
1396     for my $f (keys %fields) {
1397         my $tag_idx = -1;
1398         for my $target_field ($target_r->field($f)) {
1399
1400             # field spec contains a regex for this field.  Confirm field on 
1401             # target record matches the specified regex before replacing.
1402             if (exists($fields{$f}{match})) {
1403                 next unless (grep { $_ =~ $fields{$f}{match}{re} } 
1404                     $target_field->subfield($fields{$f}{match}{sf}));
1405             }
1406
1407             my @new_subfields;
1408             my @controlled_subfields = @{$fields{$f}{sf}};
1409
1410             # If the target record has multiple matching bib fields,
1411             # replace them from matching fields on the source record
1412             # in a predictable order to avoid replacing with them with
1413             # same source field repeatedly.
1414             my @source_fields = $source_r->field($f);
1415             my $source_field = $source_fields[++$tag_idx];
1416
1417             if (!$source_field && @controlled_subfields) {
1418                 # When there are more target fields than source fields
1419                 # and we are replacing values for subfields and not
1420                 # performing wholesale field replacment, use the last
1421                 # available source field as the input for all remaining
1422                 # target fields.
1423                 $source_field = $source_fields[$#source_fields];
1424             }
1425
1426             if (!$source_field) {
1427                 # No source field exists.  Delete all affected target
1428                 # data.  This is a little bit counterintuitive, but is
1429                 # backwards compatible with the previous version of this
1430                 # function which first deleted all affected data, then
1431                 # replaced values where possible.
1432                 if (@controlled_subfields) {
1433                     $target_field->delete_subfield($_) for @controlled_subfields;
1434                 } else {
1435                     $target_r->delete_field($target_field);
1436                 }
1437                 next;
1438             }
1439
1440             my @new_subfields = generate_replacement_subfields(
1441                 $source_field, $target_field, @controlled_subfields);
1442
1443             # Build the replacement field from scratch.  
1444             my $replacement_field = MARC::Field->new(
1445                 $target_field->tag,
1446                 $target_field->indicator(1),
1447                 $target_field->indicator(2),
1448                 @new_subfields
1449             );
1450
1451             $target_field->replace_with($replacement_field);
1452         }
1453     }
1454
1455     $target_xml = $target_r->as_xml_record;
1456     $target_xml =~ s/^<\?.+?\?>$//mo;
1457     $target_xml =~ s/\n//sgo;
1458     $target_xml =~ s/>\s+</></sgo;
1459
1460     return $target_xml;
1461
1462 $_$ LANGUAGE PLPERLU;
1463
1464 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 $_$
1465     SELECT vandelay.replace_field( vandelay.add_field( vandelay.strip_field( $1, $5) , $2, $3 ), $2, $4);
1466 $_$ LANGUAGE SQL;
1467
1468 CREATE TYPE vandelay.compile_profile AS (add_rule TEXT, replace_rule TEXT, preserve_rule TEXT, strip_rule TEXT);
1469 CREATE OR REPLACE FUNCTION vandelay.compile_profile ( incoming_xml TEXT ) RETURNS vandelay.compile_profile AS $_$
1470 DECLARE
1471     output              vandelay.compile_profile%ROWTYPE;
1472     profile             vandelay.merge_profile%ROWTYPE;
1473     profile_tmpl        TEXT;
1474     profile_tmpl_owner  TEXT;
1475     add_rule            TEXT := '';
1476     strip_rule          TEXT := '';
1477     replace_rule        TEXT := '';
1478     preserve_rule       TEXT := '';
1479
1480 BEGIN
1481
1482     profile_tmpl := (oils_xpath('//*[@tag="905"]/*[@code="t"]/text()',incoming_xml))[1];
1483     profile_tmpl_owner := (oils_xpath('//*[@tag="905"]/*[@code="o"]/text()',incoming_xml))[1];
1484
1485     IF profile_tmpl IS NOT NULL AND profile_tmpl <> '' AND profile_tmpl_owner IS NOT NULL AND profile_tmpl_owner <> '' THEN
1486         SELECT  p.* INTO profile
1487           FROM  vandelay.merge_profile p
1488                 JOIN actor.org_unit u ON (u.id = p.owner)
1489           WHERE p.name = profile_tmpl
1490                 AND u.shortname = profile_tmpl_owner;
1491
1492         IF profile.id IS NOT NULL THEN
1493             add_rule := COALESCE(profile.add_spec,'');
1494             strip_rule := COALESCE(profile.strip_spec,'');
1495             replace_rule := COALESCE(profile.replace_spec,'');
1496             preserve_rule := COALESCE(profile.preserve_spec,'');
1497         END IF;
1498     END IF;
1499
1500     add_rule := add_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="a"]/text()',incoming_xml),','),'');
1501     strip_rule := strip_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="d"]/text()',incoming_xml),','),'');
1502     replace_rule := replace_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="r"]/text()',incoming_xml),','),'');
1503     preserve_rule := preserve_rule || ',' || COALESCE(ARRAY_TO_STRING(oils_xpath('//*[@tag="905"]/*[@code="p"]/text()',incoming_xml),','),'');
1504
1505     output.add_rule := BTRIM(add_rule,',');
1506     output.replace_rule := BTRIM(replace_rule,',');
1507     output.strip_rule := BTRIM(strip_rule,',');
1508     output.preserve_rule := BTRIM(preserve_rule,',');
1509
1510     RETURN output;
1511 END;
1512 $_$ LANGUAGE PLPGSQL;
1513
1514 CREATE OR REPLACE FUNCTION vandelay.template_overlay_bib_record ( v_marc TEXT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1515 DECLARE
1516     merge_profile   vandelay.merge_profile%ROWTYPE;
1517     dyn_profile     vandelay.compile_profile%ROWTYPE;
1518     editor_string   TEXT;
1519     editor_id       INT;
1520     source_marc     TEXT;
1521     target_marc     TEXT;
1522     eg_marc         TEXT;
1523     replace_rule    TEXT;
1524     match_count     INT;
1525 BEGIN
1526
1527     SELECT  b.marc INTO eg_marc
1528       FROM  biblio.record_entry b
1529       WHERE b.id = eg_id
1530       LIMIT 1;
1531
1532     IF eg_marc IS NULL OR v_marc IS NULL THEN
1533         -- RAISE NOTICE 'no marc for template or bib record';
1534         RETURN FALSE;
1535     END IF;
1536
1537     dyn_profile := vandelay.compile_profile( v_marc );
1538
1539     IF merge_profile_id IS NOT NULL THEN
1540         SELECT * INTO merge_profile FROM vandelay.merge_profile WHERE id = merge_profile_id;
1541         IF FOUND THEN
1542             dyn_profile.add_rule := BTRIM( dyn_profile.add_rule || ',' || COALESCE(merge_profile.add_spec,''), ',');
1543             dyn_profile.strip_rule := BTRIM( dyn_profile.strip_rule || ',' || COALESCE(merge_profile.strip_spec,''), ',');
1544             dyn_profile.replace_rule := BTRIM( dyn_profile.replace_rule || ',' || COALESCE(merge_profile.replace_spec,''), ',');
1545             dyn_profile.preserve_rule := BTRIM( dyn_profile.preserve_rule || ',' || COALESCE(merge_profile.preserve_spec,''), ',');
1546         END IF;
1547     END IF;
1548
1549     IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1550         -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1551         RETURN FALSE;
1552     END IF;
1553
1554     IF dyn_profile.replace_rule = '' AND dyn_profile.preserve_rule = '' AND dyn_profile.add_rule = '' AND dyn_profile.strip_rule = '' THEN
1555         --Since we have nothing to do, just return a NOOP "we did it"
1556         RETURN TRUE;
1557     ELSIF dyn_profile.replace_rule <> '' THEN
1558         source_marc = v_marc;
1559         target_marc = eg_marc;
1560         replace_rule = dyn_profile.replace_rule;
1561     ELSE
1562         source_marc = eg_marc;
1563         target_marc = v_marc;
1564         replace_rule = dyn_profile.preserve_rule;
1565     END IF;
1566
1567     UPDATE  biblio.record_entry
1568       SET   marc = vandelay.merge_record_xml( target_marc, source_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule )
1569       WHERE id = eg_id;
1570
1571     IF NOT FOUND THEN
1572         -- RAISE NOTICE 'update of biblio.record_entry failed';
1573         RETURN FALSE;
1574     END IF;
1575
1576     RETURN TRUE;
1577
1578 END;
1579 $$ LANGUAGE PLPGSQL;
1580
1581 CREATE OR REPLACE FUNCTION vandelay.merge_record_xml ( target_marc TEXT, template_marc TEXT ) RETURNS TEXT AS $$
1582 DECLARE
1583     dyn_profile     vandelay.compile_profile%ROWTYPE;
1584     replace_rule    TEXT;
1585     tmp_marc        TEXT;
1586     trgt_marc        TEXT;
1587     tmpl_marc        TEXT;
1588     match_count     INT;
1589 BEGIN
1590
1591     IF target_marc IS NULL OR template_marc IS NULL THEN
1592         -- RAISE NOTICE 'no marc for target or template record';
1593         RETURN NULL;
1594     END IF;
1595
1596     dyn_profile := vandelay.compile_profile( template_marc );
1597
1598     IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1599         -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1600         RETURN NULL;
1601     END IF;
1602
1603     IF dyn_profile.replace_rule = '' AND dyn_profile.preserve_rule = '' AND dyn_profile.add_rule = '' AND dyn_profile.strip_rule = '' THEN
1604         --Since we have nothing to do, just return what we were given.
1605         RETURN target_marc;
1606     ELSIF dyn_profile.replace_rule <> '' THEN
1607         trgt_marc = target_marc;
1608         tmpl_marc = template_marc;
1609         replace_rule = dyn_profile.replace_rule;
1610     ELSE
1611         tmp_marc = target_marc;
1612         trgt_marc = template_marc;
1613         tmpl_marc = tmp_marc;
1614         replace_rule = dyn_profile.preserve_rule;
1615     END IF;
1616
1617     RETURN vandelay.merge_record_xml( trgt_marc, tmpl_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule );
1618
1619 END;
1620 $$ LANGUAGE PLPGSQL;
1621
1622 CREATE OR REPLACE FUNCTION vandelay.merge_record_xml_using_profile ( incoming_marc TEXT, existing_marc TEXT, merge_profile_id BIGINT ) RETURNS TEXT AS $$
1623 DECLARE
1624     merge_profile   vandelay.merge_profile%ROWTYPE;
1625     dyn_profile     vandelay.compile_profile%ROWTYPE;
1626     target_marc     TEXT;
1627     source_marc     TEXT;
1628     replace_rule    TEXT;
1629     match_count     INT;
1630 BEGIN
1631
1632     IF existing_marc IS NULL OR incoming_marc IS NULL THEN
1633         -- RAISE NOTICE 'no marc for source or target records';
1634         RETURN NULL;
1635     END IF;
1636
1637     IF merge_profile_id IS NOT NULL THEN
1638         SELECT * INTO merge_profile FROM vandelay.merge_profile WHERE id = merge_profile_id;
1639         IF FOUND THEN
1640             dyn_profile.add_rule := COALESCE(merge_profile.add_spec,'');
1641             dyn_profile.strip_rule := COALESCE(merge_profile.strip_spec,'');
1642             dyn_profile.replace_rule := COALESCE(merge_profile.replace_spec,'');
1643             dyn_profile.preserve_rule := COALESCE(merge_profile.preserve_spec,'');
1644         ELSE
1645             -- RAISE NOTICE 'merge profile not found';
1646             RETURN NULL;
1647         END IF;
1648     ELSE
1649         -- RAISE NOTICE 'no merge profile specified';
1650         RETURN NULL;
1651     END IF;
1652
1653     IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
1654         -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
1655         RETURN NULL;
1656     END IF;
1657
1658     IF dyn_profile.replace_rule = '' AND dyn_profile.preserve_rule = '' AND dyn_profile.add_rule = '' AND dyn_profile.strip_rule = '' THEN
1659         -- Since we have nothing to do, just return a target record as is
1660         RETURN existing_marc;
1661     ELSIF dyn_profile.preserve_rule <> '' THEN
1662         source_marc = existing_marc;
1663         target_marc = incoming_marc;
1664         replace_rule = dyn_profile.preserve_rule;
1665     ELSE
1666         source_marc = incoming_marc;
1667         target_marc = existing_marc;
1668         replace_rule = dyn_profile.replace_rule;
1669     END IF;
1670
1671     RETURN vandelay.merge_record_xml( target_marc, source_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule );
1672
1673 END;
1674 $$ LANGUAGE PLPGSQL;
1675
1676 CREATE OR REPLACE FUNCTION vandelay.template_overlay_bib_record ( v_marc TEXT, eg_id BIGINT) RETURNS BOOL AS $$
1677     SELECT vandelay.template_overlay_bib_record( $1, $2, NULL);
1678 $$ LANGUAGE SQL;
1679
1680 CREATE OR REPLACE FUNCTION vandelay.overlay_bib_record 
1681     ( import_id BIGINT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1682 DECLARE
1683     editor_string   TEXT;
1684     editor_id       INT;
1685     v_marc          TEXT;
1686     v_bib_source    INT;
1687     update_fields   TEXT[];
1688     update_query    TEXT;
1689     update_bib_source BOOL;
1690     update_bib_editor BOOL;
1691 BEGIN
1692
1693     SELECT  q.marc, q.bib_source INTO v_marc, v_bib_source
1694       FROM  vandelay.queued_bib_record q
1695             JOIN vandelay.bib_match m ON (m.queued_record = q.id AND q.id = import_id)
1696       LIMIT 1;
1697
1698     IF v_marc IS NULL THEN
1699         -- RAISE NOTICE 'no marc for vandelay or bib record';
1700         RETURN FALSE;
1701     END IF;
1702
1703     IF NOT vandelay.template_overlay_bib_record( v_marc, eg_id, merge_profile_id) THEN
1704         -- no update happened, get outta here.
1705         RETURN FALSE;
1706     END IF;
1707
1708     UPDATE  vandelay.queued_bib_record
1709       SET   imported_as = eg_id,
1710             import_time = NOW()
1711       WHERE id = import_id;
1712
1713     SELECT q.update_bib_source INTO update_bib_source 
1714         FROM vandelay.merge_profile q where q.id = merge_profile_Id;
1715
1716     IF update_bib_source AND v_bib_source IS NOT NULL THEN
1717         update_fields := ARRAY_APPEND(update_fields, 'source = ' || v_bib_source);
1718     END IF;
1719
1720     SELECT q.update_bib_editor INTO update_bib_editor 
1721         FROM vandelay.merge_profile q where q.id = merge_profile_Id;
1722
1723     IF update_bib_editor THEN
1724
1725         editor_string := (oils_xpath('//*[@tag="905"]/*[@code="u"]/text()',v_marc))[1];
1726
1727         IF editor_string IS NOT NULL AND editor_string <> '' THEN
1728             SELECT usr INTO editor_id FROM actor.card WHERE barcode = editor_string;
1729
1730             IF editor_id IS NULL THEN
1731                 SELECT id INTO editor_id FROM actor.usr WHERE usrname = editor_string;
1732             END IF;
1733
1734             IF editor_id IS NOT NULL THEN
1735                 --only update the edit date if we have a valid editor
1736                 update_fields := ARRAY_APPEND(
1737                     update_fields, 'editor = ' || editor_id || ', edit_date = NOW()');
1738             END IF;
1739         END IF;
1740     END IF;
1741
1742     IF ARRAY_LENGTH(update_fields, 1) > 0 THEN
1743         update_query := 'UPDATE biblio.record_entry SET ' || 
1744             ARRAY_TO_STRING(update_fields, ',') || ' WHERE id = ' || eg_id || ';';
1745         EXECUTE update_query;
1746     END IF;
1747
1748     RETURN TRUE;
1749 END;
1750 $$ LANGUAGE PLPGSQL;
1751
1752
1753 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 $$
1754 DECLARE
1755     eg_id           BIGINT;
1756     lwm_ratio_value NUMERIC;
1757 BEGIN
1758
1759     lwm_ratio_value := COALESCE(lwm_ratio_value_p, 0.0);
1760
1761     PERFORM * FROM vandelay.queued_bib_record WHERE import_time IS NOT NULL AND id = import_id;
1762
1763     IF FOUND THEN
1764         -- RAISE NOTICE 'already imported, cannot auto-overlay'
1765         RETURN FALSE;
1766     END IF;
1767
1768     SELECT  m.eg_record INTO eg_id
1769       FROM  vandelay.bib_match m
1770             JOIN vandelay.queued_bib_record qr ON (m.queued_record = qr.id)
1771             JOIN vandelay.bib_queue q ON (qr.queue = q.id)
1772             JOIN biblio.record_entry r ON (r.id = m.eg_record)
1773       WHERE m.queued_record = import_id
1774             AND qr.quality::NUMERIC / COALESCE(NULLIF(m.quality,0),1)::NUMERIC >= lwm_ratio_value
1775       ORDER BY  m.match_score DESC, -- required match score
1776                 qr.quality::NUMERIC / COALESCE(NULLIF(m.quality,0),1)::NUMERIC DESC, -- quality tie breaker
1777                 m.id -- when in doubt, use the first match
1778       LIMIT 1;
1779
1780     IF eg_id IS NULL THEN
1781         -- RAISE NOTICE 'incoming record is not of high enough quality';
1782         RETURN FALSE;
1783     END IF;
1784
1785     RETURN vandelay.overlay_bib_record( import_id, eg_id, merge_profile_id );
1786 END;
1787 $$ LANGUAGE PLPGSQL;
1788
1789 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record_with_best ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1790     SELECT vandelay.auto_overlay_bib_record_with_best( $1, $2, p.lwm_ratio ) FROM vandelay.merge_profile p WHERE id = $2;
1791 $$ LANGUAGE SQL;
1792
1793 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_record ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
1794 DECLARE
1795     eg_id           BIGINT;
1796     match_count     INT;
1797 BEGIN
1798
1799     PERFORM * FROM vandelay.queued_bib_record WHERE import_time IS NOT NULL AND id = import_id;
1800
1801     IF FOUND THEN
1802         -- RAISE NOTICE 'already imported, cannot auto-overlay'
1803         RETURN FALSE;
1804     END IF;
1805
1806     SELECT COUNT(*) INTO match_count FROM vandelay.bib_match WHERE queued_record = import_id;
1807
1808     IF match_count <> 1 THEN
1809         -- RAISE NOTICE 'not an exact match';
1810         RETURN FALSE;
1811     END IF;
1812
1813     -- Check that the one match is on the first 901c
1814     SELECT  m.eg_record INTO eg_id
1815       FROM  vandelay.queued_bib_record q
1816             JOIN vandelay.bib_match m ON (m.queued_record = q.id)
1817       WHERE q.id = import_id
1818             AND m.eg_record = oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]',marc)::BIGINT;
1819
1820     IF NOT FOUND THEN
1821         -- RAISE NOTICE 'not a 901c match';
1822         RETURN FALSE;
1823     END IF;
1824
1825     RETURN vandelay.overlay_bib_record( import_id, eg_id, merge_profile_id );
1826 END;
1827 $$ LANGUAGE PLPGSQL;
1828
1829 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue ( queue_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1830 DECLARE
1831     queued_record   vandelay.queued_bib_record%ROWTYPE;
1832 BEGIN
1833
1834     FOR queued_record IN SELECT * FROM vandelay.queued_bib_record WHERE queue = queue_id AND import_time IS NULL LOOP
1835
1836         IF vandelay.auto_overlay_bib_record( queued_record.id, merge_profile_id ) THEN
1837             RETURN NEXT queued_record.id;
1838         END IF;
1839
1840     END LOOP;
1841
1842     RETURN;
1843     
1844 END;
1845 $$ LANGUAGE PLPGSQL;
1846
1847 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 $$
1848 DECLARE
1849     queued_record   vandelay.queued_bib_record%ROWTYPE;
1850 BEGIN
1851
1852     FOR queued_record IN SELECT * FROM vandelay.queued_bib_record WHERE queue = queue_id AND import_time IS NULL LOOP
1853
1854         IF vandelay.auto_overlay_bib_record_with_best( queued_record.id, merge_profile_id, lwm_ratio_value ) THEN
1855             RETURN NEXT queued_record.id;
1856         END IF;
1857
1858     END LOOP;
1859
1860     RETURN;
1861     
1862 END;
1863 $$ LANGUAGE PLPGSQL;
1864
1865 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue_with_best ( import_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
1866     SELECT vandelay.auto_overlay_bib_queue_with_best( $1, $2, p.lwm_ratio ) FROM vandelay.merge_profile p WHERE id = $2;
1867 $$ LANGUAGE SQL;
1868
1869 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_bib_queue ( queue_id BIGINT ) RETURNS SETOF BIGINT AS $$
1870     SELECT * FROM vandelay.auto_overlay_bib_queue( $1, NULL );
1871 $$ LANGUAGE SQL;
1872
1873 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_org_unit_copies ( import_id BIGINT, merge_profile_id INT, lwm_ratio_value_p NUMERIC ) RETURNS BOOL AS $$
1874 DECLARE
1875     eg_id           BIGINT;
1876     match_count     INT;
1877     rec             vandelay.bib_match%ROWTYPE;
1878     v_owning_lib    INT;
1879     scope_org       INT;
1880     scope_orgs      INT[];
1881     copy_count      INT := 0;
1882     max_copy_count  INT := 0;
1883 BEGIN
1884
1885     PERFORM * FROM vandelay.queued_bib_record WHERE import_time IS NOT NULL AND id = import_id;
1886
1887     IF FOUND THEN
1888         -- RAISE NOTICE 'already imported, cannot auto-overlay'
1889         RETURN FALSE;
1890     END IF;
1891
1892     -- Gather all the owning libs for our import items.
1893     -- These are our initial scope_orgs.
1894     SELECT ARRAY_AGG(DISTINCT owning_lib) INTO scope_orgs
1895         FROM vandelay.import_item
1896         WHERE record = import_id;
1897
1898     WHILE CARDINALITY(scope_orgs) > 0 LOOP
1899         FOR scope_org IN SELECT * FROM UNNEST(scope_orgs) LOOP
1900             -- For each match, get a count of all copies at descendants of our scope org.
1901             FOR rec IN SELECT * FROM vandelay.bib_match AS vbm
1902                 WHERE queued_record = import_id
1903                 ORDER BY vbm.eg_record DESC
1904             LOOP
1905                 SELECT COUNT(acp.id) INTO copy_count
1906                     FROM asset.copy AS acp
1907                     INNER JOIN asset.call_number AS acn
1908                         ON acp.call_number = acn.id
1909                     WHERE acn.owning_lib IN (SELECT id FROM
1910                         actor.org_unit_descendants(scope_org))
1911                     AND acn.record = rec.eg_record
1912                     AND acp.deleted = FALSE;
1913                 IF copy_count > max_copy_count THEN
1914                     max_copy_count := copy_count;
1915                     eg_id := rec.eg_record;
1916                 END IF;
1917             END LOOP;
1918         END LOOP;
1919
1920         -- If no matching bibs had holdings, gather our next set of orgs to check, and iterate.
1921         IF max_copy_count = 0 THEN 
1922             SELECT ARRAY_AGG(DISTINCT parent_ou) INTO scope_orgs
1923                 FROM actor.org_unit
1924                 WHERE id IN (SELECT * FROM UNNEST(scope_orgs))
1925                 AND parent_ou IS NOT NULL;
1926         END IF;
1927     END LOOP;
1928
1929     IF eg_id IS NULL THEN
1930         -- Could not determine best match via copy count
1931         -- fall back to default best match
1932         IF (SELECT * FROM vandelay.auto_overlay_bib_record_with_best( import_id, merge_profile_id, lwm_ratio_value_p )) THEN
1933             RETURN TRUE;
1934         ELSE
1935             RETURN FALSE;
1936         END IF;
1937     END IF;
1938
1939     RETURN vandelay.overlay_bib_record( import_id, eg_id, merge_profile_id );
1940 END;
1941 $$ LANGUAGE PLPGSQL;
1942
1943 CREATE OR REPLACE FUNCTION vandelay.ingest_bib_marc ( ) RETURNS TRIGGER AS $$
1944 DECLARE
1945     value   TEXT;
1946     atype   TEXT;
1947     adef    RECORD;
1948 BEGIN
1949     IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1950         RETURN NEW;
1951     END IF;
1952
1953     FOR adef IN SELECT * FROM vandelay.bib_attr_definition LOOP
1954
1955         SELECT extract_marc_field('vandelay.queued_bib_record', id, adef.xpath, adef.remove) INTO value FROM vandelay.queued_bib_record WHERE id = NEW.id;
1956         IF (value IS NOT NULL AND value <> '') THEN
1957             INSERT INTO vandelay.queued_bib_record_attr (record, field, attr_value) VALUES (NEW.id, adef.id, value);
1958         END IF;
1959
1960     END LOOP;
1961
1962     RETURN NULL;
1963 END;
1964 $$ LANGUAGE PLPGSQL;
1965
1966 CREATE OR REPLACE FUNCTION vandelay.cleanup_bib_marc ( ) RETURNS TRIGGER AS $$
1967 BEGIN
1968     IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1969         RETURN NEW;
1970     END IF;
1971
1972     DELETE FROM vandelay.queued_bib_record_attr WHERE record = OLD.id;
1973     DELETE FROM vandelay.import_item WHERE record = OLD.id;
1974
1975     IF TG_OP = 'UPDATE' THEN
1976         RETURN NEW;
1977     END IF;
1978     RETURN OLD;
1979 END;
1980 $$ LANGUAGE PLPGSQL;
1981
1982 CREATE TRIGGER cleanup_bib_trigger
1983     BEFORE UPDATE OR DELETE ON vandelay.queued_bib_record
1984     FOR EACH ROW EXECUTE PROCEDURE vandelay.cleanup_bib_marc();
1985
1986 CREATE TRIGGER ingest_bib_trigger
1987     AFTER INSERT OR UPDATE ON vandelay.queued_bib_record
1988     FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_bib_marc();
1989
1990 CREATE TRIGGER zz_match_bibs_trigger
1991     BEFORE INSERT OR UPDATE ON vandelay.queued_bib_record
1992     FOR EACH ROW EXECUTE PROCEDURE vandelay.match_bib_record();
1993
1994
1995 /* Authority stuff down here */
1996 ---------------------------------------
1997 CREATE TABLE vandelay.authority_attr_definition (
1998         id                      SERIAL  PRIMARY KEY,
1999         code            TEXT    UNIQUE NOT NULL,
2000         description     TEXT,
2001         xpath           TEXT    NOT NULL,
2002         remove          TEXT    NOT NULL DEFAULT ''
2003 );
2004
2005 CREATE TYPE vandelay.authority_queue_queue_type AS ENUM ('authority');
2006 CREATE TABLE vandelay.authority_queue (
2007         queue_type      vandelay.authority_queue_queue_type NOT NULL DEFAULT 'authority',
2008         CONSTRAINT vand_authority_queue_name_once_per_owner_const UNIQUE (owner,name,queue_type)
2009 ) INHERITS (vandelay.queue);
2010 ALTER TABLE vandelay.authority_queue ADD PRIMARY KEY (id);
2011
2012 CREATE TABLE vandelay.queued_authority_record (
2013         queue           INT     NOT NULL REFERENCES vandelay.authority_queue (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
2014         imported_as     INT     REFERENCES authority.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
2015         import_error    TEXT    REFERENCES vandelay.import_error (code) ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY DEFERRED,
2016         error_detail    TEXT
2017 ) INHERITS (vandelay.queued_record);
2018 ALTER TABLE vandelay.queued_authority_record ADD PRIMARY KEY (id);
2019 CREATE INDEX queued_authority_record_queue_idx ON vandelay.queued_authority_record (queue);
2020
2021 CREATE TABLE vandelay.queued_authority_record_attr (
2022         id                      BIGSERIAL       PRIMARY KEY,
2023         record          BIGINT          NOT NULL REFERENCES vandelay.queued_authority_record (id) DEFERRABLE INITIALLY DEFERRED,
2024         field           INT                     NOT NULL REFERENCES vandelay.authority_attr_definition (id) DEFERRABLE INITIALLY DEFERRED,
2025         attr_value      TEXT            NOT NULL
2026 );
2027 CREATE INDEX queued_authority_record_attr_record_idx ON vandelay.queued_authority_record_attr (record);
2028
2029 CREATE TABLE vandelay.authority_match (
2030         id                              BIGSERIAL       PRIMARY KEY,
2031         queued_record   BIGINT          REFERENCES vandelay.queued_authority_record (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
2032         eg_record               BIGINT          REFERENCES authority.record_entry (id) DEFERRABLE INITIALLY DEFERRED,
2033     quality         INT         NOT NULL DEFAULT 0,
2034     match_score     INT         NOT NULL DEFAULT 0
2035 );
2036
2037 CREATE OR REPLACE FUNCTION vandelay.ingest_authority_marc ( ) RETURNS TRIGGER AS $$
2038 DECLARE
2039     value   TEXT;
2040     atype   TEXT;
2041     adef    RECORD;
2042 BEGIN
2043     IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
2044         RETURN NEW;
2045     END IF;
2046
2047     FOR adef IN SELECT * FROM vandelay.authority_attr_definition LOOP
2048
2049         SELECT extract_marc_field('vandelay.queued_authority_record', id, adef.xpath, adef.remove) INTO value FROM vandelay.queued_authority_record WHERE id = NEW.id;
2050         IF (value IS NOT NULL AND value <> '') THEN
2051             INSERT INTO vandelay.queued_authority_record_attr (record, field, attr_value) VALUES (NEW.id, adef.id, value);
2052         END IF;
2053
2054     END LOOP;
2055
2056     RETURN NULL;
2057 END;
2058 $$ LANGUAGE PLPGSQL;
2059
2060 CREATE OR REPLACE FUNCTION vandelay.cleanup_authority_marc ( ) RETURNS TRIGGER AS $$
2061 BEGIN
2062     IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
2063         RETURN NEW;
2064     END IF;
2065
2066     DELETE FROM vandelay.queued_authority_record_attr WHERE record = OLD.id;
2067     IF TG_OP = 'UPDATE' THEN
2068         RETURN NEW;
2069     END IF;
2070     RETURN OLD;
2071 END;
2072 $$ LANGUAGE PLPGSQL;
2073
2074 CREATE TRIGGER cleanup_authority_trigger
2075     BEFORE UPDATE OR DELETE ON vandelay.queued_authority_record
2076     FOR EACH ROW EXECUTE PROCEDURE vandelay.cleanup_authority_marc();
2077
2078 CREATE TRIGGER ingest_authority_trigger
2079     AFTER INSERT OR UPDATE ON vandelay.queued_authority_record
2080     FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_authority_marc();
2081
2082 CREATE OR REPLACE FUNCTION vandelay.overlay_authority_record ( import_id BIGINT, eg_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
2083 DECLARE
2084     merge_profile   vandelay.merge_profile%ROWTYPE;
2085     dyn_profile     vandelay.compile_profile%ROWTYPE;
2086     editor_string   TEXT;
2087     new_editor      INT;
2088     new_edit_date   TIMESTAMPTZ;
2089     source_marc     TEXT;
2090     target_marc     TEXT;
2091     eg_marc_row     authority.record_entry%ROWTYPE;
2092     eg_marc         TEXT;
2093     v_marc          TEXT;
2094     replace_rule    TEXT;
2095     match_count     INT;
2096     update_query    TEXT;
2097 BEGIN
2098
2099     SELECT  * INTO eg_marc_row
2100       FROM  authority.record_entry b
2101             JOIN vandelay.authority_match m ON (m.eg_record = b.id AND m.queued_record = import_id)
2102       LIMIT 1;
2103
2104     SELECT  q.marc INTO v_marc
2105       FROM  vandelay.queued_record q
2106             JOIN vandelay.authority_match m ON (m.queued_record = q.id AND q.id = import_id)
2107       LIMIT 1;
2108
2109     eg_marc := eg_marc_row.marc;
2110
2111     IF eg_marc IS NULL OR v_marc IS NULL THEN
2112         -- RAISE NOTICE 'no marc for vandelay or authority record';
2113         RETURN FALSE;
2114     END IF;
2115
2116     -- Extract the editor string before any modification to the vandelay
2117     -- MARC occur.
2118     editor_string := 
2119         (oils_xpath('//*[@tag="905"]/*[@code="u"]/text()',v_marc))[1];
2120
2121     -- If an editor value can be found, update the authority record
2122     -- editor and edit_date values.
2123     IF editor_string IS NOT NULL AND editor_string <> '' THEN
2124
2125         -- Vandelay.pm sets the value to 'usrname' when needed.  
2126         SELECT id INTO new_editor
2127             FROM actor.usr WHERE usrname = editor_string;
2128
2129         IF new_editor IS NULL THEN
2130             SELECT usr INTO new_editor
2131                 FROM actor.card WHERE barcode = editor_string;
2132         END IF;
2133
2134         IF new_editor IS NOT NULL THEN
2135             new_edit_date := NOW();
2136         ELSE -- No valid editor, use current values
2137             new_editor = eg_marc_row.editor;
2138             new_edit_date = eg_marc_row.edit_date;
2139         END IF;
2140     ELSE
2141         new_editor = eg_marc_row.editor;
2142         new_edit_date = eg_marc_row.edit_date;
2143     END IF;
2144
2145     dyn_profile := vandelay.compile_profile( v_marc );
2146
2147     IF merge_profile_id IS NOT NULL THEN
2148         SELECT * INTO merge_profile FROM vandelay.merge_profile WHERE id = merge_profile_id;
2149         IF FOUND THEN
2150             dyn_profile.add_rule := BTRIM( dyn_profile.add_rule || ',' || COALESCE(merge_profile.add_spec,''), ',');
2151             dyn_profile.strip_rule := BTRIM( dyn_profile.strip_rule || ',' || COALESCE(merge_profile.strip_spec,''), ',');
2152             dyn_profile.replace_rule := BTRIM( dyn_profile.replace_rule || ',' || COALESCE(merge_profile.replace_spec,''), ',');
2153             dyn_profile.preserve_rule := BTRIM( dyn_profile.preserve_rule || ',' || COALESCE(merge_profile.preserve_spec,''), ',');
2154         END IF;
2155     END IF;
2156
2157     IF dyn_profile.replace_rule <> '' AND dyn_profile.preserve_rule <> '' THEN
2158         -- RAISE NOTICE 'both replace [%] and preserve [%] specified', dyn_profile.replace_rule, dyn_profile.preserve_rule;
2159         RETURN FALSE;
2160     END IF;
2161
2162     IF dyn_profile.replace_rule = '' AND dyn_profile.preserve_rule = '' AND dyn_profile.add_rule = '' AND dyn_profile.strip_rule = '' THEN
2163         --Since we have nothing to do, just return a NOOP "we did it"
2164         RETURN TRUE;
2165     ELSIF dyn_profile.replace_rule <> '' THEN
2166         source_marc = v_marc;
2167         target_marc = eg_marc;
2168         replace_rule = dyn_profile.replace_rule;
2169     ELSE
2170         source_marc = eg_marc;
2171         target_marc = v_marc;
2172         replace_rule = dyn_profile.preserve_rule;
2173     END IF;
2174
2175     UPDATE  authority.record_entry
2176       SET   marc = vandelay.merge_record_xml( target_marc, source_marc, dyn_profile.add_rule, replace_rule, dyn_profile.strip_rule ),
2177             editor = new_editor,
2178             edit_date = new_edit_date
2179       WHERE id = eg_id;
2180
2181     IF NOT FOUND THEN 
2182         -- Import/merge failed.  Nothing left to do.
2183         RETURN FALSE;
2184     END IF;
2185
2186     -- Authority record successfully merged / imported.
2187
2188     -- Update the vandelay record to show the successful import.
2189     UPDATE  vandelay.queued_authority_record
2190       SET   imported_as = eg_id,
2191             import_time = NOW()
2192       WHERE id = import_id;
2193
2194     RETURN TRUE;
2195
2196 END;
2197 $$ LANGUAGE PLPGSQL;
2198
2199 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_record ( import_id BIGINT, merge_profile_id INT ) RETURNS BOOL AS $$
2200 DECLARE
2201     eg_id           BIGINT;
2202     match_count     INT;
2203 BEGIN
2204     SELECT COUNT(*) INTO match_count FROM vandelay.authority_match WHERE queued_record = import_id;
2205
2206     IF match_count <> 1 THEN
2207         -- RAISE NOTICE 'not an exact match';
2208         RETURN FALSE;
2209     END IF;
2210
2211     SELECT  m.eg_record INTO eg_id
2212       FROM  vandelay.authority_match m
2213       WHERE m.queued_record = import_id
2214       LIMIT 1;
2215
2216     IF eg_id IS NULL THEN
2217         RETURN FALSE;
2218     END IF;
2219
2220     RETURN vandelay.overlay_authority_record( import_id, eg_id, merge_profile_id );
2221 END;
2222 $$ LANGUAGE PLPGSQL;
2223
2224 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_queue ( queue_id BIGINT, merge_profile_id INT ) RETURNS SETOF BIGINT AS $$
2225 DECLARE
2226     queued_record   vandelay.queued_authority_record%ROWTYPE;
2227 BEGIN
2228
2229     FOR queued_record IN SELECT * FROM vandelay.queued_authority_record WHERE queue = queue_id AND import_time IS NULL LOOP
2230
2231         IF vandelay.auto_overlay_authority_record( queued_record.id, merge_profile_id ) THEN
2232             RETURN NEXT queued_record.id;
2233         END IF;
2234
2235     END LOOP;
2236
2237     RETURN;
2238     
2239 END;
2240 $$ LANGUAGE PLPGSQL;
2241
2242 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_queue ( queue_id BIGINT ) RETURNS SETOF BIGINT AS $$
2243     SELECT * FROM vandelay.auto_overlay_authority_queue( $1, NULL );
2244 $$ LANGUAGE SQL;
2245
2246 CREATE OR REPLACE FUNCTION vandelay.match_set_test_authxml(
2247     match_set_id INTEGER, record_xml TEXT
2248 ) RETURNS SETOF vandelay.match_set_test_result AS $$
2249 DECLARE
2250     tags_rstore HSTORE;
2251     heading     TEXT;
2252     coal        TEXT;
2253     joins       TEXT;
2254     query_      TEXT;
2255     wq          TEXT;
2256     qvalue      INTEGER;
2257     rec         RECORD;
2258 BEGIN
2259     tags_rstore := vandelay.flatten_marc_hstore(record_xml);
2260
2261     SELECT normalize_heading INTO heading 
2262         FROM authority.normalize_heading(record_xml);
2263
2264     CREATE TEMPORARY TABLE _vandelay_tmp_qrows (q INTEGER);
2265     CREATE TEMPORARY TABLE _vandelay_tmp_jrows (j TEXT);
2266
2267     -- generate the where clause and return that directly (into wq), and as
2268     -- a side-effect, populate the _vandelay_tmp_[qj]rows tables.
2269     wq := vandelay.get_expr_from_match_set(
2270         match_set_id, tags_rstore, heading);
2271
2272     query_ := 'SELECT DISTINCT(record), ';
2273
2274     -- qrows table is for the quality bits we add to the SELECT clause
2275     SELECT STRING_AGG(
2276         'COALESCE(n' || q::TEXT || '.quality, 0)', ' + '
2277     ) INTO coal FROM _vandelay_tmp_qrows;
2278
2279     -- our query string so far is the SELECT clause and the inital FROM.
2280     -- no JOINs yet nor the WHERE clause
2281     query_ := query_ || coal || ' AS quality ' || E'\n';
2282
2283     -- jrows table is for the joins we must make (and the real text conditions)
2284     SELECT STRING_AGG(j, E'\n') INTO joins
2285         FROM _vandelay_tmp_jrows;
2286
2287     -- add those joins and the where clause to our query.
2288     query_ := query_ || joins || E'\n';
2289
2290     query_ := query_ || 'JOIN authority.record_entry are ON (are.id = record) ' 
2291         || 'WHERE ' || wq || ' AND not are.deleted';
2292
2293     -- this will return rows of record,quality
2294     FOR rec IN EXECUTE query_ USING tags_rstore LOOP
2295         RETURN NEXT rec;
2296     END LOOP;
2297
2298     DROP TABLE _vandelay_tmp_qrows;
2299     DROP TABLE _vandelay_tmp_jrows;
2300     RETURN;
2301 END;
2302 $$ LANGUAGE PLPGSQL;
2303
2304 CREATE OR REPLACE FUNCTION vandelay.measure_auth_record_quality 
2305     ( xml TEXT, match_set_id INT ) RETURNS INT AS $_$
2306 DECLARE
2307     out_q   INT := 0;
2308     rvalue  TEXT;
2309     test    vandelay.match_set_quality%ROWTYPE;
2310 BEGIN
2311
2312     FOR test IN SELECT * FROM vandelay.match_set_quality 
2313             WHERE match_set = match_set_id LOOP
2314         IF test.tag IS NOT NULL THEN
2315             FOR rvalue IN SELECT value FROM vandelay.flatten_marc( xml ) 
2316                 WHERE tag = test.tag AND subfield = test.subfield LOOP
2317                 IF test.value = rvalue THEN
2318                     out_q := out_q + test.quality;
2319                 END IF;
2320             END LOOP;
2321         END IF;
2322     END LOOP;
2323
2324     RETURN out_q;
2325 END;
2326 $_$ LANGUAGE PLPGSQL;
2327
2328
2329
2330 CREATE OR REPLACE FUNCTION vandelay.match_authority_record() RETURNS TRIGGER AS $func$
2331 DECLARE
2332     incoming_existing_id    TEXT;
2333     test_result             vandelay.match_set_test_result%ROWTYPE;
2334     tmp_rec                 BIGINT;
2335     match_set               INT;
2336 BEGIN
2337     IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
2338         RETURN NEW;
2339     END IF;
2340
2341     DELETE FROM vandelay.authority_match WHERE queued_record = NEW.id;
2342
2343     SELECT q.match_set INTO match_set FROM vandelay.authority_queue q WHERE q.id = NEW.queue;
2344
2345     IF match_set IS NOT NULL THEN
2346         NEW.quality := vandelay.measure_auth_record_quality( NEW.marc, match_set );
2347     END IF;
2348
2349     -- Perfect matches on 901$c exit early with a match with high quality.
2350     incoming_existing_id :=
2351         oils_xpath_string('//*[@tag="901"]/*[@code="c"][1]', NEW.marc);
2352
2353     IF incoming_existing_id IS NOT NULL AND incoming_existing_id != '' THEN
2354         SELECT id INTO tmp_rec FROM authority.record_entry WHERE id = incoming_existing_id::bigint;
2355         IF tmp_rec IS NOT NULL THEN
2356             INSERT INTO vandelay.authority_match (queued_record, eg_record, match_score, quality) 
2357                 SELECT
2358                     NEW.id, 
2359                     b.id,
2360                     9999,
2361                     -- note: no match_set means quality==0
2362                     vandelay.measure_auth_record_quality( b.marc, match_set )
2363                 FROM authority.record_entry b
2364                 WHERE id = incoming_existing_id::bigint;
2365         END IF;
2366     END IF;
2367
2368     IF match_set IS NULL THEN
2369         RETURN NEW;
2370     END IF;
2371
2372     FOR test_result IN SELECT * FROM
2373         vandelay.match_set_test_authxml(match_set, NEW.marc) LOOP
2374
2375         INSERT INTO vandelay.authority_match ( queued_record, eg_record, match_score, quality )
2376             SELECT  
2377                 NEW.id,
2378                 test_result.record,
2379                 test_result.quality,
2380                 vandelay.measure_auth_record_quality( b.marc, match_set )
2381                 FROM  authority.record_entry b
2382                 WHERE id = test_result.record;
2383
2384     END LOOP;
2385
2386     RETURN NEW;
2387 END;
2388 $func$ LANGUAGE PLPGSQL;
2389
2390 CREATE TRIGGER zz_match_auths_trigger
2391     BEFORE INSERT OR UPDATE ON vandelay.queued_authority_record
2392     FOR EACH ROW EXECUTE PROCEDURE vandelay.match_authority_record();
2393
2394 CREATE OR REPLACE FUNCTION vandelay.auto_overlay_authority_record_with_best ( import_id BIGINT, merge_profile_id INT, lwm_ratio_value_p NUMERIC ) RETURNS BOOL AS $$
2395 DECLARE
2396     eg_id           BIGINT;
2397     lwm_ratio_value NUMERIC;
2398 BEGIN
2399
2400     lwm_ratio_value := COALESCE(lwm_ratio_value_p, 0.0);
2401
2402     PERFORM * FROM vandelay.queued_authority_record WHERE import_time IS NOT NULL AND id = import_id;
2403
2404     IF FOUND THEN
2405         -- RAISE NOTICE 'already imported, cannot auto-overlay'
2406         RETURN FALSE;
2407     END IF;
2408
2409     SELECT  m.eg_record INTO eg_id
2410       FROM  vandelay.authority_match m
2411             JOIN vandelay.queued_authority_record qr ON (m.queued_record = qr.id)
2412             JOIN vandelay.authority_queue q ON (qr.queue = q.id)
2413             JOIN authority.record_entry r ON (r.id = m.eg_record)
2414       WHERE m.queued_record = import_id
2415             AND qr.quality::NUMERIC / COALESCE(NULLIF(m.quality,0),1)::NUMERIC >= lwm_ratio_value
2416       ORDER BY  m.match_score DESC, -- required match score
2417                 qr.quality::NUMERIC / COALESCE(NULLIF(m.quality,0),1)::NUMERIC DESC, -- quality tie breaker
2418                 m.id -- when in doubt, use the first match
2419       LIMIT 1;
2420
2421     IF eg_id IS NULL THEN
2422         -- RAISE NOTICE 'incoming record is not of high enough quality';
2423         RETURN FALSE;
2424     END IF;
2425
2426     RETURN vandelay.overlay_authority_record( import_id, eg_id, merge_profile_id );
2427 END;
2428 $$ LANGUAGE PLPGSQL;
2429
2430
2431
2432
2433 -- Vandelay (for importing and exporting records) 012.schema.vandelay.sql 
2434 --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)]');
2435 --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)]');
2436 --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]');
2437 --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]');
2438 --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$);
2439 --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$);
2440 --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]');
2441 --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);
2442 --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);
2443 --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);
2444 --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);
2445 --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]');
2446 --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$);
2447 --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]');
2448 --
2449 --INSERT INTO vandelay.import_item_attr_definition (
2450 --    owner, name, tag, owning_lib, circ_lib, location,
2451 --    call_number, circ_modifier, barcode, price, copy_number,
2452 --    circulate, ref, holdable, opac_visible, status
2453 --) VALUES (
2454 --    1,
2455 --    'Evergreen 852 export format',
2456 --    '852',
2457 --    '[@code = "b"][1]',
2458 --    '[@code = "b"][2]',
2459 --    'c',
2460 --    'j',
2461 --    'g',
2462 --    'p',
2463 --    'y',
2464 --    't',
2465 --    '[@code = "x" and text() = "circulating"]',
2466 --    '[@code = "x" and text() = "reference"]',
2467 --    '[@code = "x" and text() = "holdable"]',
2468 --    '[@code = "x" and text() = "visible"]',
2469 --    'z'
2470 --);
2471 --
2472 --INSERT INTO vandelay.import_item_attr_definition (
2473 --    owner,
2474 --    name,
2475 --    tag,
2476 --    owning_lib,
2477 --    location,
2478 --    call_number,
2479 --    circ_modifier,
2480 --    barcode,
2481 --    price,
2482 --    status
2483 --) VALUES (
2484 --    1,
2485 --    'Unicorn Import format -- 999',
2486 --    '999',
2487 --    'm',
2488 --    'l',
2489 --    'a',
2490 --    't',
2491 --    'i',
2492 --    'p',
2493 --    'k'
2494 --);
2495 --
2496 --INSERT INTO vandelay.authority_attr_definition ( code, description, xpath, ident ) VALUES ('rec_identifier','Identifier','//*[@tag="001"]', TRUE);
2497
2498
2499 CREATE TABLE vandelay.session_tracker (
2500     id          BIGSERIAL PRIMARY KEY,
2501
2502     -- string of characters (e.g. md5) used for linking trackers
2503     -- of different actions into a series.  There can be multiple
2504     -- session_keys of each action type, creating the opportunity
2505     -- to link multiple action trackers into a single session.
2506     session_key TEXT NOT NULL,
2507
2508     -- optional user-supplied name
2509     name        TEXT NOT NULL, 
2510
2511     usr         INTEGER NOT NULL REFERENCES actor.usr(id)
2512                 DEFERRABLE INITIALLY DEFERRED,
2513
2514     -- org unit can be derived from WS
2515     workstation INTEGER NOT NULL REFERENCES actor.workstation(id)
2516                 ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
2517
2518     -- bib/auth
2519     record_type TEXT NOT NULL DEFAULT 'bib',
2520
2521     -- Queue defines the source of the data, it does not necessarily
2522     -- mean that an action is being performed against an entire queue.
2523     -- E.g. some imports are misc. lists of record IDs, but they always 
2524     -- come from one queue.
2525     -- No foreign key -- could be auth or bib queue.
2526     queue       BIGINT NOT NULL,
2527
2528     create_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
2529     update_time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
2530
2531     state       TEXT NOT NULL DEFAULT 'active',
2532
2533     action_type TEXT NOT NULL DEFAULT 'enqueue', -- import
2534
2535     -- total number of tasks to perform / loosely defined
2536     -- could be # of recs to import or # of recs + # of copies 
2537     -- depending on the import context
2538     total_actions INTEGER NOT NULL DEFAULT 0,
2539
2540     -- total number of tasked performed so far
2541     actions_performed INTEGER NOT NULL DEFAULT 0,
2542
2543     CONSTRAINT vand_tracker_valid_state 
2544         CHECK (state IN ('active','error','complete')),
2545
2546     CONSTRAINT vand_tracker_valid_action_type
2547         CHECK (action_type IN ('upload', 'enqueue', 'import')),
2548
2549     CONSTRAINT vand_tracker_valid_record_type
2550         CHECK (record_type IN ('bib', 'authority'))
2551 );
2552
2553 COMMIT;
2554